From 15cbfc724b49ae32613ee90fc4e7ddf2925f5363 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 17:01:45 +0100 Subject: [PATCH 001/513] Define immutable submission intake identities --- .commitrail/INDEX.md | 1 + .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 59 + .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 77 + .../artifacts/api/submission_intake.py | 134 ++ .../test_submission_intake_contracts.py | 168 ++ docs/roadmap_status.md | 6 + docs/spec_submission_execution.md | 1373 +++++++++++++++++ scripts/check_stale_authorization_docs.py | 6 + scripts/test_submission_spec_wording.py | 27 + 9 files changed, 1851 insertions(+) create mode 100644 .commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md create mode 100644 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md create mode 100644 backend/app/modules/artifacts/api/submission_intake.py create mode 100644 backend/tests/artifacts/test_submission_intake_contracts.py create mode 100644 docs/spec_submission_execution.md create mode 100644 scripts/test_submission_spec_wording.py diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index 0c1cef85f..190f7d898 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,6 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | One-request submission contracts, then durable operations, streaming custody, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md new file mode 100644 index 000000000..9816037ba --- /dev/null +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -0,0 +1,59 @@ +# WS-SUBMIT-001 — One-request submission and durable continuation + +- Disposition: Planned +- Intent: implement the user-approved [specification](../../../docs/spec_submission_execution.md), preserving downstream authority and retained evidence. + +The user authorized the complete specification on 11 November 2026. Completion +requires D01–D18, I01–I12, T1–T5 and evidence for A01–A35. This record does not +authorize merge or production deployment. + +## Current boundary + +[WS-SUBMIT-001-01](WS-SUBMIT-001-01.md) establishes exact command/source value +contracts. Database ownership and all new orchestration remain to implement. +The existing public flow stays active until coordinated cutover. + +## Delivery sequence + +1. Owner contracts/schema: exact identities, ART operation, TASK guard, accepted + authority, PRE evidence and database constraints. +2. Streaming receipt, completion reconciliation, physical accounting and cleanup. +3. One-session PRE, trusted defaults, isolation and provider substitution proof. +4. Foreground T1–T4, exact replay and durable accepted receipt. +5. Worker T5, recovery and existing POST dispatch. +6. Single API/CLI/MCP mutation and truthful progress reads. +7. Image cardinality, readiness, migration/cutover and integrated proof. + +Create each bounded record when work starts. Authorization covers this sequence; +do not repeat discovery or verification without a relevant changed assumption. + +## Acceptance tracking + +All integrated scenarios remain Planned. Contract unit tests do not complete +them. Final evidence must name the executed test/drill and proved boundary. + +| Scenarios | Proof required | Disposition | +|---|---|---| +| A01–A03 | Public success and PRE failures | Planned | +| A04–A08 | Replay, concurrency, interruptions and unknown commit | Planned | +| A09–A13 | Worker recovery, authority and pending reads | Planned | +| A14–A18 | Cleanup races, protection, versions and physical charges | Planned | +| A19–A23 | Bounded ingress, framing, archives, identity and safe findings | Planned | +| A24–A30 | Substitution, runtime isolation/recovery, capacity and adapters | Planned | +| A31–A35 | Downstream behavior, migration, policy and clients | Planned | + +## Configuration and reconciliation + +C01–C07 remain unresolved as specified; fixtures are not approved deployment +defaults. Current Caddy allows 16 KiB total headers; target packet text permits +64 KiB each. Human-review execution remains unavailable in current main and is +not delivered by preserving its guards. + +Initial main is `a4e485edea03db90c71189c51eac85cf4c3b1139`. The 14 commits after +the spec baseline change deployment/identity, not submission owners. Open PR +#698 changes CLI preparation; #707 changes public access/profile behavior. +Reconcile those surfaces when reached without modifying their branches. + +Real PostgreSQL, S3/MinIO and Smol proof is required where claimed. Request +missing live access when a concrete drill is prepared. Historical old-flow +drills cannot establish this implementation's completion. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md new file mode 100644 index 000000000..23567e809 --- /dev/null +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -0,0 +1,77 @@ +# WS-SUBMIT-001-01 — Immutable intake command and source identities + +- Initiative: WS-SUBMIT-001 +- Durable disposition: Planned +- Intended merge outcome: closed immutable ART command/source values with exact canonical identities and rejection tests. + +## Intent + +Give database, upload and execution owners one representation of the original +command and sealed source, separate from credentials and later manifest facts. +This is the first portion of specification section 22 step 1. + +## Current behavior + +`artifacts/submission_admission.py` consumes process-local prepared ZIPs; +`interfaces/artifacts.py` derives keys from content SHA. The new design needs +operation-based keys before bytes are known and exact durable identity afterward. + +## Bounded change + +### Allowed + +- `backend/app/modules/artifacts/api/submission_intake.py`: command and source values. +- `backend/tests/artifacts/test_submission_intake_contracts.py`: pure contract proof. +- `docs/spec_submission_execution.md`: user-supplied specification, with technical + Celery-worker vocabulary qualified for repository documentation checks. +- `scripts/check_stale_authorization_docs.py` and + `scripts/test_submission_spec_wording.py`: exact object-key example exemption; + public API prefix enforcement remains unchanged elsewhere. +- This initiative, index and capability ledger: target and limited delivered scope. + +### Not allowed + +- Routes, migrations, orchestration, provider I/O or claims of database enforcement. +- Historical data changes, new authority, runtime changes or deployment defaults. +- Unrelated preparations or another open PR's branch. + +## Design and decisions + +Reuse canonical JSON hashing and the archive ceiling. Keys derive from server +UUIDv7 operation identity. Sealed values bind namespace/profile, raw SHA/count, +generation and fence. Metadata identity preserves exact packet and revision +selectors; actor/key scope and locked context remain separate operation facts. +Constructing these internal values grants no authority or provider qualification. + +## Acceptance criteria + +- [ ] Exact metadata round-trip and identity changes for each command selector. +- [ ] Packet/framing metadata validation preserves empty-text warning semantics. +- [ ] Source keys derive only from UUIDv7; no arbitrary path/URL selection. +- [ ] Namespace, generation, bytes and fence remain distinct identity inputs. +- [ ] Unknown fields, mutation and coercive values fail closed. +- [ ] Focused tests, lint, boundary/docs checks and scoped frozen-candidate reviews. + +## Risk and review routing + +- Risk class: L1 +- Required reviewers: architecture, security, QA/test_delta, documentation, CI integrity +- Human review focus: exact identities and limited contract-only scope. + +## Evidence + +| Claim | Command or proof | Result | Remaining uncertainty | +|---|---|---|---| +| Baseline | Fetch main and inspect open PRs | Reconciled a4e485ed | Recheck before publication | +| Contracts | Focused pytest and ruff | 56 tests passed; lint passed | No database/storage/runtime proof | +| Module boundaries | `python -m scripts.module_boundaries validate --protected-base origin/main` | Passed | Existing private-import debt unchanged | + +## Review findings + +No findings recorded yet. + +## Reconciliation + +- Current-source reconciliation: deployment delta and header mismatch inspected. +- Next usable boundary: durable operation schema and owner commands. +- Remaining risks: A01–A35 integration and C01–C07 qualification. diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py new file mode 100644 index 000000000..e94470d88 --- /dev/null +++ b/backend/app/modules/artifacts/api/submission_intake.py @@ -0,0 +1,134 @@ +"""Immutable intake identities; values never confer storage or submit authority. + +The operation owner must generate/persist its UUID before creating a source, +authorize every use and compare these values to locked durable facts. Neither a +well-formed source nor its digest proves that an upload or PRE actually occurred. +Delivery credentials and semantic-manifest evidence are deliberately separate. +""" + +from __future__ import annotations + +from typing import Annotated, Literal, Self +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +from app.core.hashing import canonical_json_hash +from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES + + +Sha256 = Annotated[str, Field(pattern=r"^sha256:[0-9a-f]{64}$")] + + +class _IntakeValue(BaseModel): + """Closed, frozen values accepting typed Python or canonical JSON input.""" + + model_config = ConfigDict( + extra="forbid", strict=True, frozen=True, revalidate_instances="always", + ) + + +class SubmissionIntakeMetadata(_IntakeValue): + """Exact original command; actor/key namespace and locked policy are separate. + + These selectors are validated structurally only. TASK still checks current + assignment, actual predecessor and the required revision acknowledgement. + Empty summary/attestation retain existing nonblocking warning semantics. + """ + + task_id: UUID + assignment_id: UUID + predecessor_submission_id: UUID | None = None + summary: str = Field(default="", max_length=64 * 1024) + contributor_attestation: str = Field(default="", max_length=64 * 1024) + revision_preparation_id: UUID | None = None + revision_preparation_sha256: Sha256 | None = None + + @field_validator("summary", "contributor_attestation") + @classmethod + def packet_text(cls, value: str) -> str: + """Reject unsupported header text rather than silently rewriting it.""" + if value != value.strip() or any(not 32 <= ord(char) <= 126 for char in value): + raise ValueError("submission packet must be printable ASCII without edge whitespace") + return value + + @model_validator(mode="after") + def revision_pair(self) -> Self: + """Require complete acknowledgement selectors and a revision predecessor.""" + if (self.revision_preparation_id is None) != (self.revision_preparation_sha256 is None): + raise ValueError("revision acknowledgement requires both selectors") + if self.predecessor_submission_id is None and self.revision_preparation_id is not None: + raise ValueError("initial submission cannot acknowledge a revision") + return self + + def metadata_sha256(self) -> str: + """Hash exact metadata using one versioned, domain-separated schema.""" + return canonical_json_hash({ + "schema_version": "workstream.submission_intake_metadata.v1", + **self.model_dump(mode="json"), + }) + + +class SubmissionSourceLocation(_IntakeValue): + """Server-selected source address inside the existing claimed ART namespace. + + The namespace ID references ART's existing immutable namespace record. The + profile must match that record at every owner boundary. It is not a freely + selectable endpoint. The adapter alone applies the configured key prefix. + """ + + operation_id: UUID + namespace_id: UUID + provider_profile: str = Field(min_length=1, max_length=100) + + @field_validator("operation_id", "namespace_id") + @classmethod + def record_identity(cls, value: UUID) -> UUID: + """Check record shape; only the durable owner proves ID provenance.""" + if value.version != 7: + raise ValueError("submission source requires UUIDv7 record identities") + return value + + @field_validator("provider_profile") + @classmethod + def profile_name(cls, value: str) -> str: + """Keep the profile an identifier, never a locator or credential.""" + if any(char not in "abcdefghijklmnopqrstuvwxyz0123456789_-" for char in value): + raise ValueError("submission source provider profile is invalid") + return value + + @property + def object_ref(self) -> str: + """Return the operation-owned relative key without a caller path field.""" + return f"submission-source/v1/{self.operation_id}/bundle.zip" + + +class SealedSubmissionSource(_IntakeValue): + """Exact completed object identity, independent of any expiring read grant. + + SHA/count describe original ZIP bytes, not ETag or semantic manifest. The + generation is opaque: AWS uses VersionId; other providers must qualify an + equivalent immutable identity. An EOF-only operation cannot construct this + value until its owner resolves and records complete-object custody. + """ + + location: SubmissionSourceLocation + provider_generation: str = Field(min_length=1, repr=False) + raw_sha256: Sha256 + raw_byte_count: int = Field(ge=1, le=MAXIMUM_SUBMISSION_ZIP_BYTES) + sealed_upload_fence: int = Field(ge=1) + media_type: Literal["application/zip"] = "application/zip" + + @model_validator(mode="after") + def versioned_aws_source(self) -> Self: + """The qualified AWS profile cannot accept an unversioned null version.""" + if self.location.provider_profile == "aws-s3-v1" and self.provider_generation == "null": + raise ValueError("AWS submission source requires an immutable version") + return self + + def source_sha256(self) -> str: + """Bind every durable source fact; never include delivery credentials.""" + return canonical_json_hash({ + "schema_version": "workstream.sealed_submission_source.v1", + **self.model_dump(mode="json"), + }) diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py new file mode 100644 index 000000000..243565daf --- /dev/null +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -0,0 +1,168 @@ +"""Exact command/source identity proof; no database or provider claims.""" + +import hashlib +import json +from uuid import UUID, uuid4 + +import pytest +from pydantic import ValidationError + +from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, + SubmissionIntakeMetadata, + SubmissionSourceLocation, +) + + +OPERATION = UUID("019a0000-0000-7000-8000-000000000001") +NAMESPACE = UUID("019a0000-0000-7000-8000-000000000002") +TASK = UUID("019a0000-0000-7000-8000-000000000003") +ASSIGNMENT = UUID("019a0000-0000-7000-8000-000000000004") +PREDECESSOR = UUID("019a0000-0000-7000-8000-000000000005") +REVISION = UUID("019a0000-0000-7000-8000-000000000006") +SHA = "sha256:" + "a" * 64 + + +def metadata(**updates): + return SubmissionIntakeMetadata.model_validate({ + "task_id": TASK, "assignment_id": ASSIGNMENT, **updates, + }) + + +def location(**updates): + return SubmissionSourceLocation.model_validate({ + "operation_id": OPERATION, "namespace_id": NAMESPACE, + "provider_profile": "aws-s3-v1", **updates, + }) + + +def source(**updates): + return SealedSubmissionSource.model_validate({ + "location": location(), "provider_generation": "opaque/version+1=", + "raw_sha256": SHA, "raw_byte_count": 123, "sealed_upload_fence": 1, + **updates, + }) + + +def test_metadata_canonical_fixture_and_round_trip_preserve_exact_packet(): + value = metadata(summary="A B", contributor_attestation="I did this.") + # Independent literal fixture fixes field names, nulls and domain separation. + canonical = ( + '{"assignment_id":"019a0000-0000-7000-8000-000000000004",' + '"contributor_attestation":"I did this.","predecessor_submission_id":null,' + '"revision_preparation_id":null,"revision_preparation_sha256":null,' + '"schema_version":"workstream.submission_intake_metadata.v1",' + '"summary":"A B","task_id":"019a0000-0000-7000-8000-000000000003"}' + ) + assert value.metadata_sha256() == "sha256:" + hashlib.sha256(canonical.encode()).hexdigest() + restored = SubmissionIntakeMetadata.model_validate_json(value.model_dump_json()) + assert restored == value + assert restored.summary == "A B" + assert metadata().summary == metadata().contributor_attestation == "" + assert metadata(summary="x" * 65536).summary == "x" * 65536 + + +@pytest.mark.parametrize("field", ["task_id", "assignment_id", "predecessor_submission_id", + "summary", "contributor_attestation", + "revision_preparation_id", "revision_preparation_sha256"]) +def test_every_metadata_selector_participates_in_replay_identity(field): + original = metadata(predecessor_submission_id=PREDECESSOR, + revision_preparation_id=REVISION, revision_preparation_sha256=SHA) + replacement = ( + uuid4() if field.endswith("_id") else + "sha256:" + "b" * 64 if field.endswith("_sha256") else "changed" + ) + changed = SubmissionIntakeMetadata.model_validate({**original.model_dump(), field: replacement}) + assert changed.metadata_sha256() != original.metadata_sha256() + + +@pytest.mark.parametrize("text", [" leading", "trailing ", "line\nbreak", "tab\tvalue", + "café", "\x7f", "x" * 65537]) +@pytest.mark.parametrize("field", ["summary", "contributor_attestation"]) +def test_packet_rejects_unrepresentable_headers_without_normalization(field, text): + with pytest.raises(ValidationError): + metadata(**{field: text}) + + +@pytest.mark.parametrize("updates", [ + {"revision_preparation_id": REVISION}, + {"revision_preparation_sha256": SHA}, + {"revision_preparation_id": REVISION, "revision_preparation_sha256": SHA}, + {"predecessor_submission_id": PREDECESSOR, "revision_preparation_id": REVISION}, + {"predecessor_submission_id": PREDECESSOR, "revision_preparation_sha256": SHA}, +]) +def test_revision_acknowledgement_cannot_be_partial_or_initial(updates): + with pytest.raises(ValidationError): + metadata(**updates) + # Whether a revision requires acknowledgement is still a TASK policy check. + assert metadata(predecessor_submission_id=PREDECESSOR).revision_preparation_id is None + + +def test_source_address_is_operation_bound_and_opaque_generation_round_trips(): + value = source() + assert value.location.object_ref == f"submission-source/v1/{OPERATION}/bundle.zip" + assert SealedSubmissionSource.model_validate_json(value.model_dump_json()) == value + assert value.provider_generation == "opaque/version+1=" + assert value.raw_sha256 == SHA + # The raw identity is not the identity of the complete source descriptor. + assert value.source_sha256() != value.raw_sha256 + other = source(location=location(operation_id=REVISION)) + assert other.raw_sha256 == value.raw_sha256 + assert other.location.object_ref != value.location.object_ref + assert other.source_sha256() != value.source_sha256() + + +@pytest.mark.parametrize("updates", [ + {"location": location(namespace_id=REVISION)}, + {"location": location(provider_profile="qualified-managed-v1")}, + {"provider_generation": "other-version"}, + {"raw_sha256": "sha256:" + "b" * 64}, + {"raw_byte_count": 124}, + {"sealed_upload_fence": 2}, +]) +def test_source_identity_detects_substitution_of_every_custody_fact(updates): + assert source(**updates).source_sha256() != source().source_sha256() + + +@pytest.mark.parametrize("updates", [ + {"raw_byte_count": 0}, {"raw_byte_count": MAXIMUM_SUBMISSION_ZIP_BYTES + 1}, + {"raw_byte_count": True}, {"raw_byte_count": "123"}, + {"sealed_upload_fence": 0}, {"sealed_upload_fence": True}, + {"provider_generation": ""}, {"provider_generation": "null"}, + {"provider_generation": None}, {"raw_sha256": "a" * 64}, + {"raw_sha256": "sha256:" + "A" * 64}, {"media_type": "application/octet-stream"}, + {"signed_url": "https://storage.invalid/private?credential=secret"}, + {"host_path": "/tmp/bundle.zip"}, {"manifest_sha256": SHA}, +]) +def test_sealed_source_rejects_unsealed_coercive_or_authority_bearing_inputs(updates): + with pytest.raises(ValidationError): + source(**updates) + assert source(raw_byte_count=MAXIMUM_SUBMISSION_ZIP_BYTES).raw_byte_count == 524288000 + + +@pytest.mark.parametrize("updates", [ + {"operation_id": uuid4()}, {"namespace_id": uuid4()}, + {"operation_id": str(OPERATION)}, {"provider_profile": "https://storage.invalid"}, + {"object_ref": "submission-source/v1/foreign/bundle.zip"}, + {"idempotency_key": OPERATION}, +]) +def test_location_cannot_take_a_caller_path_or_nonrecord_selector(updates): + with pytest.raises(ValidationError): + location(**updates) + + +def test_frozen_values_revalidate_nested_instances_and_reject_unknown_command_fields(): + value = source() + with pytest.raises(ValidationError): + value.location.operation_id = REVISION + with pytest.raises(ValidationError): + value.raw_byte_count = 42 + with pytest.raises(ValidationError): + source(location=location().model_copy(update={"operation_id": uuid4()})) + with pytest.raises(ValidationError): + metadata(bearer_token="secret") + with pytest.raises(ValidationError): + SubmissionIntakeMetadata.model_validate_json(json.dumps({ + "task_id": str(TASK), "assignment_id": str(ASSIGNMENT), "summary": 1, + })) diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 4adbf86a8..eceebdd9f 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -107,6 +107,12 @@ CLI and MCP cannot edit email. Optional issuer name seeds first admission; subse display-name edits, including clearing it, remain local. Identity and authority remain bound to issuer/subject, not email; signed email is not proof of mailbox verification. +The [single-request submission specification](spec_submission_execution.md) is +the approved target for [WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). +Its first boundary defines immutable command/source values only. Durable intake, +streaming custody, one-session PRE, finalization and client cutover remain planned; +the active API still uses preparation followed by admission-consuming submission. + ## Product Goal Workstream turns governed work into trusted `ContributionRecord` facts: diff --git a/docs/spec_submission_execution.md b/docs/spec_submission_execution.md new file mode 100644 index 000000000..202f9bc8e --- /dev/null +++ b/docs/spec_submission_execution.md @@ -0,0 +1,1373 @@ +# Workstream submission and execution specification + +**Version: v0.1** +**Design:** one submission request, one object store, inline PRE, durable continuation +**Prepared:** 11 November 2026 +**Repository baseline:** [Flow-Research/workstream at 01299e36a486c948be6f05f4e122dea39b993a04](https://github.com/Flow-Research/workstream/tree/01299e36a486c948be6f05f4e122dea39b993a04) +**Status:** implementation specification for the user-approved architecture. This document does not claim the changes are implemented. + +## Reading and implementation guide + +Read sections 1–4 first for the complete design. Sections 5–18 define the contracts and failure behavior. Sections 19–23 define scale, migration, implementation order and acceptance evidence. Section 24 identifies deployment values that must be supplied rather than guessed. + +The terms **MUST**, **MUST NOT**, **SHOULD** and **MAY** distinguish requirements, prohibited behavior, recommendations with a documented reason for deviation, and explicitly permitted implementation freedom. Unless a section says “current baseline,” it describes the required target behavior. + +An implementation agent MUST read this entire specification and the repository's current owner contracts before changing code. It MUST implement the selected behavior, trace affected callers, and preserve unrelated behavior. If a needed product decision is absent, source evidence contradicts a required invariant, or a deployment value cannot be resolved from an approved profile, the agent MUST ask a focused follow-up question using section 24. It MUST NOT silently select another architecture, invent a business rule, weaken a guard, or claim a guessed value was approved. + +Internal class and private function names may follow existing repository conventions. Public fields, state meanings, transaction boundaries, identity guarantees, and error semantics specified here are contractual. Mechanical naming choices do not require a product decision. + +### Contents + +1. [Purpose and fixed decisions](#1-purpose-and-fixed-decisions) +2. [Scope and ownership](#2-scope-and-ownership) +3. [Terminology](#3-terminology) +4. [Complete submission journey](#4-complete-submission-journey) +5. [The single contributor API](#5-the-single-contributor-api) +6. [Idempotency and concurrent requests](#6-idempotency-and-concurrent-requests) +7. [Operation and task states](#7-operation-and-task-states) +8. [Durable data and constraints](#8-durable-data-and-constraints) +9. [Transaction boundaries and authority](#9-transaction-boundaries-and-authority) +10. [Streaming into the existing object store](#10-streaming-into-the-existing-object-store) +11. [Input identity and platform defaults](#11-input-identity-and-platform-defaults) +12. [One PRE execution session](#12-one-pre-execution-session) +13. [The execution adapter contract](#13-the-execution-adapter-contract) +14. [Durable finalization and POST dispatch](#14-durable-finalization-and-post-dispatch) +15. [POST, review, revision and acceptance](#15-post-review-revision-and-acceptance) +16. [Failure and recovery rules](#16-failure-and-recovery-rules) +17. [Object and runtime cleanup](#17-object-and-runtime-cleanup) +18. [Limits, quotas and timing](#18-limits-quotas-and-timing) +19. [Scaling and operations](#19-scaling-and-operations) +20. [Migration and cutover](#20-migration-and-cutover) +21. [Repository change map](#21-repository-change-map) +22. [Implementation sequence](#22-implementation-sequence) +23. [Acceptance evidence and completion gate](#23-acceptance-evidence-and-completion-gate) +24. [Unresolved values and follow-up protocol](#24-unresolved-values-and-follow-up-protocol) +25. [Sources and design rationale](#25-sources-and-design-rationale) + +## 1. Purpose and fixed decisions + +Workstream accepts a contributor's ZIP only after its platform checks and the project's PRE quality checker pass. The contributor receives that initial result in the same request. Workstream then durably creates the retained Submission and runs POST before any required human review or final acceptance. + +The design keeps bytes in one durable location and gives each component a clear job. The API handles the current upload and PRE interaction. The object store holds the original ZIP. The execution provider runs isolated checks. Durable workers complete accepted work after the foreground handoff. PostgreSQL determines ownership and lifecycle truth. + +### 1.1 Decision ledger + +| ID | Required decision | +| --- | --- | +| D01 | Keep this design and implementation within unreleased **v0.1**. | +| D02 | Expose one contributor submission mutation, used by the CLI and adapters. Upload, PRE feedback and the accepted handoff occur in that one request. | +| D03 | Stream the raw ZIP through the Workstream API into the **existing single artifact bucket/provider namespace** using bounded buffers. Do not retain a complete ZIP in API scratch or memory. | +| D04 | Allocate one unique, immutable object key per intake operation. PRE, registration, POST and retained evidence refer to that same object and generation. No second bucket, copy, rename, promotion or re-upload is part of this flow. | +| D05 | Create a small durable operation record before bytes are written. A completed upload may have an operation record without a retained artifact or Submission record. | +| D06 | Start PRE after the upload is complete. A slow contributor upload must not occupy a live PRE sandbox. | +| D07 | Run the Workstream default checks and exactly one selected project PRE image in **one PRE session**. The platform supplies its trusted code separately from the project image. | +| D08 | Every approved project policy requires exactly one PRE image and exactly one POST image, pinned to approved immutable identities. One image can implement many project requirements. | +| D09 | PRE failure returns actionable findings inline. It creates no Submission, changes no eligible task into evaluation, and consumes no revision round. | +| D10 | On PRE pass, the API commits the accepted operation, task `evaluation_pending` transition and finalization outbox event in **one short database transaction before returning success**. | +| D11 | Durable workers handle the remainder: register the existing object, create the formal Submission, reserve POST and dispatch it. They do not repeat PRE or upload the ZIP again. | +| D12 | A task already awaiting finalization/evaluation does not accept a new submission. Exact idempotent replay observes the existing operation. | +| D13 | Preserve existing POST execution, governed revision, review, final acceptance and contribution-record behavior. Adapt source custody where required; do not redesign POST internals. | +| D14 | Smol is an execution adapter. Core contracts must support a qualified managed provider without requiring access to its host. Qualification is required; a generic create/delete API alone is not enough. | +| D15 | Cleanup runs initially every **12 hours**, considers only eligible objects at least **2 hours** old, and checks durable ownership before deletion. Passed, pending, retrying, stalled and retained inputs remain protected regardless of age. | +| D16 | Keep the approximately **60-second PRE experience target** separate from contributor upload and later durable work. All actual execution and request lifetimes still have explicit finite limits. | +| D17 | Keep raw ZIP SHA-256, exact raw byte count and canonical semantic manifest identity distinct. These bind checks and records to the contributor's exact input. | +| D18 | Prefer existing owners, typed ports, PostgreSQL, outbox and Celery. Add only the contracts and state needed for this flow. | + +### 1.2 Non-negotiable invariants + +- **I01 — one source:** an accepted operation's original ZIP key, provider generation, raw SHA and byte count never change. +- **I02 — accepted means durable:** no accepted response is emitted unless the PRE-pass transaction has committed. +- **I03 — acceptance closes intake:** that transaction makes the task `evaluation_pending` and prevents another new contributor submission. +- **I04 — no premature Submission:** no retained submission artifact, formal Submission or POST dispatch exists because an upload merely completed or a checker printed “pass.” +- **I05 — one logical continuation:** one accepted operation produces at most one formal Submission and one logical initial POST dispatch. +- **I06 — no deletion of accepted work:** a missing formal artifact row, old age or expired Celery worker lease is never sufficient deletion authority. +- **I07 — trusted identity:** project code cannot assert or replace trusted input identity, platform-default results, image identity or acceptance authority. +- **I08 — exact locked context:** a Celery worker finishes the command accepted under its recorded assignment, predecessor and rules. It does not silently rebase it. +- **I09 — failure separation:** QC rejection, infrastructure failure, and governed POST/review outcomes remain different facts. +- **I10 — bounded work:** upload buffers, admission queues, sandboxes, output, retries and cleanup batches have finite bounds. +- **I11 — provider independence:** the core never requires a provider host path, a Smol binary, a host Unix socket or guest transport as universal execution facts. +- **I12 — durable truth:** database ownership and fenced results determine progress; message delivery and object existence do not. + +## 2. Scope and ownership + +### 2.1 Included changes + +This specification replaces the current contributor preparation-then-submit path, API-local submission ZIP custody, separate PRE intake/export/project execution handoff, post-PRE object upload, and SHA-derived-key assumption for new submission source objects. + +It introduces the early intake operation, bounded streaming object receipt, one-session PRE, atomic accepted handoff, owner-qualified finalization, operation-aware cleanup, truthful physical-object accounting, and updated clients/read models. + +It also tightens project policy cardinality and removes provider-host assumptions from the common execution boundary. + +### 2.2 Preserved behavior + +Preserve: + +- Flow Identity authentication and Workstream's own authorization decisions. +- Task assignments, locked guides and policy lineage, exact predecessor and revision acknowledgement rules. +- Canonical manifest representation and existing Workstream default-check semantics. +- Existing ART ownership, namespace/readiness checks and verification for other artifact producers. +- Existing CHECKERS terminal-result ownership, policy evaluation and governed lifecycle routing. +- Existing POST model, trial/build and forge capabilities where selected and supported. +- Human review required by default, and the existing shared final-acceptance operation when review is not required. +- Atomic final-acceptance/contribution-record/award behavior. +- Retained historical data and audit evidence. + +Shared scratch services used by guide documents, task imports, checker outputs or other flows remain unless a separately traced change removes their last consumer. Removing submission API scratch does not authorize deleting the shared subsystem. + +### 2.3 Component responsibilities + +| Component | Owns | Must not acquire | +| --- | --- | --- | +| Contributor CLI/client | ZIP, packet, assignment/revision selectors, idempotency key, display of outcomes | Storage coordinates, trusted checksums, lifecycle authority | +| API command/composition boundary | Current request orchestration, authorization, bounded streaming, synchronous PRE, accepted handoff | Long-lived ZIP scratch, background continuation of failed foreground PRE | +| ART module | Object custody, raw/manifest binding, physical reservations, registration and cleanup authority | Task acceptance or project QC verdict ownership | +| TASK module | Submission eligibility, active operation ownership on the task, accepted task transition, formal Submission and dispatch lineage | Storage-provider mechanics | +| CHECKERS module | Selected image/policy validation, execution leases, validated terminal evidence, POST routing inputs | Arbitrary changes to task acceptance policy | +| Execution adapter/runtime | Qualified isolation, trusted input loading/default execution, project execution, bounded results, runtime cleanup | Object retention decisions or contributor authority | +| Object store | Durable original object bytes under exact references | Product eligibility or database lifecycle truth | +| Celery workers/outbox | Delivery and invocation of existing owner commands after accepted handoff | Independent product state machines or direct bypasses of owner checks | +| PostgreSQL | Durable ownership, state, unique identities, fences, outbox and immutable evidence | Hosting the ZIP body | +| Redis/broker | Transport of work notifications | Sole custody of accepted work | + +The API, Celery workers and runtime may share today's server. Moving runtime execution to dedicated servers changes placement and configuration within the adapter, not this ownership model. + +## 3. Terminology + +| Term | Meaning | +| --- | --- | +| Intake operation | Durable metadata for one submission request and its object. It exists before upload and may end without a Submission. | +| Accepted handoff | The committed PRE-pass transaction that sets the task to `evaluation_pending` and schedules durable finalization. | +| Formal Submission | The immutable product record created by the Celery worker after accepted handoff and exact object registration. | +| Source object | The original uploaded ZIP at one generated object key and immutable provider generation. | +| Provider generation | Opaque storage identity that pins an exact object version. In the current AWS profile this is S3 `VersionId`. | +| Retained artifact | ART records and binding establishing that an exact source object is retained evidence for a formal Submission. | +| Raw identity | SHA-256 over the exact ZIP bytes, plus their exact count. | +| Semantic identity | Existing canonical manifest identity over normalized paths, types, file contents, sizes and executable bits. | +| PRE | Fast initial quality gate before an accepted submission handoff. Passing PRE is not final acceptance. | +| POST | Evaluation of a formal submitted task before review/acceptance, using the selected POST policy. | +| Platform bootstrap / supervisor | Workstream-controlled code inside the execution session that loads and verifies input, runs protected defaults, isolates the project process and reports trusted facts. It is not a second VM or another public service. | +| Lease and fence | Time-bounded ownership plus a monotonically changing generation. An expired or replaced owner cannot publish a current result. | +| Finalization | Durable registration of the existing object and creation of Submission plus POST dispatch. It contains no source-object copy. | +| Operational stall | An accepted operation that needs intervention after its permitted automatic retries. Its task/input remain protected and pending. | + +“Claimed” in ordinary conversation means assigned work. The current initial submission-eligible persisted task status is `in_progress` with the active assignment; this design does not add a literal `claimed` status. Governed revisions use `needs_revision`. + +## 4. Complete submission journey + +### 4.1 Successful request and continuation + +1. The contributor calls the single submit endpoint with the ZIP body, current assignment, packet, revision selectors when applicable, and an idempotency key. +2. Workstream checks authentication, task/assignment authority, current eligibility, packet validity, locked images/configuration and upload admission. +3. A short transaction creates the intake operation, reserves physical capacity, records its generated object key and installs the task's active-operation guard. +4. The API streams the original ZIP to the existing object store, hashes and counts it, and applies backpressure. The execution provider has not started a PRE sandbox yet. +5. At EOF, Workstream records completion intent, completes the immutable object and records its exact provider generation. +6. Workstream admits one PRE session with the immutable source descriptor, approved resource profile, platform defaults, project PRE image and locked context. +7. The trusted loader reads that object, verifies raw SHA/count, safely extracts it, and builds the canonical manifest. The platform defaults run; then the selected project image runs if defaults permit it. +8. CHECKERS validates the bounded response against the recorded request and current fence. The original ZIP and verified input remain read-only to project code. +9. On pass, the API revalidates the task/context and atomically records the accepted operation, `evaluation_pending` and finalization outbox event. +10. The API returns `202 Accepted` with the durable operation receipt and PRE findings. The contributor has completed the submission interaction. +11. A durable worker registers the same object, creates the formal Submission, reserves POST and writes the POST outbox event in one composed database transaction. +12. POST obtains the same original object through the execution adapter and follows existing evaluation, review/revision and acceptance rules. + +The PRE runtime session can be destroyed after its result is safely captured. Neither Celery worker finalization nor POST depends on that VM remaining alive. + +### 4.2 Flow diagram + +```mermaid +flowchart TD + C["Contributor: one submit request"] --> A["API: authorize and reserve operation"] + A --> S["Single object store: stream original ZIP"] + S --> P["One PRE session: defaults and project image"] + P --> V{"Validated PRE result"} + V -->|fails| F["Inline findings; no Submission"] + V -->|passes| H["Atomic handoff: task evaluation_pending and outbox"] + H --> R["202 receipt to contributor"] + H --> W["Durable worker: register same object and create Submission"] + W --> O["POST using the same source object"] + O --> G["Existing review, revision or final acceptance"] +``` + +The arrow from storage to PRE represents an input read. The arrow to POST also requires an input read by the provider/runtime. Giving a sandbox a source reference does not eliminate transfer of the bytes it must inspect. It eliminates a Celery worker downloading, re-uploading or copying the source to make it available. + +### 4.3 Observable meaning at each point + +| Point | Task | Intake operation | Formal Submission / retained artifact | +| --- | --- | --- | --- | +| Before request | `in_progress` or eligible `needs_revision` | None | Prior history may exist | +| Receiving ZIP / running PRE | Same eligible status, guarded by active operation | Active | No new records | +| PRE rejected / pre-handoff infrastructure failure | Same eligible status once operation terminalizes | Rejected/failed/abandoned | No new records | +| Accepted response | `evaluation_pending` | `finalization_pending` | May not exist yet | +| Celery Worker commits finalization | `evaluation_pending` | `finalized` | Both exist and are exactly bound | +| POST/review advances | Existing governed lifecycle | Finalized history | Immutable retained records | + +The task's pending-operation projection explains the gap between accepted receipt and formal Submission. A client must not infer failure or readiness to submit again from an empty Submission list. + + + +## 5. The single contributor API + +### 5.1 Mutation + +Replace the current JSON admission-consuming mutation with: + +```http +POST /api/v1/tasks/{task_id}/submissions +Content-Type: application/zip +Idempotency-Key: +X-Task-Assignment-Id: +Authorization: + + +``` + +Keep action identity `submission.create`. This endpoint is the only contributor mutation for uploading and submitting a bundle. + +The old public `POST /tasks/{task_id}/submission-bundle-preparations` and the public “prepare, receive admission ID, submit admission” contract are removed from the active v0.1 API, CLI and MCP surfaces together. Do not leave a compatibility alias or a second supported submission path. Internal ART admission/registration concepts may remain where they protect owner invariants. + +### 5.2 Request contract + +| Input | Required semantics | +| --- | --- | +| `task_id` | Valid UUID and an authorized task; preserve non-disclosing authorization behavior. | +| `Idempotency-Key` | Exactly one valid UUID header. Scope: authenticated actor plus key; a key cannot select a different task or packet later. | +| `X-Task-Assignment-Id` | Exactly one valid UUID header; must identify the currently authorized assignment for a new operation. | +| `Content-Type` | `application/zip`. Reject other media types. | +| `Content-Encoding` | Absent or `identity`. Do not transparently transform/compress/decompress the submitted body. | +| `Content-Length` | If supplied, valid and within the permitted raw limit; verify actual EOF count equals it. If absent, reserve the permitted maximum and enforce the count while streaming. Reject ambiguous or contradictory framing at the HTTP edge. | +| `X-Submission-Summary` | Optional; omitted means empty string. Preserve current printable-ASCII header semantics, at most 64 KiB, without leading/trailing header whitespace. | +| `X-Contributor-Attestation` | Same encoding/size rules as summary. Omission preserves existing warning behavior. | +| `X-Predecessor-Submission-Id` | Exactly the current predecessor when submitting a governed revision; absent for the initial submission. No client-selected replacement of the predecessor. | +| `X-Revision-Preparation-Id` and `X-Revision-Preparation-Sha256` | Both present or both absent. Required and validated where the existing governed revision contract requires acknowledgement. | +| Body | Nonempty original ZIP; actual bytes are authoritative. No multipart/form-data parser or base64 transformation at the backend submit boundary. | + +Reject duplicate occurrences of every selector/packet header rather than accepting one framework-selected value. Treat text exactly as validated; do not trim, normalize or rewrite a packet while hashing it. Clients and edge/header limits must support the published packet limits consistently. A larger Unicode/multipart packet redesign is not part of this change. + +The client need not supply an authoritative checksum or make a separate preparation call. An optional client-side source-change check in the CLI is local protection; it does not replace server hashing. + +Authentication and metadata/known-capacity rejection happen before body consumption where the HTTP stack permits it. Backpressure and early connection termination must be verified through the actual proxy/server stack; an early API decision does not itself prove the upstream proxy avoided buffering. + +### 5.3 Accepted response + +Return `202` only after transaction T4 in section 9 commits: + +```json +{ + "operation_id": "019a0000-0000-7000-8000-000000000001", + "task_id": "019a0000-0000-7000-8000-000000000002", + "assignment_id": "019a0000-0000-7000-8000-000000000003", + "status": "accepted", + "accepted_at": "2026-11-11T10:00:00Z", + "task_status_at_acceptance": "evaluation_pending", + "processing_stage_at_acceptance": "finalization_pending", + "replayed": false, + "pre_submission_results": [] +} +``` + +The IDs and timestamp above are examples, not prescribed values. The receipt records the acceptance snapshot. A replay later may occur after POST, review or acceptance; it must not claim the task is currently still pending. The accepted payload is stable apart from `replayed` and ordinary response correlation metadata. + +The initial receipt deliberately does not fabricate a Submission ID, version or evaluation request ID. Those exist after Celery worker finalization and are available from the authorized read projection. The API may not wait for finalization merely to fill those fields. + +Preserve nonblocking PRE warnings and findings using the existing bounded public projection. A displayed message should say the submission passed initial checks and is awaiting/undergoing evaluation, not that the task has been finally accepted. + +### 5.4 Failure envelope and status codes + +Use the existing structured error envelope, correlation/request IDs, sanitization and authorization-concealment conventions. The fields in this table are domain codes, not an alternative error transport. + +| HTTP | Code/category | Meaning and required behavior | +| --- | --- | --- | +| 404 | `submission_unavailable` | Task/assignment/operation not available to this actor. Do not reveal cross-actor state. | +| 409 | `submission_state_conflict` | A new request targets a task that is no longer submission-eligible. | +| 409 | `submission_operation_in_progress` | Another active operation owns this task, or this exact key is still in an unfinished foreground phase. Return its ID only if authorized. | +| 409 | `submission_idempotency_conflict` | Same actor/key with different metadata or a verified different raw body. | +| 409 | `submission_operation_terminal` | A pre-seal operation ended without a complete input identity; it cannot be resumed or reused. A new key is required once its task guard is released. | +| 409 | Existing revision/context codes | Preserve revision limit/deadline, predecessor, acknowledgement-context and locked-rule conflict semantics. | +| 413 | `submission_archive_limit_exceeded` | Declared or actual raw ZIP exceeds the permitted ceiling. Stop upload; retain cleanup ownership. | +| 415 | `submission_media_type_unsupported` | Unsupported content type or content encoding. | +| 422 | `submission_packet_invalid` | Invalid selectors, packet or revision acknowledgement syntax; preserve more specific existing revision codes. | +| 422 | `pre_submission_checker_failed` | Validated platform/project QC rejection. Include bounded actionable PRE results; `eligible_to_submit=false`; no new Submission. | +| 408 | `submission_upload_timeout` | The client upload breached its explicit idle/total upload limit before handoff. No accepted work is implied. | +| 429 | `submission_capacity_exceeded` | Admission or quota/rate bound prevents this request from proceeding. Include a finite retry hint where one is known. | +| 503 | `submission_infrastructure_unavailable` | Storage/runtime/DB/protocol failure before accepted handoff; not a QC verdict. | +| 503 | `submission_outcome_unknown` | The API cannot determine whether its acceptance commit succeeded. Client must observe/replay the same key; it must not blindly create new work. | + +A platform-safe-archive rejection is QC feedback. A transport object mismatch, untrusted runtime response, unavailable provider, Celery worker failure or expired execution deadline is infrastructure failure unless an existing approved checker contract explicitly identifies a completed deterministic QC result. + +For an operation that reached a complete raw identity, persist the original terminal response classification and bounded findings for exact replay. Do not persist secrets or raw attacker-controlled logs in public error details. + +### 5.5 Read-only progress + +Add the owner-backed read: + +```http +GET /api/v1/tasks/{task_id}/submission-operations?operation_id= +GET /api/v1/tasks/{task_id}/submission-operations?idempotency_key= +``` + +These are two selectors for the same read route; exactly one is required. They are not additional submission actions. A key lookup is actor-scoped. Read access follows the existing contributor/management authorization model; it never grants access merely because an ID is known. + +Return one closed JSON object with the following fields; fields listed as nullable remain present with JSON null rather than being omitted: + +| Field | Type and meaning | +| --- | --- | +| `operation_id`, `task_id`, `assignment_id` | UUID strings identifying this operation and its original task/assignment | +| `idempotency_key` | Original caller UUID, revealed only under the authorized read contract | +| `operation_state` | One of the eight lifecycle values in section 7.1 | +| `processing_stage` | Closed stage value defined below, derived from this operation's own evidence | +| `accepted_at` | UTC RFC 3339 timestamp or null | +| `task_status_at_acceptance` | `evaluation_pending` or null | +| `current_task_status` | Current existing TASK status enum or null when current-task visibility is not authorized; contextual information, not this historical operation's outcome | +| `submission_id` | UUID string or null before T5 | +| `submission_version` | Positive integer or null before T5, using the existing Submission version representation | +| `evaluation_request_id` | UUID string or null before T5 | +| `pre_submission_results` | Bounded array using the existing public PRE result projection; empty until results are available | +| `failure_code` | Stable sanitized owner error code or null; no raw provider exception | +| `operationally_stalled` | Boolean; true only when the relevant finalization/evaluation owner records a stall | +| `next_action` | One of `wait`, `correct_and_submit_new_key`, `retry_new_key_after_terminal`, `inspect_governed_outcome` | + +Do not expose provider keys, signed URLs, credentials or host coordinates. + +Use these processing stages: `receiving`, `pre_checking`, `finalization_pending`, `evaluation_pending`, `evaluation_running`, `review_pending`, `needs_revision`, `accepted`, `rejected`, `failed`, `abandoned`, `cancelled` and `operationally_stalled` where supported by their actual owner facts. Do not infer “evaluation_running” from the task status alone. + +Derive `processing_stage` from this operation's own PRE, Submission, evaluation and governed outcome associations. Never derive a historical operation's stage from the task's latest Submission or current status; the task may have advanced to a newer revision. + +| Operation/evidence | `processing_stage` | `next_action` | +| --- | --- | --- | +| `receiving` / `pre_checking` | Matching state | `wait` | +| `finalization_pending` without stall | `finalization_pending` | `wait` | +| Relevant finalization/evaluation owner explicitly stalled | `operationally_stalled` | `wait` | +| Finalized; its evaluation queued/retrying or actively running | `evaluation_pending` / `evaluation_running` from the actual evaluation owner | `wait` | +| Finalized; its governed review/revision/acceptance/rejection outcome exists | Matching `review_pending`, `needs_revision`, `accepted` or `rejected` | `inspect_governed_outcome` | +| Terminal PRE `rejected` | `rejected` | `correct_and_submit_new_key` only when TASK currently permits new intake; otherwise `inspect_governed_outcome` | +| Terminal pre-handoff `failed` / `abandoned` | Matching state | `retry_new_key_after_terminal` only when TASK currently permits new intake; otherwise `inspect_governed_outcome` | +| Explicitly `cancelled` | `cancelled` | `inspect_governed_outcome` | + +For a terminal operation, “TASK currently permits new intake” means this reader has current contributor submit authority for this operation's task and original still-active assignment, with compatible current predecessor/revision context and no active-operation guard. Management-only readers and contributors whose assignments have closed receive `inspect_governed_outcome`. Do not recommend a submission merely because the task is eligible for somebody else. + +No next-action value bypasses current revision acknowledgement or authorization. Derive it through the TASK read owner, not client guesswork. Preserve existing historical-read concealment: permission to read an old operation does not reveal the reassigned task's current status. A missing/corrupt finalized association is an operational integrity error, not permission to infer progress from another Submission. + +Extend existing task/work-context reads with its active/pending operation and stage. While a new revision awaits finalization, show the predecessor as historical and the new operation as pending; do not present the previous Submission as the newly submitted work. + +## 6. Idempotency and concurrent requests + +### 6.1 Exact identity + +The idempotency namespace is `(actor_profile_id, idempotency_key)`. Store the original identity-link provenance and packet. Token strings and expiry timestamps are not request identity. + +Metadata identity includes task, assignment, predecessor, summary, attestation, and revision acknowledgement. Raw identity adds server-observed ZIP SHA-256 and byte count. Canonical hashing uses existing Workstream encoding/domain-separation conventions; there is one explicit schema for this request body, covered by fixtures. + +The operation's accepted context is separately pinned. A later replay uses that original context and result; it must not reinterpret the same key using newly selected project rules. + +### 6.2 New key + +In T1, lock the task, check status/assignment/revision, and claim its active-operation guard under database uniqueness. At most one operation may actively receive, run PRE or await finalization for a task. Do not rely on a process-local semaphore or check-then-insert without a database constraint. + +Different keys racing on one task cannot both enter PRE or both produce accepted work. The loser receives the appropriate conflict before creating another live source write. + +### 6.3 Existing key + +Resolve an existing key under fresh current read authority before applying ordinary new-submission status eligibility. This permits an authorized exact replay after the task has advanced, without allowing a new submission. + +1. Compare immutable request metadata first. Any mismatch is `submission_idempotency_conflict`. +2. If the original has not sealed a complete raw identity and is active, return `submission_operation_in_progress`. Do not claim byte equality and do not start a second upload. +3. If the original ended without a complete identity, return `submission_operation_terminal`. It is not resumable; a new request requires a new key after the original is conclusively terminal. +4. If the original has a complete raw identity, consume the retry body through bounded hash/count into a discard sink. Enforce the same raw/framing limits. Do not create another object or invoke PRE. +5. Different SHA/count is `submission_idempotency_conflict`. Equal bytes return the stored terminal result, or in-progress status for any active `receiving`/`pre_checking` phase. This includes EOF recorded while provider completion is still unresolved. No replay request takes over that phase. +6. An accepted operation replays its accepted receipt. A rejected operation replays its rejection and findings. A completed pre-handoff infrastructure failure replays that recorded failure; it does not rerun PRE. + +Using an operation GET avoids retransmitting a ZIP merely to observe progress. A client disconnect during replay cannot cancel or modify the original operation. + +### 6.4 No resumable intake in this change + +An interrupted pre-acceptance operation is fenced and terminalized under section 16. No Celery worker resumes its request body, quietly completes PRE, or changes its object key into a new attempt. A contributor may submit a new request/key when eligibility is restored. + +Internal retry of a failed object part is permitted only within the same live foreground operation, with bounded retained part buffers, the same immutable identity, and the current lease. It is not a new submission or an unbounded request retry. + +## 7. Operation and task states + +### 7.1 Operation state machine + +Use one ART-owned intake-operation lifecycle: + +| State | Meaning | Allowed forward transitions | +| --- | --- | --- | +| `receiving` | Ownership/reservation committed; upload or bounded completion resolution in progress | `pre_checking`, `failed`, `abandoned`, `cancelled` | +| `pre_checking` | Complete immutable object known; inline PRE admission/execution/validation in progress | `finalization_pending`, `rejected`, `failed`, `abandoned`, `cancelled` | +| `finalization_pending` | PRE-pass handoff committed; task is `evaluation_pending` | `finalized`, or explicitly authorized cancellation under the existing lifecycle contract | +| `finalized` | Formal Submission, retained binding and POST dispatch committed | Terminal intake state; POST owns later evaluation | +| `rejected` | Platform/project PRE returned a validated QC rejection | Terminal | +| `failed` | Foreground infrastructure or context failure conclusively prevented accepted handoff | Terminal | +| `abandoned` | Foreground owner ended/expired without accepted handoff | Terminal | +| `cancelled` | Explicit cancellation with authority/provenance | Terminal | + +Upload sealing is recorded by immutable source fields/timestamps while `receiving`; a separate “uploaded” product state is unnecessary. `finalization_pending` remains the state during Celery worker retries. `stalled_at` and a stable operational reason mark exhausted retries without converting the operation into QC failure. + +Cleanup state is orthogonal: `not_claimed`, `claimed`, `deleted`. It records a deletion obligation without erasing the original rejected/failed result needed for replay. It is prohibited on active, accepted or retained work unless a separately authorized retention/cancellation operation has explicitly made deletion eligible. + +### 7.2 Task relationship + +- T1 installs `active_submission_operation_id` under the TASK owner. The task remains `in_progress` or eligible `needs_revision` during upload/PRE. +- Terminal pre-handoff failure clears that active pointer in the same task/operation transaction, provided the pointer still belongs to that operation. +- T4 keeps the pointer, records accepted ownership, and changes task status directly to `evaluation_pending` through the new authorized handoff operation. +- T5 creates the actual Submission/dispatch and clears the active-operation pointer atomically. The task stays `evaluation_pending`. +- No intermediate task transition back to `submitted` or `in_progress` is permitted during Celery worker finalization. +- Existing historical `submitted` records may remain valid; the new path does not need to persist that intermediate state. +- Assignment release/replacement/readiness operations must respect the active/pending operation guard. Absence of a Submission is not evidence that an accepted assignment may be recycled. + +No new contributor claim-expiry feature is introduced. Existing assignment/lifecycle operations must simply reject incompatible mutations while an operation owns the task. + +## 8. Durable data and constraints + +### 8.1 Intake operation + +Extend the ART owner with one cohesive `SubmissionIntakeOperation` record. Reuse existing owner types and audits; do not create an unrelated upload service/database. + +| Group | Required durable fields/facts | +| --- | --- | +| Identity | Workstream-generated UUIDv7 operation ID; task/project/assignment/actor/identity-link; caller idempotency key; request/correlation IDs | +| Original command | Exact packet and metadata digest; predecessor; revision acknowledgement; original eligible task status; locked guide/rules/PRE/POST/default identities and resource profile | +| Ownership | State; task active pointer relationship; foreground lease ID, generation, expiry; absolute deadlines; created/updated/terminal timestamps | +| Source | Provider/namespace identity; generated object key; upload maximum/reservation; provider upload handle where used; immutable completion intent; raw SHA/count at EOF; sealed provider generation; completion/observation times | +| PRE | Selected run ID; immutable execution-request digest; validated terminal digest; platform input/manifest/default evidence; selected project result and bounded public projection | +| Accepted command | Acceptance authority decision ID; accepted context digest; accepted_at; stable acceptance receipt; unique finalization event identity | +| Continuation | Celery Worker lease/generation; retry count/next retry/error/stalled_at; finalized_at; actual Submission/retained replica/evaluation IDs after T5 | +| Cleanup | Eligibility/last relevant storage activity timestamps; cleanup state/generation; exact deletion targets/obligation; confirmed absence/deletion and quota-release evidence | + +Credentials, signed URLs, bearer tokens, ZIP bytes, process-local readers and guest filesystem paths MUST NOT be the durable source/continuation payload. + +### 8.2 Constraints + +Database constraints and owner checks together enforce: + +- Unique `(actor_profile_id, idempotency_key)`. +- At most one active operation per task across `receiving`, `pre_checking` and `finalization_pending`. +- Exact task/project/assignment/actor foreign-key consistency. +- A task active pointer can only reference its own operation. +- The generated object key belongs to exactly one operation; namespace and generation are bound to that operation. +- Sealed raw SHA/count and provider generation cannot be changed by replay or finalization. +- `finalization_pending` requires complete passing evidence, accepted authority, accepted timestamp and durable handoff identity. +- `finalized` requires exactly one actual Submission, exact retained replica/binding and POST dispatch. +- A unique operation-to-Submission association and unique task/submission-version association. +- Finalization-event uniqueness by operation; existing POST request/dispatch uniqueness remains. +- Cleanup `claimed` excludes any active/accepted/retained ownership. +- Charges/reservations are released at most once, after their release condition is proved. + +A normal operation record is committed before a storage write, so normal in-flight work is never a genuine “object with no owner.” + +### 8.3 Existing CHECKERS row evolution + +Extend the existing `SelectedPreSubmitRun` owner and its lease/terminal-evidence machinery. Replace the process-local `prepared_generation_id` custody dependency with the durable intake operation and sealed source identity. + +The immutable request is known after upload. The new input's semantic manifest is not known until the trusted PRE loader inspects it. Therefore: + +- Request JSON/digest includes known raw identity, source identity, operation/run/fence, locked context, selected images/configuration, predecessor/default policy and limits. +- The new manifest and derived default-input digest are result evidence, nullable until verified input processing produces them. +- A terminal malformed/unsafe archive rejection may legitimately have no manifest and no project invocation. +- `eligible=true` requires complete verified raw/manifest/default/project evidence. +- Once produced, evidence is immutable and bound to the recorded request. +- Do not mutate request JSON to add later outputs or fabricate a manifest before inspection. + +Update all affected typed facts, canonical digest definitions, SQL constraints, fixtures and comparisons together. This is an intentional replacement of the old PRE custody contract, not permission to weaken final passing-evidence requirements. + +### 8.4 Logical content and physical object records + +`ArtifactContent` may retain logical deduplication by raw SHA/count. Each operation source remains a distinct physical replica/generation with its own custody and physical charge. Finalization binds the exact accepted replica, even if an equal-content row already exists. + +Two identical uploaded ZIPs can therefore share a logical content identity while using two stored objects. Do not substitute another operation's replica, claim only one object exists, or add a copy-based deduplication pipeline. + +## 9. Transaction boundaries and authority + +All external I/O occurs outside SQL transactions holding task/operation locks. Use short owner-composed transactions and the established module ports. Celery Workers and routes must not become alternative writers of TASK, ART or CHECKERS tables. + +Use a consistent lock order: task, operation, selected PRE run when needed, retained-artifact/dispatch rows, then quota-scope rows in stable scope order. Cleanup first selects candidates without holding a conflicting long lock, then obtains the same task/operation ownership order. Reconcile this order with existing owner locking in implementation; never introduce an inverted cross-owner acquisition. + +### T1 — reserve foreground intake + +Within one short transaction: + +1. Resolve fresh authorization and lock the task. +2. Resolve idempotency or validate new-operation eligibility. +3. Validate active assignment, predecessor/revision acknowledgement, locked policy cardinality and configured provider/profile readiness. +4. Reserve upload capacity under existing required quota scopes. +5. Create the operation, generated object key, lease/fence, deadlines and immutable command/context snapshot. +6. Install the task's active-operation pointer. +7. Commit before reading/writing the body. + +No provider sandbox is created here. On rollback, there must be no new source write. + +### T2 — record EOF and seal source + +After bounded streaming reaches valid EOF, commit trusted raw SHA/count and the bounded multipart completion intent/receipts needed to finish or reconcile the exact upload. Only the current foreground owner may do this. + +Complete the object outside the transaction using create-only semantics. Record the exact immutable provider generation and complete source receipt in a second short fenced update. The operation stays protected while acknowledgement is uncertain. Move to `pre_checking` only when exact complete-source custody is established. + +This separation is necessary because PostgreSQL and S3 do not share one transaction. No “atomic S3 plus DB commit” claim is allowed. + +### T3 — reserve and execute selected PRE + +Reserve the existing CHECKERS run using the sealed source and immutable execution request. Record provider invocation identity before any uncertain creation call. + +Execute inline outside database locks. Current leases/fences must cover the operation and CHECKERS run. The runtime may not emit a trusted pass on behalf of an expired/replaced owner. + +Validate the result, canonical outputs and request binding through CHECKERS. Failed/invalid outcomes follow section 16. A validated pass proceeds to T4 in the same foreground command; no PRE Celery worker is scheduled. + +### T4 — accept the handoff + +Within one composed short transaction: + +1. Lock task, operation and selected PRE run; verify active-operation pointer and current fences. +2. Revalidate current contributor authority, eligible task/assignment, exact predecessor/revision and locked context. +3. Validate and persist the exact passing CHECKERS terminal evidence and ART source/manifest binding. If terminal facts were already safely captured, consume the exact unconsumed facts; do not accept a detached/forged “pass.” +4. Consume an **operation-scoped submission acceptance authorization** and retain its decision/provenance. +5. Change operation to `finalization_pending`, record accepted_at and stable receipt, keep the pending owner pointer. +6. Change task to `evaluation_pending`. +7. Insert the unique finalization outbox event. +8. Commit. + +Only after this commit may the API return its accepted receipt. Failure before commit cannot produce a success response or durable POST request. A lost commit acknowledgement is resolved by reading the same operation; until resolved it is an unknown outcome, not a known failure. + +T4 does **not** create a placeholder Submission, a retained submission artifact binding, or POST dispatch. + +### T5 — finalize accepted work + +First recognize a `finalized` operation under authorized internal replay: validate its immutable operation → Submission → ART binding/replica → evaluation/dispatch association and acknowledge. Do this before requiring a pending pointer, task `evaluation_pending`, or a new Celery worker lease; POST may already have advanced the task. + +For an unfinalized accepted operation, the Celery worker claims it using a short lease/fence transaction. Necessary metadata observations occur outside task locks. Then a single owner-composed transaction: + +1. Locks task and operation and proves it is this Celery worker's current accepted continuation. +2. Checks task `evaluation_pending`, the matching pending pointer, immutable accepted context/evidence, and absence of cancellation/deletion ownership. +3. Consumes the accepted-operation authority through the narrow internal finalization port. +4. Registers the exact already stored object and trusted verification evidence in ART, reusing logical content only where identity matches. +5. Allocates the actual Submission UUIDv7 and next version under the task lock; creates its immutable packet/context and exact artifact binding. +6. Creates the existing evaluation request/dispatch and reserves the selected POST run under the accepted locked policy. +7. Writes the POST outbox event, marks operation finalized, records actual result IDs and clears the active-operation pointer. +8. Commits all those database effects together. + +A rollback leaves the accepted operation pending and protected. A retry finds the existing finalized association and returns it rather than allocating another version, binding, dispatch or event. + +Global `Submission.version` is not the assignment's revision round. Preserve existing assignment-level revision accounting and coverage-return exemptions. PRE failure, exact replay and finalization retries do not increment a revision round. The accepted pending guard prevents another submission reservation while its formal row is still absent. + +### 9.1 Accepted authority survives the original request + +The Celery worker uses recorded operation-scoped acceptance plus authorized internal finalization, not the contributor's expired bearer token. It must not call the ordinary contributor create operation with a broad “allow evaluation_pending” exception. + +The revision deadline, cap, assignment and permissions were enforced at T4. A Celery worker delayed beyond that time finishes the already accepted command. It does not invalidate it because the contributor's token expired or the original submission window later closed. + +A later administrative revocation must follow an explicit existing governed cancellation/invalidation contract if it is intended to stop accepted work. Do not silently delete, reopen or reassign the task. If no such contract exists for the requested administrative action, ask before adding one. + +Keep the original eligible creation status (`in_progress` or `needs_revision`) as historical dispatch/context evidence. It differs legitimately from the live task status `evaluation_pending` during T5. Update effective deferred SQL guards to validate that distinction. + +### 9.2 Outbox payloads and delivery + +The finalization event contains operation ID, event/schema identity and accepted-evidence digest, plus ordinary correlation metadata. It does not contain the ZIP, a signed URL, a live Python capability or a client-supplied object locator. + +The Celery worker loads authoritative state through owner ports. Immediate publication after commit is an optimization. Existing outbox scanning recovers a committed event if the process or broker fails before publication. + +Message delivery is at least once. Logical uniqueness is enforced by database keys, owner validation and fenced idempotent commands; it is not a claim that a broker or provider can execute a side effect exactly once. + + + +## 10. Streaming into the existing object store + +### 10.1 Object layout and access + +Use the already configured artifact provider, bucket and namespace claim. Generate the new source reference in a dedicated managed key namespace: + +```text +submission-source/v1//bundle.zip +``` + +The physical adapter may prepend its already configured namespace prefix. No contributor value controls a bucket, key, path or endpoint. The operation UUID is generated by `new_record_id()`, not derived from the idempotency key or content hash. + +This prefix distinguishes operation-owned source objects from existing SHA-addressed artifacts; it is not another bucket or another upload stage. A successful object remains at that key for its retained lifetime. Database registration changes its ownership classification, not its bytes or address. + +Preserve the current bucket's access protection, encryption and namespace readiness checks. “One existing bucket” does not mean public readability. Every read must be authorized for its owner and exact object. Project code receives no write/delete capability. + +### 10.2 Required typed storage capabilities + +Extend the existing ART capability/adapter composition. The following operations describe the required semantics; they are not new public HTTP routes: + +| Capability | Required input/output and guarantee | +| --- | --- | +| Begin bounded receipt | Current operation/fence, exact generated key/namespace, maximum bytes, known declared size if any and deadline. Returns an opaque upload handle that can be durably associated before parts are sent. | +| Receive bytes | Backpressured bounded stream; trusted ingress counts/hashes original bytes. Adapter buffers/part retries are explicitly bounded. | +| Prepare completion | EOF raw SHA/count plus bounded part/completion metadata. These facts are committed before external final completion. | +| Complete immutable object | Create-only finalization at the operation's key. Returns exact immutable generation and size, or a typed uncertain/conflict/failure outcome. | +| Observe exact source | Resolve existence/generation/size for this recorded operation only. Observation is not trusted raw-hash proof by itself. | +| Authorize/read source | Read the exact immutable source for the current authorized execution/retained use. Refreshable short-lived delivery authority is separate from durable identity. | +| Abort unfinished upload | Abort a recorded upload, or discover/reconcile uncertain handles only in the controlled namespace/key. | +| Delete exact eligible source | Consume ART cleanup authority for exact namespace/key/generation. Return confirmed deletion/absence or typed uncertainty. | + +Keep generic sealed-source `put` and full verification behavior for other ART consumers. Do not turn these submission-specific capabilities into a general “trust any caller's URL/hash and adopt it” route. + +A source descriptor contains provider profile, namespace identity, object ref, opaque generation, raw SHA/count, media type, operation ID and sealed-upload fence. Descriptors are immutable values, not expiring URLs or host filesystem paths. + +### 10.3 Real bounded streaming + +The FastAPI route uses an incremental body stream. Do not call whole-body `read()`, store the ZIP in `BytesIO`, use an upload parser that spools the whole file, or recreate the current full scratch ZIP. + +The S3-compatible adapter must use bounded multipart/streaming mechanics that work with the selected provider and SDK. It may retain the small number of parts necessary for bounded retries, not the entire archive. + +Calculate and measure the per-request buffer bound as: + +```text +maximum buffered part bytes ++ in-flight part/retry buffers ++ API read buffers ++ bounded HTTP/TLS/SDK overhead +``` + +An API chunk size of 1 MiB is not a claim that total request memory is 1 MiB. Set a finite part size and in-flight count compatible with provider part limits and the deployment memory budget. Backpressure must stop reading from the client when downstream buffers are full. + +If Content-Length exceeds the policy bound, reject before body receipt. If absent or dishonest, actual byte counting enforces the bound. At overflow, stop appending, abort safely, and retain cleanup ownership. A mismatching/truncated declared length cannot reach PRE. + +Configure the deployed reverse proxy and application server to stream this route without whole-request temporary-file buffering. Verify chunked and fixed-length requests separately. NGINX request buffering is enabled by default, so merely using `request.stream()` is insufficient evidence. [P1](#p1) + +### 10.4 Upload uncertainty and immutable completion + +- Record operation/key ownership before starting a provider upload. +- Record a received multipart upload handle before sending parts. +- If initiation acknowledgement is lost, a scoped reconciliation path must discover and abort/reconcile handles for that already owned key. Do not create untraceable multipart uploads. +- Persist EOF identity and completion intent before complete. +- Use conditional creation. Never retry with an unconditional overwrite. +- Treat a conflicting object as a custody conflict unless observation proves it is exactly this operation's already completed immutable generation. +- Parse the full completion outcome; an HTTP success status alone is not sufficient for protocols that can report embedded completion errors. [P2](#p2) +- If completion is uncertain, preserve ownership/reservation and reconcile the exact key. Do not start PRE on a partial or unidentified object. +- The foreground request may resolve uncertainty only within its deadline. If it cannot, it returns infrastructure/unknown outcome as applicable. A maintenance Celery worker may reconcile storage custody and cleanup; it cannot take over PRE or invent accepted work. + +A stale request may finish an already in-flight provider call after losing its fence. Its response cannot restore eligibility. The operation tombstone and reconciler account for any late object/parts and remove them when eligible. + +### 10.5 AWS versioning and exact deletion + +The current AWS profile requires bucket versioning. Preserve it. Persist the completion `VersionId` as the provider's opaque generation, pin input reads to it, and delete that exact version only when ART authorizes cleanup. + +A key-only DELETE on a versioned bucket can create a delete marker while retaining the bytes. It must not be reported as physical reclamation or used to release the physical charge. [P3](#p3) + +Update provider/readiness/live-proof contracts for exact-version reads and narrowly scoped `DeleteObjectVersion`/multipart cleanup in the new submission namespace. Existing protections on unrelated retained SHA-addressed objects remain. + +For that submission prefix, enforce create-only conditions on final object creation (`PutObject` and `CompleteMultipartUpload`). Qualify `s3:ObjectCreationOperation` in the conditional-write policy so multipart initiation and part upload remain permitted without conditional headers. The current missing-header-only deny cannot be carried forward unchanged. Do not remove final-object overwrite protection to make multipart work, and do not enable copy operations. Readiness/live tests must prove ordinary multipart receipt succeeds while unconditional final creation and overwrites are denied. [P6](#p6) + +A future nonversioned provider must qualify equivalent immutable create-only references and exact cleanup semantics. Do not add a fictitious VersionId to its contract or assume S3 compatibility proves identical behavior. + +## 11. Input identity and platform defaults + +### 11.1 Why identities remain required + +The raw SHA/count binds what the API received to what PRE read, what the Celery worker registered and what POST evaluates. It also detects incorrect object selection, truncation, substitution and conflicting replay. This is application evidence, not an assertion that S3 or another store is generally untrustworthy. + +The semantic manifest supports file-level identity and unchanged-resubmission policy even when a ZIP is repacked with different archive metadata. It does not replace the original raw ZIP identity. + +Use trusted server observation and the existing canonical representation. Do not treat ETag, a client header, object metadata set by a caller or project stdout as a raw SHA proof. Multipart composite checksums can differ from a whole-file digest. Provider transport checksums are useful additional checks, not interchangeable identities. [P4](#p4) + +### 11.2 Verification without an extra Celery worker download + +1. API ingress hashes/counts the original stream while uploading. +2. The trusted PRE loader reads the exact completed source and independently hashes/counts that necessary input read. +3. It checks expected versus observed identity before permitting project eligibility. +4. It validates/extracts the archive within configured bounds and computes the existing canonical semantic manifest. +5. CHECKERS/ART validate and persist that trusted evidence bound to the exact request/source. +6. Finalization registers that object/evidence. It does not download the ZIP again just to repeat the same raw verification. + +A metadata existence/size check before registration is permitted for availability checks but cannot establish input integrity. Preserve full verification for other artifact producer paths that lack this proof. + +### 11.3 Four Workstream defaults + +Keep `workstream.default`, its versioned behavior identity and the following check IDs/meanings: + +| Check ID | Required behavior | +| --- | --- | +| `archive_safe` | Supported, structurally valid, unencrypted ZIP; safe canonical paths/types; bounded expansion; no traversal, conflicting paths or unsafe entries. | +| `received_identity_exact` | Exact trusted ingress raw SHA/count matches the loaded object; canonical manifest describes the verified extracted tree. | +| `high_confidence_secrets_absent` | Preserve existing approved signature/decision behavior. Public findings expose bounded categories/counts, not detected secret values. | +| `submission_changed_for_current_rules` | Under unchanged canonical rules, reject the same raw archive or semantic manifest as the actual predecessor. Preserve the existing changed-rules exception. | + +Preserve current summary/attestation warning semantics. Do not silently turn omissions into blocking requirements or alter secret detection as part of moving execution. + +Canonical predecessor/rules facts come from Workstream owners, not the uploaded ZIP. The trusted session receives their frozen, authenticated request snapshot. T4 revalidates that snapshot against live task truth before accepting the result. + +Preserve the existing manifest schema, path normalization, ordering, encoding, executable-bit treatment and canonical hash function. Update behavior identity deliberately only where a contract change actually requires it, with fixtures proving preserved semantics. + +### 11.4 Archive handling requirements + +Retain existing rejection semantics for malformed/encrypted archives, unsafe links or special files, traversal/absolute paths, collisions after normalization, unsupported features, invalid CRC/size records, central-directory bounds and expansion limits. + +Write extracted files only into the session's protected bounded workspace. Never follow contributor-controlled links, use archive paths as host paths, or execute a file merely to inspect it. Bind the project read-only view to the verified manifest; writable project scratch is separate and output is untrusted. + +Distinguish an invalid contributor archive from a storage transport mismatch. A valid uploaded archive whose stored bytes do not match the ingress identity is an infrastructure/integrity incident, not proof the contributor failed project QC. + +## 12. One PRE execution session + +### 12.1 Required sequence inside one session + +The runtime creates one qualified PRE session after complete source receipt: + +1. Boot the approved platform kernel/runtime and Workstream bootstrap. +2. Deliver/read the exact source under a narrowly scoped read capability. +3. Verify raw identity and inspect/extract into the protected workspace. +4. Construct canonical manifest/default input from verified files and locked request facts. +5. Run the platform default checks. +6. If blocking defaults fail, return bounded default findings without starting the project checker. +7. Otherwise run exactly the selected project PRE image/configuration with the verified input mounted read-only. +8. Validate its output schema/limits and produce a trusted combined response. +9. Stop the workload and destroy/reap the session under the recorded cleanup obligation. + +There is no separate trusted-intake VM, exported host tree, second project PRE VM, or transfer of ZIP custody back to the API. + +### 12.2 Trusted and project-controlled code + +The qualified provider/runtime, platform kernel, bootstrap, default-checker code and authenticated control channel are trusted. The project image and contributor input are not authority for platform facts. + +Platform code is provisioned by Workstream/the qualified runtime, independently of the project OCI contents. A project author supplies its PRE and POST images; it does not have to bundle or maintain Workstream's default checker. + +Within the single session, enforce: + +- Separate project user/process/mount/resource boundaries from the trusted supervisor. +- Read-only original/verified input and image layers; a bounded independent writable workspace. +- No privilege to signal, ptrace, mount over, impersonate or write the supervisor/control channel. +- Bounded memory, CPU, processes, temporary disk, output and wall-clock limits. A workload memory limit must not make the supervisor part of the same killable untrusted process group. +- No storage write/delete credentials, long-lived cloud credentials, database credentials or broad model credentials in project environment. +- Trusted result/control framing separate from stdout/stderr. Project output cannot forge source identity, a platform check, an execution fence or lifecycle action. +- Current PRE network/capability restrictions preserved. Do not grant general egress or add trial/model/build privileges merely to accommodate a provider. + +The chosen trust model is a protected supervisor and project workload in one qualified guest. A second guest is not part of the implementation. + +### 12.3 Single call and evidence construction + +The core invokes one typed `execute_pre` operation. Its request contains the sealed source and locked facts; it does not require a pre-existing API-extracted manifest. + +The trusted runtime derives the manifest and the nested project-checker request after inspection. CHECKERS reconstructs the expected derived request digest from recorded locked facts plus the validated trusted manifest, then validates the project's registered result against it. Do not accept a pair of mutually matching echoed digests as sufficient proof. + +An unsafe archive may produce a completed default rejection with no manifest. A pass requires the complete input receipt, canonical manifest, default result and selected-project result. The runtime cannot use “project passed” to skip any platform default. + +### 12.4 Concrete Smol input path + +For the initial Smol adapter: + +- ART authorizes an exact immutable object read. +- The trusted runtime adapter opens that source and forwards it with bounded buffers over the existing trusted host-to-guest transport. +- The guest's Workstream loader verifies raw SHA/count and performs bounded inspection. +- The project runs in that same PRE guest after defaults pass. + +No whole-file host/API spool is required, and guest-wide network access need not be enabled. This is the Smol adapter's private input-delivery implementation. A managed adapter can use its trusted loader or qualified file-injection API without host access. Neither transport appears as a required core host-path contract. + +### 12.5 Cleanup is independent after evidence capture + +Record a discoverable provider invocation/session identity and cleanup obligation before an uncertain create. Validate result evidence before T4. T4 persists it or references already persisted immutable evidence atomically with accepted ownership, task status and outbox. No Celery worker continuation or accepted receipt is authorized before T4 commits. Cleanup may proceed after safe result delivery; evidence lost before T4 is a pre-acceptance failure. + +Attempt prompt destruction after terminal PRE work. A valid captured result may proceed through T4 while an independently recorded cleanup obligation is retried. Destroy uncertainty does not become a QC failure and does not require the VM to remain available for finalization. + +Keep unsettled runtime capacity charged or quarantine the affected node until termination is proved. A reaper/provider maximum lifetime must recover sessions after API/runtime death. “Destroy requested” is not the same as “capacity free.” + +## 13. The execution adapter contract + +### 13.1 Common request + +Use explicit typed ports/factories under ADR 0014. The shared request must include: + +| Group | Required facts | +| --- | --- | +| Invocation | Operation/run ID, phase, immutable request digest, lease/fence, correlation | +| Policy | Exact approved registry entry, resolved OCI platform-manifest digest, configuration/digest, platform/default identity | +| Source | Exact immutable object descriptor and expected raw SHA/count; permitted media type | +| Context | Task/assignment, packet, predecessor/revision and locked rule digests needed by this phase | +| Resource policy | Profile identity, explicit CPU/RAM/disk/process/output limits, aggregate deadline and permitted capabilities | +| Delivery | Current narrow read capability supplied separately from durable request identity | + +Mutable tags are not execution identities. A multi-architecture image must resolve to the approved architecture-specific manifest and retain that observed identity. No project/client input chooses a different provider image or bypasses registry policy. + +Expiring URLs are delivery credentials. Mint them shortly before authorized use, keep them out of project code/logs, and refresh only for the same authorized invocation. Their token bytes do not participate in immutable request digests. + +### 13.2 Common response + +The response includes: + +- Operation/run/phase/request/fence and provider invocation identity. +- Closed outcome: completed checks, infrastructure failure, cancellation or deadline exhaustion. +- Trusted observed source identity and exact provider generation. +- Canonical manifest/default-input evidence when produced; mandatory for eligibility. +- Exact selected registry/image/configuration identities and bounded schema-valid project result. +- Qualified runtime/profile identity and typed conformance evidence. +- Bounded stage timing, sanitized infrastructure reason where applicable, and cleanup obligation/disposition. + +Expected request/source/selected-image identities are always bound. Observed input/manifest evidence and project results are present only when those stages completed. A blocking default result records project status as `not_run` with no fabricated project result. PRE eligibility requires exactly one completed matching project result plus all required default/input evidence. + +The shared envelope is invocation/phase/request/source/image/profile/fence identity. Platform-default and derived default-input fields are PRE-specific; they do not introduce a new POST checking stage. POST retains its existing normalized result and selected capability evidence with exact retained-source binding. + +Reject mismatched operation, phase, source, image, configuration, defaults, request digest, profile or fence. An expired invocation cannot create an accepted handoff even if its checker later reports pass. + +Provider-specific evidence may contain Smol cgroups, local UID/GID, cache facts or Unix transport facts. The common response must not require those values from every provider. + +### 13.3 Provider qualification + +A provider is selectable only when the adapter proves: + +1. Approved image identity/architecture and Workstream-controlled trusted bootstrap. +2. The one-session PRE trust boundary, verified input and read-only project view. +3. The required finite resource, network, process/output and execution controls. +4. Authenticated, bounded, correctly bound result delivery. +5. Discoverable/reconcilable invocation creation, fenced results, cancellation and eventual cleanup after caller failure. +6. Every model/trial/forge/evaluation capability selected by the actual POST policy, with equivalent authorization, metering and evidence. +7. Source read/version behavior and credential containment appropriate to the selected object-store provider. + +Fail readiness/admission when a selected capability is unsupported. Do not silently omit it, weaken isolation or fall back to another unapproved runtime. + +This change requires the Smol implementation and a provider-substitution contract test using a managed-style adapter without host access. A production integration with a particular paid provider remains separate until that provider is selected and qualified. Do not claim arbitrary managed services already work. + +### 13.4 Exactly one image per phase + +At policy approval/locking, require one executable PRE selection and one executable POST selection. Enforce this in backend compiler/validation, project approval commands, CLI, MCP schemas and fixtures. + +A project may describe many requirements and the selected image may run many internal checks. That does not authorize multiple independently selected images for a phase. Do not auto-select a fallback image, auto-merge old selections or let setup-agent text choose executables; preserve authorized human selection of registered images/configuration. + +Freeze both selections/configurations with the task context and revalidate them at T4. Later project edits do not silently change an accepted operation. + +Current POST may invoke its one selected image for a forge locator and evaluation, and its approved trial capability may create child executions. Preserve those internals. “One selected POST image” is not a promise that existing approved POST behavior uses exactly one physical VM. + + + +## 14. Durable finalization and POST dispatch + +### 14.1 Celery Worker responsibility + +A finalization Celery worker receives an operation notification, obtains owner-qualified authority and performs T5. It does not accept contributor ZIP bytes, run PRE, keep a VM alive, upload the source, copy an object or choose a policy. + +Keep Celery worker entrypoints thin. The existing TASK/ART/CHECKERS composition owns database changes and audits. Preserve authorization, namespace identity, exact raw/manifest binding, accepted context, predecessor and dispatch guards. + +The artifact registration evidence must identify this exact accepted operation, exact sealed replica/generation and trusted PRE input receipt. It must not be synthesized from a generic HEAD, caller-provided checksum or another equal-content object's ready state. + +### 14.2 Retry and recovery + +- Recognize `finalized` replay and validate its immutable associations first, before checking current pending task status/pointer or acquiring a new Celery worker lease. +- Claim only unfinalized `finalization_pending` work with a current Celery worker lease/fence. +- A duplicate notification for currently owned work does not start a competing finalizer. +- Transient DB/provider/dispatch-composition failures retain pending state and schedule bounded backoff using the existing durable retry owner. +- Missing/corrupt input or conflicting evidence blocks finalization and raises an operational integrity issue; it does not become PRE QC failure or reopen contributor intake. +- Expired Celery worker ownership is reclaimable. It does not invalidate accepted evidence. +- Exhausted automatic retries set visible operational-stall facts and alert. The object remains protected and the task remains pending. +- An authorized retry of stalled work uses the same operation/evidence and does not consume a contributor revision. +- If the broker is down, the outbox remains authoritative. If the Celery worker commits then crashes before acknowledgement, replay observes the same formal Submission/dispatch. + +No permanently pending operation may be hidden from reads/monitoring. Every accepted operation must be finalized, visibly retrying/stalled, or affected by an explicit authorized cancellation. + +### 14.3 Dispatch barrier + +POST starts only after the formal Submission, exact retained artifact binding, evaluation request/reservation and POST outbox record exist. A consumer must validate those facts through the existing owners. + +Task status `evaluation_pending` alone cannot dispatch POST: before T5, it also represents accepted work awaiting registration. The pending-operation projection distinguishes those phases. + +## 15. POST, review, revision and acceptance + +POST uses the original accepted source object and immutable generation. The adapter/runtime reads it as required; the finalization Celery worker does not download and re-upload it. + +Preserve current POST execution organization, selected model/trial/forge capabilities, result schemas, policy thresholds, infrastructure retry rules and evidence. Adapt material/source selection to accept the new exact operation-owned replica instead of requiring a SHA-derived object address. + +POST outcomes continue through existing rules: + +| Outcome | Required behavior | +| --- | --- | +| Required checks pass; human review required | Enter the existing review-pending path. A passing checker cannot bypass required human review. | +| Required checks pass; human review not required | Invoke the existing authorized shared final-acceptance operation. | +| Governed fixable failure | Follow existing needs-revision policy, findings, rebase/acknowledgement and attempt-limit behavior. | +| Governed rejection / exhausted attempts | Follow the existing terminal outcome policy. | +| Runtime/provider/infrastructure failure | Retry/hold under existing infrastructure rules; do not consume a contributor revision as though QC failed. | + +Final acceptance, task accepted state, submitter ContributionRecord and applicable awards remain one governed atomic operation. Do not fabricate a human Review or reviewer contribution for automatic acceptance. No payment/reputation redesign is included. + +PRE failure remains outside this POST/revision accounting. A contributor can correct and submit a new key while the task remains eligible, subject to upload/rate limits and existing unchanged-input policy. + +## 16. Failure and recovery rules + +The API must know whether T4 committed before describing a submission as accepted or conclusively failed. If its connection to the database fails during commit, it must resolve by operation identity or report unknown outcome. + +| Failure point | Contributor result | Durable state and recovery | +| --- | --- | --- | +| Invalid authority/metadata before T1 | Existing concealed denial or validation error | No new operation/object/VM. | +| Concurrent new submission | Conflict | Winning operation alone owns task; loser creates no live upload/PRE. | +| Upload size/framing violation | 413/validation error | No PRE. Terminalize operation when outcome is known; abort/clean owned partial bytes. | +| Slow upload / disconnect | Timeout or no response | Cancel foreground, fence it, abandon after safe outcome resolution. Do not run PRE in a Celery worker. | +| Storage unavailable while receiving | Infrastructure error | Keep owned partial/uncertain storage accounted for; reconcile/clean. No accepted handoff. | +| EOF recorded; completion acknowledgement lost | Infrastructure/unknown result if unresolved by deadline | Exact key/generation reconciled; no new source or background PRE. | +| API dies after upload, before PRE | Client may see unknown transport outcome | Expired foreground is fenced/abandoned; cleanup owns source. New request/key required after terminalization. | +| PRE capacity exhausted | Bounded capacity response | No indefinite wait or unbounded VM queue. Uploaded object remains owned for terminal cleanup. | +| Malformed ZIP/default QC failure | Inline PRE findings | Rejected operation; no new Submission/evaluation; no round consumed. | +| Project PRE valid QC failure | Inline findings | Same rejected semantics. | +| Guest crash/OOM/timeout/bad protocol/output | Infrastructure error | No QC decision or accepted work; cleanup/reaper owns session and object. | +| Task/assignment/rules changed before T4 | Context conflict | Passing evidence cannot accept stale context. Terminalize without new Submission; preserve audit. | +| API cancelled before T4 begins | No accepted receipt | Stop/terminalize foreground; no Celery worker continuation of PRE. | +| Cancellation/disconnect while T4 commits | Receipt may be lost | Resolve commit. If committed, accepted work continues; otherwise terminalize. Never infer rollback solely from disconnect. | +| T4 commits; response/broker publish lost | Read/replay same key obtains accepted receipt | Task already pending, outbox recovers continuation, source protected. | +| PRE destroy acknowledgement lost after valid result | Accepted handoff may continue | Independently recorded cleanup obligation; capacity not falsely freed. | +| Finalization Celery worker crashes before commit | Existing accepted receipt remains valid | Lease/retry recovers; no partial formal Submission/dispatch commit. | +| Finalization commits; message redelivered | Same finalized result | No second Submission/version/binding/POST reservation. | +| Accepted Celery worker backlog lasts beyond cleanup age | Progress reads show finalization pending/stall | Object is protected regardless of age. | +| POST fails or retries | Existing evaluation/revision result | Preserve current POST rules; accepted source remains retained. | +| Object delete response is uncertain | No product outcome change | Keep cleanup obligation and conservative charge; reconcile exact generation. | + +### 16.1 Lease expiry is not proof of rollback + +When an owner expires, a recovery command locks the operation and examines committed state. It may abandon a pre-handoff operation only after fencing it and proving there is no accepted handoff. It must not abandon `finalization_pending` because a Celery worker lease expired. + +A late PRE result or late storage completion cannot revive an abandoned operation. It is retained as bounded operational/audit information where useful and reconciled for cleanup. + +### 16.2 Runtime create uncertainty + +Give each provider invocation a stable recorded identity before create. On a lost create acknowledgement, locate/reconcile that invocation or fail closed within the foreground deadline. Do not blindly launch a second PRE session on another host while the first may still be alive. + +This protects capacity and evidence. It does not require promising that a provider can execute user code exactly once under every failure. + +## 17. Object and runtime cleanup + +### 17.1 Age and schedule + +The initial object cleanup sweep interval is **12 hours**. Minimum eligible age is **2 hours**. These are cleanup policy defaults, not a promise that failed ZIPs disappear instantly. + +For an owned terminal operation, compute age from the latest of its terminal timestamp and relevant source-write/completion activity. A newly observed late completion resets the source's minimum-age protection. Ordinary status reads and failed cleanup retries do not reset source age. + +Apply the age rule **and** ownership rules. Never use either “no artifact row” or “older than two hours” alone. + +### 17.2 Protected objects + +Do not delete: + +- A live receiving or PRE-checking operation's input. +- An unresolved write with a valid current owner. +- Any `finalization_pending` operation, including retrying or operationally stalled work. +- Any exact generation referenced by retained artifact/Submission evidence. +- An object with an unresolved ownership conflict. +- A recently created or recently completed object younger than the minimum eligible age. + +An accepted operation stays protected even if no formal Submission/artifact row exists yet. Cleanup must query the intake owner and retained-reference owner. + +### 17.3 Eligible objects and deletion protocol + +Terminal rejected, failed, abandoned or cancelled pre-handoff operations may become eligible after age and ownership checks. An explicit cancellation of already accepted work requires its own authorized lifecycle/retention outcome; this cleaner does not invent one. + +For each candidate: + +1. **Claim in a short transaction.** Lock the same task/operation custody used by finalization. Recheck terminal state, exact source, minimum age, absence of accepted/retained references, live ownership and write obligations. Set cleanup `claimed` with a new generation and bounded deletion targets. +2. **Exclude revival.** A cleanup-claimed operation cannot become active, accepted or retained. T4/T5 reject that ownership. +3. **Act outside the transaction.** Abort scoped multipart handles and delete only the exact eligible object generation through the cleanup capability. +4. **Resolve uncertainty.** A timeout is not proof of deletion. Retry/observe the exact target without broadening its scope. +5. **Confirm in a short transaction.** Record confirmed removal/absence, no unresolved late writer/part obligation, and release the corresponding reservation/charge once. +6. **Retain a tombstone.** Preserve request result and custody history so late callbacks/messages cannot resurrect the key. Do not remove the only record identifying a potentially late write. + +An expired API lease fences database updates but does not magically cancel a provider request already in flight. If its storage completion remains uncertain, keep the obligation and conservative capacity reservation until reconciled. A late version/part remains owned by the terminal operation and is cleaned; it can never become a Submission. + +A successful `AbortMultipartUpload` response alone is not proof that all part storage has been reclaimed. Stop further writer calls, settle or reconcile outstanding calls, and verify the exact upload has no remaining parts using `ListParts` or authoritative `NoSuchUpload`; repeat scoped abort/observation when needed. Resolve any possibly completed object generation separately. A client timeout, expired lease, single HEAD absence or lone abort acknowledgement cannot release the reservation while a write outcome remains unresolved. Retain the tombstone and conservative charge until the adapter proves complete cleanup. [P7](#p7) + +### 17.4 Genuine orphans + +Use indexed operation candidates as the ordinary cleanup source. A bounded inventory/reconciliation job may inspect only the managed submission prefix to find objects/parts whose operation record is genuinely absent. + +For each such object, verify age and exact generation, recheck both operation ownership and retained references against authoritative current data, and create a deletion claim/tombstone before deletion. A stale LIST/inventory entry is not deletion authority. If the database is unavailable or ownership is ambiguous, skip and alert/retry. + +Do not scan/delete unrelated artifact namespaces. Do not create a global age-based lifecycle expiration rule over this mixed unretained/retained prefix: passing objects stay at those same keys. Any provider-side multipart-abort policy must be separately qualified against the maximum valid upload lifetime. + +### 17.5 Permissions and retention barrier + +The upload role can create sources conditionally; execution gets exact read authority; cleanup gets scoped deletion/abort authority. Project code gets none of those broad roles. + +Because failed and retained sources occupy the same prefix, IAM prefix scope alone cannot distinguish them. The trusted ART cleanup gate and durable ownership check are the retention barrier for this design. Preserve that gate in tests and operational tooling; do not add a general unguarded “delete by key” administrative path. + +### 17.6 Runtime cleanup + +Runtime cleanup is prompt and independently retried; it does not wait for the 12-hour object sweep. Record provider resources, deadlines, ownership and cleanup progress. Reap expired sessions and reconcile host restarts/drains under the adapter's qualified maximum-lifetime policy. + +Do not release runtime slot/RAM/disk charges on a mere destroy request. Confirm termination or quarantine capacity. Neither source retention nor durable finalization depends on a PRE sandbox surviving. + +## 18. Limits, quotas and timing + +### 18.1 Initial archive limits + +Preserve the current source-verified baseline; projects may impose tighter approved limits. + +| Limit | Initial value | +| --- | ---: | +| Compressed ZIP | 500 MiB = 524,288,000 bytes | +| Total expanded content | 512 MiB = 536,870,912 bytes | +| One expanded file | 128 MiB = 134,217,728 bytes | +| Archive entries | 2,000 | +| Normalized path bytes | 1,024 | +| Path depth | 32 | +| Central-directory bytes | 8 MiB = 8,388,608 bytes | +| Compression ratio | 100 | +| API read chunk ceiling | Existing 1 MiB setting; additional adapter buffers counted separately | +| Object cleanup interval | 12 hours | +| Minimum cleanup age | 2 hours | + +These are archive/input limits, not a 1 GB VM size. Effective limits are the minimum of applicable platform, approved project, provider and deployment limits. Validate combinations before admitting uploads. + +### 18.2 Physical storage reservations + +Reserve before bytes are written. If a valid declared size is present, reserve that bounded amount and require exact EOF equality; otherwise reserve the operation's maximum raw allowance. + +Enforce each enabled task/producer/project/deployment quota under consistent owner locking. Concurrent operations cannot spend the same remaining capacity. After complete sealing, convert the reservation to exact physical bytes and release only unused allowance. + +Retain charges for failed objects, partial multipart bytes and uncertain writes until actual cleanup is confirmed. Registration changes retention ownership, not the amount physically stored. Exact replay adds no physical charge. + +The current content-deduplicated charge table cannot be used unchanged to claim physical per-operation usage. Add/extend owner accounting for exact object generations. Keep logical content accounting separate where existing business contracts require it. + +### 18.3 Time intervals + +Measure separate intervals: + +| Interval | Start → finish | +| --- | --- | +| Upload | First body receipt → complete immutable object confirmed | +| PRE after upload | Complete immutable source confirmed → validated terminal result | +| PRE queue | Admission request → reserved execution capacity | +| PRE readiness/input | Session creation → verified input/default preparation | +| Project PRE | Selected checker start → bounded result | +| Accepted handoff | Validated pass → T4 commit | +| Finalization wait/work | T4 commit → T5 commit | +| POST queue/execution | Existing dispatch/lease stages | + +The approximately 60-second intent calibrates what belongs in PRE and what should move to POST. Contributor transfer speed is excluded. Internal queueing, boot/image readiness, object read, extraction and defaults still affect the experience and must be visible; do not report only checker process duration as total PRE latency. + +A deployment supplies one finite **aggregate PRE deadline**, initialized when complete immutable source receipt is confirmed. Reservation work, admission queueing, startup, input loading, defaults and project execution all consume the same remaining budget. Stage deadlines can shorten it but cannot restart or extend it. No unmeasured delay between sealing and admission is excluded. + +The exact hard deadline is not implicitly 60 seconds merely because the performance target is about one minute. Nor may the old independent 300-second archive inspection and 3,400-second preparation deadlines be inherited into this flow. Section 24 defines the required profile decision. + +### 18.4 Resource and request bounds + +Approved profiles must define CPU, RAM, temporary disk, process count, output/log limits, runtime lifetime and required capabilities. Disk sizing covers raw ZIP plus permitted extracted tree, image/workspace needs and bounded outputs; it is not derived from compressed size alone. + +Deployment configuration must also provide finite upload idle/total limits, storage-call/retry limits, foreground lease/heartbeat settings, PRE queue limits, finalization retry policy and cleanup/reaper limits. Registry ranges alone are not measured safe profiles. + +Heartbeat intervals must leave a safe renewal margin before lease expiry. Use a monotonic clock for local elapsed deadlines and authoritative UTC/database timestamps for durable leases/audits. Do not reset an absolute deadline after each reconnect or retry. + +HTTP proxy/client timeouts must support the approved upload plus PRE/handoff envelope. They must not cause routine valid PRE requests to be cut off earlier than the published contract. + +## 19. Scaling and operations + +### 19.1 Independent capacity controls + +| Resource | Scaling/control requirement | +| --- | --- | +| API upload connections and buffers | Explicit concurrent request/buffer/bandwidth limits; backpressure; per-actor/project admission; no local whole-file storage dependency | +| Object storage | Exact physical reservations/charges, bounded parts and request pools, cleanup backlog visibility | +| PRE | Interactive capacity separate from long POST work; bounded queue/admission wait and early overload result | +| Finalization | Short owner transactions on Celery worker capacity that long-running POST jobs cannot occupy indefinitely | +| POST | Existing longer-running execution capacity and approved child/trial peak accounting | +| Cleanup/reconciliation | Bounded batches and own concurrency so maintenance cannot exhaust interactive DB/store/runtime capacity | + +A cheap capacity check before upload can reject known overload. It is not a future PRE slot guarantee. Actual PRE capacity is reserved after upload. Do not reserve a live VM throughout contributor transfer. + +Use existing Celery routing/concurrency to keep finalization and POST from blocking each other. Separate capacity does not require inventing a new workflow engine, broker, scheduler database or service decomposition. Celery delivery/acknowledgement settings must be tested with idempotent owner commands; configuration alone is not a recovery proof. [P5](#p5) + +### 19.2 One server and later runtime fleet + +On one server, API/Celery worker/runtime processes can coexist with explicit resource reservations. Storage and PostgreSQL retain the same ownership contracts. + +For a self-hosted fleet, the runtime placement implementation selects a healthy qualified node/profile. The destination node atomically reserves authoritative slots, RAM and disk before creation. A node epoch/generation fences pre-restart reservations. Reconcile surviving processes/resources before advertising recovered capacity. + +Two API replicas must not each promise the same slot. Avoid process-local-only quota decisions for shared capacities. Delayed heartbeats are not permission to launch a duplicate potentially live invocation elsewhere. Drain nodes by refusing new work and finishing/cancelling existing bounded sessions under recorded ownership. + +A managed provider uses its qualified placement/control APIs behind the same execution port. Task states, source identity, accepted handoff and Celery worker finalization remain unchanged. + +### 19.3 Evidence-based capacity planning + +Measure representative input/profile workloads before setting deployment concurrency. Useful planning relationships are: + +- Concurrent live uploads approximately equal arrival rate × average upload duration. +- PRE slots required approximately equal admitted PRE rate × average PRE occupancy, with measured headroom for the chosen tail-latency target. +- API memory must cover admitted uploads × proved per-upload buffers plus process overhead. +- A self-hosted node must reserve each session's declared peak RAM/disk, including selected POST child peaks. +- Cleanup/storage headroom must cover retained data plus expected rejected/abandoned data between sweeps and during outages. + +These are sizing relationships, not promised throughput figures. Do not claim a particular requests-per-second or p95/p99 result from VM boot time alone. + +### 19.4 Required observability + +Correlate request, operation, selected PRE run, provider invocation, accepted event, formal Submission and evaluation IDs. Do not log ZIP contents, detected secrets, signed URLs or credentials. + +Track: + +- Admitted/rejected upload counts, active upload buffers/connections, throughput and physical reservations. +- Stage latency and PRE after-upload latency; QC versus infrastructure failures. +- PRE queue/slot usage, profile resource high-water marks and overload responses. +- Accepted operation age, finalization retry/stall count, outbox age and POST queue/run latency. +- Runtime cleanup obligations, oldest unsettled session, quarantined capacity and node epoch/health. +- Object cleanup/orphan/multipart backlog, oldest eligible object and bytes awaiting confirmed reclamation. + +Alert thresholds must be explicit deployment values. Provide an operator view for pending/stalled accepted work and a narrowly authorized, audited retry path for the same operation. Do not use monitoring remediation to rewrite a contributor packet, change locked policy or create a fresh submission. + +### 19.5 Graceful shutdown + +Stop admitting new requests when draining. Permit bounded active requests to finish when possible; otherwise fence/terminalize pre-handoff operations and preserve storage/runtime cleanup ownership. + +Already committed T4 work remains in PostgreSQL/outbox and proceeds after Celery workers recover. In-memory queues, process-local capabilities or a particular API replica are never required to recover it. + + + +## 20. Migration and cutover + +### 20.1 Inventory before changing the running path + +Record the deployed version, actual database head and effective current constraints. This specification was grounded in merged main at the commit listed above; an implementing agent must compare later changes and report material conflicts. + +Inventory: + +- In-flight old preparations, scratch-backed put attempts and ready unconsumed admissions. +- Existing formal Submissions, retained replicas, dispatches and evaluations. +- Current approved/locked project policies with zero, one or multiple phase selections. +- Object-store namespace/versioning/IAM/readiness configuration and active provider profile. +- CLI/MCP consumers and deployed proxy/request limits. + +Do not treat an old ready admission as a new accepted operation. In the old public flow the contributor had not necessarily performed the separate submit action. + +### 20.2 Coordinated replacement + +Use a controlled cutover: + +1. Stop admitting old preparation/submission mutations and drain their foreground executions. +2. Resolve or explicitly mark old unsubmitted operations/admissions stale through their current owners. Preserve evidence and retained data. Do not bulk-delete old SHA objects or silently auto-submit them. +3. Apply operation/source-generation/accounting/owner-pointer schema changes and update effective deferred custody/dispatch guards. +4. Validate future project policy selections through the authorized owner. Policies missing either image or selecting multiple images must not become valid by inventing a default or picking the first. Create approved replacement selections for future use; never edit locked or historical policy bodies. +5. Deploy the new API/CLI/MCP contracts, Celery workers/outbox handlers, execution/runtime protocol and storage permissions/readiness as one compatible release. +6. Run the required integrated proofs and readiness checks before enabling new submission admission. +7. Enable only the single new public submit flow. Observe pending-operation, storage and runtime cleanup metrics. + +New endpoints and client behavior must not be enabled against Celery workers/runtimes unable to consume their accepted contracts. + +The new cardinality rule must not be applied retroactively to invalidate retained evaluations or reinterpret their evidence. Finish/drain already accepted executions under their original locked contracts before retiring any execution support they require. Historical read/review evidence remains valid. A task already locked to an incompatible policy requires an existing governed rebase/re-release before a new submission, or remains blocked pending an owner decision; it is never silently relocked. + +### 20.3 Historical data and reference formats + +Historical retained SHA-addressed objects remain readable and immutable. Other ART producers may still legitimately use that namespace and their existing sealed-source workflows. + +Source-reference validation must distinguish the current content-addressed form from the new operation-source form, with strict parsing and owner validation for each. This is retained-data/producer support, not parallel old/new contributor submission APIs. + +Do not move, rename, copy or re-upload historical retained objects merely to normalize their keys. New submission-source objects use their own exact operation-based refs. + +Existing `evaluation_pending` tasks with a formal Submission remain valid without a new pending-operation pointer. New T4 work may have a pointer without a new formal Submission. Effective database guards and reads must understand these two legitimate custody situations without weakening lineage. + +### 20.4 Migration failure and rollback + +Before cutover, migration failure leaves submission admission disabled until corrected; it must not allow partially updated writers to proceed. + +After a new accepted operation exists, do not roll back to code incapable of representing its pending custody/source reference. Disable new admission, preserve state and Celery workers capable of recovery, and repair forward unless an explicitly reviewed migration provides a safe rollback. + +No rollback may erase accepted operations, retained bindings, object generations, physical charges or their outbox evidence. + +## 21. Repository change map + +All paths below are relative to the pinned repository. They identify inspected current owners, not proof that the new behavior already exists. Implementers must trace callers and the effective latest schema, not edit only these listed files. + +| Area / current source | Required change | +| --- | --- | +| `backend/app/api/routes/artifact_submissions.py`; `backend/app/modules/tasks/router.py`; TASK schemas | Replace public preparation + JSON admission submit with raw-ZIP `submission.create`; accepted receipt, failure envelope and operation reads. | +| `backend/app/modules/artifacts/submission_admission.py`; `selected_pre_submit_admission.py`; `submission_custody.py` | Replace process-local prepared-source authority with early durable operation/sealed source; preserve exact admission evidence guards; integrate T4/T5. | +| `backend/app/modules/artifacts/preparation.py`; `sources.py` | Remove full API scratch requirement from submission intake only; preserve other consumers and their sealed-source protections. | +| `backend/app/interfaces/artifacts.py` | Add typed streaming receipt, exact operation source/generation, read and cleanup capabilities. Keep other artifact contracts. | +| `backend/app/adapters/artifacts/s3_compatible.py`; `local.py` | Implement bounded receive, conditional completion, exact observation/generation/read/abort/delete and strict operation-ref validation. | +| `backend/app/adapters/artifacts/aws_live_proof.py` | Qualify new controlled namespace permissions, version-aware cleanup, multipart conditions and no-overwrite proofs. Preserve unrelated namespace protection. | +| `backend/app/modules/artifacts/models.py`; `service.py` | Early operation, physical per-object reservation/charge, exact registration and cleanup fencing; preserve logical content identity. | +| `backend/app/modules/artifacts/submission_manifest.py` | Reuse canonical representation and change-gate semantics; add exact request/source binding where required. | +| `backend/app/modules/artifacts/submission_materialization.py` | Replace submission PRE intake/export/close/second-runtime handoff with one-session source execution. Do not delete shared POST/other consumers blindly. | +| `backend/app/modules/checkers/models.py`; `selected_pre_submit_coordination.py`; PRE API facts | Replace required pre-extraction manifest/process-local generation with immutable raw source request and nullable derived result evidence; preserve leases/audits. | +| `backend/app/modules/checkers/selected_pre_submit_execution.py` | One platform/default/project PRE invocation; validate derived request/result and terminal evidence. | +| `backend/app/modules/checkers/api/default_checker.py`; `default_checker.py` | Relocate/reuse four defaults with semantic fixtures; no accidental policy change. | +| `backend/app/interfaces/external_checker_execution.py`; `backend/app/adapters/checkers/__init__.py` | Provider-qualified common source/request/result/health/cleanup contracts; Smol-specific host facts stay inside its adapter. | +| `external_checkers/workstream-checker-service/src/smol.rs`; `smol/io.rs`; `smol/intake.rs`; `smol/admission.rs` | Single PRE creation and bounded object input delivery, qualified reservation, cleanup/reconciliation; no API/host whole-file export requirement. | +| `external_checkers/workstream-checker-guest/src/main.rs` | Combined protected PRE bootstrap/default/project purpose in one guest; bounded evidence and process/control isolation. | +| `backend/app/modules/tasks/submission_composition.py`; `api/submission_command.py` | Operation-scoped acceptance and exact internal finalization authority; actual Submission/POST dispatch T5 under existing owners. | +| `backend/app/modules/tasks/lifecycle.py`; `models.py`; `repository.py`; `submission_context.py` | Active operation guard; direct accepted transition; eligible-state/revision/currentness validation; owner-qualified pending continuation. | +| `backend/app/modules/tasks/assignment_invalidation.py` | Respect active/pending operation custody; never reopen accepted work because the new Submission row is not created yet. | +| `backend/app/modules/tasks/contributor_reads.py` and read API schemas | Single submit next-action; distinguish active upload/PRE, pending finalization, actual POST and historical predecessor. | +| `backend/app/modules/artifacts/post_submit_selection.py` | Replace the SHA-derived-key equality assumption with exact accepted operation/replica/generation selection. | +| `backend/app/modules/artifacts/post_submit_materialization.py`; selected POST execution | Adapt source contract as needed; preserve evaluation/trial/model/forge behavior and guards. | +| `backend/app/Celery workers/artifacts.py`; `outbox.py`; `celery_app.py` and owner composition | Finalization notification/recovery, scoped object cleanup, runtime obligations, queue separation and idempotent retries. No PRE Celery worker. | +| `backend/alembic/versions/` and schema baseline/evidence workflow | Migrate effective constraints/functions/indexes/foreign keys; include dispatch/custody evolution originating in 0025, 0034, 0036 and 0043 plus later definitions. | +| `backend/app/modules/checkers/api/external_policy.py`; project guide approval/compiler | Exactly one approved executable entry per phase, locked together; retain many project requirements inside the selected image/specification. | +| `cli/internal/command/submission.go`; `cli/internal/api/submission.go`; reads/feedback | One `task submit` with file and existing selectors/key; remove separate bundle prepare/admission submit; parse accepted operation receipt and progress safely. | +| `mcp_server/workstream_mcp/tools/task_execution.py`; `http_gateway.py`; schemas/contracts | One submission tool delegates to the same raw-ZIP backend mutation; bounded input transport and updated receipt/read projection. | +| Policy approval CLI/MCP contracts | Tighten phase cardinality consistently; do not leave clients able to publish invalid zero/multiple selections. | +| Proxy/deployment configuration and readiness | Prove true streaming, finite envelopes, provider qualifications, namespace permissions and resource/admission profiles. | + +### 21.1 Client details + +The CLI's submit action uploads once, waits for inline PRE outcome, prints the durable acceptance receipt or actionable findings, and ends. It does not instruct the user to perform another submit or wait for a ready admission. + +Keep local file-source stability checks where needed, safe JSON/terminal output, explicit unknown-outcome recovery and exact input/key replay. Add operation status inspection without implicitly resubmitting or polling an unbounded loop. + +Preserve governed **revision preparation/acknowledgement** actions where the existing revision workflow requires them. Removing the old bundle-preparation action does not remove that separate revision rule. + +MCP is an adapter to the same backend action. Its current 64 MiB transfer bound and 120-second timeout are narrower than the backend archive ceiling; update documentation and effective timeout validation honestly. Do not silently raise a base64 JSON/tool transport to 500 MiB or create a second backend upload flow. A larger MCP transport redesign needs an explicit scoped decision; it is not necessary to implement the single backend submission contract. + +### 21.2 Tests and current documentation + +Update the affected outcome/contract tests, including: + +- Public submission intake, preparation recovery, exact replay and revision/dispatch concurrency. +- Selected PRE coordination/materialization and current tests expecting a separate intake export/cleanup before project PRE. +- Artifact admission/custody, storage streaming/uncertain completion and cleanup wiring. +- Artifact architecture tests currently forbidding all multipart/list/delete operations: replace obsolete blanket prohibitions with narrow typed-owner/bounded/authorized behavior assertions. Copy remains unnecessary. +- AWS live proof and exact retained-data protections. +- External policy tests and project fixtures currently permitting empty/multiple phase selections. +- CLI/MCP request/receipt/feedback/progress schemas. +- Existing POST, review, revision and contribution-record regression proofs. + +Update current entry-point documentation, architecture/checker framework docs, guide-checker specification, checker policy template, ADR 0014 integration assumptions, external-checker README, MCP README and capability ledger as warranted by delivered evidence. Do not claim the entire design shipped merely because a schema or isolated unit test landed. + +## 22. Implementation sequence + +Use a bounded sequence with explicit completion evidence: + +1. **Owner contracts and schema.** Add intake operation, exact source/generation, accepted authority, task pointer, derived PRE evidence and constraints. Establish migration compatibility with retained data. +2. **Streaming custody and cleanup.** Implement bounded receipt, EOF/completion recording, physical accounting, exact version reads/deletion and uncertain multipart recovery. Prove limits and cleanup fences independently. +3. **One-session PRE.** Implement trusted input/default/project flow, exact result binding, finite profiles and provider-neutral contract; prove the Smol path and managed-style substitution. +4. **Atomic accepted handoff.** Compose T1–T4 with eligibility/revision/authority, fenced evidence and outbox. Prove request failure/commit ambiguity and no premature receipt. +5. **Durable finalization.** Implement T5 through existing owners; prove replay, Celery worker crash and no copy/reupload. Gate POST on formal committed dispatch. +6. **Clients and progress.** Replace the public split flow across API/CLI/MCP; add truthful pending-operation reads and bounded errors/findings. +7. **Policy/cutover/deployment proof.** Enforce one image per phase, update SQL guards/fixtures/docs/readiness, execute the integrated failure/load/retention matrix. + +These are implementation increments, not separate product versions or a reason to expose an incomplete alternative path. The final enabled flow must satisfy all invariants. + +## 23. Acceptance evidence and completion gate + +Tests must prove real boundaries. Mocking a method name does not prove bounded memory, object immutability, cross-process fencing or runtime isolation. Use focused owner tests, real PostgreSQL concurrency/rollback proofs, qualified local S3/MinIO integration, actual Smol execution and targeted provider/live proof where required. + +### 23.1 Mandatory outcome matrix + +| ID | Scenario | Observable pass condition | +| --- | --- | --- | +| A01 | Successful initial submission through public API/CLI | One body upload, one source key/generation, one PRE session; T4 pending+outbox before 202; T5 exact formal Submission; POST follows. | +| A02 | Default QC failure before project execution | Inline bounded default findings; project marked not run; no new Submission/retained binding/POST/revision count. | +| A03 | Project PRE QC failure | Inline project findings; task remains eligible; cleanup owns failed object. | +| A04 | Same actor/key, changed metadata | 409 before new object/PRE work. | +| A05 | Same sealed key/body replay and changed-body replay | Bounded discard hash; original result or conflict respectively; no storage write/PRE rerun. | +| A06 | Concurrent different keys on same task | One active owner; loser cannot allocate a competing source or PRE session. | +| A07 | Interrupted pre-seal operation | Fenced terminal outcome; same key cannot resume unknown input; no PRE Celery worker fallback. | +| A08 | Lost response/unknown commit around T4 | Read/replay resolves one durable outcome; no duplicate accepted operation or premature task reopening. | +| A09 | Celery Worker crash before/during/after T5 and redelivery | One version, Submission, exact binding and logical initial POST dispatch; rollback leaves pending custody. | +| A10 | Broker unavailable after T4 or T5 | Database outbox repairs delivery; source/task remain protected. | +| A11 | Celery Worker delayed past token/revision deadline | Accepted command completes under recorded authority; no new eligibility check rejects elapsed time alone. | +| A12 | Authority/assignment/predecessor/rules change before T4 | Stale pass cannot accept; failure has no contributor revision penalty. | +| A13 | New revision pending with older Submission present | Reads identify the new operation; old Submission is history; no accidental old POST dispatch. | +| A14 | Cleanup races T4/T5 | Same custody lock/fence allows only valid ownership outcome; accepted input is never deleted. | +| A15 | Celery Worker unavailable through multiple cleanup sweeps | Pending/retrying/stalled object survives regardless of age. | +| A16 | AWS versioned failed-object cleanup | Exact eligible VersionId removed; retained versions unaffected; actual charge released once. | +| A17 | Lost multipart begin/complete/delete acknowledgement and late part writes | Scoped reconciliation owns every handle/version; no false deletion/quota release or accepted late result. | +| A18 | Equal content uploaded in separate operations | Logical content may share identity; each exact physical object/generation is counted and correctly bound. | +| A19 | Maximum/slow upload and stalled provider | Proved bounded API/SDK memory and part concurrency; no proxy/framework/API whole-file spool; deadline enforced. | +| A20 | Over-limit, truncated, dishonest length and malformed framing | No PRE handoff; exact terminal/cleanup ownership; no unbounded buffering. | +| A21 | ZIP bombs, traversal, collisions, encryption, unsafe entries | Existing safe-archive behavior and limits preserved; protected filesystem untouched. | +| A22 | Repacked identical files under unchanged rules; changed-rule exception | Existing raw/semantic unchanged-input policy preserved with canonical fixtures. | +| A23 | Secret detection and malicious output | Bounded safe findings, no secret/credential/signed-URL leakage; no control-frame forgery. | +| A24 | Object/raw/count/manifest/image/config/request/fence substitution | No accepted handoff or retained registration; integrity/protocol failure distinguished from QC. | +| A25 | PRE stage timeout, guest OOM/crash or oversized output | Infrastructure result, no revision penalty, recorded runtime/object cleanup. | +| A26 | PRE result valid, destroy uncertain | Accepted work can continue; cleanup obligation remains; capacity not falsely free. | +| A27 | Malicious project tries to alter input/supervisor/credentials | Isolation and exact source proof hold in one guest. | +| A28 | Two API replicas and multiple self-hosted nodes | Shared admission/owner uniqueness and authoritative node reservations survive races/restart/drain. | +| A29 | POST saturation and PRE/finalization admission | Bounded independently reserved capacity; no unbounded queues or starvation by long POST jobs. | +| A30 | Managed-style adapter without host path/Unix/Smol facts | Core lifecycle/source/result/cleanup code works through the same typed contract; unsupported capabilities reject. | +| A31 | Existing POST model/trial/forge and review/revision paths | Behavior/authority preserved; one selected image; required review cannot be bypassed. | +| A32 | Automatic acceptance and human acceptance | Existing atomic FinalAcceptance/ContributionRecord/award facts; no fabricated Review. | +| A33 | Migration with retained SHA artifacts and old admissions | Historical evidence remains readable; unsubmitted ready admissions not auto-submitted; no bulk object rewrite/delete. | +| A34 | Policy cardinality and setup selection | Missing/multiple PRE or POST selection rejected everywhere; only authorized approved exact images used. | +| A35 | Foreground/client edge and API schema convergence | One mutation across CLI/MCP/backend; removed bundle-preparation path absent from active contract; revision acknowledgement preserved. | + +### 23.2 Performance and provider evidence + +For measured PRE latency and limits, record actual provider/host hardware, resource profile, input sizes/expansion, image/default digests, image-cache conditions, concurrency, sample size, stage durations and percentiles. Include representative permitted maxima and cold/uncached conditions. + +Demonstrate the chosen finite aggregate deadline and request buffering behavior through the deployed edge. Separate observed benchmark results from a target or configured limit. + +A fake managed adapter proves decoupling, not production qualification of a paid service. A local MinIO proof does not by itself prove AWS version/IAM behavior. State exactly which provider tests ran. + +### 23.3 Definition of implementation complete + +The implementation is complete only when: + +- All D01–D18 decisions and I01–I12 invariants are implemented. +- T1–T5 and database guards are proved under failure/concurrency, not just happy-path unit tests. +- The same object/generation can be traced from ingress through PRE, registration and POST. +- Existing relevant POST/review/revision/record behavior remains proved. +- All required deployment profiles/limits are resolved and readiness rejects unsupported configurations. +- The single API/CLI/MCP contract and current docs match delivered behavior. +- Superseded submission code/tests are removed within traced scope; shared consumers and retained data remain intact. +- The implementation report lists evidence for every acceptance scenario, any deliberately deferred live-provider proof, and remaining limitations without declaring untested support. + +This document itself was reviewed as a design. It is not test execution evidence for a future implementation. + +## 24. Unresolved values and follow-up protocol + +The architecture, storage location, Celery worker boundary, image cardinality, replay semantics and cleanup policy are selected above. No architectural menu remains. + +Some numerical deployment settings cannot be responsibly inferred from this conversation or the inspected code. They are configuration inputs to the selected design, not permission to choose another design. An implementing agent may use an existing approved value only when its scope/meaning matches this new flow and its source is recorded. + +### 24.1 Required configuration register + +| ID | Required value/profile | Current authority | Required action if absent | +| --- | --- | --- | --- | +| C01 | Finite aggregate PRE hard deadline; PRE admission bound; related HTTP envelope | Approximately 60-second experience target is approved; a precise aggregate hard cutoff is not | Ask for the approved hard envelope, presenting measured representative results. Never inherit the old 300s/3400s timers or silently turn the target into a cutoff. | +| C02 | Approved default PRE/POST CPU, RAM, disk, process and output profiles; selected capability limits | Existing registry/profile values and phase restrictions where applicable; no universal 1 GB selection | Reuse qualified profiles that satisfy the full request; ask for approval of missing measured values. Do not assume resource ranges are tested defaults. | +| C03 | Upload idle/total limits, multipart part size/in-flight count, SDK buffer/retry bounds, request/header envelope | Existing matching transport limits where valid; archive maxima fixed in section 18 | Supply and verify a finite deployment profile. Ask where a change affects supported contributor input/wait behavior. | +| C04 | API/PRE/POST/finalization admission/concurrency limits and enabled physical quota scopes | Existing authorized deployment capacities/policy where valid | Measure and record initial values before enabling admission. Do not translate scratch-file counts into upload capacity by name alone. | +| C05 | Celery Worker retry/backoff/lease/heartbeat/stall thresholds and operator retry authority | Existing durable owner conventions where semantics match | Specify finite values and the existing authorized operator mechanism; ask before inventing a new business/admin capability. | +| C06 | Runtime maximum lifetime/reaper/destroy envelope; storage cleanup batch/retry settings and metadata/tombstone retention | Prompt runtime cleanup required; object sweep12h/minimum age2h fixed; historical evidence governed by existing retention | Supply bounded operational settings. Do not remove tombstones while stale outcomes can still arrive or alter retained-evidence policy. | +| C07 | Any selected managed provider and its full capability qualification | No specific paid provider was selected; initial implementation remains qualified Smol | Do not choose a vendor or claim production support. Implement the common contract and substitution proof; ask when a live provider is actually required. | + +Implementation of the owner contracts, data model, finite-setting validation and test fixtures may proceed while deployment-specific values are gathered. Production/default values must not be fabricated. Mark test-only resource/time settings as fixtures, not approved deployment defaults. + +Readiness/startup validation must reject missing, nonfinite, contradictory or unsupported required settings. Configuration failure must not quietly enable unbounded work or weaken checks. + +### 24.2 Follow-up format for an implementation agent + +When blocked, report: + +1. **Requirement:** the exact section/decision/invariant affected. +2. **Evidence:** current code/schema/profile location and observed conflict. +3. **Missing decision:** one precise question, including the concrete value or behavior needed. +4. **Impact:** what cannot be safely implemented/enabled until answered. +5. **Completed work:** authorized unaffected work already finished and its evidence. + +Do not ask the user to reapprove choices already fixed here. Do not resolve a conflict by introducing a second bucket, API scratch custody, two PRE guests, multiple selected project images, a second public submit action, Celery worker-run PRE, direct client-to-store upload, object copying, or a provider-host requirement. + +If later repository behavior conflicts materially with the pinned baseline, report it before deleting shared code or changing retained-data/authorization semantics. Adapt routine implementation details within existing owners without treating every private function name as a product question. + +## 25. Sources and design rationale + +### 25.1 How to interpret sources + +The following links establish the inspected current implementation and external provider mechanics. The target design choices in this document come from the user's approved decisions and the explicit contracts above; they are not claims that current main already implements them. + +All repository links are pinned to the reviewed commit so a later main change cannot silently alter this document's evidence. + +### 25.2 Current repository evidence + +- **R1 — current split public submission path:** [preparation route](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/api/routes/artifact_submissions.py), [formal submit route](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/tasks/router.py), [CLI contract](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/cli/internal/api/submission.go). +- **R2 — existing submission custody and admission:** [submission_admission.py](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/artifacts/submission_admission.py), [preparation.py](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/artifacts/preparation.py), [submission_materialization.py](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/artifacts/submission_materialization.py). +- **R3 — storage references, S3 implementation and AWS proof:** [storage interface](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/interfaces/artifacts.py), [S3-compatible adapter](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/adapters/artifacts/s3_compatible.py), [AWS live proof](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/adapters/artifacts/aws_live_proof.py), [POST source selection](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/artifacts/post_submit_selection.py). +- **R4 — task creation, authority and reads:** [submission composition](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/tasks/submission_composition.py), [typed command/authority](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/tasks/api/submission_command.py), [lifecycle](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/tasks/lifecycle.py), [contributor reads](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/tasks/contributor_reads.py). +- **R5 — canonical defaults, manifest and limits:** [default contracts](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/checkers/api/default_checker.py), [default execution semantics](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/checkers/default_checker.py), [manifest](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/artifacts/submission_manifest.py), [archive limits](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/artifacts/api/submission_archive.py), [deployment settings](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/core/config.py). +- **R6 — selected execution and provider coupling:** [execution interface](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/interfaces/external_checker_execution.py), [PRE coordination](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/checkers/selected_pre_submit_coordination.py), [PRE execution](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/checkers/selected_pre_submit_execution.py), [POST execution](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/backend/app/modules/checkers/selected_post_submit_execution.py), [Smol runtime](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/external_checkers/workstream-checker-service/src/smol.rs). +- **R7 — ownership and implementation conventions:** [AGENTS.md](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/AGENTS.md), [ADR 0014](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/docs/decision_0014_external_service_adapter_convention.md), [MCP transport documentation](https://github.com/Flow-Research/workstream/blob/01299e36a486c948be6f05f4e122dea39b993a04/mcp_server/README.md). + +### 25.3 Primary provider references + + +**P1 — request streaming:** [NGINX proxy_request_buffering](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_request_buffering). Supports the requirement to verify actual edge streaming rather than assuming an application iterator proves it. + + +**P2 — object completion:** [S3 CompleteMultipartUpload](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html). Supports conditional completion, immutable-generation receipt and full response parsing. + + +**P3 — exact version deletion:** [Deleting object versions](https://docs.aws.amazon.com/AmazonS3/latest/userguide/DeletingObjectVersions.html). Supports distinguishing delete markers from removal of the bytes of a specific version. + + +**P4 — checksum semantics:** [Checking object integrity for uploads](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity-upload.html). Supports keeping whole-file SHA, multipart/provider checksums and ETag semantics distinct. + + +**P5 — Celery worker delivery:** [Celery tasks](https://docs.celeryq.dev/en/stable/userguide/tasks.html). Supports idempotent handlers, explicit timeouts and verification of acknowledgement/recovery behavior. + + +**P6 — multipart conditional policy:** [Enforce conditional writes](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes-enforce.html). Supports permitting multipart setup/parts while enforcing create-only conditions at final object creation. + + +**P7 — multipart abort:** [S3 AbortMultipartUpload](https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html). Supports confirming part cleanup and resolving in-flight uploads rather than releasing charges after one abort response. + +External documentation was checked while drafting. An implementer must verify the selected provider/SDK versions during qualification; a reference URL is not a substitute for the required integration proof. + + diff --git a/scripts/check_stale_authorization_docs.py b/scripts/check_stale_authorization_docs.py index 55830c539..9c15caa46 100644 --- a/scripts/check_stale_authorization_docs.py +++ b/scripts/check_stale_authorization_docs.py @@ -273,6 +273,12 @@ class Rule: ) MATCH_EXEMPTIONS = { + # Exact storage-key example, not a public API route. All other /v1 uses + # in this active specification remain subject to the API-prefix rule. + ( + "docs/spec_submission_execution.md", + "NON_CANONICAL_API_PREFIX", + ): re.compile(r"^submission-source/v1//bundle\.zip$"), ( "docs/reference_specs/README.md", "NON_CANONICAL_API_PREFIX", diff --git a/scripts/test_submission_spec_wording.py b/scripts/test_submission_spec_wording.py new file mode 100644 index 000000000..779eccc9e --- /dev/null +++ b/scripts/test_submission_spec_wording.py @@ -0,0 +1,27 @@ +"""The storage-key example must not exempt noncanonical public API routes.""" + +import unittest + +from scripts.check_stale_authorization_docs import RULES, exempt_match + + +class SubmissionSpecWordingTests(unittest.TestCase): + def test_only_the_exact_storage_key_line_is_exempt(self): + rule = next(item for item in RULES if item.code == "NON_CANONICAL_API_PREFIX") + key = "submission-source/v1//bundle.zip" + for path, line, expected in ( + ("docs/spec_submission_execution.md", key, True), + ("docs/other.md", key, False), + ("docs/spec_submission_execution.md", "POST /v1/tasks", False), + ("docs/spec_submission_execution.md", key + " POST /v1/tasks", False), + ("docs/spec_submission_execution.md", "/v1/submission-source", False), + ): + with self.subTest(path=path, line=line): + matches = list(rule.pattern.finditer(line)) + self.assertTrue(matches) + for match in matches: + self.assertEqual(exempt_match(path, rule, line, match.start()), expected) + + +if __name__ == "__main__": + unittest.main() From 4e94347736d2e50d8fe4480fa3e52b1ef8a4b6f1 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 17:02:17 +0100 Subject: [PATCH 002/513] Keep API prefix checks precise for the source-key example --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 2 +- scripts/check_stale_review_contracts.py | 8 ++++++++ scripts/test_submission_spec_wording.py | 3 +++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 23567e809..2a9123d08 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -24,7 +24,7 @@ operation-based keys before bytes are known and exact durable identity afterward - `backend/tests/artifacts/test_submission_intake_contracts.py`: pure contract proof. - `docs/spec_submission_execution.md`: user-supplied specification, with technical Celery-worker vocabulary qualified for repository documentation checks. -- `scripts/check_stale_authorization_docs.py` and +- `scripts/check_stale_authorization_docs.py`, `scripts/check_stale_review_contracts.py` and `scripts/test_submission_spec_wording.py`: exact object-key example exemption; public API prefix enforcement remains unchanged elsewhere. - This initiative, index and capability ledger: target and limited delivered scope. diff --git a/scripts/check_stale_review_contracts.py b/scripts/check_stale_review_contracts.py index c6313ad80..82653fb13 100644 --- a/scripts/check_stale_review_contracts.py +++ b/scripts/check_stale_review_contracts.py @@ -322,6 +322,14 @@ def scan_text(relative_path: str, text: str) -> list[str]: failures: list[str] = [] for rule in RULES: for match in rule.pattern.finditer(text): + # This exact line describes a storage key, not an API route. + if ( + relative_path == "docs/spec_submission_execution.md" + and rule.code == "NON_CANONICAL_API_PREFIX" + and text.splitlines()[line_number(text, match.start()) - 1] + == "submission-source/v1//bundle.zip" + ): + continue failures.append( f"{relative_path}:{line_number(text, match.start())}: {rule.code}" ) diff --git a/scripts/test_submission_spec_wording.py b/scripts/test_submission_spec_wording.py index 779eccc9e..6b211d1fc 100644 --- a/scripts/test_submission_spec_wording.py +++ b/scripts/test_submission_spec_wording.py @@ -3,6 +3,7 @@ import unittest from scripts.check_stale_authorization_docs import RULES, exempt_match +from scripts.check_stale_review_contracts import scan_text class SubmissionSpecWordingTests(unittest.TestCase): @@ -21,6 +22,8 @@ def test_only_the_exact_storage_key_line_is_exempt(self): self.assertTrue(matches) for match in matches: self.assertEqual(exempt_match(path, rule, line, match.start()), expected) + failures = scan_text(path, line) + self.assertEqual(bool(failures), not expected) if __name__ == "__main__": From 87fde6c310f1ddfbb7664054f3f0efc8559238ab Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 17:08:22 +0100 Subject: [PATCH 003/513] Bind intake sources to the existing ART namespace and select regression proof --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 4 ++ .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 38 +++++++++----- .../artifacts/api/submission_intake.py | 10 ++-- backend/scripts/test_lane_catalogue.py | 1 + .../test_submission_intake_contracts.py | 49 +++++++++++++++++-- backend/tests/test_ci_lane_catalogue.py | 4 +- docs/spec_submission_execution.md | 2 +- scripts/check_stale_authorization_docs.py | 7 +++ scripts/test_lightweight_agent_gates.py | 14 ++++++ scripts/test_stale_review_contracts.py | 11 +++++ scripts/test_submission_spec_wording.py | 30 ------------ 11 files changed, 118 insertions(+), 52 deletions(-) delete mode 100644 scripts/test_submission_spec_wording.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 9816037ba..64b58650d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -54,6 +54,10 @@ the spec baseline change deployment/identity, not submission owners. Open PR #698 changes CLI preparation; #707 changes public access/profile behavior. Reconcile those surfaces when reached without modifying their branches. +PR #707 merged during the first change. Reconciled current main `94334ccf4`, +including issuer-owned profile metadata, public Swagger and schema head 0068. +Its roadmap paragraph is preserved; no new submission behavior was introduced. + Real PostgreSQL, S3/MinIO and Smol proof is required where claimed. Request missing live access when a concrete drill is prepared. Historical old-flow drills cannot establish this implementation's completion. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2a9123d08..dbb569856 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -22,10 +22,13 @@ operation-based keys before bytes are known and exact durable identity afterward - `backend/app/modules/artifacts/api/submission_intake.py`: command and source values. - `backend/tests/artifacts/test_submission_intake_contracts.py`: pure contract proof. +- `backend/scripts/test_lane_catalogue.py` and `backend/tests/test_ci_lane_catalogue.py`: + register the new tests in the shared-foundations lane, preserving every existing member. - `docs/spec_submission_execution.md`: user-supplied specification, with technical Celery-worker vocabulary qualified for repository documentation checks. -- `scripts/check_stale_authorization_docs.py`, `scripts/check_stale_review_contracts.py` and - `scripts/test_submission_spec_wording.py`: exact object-key example exemption; +- `scripts/check_stale_authorization_docs.py`, `scripts/check_stale_review_contracts.py`, + `scripts/test_lightweight_agent_gates.py` and `scripts/test_stale_review_contracts.py`: + exact storage example exemptions and tests in already-selected CI modules; public API prefix enforcement remains unchanged elsewhere. - This initiative, index and capability ledger: target and limited delivered scope. @@ -38,18 +41,19 @@ operation-based keys before bytes are known and exact durable identity afterward ## Design and decisions Reuse canonical JSON hashing and the archive ceiling. Keys derive from server -UUIDv7 operation identity. Sealed values bind namespace/profile, raw SHA/count, +UUIDv7 operation identity. Sealed values bind ART's `primary` namespace ID and +fingerprint, provider profile, raw SHA/count, generation and fence. Metadata identity preserves exact packet and revision selectors; actor/key scope and locked context remain separate operation facts. Constructing these internal values grants no authority or provider qualification. ## Acceptance criteria -- [ ] Exact metadata round-trip and identity changes for each command selector. -- [ ] Packet/framing metadata validation preserves empty-text warning semantics. -- [ ] Source keys derive only from UUIDv7; no arbitrary path/URL selection. -- [ ] Namespace, generation, bytes and fence remain distinct identity inputs. -- [ ] Unknown fields, mutation and coercive values fail closed. +- [x] Exact metadata round-trip and identity changes for each command selector. +- [x] Packet metadata validation preserves empty-text warning semantics. +- [x] Source keys derive only from UUIDv7; no arbitrary path/URL selection. +- [x] Namespace, generation, bytes and fence remain distinct identity inputs. +- [x] Unknown fields, mutation and coercive values fail closed. - [ ] Focused tests, lint, boundary/docs checks and scoped frozen-candidate reviews. ## Risk and review routing @@ -62,16 +66,26 @@ Constructing these internal values grants no authority or provider qualification | Claim | Command or proof | Result | Remaining uncertainty | |---|---|---|---| -| Baseline | Fetch main and inspect open PRs | Reconciled a4e485ed | Recheck before publication | -| Contracts | Focused pytest and ruff | 56 tests passed; lint passed | No database/storage/runtime proof | +| Baseline | Fetch main and inspect open PRs | Reconciled 94334ccf4 | Recheck before publication | +| Contracts and CI selection | `pytest -q tests/artifacts/test_submission_intake_contracts.py tests/test_ci_lane_catalogue.py`; ruff | 118 tests passed; lint passed | No database/storage/runtime proof | +| Documentation guard regression | `python -m unittest scripts.test_lightweight_agent_gates scripts.test_stale_review_contracts -q` | 35 tests passed | Narrow storage examples only | | Module boundaries | `python -m scripts.module_boundaries validate --protected-base origin/main` | Passed | Existing private-import debt unchanged | ## Review findings -No findings recorded yet. +- Architecture/security found a synthetic UUID namespace fixture incompatible + with ART's natural singleton ID, and missing fingerprint binding. The value + now uses `primary` and its fingerprint; an actual adapter-derived namespace + regression replaces the unsupported assumption. No namespace schema changed. +- Documentation found a mechanically altered implementation path. Restored the + exact path and scoped the vocabulary exception to that literal token only. +- CI review found the new wording regression unselected. Moved it into existing + selected suites. Registered backend contracts in the semantic lane catalogue; + updated only that lane's expected member count/fingerprint. ## Reconciliation -- Current-source reconciliation: deployment delta and header mismatch inspected. +- Current-source reconciliation: rebased onto 94334ccf4 (PR #707); preserved issuer + profile roadmap changes and schema head 0068. Submission owner contracts unchanged. - Next usable boundary: durable operation schema and owner commands. - Remaining risks: A01–A35 integration and C01–C07 qualification. diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py index e94470d88..808a28f8b 100644 --- a/backend/app/modules/artifacts/api/submission_intake.py +++ b/backend/app/modules/artifacts/api/submission_intake.py @@ -73,15 +73,17 @@ class SubmissionSourceLocation(_IntakeValue): """Server-selected source address inside the existing claimed ART namespace. The namespace ID references ART's existing immutable namespace record. The - profile must match that record at every owner boundary. It is not a freely - selectable endpoint. The adapter alone applies the configured key prefix. + fingerprint and profile must match that record at every owner boundary. + The singleton ID alone cannot identify storage across deployments. It is + not a freely selectable endpoint. The adapter applies its configured prefix. """ operation_id: UUID - namespace_id: UUID + namespace_id: Literal["primary"] + namespace_fingerprint: Sha256 provider_profile: str = Field(min_length=1, max_length=100) - @field_validator("operation_id", "namespace_id") + @field_validator("operation_id") @classmethod def record_identity(cls, value: UUID) -> UUID: """Check record shape; only the durable owner proves ID provenance.""" diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 31929f227..2d8f1fb57 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -52,6 +52,7 @@ class TestLane: "tests/artifacts/test_review_packet_contract.py", "tests/reviews/packet/test_storage.py", "tests/artifacts/test_selected_predecessor_rules.py", + "tests/artifacts/test_submission_intake_contracts.py", "tests/authorization/post_submit/test_atomicity.py", "tests/authorization/post_submit/test_concurrency.py", "tests/authorization/post_submit/test_live_authority.py", diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py index 243565daf..01461f826 100644 --- a/backend/tests/artifacts/test_submission_intake_contracts.py +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -16,7 +16,7 @@ OPERATION = UUID("019a0000-0000-7000-8000-000000000001") -NAMESPACE = UUID("019a0000-0000-7000-8000-000000000002") +NAMESPACE_FINGERPRINT = "sha256:" + "c" * 64 TASK = UUID("019a0000-0000-7000-8000-000000000003") ASSIGNMENT = UUID("019a0000-0000-7000-8000-000000000004") PREDECESSOR = UUID("019a0000-0000-7000-8000-000000000005") @@ -32,7 +32,8 @@ def metadata(**updates): def location(**updates): return SubmissionSourceLocation.model_validate({ - "operation_id": OPERATION, "namespace_id": NAMESPACE, + "operation_id": OPERATION, "namespace_id": "primary", + "namespace_fingerprint": NAMESPACE_FINGERPRINT, "provider_profile": "aws-s3-v1", **updates, }) @@ -114,7 +115,7 @@ def test_source_address_is_operation_bound_and_opaque_generation_round_trips(): @pytest.mark.parametrize("updates", [ - {"location": location(namespace_id=REVISION)}, + {"location": location(namespace_fingerprint="sha256:" + "d" * 64)}, {"location": location(provider_profile="qualified-managed-v1")}, {"provider_generation": "other-version"}, {"raw_sha256": "sha256:" + "b" * 64}, @@ -143,6 +144,7 @@ def test_sealed_source_rejects_unsealed_coercive_or_authority_bearing_inputs(upd @pytest.mark.parametrize("updates", [ {"operation_id": uuid4()}, {"namespace_id": uuid4()}, + {"namespace_id": "other"}, {"namespace_fingerprint": "invalid"}, {"operation_id": str(OPERATION)}, {"provider_profile": "https://storage.invalid"}, {"object_ref": "submission-source/v1/foreign/bundle.zip"}, {"idempotency_key": OPERATION}, @@ -166,3 +168,44 @@ def test_frozen_values_revalidate_nested_instances_and_reject_unknown_command_fi SubmissionIntakeMetadata.model_validate_json(json.dumps({ "task_id": str(TASK), "assignment_id": str(ASSIGNMENT), "summary": 1, })) + + +def test_source_accepts_existing_art_namespace_and_binds_its_fingerprint(tmp_path): + """Use ART's actual singleton and adapter-derived fingerprint, not a fake UUID.""" + from app.adapters.artifacts.local import LocalStorageAdapter, LocalStorageBootstrap + from app.core.config import Settings + from app.modules.artifacts.models import ArtifactStorageNamespace + from app.modules.artifacts.service import ( + ARTIFACT_STORAGE_NAMESPACE_ID, + artifact_storage_namespace_spec, + ) + from tests.artifact_store_helpers import artifact_admission_limit_settings + + root = tmp_path / "store" + root.mkdir(mode=0o700) + settings = Settings( + **artifact_admission_limit_settings(), environment="test", + artifact_store_backend="local", artifact_local_root=root, + artifact_scratch_root=tmp_path / "scratch", artifact_scratch_minimum_free_bytes=0, + ) + bootstrap = LocalStorageBootstrap(LocalStorageAdapter( + root=root, buffer_bytes=settings.artifact_stream_buffer_bytes, + lock_timeout_seconds=settings.artifact_operation_lock_timeout_seconds, + )) + try: + spec = artifact_storage_namespace_spec(settings, bootstrap) + finally: + bootstrap.close() + namespace = ArtifactStorageNamespace( + id=ARTIFACT_STORAGE_NAMESPACE_ID, backend=spec.backend, adapter=spec.adapter, + provider_profile=spec.provider_profile, namespace_descriptor=spec.namespace_descriptor, + namespace_fingerprint=spec.namespace_fingerprint, + ) + bound = location(namespace_id=namespace.id, namespace_fingerprint=namespace.namespace_fingerprint, + provider_profile=namespace.provider_profile) + assert bound.namespace_id == "primary" + assert bound.namespace_fingerprint == spec.namespace_fingerprint + assert source(location=bound).source_sha256() != source(location=location( + namespace_id=namespace.id, namespace_fingerprint="sha256:" + "d" * 64, + provider_profile=namespace.provider_profile, + )).source_sha256() diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 13e263bd6..c7a758bfe 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -317,8 +317,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 268, - "9ff668cabce1f8017f8784bd1233bed7aae0b892cf6aa9da82b3249a06cd819b", + 269, + "e302d703e1236f8fbc857009e1df5e2ceec39ea1053ba430cdc8747074d87b7f", ), "project": ( 255, diff --git a/docs/spec_submission_execution.md b/docs/spec_submission_execution.md index 202f9bc8e..af6b89751 100644 --- a/docs/spec_submission_execution.md +++ b/docs/spec_submission_execution.md @@ -1177,7 +1177,7 @@ All paths below are relative to the pinned repository. They identify inspected c | `backend/app/modules/tasks/contributor_reads.py` and read API schemas | Single submit next-action; distinguish active upload/PRE, pending finalization, actual POST and historical predecessor. | | `backend/app/modules/artifacts/post_submit_selection.py` | Replace the SHA-derived-key equality assumption with exact accepted operation/replica/generation selection. | | `backend/app/modules/artifacts/post_submit_materialization.py`; selected POST execution | Adapt source contract as needed; preserve evaluation/trial/model/forge behavior and guards. | -| `backend/app/Celery workers/artifacts.py`; `outbox.py`; `celery_app.py` and owner composition | Finalization notification/recovery, scoped object cleanup, runtime obligations, queue separation and idempotent retries. No PRE Celery worker. | +| `backend/app/workers/artifacts.py`; `outbox.py`; `celery_app.py` and owner composition | Finalization notification/recovery, scoped object cleanup, runtime obligations, queue separation and idempotent retries. No PRE Celery worker. | | `backend/alembic/versions/` and schema baseline/evidence workflow | Migrate effective constraints/functions/indexes/foreign keys; include dispatch/custody evolution originating in 0025, 0034, 0036 and 0043 plus later definitions. | | `backend/app/modules/checkers/api/external_policy.py`; project guide approval/compiler | Exactly one approved executable entry per phase, locked together; retain many project requirements inside the selected image/specification. | | `cli/internal/command/submission.go`; `cli/internal/api/submission.go`; reads/feedback | One `task submit` with file and existing selectors/key; remove separate bundle prepare/admission submit; parse accepted operation receipt and progress safely. | diff --git a/scripts/check_stale_authorization_docs.py b/scripts/check_stale_authorization_docs.py index 9c15caa46..65f7ee311 100644 --- a/scripts/check_stale_authorization_docs.py +++ b/scripts/check_stale_authorization_docs.py @@ -344,6 +344,13 @@ def containing_line(text: str, offset: int) -> str: def exempt_match(relative_path: str, rule: Rule, text: str, offset: int) -> bool: """Return whether one exact reviewed archival marker match is allowed.""" + # Preserve the literal implementation path in the imported specification. + # Exempt only its workers token; adjacent prose still undergoes every rule. + if (relative_path == "docs/spec_submission_execution.md" + and rule.code == "HUMAN_WORKER_VOCABULARY"): + start = offset - len("`backend/app/") + if start >= 0 and text[start:].startswith("`backend/app/workers/artifacts.py`"): + return True exemption = MATCH_EXEMPTIONS.get((relative_path, rule.code)) return bool(exemption and exemption.fullmatch(containing_line(text, offset))) diff --git a/scripts/test_lightweight_agent_gates.py b/scripts/test_lightweight_agent_gates.py index 2a58f70e8..8b5f5486e 100644 --- a/scripts/test_lightweight_agent_gates.py +++ b/scripts/test_lightweight_agent_gates.py @@ -352,6 +352,20 @@ def test_stale_authorization_rejects_noncanonical_api_prefix(self) -> None: failures = scan_authorization_text("docs/new-guide.md", "Call /v1/tasks.") self.assertIn("docs/new-guide.md:1: NON_CANONICAL_API_PREFIX", failures) + def test_submission_storage_examples_do_not_exempt_public_routes_or_human_roles(self): + path = "docs/spec_submission_execution.md" + key = "submission-source/v1//bundle.zip" + for candidate_path, line, rejected in ( + (path, key, False), ("docs/other.md", key, True), + (path, "POST /v1/tasks", True), (path, key + " POST /v1/tasks", True), + (path, "/v1/submission-source", True), + (path, "`backend/app/workers/artifacts.py`; task delivery", False), + (path, "`backend/app/workers/artifacts.py`; the worker submits a task", True), + (path, "A worker submits work", True), + ): + with self.subTest(path=candidate_path, line=line): + self.assertEqual(bool(scan_authorization_text(candidate_path, line)), rejected) + def test_stale_authorization_allows_exact_compose_worker_service(self) -> None: commands = ( "docker compose --profile backend exec -T worker " diff --git a/scripts/test_stale_review_contracts.py b/scripts/test_stale_review_contracts.py index 8411fc4ac..7fc058d21 100644 --- a/scripts/test_stale_review_contracts.py +++ b/scripts/test_stale_review_contracts.py @@ -6,6 +6,17 @@ class RevisionTimeoutContractTests(unittest.TestCase): + def test_only_the_exact_submission_storage_key_is_not_an_api_prefix(self): + path = "docs/spec_submission_execution.md" + key = "submission-source/v1//bundle.zip" + for candidate_path, line, rejected in ( + (path, key, False), ("docs/other.md", key, True), + (path, "POST /v1/tasks", True), (path, key + " POST /v1/tasks", True), + (path, "/v1/submission-source", True), + ): + with self.subTest(path=candidate_path, line=line): + self.assertEqual(bool(scan_text(candidate_path, line)), rejected) + def test_deadline_rejection_receipt_is_allowed(self) -> None: for text in ( "The revision deadline automatically rejects the outstanding attempt.", diff --git a/scripts/test_submission_spec_wording.py b/scripts/test_submission_spec_wording.py deleted file mode 100644 index 6b211d1fc..000000000 --- a/scripts/test_submission_spec_wording.py +++ /dev/null @@ -1,30 +0,0 @@ -"""The storage-key example must not exempt noncanonical public API routes.""" - -import unittest - -from scripts.check_stale_authorization_docs import RULES, exempt_match -from scripts.check_stale_review_contracts import scan_text - - -class SubmissionSpecWordingTests(unittest.TestCase): - def test_only_the_exact_storage_key_line_is_exempt(self): - rule = next(item for item in RULES if item.code == "NON_CANONICAL_API_PREFIX") - key = "submission-source/v1//bundle.zip" - for path, line, expected in ( - ("docs/spec_submission_execution.md", key, True), - ("docs/other.md", key, False), - ("docs/spec_submission_execution.md", "POST /v1/tasks", False), - ("docs/spec_submission_execution.md", key + " POST /v1/tasks", False), - ("docs/spec_submission_execution.md", "/v1/submission-source", False), - ): - with self.subTest(path=path, line=line): - matches = list(rule.pattern.finditer(line)) - self.assertTrue(matches) - for match in matches: - self.assertEqual(exempt_match(path, rule, line, match.start()), expected) - failures = scan_text(path, line) - self.assertEqual(bool(failures), not expected) - - -if __name__ == "__main__": - unittest.main() From e0d6b64c3bcd0c3ccc06f4d11f94791bb3ea86a3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 17:11:17 +0100 Subject: [PATCH 004/513] Clarify the initial intake PR snapshot --- .commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 64b58650d..eb5c7602a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -50,9 +50,9 @@ defaults. Current Caddy allows 16 KiB total headers; target packet text permits not delivered by preserving its guards. Initial main is `a4e485edea03db90c71189c51eac85cf4c3b1139`. The 14 commits after -the spec baseline change deployment/identity, not submission owners. Open PR -#698 changes CLI preparation; #707 changes public access/profile behavior. -Reconcile those surfaces when reached without modifying their branches. +the spec baseline change deployment/identity, not submission owners. At initial +intake, open PR #698 changed CLI preparation and #707 changed public access/profile +behavior. Reconcile affected surfaces without modifying their branches. PR #707 merged during the first change. Reconciled current main `94334ccf4`, including issuer-owned profile metadata, public Swagger and schema head 0068. From 0ae158aaa4bcedd0f49ace5ba7556c9a5a250317 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 17:46:34 +0100 Subject: [PATCH 005/513] Register submission intake in the protected behavior partition --- .ci/behavior-ownership/partition.v1.json | 6 +++- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 36 +++++++++++++------ backend/scripts/behavior_ownership.py | 4 +++ backend/tests/test_behavior_ownership.py | 11 ++++++ 4 files changed, 46 insertions(+), 11 deletions(-) diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index baf90ec36..36877128b 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -552,6 +552,10 @@ "group": "artifacts", "target": "backend/app/modules/artifacts/api/submission_archive.py" }, + { + "group": "artifacts", + "target": "backend/app/modules/artifacts/api/submission_intake.py" + }, { "group": "artifacts", "target": "backend/app/modules/artifacts/api/submission_preparation.py" @@ -2593,7 +2597,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "a35f53b2939c6ce611f86f44336bfe43f0aec5e08fcfa9d688804b57661d3b46", + "authority_digest": "d303fa6bac1b76637fe1f4a31cf700c38bda0c84fc173b168850d3bbc1082537", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index dbb569856..60cd29819 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1,14 +1,19 @@ -# WS-SUBMIT-001-01 — Immutable intake command and source identities +# WS-SUBMIT-001-01 — Single-request submission execution - Initiative: WS-SUBMIT-001 - Durable disposition: Planned -- Intended merge outcome: closed immutable ART command/source values with exact canonical identities and rejection tests. +- Intended merge outcome: the complete single-request submission specification, including durable intake, one-session PRE, accepted handoff, finalization, clients and end-to-end proof. ## Intent -Give database, upload and execution owners one representation of the original -command and sealed source, separate from credentials and later manifest facts. -This is the first portion of specification section 22 step 1. +Implement the [approved specification](../../../docs/spec_submission_execution.md) +in one PR with focused commits for each stage. The user explicitly requires the +complete end-to-end behavior and tests before requesting merge; intermediate +contract, schema or runtime stages are not separate merge checkpoints. + +The first stage gives database, upload and execution owners one representation +of the original command and sealed source, separate from credentials and later +manifest facts. ## Current behavior @@ -32,10 +37,19 @@ operation-based keys before bytes are known and exact durable identity afterward public API prefix enforcement remains unchanged elsewhere. - This initiative, index and capability ledger: target and limited delivered scope. +- `backend/scripts/behavior_ownership.py`, its existing test module and + `.ci/behavior-ownership/partition.v1.json`: register only the new immutable + contract target in the protected partition after CI exposed the missing entry. + +- Existing ART/TASK/AUTH/CHECKERS owners, composition roots, routes, migrations, + storage/runtime adapters, durable continuation, CLI/MCP and their tests and + current documentation as required by the specification. Each stage records + concrete proof; incomplete stages remain unexposed until coordinated cutover. + ### Not allowed -- Routes, migrations, orchestration, provider I/O or claims of database enforcement. -- Historical data changes, new authority, runtime changes or deployment defaults. +- Retained evidence deletion or rewriting, unrelated product changes, fabricated + deployment defaults or unsupported storage/runtime qualification claims. - Unrelated preparations or another open PR's branch. ## Design and decisions @@ -58,9 +72,10 @@ Constructing these internal values grants no authority or provider qualification ## Risk and review routing -- Risk class: L1 +- Risk class: L0 - Required reviewers: architecture, security, QA/test_delta, documentation, CI integrity -- Human review focus: exact identities and limited contract-only scope. +- Human review focus: authorization, immutable lineage, custody, quota/cleanup, + atomic handoff, recovery, client truthfulness and complete end-to-end proof. ## Evidence @@ -87,5 +102,6 @@ Constructing these internal values grants no authority or provider qualification - Current-source reconciliation: rebased onto 94334ccf4 (PR #707); preserved issuer profile roadmap changes and schema head 0068. Submission owner contracts unchanged. -- Next usable boundary: durable operation schema and owner commands. +- Next implementation stage: durable operation schema and owner commands in + the same PR, followed by streaming, PRE, handoff/finalization and clients. - Remaining risks: A01–A35 integration and C01–C07 qualification. diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 61bb301c2..b7a58457f 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -932,6 +932,9 @@ "backend/app/modules/authorization/domain/project_catalogue.py", "backend/app/modules/authorization/project_catalogue.py", }) +SUBMISSION_INTAKE_TARGETS = frozenset({ + "backend/app/modules/artifacts/api/submission_intake.py", +}) FORGE_PROOF_FACTS_TARGETS = frozenset({ "backend/app/adapters/github/app_facts.py", "backend/app/interfaces/forge_facts.py", @@ -1221,6 +1224,7 @@ def _validate_additive_partition_transition( | PILOT_02C_BULK_TRANSITION_TARGETS | PROJECT_CATALOGUE_TARGETS | FORGE_PROOF_FACTS_TARGETS + | SUBMISSION_INTAKE_TARGETS ) expected_additions = (approved_additions & additions) - set(trusted_targets) if POL_03A_DECLARATIVE_MODEL_TARGET in additions: diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index f4509e269..2d4ba4308 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2757,3 +2757,14 @@ def test_art_operator_ownership_accepts_only_exact_new_modules(): wrong_group["authority_digest"] = ownership._digest(authority) with pytest.raises(ownership.BehaviorOwnershipError, match="untrusted_partition_change"): ownership._validate_additive_partition_transition(wrong_group, trusted) + + +def test_submission_intake_partition_addition_is_exact_and_retains_existing_targets() -> None: + retained = "backend/app/core/config.py" + target = "backend/app/modules/artifacts/api/submission_intake.py" + assert ownership.SUBMISSION_INTAKE_TARGETS == {target} + trusted = _partition([retained]) + ownership._validate_additive_partition_transition(_partition(sorted([retained, target])), trusted) + for targets in ([target], [retained, target, "backend/app/modules/artifacts/api/intake_override.py"]): + with pytest.raises(ownership.BehaviorOwnershipError, match="untrusted_partition_change"): + ownership._validate_additive_partition_transition(_partition(sorted(targets)), trusted) From cd74a7a48bf5b19222297cd8e9129d0f54e09d44 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 17:46:43 +0100 Subject: [PATCH 006/513] Persist fenced foreground submission intake custody --- .commitrail/INDEX.md | 2 +- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 4 +- .../WS-SUBMIT-001/WS-SUBMIT-001-02.md | 88 +++++ backend/alembic/env.py | 3 +- .../0069_submission_intake_custody.py | 252 +++++++++++++++ backend/app/db/models.py | 1 + .../app/modules/artifacts/intake/__init__.py | 1 + .../app/modules/artifacts/intake/models.py | 79 +++++ .../modules/artifacts/intake/repository.py | 166 ++++++++++ .../app/modules/tasks/api/intake_custody.py | 32 ++ backend/app/modules/tasks/intake_custody.py | 56 ++++ backend/app/modules/tasks/models.py | 7 + backend/scripts/test_lane_catalogue.py | 1 + .../test_submission_intake_custody.py | 305 ++++++++++++++++++ backend/tests/conftest.py | 3 +- .../submission_dispatch/test_migration.py | 1 + backend/tests/test_alembic.py | 1 + backend/tests/test_ci_lane_catalogue.py | 4 +- docs/roadmap_status.md | 6 +- 19 files changed, 1004 insertions(+), 8 deletions(-) create mode 100644 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-02.md create mode 100644 backend/alembic/versions/0069_submission_intake_custody.py create mode 100644 backend/app/modules/artifacts/intake/__init__.py create mode 100644 backend/app/modules/artifacts/intake/models.py create mode 100644 backend/app/modules/artifacts/intake/repository.py create mode 100644 backend/app/modules/tasks/api/intake_custody.py create mode 100644 backend/app/modules/tasks/intake_custody.py create mode 100644 backend/tests/artifacts/test_submission_intake_custody.py diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index 190f7d898..bacb75977 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | One-request submission contracts, then durable operations, streaming custody, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | One-request command/source contracts and hidden foreground custody; next physical capacity, streaming custody, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index eb5c7602a..a674e5291 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -10,7 +10,9 @@ authorize merge or production deployment. ## Current boundary [WS-SUBMIT-001-01](WS-SUBMIT-001-01.md) establishes exact command/source value -contracts. Database ownership and all new orchestration remain to implement. +contracts. [WS-SUBMIT-001-02](WS-SUBMIT-001-02.md) adds hidden pre-handoff +database custody and TASK/source/lease guards. Physical capacity, provider I/O, +accepted authority and orchestration remain to implement. The existing public flow stays active until coordinated cutover. ## Delivery sequence diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-02.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-02.md new file mode 100644 index 000000000..e9b75720e --- /dev/null +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-02.md @@ -0,0 +1,88 @@ +# WS-SUBMIT-001-02 — Durable foreground intake custody + +- Initiative: WS-SUBMIT-001 +- Durable disposition: Planned +- Intended merge outcome: persist fenced pre-handoff intake with one matching task owner, immutable command/source identity and PostgreSQL failure/concurrency proof. + +## Intent + +Make an original upload accountable before provider writes begin. A process-local +prepared ZIP cannot provide ownership after API failure. This change supplies +durable foreground custody for subsequent bounded streaming and T1–T4 composition. + +## Current behavior + +The prior change defines immutable value contracts but creates no durable intake. +ART stores prepared admissions only after PRE; TASK has no early active-operation +pointer. Schema head is 0068 on main 94334ccf4. This change is stacked on PR #708; +it does not merge or modify that PR's branch. + +## Bounded change + +### Allowed + +- ART intake model/repository and typed value additions under existing owners. +- TASK active-operation pointer and narrow owner methods; existing lifecycle + guards must reject inconsistent assignment or task transitions while guarded. +- Migration after 0068: constraints, composite foreign keys, immutable identity, + fenced forward transitions and matching task/operation custody. +- Database metadata registration, canonical migration/reset fixtures, semantic + test selection and targeted real PostgreSQL tests required by this schema. +- Initiative/index/roadmap statements of exactly delivered and remaining behavior. + +### Not allowed + +- Public endpoint/client cutover, provider writes, background PRE or new authority. +- Claims of physical quota enforcement, storage cleanup or runtime qualification. +- Accepted handoff before the exact AUTH/CHECKERS/outbox composition exists. +- Historical artifact rewrites, deletion, changed revision rules or deployment defaults. + +## Design and decisions + +The initial hidden persistence boundary permits receiving, pre_checking and +pre-handoff terminal outcomes only. Finalization_pending/finalized remain denied +until the later accepted-authority and outbox transaction adds their full guards. +This is staged implementation of one lifecycle, not an alternative submission API. + +Actor/key uniqueness and a partial unique task index fence concurrent operations. +The task pointer is composite-bound to its own operation and checked at commit. +Command, actual TASK locked-context snapshot, namespace and object key are +immutable. EOF raw identity precedes sealed generation; completed source facts +cannot change. Foreground owners use a generation and database-time lease. +Expired or terminal ownership cannot publish new source facts. Recovery may fence +and abandon expired pre-handoff work, never accept it. Persistence primitives are +internal; they grant no upload/read capability and do not replace AUTH. + +## Acceptance criteria + +- [ ] Current schema upgrades without rewriting retained data. +- [ ] Exact actor/key and one-active-task constraints hold across independent transactions. +- [ ] Task, assignment, actor/link, project and namespace substitutions fail in SQL. +- [ ] Task pointer and operation state commit together; rollback leaves neither. +- [ ] Command/context/source identities cannot mutate after binding. +- [ ] EOF precedes exact source sealing; stale/expired owners and terminal revival fail. +- [ ] Existing affected task/submission behavior remains valid with null intake pointers. +- [ ] Focused PostgreSQL, migration/model parity, lint and impact-routed reviews pass. + +## Risk and review routing + +- Risk class: L0 +- Required reviewers: architecture, security, QA/test_delta, CI integrity, documentation +- Human review focus: custody locks/fences, deferred closure and retained-data preservation. + +## Evidence + +| Claim | Command or proof | Result | Remaining uncertainty | +|---|---|---|---| +| Baseline | Fetch main; inspect PR #708 | Main 94334ccf4, parent PR open and CI running | No merge authority implied | +| Custody | Real PostgreSQL owner/direct-SQL/concurrency tests | Not executed | No integrated T1–T5 proof yet | + +## Review findings + +None recorded yet. + +## Reconciliation + +- Current-source reconciliation: parent identity contracts include ART primary/fingerprint binding. +- Next usable boundary: streaming storage reservation/receipt and complete acceptance authority. +- Remaining risks: T4/T5, physical storage, runtime and public cutover remain unimplemented. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 45a704286..9a9519d84 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0068_issuer_profile_email" +_CURRENT_HEAD_REVISION = "0069_submission_intake_custody" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -122,6 +122,7 @@ def do_run_migrations(connection: Connection) -> None: ("0065_claim_starts_work",), ("0066_guide_check_specification",), ("0067_canonical_json_restore_path",), + ("0068_issuer_profile_email",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0069_submission_intake_custody.py b/backend/alembic/versions/0069_submission_intake_custody.py new file mode 100644 index 000000000..e2e4ed73c --- /dev/null +++ b/backend/alembic/versions/0069_submission_intake_custody.py @@ -0,0 +1,252 @@ +"""Persist non-resumable foreground intake before the accepted handoff cutover.""" + +from alembic import op +import sqlalchemy as sa +from scripts.schema_baseline_sql import split_sql_statements + +revision = "0069_submission_intake_custody" +down_revision = "0068_issuer_profile_email" +branch_labels = None +depends_on = None + +TABLE_SQL = r""" + +CREATE TABLE public.submission_intake_operations ( + id UUID NOT NULL, + project_id UUID NOT NULL, + task_id UUID NOT NULL, + assignment_id UUID NOT NULL, + actor_profile_id UUID NOT NULL, + identity_link_id UUID NOT NULL, + idempotency_key UUID NOT NULL, + command_metadata JSONB NOT NULL, + metadata_sha256 VARCHAR(71) NOT NULL, + locked_task_context JSONB NOT NULL, + locked_context_sha256 VARCHAR(71) NOT NULL, + eligible_task_status VARCHAR(30) NOT NULL, + namespace_id VARCHAR(20) NOT NULL, + namespace_fingerprint VARCHAR(71) NOT NULL, + provider_profile VARCHAR(100) NOT NULL, + object_ref VARCHAR(1024) NOT NULL, + maximum_raw_bytes BIGINT NOT NULL, + state VARCHAR(30) NOT NULL, + lease_id UUID NOT NULL, + lease_generation BIGINT NOT NULL, + lease_expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + upload_deadline_at TIMESTAMP WITH TIME ZONE NOT NULL, + pre_deadline_at TIMESTAMP WITH TIME ZONE, + raw_sha256 VARCHAR(71), + raw_byte_count BIGINT, + eof_at TIMESTAMP WITH TIME ZONE, + provider_generation VARCHAR, + sealed_upload_fence BIGINT, + sealed_at TIMESTAMP WITH TIME ZONE, + terminal_at TIMESTAMP WITH TIME ZONE, + failure_code VARCHAR(100), + created_at TIMESTAMP WITH TIME ZONE DEFAULT clock_timestamp() NOT NULL, + CONSTRAINT pk_submission_intake_operations PRIMARY KEY (id), + CONSTRAINT ck_submission_intake_operations_id_uuid7 CHECK ((get_byte(uuid_send(id),6)>>4)=7 and (get_byte(uuid_send(id),8)&192)=128), + CONSTRAINT uq_submission_intake_task_identity UNIQUE (id, task_id), + CONSTRAINT uq_submission_intake_actor_key UNIQUE (actor_profile_id, idempotency_key), + CONSTRAINT uq_submission_intake_source_key UNIQUE (namespace_id, namespace_fingerprint, object_ref), + CONSTRAINT fk_submission_intake_task FOREIGN KEY(task_id, project_id) REFERENCES public.workstream_tasks (id, project_id) DEFERRABLE INITIALLY DEFERRED, + CONSTRAINT fk_submission_intake_assignment FOREIGN KEY(assignment_id, task_id, actor_profile_id) REFERENCES public.task_assignments (id, task_id, contributor_id) DEFERRABLE INITIALLY DEFERRED, + CONSTRAINT fk_submission_intake_identity FOREIGN KEY(identity_link_id, actor_profile_id) REFERENCES public.actor_identity_links (id, actor_profile_id) DEFERRABLE INITIALLY DEFERRED, + CONSTRAINT fk_submission_intake_namespace FOREIGN KEY(namespace_id, namespace_fingerprint) REFERENCES public.artifact_storage_namespaces (id, namespace_fingerprint), + CONSTRAINT ck_submission_intake_operations_foreground_state CHECK (state in ('receiving','pre_checking','rejected','failed','abandoned','cancelled')), + CONSTRAINT ck_submission_intake_operations_eligible_status CHECK (eligible_task_status in ('in_progress','needs_revision')), + CONSTRAINT ck_submission_intake_operations_identity_digests CHECK (metadata_sha256 ~ '^sha256:[0-9a-f]{64}$' and locked_context_sha256 ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_submission_intake_operations_command_shape CHECK (jsonb_typeof(command_metadata)='object' and jsonb_typeof(locked_task_context)='object'), + CONSTRAINT ck_submission_intake_operations_source_key CHECK (object_ref='submission-source/v1/'||id::text||'/bundle.zip'), + CONSTRAINT ck_submission_intake_operations_raw_limit CHECK (maximum_raw_bytes between 1 and 524288000), + CONSTRAINT ck_submission_intake_operations_lease_bounds CHECK (lease_generation>0 and lease_expires_at<=coalesce(pre_deadline_at,upload_deadline_at) and upload_deadline_at>created_at), + CONSTRAINT ck_submission_intake_operations_eof_identity CHECK ((raw_sha256 is null and raw_byte_count is null and eof_at is null) or (raw_sha256 is not null and raw_sha256 ~ '^sha256:[0-9a-f]{64}$' and raw_byte_count is not null and raw_byte_count between 1 and maximum_raw_bytes and eof_at is not null)), + CONSTRAINT ck_submission_intake_operations_sealed_identity CHECK ((provider_generation is null and sealed_upload_fence is null and sealed_at is null and pre_deadline_at is null) or (provider_generation is not null and sealed_upload_fence is not null and sealed_upload_fence>0 and length(provider_generation)>0 and raw_sha256 is not null and sealed_at is not null and sealed_at>=eof_at and pre_deadline_at is not null and pre_deadline_at>sealed_at and (provider_profile<>'aws-s3-v1' or provider_generation<>'null'))), + CONSTRAINT ck_submission_intake_operations_pre_requires_source CHECK (state<>'pre_checking' or sealed_at is not null), + CONSTRAINT ck_submission_intake_operations_terminal_shape CHECK ((state in ('receiving','pre_checking') and terminal_at is null and failure_code is null) or (state in ('rejected','failed','abandoned','cancelled') and terminal_at is not null and failure_code is not null)) +) + +; +CREATE INDEX ix_submission_intake_expiry ON public.submission_intake_operations (lease_expires_at, id) WHERE state in ('receiving','pre_checking'); +CREATE UNIQUE INDEX uq_submission_intake_active_task ON public.submission_intake_operations (task_id) WHERE state in ('receiving','pre_checking') +""" + +GUARDS = r""" +CREATE FUNCTION public.submission_intake_task_snapshot(t public.workstream_tasks) +RETURNS jsonb LANGUAGE sql IMMUTABLE STRICT +SET search_path=pg_catalog,public,pg_temp AS $$ + SELECT jsonb_object_agg(key,value) FROM jsonb_each(to_jsonb(t)) + WHERE starts_with(key,'locked_') + OR key IN ('id','project_id','assigned_to','acceptance_criteria') +$$; + +CREATE FUNCTION public.guard_submission_intake_mutation() +RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ +DECLARE + m jsonb; + canonical text; +BEGIN + IF TG_OP='DELETE' THEN + RAISE EXCEPTION 'submission intake custody cannot be deleted' USING ERRCODE='23514'; + END IF; + IF TG_OP='INSERT' THEN + NEW.created_at := clock_timestamp(); + IF NEW.state<>'receiving' OR NEW.lease_generation<>1 + OR NEW.raw_sha256 IS NOT NULL OR NEW.provider_generation IS NOT NULL + OR NEW.lease_expires_at<=NEW.created_at THEN + RAISE EXCEPTION 'invalid initial submission intake' USING ERRCODE='23514'; + END IF; + m:=NEW.command_metadata; + IF NOT (m ?& ARRAY['task_id','assignment_id','predecessor_submission_id','summary', + 'contributor_attestation','revision_preparation_id','revision_preparation_sha256']) + OR m - ARRAY['task_id','assignment_id','predecessor_submission_id','summary', + 'contributor_attestation','revision_preparation_id','revision_preparation_sha256'] <> '{}'::jsonb + OR m->>'task_id' IS DISTINCT FROM NEW.task_id::text + OR m->>'assignment_id' IS DISTINCT FROM NEW.assignment_id::text + OR jsonb_typeof(m->'summary') IS DISTINCT FROM 'string' + OR jsonb_typeof(m->'contributor_attestation') IS DISTINCT FROM 'string' + OR octet_length(m->>'summary')>65536 OR octet_length(m->>'contributor_attestation')>65536 + OR (m->>'summary') COLLATE "C" ~ '[^ -~]' + OR (m->>'contributor_attestation') COLLATE "C" ~ '[^ -~]' + OR btrim(m->>'summary') IS DISTINCT FROM m->>'summary' + OR btrim(m->>'contributor_attestation') IS DISTINCT FROM m->>'contributor_attestation' + OR ((m->>'revision_preparation_id' IS NULL)<>(m->>'revision_preparation_sha256' IS NULL)) + OR (m->>'predecessor_submission_id' IS NULL AND m->>'revision_preparation_id' IS NOT NULL) + OR (m->>'revision_preparation_sha256' IS NOT NULL AND + m->>'revision_preparation_sha256' !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'invalid intake metadata' USING ERRCODE='23514'; + END IF; + canonical:=public.project_guide_projection_canonical_json( + m || jsonb_build_object('schema_version','workstream.submission_intake_metadata.v1')); + IF NEW.metadata_sha256 IS DISTINCT FROM 'sha256:'||encode(sha256(convert_to(canonical,'UTF8')),'hex') + OR NEW.locked_context_sha256 IS DISTINCT FROM 'sha256:'||encode(sha256(convert_to( + public.project_guide_projection_canonical_json(NEW.locked_task_context),'UTF8')),'hex') THEN + RAISE EXCEPTION 'intake identity digest mismatch' USING ERRCODE='23514'; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.artifact_storage_namespaces n + WHERE n.id=NEW.namespace_id AND n.namespace_fingerprint=NEW.namespace_fingerprint + AND n.provider_profile=NEW.provider_profile) THEN + RAISE EXCEPTION 'intake namespace mismatch' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF (to_jsonb(NEW)-ARRAY['state','lease_generation','lease_expires_at','raw_sha256', + 'raw_byte_count','eof_at','provider_generation','sealed_upload_fence','sealed_at','pre_deadline_at', + 'terminal_at','failure_code']) IS DISTINCT FROM + (to_jsonb(OLD)-ARRAY['state','lease_generation','lease_expires_at','raw_sha256', + 'raw_byte_count','eof_at','provider_generation','sealed_upload_fence','sealed_at','pre_deadline_at', + 'terminal_at','failure_code']) THEN + RAISE EXCEPTION 'intake command and source location are immutable' USING ERRCODE='23514'; + END IF; + IF OLD.state NOT IN ('receiving','pre_checking') THEN + IF to_jsonb(NEW) IS DISTINCT FROM to_jsonb(OLD) THEN + RAISE EXCEPTION 'terminal intake is immutable' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.raw_sha256 IS NOT NULL AND ROW(NEW.raw_sha256,NEW.raw_byte_count,NEW.eof_at) + IS DISTINCT FROM ROW(OLD.raw_sha256,OLD.raw_byte_count,OLD.eof_at) THEN + RAISE EXCEPTION 'intake EOF identity is immutable' USING ERRCODE='23514'; + END IF; + IF OLD.provider_generation IS NOT NULL AND + ROW(NEW.provider_generation,NEW.sealed_upload_fence,NEW.sealed_at,NEW.pre_deadline_at) IS DISTINCT FROM + ROW(OLD.provider_generation,OLD.sealed_upload_fence,OLD.sealed_at,OLD.pre_deadline_at) THEN + RAISE EXCEPTION 'intake sealed source is immutable' USING ERRCODE='23514'; + END IF; + IF NEW.state IN ('rejected','failed','abandoned','cancelled') THEN + IF NEW.lease_generation<>OLD.lease_generation+1 + OR (NEW.state='rejected' AND OLD.state<>'pre_checking') + OR ROW(NEW.raw_sha256,NEW.raw_byte_count,NEW.eof_at,NEW.provider_generation,NEW.sealed_upload_fence, + NEW.sealed_at,NEW.pre_deadline_at,NEW.lease_expires_at) IS DISTINCT FROM + ROW(OLD.raw_sha256,OLD.raw_byte_count,OLD.eof_at,OLD.provider_generation,OLD.sealed_upload_fence, + OLD.sealed_at,OLD.pre_deadline_at,OLD.lease_expires_at) THEN + RAISE EXCEPTION 'invalid intake terminal fence' USING ERRCODE='23514'; + END IF; + IF OLD.lease_expires_at<=clock_timestamp() AND NEW.state<>'abandoned' THEN + RAISE EXCEPTION 'expired intake requires abandonment' USING ERRCODE='23514'; + END IF; + IF NEW.state='abandoned' AND OLD.lease_expires_at>clock_timestamp() THEN + RAISE EXCEPTION 'live intake cannot be abandoned' USING ERRCODE='23514'; + END IF; + NEW.terminal_at:=clock_timestamp(); + RETURN NEW; + END IF; + IF OLD.lease_expires_at<=clock_timestamp() OR NEW.lease_generation<>OLD.lease_generation + OR (OLD.state='pre_checking' AND NEW.state<>'pre_checking') THEN + RAISE EXCEPTION 'stale intake foreground owner' USING ERRCODE='23514'; + END IF; + IF OLD.raw_sha256 IS NULL AND NEW.raw_sha256 IS NOT NULL THEN + NEW.eof_at:=clock_timestamp(); + END IF; + IF OLD.provider_generation IS NULL AND NEW.provider_generation IS NOT NULL THEN + IF OLD.raw_sha256 IS NULL OR NEW.state<>'pre_checking' THEN + RAISE EXCEPTION 'source sealing requires recorded EOF' USING ERRCODE='23514'; + END IF; + NEW.sealed_at:=clock_timestamp(); + NEW.sealed_upload_fence:=OLD.lease_generation; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER submission_intake_mutation +BEFORE INSERT OR UPDATE OR DELETE ON public.submission_intake_operations +FOR EACH ROW EXECUTE FUNCTION public.guard_submission_intake_mutation(); + +CREATE FUNCTION public.check_submission_intake_custody() +RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ +DECLARE + task_key uuid; + t public.workstream_tasks%ROWTYPE; + o public.submission_intake_operations%ROWTYPE; +BEGIN + IF TG_TABLE_NAME='workstream_tasks' THEN + task_key:=coalesce(NEW.id,OLD.id); + ELSE + task_key:=coalesce(NEW.task_id,OLD.task_id); + END IF; + SELECT * INTO t FROM public.workstream_tasks WHERE id=task_key FOR UPDATE; + SELECT * INTO o FROM public.submission_intake_operations + WHERE task_id=task_key AND state IN ('receiving','pre_checking'); + IF o.id IS NULL THEN + IF t.active_submission_operation_id IS NOT NULL THEN + RAISE EXCEPTION 'intake pointer has no active owner' USING ERRCODE='23514'; + END IF; + RETURN NULL; + END IF; + IF t.id IS NULL OR t.active_submission_operation_id IS DISTINCT FROM o.id + OR t.status IS DISTINCT FROM o.eligible_task_status + OR t.assigned_to IS DISTINCT FROM o.actor_profile_id + OR public.submission_intake_task_snapshot(t) IS DISTINCT FROM o.locked_task_context + OR NOT EXISTS (SELECT 1 FROM public.task_assignments a + WHERE a.id=o.assignment_id AND a.task_id=o.task_id AND a.project_id=o.project_id + AND a.contributor_id=o.actor_profile_id AND a.status='active') THEN + RAISE EXCEPTION 'intake task custody mismatch' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END $$; +CREATE CONSTRAINT TRIGGER submission_intake_owner_closure +AFTER INSERT OR UPDATE OR DELETE ON public.submission_intake_operations +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_intake_custody(); +CREATE CONSTRAINT TRIGGER task_submission_intake_closure +AFTER INSERT OR UPDATE OR DELETE ON public.workstream_tasks +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_intake_custody(); +CREATE CONSTRAINT TRIGGER assignment_submission_intake_closure +AFTER INSERT OR UPDATE OR DELETE ON public.task_assignments +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_intake_custody(); +""" + + +def upgrade() -> None: + """Add closed foreground custody without touching existing artifact bytes or rows.""" + for statement in split_sql_statements(TABLE_SQL): + op.execute(statement) + op.add_column("workstream_tasks", sa.Column("active_submission_operation_id", sa.Uuid(), nullable=True), schema="public") + op.create_foreign_key("fk_task_active_submission_intake", "workstream_tasks", + "submission_intake_operations", ["active_submission_operation_id", "id"], + ["id", "task_id"], source_schema="public", referent_schema="public", deferrable=True, initially="DEFERRED") + for statement in split_sql_statements(GUARDS): + op.execute(statement) + + +def downgrade() -> None: + """Retain custody and tombstones; restore only into a fresh database.""" + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/db/models.py b/backend/app/db/models.py index e2bb7a027..64408d098 100644 --- a/backend/app/db/models.py +++ b/backend/app/db/models.py @@ -7,6 +7,7 @@ LegacyWorkflowEligibility, ) from app.modules.api_controls.models import ApiRateControlCounter # noqa: F401 +from app.modules.artifacts.intake.models import SubmissionIntakeOperation # noqa: F401 from app.modules.artifacts.models import ( # noqa: F401 ArtifactBinding, ArtifactContent, diff --git a/backend/app/modules/artifacts/intake/__init__.py b/backend/app/modules/artifacts/intake/__init__.py new file mode 100644 index 000000000..b33c5c8cf --- /dev/null +++ b/backend/app/modules/artifacts/intake/__init__.py @@ -0,0 +1 @@ +"""Private ART foreground intake custody.""" diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py new file mode 100644 index 000000000..4e5642f65 --- /dev/null +++ b/backend/app/modules/artifacts/intake/models.py @@ -0,0 +1,79 @@ +"""ART-owned durable foreground custody before submission acceptance.""" + +from datetime import datetime + +from sqlalchemy import ( + BigInteger, CheckConstraint, DateTime, ForeignKeyConstraint, Index, + String, UniqueConstraint, Uuid, text, +) +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.sql import func + +from app.db.base import Base + + +class SubmissionIntakeOperation(Base): + """One immutable command/source with a fenced, non-resumable foreground owner. + + Accepted states are deliberately unavailable until the accepted-authority + and outbox transaction is installed. This table grants no provider capability. + """ + + __tablename__ = "submission_intake_operations" + __table_args__ = ( + CheckConstraint("(get_byte(uuid_send(id),6)>>4)=7 and (get_byte(uuid_send(id),8)&192)=128", name="id_uuid7"), + UniqueConstraint("id", "task_id", name="uq_submission_intake_task_identity"), + UniqueConstraint("actor_profile_id", "idempotency_key", name="uq_submission_intake_actor_key"), + UniqueConstraint("namespace_id", "namespace_fingerprint", "object_ref", name="uq_submission_intake_source_key"), + ForeignKeyConstraint(["task_id", "project_id"], ["workstream_tasks.id", "workstream_tasks.project_id"], name="fk_submission_intake_task", deferrable=True, initially="DEFERRED"), + ForeignKeyConstraint(["assignment_id", "task_id", "actor_profile_id"], ["task_assignments.id", "task_assignments.task_id", "task_assignments.contributor_id"], name="fk_submission_intake_assignment", deferrable=True, initially="DEFERRED"), + ForeignKeyConstraint(["identity_link_id", "actor_profile_id"], ["actor_identity_links.id", "actor_identity_links.actor_profile_id"], name="fk_submission_intake_identity", deferrable=True, initially="DEFERRED"), + ForeignKeyConstraint(["namespace_id", "namespace_fingerprint"], ["artifact_storage_namespaces.id", "artifact_storage_namespaces.namespace_fingerprint"], name="fk_submission_intake_namespace"), + CheckConstraint("state in ('receiving','pre_checking','rejected','failed','abandoned','cancelled')", name="foreground_state"), + CheckConstraint("eligible_task_status in ('in_progress','needs_revision')", name="eligible_status"), + CheckConstraint("metadata_sha256 ~ '^sha256:[0-9a-f]{64}$' and locked_context_sha256 ~ '^sha256:[0-9a-f]{64}$'", name="identity_digests"), + CheckConstraint("jsonb_typeof(command_metadata)='object' and jsonb_typeof(locked_task_context)='object'", name="command_shape"), + CheckConstraint("object_ref='submission-source/v1/'||id::text||'/bundle.zip'", name="source_key"), + CheckConstraint("maximum_raw_bytes between 1 and 524288000", name="raw_limit"), + CheckConstraint("lease_generation>0 and lease_expires_at<=coalesce(pre_deadline_at,upload_deadline_at) and upload_deadline_at>created_at", name="lease_bounds"), + CheckConstraint("(raw_sha256 is null and raw_byte_count is null and eof_at is null) or (raw_sha256 is not null and raw_sha256 ~ '^sha256:[0-9a-f]{64}$' and raw_byte_count is not null and raw_byte_count between 1 and maximum_raw_bytes and eof_at is not null)", name="eof_identity"), + CheckConstraint("(provider_generation is null and sealed_upload_fence is null and sealed_at is null and pre_deadline_at is null) or (provider_generation is not null and sealed_upload_fence is not null and sealed_upload_fence>0 and length(provider_generation)>0 and raw_sha256 is not null and sealed_at is not null and sealed_at>=eof_at and pre_deadline_at is not null and pre_deadline_at>sealed_at and (provider_profile<>'aws-s3-v1' or provider_generation<>'null'))", name="sealed_identity"), + CheckConstraint("state<>'pre_checking' or sealed_at is not null", name="pre_requires_source"), + CheckConstraint("(state in ('receiving','pre_checking') and terminal_at is null and failure_code is null) or (state in ('rejected','failed','abandoned','cancelled') and terminal_at is not null and failure_code is not null)", name="terminal_shape"), + Index("uq_submission_intake_active_task", "task_id", unique=True, postgresql_where=text("state in ('receiving','pre_checking')")), + Index("ix_submission_intake_expiry", "lease_expires_at", "id", postgresql_where=text("state in ('receiving','pre_checking')")), + ) + + id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True) + project_id: Mapped[str] = mapped_column(Uuid(as_uuid=False)) + task_id: Mapped[str] = mapped_column(Uuid(as_uuid=False)) + assignment_id: Mapped[str] = mapped_column(Uuid(as_uuid=False)) + actor_profile_id: Mapped[str] = mapped_column(Uuid(as_uuid=False)) + identity_link_id: Mapped[str] = mapped_column(Uuid(as_uuid=False)) + idempotency_key: Mapped[str] = mapped_column(Uuid(as_uuid=False)) + command_metadata: Mapped[dict] = mapped_column(JSONB) + metadata_sha256: Mapped[str] = mapped_column(String(71)) + locked_task_context: Mapped[dict] = mapped_column(JSONB) + locked_context_sha256: Mapped[str] = mapped_column(String(71)) + eligible_task_status: Mapped[str] = mapped_column(String(30)) + namespace_id: Mapped[str] = mapped_column(String(20)) + namespace_fingerprint: Mapped[str] = mapped_column(String(71)) + provider_profile: Mapped[str] = mapped_column(String(100)) + object_ref: Mapped[str] = mapped_column(String(1024)) + maximum_raw_bytes: Mapped[int] = mapped_column(BigInteger) + state: Mapped[str] = mapped_column(String(30)) + lease_id: Mapped[str] = mapped_column(Uuid(as_uuid=False)) + lease_generation: Mapped[int] = mapped_column(BigInteger) + lease_expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + upload_deadline_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + pre_deadline_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + raw_sha256: Mapped[str | None] = mapped_column(String(71)) + raw_byte_count: Mapped[int | None] = mapped_column(BigInteger) + eof_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + provider_generation: Mapped[str | None] = mapped_column(String) + sealed_upload_fence: Mapped[int | None] = mapped_column(BigInteger) + sealed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + terminal_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + failure_code: Mapped[str | None] = mapped_column(String(100)) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py new file mode 100644 index 000000000..e5c258400 --- /dev/null +++ b/backend/app/modules/artifacts/intake/repository.py @@ -0,0 +1,166 @@ +"""Private ART persistence primitives; no storage, acceptance or AUTH capability. + +The future foreground composition must authorize and reserve physical capacity +before allowing storage writes. These flush-only operations leave root commits +and replay authorization to that composition. Expired foreground work is never +resumed by another request or by a background PRE worker. +""" + +from datetime import datetime +import json +import re +from uuid import UUID + +from sqlalchemy import select, func +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.hashing import canonical_json_hash +from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, SubmissionIntakeMetadata, SubmissionSourceLocation, +) +from app.modules.artifacts.intake.models import SubmissionIntakeOperation +from app.modules.artifacts.models import ArtifactStorageNamespace +from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort +from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest + + +class IntakeCustodyConflict(RuntimeError): + """A private owner conflict, never a quality verdict or permission grant.""" + + +class SubmissionIntakeRepository: + """Persist exact source facts under TASK-first locks and a live owner fence.""" + + def __init__(self, session: AsyncSession, tasks: IntakeTaskCustodyPort) -> None: + self._session = session + self._tasks = tasks + + def _require_transaction(self) -> None: + if not self._session.in_transaction() or self._session.in_nested_transaction(): + raise IntakeCustodyConflict("intake_requires_root_transaction") + + async def reserve( + self, *, metadata: SubmissionIntakeMetadata, actor_id: UUID, identity_link_id: UUID, + idempotency_key: UUID, maximum_raw_bytes: int, + upload_deadline_at: datetime, lease_expires_at: datetime, + ) -> SubmissionIntakeOperation: + """Reserve metadata custody only; callers must still perform full T1 admission.""" + self._require_transaction() + metadata = SubmissionIntakeMetadata.model_validate(metadata) + operation_id = new_record_id() + snapshot = await self._tasks.claim(TaskSubmissionContextRequest( + metadata.task_id, metadata.assignment_id, actor_id, metadata.predecessor_submission_id, + ), operation_id) + namespace = await self._session.get(ArtifactStorageNamespace, "primary") + if namespace is None: + raise IntakeCustodyConflict("intake_namespace_unavailable") + location = SubmissionSourceLocation( + operation_id=operation_id, namespace_id=namespace.id, + namespace_fingerprint=namespace.namespace_fingerprint, + provider_profile=namespace.provider_profile, + ) + context = json.loads(snapshot.context_json) + row = SubmissionIntakeOperation( + id=str(operation_id), project_id=str(snapshot.project_id), + task_id=str(metadata.task_id), assignment_id=str(metadata.assignment_id), + actor_profile_id=str(actor_id), identity_link_id=str(identity_link_id), + idempotency_key=str(idempotency_key), command_metadata=metadata.model_dump(mode="json"), + metadata_sha256=metadata.metadata_sha256(), locked_task_context=context, + locked_context_sha256=canonical_json_hash(context), eligible_task_status=snapshot.eligible_status, + namespace_id=location.namespace_id, namespace_fingerprint=location.namespace_fingerprint, + provider_profile=location.provider_profile, object_ref=location.object_ref, + maximum_raw_bytes=maximum_raw_bytes, state="receiving", + lease_id=str(new_record_id()), lease_generation=1, + lease_expires_at=lease_expires_at, upload_deadline_at=upload_deadline_at, + ) + self._session.add(row) + await self._session.flush() + await self._session.refresh(row) + return row + + async def _lock(self, operation_id: UUID) -> SubmissionIntakeOperation: + self._require_transaction() + task_id = await self._session.scalar(select(SubmissionIntakeOperation.task_id).where( + SubmissionIntakeOperation.id == str(operation_id), + )) + if task_id is None: + raise IntakeCustodyConflict("intake_unavailable") + await self._tasks.lock(UUID(task_id)) + row = await self._session.scalar(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.id == str(operation_id), + ).with_for_update().execution_options(populate_existing=True)) + if row is None: + raise IntakeCustodyConflict("intake_unavailable") + return row + + async def _owned(self, operation_id: UUID, lease_id: UUID, generation: int) -> SubmissionIntakeOperation: + row = await self._lock(operation_id) + now = await self._session.scalar(select(func.clock_timestamp())) + if (row.state not in {"receiving", "pre_checking"} or row.lease_id != str(lease_id) + or row.lease_generation != generation or row.lease_expires_at <= now): + raise IntakeCustodyConflict("intake_owner_stale") + return row + + async def record_eof(self, operation_id: UUID, lease_id: UUID, generation: int, + *, raw_sha256: str, raw_byte_count: int) -> None: + """Persist ingress identity before the adapter may complete the object.""" + row = await self._owned(operation_id, lease_id, generation) + if row.state != "receiving" or row.raw_sha256 is not None: + raise IntakeCustodyConflict("intake_eof_already_recorded") + row.raw_sha256, row.raw_byte_count = raw_sha256, raw_byte_count + row.eof_at = func.clock_timestamp() + await self._session.flush() + + async def seal(self, operation_id: UUID, lease_id: UUID, generation: int, + *, provider_generation: str, pre_deadline_at: datetime, + lease_expires_at: datetime) -> SealedSubmissionSource: + """Bind the known completed generation; this does not prove provider I/O.""" + row = await self._owned(operation_id, lease_id, generation) + if row.state != "receiving" or row.raw_sha256 is None or row.provider_generation is not None: + raise IntakeCustodyConflict("intake_source_not_sealable") + row.provider_generation, row.pre_deadline_at = provider_generation, pre_deadline_at + row.sealed_at, row.sealed_upload_fence = func.clock_timestamp(), generation + row.state, row.lease_expires_at = "pre_checking", lease_expires_at + await self._session.flush() + await self._session.refresh(row) + return SealedSubmissionSource( + location=SubmissionSourceLocation( + operation_id=operation_id, namespace_id=row.namespace_id, + namespace_fingerprint=row.namespace_fingerprint, provider_profile=row.provider_profile, + ), provider_generation=row.provider_generation, raw_sha256=row.raw_sha256, + raw_byte_count=row.raw_byte_count, sealed_upload_fence=row.sealed_upload_fence, + ) + + async def heartbeat(self, operation_id: UUID, lease_id: UUID, generation: int, + *, lease_expires_at: datetime) -> None: + """Renew within the immutable phase deadline; never revive an expired owner.""" + row = await self._owned(operation_id, lease_id, generation) + row.lease_expires_at = lease_expires_at + await self._session.flush() + + async def terminalize(self, operation_id: UUID, lease_id: UUID, generation: int, + *, state: str, failure_code: str) -> None: + """Fence conclusively ended foreground work and clear only its task guard.""" + if state not in {"failed", "rejected", "cancelled"}: + raise IntakeCustodyConflict("intake_terminal_state_invalid") + row = await self._owned(operation_id, lease_id, generation) + await self._terminal(row, state, failure_code) + + async def abandon_expired(self, operation_id: UUID) -> bool: + """Recovery can end expired foreground custody, never resume or accept it.""" + row = await self._lock(operation_id) + now = await self._session.scalar(select(func.clock_timestamp())) + if row.state not in {"receiving", "pre_checking"} or row.lease_expires_at > now: + return False + await self._terminal(row, "abandoned", "submission_foreground_expired") + return True + + async def _terminal(self, row: SubmissionIntakeOperation, state: str, code: str) -> None: + if re.fullmatch(r"[a-z][a-z0-9_]{0,99}", code) is None: + raise IntakeCustodyConflict("intake_failure_code_invalid") + row.state, row.failure_code = state, code + row.lease_generation += 1 + row.terminal_at = func.clock_timestamp() + await self._session.flush() + await self._tasks.release(UUID(row.task_id), UUID(row.id)) diff --git a/backend/app/modules/tasks/api/intake_custody.py b/backend/app/modules/tasks/api/intake_custody.py new file mode 100644 index 000000000..08f0d4c2e --- /dev/null +++ b/backend/app/modules/tasks/api/intake_custody.py @@ -0,0 +1,32 @@ +"""Narrow TASK participation in a caller-owned intake transaction, not AUTH.""" + +from dataclasses import dataclass +from typing import Protocol +from uuid import UUID + +from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest + + +@dataclass(frozen=True, slots=True) +class IntakeTaskSnapshot: + """Exact TASK context captured while its row and assignment remain locked.""" + + project_id: UUID + eligible_status: str + context_json: str + + +class IntakeTaskCustodyPort(Protocol): + """Maintain the task pointer only; caller must supply authorized owner work.""" + + async def claim(self, request: TaskSubmissionContextRequest, operation_id: UUID) -> IntakeTaskSnapshot: + """Lock canonical submission context and install its unique operation pointer.""" + ... + + async def lock(self, task_id: UUID) -> None: + """Acquire the TASK lock before ART locks the associated operation.""" + ... + + async def release(self, task_id: UUID, operation_id: UUID) -> None: + """Clear only this operation's pointer inside the terminal transaction.""" + ... diff --git a/backend/app/modules/tasks/intake_custody.py b/backend/app/modules/tasks/intake_custody.py new file mode 100644 index 000000000..077e07c43 --- /dev/null +++ b/backend/app/modules/tasks/intake_custody.py @@ -0,0 +1,56 @@ +"""TASK-owned pointer participation using the existing submission context port.""" + +import json +from uuid import UUID + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from app.modules.tasks.api.intake_custody import IntakeTaskSnapshot +from app.modules.tasks.api.submission_context import ( + TaskSubmissionContextPort, TaskSubmissionContextRequest, TaskSubmissionContextUnavailable, +) +from app.modules.tasks.repository import TaskRepository + + +class IntakeTaskCustody: + """Flush-only TASK participant; no new route or authorization capability.""" + + def __init__(self, session: AsyncSession, contexts: TaskSubmissionContextPort) -> None: + self._session = session + self._tasks = TaskRepository(session) + self._contexts = contexts + + async def lock(self, task_id: UUID) -> None: + """Lock TASK first and require a root transaction owned by the caller.""" + if not self._session.in_transaction() or self._session.in_nested_transaction(): + raise TaskSubmissionContextUnavailable("task_submission_context_invalid") + if await self._tasks.get_task(str(task_id), for_update=True) is None: + raise TaskSubmissionContextUnavailable("task_submission_context_invalid") + + async def claim(self, request: TaskSubmissionContextRequest, operation_id: UUID) -> IntakeTaskSnapshot: + """Use canonical eligibility/currentness before installing a new pointer.""" + await self.lock(request.task_id) + task = await self._tasks.get_task(str(request.task_id), for_update=True) + if task.active_submission_operation_id is not None: + raise TaskSubmissionContextUnavailable("task_submission_context_invalid") + context = await self._contexts.lock_submission_context(request) + snapshot = await self._session.scalar(text( + "SELECT public.submission_intake_task_snapshot(t) " + "FROM public.workstream_tasks t WHERE id=:id" + ), {"id": request.task_id}) + task.active_submission_operation_id = str(operation_id) + await self._session.flush() + return IntakeTaskSnapshot( + context.locked_project_context.project_id, context.status, + json.dumps(snapshot, sort_keys=True, separators=(",", ":")), + ) + + async def release(self, task_id: UUID, operation_id: UUID) -> None: + """Never clear a different operation's ownership.""" + await self.lock(task_id) + task = await self._tasks.get_task(str(task_id), for_update=True) + if task.active_submission_operation_id != str(operation_id): + raise TaskSubmissionContextUnavailable("task_submission_context_invalid") + task.active_submission_operation_id = None + await self._session.flush() diff --git a/backend/app/modules/tasks/models.py b/backend/app/modules/tasks/models.py index 39293b6b0..f2d97dcf6 100644 --- a/backend/app/modules/tasks/models.py +++ b/backend/app/modules/tasks/models.py @@ -102,6 +102,12 @@ class WorkstreamTask(Base): __tablename__ = "workstream_tasks" __table_args__ = ( + ForeignKeyConstraint( + ["active_submission_operation_id", "id"], + ["submission_intake_operations.id", "submission_intake_operations.task_id"], + name="fk_task_active_submission_intake", deferrable=True, initially="DEFERRED", + use_alter=True, + ), CheckConstraint("(get_byte(uuid_send(id), 6) >> 4) = 7 and (get_byte(uuid_send(id), 8) & 192) = 128", name="id_uuid7"), CheckConstraint( "status in ('draft','screening','ready','in_progress','submitted','evaluation_pending','review_pending','needs_revision','accepted')", @@ -328,6 +334,7 @@ class WorkstreamTask(Base): deadline_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) created_by: Mapped[str] = mapped_column(String(100), nullable=False) assigned_to: Mapped[str | None] = mapped_column(Uuid(as_uuid=False), index=True) + active_submission_operation_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) # PostgreSQL owns this stamp on every committed change, including raw SQL updates. updated_at: Mapped[datetime] = mapped_column( diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 2d8f1fb57..95d61a84a 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -53,6 +53,7 @@ class TestLane: "tests/reviews/packet/test_storage.py", "tests/artifacts/test_selected_predecessor_rules.py", "tests/artifacts/test_submission_intake_contracts.py", + "tests/artifacts/test_submission_intake_custody.py", "tests/authorization/post_submit/test_atomicity.py", "tests/authorization/post_submit/test_concurrency.py", "tests/authorization/post_submit/test_live_authority.py", diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py new file mode 100644 index 000000000..8295ce213 --- /dev/null +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -0,0 +1,305 @@ +"""Real PostgreSQL proof of pre-handoff custody, not upload or acceptance authority.""" + +import asyncio + +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace +from uuid import UUID + +import pytest +from sqlalchemy import text +from sqlalchemy.exc import DBAPIError +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.adapters.tasks import task_submission_context_port +from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata +from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository +from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable +from app.modules.tasks.intake_custody import IntakeTaskCustody +from tests.selected_policy_fixtures import approved_selected_policy_fixture +from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test +from tests.test_artifact_admission import _context, _namespace, _seed_human_actor, _settings + +SHA = "sha256:" + "a" * 64 + + +def repository(session): + return SubmissionIntakeRepository( + session, IntakeTaskCustody(session, task_submission_context_port(session)), + ) + + +@pytest.fixture +async def intake(tmp_path, isolated_database_env): + engine = create_async_engine(isolated_database_env) + factory = async_sessionmaker(engine, expire_on_commit=False) + try: + plan, _ = await approved_selected_policy_fixture( + factory, _namespace(_settings(tmp_path)), guide_version="v1", + ) + actor = _context() + async with factory.begin() as session: + await _seed_human_actor(session, actor) + task, assignment = new_record_id(), new_record_id() + async with engine.begin() as connection: + await seed_started_task_for_artifact_test(connection, dict( + task=str(task), assignment=str(assignment), + project=str(plan.lineage.project_id), actor=str(actor.actor_profile_id), + )) + yield SimpleNamespace(engine=engine, factory=factory, actor=actor, task=task, assignment=assignment) + finally: + await engine.dispose() + + +async def reserve(intake, session, *, key=None): + now = datetime.now(UTC) + return await repository(session).reserve( + metadata=SubmissionIntakeMetadata(task_id=intake.task, assignment_id=intake.assignment), + actor_id=intake.actor.actor_profile_id, identity_link_id=intake.actor.identity_link_id, + idempotency_key=key or new_record_id(), maximum_raw_bytes=1024, + upload_deadline_at=now + timedelta(minutes=5), + lease_expires_at=now + timedelta(minutes=1), + ) + + +async def test_foreground_eof_seal_terminal_and_stale_fence(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + async with intake.factory.begin() as session: + await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + async with intake.factory.begin() as session: + deadline = datetime.now(UTC) + timedelta(minutes=2) + source = await repository(session).seal( + operation, lease, 1, provider_generation="exact-generation", + pre_deadline_at=deadline, lease_expires_at=deadline, + ) + assert source.raw_byte_count == 100 + assert source.sealed_upload_fence == 1 + async with intake.factory.begin() as session: + await repository(session).terminalize(operation, lease, 1, state="rejected", failure_code="pre_failed") + async with intake.factory() as session: + stored = (await session.execute(text( + "SELECT o.state,o.lease_generation,o.sealed_upload_fence,t.active_submission_operation_id " + "FROM submission_intake_operations o JOIN workstream_tasks t ON t.id=o.task_id WHERE o.id=:id" + ), {"id": operation})).one() + assert tuple(stored) == ("rejected", 2, 1, None) + with pytest.raises(IntakeCustodyConflict, match="intake_owner_stale"): + async with intake.factory.begin() as session: + await repository(session).heartbeat(operation, lease, 1, lease_expires_at=deadline) + + +async def test_reservation_rollback_leaves_no_pointer_or_operation(intake): + async with intake.factory() as session: + await session.begin() + await reserve(intake, session) + await session.rollback() + async with intake.factory() as session: + assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 0 + assert await session.scalar(text( + "SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id" + ), {"id": intake.task}) is None + + +@pytest.mark.parametrize("mutation", [ + "raw_sha256='" + SHA + "',raw_byte_count=NULL,eof_at=clock_timestamp()", + "state='pre_checking'", + "state='finalization_pending'", + "metadata_sha256='sha256:'||repeat('b',64)", + "object_ref='submission-source/v1/other/bundle.zip'", + "lease_generation=2", +]) +async def test_database_rejects_incomplete_or_rebound_custody(intake, mutation): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + with pytest.raises(DBAPIError): + async with intake.factory.begin() as session: + await session.execute(text( + f"UPDATE submission_intake_operations SET {mutation} WHERE id=:id" + ), {"id": UUID(row.id)}) + + +async def test_database_requires_matching_task_pointer_at_commit(intake): + async with intake.factory.begin() as session: + await reserve(intake, session) + with pytest.raises(DBAPIError, match="intake task custody mismatch"): + async with intake.factory.begin() as session: + await session.execute(text( + "UPDATE workstream_tasks SET active_submission_operation_id=NULL WHERE id=:id" + ), {"id": intake.task}) + + +async def test_expiry_can_only_abandon_and_cannot_resume(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + async with intake.factory.begin() as session: + # Move the still-live lease into the past without sleeping or changing DB time. + await session.execute(text( + "UPDATE submission_intake_operations SET lease_expires_at=clock_timestamp()-interval '1 second' " + "WHERE id=:id" + ), {"id": operation}) + with pytest.raises(IntakeCustodyConflict, match="intake_owner_stale"): + async with intake.factory.begin() as session: + await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + async with intake.factory.begin() as session: + assert await repository(session).abandon_expired(operation) + async with intake.factory.begin() as session: + assert not await repository(session).abandon_expired(operation) + replacement = await reserve(intake, session) + assert replacement.id != str(operation) + with pytest.raises(DBAPIError, match="terminal intake is immutable"): + async with intake.factory.begin() as session: + await session.execute(text( + "UPDATE submission_intake_operations SET state='receiving' WHERE id=:id" + ), {"id": operation}) + + +async def test_actor_key_stays_reserved_after_terminal_outcome(intake): + key = new_record_id() + async with intake.factory.begin() as session: + row = await reserve(intake, session, key=key) + async with intake.factory.begin() as session: + await repository(session).terminalize(UUID(row.id), UUID(row.lease_id), 1, + state="failed", failure_code="upload_failed") + with pytest.raises(DBAPIError, match="uq_submission_intake_actor_key"): + async with intake.factory.begin() as session: + await reserve(intake, session, key=key) + async with intake.factory() as session: + assert await session.scalar(text( + "SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id" + ), {"id": intake.task}) is None + + +async def test_two_requests_serialize_on_task_and_only_one_claims(intake): + async with intake.factory() as first, intake.factory() as second: + await first.begin() + await second.begin() + winner = await reserve(intake, first) + second_pid = await second.scalar(text("SELECT pg_backend_pid()")) + contender = asyncio.create_task(reserve(intake, second)) + try: + async with intake.factory() as observer: + async with asyncio.timeout(10): + while not await observer.scalar(text( + "SELECT cardinality(pg_blocking_pids(:pid))>0" + ), {"pid": second_pid}): + if contender.done(): + await contender + pytest.fail("contender bypassed the TASK lock") + await asyncio.sleep(0.02) + await first.commit() + with pytest.raises(TaskSubmissionContextUnavailable): + await contender + finally: + if not contender.done(): + contender.cancel() + await asyncio.gather(contender, return_exceptions=True) + await first.rollback() + await second.rollback() + async with intake.factory() as session: + assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 1 + assert str(await session.scalar(text( + "SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id" + ), {"id": intake.task})) == winner.id + + +async def test_recorded_source_identity_is_immutable(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + async with intake.factory.begin() as session: + await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + with pytest.raises(DBAPIError, match="sealed_identity"): + async with intake.factory.begin() as session: + await session.execute(text( + "UPDATE submission_intake_operations SET state='pre_checking'," + "provider_generation='generation-without-deadline' WHERE id=:id" + ), {"id": operation}) + with pytest.raises(DBAPIError, match="intake EOF identity is immutable"): + async with intake.factory.begin() as session: + await session.execute(text( + "UPDATE submission_intake_operations SET raw_byte_count=101 WHERE id=:id" + ), {"id": operation}) + async with intake.factory.begin() as session: + deadline = datetime.now(UTC) + timedelta(minutes=2) + await repository(session).seal(operation, lease, 1, provider_generation="generation-a", + pre_deadline_at=deadline, lease_expires_at=deadline) + with pytest.raises(DBAPIError, match="intake sealed source is immutable"): + async with intake.factory.begin() as session: + await session.execute(text( + "UPDATE submission_intake_operations SET provider_generation='generation-b' WHERE id=:id" + ), {"id": operation}) + + +async def test_intake_model_matches_installed_schema(isolated_database_env): + from sqlalchemy import inspect + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + + engine = create_async_engine(isolated_database_env) + try: + async with engine.connect() as connection: + def compare(sync): + inspector = inspect(sync) + table = SubmissionIntakeOperation.__table__ + assert { + (c["name"], str(c["type"].compile(dialect=sync.dialect)), c["nullable"]) + for c in inspector.get_columns(table.name) + } == { + (c.name, str(c.type.compile(dialect=sync.dialect)), c.nullable) + for c in table.columns + } + assert { + (tuple(f["constrained_columns"]), f["referred_table"], tuple(f["referred_columns"])) + for f in inspector.get_foreign_keys(table.name) + } == { + (tuple(f.column_keys), f.referred_table.name, tuple(e.column.name for e in f.elements)) + for f in table.foreign_key_constraints + } + assert {c["name"] for c in inspector.get_check_constraints(table.name)} == { + c.name for c in table.constraints if c.__class__.__name__ == "CheckConstraint" + } + assert {i["name"] for i in inspector.get_indexes(table.name) if not i.get("duplicates_constraint")} == { + i.name for i in table.indexes + } + await connection.run_sync(compare) + finally: + await engine.dispose() + + +@pytest.mark.parametrize(("field", "constraint"), [ + ("project_id", "fk_submission_intake_task"), + ("identity_link_id", "fk_submission_intake_identity"), + ("assignment_id", "fk_submission_intake_assignment"), + ("namespace_fingerprint", "intake namespace mismatch"), +]) +async def test_sql_insert_cannot_substitute_bound_parents(intake, field, constraint): + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + + # Capture a legitimate command, then roll back both participants. The probe + # inserts through SQLAlchemy Core, bypassing the owner repository entirely. + async with intake.factory() as session: + await session.begin() + row = await reserve(intake, session) + values = {c.name: getattr(row, c.name) for c in row.__table__.columns} + await session.rollback() + values[field] = "sha256:" + "f" * 64 if field == "namespace_fingerprint" else str(new_record_id()) + if field == "identity_link_id": + foreign = _context() + async with intake.factory.begin() as session: + await _seed_human_actor(session, foreign) + values[field] = str(foreign.identity_link_id) + if field == "assignment_id": + async with intake.engine.begin() as connection: + await seed_started_task_for_artifact_test(connection, dict( + task=str(new_record_id()), assignment=values[field], + project=values["project_id"], actor=str(intake.actor.actor_profile_id), + )) + metadata = SubmissionIntakeMetadata(task_id=intake.task, assignment_id=UUID(values[field])) + values["command_metadata"] = metadata.model_dump(mode="json") + values["metadata_sha256"] = metadata.metadata_sha256() + with pytest.raises(DBAPIError, match=constraint): + async with intake.factory.begin() as session: + await session.execute(SubmissionIntakeOperation.__table__.insert().values(**values)) + await session.execute(text("SET CONSTRAINTS ALL IMMEDIATE")) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 54fe3d026..c524a0ab0 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,13 +23,14 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "6d2ca52a824038b7cae4ee63a335d852eedfa1764847dba507598e818ba7e0b4" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "cb0bf14485586460459cd35d54647c2de614482c12662e33c4572db6ea6d727e" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", "iso_4217_currency_codes", ) RESETTABLE_TEST_TABLES = ( + "submission_intake_operations", "joint_lifecycle_release_control", "joint_lifecycle_transitions", "actor_identity_links", diff --git a/backend/tests/tasks/submission_dispatch/test_migration.py b/backend/tests/tasks/submission_dispatch/test_migration.py index 80b5b286b..0127d4660 100644 --- a/backend/tests/tasks/submission_dispatch/test_migration.py +++ b/backend/tests/tasks/submission_dispatch/test_migration.py @@ -38,6 +38,7 @@ async def snapshot(): await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) after = await snapshot() added_columns = { + "workstream_tasks": {"active_submission_operation_id"}, "outbox_events": {"not_before_at"}, "submissions": { "selected_post_submit_policy_sha256", "selected_post_submit_policy_body", diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 64a4b66da..44d0f421e 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -817,6 +817,7 @@ async def probe(*, empty_path_fails: bool) -> list[tuple[object, ...]]: "0063_checker_revision_input", "0066_guide_check_specification", "0067_canonical_json_restore_path", + "0068_issuer_profile_email", ], ) def test_preceding_head_upgrades_to_current_without_recreation( diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index c7a758bfe..5e576188b 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -317,8 +317,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 269, - "e302d703e1236f8fbc857009e1df5e2ceec39ea1053ba430cdc8747074d87b7f", + 270, + "9ba49de5926e44beb473c22a3aaf9ba82c6c4f54079d8f54661470b4d96db63c", ), "project": ( 255, diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index eceebdd9f..b53c107ea 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -109,8 +109,10 @@ bound to issuer/subject, not email; signed email is not proof of mailbox verific The [single-request submission specification](spec_submission_execution.md) is the approved target for [WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). -Its first boundary defines immutable command/source values only. Durable intake, -streaming custody, one-session PRE, finalization and client cutover remain planned; +Its hidden owner boundaries define immutable command/source values and durable +foreground intake custody with a matching TASK pointer and source/lease fences. +Physical reservation, streaming custody, one-session PRE, accepted handoff, +finalization and client cutover remain planned; the active API still uses preparation followed by admission-consuming submission. ## Product Goal From f24109eaf7f1550fa14fb448201c2175d1839200 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 17:49:50 +0100 Subject: [PATCH 007/513] Keep submission execution in one PR and register custody proof --- .ci/behavior-ownership/partition.v1.json | 18 +++- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 11 ++- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 36 ++++++++ .../WS-SUBMIT-001/WS-SUBMIT-001-02.md | 88 ------------------- backend/scripts/behavior_ownership.py | 4 + backend/tests/test_behavior_ownership.py | 12 ++- 6 files changed, 73 insertions(+), 96 deletions(-) delete mode 100644 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-02.md diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 36877128b..7708f2766 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -596,6 +596,14 @@ "group": "artifacts", "target": "backend/app/modules/artifacts/guide_formats.py" }, + { + "group": "artifacts", + "target": "backend/app/modules/artifacts/intake/models.py" + }, + { + "group": "artifacts", + "target": "backend/app/modules/artifacts/intake/repository.py" + }, { "group": "artifacts", "target": "backend/app/modules/artifacts/metrics.py" @@ -2124,6 +2132,10 @@ "group": "lifecycle", "target": "backend/app/modules/tasks/api/guide_documents.py" }, + { + "group": "lifecycle", + "target": "backend/app/modules/tasks/api/intake_custody.py" + }, { "group": "lifecycle", "target": "backend/app/modules/tasks/api/management_queue.py" @@ -2228,6 +2240,10 @@ "group": "lifecycle", "target": "backend/app/modules/tasks/evaluation_revision.py" }, + { + "group": "lifecycle", + "target": "backend/app/modules/tasks/intake_custody.py" + }, { "group": "lifecycle", "target": "backend/app/modules/tasks/lifecycle.py" @@ -2597,7 +2613,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "d303fa6bac1b76637fe1f4a31cf700c38bda0c84fc173b168850d3bbc1082537", + "authority_digest": "e5a34050788944ca725e2c7585d25a06f4fd3987e65bcae28d6b54e908a026cc", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index a674e5291..936478863 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -10,8 +10,7 @@ authorize merge or production deployment. ## Current boundary [WS-SUBMIT-001-01](WS-SUBMIT-001-01.md) establishes exact command/source value -contracts. [WS-SUBMIT-001-02](WS-SUBMIT-001-02.md) adds hidden pre-handoff -database custody and TASK/source/lease guards. Physical capacity, provider I/O, +contracts and hidden pre-handoff database custody with TASK/source/lease guards. Physical capacity, provider I/O, accepted authority and orchestration remain to implement. The existing public flow stays active until coordinated cutover. @@ -26,8 +25,12 @@ The existing public flow stays active until coordinated cutover. 6. Single API/CLI/MCP mutation and truthful progress reads. 7. Image cardinality, readiness, migration/cutover and integrated proof. -Create each bounded record when work starts. Authorization covers this sequence; -do not repeat discovery or verification without a relevant changed assumption. +The user requires one PR for the complete work, with focused commits for each +stage and end-to-end testing before requesting merge. Maintain the single +WS-SUBMIT-001-01 change record as implementation proceeds. This explicit +instruction supersedes the repository default of separate PRs per stage. +Authorization covers the sequence; do not stop for intermediate merges or +repeat discovery or verification without a relevant changed assumption. ## Acceptance tracking diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 60cd29819..b8fc750c0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -61,6 +61,28 @@ generation and fence. Metadata identity preserves exact packet and revision selectors; actor/key scope and locked context remain separate operation facts. Constructing these internal values grants no authority or provider qualification. +## Foreground custody stage + +ART now has a private operation model/repository and TASK has a narrow custody +port plus a composite-bound active-operation pointer. Migration 0069 adds these +without rewriting retained rows. Actor/key uniqueness and one active operation +per task protect concurrent intake. Command, actual locked TASK snapshot, +namespace and source key are immutable. Recorded EOF precedes source sealing; +completed generation, raw digest/count and sealed upload fence cannot change. +A database-time lease fences stale publishers. Recovery can abandon expired +foreground work, never resume PRE or accept it. + +Only receiving, pre_checking and pre-handoff terminal outcomes are currently +permitted. Accepted states remain denied until exact AUTH/CHECKERS/outbox handoff +is implemented. These flush-only persistence primitives provide neither storage +capacity nor provider capability nor authorization. Root transaction composition, +physical reservation, streaming, accepted handoff and public cutover remain work. + +The schema comparison from 0068 to 0069 added one table, 33 columns (including +the TASK pointer), 24 constraints, six indexes, three functions and four triggers; +no previous schema objects or reference rows changed. Model registration uses +ART's `intake/models.py` through the canonical database model registry. + ## Acceptance criteria - [x] Exact metadata round-trip and identity changes for each command selector. @@ -70,6 +92,13 @@ Constructing these internal values grants no authority or provider qualification - [x] Unknown fields, mutation and coercive values fail closed. - [ ] Focused tests, lint, boundary/docs checks and scoped frozen-candidate reviews. +- [x] Task/operation commit and rollback, real parent substitution, retained-key + uniqueness, TASK-lock concurrency, EOF/seal immutability and stale-owner proof. +- [x] Retained-submission migration and model/schema parity proof. +- [ ] Complete D01–D18, I01–I12 and T1–T5 behavior with executed A01–A35 evidence. +- [ ] Single API/CLI/MCP cutover, durable recovery and cleanup, existing downstream + policy branches and full-suite/end-to-end verification. + ## Risk and review routing - Risk class: L0 @@ -85,9 +114,16 @@ Constructing these internal values grants no authority or provider qualification | Contracts and CI selection | `pytest -q tests/artifacts/test_submission_intake_contracts.py tests/test_ci_lane_catalogue.py`; ruff | 118 tests passed; lint passed | No database/storage/runtime proof | | Documentation guard regression | `python -m unittest scripts.test_lightweight_agent_gates scripts.test_stale_review_contracts -q` | 35 tests passed | Narrow storage examples only | | Module boundaries | `python -m scripts.module_boundaries validate --protected-base origin/main` | Passed | Existing private-import debt unchanged | +| Foreground custody and retained-data upgrade | `pytest tests/artifacts/test_submission_intake_custody.py 'tests/test_alembic.py::test_preceding_head_upgrades_to_current_without_recreation[0068_issuer_profile_email]' tests/test_alembic.py::test_repeated_upgrade_head_preserves_current_database tests/tasks/submission_dispatch/test_migration.py -q` through the isolated PostgreSQL 16 runner | 21 passed; isolated database and role cleanup confirmed | Pre-handoff persistence only; no provider, PRE, acceptance or public-route proof | +| Protected target partition | `pytest tests/test_behavior_ownership.py -q` | 170 passed | Exact added paths only; no relaxed selection | +| Model registration | UUID inventory and protected module-boundary tests | Both passed | No new cross-owner private imports | ## Review findings +- Hosted CI exposed an unregistered contract file in the protected behavior + partition. The exact target is now registered; unrelated additions and removal + of retained targets remain rejected. The 170-test ownership suite passed. + - Architecture/security found a synthetic UUID namespace fixture incompatible with ART's natural singleton ID, and missing fingerprint binding. The value now uses `primary` and its fingerprint; an actual adapter-derived namespace diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-02.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-02.md deleted file mode 100644 index e9b75720e..000000000 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-02.md +++ /dev/null @@ -1,88 +0,0 @@ -# WS-SUBMIT-001-02 — Durable foreground intake custody - -- Initiative: WS-SUBMIT-001 -- Durable disposition: Planned -- Intended merge outcome: persist fenced pre-handoff intake with one matching task owner, immutable command/source identity and PostgreSQL failure/concurrency proof. - -## Intent - -Make an original upload accountable before provider writes begin. A process-local -prepared ZIP cannot provide ownership after API failure. This change supplies -durable foreground custody for subsequent bounded streaming and T1–T4 composition. - -## Current behavior - -The prior change defines immutable value contracts but creates no durable intake. -ART stores prepared admissions only after PRE; TASK has no early active-operation -pointer. Schema head is 0068 on main 94334ccf4. This change is stacked on PR #708; -it does not merge or modify that PR's branch. - -## Bounded change - -### Allowed - -- ART intake model/repository and typed value additions under existing owners. -- TASK active-operation pointer and narrow owner methods; existing lifecycle - guards must reject inconsistent assignment or task transitions while guarded. -- Migration after 0068: constraints, composite foreign keys, immutable identity, - fenced forward transitions and matching task/operation custody. -- Database metadata registration, canonical migration/reset fixtures, semantic - test selection and targeted real PostgreSQL tests required by this schema. -- Initiative/index/roadmap statements of exactly delivered and remaining behavior. - -### Not allowed - -- Public endpoint/client cutover, provider writes, background PRE or new authority. -- Claims of physical quota enforcement, storage cleanup or runtime qualification. -- Accepted handoff before the exact AUTH/CHECKERS/outbox composition exists. -- Historical artifact rewrites, deletion, changed revision rules or deployment defaults. - -## Design and decisions - -The initial hidden persistence boundary permits receiving, pre_checking and -pre-handoff terminal outcomes only. Finalization_pending/finalized remain denied -until the later accepted-authority and outbox transaction adds their full guards. -This is staged implementation of one lifecycle, not an alternative submission API. - -Actor/key uniqueness and a partial unique task index fence concurrent operations. -The task pointer is composite-bound to its own operation and checked at commit. -Command, actual TASK locked-context snapshot, namespace and object key are -immutable. EOF raw identity precedes sealed generation; completed source facts -cannot change. Foreground owners use a generation and database-time lease. -Expired or terminal ownership cannot publish new source facts. Recovery may fence -and abandon expired pre-handoff work, never accept it. Persistence primitives are -internal; they grant no upload/read capability and do not replace AUTH. - -## Acceptance criteria - -- [ ] Current schema upgrades without rewriting retained data. -- [ ] Exact actor/key and one-active-task constraints hold across independent transactions. -- [ ] Task, assignment, actor/link, project and namespace substitutions fail in SQL. -- [ ] Task pointer and operation state commit together; rollback leaves neither. -- [ ] Command/context/source identities cannot mutate after binding. -- [ ] EOF precedes exact source sealing; stale/expired owners and terminal revival fail. -- [ ] Existing affected task/submission behavior remains valid with null intake pointers. -- [ ] Focused PostgreSQL, migration/model parity, lint and impact-routed reviews pass. - -## Risk and review routing - -- Risk class: L0 -- Required reviewers: architecture, security, QA/test_delta, CI integrity, documentation -- Human review focus: custody locks/fences, deferred closure and retained-data preservation. - -## Evidence - -| Claim | Command or proof | Result | Remaining uncertainty | -|---|---|---|---| -| Baseline | Fetch main; inspect PR #708 | Main 94334ccf4, parent PR open and CI running | No merge authority implied | -| Custody | Real PostgreSQL owner/direct-SQL/concurrency tests | Not executed | No integrated T1–T5 proof yet | - -## Review findings - -None recorded yet. - -## Reconciliation - -- Current-source reconciliation: parent identity contracts include ART primary/fingerprint binding. -- Next usable boundary: streaming storage reservation/receipt and complete acceptance authority. -- Remaining risks: T4/T5, physical storage, runtime and public cutover remain unimplemented. diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index b7a58457f..f3c193b7d 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -934,6 +934,10 @@ }) SUBMISSION_INTAKE_TARGETS = frozenset({ "backend/app/modules/artifacts/api/submission_intake.py", + "backend/app/modules/artifacts/intake/models.py", + "backend/app/modules/artifacts/intake/repository.py", + "backend/app/modules/tasks/api/intake_custody.py", + "backend/app/modules/tasks/intake_custody.py", }) FORGE_PROOF_FACTS_TARGETS = frozenset({ "backend/app/adapters/github/app_facts.py", diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index 2d4ba4308..28eb5821f 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2762,9 +2762,15 @@ def test_art_operator_ownership_accepts_only_exact_new_modules(): def test_submission_intake_partition_addition_is_exact_and_retains_existing_targets() -> None: retained = "backend/app/core/config.py" target = "backend/app/modules/artifacts/api/submission_intake.py" - assert ownership.SUBMISSION_INTAKE_TARGETS == {target} + additions = { + target, "backend/app/modules/artifacts/intake/models.py", + "backend/app/modules/artifacts/intake/repository.py", + "backend/app/modules/tasks/api/intake_custody.py", + "backend/app/modules/tasks/intake_custody.py", + } + assert ownership.SUBMISSION_INTAKE_TARGETS == additions trusted = _partition([retained]) - ownership._validate_additive_partition_transition(_partition(sorted([retained, target])), trusted) - for targets in ([target], [retained, target, "backend/app/modules/artifacts/api/intake_override.py"]): + ownership._validate_additive_partition_transition(_partition(sorted({retained, *additions})), trusted) + for targets in (additions, {retained, *additions, "backend/app/modules/artifacts/api/intake_override.py"}): with pytest.raises(ownership.BehaviorOwnershipError, match="untrusted_partition_change"): ownership._validate_additive_partition_transition(_partition(sorted(targets)), trusted) From 2d223e435db3b1988fdd6f6a198429036094500e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 17:55:55 +0100 Subject: [PATCH 008/513] Reject malformed immutable intake selectors in PostgreSQL --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++++-- .../0069_submission_intake_custody.py | 8 +++++ .../test_submission_intake_custody.py | 31 +++++++++++++++++++ backend/tests/conftest.py | 2 +- 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b8fc750c0..5555faaeb 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -120,6 +120,12 @@ ART's `intake/models.py` through the canonical database model registry. ## Review findings +- Custody review found nullable predecessor/revision selector types and UUID + shape unchecked in the SQL insert guard. A direct-SQL regression recomputed + the digest and installed the matching task pointer; it reproduced acceptance + of a numeric predecessor before the repair. The guard now requires canonical + UUID strings for both non-null selectors, matching stored typed commands. + - Hosted CI exposed an unregistered contract file in the protected behavior partition. The exact target is now registered; unrelated additions and removal of retained targets remain rejected. The 170-test ownership suite passed. @@ -138,6 +144,6 @@ ART's `intake/models.py` through the canonical database model registry. - Current-source reconciliation: rebased onto 94334ccf4 (PR #707); preserved issuer profile roadmap changes and schema head 0068. Submission owner contracts unchanged. -- Next implementation stage: durable operation schema and owner commands in - the same PR, followed by streaming, PRE, handoff/finalization and clients. +- Next implementation stage: physical reservation and streaming custody in + the same PR, followed by PRE, handoff/finalization and clients. - Remaining risks: A01–A35 integration and C01–C07 qualification. diff --git a/backend/alembic/versions/0069_submission_intake_custody.py b/backend/alembic/versions/0069_submission_intake_custody.py index e2e4ed73c..544fa2a3e 100644 --- a/backend/alembic/versions/0069_submission_intake_custody.py +++ b/backend/alembic/versions/0069_submission_intake_custody.py @@ -85,6 +85,7 @@ DECLARE m jsonb; canonical text; + selector text; BEGIN IF TG_OP='DELETE' THEN RAISE EXCEPTION 'submission intake custody cannot be deleted' USING ERRCODE='23514'; @@ -116,6 +117,13 @@ m->>'revision_preparation_sha256' !~ '^sha256:[0-9a-f]{64}$') THEN RAISE EXCEPTION 'invalid intake metadata' USING ERRCODE='23514'; END IF; + FOREACH selector IN ARRAY ARRAY['predecessor_submission_id','revision_preparation_id'] LOOP + IF m->>selector IS NOT NULL AND ( + jsonb_typeof(m->selector) IS DISTINCT FROM 'string' + OR m->>selector !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') THEN + RAISE EXCEPTION 'invalid intake metadata' USING ERRCODE='23514'; + END IF; + END LOOP; canonical:=public.project_guide_projection_canonical_json( m || jsonb_build_object('schema_version','workstream.submission_intake_metadata.v1')); IF NEW.metadata_sha256 IS DISTINCT FROM 'sha256:'||encode(sha256(convert_to(canonical,'UTF8')),'hex') diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 8295ce213..37b8d1cc5 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -303,3 +303,34 @@ async def test_sql_insert_cannot_substitute_bound_parents(intake, field, constra async with intake.factory.begin() as session: await session.execute(SubmissionIntakeOperation.__table__.insert().values(**values)) await session.execute(text("SET CONSTRAINTS ALL IMMEDIATE")) + + +async def test_sql_rejects_malformed_command_selectors_even_with_matching_digest(intake): + from app.core.hashing import canonical_json_hash + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + + async with intake.factory() as session: + await session.begin() + row = await reserve(intake, session) + values = {c.name: getattr(row, c.name) for c in row.__table__.columns} + await session.rollback() + cases = [ + {"predecessor_submission_id": value} + for value in (42, True, {}, [], "not-a-uuid", str(new_record_id()).upper()) + ] + [ + {"predecessor_submission_id": str(new_record_id()), + "revision_preparation_id": value, "revision_preparation_sha256": SHA} + for value in (42, {}, "not-a-uuid") + ] + for selectors in cases: + metadata = {**values["command_metadata"], **selectors} + candidate = {**values, "command_metadata": metadata, + "metadata_sha256": canonical_json_hash({ + "schema_version": "workstream.submission_intake_metadata.v1", **metadata, + })} + with pytest.raises(DBAPIError, match="invalid intake metadata"): + async with intake.factory.begin() as session: + await session.execute(text( + "UPDATE workstream_tasks SET active_submission_operation_id=:operation WHERE id=:task" + ), {"operation": UUID(row.id), "task": intake.task}) + await session.execute(SubmissionIntakeOperation.__table__.insert().values(**candidate)) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index c524a0ab0..cdac78941 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "cb0bf14485586460459cd35d54647c2de614482c12662e33c4572db6ea6d727e" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "d787347d49ee27b4b8dca0da9ca254f40703da6b4445644d38271c5a40a6b2a2" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", From eaf2e4bfcc959c4aecd41f12f6463106bac8881a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 18:23:42 +0100 Subject: [PATCH 009/513] Reserve and retain physical bytes for each submission source --- .ci/behavior-ownership/partition.v1.json | 6 +- .commitrail/INDEX.md | 2 +- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 3 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 35 ++- .../0069_submission_intake_custody.py | 158 ++++++++++- backend/app/db/models.py | 4 +- .../artifacts/api/submission_intake.py | 16 ++ .../app/modules/artifacts/intake/capacity.py | 101 +++++++ .../app/modules/artifacts/intake/models.py | 46 ++++ .../modules/artifacts/intake/repository.py | 8 +- backend/scripts/behavior_ownership.py | 1 + backend/scripts/identifier_inventory.py | 2 + .../test_submission_intake_custody.py | 255 ++++++++++++++++-- backend/tests/conftest.py | 7 +- backend/tests/test_behavior_ownership.py | 1 + docs/roadmap_status.md | 5 +- 16 files changed, 613 insertions(+), 37 deletions(-) create mode 100644 backend/app/modules/artifacts/intake/capacity.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 7708f2766..fe48f5708 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -596,6 +596,10 @@ "group": "artifacts", "target": "backend/app/modules/artifacts/guide_formats.py" }, + { + "group": "artifacts", + "target": "backend/app/modules/artifacts/intake/capacity.py" + }, { "group": "artifacts", "target": "backend/app/modules/artifacts/intake/models.py" @@ -2613,7 +2617,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "e5a34050788944ca725e2c7585d25a06f4fd3987e65bcae28d6b54e908a026cc", + "authority_digest": "f8f9f1525d11ac23ce78f7dd22ea7258bee8417adece74ca9c205a3b0d901864", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index bacb75977..d943394f1 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | One-request command/source contracts and hidden foreground custody; next physical capacity, streaming custody, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | One-request command/source contracts, hidden foreground custody and physical source reservations; next streaming/cleanup custody, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 936478863..06d5d1271 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -10,7 +10,8 @@ authorize merge or production deployment. ## Current boundary [WS-SUBMIT-001-01](WS-SUBMIT-001-01.md) establishes exact command/source value -contracts and hidden pre-handoff database custody with TASK/source/lease guards. Physical capacity, provider I/O, +contracts and hidden pre-handoff database custody with TASK/source/lease guards. Per-operation physical source reservations are implemented with explicit limits. +Provider I/O, confirmed physical reclamation, accepted authority and orchestration remain to implement. The existing public flow stays active until coordinated cutover. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 5555faaeb..df36c84b3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -76,13 +76,38 @@ Only receiving, pre_checking and pre-handoff terminal outcomes are currently permitted. Accepted states remain denied until exact AUTH/CHECKERS/outbox handoff is implemented. These flush-only persistence primitives provide neither storage capacity nor provider capability nor authorization. Root transaction composition, -physical reservation, streaming, accepted handoff and public cutover remain work. +streaming, accepted handoff and public cutover remain work. The schema comparison from 0068 to 0069 added one table, 33 columns (including the TASK pointer), 24 constraints, six indexes, three functions and four triggers; no previous schema objects or reference rows changed. Model registration uses ART's `intake/models.py` through the canonical database model registry. +## Physical reservation stage + +Source accounting extends ART's intake model/repository and migration 0069 +with per-operation source-byte charges. The existing SHA-deduplicated admission +ledger remains intact for its consumers: it cannot count separate equal-content +source objects. Source quotas are a distinct configured allocation for this +managed prefix, not a claim to measure every existing object in the bucket. + +Use one immutable namespace capacity profile and serialize reservation/sealing +under its row lock, after TASK and operation locks. Sum actual charge rows rather +than adding a second mutable counter that could drift. Explicit required limits +cover the source allocation, with optional task/project/producer caps. No +production defaults are selected. Declared size reserves exactly that bounded +amount; otherwise reserve the operation raw limit. EOF must match a declaration. +Sealing converts to actual raw bytes and releases only unused allowance. Failure, +lease expiry and registration do not release physical charges. Reclamation will +require the subsequent exact cleanup implementation; it is not exposed here. + +Allowed files are the existing intake models/repository, a cohesive ART capacity +owner and typed limits in the intake API, migration0069, their targeted tests, +canonical reset/ownership catalogues and this current record. This stage adds no +provider writes, route or AUTH authority. Proof must cover simultaneous spending, +rollback, same-content distinct operations, declared-size equality, sealed-byte +conversion and failed/expired charge retention on real PostgreSQL. + ## Acceptance criteria - [x] Exact metadata round-trip and identity changes for each command selector. @@ -99,6 +124,10 @@ ART's `intake/models.py` through the canonical database model registry. - [ ] Single API/CLI/MCP cutover, durable recovery and cleanup, existing downstream policy branches and full-suite/end-to-end verification. +- [x] Physical source reservations enforce every enabled scope, retain failed and + expired obligations, reject declared-length mismatch and count equal-content + sources separately; concurrent tasks cannot spend the same remaining bytes. + ## Risk and review routing - Risk class: L0 @@ -115,6 +144,8 @@ ART's `intake/models.py` through the canonical database model registry. | Documentation guard regression | `python -m unittest scripts.test_lightweight_agent_gates scripts.test_stale_review_contracts -q` | 35 tests passed | Narrow storage examples only | | Module boundaries | `python -m scripts.module_boundaries validate --protected-base origin/main` | Passed | Existing private-import debt unchanged | | Foreground custody and retained-data upgrade | `pytest tests/artifacts/test_submission_intake_custody.py 'tests/test_alembic.py::test_preceding_head_upgrades_to_current_without_recreation[0068_issuer_profile_email]' tests/test_alembic.py::test_repeated_upgrade_head_preserves_current_database tests/tasks/submission_dispatch/test_migration.py -q` through the isolated PostgreSQL 16 runner | 21 passed; isolated database and role cleanup confirmed | Pre-handoff persistence only; no provider, PRE, acceptance or public-route proof | +| Physical source accounting | `pytest tests/artifacts/test_submission_intake_custody.py -q` through isolated PostgreSQL 16 | 34 passed on the capacity-stage working tree; cleanup confirmed | No provider bytes written or cleanup/reclamation claim | +| Capacity-stage static ownership | UUID inventory, behavior partition, semantic lane catalogue and module boundary tests | 254 passed; ruff passed | Final integrated suite still required | | Protected target partition | `pytest tests/test_behavior_ownership.py -q` | 170 passed | Exact added paths only; no relaxed selection | | Model registration | UUID inventory and protected module-boundary tests | Both passed | No new cross-owner private imports | @@ -144,6 +175,6 @@ ART's `intake/models.py` through the canonical database model registry. - Current-source reconciliation: rebased onto 94334ccf4 (PR #707); preserved issuer profile roadmap changes and schema head 0068. Submission owner contracts unchanged. -- Next implementation stage: physical reservation and streaming custody in +- Next implementation stage: bounded streaming and exact cleanup custody in the same PR, followed by PRE, handoff/finalization and clients. - Remaining risks: A01–A35 integration and C01–C07 qualification. diff --git a/backend/alembic/versions/0069_submission_intake_custody.py b/backend/alembic/versions/0069_submission_intake_custody.py index 544fa2a3e..7f69352eb 100644 --- a/backend/alembic/versions/0069_submission_intake_custody.py +++ b/backend/alembic/versions/0069_submission_intake_custody.py @@ -71,6 +71,39 @@ CREATE UNIQUE INDEX uq_submission_intake_active_task ON public.submission_intake_operations (task_id) WHERE state in ('receiving','pre_checking') """ +CAPACITY_TABLE_SQL = r""" +CREATE TABLE public.submission_source_capacity_profiles ( + namespace_id VARCHAR(20) NOT NULL, + namespace_fingerprint VARCHAR(71) NOT NULL, + maximum_total_bytes BIGINT NOT NULL, + maximum_project_bytes BIGINT, + maximum_producer_bytes BIGINT, + maximum_task_bytes BIGINT, + configuration_sha256 VARCHAR(71) NOT NULL, + CONSTRAINT pk_submission_source_capacity_profiles PRIMARY KEY (namespace_id), + CONSTRAINT fk_submission_source_capacity_namespace FOREIGN KEY(namespace_id, namespace_fingerprint) REFERENCES public.artifact_storage_namespaces (id, namespace_fingerprint), + CONSTRAINT ck_submission_source_capacity_profiles_positive_limits CHECK (maximum_total_bytes>0 and (maximum_project_bytes is null or maximum_project_bytes>0) and (maximum_producer_bytes is null or maximum_producer_bytes>0) and (maximum_task_bytes is null or maximum_task_bytes>0)), + CONSTRAINT ck_submission_source_capacity_profiles_configuration_digest CHECK (configuration_sha256 ~ '^sha256:[0-9a-f]{64}$') +) + +; + +CREATE TABLE public.submission_source_charges ( + operation_id UUID NOT NULL, + declared_raw_bytes BIGINT, + reserved_bytes BIGINT NOT NULL, + accounted_bytes BIGINT NOT NULL, + state VARCHAR(20) NOT NULL, + sealed_at TIMESTAMP WITH TIME ZONE, + CONSTRAINT pk_submission_source_charges PRIMARY KEY (operation_id), + CONSTRAINT fk_submission_source_charge_operation FOREIGN KEY(operation_id) REFERENCES public.submission_intake_operations (id), + CONSTRAINT ck_submission_source_charges_positive_charge CHECK (reserved_bytes>0 and accounted_bytes>0 and accounted_bytes<=reserved_bytes), + CONSTRAINT ck_submission_source_charges_declared_reservation CHECK (declared_raw_bytes is null or declared_raw_bytes=reserved_bytes), + CONSTRAINT ck_submission_source_charges_charge_state CHECK (state in ('reserved','sealed')), + CONSTRAINT ck_submission_source_charges_charge_shape CHECK ((state='reserved' and accounted_bytes=reserved_bytes and sealed_at is null) or (state='sealed' and sealed_at is not null)) +); +""" + GUARDS = r""" CREATE FUNCTION public.submission_intake_task_snapshot(t public.workstream_tasks) RETURNS jsonb LANGUAGE sql IMMUTABLE STRICT @@ -87,7 +120,7 @@ canonical text; selector text; BEGIN - IF TG_OP='DELETE' THEN + IF TG_OP IN ('DELETE','TRUNCATE') THEN RAISE EXCEPTION 'submission intake custody cannot be deleted' USING ERRCODE='23514'; END IF; IF TG_OP='INSERT' THEN @@ -184,6 +217,10 @@ RAISE EXCEPTION 'stale intake foreground owner' USING ERRCODE='23514'; END IF; IF OLD.raw_sha256 IS NULL AND NEW.raw_sha256 IS NOT NULL THEN + IF EXISTS (SELECT 1 FROM public.submission_source_charges c WHERE c.operation_id=OLD.id + AND c.declared_raw_bytes IS NOT NULL AND c.declared_raw_bytes IS DISTINCT FROM NEW.raw_byte_count) THEN + RAISE EXCEPTION 'submission source declared size mismatch' USING ERRCODE='23514'; + END IF; NEW.eof_at:=clock_timestamp(); END IF; IF OLD.provider_generation IS NULL AND NEW.provider_generation IS NOT NULL THEN @@ -240,6 +277,123 @@ CREATE CONSTRAINT TRIGGER assignment_submission_intake_closure AFTER INSERT OR UPDATE OR DELETE ON public.task_assignments DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_intake_custody(); +CREATE FUNCTION public.guard_submission_source_capacity_profile() +RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ +DECLARE canonical text; +BEGIN + IF TG_OP<>'INSERT' THEN + IF TG_OP='UPDATE' AND to_jsonb(NEW)=to_jsonb(OLD) THEN RETURN NEW; END IF; + RAISE EXCEPTION 'submission source capacity configuration is immutable' USING ERRCODE='23514'; + END IF; + canonical:=public.project_guide_projection_canonical_json(jsonb_build_object( + 'schema_version','workstream.submission_source_capacity.v1', + 'maximum_total_bytes',NEW.maximum_total_bytes,'maximum_project_bytes',NEW.maximum_project_bytes, + 'maximum_producer_bytes',NEW.maximum_producer_bytes,'maximum_task_bytes',NEW.maximum_task_bytes)); + IF NEW.configuration_sha256 IS DISTINCT FROM 'sha256:'||encode(sha256(convert_to(canonical,'UTF8')),'hex') THEN + RAISE EXCEPTION 'submission source capacity digest mismatch' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER submission_source_capacity_profile_guard +BEFORE INSERT OR UPDATE OR DELETE ON public.submission_source_capacity_profiles +FOR EACH ROW EXECUTE FUNCTION public.guard_submission_source_capacity_profile(); + +CREATE FUNCTION public.guard_submission_source_charge() +RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ +DECLARE + o public.submission_intake_operations%ROWTYPE; + p public.submission_source_capacity_profiles%ROWTYPE; + total_bytes numeric; project_bytes numeric; producer_bytes numeric; task_bytes numeric; +BEGIN + IF TG_OP IN ('DELETE','TRUNCATE') THEN + RAISE EXCEPTION 'submission source charges require confirmed cleanup' USING ERRCODE='23514'; + END IF; + SELECT * INTO o FROM public.submission_intake_operations WHERE id=NEW.operation_id; + SELECT * INTO p FROM public.submission_source_capacity_profiles + WHERE namespace_id=o.namespace_id AND namespace_fingerprint=o.namespace_fingerprint FOR UPDATE; + IF o.id IS NULL OR p.namespace_id IS NULL THEN + RAISE EXCEPTION 'submission source capacity owner missing' USING ERRCODE='23514'; + END IF; + IF TG_OP='INSERT' THEN + IF o.state<>'receiving' OR o.raw_sha256 IS NOT NULL + OR NEW.state<>'reserved' OR NEW.sealed_at IS NOT NULL + OR NEW.reserved_bytes IS DISTINCT FROM coalesce(NEW.declared_raw_bytes,o.maximum_raw_bytes) + OR NEW.reserved_bytes>o.maximum_raw_bytes + OR NEW.accounted_bytes IS DISTINCT FROM NEW.reserved_bytes THEN + RAISE EXCEPTION 'invalid submission source reservation' USING ERRCODE='23514'; + END IF; + ELSE + IF (to_jsonb(NEW)-ARRAY['state','accounted_bytes','sealed_at']) IS DISTINCT FROM + (to_jsonb(OLD)-ARRAY['state','accounted_bytes','sealed_at']) THEN + RAISE EXCEPTION 'submission source reservation identity is immutable' USING ERRCODE='23514'; + END IF; + IF OLD.state='sealed' THEN + IF to_jsonb(NEW) IS DISTINCT FROM to_jsonb(OLD) THEN + RAISE EXCEPTION 'sealed submission source charge is immutable' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.state<>'sealed' OR o.provider_generation IS NULL + OR NEW.accounted_bytes IS DISTINCT FROM o.raw_byte_count + OR (NEW.declared_raw_bytes IS NOT NULL AND NEW.declared_raw_bytes IS DISTINCT FROM o.raw_byte_count) THEN + RAISE EXCEPTION 'invalid sealed submission source charge' USING ERRCODE='23514'; + END IF; + NEW.sealed_at:=clock_timestamp(); + END IF; + SELECT coalesce(sum(c.accounted_bytes),0), + coalesce(sum(c.accounted_bytes) FILTER (WHERE i.project_id=o.project_id),0), + coalesce(sum(c.accounted_bytes) FILTER (WHERE i.actor_profile_id=o.actor_profile_id),0), + coalesce(sum(c.accounted_bytes) FILTER (WHERE i.task_id=o.task_id),0) + INTO total_bytes,project_bytes,producer_bytes,task_bytes + FROM public.submission_source_charges c JOIN public.submission_intake_operations i ON i.id=c.operation_id + WHERE i.namespace_id=o.namespace_id AND i.namespace_fingerprint=o.namespace_fingerprint + AND c.operation_id<>NEW.operation_id; + IF total_bytes+NEW.accounted_bytes>p.maximum_total_bytes + OR (p.maximum_project_bytes IS NOT NULL AND project_bytes+NEW.accounted_bytes>p.maximum_project_bytes) + OR (p.maximum_producer_bytes IS NOT NULL AND producer_bytes+NEW.accounted_bytes>p.maximum_producer_bytes) + OR (p.maximum_task_bytes IS NOT NULL AND task_bytes+NEW.accounted_bytes>p.maximum_task_bytes) THEN + RAISE EXCEPTION 'submission source capacity exhausted' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER submission_source_charge_guard +BEFORE INSERT OR UPDATE OR DELETE ON public.submission_source_charges +FOR EACH ROW EXECUTE FUNCTION public.guard_submission_source_charge(); + +CREATE FUNCTION public.check_submission_source_accounting() +RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ +DECLARE + operation_key uuid; + o public.submission_intake_operations%ROWTYPE; + c public.submission_source_charges%ROWTYPE; +BEGIN + IF TG_TABLE_NAME='submission_intake_operations' THEN + operation_key:=coalesce(NEW.id,OLD.id); + ELSE + operation_key:=coalesce(NEW.operation_id,OLD.operation_id); + END IF; + SELECT * INTO o FROM public.submission_intake_operations WHERE id=operation_key; + SELECT * INTO c FROM public.submission_source_charges WHERE operation_id=operation_key; + IF o.id IS NULL OR c.operation_id IS NULL + OR (o.provider_generation IS NULL AND c.state<>'reserved') + OR (o.provider_generation IS NOT NULL AND + (c.state<>'sealed' OR c.accounted_bytes IS DISTINCT FROM o.raw_byte_count)) THEN + RAISE EXCEPTION 'submission source accounting custody mismatch' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END $$; +CREATE CONSTRAINT TRIGGER submission_intake_source_accounting +AFTER INSERT OR UPDATE ON public.submission_intake_operations +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_source_accounting(); +CREATE CONSTRAINT TRIGGER submission_source_charge_accounting +AFTER INSERT OR UPDATE OR DELETE ON public.submission_source_charges +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_source_accounting(); +CREATE TRIGGER submission_intake_operations_no_truncate BEFORE TRUNCATE ON public.submission_intake_operations +FOR EACH STATEMENT EXECUTE FUNCTION public.guard_submission_intake_mutation(); +CREATE TRIGGER submission_source_capacity_profiles_no_truncate BEFORE TRUNCATE ON public.submission_source_capacity_profiles +FOR EACH STATEMENT EXECUTE FUNCTION public.guard_submission_source_capacity_profile(); +CREATE TRIGGER submission_source_charges_no_truncate BEFORE TRUNCATE ON public.submission_source_charges +FOR EACH STATEMENT EXECUTE FUNCTION public.guard_submission_source_charge(); """ @@ -251,6 +405,8 @@ def upgrade() -> None: op.create_foreign_key("fk_task_active_submission_intake", "workstream_tasks", "submission_intake_operations", ["active_submission_operation_id", "id"], ["id", "task_id"], source_schema="public", referent_schema="public", deferrable=True, initially="DEFERRED") + for statement in split_sql_statements(CAPACITY_TABLE_SQL): + op.execute(statement) for statement in split_sql_statements(GUARDS): op.execute(statement) diff --git a/backend/app/db/models.py b/backend/app/db/models.py index 64408d098..dbdf73bd4 100644 --- a/backend/app/db/models.py +++ b/backend/app/db/models.py @@ -7,7 +7,9 @@ LegacyWorkflowEligibility, ) from app.modules.api_controls.models import ApiRateControlCounter # noqa: F401 -from app.modules.artifacts.intake.models import SubmissionIntakeOperation # noqa: F401 +from app.modules.artifacts.intake.models import ( # noqa: F401 + SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge, +) from app.modules.artifacts.models import ( # noqa: F401 ArtifactBinding, ArtifactContent, diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py index 808a28f8b..6b014bbf5 100644 --- a/backend/app/modules/artifacts/api/submission_intake.py +++ b/backend/app/modules/artifacts/api/submission_intake.py @@ -134,3 +134,19 @@ def source_sha256(self) -> str: "schema_version": "workstream.sealed_submission_source.v1", **self.model_dump(mode="json"), }) + + +class SubmissionSourceCapacityLimits(_IntakeValue): + """Explicit physical source allocation; no deployment defaults or logical dedup.""" + + maximum_total_bytes: int = Field(ge=1, le=2**63 - 1) + maximum_project_bytes: int | None = Field(default=None, ge=1, le=2**63 - 1) + maximum_producer_bytes: int | None = Field(default=None, ge=1, le=2**63 - 1) + maximum_task_bytes: int | None = Field(default=None, ge=1, le=2**63 - 1) + + def configuration_sha256(self) -> str: + """Bind the explicit allocation used by every writer in this namespace.""" + return canonical_json_hash({ + "schema_version": "workstream.submission_source_capacity.v1", + **self.model_dump(mode="json"), + }) diff --git a/backend/app/modules/artifacts/intake/capacity.py b/backend/app/modules/artifacts/intake/capacity.py new file mode 100644 index 000000000..7429b0700 --- /dev/null +++ b/backend/app/modules/artifacts/intake/capacity.py @@ -0,0 +1,101 @@ +"""Physical source-byte reservations, separate from SHA-deduplicated ART charges.""" + +from sqlalchemy import func, select +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.ext.asyncio import AsyncSession + +from app.modules.artifacts.api.submission_intake import SubmissionSourceCapacityLimits +from app.modules.artifacts.intake.models import ( + SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge, +) + + +class SubmissionSourceCapacityConflict(RuntimeError): + """Stable allocation conflict; never a checker verdict or storage permission.""" + + +class SubmissionSourceCapacity: + """Flush-only capacity owner; caller holds TASK and operation custody first.""" + + def __init__(self, session: AsyncSession) -> None: + self._session = session + + def _require_transaction(self) -> None: + if not self._session.in_transaction() or self._session.in_nested_transaction(): + raise SubmissionSourceCapacityConflict("source_capacity_requires_root_transaction") + + async def _profile( + self, operation: SubmissionIntakeOperation, limits: SubmissionSourceCapacityLimits | None, + ) -> SubmissionSourceCapacityProfile: + self._require_transaction() + if limits is not None: + limits = SubmissionSourceCapacityLimits.model_validate(limits) + await self._session.execute(insert(SubmissionSourceCapacityProfile).values( + namespace_id=operation.namespace_id, + namespace_fingerprint=operation.namespace_fingerprint, + configuration_sha256=limits.configuration_sha256(), + **limits.model_dump(), + ).on_conflict_do_nothing(index_elements=["namespace_id"])) + profile = await self._session.scalar(select(SubmissionSourceCapacityProfile).where( + SubmissionSourceCapacityProfile.namespace_id == operation.namespace_id, + ).with_for_update().execution_options(populate_existing=True)) + if (profile is None or profile.namespace_fingerprint != operation.namespace_fingerprint + or (limits is not None and profile.configuration_sha256 != limits.configuration_sha256())): + raise SubmissionSourceCapacityConflict("source_capacity_configuration_mismatch") + return profile + + async def reserve( + self, operation: SubmissionIntakeOperation, *, limits: SubmissionSourceCapacityLimits, + declared_raw_bytes: int | None, + ) -> SubmissionSourceCharge: + """Reserve declared bytes or the raw ceiling before any provider write.""" + if declared_raw_bytes is not None and ( + type(declared_raw_bytes) is not int or not 1 <= declared_raw_bytes <= operation.maximum_raw_bytes + ): + raise SubmissionSourceCapacityConflict("source_declared_size_invalid") + profile = await self._profile(operation, limits) + reserved = declared_raw_bytes if declared_raw_bytes is not None else operation.maximum_raw_bytes + existing = await self._session.get(SubmissionSourceCharge, operation.id) + if existing is not None: + if existing.declared_raw_bytes != declared_raw_bytes or existing.reserved_bytes != reserved: + raise SubmissionSourceCapacityConflict("source_reservation_replay_mismatch") + return existing + charge, parent = SubmissionSourceCharge, SubmissionIntakeOperation + totals = (await self._session.execute(select( + func.coalesce(func.sum(charge.accounted_bytes), 0), + func.coalesce(func.sum(charge.accounted_bytes).filter(parent.project_id == operation.project_id), 0), + func.coalesce(func.sum(charge.accounted_bytes).filter(parent.actor_profile_id == operation.actor_profile_id), 0), + func.coalesce(func.sum(charge.accounted_bytes).filter(parent.task_id == operation.task_id), 0), + ).join(parent, parent.id == charge.operation_id).where( + parent.namespace_id == operation.namespace_id, + parent.namespace_fingerprint == operation.namespace_fingerprint, + ))).one() + ceilings = (profile.maximum_total_bytes, profile.maximum_project_bytes, + profile.maximum_producer_bytes, profile.maximum_task_bytes) + if any(limit is not None and used + reserved > limit for used, limit in zip(totals, ceilings, strict=True)): + raise SubmissionSourceCapacityConflict("source_capacity_exhausted") + row = SubmissionSourceCharge( + operation_id=operation.id, declared_raw_bytes=declared_raw_bytes, + reserved_bytes=reserved, accounted_bytes=reserved, state="reserved", + ) + self._session.add(row) + await self._session.flush() + return row + + async def seal(self, operation: SubmissionIntakeOperation) -> None: + """Convert only unused allowance; terminal failures never reclaim bytes.""" + await self._profile(operation, None) + charge = await self._session.scalar(select(SubmissionSourceCharge).where( + SubmissionSourceCharge.operation_id == operation.id, + ).with_for_update().execution_options(populate_existing=True)) + if (charge is None or operation.provider_generation is None or operation.raw_byte_count is None + or operation.raw_byte_count > charge.reserved_bytes + or (charge.declared_raw_bytes is not None and charge.declared_raw_bytes != operation.raw_byte_count)): + raise SubmissionSourceCapacityConflict("source_sealed_charge_mismatch") + if charge.state == "sealed": + if charge.accounted_bytes != operation.raw_byte_count: + raise SubmissionSourceCapacityConflict("source_sealed_charge_mismatch") + return + charge.state, charge.accounted_bytes = "sealed", operation.raw_byte_count + charge.sealed_at = func.clock_timestamp() + await self._session.flush() diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py index 4e5642f65..db1f9fd4a 100644 --- a/backend/app/modules/artifacts/intake/models.py +++ b/backend/app/modules/artifacts/intake/models.py @@ -77,3 +77,49 @@ class SubmissionIntakeOperation(Base): terminal_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) failure_code: Mapped[str | None] = mapped_column(String(100)) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) + + +class SubmissionSourceCapacityProfile(Base): + """One explicit source-byte allocation shared by namespace writers.""" + + __tablename__ = "submission_source_capacity_profiles" + __table_args__ = ( + ForeignKeyConstraint(["namespace_id", "namespace_fingerprint"], + ["artifact_storage_namespaces.id", "artifact_storage_namespaces.namespace_fingerprint"], + name="fk_submission_source_capacity_namespace"), + CheckConstraint("maximum_total_bytes>0 and (maximum_project_bytes is null or maximum_project_bytes>0) " + "and (maximum_producer_bytes is null or maximum_producer_bytes>0) " + "and (maximum_task_bytes is null or maximum_task_bytes>0)", name="positive_limits"), + CheckConstraint("configuration_sha256 ~ '^sha256:[0-9a-f]{64}$'", name="configuration_digest"), + ) + + namespace_id: Mapped[str] = mapped_column(String(20), primary_key=True) + namespace_fingerprint: Mapped[str] = mapped_column(String(71)) + maximum_total_bytes: Mapped[int] = mapped_column(BigInteger) + maximum_project_bytes: Mapped[int | None] = mapped_column(BigInteger) + maximum_producer_bytes: Mapped[int | None] = mapped_column(BigInteger) + maximum_task_bytes: Mapped[int | None] = mapped_column(BigInteger) + configuration_sha256: Mapped[str] = mapped_column(String(71)) + + +class SubmissionSourceCharge(Base): + """Physical source obligation, retained independently of command outcome.""" + + __tablename__ = "submission_source_charges" + __table_args__ = ( + ForeignKeyConstraint(["operation_id"], ["submission_intake_operations.id"], + name="fk_submission_source_charge_operation"), + CheckConstraint("reserved_bytes>0 and accounted_bytes>0 and accounted_bytes<=reserved_bytes", + name="positive_charge"), + CheckConstraint("declared_raw_bytes is null or declared_raw_bytes=reserved_bytes", name="declared_reservation"), + CheckConstraint("state in ('reserved','sealed')", name="charge_state"), + CheckConstraint("(state='reserved' and accounted_bytes=reserved_bytes and sealed_at is null) " + "or (state='sealed' and sealed_at is not null)", name="charge_shape"), + ) + + operation_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True) + declared_raw_bytes: Mapped[int | None] = mapped_column(BigInteger) + reserved_bytes: Mapped[int] = mapped_column(BigInteger) + accounted_bytes: Mapped[int] = mapped_column(BigInteger) + state: Mapped[str] = mapped_column(String(20)) + sealed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py index e5c258400..7cb07acdc 100644 --- a/backend/app/modules/artifacts/intake/repository.py +++ b/backend/app/modules/artifacts/intake/repository.py @@ -18,8 +18,10 @@ from app.core.identifiers import new_record_id from app.modules.artifacts.api.submission_intake import ( SealedSubmissionSource, SubmissionIntakeMetadata, SubmissionSourceLocation, + SubmissionSourceCapacityLimits, ) from app.modules.artifacts.intake.models import SubmissionIntakeOperation +from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity from app.modules.artifacts.models import ArtifactStorageNamespace from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest @@ -35,6 +37,7 @@ class SubmissionIntakeRepository: def __init__(self, session: AsyncSession, tasks: IntakeTaskCustodyPort) -> None: self._session = session self._tasks = tasks + self._capacity = SubmissionSourceCapacity(session) def _require_transaction(self) -> None: if not self._session.in_transaction() or self._session.in_nested_transaction(): @@ -44,8 +47,9 @@ async def reserve( self, *, metadata: SubmissionIntakeMetadata, actor_id: UUID, identity_link_id: UUID, idempotency_key: UUID, maximum_raw_bytes: int, upload_deadline_at: datetime, lease_expires_at: datetime, + capacity_limits: SubmissionSourceCapacityLimits, declared_raw_bytes: int | None, ) -> SubmissionIntakeOperation: - """Reserve metadata custody only; callers must still perform full T1 admission.""" + """Reserve command and physical bytes; callers still own AUTH and full T1 admission.""" self._require_transaction() metadata = SubmissionIntakeMetadata.model_validate(metadata) operation_id = new_record_id() @@ -77,6 +81,7 @@ async def reserve( self._session.add(row) await self._session.flush() await self._session.refresh(row) + await self._capacity.reserve(row, limits=capacity_limits, declared_raw_bytes=declared_raw_bytes) return row async def _lock(self, operation_id: UUID) -> SubmissionIntakeOperation: @@ -124,6 +129,7 @@ async def seal(self, operation_id: UUID, lease_id: UUID, generation: int, row.state, row.lease_expires_at = "pre_checking", lease_expires_at await self._session.flush() await self._session.refresh(row) + await self._capacity.seal(row) return SealedSubmissionSource( location=SubmissionSourceLocation( operation_id=operation_id, namespace_id=row.namespace_id, diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index f3c193b7d..ac8d237e8 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -935,6 +935,7 @@ SUBMISSION_INTAKE_TARGETS = frozenset({ "backend/app/modules/artifacts/api/submission_intake.py", "backend/app/modules/artifacts/intake/models.py", + "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", "backend/app/modules/tasks/intake_custody.py", diff --git a/backend/scripts/identifier_inventory.py b/backend/scripts/identifier_inventory.py index 862001922..20a26b3ca 100644 --- a/backend/scripts/identifier_inventory.py +++ b/backend/scripts/identifier_inventory.py @@ -20,6 +20,8 @@ GENERATION_CLASSIFICATION_FORMAT = "workstream-uuid-generation-classifications-1" GENERATION_CLASSIFICATIONS = "identifier_generation_classifications.json" SEMANTIC_KEYS = { + "submission_source_capacity_profiles": ("ART namespace-owned source allocation", ("namespace_id",)), + "submission_source_charges": ("intake-operation-owned physical obligation", ("operation_id",)), "submission_dispatches": ("submission-owned original dispatch receipt", ("submission_id",)), "submission_binding_receipts": ("admission-owned binding authority receipt", ("admission_id",)), "review_packet_guide_items": ( diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 37b8d1cc5..5a7cd20a5 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -13,7 +13,7 @@ from app.adapters.tasks import task_submission_context_port from app.core.identifiers import new_record_id -from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable from app.modules.tasks.intake_custody import IntakeTaskCustody @@ -31,7 +31,12 @@ def repository(session): @pytest.fixture -async def intake(tmp_path, isolated_database_env): +def capacity_limits(request): + return getattr(request, "param", SubmissionSourceCapacityLimits(maximum_total_bytes=1_000_000)) + + +@pytest.fixture +async def intake(tmp_path, isolated_database_env, capacity_limits): engine = create_async_engine(isolated_database_env) factory = async_sessionmaker(engine, expire_on_commit=False) try: @@ -47,17 +52,19 @@ async def intake(tmp_path, isolated_database_env): task=str(task), assignment=str(assignment), project=str(plan.lineage.project_id), actor=str(actor.actor_profile_id), )) - yield SimpleNamespace(engine=engine, factory=factory, actor=actor, task=task, assignment=assignment) + yield SimpleNamespace(engine=engine, factory=factory, actor=actor, task=task, assignment=assignment, + capacity_limits=capacity_limits) finally: await engine.dispose() -async def reserve(intake, session, *, key=None): +async def reserve(intake, session, *, key=None, declared_raw_bytes=None): now = datetime.now(UTC) return await repository(session).reserve( metadata=SubmissionIntakeMetadata(task_id=intake.task, assignment_id=intake.assignment), actor_id=intake.actor.actor_profile_id, identity_link_id=intake.actor.identity_link_id, idempotency_key=key or new_record_id(), maximum_raw_bytes=1024, + capacity_limits=intake.capacity_limits, declared_raw_bytes=declared_raw_bytes, upload_deadline_at=now + timedelta(minutes=5), lease_expires_at=now + timedelta(minutes=1), ) @@ -97,6 +104,7 @@ async def test_reservation_rollback_leaves_no_pointer_or_operation(intake): await session.rollback() async with intake.factory() as session: assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 0 + assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 0 assert await session.scalar(text( "SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id" ), {"id": intake.task}) is None @@ -147,6 +155,7 @@ async def test_expiry_can_only_abandon_and_cannot_resume(intake): assert await repository(session).abandon_expired(operation) async with intake.factory.begin() as session: assert not await repository(session).abandon_expired(operation) + assert await session.scalar(text("SELECT sum(accounted_bytes) FROM submission_source_charges")) == 1024 replacement = await reserve(intake, session) assert replacement.id != str(operation) with pytest.raises(DBAPIError, match="terminal intake is immutable"): @@ -235,34 +244,37 @@ async def test_recorded_source_identity_is_immutable(intake): async def test_intake_model_matches_installed_schema(isolated_database_env): from sqlalchemy import inspect - from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from app.modules.artifacts.intake.models import ( + SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge, + ) engine = create_async_engine(isolated_database_env) try: async with engine.connect() as connection: def compare(sync): inspector = inspect(sync) - table = SubmissionIntakeOperation.__table__ - assert { - (c["name"], str(c["type"].compile(dialect=sync.dialect)), c["nullable"]) - for c in inspector.get_columns(table.name) - } == { - (c.name, str(c.type.compile(dialect=sync.dialect)), c.nullable) - for c in table.columns - } - assert { - (tuple(f["constrained_columns"]), f["referred_table"], tuple(f["referred_columns"])) - for f in inspector.get_foreign_keys(table.name) - } == { - (tuple(f.column_keys), f.referred_table.name, tuple(e.column.name for e in f.elements)) - for f in table.foreign_key_constraints - } - assert {c["name"] for c in inspector.get_check_constraints(table.name)} == { - c.name for c in table.constraints if c.__class__.__name__ == "CheckConstraint" - } - assert {i["name"] for i in inspector.get_indexes(table.name) if not i.get("duplicates_constraint")} == { - i.name for i in table.indexes - } + for owner in (SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge): + table = owner.__table__ + assert { + (c["name"], str(c["type"].compile(dialect=sync.dialect)), c["nullable"]) + for c in inspector.get_columns(table.name) + } == { + (c.name, str(c.type.compile(dialect=sync.dialect)), c.nullable) + for c in table.columns + } + assert { + (tuple(f["constrained_columns"]), f["referred_table"], tuple(f["referred_columns"])) + for f in inspector.get_foreign_keys(table.name) + } == { + (tuple(f.column_keys), f.referred_table.name, tuple(e.column.name for e in f.elements)) + for f in table.foreign_key_constraints + } + assert {c["name"] for c in inspector.get_check_constraints(table.name)} == { + c.name for c in table.constraints if c.__class__.__name__ == "CheckConstraint" + } + assert {i["name"] for i in inspector.get_indexes(table.name) if not i.get("duplicates_constraint")} == { + i.name for i in table.indexes + } await connection.run_sync(compare) finally: await engine.dispose() @@ -334,3 +346,194 @@ async def test_sql_rejects_malformed_command_selectors_even_with_matching_digest "UPDATE workstream_tasks SET active_submission_operation_id=:operation WHERE id=:task" ), {"operation": UUID(row.id), "task": intake.task}) await session.execute(SubmissionIntakeOperation.__table__.insert().values(**candidate)) + from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity + stored = await session.get(SubmissionIntakeOperation, values["id"]) + await SubmissionSourceCapacity(session).reserve( + stored, limits=intake.capacity_limits, declared_raw_bytes=None, + ) + + +@pytest.mark.parametrize("declared", [None, 100]) +async def test_source_reservation_becomes_exact_bytes_only_after_sealing(intake, declared): + from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + + async with intake.factory.begin() as session: + row = await reserve(intake, session, declared_raw_bytes=declared) + operation, lease = UUID(row.id), UUID(row.lease_id) + charge = await session.get(SubmissionSourceCharge, row.id) + assert charge.accounted_bytes == (1024 if declared is None else 100) + async with intake.factory.begin() as session: + await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + async with intake.factory.begin() as session: + deadline = datetime.now(UTC) + timedelta(minutes=2) + await repository(session).seal(operation, lease, 1, provider_generation="exact-source", + pre_deadline_at=deadline, lease_expires_at=deadline) + async with intake.factory.begin() as session: + stored = await session.get(SubmissionIntakeOperation, str(operation)) + charge = await SubmissionSourceCapacity(session).reserve( + stored, limits=intake.capacity_limits, declared_raw_bytes=declared, + ) + assert (charge.state, charge.accounted_bytes) == ("sealed", 100) + assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 1 + + +async def test_declared_length_mismatch_cannot_record_eof_or_free_its_charge(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session, declared_raw_bytes=101) + operation, lease = UUID(row.id), UUID(row.lease_id) + with pytest.raises(DBAPIError, match="declared size mismatch"): + async with intake.factory.begin() as session: + await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + async with intake.factory.begin() as session: + await repository(session).terminalize(operation, lease, 1, state="failed", failure_code="length_mismatch") + async with intake.factory() as session: + assert await session.scalar(text("SELECT sum(accounted_bytes) FROM submission_source_charges")) == 101 + assert await session.scalar(text("SELECT raw_sha256 FROM submission_intake_operations")) is None + for statement in ("DELETE FROM submission_source_charges", "TRUNCATE submission_source_charges"): + with pytest.raises(DBAPIError, match="require confirmed cleanup"): + async with intake.factory.begin() as session: + await session.execute(text(statement)) + + +@pytest.mark.parametrize("capacity_limits", [ + SubmissionSourceCapacityLimits(maximum_total_bytes=150), + SubmissionSourceCapacityLimits(maximum_total_bytes=2000, maximum_project_bytes=150), + SubmissionSourceCapacityLimits(maximum_total_bytes=2000, maximum_producer_bytes=150), + SubmissionSourceCapacityLimits(maximum_total_bytes=2000, maximum_task_bytes=150), +], indirect=True) +async def test_each_enabled_source_quota_counts_failed_objects(intake): + from app.modules.artifacts.intake.capacity import SubmissionSourceCapacityConflict + + async with intake.factory.begin() as session: + row = await reserve(intake, session, declared_raw_bytes=100) + async with intake.factory.begin() as session: + await repository(session).terminalize(UUID(row.id), UUID(row.lease_id), 1, + state="failed", failure_code="upload_uncertain") + with pytest.raises(SubmissionSourceCapacityConflict, match="source_capacity_exhausted"): + async with intake.factory.begin() as session: + await reserve(intake, session, declared_raw_bytes=100) + async with intake.factory() as session: + assert await session.scalar(text("SELECT sum(accounted_bytes) FROM submission_source_charges")) == 100 + assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 1 + + +async def test_equal_content_sources_keep_distinct_physical_charges(intake): + operations = [] + for _ in range(2): + async with intake.factory.begin() as session: + row = await reserve(intake, session, declared_raw_bytes=100) + operation, lease = UUID(row.id), UUID(row.lease_id) + operations.append(operation) + async with intake.factory.begin() as session: + await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + async with intake.factory.begin() as session: + deadline = datetime.now(UTC) + timedelta(minutes=2) + await repository(session).seal(operation, lease, 1, provider_generation=f"generation-{operation}", + pre_deadline_at=deadline, lease_expires_at=deadline) + await repository(session).terminalize(operation, lease, 1, state="rejected", failure_code="pre_failed") + assert operations[0] != operations[1] + async with intake.factory() as session: + counts = (await session.execute(text( + "SELECT count(*),sum(accounted_bytes) FROM submission_source_charges" + ))).one() + assert tuple(counts) == (2, 200) + + +@pytest.mark.parametrize("capacity_limits", [SubmissionSourceCapacityLimits(maximum_total_bytes=150)], indirect=True) +async def test_source_quota_serializes_distinct_tasks(intake): + from app.modules.artifacts.intake.capacity import SubmissionSourceCapacityConflict + + async with intake.factory() as session: + project = await session.scalar(text("SELECT project_id FROM workstream_tasks WHERE id=:id"), {"id": intake.task}) + other = SimpleNamespace(**{**vars(intake), "task": new_record_id(), "assignment": new_record_id()}) + async with intake.engine.begin() as connection: + await seed_started_task_for_artifact_test(connection, dict( + task=str(other.task), assignment=str(other.assignment), project=str(project), actor=str(intake.actor.actor_profile_id), + )) + async with intake.factory() as first, intake.factory() as second: + await first.begin() + await second.begin() + await reserve(intake, first, declared_raw_bytes=100) + pid = await second.scalar(text("SELECT pg_backend_pid()")) + contender = asyncio.create_task(reserve(other, second, declared_raw_bytes=100)) + try: + async with intake.factory() as observer: + async with asyncio.timeout(10): + while not await observer.scalar(text("SELECT cardinality(pg_blocking_pids(:pid))>0"), {"pid": pid}): + if contender.done(): + await contender + pytest.fail("second task bypassed the shared capacity lock") + await asyncio.sleep(0.02) + query = await observer.scalar(text("SELECT query FROM pg_stat_activity WHERE pid=:pid"), {"pid": pid}) + assert "submission_source_capacity_profiles" in query + await first.commit() + with pytest.raises(SubmissionSourceCapacityConflict, match="source_capacity_exhausted"): + await contender + finally: + if not contender.done(): + contender.cancel() + await asyncio.gather(contender, return_exceptions=True) + await first.rollback() + await second.rollback() + async with intake.factory() as session: + assert await session.scalar(text("SELECT sum(accounted_bytes) FROM submission_source_charges")) == 100 + assert await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": other.task}) is None + + +@pytest.mark.parametrize("capacity_limits", [SubmissionSourceCapacityLimits(maximum_total_bytes=150)], indirect=True) +async def test_sql_cannot_bypass_source_quota(intake): + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + + async with intake.factory.begin() as session: + row = await reserve(intake, session, declared_raw_bytes=100) + values = {c.name: getattr(row, c.name) for c in row.__table__.columns} + async with intake.factory.begin() as session: + await repository(session).terminalize(UUID(row.id), UUID(row.lease_id), 1, + state="failed", failure_code="upload_uncertain") + new_id = new_record_id() + values.update(id=str(new_id), lease_id=str(new_record_id()), idempotency_key=str(new_record_id()), + object_ref=f"submission-source/v1/{new_id}/bundle.zip") + with pytest.raises(DBAPIError, match="submission source capacity exhausted"): + async with intake.factory.begin() as session: + await session.execute(text("UPDATE workstream_tasks SET active_submission_operation_id=:op WHERE id=:task"), + {"op": new_id, "task": intake.task}) + await session.execute(SubmissionIntakeOperation.__table__.insert().values(**values)) + await session.execute(SubmissionSourceCharge.__table__.insert().values( + operation_id=str(new_id), declared_raw_bytes=100, reserved_bytes=100, accounted_bytes=100, state="reserved", + )) + + +async def test_capacity_configuration_cannot_be_replaced_or_truncated(intake): + from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity, SubmissionSourceCapacityConflict + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + + async with intake.factory.begin() as session: + row = await reserve(intake, session) + for statement in ( + "UPDATE submission_source_capacity_profiles SET maximum_total_bytes=maximum_total_bytes+1", + "DELETE FROM submission_source_capacity_profiles", + "TRUNCATE submission_source_capacity_profiles", + ): + with pytest.raises(DBAPIError, match="capacity configuration is immutable"): + async with intake.factory.begin() as session: + await session.execute(text(statement)) + with pytest.raises(SubmissionSourceCapacityConflict, match="configuration_mismatch"): + async with intake.factory.begin() as session: + operation = await session.get(SubmissionIntakeOperation, row.id) + await SubmissionSourceCapacity(session).reserve( + operation, limits=SubmissionSourceCapacityLimits(maximum_total_bytes=2_000_000), declared_raw_bytes=None, + ) + + +@pytest.mark.parametrize("declared", [True, 0, -1, 1025]) +async def test_invalid_declared_size_rolls_back_all_custody(intake, declared): + from app.modules.artifacts.intake.capacity import SubmissionSourceCapacityConflict + + with pytest.raises(SubmissionSourceCapacityConflict, match="source_declared_size_invalid"): + async with intake.factory.begin() as session: + await reserve(intake, session, declared_raw_bytes=declared) + async with intake.factory() as session: + assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 0 + assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 0 + assert await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": intake.task}) is None diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index cdac78941..92d4b768b 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,13 +23,15 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "d787347d49ee27b4b8dca0da9ca254f40703da6b4445644d38271c5a40a6b2a2" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "7b109141c3a6f4eccbf24dd6c68d3fa75e709c1ed8d110cc2546e972a65537c4" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", "iso_4217_currency_codes", ) RESETTABLE_TEST_TABLES = ( + "submission_source_capacity_profiles", + "submission_source_charges", "submission_intake_operations", "joint_lifecycle_release_control", "joint_lifecycle_transitions", @@ -164,6 +166,9 @@ "workstream_tasks", ) TRUNCATE_GUARDED_TABLES = ( + "submission_intake_operations", + "submission_source_capacity_profiles", + "submission_source_charges", "artifact_provider_activations", "artifact_provider_probe_results", "artifact_task_import_sources", diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index 28eb5821f..c3b1125b6 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2764,6 +2764,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ target = "backend/app/modules/artifacts/api/submission_intake.py" additions = { target, "backend/app/modules/artifacts/intake/models.py", + "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", "backend/app/modules/tasks/intake_custody.py", diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index b53c107ea..9e973a3ed 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -110,8 +110,9 @@ bound to issuer/subject, not email; signed email is not proof of mailbox verific The [single-request submission specification](spec_submission_execution.md) is the approved target for [WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). Its hidden owner boundaries define immutable command/source values and durable -foreground intake custody with a matching TASK pointer and source/lease fences. -Physical reservation, streaming custody, one-session PRE, accepted handoff, +foreground intake custody with a matching TASK pointer, source/lease fences and +per-operation physical source reservations under explicit limits. Bounded +streaming/cleanup custody, one-session PRE, accepted handoff, finalization and client cutover remain planned; the active API still uses preparation followed by admission-consuming submission. From 832f9304e862530abfa7d30edcdb45fe913d30e0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 18:41:48 +0100 Subject: [PATCH 010/513] Stream bounded submission parts into immutable versioned sources --- .ci/behavior-ownership/partition.v1.json | 6 +- .commitrail/INDEX.md | 2 +- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 7 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 34 +++ .../app/adapters/artifacts/s3_compatible.py | 267 ++++++++++++++++++ backend/app/interfaces/artifacts.py | 49 ++++ .../artifacts/api/submission_intake.py | 68 ++++- .../app/modules/artifacts/intake/streaming.py | 98 +++++++ backend/scripts/behavior_ownership.py | 1 + .../test_submission_intake_contracts.py | 125 ++++++++ backend/tests/test_artifact_architecture.py | 37 ++- backend/tests/test_behavior_ownership.py | 1 + backend/tests/test_s3_artifact_store.py | 188 +++++++++++- docs/roadmap_status.md | 6 +- 14 files changed, 871 insertions(+), 18 deletions(-) create mode 100644 backend/app/modules/artifacts/intake/streaming.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index fe48f5708..df9f5539c 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -608,6 +608,10 @@ "group": "artifacts", "target": "backend/app/modules/artifacts/intake/repository.py" }, + { + "group": "artifacts", + "target": "backend/app/modules/artifacts/intake/streaming.py" + }, { "group": "artifacts", "target": "backend/app/modules/artifacts/metrics.py" @@ -2617,7 +2621,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "f8f9f1525d11ac23ce78f7dd22ea7258bee8417adece74ca9c205a3b0d901864", + "authority_digest": "a2f87870061a79753411f0d4d1ff941e830e00a4168af1f001f4910ba8f131b5", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index d943394f1..ad197fd30 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | One-request command/source contracts, hidden foreground custody and physical source reservations; next streaming/cleanup custody, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Hidden foreground custody, physical source reservations and bounded S3-compatible receipt; next durable upload/cleanup orchestration, local/AWS source qualification, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 06d5d1271..4e29bd1b0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -11,8 +11,11 @@ authorize merge or production deployment. [WS-SUBMIT-001-01](WS-SUBMIT-001-01.md) establishes exact command/source value contracts and hidden pre-handoff database custody with TASK/source/lease guards. Per-operation physical source reservations are implemented with explicit limits. -Provider I/O, confirmed physical reclamation, -accepted authority and orchestration remain to implement. +Hidden S3-compatible source methods and a backpressured receiver now provide +bounded parts, conditional completion, exact-version reads and scoped uncertain +upload discovery. Durable upload receipt orchestration, local source support, +confirmed physical reclamation, AWS qualification and accepted authority remain +to implement and integrate. The existing public flow stays active until coordinated cutover. ## Delivery sequence diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index df36c84b3..2818e01ad 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -108,6 +108,39 @@ provider writes, route or AUTH authority. Proof must cover simultaneous spending rollback, same-content distinct operations, declared-size equality, sealed-byte conversion and failed/expired charge retention on real PostgreSQL. +## Streaming provider stage + +Extend `interfaces/artifacts.py`, the existing S3-compatible and local adapters, +ART intake values/receipt persistence and their existing focused suites. Keep +composition through the current ArtifactStore factory. Submission keys remain +operation-derived; generic committed SHA-object consumers keep their protections. +Explicit upload bounds and deadline accompany typed handles and ordered part +receipts. Commit the handle before parts and EOF/completion intent before external +completion. Provider calls never hold database locks. Receipt values alone grant +no authorization. No public cutover occurs before root orchestration is complete. + +Verification covers bounded backpressure, lost begin/complete acknowledgement, +conditional completion, exact-version read/delete, scoped handle reconciliation, +and retained charge until confirmed cleanup. Use real pinned MinIO for protocol +claims; do not treat existing AWS activation as qualification of new capabilities. +Update the architecture guard's obsolete blanket multipart ban with exact scoped +capability restrictions, preserving copy/ACL/bulk-delete prohibitions. This stage +has the same L0 risk and reviewer routing as the full change. + +The receiver holds at most two configured parts plus one 1 MiB ingress chunk, +separate from SDK/TLS overhead. It awaits each part before reading further and +enforces explicit idle and immutable aggregate upload deadlines. Part size is an +explicit 5–16 MiB supported input, with one in flight; neither part size nor idle +timeout has a deployment default. Provider source methods bind the claimed +namespace and operation key, require versioning, complete with `IfNoneMatch`, +and verify raw bytes when resolving uncertain completion. Lost initiation can +be enumerated only at the already-owned key. Abort acknowledgement never releases +a charge. Existing AWS activation remains insufficient for this new surface. + +The methods are hidden prerequisites. Durable handle/completion persistence, +local source support, exact cleanup authority/reclamation and AWS qualification +remain required before the public flow can use them. + ## Acceptance criteria - [x] Exact metadata round-trip and identity changes for each command selector. @@ -146,6 +179,7 @@ conversion and failed/expired charge retention on real PostgreSQL. | Foreground custody and retained-data upgrade | `pytest tests/artifacts/test_submission_intake_custody.py 'tests/test_alembic.py::test_preceding_head_upgrades_to_current_without_recreation[0068_issuer_profile_email]' tests/test_alembic.py::test_repeated_upgrade_head_preserves_current_database tests/tasks/submission_dispatch/test_migration.py -q` through the isolated PostgreSQL 16 runner | 21 passed; isolated database and role cleanup confirmed | Pre-handoff persistence only; no provider, PRE, acceptance or public-route proof | | Physical source accounting | `pytest tests/artifacts/test_submission_intake_custody.py -q` through isolated PostgreSQL 16 | 34 passed on the capacity-stage working tree; cleanup confirmed | No provider bytes written or cleanup/reclamation claim | | Capacity-stage static ownership | UUID inventory, behavior partition, semantic lane catalogue and module boundary tests | 254 passed; ruff passed | Final integrated suite still required | +| Bounded receive | Contract/stream tests including provider backpressure, byte bounds, idle expiry and in-flight cancellation | 70 passed; ruff passed | Transport/server buffers and real provider proof remain separate | | Protected target partition | `pytest tests/test_behavior_ownership.py -q` | 170 passed | Exact added paths only; no relaxed selection | | Model registration | UUID inventory and protected module-boundary tests | Both passed | No new cross-owner private imports | diff --git a/backend/app/adapters/artifacts/s3_compatible.py b/backend/app/adapters/artifacts/s3_compatible.py index 318d34132..120a1b9d5 100644 --- a/backend/app/adapters/artifacts/s3_compatible.py +++ b/backend/app/adapters/artifacts/s3_compatible.py @@ -68,8 +68,10 @@ ArtifactObjectHead, ArtifactObjectMissingError, ArtifactOperationConflictError, + ArtifactPreconditionFailedError, ArtifactProviderActivationGuard, ArtifactProviderOperationEvidence, + ArtifactProviderLiveProofRequiredError, ArtifactPutObservation, ArtifactPutResult, ArtifactRangeInvalidError, @@ -84,6 +86,14 @@ from app.interfaces.external_services import ExternalServiceAdapterIdentity from app.modules.artifacts.preparation import HARD_MAXIMUM_ARTIFACT_BYTES from app.modules.artifacts.sources import ArtifactCommitment, CommittedArtifactSource +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, + SubmissionSourceCompletion, + SubmissionSourceLocation, + SubmissionSourcePart, + SubmissionSourceUpload, + SubmissionSourceUploadIntent, +) _IDENTITY = ExternalServiceAdapterIdentity(ARTIFACT_STORE_CAPABILITY_KEY, "s3_compatible") @@ -554,6 +564,263 @@ def close(self) -> None: self._initialized = False self._session = None + def _source_key(self, location: SubmissionSourceLocation) -> str: + """Accept only this claimed namespace and the operation-derived ZIP key.""" + self._require_initialized() + location = SubmissionSourceLocation.model_validate(location) + if ( + location.namespace_fingerprint != self._expected_namespace_fingerprint() + or location.provider_profile != self._namespace_identity.provider_profile + ): + raise ArtifactOperationConflictError("submission source namespace mismatch") + # Existing AWS activation qualifies SHA-object put/read only. Extend its + # live-proof contract before allowing the new version/multipart surface. + if self._provider_profile == "aws_s3": + raise ArtifactProviderLiveProofRequiredError( + "submission source capability requires provider qualification" + ) + return f"{self._private_prefix}/{location.object_ref}" + + @asynccontextmanager + async def _source_client( + self, location: SubmissionSourceLocation, + evidence: ArtifactProviderOperationEvidence, + deadline: datetime.datetime | None = None, + ) -> AsyncIterator[Any]: + """Bound a source request and suppress provider details on every failure.""" + self._source_key(location) + budget = self._operation_total_timeout_seconds + if deadline is not None: + budget = min(budget, (deadline - datetime.datetime.now(datetime.UTC)).total_seconds()) + if budget <= 0: + raise ArtifactStoreUnavailableError("submission upload deadline expired") + try: + async with asyncio.timeout(budget): + await self._require_activation_for_sdk_call(evidence) + async with self._client() as client: + await self._require_activation_for_sdk_call(evidence) + yield client + except ClientError as error: + status = _provider_http_status(error) + code = _provider_error_code(error) + if status in {409, 412} and code in _PRECONDITION_ERROR_CODES: + raise ArtifactPreconditionFailedError("submission source creation conflicted") from None + if status == 404 and code in _MISSING_ERROR_CODES | {"NoSuchVersion", "NoSuchUpload"}: + raise ArtifactObjectMissingError("submission source is missing") from None + raise ArtifactStoreUnavailableError("submission source provider operation failed") from None + except ArtifactStoreError: + raise + except (TimeoutError, BotoCoreError, OSError): + raise ArtifactStoreUnavailableError("submission source provider operation failed") from None + + async def begin_source_upload( + self, intent: SubmissionSourceUploadIntent, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SubmissionSourceUpload: + """Return a handle without sending bytes; caller must durably record it.""" + intent = SubmissionSourceUploadIntent.model_validate(intent) + evidence = operation_evidence or ArtifactProviderOperationEvidence() + async with self._source_client(intent.location, evidence, intent.upload_deadline_at) as client: + versioning = await client.get_bucket_versioning(Bucket=self._bucket) + if versioning.get("Status") != "Enabled": + raise ArtifactConfigurationError("submission source requires bucket versioning") + await self._require_activation_for_sdk_call(evidence) + response = await client.create_multipart_upload( + Bucket=self._bucket, Key=self._source_key(intent.location), + ContentType="application/zip", + Metadata={"operation-id": str(intent.location.operation_id), + "upload-fence": str(intent.upload_fence)}, + ) + handle = response.get("UploadId") + if not isinstance(handle, str) or not 1 <= len(handle) <= 2048: + raise ArtifactIntegrityError("submission upload handle is invalid") + return SubmissionSourceUpload(intent=intent, provider_upload_id=handle) + + async def upload_source_part( + self, upload: SubmissionSourceUpload, number: int, data: bytes, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SubmissionSourcePart: + """Transmit one bounded part, without collecting or retrying the archive.""" + upload = SubmissionSourceUpload.model_validate(upload) + intent = upload.intent + if ( + type(number) is not int or not 1 <= number <= 100 + or type(data) is not bytes or not 1 <= len(data) <= intent.part_bytes + or (number - 1) * intent.part_bytes + len(data) > intent.maximum_raw_bytes + or (intent.declared_raw_bytes is not None + and (number - 1) * intent.part_bytes + len(data) > intent.declared_raw_bytes) + ): + raise ArtifactInputMismatchError("submission part violates upload bounds") + evidence = operation_evidence or ArtifactProviderOperationEvidence() + async with self._source_client(intent.location, evidence, intent.upload_deadline_at) as client: + response = await client.upload_part( + Bucket=self._bucket, Key=self._source_key(intent.location), + UploadId=upload.provider_upload_id, PartNumber=number, + Body=data, ContentLength=len(data), + ) + etag = response.get("ETag") + if not isinstance(etag, str) or not 1 <= len(etag) <= 1024: + raise ArtifactIntegrityError("submission part receipt is invalid") + return SubmissionSourcePart(number=number, byte_count=len(data), provider_etag=etag) + + async def discover_source_uploads( + self, intent: SubmissionSourceUploadIntent, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> tuple[SubmissionSourceUpload, ...]: + """Reconcile lost initiation only within this operation's exact owned key. + + A valid operation initiates once. Refuse an anomalous unbounded backlog, + rather than reporting partial enumeration as confirmed absence. + """ + intent = SubmissionSourceUploadIntent.model_validate(intent) + evidence = operation_evidence or ArtifactProviderOperationEvidence() + key = self._source_key(intent.location) + async with self._source_client(intent.location, evidence) as client: + response = await client.list_multipart_uploads( + Bucket=self._bucket, Prefix=key, MaxUploads=100, + ) + if response.get("IsTruncated") is not False: + raise ArtifactStoreUnavailableError("submission upload enumeration is incomplete") + rows = response.get("Uploads", []) + if not isinstance(rows, list) or len(rows) > 100: + raise ArtifactIntegrityError("submission upload enumeration is invalid") + handles = [] + for row in rows: + if not isinstance(row, dict) or row.get("Key") != key: + raise ArtifactIntegrityError("submission upload enumeration escaped its key") + handle = row.get("UploadId") + if not isinstance(handle, str) or not 1 <= len(handle) <= 2048 or handle in handles: + raise ArtifactIntegrityError("submission upload enumeration has invalid handles") + handles.append(handle) + return tuple(SubmissionSourceUpload(intent=intent, provider_upload_id=handle) for handle in handles) + + async def request_source_abort( + self, upload: SubmissionSourceUpload, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> None: + """Abort this handle; owner retains charges while late writes are possible.""" + upload = SubmissionSourceUpload.model_validate(upload) + evidence = operation_evidence or ArtifactProviderOperationEvidence() + try: + async with self._source_client(upload.intent.location, evidence) as client: + await client.abort_multipart_upload( + Bucket=self._bucket, Key=self._source_key(upload.intent.location), + UploadId=upload.provider_upload_id, + ) + except ArtifactObjectMissingError: + return + + async def complete_source_upload( + self, completion: SubmissionSourceCompletion, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SealedSubmissionSource: + """Create only; uncertain outcomes retain their upload and EOF ownership.""" + completion = SubmissionSourceCompletion.model_validate(completion) + upload = completion.upload + intent = upload.intent + evidence = operation_evidence or ArtifactProviderOperationEvidence() + async with self._source_client(intent.location, evidence, intent.upload_deadline_at) as client: + response = await client.complete_multipart_upload( + Bucket=self._bucket, Key=self._source_key(intent.location), + UploadId=upload.provider_upload_id, IfNoneMatch="*", + MultipartUpload={"Parts": [ + {"PartNumber": part.number, "ETag": part.provider_etag} + for part in completion.parts + ]}, + ) + # botocore parses the full response, including embedded errors on HTTP200. + generation = response.get("VersionId") + if not isinstance(generation, str) or generation == "null" or not 1 <= len(generation) <= 2048: + raise ArtifactIntegrityError("submission completion lacks an immutable version") + source = SealedSubmissionSource( + location=intent.location, provider_generation=generation, + raw_sha256=completion.raw_sha256, raw_byte_count=completion.raw_byte_count, + sealed_upload_fence=intent.upload_fence, + ) + async with self._source_client(intent.location, evidence, intent.upload_deadline_at) as client: + observed = await client.head_object( + Bucket=self._bucket, Key=self._source_key(intent.location), VersionId=generation, + ) + self._check_source_response(source, observed) + return source + + @staticmethod + def _check_source_response(source: SealedSubmissionSource, response: Mapping[str, Any]) -> None: + """Bind a response to exact generation, count and upload provenance.""" + if ( + response.get("VersionId") != source.provider_generation + or type(response.get("ContentLength")) is not int + or response["ContentLength"] != source.raw_byte_count + or response.get("ContentType") != "application/zip" + or response.get("Metadata") != { + "operation-id": str(source.location.operation_id), + "upload-fence": str(source.sealed_upload_fence), + } + ): + raise ArtifactIntegrityError("submission source response violates custody") + + async def observe_source_upload( + self, completion: SubmissionSourceCompletion, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SealedSubmissionSource | None: + """Recover an uncertain completion only by reading its exact version.""" + completion = SubmissionSourceCompletion.model_validate(completion) + intent = completion.upload.intent + evidence = operation_evidence or ArtifactProviderOperationEvidence() + try: + async with self._source_client(intent.location, evidence) as client: + response = await client.head_object( + Bucket=self._bucket, Key=self._source_key(intent.location), + ) + except ArtifactObjectMissingError: + return None + generation = response.get("VersionId") + if not isinstance(generation, str) or generation == "null" or not 1 <= len(generation) <= 2048: + raise ArtifactIntegrityError("submission observation lacks an immutable version") + source = SealedSubmissionSource( + location=intent.location, provider_generation=generation, + raw_sha256=completion.raw_sha256, raw_byte_count=completion.raw_byte_count, + sealed_upload_fence=intent.upload_fence, + ) + self._check_source_response(source, response) + # HEAD/ETag alone never establish trusted raw identity after uncertainty. + async for _ in self.open_source(source, operation_evidence=evidence): + pass + return source + + def open_source( + self, source: SealedSubmissionSource, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> AsyncIterator[bytes]: + """Read one immutable version; verify the original ZIP at stream exhaustion.""" + source = SealedSubmissionSource.model_validate(source) + self._source_key(source.location) + evidence = operation_evidence or ArtifactProviderOperationEvidence() + + async def iterate() -> AsyncIterator[bytes]: + digest = hashlib.sha256() + observed = 0 + async with self._source_client(source.location, evidence) as client: + response = await client.get_object( + Bucket=self._bucket, Key=self._source_key(source.location), + VersionId=source.provider_generation, + ) + async with response["Body"] as body: + self._check_source_response(source, response) + while True: + chunk = await body.read(min(self._buffer_bytes, source.raw_byte_count - observed + 1)) + if not chunk: + break + if type(chunk) is not bytes or observed + len(chunk) > source.raw_byte_count: + raise ArtifactIntegrityError("submission source exceeded exact size") + observed += len(chunk) + digest.update(chunk) + yield chunk + if observed != source.raw_byte_count or f"sha256:{digest.hexdigest()}" != source.raw_sha256: + raise ArtifactIntegrityError("submission source violates raw identity") + + return iterate() + async def put( self, source: CommittedArtifactSource, diff --git a/backend/app/interfaces/artifacts.py b/backend/app/interfaces/artifacts.py index 67c87326f..062b8bdc4 100644 --- a/backend/app/interfaces/artifacts.py +++ b/backend/app/interfaces/artifacts.py @@ -15,6 +15,13 @@ ExternalServiceAdapterIdentity, ) from app.modules.artifacts.sources import ArtifactCommitment, CommittedArtifactSource +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, + SubmissionSourceCompletion, + SubmissionSourcePart, + SubmissionSourceUpload, + SubmissionSourceUploadIntent, +) ARTIFACT_STORE_CAPABILITY_KEY = "artifact_store" @@ -367,6 +374,48 @@ class ArtifactProviderLiveProofRequiredError(ArtifactConfigurationError): class ArtifactStore(ExternalServiceAdapter, Protocol): """Immutable byte-provider capability used only by artifact orchestration.""" + async def begin_source_upload( + self, intent: SubmissionSourceUploadIntent, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SubmissionSourceUpload: + """Initiate an owned key; persist returned handle before sending parts.""" + + async def upload_source_part( + self, upload: SubmissionSourceUpload, number: int, data: bytes, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SubmissionSourcePart: + """Send one bounded part; the owner serializes parts and enforces total.""" + + async def complete_source_upload( + self, completion: SubmissionSourceCompletion, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SealedSubmissionSource: + """Conditionally complete a previously persisted EOF/completion intent.""" + + def open_source( + self, source: SealedSubmissionSource, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> AsyncIterator[bytes]: + """Read the exact authorized version with bounded raw identity verification.""" + + async def observe_source_upload( + self, completion: SubmissionSourceCompletion, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SealedSubmissionSource | None: + """Resolve a lost completion acknowledgement by exact provenance and bytes.""" + + async def discover_source_uploads( + self, intent: SubmissionSourceUploadIntent, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> tuple[SubmissionSourceUpload, ...]: + """Find unfinished handles only for one already-owned operation key.""" + + async def request_source_abort( + self, upload: SubmissionSourceUpload, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> None: + """Request scoped abort; acknowledgement alone never releases a charge.""" + async def put( self, source: CommittedArtifactSource, diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py index 6b014bbf5..54e43ab88 100644 --- a/backend/app/modules/artifacts/api/submission_intake.py +++ b/backend/app/modules/artifacts/api/submission_intake.py @@ -11,7 +11,7 @@ from typing import Annotated, Literal, Self from uuid import UUID -from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator, model_validator from app.core.hashing import canonical_json_hash from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES @@ -115,7 +115,7 @@ class SealedSubmissionSource(_IntakeValue): """ location: SubmissionSourceLocation - provider_generation: str = Field(min_length=1, repr=False) + provider_generation: str = Field(min_length=1, max_length=2048, repr=False) raw_sha256: Sha256 raw_byte_count: int = Field(ge=1, le=MAXIMUM_SUBMISSION_ZIP_BYTES) sealed_upload_fence: int = Field(ge=1) @@ -150,3 +150,67 @@ def configuration_sha256(self) -> str: "schema_version": "workstream.submission_source_capacity.v1", **self.model_dump(mode="json"), }) + + +class SubmissionSourceUploadIntent(_IntakeValue): + """Durably owned bounds before provider initiation; not write authority. + + The implementation supports one in-flight part of at most 16 MiB, separately + from the 1 MiB ingress/read ceiling and bounded SDK transport overhead. + Deployment must select a part size and deadline; neither has a default. + """ + + location: SubmissionSourceLocation + upload_fence: int = Field(ge=1) + maximum_raw_bytes: int = Field(ge=1, le=MAXIMUM_SUBMISSION_ZIP_BYTES) + declared_raw_bytes: int | None = Field(default=None, ge=1) + part_bytes: int = Field(ge=5 * 1024 * 1024, le=16 * 1024 * 1024) + idle_timeout_seconds: float = Field(gt=0, allow_inf_nan=False) + upload_deadline_at: AwareDatetime + + @model_validator(mode="after") + def bounded_declaration(self) -> Self: + """Reject an impossible declaration before sending provider requests.""" + if self.declared_raw_bytes is not None and self.declared_raw_bytes > self.maximum_raw_bytes: + raise ValueError("declared source length exceeds upload limit") + return self + + +class SubmissionSourceUpload(_IntakeValue): + """Opaque provider handle that the owner persists before sending parts.""" + + intent: SubmissionSourceUploadIntent + provider_upload_id: str = Field(min_length=1, max_length=2048, repr=False) + + +class SubmissionSourcePart(_IntakeValue): + """One bounded part receipt; ETag is a completion token, never raw SHA.""" + + number: int = Field(ge=1, le=100) + byte_count: int = Field(ge=1, le=16 * 1024 * 1024) + provider_etag: str = Field(min_length=1, max_length=1024, repr=False) + + +class SubmissionSourceCompletion(_IntakeValue): + """Exact EOF and ordered receipts committed before provider completion.""" + + upload: SubmissionSourceUpload + parts: tuple[SubmissionSourcePart, ...] = Field(min_length=1, max_length=100) + raw_sha256: Sha256 + raw_byte_count: int = Field(ge=1, le=MAXIMUM_SUBMISSION_ZIP_BYTES) + + @model_validator(mode="after") + def complete_receipt(self) -> Self: + """Require a contiguous, bounded multipart sequence and exact EOF count.""" + intent = self.upload.intent + if ( + self.raw_byte_count > intent.maximum_raw_bytes + or (intent.declared_raw_bytes is not None + and self.raw_byte_count != intent.declared_raw_bytes) + or sum(part.byte_count for part in self.parts) != self.raw_byte_count + or any(part.number != number for number, part in enumerate(self.parts, 1)) + or any(part.byte_count != intent.part_bytes for part in self.parts[:-1]) + or self.parts[-1].byte_count > intent.part_bytes + ): + raise ValueError("source completion does not match bounded EOF") + return self diff --git a/backend/app/modules/artifacts/intake/streaming.py b/backend/app/modules/artifacts/intake/streaming.py new file mode 100644 index 000000000..60476587f --- /dev/null +++ b/backend/app/modules/artifacts/intake/streaming.py @@ -0,0 +1,98 @@ +"""Bounded foreground ZIP receipt without an API scratch file. + +The owner persists operation/intent before initiation and the returned upload +handle before calling this function. The result is EOF/completion intent: it +must be committed under the live fence before calling complete_source_upload. +Errors leave physical ownership with that operation; this helper neither frees +capacity nor invents a successful abort after cancellation. +""" + +from collections.abc import AsyncIterator +import asyncio +from datetime import UTC, datetime +import hashlib + +from app.interfaces.artifacts import ( + ArtifactInputMismatchError, + ArtifactLimitExceededError, + ArtifactProviderOperationEvidence, + ArtifactStore, + ArtifactStoreUnavailableError, +) +from app.modules.artifacts.api.submission_intake import ( + SubmissionSourceCompletion, + SubmissionSourceUpload, +) + + +MAXIMUM_INGRESS_CHUNK_BYTES = 1024 * 1024 + + +async def receive_submission_source( + store: ArtifactStore, upload: SubmissionSourceUpload, chunks: AsyncIterator[bytes], *, + operation_evidence: ArtifactProviderOperationEvidence | None = None, +) -> SubmissionSourceCompletion: + """Count/hash raw bytes and await every part before reading more input. + + Application-owned memory is at most two configured parts (assembly plus + immutable in-flight bytes) and one ingress chunk. SDK/TLS overhead is separate. + Parts are sequential, with no application retry queue or whole-file spool. + The transport must provide chunks within its own published 1 MiB bound. + """ + upload = SubmissionSourceUpload.model_validate(upload) + remaining = (upload.intent.upload_deadline_at - datetime.now(UTC)).total_seconds() + if remaining <= 0: + raise ArtifactStoreUnavailableError("submission upload deadline expired") + try: + async with asyncio.timeout(remaining): + return await _receive_parts(store, upload, chunks, operation_evidence) + except TimeoutError: + raise ArtifactStoreUnavailableError("submission upload deadline expired") from None + + +async def _receive_parts( + store: ArtifactStore, upload: SubmissionSourceUpload, chunks: AsyncIterator[bytes], + operation_evidence: ArtifactProviderOperationEvidence | None, +) -> SubmissionSourceCompletion: + """Receive sequential parts inside the caller's immutable total deadline.""" + intent = upload.intent + evidence = operation_evidence or ArtifactProviderOperationEvidence() + digest = hashlib.sha256() + count = 0 + pending = bytearray() + parts = [] + while True: + try: + async with asyncio.timeout(intent.idle_timeout_seconds): + chunk = await anext(chunks) + except StopAsyncIteration: + break + if type(chunk) is not bytes: + raise ArtifactInputMismatchError("submission ingress returned invalid bytes") + if len(chunk) > MAXIMUM_INGRESS_CHUNK_BYTES: + raise ArtifactLimitExceededError("submission ingress chunk exceeds transport bound") + count += len(chunk) + if count > intent.maximum_raw_bytes: + raise ArtifactLimitExceededError("submission ZIP exceeds raw byte limit") + if intent.declared_raw_bytes is not None and count > intent.declared_raw_bytes: + raise ArtifactInputMismatchError("submission exceeds declared byte count") + digest.update(chunk) + view = memoryview(chunk) + while view: + amount = min(intent.part_bytes - len(pending), len(view)) + pending.extend(view[:amount]) + view = view[amount:] + if len(pending) == intent.part_bytes: + parts.append(await store.upload_source_part( + upload, len(parts) + 1, bytes(pending), operation_evidence=evidence, + )) + pending.clear() + if count == 0 or (intent.declared_raw_bytes is not None and count != intent.declared_raw_bytes): + raise ArtifactInputMismatchError("submission EOF violates declared or nonempty size") + if pending: + parts.append(await store.upload_source_part( + upload, len(parts) + 1, bytes(pending), operation_evidence=evidence, + )) + return SubmissionSourceCompletion( + upload=upload, parts=tuple(parts), raw_sha256="sha256:" + digest.hexdigest(), raw_byte_count=count, + ) diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index ac8d237e8..595efb0bc 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -936,6 +936,7 @@ "backend/app/modules/artifacts/api/submission_intake.py", "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", + "backend/app/modules/artifacts/intake/streaming.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", "backend/app/modules/tasks/intake_custody.py", diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py index 01461f826..6b1bfb79a 100644 --- a/backend/tests/artifacts/test_submission_intake_contracts.py +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -1,6 +1,8 @@ """Exact command/source identity proof; no database or provider claims.""" import hashlib +import asyncio +from datetime import UTC, datetime, timedelta import json from uuid import UUID, uuid4 @@ -12,7 +14,15 @@ SealedSubmissionSource, SubmissionIntakeMetadata, SubmissionSourceLocation, + SubmissionSourceCompletion, + SubmissionSourcePart, + SubmissionSourceUpload, + SubmissionSourceUploadIntent, ) +from app.interfaces.artifacts import ( + ArtifactInputMismatchError, ArtifactLimitExceededError, ArtifactStoreUnavailableError, +) +from app.modules.artifacts.intake.streaming import receive_submission_source OPERATION = UUID("019a0000-0000-7000-8000-000000000001") @@ -209,3 +219,118 @@ def test_source_accepts_existing_art_namespace_and_binds_its_fingerprint(tmp_pat namespace_id=namespace.id, namespace_fingerprint="sha256:" + "d" * 64, provider_profile=namespace.provider_profile, )).source_sha256() + + +def upload_value(**updates): + return SubmissionSourceUpload( + intent=SubmissionSourceUploadIntent.model_validate({ + "location": location(), "upload_fence": 1, + "maximum_raw_bytes": 6 * 1024 * 1024, "part_bytes": 5 * 1024 * 1024, + "idle_timeout_seconds": 20.0, + "upload_deadline_at": datetime.now(UTC) + timedelta(minutes=1), **updates, + }), provider_upload_id="opaque-upload", + ) + + +@pytest.mark.asyncio +async def test_source_stream_backpressures_and_hashes_original_bytes_without_completing(): + first_part_started, release = asyncio.Event(), asyncio.Event() + reads = 0 + part_sizes = [] + + class Store: + async def upload_source_part(self, upload, number, data, **kwargs): + part_sizes.append(len(data)) + if number == 1: + first_part_started.set() + await release.wait() + return SubmissionSourcePart(number=number, byte_count=len(data), provider_etag=f"part-{number}") + + async def chunks(): + nonlocal reads + for chunk in [b"a" * (1024 * 1024)] * 5 + [b"end"]: + reads += 1 + yield chunk + + task = asyncio.create_task(receive_submission_source(Store(), upload_value(), chunks())) + try: + await asyncio.wait_for(first_part_started.wait(), 2) + assert reads == 5 # The sixth input chunk cannot outrun a pending provider write. + assert not task.done() + release.set() + completion = await asyncio.wait_for(task, 2) + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert reads == 6 + assert part_sizes == [5 * 1024 * 1024, 3] + assert completion.raw_sha256 == "sha256:" + hashlib.sha256(b"a" * (5 * 1024 * 1024) + b"end").hexdigest() + assert completion.raw_byte_count == 5 * 1024 * 1024 + 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("updates,chunks,error", [ + ({}, [], ArtifactInputMismatchError), + ({"declared_raw_bytes": 4}, [b"abc"], ArtifactInputMismatchError), + ({"declared_raw_bytes": 2}, [b"abc"], ArtifactInputMismatchError), + ({"maximum_raw_bytes": 2}, [b"abc"], ArtifactLimitExceededError), + ({}, [b"a" * (1024 * 1024 + 1)], ArtifactLimitExceededError), +]) +async def test_invalid_stream_cannot_send_final_part_or_produce_eof(updates, chunks, error): + class NoWrites: + async def upload_source_part(self, *args, **kwargs): + pytest.fail("invalid small input reached storage") + + async def ingress(): + for chunk in chunks: + yield chunk + + with pytest.raises(error): + await receive_submission_source(NoWrites(), upload_value(**updates), ingress()) + + +@pytest.mark.parametrize("parts,count", [ + ((SubmissionSourcePart(number=2, byte_count=1, provider_etag="x"),), 1), + ((SubmissionSourcePart(number=1, byte_count=1, provider_etag="x"),), 2), + ((SubmissionSourcePart(number=1, byte_count=1, provider_etag="x"), + SubmissionSourcePart(number=2, byte_count=1, provider_etag="y")), 2), +]) +def test_completion_rejects_missing_short_nonfinal_or_count_mismatched_parts(parts, count): + with pytest.raises(ValidationError): + SubmissionSourceCompletion(upload=upload_value(), parts=parts, raw_sha256=SHA, raw_byte_count=count) + + +@pytest.mark.asyncio +async def test_source_stream_idle_deadline_stops_without_emitting_completion(): + stopped = asyncio.Event() + + async def stalled_input(): + try: + await asyncio.Event().wait() + yield b"never" + finally: + stopped.set() + + with pytest.raises(ArtifactStoreUnavailableError): + await receive_submission_source(object(), upload_value(idle_timeout_seconds=0.01), stalled_input()) + assert stopped.is_set() + + +@pytest.mark.asyncio +async def test_source_stream_total_deadline_cancels_an_inflight_part_without_completion(): + stopped = asyncio.Event() + + class SlowStore: + async def upload_source_part(self, *args, **kwargs): + try: + await asyncio.Event().wait() + finally: + stopped.set() + + async def ingress(): + yield b"abc" + + upload = upload_value(upload_deadline_at=datetime.now(UTC) + timedelta(seconds=0.2)) + with pytest.raises(ArtifactStoreUnavailableError): + await receive_submission_source(SlowStore(), upload, ingress()) + assert stopped.is_set() diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py index b02fb1f46..c09579b37 100644 --- a/backend/tests/test_artifact_architecture.py +++ b/backend/tests/test_artifact_architecture.py @@ -91,7 +91,9 @@ "lock_upload_session", "_contributor_facts", } -PROVIDER_METHODS = {"put", "observe_put_result", "open", "head"} +PROVIDER_METHODS = {"put", "observe_put_result", "open", "head", "begin_source_upload", + "upload_source_part", "complete_source_upload", "open_source", + "observe_source_upload", "discover_source_uploads", "request_source_abort"} CONCRETE_ADAPTER_MODULES = { "app.adapters.artifacts.local", "app.adapters.artifacts.s3_compatible", @@ -451,20 +453,18 @@ def test_composition_proof_rejects_aliased_factories_and_concrete_runtimes( def test_s3_adapter_exposes_only_required_immutable_object_operations() -> None: - """Keep list, delete, copy, ACL, and multipart behavior out of the provider.""" - allowed = {"get_object", "head_object", "put_object"} + """Permit multipart only at typed source methods; preserve unrelated objects.""" + allowed = {"get_object", "head_object", "put_object", "get_bucket_versioning", + "create_multipart_upload", "upload_part", "complete_multipart_upload", + "list_multipart_uploads", "abort_multipart_upload"} forbidden = { - "abort_multipart_upload", - "complete_multipart_upload", "copy_object", - "create_multipart_upload", "delete_object", "delete_objects", "list_buckets", "list_objects", "list_objects_v2", "put_object_acl", - "upload_part", "upload_part_copy", } called = { @@ -477,6 +477,29 @@ def test_s3_adapter_exposes_only_required_immutable_object_operations() -> None: } assert called & forbidden == set() assert called & allowed == allowed + source_methods = { + "begin_source_upload": {"get_bucket_versioning", "create_multipart_upload"}, + "upload_source_part": {"upload_part"}, + "complete_source_upload": {"complete_multipart_upload", "head_object"}, + "open_source": {"get_object"}, + "observe_source_upload": {"head_object"}, + "discover_source_uploads": {"list_multipart_uploads"}, + "request_source_abort": {"abort_multipart_upload"}, + } + source_only = {"get_bucket_versioning", "create_multipart_upload", "upload_part", + "complete_multipart_upload", "list_multipart_uploads", "abort_multipart_upload"} + store = next(node for node in _tree(S3_ADAPTER_MODULE).body + if isinstance(node, ast.ClassDef) and node.name == "S3CompatibleArtifactStore") + for method in store.body: + if not isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + calls = {node.func.attr for node in ast.walk(method) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) and node.func.value.id == "client"} + if method.name in source_methods: + assert calls == source_methods[method.name] + else: + assert not calls & source_only def test_provider_methods_stay_inside_artifact_orchestration_and_adapters() -> None: diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index c3b1125b6..401987fd2 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2765,6 +2765,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ additions = { target, "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", + "backend/app/modules/artifacts/intake/streaming.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", "backend/app/modules/tasks/intake_custody.py", diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py index fef5f1254..113fee58e 100644 --- a/backend/tests/test_s3_artifact_store.py +++ b/backend/tests/test_s3_artifact_store.py @@ -6,9 +6,11 @@ from collections.abc import AsyncIterator from contextlib import asynccontextmanager import hashlib +from datetime import UTC, datetime, timedelta import os from pathlib import Path from typing import Any +from uuid import UUID, uuid4 from aiobotocore.config import AioConfig from aiobotocore.session import AioSession @@ -30,6 +32,7 @@ ArtifactInputMismatchError, ArtifactObjectMissingError, ArtifactOperationConflictError, + ArtifactPreconditionFailedError, ArtifactStore, ArtifactStoreNamespaceClaim, ArtifactStoreUnavailableError, @@ -38,6 +41,11 @@ from app.interfaces.external_services import ExternalServiceAdapterIdentity from app.modules.artifacts.preparation import ArtifactPreparationService from app.modules.artifacts.sources import ArtifactCommitment +from app.modules.artifacts.api.submission_intake import ( + SubmissionSourceCompletion, + SubmissionSourceLocation, + SubmissionSourceUploadIntent, +) from tests.assertion_helpers import assert_secret_not_retained from tests.artifact_store_helpers import ( artifact_admission_limit_settings, @@ -93,6 +101,7 @@ def minio_settings( private_prefix: str, access_key: str = MINIO_ACCESS_KEY, secret_key: str = MINIO_SECRET_KEY, + buffer_bytes: int = 2, ) -> Settings: """Return one complete local-only MinIO configuration.""" return Settings( @@ -109,16 +118,16 @@ def minio_settings( artifact_s3_credential_mode="local_static", artifact_s3_access_key_id=access_key, artifact_s3_secret_access_key=secret_key, - artifact_stream_buffer_bytes=2, + artifact_stream_buffer_bytes=buffer_bytes, artifact_s3_operation_total_timeout_seconds=20, artifact_s3_write_timeout_seconds=20, ) -def initialize_minio_store(*, private_prefix: str) -> S3CompatibleArtifactStore: +def initialize_minio_store(*, private_prefix: str, buffer_bytes: int = 2) -> S3CompatibleArtifactStore: """Construct, claim, and initialize one MinIO namespace.""" bootstrap = create_artifact_store_bootstrap( - minio_settings(private_prefix=private_prefix), activation_guard=None + minio_settings(private_prefix=private_prefix, buffer_bytes=buffer_bytes), activation_guard=None ) assert type(bootstrap) is S3CompatibleArtifactStoreBootstrap namespace_identity = bootstrap.namespace_identity @@ -988,3 +997,176 @@ def _client_error(code: str, status: int | None) -> ClientError: response, "HeadObject", ) + + +@pytest.fixture +async def source_store(): + """Qualify source operations against a versioned real MinIO namespace.""" + store = initialize_minio_store(private_prefix=f"submission/{uuid4().hex}", buffer_bytes=65536) + async with store._client() as client: + await client.put_bucket_versioning( + Bucket=MINIO_BUCKET, VersioningConfiguration={"Status": "Enabled"}, + ) + try: + yield store + finally: + store.close() + + +def source_intent(store, **updates): + """Explicit test limits are not deployment defaults.""" + return SubmissionSourceUploadIntent.model_validate({ + "location": SubmissionSourceLocation( + operation_id=UUID("019a0000-0000-7000-8000-000000000001"), namespace_id="primary", + namespace_fingerprint=store._expected_namespace_fingerprint(), + provider_profile="minio-v1", + ), + "upload_fence": 1, "maximum_raw_bytes": 6 * 1024 * 1024, + "declared_raw_bytes": None, "part_bytes": 5 * 1024 * 1024, + "idle_timeout_seconds": 20.0, + "upload_deadline_at": datetime.now(UTC) + timedelta(seconds=90), + **updates, + }) + + +async def source_completion(store, payload, **intent_updates): + """Send parts sequentially as the eventual durable owner must do.""" + upload = await store.begin_source_upload(source_intent(store, **intent_updates)) + parts = [] + for offset in range(0, len(payload), upload.intent.part_bytes): + parts.append(await store.upload_source_part( + upload, len(parts) + 1, payload[offset:offset + upload.intent.part_bytes], + )) + return SubmissionSourceCompletion( + upload=upload, parts=tuple(parts), raw_sha256="sha256:" + hashlib.sha256(payload).hexdigest(), + raw_byte_count=len(payload), + ) + + +@pytest.mark.asyncio +async def test_submission_source_real_multipart_preserves_exact_version_and_refuses_overwrite(source_store): + store = source_store + payload = b"a" * (5 * 1024 * 1024) + b"last part" + completion = await source_completion(store, payload, declared_raw_bytes=len(payload)) + assert len(completion.parts) == 2 + assert await store.observe_source_upload(completion) is None + source = await store.complete_source_upload(completion) + assert source.provider_generation not in {"", "null"} + chunks = [chunk async for chunk in store.open_source(source)] + assert max(map(len, chunks)) <= 65536 + assert b"".join(chunks) == payload + assert await store.observe_source_upload(completion) == source + competing = await source_completion(store, b"different", upload_fence=2) + with pytest.raises(ArtifactPreconditionFailedError): + await store.complete_source_upload(competing) + with pytest.raises(ArtifactIntegrityError): + await store.observe_source_upload(competing) + assert b"".join([part async for part in store.open_source(source)]) == payload + + +@pytest.mark.asyncio +async def test_submission_source_reads_pinned_version_and_rejects_wrong_raw_identity(source_store): + store = source_store + completion = await source_completion(store, b"original") + source = await store.complete_source_upload(completion) + # Privileged test setup simulates a newer version outside the adapter. The + # authorized source must still read its exact old version, never current key. + async with store._client() as client: + await client.put_object(Bucket=MINIO_BUCKET, Key=store._source_key(source.location), Body=b"changed") + assert b"".join([part async for part in store.open_source(source)]) == b"original" + wrong = source.model_copy(update={"raw_sha256": "sha256:" + "0" * 64}) + with pytest.raises(ArtifactIntegrityError): + _ = [part async for part in store.open_source(wrong)] + with pytest.raises(ArtifactIntegrityError): + await store.observe_source_upload(completion) + + +@pytest.mark.asyncio +async def test_submission_source_lost_completion_ack_recovers_by_exact_bytes(source_store, monkeypatch): + store = source_store + completion = await source_completion(store, b"trusted ingress bytes") + original_client = store._client + + class LostAcknowledgement: + def __init__(self, client): + self.client = client + + async def complete_multipart_upload(self, **kwargs): + await self.client.complete_multipart_upload(**kwargs) + raise OSError("lost provider response") + + @asynccontextmanager + async def interrupted_client(): + async with original_client() as client: + yield LostAcknowledgement(client) + + monkeypatch.setattr(store, "_client", interrupted_client) + with pytest.raises(ArtifactStoreUnavailableError): + await store.complete_source_upload(completion) + monkeypatch.setattr(store, "_client", original_client) + source = await store.observe_source_upload(completion) + assert source is not None + assert b"".join([part async for part in store.open_source(source)]) == b"trusted ingress bytes" + wrong = completion.model_copy(update={"raw_sha256": "sha256:" + "0" * 64}) + with pytest.raises(ArtifactIntegrityError): + await store.observe_source_upload(wrong) + + +@pytest.mark.asyncio +async def test_submission_source_rejects_expired_foreign_or_oversized_uploads_before_io(source_store, monkeypatch): + store = source_store + upload = await store.begin_source_upload(source_intent(store, maximum_raw_bytes=3, declared_raw_bytes=3)) + + @asynccontextmanager + async def no_provider_io(): + pytest.fail("invalid input reached provider") + yield + + monkeypatch.setattr(store, "_client", no_provider_io) + for number, data in [(1, b"1234"), (True, b"1"), (2, b"1"), (1, b"")]: + with pytest.raises(ArtifactInputMismatchError): + await store.upload_source_part(upload, number, data) + with pytest.raises(ArtifactStoreUnavailableError): + await store.begin_source_upload(source_intent(store, upload_deadline_at=datetime.now(UTC) - timedelta(seconds=1))) + wrong_location = upload.intent.location.model_copy(update={"namespace_fingerprint": "sha256:" + "0" * 64}) + with pytest.raises(ArtifactOperationConflictError): + await store.begin_source_upload(source_intent(store, location=wrong_location)) + + +@pytest.mark.asyncio +async def test_submission_source_lost_begin_ack_discovers_and_aborts_only_owned_key(source_store, monkeypatch): + store = source_store + intent = source_intent(store) + other_location = intent.location.model_copy(update={ + "operation_id": UUID("019a0000-0000-7000-8000-000000000002"), + }) + other = await store.begin_source_upload(source_intent(store, location=other_location)) + original_client = store._client + + class LostBeginAcknowledgement: + def __init__(self, client): + self.client = client + + async def get_bucket_versioning(self, **kwargs): + return await self.client.get_bucket_versioning(**kwargs) + + async def create_multipart_upload(self, **kwargs): + await self.client.create_multipart_upload(**kwargs) + raise OSError("lost initiation response") + + @asynccontextmanager + async def interrupted_client(): + async with original_client() as client: + yield LostBeginAcknowledgement(client) + + monkeypatch.setattr(store, "_client", interrupted_client) + with pytest.raises(ArtifactStoreUnavailableError): + await store.begin_source_upload(intent) + monkeypatch.setattr(store, "_client", original_client) + discovered = await store.discover_source_uploads(intent) + assert len(discovered) == 1 + await store.request_source_abort(discovered[0]) + await store.request_source_abort(discovered[0]) # NoSuchUpload is safe to repeat. + assert await store.discover_source_uploads(intent) == () + assert await store.discover_source_uploads(other.intent) == (other,) + await store.request_source_abort(other) diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 9e973a3ed..5d6665cca 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -111,8 +111,10 @@ The [single-request submission specification](spec_submission_execution.md) is the approved target for [WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). Its hidden owner boundaries define immutable command/source values and durable foreground intake custody with a matching TASK pointer, source/lease fences and -per-operation physical source reservations under explicit limits. Bounded -streaming/cleanup custody, one-session PRE, accepted handoff, +per-operation physical source reservations under explicit limits. Hidden bounded +receipt and S3-compatible source capabilities cover conditional completion and +exact-version reads. Durable upload/cleanup orchestration, local source support, +AWS source qualification, one-session PRE, accepted handoff, finalization and client cutover remain planned; the active API still uses preparation followed by admission-consuming submission. From 4e8431fbcf4db92eb3665749bf41b43c8baf95a8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 18:47:10 +0100 Subject: [PATCH 011/513] Prove existing AWS activation cannot authorize new source writes --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++- .../test_aws_artifact_provider_activation.py | 29 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2818e01ad..7200a7136 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -185,6 +185,13 @@ remain required before the public flow can use them. ## Review findings +- S3-QUAL-001: QA found the deliberate AWS source qualification denial lacked + a negative regression. The existing offline AWS activation suite now constructs + a real AWS-profile adapter with an allowed SHA-object activation and a provider + I/O tripwire. An in-memory removal of the source gate fails that test at the + tripwire. The documentation next-stage line now names durable receipt + orchestration explicitly. Neither change asserts AWS source qualification. + - Custody review found nullable predecessor/revision selector types and UUID shape unchecked in the SQL insert guard. A direct-SQL regression recomputed the digest and installed the matching task pointer; it reproduced acceptance @@ -209,6 +216,6 @@ remain required before the public flow can use them. - Current-source reconciliation: rebased onto 94334ccf4 (PR #707); preserved issuer profile roadmap changes and schema head 0068. Submission owner contracts unchanged. -- Next implementation stage: bounded streaming and exact cleanup custody in +- Next implementation stage: durable upload receipt orchestration and exact cleanup custody in the same PR, followed by PRE, handoff/finalization and clients. - Remaining risks: A01–A35 integration and C01–C07 qualification. diff --git a/backend/tests/test_aws_artifact_provider_activation.py b/backend/tests/test_aws_artifact_provider_activation.py index 7e5b4b425..772afe68a 100644 --- a/backend/tests/test_aws_artifact_provider_activation.py +++ b/backend/tests/test_aws_artifact_provider_activation.py @@ -3,6 +3,7 @@ from __future__ import annotations from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any from uuid import UUID @@ -22,6 +23,10 @@ artifact_store_namespace_material, ) from tests.artifact_store_helpers import minted_source +from app.modules.artifacts.api.submission_intake import ( + SubmissionSourceLocation, + SubmissionSourceUploadIntent, +) _ACTIVATION_ID = UUID("0199e648-0b77-7000-8000-000000000001") @@ -191,6 +196,30 @@ def session_factory() -> object: assert events == [("select", fingerprint)] +@pytest.mark.asyncio +async def test_existing_aws_activation_cannot_authorize_unqualified_submission_sources() -> None: + """An existing SHA-object qualification cannot silently authorize new writes.""" + events: list[object] = [] + store, fingerprint = _initialized_store( + _Guard(events), + session_factory=lambda: (_ for _ in ()).throw(AssertionError("unqualified provider I/O")), + ) + intent = SubmissionSourceUploadIntent( + location=SubmissionSourceLocation( + operation_id=_ACTIVATION_ID, namespace_id="primary", + namespace_fingerprint=fingerprint, provider_profile="aws-s3-v1", + ), + upload_fence=1, maximum_raw_bytes=1024, part_bytes=5 * 1024 * 1024, + idle_timeout_seconds=10.0, upload_deadline_at=datetime.now(UTC) + timedelta(seconds=30), + ) + try: + with pytest.raises(ArtifactProviderLiveProofRequiredError): + await store.begin_source_upload(intent) + assert events == [] + finally: + store.close() + + def _assert_same_activation_immediately_precedes_sdk_calls( events: list[object], fingerprint: str, From 7c23981f7046d582b8b11dbfb12cf1c09ffa5413 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 18:55:05 +0100 Subject: [PATCH 012/513] Persist upload handles and exact completion receipts before sealing --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++ .../0069_submission_intake_custody.py | 137 +++++++++++++++++ backend/app/db/models.py | 1 + .../app/modules/artifacts/intake/models.py | 35 ++++- .../modules/artifacts/intake/repository.py | 74 +++++++++- backend/scripts/identifier_inventory.py | 1 + .../test_submission_intake_custody.py | 138 ++++++++++++++++-- backend/tests/conftest.py | 4 +- 8 files changed, 383 insertions(+), 17 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 7200a7136..8f638d8d4 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -143,6 +143,16 @@ remain required before the public flow can use them. ## Acceptance criteria +Durable receipt integration next extends the existing intake models/repository, +migration 0069, registry/reset/identifier catalogues and custody suite. One +operation-owned row records immutable part/deadline bounds before initiation, +then its opaque handle before parts, then ordered bounded completion receipts +with EOF. Fenced owner methods flush only; root transactions commit each external +I/O boundary. SQL closure must prohibit EOF without matching receipts, malformed +part sequences and mutation/deletion of recorded custody. Test rollback, stale +owners, mismatched handles/locations and direct-SQL substitutions on PostgreSQL. +This does not authorize late foreground callbacks, cleanup charge release or PRE. + - [x] Exact metadata round-trip and identity changes for each command selector. - [x] Packet metadata validation preserves empty-text warning semantics. - [x] Source keys derive only from UUIDv7; no arbitrary path/URL selection. diff --git a/backend/alembic/versions/0069_submission_intake_custody.py b/backend/alembic/versions/0069_submission_intake_custody.py index 7f69352eb..6bdab6cc5 100644 --- a/backend/alembic/versions/0069_submission_intake_custody.py +++ b/backend/alembic/versions/0069_submission_intake_custody.py @@ -104,6 +104,139 @@ ); """ +UPLOAD_TABLE_SQL = r""" +CREATE TABLE public.submission_source_upload_receipts ( + operation_id UUID NOT NULL, + upload_fence BIGINT NOT NULL, + part_bytes INTEGER NOT NULL, + idle_timeout_seconds DOUBLE PRECISION NOT NULL, + provider_upload_id VARCHAR(2048), + completion_parts JSONB, + created_at TIMESTAMP WITH TIME ZONE DEFAULT clock_timestamp() NOT NULL, + handle_recorded_at TIMESTAMP WITH TIME ZONE, + completion_recorded_at TIMESTAMP WITH TIME ZONE, + CONSTRAINT pk_submission_source_upload_receipts PRIMARY KEY (operation_id), + CONSTRAINT fk_submission_source_upload_operation FOREIGN KEY(operation_id) REFERENCES public.submission_intake_operations (id), + CONSTRAINT ck_submission_source_upload_receipts_upload_bounds CHECK (upload_fence>0 and part_bytes between 5242880 and 16777216 and idle_timeout_seconds>0 and idle_timeout_seconds<'Infinity'::float8), + CONSTRAINT ck_submission_source_upload_receipts_handle_shape CHECK ((provider_upload_id is null and handle_recorded_at is null) or (provider_upload_id is not null and length(provider_upload_id) between 1 and 2048 and handle_recorded_at is not null)), + CONSTRAINT ck_submission_source_upload_receipts_completion_shape CHECK ((completion_parts is null and completion_recorded_at is null) or (completion_parts is not null and jsonb_typeof(completion_parts)='array' and jsonb_array_length(completion_parts) between 1 and 100 and completion_recorded_at is not null and provider_upload_id is not null)) +); +""" + +UPLOAD_GUARDS = r""" +CREATE FUNCTION public.guard_submission_source_upload_receipt() +RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ +DECLARE + o public.submission_intake_operations; +BEGIN + IF TG_OP IN ('DELETE','TRUNCATE') THEN + RAISE EXCEPTION 'submission upload custody cannot be deleted' USING ERRCODE='23514'; + END IF; + SELECT * INTO o FROM public.submission_intake_operations WHERE id=NEW.operation_id FOR UPDATE; + IF NOT FOUND OR o.state<>'receiving' OR o.lease_generation<>NEW.upload_fence + OR o.lease_expires_at<=clock_timestamp() THEN + RAISE EXCEPTION 'submission upload owner is stale' USING ERRCODE='23514'; + END IF; + IF TG_OP='INSERT' THEN + IF o.raw_sha256 IS NOT NULL OR NEW.provider_upload_id IS NOT NULL + OR NEW.completion_parts IS NOT NULL THEN + RAISE EXCEPTION 'invalid initial submission upload intent' USING ERRCODE='23514'; + END IF; + NEW.created_at:=clock_timestamp(); + RETURN NEW; + END IF; + IF ROW(NEW.operation_id,NEW.upload_fence,NEW.part_bytes,NEW.idle_timeout_seconds,NEW.created_at) + IS DISTINCT FROM ROW(OLD.operation_id,OLD.upload_fence,OLD.part_bytes,OLD.idle_timeout_seconds,OLD.created_at) + OR (OLD.provider_upload_id IS NOT NULL AND + ROW(NEW.provider_upload_id,NEW.handle_recorded_at) IS DISTINCT FROM + ROW(OLD.provider_upload_id,OLD.handle_recorded_at)) + OR (OLD.completion_parts IS NOT NULL AND + ROW(NEW.completion_parts,NEW.completion_recorded_at) IS DISTINCT FROM + ROW(OLD.completion_parts,OLD.completion_recorded_at)) THEN + RAISE EXCEPTION 'submission upload receipt is immutable' USING ERRCODE='23514'; + END IF; + IF OLD.provider_upload_id IS NULL AND NEW.provider_upload_id IS NOT NULL THEN + IF o.raw_sha256 IS NOT NULL OR NEW.completion_parts IS NOT NULL THEN + RAISE EXCEPTION 'submission upload handle must precede EOF' USING ERRCODE='23514'; + END IF; + NEW.handle_recorded_at:=clock_timestamp(); + END IF; + IF OLD.completion_parts IS NULL AND NEW.completion_parts IS NOT NULL THEN + IF OLD.provider_upload_id IS NULL OR o.raw_sha256 IS NULL THEN + RAISE EXCEPTION 'submission completion requires handle and EOF' USING ERRCODE='23514'; + END IF; + NEW.completion_recorded_at:=clock_timestamp(); + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER submission_source_upload_receipt_guard +BEFORE INSERT OR UPDATE OR DELETE ON public.submission_source_upload_receipts +FOR EACH ROW EXECUTE FUNCTION public.guard_submission_source_upload_receipt(); +CREATE TRIGGER submission_source_upload_receipts_no_truncate +BEFORE TRUNCATE ON public.submission_source_upload_receipts +FOR EACH STATEMENT EXECUTE FUNCTION public.guard_submission_source_upload_receipt(); + +CREATE FUNCTION public.check_submission_source_completion() +RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ +DECLARE + oid uuid; + o public.submission_intake_operations; + u public.submission_source_upload_receipts; + p jsonb; + n bigint; + total bigint:=0; + size bigint; +BEGIN + IF TG_TABLE_NAME='submission_intake_operations' THEN + oid:=NEW.id; + ELSE + oid:=NEW.operation_id; + END IF; + SELECT * INTO o FROM public.submission_intake_operations WHERE id=oid; + SELECT * INTO u FROM public.submission_source_upload_receipts WHERE operation_id=oid; + IF o.raw_sha256 IS NULL THEN + IF u.completion_parts IS NOT NULL THEN + RAISE EXCEPTION 'submission completion has no EOF' USING ERRCODE='23514'; + END IF; + RETURN NULL; + END IF; + IF u.operation_id IS NULL OR u.provider_upload_id IS NULL OR u.completion_parts IS NULL + OR jsonb_typeof(u.completion_parts)<>'array' + OR jsonb_array_length(u.completion_parts) NOT BETWEEN 1 AND 100 + OR (o.sealed_upload_fence IS NOT NULL AND o.sealed_upload_fence<>u.upload_fence) THEN + RAISE EXCEPTION 'submission EOF requires exact completion receipts' USING ERRCODE='23514'; + END IF; + FOR p,n IN SELECT value,ordinality FROM jsonb_array_elements(u.completion_parts) WITH ORDINALITY LOOP + IF jsonb_typeof(p) IS DISTINCT FROM 'object' + OR NOT (p ?& ARRAY['number','byte_count','provider_etag']) + OR p-ARRAY['number','byte_count','provider_etag']<>'{}'::jsonb + OR jsonb_typeof(p->'number') IS DISTINCT FROM 'number' + OR p->>'number' IS DISTINCT FROM n::text + OR jsonb_typeof(p->'byte_count') IS DISTINCT FROM 'number' + OR (p->>'byte_count') !~ '^[1-9][0-9]{0,7}$' + OR jsonb_typeof(p->'provider_etag') IS DISTINCT FROM 'string' + OR length(p->>'provider_etag') NOT BETWEEN 1 AND 1024 THEN + RAISE EXCEPTION 'invalid submission completion part' USING ERRCODE='23514'; + END IF; + size:=(p->>'byte_count')::bigint; + IF size>u.part_bytes OR (nu.part_bytes) THEN + RAISE EXCEPTION 'invalid submission completion part size' USING ERRCODE='23514'; + END IF; + total:=total+size; + END LOOP; + IF total IS DISTINCT FROM o.raw_byte_count THEN + RAISE EXCEPTION 'submission completion byte count mismatch' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END $$; +CREATE CONSTRAINT TRIGGER submission_intake_completion_closure +AFTER INSERT OR UPDATE ON public.submission_intake_operations +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_source_completion(); +CREATE CONSTRAINT TRIGGER submission_upload_completion_closure +AFTER INSERT OR UPDATE ON public.submission_source_upload_receipts +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_source_completion(); +""" + GUARDS = r""" CREATE FUNCTION public.submission_intake_task_snapshot(t public.workstream_tasks) RETURNS jsonb LANGUAGE sql IMMUTABLE STRICT @@ -407,8 +540,12 @@ def upgrade() -> None: ["id", "task_id"], source_schema="public", referent_schema="public", deferrable=True, initially="DEFERRED") for statement in split_sql_statements(CAPACITY_TABLE_SQL): op.execute(statement) + for statement in split_sql_statements(UPLOAD_TABLE_SQL): + op.execute(statement) for statement in split_sql_statements(GUARDS): op.execute(statement) + for statement in split_sql_statements(UPLOAD_GUARDS): + op.execute(statement) def downgrade() -> None: diff --git a/backend/app/db/models.py b/backend/app/db/models.py index dbdf73bd4..b7a86ef09 100644 --- a/backend/app/db/models.py +++ b/backend/app/db/models.py @@ -9,6 +9,7 @@ from app.modules.api_controls.models import ApiRateControlCounter # noqa: F401 from app.modules.artifacts.intake.models import ( # noqa: F401 SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge, + SubmissionSourceUploadReceipt, ) from app.modules.artifacts.models import ( # noqa: F401 ArtifactBinding, diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py index db1f9fd4a..b10376c3d 100644 --- a/backend/app/modules/artifacts/intake/models.py +++ b/backend/app/modules/artifacts/intake/models.py @@ -3,10 +3,10 @@ from datetime import datetime from sqlalchemy import ( - BigInteger, CheckConstraint, DateTime, ForeignKeyConstraint, Index, + BigInteger, CheckConstraint, DateTime, ForeignKeyConstraint, Index, Integer, String, UniqueConstraint, Uuid, text, ) -from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION, JSONB from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.sql import func @@ -123,3 +123,34 @@ class SubmissionSourceCharge(Base): accounted_bytes: Mapped[int] = mapped_column(BigInteger) state: Mapped[str] = mapped_column(String(20)) sealed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + +class SubmissionSourceUploadReceipt(Base): + """Operation-owned initiation and completion facts across provider I/O.""" + + __tablename__ = "submission_source_upload_receipts" + __table_args__ = ( + ForeignKeyConstraint(["operation_id"], ["submission_intake_operations.id"], + name="fk_submission_source_upload_operation"), + CheckConstraint("upload_fence>0 and part_bytes between 5242880 and 16777216 " + "and idle_timeout_seconds>0 and idle_timeout_seconds<'Infinity'::float8", + name="upload_bounds"), + CheckConstraint("(provider_upload_id is null and handle_recorded_at is null) or " + "(provider_upload_id is not null and length(provider_upload_id) between 1 and 2048 " + "and handle_recorded_at is not null)", name="handle_shape"), + CheckConstraint("(completion_parts is null and completion_recorded_at is null) or " + "(completion_parts is not null and jsonb_typeof(completion_parts)='array' " + "and jsonb_array_length(completion_parts) between 1 and 100 " + "and completion_recorded_at is not null and provider_upload_id is not null)", + name="completion_shape"), + ) + + operation_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True) + upload_fence: Mapped[int] = mapped_column(BigInteger) + part_bytes: Mapped[int] = mapped_column(Integer) + idle_timeout_seconds: Mapped[float] = mapped_column(DOUBLE_PRECISION) + provider_upload_id: Mapped[str | None] = mapped_column(String(2048)) + completion_parts: Mapped[list | None] = mapped_column(JSONB(none_as_null=True)) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) + handle_recorded_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + completion_recorded_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py index 7cb07acdc..c4cd436ac 100644 --- a/backend/app/modules/artifacts/intake/repository.py +++ b/backend/app/modules/artifacts/intake/repository.py @@ -19,8 +19,11 @@ from app.modules.artifacts.api.submission_intake import ( SealedSubmissionSource, SubmissionIntakeMetadata, SubmissionSourceLocation, SubmissionSourceCapacityLimits, + SubmissionSourceCompletion, SubmissionSourceUpload, SubmissionSourceUploadIntent, +) +from app.modules.artifacts.intake.models import ( + SubmissionIntakeOperation, SubmissionSourceCharge, SubmissionSourceUploadReceipt, ) -from app.modules.artifacts.intake.models import SubmissionIntakeOperation from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity from app.modules.artifacts.models import ArtifactStorageNamespace from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort @@ -107,15 +110,78 @@ async def _owned(self, operation_id: UUID, lease_id: UUID, generation: int) -> S raise IntakeCustodyConflict("intake_owner_stale") return row + async def _upload_intent( + self, row: SubmissionIntakeOperation, receipt: SubmissionSourceUploadReceipt, + ) -> SubmissionSourceUploadIntent: + """Reconstruct provider bounds only from immutable operation-owned facts.""" + charge = await self._session.get(SubmissionSourceCharge, row.id) + if charge is None: + raise IntakeCustodyConflict("intake_source_charge_missing") + return SubmissionSourceUploadIntent( + location=SubmissionSourceLocation( + operation_id=UUID(row.id), namespace_id=row.namespace_id, + namespace_fingerprint=row.namespace_fingerprint, provider_profile=row.provider_profile, + ), + upload_fence=receipt.upload_fence, maximum_raw_bytes=row.maximum_raw_bytes, + declared_raw_bytes=charge.declared_raw_bytes, part_bytes=receipt.part_bytes, + idle_timeout_seconds=receipt.idle_timeout_seconds, upload_deadline_at=row.upload_deadline_at, + ) + + async def prepare_upload( + self, operation_id: UUID, lease_id: UUID, generation: int, *, + part_bytes: int, idle_timeout_seconds: float, + ) -> SubmissionSourceUploadIntent: + """Record initiation intent once; caller commits it before provider begin.""" + row = await self._owned(operation_id, lease_id, generation) + if row.state != "receiving" or row.raw_sha256 is not None: + raise IntakeCustodyConflict("intake_upload_not_receiving") + if await self._session.get(SubmissionSourceUploadReceipt, row.id) is not None: + raise IntakeCustodyConflict("intake_upload_already_initiated") + receipt = SubmissionSourceUploadReceipt( + operation_id=row.id, upload_fence=generation, part_bytes=part_bytes, + idle_timeout_seconds=idle_timeout_seconds, + ) + intent = await self._upload_intent(row, receipt) + self._session.add(receipt) + await self._session.flush() + return intent + + async def record_upload( + self, operation_id: UUID, lease_id: UUID, generation: int, *, upload: SubmissionSourceUpload, + ) -> None: + """Persist the exact begun handle before the first part may be sent.""" + row = await self._owned(operation_id, lease_id, generation) + upload = SubmissionSourceUpload.model_validate(upload) + receipt = await self._session.get(SubmissionSourceUploadReceipt, row.id) + if (row.state != "receiving" or receipt is None + or upload.intent != await self._upload_intent(row, receipt)): + raise IntakeCustodyConflict("intake_upload_receipt_mismatch") + if receipt.provider_upload_id is not None: + if receipt.provider_upload_id != upload.provider_upload_id: + raise IntakeCustodyConflict("intake_upload_handle_immutable") + return + receipt.provider_upload_id = upload.provider_upload_id + receipt.handle_recorded_at = func.clock_timestamp() + await self._session.flush() + async def record_eof(self, operation_id: UUID, lease_id: UUID, generation: int, - *, raw_sha256: str, raw_byte_count: int) -> None: - """Persist ingress identity before the adapter may complete the object.""" + *, completion: SubmissionSourceCompletion) -> None: + """Persist raw identity and exact receipts before external completion.""" row = await self._owned(operation_id, lease_id, generation) + completion = SubmissionSourceCompletion.model_validate(completion) if row.state != "receiving" or row.raw_sha256 is not None: raise IntakeCustodyConflict("intake_eof_already_recorded") - row.raw_sha256, row.raw_byte_count = raw_sha256, raw_byte_count + receipt = await self._session.get(SubmissionSourceUploadReceipt, row.id) + if (receipt is None or receipt.provider_upload_id is None + or completion.upload.intent != await self._upload_intent(row, receipt) + or completion.upload.provider_upload_id != receipt.provider_upload_id): + raise IntakeCustodyConflict("intake_completion_receipt_mismatch") + row.raw_sha256, row.raw_byte_count = completion.raw_sha256, completion.raw_byte_count row.eof_at = func.clock_timestamp() await self._session.flush() + receipt.completion_parts = [part.model_dump(mode="json") for part in completion.parts] + receipt.completion_recorded_at = func.clock_timestamp() + await self._session.flush() async def seal(self, operation_id: UUID, lease_id: UUID, generation: int, *, provider_generation: str, pre_deadline_at: datetime, diff --git a/backend/scripts/identifier_inventory.py b/backend/scripts/identifier_inventory.py index 20a26b3ca..94d613e7f 100644 --- a/backend/scripts/identifier_inventory.py +++ b/backend/scripts/identifier_inventory.py @@ -20,6 +20,7 @@ GENERATION_CLASSIFICATION_FORMAT = "workstream-uuid-generation-classifications-1" GENERATION_CLASSIFICATIONS = "identifier_generation_classifications.json" SEMANTIC_KEYS = { + "submission_source_upload_receipts": ("intake-operation-owned upload receipt", ("operation_id",)), "submission_source_capacity_profiles": ("ART namespace-owned source allocation", ("namespace_id",)), "submission_source_charges": ("intake-operation-owned physical obligation", ("operation_id",)), "submission_dispatches": ("submission-owned original dispatch receipt", ("submission_id",)), diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 5a7cd20a5..16874662f 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -1,6 +1,7 @@ """Real PostgreSQL proof of pre-handoff custody, not upload or acceptance authority.""" import asyncio +import json from datetime import UTC, datetime, timedelta from types import SimpleNamespace @@ -13,7 +14,11 @@ from app.adapters.tasks import task_submission_context_port from app.core.identifiers import new_record_id -from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits +from app.modules.artifacts.api.submission_intake import ( + SubmissionIntakeMetadata, SubmissionSourceCapacityLimits, SubmissionSourceCompletion, + SubmissionSourcePart, SubmissionSourceUpload, +) +from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceUploadReceipt from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable from app.modules.tasks.intake_custody import IntakeTaskCustody @@ -58,9 +63,9 @@ async def intake(tmp_path, isolated_database_env, capacity_limits): await engine.dispose() -async def reserve(intake, session, *, key=None, declared_raw_bytes=None): +async def reserve(intake, session, *, key=None, declared_raw_bytes=None, with_upload=True): now = datetime.now(UTC) - return await repository(session).reserve( + row = await repository(session).reserve( metadata=SubmissionIntakeMetadata(task_id=intake.task, assignment_id=intake.assignment), actor_id=intake.actor.actor_profile_id, identity_link_id=intake.actor.identity_link_id, idempotency_key=key or new_record_id(), maximum_raw_bytes=1024, @@ -68,6 +73,114 @@ async def reserve(intake, session, *, key=None, declared_raw_bytes=None): upload_deadline_at=now + timedelta(minutes=5), lease_expires_at=now + timedelta(minutes=1), ) + if not with_upload: + return row + intent = await repository(session).prepare_upload( + UUID(row.id), UUID(row.lease_id), 1, part_bytes=5 * 1024 * 1024, idle_timeout_seconds=20.0, + ) + await repository(session).record_upload( + UUID(row.id), UUID(row.lease_id), 1, + upload=SubmissionSourceUpload(intent=intent, provider_upload_id="fixture-upload"), + ) + return row + + +async def record_eof(session, operation, lease, generation, *, raw_sha256, raw_byte_count): + """Database-only fixture: build a completed provider receipt, never claim byte I/O.""" + row = await session.get(SubmissionIntakeOperation, str(operation)) + receipt = await session.get(SubmissionSourceUploadReceipt, str(operation)) + repo = repository(session) + upload = SubmissionSourceUpload( + intent=await repo._upload_intent(row, receipt), provider_upload_id=receipt.provider_upload_id, + ) + await repo.record_eof(operation, lease, generation, completion=SubmissionSourceCompletion( + upload=upload, parts=(SubmissionSourcePart(number=1, byte_count=raw_byte_count, provider_etag="part-etag"),), + raw_sha256=raw_sha256, raw_byte_count=raw_byte_count, + )) + + +async def test_upload_intent_and_handle_commit_before_parts_and_cannot_be_replaced(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation, lease = UUID(row.id), UUID(row.lease_id) + async with intake.factory.begin() as session: + intent = await repository(session).prepare_upload( + operation, lease, 1, part_bytes=5 * 1024 * 1024, idle_timeout_seconds=20.0, + ) + with pytest.raises(IntakeCustodyConflict, match="already_initiated"): + async with intake.factory.begin() as session: + await repository(session).prepare_upload( + operation, lease, 1, part_bytes=5 * 1024 * 1024, idle_timeout_seconds=20.0, + ) + wrong = intent.model_copy(update={"location": intent.location.model_copy(update={"operation_id": new_record_id()})}) + with pytest.raises(IntakeCustodyConflict, match="receipt_mismatch"): + async with intake.factory.begin() as session: + await repository(session).record_upload( + operation, lease, 1, upload=SubmissionSourceUpload(intent=wrong, provider_upload_id="handle"), + ) + upload = SubmissionSourceUpload(intent=intent, provider_upload_id="handle") + for _ in range(2): + async with intake.factory.begin() as session: + await repository(session).record_upload(operation, lease, 1, upload=upload) + with pytest.raises(IntakeCustodyConflict, match="handle_immutable"): + async with intake.factory.begin() as session: + await repository(session).record_upload( + operation, lease, 1, upload=upload.model_copy(update={"provider_upload_id": "replacement"}), + ) + async with intake.factory.begin() as session: + await repository(session).terminalize(operation, lease, 1, state="failed", failure_code="upload_failed") + with pytest.raises(IntakeCustodyConflict, match="owner_stale"): + async with intake.factory.begin() as session: + await repository(session).record_upload(operation, lease, 1, upload=upload) + + +async def test_eof_cannot_commit_without_exact_bounded_completion_receipts(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation = UUID(row.id) + valid_part = {"number": 1, "byte_count": 100, "provider_etag": "opaque-part"} + for parts, error in ( + (None, "requires exact completion"), + ([dict(valid_part, number="1")], "invalid submission completion part"), + ([dict(valid_part, number=2)], "invalid submission completion part"), + ([dict(valid_part, byte_count=99)], "byte count mismatch"), + ([dict(valid_part, provider_etag="")], "invalid submission completion part"), + ([dict(valid_part, unexpected="field")], "invalid submission completion part"), + ([dict(valid_part, byte_count=50), dict(valid_part, number=2, byte_count=50)], "part size"), + ): + with pytest.raises(DBAPIError, match=error): + async with intake.factory.begin() as session: + await session.execute(text( + "UPDATE submission_intake_operations SET raw_sha256=:sha,raw_byte_count=100," + "eof_at=clock_timestamp() WHERE id=:id" + ), {"sha": SHA, "id": operation}) + if parts is not None: + await session.execute(text( + "UPDATE submission_source_upload_receipts SET completion_parts=CAST(:parts AS jsonb)," + "completion_recorded_at=clock_timestamp() WHERE operation_id=:id" + ), {"parts": json.dumps(parts), "id": operation}) + async with intake.factory() as session: + assert await session.scalar(text("SELECT raw_sha256 FROM submission_intake_operations")) is None + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges")) == 1024 + + +async def test_recorded_upload_and_completion_are_immutable_custody(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + async with intake.factory.begin() as session: + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + for assignment in ( + "provider_upload_id='replacement'", "part_bytes=8388608", "idle_timeout_seconds=99", + "completion_parts='[]'::jsonb", "completion_recorded_at=clock_timestamp()", + ): + with pytest.raises(DBAPIError, match="receipt is immutable"): + async with intake.factory.begin() as session: + await session.execute(text("UPDATE submission_source_upload_receipts SET " + assignment)) + for statement in ("DELETE FROM submission_source_upload_receipts", "TRUNCATE submission_source_upload_receipts"): + with pytest.raises(DBAPIError, match="custody cannot be deleted"): + async with intake.factory.begin() as session: + await session.execute(text(statement)) async def test_foreground_eof_seal_terminal_and_stale_fence(intake): @@ -75,7 +188,7 @@ async def test_foreground_eof_seal_terminal_and_stale_fence(intake): row = await reserve(intake, session) operation, lease = UUID(row.id), UUID(row.lease_id) async with intake.factory.begin() as session: - await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) async with intake.factory.begin() as session: deadline = datetime.now(UTC) + timedelta(minutes=2) source = await repository(session).seal( @@ -105,6 +218,7 @@ async def test_reservation_rollback_leaves_no_pointer_or_operation(intake): async with intake.factory() as session: assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 0 assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 0 + assert await session.scalar(text("SELECT count(*) FROM submission_source_upload_receipts")) == 0 assert await session.scalar(text( "SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id" ), {"id": intake.task}) is None @@ -150,7 +264,7 @@ async def test_expiry_can_only_abandon_and_cannot_resume(intake): ), {"id": operation}) with pytest.raises(IntakeCustodyConflict, match="intake_owner_stale"): async with intake.factory.begin() as session: - await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) async with intake.factory.begin() as session: assert await repository(session).abandon_expired(operation) async with intake.factory.begin() as session: @@ -219,7 +333,7 @@ async def test_recorded_source_identity_is_immutable(intake): row = await reserve(intake, session) operation, lease = UUID(row.id), UUID(row.lease_id) async with intake.factory.begin() as session: - await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) with pytest.raises(DBAPIError, match="sealed_identity"): async with intake.factory.begin() as session: await session.execute(text( @@ -253,7 +367,8 @@ async def test_intake_model_matches_installed_schema(isolated_database_env): async with engine.connect() as connection: def compare(sync): inspector = inspect(sync) - for owner in (SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge): + for owner in (SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge, + SubmissionSourceUploadReceipt): table = owner.__table__ assert { (c["name"], str(c["type"].compile(dialect=sync.dialect)), c["nullable"]) @@ -364,7 +479,7 @@ async def test_source_reservation_becomes_exact_bytes_only_after_sealing(intake, charge = await session.get(SubmissionSourceCharge, row.id) assert charge.accounted_bytes == (1024 if declared is None else 100) async with intake.factory.begin() as session: - await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) async with intake.factory.begin() as session: deadline = datetime.now(UTC) + timedelta(minutes=2) await repository(session).seal(operation, lease, 1, provider_generation="exact-source", @@ -384,7 +499,10 @@ async def test_declared_length_mismatch_cannot_record_eof_or_free_its_charge(int operation, lease = UUID(row.id), UUID(row.lease_id) with pytest.raises(DBAPIError, match="declared size mismatch"): async with intake.factory.begin() as session: - await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + await session.execute(text( + "UPDATE submission_intake_operations SET raw_sha256=:sha,raw_byte_count=100," + "eof_at=clock_timestamp() WHERE id=:id" + ), {"sha": SHA, "id": operation}) async with intake.factory.begin() as session: await repository(session).terminalize(operation, lease, 1, state="failed", failure_code="length_mismatch") async with intake.factory() as session: @@ -426,7 +544,7 @@ async def test_equal_content_sources_keep_distinct_physical_charges(intake): operation, lease = UUID(row.id), UUID(row.lease_id) operations.append(operation) async with intake.factory.begin() as session: - await repository(session).record_eof(operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) async with intake.factory.begin() as session: deadline = datetime.now(UTC) + timedelta(minutes=2) await repository(session).seal(operation, lease, 1, provider_generation=f"generation-{operation}", diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 92d4b768b..1717f418b 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,13 +23,14 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "7b109141c3a6f4eccbf24dd6c68d3fa75e709c1ed8d110cc2546e972a65537c4" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "2eb17457ad8fda593e7a997f3598dc0b2e463ab323524e42921ac65c71ffc625" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", "iso_4217_currency_codes", ) RESETTABLE_TEST_TABLES = ( + "submission_source_upload_receipts", "submission_source_capacity_profiles", "submission_source_charges", "submission_intake_operations", @@ -169,6 +170,7 @@ "submission_intake_operations", "submission_source_capacity_profiles", "submission_source_charges", + "submission_source_upload_receipts", "artifact_provider_activations", "artifact_provider_probe_results", "artifact_task_import_sources", From cb1f8d9502efd9ba7f163c4fca369e9eded21030 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 19:11:12 +0100 Subject: [PATCH 013/513] Reconcile retained migration fixtures and explicit storage surfaces --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 ++++++++++++++++ .../versions/0069_submission_intake_custody.py | 2 +- backend/app/modules/artifacts/intake/models.py | 2 +- backend/tests/migration_revision_fixtures.py | 1 + backend/tests/test_alembic.py | 1 + backend/tests/test_artifact_store_conformance.py | 13 +++++++++---- .../tests/test_checker_evidence_migrations.py | 6 +++++- backend/tests/test_identifier_schema.py | 3 +++ backend/tests/test_s3_artifact_store.py | 4 ++++ 9 files changed, 41 insertions(+), 7 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8f638d8d4..6d680a051 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -190,6 +190,7 @@ This does not authorize late foreground callbacks, cleanup charge release or PRE | Physical source accounting | `pytest tests/artifacts/test_submission_intake_custody.py -q` through isolated PostgreSQL 16 | 34 passed on the capacity-stage working tree; cleanup confirmed | No provider bytes written or cleanup/reclamation claim | | Capacity-stage static ownership | UUID inventory, behavior partition, semantic lane catalogue and module boundary tests | 254 passed; ruff passed | Final integrated suite still required | | Bounded receive | Contract/stream tests including provider backpressure, byte bounds, idle expiry and in-flight cancellation | 70 passed; ruff passed | Transport/server buffers and real provider proof remain separate | +| Durable provider receipts | Real PostgreSQL custody suite at `7c23981f7`; immutable handles/parts, direct-SQL malformed receipts, rollback and stale-owner checks | 37 passed; isolated database/role cleanup confirmed; 61 identifier/boundary checks passed | Root foreground orchestration and live provider integration remain required | | Protected target partition | `pytest tests/test_behavior_ownership.py -q` | 170 passed | Exact added paths only; no relaxed selection | | Model registration | UUID inventory and protected module-boundary tests | Both passed | No new cross-owner private imports | @@ -202,6 +203,21 @@ This does not authorize late foreground callbacks, cleanup charge release or PRE tripwire. The documentation next-stage line now names durable receipt orchestration explicitly. Neither change asserts AWS source qualification. +- The retained store conformance vector still allowed only the former four + generic methods. Invoking that vector against the new S3 store reproduced its + surface mismatch without provider I/O. Its closed assertion now includes the + seven explicit source operations for S3; local source parity is still pending. + No unrelated public methods or removed capability aliases are allowed. + +- Hosted CI exposed stale migration test assumptions after adding 0069: the + explicit revision graph omitted 0068, the exact 0062 table list included new + intake tables, and current TASK reads lacked a null-only active-operation + projection while seeding historical schemas. Update only those test fixtures; + keep captured archives and historical schema fingerprints unchanged, and + require the temporary projection to remain null before removing it. Align the + intake model's UUIDv7 constraint text with the existing canonical guard without + changing its SQL semantics or weakening the identifier assertion. + - Custody review found nullable predecessor/revision selector types and UUID shape unchecked in the SQL insert guard. A direct-SQL regression recomputed the digest and installed the matching task pointer; it reproduced acceptance diff --git a/backend/alembic/versions/0069_submission_intake_custody.py b/backend/alembic/versions/0069_submission_intake_custody.py index 6bdab6cc5..c0fec2fc5 100644 --- a/backend/alembic/versions/0069_submission_intake_custody.py +++ b/backend/alembic/versions/0069_submission_intake_custody.py @@ -45,7 +45,7 @@ failure_code VARCHAR(100), created_at TIMESTAMP WITH TIME ZONE DEFAULT clock_timestamp() NOT NULL, CONSTRAINT pk_submission_intake_operations PRIMARY KEY (id), - CONSTRAINT ck_submission_intake_operations_id_uuid7 CHECK ((get_byte(uuid_send(id),6)>>4)=7 and (get_byte(uuid_send(id),8)&192)=128), + CONSTRAINT ck_submission_intake_operations_id_uuid7 CHECK ((get_byte(uuid_send(id), 6) >> 4) = 7 and (get_byte(uuid_send(id), 8) & 192) = 128), CONSTRAINT uq_submission_intake_task_identity UNIQUE (id, task_id), CONSTRAINT uq_submission_intake_actor_key UNIQUE (actor_profile_id, idempotency_key), CONSTRAINT uq_submission_intake_source_key UNIQUE (namespace_id, namespace_fingerprint, object_ref), diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py index b10376c3d..54651f453 100644 --- a/backend/app/modules/artifacts/intake/models.py +++ b/backend/app/modules/artifacts/intake/models.py @@ -22,7 +22,7 @@ class SubmissionIntakeOperation(Base): __tablename__ = "submission_intake_operations" __table_args__ = ( - CheckConstraint("(get_byte(uuid_send(id),6)>>4)=7 and (get_byte(uuid_send(id),8)&192)=128", name="id_uuid7"), + CheckConstraint("(get_byte(uuid_send(id), 6) >> 4) = 7 and (get_byte(uuid_send(id), 8) & 192) = 128", name="id_uuid7"), UniqueConstraint("id", "task_id", name="uq_submission_intake_task_identity"), UniqueConstraint("actor_profile_id", "idempotency_key", name="uq_submission_intake_actor_key"), UniqueConstraint("namespace_id", "namespace_fingerprint", "object_ref", name="uq_submission_intake_source_key"), diff --git a/backend/tests/migration_revision_fixtures.py b/backend/tests/migration_revision_fixtures.py index 6dfd4feff..ddb0eab56 100644 --- a/backend/tests/migration_revision_fixtures.py +++ b/backend/tests/migration_revision_fixtures.py @@ -45,6 +45,7 @@ _REVISION_ARCHIVE_SCHEMA = "workstream.historical_revision_rows.v1" _REVISION_ARCHIVE_SOURCE = "6fa9a9b557fa3ae22c16af67bca25dc868f67b38" _OWNER_READ_PROJECTION_COLUMNS = ( + ("workstream_tasks", "active_submission_operation_id", "uuid"), ("actor_identity_links", "email_observed_issued_at", "bigint"), ("project_guide_compilation_attempts", "result_schema_version", "varchar(100)"), ("project_guide_compilations", "result_schema_version", "varchar(100)"), diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 44d0f421e..85fc730cd 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -388,6 +388,7 @@ def test_v01_graph_has_one_root_and_head() -> None: assert [revision.revision for revision in revisions] == [ HEAD_REVISION, + "0068_issuer_profile_email", "0067_canonical_json_restore_path", "0066_guide_check_specification", "0065_claim_starts_work", diff --git a/backend/tests/test_artifact_store_conformance.py b/backend/tests/test_artifact_store_conformance.py index a753989c8..1e264d412 100644 --- a/backend/tests/test_artifact_store_conformance.py +++ b/backend/tests/test_artifact_store_conformance.py @@ -32,6 +32,7 @@ class ArtifactStoreConformanceTests: """Reusable v2 vectors for LocalStorage and later provider adapters.""" expected_identity: ExternalServiceAdapterIdentity + expected_source_operations: frozenset[str] = frozenset() def make_store(self, root: Path) -> ArtifactStore: """Construct the provider under test.""" @@ -46,7 +47,7 @@ def close_store(store: ArtifactStore) -> None: @pytest.mark.asyncio async def test_identity_and_exact_public_surface(self, tmp_path: Path) -> None: - """Expose only shared identity and the four ArtifactStore v2 operations.""" + """Expose only generic immutable operations and the implemented source port.""" store = self.make_store(tmp_path / "store") try: assert store.identity == self.expected_identity @@ -55,7 +56,7 @@ async def test_identity_and_exact_public_surface(self, tmp_path: Path) -> None: for name in dir(store) if not name.startswith("_") and name not in {"close"} } - assert public == {"head", "identity", "observe_put_result", "open", "put"} + assert public == {"head", "identity", "observe_put_result", "open", "put"} | self.expected_source_operations for removed in ( "store", "recover_committed_store", @@ -387,10 +388,14 @@ def test_namespace_startup_values_are_closed_and_immutable() -> None: def test_artifact_store_protocol_declares_only_v2_operations() -> None: - """Prevent v1 operation or receipt methods from returning to the port.""" + """Keep the port closed to explicit generic and operation-owned source methods.""" methods = { name for name, value in inspect.getmembers(ArtifactStore) if not name.startswith("_") and (inspect.isfunction(value) or isinstance(value, property)) } - assert methods == {"head", "identity", "observe_put_result", "open", "put"} + assert methods == { + "head", "identity", "observe_put_result", "open", "put", + "begin_source_upload", "upload_source_part", "complete_source_upload", + "open_source", "observe_source_upload", "discover_source_uploads", "request_source_abort", + } diff --git a/backend/tests/test_checker_evidence_migrations.py b/backend/tests/test_checker_evidence_migrations.py index 25190adf6..faa44da1c 100644 --- a/backend/tests/test_checker_evidence_migrations.py +++ b/backend/tests/test_checker_evidence_migrations.py @@ -78,7 +78,11 @@ async def _assert_exact_0062_schema(database_url: str, monkeypatch) -> None: tables = tuple( table for table in suite_fixtures.RESETTABLE_TEST_TABLES - if table != "checker_trial_evidence" + if table not in { + "checker_trial_evidence", "submission_intake_operations", + "submission_source_capacity_profiles", "submission_source_charges", + "submission_source_upload_receipts", + } ) with monkeypatch.context() as patch: patch.setattr(suite_fixtures, "RESETTABLE_TEST_TABLES", tables) diff --git a/backend/tests/test_identifier_schema.py b/backend/tests/test_identifier_schema.py index 079571196..63f682390 100644 --- a/backend/tests/test_identifier_schema.py +++ b/backend/tests/test_identifier_schema.py @@ -9,6 +9,9 @@ # These keys express business uniqueness, not generated record identities. NATURAL_PRIMARY_KEYS = { + "submission_source_capacity_profiles": ("namespace_id",), + "submission_source_charges": ("operation_id",), + "submission_source_upload_receipts": ("operation_id",), "submission_dispatches": ("submission_id",), "submission_binding_receipts": ("admission_id",), "review_packet_guide_items": ("packet_id", "source_item_id"), diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py index 113fee58e..7f6488483 100644 --- a/backend/tests/test_s3_artifact_store.py +++ b/backend/tests/test_s3_artifact_store.py @@ -89,6 +89,10 @@ class TestMinioArtifactStoreConformance(ArtifactStoreConformanceTests): "artifact_store", "s3_compatible", ) + expected_source_operations = frozenset({ + "begin_source_upload", "upload_source_part", "complete_source_upload", + "open_source", "observe_source_upload", "discover_source_uploads", "request_source_abort", + }) def make_store(self, root: Path) -> ArtifactStore: """Construct one namespace-isolated real MinIO adapter.""" From 5140f7cda130892ee362b8185a8afb9f7cc53e8e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 19:13:38 +0100 Subject: [PATCH 014/513] Preserve retained and scale fixtures with deferred intake custody --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 5 +++++ backend/tests/contributor_reads/test_scale.py | 3 +++ backend/tests/tasks/test_payment_policy_migration.py | 1 + 3 files changed, 9 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6d680a051..e81c8bcd1 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -217,6 +217,11 @@ This does not authorize late foreground callbacks, cleanup charge release or PRE require the temporary projection to remain null before removing it. Align the intake model's UUIDv7 constraint text with the existing canonical guard without changing its SQL semantics or weakening the identifier assertion. + Register the namespace and operation-owned shared keys in the identifier + schema test's closed natural-key list. The historical payment cleanup proof + explicitly expects the new TASK pointer to stay null. The shared scale-data + fixture validates deferred foreign keys before restoring user triggers; + foreign keys remain enabled throughout, and no performance budget is changed. - Custody review found nullable predecessor/revision selector types and UUID shape unchecked in the SQL insert guard. A direct-SQL regression recomputed diff --git a/backend/tests/contributor_reads/test_scale.py b/backend/tests/contributor_reads/test_scale.py index 626d00903..ebc0a21be 100644 --- a/backend/tests/contributor_reads/test_scale.py +++ b/backend/tests/contributor_reads/test_scale.py @@ -73,6 +73,9 @@ async def _seed(database_url, task, submission, *, preparations=PREPARATIONS): "terminal_json", "terminal_digest", "eligible", "lease_id", "lease_expires_at", "started_at", "completed_at", "execute_evidence_id", "finalize_evidence_id", ), "NULL")}) + # Settle deferred foreign keys (including the nullable intake pointer) + # before ALTER TABLE; none are disabled during this fixture restore. + await connection.execute("SET CONSTRAINTS ALL IMMEDIATE") for table in _TABLES: await connection.execute(f"ALTER TABLE public.{table} ENABLE TRIGGER USER") for table in _TABLES: diff --git a/backend/tests/tasks/test_payment_policy_migration.py b/backend/tests/tasks/test_payment_policy_migration.py index baa678b6d..d14baea4f 100644 --- a/backend/tests/tasks/test_payment_policy_migration.py +++ b/backend/tests/tasks/test_payment_policy_migration.py @@ -131,6 +131,7 @@ async def test_payment_cleanup_refuses_each_retained_fact_then_preserves_current # Later migrations add columns; 0048 backfills unrouted attempts # and unstarted assignments from their own retained timestamps. added = { + "workstream_tasks": {"active_submission_operation_id": None}, "submissions": { "selected_post_submit_policy_sha256": None, "selected_post_submit_policy_body": None, From 81abbcd487e94c4bfa97b4d97897a8f0728466ae Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Wed, 11 Nov 2026 19:34:29 +0100 Subject: [PATCH 015/513] Clean exact versioned test objects in the runner-owned MinIO bucket --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 19 ++++-- backend/scripts/run_isolated_tests.py | 35 +++++----- .../tests/test_isolated_database_runner.py | 65 +++++++++++++++++++ backend/tests/test_s3_artifact_store.py | 2 +- 4 files changed, 100 insertions(+), 21 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e81c8bcd1..439b8a36a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -137,13 +137,13 @@ and verify raw bytes when resolving uncertain completion. Lost initiation can be enumerated only at the already-owned key. Abort acknowledgement never releases a charge. Existing AWS activation remains insufficient for this new surface. -The methods are hidden prerequisites. Durable handle/completion persistence, -local source support, exact cleanup authority/reclamation and AWS qualification -remain required before the public flow can use them. +The methods are hidden prerequisites. Durable handle/completion persistence is +implemented. Root orchestration, local source support, exact cleanup authority/ +reclamation and AWS qualification remain required before public use. ## Acceptance criteria -Durable receipt integration next extends the existing intake models/repository, +Durable receipt integration extends the existing intake models/repository, migration 0069, registry/reset/identifier catalogues and custody suite. One operation-owned row records immutable part/deadline bounds before initiation, then its opaque handle before parts, then ordered bounded completion receipts @@ -250,3 +250,14 @@ This does not authorize late foreground callbacks, cleanup charge release or PRE - Next implementation stage: durable upload receipt orchestration and exact cleanup custody in the same PR, followed by PRE, handoff/finalization and clients. - Remaining risks: A01–A35 integration and C01–C07 qualification. + + +Hosted storage CI passed all 121 selected tests but exposed incomplete runner +cleanup after enabling versioning. The runner must abort remaining multipart +uploads and delete exact versions and delete markers in its freshly claimed test +bucket, reject per-object deletion errors, and prove bucket removal. The S3 suite +must use the runner-provided bucket when supplied. Earlier standalone 47-pass +runs exercised the real provider but their cleanup metadata covered a different +empty bucket; they do not prove cleanup of the test objects. This repair changes +only test-infrastructure disposal, never product cleanup authority or charge +release. Re-run the real suite and cleanup regression before crediting this proof. diff --git a/backend/scripts/run_isolated_tests.py b/backend/scripts/run_isolated_tests.py index dc78517c1..c05faab68 100644 --- a/backend/scripts/run_isolated_tests.py +++ b/backend/scripts/run_isolated_tests.py @@ -266,25 +266,28 @@ async def _create_minio(endpoint: str, bucket: str, prefix: str) -> None: async def _drop_minio(endpoint: str, bucket: str, prefix: str) -> None: - """Delete every object in the exact owned bucket, then prove its removal.""" + """Remove multipart uploads and every version in the runner-owned bucket.""" async with _minio_client(endpoint) as client: - continuation = None - while True: - request = {"Bucket": bucket} - if continuation: - request["ContinuationToken"] = continuation - response = await client.list_objects_v2(**request) - objects = response.get("Contents", []) + # The child has exited. This is disposal of a freshly claimed test bucket, + # not product cleanup authority for retained submission sources. + uploads = client.get_paginator("list_multipart_uploads") + async for page in uploads.paginate(Bucket=bucket): + for upload in page.get("Uploads", []): + await client.abort_multipart_upload( + Bucket=bucket, Key=upload["Key"], UploadId=upload["UploadId"], + ) + versions = client.get_paginator("list_object_versions") + async for page in versions.paginate(Bucket=bucket): + objects = [ + {"Key": item["Key"], "VersionId": item["VersionId"]} + for item in (*page.get("Versions", []), *page.get("DeleteMarkers", [])) + ] if objects: - await client.delete_objects( - Bucket=bucket, - Delete={"Objects": [{"Key": item["Key"]} for item in objects]}, + result = await client.delete_objects( + Bucket=bucket, Delete={"Objects": objects}, ) - if not response.get("IsTruncated"): - break - continuation = response.get("NextContinuationToken") - if not continuation: - raise RunnerError("minio_cleanup_failed") + if result.get("Errors"): + raise RunnerError("minio_cleanup_failed") await client.delete_bucket(Bucket=bucket) buckets = await client.list_buckets() if bucket in {item["Name"] for item in buckets.get("Buckets", [])}: diff --git a/backend/tests/test_isolated_database_runner.py b/backend/tests/test_isolated_database_runner.py index 40eb39de4..736766a1a 100644 --- a/backend/tests/test_isolated_database_runner.py +++ b/backend/tests/test_isolated_database_runner.py @@ -535,3 +535,68 @@ async def signalled_drop(*_): os.kill(os.getpid(), signal.SIGTERM) _mock_successful_main(tmp_path, monkeypatch, signalled_drop) assert runner.main() == 0 + + +@pytest.mark.parametrize("delete_error", [False, True]) +def test_minio_cleanup_removes_versions_markers_and_uploads(monkeypatch, delete_error): + """Hidden versions and incomplete uploads cannot survive successful cleanup.""" + bucket = "workstream-ci-isolated-012345abcdef" + remaining = {("source", "old"), ("source", "new"), ("source", "marker"), ("plain", "null")} + uploads = {("partial", "upload")} + removed = [] + + class Pages: + def __init__(self, pages): + self.pages = pages + + async def paginate(self, **kwargs): + assert kwargs == {"Bucket": bucket} + for page in self.pages: + yield page + + class Client: + async def __aenter__(self): return self + async def __aexit__(self, *_): return False + + def get_paginator(self, operation): + if operation == "list_multipart_uploads": + return Pages([{"Uploads": [{"Key": "partial", "UploadId": "upload"}]}]) + assert operation == "list_object_versions" + return Pages([ + {"Versions": [{"Key": "source", "VersionId": "old"}, {"Key": "plain", "VersionId": "null"}]}, + {"Versions": [{"Key": "source", "VersionId": "new"}], + "DeleteMarkers": [{"Key": "source", "VersionId": "marker"}]}, + ]) + + async def list_objects_v2(self, **kwargs): + assert kwargs == {"Bucket": bucket} + return {"Contents": []} # Marker hides retained versions. + + async def abort_multipart_upload(self, **kwargs): + assert kwargs["Bucket"] == bucket + uploads.remove((kwargs["Key"], kwargs["UploadId"])) + + async def delete_objects(self, **kwargs): + assert kwargs["Bucket"] == bucket + if delete_error: + return {"Errors": [{"Code": "AccessDenied"}]} + for item in kwargs["Delete"]["Objects"]: + remaining.remove((item["Key"], item["VersionId"])) + return {} + + async def delete_bucket(self, **kwargs): + assert kwargs == {"Bucket": bucket} + assert not remaining and not uploads, "versioned bytes or uploads survived cleanup" + removed.append(bucket) + + async def list_buckets(self): + return {"Buckets": [{"Name": "foreign-retained-bucket"}]} + + monkeypatch.setattr(runner, "_minio_client", lambda _: Client()) + if delete_error: + with pytest.raises(runner.RunnerError, match="minio_cleanup_failed"): + asyncio.run(runner._drop_minio("http://localhost:9000", bucket, "ci/test/run")) + assert remaining and not removed + else: + asyncio.run(runner._drop_minio("http://localhost:9000", bucket, "ci/test/run")) + assert removed == [bucket] and not remaining and not uploads diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py index 7f6488483..5262e6f2a 100644 --- a/backend/tests/test_s3_artifact_store.py +++ b/backend/tests/test_s3_artifact_store.py @@ -56,7 +56,7 @@ MINIO_ENDPOINT = os.environ.get("WORKSTREAM_TEST_MINIO_ENDPOINT", "http://localhost:9000") MINIO_REGION = "us-east-1" -MINIO_BUCKET = "workstream-artifacts" +MINIO_BUCKET = os.environ.get("WORKSTREAM_TEST_MINIO_BUCKET", "workstream-artifacts") MINIO_ACCESS_KEY = "workstream-minio" MINIO_SECRET_KEY = "workstream-minio-secret-key" From f364cb5487cc5748b515bb1c3b93ca5d9b5852a1 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 00:32:49 +0100 Subject: [PATCH 016/513] Preserve operation-owned local source bytes through immutable sealing --- .ci/behavior-ownership/partition.v1.json | 6 +- .commitrail/INDEX.md | 2 +- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 5 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 38 +- backend/app/adapters/artifacts/local.py | 63 ++- .../artifacts/local_submission_source.py | 359 ++++++++++++++++++ backend/scripts/behavior_ownership.py | 1 + .../tests/test_artifact_store_conformance.py | 5 + backend/tests/test_behavior_ownership.py | 1 + backend/tests/test_local_artifact_store.py | 242 ++++++++++++ docs/roadmap_status.md | 5 +- 11 files changed, 718 insertions(+), 9 deletions(-) create mode 100644 backend/app/adapters/artifacts/local_submission_source.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index df9f5539c..6d8c256a9 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -20,6 +20,10 @@ "group": "artifacts", "target": "backend/app/adapters/artifacts/local.py" }, + { + "group": "artifacts", + "target": "backend/app/adapters/artifacts/local_submission_source.py" + }, { "group": "artifacts", "target": "backend/app/adapters/artifacts/s3_compatible.py" @@ -2621,7 +2625,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "a2f87870061a79753411f0d4d1ff941e830e00a4168af1f001f4910ba8f131b5", + "authority_digest": "84602ecd36037090ed183474d7020b1a046c316f77ea4963ef6be9e64d80d481", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index ad197fd30..8eb30f164 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Hidden foreground custody, physical source reservations and bounded S3-compatible receipt; next durable upload/cleanup orchestration, local/AWS source qualification, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Hidden foreground custody, physical source reservations and bounded S3-compatible/local source methods; next durable upload/cleanup orchestration, AWS source qualification, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 4e29bd1b0..ce9c371f7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -13,8 +13,9 @@ authorize merge or production deployment. contracts and hidden pre-handoff database custody with TASK/source/lease guards. Per-operation physical source reservations are implemented with explicit limits. Hidden S3-compatible source methods and a backpressured receiver now provide bounded parts, conditional completion, exact-version reads and scoped uncertain -upload discovery. Durable upload receipt orchestration, local source support, -confirmed physical reclamation, AWS qualification and accepted authority remain +upload discovery. Local source methods keep one ZIP inode through sealing, verify +exact generations and preserve completed bytes on late abort. Durable upload +orchestration, confirmed physical reclamation, AWS qualification and accepted authority remain to implement and integrate. The existing public flow stays active until coordinated cutover. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 439b8a36a..4c3b8d8f2 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -138,7 +138,7 @@ be enumerated only at the already-owned key. Abort acknowledgement never release a charge. Existing AWS activation remains insufficient for this new surface. The methods are hidden prerequisites. Durable handle/completion persistence is -implemented. Root orchestration, local source support, exact cleanup authority/ +implemented, together with local source methods. Root orchestration and exact cleanup authority/ reclamation and AWS qualification remain required before public use. ## Acceptance criteria @@ -206,7 +206,7 @@ This does not authorize late foreground callbacks, cleanup charge release or PRE - The retained store conformance vector still allowed only the former four generic methods. Invoking that vector against the new S3 store reproduced its surface mismatch without provider I/O. Its closed assertion now includes the - seven explicit source operations for S3; local source parity is still pending. + seven explicit source operations for both local and S3 stores. No unrelated public methods or removed capability aliases are allowed. - Hosted CI exposed stale migration test assumptions after adding 0069: the @@ -261,3 +261,37 @@ runs exercised the real provider but their cleanup metadata covered a different empty bucket; they do not prove cleanup of the test objects. This repair changes only test-infrastructure disposal, never product cleanup authority or charge release. Re-run the real suite and cleanup regression before crediting this proof. + +## Local source stage + +Extend the existing local ArtifactStore with the seven source methods through a +private helper in the same adapter package. Preserve the existing namespace +fingerprint, factory and SHA-object layout. Create each operation ZIP directly +at its final key and retain that inode through sealing; never copy or rename raw +ZIP bytes. Use exact operation locks, no-follow private descriptors, bounded +metadata publication and cancellation-resistant off-loop I/O. A completed source +survives late abort; receiving abort retains a tombstone and bytes for separate +cleanup authority. No charge reclamation or public cutover is included. + +Allowed changes: local adapter and cohesive helper, existing local/conformance +suites, exact behavior partition registration and affected current documentation. +Required proof covers bounded parts and exact read/hash, inode substitution, +namespace/handle substitution, late writes and abort, interrupted metadata/seal, +startup during a live writer, and cancellation without a surviving writable fd. +Architecture/security plan review passed with low risks after requiring abort +under the operation lock to preserve any completed source. Runtime evidence is +still required. Risk/reviewer routing remains the initiative's existing L0 scope. + + +Local source implementation evidence: 67 local/conformance cases passed on the +restored working tree, covering exact inode preservation, restarted reads, +completed-source protection on late abort, rejected inode substitution, +cancellation draining before abort, interrupted sealing, namespace/handle and +receipt substitutions, lost-initiation discovery and symlink rejection. The +170-test protected ownership suite passed after registering the new helper; +existing targets and the protected base remain unchanged. These results cover +provider primitives, not the absent public orchestration or physical reclamation. +Metadata publication uses a private temporary file, fsync and rename under the +operation lock; raw ZIP bytes are never renamed or copied. Every caller uses the +same operation lock, and existing metadata is rejected before publication. +New directories are fsynced through their parents before begin acknowledgement. diff --git a/backend/app/adapters/artifacts/local.py b/backend/app/adapters/artifacts/local.py index fa0e5fa92..6af06f7d1 100644 --- a/backend/app/adapters/artifacts/local.py +++ b/backend/app/adapters/artifacts/local.py @@ -16,6 +16,12 @@ from typing import Any, Iterator from uuid import uuid4 +from app.adapters.artifacts.local_submission_source import LocalSubmissionSource +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, SubmissionSourceCompletion, SubmissionSourceUpload, + SubmissionSourceUploadIntent, SubmissionSourcePart, +) + from app.core.cancellation import ( await_cancellation_resistant, run_blocking_cancellation_resistant, @@ -211,6 +217,59 @@ def __del__(self) -> None: """Best-effort descriptor cleanup.""" self.close() + async def _source_io(self, operation: Any, *args: Any) -> Any: + try: + return await self._run_io(operation, *args) + except ArtifactStoreError: + raise + except FileNotFoundError: + raise ArtifactObjectMissingError("submission source is missing") from None + except (OSError, ValueError): + raise ArtifactStoreUnavailableError("local submission source operation failed") from None + + async def begin_source_upload(self, intent: SubmissionSourceUploadIntent, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None) -> SubmissionSourceUpload: + return await self._source_io(LocalSubmissionSource(self).begin, intent) + + async def upload_source_part(self, upload: SubmissionSourceUpload, number: int, + data: bytes, *, operation_evidence: ArtifactProviderOperationEvidence | None = None) -> SubmissionSourcePart: + return await self._source_io(LocalSubmissionSource(self).part, upload, number, data) + + async def complete_source_upload(self, completion: SubmissionSourceCompletion, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None) -> SealedSubmissionSource: + return await self._source_io(LocalSubmissionSource(self).complete, completion) + + async def observe_source_upload(self, completion: SubmissionSourceCompletion, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None) -> SealedSubmissionSource | None: + return await self._source_io(LocalSubmissionSource(self).observe, completion) + + async def discover_source_uploads(self, intent: SubmissionSourceUploadIntent, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None) -> tuple[SubmissionSourceUpload, ...]: + return await self._source_io(LocalSubmissionSource(self).discover, intent) + + async def request_source_abort(self, upload: SubmissionSourceUpload, *, + operation_evidence: ArtifactProviderOperationEvidence | None = None) -> None: + await self._source_io(LocalSubmissionSource(self).abort, upload) + + def open_source(self, source: SealedSubmissionSource, *, operation_evidence: ArtifactProviderOperationEvidence | None = None) -> AsyncIterator[bytes]: + source = SealedSubmissionSource.model_validate(source) + helper = LocalSubmissionSource(self) + helper.location(source.location) + + async def iterate() -> AsyncIterator[bytes]: + position = 0 + digest = hashlib.sha256() + while position < source.raw_byte_count: + chunk = await self._source_io(helper.chunk, source, position) + if not chunk: + raise ArtifactIntegrityError("submission source was truncated") + position += len(chunk) + digest.update(chunk) + yield chunk + if "sha256:" + digest.hexdigest() != source.raw_sha256: + raise ArtifactIntegrityError("submission source digest mismatch") + return iterate() + async def put( self, source: CommittedArtifactSource, @@ -623,8 +682,10 @@ def _validate_existing_layout(self, root_entries: set[str]) -> None: def _validate_object_entries(self, objects_fd: int) -> set[tuple[int, int]]: """Require only canonical immutable objects and recoverable hard links.""" object_entries = set(os.listdir(objects_fd)) - if not object_entries.issubset({"sha256"}): + if not object_entries.issubset({"sha256", "submission-source"}): raise ArtifactConfigurationError("local artifact layout is incompatible") + if "submission-source" in object_entries: + LocalSubmissionSource(self).validate_layout(objects_fd) if "sha256" not in object_entries: return set() sha256_fd = self._open_existing_directory(objects_fd, "sha256") diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py new file mode 100644 index 000000000..cf7212bdf --- /dev/null +++ b/backend/app/adapters/artifacts/local_submission_source.py @@ -0,0 +1,359 @@ +"""Operation-owned local ZIPs; the existing local adapter owns all path safety.""" +from __future__ import annotations + +from contextlib import contextmanager +from datetime import UTC, datetime +import hashlib +import json +import os +import re +import stat +from typing import TYPE_CHECKING, Any, Iterator +from uuid import UUID, uuid4 + +from app.core.file_locks import acquire_exclusive_file_lock +from app.interfaces.artifacts import ( + ArtifactIntegrityError, ArtifactOperationConflictError, + ArtifactPreconditionFailedError, ArtifactStoreUnavailableError, + ArtifactInputMismatchError, ArtifactLimitExceededError, +) +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, SubmissionSourceCompletion, SubmissionSourceLocation, + SubmissionSourcePart, SubmissionSourceUpload, SubmissionSourceUploadIntent, +) + +if TYPE_CHECKING: + from app.adapters.artifacts.local import LocalStorageAdapter + +_METADATA_LIMIT = 256 * 1024 +_TEMP = re.compile(r"^\.(?:upload|seal|aborted)\.[0-9a-f]{32}\.tmp$") +_FILES = frozenset({"upload.json", "seal.json", "aborted.json", "bundle.zip"}) + + +class LocalSubmissionSource: + """Private synchronous primitives, called off-loop with cancellation drained.""" + + def __init__(self, store: LocalStorageAdapter) -> None: + self.store = store + + def location(self, value: SubmissionSourceLocation) -> SubmissionSourceLocation: + self.store._require_initialized() + value = SubmissionSourceLocation.model_validate(value) + if (value.provider_profile != "local-v2" + or value.namespace_fingerprint != self.store._expected_namespace_fingerprint()): + raise ArtifactOperationConflictError("submission source namespace mismatch") + return value + + @staticmethod + def deadline(intent: SubmissionSourceUploadIntent) -> float: + remaining = (intent.upload_deadline_at - datetime.now(UTC)).total_seconds() + if remaining <= 0: + raise ArtifactStoreUnavailableError("submission upload deadline expired") + return remaining + + @contextmanager + def locked(self, location: SubmissionSourceLocation, intent: SubmissionSourceUploadIntent | None = None, *, create: bool = False) -> Iterator[int]: + location = self.location(location) + key = hashlib.sha256(location.object_ref.encode()).hexdigest() + lock_fd = os.open(key + ".lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, + 0o600, dir_fd=self.store._locks_fd) + directories = [] + try: + self.store._assert_private_regular(lock_fd) + timeout = self.store._lock_timeout_seconds + if intent is not None: + timeout = min(timeout, self.deadline(intent)) + acquire_exclusive_file_lock(lock_fd, timeout_seconds=timeout) + if intent is not None: + self.deadline(intent) + parent = self.store._root_fd + for name in ("objects", "submission-source", "v1", str(location.operation_id)): + method = self.store._ensure_directory if create else self.store._open_existing_directory + child = method(parent, name) + if create: + os.fsync(parent) + parent = child + directories.append(parent) + yield parent + except TimeoutError: + raise ArtifactStoreUnavailableError("submission source lock deadline expired") from None + finally: + for descriptor in reversed(directories): + os.close(descriptor) + os.close(lock_fd) + + def read(self, directory: int, name: str) -> bytes: + descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + try: + info = self.store._assert_private_regular(descriptor) + if info.st_size > _METADATA_LIMIT: + raise ArtifactIntegrityError("submission source metadata exceeds bound") + raw = os.read(descriptor, _METADATA_LIMIT + 1) + if len(raw) != info.st_size: + raise ArtifactIntegrityError("submission source metadata changed") + return raw + except (ValueError, UnicodeError): + raise ArtifactIntegrityError("submission source metadata is invalid") from None + finally: + os.close(descriptor) + + def publish(self, directory: int, name: str, value: dict[str, Any]) -> None: + # Every caller holds the same operation lock. Only metadata is renamed; + # the raw ZIP remains at its original key and inode from begin onward. + try: + os.stat(name, dir_fd=directory, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise ArtifactPreconditionFailedError("submission source metadata already exists") + raw = json.dumps(value, separators=(",", ":"), sort_keys=True).encode() + if len(raw) > _METADATA_LIMIT: + raise ArtifactIntegrityError("submission source metadata exceeds bound") + temporary = f".{name[:-5]}.{uuid4().hex}.tmp" + descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, + 0o600, dir_fd=directory) + try: + self.store._write_all(descriptor, memoryview(raw)) + os.fsync(descriptor) + finally: + os.close(descriptor) + os.rename(temporary, name, src_dir_fd=directory, dst_dir_fd=directory) + os.fsync(directory) + + def upload(self, directory: int, supplied: SubmissionSourceUpload) -> SubmissionSourceUpload: + stored = SubmissionSourceUpload.model_validate_json(self.read(directory, "upload.json")) + if stored != supplied: + raise ArtifactOperationConflictError("submission upload identity mismatch") + return stored + + @staticmethod + def exists(directory: int, name: str) -> bool: + try: + os.stat(name, dir_fd=directory, follow_symlinks=False) + return True + except FileNotFoundError: + return False + + def begin(self, intent: SubmissionSourceUploadIntent) -> SubmissionSourceUpload: + intent = SubmissionSourceUploadIntent.model_validate(intent) + with self.locked(intent.location, intent, create=True) as directory: + if self.exists(directory, "upload.json") or self.exists(directory, "aborted.json"): + raise ArtifactPreconditionFailedError("submission source already initiated") + upload = SubmissionSourceUpload(intent=intent, provider_upload_id=uuid4().hex) + self.publish(directory, "upload.json", upload.model_dump(mode="json")) + descriptor = os.open("bundle.zip", os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, + 0o600, dir_fd=directory) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + os.fsync(directory) + return upload + + def part(self, upload: SubmissionSourceUpload, number: int, data: bytes) -> SubmissionSourcePart: + upload = SubmissionSourceUpload.model_validate(upload) + if type(number) is not int or not 1 <= number <= 100 or type(data) is not bytes or not data: + raise ArtifactInputMismatchError("submission source part is invalid") + intent = upload.intent + offset = (number - 1) * intent.part_bytes + limit = intent.declared_raw_bytes or intent.maximum_raw_bytes + if len(data) > intent.part_bytes or offset + len(data) > limit: + raise ArtifactLimitExceededError("submission source part exceeds bound") + with self.locked(intent.location, intent) as directory: + self.upload(directory, upload) + if self.exists(directory, "seal.json") or self.exists(directory, "aborted.json"): + raise ArtifactPreconditionFailedError("submission source no longer writable") + descriptor = os.open("bundle.zip", os.O_WRONLY | os.O_NOFOLLOW, dir_fd=directory) + try: + info = self.store._assert_private_regular(descriptor) + if info.st_size != offset or stat.S_IMODE(info.st_mode) != 0o600: + raise ArtifactPreconditionFailedError("submission source part is not next") + os.lseek(descriptor, offset, os.SEEK_SET) + self.store._write_all(descriptor, memoryview(data)) + os.fsync(descriptor) + finally: + os.close(descriptor) + self.deadline(intent) + return SubmissionSourcePart(number=number, byte_count=len(data), + provider_etag=hashlib.sha256(data).hexdigest()) + + def verify(self, descriptor: int, completion: SubmissionSourceCompletion) -> os.stat_result: + info = self.store._assert_private_regular(descriptor) + if info.st_size != completion.raw_byte_count: + raise ArtifactIntegrityError("submission source size mismatch") + raw_hash = hashlib.sha256() + position = 0 + for part in completion.parts: + part_hash = hashlib.sha256() + remaining = part.byte_count + while remaining: + chunk = os.pread(descriptor, min(self.store._buffer_bytes, remaining), position) + if not chunk: + raise ArtifactIntegrityError("submission source was truncated") + raw_hash.update(chunk) + part_hash.update(chunk) + position += len(chunk) + remaining -= len(chunk) + if part_hash.hexdigest() != part.provider_etag: + raise ArtifactIntegrityError("submission source part mismatch") + if "sha256:" + raw_hash.hexdigest() != completion.raw_sha256: + raise ArtifactIntegrityError("submission source digest mismatch") + return info + + @staticmethod + def source(completion: SubmissionSourceCompletion, info: os.stat_result) -> SealedSubmissionSource: + return SealedSubmissionSource( + location=completion.upload.intent.location, + provider_generation=f"{completion.upload.provider_upload_id}:{info.st_dev}:{info.st_ino}", + raw_sha256=completion.raw_sha256, raw_byte_count=completion.raw_byte_count, + sealed_upload_fence=completion.upload.intent.upload_fence, + ) + + def complete(self, completion: SubmissionSourceCompletion) -> SealedSubmissionSource: + completion = SubmissionSourceCompletion.model_validate(completion) + upload = completion.upload + with self.locked(upload.intent.location, upload.intent) as directory: + self.upload(directory, upload) + if self.exists(directory, "aborted.json") or self.exists(directory, "seal.json"): + raise ArtifactPreconditionFailedError("submission source completion already decided") + descriptor = os.open("bundle.zip", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + try: + info = self.verify(descriptor, completion) + if stat.S_IMODE(info.st_mode) != 0o600: + raise ArtifactIntegrityError("submission source seal state is invalid") + self.deadline(upload.intent) + self.publish(directory, "seal.json", { + "completion": completion.model_dump(mode="json"), + "source": self.source(completion, info).model_dump(mode="json"), + }) + os.fchmod(descriptor, 0o400) + os.fsync(descriptor) + return self.source(completion, info) + finally: + os.close(descriptor) + + def observe(self, completion: SubmissionSourceCompletion) -> SealedSubmissionSource | None: + completion = SubmissionSourceCompletion.model_validate(completion) + try: + with self.locked(completion.upload.intent.location) as directory: + self.upload(directory, completion.upload) + if self.exists(directory, "aborted.json") or not self.exists(directory, "seal.json"): + return None + stored, sealed = self.seal(directory) + if stored != completion: + raise ArtifactOperationConflictError("submission source completion mismatch") + descriptor = os.open("bundle.zip", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + try: + info = self.verify(descriptor, completion) + if stat.S_IMODE(info.st_mode) != 0o400: + return None + if self.source(completion, info) != sealed: + raise ArtifactIntegrityError("submission source generation mismatch") + return sealed + finally: + os.close(descriptor) + except FileNotFoundError: + return None + + def discover(self, intent: SubmissionSourceUploadIntent) -> tuple[SubmissionSourceUpload, ...]: + intent = SubmissionSourceUploadIntent.model_validate(intent) + try: + with self.locked(intent.location) as directory: + upload = SubmissionSourceUpload.model_validate_json(self.read(directory, "upload.json")) + if upload.intent != intent: + raise ArtifactOperationConflictError("submission upload intent mismatch") + if self.exists(directory, "aborted.json"): + return () + if self.exists(directory, "seal.json"): + completion, sealed = self.seal(directory) + descriptor = os.open("bundle.zip", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + try: + info = self.store._assert_private_regular(descriptor) + if completion.upload != upload or self.source(completion, info) != sealed: + raise ArtifactIntegrityError("submission source generation mismatch") + if stat.S_IMODE(info.st_mode) == 0o400: + return () + finally: + os.close(descriptor) + return (upload,) + except FileNotFoundError: + return () + + def abort(self, upload: SubmissionSourceUpload) -> None: + upload = SubmissionSourceUpload.model_validate(upload) + try: + with self.locked(upload.intent.location) as directory: + self.upload(directory, upload) + if self.exists(directory, "seal.json"): + info = os.stat("bundle.zip", dir_fd=directory, follow_symlinks=False) + if stat.S_ISREG(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o400: + return # A late abort never invalidates completed retained bytes. + if not self.exists(directory, "aborted.json"): + self.publish(directory, "aborted.json", {"provider_upload_id": upload.provider_upload_id}) + except FileNotFoundError: + return + + def seal(self, directory: int) -> tuple[SubmissionSourceCompletion, SealedSubmissionSource]: + value = json.loads(self.read(directory, "seal.json")) + if not isinstance(value, dict) or set(value) != {"completion", "source"}: + raise ArtifactIntegrityError("submission source seal is invalid") + return ( + SubmissionSourceCompletion.model_validate_json(json.dumps(value["completion"])), + SealedSubmissionSource.model_validate_json(json.dumps(value["source"])), + ) + + def chunk(self, source: SealedSubmissionSource, position: int) -> bytes: + source = SealedSubmissionSource.model_validate(source) + with self.locked(source.location) as directory: + completion, sealed = self.seal(directory) + self.upload(directory, completion.upload) + if self.exists(directory, "aborted.json"): + raise ArtifactIntegrityError("submission source was aborted") + descriptor = os.open("bundle.zip", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + try: + info = self.store._assert_private_regular(descriptor) + if (sealed != source or self.source(completion, info) != source or info.st_size != source.raw_byte_count + or stat.S_IMODE(info.st_mode) != 0o400): + raise ArtifactIntegrityError("submission source generation mismatch") + return os.pread(descriptor, min(self.store._buffer_bytes, source.raw_byte_count - position), position) + finally: + os.close(descriptor) + + def validate_layout(self, objects_fd: int) -> None: + """Check path grammar and inode safety without racing multi-file state.""" + source_fd = self.store._open_existing_directory(objects_fd, "submission-source") + try: + entries = set(os.listdir(source_fd)) + if not entries.issubset({"v1"}): + raise ArtifactIntegrityError("submission source layout is invalid") + if "v1" not in entries: + return + version_fd = self.store._open_existing_directory(source_fd, "v1") + try: + for name in os.listdir(version_fd): + try: + operation = UUID(name) + except ValueError: + raise ArtifactIntegrityError("submission source operation path is invalid") from None + if operation.version != 7 or str(operation) != name: + raise ArtifactIntegrityError("submission source operation path is invalid") + directory = self.store._open_existing_directory(version_fd, name) + try: + files = os.listdir(directory) + if len(files) > 16: + raise ArtifactIntegrityError("submission source metadata exceeds bound") + for filename in files: + if filename not in _FILES and _TEMP.fullmatch(filename) is None: + raise ArtifactIntegrityError("submission source file path is invalid") + details = self.store._stat_layout_file(directory, filename, recoverable=False) + if details is None: # Metadata publication may remove a temporary. + continue + if (stat.S_IMODE(details.st_mode) not in {0o400, 0o600} + or (filename != "bundle.zip" and details.st_size > _METADATA_LIMIT)): + raise ArtifactIntegrityError("submission source file is unsafe") + finally: + os.close(directory) + finally: + os.close(version_fd) + finally: + os.close(source_fd) diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 595efb0bc..75645ff2a 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -937,6 +937,7 @@ "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/streaming.py", + "backend/app/adapters/artifacts/local_submission_source.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", "backend/app/modules/tasks/intake_custody.py", diff --git a/backend/tests/test_artifact_store_conformance.py b/backend/tests/test_artifact_store_conformance.py index 1e264d412..f4f7c7847 100644 --- a/backend/tests/test_artifact_store_conformance.py +++ b/backend/tests/test_artifact_store_conformance.py @@ -216,6 +216,11 @@ async def test_empty_object_is_present_and_readable(self, tmp_path: Path) -> Non class TestLocalArtifactStoreConformance(ArtifactStoreConformanceTests): """Run the shared v2 contract against LocalStorage.""" + expected_source_operations = frozenset({ + "begin_source_upload", "upload_source_part", "complete_source_upload", + "open_source", "observe_source_upload", "discover_source_uploads", "request_source_abort", + }) + expected_identity = ExternalServiceAdapterIdentity("artifact_store", "local") def make_store(self, root: Path) -> ArtifactStore: diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index 401987fd2..6898af603 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2766,6 +2766,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ target, "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/streaming.py", + "backend/app/adapters/artifacts/local_submission_source.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", "backend/app/modules/tasks/intake_custody.py", diff --git a/backend/tests/test_local_artifact_store.py b/backend/tests/test_local_artifact_store.py index 30852212b..a75a9d14a 100644 --- a/backend/tests/test_local_artifact_store.py +++ b/backend/tests/test_local_artifact_store.py @@ -870,3 +870,245 @@ def fail_unlink(*_args: object, **_kwargs: object) -> None: adapter.close() assert released == [lock] + + +def local_source_intent(store): + from datetime import UTC, datetime, timedelta + from app.core.identifiers import new_record_id + from app.modules.artifacts.api.submission_intake import SubmissionSourceLocation, SubmissionSourceUploadIntent + return SubmissionSourceUploadIntent( + location=SubmissionSourceLocation(operation_id=new_record_id(), namespace_id="primary", + namespace_fingerprint=store._expected_namespace_fingerprint(), provider_profile="local-v2"), + upload_fence=1, maximum_raw_bytes=6 * 1024 * 1024, declared_raw_bytes=None, + part_bytes=5 * 1024 * 1024, idle_timeout_seconds=20.0, + upload_deadline_at=datetime.now(UTC) + timedelta(seconds=90), + ) + + +async def local_source_completion(store, upload, data): + from app.modules.artifacts.api.submission_intake import SubmissionSourceCompletion + parts = [] + for offset in range(0, len(data), upload.intent.part_bytes): + parts.append(await store.upload_source_part(upload, len(parts) + 1, data[offset:offset + upload.intent.part_bytes])) + return SubmissionSourceCompletion(upload=upload, parts=tuple(parts), + raw_sha256="sha256:" + hashlib.sha256(data).hexdigest(), raw_byte_count=len(data)) + + +@pytest.mark.asyncio +async def test_local_submission_source_keeps_one_inode_and_survives_late_abort_and_restart(tmp_path): + from app.interfaces.artifacts import ArtifactPreconditionFailedError + root = tmp_path / "store" + store = initialize_local_store(root=root, buffer_bytes=65536) + intent = local_source_intent(store) + upload = await store.begin_source_upload(intent) + path = root / "objects" / intent.location.object_ref + inode = path.stat().st_ino + data = b"x" * (5 * 1024 * 1024) + b"original tail" + completion = await local_source_completion(store, upload, data) + sealed = await store.complete_source_upload(completion) + assert await store.discover_source_uploads(intent) == () + assert path.stat().st_ino == inode and path.stat().st_nlink == 1 + assert path.stat().st_mode & 0o777 == 0o400 + await store.request_source_abort(upload) + assert await store.observe_source_upload(completion) == sealed + with pytest.raises(ArtifactPreconditionFailedError): + await store.upload_source_part(upload, 1, b"replacement") + store.close() + store = initialize_local_store(root=root, buffer_bytes=65536) + try: + chunks = [chunk async for chunk in store.open_source(sealed)] + assert max(map(len, chunks)) <= 65536 and b"".join(chunks) == data + assert path.stat().st_ino == inode + assert list(root.rglob("bundle.zip")) == [path] + finally: + store.close() + + +@pytest.mark.asyncio +async def test_local_submission_source_abort_tombstone_retains_bytes_and_fences_complete(tmp_path): + from app.interfaces.artifacts import ArtifactPreconditionFailedError + root = tmp_path / "store" + store = initialize_local_store(root=root) + try: + intent = local_source_intent(store) + upload = await store.begin_source_upload(intent) + assert await store.discover_source_uploads(intent) == (upload,) + completion = await local_source_completion(store, upload, b"partial owned bytes") + await store.request_source_abort(upload) + assert (root / "objects" / intent.location.object_ref).read_bytes() == b"partial owned bytes" + assert await store.discover_source_uploads(intent) == () + assert await store.observe_source_upload(completion) is None + with pytest.raises(ArtifactPreconditionFailedError): + await store.complete_source_upload(completion) + with pytest.raises(ArtifactPreconditionFailedError): + await store.begin_source_upload(intent) + finally: + store.close() + + +@pytest.mark.asyncio +async def test_local_submission_source_rejects_replaced_inode_even_with_identical_bytes(tmp_path): + root = tmp_path / "store" + store = initialize_local_store(root=root) + try: + upload = await store.begin_source_upload(local_source_intent(store)) + completion = await local_source_completion(store, upload, b"identical bytes") + sealed = await store.complete_source_upload(completion) + path = root / "objects" / upload.intent.location.object_ref + replacement = path.with_name("replacement") + replacement.write_bytes(b"identical bytes") + replacement.chmod(0o400) + replacement.replace(path) + with pytest.raises(ArtifactIntegrityError, match="generation"): + await store.observe_source_upload(completion) + with pytest.raises(ArtifactIntegrityError, match="generation"): + _ = [chunk async for chunk in store.open_source(sealed)] + finally: + store.close() + + +@pytest.mark.asyncio +async def test_local_submission_cancel_drains_writer_before_abort_and_allows_safe_startup(tmp_path, monkeypatch): + from app.interfaces.artifacts import ArtifactPreconditionFailedError + root = tmp_path / "store" + store = initialize_local_store(root=root) + upload = await store.begin_source_upload(local_source_intent(store)) + entered, release = threading.Event(), threading.Event() + original = store._write_all + + def paused(descriptor, chunk): + if bytes(chunk) == b"in flight": + entered.set() + if not release.wait(5): + raise AssertionError("writer was not released") + return original(descriptor, chunk) + + monkeypatch.setattr(store, "_write_all", paused) + writer = asyncio.create_task(store.upload_source_part(upload, 1, b"in flight")) + abort = None + try: + assert await asyncio.to_thread(entered.wait, 3) + reopened = await asyncio.to_thread(initialize_local_store, root=root) + reopened.close() # Layout validation tolerates an active private write. + writer.cancel() + abort = asyncio.create_task(store.request_source_abort(upload)) + await asyncio.sleep(0.05) + assert not writer.done() and not abort.done() + release.set() + with pytest.raises(asyncio.CancelledError): + await writer + await abort + assert (root / "objects" / upload.intent.location.object_ref).read_bytes() == b"in flight" + with pytest.raises(ArtifactPreconditionFailedError): + await store.upload_source_part(upload, 1, b"late writer") + finally: + release.set() + await asyncio.gather(writer, *([abort] if abort else []), return_exceptions=True) + store.close() + + +@pytest.mark.asyncio +async def test_local_submission_interrupted_seal_cannot_admit_more_parts(tmp_path, monkeypatch): + from app.interfaces.artifacts import ArtifactPreconditionFailedError + root = tmp_path / "store" + store = initialize_local_store(root=root) + upload = await store.begin_source_upload(local_source_intent(store)) + completion = await local_source_completion(store, upload, b"exact raw bytes") + original = os.fchmod + + def fail_seal(descriptor, mode): + if mode == 0o400: + raise OSError("simulated interrupted seal") + return original(descriptor, mode) + + with monkeypatch.context() as patch: + patch.setattr(os, "fchmod", fail_seal) + with pytest.raises(ArtifactStoreUnavailableError): + await store.complete_source_upload(completion) + store.close() + store = initialize_local_store(root=root) + try: + assert await store.observe_source_upload(completion) is None + with pytest.raises(ArtifactPreconditionFailedError): + await store.upload_source_part(upload, 1, b"overwrite") + await store.request_source_abort(upload) + assert (root / "objects" / upload.intent.location.object_ref).read_bytes() == b"exact raw bytes" + finally: + store.close() + + +@pytest.mark.asyncio +async def test_local_submission_rejects_foreign_namespace_handle_and_false_receipts(tmp_path): + root = tmp_path / "store" + store = initialize_local_store(root=root) + try: + intent = local_source_intent(store) + foreign = intent.model_copy(update={"location": intent.location.model_copy( + update={"namespace_fingerprint": "sha256:" + "f" * 64})}) + with pytest.raises(ArtifactOperationConflictError, match="namespace"): + await store.begin_source_upload(foreign) + assert not (root / "objects" / "submission-source").exists() + upload = await store.begin_source_upload(intent) + with pytest.raises(ArtifactOperationConflictError, match="identity"): + await store.upload_source_part(upload.model_copy(update={"provider_upload_id": "foreign"}), 1, b"forged") + completion = await local_source_completion(store, upload, b"original") + with pytest.raises(ArtifactIntegrityError, match="part"): + await store.complete_source_upload(completion.model_copy(update={"parts": ( + completion.parts[0].model_copy(update={"provider_etag": "false"}),)})) + with pytest.raises(ArtifactIntegrityError, match="digest"): + await store.complete_source_upload(completion.model_copy(update={"raw_sha256": "sha256:" + "0" * 64})) + sealed = await store.complete_source_upload(completion) + assert b"".join([part async for part in store.open_source(sealed)]) == b"original" + finally: + store.close() + + +@pytest.mark.asyncio +async def test_local_submission_lost_begin_ack_keeps_discoverable_abort_ownership(tmp_path, monkeypatch): + from app.adapters.artifacts.local_submission_source import LocalSubmissionSource + from app.interfaces.artifacts import ArtifactPreconditionFailedError + root = tmp_path / "store" + store = initialize_local_store(root=root) + intent = local_source_intent(store) + original = LocalSubmissionSource.publish + + def lost_ack(self, directory, name, value): + original(self, directory, name, value) + if name == "upload.json": + raise OSError("lost begin acknowledgement") + + with monkeypatch.context() as patch: + patch.setattr(LocalSubmissionSource, "publish", lost_ack) + with pytest.raises(ArtifactStoreUnavailableError): + await store.begin_source_upload(intent) + store.close() + store = initialize_local_store(root=root) + try: + uploads = await store.discover_source_uploads(intent) + assert len(uploads) == 1 and uploads[0].intent == intent + await store.request_source_abort(uploads[0]) + assert await store.discover_source_uploads(intent) == () + with pytest.raises(ArtifactPreconditionFailedError): + await store.begin_source_upload(intent) + finally: + store.close() + + +@pytest.mark.asyncio +async def test_local_submission_symlink_cannot_write_outside_owned_source(tmp_path): + root = tmp_path / "store" + store = initialize_local_store(root=root) + upload = await store.begin_source_upload(local_source_intent(store)) + path = root / "objects" / upload.intent.location.object_ref + outside = tmp_path / "retained" + outside.write_bytes(b"retained bytes") + path.unlink() + path.symlink_to(outside) + try: + with pytest.raises(ArtifactStoreUnavailableError): + await store.upload_source_part(upload, 1, b"overwrite") + assert outside.read_bytes() == b"retained bytes" + finally: + store.close() + with pytest.raises((ArtifactConfigurationError, ArtifactIntegrityError)): + initialize_local_store(root=root) diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 5d6665cca..863866608 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -113,8 +113,9 @@ Its hidden owner boundaries define immutable command/source values and durable foreground intake custody with a matching TASK pointer, source/lease fences and per-operation physical source reservations under explicit limits. Hidden bounded receipt and S3-compatible source capabilities cover conditional completion and -exact-version reads. Durable upload/cleanup orchestration, local source support, -AWS source qualification, one-session PRE, accepted handoff, +exact-version reads. Local source methods preserve one ZIP inode through sealing +and completed bytes on late abort. Durable upload/cleanup orchestration, AWS +source qualification, one-session PRE, accepted handoff, finalization and client cutover remain planned; the active API still uses preparation followed by admission-consuming submission. From e7624befb56e4e621f3e754958f9d33c31332c16 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 00:36:27 +0100 Subject: [PATCH 017/513] Close local source directory descriptors when parent sync fails --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 6 ++++ .../artifacts/local_submission_source.py | 2 +- backend/tests/test_local_artifact_store.py | 36 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 4c3b8d8f2..9814df3da 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -295,3 +295,9 @@ Metadata publication uses a private temporary file, fsync and rename under the operation lock; raw ZIP bytes are never renamed or copied. Every caller uses the same operation lock, and existing metadata is rejected before publication. New directories are fsynced through their parents before begin acknowledgement. + +LOCAL-SOURCE-01: architecture/security fault injection found a child directory +descriptor leak when parent fsync failed before cleanup registration. The focused +regression reproduced the open descriptor on that failure. Register the child +immediately after opening it, before any failing fsync; the failure path must +close it before releasing the operation lock. diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py index cf7212bdf..3fd4473ff 100644 --- a/backend/app/adapters/artifacts/local_submission_source.py +++ b/backend/app/adapters/artifacts/local_submission_source.py @@ -70,10 +70,10 @@ def locked(self, location: SubmissionSourceLocation, intent: SubmissionSourceUpl for name in ("objects", "submission-source", "v1", str(location.operation_id)): method = self.store._ensure_directory if create else self.store._open_existing_directory child = method(parent, name) + directories.append(child) if create: os.fsync(parent) parent = child - directories.append(parent) yield parent except TimeoutError: raise ArtifactStoreUnavailableError("submission source lock deadline expired") from None diff --git a/backend/tests/test_local_artifact_store.py b/backend/tests/test_local_artifact_store.py index a75a9d14a..7cb6720c0 100644 --- a/backend/tests/test_local_artifact_store.py +++ b/backend/tests/test_local_artifact_store.py @@ -1112,3 +1112,39 @@ async def test_local_submission_symlink_cannot_write_outside_owned_source(tmp_pa store.close() with pytest.raises((ArtifactConfigurationError, ArtifactIntegrityError)): initialize_local_store(root=root) + + +@pytest.mark.asyncio +async def test_local_submission_parent_sync_failure_closes_new_directory(tmp_path, monkeypatch): + import errno + store = initialize_local_store(root=tmp_path / "store") + opened = [] + original = store._ensure_directory + + def track_directory(parent, name): + descriptor = original(parent, name) + opened.append(descriptor) + return descriptor + + def fail_sync(_descriptor): + raise OSError(errno.EIO, "simulated parent directory sync failure") + + try: + with monkeypatch.context() as patch: + patch.setattr(store, "_ensure_directory", track_directory) + patch.setattr(os, "fsync", fail_sync) + with pytest.raises(ArtifactStoreUnavailableError): + await store.begin_source_upload(local_source_intent(store)) + assert opened + for descriptor in opened: + with pytest.raises(OSError) as failure: + os.fstat(descriptor) + assert failure.value.errno == errno.EBADF + finally: + # Close leaked test descriptors if this regression is run against the defect. + for descriptor in opened: + try: + os.close(descriptor) + except OSError: + pass + store.close() From b85ef377bead83b1002219e73297a40bc7703ae3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 03:00:41 +0100 Subject: [PATCH 018/513] Use opaque local source tokens without concrete adapter imports --- .../adapters/artifacts/local_submission_source.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py index 3fd4473ff..55a3a41bd 100644 --- a/backend/app/adapters/artifacts/local_submission_source.py +++ b/backend/app/adapters/artifacts/local_submission_source.py @@ -7,9 +7,10 @@ import json import os import re +import secrets import stat -from typing import TYPE_CHECKING, Any, Iterator -from uuid import UUID, uuid4 +from typing import Any, Iterator +from uuid import UUID from app.core.file_locks import acquire_exclusive_file_lock from app.interfaces.artifacts import ( @@ -22,9 +23,6 @@ SubmissionSourcePart, SubmissionSourceUpload, SubmissionSourceUploadIntent, ) -if TYPE_CHECKING: - from app.adapters.artifacts.local import LocalStorageAdapter - _METADATA_LIMIT = 256 * 1024 _TEMP = re.compile(r"^\.(?:upload|seal|aborted)\.[0-9a-f]{32}\.tmp$") _FILES = frozenset({"upload.json", "seal.json", "aborted.json", "bundle.zip"}) @@ -33,7 +31,7 @@ class LocalSubmissionSource: """Private synchronous primitives, called off-loop with cancellation drained.""" - def __init__(self, store: LocalStorageAdapter) -> None: + def __init__(self, store: Any) -> None: self.store = store def location(self, value: SubmissionSourceLocation) -> SubmissionSourceLocation: @@ -109,7 +107,7 @@ def publish(self, directory: int, name: str, value: dict[str, Any]) -> None: raw = json.dumps(value, separators=(",", ":"), sort_keys=True).encode() if len(raw) > _METADATA_LIMIT: raise ArtifactIntegrityError("submission source metadata exceeds bound") - temporary = f".{name[:-5]}.{uuid4().hex}.tmp" + temporary = f".{name[:-5]}.{secrets.token_hex(16)}.tmp" descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600, dir_fd=directory) try: @@ -139,7 +137,8 @@ def begin(self, intent: SubmissionSourceUploadIntent) -> SubmissionSourceUpload: with self.locked(intent.location, intent, create=True) as directory: if self.exists(directory, "upload.json") or self.exists(directory, "aborted.json"): raise ArtifactPreconditionFailedError("submission source already initiated") - upload = SubmissionSourceUpload(intent=intent, provider_upload_id=uuid4().hex) + # An opaque provider token is not a Workstream surrogate record ID. + upload = SubmissionSourceUpload(intent=intent, provider_upload_id=secrets.token_hex(16)) self.publish(directory, "upload.json", upload.model_dump(mode="json")) descriptor = os.open("bundle.zip", os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600, dir_fd=directory) From e83ee8642ad30e9b2d27eccc8f9fec60b6b7a79d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 03:00:41 +0100 Subject: [PATCH 019/513] Commit foreground upload receipts before external source operations --- .ci/behavior-ownership/partition.v1.json | 6 +- .commitrail/INDEX.md | 2 +- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 6 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 38 +++++ .../artifacts/intake/foreground_upload.py | 126 +++++++++++++++++ backend/scripts/behavior_ownership.py | 1 + .../test_submission_intake_contracts.py | 24 ++++ .../test_submission_intake_custody.py | 130 +++++++++++++++++- backend/tests/test_artifact_architecture.py | 9 +- backend/tests/test_behavior_ownership.py | 1 + docs/roadmap_status.md | 4 +- 11 files changed, 338 insertions(+), 9 deletions(-) create mode 100644 backend/app/modules/artifacts/intake/foreground_upload.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 6d8c256a9..6e92853c0 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -604,6 +604,10 @@ "group": "artifacts", "target": "backend/app/modules/artifacts/intake/capacity.py" }, + { + "group": "artifacts", + "target": "backend/app/modules/artifacts/intake/foreground_upload.py" + }, { "group": "artifacts", "target": "backend/app/modules/artifacts/intake/models.py" @@ -2625,7 +2629,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "84602ecd36037090ed183474d7020b1a046c316f77ea4963ef6be9e64d80d481", + "authority_digest": "c998d25cd6131292cb0dff169ed651698c2b84daaebe2e6761cf5333cb094545", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index 8eb30f164..b630d3508 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Hidden foreground custody, physical source reservations and bounded S3-compatible/local source methods; next durable upload/cleanup orchestration, AWS source qualification, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Hidden foreground custody, physical source reservations and bounded S3-compatible/local source methods and private upload composition; next shared foreground lifecycle/cleanup, AWS source qualification, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index ce9c371f7..41d58f95a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -14,8 +14,10 @@ contracts and hidden pre-handoff database custody with TASK/source/lease guards. Hidden S3-compatible source methods and a backpressured receiver now provide bounded parts, conditional completion, exact-version reads and scoped uncertain upload discovery. Local source methods keep one ZIP inode through sealing, verify -exact generations and preserve completed bytes on late abort. Durable upload -orchestration, confirmed physical reclamation, AWS qualification and accepted authority remain +exact generations and preserve completed bytes on late abort. Private upload +composition now commits intent, handle and EOF before provider I/O, and binds +known source facts before fenced sealing. Full foreground authorization/heartbeat +integration, confirmed physical reclamation, AWS qualification and accepted authority remain to implement and integrate. The existing public flow stays active until coordinated cutover. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 9814df3da..45be61e44 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -301,3 +301,41 @@ descriptor leak when parent fsync failed before cleanup registration. The focuse regression reproduced the open descriptor on that failure. Register the child immediately after opening it, before any failing fsync; the failure path must close it before releasing the operation lock. + +## Foreground upload composition stage + +Connect an already committed T1 operation to the existing provider and bounded +receiver through one private ART orchestrator. Inject the existing async session +factory, a factory for the public TASK custody port, and ArtifactStore. Commit +intent before begin, handle before parts, and EOF/completion before external +completion. No provider call may retain SQL row locks. Bind the returned source +to original namespace/location, raw digest/count and upload fence before sealing +under the live database owner fence. Compute explicit PRE deadline/initial lease +from database time; no default profile values are introduced. + +A single exact observation may resolve unavailable completion acknowledgement +within the immutable upload deadline. Never retry complete blindly, adopt a +precondition conflict, continue on cancellation, or start background PRE. Errors +retain operation/physical ownership for the shared foreground lifecycle and +cleanup owner. This stage does not replace that lifecycle's heartbeat, authorize +T1, expose a route, accept work or release a charge. Long-upload readiness remains +unproven until the common lifecycle heartbeat is connected. + +Allowed files: one cohesive private intake foreground uploader, existing custody +suite and fixture, exact protected partition registration, and affected capability +records. Keep repositories flush-only and module edges through public ports. +Risk remains L0; architecture/security plan and implementation review plus QA +proof review are required. Real PostgreSQL plus real local storage must prove +cross-transaction visibility and NOWAIT row locks at provider calls, rollback +before any initiation, lost begin/complete acknowledgement, cancellation and +false source identity rejection. Provider generation truth comes from qualified +adapter complete/observe/read behavior; comparing a returned generation with its +own newly persisted copy is not independent physical-version verification. + +Hosted local-stage CI exposed a type-only concrete adapter import in the private +filesystem helper and two unclassified UUID generation sites. Remove the +unnecessary concrete adapter type dependency; the helper still receives the +existing adapter's private filesystem operations and creates no adapter/factory. +Use cryptographic opaque tokens for provider upload handles and temporary names, +which are not Workstream surrogate record IDs. Existing composition and UUID +inventory guards reproduced both failures and remain unchanged. diff --git a/backend/app/modules/artifacts/intake/foreground_upload.py b/backend/app/modules/artifacts/intake/foreground_upload.py new file mode 100644 index 000000000..58966d059 --- /dev/null +++ b/backend/app/modules/artifacts/intake/foreground_upload.py @@ -0,0 +1,126 @@ +"""Foreground T2 composition for an already committed, owned intake operation. + +This private command grants no contributor authority. The outer T1–T4 lifecycle +owns authorization, heartbeats, failure terminalization and cleanup scheduling. +Failures leave durable write obligations charged; this command never retries PRE, +releases bytes, or resumes a different foreground owner. +""" +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator, Callable +from datetime import UTC, datetime, timedelta +import math +from uuid import UUID + +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker + +from app.interfaces.artifacts import ( + ArtifactIntegrityError, ArtifactProviderOperationEvidence, ArtifactStore, + ArtifactStoreUnavailableError, +) +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, SubmissionSourceCompletion, +) +from app.modules.artifacts.intake.repository import SubmissionIntakeRepository +from app.modules.artifacts.intake.streaming import receive_submission_source +from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort + + +def _duration(seconds: float) -> timedelta: + """Validate an explicit finite duration before any provider side effect.""" + if isinstance(seconds, bool) or not isinstance(seconds, (int, float)) or not math.isfinite(seconds) or seconds <= 0: + raise ValueError("foreground source duration must be finite and positive") + try: + value = timedelta(seconds=seconds) + datetime.now(UTC) + value # Validate representation, not deadline authority. + except OverflowError: + raise ValueError("foreground source duration is not representable") from None + if value <= timedelta(0): + raise ValueError("foreground source duration is below timestamp precision") + return value + + +class ForegroundSourceUpload: + """Commit every durable boundary before its external provider operation.""" + + def __init__( + self, sessions: async_sessionmaker[AsyncSession], + tasks: Callable[[AsyncSession], IntakeTaskCustodyPort], store: ArtifactStore, + ) -> None: + self._sessions, self._tasks, self._store = sessions, tasks, store + + def _repository(self, session: AsyncSession) -> SubmissionIntakeRepository: + return SubmissionIntakeRepository(session, self._tasks(session)) + + async def receive( + self, operation_id: UUID, lease_id: UUID, generation: int, + chunks: AsyncIterator[bytes], *, part_bytes: int, idle_timeout_seconds: float, + pre_timeout_seconds: float, pre_lease_seconds: float, + operation_evidence: ArtifactProviderOperationEvidence | None = None, + ) -> SealedSubmissionSource: + """Receive once under the original fence; return only committed source facts.""" + pre_timeout = _duration(pre_timeout_seconds) + pre_lease = _duration(pre_lease_seconds) + if pre_lease > pre_timeout: + raise ValueError("foreground PRE lease exceeds its hard deadline") + async with self._sessions.begin() as session: + intent = await self._repository(session).prepare_upload( + operation_id, lease_id, generation, + part_bytes=part_bytes, idle_timeout_seconds=idle_timeout_seconds, + ) + upload = await self._store.begin_source_upload(intent, operation_evidence=operation_evidence) + async with self._sessions.begin() as session: + await self._repository(session).record_upload( + operation_id, lease_id, generation, upload=upload, + ) + completion = await receive_submission_source( + self._store, upload, chunks, operation_evidence=operation_evidence, + ) + async with self._sessions.begin() as session: + await self._repository(session).record_eof( + operation_id, lease_id, generation, completion=completion, + ) + try: + source = await self._store.complete_source_upload( + completion, operation_evidence=operation_evidence, + ) + except ArtifactStoreUnavailableError: + remaining = (intent.upload_deadline_at - datetime.now(UTC)).total_seconds() + if remaining <= 0: + raise + try: + async with asyncio.timeout(remaining): + source = await self._store.observe_source_upload( + completion, operation_evidence=operation_evidence, + ) + except TimeoutError: + raise ArtifactStoreUnavailableError("submission completion observation expired") from None + if source is None: + raise + source = self._bind_source(completion, source) + async with self._sessions.begin() as session: + now = await session.scalar(select(func.clock_timestamp())) + committed = await self._repository(session).seal( + operation_id, lease_id, generation, + provider_generation=source.provider_generation, + pre_deadline_at=now + pre_timeout, lease_expires_at=now + pre_lease, + ) + if committed != source: + raise ArtifactIntegrityError("submission source differs from committed intake") + return committed + + @staticmethod + def _bind_source(completion: SubmissionSourceCompletion, source: SealedSubmissionSource) -> SealedSubmissionSource: + """Bind owner-known facts; provider generation truth belongs to the adapter.""" + try: + source = SealedSubmissionSource.model_validate(source) + except ValueError: + raise ArtifactIntegrityError("submission provider returned invalid source") from None + if (source.location != completion.upload.intent.location + or source.raw_sha256 != completion.raw_sha256 + or source.raw_byte_count != completion.raw_byte_count + or source.sealed_upload_fence != completion.upload.intent.upload_fence): + raise ArtifactIntegrityError("submission provider source identity mismatch") + return source diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 75645ff2a..0006e3482 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -937,6 +937,7 @@ "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/streaming.py", + "backend/app/modules/artifacts/intake/foreground_upload.py", "backend/app/adapters/artifacts/local_submission_source.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py index 6b1bfb79a..7db7580e5 100644 --- a/backend/tests/artifacts/test_submission_intake_contracts.py +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -334,3 +334,27 @@ async def ingress(): with pytest.raises(ArtifactStoreUnavailableError): await receive_submission_source(SlowStore(), upload, ingress()) assert stopped.is_set() + + +@pytest.mark.parametrize("field,value", [ + ("raw_sha256", "sha256:" + "f" * 64), ("raw_byte_count", 2), ("sealed_upload_fence", 2), +]) +def test_foreground_upload_source_must_match_committed_receipt_facts(field, value): + from app.interfaces.artifacts import ArtifactIntegrityError + from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload + upload = upload_value() + completion = SubmissionSourceCompletion(upload=upload, + parts=(SubmissionSourcePart(number=1, byte_count=1, provider_etag="part"),), + raw_sha256="sha256:" + "a" * 64, raw_byte_count=1) + original = SealedSubmissionSource(location=upload.intent.location, provider_generation="version", + raw_sha256=completion.raw_sha256, raw_byte_count=1, sealed_upload_fence=upload.intent.upload_fence) + assert ForegroundSourceUpload._bind_source(completion, original) == original + with pytest.raises(ArtifactIntegrityError, match="identity mismatch"): + ForegroundSourceUpload._bind_source(completion, original.model_copy(update={field: value})) + + +@pytest.mark.parametrize("seconds", [0, -1, float("inf"), float("nan"), True, "60", 1e30]) +def test_foreground_upload_rejects_unbounded_or_coercive_deadlines(seconds): + from app.modules.artifacts.intake.foreground_upload import _duration + with pytest.raises(ValueError): + _duration(seconds) diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 16874662f..9001e388f 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -58,7 +58,7 @@ async def intake(tmp_path, isolated_database_env, capacity_limits): project=str(plan.lineage.project_id), actor=str(actor.actor_profile_id), )) yield SimpleNamespace(engine=engine, factory=factory, actor=actor, task=task, assignment=assignment, - capacity_limits=capacity_limits) + capacity_limits=capacity_limits, durable_root=tmp_path / "durable") finally: await engine.dispose() @@ -655,3 +655,131 @@ async def test_invalid_declared_size_rolls_back_all_custody(intake, declared): assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 0 assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 0 assert await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": intake.task}) is None + + +def foreground_upload(intake, store): + from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload + return ForegroundSourceUpload(intake.factory, + lambda session: IntakeTaskCustody(session, task_submission_context_port(session)), store) + + +async def foreground_bytes(): + yield b"original source bytes" + + +def foreground_limits(): + """Explicit fixture limits, never approved production settings.""" + return dict(part_bytes=5 * 1024 * 1024, idle_timeout_seconds=20.0, + pre_timeout_seconds=60.0, pre_lease_seconds=30.0) + + +@pytest.mark.parametrize("scenario", ["success", "lost_complete", "lost_begin", "cancel_part", "precondition", + "fence_begin", "fence_part", "fence_complete", "foreign_source"]) +async def test_foreground_upload_committed_boundaries_and_retained_uncertainty(intake, monkeypatch, scenario): + from app.interfaces.artifacts import ArtifactIntegrityError, ArtifactPreconditionFailedError, ArtifactStoreUnavailableError + from tests.artifact_store_helpers import initialize_local_store + store = initialize_local_store(root=intake.durable_root, buffer_bytes=7) + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation, lease = UUID(row.id), UUID(row.lease_id) + seen, handles = [], [] + + async def committed(stage): + async with intake.factory.begin() as session: + # Independent real locks prove SQL locks are not retained during I/O. + for sql, parameters in ( + ("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE NOWAIT", {"id": intake.task}), + ("SELECT id FROM submission_intake_operations WHERE id=:id FOR UPDATE NOWAIT", {"id": operation}), + ("SELECT namespace_id FROM submission_source_capacity_profiles WHERE namespace_id=:id FOR UPDATE NOWAIT", {"id": "primary"}), + ): + assert (await session.execute(text(sql), parameters)).one() + stored = await session.get(SubmissionIntakeOperation, str(operation)) + receipt = await session.get(SubmissionSourceUploadReceipt, str(operation)) + assert receipt is not None and stored.state == "receiving" + if stage == "begin": + assert receipt.provider_upload_id is None and stored.raw_sha256 is None + elif stage == "part": + assert receipt.provider_upload_id and stored.raw_sha256 is None + else: + assert stored.raw_byte_count == len(b"original source bytes") + assert receipt.completion_parts and receipt.completion_recorded_at is not None + seen.append(stage) + + def checked(stage, original): + async def call(*args, **kwargs): + await committed(stage) + if stage == "observe": + assert scenario == "lost_complete", "unexpected source observation" + result = await original(*args, **kwargs) + if stage == "begin": + handles.append(result) + if scenario == "fence_" + stage: + async with intake.factory.begin() as session: + await repository(session).terminalize(operation, lease, 1, state="failed", failure_code="owner_ended") + if (stage, scenario) in {("begin", "lost_begin"), ("complete", "lost_complete")}: + raise ArtifactStoreUnavailableError("lost acknowledgement") + if stage == "part" and scenario == "cancel_part": + raise asyncio.CancelledError + if stage == "complete" and scenario == "precondition": + raise ArtifactPreconditionFailedError("conditional completion conflict") + if stage == "complete" and scenario == "foreign_source": + return result.model_copy(update={"location": result.location.model_copy(update={"operation_id": new_record_id()})}) + return result + return call + + for stage, name in (("begin", "begin_source_upload"), ("part", "upload_source_part"), + ("complete", "complete_source_upload"), ("observe", "observe_source_upload")): + monkeypatch.setattr(store, name, checked(stage, getattr(store, name))) + failures = dict(lost_begin=ArtifactStoreUnavailableError, cancel_part=asyncio.CancelledError, + precondition=ArtifactPreconditionFailedError, foreign_source=ArtifactIntegrityError, + fence_begin=IntakeCustodyConflict, fence_part=IntakeCustodyConflict, fence_complete=IntakeCustodyConflict) + try: + command = foreground_upload(intake, store).receive(operation, lease, 1, + foreground_bytes(), **foreground_limits()) + if scenario in failures: + with pytest.raises(failures[scenario]): + await command + else: + source = await command + assert seen == ["begin", "part", "complete"] + (["observe"] if scenario == "lost_complete" else []) + assert b"".join([chunk async for chunk in store.open_source(source)]) == b"original source bytes" + async with intake.factory() as session: + stored = await session.get(SubmissionIntakeOperation, str(operation)) + charge = (await session.execute(text( + "SELECT state,accounted_bytes FROM submission_source_charges WHERE operation_id=:id" + ), {"id": operation})).one() + if scenario in failures: + assert stored.provider_generation is None + assert stored.state == ("failed" if scenario.startswith("fence_") else "receiving") + assert charge == ("reserved", 1024) + else: + assert stored.state == "pre_checking" and stored.provider_generation == source.provider_generation + assert stored.raw_sha256 == source.raw_sha256 and stored.sealed_upload_fence == 1 + assert charge == ("sealed", len(b"original source bytes")) + if scenario in {"lost_begin", "cancel_part", "fence_begin", "fence_part"}: + assert stored.raw_sha256 is None + if scenario == "lost_begin": + assert await store.discover_source_uploads(handles[0].intent) == tuple(handles) + finally: + store.close() + + +async def test_foreground_upload_rolled_back_reservation_cannot_start_provider(intake, monkeypatch): + from tests.artifact_store_helpers import initialize_local_store + store = initialize_local_store(root=intake.durable_root) + async with intake.factory() as session: + async with session.begin(): + row = await reserve(intake, session, with_upload=False) + operation, lease = UUID(row.id), UUID(row.lease_id) + await session.rollback() + + async def forbidden(*args, **kwargs): + pytest.fail("provider called without committed T1") + + monkeypatch.setattr(store, "begin_source_upload", forbidden) + try: + with pytest.raises(IntakeCustodyConflict, match="unavailable"): + await foreground_upload(intake, store).receive(operation, lease, 1, + foreground_bytes(), **foreground_limits()) + finally: + store.close() diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py index c09579b37..5ec55a8bd 100644 --- a/backend/tests/test_artifact_architecture.py +++ b/backend/tests/test_artifact_architecture.py @@ -256,12 +256,13 @@ def test_only_artifact_custody_services_own_provider_execution() -> None: node.name: node for node in tree.body if isinstance(node, ast.ClassDef) - and node.name in { + and (node.name in { "ArtifactStorageOrchestrator", "CheckerArtifactOutputService", "ScopedGuideDocumentGrant", "PostSubmissionMaterializer", - } + } or (node.name == "ForegroundSourceUpload" + and path == APP_ROOT / "modules/artifacts/intake/foreground_upload.py")) } for node in ast.walk(tree): if ( @@ -289,7 +290,9 @@ def test_only_artifact_custody_services_own_provider_execution() -> None: "PostSubmissionMaterializer", } and node.func.attr != "open" - ): + ) or (owner.name == "ForegroundSourceUpload" and node.func.attr not in { + "begin_source_upload", "complete_source_upload", "observe_source_upload", + }): violations.append(f"{path.relative_to(BACKEND_ROOT)} calls {node.func.attr}") assert violations == [] diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index 6898af603..41d51ec91 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2766,6 +2766,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ target, "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/streaming.py", + "backend/app/modules/artifacts/intake/foreground_upload.py", "backend/app/adapters/artifacts/local_submission_source.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 863866608..393bb28a3 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -114,7 +114,9 @@ foreground intake custody with a matching TASK pointer, source/lease fences and per-operation physical source reservations under explicit limits. Hidden bounded receipt and S3-compatible source capabilities cover conditional completion and exact-version reads. Local source methods preserve one ZIP inode through sealing -and completed bytes on late abort. Durable upload/cleanup orchestration, AWS +and completed bytes on late abort. Private upload composition commits receipts +before external writes and binds the resulting source under the current fence. +Full foreground authorization/heartbeat integration, cleanup orchestration, AWS source qualification, one-session PRE, accepted handoff, finalization and client cutover remain planned; the active API still uses preparation followed by admission-consuming submission. From 552a5d5537bb4490612de939197f08221c54579d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 03:05:27 +0100 Subject: [PATCH 020/513] State exact upload commit ordering and scoped proof --- .commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md | 4 ++-- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 ++++++++++++-- docs/roadmap_status.md | 5 +++-- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 41d58f95a..033303108 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -15,8 +15,8 @@ Hidden S3-compatible source methods and a backpressured receiver now provide bounded parts, conditional completion, exact-version reads and scoped uncertain upload discovery. Local source methods keep one ZIP inode through sealing, verify exact generations and preserve completed bytes on late abort. Private upload -composition now commits intent, handle and EOF before provider I/O, and binds -known source facts before fenced sealing. Full foreground authorization/heartbeat +composition commits intent before provider begin, handle before parts, and EOF +before provider completion, then binds known source facts before fenced sealing. Full foreground authorization/heartbeat integration, confirmed physical reclamation, AWS qualification and accepted authority remain to implement and integrate. The existing public flow stays active until coordinated cutover. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 45be61e44..d2d3d0234 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -247,8 +247,8 @@ This does not authorize late foreground callbacks, cleanup charge release or PRE - Current-source reconciliation: rebased onto 94334ccf4 (PR #707); preserved issuer profile roadmap changes and schema head 0068. Submission owner contracts unchanged. -- Next implementation stage: durable upload receipt orchestration and exact cleanup custody in - the same PR, followed by PRE, handoff/finalization and clients. +- Next implementation stage: shared foreground authorization/heartbeat and exact cleanup + custody in the same PR, followed by PRE, handoff/finalization and clients. - Remaining risks: A01–A35 integration and C01–C07 qualification. @@ -339,3 +339,13 @@ existing adapter's private filesystem operations and creates no adapter/factory. Use cryptographic opaque tokens for provider upload handles and temporary names, which are not Workstream surrogate record IDs. Existing composition and UUID inventory guards reproduced both failures and remain unchanged. + +Private upload composition at `e83ee8642` passed 10 real PostgreSQL/local-store +cases with database/role cleanup confirmed and 390 static/local checks. Independent +provider-call transactions proved committed receipts and NOWAIT acquisition of +TASK, operation and capacity locks. A removed raw-SHA binding check made its +negative test fail. Scoped architecture/security and QA/test-delta/CI reviews +passed; none establish the still-missing public foreground lifecycle. +DOC-UPLOAD-01 corrected summary wording to distinguish intent before begin, +handle before parts and EOF before completion; receipts do not all precede +every provider call. diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 393bb28a3..1eeb65836 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -114,8 +114,9 @@ foreground intake custody with a matching TASK pointer, source/lease fences and per-operation physical source reservations under explicit limits. Hidden bounded receipt and S3-compatible source capabilities cover conditional completion and exact-version reads. Local source methods preserve one ZIP inode through sealing -and completed bytes on late abort. Private upload composition commits receipts -before external writes and binds the resulting source under the current fence. +and completed bytes on late abort. Private upload composition commits intent +before provider begin, handle before parts, and EOF before provider completion, +then binds the resulting source under the current fence. Full foreground authorization/heartbeat integration, cleanup orchestration, AWS source qualification, one-session PRE, accepted handoff, finalization and client cutover remain planned; From c054442e730761a0e4ef6d3e11029b445341be5d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:03:21 +0100 Subject: [PATCH 021/513] Specify shared foreground lease renewal and cancellation contract --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d2d3d0234..d14f8469a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -349,3 +349,41 @@ passed; none establish the still-missing public foreground lifecycle. DOC-UPLOAD-01 corrected summary wording to distinguish intent before begin, handle before parts and EOF before completion; receipts do not all precede every provider call. + +## Shared foreground lease stage + +Add one private runner for the same foreground command across upload and PRE. +Renew the existing operation lease from database time in short TASK-first owner +transactions, bounded by the persisted phase deadline. Renewal must never shorten +a live lease, including a longer PRE lease installed by sealing: use the greater +of current expiry and the deadline-capped database-now plus duration. Replace the unused +absolute-expiry heartbeat input with a positive duration; preserve its stale-owner +proof. Explicit heartbeat interval must be positive and shorter than lease duration. +No defaults, new lease identity, generation takeover, background continuation, +acceptance, automatic terminalization or charge release are allowed. + +The runner renews before invoking the callback, then runs one renewal task beside +that callback, passing the pinned operation/lease/generation tuple to its factory. +Subtract whole-transaction monotonic elapsed time from the database remaining +lease measured after flush; reject an exhausted post-commit budget before invoking +work. Sleep at most half the remaining budget and at most the explicit interval. +A renewal failure cancels and drains callback work; caller +cancellation cancels both children before draining them together with +`gather(..., return_exceptions=True)` under the existing cancellation-preserving +helper. Repeated cancellation must not return while provider writes remain live. +A completed callback's +already-known result takes precedence if it finishes alongside a renewal failure. +The full lifecycle must return only committed owner results and resolve uncertain +handoff before choosing an API response; this helper does not infer rollback. + +Allowed files: intake lease runner/repository, existing custody and contract suites, +exact protected partition registration and affected current records. L0 review +routes remain architecture/security and QA/test-delta/CI. Prove real delayed local +upload success beyond the initial lease, unchanged owner identity/generation, +immutable phase deadline caps, non-shortening PRE renewal, exhausted commit budget, +stale/terminal/wrong-lease/wrong-generation startup without callback invocation, +fencing during blocked foreground work, and cancellation without surviving child +work. Shared caller authorization, PRE and public handoff remain separate work. + +Human review focus: same-owner custody across upload/PRE, cancellation drainage, +and expiry authority without authorization or acceptance claims. From fc52a1b4243f70fa834687a62df9b420450d1765 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:08:28 +0100 Subject: [PATCH 022/513] Renew pinned foreground intake leases and drain cancelled work --- .ci/behavior-ownership/partition.v1.json | 6 +- .../artifacts/intake/foreground_lease.py | 75 ++++++++ .../modules/artifacts/intake/repository.py | 15 +- backend/scripts/behavior_ownership.py | 1 + .../test_submission_intake_contracts.py | 33 ++++ .../test_submission_intake_custody.py | 172 +++++++++++++++++- backend/tests/test_behavior_ownership.py | 1 + 7 files changed, 294 insertions(+), 9 deletions(-) create mode 100644 backend/app/modules/artifacts/intake/foreground_lease.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 6e92853c0..5866be5aa 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -604,6 +604,10 @@ "group": "artifacts", "target": "backend/app/modules/artifacts/intake/capacity.py" }, + { + "group": "artifacts", + "target": "backend/app/modules/artifacts/intake/foreground_lease.py" + }, { "group": "artifacts", "target": "backend/app/modules/artifacts/intake/foreground_upload.py" @@ -2629,7 +2633,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "c998d25cd6131292cb0dff169ed651698c2b84daaebe2e6761cf5333cb094545", + "authority_digest": "dc15adbaadae2df7f51bd35f15d210d5591dabd5f7c71f8f13367a7410ffc170", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/backend/app/modules/artifacts/intake/foreground_lease.py b/backend/app/modules/artifacts/intake/foreground_lease.py new file mode 100644 index 000000000..42c44752c --- /dev/null +++ b/backend/app/modules/artifacts/intake/foreground_lease.py @@ -0,0 +1,75 @@ +"""Keep one foreground command owned; never resume, accept or release its source.""" +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Coroutine +from datetime import timedelta +from typing import Any, TypeVar +from uuid import UUID + +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker + +from app.core.cancellation import await_completion_preserving_cancellation +from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository +from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort + +Result = TypeVar("Result") + + +class ForegroundIntakeLease: + """Renew the pinned owner in short transactions beside its foreground work.""" + + def __init__( + self, sessions: async_sessionmaker[AsyncSession], + tasks: Callable[[AsyncSession], IntakeTaskCustodyPort], *, + lease_duration: timedelta, heartbeat_interval: timedelta, + ) -> None: + if (not isinstance(lease_duration, timedelta) + or not isinstance(heartbeat_interval, timedelta) + or not timedelta(0) < heartbeat_interval < lease_duration): + raise ValueError("foreground heartbeat interval must be positive and shorter than lease duration") + self._sessions, self._tasks = sessions, tasks + self._duration = lease_duration + self._interval = heartbeat_interval.total_seconds() + + async def _renew(self, operation_id: UUID, lease_id: UUID, generation: int) -> float: + loop = asyncio.get_running_loop() + started = loop.time() + async with self._sessions.begin() as session: + remaining = await SubmissionIntakeRepository(session, self._tasks(session)).heartbeat( + operation_id, lease_id, generation, lease_duration=self._duration, + ) + # Conservative: includes lock wait, flush and commit response, not host wall time. + budget = remaining - (loop.time() - started) + if budget <= 0: + raise IntakeCustodyConflict("intake_owner_renewal_expired") + return budget + + async def run( + self, operation_id: UUID, lease_id: UUID, generation: int, + command_factory: Callable[[UUID, UUID, int], Coroutine[Any, Any, Result]], + ) -> Result: + """Invoke once after committed renewal; drain all work before returning.""" + budget = await self._renew(operation_id, lease_id, generation) + + async def pulse() -> None: + remaining = budget + while True: + await asyncio.sleep(min(self._interval, remaining / 2)) + remaining = await self._renew(operation_id, lease_id, generation) + + command = asyncio.create_task(command_factory(operation_id, lease_id, generation), + name=f"submission-foreground:{operation_id}") + renewal = asyncio.create_task(pulse(), name=f"submission-lease:{operation_id}") + try: + await asyncio.wait((command, renewal), return_when=asyncio.FIRST_COMPLETED) + if command.done(): + return command.result() + renewal.result() + raise AssertionError("foreground renewal unexpectedly returned") + finally: + command.cancel() + renewal.cancel() + await await_completion_preserving_cancellation( + asyncio.gather(command, renewal, return_exceptions=True), + ) diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py index c4cd436ac..533e6ed7e 100644 --- a/backend/app/modules/artifacts/intake/repository.py +++ b/backend/app/modules/artifacts/intake/repository.py @@ -6,7 +6,7 @@ resumed by another request or by a background PRE worker. """ -from datetime import datetime +from datetime import datetime, timedelta import json import re from uuid import UUID @@ -205,11 +205,18 @@ async def seal(self, operation_id: UUID, lease_id: UUID, generation: int, ) async def heartbeat(self, operation_id: UUID, lease_id: UUID, generation: int, - *, lease_expires_at: datetime) -> None: - """Renew within the immutable phase deadline; never revive an expired owner.""" + *, lease_duration: timedelta) -> float: + """Renew without shortening custody; return DB remaining seconds after flush.""" + if not isinstance(lease_duration, timedelta) or lease_duration <= timedelta(0): + raise ValueError("foreground lease duration must be positive") row = await self._owned(operation_id, lease_id, generation) - row.lease_expires_at = lease_expires_at + now = await self._session.scalar(select(func.clock_timestamp())) + deadline = row.upload_deadline_at if row.state == "receiving" else row.pre_deadline_at + extension = min(lease_duration, deadline - now) + row.lease_expires_at = max(row.lease_expires_at, now + extension) await self._session.flush() + now = await self._session.scalar(select(func.clock_timestamp())) + return (row.lease_expires_at - now).total_seconds() async def terminalize(self, operation_id: UUID, lease_id: UUID, generation: int, *, state: str, failure_code: str) -> None: diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 0006e3482..663d9b5d9 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -937,6 +937,7 @@ "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/streaming.py", + "backend/app/modules/artifacts/intake/foreground_lease.py", "backend/app/modules/artifacts/intake/foreground_upload.py", "backend/app/adapters/artifacts/local_submission_source.py", "backend/app/modules/artifacts/intake/repository.py", diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py index 7db7580e5..1ff349f3f 100644 --- a/backend/tests/artifacts/test_submission_intake_contracts.py +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -9,6 +9,7 @@ import pytest from pydantic import ValidationError +from app.core.identifiers import new_record_id from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES from app.modules.artifacts.api.submission_intake import ( SealedSubmissionSource, @@ -358,3 +359,35 @@ def test_foreground_upload_rejects_unbounded_or_coercive_deadlines(seconds): from app.modules.artifacts.intake.foreground_upload import _duration with pytest.raises(ValueError): _duration(seconds) + + +@pytest.mark.parametrize("duration,interval", [(0, 1), (1, 0), (1, 1), (1, 2), (-1, 1)]) +def test_foreground_lease_rejects_invalid_timing(duration, interval): + from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease + with pytest.raises(ValueError): + ForegroundIntakeLease(None, None, lease_duration=timedelta(seconds=duration), + heartbeat_interval=timedelta(seconds=interval)) + + +async def test_foreground_lease_committed_command_wins_simultaneous_pulse_failure(monkeypatch): + from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease + from app.modules.artifacts.intake.repository import IntakeCustodyConflict + runner = ForegroundIntakeLease(None, None, lease_duration=timedelta(seconds=2), + heartbeat_interval=timedelta(seconds=0.1)) + release = asyncio.Event() + calls = 0 + + async def renew(*owner): + nonlocal calls + calls += 1 + if calls == 1: + return 1 + release.set() + raise IntakeCustodyConflict("fixture_after_commit") + + async def command(*owner): + await release.wait() + return "committed" + + monkeypatch.setattr(runner, "_renew", renew) + assert await runner.run(new_record_id(), new_record_id(), 1, command) == "committed" diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 9001e388f..b1000bd0c 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -63,15 +63,16 @@ async def intake(tmp_path, isolated_database_env, capacity_limits): await engine.dispose() -async def reserve(intake, session, *, key=None, declared_raw_bytes=None, with_upload=True): +async def reserve(intake, session, *, key=None, declared_raw_bytes=None, with_upload=True, + lease_seconds=60, upload_seconds=300): now = datetime.now(UTC) row = await repository(session).reserve( metadata=SubmissionIntakeMetadata(task_id=intake.task, assignment_id=intake.assignment), actor_id=intake.actor.actor_profile_id, identity_link_id=intake.actor.identity_link_id, idempotency_key=key or new_record_id(), maximum_raw_bytes=1024, capacity_limits=intake.capacity_limits, declared_raw_bytes=declared_raw_bytes, - upload_deadline_at=now + timedelta(minutes=5), - lease_expires_at=now + timedelta(minutes=1), + upload_deadline_at=now + timedelta(seconds=upload_seconds), + lease_expires_at=now + timedelta(seconds=lease_seconds), ) if not with_upload: return row @@ -207,7 +208,7 @@ async def test_foreground_eof_seal_terminal_and_stale_fence(intake): assert tuple(stored) == ("rejected", 2, 1, None) with pytest.raises(IntakeCustodyConflict, match="intake_owner_stale"): async with intake.factory.begin() as session: - await repository(session).heartbeat(operation, lease, 1, lease_expires_at=deadline) + await repository(session).heartbeat(operation, lease, 1, lease_duration=timedelta(seconds=30)) async def test_reservation_rollback_leaves_no_pointer_or_operation(intake): @@ -783,3 +784,166 @@ async def forbidden(*args, **kwargs): foreground_bytes(), **foreground_limits()) finally: store.close() + + +def foreground_lease(intake, *, duration=2, interval=0.1): + from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease + return ForegroundIntakeLease(intake.factory, + lambda session: IntakeTaskCustody(session, task_submission_context_port(session)), + lease_duration=timedelta(seconds=duration), heartbeat_interval=timedelta(seconds=interval)) + + +async def test_foreground_lease_delayed_local_upload_and_longer_pre_lease(intake): + from tests.artifact_store_helpers import initialize_local_store + store = initialize_local_store(root=intake.durable_root, buffer_bytes=7) + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False, lease_seconds=2) + operation, lease, initial_expiry = UUID(row.id), UUID(row.lease_id), row.lease_expires_at + + async def delayed_bytes(): + while True: + async with intake.factory() as session: + now = await session.scalar(text("SELECT clock_timestamp()")) + if now > initial_expiry: + break + await asyncio.sleep(0.1) + yield b"original source bytes" + + async def command(op, owner, generation): + assert (op, owner, generation) == (operation, lease, 1) + return await foreground_upload(intake, store).receive(op, owner, generation, + delayed_bytes(), **foreground_limits()) + + source = await foreground_lease(intake).run(operation, lease, 1, command) + async with intake.factory.begin() as session: + row = await session.get(SubmissionIntakeOperation, str(operation)) + pre_expiry = row.lease_expires_at + assert row.state == "pre_checking" and row.lease_generation == 1 and row.lease_id == str(lease) + assert row.lease_expires_at > initial_expiry + assert row.provider_generation == source.provider_generation + await repository(session).heartbeat(operation, lease, 1, lease_duration=timedelta(seconds=2)) + async with intake.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(operation)) + assert row.lease_expires_at == pre_expiry + + +@pytest.mark.parametrize("invalid", ["lease", "generation", "terminal", "expired"]) +async def test_foreground_lease_invalid_owner_never_invokes_callback(intake, invalid): + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation, lease = UUID(row.id), UUID(row.lease_id) + if invalid == "terminal": + async with intake.factory.begin() as session: + await repository(session).terminalize(operation, lease, 1, state="failed", failure_code="fixture_failed") + if invalid == "expired": + async with intake.factory.begin() as session: + await session.execute(text("UPDATE submission_intake_operations SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=:id"), {"id": operation}) + called = False + + def command(*owner): + nonlocal called + called = True + raise AssertionError("stale owner invoked command") + + with pytest.raises(IntakeCustodyConflict, match="owner_stale"): + await foreground_lease(intake).run(operation, new_record_id() if invalid == "lease" else lease, + 2 if invalid == "generation" else 1, command) + assert not called + + +@pytest.mark.parametrize("stop", ["caller", "fence", "deadline"]) +async def test_foreground_lease_drains_local_write_and_retains_charge(intake, monkeypatch, stop): + from app.core.cancellation import await_completion_preserving_cancellation + from app.interfaces.artifacts import ArtifactStoreUnavailableError + from tests.artifact_store_helpers import initialize_local_store + store = initialize_local_store(root=intake.durable_root, buffer_bytes=7) + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False, + lease_seconds=2, upload_seconds=2 if stop == "deadline" else 60) + operation, lease = UUID(row.id), UUID(row.lease_id) + started, cancelled, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + original = store.upload_source_part + writes = [] + + async def held_part(*args, **kwargs): + async def write(): + started.set() + await release.wait() + result = await original(*args, **kwargs) + writes.append(result) + return result + try: + return await await_completion_preserving_cancellation(write()) + finally: + cancelled.set() + + monkeypatch.setattr(store, "upload_source_part", held_part) + + async def command(op, owner, generation): + return await foreground_upload(intake, store).receive(op, owner, generation, + foreground_bytes(), **foreground_limits()) + + runner = asyncio.create_task(foreground_lease(intake).run(operation, lease, 1, command)) + try: + await asyncio.wait_for(started.wait(), 5) + if stop == "caller": + runner.cancel() + await asyncio.sleep(0.05) + runner.cancel() + elif stop == "fence": + async with intake.factory.begin() as session: + await repository(session).terminalize(operation, lease, 1, state="failed", failure_code="fixture_fenced") + else: + await asyncio.sleep(2.1) + await asyncio.sleep(0.3) + assert not runner.done() and not cancelled.is_set() + release.set() + with pytest.raises(asyncio.CancelledError if stop == "caller" else (IntakeCustodyConflict, DBAPIError, ArtifactStoreUnavailableError)): + await asyncio.wait_for(runner, 5) + assert cancelled.is_set() and len(writes) == (0 if stop == "deadline" else 1) + assert not [task for task in asyncio.all_tasks() + if task.get_name() in {f"submission-foreground:{operation}", f"submission-lease:{operation}"}] + async with intake.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(operation)) + expiry = row.lease_expires_at + assert expiry <= row.upload_deadline_at + assert row.state == ("failed" if stop == "fence" else "receiving") + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges")) == 1024 + await asyncio.sleep(0.2) + async with intake.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(operation)) + assert row.lease_expires_at == expiry and len(writes) == (0 if stop == "deadline" else 1) + finally: + release.set() + if not runner.done(): + runner.cancel() + await asyncio.gather(runner, return_exceptions=True) + + +async def test_foreground_lease_exhausted_commit_response_budget_does_not_start(intake): + from contextlib import asynccontextmanager + from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False, lease_seconds=2) + operation, lease = UUID(row.id), UUID(row.lease_id) + + class DelayedCommitResponse: + @asynccontextmanager + async def begin(self): + async with intake.factory.begin() as session: + yield session + await asyncio.sleep(2.1) + + runner = ForegroundIntakeLease(DelayedCommitResponse(), + lambda session: IntakeTaskCustody(session, task_submission_context_port(session)), + lease_duration=timedelta(seconds=2), heartbeat_interval=timedelta(seconds=0.1)) + called = False + + def command(*owner): + nonlocal called + called = True + raise AssertionError("expired commit budget invoked command") + + with pytest.raises(IntakeCustodyConflict, match="renewal_expired"): + await runner.run(operation, lease, 1, command) + assert not called diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index 41d51ec91..46d1624fd 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2766,6 +2766,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ target, "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/streaming.py", + "backend/app/modules/artifacts/intake/foreground_lease.py", "backend/app/modules/artifacts/intake/foreground_upload.py", "backend/app/adapters/artifacts/local_submission_source.py", "backend/app/modules/artifacts/intake/repository.py", From 6ad7f6747651edc8b5f78f89267e3cec50d140aa Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:11:33 +0100 Subject: [PATCH 023/513] Prove foreground lease renewal across upload and PRE phases --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 ++++++++ .../test_submission_intake_custody.py | 23 ++++++++++++++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d14f8469a..03bb487a7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -387,3 +387,12 @@ work. Shared caller authorization, PRE and public handoff remain separate work. Human review focus: same-owner custody across upload/PRE, cancellation drainage, and expiry authority without authorization or acceptance claims. + +The private runner now implements the pinned-owner duration renewal and shared +cancellation drainage. Ten real PostgreSQL/local cases passed at `fc52a1b42`, +with isolated database/role cleanup, alongside 256 contract/partition and 109 +boundary checks. A completed-command-priority mutation failed its intended test. +Review finding LEASE-QA-001 identified missing runner proof across the phase +transition; the delayed-upload case now holds the same callback in PRE beyond +its initial PRE lease and independently observes unchanged owner and renewed +expiry. This is private custody proof, not executed PRE or public T1–T4 proof. diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index b1000bd0c..6655fc45a 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -811,8 +811,25 @@ async def delayed_bytes(): async def command(op, owner, generation): assert (op, owner, generation) == (operation, lease, 1) - return await foreground_upload(intake, store).receive(op, owner, generation, - delayed_bytes(), **foreground_limits()) + limits = dict(foreground_limits(), pre_lease_seconds=2.0) + source = await foreground_upload(intake, store).receive(op, owner, generation, + delayed_bytes(), **limits) + async with intake.factory() as session: + sealed = await session.get(SubmissionIntakeOperation, str(op)) + first_pre_expiry, pre_deadline = sealed.lease_expires_at, sealed.pre_deadline_at + # Keep the same foreground command alive in PRE beyond its first PRE lease. + while True: + async with intake.factory() as session: + now = await session.scalar(text("SELECT clock_timestamp()")) + observed = await session.get(SubmissionIntakeOperation, str(op)) + assert observed.state == "pre_checking" + assert (observed.lease_id, observed.lease_generation) == (str(owner), generation) + assert observed.pre_deadline_at == pre_deadline + if now > first_pre_expiry: + assert now < observed.lease_expires_at <= pre_deadline + break + await asyncio.sleep(0.1) + return source source = await foreground_lease(intake).run(operation, lease, 1, command) async with intake.factory.begin() as session: @@ -821,7 +838,7 @@ async def command(op, owner, generation): assert row.state == "pre_checking" and row.lease_generation == 1 and row.lease_id == str(lease) assert row.lease_expires_at > initial_expiry assert row.provider_generation == source.provider_generation - await repository(session).heartbeat(operation, lease, 1, lease_duration=timedelta(seconds=2)) + await repository(session).heartbeat(operation, lease, 1, lease_duration=timedelta(milliseconds=10)) async with intake.factory() as session: row = await session.get(SubmissionIntakeOperation, str(operation)) assert row.lease_expires_at == pre_expiry From 1da35ae7b7217884190808cc43f9928674f9197e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:18:32 +0100 Subject: [PATCH 024/513] Specify operation-scoped intake reservation and replay authority --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 03bb487a7..db0d3bfd0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -396,3 +396,44 @@ Review finding LEASE-QA-001 identified missing runner proof across the phase transition; the delayed-upload case now holds the same callback in PRE beyond its initial PRE lease and independently observes unchanged owner and renewed expiry. This is private custody proof, not executed PRE or public T1–T4 proof. + +## Intake authorization stage + +T1 cannot reuse the old prepared-generation or formal Submission authority: +reservation precedes both. Extend the existing AUTH prepared service with exact +`submission.intake.reserve` (existing `submission.create` permission), and its +contributor read family with `task.submission_operation.read` (existing +`submission.read_own` permission). Keep retained audit vocabulary. This stage +supplies the real transaction-bound authority consumed by the forthcoming ART +T1 composition; it does not expose a route or claim that reservation is wired. + +The reservation resource pins operation, task, assignment, current actor/link, +idempotency key, immutable command metadata and locked context digests, and +eligible task status. Prepared handles remain exact, single-use and bound to the +same root transaction; AUTH checks the live human identity and exact-project +Submitter grant without administrator bypass. TASK/ART remain responsible for +loading and locking canonical facts. The operation ID is never a Submission ID. +Own-operation reads use the current actor/link/grant and recorded project, +independent of current task eligibility. A later login does not replace original +operation identity-link provenance. ART must narrow by actor and key/operation +before invoking read authority; the read grant alone cannot select another owner. + +Allowed files: AUTH public intake contract and adapter, typed domain resources, +existing prepared/task-authority and contributor-read dispatch, action catalogue +and definitions, audit vocabulary migration/model-derived schema fingerprint, +focused AUTH tests and exact partition registration, affected current records. +No role/permission expansion, acceptance/finalization authority, data rewrite, +provider work, production defaults, route exposure or relaxed guard is allowed. +Risk L0; architecture/security, QA/test-delta/CI and affected docs review required. +Human review focus: exact operation binding, current authority and historical +replay separation. Plan review precedes implementation. + +Verify real PostgreSQL prepared consume/rollback and exact audit evidence; +reject foreign actor, service/admin-only actor, revoked grant/link and substituted +operation/task/key/metadata/context. Reject repeated or cross-transaction handles. +Prove own-operation read under current grant after task eligibility changes and +with a different active identity link; deny wrong-project grants. Preserve all +existing TASK prepared and contributor-read tests. Extend the closed catalogue +and audit migration together and verify migrated schema equality. Full T1 +currentness/cardinality/readiness, actor-key concurrency, body discard replay and +public concealment proof remain the next composition work, not this AUTH proof. From 71a2bff9f76debb15f1b49e613c0c6f93b6f4e04 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:19:33 +0100 Subject: [PATCH 025/513] Keep intake reservation in the project submitter authority owner --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index db0d3bfd0..52b1e890b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -419,7 +419,7 @@ operation identity-link provenance. ART must narrow by actor and key/operation before invoking read authority; the read grant alone cannot select another owner. Allowed files: AUTH public intake contract and adapter, typed domain resources, -existing prepared/task-authority and contributor-read dispatch, action catalogue +existing prepared/project-submitter and contributor-read dispatch, action catalogue and definitions, audit vocabulary migration/model-derived schema fingerprint, focused AUTH tests and exact partition registration, affected current records. No role/permission expansion, acceptance/finalization authority, data rewrite, @@ -437,3 +437,6 @@ existing TASK prepared and contributor-read tests. Extend the closed catalogue and audit migration together and verify migrated schema equality. Full T1 currentness/cardinality/readiness, actor-key concurrency, body discard replay and public concealment proof remain the next composition work, not this AUTH proof. + +Reservation extends the existing project-submitter evaluator with its own exact +resource and prepared binding; TASK claim/manager/read guards stay unchanged. From 7f3fb1a705609c5c9bdf53042d418a67d9f4284a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:31:08 +0100 Subject: [PATCH 026/513] Authorize exact intake reservations and current own-operation reads --- .ci/behavior-ownership/partition.v1.json | 14 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 +- .../0070_submission_intake_authority.py | 49 +++++ backend/app/modules/audit/schemas.py | 3 +- .../authorization/action_definitions.py | 1 + .../authorization/api/contributor_reads.py | 2 +- .../authorization/api/submission_intake.py | 42 +++++ .../artifact_project_authority.py | 11 +- .../app/modules/authorization/catalogue.py | 7 +- .../authorization/domain/action_groups.py | 4 +- .../app/modules/authorization/domain/audit.py | 4 + .../authorization/domain/audit_targets.py | 8 + .../authorization/domain/contributor_reads.py | 2 + .../authorization/domain/submission_intake.py | 44 +++++ backend/app/modules/authorization/prepared.py | 17 ++ backend/app/modules/authorization/runtime.py | 2 + .../authorization/submission_intake.py | 113 ++++++++++++ backend/scripts/behavior_ownership.py | 3 + .../tests/authorization/catalogue_fixtures.py | 3 + .../task_authority/test_intake_authority.py | 170 ++++++++++++++++++ .../task_authority/test_prepared.py | 51 ++++++ backend/tests/authorization/test_catalogue.py | 4 +- backend/tests/conftest.py | 2 +- backend/tests/test_alembic.py | 23 +++ backend/tests/test_behavior_ownership.py | 3 + 25 files changed, 585 insertions(+), 13 deletions(-) create mode 100644 backend/alembic/versions/0070_submission_intake_authority.py create mode 100644 backend/app/modules/authorization/api/submission_intake.py create mode 100644 backend/app/modules/authorization/domain/submission_intake.py create mode 100644 backend/app/modules/authorization/submission_intake.py create mode 100644 backend/tests/authorization/task_authority/test_intake_authority.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 5866be5aa..ec79d2afe 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -836,6 +836,10 @@ "group": "auth", "target": "backend/app/modules/authorization/api/project_setup_finalization.py" }, + { + "group": "auth", + "target": "backend/app/modules/authorization/api/submission_intake.py" + }, { "group": "auth", "target": "backend/app/modules/authorization/api/task_queues.py" @@ -1064,6 +1068,10 @@ "group": "auth", "target": "backend/app/modules/authorization/domain/submission_history.py" }, + { + "group": "auth", + "target": "backend/app/modules/authorization/domain/submission_intake.py" + }, { "group": "auth", "target": "backend/app/modules/authorization/domain/task_authority.py" @@ -1268,6 +1276,10 @@ "group": "auth", "target": "backend/app/modules/authorization/submission_creation_authorization.py" }, + { + "group": "auth", + "target": "backend/app/modules/authorization/submission_intake.py" + }, { "group": "auth", "target": "backend/app/modules/authorization/submission_preparation.py" @@ -2633,7 +2645,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "dc15adbaadae2df7f51bd35f15d210d5591dabd5f7c71f8f13367a7410ffc170", + "authority_digest": "2ebaa06f0f65d9ddad2d1013d0256f51ccb8248a09ae3c14bb518c118041c5ce", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 52b1e890b..d392f16ac 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -432,7 +432,7 @@ Verify real PostgreSQL prepared consume/rollback and exact audit evidence; reject foreign actor, service/admin-only actor, revoked grant/link and substituted operation/task/key/metadata/context. Reject repeated or cross-transaction handles. Prove own-operation read under current grant after task eligibility changes and -with a different active identity link; deny wrong-project grants. Preserve all +under its current active identity link; deny revoked/foreign links and wrong-project grants. Preserve all existing TASK prepared and contributor-read tests. Extend the closed catalogue and audit migration together and verify migrated schema equality. Full T1 currentness/cardinality/readiness, actor-key concurrency, body discard replay and @@ -440,3 +440,17 @@ public concealment proof remain the next composition work, not this AUTH proof. Reservation extends the existing project-submitter evaluator with its own exact resource and prepared binding; TASK claim/manager/read guards stay unchanged. + +Canonical identity currently permits one link per actor (database uniqueness). +A renewed login uses that stable link; this stage does not invent a second active +link or weaken identity custody to exercise a hypothetical replay configuration. + +Migration 0070 adds only the two action/permission pairs and exact operation audit +target to the existing closed constraints. A real before/after schema manifest +comparison confirmed that only those two audit constraints change. Initial real +AUTH negatives exposed missing prepared-denial registration: rejected actors +raised an unsupported-denial error instead of canonical evidence. Register the +exact new action/resource pair and compare the denial binding; the fixed-service +matrix then passed. Live own-operation reads consume resolved historical facts +without an eligible-status input. ART must still prove stored-operation replay +after task progression and denied-body nonconsumption in T1 composition. diff --git a/backend/alembic/versions/0070_submission_intake_authority.py b/backend/alembic/versions/0070_submission_intake_authority.py new file mode 100644 index 000000000..ddea0d64b --- /dev/null +++ b/backend/alembic/versions/0070_submission_intake_authority.py @@ -0,0 +1,49 @@ +"""Admit exact source-reservation and own-operation read authorization evidence.""" +from alembic import op +from sqlalchemy import text + +revision = "0070_submission_intake_authority" +down_revision = "0069_submission_intake_custody" +branch_labels = None +depends_on = None + + +def _definition(name): + return op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_constraintdef(oid) FROM pg_catalog.pg_constraint " + "WHERE conrelid='public.audit_events'::regclass AND conname=:name" + ), {"name": name}).scalar_one() + + +def _replace(name, definition): + op.execute("ALTER TABLE public.audit_events DROP CONSTRAINT " + name) + op.execute("ALTER TABLE public.audit_events ADD CONSTRAINT " + name + " " + definition) + + +def upgrade(): + """Extend closed evidence vocabulary without rewriting retained decisions.""" + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.audit_events IN ACCESS EXCLUSIVE MODE") + name = "ck_audit_events_authorization_action_evidence" + definition = _definition(name) + anchor = "(((action_id)::text = 'contribution.read_self'::text) AND ((permission_id)::text = 'contribution.read_self'::text))" + actions = (("submission.intake.reserve", "submission.create"), + ("task.submission_operation.read", "submission.read_own")) + if definition.count(anchor) != 2 or any(action in definition for action, _ in actions): + raise RuntimeError("intake authorization audit action constraint shape changed") + addition = "".join(f" OR (((action_id)::text = '{action}'::text) AND ((permission_id)::text = '{permission}'::text))" + for action, permission in actions) + _replace(name, definition.replace(anchor, anchor + addition)) + name = "ck_audit_events_authority_privacy_bounds" + definition = _definition(name) + if "'submission_operation'::character varying" in definition: + raise RuntimeError("intake audit target constraint already changed") + positions = [definition.index("resource_type IS NULL"), definition.index("target_ref_kind IS NULL")] + for start in sorted(positions, reverse=True): + index = definition.index("ARRAY[", start) + len("ARRAY[") + definition = definition[:index] + "('submission_operation'::character varying)::text, " + definition[index:] + _replace(name, definition) + + +def downgrade(): + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/modules/audit/schemas.py b/backend/app/modules/audit/schemas.py index 7ebf83628..4dfd3a8ee 100644 --- a/backend/app/modules/audit/schemas.py +++ b/backend/app/modules/audit/schemas.py @@ -35,7 +35,7 @@ ) _RESOURCE_TYPES = frozenset( """task_post_submit_routing_manifest joint_lifecycle_control checker_run selected_pre_submit_run outbox_event outbox_delivery actor_profile actor_identity_link admin_role_grant project qualification_snapshot project_role_grant task - submission submission_creation submission_binding review contribution compensation_award compensation_delivery compensation_adapter_binding contribution_policy operations + submission_operation submission submission_creation submission_binding review contribution compensation_award compensation_delivery compensation_adapter_binding contribution_policy operations audit_event project_create_operation project_submission_artifact_policy_mutation project_guide_activation pre_submit_checker_input project_guide_compilation_request project_guide_compilation_attempt project_guide_sufficiency_projection @@ -45,6 +45,7 @@ ) _UUID_TARGET_KINDS = frozenset( { + "submission_operation", "joint_lifecycle_control", "actor_profile", "actor_identity_link", diff --git a/backend/app/modules/authorization/action_definitions.py b/backend/app/modules/authorization/action_definitions.py index 4475dc6f2..2aa06c193 100644 --- a/backend/app/modules/authorization/action_definitions.py +++ b/backend/app/modules/authorization/action_definitions.py @@ -14,6 +14,7 @@ ACTION_DEFINITIONS = ( + _active(ActionId.SUBMISSION_INTAKE_RESERVE, PermissionId.SUBMISSION_CREATE, ActionOwner.SUBMISSION_INTAKE), _active( ActionId.ACTOR_PROJECT_LIST, PermissionId.ACTOR_PROFILE_READ_SELF, ActionOwner.PILOT_READ_2 ), diff --git a/backend/app/modules/authorization/api/contributor_reads.py b/backend/app/modules/authorization/api/contributor_reads.py index 1166852eb..1b6b07114 100644 --- a/backend/app/modules/authorization/api/contributor_reads.py +++ b/backend/app/modules/authorization/api/contributor_reads.py @@ -8,7 +8,7 @@ ContributorReadAction = Literal[ "actor.project.list", "actor.assignment.list", "actor.submission.list", "actor.work_summary.read", "task.submission_bundle_preparation.list", - "task.submission_bundle_preparation.read", + "task.submission_bundle_preparation.read", "task.submission_operation.read", ] _ACTIONS = frozenset(ContributorReadAction.__args__) JsonQueryValue = str | int | None diff --git a/backend/app/modules/authorization/api/submission_intake.py b/backend/app/modules/authorization/api/submission_intake.py new file mode 100644 index 000000000..8396a2e61 --- /dev/null +++ b/backend/app/modules/authorization/api/submission_intake.py @@ -0,0 +1,42 @@ +"""Operation-scoped intake authority; these facts are not a grant or acceptance.""" +from dataclasses import dataclass +from typing import Literal, Protocol +from uuid import UUID + + +@dataclass(frozen=True, slots=True) +class IntakeReservationAuthorityFacts: + """Canonical locked facts supplied by ART/TASK before reserving source custody.""" + operation_id: UUID + project_id: UUID + task_id: UUID + assignment_id: UUID + actor_profile_id: UUID + identity_link_id: UUID + idempotency_key: UUID + metadata_sha256: str + locked_context_sha256: str + task_status: Literal["in_progress", "needs_revision"] + + +@dataclass(frozen=True, slots=True) +class IntakeOperationReadFacts: + """An actor-owned stored operation, resolved before current-task eligibility.""" + operation_id: UUID + project_id: UUID + task_id: UUID + actor_profile_id: UUID + + +class IntakeAuthorityDenied(RuntimeError): + """Concealed intake authorization failure.""" + + +class IntakeAuthorizationPort(Protocol): + """The caller owns root transactions, product locks and original provenance.""" + async def lock_actor(self, actor_id: UUID, identity_link_id: UUID) -> None: ... + async def prepare(self, facts: IntakeReservationAuthorityFacts) -> object: ... + async def consume(self, handle: object, facts: IntakeReservationAuthorityFacts) -> UUID: ... + async def authorize_read(self, facts: IntakeOperationReadFacts) -> UUID: ... + async def restage_denial(self, error: IntakeAuthorityDenied) -> bool: ... + def close(self) -> None: ... diff --git a/backend/app/modules/authorization/artifact_project_authority.py b/backend/app/modules/authorization/artifact_project_authority.py index 2d19f3bce..0bb5490dc 100644 --- a/backend/app/modules/authorization/artifact_project_authority.py +++ b/backend/app/modules/authorization/artifact_project_authority.py @@ -4,6 +4,7 @@ from uuid import UUID +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext from app.modules.authorization.catalogue import ActionAvailability, ActionId from app.modules.authorization.schemas import AdminRole from app.modules.authorization.domain.task_authority import ( @@ -22,7 +23,7 @@ PROJECT_SUBMITTER_ACTIONS = TASK_SUBMITTER_ACTIONS | { - ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE, ActionId.SUBMISSION_CREATE, + ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE, ActionId.SUBMISSION_CREATE, ActionId.SUBMISSION_INTAKE_RESERVE, } PROJECT_AUTHORITY_ACTIONS = TASK_ACTIONS | TASK_IMPORT_BATCH_ACTIONS | PROJECT_SUBMITTER_ACTIONS | { ActionId.ARTIFACT_GUIDE_SOURCE_INGEST, @@ -187,9 +188,11 @@ def evaluate_submitter_authority(action, context, authority, resource, lifecycle denial = lifecycle_denial if denial is None and action.availability is not ActionAvailability.ACTIVE: denial = AuthorizationDenialCode.ACTION_UNAVAILABLE - elif denial is None and not isinstance( - resource, - (SubmissionBundlePreparationResourceContext, SubmissionCreationResourceContext), + elif denial is None and ( + (action.action_id is ActionId.SUBMISSION_INTAKE_RESERVE + and type(resource) is not IntakeReservationResourceContext) + or (action.action_id is not ActionId.SUBMISSION_INTAKE_RESERVE + and not isinstance(resource, (SubmissionBundlePreparationResourceContext, SubmissionCreationResourceContext))) ): denial = AuthorizationDenialCode.RESOURCE_GUARD_DENIED elif denial is None and resource.scope_project_id != authority.scope_project_id: diff --git a/backend/app/modules/authorization/catalogue.py b/backend/app/modules/authorization/catalogue.py index 821abe1b0..14804b7eb 100644 --- a/backend/app/modules/authorization/catalogue.py +++ b/backend/app/modules/authorization/catalogue.py @@ -113,6 +113,8 @@ class PermissionId(StrEnum): class ActionId(StrEnum): """Closed action identifiers reserved by approved owner chunks.""" + SUBMISSION_INTAKE_RESERVE = "submission.intake.reserve" + TASK_SUBMISSION_OPERATION_READ = "task.submission_operation.read" TASK_SUBMISSION_LIST = "task.submission.list" SUBMISSION_READ = "submission.read" SUBMISSION_CHECKER_RUN_LIST = "submission.checker_run.list" @@ -325,6 +327,7 @@ class ActionId(StrEnum): ActionId.ACTOR_WORK_SUMMARY_READ, ActionId.TASK_SUBMISSION_BUNDLE_PREPARATION_LIST, ActionId.TASK_SUBMISSION_BUNDLE_PREPARATION_READ, + ActionId.TASK_SUBMISSION_OPERATION_READ, } ) CONTRIBUTOR_READ_ACTIONS = CONTRIBUTOR_WORK_READ_ACTIONS | {ActionId.ACTOR_PROJECT_LIST} @@ -396,6 +399,7 @@ class ActionOwner(StrEnum): PILOT_05 = "PILOT-05" PILOT_08 = "PILOT-08" PILOT_10 = "PILOT-10" + SUBMISSION_INTAKE = "WS-SUBMIT-001" PILOT_READ_2 = "PILOT-READ-2" CLI_46 = "WS-CLI-001-46" PILOT_READ_3 = "PILOT-READ-3" @@ -563,7 +567,7 @@ def _active( def _require_catalogue_counts() -> None: """Keep the closed action inventory and permission boundary exact.""" - if len(PERMISSION_IDS) != 94 or len(ACTION_IDS) != 190: + if len(PERMISSION_IDS) != 94 or len(ACTION_IDS) != 192: raise RuntimeError("authorization catalogue count mismatch") if len(HISTORICAL_PERMISSION_IDS) != 49 or len(NEW_PERMISSION_IDS) != 45: raise RuntimeError("authorization permission boundary mismatch") @@ -693,6 +697,7 @@ def _validate_action_definitions(definitions: tuple[ActionDefinition, ...]) -> N ActionId.OPERATIONS_ARTIFACT_STORAGE_ADMISSION_READ, ActionId.ARTIFACT_GUIDE_SOURCE_INGEST, ActionId.ARTIFACT_GUIDE_SOURCE_READ, + ActionId.SUBMISSION_INTAKE_RESERVE, ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE, ActionId.SUBMISSION_CREATE, ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE, diff --git a/backend/app/modules/authorization/domain/action_groups.py b/backend/app/modules/authorization/domain/action_groups.py index 6877c02c9..250289e86 100644 --- a/backend/app/modules/authorization/domain/action_groups.py +++ b/backend/app/modules/authorization/domain/action_groups.py @@ -72,6 +72,7 @@ def supports_prepared_denial(action_id: ActionId, resource_context: object) -> bool: """Admit only the existing action/context pairs for prepare-time denial evidence.""" + from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext from app.modules.authorization.domain.task_authority import TASK_ACTIONS, TaskAuthorityResourceContext from app.modules.authorization.domain.project_create import ProjectCreateResourceContext from app.modules.authorization.domain.checker_retry import ( @@ -83,7 +84,8 @@ def supports_prepared_denial(action_id: ActionId, resource_context: object) -> b ProjectPolicyMutationPrepareDenialResourceContext, ProjectSubmissionArtifactPolicyMutationResourceContext, ) return ( - ( + (action_id is ActionId.SUBMISSION_INTAKE_RESERVE and type(resource_context) is IntakeReservationResourceContext) + or ( action_id in checker_outputs.CHECKER_OUTPUT_ACTIONS and type(resource_context) is checker_outputs.CheckerOutputResourceContext ) diff --git a/backend/app/modules/authorization/domain/audit.py b/backend/app/modules/authorization/domain/audit.py index cb613ae14..6b1c18747 100644 --- a/backend/app/modules/authorization/domain/audit.py +++ b/backend/app/modules/authorization/domain/audit.py @@ -20,6 +20,8 @@ "checker_run", "selected_pre_submit_run", "task_post_submit_routing_manifest", + "submission_intake_reservation", + "submission_operation_read", "task_authority", "task_submission_history", "submission_history", @@ -85,6 +87,8 @@ "checker_run", "selected_pre_submit_run", "task_post_submit_routing_manifest", + "submission_intake_reservation", + "submission_operation_read", "task_authority", "task_submission_history", "submission_history", diff --git a/backend/app/modules/authorization/domain/audit_targets.py b/backend/app/modules/authorization/domain/audit_targets.py index 624239a67..2585acbfe 100644 --- a/backend/app/modules/authorization/domain/audit_targets.py +++ b/backend/app/modules/authorization/domain/audit_targets.py @@ -1,6 +1,8 @@ """Exact project resource audit selectors, without raw product facts.""" from uuid import UUID +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext +from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext from app.modules.authorization.catalogue import ActionId from app.modules.authorization.domain.lifecycle import ReviewLifecycleActivationContract @@ -108,6 +110,12 @@ def project_authority_audit_target( ProjectGuideActivationResourceContext, ) + if type(resource) is IntakeReservationResourceContext or ( + type(resource) is ContributorWorkReadResourceContext + and resource.resource_type == "submission_operation_read" + ): + return (str(resource.scope_project_id), "submission_operation", str(resource.resource_id), + "submission_operation", str(resource.resource_id)) if type(resource) is ReviewLifecycleActivationContract: return None, resource.resource_type, str(resource.resource_id), "joint_lifecycle_control", str(resource.resource_id) if type(resource) is TaskImportBatchResourceContext: diff --git a/backend/app/modules/authorization/domain/contributor_reads.py b/backend/app/modules/authorization/domain/contributor_reads.py index 00e4db32b..d8b43f0d5 100644 --- a/backend/app/modules/authorization/domain/contributor_reads.py +++ b/backend/app/modules/authorization/domain/contributor_reads.py @@ -31,12 +31,14 @@ def exact_actor(self): ContributorWorkResourceType = Literal[ "actor_assignment_collection", "actor_submission_collection", "actor_work_summary", + "submission_operation_read", "task_submission_bundle_preparation_collection", "submission_bundle_preparation_read", ] _ACTOR_WIDE = frozenset({ "actor_assignment_collection", "actor_submission_collection", "actor_work_summary", }) WORK_RESOURCE_BY_ACTION = { + ActionId.TASK_SUBMISSION_OPERATION_READ: "submission_operation_read", ActionId.ACTOR_ASSIGNMENT_LIST: "actor_assignment_collection", ActionId.ACTOR_SUBMISSION_LIST: "actor_submission_collection", ActionId.ACTOR_WORK_SUMMARY_READ: "actor_work_summary", diff --git a/backend/app/modules/authorization/domain/submission_intake.py b/backend/app/modules/authorization/domain/submission_intake.py new file mode 100644 index 000000000..d4e2ed377 --- /dev/null +++ b/backend/app/modules/authorization/domain/submission_intake.py @@ -0,0 +1,44 @@ +"""Exact reservation commitment; existing project Submitter authority decides.""" +import json +from typing import Literal +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from app.modules.authorization.catalogue import ActionId + + +class IntakeReservationResourceContext(BaseModel): + """A source-custody reservation, never a prepared artifact or Submission.""" + model_config = ConfigDict(extra="forbid", frozen=True, strict=True, revalidate_instances="always") + resource_type: Literal["submission_intake_reservation"] = "submission_intake_reservation" + resource_id: UUID + scope_project_id: UUID + task_id: UUID + assignment_id: UUID + actor_profile_id: UUID + identity_link_id: UUID + idempotency_key: UUID + metadata_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") + locked_context_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") + task_status: Literal["in_progress", "needs_revision"] + + @field_validator("resource_id") + @classmethod + def operation_record(cls, value: UUID) -> UUID: + if value.version != 7: + raise ValueError("intake operation must be a generated UUIDv7 record") + return value + + +def parse_intake_binding(action, request, key, invalid_error): + """Bind every supplied field and caller key using the strict reservation schema.""" + if action is not ActionId.SUBMISSION_INTAKE_RESERVE: + return None + try: + resource = IntakeReservationResourceContext.model_validate_json(json.dumps(dict(request))) + if resource.idempotency_key != key: + raise ValueError("intake key differs from prepared binding") + return resource + except (TypeError, ValueError) as exc: + raise invalid_error("invalid prepared intake authorization") from exc diff --git a/backend/app/modules/authorization/prepared.py b/backend/app/modules/authorization/prepared.py index 78acfd1ee..109f33fd4 100644 --- a/backend/app/modules/authorization/prepared.py +++ b/backend/app/modules/authorization/prepared.py @@ -1,6 +1,7 @@ """Transaction-bound, single-use authorization for sensitive mutations.""" from __future__ import annotations +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, parse_intake_binding from app.modules.authorization.catalogue import GUIDE_PROPOSAL_ACTION_IDS, POST_POLICY_ACTION_IDS from app.modules.authorization.domain.lifecycle import parse_lifecycle_prepare, lifecycle_matches from app.modules.authorization.prepared_routing_replay import validate_routing_replay @@ -257,6 +258,7 @@ class _PreparedAuthorizationBinding: submission_policy_resource_digest: str | None = None exact_artifact_context: dict | None = None exact_artifact_resource_digest: str | None = None + intake_reservation_context: IntakeReservationResourceContext | None = None submission_preparation_context: dict | None = None submission_preparation_resource_digest: str | None = None submission_preparation_final_context: dict | None = None @@ -682,6 +684,11 @@ async def consume( """Consume one exact capability before evaluating and evidencing final facts.""" issuance = self._live_issuance(handle) self._validate_consumption(issuance, expected_action_id, caller_input, final_resource_context) + if expected_action_id is ActionId.SUBMISSION_INTAKE_RESERVE and ( + type(final_resource_context) is not IntakeReservationResourceContext + or issuance.binding.intake_reservation_context != final_resource_context + ): + raise PreparedAuthorizationHandleInvalid("invalid prepared intake authorization") if expected_action_id in TASK_ACTIONS | TASK_IMPORT_BATCH_ACTIONS and ( not isinstance(final_resource_context, (TaskAuthorityResourceContext, TaskImportBatchResourceContext)) or issuance.binding.task_authority_context != final_resource_context @@ -832,6 +839,11 @@ async def deny_unsupported( else self._scope_from_resource(action_id, final_resource_context) ) binding = self._binding(action_id, caller_input, scope) + if action_id is ActionId.SUBMISSION_INTAKE_RESERVE and ( + type(final_resource_context) is not IntakeReservationResourceContext + or binding.intake_reservation_context != final_resource_context + ): + raise PreparedAuthorizationHandleInvalid("invalid prepared intake denial") if isinstance(final_resource_context, ProjectCreateResourceContext) and not ( _project_create_binding_matches(binding, final_resource_context) ): @@ -964,6 +976,9 @@ def _binding( submission_policy_context=submission_policy_context, submission_policy_resource_digest=submission_policy_resource_digest, lifecycle_command=parse_lifecycle_prepare(action_id, caller_input, scope, self._context), + intake_reservation_context=parse_intake_binding( + action_id, caller_input.request_value, caller_input.idempotency_key, PreparedAuthorizationHandleInvalid, + ), task_authority_context=parse_task_authority_binding( action_id, caller_input.request_value, PreparedAuthorizationHandleInvalid, caller_input.idempotency_key, @@ -1003,6 +1018,8 @@ def _scope_from_resource( if admin_scope := _admin_prepared_scope(action_id, resource): return admin_scope expected_project_resource = ( + (IntakeReservationResourceContext if action_id is ActionId.SUBMISSION_INTAKE_RESERVE else None) + or PROJECT_MUTATION_RESOURCE_BY_ACTION.get(action_id) or GUIDE_PROPOSAL_RESOURCE_BY_ACTION.get(action_id) or COMPILATION_RESOURCE_BY_ACTION.get(action_id) diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py index ffaf4ad18..cbc331c82 100644 --- a/backend/app/modules/authorization/runtime.py +++ b/backend/app/modules/authorization/runtime.py @@ -47,6 +47,7 @@ from app.modules.authorization.domain.guide_activation import ProjectGuideActivationResourceContext from app.modules.authorization.domain.lifecycle import ReviewLifecycleActivationContract from app.modules.authorization.service_actor_schemas import ServiceActorProvisionResourceContext +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext from app.modules.authorization.catalogue import ActionId from app.modules.authorization.domain.artifact_storage import ( ArtifactPutAttemptResourceContext as ArtifactPutAttemptResourceContext, @@ -1066,6 +1067,7 @@ class PreSubmitCheckerInputResourceContext(PreSubmitCheckerInputPreparationConte | checker_models.CheckerModelCallResourceContext | checker_models.ProjectModelAdministrationResourceContext | checker_outputs.CheckerOutputResourceContext + | IntakeReservationResourceContext | contributor_reads.ActorProjectListResourceContext | contributor_reads.ContributorWorkReadResourceContext | project_catalogue.ProjectCatalogueResourceContext | management_reads.ProjectManagementReadResourceContext | diff --git a/backend/app/modules/authorization/submission_intake.py b/backend/app/modules/authorization/submission_intake.py new file mode 100644 index 000000000..eb768ae65 --- /dev/null +++ b/backend/app/modules/authorization/submission_intake.py @@ -0,0 +1,113 @@ +"""AUTH adapter for source reservation and current own-operation read authority.""" +from dataclasses import asdict +from uuid import UUID + +from pydantic import ValidationError +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.hashing import canonical_json_hash +from app.modules.authorization.api.submission_intake import ( + IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, +) +from app.modules.authorization.catalogue import ActionId +from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext +from app.modules.authorization.kernel import AuthorizationService +from app.modules.authorization.prepared import PreparedAuthorizationService +from app.modules.authorization.repository import AdminAuthorizationRepository +from app.modules.authorization.runtime import ( + AuthorizationContext, AuthorizationDenied, HumanAuthorizationContext, + PreparedAuthorizationHandleInvalid, PreparedAuthorizationInput, PreparedAuthorizationUnsupported, + PreparedAuthorityScope, PreparedAuthorityScopeKind, +) + + +class SubmissionIntakeAuthorization: + """Reuse exact prepared handles and the current contributor read evaluator.""" + def __init__(self, session: AsyncSession, context: AuthorizationContext) -> None: + self._session, self._context = session, context + self._repository = AdminAuthorizationRepository(session) + self._kernel = AuthorizationService(session, context, admin_repository=self._repository) + self._prepared = PreparedAuthorizationService(session, context, self._kernel, self._repository) + + async def lock_actor(self, actor_id: UUID, identity_link_id: UUID) -> None: + """Take actor/link locks after TASK and before PROJECT and grant locks.""" + context = self._context + if (not self._session.in_transaction() or self._session.in_nested_transaction() + or not isinstance(context, HumanAuthorizationContext) + or (actor_id, identity_link_id) != (context.actor_profile_id, context.identity_link_id)): + raise IntakeAuthorityDenied("submission intake is unavailable") + locked = await self._repository.lock_request_actor(identity_link_id, actor_id) + if locked is None: + raise IntakeAuthorityDenied("submission intake is unavailable") + link, profile = locked + if (link.id != str(identity_link_id) or link.actor_profile_id != str(actor_id) + or profile.id != str(actor_id) or profile.actor_kind != "human" + or link.status != "active" or profile.status != "active"): + raise IntakeAuthorityDenied("submission intake is unavailable") + + def _resource(self, facts: IntakeReservationAuthorityFacts) -> IntakeReservationResourceContext: + if (type(facts) is not IntakeReservationAuthorityFacts + or facts.actor_profile_id != self._context.actor_profile_id + or facts.identity_link_id != self._context.identity_link_id): + raise IntakeAuthorityDenied("submission intake is unavailable") + values = asdict(facts) + values["resource_id"] = values.pop("operation_id") + values["scope_project_id"] = values.pop("project_id") + try: + return IntakeReservationResourceContext(**values) + except ValidationError as exc: + raise IntakeAuthorityDenied("submission intake is unavailable") from exc + + @staticmethod + def _input(resource: IntakeReservationResourceContext) -> PreparedAuthorizationInput: + return PreparedAuthorizationInput(idempotency_key=resource.idempotency_key, + request_value=resource.model_dump(mode="json")) + + async def prepare(self, facts: IntakeReservationAuthorityFacts) -> object: + resource = self._resource(facts) + value = self._input(resource) + try: + try: + return await self._prepared.prepare(ActionId.SUBMISSION_INTAKE_RESERVE, value, + PreparedAuthorityScope(kind=PreparedAuthorityScopeKind.PROJECT, + project_id=resource.scope_project_id)) + except PreparedAuthorizationUnsupported as exc: + await self._prepared.deny_unsupported(ActionId.SUBMISSION_INTAKE_RESERVE, value, resource, exc) + raise + except (AuthorizationDenied, PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported) as exc: + raise IntakeAuthorityDenied("submission intake is unavailable") from exc + + async def consume(self, handle: object, facts: IntakeReservationAuthorityFacts) -> UUID: + resource = self._resource(facts) + try: + decision = await self._prepared.consume(handle, ActionId.SUBMISSION_INTAKE_RESERVE, + self._input(resource), resource) + return decision.decision_id + except (AuthorizationDenied, PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported) as exc: + raise IntakeAuthorityDenied("submission intake is unavailable") from exc + + async def authorize_read(self, facts: IntakeOperationReadFacts) -> UUID: + """Read own recorded context under current grant, regardless of task status.""" + if (not self._session.in_transaction() or self._session.in_nested_transaction() + or type(facts) is not IntakeOperationReadFacts + or facts.actor_profile_id != self._context.actor_profile_id): + raise IntakeAuthorityDenied("submission intake is unavailable") + resource = ContributorWorkReadResourceContext(resource_type="submission_operation_read", + resource_id=facts.operation_id, actor_profile_id=facts.actor_profile_id, + scope_project_id=facts.project_id, + request_digest=canonical_json_hash({key: str(value) for key, value in asdict(facts).items()})) + try: + return (await self._kernel.require(ActionId.TASK_SUBMISSION_OPERATION_READ, resource)).decision_id + except AuthorizationDenied as exc: + raise IntakeAuthorityDenied("submission intake is unavailable") from exc + + async def restage_denial(self, error: IntakeAuthorityDenied) -> bool: + """Restage only this request kernel's retained denial after root rollback.""" + if isinstance(error.__cause__, AuthorizationDenied): + await self._kernel.restage_denial(error.__cause__.decision) + return True + return False + + def close(self) -> None: + self._prepared.close() diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 663d9b5d9..74d65ae5d 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -937,6 +937,9 @@ "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/streaming.py", + "backend/app/modules/authorization/api/submission_intake.py", + "backend/app/modules/authorization/domain/submission_intake.py", + "backend/app/modules/authorization/submission_intake.py", "backend/app/modules/artifacts/intake/foreground_lease.py", "backend/app/modules/artifacts/intake/foreground_upload.py", "backend/app/adapters/artifacts/local_submission_source.py", diff --git a/backend/tests/authorization/catalogue_fixtures.py b/backend/tests/authorization/catalogue_fixtures.py index 0392aa228..1b271bf66 100644 --- a/backend/tests/authorization/catalogue_fixtures.py +++ b/backend/tests/authorization/catalogue_fixtures.py @@ -294,6 +294,8 @@ ) expected = { + "submission.intake.reserve": ("submission.create", "WS-SUBMIT-001"), + "task.submission_operation.read": ("submission.read_own", "PILOT-READ-2"), "actor.project.list": ("actor.profile.read_self", "PILOT-READ-2"), "project.catalogue.list": ("project.read", "WS-CLI-001-46"), **dict.fromkeys( @@ -575,6 +577,7 @@ AUDIT_ALLOWED_ACTION_VALUES = { + "submission.intake.reserve", "task.submission_operation.read", "project.catalogue.list", "checker.model_call.prepare", "checker.model_call.dispatch", diff --git a/backend/tests/authorization/task_authority/test_intake_authority.py b/backend/tests/authorization/task_authority/test_intake_authority.py new file mode 100644 index 000000000..31f8005b6 --- /dev/null +++ b/backend/tests/authorization/task_authority/test_intake_authority.py @@ -0,0 +1,170 @@ +"""Real AUTH prepared/read evidence for intake operations, not ART T1 admission.""" +from dataclasses import replace + +import pytest +from sqlalchemy import select, text + +from app.core.identifiers import new_record_id +from app.db import session as db_session +from app.modules.authorization.api.submission_intake import ( + IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, +) +from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization +from app.modules.tasks.models import AuditEvent +from tests.authorization.admin_access.support import create_project +from tests.authorization.task_authority.test_postgresql import context, grant, project_manager + + +def reservation(ctx, project): + return IntakeReservationAuthorityFacts( + operation_id=new_record_id(), project_id=project, task_id=new_record_id(), + assignment_id=new_record_id(), actor_profile_id=ctx.actor_profile_id, + identity_link_id=ctx.identity_link_id, idempotency_key=new_record_id(), + metadata_sha256="sha256:" + "a" * 64, locked_context_sha256="sha256:" + "b" * 64, + task_status="in_progress", + ) + + +@pytest.fixture +async def intake_authority(admin_access): + project = await create_project("Intake authority") + manager = await project_manager(admin_access, project) + grant_id = await grant(admin_access, manager, project) + return admin_access, project, grant_id, await context(admin_access) + + +async def test_intake_authority_exact_audit_rollback_and_single_use(intake_authority): + _, project, grant_id, ctx = intake_authority + facts = reservation(ctx, project) + async with db_session.get_session_factory()() as session: + authority = SubmissionIntakeAuthorization(session, ctx) + try: + async with session.begin(): + await authority.lock_actor(ctx.actor_profile_id, ctx.identity_link_id) + handle = await authority.prepare(facts) + decision = await authority.consume(handle, facts) + row = await session.get(AuditEvent, str(decision)) + assert (row.action_id, row.permission_id, row.matched_grant_id) == ( + "submission.intake.reserve", "submission.create", grant_id) + assert (row.resource_type, row.resource_id, row.target_ref_kind, row.target_ref_id) == ( + "submission_operation", str(facts.operation_id), "submission_operation", str(facts.operation_id)) + assert row.project_id == str(project) and row.after_facts["allowed"] is True + assert set(row.after_facts) == {"allowed", "resource_context_digest"} + await session.rollback() + with pytest.raises(IntakeAuthorityDenied): + async with session.begin(): + await authority.consume(handle, facts) + async with session.begin(): + pending = await authority.prepare(facts) + with pytest.raises(IntakeAuthorityDenied): + async with session.begin(): + await authority.consume(pending, facts) + async with session.begin(): + rolled_back = await authority.consume(await authority.prepare(facts), facts) + await session.rollback() + assert await session.get(AuditEvent, str(rolled_back)) is None + finally: + authority.close() + + +@pytest.mark.parametrize("field", ["operation_id", "task_id", "assignment_id", "idempotency_key", + "actor_profile_id", "identity_link_id", "metadata_sha256", "locked_context_sha256"]) +async def test_intake_authority_substitution_cannot_consume(intake_authority, field): + _, project, _, ctx = intake_authority + facts = reservation(ctx, project) + changed = replace(facts, **{field: "sha256:" + "c" * 64 if field.endswith("sha256") else new_record_id()}) + async with db_session.get_session_factory()() as session: + authority = SubmissionIntakeAuthorization(session, ctx) + try: + with pytest.raises(IntakeAuthorityDenied): + async with session.begin(): + handle = await authority.prepare(facts) + await authority.consume(handle, changed) + assert not list(await session.scalars(select(AuditEvent).where(AuditEvent.request_id == str(ctx.request_id)))) + finally: + authority.close() + + +@pytest.mark.parametrize("case", ["missing", "reviewer", "foreign", "revoked", "admin"]) +async def test_intake_reserve_and_read_require_exact_current_submitter(admin_access, case): + project = await create_project("Intake denial") + if case == "admin": + await admin_access.signed.grant(admin_access.admin, admin_access.target, role="project_manager", project_id=project) + elif case != "missing": + grant_project = await create_project("Other intake project") if case == "foreign" else project + manager = await project_manager(admin_access, grant_project) + grant_id = await grant(admin_access, manager, grant_project, "reviewer" if case == "reviewer" else "submitter") + if case == "revoked": + response = await admin_access.signed.client.post( + f"/api/v1/projects/{project}/role-grants/{grant_id}/revoke", + headers=manager.headers | {"Idempotency-Key": str(new_record_id())}, + json={"reason": "Withdraw intake grant"}) + assert response.status_code == 200, response.text + ctx = await context(admin_access) + facts = reservation(ctx, project) + read = IntakeOperationReadFacts(facts.operation_id, project, facts.task_id, ctx.actor_profile_id) + for method, value in (("prepare", facts), ("authorize_read", read)): + async with db_session.get_session_factory()() as session: + authority = SubmissionIntakeAuthorization(session, ctx) + try: + with pytest.raises(IntakeAuthorityDenied) as caught: + async with session.begin(): + await getattr(authority, method)(value) + assert await authority.restage_denial(caught.value) + await session.commit() + rows = list(await session.scalars(select(AuditEvent).where(AuditEvent.request_id == str(ctx.request_id)))) + assert rows and all(row.after_facts["allowed"] is False for row in rows) + assert all(row.resource_id == str(facts.operation_id) for row in rows) + finally: + authority.close() + + +async def test_intake_read_has_no_new_submission_status_or_original_link_dependency(intake_authority): + _, project, _, ctx = intake_authority + facts = reservation(ctx, project) + # AUTH reads only resolved historical owner/project, not current TASK eligibility. + read = IntakeOperationReadFacts(facts.operation_id, project, facts.task_id, ctx.actor_profile_id) + async with db_session.get_session_factory()() as session: + authority = SubmissionIntakeAuthorization(session, ctx) + try: + async with session.begin(): + decision = await authority.authorize_read(read) + row = await session.get(AuditEvent, str(decision)) + assert row.action_id == "task.submission_operation.read" and row.permission_id == "submission.read_own" + assert row.resource_id == str(facts.operation_id) + await session.rollback() + with pytest.raises(IntakeAuthorityDenied): + async with session.begin_nested(): + await authority.authorize_read(read) + await session.rollback() + with pytest.raises(IntakeAuthorityDenied): + async with session.begin(): + await authority.authorize_read(replace(read, actor_profile_id=new_record_id())) + with pytest.raises(IntakeAuthorityDenied): + async with session.begin(): + await authority.lock_actor(ctx.actor_profile_id, new_record_id()) + finally: + authority.close() + + +async def test_intake_revoked_current_link_cannot_reserve_or_read(intake_authority): + _, project, _, ctx = intake_authority + facts = reservation(ctx, project) + async with db_session.get_session_factory()() as session: + async with session.begin(): + await session.execute(text( + "UPDATE actor_identity_links SET status='revoked',revoked_by=:actor," + "revoked_at=clock_timestamp(),revoked_reason='intake proof' WHERE id=:link" + ), {"actor": str(ctx.actor_profile_id), "link": str(ctx.identity_link_id)}) + authority = SubmissionIntakeAuthorization(session, ctx) + try: + for method, args in ( + ("lock_actor", (ctx.actor_profile_id, ctx.identity_link_id)), + ("prepare", (facts,)), + ("authorize_read", (IntakeOperationReadFacts(facts.operation_id, project, facts.task_id, ctx.actor_profile_id),)), + ): + with pytest.raises(IntakeAuthorityDenied): + async with session.begin(): + await getattr(authority, method)(*args) + finally: + authority.close() diff --git a/backend/tests/authorization/task_authority/test_prepared.py b/backend/tests/authorization/task_authority/test_prepared.py index 293fbfdc2..efaa3cd32 100644 --- a/backend/tests/authorization/task_authority/test_prepared.py +++ b/backend/tests/authorization/task_authority/test_prepared.py @@ -375,3 +375,54 @@ async def test_service_task_denials_have_canonical_restageable_evidence(identity assert len(evidence.events) == 1 assert evidence.events[0].after_facts == first.after_facts assert evidence.events[0].project_id == first.project_id + + +@pytest.mark.parametrize("mutation", ["operation", "task", "key", "metadata", "status", "foreign_resource"]) +async def test_intake_prepared_binding_rejects_cross_operation_and_wrong_resource(mutation): + from app.core.identifiers import new_record_id + from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext + _, _, prepared, task, evidence = setup() + resource = IntakeReservationResourceContext(resource_id=new_record_id(), scope_project_id=task.scope_project_id, + task_id=new_record_id(), assignment_id=new_record_id(), actor_profile_id=task.actor_profile_id, + identity_link_id=task.identity_link_id, idempotency_key=new_record_id(), + metadata_sha256="sha256:" + "a" * 64, locked_context_sha256="sha256:" + "b" * 64, + task_status="in_progress") + changes = {"operation": {"resource_id": new_record_id()}, "task": {"task_id": new_record_id()}, + "key": {"idempotency_key": new_record_id()}, "metadata": {"metadata_sha256": "sha256:" + "c" * 64}, + "status": {"task_status": "accepted"}} + wrong = task if mutation == "foreign_resource" else resource.model_copy(update=changes[mutation]) + try: + handle, value = await prepare(prepared, resource, ActionId.SUBMISSION_INTAKE_RESERVE) + with pytest.raises(PreparedAuthorizationHandleInvalid): + await prepared.consume(handle, ActionId.SUBMISSION_INTAKE_RESERVE, value, wrong) + assert evidence.events == [] + finally: + prepared.close() + + +@pytest.mark.parametrize("identity", list(ServiceIdentity)) +async def test_fixed_services_cannot_reserve_submission_intake(identity): + from app.core.identifiers import new_record_id + from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied, IntakeReservationAuthorityFacts + from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization + context = ServiceAuthorizationContext( + actor_profile_id=uuid4(), actor_kind=ActorKind.SERVICE, + actor_status=ActorStatus.ACTIVE, identity_link_id=uuid4(), + identity_link_status=IdentityLinkStatus.ACTIVE, service_identity=identity, + request_id=uuid4(), correlation_id=uuid4(), + ) + authority = SubmissionIntakeAuthorization(Session(), context) + evidence = Evidence() + authority._kernel._audit = evidence + facts = IntakeReservationAuthorityFacts(new_record_id(), uuid4(), uuid4(), uuid4(), + context.actor_profile_id, context.identity_link_id, uuid4(), + "sha256:" + "a" * 64, "sha256:" + "b" * 64, "in_progress") + try: + with pytest.raises(IntakeAuthorityDenied) as caught: + await authority.prepare(facts) + assert isinstance(caught.value.__cause__, AuthorizationDenied) + assert caught.value.__cause__.decision.denial_code.value == "permission_not_granted" + assert len(evidence.events) == 1 and evidence.events[0].resource_id == str(facts.operation_id) + assert evidence.events[0].after_facts["allowed"] is False + finally: + authority.close() diff --git a/backend/tests/authorization/test_catalogue.py b/backend/tests/authorization/test_catalogue.py index bbd602fbe..1295e6b56 100644 --- a/backend/tests/authorization/test_catalogue.py +++ b/backend/tests/authorization/test_catalogue.py @@ -39,7 +39,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() -> assert {item.value for item in HISTORICAL_PERMISSION_IDS} == historical_permissions assert {item.value for item in NEW_PERMISSION_IDS} == new_permissions assert {item.value for item in PERMISSION_IDS} == historical_permissions | new_permissions - assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 190 + assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 192 assert set(ACTION_BY_ID) == ACTION_IDS assert {definition.owner for definition in ACTION_DEFINITIONS} == set(ActionOwner) assert { @@ -118,7 +118,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() -> } assert all(not owner.value.startswith("WS-REV-") for owner in ActionOwner) assert Counter(definition.availability for definition in ACTION_DEFINITIONS) == { - ActionAvailability.ACTIVE: 165, + ActionAvailability.ACTIVE: 167, ActionAvailability.PLANNED: 25, } assert ( diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 1717f418b..e4563fc1a 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "2eb17457ad8fda593e7a997f3598dc0b2e463ab323524e42921ac65c71ffc625" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "c7829662a20e2ac52fcab3f9cb5830a7a0656f9eb7c4564aeae76d1230c2d84a" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 85fc730cd..018439567 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -2106,3 +2106,26 @@ async def creation_guards() -> int: await connection.close() assert asyncio.run(creation_guards()) == 3 + + + +def test_intake_authority_upgrade_changes_only_two_audit_constraints(isolated_database_env, migration_lock): + config = _alembic_config() + with migration_lock(): + asyncio.run(_execute(isolated_database_env, "drop schema public cascade; create schema public")) + command.upgrade(config, "0069_submission_intake_custody") + before = asyncio.run(build_manifest(isolated_database_env)) + command.upgrade(config, "0070_submission_intake_authority") + after = asyncio.run(build_manifest(isolated_database_env)) + changed = {key for key in before if before[key] != after[key]} + assert changed == {"constraints"} + old = {(row["table_name"], row["name"]): row for row in before["constraints"]} + new = {(row["table_name"], row["name"]): row for row in after["constraints"]} + assert old.keys() == new.keys() + assert {key for key in old if old[key] != new[key]} == { + ("audit_events", "ck_audit_events_authorization_action_evidence"), + ("audit_events", "ck_audit_events_authority_privacy_bounds"), + } + actions = new[("audit_events", "ck_audit_events_authorization_action_evidence")]["definition"] + assert "submission.intake.reserve" in actions and "task.submission_operation.read" in actions + assert "artifact.submission_bundle.prepare" in actions and "submission.create" in actions diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index 46d1624fd..dfafc1d7d 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2766,6 +2766,9 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ target, "backend/app/modules/artifacts/intake/models.py", "backend/app/modules/artifacts/intake/capacity.py", "backend/app/modules/artifacts/intake/streaming.py", + "backend/app/modules/authorization/api/submission_intake.py", + "backend/app/modules/authorization/domain/submission_intake.py", + "backend/app/modules/authorization/submission_intake.py", "backend/app/modules/artifacts/intake/foreground_lease.py", "backend/app/modules/artifacts/intake/foreground_upload.py", "backend/app/adapters/artifacts/local_submission_source.py", From ae0da435ade0c57d8724afd029de157fd1dcc4cf Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:38:11 +0100 Subject: [PATCH 027/513] Register intake authority CI coverage and exact action ownership --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++++ backend/app/modules/authorization/action_definitions.py | 3 ++- backend/scripts/test_lane_catalogue.py | 1 + backend/tests/authorization/catalogue_fixtures.py | 2 +- 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d392f16ac..8c66b0b4b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -454,3 +454,11 @@ exact new action/resource pair and compare the denial binding; the fixed-service matrix then passed. Live own-operation reads consume resolved historical facts without an eligible-status input. ART must still prove stored-operation replay after task progression and denied-body nonconsumption in T1 composition. + +AUTH-only review found no grant bypass. ARCH-AUTH-01 corrects the new read action's +catalogue owner to this initiative while preserving its contributor evaluator. +The CI review found the new PostgreSQL test module absent from the explicit +semantic lane catalogue; register it with the existing task-authority modules. +The focused migration comparison is replayed at the repaired commit so its +receipt identifies the same reviewed source. These are necessary verification +and metadata corrections, not expanded authority or public exposure. diff --git a/backend/app/modules/authorization/action_definitions.py b/backend/app/modules/authorization/action_definitions.py index 2aa06c193..a83d11aa8 100644 --- a/backend/app/modules/authorization/action_definitions.py +++ b/backend/app/modules/authorization/action_definitions.py @@ -15,12 +15,13 @@ ACTION_DEFINITIONS = ( _active(ActionId.SUBMISSION_INTAKE_RESERVE, PermissionId.SUBMISSION_CREATE, ActionOwner.SUBMISSION_INTAKE), + _active(ActionId.TASK_SUBMISSION_OPERATION_READ, PermissionId.SUBMISSION_READ_OWN, ActionOwner.SUBMISSION_INTAKE), _active( ActionId.ACTOR_PROJECT_LIST, PermissionId.ACTOR_PROFILE_READ_SELF, ActionOwner.PILOT_READ_2 ), *( _active(action, PermissionId.SUBMISSION_READ_OWN, ActionOwner.PILOT_READ_2) - for action in sorted(CONTRIBUTOR_WORK_READ_ACTIONS) + for action in sorted(CONTRIBUTOR_WORK_READ_ACTIONS - {ActionId.TASK_SUBMISSION_OPERATION_READ}) ), *( _active(a, PermissionId.PROJECT_GUIDE_MANAGE, ActionOwner.PILOT_READ_3) diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 95d61a84a..ec6fc5902 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -211,6 +211,7 @@ class TestLane: "tests/actors/test_issuer_profile.py", "tests/actors/test_self_api_lifecycle.py", "tests/actors/test_identity_bounds_and_rate_controls.py", + "tests/authorization/task_authority/test_intake_authority.py", "tests/authorization/task_authority/test_audit_contract.py", "tests/authorization/task_authority/test_concurrency.py", "tests/authorization/task_authority/test_postgresql.py", diff --git a/backend/tests/authorization/catalogue_fixtures.py b/backend/tests/authorization/catalogue_fixtures.py index 1b271bf66..262e4875b 100644 --- a/backend/tests/authorization/catalogue_fixtures.py +++ b/backend/tests/authorization/catalogue_fixtures.py @@ -295,7 +295,7 @@ expected = { "submission.intake.reserve": ("submission.create", "WS-SUBMIT-001"), - "task.submission_operation.read": ("submission.read_own", "PILOT-READ-2"), + "task.submission_operation.read": ("submission.read_own", "WS-SUBMIT-001"), "actor.project.list": ("actor.profile.read_self", "PILOT-READ-2"), "project.catalogue.list": ("project.read", "WS-CLI-001-46"), **dict.fromkeys( From 2cdf10ee4b2ace21dbddc27c689c694ae031d805 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:39:17 +0100 Subject: [PATCH 028/513] Update exact CI family fingerprint for intake authority tests --- backend/tests/test_ci_lane_catalogue.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 5e576188b..836f3023e 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -317,8 +317,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 270, - "9ba49de5926e44beb473c22a3aaf9ba82c6c4f54079d8f54661470b4d96db63c", + 271, + "6e35cc7ad001abe952f6ffbc8b7dad3ed0db6636e113e6c7fa347bddc768da88", ), "project": ( 255, From 00aab633d30de9c173234175c219d7ae4f113aec Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 07:47:11 +0100 Subject: [PATCH 029/513] Specify authorized T1 admission and exact discard replay --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8c66b0b4b..d6893bbc6 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -462,3 +462,60 @@ semantic lane catalogue; register it with the existing task-authority modules. The focused migration comparison is replayed at the repaired commit so its receipt identifies the same reviewed source. These are necessary verification and metadata corrections, not expanded authority or public exposure. + +## T1 admission and exact replay composition + +Connect the private foreground path to real AUTH/TASK/PROJECT owners. Add a +strict selector-only reservation preflight under the existing intake action; +it checks current human/Submitter authority without issuing a handle or staging +an allow. Full prepare/consume continues to require exact locked context/status. +TASK's existing lock returns the stored project ID. Preserve the actual AUTH +lock sequence: TASK, actor/link, exact grant, canonical TASK context/PROJECT +policy, new operation, capacity. No body or provider call occurs in these short +root transactions. Old preparation and accepted execution retain their contracts. + +The ART admission composition generates the operation UUID before preflight and +passes it into the existing repository reservation. It validates current task, +assignment, predecessor/revision acknowledgement and capacity, exactly one locked +PRE and POST selection, and the configured claimed storage namespace/profile. +Unqualified AWS source capability fails closed before reservation. Explicit +positive raw/deadline/lease/capacity limits have no deployment defaults. The full +PRE runtime/readiness and public rate/framing gates remain cutover dependencies; +this private composition cannot expose a public accepted response. + +Resolve actor/key first. An existing operation uses its stored task/project and +current own-operation read authority before metadata comparison or ordinary new +submission eligibility. Active/no-EOF and terminal/no-EOF never consume a retry +body. Complete EOF identity permits bounded hash/count into a discard sink, +including unresolved provider completion; no new object or PRE is created. +Reauthorize and reread the same operation after hashing. Metadata or raw mismatch +is conflict; an exact replay returns the operation's own current state/failure, +not another task submission or a takeover. Cancellation cannot mutate the original. +Share ingress framing/count/hash enforcement with upload rather than duplicate it. + +Recheck actor/key after serialization. A raced-in key or exact uniqueness loser +rolls back its root transaction, then resolves the committed original under read +authority. Do not lock another task while holding the requested task. If commit +acknowledgement is lost, never infer rollback or begin upload from an in-memory +row: resolve in a fresh authorized read or leave an unknown infrastructure result. +Caller cancellation drains transaction cleanup and remains cancellation; it cannot +start upload. Retained uncertain custody stays charged for later recovery. + +Allowed files: intake AUTH public/domain/adapter preflight and existing prepared +service; TASK custody API/owner and canonical revision acknowledgement helper; +ART intake repository/streaming/admission and existing preparation helper caller; +exact partition and semantic CI test registration, focused custody/contract/AUTH +tests, affected current records. No accepted state, source deletion/release, +background PRE, new provider/config parser, fabricated readiness, public route or +production default. Risk L0; architecture/security, QA/test-delta/CI and affected +docs reviews. Human review focus: fresh authority before disclosure, same-key +concurrency/commit uncertainty, exact context and bounded replay without writes. + +Prove real PostgreSQL/local admission with canonical AUTH grants; denied/revoked +and foreign callers leave no operation/pointer/charge/allow or provider work. +Prove metadata/raw conflicts, EOF-unsealed replay, terminal replay after TASK +advances, concurrent same/different keys and cross-task key reuse, capacity +rollback, wrong namespace/unqualified AWS, revision/cardinality refusal, lost +commit acknowledgement and cancelled retry. Existing upload/lease/custody and +old preparation authority proof must remain intact. Integrated accepted replay +and public API concealment remain required after T4 and route cutover. From dfdcfa181089790fec43ece3dd04e8e0056f82bb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 08:22:33 +0100 Subject: [PATCH 030/513] Compose authorized intake reservation and exact replay --- .ci/behavior-ownership/partition.v1.json | 10 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 71 +++ .../artifacts/intake/foreground_admission.py | 221 +++++++++ .../modules/artifacts/intake/repository.py | 13 +- .../app/modules/artifacts/intake/streaming.py | 95 +++- .../modules/artifacts/submission_admission.py | 31 +- .../authorization/api/submission_intake.py | 10 +- .../authorization/domain/action_groups.py | 4 +- .../app/modules/authorization/domain/audit.py | 2 + .../authorization/domain/audit_targets.py | 25 +- .../authorization/domain/submission_intake.py | 33 +- backend/app/modules/authorization/prepared.py | 58 +-- .../authorization/prepared_preflight.py | 57 +++ backend/app/modules/authorization/runtime.py | 4 +- .../authorization/submission_intake.py | 25 +- .../app/modules/tasks/api/intake_custody.py | 4 +- .../modules/tasks/api/submission_context.py | 33 ++ backend/app/modules/tasks/intake_custody.py | 8 +- backend/scripts/behavior_ownership.py | 2 + backend/scripts/test_lane_catalogue.py | 1 + .../test_submission_intake_admission.py | 427 ++++++++++++++++++ .../test_submission_intake_contracts.py | 88 ++++ .../test_submission_intake_custody.py | 1 + .../setup_finalization/test_catalogue.py | 2 + .../task_authority/test_intake_authority.py | 34 +- .../task_authority/test_prepared.py | 49 +- backend/tests/test_behavior_ownership.py | 2 + backend/tests/test_ci_lane_catalogue.py | 4 +- 28 files changed, 1189 insertions(+), 125 deletions(-) create mode 100644 backend/app/modules/artifacts/intake/foreground_admission.py create mode 100644 backend/app/modules/authorization/prepared_preflight.py create mode 100644 backend/tests/artifacts/test_submission_intake_admission.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index ec79d2afe..62e181b90 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -604,6 +604,10 @@ "group": "artifacts", "target": "backend/app/modules/artifacts/intake/capacity.py" }, + { + "group": "artifacts", + "target": "backend/app/modules/artifacts/intake/foreground_admission.py" + }, { "group": "artifacts", "target": "backend/app/modules/artifacts/intake/foreground_lease.py" @@ -1192,6 +1196,10 @@ "group": "auth", "target": "backend/app/modules/authorization/prepared_post_submit_replay.py" }, + { + "group": "auth", + "target": "backend/app/modules/authorization/prepared_preflight.py" + }, { "group": "auth", "target": "backend/app/modules/authorization/prepared_projection_replay.py" @@ -2645,7 +2653,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "2ebaa06f0f65d9ddad2d1013d0256f51ccb8248a09ae3c14bb518c118041c5ce", + "authority_digest": "3f4b580a947ef98164cf6df277feee494299cbc506dd9f4d02f2b2e41f436598", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d6893bbc6..6bc3af754 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -519,3 +519,74 @@ rollback, wrong namespace/unqualified AWS, revision/cardinality refusal, lost commit acknowledgement and cancelled retry. Existing upload/lease/custody and old preparation authority proof must remain intact. Integrated accepted replay and public API concealment remain required after T4 and route cutover. + +T1 component evidence (implementation worktree based on `00aab633d`, not a +frozen candidate): selector-only AUTH preflight now checks the current Submitter +grant without an allow or prepared handle. Full reservation preparation still +requires locked context/status. The shared bounded ingress reader supports +provider-free discard hashing, including exact EOF, size/framing refusal, +idle/total deadlines and cancellation propagation. TASK owns the shared revision +acknowledgement validation used by existing preparation and future T1 admission. + +Verification: 518 focused intake-contract/prepared-authority tests passed; +17 isolated PostgreSQL intake-authority tests passed (47.92s, migration head +0070, database/role cleanup confirmed); 14 existing selected-PRE tests passed, +including revision acknowledgement checks. Ruff and whitespace checks passed. +The PostgreSQL runner was initially invoked from the repository root and failed +migration import before tests; rerunning from backend corrected that invocation. +Local evidence: `/tmp/workstream-t1-preflight-static.log` and +`/tmp/workstream-t1-preflight-pg.log` with matching metadata JSON. These results +prove components only: ART admission/replay transaction composition, races, +commit-acknowledgement uncertainty and integrated T1 acceptance remain unproven. + +T1 composition now exists privately in `foreground_admission.py`. It owns short +root transactions, TASK/actor/grant/context ordering, capacity reservation and +full reservation authorization. Only acknowledged commit yields a foreground +owner. Existing/raced keys and uncertain commit acknowledgements use a fresh +current-authority read; replay hashes outside the transaction and reauthorizes +before returning the same operation. Commit cancellation drains cleanup and +preserves cancellation without issuing upload ownership. + +Initial composition evidence on the implementation worktree: six PostgreSQL +cases passed (73.30s) for atomic custody/allow, EOF-unsealed replay, same-key race, +lost acknowledgement, revocation and namespace refusal. Three further cases +passed (33.85s) for conflicting retries, capacity rollback and repeated commit +cancellation. Both isolated databases and roles were cleaned up. Protected owner +registration and module boundaries passed 207 tests. The initial older policy +fixture had no project checker selections and correctly failed T1 cardinality; +the positive fixture now registers and selects one image in each phase through +canonical policy setup. This is not yet frozen T1 review evidence or public API +acceptance proof; remaining planned refusal/race/advanced-context cases and +full custody regression must be assessed before declaring this stage complete. + +Hosted verification of pushed `2cdf10ee4` exposed structural-debt mismatch and +an omitted exact active-action inventory assertion (Backend run 43170021484; +shared-foundations-c otherwise reported 2093 passing tests). Repair remains in +this T1 worktree: extract cohesive prepared preflight handling, keep exact intake +audit selectors in their own target helper, split admission integration tests +from custody tests and explicitly register the new module/protected paths, and +include both intake actions in the existing active-action inventory. Structural +limits and the frozen debt ledger remain unchanged. New admission test family +membership is checked against the previous fingerprint with only that exact +module added. Fetched `origin/main` remains `94334ccf4`, already an ancestor. + +The focused CI repair checks passed 709 tests in 60.80s, covering prepared +AUTH, exact active-action inventory, lane membership, behavior ownership and +structural-boundary contracts (`/tmp/workstream-t1-ci-repair.log`). Ruff and +whitespace checks passed. The full custody regression was launched before the +cohesive file split; its eventual result must be distinguished from verification +of the final split modules and extracted preflight helper. + +Additional T1 evidence: the full pre-split custody regression passed 65 tests in +551.27s with isolated cleanup confirmed. The final split admission/AUTH suites +passed 30 tests in 213.09s, including missing phase-selection refusal, cross-task +same-key serialization and cancelled discard replay. Two additional PostgreSQL +cases passed in 34.74s: canonical configured AWS namespace refusal before source +reservation, and current grant revocation during replay body hashing. All three +isolated database/role cleanups completed. The AWS case proves refusal only, +not AWS provider qualification. Direct AUTH and test-structure CLI validators +passed without changing their ledgers. The terminal EOF replay case retains the +original failure even after another operation claims the same task. Integrated +accepted replay, revision journey, public framing/runtime readiness, and the +full T1–T5 public drill remain later required evidence; these tests do not prove +the public submission cutover. diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py new file mode 100644 index 000000000..6a9466d5e --- /dev/null +++ b/backend/app/modules/artifacts/intake/foreground_admission.py @@ -0,0 +1,221 @@ +"""Authorized T1 reservation and exact replay, without body/provider writes. + +Only a positively acknowledged reservation returns a foreground owner. A raced +key or uncertain commit resolves the stored operation through current read +authority and cannot acquire a replacement lease or start a second upload. +""" +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager +from dataclasses import asdict, dataclass +from datetime import UTC, datetime, timedelta +from uuid import UUID + +from sqlalchemy import func, select +from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker + +from app.core.cancellation import await_completion_preserving_cancellation +from app.core.identifiers import new_record_id +from app.db.errors import integrity_constraint_name +from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits +from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository +from app.modules.artifacts.intake.streaming import hash_submission_replay +from app.modules.artifacts.models import ArtifactStorageNamespace +from app.modules.artifacts.service import ArtifactStorageNamespaceSpec +from app.modules.authorization.api.submission_intake import ( + IntakeAuthorizationPort, IntakeAuthorityDenied, IntakeOperationReadFacts, + IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts, +) +from app.modules.checkers.api.external_policy import LockedExternalCheckerPolicies +from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextPort, ProjectLockedPolicyContextRequest +from app.modules.projects.api.policy_lineage import RevisionPolicySemantics +from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort +from app.modules.tasks.api.submission_context import ( + TaskSubmissionContextPort, TaskSubmissionContextRequest, + require_revision_acknowledgement, require_revision_capacity, +) + + +@dataclass(frozen=True, slots=True) +class IntakeReservationOwner: + operation_id: UUID + lease_id: UUID + generation: int + + +@dataclass(frozen=True, slots=True) +class IntakeReplay: + """Detached operation state, never foreground write authority.""" + operation_id: UUID + state: str + failure_code: str | None + maximum_raw_bytes: int + raw_sha256: str | None + raw_byte_count: int | None + + +class IntakeCommitUnknown(RuntimeError): + """Commit outcome cannot authorize new provider work.""" + + +class _ExistingKey(RuntimeError): + pass + + +class ForegroundIntakeAdmission: + def __init__( + self, sessions: async_sessionmaker[AsyncSession], *, + tasks: Callable[[AsyncSession], IntakeTaskCustodyPort], + task_contexts: Callable[[AsyncSession], TaskSubmissionContextPort], + projects: Callable[[AsyncSession], ProjectLockedPolicyContextPort], + authorization: Callable[[AsyncSession], IntakeAuthorizationPort], + namespace: ArtifactStorageNamespaceSpec, capacity_limits: SubmissionSourceCapacityLimits, + maximum_raw_bytes: int, upload_duration: timedelta, lease_duration: timedelta, + ) -> None: + if (type(maximum_raw_bytes) is not int or not 1 <= maximum_raw_bytes <= MAXIMUM_SUBMISSION_ZIP_BYTES + or not isinstance(upload_duration, timedelta) or not isinstance(lease_duration, timedelta) + or not timedelta(0) < lease_duration <= upload_duration): + raise ValueError("intake reservation limits are invalid") + self._sessions, self._tasks, self._contexts = sessions, tasks, task_contexts + self._projects, self._authorization = projects, authorization + self._namespace = namespace + self._capacity = SubmissionSourceCapacityLimits.model_validate(capacity_limits) + self._maximum, self._upload_duration, self._lease_duration = maximum_raw_bytes, upload_duration, lease_duration + + @asynccontextmanager + async def _root(self): + session = self._sessions() + authority = self._authorization(session) + try: + await session.begin() + try: + yield session, authority + except IntakeAuthorityDenied as exc: + await await_completion_preserving_cancellation(session.rollback()) + if await authority.restage_denial(exc): + await await_completion_preserving_cancellation(session.commit()) + raise + else: + try: + await await_completion_preserving_cancellation(session.commit()) + except Exception as exc: + raise IntakeCommitUnknown("intake commit acknowledgement unavailable") from exc + finally: + authority.close() + await await_completion_preserving_cancellation(session.close()) + + async def admit( + self, metadata: SubmissionIntakeMetadata, *, actor_id: UUID, identity_link_id: UUID, + idempotency_key: UUID, declared_raw_bytes: int | None, + ) -> IntakeReservationOwner | IntakeReplay: + metadata = SubmissionIntakeMetadata.model_validate(metadata) + if declared_raw_bytes is not None and ( + type(declared_raw_bytes) is not int or not 1 <= declared_raw_bytes <= self._maximum + ): + raise ValueError("intake declared byte count is invalid") + try: + return await self._reserve(metadata, actor_id, identity_link_id, idempotency_key, declared_raw_bytes) + except IntegrityError as exc: + if integrity_constraint_name(exc) != "uq_submission_intake_actor_key": + raise + except (_ExistingKey, IntakeCommitUnknown): + pass + # The old root has been closed. Never acquire a second TASK in that root. + return await self._read(metadata, actor_id, idempotency_key) + + async def _reserve(self, metadata, actor_id, identity_link_id, key, declared): + async with self._root() as (session, authority): + tasks = self._tasks(session) + repository = SubmissionIntakeRepository(session, tasks) + if await repository.find_actor_key(actor_id, key) is not None: + raise _ExistingKey() + project_id = await tasks.lock(metadata.task_id) + await authority.lock_actor(actor_id, identity_link_id) + selectors = IntakeReservationPreflightFacts( + new_record_id(), project_id, metadata.task_id, metadata.assignment_id, + actor_id, identity_link_id, key, metadata.metadata_sha256(), + ) + await authority.preflight(selectors) + if await repository.find_actor_key(actor_id, key) is not None: + raise _ExistingKey() + await self._validate_context(session, metadata, actor_id) + now = await session.scalar(select(func.clock_timestamp())) + row = await repository.reserve( + operation_id=selectors.operation_id, metadata=metadata, actor_id=actor_id, + identity_link_id=identity_link_id, idempotency_key=key, + maximum_raw_bytes=self._maximum, capacity_limits=self._capacity, + declared_raw_bytes=declared, upload_deadline_at=now + self._upload_duration, + lease_expires_at=now + self._lease_duration, + ) + facts = IntakeReservationAuthorityFacts( + **asdict(selectors), locked_context_sha256=row.locked_context_sha256, + task_status=row.eligible_task_status, + ) + await authority.consume(await authority.prepare(facts), facts) + owner = IntakeReservationOwner(UUID(row.id), UUID(row.lease_id), row.lease_generation) + return owner + + async def _validate_context(self, session, metadata, actor_id): + task = await self._contexts(session).lock_submission_context(TaskSubmissionContextRequest( + metadata.task_id, metadata.assignment_id, actor_id, metadata.predecessor_submission_id, + )) + references = asdict(task.locked_project_context) + references.pop("locked_contribution_policy_version_id") + project = await self._projects(session).lock_locked_policy_context(ProjectLockedPolicyContextRequest(**references)) + if task.predecessor is not None: + revision = project.activation_receipt.command.revision + require_revision_capacity( + task, project_id=project.project_id, policy_id=revision.policy_id, + policy_generation=revision.generation, policy_hash=revision.policy_hash, + max_revision_rounds=RevisionPolicySemantics.model_validate_json(project.revision_policy.value).max_revision_rounds, + ) + require_revision_acknowledgement(task, metadata.revision_preparation_id, metadata.revision_preparation_sha256) + policies = LockedExternalCheckerPolicies.model_validate_json(project.external_checker_policies.value) + if len(policies.pre_submit.entries) != 1 or len(policies.post_submit.entries) != 1: + raise IntakeCustodyConflict("intake_requires_one_pre_and_post_checker") + namespace = await session.get(ArtifactStorageNamespace, "primary") + if namespace is None or any(getattr(namespace, name) != value for name, value in asdict(self._namespace).items()): + raise IntakeCustodyConflict("intake_namespace_unavailable") + if namespace.provider_profile not in {"local-v2", "minio-v1"}: + raise IntakeCustodyConflict("intake_source_provider_unqualified") + + async def _read(self, metadata, actor_id, key, *, expected_operation_id=None): + async with self._root() as (session, authority): + repository = SubmissionIntakeRepository(session, self._tasks(session)) + found = await repository.find_actor_key(actor_id, key) + if found is None: + raise IntakeCommitUnknown("intake reservation could not be resolved") + row = await repository._lock(UUID(found.id)) + await authority.authorize_read(IntakeOperationReadFacts( + UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id), + )) + if row.metadata_sha256 != metadata.metadata_sha256(): + raise IntakeCustodyConflict("submission_idempotency_conflict") + if expected_operation_id is not None and UUID(row.id) != expected_operation_id: + raise IntakeCustodyConflict("submission_idempotency_conflict") + result = IntakeReplay(UUID(row.id), row.state, row.failure_code, + row.maximum_raw_bytes, row.raw_sha256, row.raw_byte_count) + return result + + async def replay( + self, metadata: SubmissionIntakeMetadata, chunks: AsyncIterator[bytes], *, + actor_id: UUID, idempotency_key: UUID, declared_raw_bytes: int | None, + idle_timeout_seconds: float, replay_duration: timedelta, + ) -> IntakeReplay: + """Authorize before reading bytes and again before revealing current state.""" + if not isinstance(replay_duration, timedelta) or replay_duration <= timedelta(0): + raise ValueError("intake replay duration must be positive") + metadata = SubmissionIntakeMetadata.model_validate(metadata) + original = await self._read(metadata, actor_id, idempotency_key) + if original.raw_sha256 is None or original.raw_byte_count is None: + code = "submission_operation_in_progress" if original.state in {"receiving", "pre_checking"} else "submission_operation_terminal" + raise IntakeCustodyConflict(code) + raw = await hash_submission_replay( + chunks, maximum_raw_bytes=original.maximum_raw_bytes, declared_raw_bytes=declared_raw_bytes, + idle_timeout_seconds=idle_timeout_seconds, deadline_at=datetime.now(UTC) + replay_duration, + ) + current = await self._read(metadata, actor_id, idempotency_key, expected_operation_id=original.operation_id) + if (raw.raw_sha256, raw.raw_byte_count) != (current.raw_sha256, current.raw_byte_count): + raise IntakeCustodyConflict("submission_idempotency_conflict") + return current diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py index 533e6ed7e..7126d61ac 100644 --- a/backend/app/modules/artifacts/intake/repository.py +++ b/backend/app/modules/artifacts/intake/repository.py @@ -47,7 +47,7 @@ def _require_transaction(self) -> None: raise IntakeCustodyConflict("intake_requires_root_transaction") async def reserve( - self, *, metadata: SubmissionIntakeMetadata, actor_id: UUID, identity_link_id: UUID, + self, *, operation_id: UUID, metadata: SubmissionIntakeMetadata, actor_id: UUID, identity_link_id: UUID, idempotency_key: UUID, maximum_raw_bytes: int, upload_deadline_at: datetime, lease_expires_at: datetime, capacity_limits: SubmissionSourceCapacityLimits, declared_raw_bytes: int | None, @@ -55,7 +55,8 @@ async def reserve( """Reserve command and physical bytes; callers still own AUTH and full T1 admission.""" self._require_transaction() metadata = SubmissionIntakeMetadata.model_validate(metadata) - operation_id = new_record_id() + if not isinstance(operation_id, UUID) or operation_id.version != 7: + raise ValueError("intake operation requires a generated UUIDv7") snapshot = await self._tasks.claim(TaskSubmissionContextRequest( metadata.task_id, metadata.assignment_id, actor_id, metadata.predecessor_submission_id, ), operation_id) @@ -87,6 +88,14 @@ async def reserve( await self._capacity.reserve(row, limits=capacity_limits, declared_raw_bytes=declared_raw_bytes) return row + async def find_actor_key(self, actor_id: UUID, key: UUID) -> SubmissionIntakeOperation | None: + """Resolve immutable caller identity before current TASK eligibility; not AUTH.""" + self._require_transaction() + return await self._session.scalar(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.actor_profile_id == str(actor_id), + SubmissionIntakeOperation.idempotency_key == str(key), + ).execution_options(populate_existing=True)) + async def _lock(self, operation_id: UUID) -> SubmissionIntakeOperation: self._require_transaction() task_id = await self._session.scalar(select(SubmissionIntakeOperation.task_id).where( diff --git a/backend/app/modules/artifacts/intake/streaming.py b/backend/app/modules/artifacts/intake/streaming.py index 60476587f..27b80d39f 100644 --- a/backend/app/modules/artifacts/intake/streaming.py +++ b/backend/app/modules/artifacts/intake/streaming.py @@ -10,6 +10,8 @@ from collections.abc import AsyncIterator import asyncio from datetime import UTC, datetime +from dataclasses import dataclass +import math import hashlib from app.interfaces.artifacts import ( @@ -28,6 +30,74 @@ MAXIMUM_INGRESS_CHUNK_BYTES = 1024 * 1024 +@dataclass(frozen=True, slots=True) +class RawSubmissionIdentity: + raw_sha256: str + raw_byte_count: int + + +class _IngressReceipt: + def __init__(self) -> None: + self.digest = hashlib.sha256() + self.count = 0 + + def identity(self) -> RawSubmissionIdentity: + return RawSubmissionIdentity("sha256:" + self.digest.hexdigest(), self.count) + + +async def _bounded_chunks( + chunks: AsyncIterator[bytes], receipt: _IngressReceipt, *, maximum_raw_bytes: int, + declared_raw_bytes: int | None, idle_timeout_seconds: float, +) -> AsyncIterator[bytes]: + """The same framing, size and EOF rules govern upload and discard replay.""" + while True: + try: + async with asyncio.timeout(idle_timeout_seconds): + chunk = await anext(chunks) + except StopAsyncIteration: + break + if type(chunk) is not bytes: + raise ArtifactInputMismatchError("submission ingress returned invalid bytes") + if len(chunk) > MAXIMUM_INGRESS_CHUNK_BYTES: + raise ArtifactLimitExceededError("submission ingress chunk exceeds transport bound") + receipt.count += len(chunk) + if receipt.count > maximum_raw_bytes: + raise ArtifactLimitExceededError("submission ZIP exceeds raw byte limit") + if declared_raw_bytes is not None and receipt.count > declared_raw_bytes: + raise ArtifactInputMismatchError("submission exceeds declared byte count") + receipt.digest.update(chunk) + yield chunk + if receipt.count == 0 or (declared_raw_bytes is not None and receipt.count != declared_raw_bytes): + raise ArtifactInputMismatchError("submission EOF violates declared or nonempty size") + + +async def hash_submission_replay( + chunks: AsyncIterator[bytes], *, maximum_raw_bytes: int, declared_raw_bytes: int | None, + idle_timeout_seconds: float, deadline_at: datetime, +) -> RawSubmissionIdentity: + """Hash/count a retry into a discard sink with no source/provider capability.""" + from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES + if (type(maximum_raw_bytes) is not int or not 1 <= maximum_raw_bytes <= MAXIMUM_SUBMISSION_ZIP_BYTES + or (declared_raw_bytes is not None and (type(declared_raw_bytes) is not int + or not 1 <= declared_raw_bytes <= maximum_raw_bytes)) + or isinstance(idle_timeout_seconds, bool) or not isinstance(idle_timeout_seconds, (int, float)) + or not math.isfinite(idle_timeout_seconds) or idle_timeout_seconds <= 0 + or not isinstance(deadline_at, datetime) or deadline_at.utcoffset() is None): + raise ValueError("submission replay limits are invalid") + remaining = (deadline_at - datetime.now(UTC)).total_seconds() + if remaining <= 0: + raise ArtifactStoreUnavailableError("submission replay deadline expired") + receipt = _IngressReceipt() + try: + async with asyncio.timeout(remaining): + async for _chunk in _bounded_chunks(chunks, receipt, maximum_raw_bytes=maximum_raw_bytes, + declared_raw_bytes=declared_raw_bytes, idle_timeout_seconds=idle_timeout_seconds): + pass + except TimeoutError: + raise ArtifactStoreUnavailableError("submission replay deadline expired") from None + return receipt.identity() + + async def receive_submission_source( store: ArtifactStore, upload: SubmissionSourceUpload, chunks: AsyncIterator[bytes], *, operation_evidence: ArtifactProviderOperationEvidence | None = None, @@ -57,26 +127,11 @@ async def _receive_parts( """Receive sequential parts inside the caller's immutable total deadline.""" intent = upload.intent evidence = operation_evidence or ArtifactProviderOperationEvidence() - digest = hashlib.sha256() - count = 0 + receipt = _IngressReceipt() pending = bytearray() parts = [] - while True: - try: - async with asyncio.timeout(intent.idle_timeout_seconds): - chunk = await anext(chunks) - except StopAsyncIteration: - break - if type(chunk) is not bytes: - raise ArtifactInputMismatchError("submission ingress returned invalid bytes") - if len(chunk) > MAXIMUM_INGRESS_CHUNK_BYTES: - raise ArtifactLimitExceededError("submission ingress chunk exceeds transport bound") - count += len(chunk) - if count > intent.maximum_raw_bytes: - raise ArtifactLimitExceededError("submission ZIP exceeds raw byte limit") - if intent.declared_raw_bytes is not None and count > intent.declared_raw_bytes: - raise ArtifactInputMismatchError("submission exceeds declared byte count") - digest.update(chunk) + async for chunk in _bounded_chunks(chunks, receipt, maximum_raw_bytes=intent.maximum_raw_bytes, + declared_raw_bytes=intent.declared_raw_bytes, idle_timeout_seconds=intent.idle_timeout_seconds): view = memoryview(chunk) while view: amount = min(intent.part_bytes - len(pending), len(view)) @@ -87,12 +142,10 @@ async def _receive_parts( upload, len(parts) + 1, bytes(pending), operation_evidence=evidence, )) pending.clear() - if count == 0 or (intent.declared_raw_bytes is not None and count != intent.declared_raw_bytes): - raise ArtifactInputMismatchError("submission EOF violates declared or nonempty size") if pending: parts.append(await store.upload_source_part( upload, len(parts) + 1, bytes(pending), operation_evidence=evidence, )) return SubmissionSourceCompletion( - upload=upload, parts=tuple(parts), raw_sha256="sha256:" + digest.hexdigest(), raw_byte_count=count, + upload=upload, parts=tuple(parts), raw_sha256=receipt.identity().raw_sha256, raw_byte_count=receipt.count, ) diff --git a/backend/app/modules/artifacts/submission_admission.py b/backend/app/modules/artifacts/submission_admission.py index e0306775c..cdad22c49 100644 --- a/backend/app/modules/artifacts/submission_admission.py +++ b/backend/app/modules/artifacts/submission_admission.py @@ -6,7 +6,6 @@ from contextlib import AbstractAsyncContextManager, AsyncExitStack import asyncio from dataclasses import dataclass, field, replace -import re from uuid import UUID from app.core.hashing import canonical_json_hash from app.interfaces.trusted_submission_intake import TrustedSubmissionIntakeAdapter @@ -98,7 +97,7 @@ ProjectLockedPolicyContextUnavailable, ) from app.modules.projects.api.policy_lineage import RevisionPolicySemantics -from app.modules.tasks.api.submission_context import require_revision_capacity +from app.modules.tasks.api.submission_context import require_revision_capacity, require_revision_acknowledgement from app.modules.tasks.api import ( TaskRetainedSubmissionParentsRequest, TaskSubmissionContextFacts, @@ -124,32 +123,10 @@ def require_revision_preparation_acknowledgement( request: SubmissionBundlePreparationRequest, ) -> None: """Compare the contributor's explicit acknowledgement after fresh authority.""" - supplied_id = request.revision_preparation_id - supplied_sha256 = request.revision_preparation_sha256 - if task.predecessor is None: - if supplied_id is not None or supplied_sha256 is not None: - raise SubmissionBundlePreparationRejected("revision_acknowledgement_invalid") - return - context = task.revision_context - if context is None: - raise SubmissionBundlePreparationRejected("revision_context_changed") - if supplied_id is None and supplied_sha256 is None: - raise SubmissionBundlePreparationRejected("revision_acknowledgement_required") - if not isinstance(supplied_id, str) or not isinstance(supplied_sha256, str): - raise SubmissionBundlePreparationRejected("revision_acknowledgement_invalid") try: - acknowledged_id = UUID(supplied_id) - except ValueError as exc: - raise SubmissionBundlePreparationRejected("revision_acknowledgement_invalid") from exc - if re.fullmatch(r"sha256:[0-9a-f]{64}", supplied_sha256) is None: - raise SubmissionBundlePreparationRejected("revision_acknowledgement_invalid") - if ( - context.source_submission_id != task.predecessor.submission_id - or context.source_routing_manifest_id != task.checker_remediation_manifest_id - or acknowledged_id != context.preparation_id - or supplied_sha256 != context.preparation_sha256 - ): - raise SubmissionBundlePreparationRejected("revision_context_changed") + require_revision_acknowledgement(task, request.revision_preparation_id, request.revision_preparation_sha256) + except TaskSubmissionContextUnavailable as exc: + raise SubmissionBundlePreparationRejected(exc.code) from exc @dataclass(frozen=True, slots=True) diff --git a/backend/app/modules/authorization/api/submission_intake.py b/backend/app/modules/authorization/api/submission_intake.py index 8396a2e61..430cf0c35 100644 --- a/backend/app/modules/authorization/api/submission_intake.py +++ b/backend/app/modules/authorization/api/submission_intake.py @@ -5,8 +5,8 @@ @dataclass(frozen=True, slots=True) -class IntakeReservationAuthorityFacts: - """Canonical locked facts supplied by ART/TASK before reserving source custody.""" +class IntakeReservationPreflightFacts: + """Exact selectors before task eligibility; no final context or grant.""" operation_id: UUID project_id: UUID task_id: UUID @@ -15,6 +15,11 @@ class IntakeReservationAuthorityFacts: identity_link_id: UUID idempotency_key: UUID metadata_sha256: str + + +@dataclass(frozen=True, slots=True) +class IntakeReservationAuthorityFacts(IntakeReservationPreflightFacts): + """Canonical locked facts required for the final reservation decision.""" locked_context_sha256: str task_status: Literal["in_progress", "needs_revision"] @@ -35,6 +40,7 @@ class IntakeAuthorityDenied(RuntimeError): class IntakeAuthorizationPort(Protocol): """The caller owns root transactions, product locks and original provenance.""" async def lock_actor(self, actor_id: UUID, identity_link_id: UUID) -> None: ... + async def preflight(self, facts: IntakeReservationPreflightFacts) -> None: ... async def prepare(self, facts: IntakeReservationAuthorityFacts) -> object: ... async def consume(self, handle: object, facts: IntakeReservationAuthorityFacts) -> UUID: ... async def authorize_read(self, facts: IntakeOperationReadFacts) -> UUID: ... diff --git a/backend/app/modules/authorization/domain/action_groups.py b/backend/app/modules/authorization/domain/action_groups.py index 250289e86..55cf3ea75 100644 --- a/backend/app/modules/authorization/domain/action_groups.py +++ b/backend/app/modules/authorization/domain/action_groups.py @@ -72,7 +72,7 @@ def supports_prepared_denial(action_id: ActionId, resource_context: object) -> bool: """Admit only the existing action/context pairs for prepare-time denial evidence.""" - from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext + from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext from app.modules.authorization.domain.task_authority import TASK_ACTIONS, TaskAuthorityResourceContext from app.modules.authorization.domain.project_create import ProjectCreateResourceContext from app.modules.authorization.domain.checker_retry import ( @@ -84,7 +84,7 @@ def supports_prepared_denial(action_id: ActionId, resource_context: object) -> b ProjectPolicyMutationPrepareDenialResourceContext, ProjectSubmissionArtifactPolicyMutationResourceContext, ) return ( - (action_id is ActionId.SUBMISSION_INTAKE_RESERVE and type(resource_context) is IntakeReservationResourceContext) + (action_id is ActionId.SUBMISSION_INTAKE_RESERVE and type(resource_context) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext}) or ( action_id in checker_outputs.CHECKER_OUTPUT_ACTIONS and type(resource_context) is checker_outputs.CheckerOutputResourceContext diff --git a/backend/app/modules/authorization/domain/audit.py b/backend/app/modules/authorization/domain/audit.py index 6b1c18747..cafe4acbf 100644 --- a/backend/app/modules/authorization/domain/audit.py +++ b/backend/app/modules/authorization/domain/audit.py @@ -21,6 +21,7 @@ "selected_pre_submit_run", "task_post_submit_routing_manifest", "submission_intake_reservation", + "submission_intake_preflight", "submission_operation_read", "task_authority", "task_submission_history", @@ -88,6 +89,7 @@ "selected_pre_submit_run", "task_post_submit_routing_manifest", "submission_intake_reservation", + "submission_intake_preflight", "submission_operation_read", "task_authority", "task_submission_history", diff --git a/backend/app/modules/authorization/domain/audit_targets.py b/backend/app/modules/authorization/domain/audit_targets.py index 2585acbfe..8890e026d 100644 --- a/backend/app/modules/authorization/domain/audit_targets.py +++ b/backend/app/modules/authorization/domain/audit_targets.py @@ -1,7 +1,7 @@ """Exact project resource audit selectors, without raw product facts.""" from uuid import UUID -from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext from app.modules.authorization.catalogue import ActionId @@ -79,6 +79,21 @@ def _model_administration_target(resource): return project_id, "project", project_id, "project", project_id +def _submission_operation_target(resource): + if type(resource) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext} or ( + type(resource) is ContributorWorkReadResourceContext + and resource.resource_type == "submission_operation_read" + ): + return (str(resource.scope_project_id), "submission_operation", str(resource.resource_id), + "submission_operation", str(resource.resource_id)) + return None + + +def _special_authority_target(resource): + return (_submission_operation_target(resource) or _post_submit_delivery_target(resource) + or _compensation_unit_target(resource) or _model_administration_target(resource)) + + def project_authority_audit_target( resource: object, action_id: ActionId, *, matched_scope_project_id: UUID | None = None, @@ -110,12 +125,6 @@ def project_authority_audit_target( ProjectGuideActivationResourceContext, ) - if type(resource) is IntakeReservationResourceContext or ( - type(resource) is ContributorWorkReadResourceContext - and resource.resource_type == "submission_operation_read" - ): - return (str(resource.scope_project_id), "submission_operation", str(resource.resource_id), - "submission_operation", str(resource.resource_id)) if type(resource) is ReviewLifecycleActivationContract: return None, resource.resource_type, str(resource.resource_id), "joint_lifecycle_control", str(resource.resource_id) if type(resource) is TaskImportBatchResourceContext: @@ -156,7 +165,7 @@ def project_authority_audit_target( return project_id, "checker_run", str(resource.resource_id), "project", project_id if type(resource) is CheckerRetrySourceReadResourceContext: return _checker_retry_read_target(resource) - if target := _post_submit_delivery_target(resource) or _compensation_unit_target(resource) or _model_administration_target(resource): + if target := _special_authority_target(resource): return target if action_id in SUBMISSION_POLICY_MUTATIONS and isinstance( resource, ProjectSubmissionArtifactPolicyMutationResourceContext, diff --git a/backend/app/modules/authorization/domain/submission_intake.py b/backend/app/modules/authorization/domain/submission_intake.py index d4e2ed377..aaecc20f3 100644 --- a/backend/app/modules/authorization/domain/submission_intake.py +++ b/backend/app/modules/authorization/domain/submission_intake.py @@ -8,10 +8,9 @@ from app.modules.authorization.catalogue import ActionId -class IntakeReservationResourceContext(BaseModel): +class _IntakeReservationSelectors(BaseModel): """A source-custody reservation, never a prepared artifact or Submission.""" model_config = ConfigDict(extra="forbid", frozen=True, strict=True, revalidate_instances="always") - resource_type: Literal["submission_intake_reservation"] = "submission_intake_reservation" resource_id: UUID scope_project_id: UUID task_id: UUID @@ -20,8 +19,6 @@ class IntakeReservationResourceContext(BaseModel): identity_link_id: UUID idempotency_key: UUID metadata_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - locked_context_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - task_status: Literal["in_progress", "needs_revision"] @field_validator("resource_id") @classmethod @@ -31,6 +28,34 @@ def operation_record(cls, value: UUID) -> UUID: return value + +class IntakeReservationPreflightResourceContext(_IntakeReservationSelectors): + """Selector-only preflight; cannot become a prepared reservation handle.""" + resource_type: Literal["submission_intake_preflight"] = "submission_intake_preflight" + + +class IntakeReservationResourceContext(_IntakeReservationSelectors): + """Complete locked reservation facts used only for prepare and consume.""" + resource_type: Literal["submission_intake_reservation"] = "submission_intake_reservation" + locked_context_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") + task_status: Literal["in_progress", "needs_revision"] + + +def intake_preflight_matches(caller_input, resource, scope) -> bool: + """Match strict partial selectors and exact project/key without issuing custody.""" + from app.modules.authorization.runtime import PreparedAuthorityScopeKind + if type(resource) is not IntakeReservationPreflightResourceContext: + return False + try: + parsed = IntakeReservationPreflightResourceContext.model_validate_json( + json.dumps(dict(caller_input.request_value))) + return (parsed == resource and caller_input.idempotency_key == parsed.idempotency_key + and scope.kind is PreparedAuthorityScopeKind.PROJECT + and scope.project_id == parsed.scope_project_id) + except (TypeError, ValueError): + return False + + def parse_intake_binding(action, request, key, invalid_error): """Bind every supplied field and caller key using the strict reservation schema.""" if action is not ActionId.SUBMISSION_INTAKE_RESERVE: diff --git a/backend/app/modules/authorization/prepared.py b/backend/app/modules/authorization/prepared.py index 109f33fd4..ff09ef68d 100644 --- a/backend/app/modules/authorization/prepared.py +++ b/backend/app/modules/authorization/prepared.py @@ -1,7 +1,8 @@ """Transaction-bound, single-use authorization for sensitive mutations.""" from __future__ import annotations -from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, parse_intake_binding +from app.modules.authorization.prepared_preflight import preflight_authority +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, intake_preflight_matches, parse_intake_binding from app.modules.authorization.catalogue import GUIDE_PROPOSAL_ACTION_IDS, POST_POLICY_ACTION_IDS from app.modules.authorization.domain.lifecycle import parse_lifecycle_prepare, lifecycle_matches from app.modules.authorization.prepared_routing_replay import validate_routing_replay @@ -66,7 +67,7 @@ parse_prepared_adapter_binding, prepared_adapter_binding_matches, ) -from app.modules.authorization.domain.prepared_service import project_setup_resource_matches, prepared_fixed_service_bindings +from app.modules.authorization.domain.prepared_service import prepared_fixed_service_bindings from app.modules.authorization.domain.prepared_guide_mutations import parse_prepared_guide_mutation from app.modules.authorization.domain.guide_compilation_projections import ( ProjectGuideProjectionResourceContext, @@ -552,48 +553,11 @@ async def prepare( return handle async def preflight( - self, - action_id: ActionId, - caller_input: PreparedAuthorizationInput, - scope: PreparedAuthorityScope, - resource: AuthorizationResourceContext, + self, action_id: ActionId, caller_input: PreparedAuthorizationInput, + scope: PreparedAuthorityScope, resource: AuthorizationResourceContext, ) -> None: """Revalidate current authority without issuing a handle or staging evidence.""" - self._root_transaction() - binding = self._binding(action_id, caller_input, scope) - scope_matches = self._scope_from_resource(action_id, resource) == scope - if isinstance(resource, SubmissionBundlePreparationPreflightResourceContext): - resource_matches = _submission_preparation_binding_matches(binding, resource) - else: - resource_matches = prepared_compilation_matches( - binding.guide_compilation_context, - binding.guide_compilation_resource_digest, - resource, - ) - if not scope_matches or not resource_matches: - raise PreparedAuthorizationHandleInvalid("invalid prepared authorization preflight") - authority = await self._authorization._prepare_prelocked( - self._consumer_token, action_id, scope - ) - try: - setup_match = project_setup_resource_matches( - action_id, resource, authority.scope_project_id - ) - if setup_match is False or ( - setup_match is None - and action_id is not ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE - and not ( - action_id is ActionId.PROJECT_GUIDE_COMPILATION_REQUEST - and isinstance(resource, ProjectGuideCompilationRequestResourceContext) - and resource.trigger == "project_manager" - and resource.scope_project_id == authority.scope_project_id - ) - ): - raise PreparedAuthorizationUnsupported( - AuthorizationDenialCode.RESOURCE_GUARD_DENIED - ) - finally: - self._authorization._discard_prelocked(authority) + await preflight_authority(self, action_id, caller_input, scope, resource) def _live_issuance(self, handle: PreparedAuthorizationHandle) -> _Issuance: """Reject foreign, consumed and closed-session handles at the shared entry boundary.""" @@ -823,6 +787,16 @@ async def deny_unsupported( denial: PreparedAuthorizationUnsupported, ) -> NoReturn: """Evidence an exact prepare-time denial without issuing a handle.""" + if action_id is ActionId.SUBMISSION_INTAKE_RESERVE and type(final_resource_context) is IntakeReservationPreflightResourceContext: + self._root_transaction() + scope = PreparedAuthorityScope(kind=PreparedAuthorityScopeKind.PROJECT, + project_id=final_resource_context.scope_project_id) + if caller_input is None or not intake_preflight_matches(caller_input, final_resource_context, scope): + raise PreparedAuthorizationHandleInvalid("invalid intake preflight denial") + await self._authorization._complete_prepared_denial( + self._consumer_token, action_id, final_resource_context, denial.denial_code, + ) + raise RuntimeError("denied intake preflight unexpectedly returned") if type(final_resource_context) is ContributionPolicyMutationScopeDenialResourceContext: self._root_transaction() if caller_input is not None or action_id != final_resource_context.requested_action: diff --git a/backend/app/modules/authorization/prepared_preflight.py b/backend/app/modules/authorization/prepared_preflight.py new file mode 100644 index 000000000..94ca10aa3 --- /dev/null +++ b/backend/app/modules/authorization/prepared_preflight.py @@ -0,0 +1,57 @@ +"""Selector-only AUTH preflight without prepared handles or allow evidence.""" +from app.modules.authorization.catalogue import ActionId +from app.modules.authorization.domain.guide_compilation import ProjectGuideCompilationRequestResourceContext +from app.modules.authorization.domain.prepared_compilation import prepared_compilation_matches +from app.modules.authorization.domain.prepared_service import project_setup_resource_matches +from app.modules.authorization.domain.submission_intake import IntakeReservationPreflightResourceContext, intake_preflight_matches +from app.modules.authorization.submission_preparation import SubmissionBundlePreparationPreflightResourceContext +from app.modules.authorization.runtime import ( + AuthorizationDenialCode, PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported, +) + + +async def preflight_authority(service, action_id, caller_input, scope, resource): + """Check exact selectors and current grant under the issuing service's root.""" + from app.modules.authorization.prepared import _submission_preparation_binding_matches + service._root_transaction() + if action_id is ActionId.SUBMISSION_INTAKE_RESERVE: + scope_matches = True # The strict intake matcher compares both scope and selectors. + resource_matches = intake_preflight_matches(caller_input, resource, scope) + else: + binding = service._binding(action_id, caller_input, scope) + scope_matches = service._scope_from_resource(action_id, resource) == scope + if isinstance(resource, SubmissionBundlePreparationPreflightResourceContext): + resource_matches = _submission_preparation_binding_matches(binding, resource) + else: + resource_matches = prepared_compilation_matches( + binding.guide_compilation_context, + binding.guide_compilation_resource_digest, + resource, + ) + if not scope_matches or not resource_matches: + raise PreparedAuthorizationHandleInvalid("invalid prepared authorization preflight") + authority = await service._authorization._prepare_prelocked( + service._consumer_token, action_id, scope + ) + try: + setup_match = project_setup_resource_matches( + action_id, resource, authority.scope_project_id + ) + if setup_match is False or ( + setup_match is None + and action_id is not ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE + and not (action_id is ActionId.SUBMISSION_INTAKE_RESERVE + and type(resource) is IntakeReservationPreflightResourceContext) + and not ( + action_id is ActionId.PROJECT_GUIDE_COMPILATION_REQUEST + and isinstance(resource, ProjectGuideCompilationRequestResourceContext) + and resource.trigger == "project_manager" + and resource.scope_project_id == authority.scope_project_id + ) + ): + raise PreparedAuthorizationUnsupported( + AuthorizationDenialCode.RESOURCE_GUARD_DENIED + ) + finally: + service._authorization._discard_prelocked(authority) + diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py index cbc331c82..428fc8986 100644 --- a/backend/app/modules/authorization/runtime.py +++ b/backend/app/modules/authorization/runtime.py @@ -47,7 +47,7 @@ from app.modules.authorization.domain.guide_activation import ProjectGuideActivationResourceContext from app.modules.authorization.domain.lifecycle import ReviewLifecycleActivationContract from app.modules.authorization.service_actor_schemas import ServiceActorProvisionResourceContext -from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext from app.modules.authorization.catalogue import ActionId from app.modules.authorization.domain.artifact_storage import ( ArtifactPutAttemptResourceContext as ArtifactPutAttemptResourceContext, @@ -1067,7 +1067,7 @@ class PreSubmitCheckerInputResourceContext(PreSubmitCheckerInputPreparationConte | checker_models.CheckerModelCallResourceContext | checker_models.ProjectModelAdministrationResourceContext | checker_outputs.CheckerOutputResourceContext - | IntakeReservationResourceContext + | IntakeReservationResourceContext | IntakeReservationPreflightResourceContext | contributor_reads.ActorProjectListResourceContext | contributor_reads.ContributorWorkReadResourceContext | project_catalogue.ProjectCatalogueResourceContext | management_reads.ProjectManagementReadResourceContext | diff --git a/backend/app/modules/authorization/submission_intake.py b/backend/app/modules/authorization/submission_intake.py index eb768ae65..d1d6cca60 100644 --- a/backend/app/modules/authorization/submission_intake.py +++ b/backend/app/modules/authorization/submission_intake.py @@ -7,11 +7,11 @@ from app.core.hashing import canonical_json_hash from app.modules.authorization.api.submission_intake import ( - IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, + IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts, ) from app.modules.authorization.catalogue import ActionId from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext -from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext +from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext from app.modules.authorization.kernel import AuthorizationService from app.modules.authorization.prepared import PreparedAuthorizationService from app.modules.authorization.repository import AdminAuthorizationRepository @@ -64,6 +64,27 @@ def _input(resource: IntakeReservationResourceContext) -> PreparedAuthorizationI return PreparedAuthorizationInput(idempotency_key=resource.idempotency_key, request_value=resource.model_dump(mode="json")) + async def preflight(self, facts: IntakeReservationPreflightFacts) -> None: + """Check fresh Submitter authority before eligibility disclosure, with no handle.""" + if (type(facts) is not IntakeReservationPreflightFacts + or facts.actor_profile_id != self._context.actor_profile_id + or facts.identity_link_id != self._context.identity_link_id): + raise IntakeAuthorityDenied("submission intake is unavailable") + values = asdict(facts) + values["resource_id"] = values.pop("operation_id") + values["scope_project_id"] = values.pop("project_id") + try: + resource = IntakeReservationPreflightResourceContext(**values) + value = PreparedAuthorizationInput(idempotency_key=facts.idempotency_key, + request_value=resource.model_dump(mode="json")) + try: + await self._prepared.preflight(ActionId.SUBMISSION_INTAKE_RESERVE, value, + PreparedAuthorityScope(kind=PreparedAuthorityScopeKind.PROJECT, project_id=facts.project_id), resource) + except PreparedAuthorizationUnsupported as exc: + await self._prepared.deny_unsupported(ActionId.SUBMISSION_INTAKE_RESERVE, value, resource, exc) + except (AuthorizationDenied, PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported, ValidationError) as exc: + raise IntakeAuthorityDenied("submission intake is unavailable") from exc + async def prepare(self, facts: IntakeReservationAuthorityFacts) -> object: resource = self._resource(facts) value = self._input(resource) diff --git a/backend/app/modules/tasks/api/intake_custody.py b/backend/app/modules/tasks/api/intake_custody.py index 08f0d4c2e..0a9934e10 100644 --- a/backend/app/modules/tasks/api/intake_custody.py +++ b/backend/app/modules/tasks/api/intake_custody.py @@ -23,8 +23,8 @@ async def claim(self, request: TaskSubmissionContextRequest, operation_id: UUID) """Lock canonical submission context and install its unique operation pointer.""" ... - async def lock(self, task_id: UUID) -> None: - """Acquire the TASK lock before ART locks the associated operation.""" + async def lock(self, task_id: UUID) -> UUID: + """Acquire TASK first and return its project without asserting eligibility.""" ... async def release(self, task_id: UUID, operation_id: UUID) -> None: diff --git a/backend/app/modules/tasks/api/submission_context.py b/backend/app/modules/tasks/api/submission_context.py index 1f87e1f89..d60e9d667 100644 --- a/backend/app/modules/tasks/api/submission_context.py +++ b/backend/app/modules/tasks/api/submission_context.py @@ -2,6 +2,7 @@ from __future__ import annotations +import re from dataclasses import dataclass from typing import Literal, Protocol, get_args from uuid import UUID @@ -14,6 +15,9 @@ TaskSubmissionContextStatus = Literal["in_progress", "needs_revision"] TaskSubmissionContextFailure = Literal[ "task_submission_context_invalid", + "task_submission_operation_in_progress", + "revision_acknowledgement_required", + "revision_acknowledgement_invalid", "task_submission_predecessor_changed", "revision_limit_reached", "revision_deadline_expired", @@ -198,3 +202,32 @@ def require_revision_capacity( # A global Submission version is not an assignment's revision allowance. if task.predecessor.revision_round > max_revision_rounds: raise TaskSubmissionContextUnavailable("revision_limit_reached") + + + +def require_revision_acknowledgement( + task: TaskSubmissionContextFacts, preparation_id: UUID | str | None, preparation_sha256: str | None, +) -> None: + """Compare an explicit packet acknowledgement with canonical locked revision facts.""" + if task.predecessor is None: + if preparation_id is not None or preparation_sha256 is not None: + raise TaskSubmissionContextUnavailable("revision_acknowledgement_invalid") + return + context = task.revision_context + if context is None: + raise TaskSubmissionContextUnavailable("revision_context_changed") + if preparation_id is None and preparation_sha256 is None: + raise TaskSubmissionContextUnavailable("revision_acknowledgement_required") + if not isinstance(preparation_id, (UUID, str)) or not isinstance(preparation_sha256, str): + raise TaskSubmissionContextUnavailable("revision_acknowledgement_invalid") + try: + acknowledged_id = UUID(preparation_id) if isinstance(preparation_id, str) else preparation_id + except ValueError as exc: + raise TaskSubmissionContextUnavailable("revision_acknowledgement_invalid") from exc + if re.fullmatch(r"sha256:[0-9a-f]{64}", preparation_sha256) is None: + raise TaskSubmissionContextUnavailable("revision_acknowledgement_invalid") + if (context.source_submission_id != task.predecessor.submission_id + or context.source_routing_manifest_id != task.checker_remediation_manifest_id + or acknowledged_id != context.preparation_id + or preparation_sha256 != context.preparation_sha256): + raise TaskSubmissionContextUnavailable("revision_context_changed") diff --git a/backend/app/modules/tasks/intake_custody.py b/backend/app/modules/tasks/intake_custody.py index 077e07c43..d1cbc0fbe 100644 --- a/backend/app/modules/tasks/intake_custody.py +++ b/backend/app/modules/tasks/intake_custody.py @@ -21,19 +21,21 @@ def __init__(self, session: AsyncSession, contexts: TaskSubmissionContextPort) - self._tasks = TaskRepository(session) self._contexts = contexts - async def lock(self, task_id: UUID) -> None: + async def lock(self, task_id: UUID) -> UUID: """Lock TASK first and require a root transaction owned by the caller.""" if not self._session.in_transaction() or self._session.in_nested_transaction(): raise TaskSubmissionContextUnavailable("task_submission_context_invalid") - if await self._tasks.get_task(str(task_id), for_update=True) is None: + task = await self._tasks.get_task(str(task_id), for_update=True) + if task is None: raise TaskSubmissionContextUnavailable("task_submission_context_invalid") + return UUID(task.project_id) async def claim(self, request: TaskSubmissionContextRequest, operation_id: UUID) -> IntakeTaskSnapshot: """Use canonical eligibility/currentness before installing a new pointer.""" await self.lock(request.task_id) task = await self._tasks.get_task(str(request.task_id), for_update=True) if task.active_submission_operation_id is not None: - raise TaskSubmissionContextUnavailable("task_submission_context_invalid") + raise TaskSubmissionContextUnavailable("task_submission_operation_in_progress") context = await self._contexts.lock_submission_context(request) snapshot = await self._session.scalar(text( "SELECT public.submission_intake_task_snapshot(t) " diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 74d65ae5d..655cd3392 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -939,7 +939,9 @@ "backend/app/modules/artifacts/intake/streaming.py", "backend/app/modules/authorization/api/submission_intake.py", "backend/app/modules/authorization/domain/submission_intake.py", + "backend/app/modules/authorization/prepared_preflight.py", "backend/app/modules/authorization/submission_intake.py", + "backend/app/modules/artifacts/intake/foreground_admission.py", "backend/app/modules/artifacts/intake/foreground_lease.py", "backend/app/modules/artifacts/intake/foreground_upload.py", "backend/app/adapters/artifacts/local_submission_source.py", diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index ec6fc5902..609cdf79c 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -54,6 +54,7 @@ class TestLane: "tests/artifacts/test_selected_predecessor_rules.py", "tests/artifacts/test_submission_intake_contracts.py", "tests/artifacts/test_submission_intake_custody.py", + "tests/artifacts/test_submission_intake_admission.py", "tests/authorization/post_submit/test_atomicity.py", "tests/authorization/post_submit/test_concurrency.py", "tests/authorization/post_submit/test_live_authority.py", diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py new file mode 100644 index 000000000..651434c7b --- /dev/null +++ b/backend/tests/artifacts/test_submission_intake_admission.py @@ -0,0 +1,427 @@ +"""Real AUTH/TASK/PROJECT T1 transaction and exact replay proof.""" +import asyncio +from datetime import timedelta +from types import SimpleNamespace + +import pytest +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.adapters.tasks import task_submission_context_port +from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits, SubmissionSourceUpload +from app.modules.artifacts.intake.models import SubmissionIntakeOperation +from app.modules.artifacts.intake.repository import IntakeCustodyConflict +from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable +from app.modules.tasks.intake_custody import IntakeTaskCustody +from tests.artifacts.test_submission_intake_custody import repository, record_eof +from tests.selected_policy_fixtures import approved_selected_policy_fixture +from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test +from tests.test_artifact_admission import _namespace, _settings +# Signed grant fixtures are scoped to this integration suite. +from tests.authentication.fixtures import ( + auth_database_env as auth_database_env, + clear_settings_cache as clear_settings_cache, + rsa_signing_material as rsa_signing_material, +) +from tests.authorization.admin_access.fixtures import ( + signed_access as signed_access, + admin_access as admin_access, +) + + +@pytest.fixture +async def admission_intake(tmp_path, isolated_database_env, admin_access, request): + from app.adapters.projects import project_locked_policy_context_port + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization + from tests.authorization.task_authority.test_postgresql import context, grant, project_manager + + engine = create_async_engine(isolated_database_env) + factory = async_sessionmaker(engine, expire_on_commit=False) + namespace = _namespace(_settings(tmp_path)) + if getattr(request, "param", None) == "aws": + from app.interfaces.artifacts import ArtifactStoreNamespaceIdentity, artifact_store_namespace_material + from app.interfaces.external_services import ExternalServiceAdapterIdentity + from app.modules.artifacts.service import ArtifactStorageNamespaceSpec + identity = ArtifactStoreNamespaceIdentity("aws-s3-v1", ( + ("addressing_style", "virtual"), ("bucket", "intake-refusal-fixture"), + ("private_prefix", "workstream/artifacts"), ("region", "us-east-1"), + )) + descriptor, fingerprint = artifact_store_namespace_material( + backend="s3", adapter_identity=ExternalServiceAdapterIdentity("artifact_store", "s3"), + namespace_identity=identity, + ) + namespace = ArtifactStorageNamespaceSpec("s3", "s3", identity.provider_profile, descriptor, fingerprint) + try: + from tests.checkers.external.support import pre_registry_spec, post_registry_spec + plan, _ = await approved_selected_policy_fixture( + factory, namespace, guide_version="v1", + pre_submit_registry_spec=None if getattr(request, "param", None) == "no_pre" else pre_registry_spec(), + post_submit_registry_spec=None if getattr(request, "param", None) == "no_post" else post_registry_spec(), + ) + project = plan.lineage.project_id + manager = await project_manager(admin_access, project) + grant_id = await grant(admin_access, manager, project) + actor = await context(admin_access) + task, assignment = new_record_id(), new_record_id() + async with engine.begin() as connection: + await seed_started_task_for_artifact_test(connection, dict( + task=str(task), assignment=str(assignment), project=str(project), actor=str(actor.actor_profile_id), + )) + admission = ForegroundIntakeAdmission( + factory, tasks=lambda session: IntakeTaskCustody(session, task_submission_context_port(session)), + task_contexts=task_submission_context_port, projects=project_locked_policy_context_port, + authorization=lambda session: SubmissionIntakeAuthorization(session, actor), namespace=namespace, + capacity_limits=SubmissionSourceCapacityLimits(maximum_total_bytes=1_000_000), maximum_raw_bytes=1024, + upload_duration=timedelta(seconds=300), lease_duration=timedelta(seconds=60), + ) + yield SimpleNamespace(factory=factory, actor=actor, task=task, assignment=assignment, + admission=admission, project=project, namespace=namespace, + access=admin_access, manager=manager, grant_id=grant_id) + finally: + await engine.dispose() + + +async def admit_new(fixture, *, key=None, metadata=None): + return await fixture.admission.admit( + metadata or SubmissionIntakeMetadata(task_id=fixture.task, assignment_id=fixture.assignment), + actor_id=fixture.actor.actor_profile_id, identity_link_id=fixture.actor.identity_link_id, + idempotency_key=key or new_record_id(), declared_raw_bytes=None, + ) + + +async def test_t1_commits_exact_owner_charge_pointer_and_allow(admission_intake): + from sqlalchemy import select + from app.modules.artifacts.intake.foreground_admission import IntakeReservationOwner, IntakeReplay + from app.modules.artifacts.intake.models import SubmissionSourceCharge + from app.modules.tasks.models import AuditEvent, WorkstreamTask + + f = admission_intake + key = new_record_id() + owner = await admit_new(f, key=key) + assert isinstance(owner, IntakeReservationOwner) + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + charge = await session.get(SubmissionSourceCharge, row.id) + task = await session.get(WorkstreamTask, str(f.task)) + assert row.state == "receiving" and row.raw_sha256 is None + assert row.idempotency_key == str(key) and row.identity_link_id == str(f.actor.identity_link_id) + assert task.active_submission_operation_id == row.id + assert charge.accounted_bytes == 1024 and charge.state == "reserved" + events = list(await session.scalars(select(AuditEvent).where( + AuditEvent.action_id == "submission.intake.reserve", AuditEvent.resource_id == row.id))) + assert len(events) == 1 and events[0].after_facts["allowed"] is True + retry = await admit_new(f, key=key) + assert isinstance(retry, IntakeReplay) and retry.operation_id == owner.operation_id + + async def forbidden_body(): + pytest.fail("a retry without EOF read the body") + yield b"never" + + with pytest.raises(IntakeCustodyConflict, match="submission_operation_in_progress"): + await f.admission.replay( + SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment), forbidden_body(), + actor_id=f.actor.actor_profile_id, idempotency_key=key, declared_raw_bytes=None, + idle_timeout_seconds=1, replay_duration=timedelta(seconds=10), + ) + + +async def test_t1_replays_eof_before_provider_completion_without_changing_custody(admission_intake): + from app.modules.artifacts.intake.foreground_admission import IntakeReplay + f = admission_intake + key = new_record_id() + owner = await admit_new(f, key=key) + payload = b"original raw ZIP" + await record_intake_eof(f, owner, payload) + + async def body(value): + yield value + + arguments = dict(actor_id=f.actor.actor_profile_id, idempotency_key=key, + declared_raw_bytes=None, idle_timeout_seconds=1, replay_duration=timedelta(seconds=10)) + metadata = SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment) + replay = await f.admission.replay(metadata, body(payload), **arguments) + assert isinstance(replay, IntakeReplay) and replay.operation_id == owner.operation_id + with pytest.raises(IntakeCustodyConflict, match="submission_idempotency_conflict"): + await f.admission.replay(metadata, body(b"different"), **arguments) + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + assert row.state == "receiving" and row.provider_generation is None + assert (row.lease_id, row.lease_generation) == (str(owner.lease_id), owner.generation) + + + + async with f.factory.begin() as session: + await repository(session).terminalize(owner.operation_id, owner.lease_id, owner.generation, + state="failed", failure_code="upload_failed") + replacement = await admit_new(f) + terminal = await f.admission.replay(metadata, body(payload), **arguments) + assert terminal.operation_id == owner.operation_id and terminal.state == "failed" + assert terminal.failure_code == "upload_failed" and replacement.operation_id != owner.operation_id + + +async def test_t1_same_key_race_has_one_owner_and_one_operation(admission_intake): + from sqlalchemy import select, func + from app.modules.artifacts.intake.foreground_admission import IntakeReservationOwner, IntakeReplay + f = admission_intake + key = new_record_id() + results = await asyncio.wait_for(asyncio.gather(admit_new(f, key=key), admit_new(f, key=key)), 10) + assert sum(isinstance(value, IntakeReservationOwner) for value in results) == 1 + assert sum(isinstance(value, IntakeReplay) for value in results) == 1 + assert results[0].operation_id == results[1].operation_id + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation)) == 1 + + +async def test_t1_lost_commit_ack_resolves_as_replay_not_upload_owner(admission_intake): + from sqlalchemy.ext.asyncio import AsyncSession + from app.modules.artifacts.intake.foreground_admission import IntakeReplay + f = admission_intake + committed = False + + class LostAcknowledgement(AsyncSession): + async def commit(self): + nonlocal committed + await super().commit() + if not committed: + committed = True + raise OSError("simulated lost commit acknowledgement") + + f.admission._sessions = async_sessionmaker(f.factory.kw["bind"], class_=LostAcknowledgement, expire_on_commit=False) + result = await admit_new(f) + assert committed and isinstance(result, IntakeReplay) and result.state == "receiving" + async with f.factory() as session: + assert await session.get(SubmissionIntakeOperation, str(result.operation_id)) is not None + + +async def test_t1_revoked_grant_blocks_new_admission_and_existing_replay(admission_intake): + from sqlalchemy import func, select + from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied + f = admission_intake + key = new_record_id() + owner = await admit_new(f, key=key) + response = await f.access.signed.client.post( + f"/api/v1/projects/{f.project}/role-grants/{f.grant_id}/revoke", + headers=f.manager.headers | {"Idempotency-Key": str(new_record_id())}, + json={"reason": "Withdraw intake test grant"}, + ) + assert response.status_code == 200, response.text + for retry_key in (key, new_record_id()): + with pytest.raises(IntakeAuthorityDenied): + await admit_new(f, key=retry_key) + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation)) == 1 + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + assert row.state == "receiving" and row.lease_id == str(owner.lease_id) + + +async def test_t1_namespace_refusal_leaves_no_pointer_charge_or_allow(admission_intake): + from dataclasses import replace + from sqlalchemy import func, select + from app.modules.artifacts.intake.models import SubmissionSourceCharge + from app.modules.tasks.models import AuditEvent, WorkstreamTask + f = admission_intake + f.admission._namespace = replace(f.namespace, namespace_fingerprint="sha256:" + "0" * 64) + with pytest.raises(IntakeCustodyConflict, match="intake_namespace_unavailable"): + await admit_new(f) + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation)) == 0 + assert await session.scalar(select(func.count()).select_from(SubmissionSourceCharge)) == 0 + task = await session.get(WorkstreamTask, str(f.task)) + assert task.active_submission_operation_id is None + assert not list(await session.scalars(select(AuditEvent).where( + AuditEvent.action_id == "submission.intake.reserve"))) + + +async def test_t1_different_key_and_changed_metadata_cannot_replace_active_owner(admission_intake): + f = admission_intake + key = new_record_id() + owner = await admit_new(f, key=key) + with pytest.raises(TaskSubmissionContextUnavailable, match="task_submission_operation_in_progress"): + await admit_new(f) + with pytest.raises(IntakeCustodyConflict, match="submission_idempotency_conflict"): + await admit_new(f, key=key, metadata=SubmissionIntakeMetadata(task_id=f.task, assignment_id=new_record_id())) + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + assert row.state == "receiving" and row.assignment_id == str(f.assignment) + + +async def test_t1_capacity_refusal_rolls_back_pointer_operation_and_allow(admission_intake): + from sqlalchemy import select, func + from app.modules.artifacts.intake.capacity import SubmissionSourceCapacityConflict + from app.modules.tasks.models import AuditEvent, WorkstreamTask + f = admission_intake + f.admission._capacity = SubmissionSourceCapacityLimits(maximum_total_bytes=1) + with pytest.raises(SubmissionSourceCapacityConflict, match="source_capacity_exhausted"): + await admit_new(f) + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation)) == 0 + assert (await session.get(WorkstreamTask, str(f.task))).active_submission_operation_id is None + assert not list(await session.scalars(select(AuditEvent).where( + AuditEvent.action_id == "submission.intake.reserve"))) + + +async def test_t1_cancelled_commit_drains_and_never_returns_upload_owner(admission_intake): + from sqlalchemy import select + from sqlalchemy.ext.asyncio import AsyncSession + from app.modules.artifacts.intake.models import SubmissionSourceCharge + f = admission_intake + committed, release = asyncio.Event(), asyncio.Event() + key = new_record_id() + + class DelayedAcknowledgement(AsyncSession): + async def commit(self): + await super().commit() + committed.set() + await release.wait() + + f.admission._sessions = async_sessionmaker(f.factory.kw["bind"], class_=DelayedAcknowledgement, expire_on_commit=False) + command = asyncio.create_task(admit_new(f, key=key)) + try: + await asyncio.wait_for(committed.wait(), 10) + command.cancel() + await asyncio.sleep(0) + command.cancel() + assert not command.done() + release.set() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(command, 10) + finally: + release.set() + command.cancel() + await asyncio.gather(command, return_exceptions=True) + async with f.factory() as session: + row = await session.scalar(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.idempotency_key == str(key))) + assert row is not None and row.state == "receiving" + assert (await session.get(SubmissionSourceCharge, row.id)).accounted_bytes == 1024 + + +async def record_intake_eof(f, owner, payload): + import hashlib + async with f.factory.begin() as session: + repo = repository(session) + intent = await repo.prepare_upload(owner.operation_id, owner.lease_id, owner.generation, + part_bytes=5 * 1024 * 1024, idle_timeout_seconds=1) + await repo.record_upload(owner.operation_id, owner.lease_id, owner.generation, + upload=SubmissionSourceUpload(intent=intent, provider_upload_id="recorded-handle")) + await record_eof(session, owner.operation_id, owner.lease_id, owner.generation, + raw_sha256="sha256:" + hashlib.sha256(payload).hexdigest(), raw_byte_count=len(payload)) + + + +@pytest.mark.parametrize("admission_intake", ["no_pre", "no_post"], indirect=True) +async def test_t1_requires_one_selected_checker_in_each_phase(admission_intake): + from sqlalchemy import func, select + from app.modules.tasks.models import WorkstreamTask, AuditEvent + f = admission_intake + with pytest.raises(IntakeCustodyConflict, match="intake_requires_one_pre_and_post_checker"): + await admit_new(f) + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation)) == 0 + assert (await session.get(WorkstreamTask, str(f.task))).active_submission_operation_id is None + assert not list(await session.scalars(select(AuditEvent).where( + AuditEvent.action_id == "submission.intake.reserve"))) + + +async def test_t1_cross_task_same_key_race_resolves_original_before_eligibility(admission_intake): + from sqlalchemy import select, func + from app.modules.artifacts.intake.foreground_admission import IntakeReservationOwner + f = admission_intake + other_task, other_assignment = new_record_id(), new_record_id() + async with f.factory.kw["bind"].begin() as connection: + await seed_started_task_for_artifact_test(connection, dict( + task=str(other_task), assignment=str(other_assignment), project=str(f.project), actor=str(f.actor.actor_profile_id), + )) + key = new_record_id() + selectors = [SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment), + SubmissionIntakeMetadata(task_id=other_task, assignment_id=other_assignment)] + results = await asyncio.wait_for(asyncio.gather( + *(admit_new(f, key=key, metadata=metadata) for metadata in selectors), return_exceptions=True, + ), 10) + assert sum(isinstance(value, IntakeReservationOwner) for value in results) == 1 + conflicts = [value for value in results if isinstance(value, IntakeCustodyConflict)] + assert len(conflicts) == 1 and str(conflicts[0]) == "submission_idempotency_conflict" + # Even a now-missing requested task resolves the old operation before eligibility. + with pytest.raises(IntakeCustodyConflict, match="submission_idempotency_conflict"): + await admit_new(f, key=key, metadata=SubmissionIntakeMetadata(task_id=new_record_id(), assignment_id=new_record_id())) + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation)) == 1 + + +async def test_t1_cancelled_discard_replay_does_not_terminalize_original(admission_intake): + from app.modules.artifacts.intake.models import SubmissionSourceCharge + f = admission_intake + key = new_record_id() + owner = await admit_new(f, key=key) + await record_intake_eof(f, owner, b"raw ZIP") + started, stopped = asyncio.Event(), asyncio.Event() + + async def body(): + try: + started.set() + await asyncio.Event().wait() + yield b"never" + finally: + stopped.set() + + command = asyncio.create_task(f.admission.replay( + SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment), body(), + actor_id=f.actor.actor_profile_id, idempotency_key=key, declared_raw_bytes=None, + idle_timeout_seconds=10, replay_duration=timedelta(seconds=30), + )) + try: + await asyncio.wait_for(started.wait(), 10) + command.cancel() + with pytest.raises(asyncio.CancelledError): + await command + finally: + command.cancel() + await asyncio.gather(command, return_exceptions=True) + assert stopped.is_set() + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + assert row.state == "receiving" and row.lease_generation == owner.generation + assert (await session.get(SubmissionSourceCharge, row.id)).accounted_bytes == 1024 + + +@pytest.mark.parametrize("admission_intake", ["aws"], indirect=True) +async def test_t1_unqualified_aws_source_refuses_before_reservation(admission_intake): + from sqlalchemy import func, select + from app.modules.artifacts.intake.models import SubmissionSourceCharge + from app.modules.tasks.models import WorkstreamTask + f = admission_intake + with pytest.raises(IntakeCustodyConflict, match="intake_source_provider_unqualified"): + await admit_new(f) + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation)) == 0 + assert await session.scalar(select(func.count()).select_from(SubmissionSourceCharge)) == 0 + assert (await session.get(WorkstreamTask, str(f.task))).active_submission_operation_id is None + + +async def test_t1_replay_reauthorizes_after_body_read(admission_intake): + from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied + f = admission_intake + key = new_record_id() + owner = await admit_new(f, key=key) + payload = b"raw ZIP" + await record_intake_eof(f, owner, payload) + + async def body(): + yield payload + response = await f.access.signed.client.post( + f"/api/v1/projects/{f.project}/role-grants/{f.grant_id}/revoke", + headers=f.manager.headers | {"Idempotency-Key": str(new_record_id())}, + json={"reason": "Withdraw grant during intake replay"}, + ) + assert response.status_code == 200, response.text + + with pytest.raises(IntakeAuthorityDenied): + await asyncio.wait_for(f.admission.replay( + SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment), body(), + actor_id=f.actor.actor_profile_id, idempotency_key=key, declared_raw_bytes=None, + idle_timeout_seconds=10, replay_duration=timedelta(seconds=20), + ), 20) + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + assert row.state == "receiving" and row.lease_generation == owner.generation diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py index 1ff349f3f..dee7f8c25 100644 --- a/backend/tests/artifacts/test_submission_intake_contracts.py +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -391,3 +391,91 @@ async def command(*owner): monkeypatch.setattr(runner, "_renew", renew) assert await runner.run(new_record_id(), new_record_id(), 1, command) == "committed" + + +@pytest.mark.asyncio +async def test_discard_replay_hashes_exact_raw_bytes_across_chunk_boundaries(): + from app.modules.artifacts.intake.streaming import hash_submission_replay + + payload = b"PK\x03\x04\x00\xffraw ZIP bytes" + + async def chunks(): + for chunk in (payload[:3], b"", payload[3:8], payload[8:]): + yield chunk + + receipt = await hash_submission_replay( + chunks(), maximum_raw_bytes=100, declared_raw_bytes=len(payload), + idle_timeout_seconds=1, deadline_at=datetime.now(UTC) + timedelta(seconds=2), + ) + assert receipt.raw_byte_count == len(payload) + assert receipt.raw_sha256 == "sha256:" + hashlib.sha256(payload).hexdigest() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("updates,payload,error", [ + ({}, [], ArtifactInputMismatchError), + ({"declared_raw_bytes": 4}, [b"abc"], ArtifactInputMismatchError), + ({"declared_raw_bytes": 2}, [b"abc"], ArtifactInputMismatchError), + ({"maximum_raw_bytes": 2}, [b"abc"], ArtifactLimitExceededError), + ({"maximum_raw_bytes": 2 * 1024 * 1024}, [b"x" * (1024 * 1024 + 1)], ArtifactLimitExceededError), + ({}, [bytearray(b"abc")], ArtifactInputMismatchError), +]) +async def test_discard_replay_enforces_raw_ingress_contract(updates, payload, error): + from app.modules.artifacts.intake.streaming import hash_submission_replay + + async def chunks(): + for chunk in payload: + yield chunk + + limits = dict(maximum_raw_bytes=100, declared_raw_bytes=None, + idle_timeout_seconds=1, deadline_at=datetime.now(UTC) + timedelta(seconds=2)) + with pytest.raises(error): + await hash_submission_replay(chunks(), **(limits | updates)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("total_deadline", [False, True]) +async def test_discard_replay_deadlines_drain_pending_body_read(total_deadline): + from app.modules.artifacts.intake.streaming import hash_submission_replay + + stopped = asyncio.Event() + + async def chunks(): + try: + await asyncio.Event().wait() + yield b"never" + finally: + stopped.set() + + with pytest.raises(ArtifactStoreUnavailableError): + await hash_submission_replay( + chunks(), maximum_raw_bytes=100, declared_raw_bytes=None, + idle_timeout_seconds=10 if total_deadline else 0.01, + deadline_at=datetime.now(UTC) + timedelta(seconds=0.02 if total_deadline else 10), + ) + assert stopped.is_set() + + +@pytest.mark.asyncio +async def test_discard_replay_cancellation_drains_read_and_remains_cancellation(): + from app.modules.artifacts.intake.streaming import hash_submission_replay + + started, stopped = asyncio.Event(), asyncio.Event() + + async def chunks(): + try: + started.set() + await asyncio.Event().wait() + yield b"never" + finally: + stopped.set() + + task = asyncio.create_task(hash_submission_replay( + chunks(), maximum_raw_bytes=100, declared_raw_bytes=None, + idle_timeout_seconds=10, deadline_at=datetime.now(UTC) + timedelta(seconds=10), + )) + await asyncio.wait_for(started.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert stopped.is_set() diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 6655fc45a..4c89ed0a3 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -67,6 +67,7 @@ async def reserve(intake, session, *, key=None, declared_raw_bytes=None, with_up lease_seconds=60, upload_seconds=300): now = datetime.now(UTC) row = await repository(session).reserve( + operation_id=new_record_id(), metadata=SubmissionIntakeMetadata(task_id=intake.task, assignment_id=intake.assignment), actor_id=intake.actor.actor_profile_id, identity_link_id=intake.actor.identity_link_id, idempotency_key=key or new_record_id(), maximum_raw_bytes=1024, diff --git a/backend/tests/authorization/setup_finalization/test_catalogue.py b/backend/tests/authorization/setup_finalization/test_catalogue.py index 5c8bc4cbc..2e8c0b752 100644 --- a/backend/tests/authorization/setup_finalization/test_catalogue.py +++ b/backend/tests/authorization/setup_finalization/test_catalogue.py @@ -51,6 +51,7 @@ ActionId.ACTOR_PROJECT_LIST, ActionId.ACTOR_ASSIGNMENT_LIST, ActionId.ACTOR_SUBMISSION_LIST, ActionId.ACTOR_WORK_SUMMARY_READ, ActionId.TASK_SUBMISSION_BUNDLE_PREPARATION_LIST, ActionId.TASK_SUBMISSION_BUNDLE_PREPARATION_READ, + ActionId.TASK_SUBMISSION_OPERATION_READ, ActionId.PROJECT_GUIDE_LIST, ActionId.PROJECT_GUIDE_READ, ActionId.PROJECT_GUIDE_ACTIVATION_READINESS_READ, ActionId.PROJECT_GUIDE_DOCUMENT_READ, ActionId.PROJECT_SUBMISSION_LIST, ActionId.PROJECT_ASSIGNMENT_LIST, ActionId.PROJECT_SUMMARY_READ, @@ -151,6 +152,7 @@ ActionId.ARTIFACT_AUDIT_READ, ActionId.OPERATIONS_ARTIFACT_STORAGE_ADMISSION_READ, ActionId.SUBMISSION_CREATE, + ActionId.SUBMISSION_INTAKE_RESERVE, ActionId.TASK_CLAIM, ActionId.TASK_WORK_CONTEXT_READ, ActionId.PROJECT_TASK_WORK_CONTEXT_READ, diff --git a/backend/tests/authorization/task_authority/test_intake_authority.py b/backend/tests/authorization/task_authority/test_intake_authority.py index 31f8005b6..fa8a1999f 100644 --- a/backend/tests/authorization/task_authority/test_intake_authority.py +++ b/backend/tests/authorization/task_authority/test_intake_authority.py @@ -1,5 +1,5 @@ """Real AUTH prepared/read evidence for intake operations, not ART T1 admission.""" -from dataclasses import replace +from dataclasses import fields, replace import pytest from sqlalchemy import select, text @@ -7,7 +7,7 @@ from app.core.identifiers import new_record_id from app.db import session as db_session from app.modules.authorization.api.submission_intake import ( - IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, + IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts, ) from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization from app.modules.tasks.models import AuditEvent @@ -103,7 +103,7 @@ async def test_intake_reserve_and_read_require_exact_current_submitter(admin_acc ctx = await context(admin_access) facts = reservation(ctx, project) read = IntakeOperationReadFacts(facts.operation_id, project, facts.task_id, ctx.actor_profile_id) - for method, value in (("prepare", facts), ("authorize_read", read)): + for method, value in (("preflight", preflight_facts(facts)), ("prepare", facts), ("authorize_read", read)): async with db_session.get_session_factory()() as session: authority = SubmissionIntakeAuthorization(session, ctx) try: @@ -168,3 +168,31 @@ async def test_intake_revoked_current_link_cannot_reserve_or_read(intake_authori await getattr(authority, method)(*args) finally: authority.close() + + +def preflight_facts(facts): + return IntakeReservationPreflightFacts(**{ + field.name: getattr(facts, field.name) for field in fields(IntakeReservationPreflightFacts) + }) + + +async def test_intake_preflight_has_no_allow_or_consumable_handle(intake_authority): + _, project, _, ctx = intake_authority + facts = reservation(ctx, project) + selectors = preflight_facts(facts) + async with db_session.get_session_factory()() as session: + authority = SubmissionIntakeAuthorization(session, ctx) + try: + async with session.begin(): + await authority.lock_actor(ctx.actor_profile_id, ctx.identity_link_id) + assert await authority.preflight(selectors) is None + assert not list(await session.scalars(select(AuditEvent).where( + AuditEvent.request_id == str(ctx.request_id)))) + with pytest.raises(IntakeAuthorityDenied): + await authority.prepare(selectors) + # Only complete locked-context facts may produce reservation authority. + decision = await authority.consume(await authority.prepare(facts), facts) + row = await session.get(AuditEvent, str(decision)) + assert row.after_facts["allowed"] is True + finally: + authority.close() diff --git a/backend/tests/authorization/task_authority/test_prepared.py b/backend/tests/authorization/task_authority/test_prepared.py index efaa3cd32..79e5aae06 100644 --- a/backend/tests/authorization/task_authority/test_prepared.py +++ b/backend/tests/authorization/task_authority/test_prepared.py @@ -401,7 +401,8 @@ async def test_intake_prepared_binding_rejects_cross_operation_and_wrong_resourc @pytest.mark.parametrize("identity", list(ServiceIdentity)) -async def test_fixed_services_cannot_reserve_submission_intake(identity): +@pytest.mark.parametrize("phase", ["preflight", "prepare"]) +async def test_fixed_services_cannot_reserve_submission_intake(identity, phase): from app.core.identifiers import new_record_id from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied, IntakeReservationAuthorityFacts from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization @@ -417,12 +418,56 @@ async def test_fixed_services_cannot_reserve_submission_intake(identity): facts = IntakeReservationAuthorityFacts(new_record_id(), uuid4(), uuid4(), uuid4(), context.actor_profile_id, context.identity_link_id, uuid4(), "sha256:" + "a" * 64, "sha256:" + "b" * 64, "in_progress") + if phase == "preflight": + from dataclasses import fields + from app.modules.authorization.api.submission_intake import IntakeReservationPreflightFacts + facts = IntakeReservationPreflightFacts(**{ + field.name: getattr(facts, field.name) for field in fields(IntakeReservationPreflightFacts) + }) try: with pytest.raises(IntakeAuthorityDenied) as caught: - await authority.prepare(facts) + await getattr(authority, phase)(facts) assert isinstance(caught.value.__cause__, AuthorizationDenied) assert caught.value.__cause__.decision.denial_code.value == "permission_not_granted" assert len(evidence.events) == 1 and evidence.events[0].resource_id == str(facts.operation_id) assert evidence.events[0].after_facts["allowed"] is False finally: authority.close() + + +@pytest.mark.parametrize("mutation", [None, "project", "task", "key", "extra", "full"]) +async def test_intake_preflight_selectors_cannot_issue_prepared_handle(mutation): + from app.core.identifiers import new_record_id + from app.modules.authorization.domain.submission_intake import IntakeReservationPreflightResourceContext + _, _, prepared, task, evidence = setup() + resource = IntakeReservationPreflightResourceContext( + resource_id=new_record_id(), scope_project_id=task.scope_project_id, + task_id=new_record_id(), assignment_id=new_record_id(), actor_profile_id=task.actor_profile_id, + identity_link_id=task.identity_link_id, idempotency_key=new_record_id(), + metadata_sha256="sha256:" + "a" * 64, + ) + request = resource.model_dump(mode="json") + if mutation == "project": + request["scope_project_id"] = str(new_record_id()) + elif mutation == "task": + request["task_id"] = str(new_record_id()) + elif mutation == "key": + request["idempotency_key"] = str(new_record_id()) + elif mutation == "extra": + request["unexpected"] = True + elif mutation == "full": + request.update(resource_type="submission_intake_reservation", task_status="in_progress", + locked_context_sha256="sha256:" + "b" * 64) + value = PreparedAuthorizationInput(idempotency_key=resource.idempotency_key, request_value=request) + scope = PreparedAuthorityScope(kind=PreparedAuthorityScopeKind.PROJECT, project_id=resource.scope_project_id) + try: + if mutation is None: + assert await prepared.preflight(ActionId.SUBMISSION_INTAKE_RESERVE, value, scope, resource) is None + with pytest.raises(PreparedAuthorizationHandleInvalid): + await prepared.prepare(ActionId.SUBMISSION_INTAKE_RESERVE, value, scope) + else: + with pytest.raises(PreparedAuthorizationHandleInvalid): + await prepared.preflight(ActionId.SUBMISSION_INTAKE_RESERVE, value, scope, resource) + assert evidence.events == [] + finally: + prepared.close() diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index dfafc1d7d..f353af671 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2768,7 +2768,9 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ "backend/app/modules/artifacts/intake/streaming.py", "backend/app/modules/authorization/api/submission_intake.py", "backend/app/modules/authorization/domain/submission_intake.py", + "backend/app/modules/authorization/prepared_preflight.py", "backend/app/modules/authorization/submission_intake.py", + "backend/app/modules/artifacts/intake/foreground_admission.py", "backend/app/modules/artifacts/intake/foreground_lease.py", "backend/app/modules/artifacts/intake/foreground_upload.py", "backend/app/adapters/artifacts/local_submission_source.py", diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 836f3023e..da76e2051 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -317,8 +317,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 271, - "6e35cc7ad001abe952f6ffbc8b7dad3ed0db6636e113e6c7fa347bddc768da88", + 272, + "47631a336f437eb3d3ddffe79a0a9f5f6ea8b1d02a418965ddb75dd4aa842844", ), "project": ( 255, From 3e9157ce26077083c74f071a4af77c4cb1f54d18 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 08:55:16 +0100 Subject: [PATCH 031/513] Enforce ingress deadlines and repair migration contract checks --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 33 +++++++++++++ backend/alembic/env.py | 3 +- .../artifacts/intake/foreground_admission.py | 7 +++ .../app/modules/artifacts/intake/streaming.py | 28 +++++++++-- .../test_submission_intake_contracts.py | 46 +++++++++++++++++++ backend/tests/test_alembic.py | 1 + .../contracts/authorization_context_get.json | 6 ++- 7 files changed, 118 insertions(+), 6 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6bc3af754..ef62f357e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -590,3 +590,36 @@ original failure even after another operation claims the same task. Integrated accepted replay, revision journey, public framing/runtime readiness, and the full T1–T5 public drill remain later required evidence; these tests do not prove the public submission cutover. + +Frozen candidate `dfdcfa181` subsequently passed all 15 admission cases against +that exact commit in 173.76s, with isolated cleanup confirmed. Documentation +review passed its scoped claims. Architecture/security and QA independently +found a concrete deadline escape: a non-yielding async body reader can return +bytes or EOF after an `asyncio.timeout` deadline without running the cancellation +callback. The shared upload reader and final provider-part response had the same +boundary risk. Repair checks elapsed idle time after each read, including EOF, +and absolute time before/after read boundaries and before upload completion; +cooperative timeout cancellation remains. Nine new regressions all fail against +the frozen pre-fix implementation in memory; all 105 intake contract tests pass +with the repair. No test skips or deadline relaxation were introduced. + +Remaining hosted failures were traced to concrete current-consumer omissions: +Alembic's supported-head constant still named 0069 after installing 0070, the +independent linear-graph assertion omitted 0069, and the MCP authorization-context +snapshot lacked the two new ActionId values. Repair scope includes Alembic env +and its existing graph/resume tests, plus that exact generated MCP snapshot and +its canonical digest. It preserves the allowed historical revisions and refusal +of unknown revisions, and changes no MCP tool or product route. Targeted repeated +upgrade/downgrade/historical-resume checks and real OpenAPI comparison must pass +before the next review candidate is frozen. + +The selected MCP contract checks now pass all 144 tests against actual backend +OpenAPI (58.94s). The snapshot delta is exactly the two intake action values, +canonical digest and capture source revision; no tool behavior changed. The +migration repair run remains separate from this contract evidence. + +The full backend Ruff check passed. The existing app docstring check initially +fell just below its unchanged threshold after the new admission class; documenting +its constructor, transaction ownership, reservation validation and authorized-read +contracts restores the check (80.1%). This is documentation of the actual owner +boundaries, with no behavior or threshold change. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 9a9519d84..4704c3574 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0069_submission_intake_custody" +_CURRENT_HEAD_REVISION = "0070_submission_intake_authority" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -123,6 +123,7 @@ def do_run_migrations(connection: Connection) -> None: ("0066_guide_check_specification",), ("0067_canonical_json_restore_path",), ("0068_issuer_profile_email",), + ("0069_submission_intake_custody",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py index 6a9466d5e..3a03e341d 100644 --- a/backend/app/modules/artifacts/intake/foreground_admission.py +++ b/backend/app/modules/artifacts/intake/foreground_admission.py @@ -64,6 +64,7 @@ class _ExistingKey(RuntimeError): class ForegroundIntakeAdmission: + """Reserve one authorized foreground owner or resolve its immutable retry key.""" def __init__( self, sessions: async_sessionmaker[AsyncSession], *, tasks: Callable[[AsyncSession], IntakeTaskCustodyPort], @@ -73,6 +74,7 @@ def __init__( namespace: ArtifactStorageNamespaceSpec, capacity_limits: SubmissionSourceCapacityLimits, maximum_raw_bytes: int, upload_duration: timedelta, lease_duration: timedelta, ) -> None: + """Bind explicit limits and transaction-local owner ports without provider I/O.""" if (type(maximum_raw_bytes) is not int or not 1 <= maximum_raw_bytes <= MAXIMUM_SUBMISSION_ZIP_BYTES or not isinstance(upload_duration, timedelta) or not isinstance(lease_duration, timedelta) or not timedelta(0) < lease_duration <= upload_duration): @@ -85,6 +87,7 @@ def __init__( @asynccontextmanager async def _root(self): + """Own commit/cleanup and restage only this request's canonical AUTH denial.""" session = self._sessions() authority = self._authorization(session) try: @@ -109,6 +112,7 @@ async def admit( self, metadata: SubmissionIntakeMetadata, *, actor_id: UUID, identity_link_id: UUID, idempotency_key: UUID, declared_raw_bytes: int | None, ) -> IntakeReservationOwner | IntakeReplay: + """Return upload ownership only after commit, otherwise resolve current read authority.""" metadata = SubmissionIntakeMetadata.model_validate(metadata) if declared_raw_bytes is not None and ( type(declared_raw_bytes) is not int or not 1 <= declared_raw_bytes <= self._maximum @@ -125,6 +129,7 @@ async def admit( return await self._read(metadata, actor_id, idempotency_key) async def _reserve(self, metadata, actor_id, identity_link_id, key, declared): + """Serialize TASK then actor/grant before committing pointer, charge and allow.""" async with self._root() as (session, authority): tasks = self._tasks(session) repository = SubmissionIntakeRepository(session, tasks) @@ -157,6 +162,7 @@ async def _reserve(self, metadata, actor_id, identity_link_id, key, declared): return owner async def _validate_context(self, session, metadata, actor_id): + """Require canonical lineage, selected phases and the exact qualified namespace.""" task = await self._contexts(session).lock_submission_context(TaskSubmissionContextRequest( metadata.task_id, metadata.assignment_id, actor_id, metadata.predecessor_submission_id, )) @@ -181,6 +187,7 @@ async def _validate_context(self, session, metadata, actor_id): raise IntakeCustodyConflict("intake_source_provider_unqualified") async def _read(self, metadata, actor_id, key, *, expected_operation_id=None): + """Authorize the stored operation before comparing metadata or returning its state.""" async with self._root() as (session, authority): repository = SubmissionIntakeRepository(session, self._tasks(session)) found = await repository.find_actor_key(actor_id, key) diff --git a/backend/app/modules/artifacts/intake/streaming.py b/backend/app/modules/artifacts/intake/streaming.py index 27b80d39f..72bc220e9 100644 --- a/backend/app/modules/artifacts/intake/streaming.py +++ b/backend/app/modules/artifacts/intake/streaming.py @@ -45,16 +45,32 @@ def identity(self) -> RawSubmissionIdentity: return RawSubmissionIdentity("sha256:" + self.digest.hexdigest(), self.count) +def _require_deadline(deadline_at: datetime) -> None: + if datetime.now(UTC) >= deadline_at: + raise TimeoutError("submission total deadline expired") + + async def _bounded_chunks( chunks: AsyncIterator[bytes], receipt: _IngressReceipt, *, maximum_raw_bytes: int, - declared_raw_bytes: int | None, idle_timeout_seconds: float, + declared_raw_bytes: int | None, idle_timeout_seconds: float, deadline_at: datetime, ) -> AsyncIterator[bytes]: """The same framing, size and EOF rules govern upload and discard replay.""" + loop = asyncio.get_running_loop() while True: + _require_deadline(deadline_at) + started = loop.time() + ended = False try: async with asyncio.timeout(idle_timeout_seconds): chunk = await anext(chunks) except StopAsyncIteration: + ended = True + # A buffered or blocking iterator may never yield control to the timeout + # callback. Check elapsed time even when the read reports EOF. + if loop.time() - started >= idle_timeout_seconds: + raise TimeoutError("submission ingress idle deadline expired") + _require_deadline(deadline_at) + if ended: break if type(chunk) is not bytes: raise ArtifactInputMismatchError("submission ingress returned invalid bytes") @@ -91,8 +107,10 @@ async def hash_submission_replay( try: async with asyncio.timeout(remaining): async for _chunk in _bounded_chunks(chunks, receipt, maximum_raw_bytes=maximum_raw_bytes, - declared_raw_bytes=declared_raw_bytes, idle_timeout_seconds=idle_timeout_seconds): + declared_raw_bytes=declared_raw_bytes, idle_timeout_seconds=idle_timeout_seconds, + deadline_at=deadline_at): pass + _require_deadline(deadline_at) except TimeoutError: raise ArtifactStoreUnavailableError("submission replay deadline expired") from None return receipt.identity() @@ -131,21 +149,25 @@ async def _receive_parts( pending = bytearray() parts = [] async for chunk in _bounded_chunks(chunks, receipt, maximum_raw_bytes=intent.maximum_raw_bytes, - declared_raw_bytes=intent.declared_raw_bytes, idle_timeout_seconds=intent.idle_timeout_seconds): + declared_raw_bytes=intent.declared_raw_bytes, idle_timeout_seconds=intent.idle_timeout_seconds, + deadline_at=intent.upload_deadline_at): view = memoryview(chunk) while view: amount = min(intent.part_bytes - len(pending), len(view)) pending.extend(view[:amount]) view = view[amount:] if len(pending) == intent.part_bytes: + _require_deadline(intent.upload_deadline_at) parts.append(await store.upload_source_part( upload, len(parts) + 1, bytes(pending), operation_evidence=evidence, )) pending.clear() if pending: + _require_deadline(intent.upload_deadline_at) parts.append(await store.upload_source_part( upload, len(parts) + 1, bytes(pending), operation_evidence=evidence, )) + _require_deadline(intent.upload_deadline_at) return SubmissionSourceCompletion( upload=upload, parts=tuple(parts), raw_sha256=receipt.identity().raw_sha256, raw_byte_count=receipt.count, ) diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py index dee7f8c25..f7196abd0 100644 --- a/backend/tests/artifacts/test_submission_intake_contracts.py +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -479,3 +479,49 @@ async def chunks(): with pytest.raises(asyncio.CancelledError): await task assert stopped.is_set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("path", ["replay", "upload"]) +@pytest.mark.parametrize("deadline", ["idle", "total"]) +@pytest.mark.parametrize("stall_at_eof", [False, True]) +async def test_non_yielding_ingress_cannot_escape_deadline(path, deadline, stall_at_eof): + import time + from app.modules.artifacts.intake.streaming import hash_submission_replay + + async def chunks(): + if not stall_at_eof: + time.sleep(0.05) + yield b"abc" + if stall_at_eof: + time.sleep(0.05) + + idle = 0.01 if deadline == "idle" else 10 + expires = datetime.now(UTC) + timedelta(seconds=0.01 if deadline == "total" else 10) + with pytest.raises(ArtifactStoreUnavailableError): + if path == "replay": + await hash_submission_replay(chunks(), maximum_raw_bytes=100, declared_raw_bytes=None, + idle_timeout_seconds=idle, deadline_at=expires) + else: + # This small body must not reach a provider when its reader expires. + await receive_submission_source(object(), upload_value( + idle_timeout_seconds=idle, upload_deadline_at=expires, + ), chunks()) + + +@pytest.mark.asyncio +async def test_non_yielding_final_part_cannot_return_completion_after_deadline(): + import time + + class BufferedStore: + async def upload_source_part(self, upload, number, data, **kwargs): + time.sleep(0.05) + return SubmissionSourcePart(number=number, byte_count=len(data), provider_etag="late") + + async def chunks(): + yield b"abc" + + with pytest.raises(ArtifactStoreUnavailableError): + await receive_submission_source(BufferedStore(), upload_value( + upload_deadline_at=datetime.now(UTC) + timedelta(seconds=0.01), + ), chunks()) diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 018439567..3edc8c2ae 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -388,6 +388,7 @@ def test_v01_graph_has_one_root_and_head() -> None: assert [revision.revision for revision in revisions] == [ HEAD_REVISION, + "0069_submission_intake_custody", "0068_issuer_profile_email", "0067_canonical_json_restore_path", "0066_guide_check_specification", diff --git a/mcp_server/contracts/authorization_context_get.json b/mcp_server/contracts/authorization_context_get.json index c7c481c55..9576b0916 100644 --- a/mcp_server/contracts/authorization_context_get.json +++ b/mcp_server/contracts/authorization_context_get.json @@ -1,10 +1,12 @@ { - "canonical_sha256": "c430757c46cc05fa4af20ac600b875f7bfad7cb8c4461bf505ab3807d51f0102", + "canonical_sha256": "9e60e21c075c212a67255a1bef3bbff256541e40d773e087b3a3bbfdcc6eda1c", "components": { "schemas": { "ActionId": { "description": "Closed action identifiers reserved by approved owner chunks.", "enum": [ + "submission.intake.reserve", + "task.submission_operation.read", "task.submission.list", "submission.read", "submission.checker_run.list", @@ -581,7 +583,7 @@ "schema_version": 1, "source": { "action_id": "actor.authorization_context.read", - "backend_git_sha": "8b068f2b788f159b1085d47f162c39ce3323d5b6", + "backend_git_sha": "dfdcfa181089790fec43ece3dd04e8e0056f82bb", "method": "GET", "openapi_version": "3.1.0", "path": "/api/v1/actors/me/authorization-context" From 0051687fcf7e4e310b12c7a18a9738a53f3d8c41 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 08:58:10 +0100 Subject: [PATCH 032/513] Clarify T1 proof gates and assert expired ingress cannot write --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 17 +++++++++++++++-- .../test_submission_intake_contracts.py | 6 +++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index ef62f357e..4b733cf1d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -610,8 +610,9 @@ snapshot lacked the two new ActionId values. Repair scope includes Alembic env and its existing graph/resume tests, plus that exact generated MCP snapshot and its canonical digest. It preserves the allowed historical revisions and refusal of unknown revisions, and changes no MCP tool or product route. Targeted repeated -upgrade/downgrade/historical-resume checks and real OpenAPI comparison must pass -before the next review candidate is frozen. +upgrade/downgrade/historical-resume checks and real OpenAPI comparison gate +publication/readiness. Source may be frozen for conditional review while a long +integration run finishes; a live run is not passing evidence. The selected MCP contract checks now pass all 144 tests against actual backend OpenAPI (58.94s). The snapshot delta is exactly the two intake action values, @@ -623,3 +624,15 @@ fell just below its unchanged threshold after the new admission class; documenti its constructor, transaction ownership, reservation validation and authorized-read contracts restores the check (80.1%). This is documentation of the actual owner boundaries, with no behavior or threshold change. + + +The historical migration repair run completed: 35 passed, 33 deselected in +1524.15s; migration head 0070 and database/role cleanup were confirmed. The +receipt records HEAD `dfdcfa181` because it ran the repair worktree before freeze; +architecture/security inspected the narrow code delta on clean `3e9157ce` and +ran the exact-head migration graph check. Its independent total/idle deadline +probes now reject the formerly accepted late reads. Documentation review found +and corrected the earlier freeze/publication sequencing sentence. Upload deadline +regressions now use an explicit forbidden-write assertion instead of relying on +a missing provider method; replay and late-part regressions retain their direct +late-success assertions. No full public API or T1–T5 readiness is inferred. diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py index f7196abd0..8511d4be5 100644 --- a/backend/tests/artifacts/test_submission_intake_contracts.py +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -489,6 +489,10 @@ async def test_non_yielding_ingress_cannot_escape_deadline(path, deadline, stall import time from app.modules.artifacts.intake.streaming import hash_submission_replay + class NoWrites: + async def upload_source_part(self, *args, **kwargs): + pytest.fail("expired ingress reader reached provider storage") + async def chunks(): if not stall_at_eof: time.sleep(0.05) @@ -504,7 +508,7 @@ async def chunks(): idle_timeout_seconds=idle, deadline_at=expires) else: # This small body must not reach a provider when its reader expires. - await receive_submission_source(object(), upload_value( + await receive_submission_source(NoWrites(), upload_value( idle_timeout_seconds=idle, upload_deadline_at=expires, ), chunks()) From 9ba6b888b797542e7b38d5487a61f79a853c3c4f Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 09:11:18 +0100 Subject: [PATCH 033/513] Trace one-session PRE owners and runtime isolation requirements --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 4b733cf1d..e5b2e062e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -636,3 +636,62 @@ and corrected the earlier freeze/publication sequencing sentence. Upload deadlin regressions now use an explicit forbidden-write assertion instead of relying on a missing provider method; replay and late-part regressions retain their direct late-success assertions. No full public API or T1–T5 readiness is inferred. + +## One-session PRE: owner trace and implementation boundary + +Inspection at `0051687fc` confirms that the existing submission PRE cannot be +used unchanged after source sealing. `submission_materialization.py` consumes +an API-prepared archive and exports the trusted guest's verified tree; +`SelectedPreSubmitProcessor.process` then starts a separate execution for each +locked PRE entry. The trusted worker requires `export` before `default`, and +selected-PRE reservation requires a semantic manifest and default-input digest +before runtime invocation. These are the precise call paths to replace for the +single-source execution, rather than wrap as an ostensibly single call. + +The next implementation boundary must cover source-bound CHECKERS custody, +ART's exact-generation read authorization, the typed `execute_pre` invocation, +guest inspection/default/project composition and validation of combined evidence. +It must not stop at a type-only adapter with the two-guest implementation behind +it. Core requests carry locked facts and the sealed source without an extracted +manifest; runtime derives the manifest and nested project request, and CHECKERS +independently reconstructs that request from locked facts and observed manifest. +Expiring delivery authority stays separate from the immutable request digest. + +Reuse the existing canonical archive inspector, semantic-manifest construction, +four default checks, registered external request/result validation, foreground +lease and runtime guardian/capacity ownership. Retain shared POST consumers while +replacing submission PRE callers. An unsafe archive may complete defaults with +no manifest or project run; raw source mismatch is an infrastructure failure. +Neither project output nor matching echoed digests establish platform evidence. + +Runtime feasibility is a specific design dependency: `Machine::prepare` boots +one cache image and injects the static guest bootstrap before the image command. +The existing trusted defaults require Python and Workstream code from the pinned +intake image; project images need not contain either. The existing image-archive +validator verifies layer identities and bounds but does not materialize a second +root filesystem. Therefore neither a second mounted image nor a safe layer +extractor may be assumed to exist. Architecture/security review must resolve +independent trusted-platform provisioning inside that one guest before runtime +implementation. Loading trusted Python from the project image is forbidden. + +Allowed impact cone for the resulting L0 plan: CHECKERS selected-PRE public +contracts/coordination and validation; ART source grants and submission +materialization; typed execution interface and concrete adapter; checker service, +static guest, trusted intake worker and image-cache provisioning; necessary +custody migration, explicit ownership/lane registrations and focused tests; +affected operational documentation. No acceptance/finalization shortcut, +second PRE guest, host verified-tree export, project network/model/trial +privileges, retained-data deletion, provider qualification claim or deployment +default is authorized by this boundary. T4 and public cutover remain subsequent +integration work in the same PR. + +Required proof includes one invocation and one guest on pass; no project launch +on default rejection; hostile project output, filesystem/process/control-channel +access and resource exhaustion; substituted source/image/fence/derived request; +unchanged canonical default/manifest semantics; cancellation and uncertain create +with retained cleanup/capacity obligations; and a managed-style adapter fixture +without host paths. Native guest isolation needs actual qualified runtime proof, +not just collection of its fixtures. This checkout currently has neither a Smol +executable on PATH nor `/dev/kvm`; portable proof can proceed, but cannot establish +native runtime qualification. Human review focuses on platform-code provenance, +the supervisor/project boundary and durable evidence binding before T4. From 64c90158107f3da124cfc5cd7129d41d3f7c5847 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 09:14:28 +0100 Subject: [PATCH 034/513] Specify trusted platform bundle provisioning for one-session PRE --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e5b2e062e..17325db28 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -695,3 +695,49 @@ not just collection of its fixtures. This checkout currently has neither a Smol executable on PATH nor `/dev/kvm`; portable proof can proceed, but cannot establish native runtime qualification. Human review focuses on platform-code provenance, the supervisor/project boundary and durable evidence binding before T4. + +### Trusted platform provisioning and guest ingestion plan + +The architecture review selected project-image boot with an independently pinned +trusted Python root as the smaller viable change. Provision the root offline, +before runtime admission, using the already approved intake image graph. The +provisioning Docker daemon is trusted build infrastructure, never a PRE runtime +or a source of submission bytes. Validate the local Docker-save graph through +the existing cache provisioner, require the exact config image ID already loaded +in the daemon, and verify its platform and rootfs diff IDs. Create an isolated +container with pulling disabled; never start it or invoke its entrypoint. Export +its root filesystem through bounded storage, then remove only that invocation's +container. Docker's documented create/export operations support this without +executing the image. Reject image-declared volumes for this trusted profile. + +Produce a closed, length-framed root bundle rather than asking the guest to +interpret OCI layers or arbitrary tar extensions. Normalize a bounded export +into directories, regular files and symlinks; resolve hard links to regular file +content without host extraction. Reject duplicate paths, traversal, special +files, link-parent ancestry, invalid link targets and excessive bytes/entries. +Directories precede files; symlinks are installed last. File permissions are +read-only, preserving only executable intent; set-ID bits, ownership, devices, +xattrs and host identities confer no authority. A canonical descriptor binds +the bundle digest/count, platform manifest, config, default behavior and bounds. +Outputs are exclusive, sealed and fsynced; failure removes only owned partial +files. No implicit image pull, image registration or policy change occurs. + +The static guest verifies the complete bundle before writing into its fresh +private root, then validates the closed framing and bounds during staging. It +must never follow a link while writing. Absolute symlink targets are meaningful +only inside the eventual chroot, never during host/guest unpack. The trusted +worker uses that root's interpreter/libraries and a separate protected workspace; +project execution remains disabled until the combined-purpose supervisor exists. +The bundle is a necessary executable dependency for that supervisor, not proof +that the one-session PRE path is complete. + +Allowed first implementation files: the existing cache provisioner and a cohesive +trusted-root provisioning module, its existing test family, guest bundle reader +and focused tests, exact test registration if needed, this record and runtime +documentation. Risk L0; architecture/security plan and implementation review, +QA/test-delta review and affected documentation review. Prove source-image +substitution refusal, no-start/no-pull behavior, bounded export and cleanup, +hardlink/symlink/path attacks, truncation/digest/bounds refusal and a valid Python +root round trip. Native mount/chroot isolation remains a subsequent guest +integration gate. No backend public cutover, second PRE guest, deployment default +or provider qualification is included in this provisioning step. From f6755d33ec1b70b92d346dee422bd07dec5141c0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 09:16:03 +0100 Subject: [PATCH 035/513] Bind trusted root export and account guest staging custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 17325db28..c961ded6e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -707,7 +707,13 @@ the existing cache provisioner, require the exact config image ID already loaded in the daemon, and verify its platform and rootfs diff IDs. Create an isolated container with pulling disabled; never start it or invoke its entrypoint. Export its root filesystem through bounded storage, then remove only that invocation's -container. Docker's documented create/export operations support this without +container. Before export, inspect the returned container ID and require its exact +image ID and never-started created state. Use that ID for cleanup; uncertain +creation retains a unique invocation label/name for discovery and exact-owner +cleanup. Reuse the existing bounded subprocess runner with a binary stdout sink, +preserving aggregate output/time limits and process-group termination rather +than exporting to an unbounded Docker output path. +Docker's documented create/export operations support this without executing the image. Reject image-declared volumes for this trusted profile. Produce a closed, length-framed root bundle rather than asking the guest to @@ -722,8 +728,12 @@ the bundle digest/count, platform manifest, config, default behavior and bounds. Outputs are exclusive, sealed and fsynced; failure removes only owned partial files. No implicit image pull, image registration or policy change occurs. -The static guest verifies the complete bundle before writing into its fresh -private root, then validates the closed framing and bounds during staging. It +The static guest receives the bundle into a private bounded guest spool and +verifies its complete digest/count before writing into its fresh private root, +then validates the closed framing and bounds during staging. Charge both the +bundle spool and expanded root against guest disk capacity and clean both on +cancellation or failure. Recheck the consumed digest while staging so a changed +spool cannot authorize execution. It must never follow a link while writing. Absolute symlink targets are meaningful only inside the eventual chroot, never during host/guest unpack. The trusted worker uses that root's interpreter/libraries and a separate protected workspace; From 0bdd8607745d3b1c87447011e06b1e03a09dfdd6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 09:29:54 +0100 Subject: [PATCH 036/513] Provision and verify trusted PRE runtime bundles without image execution --- .ci/behavior-ownership/partition.v1.json | 6 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 25 + backend/scripts/behavior_ownership.py | 1 + backend/scripts/checker_image_process.py | 6 +- backend/scripts/checker_trusted_root.py | 282 +++++++++ backend/tests/test_checker_image.py | 22 + backend/tests/test_checker_smol_cache.py | 196 ++++++- external_checkers/README.md | 35 ++ .../workstream-checker-guest/src/lib.rs | 1 + .../src/trusted_root.rs | 540 ++++++++++++++++++ 10 files changed, 1110 insertions(+), 4 deletions(-) create mode 100644 backend/scripts/checker_trusted_root.py create mode 100644 external_checkers/workstream-checker-guest/src/trusted_root.rs diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 62e181b90..88a963af1 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -2556,6 +2556,10 @@ "group": "artifacts", "target": "backend/scripts/checker_smol_cache.py" }, + { + "group": "artifacts", + "target": "backend/scripts/checker_trusted_root.py" + }, { "group": "shared", "target": "backend/scripts/coverage_policy.py" @@ -2653,7 +2657,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "3f4b580a947ef98164cf6df277feee494299cbc506dd9f4d02f2b2e41f436598", + "authority_digest": "5093f0ae793900f5aacc8dc30f7b7711e405fa8b36c6b8eba758ddecc8b7f147", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c961ded6e..fb52683b4 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -751,3 +751,28 @@ hardlink/symlink/path attacks, truncation/digest/bounds refusal and a valid Pyth root round trip. Native mount/chroot isolation remains a subsequent guest integration gate. No backend public cutover, second PRE guest, deployment default or provider qualification is included in this provisioning step. + +The provisioning implementation now reuses the existing verified image graph +and bounded subprocess runner. `checker_trusted_root.py` exports only the +inspected never-started container, resolves uncertain create acknowledgement by +unique label/name and rechecks ownership before removal. It writes a sealed +`WSROOT1` bundle and separate descriptor; completed verified cache files may +remain after bundle failure. Parsing and hardlink expansion have explicit byte, +entry and deadline checks. No host extraction or image execution occurs. + +The guest `trusted_root` library verifies the bounded spool, enforces exact +platform/config/default identities, rejects invalid path ancestry and record +ordering, installs links last, and hashes consumed bytes again before returning. +It creates only a fresh root and removes partial staging on cancellation or +failure. Its caller must own a protected parent, charge spool plus expanded root, +and mount the result read-only. The combined PRE supervisor is not wired yet. + +Initial focused checks passed 75 Python tests and 170 ownership tests, plus nine +guest-library tests including source mutation after first verification. The real +pinned intake image built locally. Its first export hit the subprocess helper's +unrelated default 120-second timeout despite an explicit 600-second provisioning +budget; owned-container cleanup succeeded. Export now uses the remaining +aggregate deadline. Real-image export/staging and final verification remain +publication gates. A newer local Clippy reports existing workspace warnings; +the required runtime gate uses CI's pinned Rust 1.84.0 and unchanged test command. +No native Smol qualification follows from portable guest-library execution. diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 655cd3392..d22cf1d31 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -107,6 +107,7 @@ "backend/scripts/checker_image_process.py", "backend/scripts/checker_image_manifest.py", "backend/scripts/checker_smol_cache.py", + "backend/scripts/checker_trusted_root.py", "backend/scripts/checker_image_samples.py", }) AWS_ARTIFACT_ACTIVATION_TARGETS = frozenset({ diff --git a/backend/scripts/checker_image_process.py b/backend/scripts/checker_image_process.py index 91cd776ea..8cc01238d 100644 --- a/backend/scripts/checker_image_process.py +++ b/backend/scripts/checker_image_process.py @@ -38,6 +38,7 @@ def run( data: bytes = b"", env: dict[str, str] | None = None, budget: ExecutionBudget | None = None, + stdout_sink=None, ) -> bytes: """Drain both pipes within one byte/time budget and kill owned processes on failure.""" deadline = ( @@ -80,7 +81,10 @@ def run( if consumed > limit: raise ImageError(f"{step}: output limit exceeded") if key.data: - output.extend(chunk) + if stdout_sink is None: + output.extend(chunk) + elif stdout_sink.write(chunk) != len(chunk): + raise ImageError(f"{step}: incomplete output write") code = process.wait(timeout=max(0.001, deadline - time.monotonic())) if code: raise ImageError(f"{step}: command exited {code}") diff --git a/backend/scripts/checker_trusted_root.py b/backend/scripts/checker_trusted_root.py new file mode 100644 index 000000000..b9e71e3b2 --- /dev/null +++ b/backend/scripts/checker_trusted_root.py @@ -0,0 +1,282 @@ +"""Provision the trusted PRE interpreter from a verified image, without running it. + +Docker is trusted offline build infrastructure. The produced bundle is not a +qualification receipt and is never accepted without its independently pinned +identity. No submitted archive or project image enters this command. +""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import re +import secrets +import struct +import tarfile +import tempfile +import time + +from scripts import checker_smol_cache as cache +from scripts.checker_image_process import ExecutionBudget, ImageError, run + +MAGIC = b"WSROOT1\n" +MAX_HEADER = 16384 + + +def _path(value: str) -> str: + if (not value or len(value.encode()) > 4096 or value.startswith("/") + or "\\" in value or "\0" in value + or any(part in {"", ".", ".."} for part in value.split("/"))): + raise ImageError("trusted root path invalid") + return value + + +def _frame(output, value): + raw = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() + if len(raw) > MAX_HEADER: + raise ImageError("trusted root header exceeds limit") + output.write(struct.pack(">I", len(raw))) + output.write(raw) + + +def _available(deadline): + if deadline is not None and time.monotonic() >= deadline: + raise ImageError("trusted root provisioning deadline exceeded") + + +def _members(archive, maximum_entries, maximum_bytes, deadline): + members, total = {}, 0 + for index, item in enumerate(archive): + _available(deadline) + if index >= maximum_entries: + raise ImageError("trusted root entry limit exceeded") + name = item.name.removesuffix("/") if item.isdir() else item.name + if name in {"", "."} and item.isdir(): + continue + _path(name) + if name in members or not (item.isdir() or item.isfile() or item.issym() or item.islnk()): + raise ImageError("trusted root entry invalid") + if item.size < 0 or (not item.isfile() and item.size): + raise ImageError("trusted root entry size invalid") + if item.issym() and (not item.linkname or "\0" in item.linkname + or "\\" in item.linkname or len(item.linkname.encode()) > 4096): + raise ImageError("trusted root link invalid") + total += item.size + if total > maximum_bytes: + raise ImageError("trusted root expanded byte limit exceeded") + members[name] = item + directories = set() + for name in members: + parts = name.split("/") + for end in range(1, len(parts)): + parent = "/".join(parts[:end]) + if parent in members and not members[parent].isdir(): + raise ImageError("trusted root has a nondirectory ancestor") + directories.add(parent) + directories.update(name for name, item in members.items() if item.isdir()) + if len(directories | members.keys()) > maximum_entries: + raise ImageError("trusted root implicit directory limit exceeded") + return members, directories + + +def _regular(name, members): + visited = set() + while True: + if name in visited or name not in members: + raise ImageError("trusted root hardlink invalid") + visited.add(name) + item = members[name] + if item.isfile(): + return item + if not item.islnk(): + raise ImageError("trusted root hardlink target is not regular") + name = _path(item.linkname) + + +def pack_root(source, output, *, identity, maximum_entries, maximum_bytes, deadline=None): + """Normalize a bounded Docker export; never extract paths onto the host.""" + if maximum_entries <= 0 or maximum_bytes <= 0: + raise ImageError("trusted root bounds must be positive") + output.write(MAGIC) + _frame(output, {"kind": "identity", **identity}) + with tarfile.open(fileobj=source, mode="r:") as archive: + members, directories = _members(archive, maximum_entries, maximum_bytes, deadline) + for name in sorted(directories, key=lambda value: (value.count("/"), value)): + _available(deadline) + _frame(output, {"kind": "directory", "path": name}) + total, entries = 0, len(directories) + for name, item in sorted(members.items()): + _available(deadline) + if not (item.isfile() or item.islnk()): + continue + regular = _regular(name, members) + total += regular.size + entries += 1 + if total > maximum_bytes: + raise ImageError("trusted root hardlink expansion exceeds limit") + _frame(output, {"kind": "file", "path": name, "byte_count": regular.size, + "executable": bool(regular.mode & 0o111)}) + with archive.extractfile(regular) as content: + remaining = regular.size + while remaining: + _available(deadline) + data = content.read(min(65536, remaining)) + if not data: + raise ImageError("trusted root file truncated") + output.write(data) + remaining -= len(data) + for name, item in sorted(members.items()): + _available(deadline) + if item.issym(): + entries += 1 + _frame(output, {"kind": "symlink", "path": name, "target": item.linkname}) + _frame(output, {"kind": "end"}) + _available(deadline) + return {"expanded_bytes": total, "entries": entries} + + +def _inspect(docker, kind, selector, budget): + raw = run([docker, kind, "inspect", selector], step="inspect trusted root custody", budget=budget) + body = cache._json(raw) + if type(body) is not list or len(body) != 1 or type(body[0]) is not dict: + raise ImageError("trusted root inspection invalid") + return body[0] + + +def _container_matches(value, config_id, token): + return (value.get("Image") == config_id + and value.get("Config", {}).get("Labels", {}).get("workstream.root-provision") == token + and value.get("State", {}).get("Status") == "created" + and value.get("State", {}).get("Running") is False) + + +def export_root(docker, config_id, config, sink, *, maximum_bytes, deadline): + """Export a never-started exact image and clean only the invocation's container.""" + budget = ExecutionBudget(deadline, maximum_bytes + 1024 * 1024) + image = _inspect(docker, "image", config_id, budget) + if (image.get("Id") != config_id or image.get("Os") != "linux" + or image.get("Architecture") != "amd64" + or image.get("RootFS", {}).get("Layers") != config["rootfs"]["diff_ids"] + or image.get("Config", {}).get("Volumes") or config.get("config", {}).get("Volumes")): + raise ImageError("trusted root image differs") + token = secrets.token_hex(16) + name = "workstream-root-" + token + container_id = None + try: + raw = run([docker, "create", "--pull=never", "--network=none", "--name", name, + "--label", "workstream.root-provision=" + token, config_id], + step="create trusted root export", budget=budget) + container_id = raw.decode("ascii").strip() + if re.fullmatch(r"[0-9a-f]{64}", container_id) is None: + raise ImageError("trusted root container id invalid") + value = _inspect(docker, "container", container_id, budget) + if not _container_matches(value, config_id, token): + raise ImageError("trusted root container differs") + run([docker, "export", container_id], step="export trusted root", budget=budget, + timeout=max(0.001, deadline - time.monotonic()), + limit=maximum_bytes, stdout_sink=sink) + finally: + # A fresh cleanup budget is independent of an exhausted export budget. + cleanup = ExecutionBudget(time.monotonic() + 30, 1024 * 1024) + if container_id is None or re.fullmatch(r"[0-9a-f]{64}", container_id) is None: + matches = run([docker, "ps", "-aq", "--no-trunc", "--filter", "name=^/" + name + "$", + "--filter", "label=workstream.root-provision=" + token], + step="discover trusted root export", budget=cleanup).decode().split() + if len(matches) > 1: + raise ImageError("trusted root cleanup discovery ambiguous") + container_id = matches[0] if matches else None + if container_id is not None: + value = _inspect(docker, "container", container_id, cleanup) + if not _container_matches(value, config_id, token): + raise ImageError("trusted root cleanup ownership unconfirmed") + run([docker, "rm", container_id], step="remove trusted root export", budget=cleanup) + + +def provision_root(archive: Path, repository: str, manifest_digest: str, *, + archive_output: Path, config_output: Path, bundle_output: Path, + descriptor_output: Path, docker: str, default_behavior_sha256: str, + maximum_export_bytes: int, maximum_root_bytes: int, + maximum_entries: int, timeout_seconds: float): + """Bind an exclusive sealed runtime bundle to the already verified image graph.""" + if (any(type(value) is not int or value <= 0 for value in + (maximum_export_bytes, maximum_root_bytes, maximum_entries)) + or not 0 < timeout_seconds <= 7200 + or cache.DIGEST.fullmatch(default_behavior_sha256) is None): + raise ImageError("trusted root provisioning limits invalid") + paths = [p.parent.resolve(strict=True) / p.name for p in + (archive_output, config_output, bundle_output, descriptor_output)] + if len(set(paths)) != 4 or archive.resolve(strict=True) in paths: + raise ImageError("trusted root outputs must be distinct") + deadline = time.monotonic() + timeout_seconds + receipt = cache.provision(archive, repository, manifest_digest, + archive_output=archive_output, config_output=config_output) + raw_config = config_output.read_bytes() + if "sha256:" + hashlib.sha256(raw_config).hexdigest() != receipt["config_image_id"]: + raise ImageError("trusted root config changed") + config = cache._json(raw_config) + identity = {"platform_manifest_digest": manifest_digest, + "config_image_id": receipt["config_image_id"], + "default_behavior_sha256": default_behavior_sha256} + created = [] + try: + with tempfile.TemporaryFile() as exported: + export_root(docker, receipt["config_image_id"], config, exported, + maximum_bytes=maximum_export_bytes, deadline=deadline) + exported.seek(0) + with cache._output_files(paths[2:], created) as (bundle, descriptor): + facts = pack_root(exported, bundle, identity=identity, + maximum_entries=maximum_entries, maximum_bytes=maximum_root_bytes, + deadline=deadline) + bundle.flush() + size = bundle.tell() + bundle.seek(0) + result = {"schema_version": "workstream.trusted_root.v1", **identity, **facts, + "bundle_sha256": cache.digest(bundle), "bundle_byte_count": size} + _available(deadline) + descriptor.write(json.dumps(result, sort_keys=True, separators=(",", ":")).encode()) + for output in (bundle, descriptor): + output.flush() + os.fchmod(output.fileno(), 0o400) + os.fsync(output.fileno()) + for path, device, inode in created: + info = path.lstat() + if (info.st_dev, info.st_ino) != (device, inode): + raise ImageError("trusted root publication changed") + for parent in {path.parent for path in paths[2:]}: + fd = os.open(parent, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + try: + os.fsync(fd) + finally: + os.close(fd) + return result + except BaseException: + for path, device, inode in reversed(created): + try: + info = path.lstat() + if (info.st_dev, info.st_ino) == (device, inode): + path.unlink() + except FileNotFoundError: + pass + raise + + +def main(): + """Require explicit approved identities, output paths and provisioning bounds.""" + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + for option in ("archive", "archive-output", "config-output", "bundle-output", "descriptor-output"): + parser.add_argument("--" + option, type=Path, required=True) + for option in ("repository", "manifest", "docker", "default-behavior-sha256"): + parser.add_argument("--" + option, required=True) + for option in ("maximum-export-bytes", "maximum-root-bytes", "maximum-entries"): + parser.add_argument("--" + option, type=int, required=True) + parser.add_argument("--timeout-seconds", type=float, required=True) + args = vars(parser.parse_args()) + args["manifest_digest"] = args.pop("manifest") + print(json.dumps(provision_root(**args), sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/backend/tests/test_checker_image.py b/backend/tests/test_checker_image.py index 48ef553d9..c2c56e34e 100644 --- a/backend/tests/test_checker_image.py +++ b/backend/tests/test_checker_image.py @@ -494,3 +494,25 @@ def test_build_and_samples_do_not_inherit_docker_proxy_configuration(monkeypatch assert argv[argv.index("--config") + 1] == str(config) assert marker not in str(options["env"]) assert "DOCKER_CONFIG" not in options["env"] + + +def test_binary_sink_streams_output_and_still_charges_stderr(): + """Root exports use bounded storage without accumulating their bytes in RAM.""" + import io + + sink = io.BytesIO() + command = [sys.executable, "-c", "import os; os.write(1,b'root'); os.write(2,b'noise')"] + assert run(command, step="export", stdout_sink=sink, limit=9) == b"" + assert sink.getvalue() == b"root" + with pytest.raises(ImageError, match="output limit"): + run(command, step="export", stdout_sink=io.BytesIO(), limit=8) + + +def test_binary_sink_short_write_refuses_success(): + """A failed sink cannot publish a seemingly complete root export.""" + class ShortSink: + def write(self, data): + return len(data) - 1 + + with pytest.raises(ImageError, match="incomplete output"): + run([sys.executable, "-c", "print('root')"], step="export", stdout_sink=ShortSink()) diff --git a/backend/tests/test_checker_smol_cache.py b/backend/tests/test_checker_smol_cache.py index 3fc5d3ca5..a36ea092b 100644 --- a/backend/tests/test_checker_smol_cache.py +++ b/backend/tests/test_checker_smol_cache.py @@ -16,7 +16,7 @@ def sha(raw): return "sha256:" + hashlib.sha256(raw).hexdigest() -def bundle(root, *, compressed=False, defect=None): +def bundle(root, *, compressed=False, defect=None, volumes=True): layer_output = io.BytesIO() with tarfile.open(fileobj=layer_output, mode="w", format=tarfile.USTAR_FORMAT) as output: info = tarfile.TarInfo("usr/bin/checker") @@ -28,7 +28,7 @@ def bundle(root, *, compressed=False, defect=None): "digest": sha(blob), "size": len(blob)} config = json.dumps({"os": "linux", "architecture": "amd64", "rootfs": {"type": "layers", "diff_ids": [sha(layer)]}, - "config": {"Entrypoint": ["/checker"], "Volumes": {"/busybox": {}}}}).encode() + "config": {"Entrypoint": ["/checker"], "Volumes": {"/busybox": {}} if volumes else {}}}).encode() manifest = {"schemaVersion": 2, "mediaType": "application/vnd.oci.image.manifest.v1+json", "config": {"digest": sha(config), "size": len(config), "mediaType": "application/vnd.oci.image.config.v1+json"}, @@ -269,3 +269,195 @@ def test_cli_requires_a_distinct_archive_output(tmp_path, monkeypatch, capsys): assert error.value.code == 2 assert "--archive-output" in capsys.readouterr().err assert not (tmp_path / "config.json").exists() + + +def root_export(entries): + """A flattened image export, independent of contributor ZIP handling.""" + output = io.BytesIO() + with tarfile.open(fileobj=output, mode="w") as archive: + for name, kind, content in entries: + item = tarfile.TarInfo(name) + item.type = kind + if kind == tarfile.REGTYPE: + item.size = len(content) + item.mode = 0o4755 + archive.addfile(item, io.BytesIO(content)) + else: + if kind in {tarfile.SYMTYPE, tarfile.LNKTYPE}: + item.linkname = content + archive.addfile(item) + output.seek(0) + return output + + +def test_trusted_root_bundle_normalizes_links_and_keeps_bytes(): + """Flattened hardlinks retain content; symlinks follow all file records.""" + import struct + from scripts.checker_trusted_root import MAGIC, pack_root + + source = root_export([ + ("usr/bin/python", tarfile.REGTYPE, b"trusted interpreter"), + ("usr/bin/python3", tarfile.LNKTYPE, "usr/bin/python"), + ("bin", tarfile.SYMTYPE, "usr/bin"), + ]) + output = io.BytesIO() + facts = pack_root(source, output, identity={"test": "identity"}, + maximum_entries=10, maximum_bytes=100) + output.seek(0) + assert output.read(len(MAGIC)) == MAGIC + records, files = [], {} + while raw := output.read(4): + value = json.loads(output.read(struct.unpack(">I", raw)[0])) + records.append(value) + if value["kind"] == "file": + files[value["path"]] = output.read(value["byte_count"]) + assert files == {"usr/bin/python": b"trusted interpreter", "usr/bin/python3": b"trusted interpreter"} + assert [item["kind"] for item in records] == ["identity", "directory", "directory", "file", "file", "symlink", "end"] + assert all(set(item) == {"kind", "path", "byte_count", "executable"} + for item in records if item["kind"] == "file") + assert facts == {"expanded_bytes": 38, "entries": 5} + + +@pytest.mark.parametrize("entries", [ + [("../escape", tarfile.REGTYPE, b"x")], + [("/escape", tarfile.REGTYPE, b"x")], + [("x", tarfile.REGTYPE, b"x"), ("x", tarfile.REGTYPE, b"y")], + [("a", tarfile.SYMTYPE, "/outside"), ("a/b", tarfile.REGTYPE, b"x")], + [("a", tarfile.LNKTYPE, "b"), ("b", tarfile.LNKTYPE, "a")], + [("a", tarfile.SYMTYPE, "b"), ("b", tarfile.LNKTYPE, "a")], + [("device", tarfile.CHRTYPE, "")], +]) +def test_trusted_root_refuses_paths_special_files_and_link_ancestry(entries): + from scripts.checker_trusted_root import pack_root + + with pytest.raises(ImageError): + pack_root(root_export(entries), io.BytesIO(), identity={}, maximum_entries=20, maximum_bytes=100) + + +def test_trusted_root_charges_hardlink_expansion_and_implicit_directories(): + from scripts.checker_trusted_root import pack_root + + source = [("a/b/c", tarfile.REGTYPE, b"12345"), ("copy", tarfile.LNKTYPE, "a/b/c")] + with pytest.raises(ImageError, match="hardlink expansion"): + pack_root(root_export(source), io.BytesIO(), identity={}, maximum_entries=10, maximum_bytes=9) + with pytest.raises(ImageError, match="implicit directory"): + pack_root(root_export(source), io.BytesIO(), identity={}, maximum_entries=3, maximum_bytes=20) + + +@pytest.mark.parametrize("defect", [None, "image", "container", "started", "export"]) +def test_root_export_requires_exact_never_started_container_and_cleans_owned_id(monkeypatch, defect): + import time + from scripts import checker_trusted_root as root + + config_id, container_id = "sha256:" + "1" * 64, "2" * 64 + config = {"rootfs": {"diff_ids": ["sha256:" + "3" * 64]}} + calls, state = [], {} + + def command(argv, **kwargs): + calls.append(argv) + if argv[1:3] == ["image", "inspect"]: + return json.dumps([{"Id": "other" if defect == "image" else config_id, + "Os": "linux", "Architecture": "amd64", + "RootFS": {"Layers": config["rootfs"]["diff_ids"]}, "Config": {}}]).encode() + if argv[1] == "create": + assert "--pull=never" in argv and argv[-1] == config_id + state["token"] = argv[argv.index("--label") + 1].split("=", 1)[1] + return container_id.encode() + if argv[1:3] == ["container", "inspect"]: + return json.dumps([{"Image": "other" if defect == "container" else config_id, + "Config": {"Labels": {"workstream.root-provision": state["token"]}}, + "State": {"Status": "running" if defect == "started" else "created", "Running": defect == "started"}}]).encode() + if argv[1] == "export": + if defect == "export": + raise ImageError("export failed") + kwargs["stdout_sink"].write(b"root bytes") + elif argv[1] == "rm": + assert argv == ["docker", "rm", container_id] + else: + pytest.fail(f"unexpected Docker command {argv}") + return b"" + + monkeypatch.setattr(root, "run", command) + output = io.BytesIO() + if defect: + with pytest.raises(ImageError): + root.export_root("docker", config_id, config, output, maximum_bytes=1000, deadline=time.monotonic() + 10) + else: + root.export_root("docker", config_id, config, output, maximum_bytes=1000, deadline=time.monotonic() + 10) + assert output.getvalue() == b"root bytes" + assert not any("start" in item or "pull" in item for item in calls) + assert any(item[1] == "rm" for item in calls) == (defect in {None, "export"}) + assert any(item[1] == "export" for item in calls) == (defect in {None, "export"}) + + +@pytest.mark.parametrize("failure", [False, True]) +def test_trusted_root_publication_binds_verified_graph_and_removes_partial_bundle(tmp_path, monkeypatch, failure): + from scripts import checker_trusted_root as root + + archive, manifest, config_id = bundle(tmp_path, volumes=False) + def export(docker, selected_id, config, sink, **kwargs): + assert selected_id == config_id + assert config["rootfs"]["diff_ids"] + sink.write(root_export([("python", tarfile.REGTYPE, b"trusted")]).read()) + monkeypatch.setattr(root, "export_root", export) + kwargs = dict(archive_output=tmp_path / "cache.tar", config_output=tmp_path / "config.json", + bundle_output=tmp_path / "root.bundle", descriptor_output=tmp_path / "root.json", + docker="docker", default_behavior_sha256=sha(b"behavior"), + maximum_export_bytes=100000, maximum_root_bytes=1 if failure else 100, + maximum_entries=10, timeout_seconds=5) + if failure: + with pytest.raises(ImageError, match="expanded byte limit"): + root.provision_root(archive, "trusted/intake", manifest, **kwargs) + assert not kwargs["bundle_output"].exists() + assert not kwargs["descriptor_output"].exists() + else: + receipt = root.provision_root(archive, "trusted/intake", manifest, **kwargs) + assert receipt["config_image_id"] == config_id + assert receipt["platform_manifest_digest"] == manifest + assert receipt["bundle_sha256"] == sha(kwargs["bundle_output"].read_bytes()) + assert receipt["bundle_byte_count"] == kwargs["bundle_output"].stat().st_size + assert json.loads(kwargs["descriptor_output"].read_bytes()) == receipt + assert kwargs["bundle_output"].stat().st_mode & 0o777 == 0o400 + + +def test_uncertain_root_container_creation_discovers_exact_owned_id_for_cleanup(monkeypatch): + import time + from scripts import checker_trusted_root as root + + image_id, container_id = sha(b"image"), "a" * 64 + diff_ids = [sha(b"layer")] + state, calls = {}, [] + def command(argv, **kwargs): + calls.append(argv) + if argv[1:3] == ["image", "inspect"]: + return json.dumps([{"Id": image_id, "Os": "linux", "Architecture": "amd64", + "RootFS": {"Layers": diff_ids}, "Config": {}}]).encode() + if argv[1] == "create": + state["token"] = argv[argv.index("--label") + 1].split("=", 1)[1] + state["name"] = argv[argv.index("--name") + 1] + raise ImageError("create acknowledgement lost") + if argv[1] == "ps": + assert "name=^/" + state["name"] + "$" in argv + assert "label=workstream.root-provision=" + state["token"] in argv + return container_id.encode() + if argv[1:3] == ["container", "inspect"]: + assert argv[-1] == container_id + return json.dumps([{"Image": image_id, "State": {"Status": "created", "Running": False}, + "Config": {"Labels": {"workstream.root-provision": state["token"]}}}]).encode() + assert argv == ["docker", "rm", container_id] + return b"" + monkeypatch.setattr(root, "run", command) + with pytest.raises(ImageError, match="acknowledgement lost"): + root.export_root("docker", image_id, {"rootfs": {"diff_ids": diff_ids}}, io.BytesIO(), + maximum_bytes=100, deadline=time.monotonic() + 10) + assert calls[-1] == ["docker", "rm", container_id] + assert not any(item[1] == "export" for item in calls) + + +def test_root_pack_cannot_publish_after_deadline(): + import time + from scripts.checker_trusted_root import pack_root + + with pytest.raises(ImageError, match="deadline"): + pack_root(root_export([("python", tarfile.REGTYPE, b"trusted")]), io.BytesIO(), + identity={}, maximum_entries=10, maximum_bytes=100, deadline=time.monotonic() - 1) diff --git a/external_checkers/README.md b/external_checkers/README.md index a867ee5a8..1e05f33ed 100644 --- a/external_checkers/README.md +++ b/external_checkers/README.md @@ -458,3 +458,38 @@ This matrix proves the adapter/ART boundary. The separate connects the same node to API uploads and durable workers, including the public Operator retry and both governed policy branches. Its recorded Flow/inference fixtures do not certify production identity, live models or hosted deployment. + +### Trusted root provisioning for single-session PRE development + +`backend/scripts/checker_trusted_root.py` provisions a separate pinned Python +root for the single-session PRE supervisor under development. This command and +the guest bundle reader do not yet replace the current submission PRE flow or +establish native runtime qualification. + +The command first verifies the approved local image graph with the existing Smol +cache provisioner. A trusted offline Docker daemon must already contain that +exact config image ID. It checks the platform and ordered layer identities, +creates a container with pulling disabled, verifies its exact image and created +state, exports without starting it, and removes the owned container. Images with +volumes are refused. The daemon is build infrastructure; it is not used for PRE +execution, and no submission bytes enter this provisioning path. + +Run the module from `backend/` with `--archive`, `--repository`, `--manifest`, +`--archive-output` and `--config-output` as for the cache command. Also supply +new `--bundle-output` and `--descriptor-output` paths, `--docker`, +`--default-behavior-sha256`, `--maximum-export-bytes`, `--maximum-root-bytes`, +`--maximum-entries`, and `--timeout-seconds`. All bounds and identities are +explicit; the command does not choose deployment values. Keep the emitted +bundle and descriptor operator-controlled and pin their identities independently +before use. Completed cache files may remain if later bundle provisioning fails; +a partial bundle/descriptor never establishes readiness. + +The `WSROOT1` format carries bounded closed JSON records and inline regular-file +bytes. Hard links become independently charged file content; symlinks are +installed last. No image paths are extracted on the host. The guest library +verifies the entire bounded spool and descriptor, stages into a fresh private +root, and rechecks consumed bytes before returning. The caller must provide a +protected parent, aggregate deadline/cancellation checks, and capacity for both +the spool and expanded root, then mount the root read-only before executing a +trusted child. Combined supervisor wiring and native isolation proof remain +required; this library alone does not authorize project execution. diff --git a/external_checkers/workstream-checker-guest/src/lib.rs b/external_checkers/workstream-checker-guest/src/lib.rs index bc9e7f632..48aec1bfa 100644 --- a/external_checkers/workstream-checker-guest/src/lib.rs +++ b/external_checkers/workstream-checker-guest/src/lib.rs @@ -2,6 +2,7 @@ use serde::{Deserialize, Serialize}; pub mod confinement; +pub mod trusted_root; pub const MAX_JOB_BYTES: usize = 4 * 1024 * 1024; pub const CAPACITY_EXIT_CODE: i32 = 201; diff --git a/external_checkers/workstream-checker-guest/src/trusted_root.rs b/external_checkers/workstream-checker-guest/src/trusted_root.rs new file mode 100644 index 000000000..7d6d4b5a2 --- /dev/null +++ b/external_checkers/workstream-checker-guest/src/trusted_root.rs @@ -0,0 +1,540 @@ +//! Independently pinned platform-root staging. This does not execute a workload. +//! The caller owns a private bounded spool and charges spool plus expanded root. +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +use std::path::Path; + +const MAGIC: &[u8] = b"WSROOT1\n"; +const MAX_HEADER: usize = 16384; +type Result = std::result::Result>; + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RootDescriptor { + pub schema_version: String, + pub platform_manifest_digest: String, + pub config_image_id: String, + pub default_behavior_sha256: String, + pub expanded_bytes: u64, + pub entries: u64, + pub bundle_sha256: String, + pub bundle_byte_count: u64, +} + +pub struct RootLimits { + pub maximum_bundle_bytes: u64, + pub maximum_root_bytes: u64, + pub maximum_entries: u64, +} + +#[derive(Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +enum Record { + Identity { + platform_manifest_digest: String, + config_image_id: String, + default_behavior_sha256: String, + }, + Directory { + path: String, + }, + File { + path: String, + byte_count: u64, + executable: bool, + }, + Symlink { + path: String, + target: String, + }, + End, +} + +fn digest_valid(value: &str) -> bool { + value.len() == 71 + && value.starts_with("sha256:") + && value[7..] + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +fn path_valid(value: &str) -> bool { + !value.is_empty() + && value.len() <= 4096 + && !value.contains(['\\', '\0']) + && value + .split('/') + .all(|part| !part.is_empty() && part != "." && part != "..") +} + +struct Hashed<'a> { + file: &'a mut File, + digest: Sha256, + count: u64, + maximum: u64, +} +impl Read for Hashed<'_> { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + let size = self.file.read(bytes)?; + self.count = self + .count + .checked_add(size as u64) + .ok_or_else(|| io::Error::other("root bundle count overflow"))?; + if self.count > self.maximum { + return Err(io::Error::other("root bundle exceeds pinned count")); + } + self.digest.update(&bytes[..size]); + Ok(size) + } +} + +fn frame(reader: &mut impl Read) -> Result { + let mut prefix = [0; 4]; + reader.read_exact(&mut prefix)?; + let size = u32::from_be_bytes(prefix) as usize; + if size == 0 || size > MAX_HEADER { + return Err("root frame exceeds limit".into()); + } + let mut body = vec![0; size]; + reader.read_exact(&mut body)?; + Ok(serde_json::from_slice(&body)?) +} + +fn check_digest(reader: Hashed<'_>, expected: &RootDescriptor) -> Result<()> { + if reader.count != expected.bundle_byte_count + || format!("sha256:{:x}", reader.digest.finalize()) != expected.bundle_sha256 + { + return Err("root bundle identity differs".into()); + } + Ok(()) +} + +/// Verify the pinned spool, then stage only into an exclusively created root. +/// `check` must enforce the invocation's aggregate deadline/cancellation fence. +/// The caller must isolate the parent from all concurrent untrusted writers. +pub fn stage_root( + source: &mut File, + target: &Path, + expected: &RootDescriptor, + limits: &RootLimits, + check: impl Fn() -> Result<()>, +) -> Result<()> { + if expected.schema_version != "workstream.trusted_root.v1" + || ![ + &expected.platform_manifest_digest, + &expected.config_image_id, + &expected.default_behavior_sha256, + &expected.bundle_sha256, + ] + .into_iter() + .all(|value| digest_valid(value)) + || expected.bundle_byte_count == 0 + || expected.entries == 0 + || expected.bundle_byte_count > limits.maximum_bundle_bytes + || expected.expanded_bytes > limits.maximum_root_bytes + || expected.entries > limits.maximum_entries + { + return Err("root descriptor invalid".into()); + } + source.seek(SeekFrom::Start(0))?; + let mut reader = Hashed { + file: source, + digest: Sha256::new(), + count: 0, + maximum: expected.bundle_byte_count, + }; + let mut chunk = [0; 65536]; + loop { + check()?; + if reader.read(&mut chunk)? == 0 { + break; + } + } + check_digest(reader, expected)?; + check()?; + source.seek(SeekFrom::Start(0))?; + fs::create_dir(target)?; + fs::set_permissions(target, fs::Permissions::from_mode(0o700))?; + let result = unpack(source, target, expected, &check); + if result.is_err() { + fs::remove_dir_all(target)?; + } + result +} + +fn unpack( + source: &mut File, + target: &Path, + expected: &RootDescriptor, + check: &impl Fn() -> Result<()>, +) -> Result<()> { + let mut reader = Hashed { + file: source, + digest: Sha256::new(), + count: 0, + maximum: expected.bundle_byte_count, + }; + let mut magic = [0; 8]; + reader.read_exact(&mut magic)?; + if magic != MAGIC { + return Err("root magic invalid".into()); + } + match frame(&mut reader)? { + Record::Identity { + platform_manifest_digest, + config_image_id, + default_behavior_sha256, + } if platform_manifest_digest == expected.platform_manifest_digest + && config_image_id == expected.config_image_id + && default_behavior_sha256 == expected.default_behavior_sha256 => {} + _ => return Err("root platform identity differs".into()), + } + let (mut paths, mut directories) = (HashSet::new(), HashSet::new()); + let (mut bytes, mut phase) = (0_u64, 0); + loop { + check()?; + let record = frame(&mut reader)?; + let (name, next_phase) = match &record { + Record::Directory { path } => (path, 0), + Record::File { path, .. } => (path, 1), + Record::Symlink { path, .. } => (path, 2), + Record::End => break, + _ => return Err("unexpected root identity".into()), + }; + if !path_valid(name) + || next_phase < phase + || !paths.insert(name.clone()) + || paths.len() as u64 > expected.entries + { + return Err("root path or sequence invalid".into()); + } + phase = next_phase; + if let Some((parent, _)) = name.rsplit_once('/') { + if !directories.contains(parent) { + return Err("root parent is not a directory".into()); + } + } + let path = target.join(name); + match record { + Record::Directory { path: name } => { + fs::create_dir(&path)?; + fs::set_permissions(&path, fs::Permissions::from_mode(0o700))?; + directories.insert(name); + } + Record::File { + byte_count, + executable, + .. + } => { + bytes = bytes.checked_add(byte_count).ok_or("root size overflow")?; + if bytes > expected.expanded_bytes { + return Err("root expansion exceeds limit".into()); + } + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(&path)?; + let mut remaining = byte_count; + let mut chunk = [0; 65536]; + while remaining > 0 { + check()?; + let length = remaining.min(chunk.len() as u64) as usize; + reader.read_exact(&mut chunk[..length])?; + file.write_all(&chunk[..length])?; + remaining -= length as u64; + } + file.set_permissions(fs::Permissions::from_mode(if executable { + 0o555 + } else { + 0o444 + }))?; + } + Record::Symlink { target: link, .. } => { + if link.is_empty() || link.len() > 4096 || link.contains(['\\', '\0']) { + return Err("root symlink invalid".into()); + } + std::os::unix::fs::symlink(link, path)?; + } + _ => unreachable!(), + } + } + if bytes != expected.expanded_bytes || paths.len() as u64 != expected.entries { + return Err("root observed bounds differ".into()); + } + if reader.read(&mut [0])? != 0 { + return Err("root trailing bytes".into()); + } + check_digest(reader, expected)?; + check()?; + // The caller still mounts this root read-only before any child runs. + for directory in directories { + fs::set_permissions(target.join(directory), fs::Permissions::from_mode(0o555))?; + } + fs::set_permissions(target, fs::Permissions::from_mode(0o555))?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + use std::cell::Cell; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(0); + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "workstream-root-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Fixture { + fn drop(&mut self) { + fn writable(path: &Path) { + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + for entry in fs::read_dir(path).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_dir() { + writable(&entry.path()); + } + } + } + writable(&self.0); + fs::remove_dir_all(&self.0).unwrap(); + } + } + fn sha(bytes: &[u8]) -> String { + format!("sha256:{:x}", Sha256::digest(bytes)) + } + fn frame_bytes(bytes: &mut Vec, value: Value) { + let body = serde_json::to_vec(&value).unwrap(); + bytes.extend_from_slice(&(body.len() as u32).to_be_bytes()); + bytes.extend(body); + } + fn bundle(records: Vec<(Value, &[u8])>) -> (Vec, RootDescriptor) { + let mut bytes = MAGIC.to_vec(); + frame_bytes( + &mut bytes, + json!({"kind":"identity", "platform_manifest_digest":sha(b"platform"), + "config_image_id":sha(b"config"), "default_behavior_sha256":sha(b"behavior")}), + ); + let mut expanded = 0; + let count = records.len() as u64; + for (value, data) in records { + frame_bytes(&mut bytes, value); + bytes.extend_from_slice(data); + expanded += data.len() as u64; + } + frame_bytes(&mut bytes, json!({"kind":"end"})); + let descriptor = RootDescriptor { + schema_version: "workstream.trusted_root.v1".into(), + platform_manifest_digest: sha(b"platform"), + config_image_id: sha(b"config"), + default_behavior_sha256: sha(b"behavior"), + expanded_bytes: expanded, + entries: count, + bundle_sha256: sha(&bytes), + bundle_byte_count: bytes.len() as u64, + }; + (bytes, descriptor) + } + fn limits() -> RootLimits { + RootLimits { + maximum_bundle_bytes: 10000, + maximum_root_bytes: 1000, + maximum_entries: 20, + } + } + fn valid() -> (Vec, RootDescriptor) { + bundle(vec![ + (json!({"kind":"directory", "path":"usr"}), b""), + ( + json!({"kind":"file", "path":"usr/python", "byte_count":4, "executable":true}), + b"code", + ), + ( + json!({"kind":"symlink", "path":"python", "target":"/usr/python"}), + b"", + ), + ]) + } + fn source(fixture: &Fixture, bytes: &[u8]) -> File { + let path = fixture.0.join("bundle"); + fs::write(&path, bytes).unwrap(); + File::open(path).unwrap() + } + #[test] + fn stages_exact_files_and_links_without_following_absolute_targets() { + let fixture = Fixture::new(); + let (bytes, descriptor) = valid(); + let root = fixture.0.join("root"); + stage_root( + &mut source(&fixture, &bytes), + &root, + &descriptor, + &limits(), + || Ok(()), + ) + .unwrap(); + assert_eq!(fs::read(root.join("usr/python")).unwrap(), b"code"); + assert_eq!( + fs::read_link(root.join("python")).unwrap(), + Path::new("/usr/python") + ); + assert_eq!( + fs::metadata(root.join("usr/python")) + .unwrap() + .permissions() + .mode() + & 0o7777, + 0o555 + ); + } + #[test] + fn rejects_digest_truncation_identity_bounds_and_trailing_content() { + for defect in 0..6 { + let fixture = Fixture::new(); + let (mut bytes, mut descriptor) = valid(); + match defect { + 0 => descriptor.bundle_sha256 = sha(b"other"), + 1 => { + bytes.pop(); + } + 2 => descriptor.config_image_id = sha(b"other config"), + 3 => descriptor.expanded_bytes = 3, + 4 => descriptor.entries = 2, + 5 => { + bytes.push(0); + descriptor.bundle_byte_count = bytes.len() as u64; + descriptor.bundle_sha256 = sha(&bytes); + } + _ => unreachable!(), + } + let root = fixture.0.join("root"); + assert!( + stage_root( + &mut source(&fixture, &bytes), + &root, + &descriptor, + &limits(), + || Ok(()) + ) + .is_err(), + "defect {defect}" + ); + assert!(!root.exists()); + } + } + #[test] + fn rejects_paths_duplicates_link_parent_and_unknown_fields() { + for records in [ + vec![( + json!({"kind":"directory", "path":"../outside"}), + b"".as_slice(), + )], + vec![( + json!({"kind":"directory", "path":"/outside"}), + b"".as_slice(), + )], + vec![ + (json!({"kind":"directory", "path":"a"}), b"".as_slice()), + (json!({"kind":"directory", "path":"a"}), b"".as_slice()), + ], + vec![ + ( + json!({"kind":"symlink", "path":"a", "target":"/outside"}), + b"".as_slice(), + ), + ( + json!({"kind":"file", "path":"a/code", "byte_count":0, "executable":false}), + b"".as_slice(), + ), + ], + vec![( + json!({"kind":"directory", "path":"a", "uid":0}), + b"".as_slice(), + )], + ] { + let fixture = Fixture::new(); + let (bytes, descriptor) = bundle(records); + let root = fixture.0.join("root"); + assert!(stage_root( + &mut source(&fixture, &bytes), + &root, + &descriptor, + &limits(), + || Ok(()) + ) + .is_err()); + assert!(!root.exists()); + } + } + #[test] + fn changed_spool_after_first_hash_cannot_publish_root() { + let fixture = Fixture::new(); + let (bytes, descriptor) = valid(); + let root = fixture.0.join("root"); + let calls = Cell::new(0); + let mut file = source(&fixture, &bytes); + assert!(stage_root(&mut file, &root, &descriptor, &limits(), || { + calls.set(calls.get() + 1); + if calls.get() == 3 { + let mut changed = bytes.clone(); + let offset = changed.windows(4).position(|part| part == b"code").unwrap(); + changed[offset..offset + 4].copy_from_slice(b"evil"); + fs::write(fixture.0.join("bundle"), changed)?; + } + Ok(()) + }) + .is_err()); + assert!(calls.get() >= 3); + assert!(!root.exists()); + } + #[test] + fn cancellation_removes_partial_root_and_existing_target_is_preserved() { + let fixture = Fixture::new(); + let (bytes, descriptor) = valid(); + let root = fixture.0.join("root"); + let calls = Cell::new(0); + assert!(stage_root( + &mut source(&fixture, &bytes), + &root, + &descriptor, + &limits(), + || { + calls.set(calls.get() + 1); + if calls.get() == 6 { + Err("cancelled".into()) + } else { + Ok(()) + } + } + ) + .is_err()); + assert!(!root.exists()); + fs::create_dir(&root).unwrap(); + fs::write(root.join("existing"), b"retained").unwrap(); + assert!(stage_root( + &mut source(&fixture, &bytes), + &root, + &descriptor, + &limits(), + || Ok(()) + ) + .is_err()); + assert_eq!(fs::read(root.join("existing")).unwrap(), b"retained"); + } +} From 9db7ab600ee0cb8f3613dbcc6547fda483202434 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 09:39:43 +0100 Subject: [PATCH 037/513] Fence trusted root links, exact container custody and staged cleanup --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 +++ backend/scripts/checker_trusted_root.py | 28 ++- backend/tests/test_checker_smol_cache.py | 10 +- external_checkers/README.md | 10 +- .../src/trusted_root.rs | 178 +++++++++++++++++- 5 files changed, 230 insertions(+), 20 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index fb52683b4..98f6c793c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -776,3 +776,27 @@ aggregate deadline. Real-image export/staging and final verification remain publication gates. A newer local Clippy reports existing workspace warnings; the required runtime gate uses CI's pinned Rust 1.84.0 and unchanged test command. No native Smol qualification follows from portable guest-library execution. + +The first review wave found three actionable gaps: escaping relative symlink +targets were accepted, inspected container IDs were not compared with the exact +selector, and initial directory permission setup sat outside the cleanup guard. +Repairs reject lexical root escape in producer and guest, compare exact returned +IDs for create and recovery, and guard every post-create staging action. Cleanup +restores writable owned directories after late failures; filesystem cleanup +failure remains an error and cannot release capacity. The guest now verifies a +supervisor-owned private parent, opens it without following its final symlink, +and anchors writes through its held descriptor across ancestor renames. + +The repair checks passed 80 Python and 12 guest tests. Running the updated Python +regressions against the frozen pre-repair producer produced exactly three +failures for the two escaping links and wrong container ID, with 12 controls +passing. Export tests also assert the explicit remaining timeout reaches the +runner. The prior pinned Rust 1.84.0 serial workspace gate completed 213 tests; +the repaired candidate needs its final gate before publication. + +Real-image provisioning produced a 460,208,808-byte bundle describing +457,060,353 expanded bytes and 24,549 entries; the repaired Rust reader staged +that whole bundle successfully. The temporary container was removed. These are +local image/bundle composition facts, not a PRE invocation or native isolation +qualification. Exact repaired producer replay and staged-interpreter execution +remain separate final proof checks. diff --git a/backend/scripts/checker_trusted_root.py b/backend/scripts/checker_trusted_root.py index b9e71e3b2..bc13f96d3 100644 --- a/backend/scripts/checker_trusted_root.py +++ b/backend/scripts/checker_trusted_root.py @@ -40,6 +40,19 @@ def _frame(output, value): output.write(raw) +def _link(path, target): + if not target or "\0" in target or "\\" in target or len(target.encode()) > 4096: + raise ImageError("trusted root link invalid") + depth = 0 if target.startswith("/") else path.count("/") + for part in target.split("/"): + if part == "..": + if depth == 0: + raise ImageError("trusted root link escapes root") + depth -= 1 + elif part not in {"", "."}: + depth += 1 + + def _available(deadline): if deadline is not None and time.monotonic() >= deadline: raise ImageError("trusted root provisioning deadline exceeded") @@ -59,9 +72,8 @@ def _members(archive, maximum_entries, maximum_bytes, deadline): raise ImageError("trusted root entry invalid") if item.size < 0 or (not item.isfile() and item.size): raise ImageError("trusted root entry size invalid") - if item.issym() and (not item.linkname or "\0" in item.linkname - or "\\" in item.linkname or len(item.linkname.encode()) > 4096): - raise ImageError("trusted root link invalid") + if item.issym(): + _link(name, item.linkname) total += item.size if total > maximum_bytes: raise ImageError("trusted root expanded byte limit exceeded") @@ -144,8 +156,8 @@ def _inspect(docker, kind, selector, budget): return body[0] -def _container_matches(value, config_id, token): - return (value.get("Image") == config_id +def _container_matches(value, config_id, token, container_id): + return (value.get("Id") == container_id and value.get("Image") == config_id and value.get("Config", {}).get("Labels", {}).get("workstream.root-provision") == token and value.get("State", {}).get("Status") == "created" and value.get("State", {}).get("Running") is False) @@ -171,7 +183,7 @@ def export_root(docker, config_id, config, sink, *, maximum_bytes, deadline): if re.fullmatch(r"[0-9a-f]{64}", container_id) is None: raise ImageError("trusted root container id invalid") value = _inspect(docker, "container", container_id, budget) - if not _container_matches(value, config_id, token): + if not _container_matches(value, config_id, token, container_id): raise ImageError("trusted root container differs") run([docker, "export", container_id], step="export trusted root", budget=budget, timeout=max(0.001, deadline - time.monotonic()), @@ -187,8 +199,10 @@ def export_root(docker, config_id, config, sink, *, maximum_bytes, deadline): raise ImageError("trusted root cleanup discovery ambiguous") container_id = matches[0] if matches else None if container_id is not None: + if re.fullmatch(r"[0-9a-f]{64}", container_id) is None: + raise ImageError("trusted root discovered container id invalid") value = _inspect(docker, "container", container_id, cleanup) - if not _container_matches(value, config_id, token): + if not _container_matches(value, config_id, token, container_id): raise ImageError("trusted root cleanup ownership unconfirmed") run([docker, "rm", container_id], step="remove trusted root export", budget=cleanup) diff --git a/backend/tests/test_checker_smol_cache.py b/backend/tests/test_checker_smol_cache.py index a36ea092b..50e8eb946 100644 --- a/backend/tests/test_checker_smol_cache.py +++ b/backend/tests/test_checker_smol_cache.py @@ -326,6 +326,8 @@ def test_trusted_root_bundle_normalizes_links_and_keeps_bytes(): [("a", tarfile.LNKTYPE, "b"), ("b", tarfile.LNKTYPE, "a")], [("a", tarfile.SYMTYPE, "b"), ("b", tarfile.LNKTYPE, "a")], [("device", tarfile.CHRTYPE, "")], + [("safe/escape", tarfile.SYMTYPE, "../../outside")], + [("escape", tarfile.SYMTYPE, "/../outside")], ]) def test_trusted_root_refuses_paths_special_files_and_link_ancestry(entries): from scripts.checker_trusted_root import pack_root @@ -344,7 +346,7 @@ def test_trusted_root_charges_hardlink_expansion_and_implicit_directories(): pack_root(root_export(source), io.BytesIO(), identity={}, maximum_entries=3, maximum_bytes=20) -@pytest.mark.parametrize("defect", [None, "image", "container", "started", "export"]) +@pytest.mark.parametrize("defect", [None, "image", "container", "container_id", "started", "export"]) def test_root_export_requires_exact_never_started_container_and_cleans_owned_id(monkeypatch, defect): import time from scripts import checker_trusted_root as root @@ -364,10 +366,12 @@ def command(argv, **kwargs): state["token"] = argv[argv.index("--label") + 1].split("=", 1)[1] return container_id.encode() if argv[1:3] == ["container", "inspect"]: - return json.dumps([{"Image": "other" if defect == "container" else config_id, + return json.dumps([{"Id": "f" * 64 if defect == "container_id" else container_id, + "Image": "other" if defect == "container" else config_id, "Config": {"Labels": {"workstream.root-provision": state["token"]}}, "State": {"Status": "running" if defect == "started" else "created", "Running": defect == "started"}}]).encode() if argv[1] == "export": + assert 0 < kwargs["timeout"] <= 10 if defect == "export": raise ImageError("export failed") kwargs["stdout_sink"].write(b"root bytes") @@ -442,7 +446,7 @@ def command(argv, **kwargs): return container_id.encode() if argv[1:3] == ["container", "inspect"]: assert argv[-1] == container_id - return json.dumps([{"Image": image_id, "State": {"Status": "created", "Running": False}, + return json.dumps([{"Id": container_id, "Image": image_id, "State": {"Status": "created", "Running": False}, "Config": {"Labels": {"workstream.root-provision": state["token"]}}}]).encode() assert argv == ["docker", "rm", container_id] return b"" diff --git a/external_checkers/README.md b/external_checkers/README.md index 1e05f33ed..49db5e813 100644 --- a/external_checkers/README.md +++ b/external_checkers/README.md @@ -488,8 +488,14 @@ The `WSROOT1` format carries bounded closed JSON records and inline regular-file bytes. Hard links become independently charged file content; symlinks are installed last. No image paths are extracted on the host. The guest library verifies the entire bounded spool and descriptor, stages into a fresh private -root, and rechecks consumed bytes before returning. The caller must provide a -protected parent, aggregate deadline/cancellation checks, and capacity for both +root, and rechecks consumed bytes before returning. It opens the supervisor-owned +private parent without following its final symlink and anchors staging through +that held directory descriptor. The caller must provide the private parent, +aggregate deadline/cancellation checks, and capacity for both the spool and expanded root, then mount the root read-only before executing a trusted child. Combined supervisor wiring and native isolation proof remain required; this library alone does not authorize project execution. +Cleanup restores owned directory permissions after late staging failures; an +underlying filesystem cleanup error is propagated and cannot establish released +capacity. Relative and absolute symlink targets that traverse above the root are +refused before installation. diff --git a/external_checkers/workstream-checker-guest/src/trusted_root.rs b/external_checkers/workstream-checker-guest/src/trusted_root.rs index 7d6d4b5a2..e5aa62a8d 100644 --- a/external_checkers/workstream-checker-guest/src/trusted_root.rs +++ b/external_checkers/workstream-checker-guest/src/trusted_root.rs @@ -5,7 +5,8 @@ use sha2::{Digest, Sha256}; use std::collections::HashSet; use std::fs::{self, File, OpenOptions}; use std::io::{self, Read, Seek, SeekFrom, Write}; -use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +use std::os::fd::AsRawFd; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; use std::path::Path; const MAGIC: &[u8] = b"WSROOT1\n"; @@ -71,6 +72,42 @@ fn path_valid(value: &str) -> bool { .all(|part| !part.is_empty() && part != "." && part != "..") } +fn link_valid(path: &str, target: &str) -> bool { + if target.is_empty() || target.len() > 4096 || target.contains(['\\', '\0']) { + return false; + } + let mut depth = if target.starts_with('/') { + 0 + } else { + path.matches('/').count() + }; + for part in target.split('/') { + match part { + ".." if depth == 0 => return false, + ".." => depth -= 1, + "" | "." => (), + _ => depth += 1, + } + } + true +} + +fn remove_owned_root(path: &Path) -> Result<()> { + // Restore directory write access after a late permission/cancellation error. + // The private held parent prevents an untrusted process replacing this tree. + fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; + for entry in fs::read_dir(path)? { + let entry = entry?; + if entry.file_type()?.is_dir() { + remove_owned_root(&entry.path())?; + } else { + fs::remove_file(entry.path())?; + } + } + fs::remove_dir(path)?; + Ok(()) +} + struct Hashed<'a> { file: &'a mut File, digest: Sha256, @@ -115,7 +152,8 @@ fn check_digest(reader: Hashed<'_>, expected: &RootDescriptor) -> Result<()> { /// Verify the pinned spool, then stage only into an exclusively created root. /// `check` must enforce the invocation's aggregate deadline/cancellation fence. -/// The caller must isolate the parent from all concurrent untrusted writers. +/// The parent must be private and owned by the supervisor. A held no-follow +/// descriptor anchors writes even if an ancestor path is renamed concurrently. pub fn stage_root( source: &mut File, target: &Path, @@ -157,11 +195,27 @@ pub fn stage_root( check_digest(reader, expected)?; check()?; source.seek(SeekFrom::Start(0))?; - fs::create_dir(target)?; - fs::set_permissions(target, fs::Permissions::from_mode(0o700))?; - let result = unpack(source, target, expected, &check); + if !target.is_absolute() { + return Err("root target must be absolute".into()); + } + let parent = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(target.parent().ok_or("root parent missing")?)?; + let metadata = parent.metadata()?; + if metadata.uid() != unsafe { libc::geteuid() } || metadata.mode() & 0o077 != 0 { + return Err("root parent is not supervisor-private".into()); + } + let anchored = std::path::PathBuf::from(format!("/proc/self/fd/{}", parent.as_raw_fd())) + .join(target.file_name().ok_or("root name missing")?); + fs::create_dir(&anchored)?; + let result = (|| { + check()?; + fs::set_permissions(&anchored, fs::Permissions::from_mode(0o700))?; + unpack(source, &anchored, expected, &check) + })(); if result.is_err() { - fs::remove_dir_all(target)?; + remove_owned_root(&anchored)?; } result } @@ -255,8 +309,11 @@ fn unpack( 0o444 }))?; } - Record::Symlink { target: link, .. } => { - if link.is_empty() || link.len() > 4096 || link.contains(['\\', '\0']) { + Record::Symlink { + path: name, + target: link, + } => { + if !link_valid(&name, &link) { return Err("root symlink invalid".into()); } std::os::unix::fs::symlink(link, path)?; @@ -277,6 +334,7 @@ fn unpack( fs::set_permissions(target.join(directory), fs::Permissions::from_mode(0o555))?; } fs::set_permissions(target, fs::Permissions::from_mode(0o555))?; + check()?; Ok(()) } @@ -298,6 +356,7 @@ mod tests { NEXT.fetch_add(1, Ordering::Relaxed) )); fs::create_dir(&path).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); Self(path) } } @@ -537,4 +596,107 @@ mod tests { .is_err()); assert_eq!(fs::read(root.join("existing")).unwrap(), b"retained"); } + #[test] + fn rejects_escaping_links_and_accepts_contained_relative_links() { + assert!(link_valid("usr/link", "../usr/python")); + for target in ["../../outside", "/../outside"] { + let fixture = Fixture::new(); + let (bytes, descriptor) = bundle(vec![ + (json!({"kind":"directory", "path":"safe"}), b""), + ( + json!({"kind":"symlink", "path":"safe/escape", "target":target}), + b"", + ), + ]); + let root = fixture.0.join("root"); + assert!(stage_root( + &mut source(&fixture, &bytes), + &root, + &descriptor, + &limits(), + || Ok(()) + ) + .is_err()); + assert!(!root.exists()); + } + } + + #[test] + fn errors_immediately_after_create_and_after_sealing_remove_owned_root() { + for early in [true, false] { + let fixture = Fixture::new(); + let (bytes, descriptor) = valid(); + let root = fixture.0.join("root"); + let calls = Cell::new(0); + let result = stage_root( + &mut source(&fixture, &bytes), + &root, + &descriptor, + &limits(), + || { + calls.set(calls.get() + 1); + let sealed = fs::metadata(&root) + .map(|info| info.permissions().mode() & 0o777 == 0o555) + .unwrap_or(false); + if (early && calls.get() == 4) || (!early && sealed) { + Err("cancelled at permission boundary".into()) + } else { + Ok(()) + } + }, + ); + assert!(result.is_err()); + assert!(!root.exists()); + } + } + + #[test] + fn requires_private_nofollow_parent_and_pins_its_identity() { + let fixture = Fixture::new(); + let (bytes, descriptor) = valid(); + let parent = fixture.0.join("private"); + fs::create_dir(&parent).unwrap(); + let target = parent.join("root"); + fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(stage_root( + &mut source(&fixture, &bytes), + &target, + &descriptor, + &limits(), + || Ok(()) + ) + .is_err()); + fs::set_permissions(&parent, fs::Permissions::from_mode(0o700)).unwrap(); + let alias = fixture.0.join("alias"); + std::os::unix::fs::symlink(&parent, &alias).unwrap(); + assert!(stage_root( + &mut source(&fixture, &bytes), + &alias.join("root"), + &descriptor, + &limits(), + || Ok(()) + ) + .is_err()); + let moved = fixture.0.join("moved"); + let outside = fixture.0.join("outside"); + fs::create_dir(&outside).unwrap(); + let calls = Cell::new(0); + stage_root( + &mut source(&fixture, &bytes), + &target, + &descriptor, + &limits(), + || { + calls.set(calls.get() + 1); + if calls.get() == 4 { + fs::rename(&parent, &moved)?; + std::os::unix::fs::symlink(&outside, &parent)?; + } + Ok(()) + }, + ) + .unwrap(); + assert_eq!(fs::read(moved.join("root/usr/python")).unwrap(), b"code"); + assert!(!outside.join("root").exists()); + } } From 09cdcdfb12bbaa02d7d9fb5e21c61a1e717ca5eb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 09:51:18 +0100 Subject: [PATCH 038/513] Record live image content mismatch and require verified-layer provisioning --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 52 +++++++++++++++++++ external_checkers/README.md | 6 +++ 2 files changed, 58 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 98f6c793c..3def16053 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -800,3 +800,55 @@ that whole bundle successfully. The temporary container was removed. These are local image/bundle composition facts, not a PRE invocation or native isolation qualification. Exact repaired producer replay and staged-interpreter execution remain separate final proof checks. + +### Live image-content mismatch and corrected provisioning boundary + +The repaired candidate's Rust 1.84.0 serial gate passed 216 tests. Its real +producer completed and cleaned its container, but comparison with the earlier +bundle disproved the assumption that daemon image metadata proves exported +filesystem contents. Both bundles have the same pinned config, platform, +default identity, byte/entry counts and valid self-digests. They differ only in +`urllib3/connectionpool.py` and its uv-cache hardlink: four bytes at offset 45088 +changed from `try:` to `00 90 01 00`. The later file is not valid UTF-8. + +Independent reads from the verified canonical image archive retain the correct +file digest `6a147869216b94449a053e869d4311cba23294551c83ee20fe5d2f1eaff50a3e`. +Two fresh never-started containers copied directly through Docker reproduce +the different digest `9b1a4e8c373fa4abc73c1b9e68cd39c7a6f8cb2ef2a558b4e7363d8f2f0e466e` +while reporting the same image config ID. Reviewer mutations were in-memory +only. This establishes a mismatch in the daemon's materialized image contents; +it does not establish its cause. The producer must not be published as qualified +or used for execution on this evidence. Runtime staging correctly authenticates +the bundle it is given, but cannot repair incorrect provenance upstream. + +Replace the daemon-export dependency with direct construction from the existing +verified canonical image archive. Preserve the bundle format and guest reader. +Build a bounded in-memory final-path inventory from the exact ordered layers, +with bounded private file-content spooling instead of host path extraction. +Use the OCI 1.1.1 layer changeset rules: process whiteouts against lower-layer +entries before same-layer additions, distinguish opaque directory removal, +merge directories, and replace other paths. Resolve regular hardlinks against +known file identities; reject unsupported entry types, ambiguous link ancestry, +duplicates, cycles and root escapes rather than assuming generic image support. +Preserve executable intent and the existing read-only normalization deliberately. +Bind every output file's size/hash to its source layer and the closed approved +graph; verify retained input identity through completion. The trusted platform +profile must accept the actual pinned intake image before this change qualifies. + +Allowed correction scope: the existing cache graph helper, trusted-root producer +and one cohesive layer-inventory helper if needed, its existing tests and exact +ownership registration, runtime documentation and this record. Remove the +superseded Docker create/export path, flags, sink-only helper changes and tests +once no required consumer remains. No second provisioner, fallback to daemon +contents, changed guest format, source-image repair/deletion, runtime cutover or +qualification shortcut. This remains L0 with architecture/security plan and +implementation review plus QA/test-delta and docs review. + +Acceptance: faithful layered replacement/whiteout/hardlink behavior, bounded +aggregate data/entries/deadline, no host extraction, wrong layer/config refusal, +deterministic complete root construction, and publication cleanup. The live +counterexample must yield the canonical archive's correct file bytes without +consulting the divergent daemon filesystem; two builds from identical approved +bytes must agree. Then repeat guest staging and trusted-interpreter checks and +retain the unchanged four-default behavior identity. This correction is a +prerequisite for the same one-session supervisor, not a separate completion goal. diff --git a/external_checkers/README.md b/external_checkers/README.md index 49db5e813..733b75f6c 100644 --- a/external_checkers/README.md +++ b/external_checkers/README.md @@ -466,6 +466,12 @@ root for the single-session PRE supervisor under development. This command and the guest bundle reader do not yet replace the current submission PRE flow or establish native runtime qualification. +Live verification found that daemon-exported file contents can differ from the +verified source archive despite matching image metadata. This development +provisioner is not ready for execution use; its export step is being replaced +with construction from the verified layers. The bundle-reader guarantees below +authenticate bundle bytes, not the daemon's claimed provenance. + The command first verifies the approved local image graph with the existing Smol cache provisioner. A trusted offline Docker daemon must already contain that exact config image ID. It checks the platform and ordered layer identities, From 9de7e23a09e400a467d300882a19e6e7ad3f4398 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 09:53:18 +0100 Subject: [PATCH 039/513] Bind verified-layer plan to reviewed parser requirements --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3def16053..85edebd6d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -852,3 +852,13 @@ consulting the divergent daemon filesystem; two builds from identical approved bytes must agree. Then repeat guest staging and trusted-interpreter checks and retain the unchanged four-default behavior identity. This correction is a prerequisite for the same one-session supervisor, not a separate completion goal. + +Architecture/security approved this corrected direction with explicit parser +requirements: whiteout markers must be empty regular entries with valid nonempty +targets, with exact handling for `.wh..wh..opq`; complete layer streams must match +their approved compressed digests and config diff IDs, and retained file bytes +must be rehashed during spool/output. Reuse the existing graph/member index. +Read-only inventory of the actual ten-layer intake image found only directories, +regular files, symlinks and hardlinks, with no duplicate layer paths, whiteouts, +or writes through nondirectory ancestors. That makes the restricted profile +concrete; synthetic whiteout/replacement regressions are still required. From 982417ab37a460d512b9d4a926e8b0497a645ed2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 10:09:49 +0100 Subject: [PATCH 040/513] Construct trusted PRE roots directly from verified image layers --- .ci/behavior-ownership/partition.v1.json | 6 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 30 ++ backend/scripts/behavior_ownership.py | 1 + backend/scripts/checker_image_process.py | 6 +- backend/scripts/checker_root_layers.py | 202 +++++++++++++ backend/scripts/checker_smol_cache.py | 34 ++- backend/scripts/checker_trusted_root.py | 273 +++++------------ backend/tests/test_checker_image.py | 22 -- backend/tests/test_checker_smol_cache.py | 286 ++++++++++-------- external_checkers/README.md | 39 ++- 10 files changed, 518 insertions(+), 381 deletions(-) create mode 100644 backend/scripts/checker_root_layers.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 88a963af1..5ff030f76 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -2552,6 +2552,10 @@ "group": "artifacts", "target": "backend/scripts/checker_image_samples.py" }, + { + "group": "artifacts", + "target": "backend/scripts/checker_root_layers.py" + }, { "group": "artifacts", "target": "backend/scripts/checker_smol_cache.py" @@ -2657,7 +2661,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "5093f0ae793900f5aacc8dc30f7b7711e405fa8b36c6b8eba758ddecc8b7f147", + "authority_digest": "e33f74715c05aa7421172de067b9b199daf6655580361a6eb740d31e8b825aaf", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 85edebd6d..58837e278 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -862,3 +862,33 @@ Read-only inventory of the actual ten-layer intake image found only directories, regular files, symlinks and hardlinks, with no duplicate layer paths, whiteouts, or writes through nondirectory ancestors. That makes the restricted profile concrete; synthetic whiteout/replacement regressions are still required. + +Direct verified-layer construction now replaces Docker export completely. +`checker_root_layers.py` reuses the canonical graph/member index, verifies each +consumed layer and its temporary spool, and constructs only an in-memory path +inventory plus bounded content bytes. Lower-layer whiteouts precede same-layer +additions; directory merges, replacements and immutable regular hardlink content +are explicit. Unsupported links, special/sparse files, duplicate paths and +invalid/nonempty whiteouts fail closed. Complete tar trailers are required. +The graph helper now accepts explicit byte/deadline bounds for this caller, so +its preliminary decompression cannot bypass the provisioning limit. + +The producer rehashes retained file bytes, checks the serialized bundle against +an independently accumulated write digest, and revalidates its retained cache +through completion before publishing the descriptor. The Docker flag/export +budget was replaced by the explicit layer byte bound. The now-unused subprocess +sink extension and its tests were removed; original image-publisher process +behavior remains. Docker ownership tests were replaced by layer semantics, +determinism and a real prohibition on subprocess materialization, while unsafe +path/link and publication cleanup proof remain. + +Focused verification passed 254 tests (84 image/cache/root tests and 170 ownership +tests), plus Ruff, Commitrail and Markdown links. Two independent constructions +of the actual pinned ten-layer intake image produced the same bundle digest, +`sha256:273ca6b9ffa7abed0dd5252d86e35fe0a218d09624cb9921cdbec734ebe049cb`: +460,208,569 serialized bytes, 457,060,471 expanded bytes and 24,543 entries. +The unchanged Rust reader staged the complete root; its urllib3 file matches +the canonical archive's correct hash rather than the daemon's altered bytes. +This validates the corrected content source, not native PRE isolation. The +existing single-request integration, combined supervisor and native runtime +qualification remain outstanding. diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index d22cf1d31..6de52fc91 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -108,6 +108,7 @@ "backend/scripts/checker_image_manifest.py", "backend/scripts/checker_smol_cache.py", "backend/scripts/checker_trusted_root.py", + "backend/scripts/checker_root_layers.py", "backend/scripts/checker_image_samples.py", }) AWS_ARTIFACT_ACTIVATION_TARGETS = frozenset({ diff --git a/backend/scripts/checker_image_process.py b/backend/scripts/checker_image_process.py index 8cc01238d..91cd776ea 100644 --- a/backend/scripts/checker_image_process.py +++ b/backend/scripts/checker_image_process.py @@ -38,7 +38,6 @@ def run( data: bytes = b"", env: dict[str, str] | None = None, budget: ExecutionBudget | None = None, - stdout_sink=None, ) -> bytes: """Drain both pipes within one byte/time budget and kill owned processes on failure.""" deadline = ( @@ -81,10 +80,7 @@ def run( if consumed > limit: raise ImageError(f"{step}: output limit exceeded") if key.data: - if stdout_sink is None: - output.extend(chunk) - elif stdout_sink.write(chunk) != len(chunk): - raise ImageError(f"{step}: incomplete output write") + output.extend(chunk) code = process.wait(timeout=max(0.001, deadline - time.monotonic())) if code: raise ImageError(f"{step}: command exited {code}") diff --git a/backend/scripts/checker_root_layers.py b/backend/scripts/checker_root_layers.py new file mode 100644 index 000000000..8a6f54c93 --- /dev/null +++ b/backend/scripts/checker_root_layers.py @@ -0,0 +1,202 @@ +"""Restricted trusted-platform root construction from an approved OCI graph. + +Layer paths are inventory keys, never host extraction paths. Unsupported alias, +sparse, special-file or hardlink semantics fail closed instead of invoking an +external filesystem materializer. +""" +from dataclasses import dataclass +import gzip +import hashlib +import json +import os +import tarfile +import tempfile +import time + +from scripts import checker_smol_cache as cache +from scripts.checker_image_process import ImageError + + +def available(deadline): + if time.monotonic() >= deadline: + raise ImageError("trusted root provisioning deadline exceeded") + + +def path_name(value): + if (not value or len(value.encode()) > 4096 or value.startswith("/") + or "\\" in value or "\0" in value + or any(part in {"", ".", ".."} for part in value.split("/"))): + raise ImageError("trusted root path invalid") + return value + + +def link_target(path, target): + if not target or "\0" in target or "\\" in target or len(target.encode()) > 4096: + raise ImageError("trusted root link invalid") + depth = 0 if target.startswith("/") else path.count("/") + for part in target.split("/"): + if part == "..": + if depth == 0: + raise ImageError("trusted root link escapes root") + depth -= 1 + elif part not in {"", "."}: + depth += 1 + + +@dataclass(frozen=True) +class RootEntry: + """A normalized entry; regular content refers only to our private byte spool.""" + + kind: str + size: int = 0 + sha256: str = "" + executable: bool = False + offset: int = 0 + target: str = "" + + +def _delete(tree, name, children_only=False): + if name and name not in tree: + return + if name and tree[name].kind != "directory": + if not children_only: + del tree[name] + return + prefix = name + "/" if name else "" + for path in list(tree): + if (not children_only and path == name) or path.startswith(prefix): + del tree[path] + + +def _parents(tree, name, create=False): + parts = name.split("/") + for index in range(1, len(parts)): + parent = "/".join(parts[:index]) + if parent in tree and tree[parent].kind != "directory": + raise ImageError("trusted layer has a nondirectory ancestor") + if create: + tree.setdefault(parent, RootEntry("directory")) + + +def _layer_entries(layer, remaining_entries, deadline): + entries, seen, whiteouts = [], set(), [] + count = 0 + for item in layer: + available(deadline) + count += 1 + if count > remaining_entries: + raise ImageError("trusted layer aggregate entry limit exceeded") + name = item.name.removeprefix("./").removesuffix("/") if item.isdir() else item.name.removeprefix("./") + if name in {"", "."} and item.isdir(): + if "." in seen: + raise ImageError("trusted layer root directory duplicated") + seen.add(".") + continue + path_name(name) + if name in seen or item.issparse() or not (item.isdir() or item.isfile() or item.issym() or item.islnk()): + raise ImageError("trusted layer entry invalid") + seen.add(name) + if item.size < 0 or (not item.isfile() and item.size): + raise ImageError("trusted layer entry size invalid") + parent, _, basename = name.rpartition("/") + if basename.startswith(".wh."): + if not item.isfile() or item.size: + raise ImageError("trusted layer whiteout invalid") + if basename == ".wh..wh..opq": + whiteouts.append((parent, True)) + else: + target = basename[4:] + path_name(target) + whiteouts.append((parent + "/" + target if parent else target, False)) + else: + entries.append((name, item)) + layer.fileobj.seek(layer.offset) + trailer_size = 0 + while chunk := layer.fileobj.read(65536): + available(deadline) + trailer_size += len(chunk) + if any(chunk): + raise ImageError("trusted layer trailing content invalid") + if trailer_size < 1024 or trailer_size % 512: + raise ImageError("trusted layer trailer truncated") + return entries, whiteouts, count + + +def apply_layer(layer_file, spool, tree, *, maximum_entries, remaining_entries, deadline): + """Apply lower-layer deletion first, then additions in their declared order.""" + with tarfile.open(fileobj=layer_file, mode="r:") as layer: + entries, whiteouts, count = _layer_entries(layer, remaining_entries, deadline) + for target, opaque in whiteouts: + available(deadline) + _parents(tree, target + "/marker" if opaque and target else target) + _delete(tree, target, children_only=opaque) + for name, item in entries: + available(deadline) + _parents(tree, name, create=True) + if not (item.isdir() and name in tree and tree[name].kind == "directory"): + _delete(tree, name) + if item.isdir(): + entry = RootEntry("directory") + elif item.issym(): + link_target(name, item.linkname) + entry = RootEntry("symlink", target=item.linkname) + elif item.islnk(): + target = path_name(item.linkname.removeprefix("./")) + if target not in tree or tree[target].kind != "file": + raise ImageError("trusted layer hardlink target is not a known regular file") + entry = tree[target] + else: + offset, digest, remaining = spool.tell(), hashlib.sha256(), item.size + with layer.extractfile(item) as content: + while remaining: + available(deadline) + chunk = content.read(min(remaining, 65536)) + if not chunk: + raise ImageError("trusted layer file truncated") + spool.write(chunk) + digest.update(chunk) + remaining -= len(chunk) + entry = RootEntry("file", item.size, digest.hexdigest(), bool(item.mode & 0o111), offset) + tree[name] = entry + if len(tree) > maximum_entries: + raise ImageError("trusted root implicit directory limit exceeded") + return count + + +def construct_root(source, spool, *, manifest_digest, config_image_id, + maximum_layer_bytes, maximum_entries, deadline): + """Reverify the graph and each consumed layer before returning its final inventory.""" + members = cache._preflight(source, os.fstat(source.fileno()).st_size) + _, config_id, raw_config, wrapper, expected = cache._graph( + source, members, manifest_digest, maximum_layer_bytes=maximum_layer_bytes, deadline=deadline) + if config_id != config_image_id: + raise ImageError("trusted root config differs") + layers = json.loads(wrapper)[0]["Layers"] + diff_ids = json.loads(raw_config)["rootfs"]["diff_ids"] + tree, expanded, count = {}, 0, 0 + for name, diff_id in zip(layers, diff_ids, strict=True): + available(deadline) + raw = cache.MemberReader(source, members[name]) + magic = raw.read(2) + raw = cache.MemberReader(source, members[name]) + reader = gzip.GzipFile(fileobj=raw) if magic == b"\x1f\x8b" else raw + digest = hashlib.sha256() + with tempfile.TemporaryFile() as layer: + while chunk := reader.read(65536): + available(deadline) + expanded += len(chunk) + if expanded > maximum_layer_bytes: + raise ImageError("trusted layer aggregate byte limit exceeded") + layer.write(chunk) + digest.update(chunk) + if ("sha256:" + digest.hexdigest() != diff_id + or "sha256:" + raw.hash.hexdigest() != expected[name]): + raise ImageError("trusted layer consumed identity differs") + layer.seek(0) + count += apply_layer(layer, spool, tree, maximum_entries=maximum_entries, + remaining_entries=maximum_entries - count, deadline=deadline) + layer.seek(0) + if cache.digest(layer, deadline=deadline) != diff_id: + raise ImageError("trusted layer spool identity differs") + available(deadline) + return tree diff --git a/backend/scripts/checker_smol_cache.py b/backend/scripts/checker_smol_cache.py index 19b89aa2e..4e90fe442 100644 --- a/backend/scripts/checker_smol_cache.py +++ b/backend/scripts/checker_smol_cache.py @@ -18,6 +18,7 @@ import re import stat import tarfile +import time from scripts.checker_image_manifest import DIGEST, verify_platform_manifest from scripts.checker_image_process import ImageError @@ -28,11 +29,22 @@ BLOCK = 512 -def digest(stream) -> str: - value = hashlib.sha256() +def _counted_digest(stream, maximum_bytes=None, deadline=None): + value, count = hashlib.sha256(), 0 while chunk := stream.read(1024 * 1024): + count += len(chunk) + if maximum_bytes is not None and count > maximum_bytes: + raise ImageError("image verification byte limit exceeded") + if deadline is not None and time.monotonic() >= deadline: + raise ImageError("image verification deadline exceeded") value.update(chunk) - return "sha256:" + value.hexdigest() + if deadline is not None and time.monotonic() >= deadline: + raise ImageError("image verification deadline exceeded") + return "sha256:" + value.hexdigest(), count + + +def digest(stream, *, maximum_bytes=None, deadline=None) -> str: + return _counted_digest(stream, maximum_bytes, deadline)[0] @dataclass(frozen=True) @@ -150,7 +162,7 @@ def unique(pairs): return json.loads(raw, object_pairs_hook=unique) -def _graph(source, members, manifest_digest): +def _graph(source, members, manifest_digest, *, maximum_layer_bytes=None, deadline=None): def regular(name): _path(name) return MemberReader(source, members[name]) @@ -186,6 +198,7 @@ def metadata(name, maximum=MAX_METADATA): raise ImageError("rootfs layer count differs") expected = {platform_path: manifest_digest, config_path: config_id} approved_layers = set() + remaining = maximum_layer_bytes for name, diff_id, descriptor in zip(layers, diff_ids, descriptors, strict=True): if not isinstance(diff_id, str) or DIGEST.fullmatch(diff_id) is None: raise ImageError("rootfs digest is invalid") @@ -201,14 +214,17 @@ def metadata(name, maximum=MAX_METADATA): for selected, approved_digest in ((approved, descriptor["digest"]), (name, None)): if not isinstance(selected, str) or selected == "manifest.json": raise ImageError("invalid selected layer") - raw_digest = digest(regular(selected)) + raw_digest = digest(regular(selected), maximum_bytes=maximum_layer_bytes, deadline=deadline) if approved_digest is not None and raw_digest != approved_digest: raise ImageError("approved layer blob digest differs") reader = regular(selected) magic = reader.read(2) reader = regular(selected) expanded = gzip.GzipFile(fileobj=reader) if magic == b"\x1f\x8b" else reader - if digest(expanded) != diff_id: + observed, count = _counted_digest(expanded, remaining, deadline) + if remaining is not None: + remaining -= count + if observed != diff_id: raise ImageError("rootfs layer digest differs") if selected in expected and expected[selected] != raw_digest: raise ImageError("image graph path conflicts") @@ -247,7 +263,8 @@ def _copy_member(bundle, source, name, member, expected_digest): def provision(archive: Path, repository: str, manifest_digest: str, *, - archive_output: Path, config_output: Path) -> dict: + archive_output: Path, config_output: Path, + maximum_layer_bytes=None, deadline=None) -> dict: created = [] try: if DIGEST.fullmatch(manifest_digest) is None: @@ -263,7 +280,8 @@ def provision(archive: Path, repository: str, manifest_digest: str, *, raise ImageError("source archive is not regular") identity = _identity(before) members = _preflight(source, before.st_size) - manifest, config_id, raw_config, wrapper, expected = _graph(source, members, manifest_digest) + manifest, config_id, raw_config, wrapper, expected = _graph( + source, members, manifest_digest, maximum_layer_bytes=maximum_layer_bytes, deadline=deadline) for name in expected: _tar_info(name, members[name].size) _unchanged(source, archive, identity) diff --git a/backend/scripts/checker_trusted_root.py b/backend/scripts/checker_trusted_root.py index bc13f96d3..63d2f5ff8 100644 --- a/backend/scripts/checker_trusted_root.py +++ b/backend/scripts/checker_trusted_root.py @@ -1,6 +1,6 @@ """Provision the trusted PRE interpreter from a verified image, without running it. -Docker is trusted offline build infrastructure. The produced bundle is not a +The approved archive is the sole source of platform file contents. The produced bundle is not a qualification receipt and is never accepted without its independently pinned identity. No submitted archive or project image enters this command. """ @@ -10,26 +10,30 @@ import json import os from pathlib import Path -import re -import secrets import struct -import tarfile +import stat import tempfile import time from scripts import checker_smol_cache as cache -from scripts.checker_image_process import ExecutionBudget, ImageError, run +from scripts.checker_image_process import ImageError +from scripts.checker_root_layers import available, construct_root MAGIC = b"WSROOT1\n" MAX_HEADER = 16384 -def _path(value: str) -> str: - if (not value or len(value.encode()) > 4096 or value.startswith("/") - or "\\" in value or "\0" in value - or any(part in {"", ".", ".."} for part in value.split("/"))): - raise ImageError("trusted root path invalid") - return value +class _BundleWriter: + """Bind the expected serialized bytes independently of the output file read.""" + + def __init__(self, output): + self.output, self.digest, self.count = output, hashlib.sha256(), 0 + + def write(self, data): + if self.output.write(data) != len(data): + raise ImageError("trusted root output write incomplete") + self.digest.update(data) + self.count += len(data) def _frame(output, value): @@ -40,181 +44,53 @@ def _frame(output, value): output.write(raw) -def _link(path, target): - if not target or "\0" in target or "\\" in target or len(target.encode()) > 4096: - raise ImageError("trusted root link invalid") - depth = 0 if target.startswith("/") else path.count("/") - for part in target.split("/"): - if part == "..": - if depth == 0: - raise ImageError("trusted root link escapes root") - depth -= 1 - elif part not in {"", "."}: - depth += 1 - - -def _available(deadline): - if deadline is not None and time.monotonic() >= deadline: - raise ImageError("trusted root provisioning deadline exceeded") - - -def _members(archive, maximum_entries, maximum_bytes, deadline): - members, total = {}, 0 - for index, item in enumerate(archive): - _available(deadline) - if index >= maximum_entries: - raise ImageError("trusted root entry limit exceeded") - name = item.name.removesuffix("/") if item.isdir() else item.name - if name in {"", "."} and item.isdir(): +def pack_root(spool, output, *, tree, identity, maximum_bytes, deadline): + """Write the verified final inventory, rehashing retained file content.""" + output.write(MAGIC) + _frame(output, {"kind": "identity", **identity}) + directories = [name for name, entry in tree.items() if entry.kind == "directory"] + for name in sorted(directories, key=lambda value: (value.count("/"), value)): + available(deadline) + _frame(output, {"kind": "directory", "path": name}) + total = 0 + for name, entry in sorted(tree.items()): + available(deadline) + if entry.kind != "file": continue - _path(name) - if name in members or not (item.isdir() or item.isfile() or item.issym() or item.islnk()): - raise ImageError("trusted root entry invalid") - if item.size < 0 or (not item.isfile() and item.size): - raise ImageError("trusted root entry size invalid") - if item.issym(): - _link(name, item.linkname) - total += item.size + total += entry.size if total > maximum_bytes: raise ImageError("trusted root expanded byte limit exceeded") - members[name] = item - directories = set() - for name in members: - parts = name.split("/") - for end in range(1, len(parts)): - parent = "/".join(parts[:end]) - if parent in members and not members[parent].isdir(): - raise ImageError("trusted root has a nondirectory ancestor") - directories.add(parent) - directories.update(name for name, item in members.items() if item.isdir()) - if len(directories | members.keys()) > maximum_entries: - raise ImageError("trusted root implicit directory limit exceeded") - return members, directories - - -def _regular(name, members): - visited = set() - while True: - if name in visited or name not in members: - raise ImageError("trusted root hardlink invalid") - visited.add(name) - item = members[name] - if item.isfile(): - return item - if not item.islnk(): - raise ImageError("trusted root hardlink target is not regular") - name = _path(item.linkname) - - -def pack_root(source, output, *, identity, maximum_entries, maximum_bytes, deadline=None): - """Normalize a bounded Docker export; never extract paths onto the host.""" - if maximum_entries <= 0 or maximum_bytes <= 0: - raise ImageError("trusted root bounds must be positive") - output.write(MAGIC) - _frame(output, {"kind": "identity", **identity}) - with tarfile.open(fileobj=source, mode="r:") as archive: - members, directories = _members(archive, maximum_entries, maximum_bytes, deadline) - for name in sorted(directories, key=lambda value: (value.count("/"), value)): - _available(deadline) - _frame(output, {"kind": "directory", "path": name}) - total, entries = 0, len(directories) - for name, item in sorted(members.items()): - _available(deadline) - if not (item.isfile() or item.islnk()): - continue - regular = _regular(name, members) - total += regular.size - entries += 1 - if total > maximum_bytes: - raise ImageError("trusted root hardlink expansion exceeds limit") - _frame(output, {"kind": "file", "path": name, "byte_count": regular.size, - "executable": bool(regular.mode & 0o111)}) - with archive.extractfile(regular) as content: - remaining = regular.size - while remaining: - _available(deadline) - data = content.read(min(65536, remaining)) - if not data: - raise ImageError("trusted root file truncated") - output.write(data) - remaining -= len(data) - for name, item in sorted(members.items()): - _available(deadline) - if item.issym(): - entries += 1 - _frame(output, {"kind": "symlink", "path": name, "target": item.linkname}) - _frame(output, {"kind": "end"}) - _available(deadline) - return {"expanded_bytes": total, "entries": entries} - - -def _inspect(docker, kind, selector, budget): - raw = run([docker, kind, "inspect", selector], step="inspect trusted root custody", budget=budget) - body = cache._json(raw) - if type(body) is not list or len(body) != 1 or type(body[0]) is not dict: - raise ImageError("trusted root inspection invalid") - return body[0] - - -def _container_matches(value, config_id, token, container_id): - return (value.get("Id") == container_id and value.get("Image") == config_id - and value.get("Config", {}).get("Labels", {}).get("workstream.root-provision") == token - and value.get("State", {}).get("Status") == "created" - and value.get("State", {}).get("Running") is False) - - -def export_root(docker, config_id, config, sink, *, maximum_bytes, deadline): - """Export a never-started exact image and clean only the invocation's container.""" - budget = ExecutionBudget(deadline, maximum_bytes + 1024 * 1024) - image = _inspect(docker, "image", config_id, budget) - if (image.get("Id") != config_id or image.get("Os") != "linux" - or image.get("Architecture") != "amd64" - or image.get("RootFS", {}).get("Layers") != config["rootfs"]["diff_ids"] - or image.get("Config", {}).get("Volumes") or config.get("config", {}).get("Volumes")): - raise ImageError("trusted root image differs") - token = secrets.token_hex(16) - name = "workstream-root-" + token - container_id = None - try: - raw = run([docker, "create", "--pull=never", "--network=none", "--name", name, - "--label", "workstream.root-provision=" + token, config_id], - step="create trusted root export", budget=budget) - container_id = raw.decode("ascii").strip() - if re.fullmatch(r"[0-9a-f]{64}", container_id) is None: - raise ImageError("trusted root container id invalid") - value = _inspect(docker, "container", container_id, budget) - if not _container_matches(value, config_id, token, container_id): - raise ImageError("trusted root container differs") - run([docker, "export", container_id], step="export trusted root", budget=budget, - timeout=max(0.001, deadline - time.monotonic()), - limit=maximum_bytes, stdout_sink=sink) - finally: - # A fresh cleanup budget is independent of an exhausted export budget. - cleanup = ExecutionBudget(time.monotonic() + 30, 1024 * 1024) - if container_id is None or re.fullmatch(r"[0-9a-f]{64}", container_id) is None: - matches = run([docker, "ps", "-aq", "--no-trunc", "--filter", "name=^/" + name + "$", - "--filter", "label=workstream.root-provision=" + token], - step="discover trusted root export", budget=cleanup).decode().split() - if len(matches) > 1: - raise ImageError("trusted root cleanup discovery ambiguous") - container_id = matches[0] if matches else None - if container_id is not None: - if re.fullmatch(r"[0-9a-f]{64}", container_id) is None: - raise ImageError("trusted root discovered container id invalid") - value = _inspect(docker, "container", container_id, cleanup) - if not _container_matches(value, config_id, token, container_id): - raise ImageError("trusted root cleanup ownership unconfirmed") - run([docker, "rm", container_id], step="remove trusted root export", budget=cleanup) + _frame(output, {"kind": "file", "path": name, "byte_count": entry.size, + "executable": entry.executable}) + spool.seek(entry.offset) + digest, remaining = hashlib.sha256(), entry.size + while remaining: + available(deadline) + chunk = spool.read(min(remaining, 65536)) + if not chunk: + raise ImageError("trusted root spool truncated") + output.write(chunk) + digest.update(chunk) + remaining -= len(chunk) + if digest.hexdigest() != entry.sha256: + raise ImageError("trusted root retained file identity differs") + for name, entry in sorted(tree.items()): + available(deadline) + if entry.kind == "symlink": + _frame(output, {"kind": "symlink", "path": name, "target": entry.target}) + _frame(output, {"kind": "end"}) + available(deadline) + return {"expanded_bytes": total, "entries": len(tree)} def provision_root(archive: Path, repository: str, manifest_digest: str, *, archive_output: Path, config_output: Path, bundle_output: Path, - descriptor_output: Path, docker: str, default_behavior_sha256: str, - maximum_export_bytes: int, maximum_root_bytes: int, + descriptor_output: Path, default_behavior_sha256: str, + maximum_layer_bytes: int, maximum_root_bytes: int, maximum_entries: int, timeout_seconds: float): """Bind an exclusive sealed runtime bundle to the already verified image graph.""" if (any(type(value) is not int or value <= 0 for value in - (maximum_export_bytes, maximum_root_bytes, maximum_entries)) + (maximum_layer_bytes, maximum_root_bytes, maximum_entries)) or not 0 < timeout_seconds <= 7200 or cache.DIGEST.fullmatch(default_behavior_sha256) is None): raise ImageError("trusted root provisioning limits invalid") @@ -224,30 +100,43 @@ def provision_root(archive: Path, repository: str, manifest_digest: str, *, raise ImageError("trusted root outputs must be distinct") deadline = time.monotonic() + timeout_seconds receipt = cache.provision(archive, repository, manifest_digest, - archive_output=archive_output, config_output=config_output) - raw_config = config_output.read_bytes() - if "sha256:" + hashlib.sha256(raw_config).hexdigest() != receipt["config_image_id"]: - raise ImageError("trusted root config changed") - config = cache._json(raw_config) + archive_output=archive_output, config_output=config_output, + maximum_layer_bytes=maximum_layer_bytes, deadline=deadline) identity = {"platform_manifest_digest": manifest_digest, "config_image_id": receipt["config_image_id"], "default_behavior_sha256": default_behavior_sha256} created = [] try: - with tempfile.TemporaryFile() as exported: - export_root(docker, receipt["config_image_id"], config, exported, - maximum_bytes=maximum_export_bytes, deadline=deadline) - exported.seek(0) + fd = os.open(paths[0], os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK) + with os.fdopen(fd, "rb") as source, tempfile.TemporaryFile() as spool: + metadata = os.fstat(source.fileno()) + if not stat.S_ISREG(metadata.st_mode): + raise ImageError("trusted root cache is not regular") + original = cache._identity(metadata) + if cache.digest(source, deadline=deadline) != receipt["smol"]["archive_sha256"]: + raise ImageError("trusted root source cache changed") + source.seek(0) + tree = construct_root(source, spool, manifest_digest=manifest_digest, + config_image_id=receipt["config_image_id"], + maximum_layer_bytes=maximum_layer_bytes, + maximum_entries=maximum_entries, deadline=deadline) with cache._output_files(paths[2:], created) as (bundle, descriptor): - facts = pack_root(exported, bundle, identity=identity, - maximum_entries=maximum_entries, maximum_bytes=maximum_root_bytes, - deadline=deadline) + writer = _BundleWriter(bundle) + facts = pack_root(spool, writer, tree=tree, identity=identity, + maximum_bytes=maximum_root_bytes, deadline=deadline) + cache._unchanged(source, paths[0], original) + source.seek(0) + if cache.digest(source, deadline=deadline) != receipt["smol"]["archive_sha256"]: + raise ImageError("trusted root source cache changed") bundle.flush() size = bundle.tell() bundle.seek(0) + observed_digest = cache.digest(bundle, deadline=deadline) + if (observed_digest != "sha256:" + writer.digest.hexdigest() or size != writer.count): + raise ImageError("trusted root serialized output identity differs") result = {"schema_version": "workstream.trusted_root.v1", **identity, **facts, - "bundle_sha256": cache.digest(bundle), "bundle_byte_count": size} - _available(deadline) + "bundle_sha256": observed_digest, "bundle_byte_count": size} + available(deadline) descriptor.write(json.dumps(result, sort_keys=True, separators=(",", ":")).encode()) for output in (bundle, descriptor): output.flush() @@ -282,9 +171,9 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) for option in ("archive", "archive-output", "config-output", "bundle-output", "descriptor-output"): parser.add_argument("--" + option, type=Path, required=True) - for option in ("repository", "manifest", "docker", "default-behavior-sha256"): + for option in ("repository", "manifest", "default-behavior-sha256"): parser.add_argument("--" + option, required=True) - for option in ("maximum-export-bytes", "maximum-root-bytes", "maximum-entries"): + for option in ("maximum-layer-bytes", "maximum-root-bytes", "maximum-entries"): parser.add_argument("--" + option, type=int, required=True) parser.add_argument("--timeout-seconds", type=float, required=True) args = vars(parser.parse_args()) diff --git a/backend/tests/test_checker_image.py b/backend/tests/test_checker_image.py index c2c56e34e..48ef553d9 100644 --- a/backend/tests/test_checker_image.py +++ b/backend/tests/test_checker_image.py @@ -494,25 +494,3 @@ def test_build_and_samples_do_not_inherit_docker_proxy_configuration(monkeypatch assert argv[argv.index("--config") + 1] == str(config) assert marker not in str(options["env"]) assert "DOCKER_CONFIG" not in options["env"] - - -def test_binary_sink_streams_output_and_still_charges_stderr(): - """Root exports use bounded storage without accumulating their bytes in RAM.""" - import io - - sink = io.BytesIO() - command = [sys.executable, "-c", "import os; os.write(1,b'root'); os.write(2,b'noise')"] - assert run(command, step="export", stdout_sink=sink, limit=9) == b"" - assert sink.getvalue() == b"root" - with pytest.raises(ImageError, match="output limit"): - run(command, step="export", stdout_sink=io.BytesIO(), limit=8) - - -def test_binary_sink_short_write_refuses_success(): - """A failed sink cannot publish a seemingly complete root export.""" - class ShortSink: - def write(self, data): - return len(data) - 1 - - with pytest.raises(ImageError, match="incomplete output"): - run([sys.executable, "-c", "print('root')"], step="export", stdout_sink=ShortSink()) diff --git a/backend/tests/test_checker_smol_cache.py b/backend/tests/test_checker_smol_cache.py index 50e8eb946..c74f9121a 100644 --- a/backend/tests/test_checker_smol_cache.py +++ b/backend/tests/test_checker_smol_cache.py @@ -271,16 +271,15 @@ def test_cli_requires_a_distinct_archive_output(tmp_path, monkeypatch, capsys): assert not (tmp_path / "config.json").exists() -def root_export(entries): - """A flattened image export, independent of contributor ZIP handling.""" +def root_layer(entries): + """Construct a layer without extracting any image path on the host.""" output = io.BytesIO() with tarfile.open(fileobj=output, mode="w") as archive: for name, kind, content in entries: item = tarfile.TarInfo(name) item.type = kind if kind == tarfile.REGTYPE: - item.size = len(content) - item.mode = 0o4755 + item.size, item.mode = len(content), 0o4755 archive.addfile(item, io.BytesIO(content)) else: if kind in {tarfile.SYMTYPE, tarfile.LNKTYPE}: @@ -290,32 +289,53 @@ def root_export(entries): return output -def test_trusted_root_bundle_normalizes_links_and_keeps_bytes(): - """Flattened hardlinks retain content; symlinks follow all file records.""" - import struct - from scripts.checker_trusted_root import MAGIC, pack_root +def layered_root(layers, *, maximum_entries=100): + import time + from scripts.checker_root_layers import apply_layer + + spool, tree, consumed = io.BytesIO(), {}, 0 + for layer in layers: + consumed += apply_layer(root_layer(layer), spool, tree, maximum_entries=maximum_entries, + remaining_entries=maximum_entries - consumed, deadline=time.monotonic() + 5) + return spool, tree + + +def root_contents(spool, tree): + result = {} + for path, entry in tree.items(): + if entry.kind == "file": + spool.seek(entry.offset) + result[path] = spool.read(entry.size) + return result + - source = root_export([ - ("usr/bin/python", tarfile.REGTYPE, b"trusted interpreter"), - ("usr/bin/python3", tarfile.LNKTYPE, "usr/bin/python"), - ("bin", tarfile.SYMTYPE, "usr/bin"), +def test_layered_root_replacements_preserve_existing_hardlink_content(): + spool, tree = layered_root([ + [("a", tarfile.REGTYPE, b"old"), ("alias", tarfile.LNKTYPE, "a")], + [("a", tarfile.REGTYPE, b"new")], ]) - output = io.BytesIO() - facts = pack_root(source, output, identity={"test": "identity"}, - maximum_entries=10, maximum_bytes=100) - output.seek(0) - assert output.read(len(MAGIC)) == MAGIC - records, files = [], {} - while raw := output.read(4): - value = json.loads(output.read(struct.unpack(">I", raw)[0])) - records.append(value) - if value["kind"] == "file": - files[value["path"]] = output.read(value["byte_count"]) - assert files == {"usr/bin/python": b"trusted interpreter", "usr/bin/python3": b"trusted interpreter"} - assert [item["kind"] for item in records] == ["identity", "directory", "directory", "file", "file", "symlink", "end"] - assert all(set(item) == {"kind", "path", "byte_count", "executable"} - for item in records if item["kind"] == "file") - assert facts == {"expanded_bytes": 38, "entries": 5} + assert root_contents(spool, tree) == {"a": b"new", "alias": b"old"} + + +@pytest.mark.parametrize("marker_first", [False, True]) +def test_whiteouts_apply_only_to_lower_layers_regardless_of_tar_order(marker_first): + addition = [("d/new", tarfile.REGTYPE, b"new")] + markers = [("d/.wh..wh..opq", tarfile.REGTYPE, b""), (".wh.old", tarfile.REGTYPE, b"")] + spool, tree = layered_root([ + [("d/old", tarfile.REGTYPE, b"old"), ("old", tarfile.REGTYPE, b"old"), + ("keep", tarfile.REGTYPE, b"keep")], + markers + addition if marker_first else addition + markers, + ]) + assert root_contents(spool, tree) == {"d/new": b"new", "keep": b"keep"} + assert not any(".wh." in name for name in tree) + + +def test_directory_replacement_removes_old_descendants_and_directory_merge_keeps_them(): + spool, tree = layered_root([ + [("d/old", tarfile.REGTYPE, b"old"), ("kept/file", tarfile.REGTYPE, b"keep")], + [("d", tarfile.REGTYPE, b"file"), ("kept", tarfile.DIRTYPE, "")], + ]) + assert root_contents(spool, tree) == {"d": b"file", "kept/file": b"keep"} @pytest.mark.parametrize("entries", [ @@ -328,140 +348,140 @@ def test_trusted_root_bundle_normalizes_links_and_keeps_bytes(): [("device", tarfile.CHRTYPE, "")], [("safe/escape", tarfile.SYMTYPE, "../../outside")], [("escape", tarfile.SYMTYPE, "/../outside")], + [(".wh.", tarfile.REGTYPE, b"")], + [(".wh...", tarfile.REGTYPE, b"")], + [(".wh.x", tarfile.REGTYPE, b"not empty")], + [(".wh.x", tarfile.SYMTYPE, "x")], ]) -def test_trusted_root_refuses_paths_special_files_and_link_ancestry(entries): - from scripts.checker_trusted_root import pack_root - +def test_trusted_layers_refuse_paths_links_whiteouts_and_special_entries(entries): with pytest.raises(ImageError): - pack_root(root_export(entries), io.BytesIO(), identity={}, maximum_entries=20, maximum_bytes=100) - + layered_root([entries]) -def test_trusted_root_charges_hardlink_expansion_and_implicit_directories(): - from scripts.checker_trusted_root import pack_root - source = [("a/b/c", tarfile.REGTYPE, b"12345"), ("copy", tarfile.LNKTYPE, "a/b/c")] - with pytest.raises(ImageError, match="hardlink expansion"): - pack_root(root_export(source), io.BytesIO(), identity={}, maximum_entries=10, maximum_bytes=9) +def test_trusted_root_charges_implicit_directories_and_replaced_entries(): with pytest.raises(ImageError, match="implicit directory"): - pack_root(root_export(source), io.BytesIO(), identity={}, maximum_entries=3, maximum_bytes=20) + layered_root([[("a/b/c", tarfile.REGTYPE, b"x")]], maximum_entries=2) + with pytest.raises(ImageError, match="aggregate entry"): + layered_root([[("a", tarfile.REGTYPE, b"old")], [("a", tarfile.REGTYPE, b"new")]], maximum_entries=1) -@pytest.mark.parametrize("defect", [None, "image", "container", "container_id", "started", "export"]) -def test_root_export_requires_exact_never_started_container_and_cleans_owned_id(monkeypatch, defect): +def test_root_bundle_rehashes_spool_and_charges_hardlink_expansion(): import time - from scripts import checker_trusted_root as root + from scripts.checker_trusted_root import pack_root - config_id, container_id = "sha256:" + "1" * 64, "2" * 64 - config = {"rootfs": {"diff_ids": ["sha256:" + "3" * 64]}} - calls, state = [], {} - - def command(argv, **kwargs): - calls.append(argv) - if argv[1:3] == ["image", "inspect"]: - return json.dumps([{"Id": "other" if defect == "image" else config_id, - "Os": "linux", "Architecture": "amd64", - "RootFS": {"Layers": config["rootfs"]["diff_ids"]}, "Config": {}}]).encode() - if argv[1] == "create": - assert "--pull=never" in argv and argv[-1] == config_id - state["token"] = argv[argv.index("--label") + 1].split("=", 1)[1] - return container_id.encode() - if argv[1:3] == ["container", "inspect"]: - return json.dumps([{"Id": "f" * 64 if defect == "container_id" else container_id, - "Image": "other" if defect == "container" else config_id, - "Config": {"Labels": {"workstream.root-provision": state["token"]}}, - "State": {"Status": "running" if defect == "started" else "created", "Running": defect == "started"}}]).encode() - if argv[1] == "export": - assert 0 < kwargs["timeout"] <= 10 - if defect == "export": - raise ImageError("export failed") - kwargs["stdout_sink"].write(b"root bytes") - elif argv[1] == "rm": - assert argv == ["docker", "rm", container_id] - else: - pytest.fail(f"unexpected Docker command {argv}") - return b"" - - monkeypatch.setattr(root, "run", command) - output = io.BytesIO() - if defect: - with pytest.raises(ImageError): - root.export_root("docker", config_id, config, output, maximum_bytes=1000, deadline=time.monotonic() + 10) - else: - root.export_root("docker", config_id, config, output, maximum_bytes=1000, deadline=time.monotonic() + 10) - assert output.getvalue() == b"root bytes" - assert not any("start" in item or "pull" in item for item in calls) - assert any(item[1] == "rm" for item in calls) == (defect in {None, "export"}) - assert any(item[1] == "export" for item in calls) == (defect in {None, "export"}) + spool, tree = layered_root([[("a", tarfile.REGTYPE, b"good"), ("b", tarfile.LNKTYPE, "a")]]) + kwargs = dict(tree=tree, identity={}, deadline=time.monotonic() + 5) + with pytest.raises(ImageError, match="expanded byte"): + pack_root(spool, io.BytesIO(), maximum_bytes=7, **kwargs) + spool.seek(0) + spool.write(b"evil") + with pytest.raises(ImageError, match="retained file identity"): + pack_root(spool, io.BytesIO(), maximum_bytes=8, **kwargs) @pytest.mark.parametrize("failure", [False, True]) -def test_trusted_root_publication_binds_verified_graph_and_removes_partial_bundle(tmp_path, monkeypatch, failure): - from scripts import checker_trusted_root as root +def test_root_publication_uses_only_approved_layers_and_removes_partial_bundle(tmp_path, monkeypatch, failure): + import subprocess + from scripts.checker_trusted_root import provision_root archive, manifest, config_id = bundle(tmp_path, volumes=False) - def export(docker, selected_id, config, sink, **kwargs): - assert selected_id == config_id - assert config["rootfs"]["diff_ids"] - sink.write(root_export([("python", tarfile.REGTYPE, b"trusted")]).read()) - monkeypatch.setattr(root, "export_root", export) + def no_process(*args, **kwargs): + pytest.fail("verified-layer provisioning invoked a filesystem materializer") + monkeypatch.setattr(subprocess, "Popen", no_process) kwargs = dict(archive_output=tmp_path / "cache.tar", config_output=tmp_path / "config.json", bundle_output=tmp_path / "root.bundle", descriptor_output=tmp_path / "root.json", - docker="docker", default_behavior_sha256=sha(b"behavior"), - maximum_export_bytes=100000, maximum_root_bytes=1 if failure else 100, - maximum_entries=10, timeout_seconds=5) + default_behavior_sha256=sha(b"behavior"), maximum_layer_bytes=100000, + maximum_root_bytes=1 if failure else 100, maximum_entries=10, timeout_seconds=5) if failure: with pytest.raises(ImageError, match="expanded byte limit"): - root.provision_root(archive, "trusted/intake", manifest, **kwargs) + provision_root(archive, "trusted/intake", manifest, **kwargs) assert not kwargs["bundle_output"].exists() assert not kwargs["descriptor_output"].exists() else: - receipt = root.provision_root(archive, "trusted/intake", manifest, **kwargs) + receipt = provision_root(archive, "trusted/intake", manifest, **kwargs) assert receipt["config_image_id"] == config_id assert receipt["platform_manifest_digest"] == manifest assert receipt["bundle_sha256"] == sha(kwargs["bundle_output"].read_bytes()) - assert receipt["bundle_byte_count"] == kwargs["bundle_output"].stat().st_size + assert b"verified filesystem layer" in kwargs["bundle_output"].read_bytes() assert json.loads(kwargs["descriptor_output"].read_bytes()) == receipt assert kwargs["bundle_output"].stat().st_mode & 0o777 == 0o400 -def test_uncertain_root_container_creation_discovers_exact_owned_id_for_cleanup(monkeypatch): +def test_layer_deadline_applies_before_parsing(): import time - from scripts import checker_trusted_root as root + from scripts.checker_root_layers import apply_layer + + with pytest.raises(ImageError, match="deadline"): + apply_layer(root_layer([("python", tarfile.REGTYPE, b"trusted")]), io.BytesIO(), {}, + maximum_entries=10, remaining_entries=10, deadline=time.monotonic() - 1) + - image_id, container_id = sha(b"image"), "a" * 64 - diff_ids = [sha(b"layer")] - state, calls = {}, [] - def command(argv, **kwargs): - calls.append(argv) - if argv[1:3] == ["image", "inspect"]: - return json.dumps([{"Id": image_id, "Os": "linux", "Architecture": "amd64", - "RootFS": {"Layers": diff_ids}, "Config": {}}]).encode() - if argv[1] == "create": - state["token"] = argv[argv.index("--label") + 1].split("=", 1)[1] - state["name"] = argv[argv.index("--name") + 1] - raise ImageError("create acknowledgement lost") - if argv[1] == "ps": - assert "name=^/" + state["name"] + "$" in argv - assert "label=workstream.root-provision=" + state["token"] in argv - return container_id.encode() - if argv[1:3] == ["container", "inspect"]: - assert argv[-1] == container_id - return json.dumps([{"Id": container_id, "Image": image_id, "State": {"Status": "created", "Running": False}, - "Config": {"Labels": {"workstream.root-provision": state["token"]}}}]).encode() - assert argv == ["docker", "rm", container_id] - return b"" - monkeypatch.setattr(root, "run", command) - with pytest.raises(ImageError, match="acknowledgement lost"): - root.export_root("docker", image_id, {"rootfs": {"diff_ids": diff_ids}}, io.BytesIO(), - maximum_bytes=100, deadline=time.monotonic() + 10) - assert calls[-1] == ["docker", "rm", container_id] - assert not any(item[1] == "export" for item in calls) - - -def test_root_pack_cannot_publish_after_deadline(): +@pytest.mark.parametrize("compressed", [False, True]) +def test_verified_root_is_deterministic_and_layer_expansion_is_bounded(tmp_path, compressed): + from scripts.checker_trusted_root import provision_root + + archive, manifest, _ = bundle(tmp_path, compressed=compressed, volumes=False) + def build(prefix, maximum=100000): + return provision_root(archive, "trusted/intake", manifest, + archive_output=tmp_path / (prefix + ".tar"), config_output=tmp_path / (prefix + ".config"), + bundle_output=tmp_path / (prefix + ".bundle"), descriptor_output=tmp_path / (prefix + ".json"), + default_behavior_sha256=sha(b"behavior"), maximum_layer_bytes=maximum, + maximum_root_bytes=100, maximum_entries=10, timeout_seconds=5) + first, second = build("one"), build("two") + assert first == second + assert (tmp_path / "one.bundle").read_bytes() == (tmp_path / "two.bundle").read_bytes() + with pytest.raises(ImageError, match="verification byte limit"): + build("limited", maximum=1024) + assert not (tmp_path / "limited.bundle").exists() + assert not (tmp_path / "limited.tar").exists() + + +def test_trusted_layer_rejects_content_hidden_after_tar_end_and_missing_trailer(): import time - from scripts.checker_trusted_root import pack_root + from scripts.checker_root_layers import apply_layer - with pytest.raises(ImageError, match="deadline"): - pack_root(root_export([("python", tarfile.REGTYPE, b"trusted")]), io.BytesIO(), - identity={}, maximum_entries=10, maximum_bytes=100, deadline=time.monotonic() - 1) + raw = root_layer([("a", tarfile.REGTYPE, b"data")]).getvalue() + for changed in [raw + b"hidden", raw[:1024]]: + with pytest.raises(ImageError, match="trai|unexpected end"): + apply_layer(io.BytesIO(changed), io.BytesIO(), {}, maximum_entries=10, + remaining_entries=10, deadline=time.monotonic() + 5) + + +@pytest.mark.parametrize("mutation", ["layer_spool", "serialized_file"]) +def test_changed_materialization_cannot_be_published_under_the_same_image_identity(tmp_path, monkeypatch, mutation): + """The real daemon mismatch must not recur at an intermediate local boundary.""" + from scripts import checker_root_layers as layers + from scripts import checker_trusted_root as root + + archive, manifest, _ = bundle(tmp_path, volumes=False) + if mutation == "layer_spool": + original = layers.apply_layer + def changed(layer, *args, **kwargs): + result = original(layer, *args, **kwargs) + layer.seek(512) + layer.write(b"X") + return result + monkeypatch.setattr(layers, "apply_layer", changed) + reason = "layer spool identity" + else: + original = root.pack_root + def changed(spool, writer, **kwargs): + result = original(spool, writer, **kwargs) + writer.output.flush() + writer.output.seek(0) + data = writer.output.read() + offset = data.index(b"verified filesystem layer") + writer.output.seek(offset) + writer.output.write(b"X") + writer.output.seek(len(data)) + return result + monkeypatch.setattr(root, "pack_root", changed) + reason = "serialized output identity" + with pytest.raises(ImageError, match=reason): + root.provision_root(archive, "trusted/intake", manifest, + archive_output=tmp_path / "cache.tar", config_output=tmp_path / "config.json", + bundle_output=tmp_path / "root.bundle", descriptor_output=tmp_path / "root.json", + default_behavior_sha256=sha(b"behavior"), maximum_layer_bytes=100000, + maximum_root_bytes=100, maximum_entries=10, timeout_seconds=5) + assert not (tmp_path / "root.bundle").exists() + assert not (tmp_path / "root.json").exists() diff --git a/external_checkers/README.md b/external_checkers/README.md index 733b75f6c..bb9e3b6ef 100644 --- a/external_checkers/README.md +++ b/external_checkers/README.md @@ -466,29 +466,28 @@ root for the single-session PRE supervisor under development. This command and the guest bundle reader do not yet replace the current submission PRE flow or establish native runtime qualification. -Live verification found that daemon-exported file contents can differ from the -verified source archive despite matching image metadata. This development -provisioner is not ready for execution use; its export step is being replaced -with construction from the verified layers. The bundle-reader guarantees below -authenticate bundle bytes, not the daemon's claimed provenance. - -The command first verifies the approved local image graph with the existing Smol -cache provisioner. A trusted offline Docker daemon must already contain that -exact config image ID. It checks the platform and ordered layer identities, -creates a container with pulling disabled, verifies its exact image and created -state, exports without starting it, and removes the owned container. Images with -volumes are refused. The daemon is build infrastructure; it is not used for PRE -execution, and no submission bytes enter this provisioning path. +The command constructs its root directly from the approved local image graph +validated by the existing Smol cache provisioner. Docker-exported files are not +used: live verification demonstrated changed file bytes behind an unchanged +Docker image ID. Ordered layers supply exact content, regular hardlink identities, +whiteouts and replacements. A restricted platform profile rejects unsupported +entries and ambiguous link ancestry instead of treating this as a generic image +extractor. Files are held in a bounded private byte spool, never extracted to +host paths, and rehashed while writing the final bundle. Run the module from `backend/` with `--archive`, `--repository`, `--manifest`, `--archive-output` and `--config-output` as for the cache command. Also supply -new `--bundle-output` and `--descriptor-output` paths, `--docker`, -`--default-behavior-sha256`, `--maximum-export-bytes`, `--maximum-root-bytes`, -`--maximum-entries`, and `--timeout-seconds`. All bounds and identities are -explicit; the command does not choose deployment values. Keep the emitted -bundle and descriptor operator-controlled and pin their identities independently -before use. Completed cache files may remain if later bundle provisioning fails; -a partial bundle/descriptor never establishes readiness. +new `--bundle-output` and `--descriptor-output` paths, +`--default-behavior-sha256`, `--maximum-layer-bytes`, `--maximum-root-bytes`, +`--maximum-entries`, and `--timeout-seconds`. Bounds and identities are explicit; +the command does not choose deployment values. The layer byte limit bounds +aggregate expansion per verification pass, including both selected and approved +layer representations; it also bounds the private content spool. Entry limits +include replaced layer entries and implicit final directories. Temporary storage +must accommodate the verified cache, one bounded expanded layer, the content +spool and output bundle. Keep emitted artifacts operator-controlled and pin their +identities independently before use. Completed cache files may remain if later +bundle provisioning fails; a partial bundle/descriptor never establishes readiness. The `WSROOT1` format carries bounded closed JSON records and inline regular-file bytes. Hard links become independently charged file content; symlinks are From 59295941093d91a4f239a649190393c588160c5f Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 10:25:04 +0100 Subject: [PATCH 041/513] Bound image archive scans and validate physical layer extension headers --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 21 ++++ backend/scripts/checker_root_layers.py | 79 +++++++++++- backend/scripts/checker_smol_cache.py | 33 ++++-- backend/scripts/checker_trusted_root.py | 12 +- backend/tests/test_checker_smol_cache.py | 112 +++++++++++++++++- external_checkers/README.md | 10 +- 6 files changed, 240 insertions(+), 27 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 58837e278..0c034273a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -892,3 +892,24 @@ the canonical archive's correct hash rather than the daemon's altered bytes. This validates the corrected content source, not native PRE isolation. The existing single-request integration, combined supervisor and native runtime qualification remain outstanding. + +The next review identified two pre-parser bounds gaps. The outer archive scan +could read an arbitrarily long zero trailer before reaching guarded graph work, +and `tarfile` consumed PAX headers before the logical entry counter. The root +command now requires `maximum_archive_bytes` for both original and prepared +archives; preflight, member reads, cache copy and hashing share the deadline. +Raw layer preflight charges every physical header before parsing and accepts only +one local PAX path/linkpath envelope, at most 16 KiB, followed by a supported +entry. Other attributes, global/stacked/dangling envelopes and oversized payloads +are refused before `tarfile` interpretation. The real pinned image contains +579 such local headers, only path/linkpath keys, with a largest payload of +281 bytes, so this is an exercised restricted profile rather than an assumed one. + +The repaired checks passed 264 tests. Updated extension regressions against +pre-repair `982417ab3` failed all eight unsafe/count cases while retaining the +ordinary-layer control. Disabling outer bounds made both outer-archive +regressions fail. A real repaired construction completed in 86.10 seconds and +retained the same canonical bundle digest and counts; no daemon materialization +or deployment configuration default was added. The unchanged guest reader and +in-chroot Python successfully load the canonical urllib3, archive inspector and +the existing default behavior identity from that root. diff --git a/backend/scripts/checker_root_layers.py b/backend/scripts/checker_root_layers.py index 8a6f54c93..d4e94228a 100644 --- a/backend/scripts/checker_root_layers.py +++ b/backend/scripts/checker_root_layers.py @@ -16,6 +16,72 @@ from scripts import checker_smol_cache as cache from scripts.checker_image_process import ImageError +MAX_PAX_BYTES = 16384 + + +def _pax_paths(payload): + """Accept only bounded path overrides needed by the pinned platform image.""" + offset, keys = 0, set() + while offset < len(payload): + separator = payload.find(b" ", offset) + digits = payload[offset:separator] + if separator < 0 or not digits.isdigit() or len(digits) > 5: + raise ImageError("trusted layer PAX record invalid") + length = int(digits) + end = offset + length + if str(length).encode() != digits or end > len(payload) or end <= separator + 2: + raise ImageError("trusted layer PAX length invalid") + record = payload[separator + 1:end] + if not record.endswith(b"\n"): + raise ImageError("trusted layer PAX record truncated") + key, separator_bytes, value = record[:-1].partition(b"=") + if key not in {b"path", b"linkpath"} or key in keys or not separator_bytes: + raise ImageError("trusted layer PAX attribute unsupported") + text = value.decode("utf-8", "strict") + if not text or len(value) > 4096 or "\0" in text: + raise ImageError("trusted layer PAX path invalid") + keys.add(key) + offset = end + + +def preflight_layer(source, remaining_entries, deadline): + """Bound physical headers and extension payloads before tarfile interprets them.""" + source.seek(0, os.SEEK_END) + length, offset, count, pending = source.tell(), 0, 0, False + if not length or length % 512: + raise ImageError("trusted layer length invalid") + while offset + 512 <= length: + available(deadline) + source.seek(offset) + raw = source.read(512) + if not any(raw): + if pending or length - offset < 1024: + raise ImageError("trusted layer trailer truncated") + source.seek(offset) + while chunk := source.read(65536): + available(deadline) + if any(chunk): + raise ImageError("trusted layer trailing content invalid") + available(deadline) + return count + count += 1 + if count > remaining_entries: + raise ImageError("trusted layer aggregate entry limit exceeded") + item = tarfile.TarInfo.frombuf(raw, "utf-8", "strict") + if item.size < 0 or offset + 512 + ((item.size + 511) // 512) * 512 > length: + raise ImageError("trusted layer entry exceeds input") + if item.type == tarfile.XHDTYPE: + if pending or not 0 < item.size <= MAX_PAX_BYTES: + raise ImageError("trusted layer PAX envelope invalid") + _pax_paths(source.read(item.size)) + pending = True + elif item.type in {tarfile.REGTYPE, tarfile.AREGTYPE, tarfile.DIRTYPE, tarfile.SYMTYPE, tarfile.LNKTYPE}: + pending = False + else: + raise ImageError("trusted layer header type unsupported") + offset += 512 + ((item.size + 511) // 512) * 512 + raise ImageError("trusted layer trailer missing") + def available(deadline): if time.monotonic() >= deadline: @@ -124,8 +190,10 @@ def _layer_entries(layer, remaining_entries, deadline): def apply_layer(layer_file, spool, tree, *, maximum_entries, remaining_entries, deadline): """Apply lower-layer deletion first, then additions in their declared order.""" + count = preflight_layer(layer_file, remaining_entries, deadline) + layer_file.seek(0) with tarfile.open(fileobj=layer_file, mode="r:") as layer: - entries, whiteouts, count = _layer_entries(layer, remaining_entries, deadline) + entries, whiteouts, _ = _layer_entries(layer, remaining_entries, deadline) for target, opaque in whiteouts: available(deadline) _parents(tree, target + "/marker" if opaque and target else target) @@ -164,9 +232,10 @@ def apply_layer(layer_file, spool, tree, *, maximum_entries, remaining_entries, def construct_root(source, spool, *, manifest_digest, config_image_id, - maximum_layer_bytes, maximum_entries, deadline): + maximum_archive_bytes, maximum_layer_bytes, maximum_entries, deadline): """Reverify the graph and each consumed layer before returning its final inventory.""" - members = cache._preflight(source, os.fstat(source.fileno()).st_size) + members = cache._preflight(source, os.fstat(source.fileno()).st_size, + maximum_bytes=maximum_archive_bytes, deadline=deadline) _, config_id, raw_config, wrapper, expected = cache._graph( source, members, manifest_digest, maximum_layer_bytes=maximum_layer_bytes, deadline=deadline) if config_id != config_image_id: @@ -176,9 +245,9 @@ def construct_root(source, spool, *, manifest_digest, config_image_id, tree, expanded, count = {}, 0, 0 for name, diff_id in zip(layers, diff_ids, strict=True): available(deadline) - raw = cache.MemberReader(source, members[name]) + raw = cache.MemberReader(source, members[name], deadline) magic = raw.read(2) - raw = cache.MemberReader(source, members[name]) + raw = cache.MemberReader(source, members[name], deadline) reader = gzip.GzipFile(fileobj=raw) if magic == b"\x1f\x8b" else raw digest = hashlib.sha256() with tempfile.TemporaryFile() as layer: diff --git a/backend/scripts/checker_smol_cache.py b/backend/scripts/checker_smol_cache.py index 4e90fe442..c45c8a058 100644 --- a/backend/scripts/checker_smol_cache.py +++ b/backend/scripts/checker_smol_cache.py @@ -56,15 +56,20 @@ class Member: class MemberReader: """Read one preflighted regular member without interpreting tar extensions.""" - def __init__(self, source, member: Member): + def __init__(self, source, member: Member, deadline=None): self.source, self.member, self.position = source, member, 0 + self.deadline = deadline self.hash = hashlib.sha256() def read(self, size=-1): + if self.deadline is not None and time.monotonic() >= self.deadline: + raise ImageError("image member deadline exceeded") remaining = self.member.size - self.position size = remaining if size < 0 else min(size, remaining) self.source.seek(self.member.offset + self.position) data = self.source.read(size) + if self.deadline is not None and time.monotonic() >= self.deadline: + raise ImageError("image member deadline exceeded") if len(data) != size: raise ImageError("image member changed while reading") self.position += len(data) @@ -93,13 +98,17 @@ def _path(name: str) -> None: raise ImageError("noncanonical archive path") -def _preflight(source, length: int) -> dict[str, Member]: +def _preflight(source, length: int, *, maximum_bytes=None, deadline=None) -> dict[str, Member]: """Bound raw headers before any tar parser can consume extension metadata.""" if not length or length % BLOCK: raise ImageError("invalid archive length") + if maximum_bytes is not None and length > maximum_bytes: + raise ImageError("image archive byte limit exceeded") files, directories, ancestors = {}, set(), set() offset = count = 0 while offset + BLOCK <= length: + if deadline is not None and time.monotonic() >= deadline: + raise ImageError("image archive preflight deadline exceeded") source.seek(offset) header = source.read(BLOCK) if len(header) != BLOCK: @@ -110,10 +119,14 @@ def _preflight(source, length: int) -> dict[str, Member]: source.seek(offset) remaining = length - offset while remaining: + if deadline is not None and time.monotonic() >= deadline: + raise ImageError("image archive preflight deadline exceeded") chunk = source.read(min(remaining, 1024 * 1024)) if not chunk or any(chunk): raise ImageError("archive trailer contains data") remaining -= len(chunk) + if deadline is not None and time.monotonic() >= deadline: + raise ImageError("image archive preflight deadline exceeded") return files count += 1 if count > MAX_HEADERS: @@ -165,7 +178,7 @@ def unique(pairs): def _graph(source, members, manifest_digest, *, maximum_layer_bytes=None, deadline=None): def regular(name): _path(name) - return MemberReader(source, members[name]) + return MemberReader(source, members[name], deadline) def metadata(name, maximum=MAX_METADATA): if not 0 < members[name].size <= maximum: @@ -255,8 +268,8 @@ def _tar_info(name, size): return info -def _copy_member(bundle, source, name, member, expected_digest): - reader = MemberReader(source, member) +def _copy_member(bundle, source, name, member, expected_digest, deadline=None): + reader = MemberReader(source, member, deadline) bundle.addfile(_tar_info(name, member.size), reader) if reader.position != member.size or "sha256:" + reader.hash.hexdigest() != expected_digest: raise ImageError("source image graph changed during copy") @@ -264,7 +277,7 @@ def _copy_member(bundle, source, name, member, expected_digest): def provision(archive: Path, repository: str, manifest_digest: str, *, archive_output: Path, config_output: Path, - maximum_layer_bytes=None, deadline=None) -> dict: + maximum_layer_bytes=None, maximum_archive_bytes=None, deadline=None) -> dict: created = [] try: if DIGEST.fullmatch(manifest_digest) is None: @@ -279,7 +292,7 @@ def provision(archive: Path, repository: str, manifest_digest: str, *, if not stat.S_ISREG(before.st_mode): raise ImageError("source archive is not regular") identity = _identity(before) - members = _preflight(source, before.st_size) + members = _preflight(source, before.st_size, maximum_bytes=maximum_archive_bytes, deadline=deadline) manifest, config_id, raw_config, wrapper, expected = _graph( source, members, manifest_digest, maximum_layer_bytes=maximum_layer_bytes, deadline=deadline) for name in expected: @@ -289,7 +302,9 @@ def provision(archive: Path, repository: str, manifest_digest: str, *, with tarfile.open(fileobj=cache, mode="w", format=tarfile.USTAR_FORMAT) as bundle: bundle.addfile(_tar_info("manifest.json", len(wrapper)), io.BytesIO(wrapper)) for name in sorted(expected): - _copy_member(bundle, source, name, members[name], expected[name]) + _copy_member(bundle, source, name, members[name], expected[name], deadline) + if maximum_archive_bytes is not None and cache.tell() > maximum_archive_bytes: + raise ImageError("prepared image archive byte limit exceeded") # This body is the same approved config copied and rehashed above. config.write(raw_config) _unchanged(source, archive, identity) @@ -298,7 +313,7 @@ def provision(archive: Path, repository: str, manifest_digest: str, *, os.fchmod(output.fileno(), 0o400) os.fsync(output.fileno()) cache.seek(0) - archive_digest = digest(cache) + archive_digest = digest(cache, deadline=deadline) for path, device, inode in created: current = path.lstat() if (current.st_dev, current.st_ino) != (device, inode): diff --git a/backend/scripts/checker_trusted_root.py b/backend/scripts/checker_trusted_root.py index 63d2f5ff8..12645c425 100644 --- a/backend/scripts/checker_trusted_root.py +++ b/backend/scripts/checker_trusted_root.py @@ -86,11 +86,11 @@ def pack_root(spool, output, *, tree, identity, maximum_bytes, deadline): def provision_root(archive: Path, repository: str, manifest_digest: str, *, archive_output: Path, config_output: Path, bundle_output: Path, descriptor_output: Path, default_behavior_sha256: str, - maximum_layer_bytes: int, maximum_root_bytes: int, + maximum_archive_bytes: int, maximum_layer_bytes: int, maximum_root_bytes: int, maximum_entries: int, timeout_seconds: float): """Bind an exclusive sealed runtime bundle to the already verified image graph.""" if (any(type(value) is not int or value <= 0 for value in - (maximum_layer_bytes, maximum_root_bytes, maximum_entries)) + (maximum_archive_bytes, maximum_layer_bytes, maximum_root_bytes, maximum_entries)) or not 0 < timeout_seconds <= 7200 or cache.DIGEST.fullmatch(default_behavior_sha256) is None): raise ImageError("trusted root provisioning limits invalid") @@ -101,7 +101,8 @@ def provision_root(archive: Path, repository: str, manifest_digest: str, *, deadline = time.monotonic() + timeout_seconds receipt = cache.provision(archive, repository, manifest_digest, archive_output=archive_output, config_output=config_output, - maximum_layer_bytes=maximum_layer_bytes, deadline=deadline) + maximum_layer_bytes=maximum_layer_bytes, + maximum_archive_bytes=maximum_archive_bytes, deadline=deadline) identity = {"platform_manifest_digest": manifest_digest, "config_image_id": receipt["config_image_id"], "default_behavior_sha256": default_behavior_sha256} @@ -112,12 +113,15 @@ def provision_root(archive: Path, repository: str, manifest_digest: str, *, metadata = os.fstat(source.fileno()) if not stat.S_ISREG(metadata.st_mode): raise ImageError("trusted root cache is not regular") + if metadata.st_size > maximum_archive_bytes: + raise ImageError("trusted root cache byte limit exceeded") original = cache._identity(metadata) if cache.digest(source, deadline=deadline) != receipt["smol"]["archive_sha256"]: raise ImageError("trusted root source cache changed") source.seek(0) tree = construct_root(source, spool, manifest_digest=manifest_digest, config_image_id=receipt["config_image_id"], + maximum_archive_bytes=maximum_archive_bytes, maximum_layer_bytes=maximum_layer_bytes, maximum_entries=maximum_entries, deadline=deadline) with cache._output_files(paths[2:], created) as (bundle, descriptor): @@ -173,7 +177,7 @@ def main(): parser.add_argument("--" + option, type=Path, required=True) for option in ("repository", "manifest", "default-behavior-sha256"): parser.add_argument("--" + option, required=True) - for option in ("maximum-layer-bytes", "maximum-root-bytes", "maximum-entries"): + for option in ("maximum-archive-bytes", "maximum-layer-bytes", "maximum-root-bytes", "maximum-entries"): parser.add_argument("--" + option, type=int, required=True) parser.add_argument("--timeout-seconds", type=float, required=True) args = vars(parser.parse_args()) diff --git a/backend/tests/test_checker_smol_cache.py b/backend/tests/test_checker_smol_cache.py index c74f9121a..fffe1fe80 100644 --- a/backend/tests/test_checker_smol_cache.py +++ b/backend/tests/test_checker_smol_cache.py @@ -228,7 +228,7 @@ def test_copy_rehash_rejects_source_mutation_after_validation(tmp_path, monkeypa archive, manifest, _ = bundle(tmp_path) copy = cache._copy_member changed = False - def substitute(bundle, source, name, member, expected): + def substitute(bundle, source, name, member, expected, deadline=None): nonlocal changed if not changed: with archive.open("r+b") as attacker: @@ -237,7 +237,7 @@ def substitute(bundle, source, name, member, expected): attacker.seek(member.offset) attacker.write(bytes([original[0] ^ 1])) changed = True - copy(bundle, source, name, member, expected) + copy(bundle, source, name, member, expected, deadline) monkeypatch.setattr(cache, "_copy_member", substitute) with pytest.raises(ImageError, match="changed during copy"): prepare(archive, manifest, tmp_path) @@ -390,7 +390,7 @@ def no_process(*args, **kwargs): monkeypatch.setattr(subprocess, "Popen", no_process) kwargs = dict(archive_output=tmp_path / "cache.tar", config_output=tmp_path / "config.json", bundle_output=tmp_path / "root.bundle", descriptor_output=tmp_path / "root.json", - default_behavior_sha256=sha(b"behavior"), maximum_layer_bytes=100000, + default_behavior_sha256=sha(b"behavior"), maximum_archive_bytes=1000000, maximum_layer_bytes=100000, maximum_root_bytes=1 if failure else 100, maximum_entries=10, timeout_seconds=5) if failure: with pytest.raises(ImageError, match="expanded byte limit"): @@ -425,7 +425,7 @@ def build(prefix, maximum=100000): return provision_root(archive, "trusted/intake", manifest, archive_output=tmp_path / (prefix + ".tar"), config_output=tmp_path / (prefix + ".config"), bundle_output=tmp_path / (prefix + ".bundle"), descriptor_output=tmp_path / (prefix + ".json"), - default_behavior_sha256=sha(b"behavior"), maximum_layer_bytes=maximum, + default_behavior_sha256=sha(b"behavior"), maximum_archive_bytes=1000000, maximum_layer_bytes=maximum, maximum_root_bytes=100, maximum_entries=10, timeout_seconds=5) first, second = build("one"), build("two") assert first == second @@ -442,7 +442,7 @@ def test_trusted_layer_rejects_content_hidden_after_tar_end_and_missing_trailer( raw = root_layer([("a", tarfile.REGTYPE, b"data")]).getvalue() for changed in [raw + b"hidden", raw[:1024]]: - with pytest.raises(ImageError, match="trai|unexpected end"): + with pytest.raises(ImageError, match="length|trai|unexpected end"): apply_layer(io.BytesIO(changed), io.BytesIO(), {}, maximum_entries=10, remaining_entries=10, deadline=time.monotonic() + 5) @@ -481,7 +481,107 @@ def changed(spool, writer, **kwargs): root.provision_root(archive, "trusted/intake", manifest, archive_output=tmp_path / "cache.tar", config_output=tmp_path / "config.json", bundle_output=tmp_path / "root.bundle", descriptor_output=tmp_path / "root.json", - default_behavior_sha256=sha(b"behavior"), maximum_layer_bytes=100000, + default_behavior_sha256=sha(b"behavior"), maximum_archive_bytes=1000000, maximum_layer_bytes=100000, maximum_root_bytes=100, maximum_entries=10, timeout_seconds=5) assert not (tmp_path / "root.bundle").exists() assert not (tmp_path / "root.json").exists() + + +def test_outer_archive_bound_and_deadline_apply_before_zero_trailer_reads(tmp_path): + import time + + class Unreadable(io.BytesIO): + def read(self, *args): + pytest.fail("preflight read beyond its admitted size/deadline") + with pytest.raises(ImageError, match="archive byte limit"): + cache._preflight(Unreadable(), 1024 * 1024 * 1024, maximum_bytes=1024) + with pytest.raises(ImageError, match="preflight deadline"): + cache._preflight(Unreadable(), 1024, maximum_bytes=1024, deadline=time.monotonic() - 1) + class ExpiringTrailer(io.BytesIO): + def read(self, size=-1): + result = super().read(size) + time.sleep(0.01) + return result + with pytest.raises(ImageError, match="preflight deadline"): + cache._preflight(ExpiringTrailer(b"\0" * 2048), 2048, + maximum_bytes=2048, deadline=time.monotonic() + 0.005) + + +def test_root_outer_bound_rejects_padding_before_any_cache_publication(tmp_path): + from scripts.checker_trusted_root import provision_root + + archive, manifest, _ = bundle(tmp_path) + original_size = archive.stat().st_size + with archive.open("ab") as output: + output.write(b"\0" * 10240) + with pytest.raises(ImageError, match="archive byte limit"): + provision_root(archive, "trusted/intake", manifest, + archive_output=tmp_path / "cache.tar", config_output=tmp_path / "config.json", + bundle_output=tmp_path / "root.bundle", descriptor_output=tmp_path / "root.json", + default_behavior_sha256=sha(b"behavior"), maximum_archive_bytes=original_size, + maximum_layer_bytes=100000, maximum_root_bytes=100, maximum_entries=10, timeout_seconds=5) + assert not (tmp_path / "cache.tar").exists() + assert not (tmp_path / "root.bundle").exists() + + +def pax_layer(attributes): + output = io.BytesIO() + with tarfile.open(fileobj=output, mode="w", format=tarfile.PAX_FORMAT) as archive: + item = tarfile.TarInfo("placeholder") + item.pax_headers, item.size = attributes, 4 + archive.addfile(item, io.BytesIO(b"code")) + output.seek(0) + return output + + +def test_pax_path_override_is_supported_and_each_physical_header_is_charged(): + import time + from scripts.checker_root_layers import apply_layer + + spool, tree = io.BytesIO(), {} + count = apply_layer(pax_layer({"path": "usr/é.py"}), spool, tree, maximum_entries=2, + remaining_entries=2, deadline=time.monotonic() + 5) + assert count == 2 + assert root_contents(spool, tree) == {"usr/é.py": b"code"} + with pytest.raises(ImageError, match="aggregate entry limit"): + apply_layer(pax_layer({"path": "usr/é.py"}), io.BytesIO(), {}, maximum_entries=2, + remaining_entries=1, deadline=time.monotonic() + 5) + + +@pytest.mark.parametrize("attributes", [ + {"comment": "surprise"}, {"size": "4"}, {"GNU.sparse.name": "a"}, + {"path": "a" * 17000}, +]) +def test_unsupported_or_oversized_pax_is_refused_before_tarfile_interpretation(monkeypatch, attributes): + import time + from scripts.checker_root_layers import apply_layer + + source = pax_layer(attributes) + def forbidden(*args, **kwargs): + pytest.fail("tarfile interpreted unsupported extension metadata") + monkeypatch.setattr(tarfile, "open", forbidden) + with pytest.raises(ImageError, match="PAX"): + apply_layer(source, io.BytesIO(), {}, maximum_entries=10, + remaining_entries=10, deadline=time.monotonic() + 5) + + +@pytest.mark.parametrize("kind", ["stacked", "global", "dangling"]) +def test_pax_envelopes_cannot_stack_or_escape_the_next_entry(monkeypatch, kind): + import time + from scripts.checker_root_layers import apply_layer + + raw = pax_layer({"path": "renamed"}).getvalue() + if kind == "stacked": + raw = raw[:1024] + raw + elif kind == "dangling": + raw = raw[:1024] + b"\0" * 1024 + else: + header = tarfile.TarInfo.frombuf(raw[:512], "utf-8", "strict") + header.type = tarfile.XGLTYPE + raw = header.tobuf(format=tarfile.USTAR_FORMAT) + raw[512:] + def forbidden(*args, **kwargs): + pytest.fail("tarfile interpreted an invalid extension envelope") + monkeypatch.setattr(tarfile, "open", forbidden) + with pytest.raises(ImageError, match="PAX|trailer|header type"): + apply_layer(io.BytesIO(raw), io.BytesIO(), {}, maximum_entries=10, + remaining_entries=10, deadline=time.monotonic() + 5) diff --git a/external_checkers/README.md b/external_checkers/README.md index bb9e3b6ef..24d234f80 100644 --- a/external_checkers/README.md +++ b/external_checkers/README.md @@ -478,12 +478,16 @@ host paths, and rehashed while writing the final bundle. Run the module from `backend/` with `--archive`, `--repository`, `--manifest`, `--archive-output` and `--config-output` as for the cache command. Also supply new `--bundle-output` and `--descriptor-output` paths, -`--default-behavior-sha256`, `--maximum-layer-bytes`, `--maximum-root-bytes`, +`--default-behavior-sha256`, `--maximum-archive-bytes`, `--maximum-layer-bytes`, `--maximum-root-bytes`, `--maximum-entries`, and `--timeout-seconds`. Bounds and identities are explicit; -the command does not choose deployment values. The layer byte limit bounds +the command does not choose deployment values. The archive byte limit bounds +both the source archive and prepared cache, including zero padding. The layer byte limit bounds aggregate expansion per verification pass, including both selected and approved layer representations; it also bounds the private content spool. Entry limits -include replaced layer entries and implicit final directories. Temporary storage +include replaced layer entries, physical extension headers and implicit final +directories. A raw-header pass admits only one bounded local PAX path/linkpath +override before a supported entry; global, stacked, size-changing and +other extension semantics are refused before the tar parser runs. Temporary storage must accommodate the verified cache, one bounded expanded layer, the content spool and output bundle. Keep emitted artifacts operator-controlled and pin their identities independently before use. Completed cache files may remain if later From 03a09b3538b209f7ba09a05acbfe601fa76f148f Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 10:39:23 +0100 Subject: [PATCH 042/513] Define source-bound single-session PRE integration and proof boundaries --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0c034273a..3c5e11cb2 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -913,3 +913,121 @@ retained the same canonical bundle digest and counts; no daemon materialization or deployment configuration default was added. The unchanged guest reader and in-chroot Python successfully load the canonical urllib3, archive inspector and the existing default behavior identity from that root. + +## Next bounded change: source-bound single-session PRE + +Risk: L0 (untrusted archive/project code, process isolation, immutable execution +identity). This change connects the verified platform root to the execution +path. It is not complete when only new types or a standalone worker pass tests. +Its reviewable outcome is one typed `execute_pre` call that streams one sealed +source into one guest, runs canonical defaults there, conditionally runs the +selected project there, and returns independently verifiable combined evidence. +The public submission cutover and accepted transaction remain later work in this +same PR; no intermediate implementation is a merge milestone. + +### Inspected constraints and replacement decisions + +- `SelectedPreSubmitReservationFacts` and its database row currently require + prepared generation, manifest and default-input digests before execution. + They cannot represent T3's source-first reservation. Evolve this existing + CHECKERS owner and row; never substitute an operation UUID into a prepared + generation field or create a second PRE job owner. +- Python external identity/material contracts and the Rust SDK both require + prepared generation today. Replace that PRE custody with operation/run/source + identity together with affected builders, validators and fixtures. POST's + submission/binding identity remains distinct. Retained historical row values + remain data; they are not authority for new source-bound invocations. +- `IntakeWorker` currently requires inspect -> host export -> default. Replace + its PRE sequence with guest-local inspect -> derive -> default. Trace and + preserve POST's currently shared inspection/export consumer until its own + retained-source replacement; do not add an alternative PRE export path. +- ART's `_projected_tree` closes its sealed in-memory content at context exit; + the projected directory is separate from that content snapshot. Keep the + trusted projection lifetime through project execution and let the supervisor + own workspace teardown. Do not infer byte identity from directory existence. +- The current guest mounts the project image as root and has one hard-coded + workload cgroup. A combined purpose must stage the approved platform bundle + in a private supervisor directory, chroot the platform worker into it, and + keep project execution in the approved project root. Separate mount namespaces, + users, cgroups and descriptors are mandatory. The project must not see the + platform root, raw archive, staging directories or trusted control endpoints. + +### Allowed files and owners + +- Existing CHECKERS `api/selected_pre_submit.py`, `api/external.py`, + `selected_pre_submit*` implementation, `models.py`, corresponding migration + and exact owner tests: source-first reservation and independent result binding. +- `backend/app/interfaces/external_checker_execution.py`, existing checker + adapters/factory composition, and ART's public source/read grant boundary: + one typed source-based PRE call and separately supplied expiring delivery. +- `external_checkers/intake/worker.py`, the existing guest `lib.rs`, `main.rs` + and cohesive PRE helper, service `smol.rs`, `smol/intake.rs`, transport and + SDK: combined guest purpose, streaming, protected worker/project sequencing. +- Canonical ART manifest/archive and CHECKERS default APIs only where an + owner-public entry point or shared derivation is required; reuse their + semantics, do not copy inspection/default algorithms into Rust. +- Existing affected tests, new focused PRE tests, exact behavior ownership and + lane registrations, SDK fixtures, this record and affected current docs. + +Prohibited: host/API whole-ZIP spool or verified-tree export for PRE; another +PRE VM/runner; project-selected platform code; manufactured manifests, default +input or prepared-generation IDs; changed default behavior; acceptance before +T4; deletion of retained evidence; POST semantic changes; capabilities/network +expansion; fabricated runtime limits or provider qualification. + +### Execution and authority sequence + +1. Reserve existing CHECKERS run under TASK/operation/fence custody after T2. + Persist immutable source descriptor, locked task/packet/rules/predecessor, + exact approved image/config/default/profile and explicit budgets. Manifest + and default-input evidence are absent until observed, not placeholder hashes. +2. Record discoverable runtime invocation/cleanup obligation before create; + use existing guardian/capacity ownership. Deliver exact authorized source + with bounded reads over the existing transport, outside database locks. + The platform bundle and guest spool/expanded workspace remain explicitly + charged. No caller path is part of the provider-neutral request. +3. In the guest, stage the trusted root with the verified reader, validate raw + SHA/count, inspect/extract and derive canonical manifest/default input from + locked facts. Run the unchanged four defaults. A source mismatch is an + infrastructure failure; unsafe ZIP can be a default rejection with no + manifest. Blocking defaults produce project `not_run`. +4. On default pass, supervisor permits exactly the registered project command + with verified input read-only and a separately bounded writable workspace. + The nested request is derived in trusted code after inspection. Project + output is bounded data on separate pipes, never a trusted response frame. + Close inherited control/source/root descriptors before project exec; forbid + mount/ptrace/signal access to the supervisor and keep it outside workload OOM. +5. CHECKERS validates the manifest and reconstructs expected nested request and + default-input digests from its persisted locked facts. Matching echoed + digests alone cannot establish eligibility. Validate every operation/run, + source generation, image/config/default/profile and fence before persistence. + Capture evidence independently of cleanup; uncertain destruction retains its + obligation and charged capacity, not a fabricated checker failure. + +### Acceptance, verification and review focus + +Future implementation tests must exercise the connected call, not only parsing: +valid ZIP -> four defaults -> exactly one selected project invocation; malformed +ZIP and secret/unchanged rejection -> no project invocation; source SHA/count +mismatch -> infrastructure failure; swapped image/config/run/fence or manifest +-> rejection; forged project stdout -> cannot supply trusted facts; deadline, +EOF, output excess, cancellation and uncertain create/destroy -> bounded terminal +behavior with retained cleanup custody. Revision/current-predecessor checks and +warning-only packet omissions preserve canonical behavior. + +Use existing real PostgreSQL harness for T3 reservation/replay/fence/rollback and +migration parity, existing Rust workspace checks under pinned 1.84.0, and real +Python canonical inspector/default fixtures for derived evidence. Include a +portable guest composition drill with the actual approved root, plus a mutation +that bypasses defaults and a mutation that trusts echoed request digests; both +must fail meaningful assertions. Namespace/cgroup/Smol isolation needs native +qualification and cannot be established by mocks or the portable drill. This +host currently has neither Smol nor `/dev/kvm`; retain that explicit evidence gap +and do not enable unqualified production execution as a fallback. + +Architecture/security review the plan and frozen implementation, specifically +source-first ownership, SDK replacement and supervisor privilege separation. +QA/test-delta review assertion reachability and discriminating mutations. +Documentation review reconciles exposure and qualification claims. Lead owns +shared checks, exact CI handles and the same PR; human review focus is the +source-to-result authority chain and confinement evidence, not test counts. From bba47ff7c36c53218e3155199234ef6167ecbb10 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 10:43:04 +0100 Subject: [PATCH 043/513] Bind PRE replacement to source custody and guest isolation review --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3c5e11cb2..3cf49f040 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1031,3 +1031,64 @@ QA/test-delta review assertion reachability and discriminating mutations. Documentation review reconciles exposure and qualification claims. Lead owns shared checks, exact CI handles and the same PR; human review focus is the source-to-result authority chain and confinement evidence, not test counts. + +### Plan review corrections: exact cutover and confinement boundaries + +Architecture/security and QA/test-delta inspected `03a09b353` and found the +single-session direction feasible with the following required corrections. +These are part of the allowed implementation and acceptance scope above: + +- Explicitly include ART `submission_admission.py`, + `selected_pre_submit_execution.py`, `submission_materialization.py`, + `selected_pre_submit_admission.py`, `submission_custody.py`, affected + trusted-intake contracts, AUTH selected-PRE facts, and + `backend/app/adapters/tasks/__init__.py` plus TASK's intake public port. + Replace the current composition in place; no second transaction owner. +- Introduce an explicit stored request schema discriminator. Historical + prepared-source rows keep their original fields and canonical JSON/digests + unchanged and remain readable. New source-bound rows require operation/source + identity and forbid a prepared-generation value. Before inspection their + manifest/default-input columns are NULL; after inspection those are immutable + result evidence. SQL and typed decoders enforce mutually exclusive historical + and new shapes. Historical decoding is read-only evidence interpretation, + never another executable PRE path. The migration does not rewrite old hashes + or delete rows. Completed unsafe-archive rejection permits absent derived + fields but forbids eligibility/project evidence. +- Replace `SelectedPreSubmitAdmissionCapability` and its ART consumer together. + New source-bound completion cannot mint or satisfy the old + `SubmissionBundlePreparedCustody` capability requiring `PreparedArtifact`. + Until T4 is installed, retain the source-bound terminal as CHECKERS evidence + only; it cannot authorize old create/admission consumption. The old live + prepare/reserve producer is removed with its affected callers in the same + coordinated replacement, not kept as an execution compatibility option. +- Extend the existing TASK-first guard: lock TASK intake custody, verify its + active operation, then check ART's exact operation/source generation and + current foreground lease/fence in that root before CHECKERS run locks. + Reserve, claim and finalize must all enforce the relevant current custody. + A valid task/assignment/lineage alone is insufficient. Keep source ownership + in ART and task pointer ownership in TASK through public ports. +- CHECKERS reconstruction consumes bounded guest-observed canonical inspection + entries tied to the exact raw source plus persisted locked task/project facts. + Recompute manifest/default-input/nested-request canonical bodies and digests; + neither locked facts alone nor a mutually consistent pair of returned hashes + proves the inspected input. +- Stage the trusted root/raw input under a supervisor-owned private directory + hidden by the project child's mount namespace (not an unmasked `/work` + directory). Before exec close inherited bundle, archive, directory and trusted + control descriptors; retain only explicitly allowed project stdin/stdout/stderr. + Separate fixed trusted/project UIDs and cgroups are part of the qualified + profile, not project image choices. Drop privileges and apply the existing + workload syscall filter after mounting. The supervisor remains outside both + killable workload groups. Namespace hiding must also prevent `/proc`/inherited + descriptor access to the trusted root and control process. + +The connected fixture must begin with a real sealed operation/generation and +NULL derived fields, then drive the existing coordinator/ART composition into +one typed PRE call. Count session creation and conditional project launch. +Add negative controls for foreign/cleared TASK active operation, stale foreground +fence, substituted provider generation, and attempted old-capability consumption +of a new source-bound terminal. Existing prepared-file/mock-execution fixtures +cannot establish these claims. Retain their still-required semantic assertions +while replacing their obsolete preparation setup. Lead plan checks passed +Commitrail, Markdown links and diff whitespace; the review is feasibility +inspection, not runtime or migration proof. From 51737026767e784c7741a352e61527bf66bada85 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 10:46:45 +0100 Subject: [PATCH 044/513] Derive default input from locked context and verified guest evidence --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 12 +++ .../selected_pre_submit_admission.py | 14 ++-- .../modules/checkers/api/default_checker.py | 76 +++++++++++++++---- .../tests/checkers/default/test_execution.py | 73 +++++++++++++++--- external_checkers/intake/worker.py | 21 ++++- 5 files changed, 165 insertions(+), 31 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3cf49f040..6f1acd1ae 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1092,3 +1092,15 @@ cannot establish these claims. Retain their still-required semantic assertions while replacing their obsolete preparation setup. Lead plan checks passed Commitrail, Markdown links and diff whitespace; the review is feasibility inspection, not runtime or migration proof. + +The first implementation step separates `WorkstreamDefaultContext` (locked +predecessor/rules/packet facts available before inspection) from the derived +`WorkstreamDefaultCheckerInput`. Both use one context validator. ART's existing +builder now binds its inspected source/manifest through that context; the trusted +worker independently derives its input from its own raw receipt and projected +entries and compares the supplied input before evaluation. The canonical input +body and four-default behavior identity are unchanged. Eighty focused default, +predecessor, trusted-worker and selected-PRE tests pass, including late binding +and digest sensitivity to locked facts and observed input. This is an internal +step in the reviewed replacement: the worker still has its old command sequence, +and source-first reservation, combined guest and T4 are not implemented yet. diff --git a/backend/app/modules/artifacts/selected_pre_submit_admission.py b/backend/app/modules/artifacts/selected_pre_submit_admission.py index 7a1d1e4b4..2ad0af672 100644 --- a/backend/app/modules/artifacts/selected_pre_submit_admission.py +++ b/backend/app/modules/artifacts/selected_pre_submit_admission.py @@ -17,6 +17,7 @@ from app.modules.checkers.api.default_checker import ( WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, WorkstreamDefaultCheckerInput, + WorkstreamDefaultContext, WorkstreamDefaultPredecessor, workstream_default_input_body, ) @@ -252,18 +253,19 @@ def bind_selected_pre_submit_admission( policy=policies.pre_submit, post_policy=policies.post_submit, policies_sha256=policies.policies_sha256, - default_input=WorkstreamDefaultCheckerInput( - archive_sha256=commitment.sha256, - archive_byte_count=commitment.byte_count, - archive_media_type=commitment.media_type, - semantic_manifest_sha256=manifest.sha256, - entries=entries, + default_input=WorkstreamDefaultContext( predecessor=default_predecessor, predecessor_exists=predecessor_exists, current_predecessor=default_predecessor, current_rules_sha256=rules_sha256, predecessor_rules_sha256=predecessor_rules_sha256, packet=packet, + ).bind_verified_input( + archive_sha256=commitment.sha256, + archive_byte_count=commitment.byte_count, + archive_media_type=commitment.media_type, + semantic_manifest_sha256=manifest.sha256, + entries=entries, ), change_gate=change_gate, rules_sha256=rules_sha256, diff --git a/backend/app/modules/checkers/api/default_checker.py b/backend/app/modules/checkers/api/default_checker.py index e869e6f71..e298e20c9 100644 --- a/backend/app/modules/checkers/api/default_checker.py +++ b/backend/app/modules/checkers/api/default_checker.py @@ -120,6 +120,58 @@ def __post_init__(self) -> None: _require_sha256(self.semantic_manifest_sha256) +@dataclass(frozen=True, slots=True) +class WorkstreamDefaultContext: + """Locked facts known before source inspection; no derived input identity. + + This value confers no authority. The owner must recover it from the locked + request, and bind only independently verified raw and manifest evidence. + """ + + predecessor: WorkstreamDefaultPredecessor | None + predecessor_exists: bool + current_predecessor: WorkstreamDefaultPredecessor | None + current_rules_sha256: str + predecessor_rules_sha256: str | None + packet: SubmissionPacketView + + def __post_init__(self) -> None: + """Validate detached rule and predecessor facts before any source read.""" + _require_sha256(self.current_rules_sha256) + if ( + (self.predecessor is not None + and type(self.predecessor) is not WorkstreamDefaultPredecessor) + or (self.current_predecessor is not None + and type(self.current_predecessor) is not WorkstreamDefaultPredecessor) + or type(self.predecessor_exists) is not bool + or type(self.packet) is not SubmissionPacketView + or (self.predecessor_rules_sha256 is None) != (self.predecessor is None) + ): + raise ValueError("default checker context is invalid") + if self.predecessor_rules_sha256 is not None: + _require_sha256(self.predecessor_rules_sha256) + + def bind_verified_input( + self, *, archive_sha256: str, archive_byte_count: int, + archive_media_type: str, semantic_manifest_sha256: str, + entries: tuple[SubmissionMaterialEntry, ...], + ) -> WorkstreamDefaultCheckerInput: + """Derive the canonical input after the owner verifies source and manifest. + + Neither this constructor nor a matching digest proves observation of + bytes. Guest and CHECKERS must independently supply their verified facts. + """ + return WorkstreamDefaultCheckerInput( + archive_sha256=archive_sha256, archive_byte_count=archive_byte_count, + archive_media_type=archive_media_type, + semantic_manifest_sha256=semantic_manifest_sha256, entries=entries, + predecessor=self.predecessor, predecessor_exists=self.predecessor_exists, + current_predecessor=self.current_predecessor, + current_rules_sha256=self.current_rules_sha256, + predecessor_rules_sha256=self.predecessor_rules_sha256, packet=self.packet, + ) + + @dataclass(frozen=True, slots=True) class WorkstreamDefaultCheckerInput: """Detached exact custody and task-rule facts; never storage authority.""" @@ -140,28 +192,23 @@ def __post_init__(self) -> None: """Reject malformed detached facts before any callback-scoped byte read.""" _require_sha256(self.archive_sha256) _require_sha256(self.semantic_manifest_sha256) - _require_sha256(self.current_rules_sha256) if ( type(self.archive_byte_count) is not int or self.archive_byte_count <= 0 or self.archive_media_type != "application/zip" or type(self.entries) is not tuple or any(type(item) is not SubmissionMaterialEntry for item in self.entries) - or ( - self.predecessor is not None - and type(self.predecessor) is not WorkstreamDefaultPredecessor - ) - or ( - self.current_predecessor is not None - and type(self.current_predecessor) is not WorkstreamDefaultPredecessor - ) - or type(self.predecessor_exists) is not bool - or type(self.packet) is not SubmissionPacketView - or (self.predecessor_rules_sha256 is None) != (self.predecessor is None) ): raise ValueError("default checker input is invalid") - if self.predecessor_rules_sha256 is not None: - _require_sha256(self.predecessor_rules_sha256) + try: + WorkstreamDefaultContext( + predecessor=self.predecessor, predecessor_exists=self.predecessor_exists, + current_predecessor=self.current_predecessor, + current_rules_sha256=self.current_rules_sha256, + predecessor_rules_sha256=self.predecessor_rules_sha256, packet=self.packet, + ) + except ValueError as exc: + raise ValueError("default checker input is invalid") from exc def workstream_default_input_body( @@ -317,6 +364,7 @@ def _failure_matches_check( "WorkstreamDefaultCheck", "WorkstreamDefaultCheckId", "WorkstreamDefaultCheckerInput", + "WorkstreamDefaultContext", "WorkstreamDefaultCheckerResult", "WorkstreamDefaultFailureCode", "WorkstreamDefaultPredecessor", diff --git a/backend/tests/checkers/default/test_execution.py b/backend/tests/checkers/default/test_execution.py index f2c3e88bf..8160f8d30 100644 --- a/backend/tests/checkers/default/test_execution.py +++ b/backend/tests/checkers/default/test_execution.py @@ -23,6 +23,8 @@ from app.modules.artifacts.submission_manifest import build_submission_manifest from app.modules.checkers.api.default_checker import ( WorkstreamDefaultCheckerInput, + WorkstreamDefaultContext, + workstream_default_input_sha256, WorkstreamDefaultPredecessor, ) from app.modules.checkers.api.materialization import SubmissionMaterialEntry @@ -69,7 +71,17 @@ def _input( attestation: str = "I confirm the submitted material is authorized.", ) -> WorkstreamDefaultCheckerInput: _, inspection, manifest, commitment = _facts(value) - return WorkstreamDefaultCheckerInput( + context = WorkstreamDefaultContext( + predecessor=predecessor, + predecessor_exists=predecessor is not None, + current_predecessor=current_predecessor, + current_rules_sha256=current_rules_sha256, + predecessor_rules_sha256=predecessor_rules_sha256, + packet=SubmissionPacketView( + summary=summary, contributor_attestation=attestation + ), + ) + return context.bind_verified_input( archive_sha256=commitment.sha256, archive_byte_count=commitment.byte_count, archive_media_type=commitment.media_type, @@ -84,17 +96,10 @@ def _input( ) for item in inspection.entries ), - predecessor=predecessor, - predecessor_exists=predecessor is not None, - current_predecessor=current_predecessor, - current_rules_sha256=current_rules_sha256, - predecessor_rules_sha256=predecessor_rules_sha256, - packet=SubmissionPacketView( - summary=summary, contributor_attestation=attestation - ), ) + def _evaluate(value: bytes, request: WorkstreamDefaultCheckerInput, workspace: Path): inspector, inspection, _, _ = _facts(value) workspace.mkdir(mode=0o700) @@ -357,3 +362,53 @@ def __eq__(self, other: object) -> bool: current_predecessor=foreign, predecessor_rules_sha256=RULES_A, ) + + +def test_default_context_exists_before_zip_and_binds_later_observation() -> None: + """No manifest/input digest is needed until trusted inspection completes.""" + context = WorkstreamDefaultContext( + predecessor=None, predecessor_exists=False, current_predecessor=None, + current_rules_sha256=RULES_A, predecessor_rules_sha256=None, + packet=SubmissionPacketView(summary="", contributor_attestation=""), + ) + archive = _archive({"work.txt": b"new work"}) + expected = _input(archive, summary="", attestation="") + observed = { + "archive_sha256": expected.archive_sha256, + "archive_byte_count": expected.archive_byte_count, + "archive_media_type": expected.archive_media_type, + "semantic_manifest_sha256": expected.semantic_manifest_sha256, + "entries": expected.entries, + } + bound = context.bind_verified_input(**observed) + assert bound == expected + digest = workstream_default_input_sha256(bound) + # Retained rules/packet and independently observed raw/manifest evidence + # must all participate; agreeing on an echoed digest cannot substitute them. + for changed_context in ( + replace(context, current_rules_sha256=RULES_B), + replace(context, packet=SubmissionPacketView( + summary="different packet", contributor_attestation="", + )), + ): + assert workstream_default_input_sha256( + changed_context.bind_verified_input(**observed) + ) != digest + for field, value in ( + ("archive_sha256", "sha256:" + "c" * 64), + ("archive_byte_count", expected.archive_byte_count + 1), + ("semantic_manifest_sha256", "sha256:" + "d" * 64), + ("entries", (replace(expected.entries[0], executable=True),)), + ): + assert workstream_default_input_sha256( + context.bind_verified_input(**(observed | {field: value})) + ) != digest + + +def test_default_context_rejects_partial_rules_before_source_read() -> None: + with pytest.raises(ValueError): + WorkstreamDefaultContext( + predecessor=None, predecessor_exists=False, current_predecessor=None, + current_rules_sha256=RULES_A, predecessor_rules_sha256=RULES_B, + packet=SubmissionPacketView(summary="", contributor_attestation=""), + ) diff --git a/external_checkers/intake/worker.py b/external_checkers/intake/worker.py index 1595e4851..48c709ead 100644 --- a/external_checkers/intake/worker.py +++ b/external_checkers/intake/worker.py @@ -33,6 +33,7 @@ from app.modules.checkers.api.default_checker import ( WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, WorkstreamDefaultCheckerInput, + WorkstreamDefaultContext, workstream_default_input_sha256, ) from app.modules.checkers.api.material import SubmissionMaterialEntry @@ -226,8 +227,24 @@ def run(self) -> None: value = TypeAdapter(WorkstreamDefaultCheckerInput).validate_json( json.dumps(raw), strict=True ) + material = _Material(tree) + derived = WorkstreamDefaultContext( + predecessor=value.predecessor, + predecessor_exists=value.predecessor_exists, + current_predecessor=value.current_predecessor, + current_rules_sha256=value.current_rules_sha256, + predecessor_rules_sha256=value.predecessor_rules_sha256, + packet=value.packet, + ).bind_verified_input( + archive_sha256=self._startup["archive_sha256"], + archive_byte_count=size, + archive_media_type="application/zip", + semantic_manifest_sha256=manifest.sha256, + entries=material.entries, + ) if ( - binding.policy_sha256 != self._preparation.policy_sha256 + value != derived + or binding.policy_sha256 != self._preparation.policy_sha256 or binding.semantic_manifest_sha256 != manifest.sha256 or value.semantic_manifest_sha256 != manifest.sha256 or value.archive_sha256 != self._startup["archive_sha256"] @@ -237,7 +254,7 @@ def run(self) -> None: ): raise ValueError("default custody differs") self._state = "evaluating" - result = evaluate_verified_archive(value, _Material(tree)) + result = evaluate_verified_archive(derived, material) self._reply("default", result.model_dump(mode="json")) self._state = "evaluated" else: From bd93d957cfdd6498d3b492fc0a071b84f965cc11 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 10:50:10 +0100 Subject: [PATCH 045/513] Guard guest observed input against rehashed supplied metadata --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++++++ backend/tests/test_trusted_intake.py | 24 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6f1acd1ae..6b5bac8db 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1104,3 +1104,14 @@ predecessor, trusted-worker and selected-PRE tests pass, including late binding and digest sensitivity to locked facts and observed input. This is an internal step in the reviewed replacement: the worker still has its old command sequence, and source-first reservation, combined guest and T4 are not implemented yet. + +Scoped architecture/security passed the default-context step at `517370267`. +QA's in-memory stale-binding mutation failed the new digest-sensitivity test. +Both tracks independently rejected forged executable metadata with a recomputed +supplied input/binding digest before the worker evaluator; that case is now a +permanent worker regression. The ownership partition regenerated identically, +and 229 ownership/lane-catalogue checks passed. These checks do not qualify a +rebuilt platform image or the still-unimplemented combined guest path. +The repaired focused suite passes 81 tests. Disabling only the worker's observed +input comparison in memory makes the new regression fail at its evaluator-entry +sentinel, confirming the assertion reaches and distinguishes that boundary. diff --git a/backend/tests/test_trusted_intake.py b/backend/tests/test_trusted_intake.py index 125ad7694..179abdcd2 100644 --- a/backend/tests/test_trusted_intake.py +++ b/backend/tests/test_trusted_intake.py @@ -466,3 +466,27 @@ def unexpected_inspector(*args, **kwargs): output.seek(0) assert _read(output)["operation"] == "ready" assert output.read() == b"" + + +def test_worker_rejects_rehashed_entries_before_default_evaluation(tmp_path, monkeypatch): + """Consistent supplied hashes cannot replace the guest's observed inventory.""" + data = _archive() + original = _default(data) + forged = replace( + original, + entries=(replace(original.entries[0], executable=not original.entries[0].executable),), + ) + assert workstream_default_input_sha256(forged) != workstream_default_input_sha256(original) + worker, output = _run( + tmp_path, data, + _command("export", {}) + _default_command(forged, _binding(forged)), + ) + + def must_not_evaluate(*args): + pytest.fail("substituted observed entries reached the default evaluator") + + monkeypatch.setattr(_WORKER, "evaluate_verified_archive", must_not_evaluate) + with pytest.raises(ValueError, match="default custody differs"): + worker.run() + _export_result(output, b"finished work") + assert output.read() == b"" From 3cee7cc5f19690aa81fbebd6e2cf8890096b970a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 10:57:57 +0100 Subject: [PATCH 046/513] Expose live source custody under TASK and ART locks for PRE --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 21 +++++ .../artifacts/api/submission_intake.py | 41 +++++++++- .../modules/artifacts/intake/repository.py | 41 ++++++++-- .../app/modules/tasks/api/intake_custody.py | 4 + backend/app/modules/tasks/intake_custody.py | 8 ++ .../test_submission_intake_custody.py | 82 +++++++++++++++++++ 6 files changed, 189 insertions(+), 8 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6b5bac8db..4c4f20b36 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1115,3 +1115,24 @@ rebuilt platform image or the still-unimplemented combined guest path. The repaired focused suite passes 81 tests. Disabling only the worker's observed input comparison in memory makes the new regression fail at its evaluator-entry sentinel, confirming the assertion reaches and distinguishes that boundary. + +The T3 source-first reservation dependency is now an explicit ART public port: +`SubmissionIntakePreSourcePort.lock_pre_source` uses the current TASK-first +repository lock, checks the live foreground lease, requires TASK's exact active +operation, and compares every sealed-source field before returning detached +actor/task/assignment/context and deadline facts. `IntakeTaskCustody.require_active` +owns the pointer comparison. These values grant neither AUTH nor provider I/O; +they must be consumed within the same root before CHECKERS locks. Source +reconstruction is shared with sealing. Existing upload/terminal behavior is not +replaced by this port, and CHECKERS reservation wiring remains the next step. +Thirteen real PostgreSQL controls passed for valid source custody and altered +source generation/hash/count/namespace/profile, lease/fence, cleared/foreign +pointer, expiry, terminal and unsealed source. The pointer tests exercise an +uncommitted state before deferred constraints, proving the in-root check matters. + +CI for `592959410` reported one shared-foundations-b failure among 2,118 tests: +`test_handler_suppressing_cancellation_cannot_ack_after_deadline` timed out waiting +two seconds for finalization after cancellation was observed. This is unresolved +failure evidence, not a passed run or grounds to relax the assertion. Exact +job 131093141927 and its lane artifact were inspected; diagnosis/reproduction +remains required. Other jobs were still running at that observation. diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py index 54e43ab88..cb87ffaed 100644 --- a/backend/app/modules/artifacts/api/submission_intake.py +++ b/backend/app/modules/artifacts/api/submission_intake.py @@ -8,7 +8,7 @@ from __future__ import annotations -from typing import Annotated, Literal, Self +from typing import Annotated, Literal, Protocol, Self from uuid import UUID from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator, model_validator @@ -136,6 +136,45 @@ def source_sha256(self) -> str: }) +class SubmissionIntakePreSourceFacts(_IntakeValue): + """Detached current T3 custody, not AUTH or a provider read capability. + + Valid only for comparisons in the caller's still-open root transaction. + Copying this value cannot extend its lease or authorize later source access. + """ + + source: SealedSubmissionSource + project_id: UUID + task_id: UUID + assignment_id: UUID + actor_profile_id: UUID + identity_link_id: UUID + metadata_sha256: Sha256 + locked_context_sha256: Sha256 + lease_id: UUID + lease_generation: int = Field(ge=1) + lease_expires_at: AwareDatetime + pre_deadline_at: AwareDatetime + + @model_validator(mode="after") + def bounded_lease(self) -> Self: + """Reject structurally contradictory lease and immutable upload facts.""" + if (self.lease_expires_at > self.pre_deadline_at + or self.lease_generation < self.source.sealed_upload_fence): + raise ValueError("PRE source lease bounds differ") + return self + + +class SubmissionIntakePreSourcePort(Protocol): + """ART exact source participation in an authorized, caller-owned T3 root.""" + + async def lock_pre_source( + self, *, source: SealedSubmissionSource, lease_id: UUID, generation: int, + ) -> SubmissionIntakePreSourceFacts: + """Check TASK pointer and live ART source/fence before CHECKERS locks.""" + ... + + class SubmissionSourceCapacityLimits(_IntakeValue): """Explicit physical source allocation; no deployment defaults or logical dedup.""" diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py index 7126d61ac..782f1c132 100644 --- a/backend/app/modules/artifacts/intake/repository.py +++ b/backend/app/modules/artifacts/intake/repository.py @@ -18,6 +18,7 @@ from app.core.identifiers import new_record_id from app.modules.artifacts.api.submission_intake import ( SealedSubmissionSource, SubmissionIntakeMetadata, SubmissionSourceLocation, + SubmissionIntakePreSourceFacts, SubmissionSourceCapacityLimits, SubmissionSourceCompletion, SubmissionSourceUpload, SubmissionSourceUploadIntent, ) @@ -119,6 +120,38 @@ async def _owned(self, operation_id: UUID, lease_id: UUID, generation: int) -> S raise IntakeCustodyConflict("intake_owner_stale") return row + async def lock_pre_source( + self, *, source: SealedSubmissionSource, lease_id: UUID, generation: int, + ) -> SubmissionIntakePreSourceFacts: + """Hold TASK/ART custody for an exact, live sealed source; never grant I/O.""" + source = SealedSubmissionSource.model_validate(source) + if type(lease_id) is not UUID or type(generation) is not int or generation < 1: + raise IntakeCustodyConflict("intake_owner_stale") + row = await self._owned(source.location.operation_id, lease_id, generation) + project_id = await self._tasks.require_active(UUID(row.task_id), UUID(row.id)) + if (row.state != "pre_checking" or project_id != UUID(row.project_id) + or row.provider_generation is None or self._sealed_source(row) != source): + raise IntakeCustodyConflict("intake_pre_source_changed") + return SubmissionIntakePreSourceFacts( + source=source, project_id=project_id, task_id=UUID(row.task_id), + assignment_id=UUID(row.assignment_id), actor_profile_id=UUID(row.actor_profile_id), + identity_link_id=UUID(row.identity_link_id), metadata_sha256=row.metadata_sha256, + locked_context_sha256=row.locked_context_sha256, lease_id=UUID(row.lease_id), + lease_generation=row.lease_generation, lease_expires_at=row.lease_expires_at, + pre_deadline_at=row.pre_deadline_at, + ) + + @staticmethod + def _sealed_source(row: SubmissionIntakeOperation) -> SealedSubmissionSource: + """Recover the exact source from durable columns after sealing.""" + return SealedSubmissionSource( + location=SubmissionSourceLocation( + operation_id=UUID(row.id), namespace_id=row.namespace_id, + namespace_fingerprint=row.namespace_fingerprint, provider_profile=row.provider_profile, + ), provider_generation=row.provider_generation, raw_sha256=row.raw_sha256, + raw_byte_count=row.raw_byte_count, sealed_upload_fence=row.sealed_upload_fence, + ) + async def _upload_intent( self, row: SubmissionIntakeOperation, receipt: SubmissionSourceUploadReceipt, ) -> SubmissionSourceUploadIntent: @@ -205,13 +238,7 @@ async def seal(self, operation_id: UUID, lease_id: UUID, generation: int, await self._session.flush() await self._session.refresh(row) await self._capacity.seal(row) - return SealedSubmissionSource( - location=SubmissionSourceLocation( - operation_id=operation_id, namespace_id=row.namespace_id, - namespace_fingerprint=row.namespace_fingerprint, provider_profile=row.provider_profile, - ), provider_generation=row.provider_generation, raw_sha256=row.raw_sha256, - raw_byte_count=row.raw_byte_count, sealed_upload_fence=row.sealed_upload_fence, - ) + return self._sealed_source(row) async def heartbeat(self, operation_id: UUID, lease_id: UUID, generation: int, *, lease_duration: timedelta) -> float: diff --git a/backend/app/modules/tasks/api/intake_custody.py b/backend/app/modules/tasks/api/intake_custody.py index 0a9934e10..940a52e80 100644 --- a/backend/app/modules/tasks/api/intake_custody.py +++ b/backend/app/modules/tasks/api/intake_custody.py @@ -27,6 +27,10 @@ async def lock(self, task_id: UUID) -> UUID: """Acquire TASK first and return its project without asserting eligibility.""" ... + async def require_active(self, task_id: UUID, operation_id: UUID) -> UUID: + """Lock TASK and require its exact active operation; return the project.""" + ... + async def release(self, task_id: UUID, operation_id: UUID) -> None: """Clear only this operation's pointer inside the terminal transaction.""" ... diff --git a/backend/app/modules/tasks/intake_custody.py b/backend/app/modules/tasks/intake_custody.py index d1cbc0fbe..079865064 100644 --- a/backend/app/modules/tasks/intake_custody.py +++ b/backend/app/modules/tasks/intake_custody.py @@ -48,6 +48,14 @@ async def claim(self, request: TaskSubmissionContextRequest, operation_id: UUID) json.dumps(snapshot, sort_keys=True, separators=(",", ":")), ) + async def require_active(self, task_id: UUID, operation_id: UUID) -> UUID: + """Retain TASK custody while refusing a foreign or cleared operation.""" + project_id = await self.lock(task_id) + task = await self._tasks.get_task(str(task_id), for_update=True) + if task.active_submission_operation_id != str(operation_id): + raise TaskSubmissionContextUnavailable("task_submission_context_invalid") + return project_id + async def release(self, task_id: UUID, operation_id: UUID) -> None: """Never clear a different operation's ownership.""" await self.lock(task_id) diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 4c89ed0a3..81b727666 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -965,3 +965,85 @@ def command(*owner): with pytest.raises(IntakeCustodyConflict, match="renewal_expired"): await runner.run(operation, lease, 1, command) assert not called + + +async def test_pre_source_custody_returns_exact_locked_facts(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + deadline = datetime.now(UTC) + timedelta(minutes=2) + source = await repository(session).seal( + operation, lease, 1, provider_generation="pre-source-generation", + pre_deadline_at=deadline, lease_expires_at=deadline, + ) + async with intake.factory.begin() as session: + facts = await repository(session).lock_pre_source(source=source, lease_id=lease, generation=1) + assert facts.source == source + assert facts.task_id == intake.task and facts.assignment_id == intake.assignment + assert facts.actor_profile_id == intake.actor.actor_profile_id + assert facts.identity_link_id == intake.actor.identity_link_id + assert facts.lease_id == lease and facts.lease_generation == 1 + assert facts.lease_expires_at == facts.pre_deadline_at == deadline + assert facts.metadata_sha256 == row.metadata_sha256 + assert facts.locked_context_sha256 == row.locked_context_sha256 + + +@pytest.mark.parametrize("changed", [ + "generation", "raw_sha", "raw_count", "namespace", "profile", "lease", "fence", + "cleared_pointer", "foreign_pointer", "expired", "terminal", "unsealed", +]) +async def test_pre_source_custody_rejects_substitution_or_stale_owner(intake, changed): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + deadline = datetime.now(UTC) + timedelta(minutes=2) + if changed == "unsealed": + from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceLocation + source = SealedSubmissionSource( + location=SubmissionSourceLocation( + operation_id=operation, namespace_id=row.namespace_id, + namespace_fingerprint=row.namespace_fingerprint, provider_profile=row.provider_profile, + ), provider_generation="pre-source-generation", raw_sha256=SHA, + raw_byte_count=100, sealed_upload_fence=1, + ) + else: + source = await repository(session).seal( + operation, lease, 1, provider_generation="pre-source-generation", + pre_deadline_at=deadline, lease_expires_at=deadline, + ) + values = source.model_dump(mode="python") + if changed == "generation": + values["provider_generation"] = "another-generation" + elif changed == "raw_sha": + values["raw_sha256"] = "sha256:" + "b" * 64 + elif changed == "raw_count": + values["raw_byte_count"] += 1 + elif changed == "namespace": + values["location"]["namespace_fingerprint"] = "sha256:" + "b" * 64 + elif changed == "profile": + values["location"]["provider_profile"] = "unqualified-profile" + supplied = type(source).model_validate(values) + async with intake.factory() as session: + await session.begin() + try: + if changed in {"cleared_pointer", "foreign_pointer"}: + # Deferrable SQL constraints do not replace the in-root owner + # check before another participant can consume custody. + await session.execute(text( + "UPDATE workstream_tasks SET active_submission_operation_id=:active WHERE id=:task" + ), {"active": None if changed == "cleared_pointer" else new_record_id(), "task": intake.task}) + elif changed == "expired": + await session.execute(text( + "UPDATE submission_intake_operations SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=:id" + ), {"id": operation}) + elif changed == "terminal": + await repository(session).terminalize(operation, lease, 1, state="rejected", failure_code="pre_failed") + with pytest.raises((IntakeCustodyConflict, TaskSubmissionContextUnavailable)): + await repository(session).lock_pre_source( + source=supplied, lease_id=new_record_id() if changed == "lease" else lease, + generation=2 if changed == "fence" else 1, + ) + finally: + await session.rollback() From 16704ddd6360c894ccd7a09ddc6e28bb9d247001 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 11:03:43 +0100 Subject: [PATCH 047/513] Separate outbox cancellation ordering from database finalization timing --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 18 ++++++++++++++++ .../tests/outbox/test_recovery_postgresql.py | 21 ++++++++++++++++--- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 4c4f20b36..485cbbf1a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1136,3 +1136,21 @@ two seconds for finalization after cancellation was observed. This is unresolved failure evidence, not a passed run or grounds to relax the assertion. Exact job 131093141927 and its lane artifact were inspected; diagnosis/reproduction remains required. Other jobs were still running at that observation. + +### Bounded CI failure diagnosis: cancellation versus database finalization + +Allowed test-only repair: `backend/tests/outbox/test_recovery_postgresql.py` +and this record. The failed test waits two seconds after observing cancellation +for all of real `finalize`, which includes multiple database roots and AUTH. +`invoke` explicitly cancels without awaiting the handler, then awaits durable +finalization. The test currently conflates those separate waits. Preserve the +prompt non-wait assertion with a two-second event at entry to real finalization, +while the uncooperative handler is still blocked. Gate that finalization in the +test to make ordering explicit, then allow a bounded ten-second database +observation and retain every UNKNOWN/replay/no-ack assertion. No production +outbox code, timeouts, authority or retry policy may change. QA must verify an +implementation that awaits the uncooperative handler before finalizing still +fails, and that the original CI timeout is not called a confirmed production +root cause merely because this scheduling defect is reproducible. The original +focused test is already running unchanged in the full custody command; do not +restart it or misattribute its eventual result to the repair. diff --git a/backend/tests/outbox/test_recovery_postgresql.py b/backend/tests/outbox/test_recovery_postgresql.py index 3ace94a77..e95fb7d52 100644 --- a/backend/tests/outbox/test_recovery_postgresql.py +++ b/backend/tests/outbox/test_recovery_postgresql.py @@ -534,12 +534,21 @@ async def blocked(envelope): assert await h.delivery.invoke(claim) is None and len(h.handled) == 1 -async def test_handler_suppressing_cancellation_cannot_ack_after_deadline(delivery_harness): +async def test_handler_suppressing_cancellation_cannot_ack_after_deadline(delivery_harness, monkeypatch): h = delivery_harness h.options = h.options.model_copy(update={"lease_seconds": 30, "handler_timeout_seconds": 1}) h.delivery = h.build() claim = await h.claim() cancelled, release = asyncio.Event(), asyncio.Event() + finalizing, allow_finalize = asyncio.Event(), asyncio.Event() + real_finalize = h.delivery.finalize + + async def observe_finalize(*args, **kwargs): + finalizing.set() + await allow_finalize.wait() + return await real_finalize(*args, **kwargs) + + monkeypatch.setattr(h.delivery, "finalize", observe_finalize) async def suppress_cancellation(envelope): try: @@ -552,8 +561,13 @@ async def suppress_cancellation(envelope): invocation = asyncio.create_task(h.delivery.invoke(claim)) try: await asyncio.wait_for(cancelled.wait(), 3) - # The dispatcher returns while the uncooperative handler remains running. - receipt = await asyncio.wait_for(asyncio.shield(invocation), 2) + # The dispatcher must reach finalization promptly without awaiting the + # uncooperative handler. Database latency is a separate observation. + await asyncio.wait_for(finalizing.wait(), 2) + assert not release.is_set() and not invocation.done() + assert h.delivery._running_handlers + allow_finalize.set() + receipt = await asyncio.wait_for(asyncio.shield(invocation), 10) assert h.delivery._running_handlers assert json.loads(receipt.outcome_json)["error_code"] == "INVOKE_OUTCOME_UNKNOWN" assert (await h.delivery.drain(h.project)).unresolved == 1 @@ -562,6 +576,7 @@ async def suppress_cancellation(envelope): assert await h.delivery.finalize(claim, FinalizationCause.UNKNOWN) == receipt assert await h.delivery.invoke(claim) is None and len(h.handled) == 1 finally: + allow_finalize.set() release.set() await asyncio.gather(invocation, return_exceptions=True) await asyncio.gather(*tuple(h.delivery._running_handlers), return_exceptions=True) From 020c0de09e0f38f8ec33e613fd682e4523d4403c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 11:06:55 +0100 Subject: [PATCH 048/513] Record source custody checks and outbox cancellation mutation evidence --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 485cbbf1a..c382d9214 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1154,3 +1154,15 @@ fails, and that the original CI timeout is not called a confirmed production root cause merely because this scheduling defect is reproducible. The original focused test is already running unchanged in the full custody command; do not restart it or misattribute its eventual result to the repair. + +The source-custody boundary passed scoped architecture/security and QA at +`3cee7cc5f`; 371 contract/ownership/lane/architecture tests also passed, with an +unchanged ownership partition. Its full PostgreSQL custody run remains separate +from the focused evidence until the exact running command completes. + +The outbox observation repair passed two focused real-PostgreSQL tests and QA +at `16704ddd6`. Mutating only `invoke` in memory to await the cancelled handler +before finalization made the repaired test fail at the two-second finalization +entry event. The mutation receipt records the exact commit and successful database +cleanup. This proves the test retains the cancellation-ordering boundary; it is +not a production outbox change or a claim that the original full CI run passed. From d8677d2f88124c86ea6be63f7725df6e35f798ca Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 11:12:39 +0100 Subject: [PATCH 049/513] Record full custody proof and historical PRE replacement boundary --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c382d9214..5da406c22 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1157,8 +1157,10 @@ restart it or misattribute its eventual result to the repair. The source-custody boundary passed scoped architecture/security and QA at `3cee7cc5f`; 371 contract/ownership/lane/architecture tests also passed, with an -unchanged ownership partition. Its full PostgreSQL custody run remains separate -from the focused evidence until the exact running command completes. +unchanged ownership partition. The full PostgreSQL run at `3cee7cc5f` passed +all 69 custody cases plus the original unmodified outbox cancellation test: +70 passed in 642.52 seconds, with database cleanup confirmed. The earlier CI +timeout did not reproduce locally; this does not erase that failed CI result. The outbox observation repair passed two focused real-PostgreSQL tests and QA at `16704ddd6`. Mutating only `invoke` in memory to await the cancelled handler @@ -1166,3 +1168,25 @@ before finalization made the repaired test fail at the two-second finalization entry event. The mutation receipt records the exact commit and successful database cleanup. This proves the test retains the cancellation-ordering boundary; it is not a production outbox change or a claim that the original full CI run passed. + + +Source-first reservation review resolved the remaining historical-data boundary: +retain v1 JSON/digests/status verbatim, including nonterminal historical rows; +make them read-only rather than fabricating terminal outcomes or migration AUTH. +Reject new v1 writes/transitions and v1 actor/key collisions as conflicts. The +live coordinator is v2-only; old prepared-bundle producer and capability consumer +are replaced together. A frozen v1 read decoder is evidence interpretation only. + +The concrete SQL transition must cover the existing 0036 insert, immutable-row, +execute/finalize audit-digest and receipt guards, not just ORM columns. Add a +nullable source operation reference with the existing `(id, task_id)` ART +composite key and uniqueness per non-null operation. The v2 insert guard also +compares project/assignment/actor/link and the full sealed descriptor under the +locked operation. Explicitly confine old ART admission guards to historical v1. +Request facts bind source, locked context/packet/predecessor, exact selected +policy/image/config/default/profile/resource limits and immutable PRE deadline; +manifest/default input become terminal evidence. Mutable heartbeat expiry is +excluded. Claims/finalization use DB time and cannot outlive ART's hard deadline. +Architecture/security found this replacement feasible; it is not implemented by +the preceding source-lock port. Fetched `origin/main` remains `94334ccf4`, already +an ancestor of this branch. From 18d3a56634f7631b1d8a5bcbbc14f974b5292f18 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 11:20:22 +0100 Subject: [PATCH 050/513] Separate retained PRE decoding from live execution contracts --- .ci/behavior-ownership/partition.v1.json | 6 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 13 + .../api/historical_selected_pre_submit.py | 706 ++++++++++++++++++ .../checkers/api/selected_pre_submit.py | 3 +- .../checkers/selected_pre_submit_reads.py | 5 +- backend/scripts/behavior_ownership.py | 1 + .../external/fixtures/selected_pre_v1.json | 59 ++ .../test_selected_pre_submit_coordination.py | 64 ++ 8 files changed, 853 insertions(+), 4 deletions(-) create mode 100644 backend/app/modules/checkers/api/historical_selected_pre_submit.py create mode 100644 backend/tests/checkers/external/fixtures/selected_pre_v1.json diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 5ff030f76..5bd595059 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -1344,6 +1344,10 @@ "group": "artifacts", "target": "backend/app/modules/checkers/api/forge_locator.py" }, + { + "group": "artifacts", + "target": "backend/app/modules/checkers/api/historical_selected_pre_submit.py" + }, { "group": "artifacts", "target": "backend/app/modules/checkers/api/history.py" @@ -2661,7 +2665,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "e33f74715c05aa7421172de067b9b199daf6655580361a6eb740d31e8b825aaf", + "authority_digest": "b6cc06f83827bf37427589437c71a084255f91a27b66bcc4109eebe8ba0160b2", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 5da406c22..13a8fb82e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1190,3 +1190,16 @@ excluded. Claims/finalization use DB time and cannot outlive ART's hard deadline Architecture/security found this replacement feasible; it is not implemented by the preceding source-lock port. Fetched `origin/main` remains `94334ccf4`, already an ancestor of this branch. + +The retained v1 reader now uses a separate frozen data decoder, containing only +lineage/request/lease/result/terminal values and no coordination or capability +ports. The read projection uses that decoder, so the live source-first request +can be changed without rewriting historical canonical bytes. A fixed v1 request +and terminal vector preserves both hashes; altered request binding/timing and +row terminal digest are rejected. Historical values cannot enter the live +reservation or lease constructor, even with identical field values. The first +test used an incomplete session stub; it now opens a real unbound SQLAlchemy root +and proves rejection before TASK/DB access. All 250 focused decoder/projection, +owner and lane checks pass. This is the read side of the coordinated replacement; +new v1 write prohibition, v2 live request/SQL guards and removal of the prepared +producer remain pending and are not implied by this checkpoint. diff --git a/backend/app/modules/checkers/api/historical_selected_pre_submit.py b/backend/app/modules/checkers/api/historical_selected_pre_submit.py new file mode 100644 index 000000000..4452945c1 --- /dev/null +++ b/backend/app/modules/checkers/api/historical_selected_pre_submit.py @@ -0,0 +1,706 @@ +"""Read-only decoding of retained prepared-source PRE v1 evidence. + +These types preserve the original canonical request/terminal representation. +They have no coordination, authority, capability or execution ports. Live owners +must not accept them as a new request or a lease, even when their fields match. +This decoder exists for retained data during source-first replacement, not for +an alternative executable PRE implementation. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from datetime import datetime +from typing import Literal +from uuid import UUID + +from app.core.hashing import canonical_json_hash +from app.modules.checkers.api.default_checker import ( + WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, WorkstreamDefaultCheckerResult, +) +from app.modules.checkers.api.external import ExternalCheckerExecutionResult + + +@dataclass(frozen=True, slots=True) +class _HistoricalAdmissionLineage: + """Immutable TASK, PROJECT, packet and manifest facts needed after verification.""" + + predecessor_submission_id: UUID | None + predecessor_submission_version: int | None + checker_remediation_manifest_id: UUID | None + guide_id: UUID + guide_version: str + source_snapshot_id: UUID + source_snapshot_sha256: str + locked_guide_sha256: str + effective_policy_id: UUID + effective_policy_sha256: str + pre_submit_policy_id: UUID + pre_submit_policy_sha256: str + effective_plan_sha256: str + rules_sha256: str + external_checker_policies_sha256: str + post_submit_policy_sha256: str + post_submit_policy_body: dict[str, object] + locked_policy_context_hash: str + semantic_manifest_id: UUID + semantic_manifest_body: dict[str, object] + packet_sha256: str + storage_scheme: str + revision_preparation_id: UUID | None = None + revision_preparation_sha256: str | None = None + + def __post_init__(self) -> None: + identifiers = ( + self.guide_id, + self.source_snapshot_id, + self.effective_policy_id, + self.pre_submit_policy_id, + self.semantic_manifest_id, + ) + digests = ( + self.source_snapshot_sha256, + self.locked_guide_sha256, + self.effective_policy_sha256, + self.pre_submit_policy_sha256, + self.effective_plan_sha256, + self.rules_sha256, + self.external_checker_policies_sha256, + self.post_submit_policy_sha256, + self.locked_policy_context_hash, + self.packet_sha256, + ) + if ( + any(type(value) is not UUID for value in identifiers) + or (self.predecessor_submission_id is None) + != (self.predecessor_submission_version is None) + or ( + self.predecessor_submission_id is not None + and type(self.predecessor_submission_id) is not UUID + ) + or ( + self.predecessor_submission_version is not None + and ( + type(self.predecessor_submission_version) is not int + or self.predecessor_submission_version < 1 + ) + ) + or (self.predecessor_submission_id is None) + != (self.checker_remediation_manifest_id is None) + or (self.revision_preparation_id is None) + != (self.revision_preparation_sha256 is None) + or (self.revision_preparation_id is not None and ( + type(self.revision_preparation_id) is not UUID + or self.predecessor_submission_id is None + )) + or (self.revision_preparation_sha256 is not None and ( + type(self.revision_preparation_sha256) is not str + or len(self.revision_preparation_sha256) != 71 + or not self.revision_preparation_sha256.startswith("sha256:") + or any(character not in "0123456789abcdef" + for character in self.revision_preparation_sha256[7:]) + )) + or ( + self.checker_remediation_manifest_id is not None + and type(self.checker_remediation_manifest_id) is not UUID + ) + or not self.guide_version.strip() + or any( + type(value) is not str or len(value) != 71 or not value.startswith("sha256:") + for value in digests + ) + or type(self.semantic_manifest_body) is not dict + or type(self.post_submit_policy_body) is not dict + or canonical_json_hash( + { + key: value + for key, value in self.post_submit_policy_body.items() + if key != "policy_sha256" + } + ) + != self.post_submit_policy_sha256 + or self.post_submit_policy_body.get("policy_sha256") != self.post_submit_policy_sha256 + or self.storage_scheme not in {"local", "s3"} + ): + raise ValueError("selected PRE admission lineage is invalid") + + def canonical_body(self) -> dict[str, object]: + """Return every fact later copied into verified admission custody.""" + body = { + "predecessor_submission_id": ( + str(self.predecessor_submission_id) + if self.predecessor_submission_id is not None + else None + ), + "predecessor_submission_version": self.predecessor_submission_version, + "checker_remediation_manifest_id": ( + str(self.checker_remediation_manifest_id) + if self.checker_remediation_manifest_id is not None + else None + ), + "guide_id": str(self.guide_id), + "guide_version": self.guide_version, + "source_snapshot_id": str(self.source_snapshot_id), + "source_snapshot_sha256": self.source_snapshot_sha256, + "locked_guide_sha256": self.locked_guide_sha256, + "effective_policy_id": str(self.effective_policy_id), + "effective_policy_sha256": self.effective_policy_sha256, + "pre_submit_policy_id": str(self.pre_submit_policy_id), + "pre_submit_policy_sha256": self.pre_submit_policy_sha256, + "effective_plan_sha256": self.effective_plan_sha256, + "rules_sha256": self.rules_sha256, + "external_checker_policies_sha256": (self.external_checker_policies_sha256), + "post_submit_policy_sha256": self.post_submit_policy_sha256, + "post_submit_policy_body": self.post_submit_policy_body, + "locked_policy_context_hash": self.locked_policy_context_hash, + "semantic_manifest_id": str(self.semantic_manifest_id), + "semantic_manifest_body": self.semantic_manifest_body, + "packet_sha256": self.packet_sha256, + "storage_scheme": self.storage_scheme, + } + # Preserve the exact canonical bytes of retained requests without an + # acknowledgement; new revision requests include both frozen facts. + if self.revision_preparation_id is not None: + body["revision_preparation_id"] = str(self.revision_preparation_id) + body["revision_preparation_sha256"] = self.revision_preparation_sha256 + return body + + @classmethod + def from_canonical_body(cls, body: object) -> _HistoricalAdmissionLineage: + """Parse the exact closed body copied into ART's durable intent.""" + required = { + "predecessor_submission_id", + "predecessor_submission_version", + "checker_remediation_manifest_id", + "guide_id", + "guide_version", + "source_snapshot_id", + "source_snapshot_sha256", + "locked_guide_sha256", + "effective_policy_id", + "effective_policy_sha256", + "pre_submit_policy_id", + "pre_submit_policy_sha256", + "effective_plan_sha256", + "rules_sha256", + "external_checker_policies_sha256", + "post_submit_policy_sha256", + "post_submit_policy_body", + "locked_policy_context_hash", + "semantic_manifest_id", + "semantic_manifest_body", + "packet_sha256", + "storage_scheme", + } + if type(body) is not dict or set(body) not in ( + required, required | {"revision_preparation_id", "revision_preparation_sha256"}, + ): + raise ValueError("selected PRE admission lineage is invalid") + if "revision_preparation_id" in body and ( + body["revision_preparation_id"] is None + or body["revision_preparation_sha256"] is None + ): + raise ValueError("selected PRE admission lineage is invalid") + predecessor = body["predecessor_submission_id"] + return cls( + predecessor_submission_id=(UUID(str(predecessor)) if predecessor is not None else None), + predecessor_submission_version=body["predecessor_submission_version"], + checker_remediation_manifest_id=( + UUID(str(body["checker_remediation_manifest_id"])) + if body["checker_remediation_manifest_id"] is not None + else None + ), + guide_id=UUID(str(body["guide_id"])), + guide_version=body["guide_version"], + source_snapshot_id=UUID(str(body["source_snapshot_id"])), + source_snapshot_sha256=body["source_snapshot_sha256"], + locked_guide_sha256=body["locked_guide_sha256"], + effective_policy_id=UUID(str(body["effective_policy_id"])), + effective_policy_sha256=body["effective_policy_sha256"], + pre_submit_policy_id=UUID(str(body["pre_submit_policy_id"])), + pre_submit_policy_sha256=body["pre_submit_policy_sha256"], + effective_plan_sha256=body["effective_plan_sha256"], + rules_sha256=body["rules_sha256"], + external_checker_policies_sha256=body["external_checker_policies_sha256"], + post_submit_policy_sha256=body["post_submit_policy_sha256"], + post_submit_policy_body=body["post_submit_policy_body"], + locked_policy_context_hash=body["locked_policy_context_hash"], + semantic_manifest_id=UUID(str(body["semantic_manifest_id"])), + semantic_manifest_body=body["semantic_manifest_body"], + packet_sha256=body["packet_sha256"], + storage_scheme=body["storage_scheme"], + revision_preparation_id=( + UUID(str(body["revision_preparation_id"])) + if body.get("revision_preparation_id") is not None else None + ), + revision_preparation_sha256=body.get("revision_preparation_sha256"), + ) + + + +@dataclass(frozen=True, slots=True) +class _HistoricalIsolationFacts: + """Observed sandbox identity detached from the trusted service response.""" + + repository: str + platform_manifest_digest: str + platform_manifest_media_type: str + platform_manifest_byte_count: int + operating_system: str + architecture: str + config_image_id: str + runtime: str + isolation_mode: str + sandbox_uid: int + sandbox_gid: int + + + +@dataclass(frozen=True, slots=True) +class _HistoricalMemberFacts: + """One completed required project PRE image in canonical policy order.""" + + order: int + requirement_id: str + registry_entry_id: UUID + registry_entry_digest: str + request_digest: str + result: ExternalCheckerExecutionResult + isolation: _HistoricalIsolationFacts + + def __post_init__(self) -> None: + if ( + type(self.order) is not int + or self.order < 0 + or not self.requirement_id + or self.result.outcome != "completed" + or self.result.request_digest != self.request_digest + or self.result.registry_entry_id != self.registry_entry_id + or self.result.registry_entry_digest != self.registry_entry_digest + ): + raise ValueError("external PRE member facts are invalid") + + + +@dataclass(frozen=True, slots=True) +class _HistoricalExecutionFacts: + """One default result followed by the executed required external prefix.""" + + policy_sha256: str + workstream_default: WorkstreamDefaultCheckerResult + required_external_count: int + external_members: tuple[_HistoricalMemberFacts, ...] + eligible: bool + + def __post_init__(self) -> None: + members = self.external_members + if ( + not self.policy_sha256.startswith("sha256:") + or len(self.policy_sha256) != 71 + or type(self.required_external_count) is not int + or self.required_external_count < 0 + or tuple(item.order for item in members) != tuple(range(len(members))) + or len({item.requirement_id for item in members}) != len(members) + or len(members) > self.required_external_count + ): + raise ValueError("selected PRE execution facts are invalid") + external_passed = all(item.result.verdict == "passed" for item in members) + complete = len(members) == self.required_external_count + if self.eligible != (self.workstream_default.eligible and complete and external_passed): + raise ValueError("selected PRE eligibility differs from required results") + if ( + not self.workstream_default.eligible + and members + or any(item.result.verdict == "failed" for item in members[:-1]) + ): + raise ValueError("selected PRE execution continued after a blocker") + + def canonical_body(self) -> dict[str, object]: + """Return the complete bounded result body retained by the durable owner.""" + return { + "schema_version": "workstream.selected_pre_submit_execution.v1", + "policy_sha256": self.policy_sha256, + "workstream_default": self.workstream_default.model_dump(mode="json"), + "required_external_count": self.required_external_count, + "external_members": [ + { + "order": member.order, + "requirement_id": member.requirement_id, + "registry_entry_id": str(member.registry_entry_id), + "registry_entry_digest": member.registry_entry_digest, + "request_digest": member.request_digest, + "result": member.result.model_dump(mode="json"), + "isolation": asdict(member.isolation), + } + for member in self.external_members + ], + "eligible": self.eligible, + } + + @classmethod + def from_canonical_body(cls, body: object) -> _HistoricalExecutionFacts: + """Parse the exact bounded result retained for idempotent work replay.""" + if ( + type(body) is not dict + or set(body) + != { + "schema_version", + "policy_sha256", + "workstream_default", + "required_external_count", + "external_members", + "eligible", + } + or body["schema_version"] != "workstream.selected_pre_submit_execution.v1" + ): + raise ValueError("selected PRE execution facts are invalid") + members = body["external_members"] + if type(members) is not list: + raise ValueError("selected PRE execution facts are invalid") + return cls( + policy_sha256=body["policy_sha256"], + workstream_default=WorkstreamDefaultCheckerResult.model_validate( + body["workstream_default"] + ), + required_external_count=body["required_external_count"], + external_members=tuple( + _HistoricalMemberFacts( + order=item["order"], + requirement_id=item["requirement_id"], + registry_entry_id=UUID(str(item["registry_entry_id"])), + registry_entry_digest=item["registry_entry_digest"], + request_digest=item["request_digest"], + result=ExternalCheckerExecutionResult.model_validate( + item["result"] + | {"registry_entry_id": UUID(str(item["result"]["registry_entry_id"]))} + ), + isolation=_HistoricalIsolationFacts(**item["isolation"]), + ) + for item in members + ), + eligible=body["eligible"], + ) + + @property + def result_digest(self) -> str: + """Bind every default, project-image and observed-isolation result fact.""" + return canonical_json_hash(self.canonical_body()) + + + +@dataclass(frozen=True, slots=True) +class HistoricalSelectedPreSubmitReservation: + """Complete durable PRE request reserved before any external work starts.""" + + actor_profile_id: UUID + identity_link_id: UUID + project_id: UUID + task_id: UUID + assignment_id: UUID + attempt_id: UUID + idempotency_key: UUID + attempt_request_digest: str + prepared_generation_id: UUID + policy_sha256: str + default_behavior_sha256: str + default_input_sha256: str + archive_sha256: str + archive_byte_count: int + semantic_manifest_sha256: str + execution_budget_ms: int + admission_lineage: _HistoricalAdmissionLineage | None = None + + def __post_init__(self) -> None: + """Reject partial authority, material, policy or default-input custody.""" + identifiers = ( + self.actor_profile_id, + self.identity_link_id, + self.project_id, + self.task_id, + self.assignment_id, + self.attempt_id, + self.idempotency_key, + self.prepared_generation_id, + ) + digests = ( + self.attempt_request_digest, + self.policy_sha256, + self.default_behavior_sha256, + self.default_input_sha256, + self.archive_sha256, + self.semantic_manifest_sha256, + ) + if ( + any(type(value) is not UUID for value in identifiers) + or any( + type(value) is not str or len(value) != 71 or not value.startswith("sha256:") + for value in digests + ) + or self.default_behavior_sha256 != WORKSTREAM_DEFAULT_BEHAVIOR_SHA256 + or type(self.archive_byte_count) is not int + or self.archive_byte_count < 0 + or type(self.execution_budget_ms) is not int + or not 100 <= self.execution_budget_ms <= 14_400_000 + or ( + self.admission_lineage is not None + and type(self.admission_lineage) is not _HistoricalAdmissionLineage + ) + or ( + self.admission_lineage is not None + and ( + canonical_json_hash(self.admission_lineage.semantic_manifest_body) + != self.semantic_manifest_sha256 + or self.admission_lineage.effective_plan_sha256 != self.policy_sha256 + ) + ) + ): + raise ValueError("selected PRE reservation facts are invalid") + + def canonical_body(self) -> dict[str, object]: + """Bind the actual contributor, task, ART generation, policy and bytes.""" + return { + "schema_version": "workstream.selected_pre_submit_reservation.v1", + "actor_profile_id": str(self.actor_profile_id), + "identity_link_id": str(self.identity_link_id), + "project_id": str(self.project_id), + "task_id": str(self.task_id), + "assignment_id": str(self.assignment_id), + "attempt_id": str(self.attempt_id), + "idempotency_key": str(self.idempotency_key), + "attempt_request_digest": self.attempt_request_digest, + "prepared_generation_id": str(self.prepared_generation_id), + "policy_sha256": self.policy_sha256, + "default_behavior_sha256": self.default_behavior_sha256, + "default_input_sha256": self.default_input_sha256, + "archive_sha256": self.archive_sha256, + "archive_byte_count": self.archive_byte_count, + "semantic_manifest_sha256": self.semantic_manifest_sha256, + "execution_budget_ms": self.execution_budget_ms, + "admission_lineage": ( + self.admission_lineage.canonical_body() + if self.admission_lineage is not None + else None + ), + } + + @classmethod + def from_canonical_body(cls, body: object) -> HistoricalSelectedPreSubmitReservation: + """Recover and validate the durable request snapshot at ART publication.""" + if ( + type(body) is not dict + or set(body) + != { + "schema_version", + "actor_profile_id", + "identity_link_id", + "project_id", + "task_id", + "assignment_id", + "attempt_id", + "idempotency_key", + "attempt_request_digest", + "prepared_generation_id", + "policy_sha256", + "default_behavior_sha256", + "default_input_sha256", + "archive_sha256", + "archive_byte_count", + "semantic_manifest_sha256", + "execution_budget_ms", + "admission_lineage", + } + or body["schema_version"] != "workstream.selected_pre_submit_reservation.v1" + ): + raise ValueError("selected PRE reservation facts are invalid") + lineage_body = body["admission_lineage"] + return cls( + actor_profile_id=UUID(str(body["actor_profile_id"])), + identity_link_id=UUID(str(body["identity_link_id"])), + project_id=UUID(str(body["project_id"])), + task_id=UUID(str(body["task_id"])), + assignment_id=UUID(str(body["assignment_id"])), + attempt_id=UUID(str(body["attempt_id"])), + idempotency_key=UUID(str(body["idempotency_key"])), + attempt_request_digest=body["attempt_request_digest"], + prepared_generation_id=UUID(str(body["prepared_generation_id"])), + policy_sha256=body["policy_sha256"], + default_behavior_sha256=body["default_behavior_sha256"], + default_input_sha256=body["default_input_sha256"], + archive_sha256=body["archive_sha256"], + archive_byte_count=body["archive_byte_count"], + semantic_manifest_sha256=body["semantic_manifest_sha256"], + execution_budget_ms=body["execution_budget_ms"], + admission_lineage=( + _HistoricalAdmissionLineage.from_canonical_body(lineage_body) + if lineage_body is not None + else None + ), + ) + + @property + def request_digest(self) -> str: + """Return the immutable request identity used by reserve and replay.""" + return canonical_json_hash(self.canonical_body()) + + + +@dataclass(frozen=True, slots=True) +class _HistoricalLeaseFacts: + """Database-timed generation for one genuine pre-admission ART attempt.""" + + reservation: HistoricalSelectedPreSubmitReservation + lease_id: UUID + lease_generation: int + lease_expires_at: datetime + + def __post_init__(self) -> None: + """Reject a copied identifier or an unbounded/non-current lease shape.""" + if ( + type(self.reservation) is not HistoricalSelectedPreSubmitReservation + or type(self.lease_id) is not UUID + or type(self.lease_generation) is not int + or self.lease_generation < 1 + or self.lease_expires_at.tzinfo is None + ): + raise ValueError("selected PRE lease facts are invalid") + + + +@dataclass(frozen=True, slots=True) +class HistoricalSelectedPreSubmitTerminal: + """Exact terminal value finalized under a fresh TASK-first transaction.""" + + lease: _HistoricalLeaseFacts + outcome: Literal["completed", "infrastructure_failed"] + execution: _HistoricalExecutionFacts | None + infrastructure_failure_code: str | None + queued_at: datetime + started_at: datetime + completed_at: datetime + + def __post_init__(self) -> None: + """Keep work findings separate from recoverable infrastructure outcomes.""" + if type(self.lease) is not _HistoricalLeaseFacts: + raise ValueError("selected PRE terminal lease is invalid") + if any( + value.tzinfo is None + for value in ( + self.queued_at, + self.started_at, + self.completed_at, + ) + ) or not (self.queued_at <= self.started_at <= self.completed_at): + raise ValueError("selected PRE terminal timing is invalid") + if self.outcome == "completed": + if ( + type(self.execution) is not _HistoricalExecutionFacts + or self.infrastructure_failure_code is not None + or self.execution.policy_sha256 != self.lease.reservation.policy_sha256 + ): + raise ValueError("selected PRE completed outcome is invalid") + elif self.execution is not None or self.infrastructure_failure_code not in { + "capacity_exceeded", + "deadline_exceeded", + "material_unavailable", + "implementation_unavailable", + "invalid_output", + }: + raise ValueError("selected PRE infrastructure outcome is invalid") + + def canonical_body(self) -> dict[str, object]: + """Return persisted latency, lease and terminal facts without private paths.""" + return { + "schema_version": "workstream.selected_pre_submit_terminal.v1", + "reservation": self.lease.reservation.canonical_body(), + "request_digest": self.lease.reservation.request_digest, + "lease_id": str(self.lease.lease_id), + "lease_generation": self.lease.lease_generation, + "lease_expires_at": self.lease.lease_expires_at.isoformat(), + "outcome": self.outcome, + "execution": self.execution.canonical_body() if self.execution else None, + "infrastructure_failure_code": self.infrastructure_failure_code, + "queued_at": self.queued_at.isoformat(), + "started_at": self.started_at.isoformat(), + "completed_at": self.completed_at.isoformat(), + "queue_latency_ms": int((self.started_at - self.queued_at).total_seconds() * 1000), + "execution_latency_ms": int( + (self.completed_at - self.started_at).total_seconds() * 1000 + ), + } + + @classmethod + def from_canonical_body(cls, body: object) -> HistoricalSelectedPreSubmitTerminal: + """Parse and revalidate every persisted lease, result and timing fact.""" + if ( + type(body) is not dict + or set(body) + != { + "schema_version", + "reservation", + "request_digest", + "lease_id", + "lease_generation", + "lease_expires_at", + "outcome", + "execution", + "infrastructure_failure_code", + "queued_at", + "started_at", + "completed_at", + "queue_latency_ms", + "execution_latency_ms", + } + or body["schema_version"] != "workstream.selected_pre_submit_terminal.v1" + ): + raise ValueError("selected PRE terminal facts are invalid") + reservation = HistoricalSelectedPreSubmitReservation.from_canonical_body(body["reservation"]) + if body["request_digest"] != reservation.request_digest: + raise ValueError("selected PRE terminal request is invalid") + execution_body = body["execution"] + value = cls( + lease=_HistoricalLeaseFacts( + reservation=reservation, + lease_id=UUID(str(body["lease_id"])), + lease_generation=body["lease_generation"], + lease_expires_at=datetime.fromisoformat(body["lease_expires_at"]), + ), + outcome=body["outcome"], + execution=( + _HistoricalExecutionFacts.from_canonical_body(execution_body) + if execution_body is not None + else None + ), + infrastructure_failure_code=body["infrastructure_failure_code"], + queued_at=datetime.fromisoformat(body["queued_at"]), + started_at=datetime.fromisoformat(body["started_at"]), + completed_at=datetime.fromisoformat(body["completed_at"]), + ) + if value.canonical_body() != body: + raise ValueError("selected PRE terminal facts are invalid") + return value + + @property + def terminal_digest(self) -> str: + """Bind the exact terminal body used by replay and admission.""" + return canonical_json_hash(self.canonical_body()) + + + +class _HistoricalInfrastructureUnavailable(RuntimeError): + """Retain a recoverable PRE infrastructure category, never a work failure.""" + + def __init__(self, code: str) -> None: + if code not in { + "capacity_exceeded", + "deadline_exceeded", + "material_unavailable", + "implementation_unavailable", + "invalid_output", + }: + raise ValueError("selected PRE infrastructure failure is invalid") + self.code = code + super().__init__(code) + + + +__all__ = ("HistoricalSelectedPreSubmitReservation", "HistoricalSelectedPreSubmitTerminal") diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py index 4366f573e..ee8642ada 100644 --- a/backend/app/modules/checkers/api/selected_pre_submit.py +++ b/backend/app/modules/checkers/api/selected_pre_submit.py @@ -12,6 +12,7 @@ from app.modules.checkers.api.default_checker import WORKSTREAM_DEFAULT_BEHAVIOR_SHA256 from app.modules.checkers.api.default_checker import WorkstreamDefaultCheckerResult from app.modules.checkers.api.external import ExternalCheckerExecutionResult +from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal @dataclass(frozen=True, slots=True) @@ -936,7 +937,7 @@ class SelectedPreSubmitRunView: archive_byte_count: int queued_at: datetime completed_at: datetime | None - terminal: SelectedPreSubmitTerminalFacts | None + terminal: SelectedPreSubmitTerminalFacts | HistoricalSelectedPreSubmitTerminal | None class SelectedPreSubmitRunReadPort(Protocol): diff --git a/backend/app/modules/checkers/selected_pre_submit_reads.py b/backend/app/modules/checkers/selected_pre_submit_reads.py index 55209ee88..00f9bae0c 100644 --- a/backend/app/modules/checkers/selected_pre_submit_reads.py +++ b/backend/app/modules/checkers/selected_pre_submit_reads.py @@ -6,9 +6,10 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitRunStatus, SelectedPreSubmitRunView, SelectedPreSubmitTerminalFacts, + SelectedPreSubmitRunStatus, SelectedPreSubmitRunView, SelectedPreSubmitUnavailable, ) +from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal from app.modules.checkers.models import SelectedPreSubmitRun @@ -16,7 +17,7 @@ def _view(row: SelectedPreSubmitRun) -> SelectedPreSubmitRunView: """Revalidate one stored terminal body against its fixed columns.""" try: terminal = ( - SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json) + HistoricalSelectedPreSubmitTerminal.from_canonical_body(row.terminal_json) if row.terminal_json is not None else None ) except (TypeError, ValueError): diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 6de52fc91..8c50a5329 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -356,6 +356,7 @@ "backend/app/modules/checkers/api/pre_submit_material.py", "backend/app/modules/checkers/api/selected_post_submit.py", "backend/app/modules/checkers/api/selected_pre_submit.py", + "backend/app/modules/checkers/api/historical_selected_pre_submit.py", "backend/app/modules/checkers/selected_post_submit_execution.py", "backend/app/modules/checkers/selected_pre_submit_coordination.py", "backend/app/modules/checkers/selected_pre_submit_execution.py", diff --git a/backend/tests/checkers/external/fixtures/selected_pre_v1.json b/backend/tests/checkers/external/fixtures/selected_pre_v1.json new file mode 100644 index 000000000..7c9ec55a5 --- /dev/null +++ b/backend/tests/checkers/external/fixtures/selected_pre_v1.json @@ -0,0 +1,59 @@ +{ + "request": { + "schema_version": "workstream.selected_pre_submit_reservation.v1", + "actor_profile_id": "01900000-0000-7000-8000-000000000001", + "identity_link_id": "01900000-0000-7000-8000-000000000002", + "project_id": "01900000-0000-7000-8000-000000000003", + "task_id": "01900000-0000-7000-8000-000000000004", + "assignment_id": "01900000-0000-7000-8000-000000000005", + "attempt_id": "01900000-0000-7000-8000-000000000006", + "idempotency_key": "01900000-0000-7000-8000-000000000007", + "attempt_request_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "prepared_generation_id": "01900000-0000-7000-8000-000000000008", + "policy_sha256": "sha256:1111111111111111111111111111111111111111111111111111111111111111", + "default_behavior_sha256": "sha256:af2c604f792c4456d3b222036c772161b1503eace65ff90c3d3a23d9d348c28f", + "default_input_sha256": "sha256:2222222222222222222222222222222222222222222222222222222222222222", + "archive_sha256": "sha256:3333333333333333333333333333333333333333333333333333333333333333", + "archive_byte_count": 1024, + "semantic_manifest_sha256": "sha256:4444444444444444444444444444444444444444444444444444444444444444", + "execution_budget_ms": 120000, + "admission_lineage": null + }, + "request_digest": "sha256:4acb5f585bc770f59847b9b011ae7608e106793118ddd73dba1570cfb6fd87d0", + "terminal": { + "schema_version": "workstream.selected_pre_submit_terminal.v1", + "reservation": { + "schema_version": "workstream.selected_pre_submit_reservation.v1", + "actor_profile_id": "01900000-0000-7000-8000-000000000001", + "identity_link_id": "01900000-0000-7000-8000-000000000002", + "project_id": "01900000-0000-7000-8000-000000000003", + "task_id": "01900000-0000-7000-8000-000000000004", + "assignment_id": "01900000-0000-7000-8000-000000000005", + "attempt_id": "01900000-0000-7000-8000-000000000006", + "idempotency_key": "01900000-0000-7000-8000-000000000007", + "attempt_request_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "prepared_generation_id": "01900000-0000-7000-8000-000000000008", + "policy_sha256": "sha256:1111111111111111111111111111111111111111111111111111111111111111", + "default_behavior_sha256": "sha256:af2c604f792c4456d3b222036c772161b1503eace65ff90c3d3a23d9d348c28f", + "default_input_sha256": "sha256:2222222222222222222222222222222222222222222222222222222222222222", + "archive_sha256": "sha256:3333333333333333333333333333333333333333333333333333333333333333", + "archive_byte_count": 1024, + "semantic_manifest_sha256": "sha256:4444444444444444444444444444444444444444444444444444444444444444", + "execution_budget_ms": 120000, + "admission_lineage": null + }, + "request_digest": "sha256:4acb5f585bc770f59847b9b011ae7608e106793118ddd73dba1570cfb6fd87d0", + "lease_id": "01900000-0000-7000-8000-000000000009", + "lease_generation": 1, + "lease_expires_at": "2026-01-01T00:02:00+00:00", + "outcome": "infrastructure_failed", + "execution": null, + "infrastructure_failure_code": "material_unavailable", + "queued_at": "2026-01-01T00:00:00+00:00", + "started_at": "2026-01-01T00:00:01+00:00", + "completed_at": "2026-01-01T00:00:02+00:00", + "queue_latency_ms": 1000, + "execution_latency_ms": 1000 + }, + "terminal_digest": "sha256:71dfc79d89afad5d8fea60e28e5ff9a46ef5e16ab100de186bf55851893cefc0" +} diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index cc5cbff4a..b73eb18d6 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -484,3 +484,67 @@ def test_selected_ready_admission_binds_selected_run() -> None: facts = SubmissionAdmissionConsumptionService._authority_facts(admission, request) assert facts.evidence_set_id is None assert facts.selected_pre_submit_run_id == run_id + + +def _retained_v1(): + """Fixed pre-cutover bytes; never regenerated from the live request schema.""" + import json + from pathlib import Path + + return json.loads((Path(__file__).parent / "fixtures" / "selected_pre_v1.json").read_text()) + + +def test_historical_pre_decoder_preserves_exact_request_and_terminal_bytes(): + from app.modules.checkers.api.historical_selected_pre_submit import ( + HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal, + ) + from app.modules.checkers.selected_pre_submit_reads import _view + + retained = _retained_v1() + request = HistoricalSelectedPreSubmitReservation.from_canonical_body(retained["request"]) + terminal = HistoricalSelectedPreSubmitTerminal.from_canonical_body(retained["terminal"]) + assert request.canonical_body() == retained["request"] + assert request.request_digest == retained["request_digest"] + assert terminal.canonical_body() == retained["terminal"] + assert terminal.terminal_digest == retained["terminal_digest"] + row = SimpleNamespace( + id=str(request.attempt_id), actor_profile_id=str(request.actor_profile_id), + task_id=str(request.task_id), assignment_id=str(request.assignment_id), + status="infrastructure_failed", archive_sha256=request.archive_sha256, + archive_byte_count=request.archive_byte_count, queued_at=terminal.queued_at, + completed_at=terminal.completed_at, terminal_json=retained["terminal"], + terminal_digest=retained["terminal_digest"], eligible=None, + ) + view = _view(row) + assert type(view.terminal) is HistoricalSelectedPreSubmitTerminal + assert view.terminal.canonical_body() == retained["terminal"] + row.terminal_digest = "sha256:" + "f" * 64 + with pytest.raises(SelectedPreSubmitUnavailable): + _view(row) + + +@pytest.mark.asyncio +async def test_historical_pre_values_cannot_become_live_reservation_or_lease(): + from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitReservation + + request = HistoricalSelectedPreSubmitReservation.from_canonical_body(_retained_v1()["request"]) + from sqlalchemy.ext.asyncio import AsyncSession + + tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock()) + async with AsyncSession() as session, session.begin(): + coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks) + with pytest.raises(TypeError, match="reservation facts are invalid"): + await coordinator.reserve(request) + tasks.lock_selected_pre_submit_scope.assert_not_awaited() + with pytest.raises(ValueError, match="lease facts are invalid"): + SelectedPreSubmitLeaseFacts(request, new_record_id(), 1, datetime.now(UTC)) + + +@pytest.mark.parametrize("field", ["request_digest", "queue_latency_ms", "execution_latency_ms"]) +def test_historical_pre_decoder_rejects_changed_binding_or_timing(field): + from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal + + body = _retained_v1()["terminal"] + body[field] = "sha256:" + "f" * 64 if field == "request_digest" else body[field] + 1 + with pytest.raises(ValueError): + HistoricalSelectedPreSubmitTerminal.from_canonical_body(body) From 90fc30643cfeb3caf8aac0e3e0eb5a8b113a7627 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 11:29:33 +0100 Subject: [PATCH 051/513] Bind historical PRE reads to exact retained row facts --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 19 ++ .../api/historical_selected_pre_submit.py | 2 +- .../checkers/selected_pre_submit_reads.py | 65 ++++- .../fixtures/selected_pre_v1_completed.json | 230 ++++++++++++++++++ .../test_selected_pre_submit_coordination.py | 99 +++++++- 5 files changed, 390 insertions(+), 25 deletions(-) create mode 100644 backend/tests/checkers/external/fixtures/selected_pre_v1_completed.json diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 13a8fb82e..ae8eb7b5d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1203,3 +1203,22 @@ and proves rejection before TASK/DB access. All 250 focused decoder/projection, owner and lane checks pass. This is the read side of the coordinated replacement; new v1 write prohibition, v2 live request/SQL guards and removal of the prepared producer remain pending and are not implied by this checkpoint. + +QA found that the inherited read projection compared terminal hash/run ID but +could accept divergent row actor/archive selectors. The repaired reader decodes +the independent retained request, compares every v1 indexed identity and source/ +policy/default/budget field, then checks terminal reservation, outcome, lease, +eligibility and timestamps. All thirteen new row-substitution controls fail with +the exact prior `18d3a5663` reader injected in memory and pass the repair. The +historical decoder also rejects an unknown outcome token explicitly; no valid +retained outcome is changed. Queued/running history stays readable without a +fabricated terminal state. + +A second fixed vector now covers complete lineage, canonical default results +and a selected project member. It was generated once through the existing ZIP/ +default pipeline with a controlled project-result adapter, not native runtime +execution or a database-origin attestation. Nested lineage/member/default +mutations are rejected. All 270 focused checks pass. The four PostgreSQL +read-consistency tests also passed with cleanup, but their fixture produced no +completed selected PRE row, so that run is not credited as historical payload +coverage. The reader's direct frozen-row tests establish that narrower claim. diff --git a/backend/app/modules/checkers/api/historical_selected_pre_submit.py b/backend/app/modules/checkers/api/historical_selected_pre_submit.py index 4452945c1..27886cd4f 100644 --- a/backend/app/modules/checkers/api/historical_selected_pre_submit.py +++ b/backend/app/modules/checkers/api/historical_selected_pre_submit.py @@ -598,7 +598,7 @@ def __post_init__(self) -> None: or self.execution.policy_sha256 != self.lease.reservation.policy_sha256 ): raise ValueError("selected PRE completed outcome is invalid") - elif self.execution is not None or self.infrastructure_failure_code not in { + elif self.outcome != "infrastructure_failed" or self.execution is not None or self.infrastructure_failure_code not in { "capacity_exceeded", "deadline_exceeded", "material_unavailable", diff --git a/backend/app/modules/checkers/selected_pre_submit_reads.py b/backend/app/modules/checkers/selected_pre_submit_reads.py index 00f9bae0c..c526b65a8 100644 --- a/backend/app/modules/checkers/selected_pre_submit_reads.py +++ b/backend/app/modules/checkers/selected_pre_submit_reads.py @@ -9,29 +9,70 @@ SelectedPreSubmitRunStatus, SelectedPreSubmitRunView, SelectedPreSubmitUnavailable, ) -from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal +from app.modules.checkers.api.historical_selected_pre_submit import ( + HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal, +) from app.modules.checkers.models import SelectedPreSubmitRun +def _request_matches(row: SelectedPreSubmitRun, request: HistoricalSelectedPreSubmitReservation) -> bool: + """Bind every v1 indexed identity to the retained canonical request.""" + identifiers = { + "id": request.attempt_id, "actor_profile_id": request.actor_profile_id, + "identity_link_id": request.identity_link_id, "project_id": request.project_id, + "task_id": request.task_id, "assignment_id": request.assignment_id, + "idempotency_key": request.idempotency_key, + "prepared_generation_id": request.prepared_generation_id, + } + return ( + row.request_json == request.canonical_body() + and row.request_digest == request.request_digest + and all(UUID(str(getattr(row, key))) == value for key, value in identifiers.items()) + and all(getattr(row, key) == getattr(request, key) for key in ( + "policy_sha256", "default_behavior_sha256", "default_input_sha256", + "archive_sha256", "archive_byte_count", "semantic_manifest_sha256", + "execution_budget_ms", + )) + ) + + +def _terminal_matches(row: SelectedPreSubmitRun, request, terminal) -> bool: + """Check retained outcome/lease/timing without conferring current liveness.""" + if terminal is None: + return ( + row.status in {"queued", "running"} and row.terminal_digest is None + and row.eligible is None and row.completed_at is None + ) + return ( + terminal.lease.reservation == request + and terminal.terminal_digest == row.terminal_digest + and terminal.outcome == row.status + and str(terminal.lease.lease_id) == str(row.lease_id) + and terminal.lease.lease_generation == row.lease_generation + and terminal.lease.lease_expires_at == row.lease_expires_at + and terminal.queued_at == row.queued_at + and terminal.started_at == row.started_at + and terminal.completed_at == row.completed_at + and (terminal.execution.eligible if terminal.execution is not None else None) is row.eligible + ) + + def _view(row: SelectedPreSubmitRun) -> SelectedPreSubmitRunView: - """Revalidate one stored terminal body against its fixed columns.""" + """Refuse any divergence between read selectors and retained v1 evidence.""" try: + request = HistoricalSelectedPreSubmitReservation.from_canonical_body(row.request_json) terminal = ( HistoricalSelectedPreSubmitTerminal.from_canonical_body(row.terminal_json) if row.terminal_json is not None else None ) - except (TypeError, ValueError): + if not _request_matches(row, request) or not _terminal_matches(row, request, terminal): + raise ValueError("retained PRE columns differ") + except (KeyError, TypeError, ValueError): raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid") from None - if terminal is not None and ( - terminal.terminal_digest != row.terminal_digest - or terminal.lease.reservation.attempt_id != UUID(str(row.id)) - or (terminal.execution is not None and terminal.execution.eligible != row.eligible) - ): - raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid") return SelectedPreSubmitRunView( - run_id=UUID(str(row.id)), actor_profile_id=UUID(str(row.actor_profile_id)), - task_id=UUID(str(row.task_id)), assignment_id=UUID(str(row.assignment_id)), status=row.status, - archive_sha256=row.archive_sha256, archive_byte_count=row.archive_byte_count, + run_id=request.attempt_id, actor_profile_id=request.actor_profile_id, + task_id=request.task_id, assignment_id=request.assignment_id, status=row.status, + archive_sha256=request.archive_sha256, archive_byte_count=request.archive_byte_count, queued_at=row.queued_at, completed_at=row.completed_at, terminal=terminal, ) diff --git a/backend/tests/checkers/external/fixtures/selected_pre_v1_completed.json b/backend/tests/checkers/external/fixtures/selected_pre_v1_completed.json new file mode 100644 index 000000000..ca8f8fb58 --- /dev/null +++ b/backend/tests/checkers/external/fixtures/selected_pre_v1_completed.json @@ -0,0 +1,230 @@ +{ + "request": { + "actor_profile_id": "01a1cf4c-d6c9-7216-882d-5e7a771cba31", + "admission_lineage": { + "checker_remediation_manifest_id": null, + "effective_plan_sha256": "sha256:c53d4239196e812de756e7816d10ee6dd753e7305f27fdbd11383215254d3a1f", + "effective_policy_id": "01a1cf4c-d6c6-7418-8bca-8e321bc3348e", + "effective_policy_sha256": "sha256:3333333333333333333333333333333333333333333333333333333333333333", + "external_checker_policies_sha256": "sha256:9999999999999999999999999999999999999999999999999999999999999999", + "guide_id": "01a1cf4c-d6c4-7ede-add7-f9bd12e64560", + "guide_version": "v2", + "locked_guide_sha256": "sha256:2222222222222222222222222222222222222222222222222222222222222222", + "locked_policy_context_hash": "sha256:6666666666666666666666666666666666666666666666666666666666666666", + "packet_sha256": "sha256:e0d6ac76841a549e4333e21fb8d4314f57e0e7445bb89d4d87df14304d3ca977", + "post_submit_policy_body": { + "entries": [], + "policy_sha256": "sha256:ffcd8b8e350f4d11a53731faf9b41c97e09562a78178bdbfb96c300b4994d401", + "schema_version": "external_post_submit_policy.v1" + }, + "post_submit_policy_sha256": "sha256:ffcd8b8e350f4d11a53731faf9b41c97e09562a78178bdbfb96c300b4994d401", + "pre_submit_policy_id": "01a1cf4c-d6c7-777d-8bdf-eb0e12879148", + "pre_submit_policy_sha256": "sha256:4444444444444444444444444444444444444444444444444444444444444444", + "predecessor_submission_id": null, + "predecessor_submission_version": null, + "rules_sha256": "sha256:8888888888888888888888888888888888888888888888888888888888888888", + "semantic_manifest_body": { + "entries": [ + { + "entry_type": "directory", + "normalized_path": "evidence" + }, + { + "byte_count": 9, + "entry_type": "file", + "executable": false, + "normalized_path": "evidence/results", + "sha256": "sha256:672eb8316fec83f94119a4193f9fc552513d56a147502f8be4830e017d817831" + }, + { + "byte_count": 20, + "entry_type": "file", + "executable": false, + "normalized_path": "task.toml", + "sha256": "sha256:db827bb156a8942c9c3f6f9a6c734959f667f0e84a8682ad1827df1e9cfc0744" + } + ], + "schema_version": "workstream.submission_bundle_manifest.v1" + }, + "semantic_manifest_id": "9dd2371a-6f33-577a-b9ab-20724b2471d0", + "source_snapshot_id": "01a1cf4c-d6c5-798a-98ae-e349ea3ac7e7", + "source_snapshot_sha256": "sha256:1111111111111111111111111111111111111111111111111111111111111111", + "storage_scheme": "s3" + }, + "archive_byte_count": 253, + "archive_sha256": "sha256:468d2c28c74d3267c606eced24803b70e02713559497efc26d6273b367a85a8a", + "assignment_id": "01a1cf4c-d6cd-75b0-bf35-75c5083fd88a", + "attempt_id": "01a1cf4c-d6ce-7e36-9146-23b07a3a300e", + "attempt_request_digest": "sha256:8888888888888888888888888888888888888888888888888888888888888888", + "default_behavior_sha256": "sha256:af2c604f792c4456d3b222036c772161b1503eace65ff90c3d3a23d9d348c28f", + "default_input_sha256": "sha256:55c5f22c51b24717ee0d87daa4f207956f5626abd3a16e9478f7416ba8498808", + "execution_budget_ms": 120000, + "idempotency_key": "01a1cf4c-d6cf-7aee-acbe-68792762e8aa", + "identity_link_id": "01a1cf4c-d6ca-776f-abe1-1eead56ec7b4", + "policy_sha256": "sha256:c53d4239196e812de756e7816d10ee6dd753e7305f27fdbd11383215254d3a1f", + "prepared_generation_id": "01a1cf4c-d6aa-7030-b53f-fa4f8c26145a", + "project_id": "01a1cf4c-d6cb-71cb-8c9b-ceb9aa6381d7", + "schema_version": "workstream.selected_pre_submit_reservation.v1", + "semantic_manifest_sha256": "sha256:dc88d211b1a40342e06eaaed145c35a1b1e9ca18c000eaf74946677ecabc502e", + "task_id": "01a1cf4c-d6cc-7685-b855-783575615290" + }, + "request_digest": "sha256:c5865ba9f9ebc8f34823c18b1900ca1e937399adde1621188770468e7fea9780", + "terminal": { + "completed_at": "2026-11-12T10:28:03.957896+00:00", + "execution": { + "eligible": true, + "external_members": [ + { + "isolation": { + "architecture": "amd64", + "config_image_id": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "isolation_mode": "gvisor", + "operating_system": "linux", + "platform_manifest_byte_count": 1024, + "platform_manifest_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "platform_manifest_media_type": "application/vnd.oci.image.manifest.v1+json", + "repository": "registry.example/workstream/checker", + "runtime": "runsc", + "sandbox_gid": 65532, + "sandbox_uid": 65532 + }, + "order": 0, + "registry_entry_digest": "sha256:2666891954c7e14a486c548a5395991ee5ff92a353495a43baee729779282e2d", + "registry_entry_id": "01a1cf4c-d6b0-777a-b9b0-40b0f8d5e63f", + "request_digest": "sha256:1ec3f0f1fb1e184245871bc579bbcba1674938a5b6c94881b94c1340d7f4ff09", + "requirement_id": "project.archive_rules", + "result": { + "findings": [], + "infrastructure_failure_code": null, + "outcome": "completed", + "phase": "pre_submit", + "registry_entry_digest": "sha256:2666891954c7e14a486c548a5395991ee5ff92a353495a43baee729779282e2d", + "registry_entry_id": "01a1cf4c-d6b0-777a-b9b0-40b0f8d5e63f", + "request_digest": "sha256:1ec3f0f1fb1e184245871bc579bbcba1674938a5b6c94881b94c1340d7f4ff09", + "result_digest": "sha256:d29b0c09210e3d41eed0d1cf9edf03cf76d6e39dc77a15cd60f3287abb049fae", + "schema_version": "external_checker_result.v1", + "verdict": "passed" + } + } + ], + "policy_sha256": "sha256:c53d4239196e812de756e7816d10ee6dd753e7305f27fdbd11383215254d3a1f", + "required_external_count": 1, + "schema_version": "workstream.selected_pre_submit_execution.v1", + "workstream_default": { + "behavior_sha256": "sha256:af2c604f792c4456d3b222036c772161b1503eace65ff90c3d3a23d9d348c28f", + "checker_id": "workstream.default", + "checker_version": "v1", + "checks": [ + { + "check_id": "archive_safe", + "failure_code": null, + "finding_count": 0, + "status": "passed" + }, + { + "check_id": "received_identity_exact", + "failure_code": null, + "finding_count": 0, + "status": "passed" + }, + { + "check_id": "high_confidence_secrets_absent", + "failure_code": null, + "finding_count": 0, + "status": "passed" + }, + { + "check_id": "submission_changed_for_current_rules", + "failure_code": null, + "finding_count": 0, + "status": "passed" + } + ], + "eligible": true, + "schema_version": "workstream.default_checker_result.v1", + "warnings": [] + } + }, + "execution_latency_ms": 1000, + "infrastructure_failure_code": null, + "lease_expires_at": "2026-11-12T10:30:01.957896+00:00", + "lease_generation": 1, + "lease_id": "01a1cf4c-d725-7a40-8da1-346570f6b642", + "outcome": "completed", + "queue_latency_ms": 1000, + "queued_at": "2026-11-12T10:28:01.957896+00:00", + "request_digest": "sha256:c5865ba9f9ebc8f34823c18b1900ca1e937399adde1621188770468e7fea9780", + "reservation": { + "actor_profile_id": "01a1cf4c-d6c9-7216-882d-5e7a771cba31", + "admission_lineage": { + "checker_remediation_manifest_id": null, + "effective_plan_sha256": "sha256:c53d4239196e812de756e7816d10ee6dd753e7305f27fdbd11383215254d3a1f", + "effective_policy_id": "01a1cf4c-d6c6-7418-8bca-8e321bc3348e", + "effective_policy_sha256": "sha256:3333333333333333333333333333333333333333333333333333333333333333", + "external_checker_policies_sha256": "sha256:9999999999999999999999999999999999999999999999999999999999999999", + "guide_id": "01a1cf4c-d6c4-7ede-add7-f9bd12e64560", + "guide_version": "v2", + "locked_guide_sha256": "sha256:2222222222222222222222222222222222222222222222222222222222222222", + "locked_policy_context_hash": "sha256:6666666666666666666666666666666666666666666666666666666666666666", + "packet_sha256": "sha256:e0d6ac76841a549e4333e21fb8d4314f57e0e7445bb89d4d87df14304d3ca977", + "post_submit_policy_body": { + "entries": [], + "policy_sha256": "sha256:ffcd8b8e350f4d11a53731faf9b41c97e09562a78178bdbfb96c300b4994d401", + "schema_version": "external_post_submit_policy.v1" + }, + "post_submit_policy_sha256": "sha256:ffcd8b8e350f4d11a53731faf9b41c97e09562a78178bdbfb96c300b4994d401", + "pre_submit_policy_id": "01a1cf4c-d6c7-777d-8bdf-eb0e12879148", + "pre_submit_policy_sha256": "sha256:4444444444444444444444444444444444444444444444444444444444444444", + "predecessor_submission_id": null, + "predecessor_submission_version": null, + "rules_sha256": "sha256:8888888888888888888888888888888888888888888888888888888888888888", + "semantic_manifest_body": { + "entries": [ + { + "entry_type": "directory", + "normalized_path": "evidence" + }, + { + "byte_count": 9, + "entry_type": "file", + "executable": false, + "normalized_path": "evidence/results", + "sha256": "sha256:672eb8316fec83f94119a4193f9fc552513d56a147502f8be4830e017d817831" + }, + { + "byte_count": 20, + "entry_type": "file", + "executable": false, + "normalized_path": "task.toml", + "sha256": "sha256:db827bb156a8942c9c3f6f9a6c734959f667f0e84a8682ad1827df1e9cfc0744" + } + ], + "schema_version": "workstream.submission_bundle_manifest.v1" + }, + "semantic_manifest_id": "9dd2371a-6f33-577a-b9ab-20724b2471d0", + "source_snapshot_id": "01a1cf4c-d6c5-798a-98ae-e349ea3ac7e7", + "source_snapshot_sha256": "sha256:1111111111111111111111111111111111111111111111111111111111111111", + "storage_scheme": "s3" + }, + "archive_byte_count": 253, + "archive_sha256": "sha256:468d2c28c74d3267c606eced24803b70e02713559497efc26d6273b367a85a8a", + "assignment_id": "01a1cf4c-d6cd-75b0-bf35-75c5083fd88a", + "attempt_id": "01a1cf4c-d6ce-7e36-9146-23b07a3a300e", + "attempt_request_digest": "sha256:8888888888888888888888888888888888888888888888888888888888888888", + "default_behavior_sha256": "sha256:af2c604f792c4456d3b222036c772161b1503eace65ff90c3d3a23d9d348c28f", + "default_input_sha256": "sha256:55c5f22c51b24717ee0d87daa4f207956f5626abd3a16e9478f7416ba8498808", + "execution_budget_ms": 120000, + "idempotency_key": "01a1cf4c-d6cf-7aee-acbe-68792762e8aa", + "identity_link_id": "01a1cf4c-d6ca-776f-abe1-1eead56ec7b4", + "policy_sha256": "sha256:c53d4239196e812de756e7816d10ee6dd753e7305f27fdbd11383215254d3a1f", + "prepared_generation_id": "01a1cf4c-d6aa-7030-b53f-fa4f8c26145a", + "project_id": "01a1cf4c-d6cb-71cb-8c9b-ceb9aa6381d7", + "schema_version": "workstream.selected_pre_submit_reservation.v1", + "semantic_manifest_sha256": "sha256:dc88d211b1a40342e06eaaed145c35a1b1e9ca18c000eaf74946677ecabc502e", + "task_id": "01a1cf4c-d6cc-7685-b855-783575615290" + }, + "schema_version": "workstream.selected_pre_submit_terminal.v1", + "started_at": "2026-11-12T10:28:02.957896+00:00" + }, + "terminal_digest": "sha256:b80ff3c92862fc92b1ae0a3f6af4898b16b192e417155fb562de76a5e1648397" +} diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index b73eb18d6..23a879dbb 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -486,35 +486,46 @@ def test_selected_ready_admission_binds_selected_run() -> None: assert facts.selected_pre_submit_run_id == run_id -def _retained_v1(): +def _retained_v1(name="selected_pre_v1"): """Fixed pre-cutover bytes; never regenerated from the live request schema.""" import json from pathlib import Path - return json.loads((Path(__file__).parent / "fixtures" / "selected_pre_v1.json").read_text()) + return json.loads((Path(__file__).parent / "fixtures" / f"{name}.json").read_text()) -def test_historical_pre_decoder_preserves_exact_request_and_terminal_bytes(): + +def _retained_row(retained): + """Complete indexed columns beside one independently frozen v1 record.""" + terminal = retained["terminal"] + values = dict(retained["request"]) + values.update( + id=values["attempt_id"], request_json=retained["request"], + request_digest=retained["request_digest"], status=terminal["outcome"], + terminal_json=terminal, terminal_digest=retained["terminal_digest"], + eligible=terminal["execution"]["eligible"] if terminal["execution"] is not None else None, + lease_id=terminal["lease_id"], lease_generation=terminal["lease_generation"], + ) + values.update({key: datetime.fromisoformat(terminal[key]) for key in ( + "queued_at", "started_at", "completed_at", "lease_expires_at", + )}) + return SimpleNamespace(**values) + +@pytest.mark.parametrize("name", ["selected_pre_v1", "selected_pre_v1_completed"]) +def test_historical_pre_decoder_preserves_exact_request_and_terminal_bytes(name): from app.modules.checkers.api.historical_selected_pre_submit import ( HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal, ) from app.modules.checkers.selected_pre_submit_reads import _view - retained = _retained_v1() + retained = _retained_v1(name) request = HistoricalSelectedPreSubmitReservation.from_canonical_body(retained["request"]) terminal = HistoricalSelectedPreSubmitTerminal.from_canonical_body(retained["terminal"]) assert request.canonical_body() == retained["request"] assert request.request_digest == retained["request_digest"] assert terminal.canonical_body() == retained["terminal"] assert terminal.terminal_digest == retained["terminal_digest"] - row = SimpleNamespace( - id=str(request.attempt_id), actor_profile_id=str(request.actor_profile_id), - task_id=str(request.task_id), assignment_id=str(request.assignment_id), - status="infrastructure_failed", archive_sha256=request.archive_sha256, - archive_byte_count=request.archive_byte_count, queued_at=terminal.queued_at, - completed_at=terminal.completed_at, terminal_json=retained["terminal"], - terminal_digest=retained["terminal_digest"], eligible=None, - ) + row = _retained_row(retained) view = _view(row) assert type(view.terminal) is HistoricalSelectedPreSubmitTerminal assert view.terminal.canonical_body() == retained["terminal"] @@ -548,3 +559,67 @@ def test_historical_pre_decoder_rejects_changed_binding_or_timing(field): body[field] = "sha256:" + "f" * 64 if field == "request_digest" else body[field] + 1 with pytest.raises(ValueError): HistoricalSelectedPreSubmitTerminal.from_canonical_body(body) + + +@pytest.mark.parametrize("field,value", [ + ("actor_profile_id", "01900000-0000-7000-8000-999999999999"), + ("identity_link_id", "01900000-0000-7000-8000-999999999999"), + ("project_id", "01900000-0000-7000-8000-999999999999"), + ("task_id", "01900000-0000-7000-8000-999999999999"), + ("assignment_id", "01900000-0000-7000-8000-999999999999"), + ("archive_sha256", "sha256:" + "f" * 64), + ("archive_byte_count", 999), + ("request_digest", "sha256:" + "f" * 64), + ("lease_id", "01900000-0000-7000-8000-999999999999"), + ("lease_generation", 2), + ("status", "completed"), + ("eligible", True), + ("completed_at", datetime(2026, 1, 2, tzinfo=UTC)), +]) +def test_historical_pre_read_rejects_foreign_row_selectors_and_facts(field, value): + from app.modules.checkers.selected_pre_submit_reads import _view + + row = _retained_row(_retained_v1()) + setattr(row, field, value) + with pytest.raises(SelectedPreSubmitUnavailable): + _view(row) + + +def test_historical_pre_decoder_rejects_an_unknown_outcome(): + from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal + + body = _retained_v1()["terminal"] + body["outcome"] = "unknown" + with pytest.raises(ValueError): + HistoricalSelectedPreSubmitTerminal.from_canonical_body(body) + + +@pytest.mark.parametrize("status", ["queued", "running"]) +def test_historical_nonterminal_pre_remains_readable_without_inventing_an_outcome(status): + from app.modules.checkers.selected_pre_submit_reads import _view + + row = _retained_row(_retained_v1()) + row.status = status + row.terminal_json = row.terminal_digest = row.completed_at = row.eligible = None + if status == "queued": + row.started_at = row.lease_id = row.lease_expires_at = None + row.lease_generation = 0 + view = _view(row) + assert view.status == status and view.terminal is None and view.completed_at is None + + +@pytest.mark.parametrize("changed", ["lineage", "member", "default"]) +def test_historical_completed_pre_rejects_changed_nested_evidence(changed): + from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal + + body = _retained_v1("selected_pre_v1_completed")["terminal"] + assert body["reservation"]["admission_lineage"] is not None + assert len(body["execution"]["external_members"]) == 1 + if changed == "lineage": + body["reservation"]["admission_lineage"]["packet_sha256"] = "sha256:" + "f" * 64 + elif changed == "member": + body["execution"]["external_members"][0]["result"]["request_digest"] = "sha256:" + "f" * 64 + else: + body["execution"]["workstream_default"]["checks"].pop() + with pytest.raises(ValueError): + HistoricalSelectedPreSubmitTerminal.from_canonical_body(body) From a99d050368ead94a44d12efec529e47b70e8c874 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 11:44:55 +0100 Subject: [PATCH 052/513] Bind live PRE reservations to sealed source and foreground custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 39 +++ backend/app/adapters/artifacts/__init__.py | 8 + backend/app/adapters/checkers/__init__.py | 2 + backend/app/adapters/tasks/__init__.py | 7 + .../artifacts/api/submission_preparation.py | 7 +- .../modules/checkers/api/default_checker.py | 47 +++ .../checkers/api/selected_pre_submit.py | 295 +++++++++--------- backend/app/modules/checkers/models.py | 13 +- .../selected_pre_submit_coordination.py | 64 ++-- .../test_selected_pre_submit_coordination.py | 200 +++++++++++- 10 files changed, 513 insertions(+), 169 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index ae8eb7b5d..64e3e49f7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1222,3 +1222,42 @@ mutations are rejected. All 270 focused checks pass. The four PostgreSQL read-consistency tests also passed with cleanup, but their fixture produced no completed selected PRE row, so that run is not credited as historical payload coverage. The reader's direct frozen-row tests establish that narrower claim. + +### Live source-first replacement in progress + +The live reservation now uses schema v2 with exact sealed source and source hash, +metadata/locked-context hashes, foreground lease ID/generation, immutable PRE +hard deadline, complete selected policy, default context and explicit runtime +profile. Prepared-generation/current-manifest/default-input facts are removed +from this request and its live lineage. The frozen v1 decoder is unchanged. +Runtime profile values have no deployment defaults and do not assert provider +or isolation qualification. Exactly one selected PRE image is required here; +policy-approval cardinality enforcement remains part of the wider cutover. + +The existing coordinator now requires ART's public source-custody port after +TASK checks and before CHECKERS locks. It compares exact source, actor/link, +project/task/assignment, metadata/context and foreground fence/deadline. Claim +expiry is capped at the existing absolute deadline. Finalization no longer +mints the old prepared-bundle capability. ORM source-operation linkage and +nullable historical derived-input columns are drafted; execute/finalize/terminal +facts use v2. A type-only import in ART's preparation feedback contract removes +an eager API import cycle exposed by the source dependency. + +This is an unfinished coordinated replacement, not a passing review candidate. +The matching SQL migration/guards, source-first ART producer, old capability and +consumer removal, derived result envelope, v2 read projection, SDK/runtime and +remaining affected fixtures still require implementation. Do not push or treat +this checkpoint as deployable. The last pushed branch remains unchanged. + +Twenty-four focused source-first tests pass, including source substitution, +forbidden derived/mutable fields, packet/deadline binding, ten current ART +custody substitutions refused before CHECKERS queries, claim deadline capping, +lease overrun and exact-one policy. These use controlled owner ports, not real +PostgreSQL migration or native execution. The full coordination module exposed +eight transition failures: seven obsolete live fixtures/capability expectations +and the historical rejection test's newly required source port. The historical +test now supplies that port and asserts neither owner is called. Remaining +failures must be replaced alongside the corresponding live callers, not hidden +by narrowing CI. Scoped Ruff and diff whitespace checks passed. Freshly fetched +main remains an ancestor of the branch. Remote CI for the prior pushed commit +was still running when polled; no green outcome is inferred. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 31607dab7..dceb715dd 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -896,3 +896,11 @@ def submission_bundle_preparation_reader(session: AsyncSession): from app.modules.artifacts.preparation_reads import SubmissionBundlePreparationReader return SubmissionBundlePreparationReader(session, runs=selected_pre_submit_run_reader(session)) + + +def submission_intake_pre_source_port(session): + """Compose ART's locked source participation in the caller-owned T3 root.""" + from app.adapters.tasks import intake_task_custody_port + from app.modules.artifacts.intake.repository import SubmissionIntakeRepository + + return SubmissionIntakeRepository(session, intake_task_custody_port(session)) diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py index 49ad9cb24..792c480c0 100644 --- a/backend/app/adapters/checkers/__init__.py +++ b/backend/app/adapters/checkers/__init__.py @@ -260,6 +260,7 @@ def external_checker_registry_service(session, authority): def selected_pre_submit_coordinator(session): """Compose selected PRE custody through CHECKERS' public adapter root.""" from app.adapters.tasks import selected_pre_submit_task_guard + from app.adapters.artifacts import submission_intake_pre_source_port from app.modules.checkers.selected_pre_submit_coordination import ( SelectedPreSubmitCoordinator, ) @@ -267,6 +268,7 @@ def selected_pre_submit_coordinator(session): return SelectedPreSubmitCoordinator( session, tasks=selected_pre_submit_task_guard(session), + sources=submission_intake_pre_source_port(session), ) diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py index 08ba911e5..d410182ff 100644 --- a/backend/app/adapters/tasks/__init__.py +++ b/backend/app/adapters/tasks/__init__.py @@ -714,3 +714,10 @@ def project_work_reader(session: AsyncSession): session, compensation_terms=locked_compensation_terms_port(session), finding_counts=checker_history_repository(session), ) + + +def intake_task_custody_port(session): + """Compose TASK-first active intake pointer custody for ART participation.""" + from app.modules.tasks.intake_custody import IntakeTaskCustody + + return IntakeTaskCustody(session) diff --git a/backend/app/modules/artifacts/api/submission_preparation.py b/backend/app/modules/artifacts/api/submission_preparation.py index 4bf75101e..bf820c876 100644 --- a/backend/app/modules/artifacts/api/submission_preparation.py +++ b/backend/app/modules/artifacts/api/submission_preparation.py @@ -6,13 +6,14 @@ from dataclasses import dataclass from enum import StrEnum from datetime import datetime -from typing import Any, Literal, Protocol +from typing import TYPE_CHECKING, Any, Literal, Protocol from uuid import UUID from pydantic import AwareDatetime, BaseModel, ConfigDict, Field from app.modules.authorization.api import ActorIdentityFacts -from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts +if TYPE_CHECKING: + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts class SubmissionBundlePreparationRejected(RuntimeError): @@ -26,6 +27,8 @@ def __init__( self, facts: SelectedPreSubmitExecutionFacts, ) -> None: + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts + if type(facts) is not SelectedPreSubmitExecutionFacts: raise TypeError("pre-submission feedback facts are invalid") if facts.eligible is not False: diff --git a/backend/app/modules/checkers/api/default_checker.py b/backend/app/modules/checkers/api/default_checker.py index e298e20c9..12d215aa6 100644 --- a/backend/app/modules/checkers/api/default_checker.py +++ b/backend/app/modules/checkers/api/default_checker.py @@ -151,6 +151,53 @@ def __post_init__(self) -> None: if self.predecessor_rules_sha256 is not None: _require_sha256(self.predecessor_rules_sha256) + def canonical_body(self) -> dict[str, object]: + """Serialize locked inputs without claiming an inspected current source.""" + def predecessor_body(value: WorkstreamDefaultPredecessor | None): + if value is None: + return None + return { + "submission_id": str(value.submission_id), + "submission_version": value.submission_version, + "archive_sha256": value.archive_sha256, + "semantic_manifest_sha256": value.semantic_manifest_sha256, + } + return { + "predecessor": predecessor_body(self.predecessor), + "predecessor_exists": self.predecessor_exists, + "current_predecessor": predecessor_body(self.current_predecessor), + "current_rules_sha256": self.current_rules_sha256, + "predecessor_rules_sha256": self.predecessor_rules_sha256, + "packet": {"summary": self.packet.summary, + "contributor_attestation": self.packet.contributor_attestation}, + } + + @classmethod + def from_canonical_body(cls, body: object) -> WorkstreamDefaultContext: + """Decode a closed locked context independently of derived default input.""" + def predecessor(value): + if value is None: + return None + return WorkstreamDefaultPredecessor( + **(value | {"submission_id": UUID(value["submission_id"])}) + ) + if type(body) is not dict: + raise ValueError("default checker context is invalid") + try: + value = cls( + predecessor=predecessor(body["predecessor"]), + predecessor_exists=body["predecessor_exists"], + current_predecessor=predecessor(body["current_predecessor"]), + current_rules_sha256=body["current_rules_sha256"], + predecessor_rules_sha256=body["predecessor_rules_sha256"], + packet=SubmissionPacketView(**body["packet"]), + ) + if value.canonical_body() != body: + raise ValueError("default checker context is not canonical") + return value + except (KeyError, TypeError, AttributeError) as exc: + raise ValueError("default checker context is invalid") from exc + def bind_verified_input( self, *, archive_sha256: str, archive_byte_count: int, archive_media_type: str, semantic_manifest_sha256: str, diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py index ee8642ada..47ec3ef62 100644 --- a/backend/app/modules/checkers/api/selected_pre_submit.py +++ b/backend/app/modules/checkers/api/selected_pre_submit.py @@ -3,13 +3,20 @@ from __future__ import annotations from dataclasses import asdict, dataclass -from datetime import datetime +from datetime import datetime, timezone from contextlib import AbstractAsyncContextManager from typing import Literal, Protocol from uuid import UUID +import json + +from pydantic import BaseModel, ConfigDict, Field + from app.core.hashing import canonical_json_hash -from app.modules.checkers.api.default_checker import WORKSTREAM_DEFAULT_BEHAVIOR_SHA256 +from app.modules.artifacts.api.submission_intake import SealedSubmissionSource +from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits +from app.modules.checkers.api.default_checker import WorkstreamDefaultContext +from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy from app.modules.checkers.api.default_checker import WorkstreamDefaultCheckerResult from app.modules.checkers.api.external import ExternalCheckerExecutionResult from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal @@ -17,7 +24,7 @@ @dataclass(frozen=True, slots=True) class SelectedPreSubmitAdmissionLineage: - """Immutable TASK, PROJECT, packet and manifest facts needed after verification.""" + """Immutable TASK, PROJECT and packet facts known before source inspection.""" predecessor_submission_id: UUID | None predecessor_submission_version: int | None @@ -37,8 +44,6 @@ class SelectedPreSubmitAdmissionLineage: post_submit_policy_sha256: str post_submit_policy_body: dict[str, object] locked_policy_context_hash: str - semantic_manifest_id: UUID - semantic_manifest_body: dict[str, object] packet_sha256: str storage_scheme: str revision_preparation_id: UUID | None = None @@ -50,7 +55,6 @@ def __post_init__(self) -> None: self.source_snapshot_id, self.effective_policy_id, self.pre_submit_policy_id, - self.semantic_manifest_id, ) digests = ( self.source_snapshot_sha256, @@ -103,7 +107,6 @@ def __post_init__(self) -> None: type(value) is not str or len(value) != 71 or not value.startswith("sha256:") for value in digests ) - or type(self.semantic_manifest_body) is not dict or type(self.post_submit_policy_body) is not dict or canonical_json_hash( { @@ -147,8 +150,6 @@ def canonical_body(self) -> dict[str, object]: "post_submit_policy_sha256": self.post_submit_policy_sha256, "post_submit_policy_body": self.post_submit_policy_body, "locked_policy_context_hash": self.locked_policy_context_hash, - "semantic_manifest_id": str(self.semantic_manifest_id), - "semantic_manifest_body": self.semantic_manifest_body, "packet_sha256": self.packet_sha256, "storage_scheme": self.storage_scheme, } @@ -181,8 +182,6 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitAdmissionLineage: "post_submit_policy_sha256", "post_submit_policy_body", "locked_policy_context_hash", - "semantic_manifest_id", - "semantic_manifest_body", "packet_sha256", "storage_scheme", } @@ -219,8 +218,6 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitAdmissionLineage: post_submit_policy_sha256=body["post_submit_policy_sha256"], post_submit_policy_body=body["post_submit_policy_body"], locked_policy_context_hash=body["locked_policy_context_hash"], - semantic_manifest_id=UUID(str(body["semantic_manifest_id"])), - semantic_manifest_body=body["semantic_manifest_body"], packet_sha256=body["packet_sha256"], storage_scheme=body["storage_scheme"], revision_preparation_id=( @@ -378,9 +375,25 @@ def result_digest(self) -> str: return canonical_json_hash(self.canonical_body()) +class SelectedPreSubmitRuntimeProfile(BaseModel): + """Explicit deployment bounds; structural validity is not qualification.""" + + model_config = ConfigDict(extra="forbid", strict=True, frozen=True) + profile_id: str = Field(min_length=1, max_length=100, pattern=r"^[a-z0-9_-]+$") + platform_root_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") + cpu_millis: int = Field(gt=0) + memory_bytes: int = Field(gt=0) + temporary_disk_bytes: int = Field(gt=0) + maximum_processes: int = Field(gt=0) + maximum_output_bytes: int = Field(gt=0) + maximum_log_bytes: int = Field(gt=0) + aggregate_deadline_ms: int = Field(ge=100, le=14_400_000) + archive_limits: SubmissionArchiveLimits + + @dataclass(frozen=True, slots=True) class SelectedPreSubmitReservationFacts: - """Complete durable PRE request reserved before any external work starts.""" + """T3 request containing only facts known before guest source inspection.""" actor_profile_id: UUID identity_link_id: UUID @@ -389,147 +402,138 @@ class SelectedPreSubmitReservationFacts: assignment_id: UUID attempt_id: UUID idempotency_key: UUID - attempt_request_digest: str - prepared_generation_id: UUID - policy_sha256: str - default_behavior_sha256: str - default_input_sha256: str - archive_sha256: str - archive_byte_count: int - semantic_manifest_sha256: str - execution_budget_ms: int - admission_lineage: SelectedPreSubmitAdmissionLineage | None = None + source: SealedSubmissionSource + metadata_sha256: str + locked_context_sha256: str + foreground_lease_id: UUID + foreground_lease_generation: int + pre_deadline_at: datetime + policy: LockedExternalPreSubmitPolicy + default_context: WorkstreamDefaultContext + runtime_profile: SelectedPreSubmitRuntimeProfile + admission_lineage: SelectedPreSubmitAdmissionLineage def __post_init__(self) -> None: - """Reject partial authority, material, policy or default-input custody.""" - identifiers = ( - self.actor_profile_id, - self.identity_link_id, - self.project_id, - self.task_id, - self.assignment_id, - self.attempt_id, - self.idempotency_key, - self.prepared_generation_id, - ) - digests = ( - self.attempt_request_digest, - self.policy_sha256, - self.default_behavior_sha256, - self.default_input_sha256, - self.archive_sha256, - self.semantic_manifest_sha256, - ) + """Reject missing source, locked context, selected image or fence facts.""" + identifiers = (self.actor_profile_id, self.identity_link_id, self.project_id, + self.task_id, self.assignment_id, self.attempt_id, + self.idempotency_key, self.foreground_lease_id) + digests = (self.metadata_sha256, self.locked_context_sha256) if ( any(type(value) is not UUID for value in identifiers) - or any( - type(value) is not str or len(value) != 71 or not value.startswith("sha256:") - for value in digests - ) - or self.default_behavior_sha256 != WORKSTREAM_DEFAULT_BEHAVIOR_SHA256 - or type(self.archive_byte_count) is not int - or self.archive_byte_count < 0 - or type(self.execution_budget_ms) is not int - or not 100 <= self.execution_budget_ms <= 14_400_000 - or ( - self.admission_lineage is not None - and type(self.admission_lineage) is not SelectedPreSubmitAdmissionLineage - ) - or ( - self.admission_lineage is not None - and ( - canonical_json_hash(self.admission_lineage.semantic_manifest_body) - != self.semantic_manifest_sha256 - or self.admission_lineage.effective_plan_sha256 != self.policy_sha256 - ) - ) + or any(type(value) is not str or len(value) != 71 + or not value.startswith("sha256:") + or any(char not in "0123456789abcdef" for char in value[7:]) + for value in digests) + or type(self.source) is not SealedSubmissionSource + or type(self.policy) is not LockedExternalPreSubmitPolicy + or type(self.default_context) is not WorkstreamDefaultContext + or type(self.runtime_profile) is not SelectedPreSubmitRuntimeProfile + or type(self.admission_lineage) is not SelectedPreSubmitAdmissionLineage + or type(self.foreground_lease_generation) is not int + or self.foreground_lease_generation < self.source.sealed_upload_fence + or type(self.pre_deadline_at) is not datetime + or self.pre_deadline_at.utcoffset() is None ): raise ValueError("selected PRE reservation facts are invalid") + lineage = self.admission_lineage + predecessor = self.default_context.predecessor + if ( + len(self.policy.entries) != 1 + or lineage.effective_plan_sha256 != self.policy_sha256 + or lineage.rules_sha256 != self.default_context.current_rules_sha256 + or lineage.packet_sha256 != self.default_context.packet.sha256 + or lineage.predecessor_submission_id != ( + predecessor.submission_id if predecessor else None) + or lineage.predecessor_submission_version != ( + predecessor.submission_version if predecessor else None) + or self.runtime_profile.archive_limits.maximum_inspection_seconds * 1000 + > self.execution_budget_ms + ): + raise ValueError("selected PRE locked context differs") + resources = self.policy.entries[0].registry.resources + if (resources.cpu_millis > self.runtime_profile.cpu_millis + or resources.memory_bytes > self.runtime_profile.memory_bytes + or resources.maximum_output_bytes > self.runtime_profile.maximum_output_bytes): + raise ValueError("selected PRE runtime cannot support selected policy") + + @property + def policy_sha256(self) -> str: + """Return the validated exact selected policy digest.""" + return self.policy.policy_sha256 + + @property + def default_behavior_sha256(self) -> str: + """Return the locked code-owned default identity.""" + return self.policy.workstream_default.behavior_sha256 + + @property + def archive_sha256(self) -> str: + """Return the sealed original ZIP identity, never a semantic digest.""" + return self.source.raw_sha256 + + @property + def archive_byte_count(self) -> int: + """Return the sealed original ZIP byte count.""" + return self.source.raw_byte_count + + @property + def execution_budget_ms(self) -> int: + """Return the aggregate ceiling; the absolute deadline may shorten it.""" + return self.runtime_profile.aggregate_deadline_ms def canonical_body(self) -> dict[str, object]: - """Bind the actual contributor, task, ART generation, policy and bytes.""" + """Bind source, operation, fence and immutable context without credentials.""" return { - "schema_version": "workstream.selected_pre_submit_reservation.v1", - "actor_profile_id": str(self.actor_profile_id), - "identity_link_id": str(self.identity_link_id), - "project_id": str(self.project_id), - "task_id": str(self.task_id), - "assignment_id": str(self.assignment_id), - "attempt_id": str(self.attempt_id), - "idempotency_key": str(self.idempotency_key), - "attempt_request_digest": self.attempt_request_digest, - "prepared_generation_id": str(self.prepared_generation_id), - "policy_sha256": self.policy_sha256, - "default_behavior_sha256": self.default_behavior_sha256, - "default_input_sha256": self.default_input_sha256, - "archive_sha256": self.archive_sha256, - "archive_byte_count": self.archive_byte_count, - "semantic_manifest_sha256": self.semantic_manifest_sha256, - "execution_budget_ms": self.execution_budget_ms, - "admission_lineage": ( - self.admission_lineage.canonical_body() - if self.admission_lineage is not None - else None - ), + "schema_version": "workstream.selected_pre_submit_reservation.v2", + **{name: str(getattr(self, name)) for name in ( + "actor_profile_id", "identity_link_id", "project_id", "task_id", + "assignment_id", "attempt_id", "idempotency_key", "foreground_lease_id")}, + "source": self.source.model_dump(mode="json"), + "source_sha256": self.source.source_sha256(), + "metadata_sha256": self.metadata_sha256, + "locked_context_sha256": self.locked_context_sha256, + "foreground_lease_generation": self.foreground_lease_generation, + "pre_deadline_at": self.pre_deadline_at.astimezone(timezone.utc).isoformat(), + "policy": self.policy.model_dump(mode="json"), + "default_context": self.default_context.canonical_body(), + "runtime_profile": self.runtime_profile.model_dump(mode="json"), + "admission_lineage": self.admission_lineage.canonical_body(), } @classmethod def from_canonical_body(cls, body: object) -> SelectedPreSubmitReservationFacts: - """Recover and validate the durable request snapshot at ART publication.""" - if ( - type(body) is not dict - or set(body) - != { - "schema_version", - "actor_profile_id", - "identity_link_id", - "project_id", - "task_id", - "assignment_id", - "attempt_id", - "idempotency_key", - "attempt_request_digest", - "prepared_generation_id", - "policy_sha256", - "default_behavior_sha256", - "default_input_sha256", - "archive_sha256", - "archive_byte_count", - "semantic_manifest_sha256", - "execution_budget_ms", - "admission_lineage", - } - or body["schema_version"] != "workstream.selected_pre_submit_reservation.v1" + """Decode only the live source-first schema; historical data is read-only.""" + if type(body) is not dict or body.get("schema_version") != ( + "workstream.selected_pre_submit_reservation.v2" ): raise ValueError("selected PRE reservation facts are invalid") - lineage_body = body["admission_lineage"] - return cls( - actor_profile_id=UUID(str(body["actor_profile_id"])), - identity_link_id=UUID(str(body["identity_link_id"])), - project_id=UUID(str(body["project_id"])), - task_id=UUID(str(body["task_id"])), - assignment_id=UUID(str(body["assignment_id"])), - attempt_id=UUID(str(body["attempt_id"])), - idempotency_key=UUID(str(body["idempotency_key"])), - attempt_request_digest=body["attempt_request_digest"], - prepared_generation_id=UUID(str(body["prepared_generation_id"])), - policy_sha256=body["policy_sha256"], - default_behavior_sha256=body["default_behavior_sha256"], - default_input_sha256=body["default_input_sha256"], - archive_sha256=body["archive_sha256"], - archive_byte_count=body["archive_byte_count"], - semantic_manifest_sha256=body["semantic_manifest_sha256"], - execution_budget_ms=body["execution_budget_ms"], - admission_lineage=( - SelectedPreSubmitAdmissionLineage.from_canonical_body(lineage_body) - if lineage_body is not None - else None - ), - ) + try: + value = cls( + **{name: UUID(body[name]) for name in ( + "actor_profile_id", "identity_link_id", "project_id", "task_id", + "assignment_id", "attempt_id", "idempotency_key", "foreground_lease_id")}, + source=SealedSubmissionSource.model_validate_json(json.dumps(body["source"])), + metadata_sha256=body["metadata_sha256"], + locked_context_sha256=body["locked_context_sha256"], + foreground_lease_generation=body["foreground_lease_generation"], + pre_deadline_at=datetime.fromisoformat(body["pre_deadline_at"]), + policy=LockedExternalPreSubmitPolicy.model_validate_json(json.dumps(body["policy"])), + default_context=WorkstreamDefaultContext.from_canonical_body(body["default_context"]), + runtime_profile=SelectedPreSubmitRuntimeProfile.model_validate_json( + json.dumps(body["runtime_profile"])), + admission_lineage=SelectedPreSubmitAdmissionLineage.from_canonical_body( + body["admission_lineage"]), + ) + if value.canonical_body() != body: + raise ValueError("selected PRE reservation facts are not canonical") + return value + except (KeyError, TypeError, AttributeError) as exc: + raise ValueError("selected PRE reservation facts are invalid") from exc @property def request_digest(self) -> str: - """Return the immutable request identity used by reserve and replay.""" + """Return the exact immutable source-first execution request identity.""" return canonical_json_hash(self.canonical_body()) @@ -549,7 +553,9 @@ def __post_init__(self) -> None: or type(self.lease_id) is not UUID or type(self.lease_generation) is not int or self.lease_generation < 1 - or self.lease_expires_at.tzinfo is None + or type(self.lease_expires_at) is not datetime + or self.lease_expires_at.utcoffset() is None + or self.lease_expires_at > self.reservation.pre_deadline_at ): raise ValueError("selected PRE lease facts are invalid") @@ -597,7 +603,7 @@ def facts_digest(self) -> str: """Bind reservation, lease generation and database expiry.""" return canonical_json_hash( { - "schema_version": "workstream.selected_pre_submit_execute.v1", + "schema_version": "workstream.selected_pre_submit_execute.v2", "reservation": self.lease.reservation.canonical_body(), "lease_id": str(self.lease.lease_id), "lease_generation": self.lease.lease_generation, @@ -632,7 +638,7 @@ def facts_digest(self) -> str: """Bind the lease to either exact results or one closed infrastructure code.""" return canonical_json_hash( { - "schema_version": "workstream.selected_pre_submit_finalize.v1", + "schema_version": "workstream.selected_pre_submit_finalize.v2", "execute_facts_digest": SelectedPreSubmitExecuteFacts(self.lease).facts_digest, "execution": ( self.execution.canonical_body() if self.execution is not None else None @@ -772,19 +778,20 @@ def __post_init__(self) -> None: or self.execution.policy_sha256 != self.lease.reservation.policy_sha256 ): raise ValueError("selected PRE completed outcome is invalid") - elif self.execution is not None or self.infrastructure_failure_code not in { + elif (self.outcome != "infrastructure_failed" or self.execution is not None + or self.infrastructure_failure_code not in { "capacity_exceeded", "deadline_exceeded", "material_unavailable", "implementation_unavailable", "invalid_output", - }: + }): raise ValueError("selected PRE infrastructure outcome is invalid") def canonical_body(self) -> dict[str, object]: """Return persisted latency, lease and terminal facts without private paths.""" return { - "schema_version": "workstream.selected_pre_submit_terminal.v1", + "schema_version": "workstream.selected_pre_submit_terminal.v2", "reservation": self.lease.reservation.canonical_body(), "request_digest": self.lease.reservation.request_digest, "lease_id": str(self.lease.lease_id), @@ -824,7 +831,7 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitTerminalFacts: "queue_latency_ms", "execution_latency_ms", } - or body["schema_version"] != "workstream.selected_pre_submit_terminal.v1" + or body["schema_version"] != "workstream.selected_pre_submit_terminal.v2" ): raise ValueError("selected PRE terminal facts are invalid") reservation = SelectedPreSubmitReservationFacts.from_canonical_body(body["reservation"]) diff --git a/backend/app/modules/checkers/models.py b/backend/app/modules/checkers/models.py index 5bb2c583e..7ba3107fb 100644 --- a/backend/app/modules/checkers/models.py +++ b/backend/app/modules/checkers/models.py @@ -513,6 +513,12 @@ class SelectedPreSubmitRun(Base): __tablename__ = "selected_pre_submit_runs" __table_args__ = ( + ForeignKeyConstraint( + ["source_operation_id", "task_id"], + ["submission_intake_operations.id", "submission_intake_operations.task_id"], + name="fk_selected_pre_run_source_operation", + ), + UniqueConstraint("source_operation_id", name="uq_selected_pre_run_source_operation"), CheckConstraint( "(get_byte(uuid_send(id), 6) >> 4) = 7 and " "(get_byte(uuid_send(id), 8) & 192) = 128", @@ -597,15 +603,16 @@ class SelectedPreSubmitRun(Base): task_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), nullable=False) assignment_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), nullable=False) idempotency_key: Mapped[str] = mapped_column(Uuid(as_uuid=False), nullable=False) - prepared_generation_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), nullable=False) + source_operation_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) + prepared_generation_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) request_json: Mapped[dict] = mapped_column(JSONB(), nullable=False) request_digest: Mapped[str] = mapped_column(String(71), nullable=False) policy_sha256: Mapped[str] = mapped_column(String(71), nullable=False) default_behavior_sha256: Mapped[str] = mapped_column(String(71), nullable=False) - default_input_sha256: Mapped[str] = mapped_column(String(71), nullable=False) + default_input_sha256: Mapped[str | None] = mapped_column(String(71)) archive_sha256: Mapped[str] = mapped_column(String(71), nullable=False) archive_byte_count: Mapped[int] = mapped_column(BigInteger, nullable=False) - semantic_manifest_sha256: Mapped[str] = mapped_column(String(71), nullable=False) + semantic_manifest_sha256: Mapped[str | None] = mapped_column(String(71)) execution_budget_ms: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(32), nullable=False) lease_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) diff --git a/backend/app/modules/checkers/selected_pre_submit_coordination.py b/backend/app/modules/checkers/selected_pre_submit_coordination.py index ff373bb54..5e8426df2 100644 --- a/backend/app/modules/checkers/selected_pre_submit_coordination.py +++ b/backend/app/modules/checkers/selected_pre_submit_coordination.py @@ -13,6 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_intake import SubmissionIntakePreSourcePort from app.modules.checkers.api.selected_pre_submit import ( PreparedSelectedPreSubmitExecution, PreparedSelectedPreSubmitFinalization, @@ -193,13 +194,14 @@ def _matches(row: SelectedPreSubmitRun, facts: SelectedPreSubmitReservationFacts and row.task_id == str(facts.task_id) and row.assignment_id == str(facts.assignment_id) and row.idempotency_key == str(facts.idempotency_key) - and row.prepared_generation_id == str(facts.prepared_generation_id) + and row.source_operation_id == str(facts.source.location.operation_id) + and row.prepared_generation_id is None and row.policy_sha256 == facts.policy_sha256 and row.default_behavior_sha256 == facts.default_behavior_sha256 - and row.default_input_sha256 == facts.default_input_sha256 + and row.default_input_sha256 is None and row.archive_sha256 == facts.archive_sha256 and row.archive_byte_count == facts.archive_byte_count - and row.semantic_manifest_sha256 == facts.semantic_manifest_sha256 + and row.semantic_manifest_sha256 is None and row.execution_budget_ms == facts.execution_budget_ms ) @@ -212,9 +214,11 @@ def __init__( session: AsyncSession, *, tasks: SelectedPreSubmitTaskGuard, + sources: SubmissionIntakePreSourcePort, ) -> None: self._session = session self._tasks = tasks + self._sources = sources self._capability: SelectedPreSubmitAdmissionCapability | None = None self._execution_capability: SelectedPreSubmitExecutionCapability | None = None @@ -225,7 +229,7 @@ async def read_current( _require_root(self._session) if type(facts) is not SelectedPreSubmitReservationFacts: raise TypeError("selected PRE reservation facts are invalid") - await self._tasks.lock_selected_pre_submit_scope(facts) + await self._lock_source(facts) row = await self._session.scalar( select(SelectedPreSubmitRun) .where( @@ -239,6 +243,8 @@ async def read_current( ) if row is None: return None + if row.request_json.get("schema_version") != "workstream.selected_pre_submit_reservation.v2": + raise SelectedPreSubmitRequestConflict("selected_pre_submit_request_conflict") try: stored = SelectedPreSubmitReservationFacts.from_canonical_body( row.request_json @@ -246,7 +252,6 @@ async def read_current( normalized = replace( facts, attempt_id=stored.attempt_id, - prepared_generation_id=stored.prepared_generation_id, ) terminal = ( SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json) @@ -286,7 +291,7 @@ async def reserve(self, facts: SelectedPreSubmitReservationFacts) -> UUID: _require_root(self._session) if type(facts) is not SelectedPreSubmitReservationFacts: raise TypeError("selected PRE reservation facts are invalid") - await self._tasks.lock_selected_pre_submit_scope(facts) + await self._lock_source(facts) await self._session.execute( text("select pg_advisory_xact_lock(hashtextextended(:key,0))"), { @@ -321,15 +326,16 @@ async def reserve(self, facts: SelectedPreSubmitReservationFacts) -> UUID: task_id=str(facts.task_id), assignment_id=str(facts.assignment_id), idempotency_key=str(facts.idempotency_key), - prepared_generation_id=str(facts.prepared_generation_id), + source_operation_id=str(facts.source.location.operation_id), + prepared_generation_id=None, request_json=facts.canonical_body(), request_digest=facts.request_digest, policy_sha256=facts.policy_sha256, default_behavior_sha256=facts.default_behavior_sha256, - default_input_sha256=facts.default_input_sha256, + default_input_sha256=None, archive_sha256=facts.archive_sha256, archive_byte_count=facts.archive_byte_count, - semantic_manifest_sha256=facts.semantic_manifest_sha256, + semantic_manifest_sha256=None, execution_budget_ms=facts.execution_budget_ms, status="queued", lease_generation=0, @@ -354,11 +360,15 @@ async def claim( raise SelectedPreSubmitUnavailable("selected_pre_submit_lease_unavailable") now = await self._session.scalar(select(func.clock_timestamp())) assert now is not None + if now >= facts.pre_deadline_at: + raise SelectedPreSubmitUnavailable("selected_pre_submit_deadline_expired") lease = SelectedPreSubmitLeaseFacts( reservation=facts, lease_id=new_record_id(), lease_generation=row.lease_generation + 1, - lease_expires_at=now + timedelta(milliseconds=facts.execution_budget_ms), + lease_expires_at=min( + facts.pre_deadline_at, now + timedelta(milliseconds=facts.execution_budget_ms) + ), ) execute_facts = SelectedPreSubmitExecuteFacts(lease) evidence = await authority.consume(execute_facts) @@ -472,15 +482,31 @@ async def finalize( row.finalize_evidence_id = str(evidence.evidence_id) row.completed_at = completed_at await self._session.flush() - capability = ( - SelectedPreSubmitAdmissionCapability._issued( - owner=self, run_id=run_id, terminal=terminal - ) - if execution is not None and execution.eligible - else None + # Source-bound evidence cannot mint the removed prepared-bundle handoff. + # Acceptance is the separate fresh-fenced T4 transaction. + return SelectedPreSubmitCompletion(terminal=terminal, capability=None) + + async def _lock_source(self, facts: SelectedPreSubmitReservationFacts) -> None: + """Hold TASK then exact live ART custody before any CHECKERS row lock.""" + await self._tasks.lock_selected_pre_submit_scope(facts) + current = await self._sources.lock_pre_source( + source=facts.source, lease_id=facts.foreground_lease_id, + generation=facts.foreground_lease_generation, ) - self._capability = capability - return SelectedPreSubmitCompletion(terminal=terminal, capability=capability) + if ( + current.source != facts.source + or current.project_id != facts.project_id + or current.task_id != facts.task_id + or current.assignment_id != facts.assignment_id + or current.actor_profile_id != facts.actor_profile_id + or current.identity_link_id != facts.identity_link_id + or current.metadata_sha256 != facts.metadata_sha256 + or current.locked_context_sha256 != facts.locked_context_sha256 + or current.lease_id != facts.foreground_lease_id + or current.lease_generation != facts.foreground_lease_generation + or current.pre_deadline_at != facts.pre_deadline_at + ): + raise SelectedPreSubmitUnavailable("selected_pre_submit_source_changed") async def _lock( self, *, run_id: UUID, facts: SelectedPreSubmitReservationFacts @@ -488,7 +514,7 @@ async def _lock( _require_root(self._session) if not isinstance(run_id, UUID) or type(facts) is not SelectedPreSubmitReservationFacts: raise SelectedPreSubmitUnavailable("selected_pre_submit_run_unavailable") - await self._tasks.lock_selected_pre_submit_scope(facts) + await self._lock_source(facts) row = await self._session.scalar( select(SelectedPreSubmitRun) .where( diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index 23a879dbb..ddb29276d 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -542,11 +542,13 @@ async def test_historical_pre_values_cannot_become_live_reservation_or_lease(): from sqlalchemy.ext.asyncio import AsyncSession tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock()) + sources = SimpleNamespace(lock_pre_source=AsyncMock()) async with AsyncSession() as session, session.begin(): - coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks) + coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, sources=sources) with pytest.raises(TypeError, match="reservation facts are invalid"): await coordinator.reserve(request) tasks.lock_selected_pre_submit_scope.assert_not_awaited() + sources.lock_pre_source.assert_not_awaited() with pytest.raises(ValueError, match="lease facts are invalid"): SelectedPreSubmitLeaseFacts(request, new_record_id(), 1, datetime.now(UTC)) @@ -623,3 +625,199 @@ def test_historical_completed_pre_rejects_changed_nested_evidence(changed): body["execution"]["workstream_default"]["checks"].pop() with pytest.raises(ValueError): HistoricalSelectedPreSubmitTerminal.from_canonical_body(body) + + +def _source_reservation() -> SelectedPreSubmitReservationFacts: + """Build a source-first request with explicit test-only execution limits.""" + from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits + from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, SubmissionSourceLocation, + ) + from app.modules.checkers.api.default_checker import WorkstreamDefaultContext + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitRuntimeProfile + from tests.checkers.external.test_selected_pre_submit import _policy + + policy = _policy() + packet = SubmissionPacketView(summary="", contributor_attestation="") + retained = _retained_v1("selected_pre_v1_completed") + lineage_body = dict(retained["request"]["admission_lineage"]) + for name in ("semantic_manifest_id", "semantic_manifest_body"): + lineage_body.pop(name) + lineage_body.update( + predecessor_submission_id=None, predecessor_submission_version=None, + checker_remediation_manifest_id=None, effective_plan_sha256=policy.policy_sha256, + packet_sha256=packet.sha256, + ) + lineage = SelectedPreSubmitAdmissionLineage.from_canonical_body(lineage_body) + return SelectedPreSubmitReservationFacts( + actor_profile_id=new_record_id(), identity_link_id=new_record_id(), + project_id=new_record_id(), task_id=new_record_id(), assignment_id=new_record_id(), + attempt_id=new_record_id(), idempotency_key=new_record_id(), + source=SealedSubmissionSource( + location=SubmissionSourceLocation( + operation_id=new_record_id(), namespace_id="primary", + namespace_fingerprint=SHA, provider_profile="local-v2", + ), provider_generation="test-generation", raw_sha256=SHA, + raw_byte_count=1024, sealed_upload_fence=1, + ), + metadata_sha256=SHA, locked_context_sha256=SHA, + foreground_lease_id=new_record_id(), foreground_lease_generation=1, + pre_deadline_at=datetime.now(UTC) + timedelta(seconds=120), + policy=policy, + default_context=WorkstreamDefaultContext( + predecessor=None, predecessor_exists=False, current_predecessor=None, + current_rules_sha256=lineage.rules_sha256, predecessor_rules_sha256=None, + packet=packet, + ), + runtime_profile=SelectedPreSubmitRuntimeProfile( + profile_id="test-only", platform_root_sha256=SHA, cpu_millis=2000, + memory_bytes=2 * 1024**3, temporary_disk_bytes=4 * 1024**3, + maximum_processes=64, maximum_output_bytes=1024 * 1024, + maximum_log_bytes=1024 * 1024, aggregate_deadline_ms=120_000, + archive_limits=SubmissionArchiveLimits(maximum_inspection_seconds=60), + ), admission_lineage=lineage, + ) + + +def test_source_first_reservation_round_trip_without_derived_inputs() -> None: + request = _source_reservation() + body = request.canonical_body() + assert SelectedPreSubmitReservationFacts.from_canonical_body(body) == request + assert body["source_sha256"] == request.source.source_sha256() + assert not {"prepared_generation_id", "default_input_sha256", "semantic_manifest_sha256"} & body.keys() + assert "semantic_manifest_body" not in body["admission_lineage"] + assert "lease_expires_at" not in body + + +@pytest.mark.parametrize("field", [ + "provider_generation", "raw_sha256", "raw_byte_count", "sealed_upload_fence", +]) +def test_source_first_reservation_rejects_substituted_source(field: str) -> None: + request = _source_reservation() + body = request.canonical_body() + body["source"][field] = { + "provider_generation": "other", "raw_sha256": "sha256:" + "1" * 64, + "raw_byte_count": 1025, "sealed_upload_fence": 2, + }[field] + with pytest.raises(ValueError): + SelectedPreSubmitReservationFacts.from_canonical_body(body) + + +@pytest.mark.parametrize("field", [ + "prepared_generation_id", "default_input_sha256", "semantic_manifest_sha256", + "lease_expires_at", +]) +def test_source_first_reservation_rejects_unobserved_or_mutable_facts(field: str) -> None: + body = _source_reservation().canonical_body() + body[field] = SHA + with pytest.raises(ValueError): + SelectedPreSubmitReservationFacts.from_canonical_body(body) + + +def test_source_first_reservation_binds_packet_and_hard_deadline() -> None: + request = _source_reservation() + assert replace(request, pre_deadline_at=request.pre_deadline_at + timedelta(seconds=1)).request_digest != request.request_digest + with pytest.raises(ValueError): + replace(request, pre_deadline_at=datetime.now()) + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + with pytest.raises(ValueError): + replace(request, default_context=replace( + request.default_context, packet=SubmissionPacketView("substituted", ""), + )) + + +def _source_guard(request): + from app.modules.artifacts.api.submission_intake import SubmissionIntakePreSourceFacts + return SimpleNamespace(lock_pre_source=AsyncMock(return_value=SubmissionIntakePreSourceFacts( + source=request.source, project_id=request.project_id, task_id=request.task_id, + assignment_id=request.assignment_id, actor_profile_id=request.actor_profile_id, + identity_link_id=request.identity_link_id, metadata_sha256=request.metadata_sha256, + locked_context_sha256=request.locked_context_sha256, + lease_id=request.foreground_lease_id, lease_generation=request.foreground_lease_generation, + lease_expires_at=request.pre_deadline_at, pre_deadline_at=request.pre_deadline_at, + ))) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("field", [ + "metadata_sha256", "locked_context_sha256", "actor_profile_id", "identity_link_id", + "assignment_id", "project_id", "task_id", "lease_id", "lease_generation", + "pre_deadline_at", +]) +async def test_source_first_reserve_checks_live_custody_before_checker_rows(field) -> None: + request = _source_reservation() + sources = _source_guard(request) + current = sources.lock_pre_source.return_value + changed = ("sha256:" + "b" * 64 if field.endswith("sha256") else + 2 if field == "lease_generation" else + request.pre_deadline_at + timedelta(seconds=1) if field == "pre_deadline_at" + else new_record_id()) + sources.lock_pre_source.return_value = current.model_copy(update={field: changed}) + session = SimpleNamespace( + sync_session=SimpleNamespace(get_transaction=lambda: SimpleNamespace(is_active=True)), + in_nested_transaction=lambda: False, scalar=AsyncMock(), execute=AsyncMock(), + ) + tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock()) + coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, sources=sources) + with pytest.raises(SelectedPreSubmitUnavailable, match="source_changed"): + await coordinator.reserve(request) + tasks.lock_selected_pre_submit_scope.assert_awaited_once_with(request) + session.execute.assert_not_awaited() + session.scalar.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_source_first_claim_caps_lease_at_existing_hard_deadline() -> None: + request = _source_reservation() + now = request.pre_deadline_at - timedelta(seconds=2) + row = SimpleNamespace( + **{name: str(getattr(request, name)) for name in ( + "actor_profile_id", "identity_link_id", "project_id", "task_id", + "assignment_id", "idempotency_key")}, + id=str(request.attempt_id), source_operation_id=str(request.source.location.operation_id), + prepared_generation_id=None, default_input_sha256=None, semantic_manifest_sha256=None, + policy_sha256=request.policy_sha256, default_behavior_sha256=request.default_behavior_sha256, + archive_sha256=request.archive_sha256, archive_byte_count=request.archive_byte_count, + execution_budget_ms=request.execution_budget_ms, request_json=request.canonical_body(), + request_digest=request.request_digest, status="queued", lease_generation=0, + ) + session = SimpleNamespace( + sync_session=SimpleNamespace(get_transaction=lambda: SimpleNamespace(is_active=True)), + in_nested_transaction=lambda: False, scalar=AsyncMock(side_effect=[row, now]), + flush=AsyncMock(), + ) + async def consume(facts): + return SimpleNamespace(facts_digest=facts.facts_digest, evidence_id=new_record_id()) + coordinator = SelectedPreSubmitCoordinator( + session, tasks=SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock()), + sources=_source_guard(request), + ) + authority = SimpleNamespace(consume=AsyncMock(side_effect=consume)) + lease = await coordinator.claim(run_id=request.attempt_id, facts=request, authority=authority) + assert lease.lease_expires_at == request.pre_deadline_at + assert row.started_at == now + + +def test_source_first_lease_cannot_extend_aggregate_deadline() -> None: + request = _source_reservation() + with pytest.raises(ValueError, match="lease facts"): + SelectedPreSubmitLeaseFacts( + reservation=request, lease_id=new_record_id(), lease_generation=1, + lease_expires_at=request.pre_deadline_at + timedelta(microseconds=1), + ) + + +def test_source_first_policy_requires_exactly_one_project_image() -> None: + from tests.checkers.external.test_selected_pre_submit import _empty_policy + with pytest.raises(ValueError, match="locked context"): + replace(_source_reservation(), policy=_empty_policy()) + + +def test_source_first_profile_rejects_archive_time_beyond_aggregate() -> None: + from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits + request = _source_reservation() + with pytest.raises(ValueError, match="locked context"): + replace(request, runtime_profile=request.runtime_profile.model_copy(update={ + "archive_limits": SubmissionArchiveLimits(maximum_inspection_seconds=121), + })) From d8de93372e83c731d7c86cc05b0abe94eca4b5eb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 11:55:38 +0100 Subject: [PATCH 053/513] Guard source-first PRE reservations with live intake custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 31 ++++ .../alembic/versions/0071_source_first_pre.py | 160 ++++++++++++++++++ backend/app/adapters/tasks/__init__.py | 2 +- .../test_submission_intake_custody.py | 142 +++++++++++++++- backend/tests/conftest.py | 2 +- 5 files changed, 334 insertions(+), 3 deletions(-) create mode 100644 backend/alembic/versions/0071_source_first_pre.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 64e3e49f7..cd749ed03 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1261,3 +1261,34 @@ failures must be replaced alongside the corresponding live callers, not hidden by narrowing CI. Scoped Ruff and diff whitespace checks passed. Freshly fetched main remains an ancestor of the branch. Remote CI for the prior pushed commit was still running when polled; no green outcome is inferred. + +The source-first SQL transition now adds migration 0071: nullable historical +columns, unique source-operation/composite TASK linkage, TASK/ART source checks, +exact approved PRE and POST policy comparisons, closed v2 request keys and +versioned execute/finalize audit digests. Existing revision-expiry/exhaustion +lineage logic is retained by exact guarded function replacements. Historical v1 +run updates are refused and old prepared-bundle admission joins are v1-only. +No retained row is rewritten or terminalized. The TASK adapter now supplies the +existing context port required by `IntakeTaskCustody`; its missing constructor +argument was found while tracing the real composition path. + +Fresh PostgreSQL migration succeeded. Schema setup correctly refused the old +fingerprint; the new fingerprint was measured from the migrated database as +`dead223f93cd881dc9710b44c91a146bbba890073c857b88ff11b137a778460b`. +The first source-guard fixture had an approved policy with no selected PRE image +and failed at the new exact-one constructor, before SQL. The test now requests +one registered image through the genuine approval fixture; production cardinality +was not relaxed. Its positive control passes the composed ART source port and +inserts a queued v2 row through the real SQL insert and deferred receipt guards. +Two separate PostgreSQL tests prove Python/SQL execute/finalize digest agreement +for both the frozen v1 vector and a v2 request. Database cleanup was confirmed. +The full eight source substitution/control cases plus those two digest tests are +running for the frozen SQL candidate; pending results are not a pass. + +This remains part of the unfinished live replacement: production source-first +producer/callers, result envelope, v2 read dispatch, old capability removal and +native one-session runtime remain outstanding. Full retained-row upgrade and +new receipt lifecycle proof are still needed; the frozen-vector digest checks +are narrower evidence. The full earlier pushed Backend run at `d8677d2f8` has +now completed successfully; it does not qualify these local changes. Scoped +Ruff/whitespace checks pass and the protected ownership partition is unchanged. diff --git a/backend/alembic/versions/0071_source_first_pre.py b/backend/alembic/versions/0071_source_first_pre.py new file mode 100644 index 000000000..77c826dce --- /dev/null +++ b/backend/alembic/versions/0071_source_first_pre.py @@ -0,0 +1,160 @@ +"""Bind new selected PRE runs to live sealed intake; retain v1 evidence read-only.""" +from alembic import op +from sqlalchemy import text + +revision = "0071_source_first_pre" +down_revision = "0070_submission_intake_authority" +branch_labels = None +depends_on = None + + +def _replace(signature, old, new): + """Preserve intervening lineage repairs and refuse an unexpected SQL shape.""" + body = op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))" + ), {"signature": signature}).scalar_one() + if body.count(old) != 1: + raise RuntimeError("source-first PRE predecessor shape changed: " + signature) + op.execute(body.replace(old, new)) + + +def _source_guard(): + op.execute(r""" +CREATE FUNCTION public.require_selected_pre_source(r public.selected_pre_submit_runs) +RETURNS void LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ +DECLARE t public.workstream_tasks%ROWTYPE; o public.submission_intake_operations%ROWTYPE; + source jsonb; request jsonb:=r.request_json; observed timestamptz; +BEGIN + SELECT * INTO t FROM public.workstream_tasks WHERE id=r.task_id FOR UPDATE; + IF NOT FOUND OR t.active_submission_operation_id IS DISTINCT FROM r.source_operation_id + THEN RAISE EXCEPTION 'selected PRE active source mismatch' USING ERRCODE='23514'; END IF; + SELECT * INTO o FROM public.submission_intake_operations + WHERE id=r.source_operation_id AND task_id=r.task_id FOR UPDATE; + observed:=clock_timestamp(); + IF NOT FOUND OR o.state IS DISTINCT FROM 'pre_checking' + OR o.lease_expires_at<=observed OR o.pre_deadline_at<=observed + OR o.project_id IS DISTINCT FROM r.project_id + OR o.assignment_id IS DISTINCT FROM r.assignment_id + OR o.actor_profile_id IS DISTINCT FROM r.actor_profile_id + OR o.identity_link_id IS DISTINCT FROM r.identity_link_id + OR o.idempotency_key IS DISTINCT FROM r.idempotency_key + OR o.metadata_sha256 IS DISTINCT FROM request->>'metadata_sha256' + OR o.locked_context_sha256 IS DISTINCT FROM request->>'locked_context_sha256' + OR o.locked_task_context IS DISTINCT FROM public.submission_intake_task_snapshot(t) + OR o.lease_id IS DISTINCT FROM (request->>'foreground_lease_id')::uuid + OR o.lease_generation IS DISTINCT FROM (request->>'foreground_lease_generation')::bigint + OR o.pre_deadline_at IS DISTINCT FROM (request->>'pre_deadline_at')::timestamptz + OR (r.lease_expires_at IS NOT NULL AND r.lease_expires_at>o.pre_deadline_at) + THEN RAISE EXCEPTION 'selected PRE source custody mismatch' USING ERRCODE='23514'; END IF; + source:=jsonb_build_object( + 'location',jsonb_build_object('operation_id',o.id::text,'namespace_id',o.namespace_id, + 'namespace_fingerprint',o.namespace_fingerprint,'provider_profile',o.provider_profile), + 'provider_generation',o.provider_generation,'raw_sha256',o.raw_sha256, + 'raw_byte_count',o.raw_byte_count,'sealed_upload_fence',o.sealed_upload_fence, + 'media_type','application/zip'); + IF request->'source' IS DISTINCT FROM source + OR request->>'source_sha256' IS DISTINCT FROM public.external_checker_registry_digest( + source||jsonb_build_object('schema_version','workstream.sealed_submission_source.v1')) + OR r.archive_sha256 IS DISTINCT FROM o.raw_sha256 + OR r.archive_byte_count IS DISTINCT FROM o.raw_byte_count + OR request->'default_context'->'packet' IS DISTINCT FROM jsonb_build_object( + 'summary',o.command_metadata->>'summary', + 'contributor_attestation',o.command_metadata->>'contributor_attestation') + OR request->'admission_lineage'->>'packet_sha256' IS DISTINCT FROM + public.external_checker_registry_digest(request->'default_context'->'packet') + OR request->'admission_lineage'->>'rules_sha256' IS DISTINCT FROM + request->'default_context'->>'current_rules_sha256' + OR request->'admission_lineage' ?| ARRAY['semantic_manifest_id','semantic_manifest_body'] + THEN RAISE EXCEPTION 'selected PRE source descriptor mismatch' USING ERRCODE='23514'; END IF; + IF NOT EXISTS(SELECT 1 FROM public.pre_submit_checker_policies p + WHERE p.id=t.locked_pre_submit_checker_policy_id AND p.project_id=r.project_id + AND p.compiled_bundle::jsonb=request->'policy') + OR NOT EXISTS(SELECT 1 FROM public.project_guide_proposal_approvals a + WHERE a.pre_submit_policy_id=t.locked_pre_submit_checker_policy_id + AND a.project_id=r.project_id + AND a.effective_pre_submit_plan::jsonb->'post_submit'= + request->'admission_lineage'->'post_submit_policy_body' + AND a.effective_pre_submit_plan_hash= + request->'admission_lineage'->>'external_checker_policies_sha256') + OR jsonb_array_length(request->'policy'->'entries') IS DISTINCT FROM 1 + OR r.policy_sha256 IS DISTINCT FROM public.external_checker_registry_digest( + (request->'policy')-'policy_sha256') + THEN RAISE EXCEPTION 'selected PRE policy custody mismatch' USING ERRCODE='23514'; END IF; +END $$ +""") + + +def _insert_guard(): + signature = "public.guard_selected_pre_submit_run_insert()" + changes = [ + ("'workstream.selected_pre_submit_reservation.v1'", "'workstream.selected_pre_submit_reservation.v2'"), + ("new.prepared_generation_id is distinct from\n (new.request_json->>'prepared_generation_id')::uuid", + "new.prepared_generation_id is not null\n or new.source_operation_id is null"), + ("new.request_json->>'policy_sha256'", "new.request_json->'policy'->>'policy_sha256'"), + ("new.request_json->>'default_behavior_sha256'", "new.request_json->'policy'->'workstream_default'->>'behavior_sha256'"), + ("new.default_input_sha256 is distinct from new.request_json->>'default_input_sha256'", "new.default_input_sha256 is not null"), + ("new.request_json->>'archive_sha256'", "new.request_json->'source'->>'raw_sha256'"), + ("new.request_json->>'archive_byte_count'", "new.request_json->'source'->>'raw_byte_count'"), + ("new.semantic_manifest_sha256 is distinct from\n new.request_json->>'semantic_manifest_sha256'", "new.semantic_manifest_sha256 is not null"), + ("or jsonb_typeof(lineage) is distinct from 'object'", """or jsonb_typeof(lineage) is distinct from 'object' + or not new.request_json ?& ARRAY['schema_version','actor_profile_id','identity_link_id', + 'project_id','task_id','assignment_id','attempt_id','idempotency_key','foreground_lease_id', + 'source','source_sha256','metadata_sha256','locked_context_sha256', + 'foreground_lease_generation','pre_deadline_at','policy','default_context', + 'runtime_profile','admission_lineage'] + or new.request_json-ARRAY['schema_version','actor_profile_id','identity_link_id', + 'project_id','task_id','assignment_id','attempt_id','idempotency_key','foreground_lease_id', + 'source','source_sha256','metadata_sha256','locked_context_sha256', + 'foreground_lease_generation','pre_deadline_at','policy','default_context', + 'runtime_profile','admission_lineage'] <> '{}'::jsonb"""), + ("new.request_json->>'execution_budget_ms'", "new.request_json->'runtime_profile'->>'aggregate_deadline_ms'"), + (" return new;", " perform public.require_selected_pre_source(new);\n return new;"), + ] + for old, new in changes: + _replace(signature, old, new) + + +def _update_guard(): + signature = "public.guard_selected_pre_submit_run()" + _replace(signature, " if row(old.id,", """ if old.request_json->>'schema_version' is distinct from + 'workstream.selected_pre_submit_reservation.v2' then + raise exception 'historical selected PRE runs are read-only' using errcode='55000'; + end if; + if old.source_operation_id is distinct from new.source_operation_id then + raise exception 'selected PRE source is immutable' using errcode='55000'; + end if; + if row(old.id,""") + _replace(signature, " return new;", " perform public.require_selected_pre_source(new);\n return new;") + signature = "public.selected_pre_submit_facts_digest(public.selected_pre_submit_runs,text)" + for phase in ("execute", "finalize"): + old = f"'workstream.selected_pre_submit_{phase}.v1'" + new = ("case when r.request_json->>'schema_version'=" + "'workstream.selected_pre_submit_reservation.v2' then " + f"'workstream.selected_pre_submit_{phase}.v2' else {old} end") + _replace(signature, old, new) + for signature in ( + "public.guard_submission_bundle_durable_intent_put_attempt()", + "public.guard_submission_bundle_admission_verified_lineage()", + ): + _replace(signature, "r.status='completed' and r.eligible", + "r.status='completed' and r.eligible and r.request_json->>'schema_version'=" + "'workstream.selected_pre_submit_reservation.v1'") + + +def upgrade(): + """Retain historical bytes while restricting new writes to source-bound runs.""" + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("ALTER TABLE public.selected_pre_submit_runs ADD COLUMN source_operation_id uuid") + for column in ("prepared_generation_id", "default_input_sha256", "semantic_manifest_sha256"): + op.execute(f"ALTER TABLE public.selected_pre_submit_runs ALTER COLUMN {column} DROP NOT NULL") + op.execute("""ALTER TABLE public.selected_pre_submit_runs + ADD CONSTRAINT fk_selected_pre_run_source_operation FOREIGN KEY(source_operation_id,task_id) + REFERENCES public.submission_intake_operations(id,task_id), + ADD CONSTRAINT uq_selected_pre_run_source_operation UNIQUE(source_operation_id)""") + _source_guard() + _insert_guard() + _update_guard() + + +def downgrade(): + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py index d410182ff..c51d62360 100644 --- a/backend/app/adapters/tasks/__init__.py +++ b/backend/app/adapters/tasks/__init__.py @@ -720,4 +720,4 @@ def intake_task_custody_port(session): """Compose TASK-first active intake pointer custody for ART participation.""" from app.modules.tasks.intake_custody import IntakeTaskCustody - return IntakeTaskCustody(session) + return IntakeTaskCustody(session, task_submission_context_port(session)) diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 81b727666..2cca38176 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -41,12 +41,14 @@ def capacity_limits(request): @pytest.fixture -async def intake(tmp_path, isolated_database_env, capacity_limits): +async def intake(tmp_path, isolated_database_env, capacity_limits, request): engine = create_async_engine(isolated_database_env) factory = async_sessionmaker(engine, expire_on_commit=False) try: + from tests.checkers.external.support import pre_registry_spec plan, _ = await approved_selected_policy_fixture( factory, _namespace(_settings(tmp_path)), guide_version="v1", + pre_submit_registry_spec=pre_registry_spec() if getattr(request, "param", False) else None, ) actor = _context() async with factory.begin() as session: @@ -1047,3 +1049,141 @@ async def test_pre_source_custody_rejects_substitution_or_stale_owner(intake, ch ) finally: await session.rollback() + + +@pytest.mark.parametrize("intake", [True], indirect=True) +@pytest.mark.parametrize("changed", [None, "source", "packet", "policy", "post_policy", "fence", "deadline", "actor"]) +async def test_selected_pre_sql_requires_exact_live_source(intake, changed): + """Exercise the SQL source participant; not full PRE execution or T4 proof.""" + from dataclasses import replace + from app.modules.checkers.api.external_policy import LockedExternalCheckerPolicies + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + deadline = datetime.now(UTC) + timedelta(minutes=2) + source = await repository(session).seal( + operation, lease, 1, provider_generation="pre-source-generation", + pre_deadline_at=deadline, lease_expires_at=deadline, + ) + from app.adapters.artifacts import submission_intake_pre_source_port + guarded = await submission_intake_pre_source_port(session).lock_pre_source( + source=source, lease_id=lease, generation=1, + ) + assert guarded.source == source + policy_body = await session.scalar(text(""" + SELECT a.effective_pre_submit_plan FROM project_guide_proposal_approvals a + JOIN workstream_tasks t ON t.locked_pre_submit_checker_policy_id=a.pre_submit_policy_id + WHERE t.id=:task + """), {"task": intake.task}) + policies = LockedExternalCheckerPolicies.model_validate_json(json.dumps(policy_body)) + base = _source_reservation() + locked = await session.scalar(text(""" + SELECT jsonb_build_object('task',to_jsonb(t),'guide_id',g.id) + FROM workstream_tasks t JOIN project_guides g + ON g.project_id=t.project_id AND g.version=t.locked_guide_version + WHERE t.id=:task + """), {"task": intake.task}) + task = locked["task"] + lineage = replace( + base.admission_lineage, effective_plan_sha256=policies.pre_submit.policy_sha256, + guide_id=UUID(locked["guide_id"]), guide_version=task["locked_guide_version"], + source_snapshot_id=UUID(task["locked_guide_source_snapshot_id"]), + source_snapshot_sha256=task["locked_guide_source_snapshot_hash"], + effective_policy_id=UUID(task["locked_effective_project_submission_artifact_policy_id"]), + effective_policy_sha256=task["locked_effective_project_submission_artifact_policy_hash"], + pre_submit_policy_id=UUID(task["locked_pre_submit_checker_policy_id"]), + pre_submit_policy_sha256=task["locked_pre_submit_checker_bundle_hash"], + external_checker_policies_sha256=policies.policies_sha256, + post_submit_policy_body=policies.post_submit.model_dump(mode="json"), + post_submit_policy_sha256=policies.post_submit.policy_sha256, + ) + request = replace( + base, actor_profile_id=UUID(row.actor_profile_id), identity_link_id=UUID(row.identity_link_id), + project_id=UUID(row.project_id), task_id=intake.task, assignment_id=intake.assignment, + idempotency_key=UUID(row.idempotency_key), source=source, + metadata_sha256=row.metadata_sha256, locked_context_sha256=row.locked_context_sha256, + foreground_lease_id=lease, foreground_lease_generation=1, pre_deadline_at=deadline, + policy=policies.pre_submit, admission_lineage=lineage, + ) + body = request.canonical_body() + if changed == "source": + body["source"]["provider_generation"] = "substituted" + elif changed == "packet": + body["default_context"]["packet"]["summary"] = "substituted" + elif changed == "policy": + body["policy"]["entries"] = [] + elif changed == "post_policy": + body["admission_lineage"]["post_submit_policy_body"] = {} + elif changed == "fence": + body["foreground_lease_generation"] += 1 + elif changed == "deadline": + body["pre_deadline_at"] = (deadline + timedelta(seconds=1)).isoformat() + value = { + "source_operation_id": str(operation), "task_id": str(intake.task), + "project_id": row.project_id, "assignment_id": str(intake.assignment), + "actor_profile_id": str(new_record_id()) if changed == "actor" else row.actor_profile_id, + "identity_link_id": row.identity_link_id, "idempotency_key": row.idempotency_key, + "request_json": body, "archive_sha256": source.raw_sha256, + "archive_byte_count": source.raw_byte_count, "policy_sha256": request.policy_sha256, + } + async with intake.factory.begin() as session: + statement = text("""SELECT public.require_selected_pre_source( + jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)))""") + if changed is None: + await session.execute(statement, {"value": json.dumps(value)}) + from app.modules.checkers.models import SelectedPreSubmitRun + session.add(SelectedPreSubmitRun( + id=str(request.attempt_id), source_operation_id=str(operation), + actor_profile_id=row.actor_profile_id, identity_link_id=row.identity_link_id, + project_id=row.project_id, task_id=str(intake.task), assignment_id=str(intake.assignment), + idempotency_key=row.idempotency_key, request_json=request.canonical_body(), + request_digest=request.request_digest, policy_sha256=request.policy_sha256, + default_behavior_sha256=request.default_behavior_sha256, + archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count, + execution_budget_ms=request.execution_budget_ms, status="queued", lease_generation=0, + )) + await session.flush() + else: + with pytest.raises(DBAPIError, match="selected PRE"): + await session.execute(statement, {"value": json.dumps(value)}) + await session.rollback() + + +@pytest.mark.parametrize("version", ["v1", "v2"]) +async def test_selected_pre_sql_audit_digest_keeps_versioned_custody(isolated_database_env, version): + from app.core.hashing import canonical_json_hash + from tests.checkers.external.test_selected_pre_submit_coordination import _retained_v1, _source_reservation + + retained = _retained_v1() + request = retained["request"] if version == "v1" else _source_reservation().canonical_body() + terminal = retained["terminal"] + execute = { + "schema_version": f"workstream.selected_pre_submit_execute.{version}", + "reservation": request, "lease_id": terminal["lease_id"], + "lease_generation": terminal["lease_generation"], "lease_expires_at": terminal["lease_expires_at"], + } + expected_execute = canonical_json_hash(execute) + expected_finalize = canonical_json_hash({ + "schema_version": f"workstream.selected_pre_submit_finalize.{version}", + "execute_facts_digest": expected_execute, + "execution": terminal["execution"], + "infrastructure_failure_code": terminal["infrastructure_failure_code"], + }) + value = { + "request_json": request, "lease_id": execute["lease_id"], + "lease_generation": execute["lease_generation"], "lease_expires_at": execute["lease_expires_at"], + "terminal_json": terminal, + } + engine = create_async_engine(isolated_database_env) + try: + async with engine.connect() as connection: + for phase, expected in (("execute", expected_execute), ("finalize", expected_finalize)): + actual = await connection.scalar(text("""SELECT public.selected_pre_submit_facts_digest( + jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)), + :phase)"""), {"value": json.dumps(value), "phase": phase}) + assert actual == expected + finally: + await engine.dispose() diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index e4563fc1a..fc2f790fe 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "c7829662a20e2ac52fcab3f9cb5830a7a0656f9eb7c4564aeae76d1230c2d84a" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "dead223f93cd881dc9710b44c91a146bbba890073c857b88ff11b137a778460b" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", From 2910cdef5bf84a4ee248c2e21849bd6c171c65f1 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:05:48 +0100 Subject: [PATCH 054/513] Bind PRE terminal and default context to authoritative custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 27 ++++ backend/alembic/env.py | 3 +- .../alembic/versions/0071_source_first_pre.py | 84 ++++++++++- .../checkers/api/selected_pre_submit.py | 8 +- .../test_submission_intake_custody.py | 134 ++++++++++++++++-- backend/tests/conftest.py | 2 +- 6 files changed, 236 insertions(+), 22 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index cd749ed03..8a1b086a5 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1292,3 +1292,30 @@ new receipt lifecycle proof are still needed; the frozen-vector digest checks are narrower evidence. The full earlier pushed Backend run at `d8677d2f8` has now completed successfully; it does not qualify these local changes. Scoped Ruff/whitespace checks pass and the protected ownership partition is unchanged. + +Scoped architecture/security and QA held `d8de93372`: terminal updates could +rebind committed lease/execute receipt fields; separate default predecessor +facts lacked authoritative comparison; terminal outer JSON lacked row/hash +binding; and Alembic's accepted starting-revision list omitted 0071. QA also +required recomputed-hash forgeries and negative INSERT coverage. The 10 prior +PostgreSQL tests passed with cleanup, but their receipt records base `a99d05036` +and dirty-tree code later committed as `d8de93372`; credit them as compatible +scope proof, not exact-head execution. + +The repair freezes committed claim fields, binds closed terminal outer facts and +canonical digest to row identity/timing/outcome, and derives the entire default +context from locked TASK policy identities, approved policy hash, original packet +and exact consumed predecessor admission. The predecessor lookup uses existing +Submission TASK/assignment ownership plus ART admission project/source/rules +custody. Live latency arithmetic now uses integer milliseconds to agree exactly +with SQL; frozen historical serialization is unchanged. Alembic accepts both +0070 upgrades and already-current 0071. Tests recompute source/packet/request +hashes, send negative INSERTs, and use real fixed-service AUTH claim/finalize with +attempted claim/terminal substitutions. The existing repeat-upgrade test is reused. + +Forty-nine source-first/historical contract tests pass. The repaired migration +applies with measured schema fingerprint +`d12af28660d6d712d4c97828a39831c34e7c7bf2aec96efe0ba104cee1512b2a`. +The repaired PostgreSQL lifecycle/negative/repeat-upgrade command will run after +this candidate is committed, so its receipt can identify the actual head. +Required re-review and full live caller/result/read/runtime cutover remain open. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 4704c3574..397596ffb 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0070_submission_intake_authority" +_CURRENT_HEAD_REVISION = "0071_source_first_pre" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -124,6 +124,7 @@ def do_run_migrations(connection: Connection) -> None: ("0067_canonical_json_restore_path",), ("0068_issuer_profile_email",), ("0069_submission_intake_custody",), + ("0070_submission_intake_authority",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0071_source_first_pre.py b/backend/alembic/versions/0071_source_first_pre.py index 77c826dce..fb592b4bd 100644 --- a/backend/alembic/versions/0071_source_first_pre.py +++ b/backend/alembic/versions/0071_source_first_pre.py @@ -24,6 +24,8 @@ def _source_guard(): RETURNS void LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ DECLARE t public.workstream_tasks%ROWTYPE; o public.submission_intake_operations%ROWTYPE; source jsonb; request jsonb:=r.request_json; observed timestamptz; + predecessor jsonb:='null'::jsonb; predecessor_rules text; policy_lineage jsonb; + rules text; expected_context jsonb; predecessor_id uuid; BEGIN SELECT * INTO t FROM public.workstream_tasks WHERE id=r.task_id FOR UPDATE; IF NOT FOUND OR t.active_submission_operation_id IS DISTINCT FROM r.source_operation_id @@ -33,6 +35,7 @@ def _source_guard(): observed:=clock_timestamp(); IF NOT FOUND OR o.state IS DISTINCT FROM 'pre_checking' OR o.lease_expires_at<=observed OR o.pre_deadline_at<=observed + OR t.status IS DISTINCT FROM o.eligible_task_status OR o.project_id IS DISTINCT FROM r.project_id OR o.assignment_id IS DISTINCT FROM r.assignment_id OR o.actor_profile_id IS DISTINCT FROM r.actor_profile_id @@ -80,6 +83,46 @@ def _source_guard(): OR r.policy_sha256 IS DISTINCT FROM public.external_checker_registry_digest( (request->'policy')-'policy_sha256') THEN RAISE EXCEPTION 'selected PRE policy custody mismatch' USING ERRCODE='23514'; END IF; + SELECT jsonb_object_agg(key,value) INTO policy_lineage FROM jsonb_each(to_jsonb(t)) + WHERE key=ANY(ARRAY[ + 'locked_guide_version','locked_guide_source_snapshot_id','locked_guide_source_snapshot_hash', + 'locked_effective_project_submission_artifact_policy_id', + 'locked_effective_project_submission_artifact_policy_hash','locked_pre_submit_checker_policy_id', + 'locked_pre_submit_checker_bundle_hash','locked_post_submit_checker_policy_id', + 'locked_post_submit_checker_policy_version','locked_post_submit_checker_policy_hash', + 'locked_review_policy_id','locked_review_policy_generation','locked_review_policy_hash', + 'locked_revision_policy_id','locked_revision_policy_generation','locked_revision_policy_hash', + 'locked_contribution_policy_version_id']); + rules:=public.external_checker_registry_digest(jsonb_build_object( + 'schema_version','workstream.task_checker_rules.v1','task_policy',policy_lineage, + 'external_checker_policies_sha256',request->'admission_lineage'->>'external_checker_policies_sha256')); + predecessor_id:=(request->'admission_lineage'->>'predecessor_submission_id')::uuid; + IF predecessor_id IS NOT NULL THEN + SELECT jsonb_build_object('submission_id',s.id::text,'submission_version',s.version, + 'archive_sha256',a.archive_sha256,'semantic_manifest_sha256',a.semantic_manifest_sha256), + a.selected_rules_sha256 INTO predecessor,predecessor_rules + FROM public.submissions s JOIN public.submission_bundle_admissions a + ON a.consumed_by_submission_id=s.id AND a.status='consumed' + WHERE s.id=predecessor_id AND s.task_id=r.task_id AND a.project_id=r.project_id + AND a.task_id=s.task_id AND a.assignment_id=r.assignment_id + AND s.task_assignment_id=r.assignment_id AND s.contributor_id=r.actor_profile_id + AND s.version=(request->'admission_lineage'->>'predecessor_submission_version')::integer + AND a.selected_pre_submit_run_id IS NOT NULL AND a.pre_submit_evidence_set_id IS NULL + AND a.selected_rules_sha256 IS NOT NULL + AND NOT EXISTS(SELECT 1 FROM public.submissions later + WHERE later.task_id=s.task_id AND later.version>s.version); + IF NOT FOUND THEN + RAISE EXCEPTION 'selected PRE predecessor custody mismatch' USING ERRCODE='23514'; + END IF; + END IF; + expected_context:=jsonb_build_object('predecessor',predecessor, + 'current_predecessor',predecessor,'predecessor_exists',predecessor_id IS NOT NULL, + 'predecessor_rules_sha256',predecessor_rules,'current_rules_sha256',rules, + 'packet',jsonb_build_object('summary',o.command_metadata->>'summary', + 'contributor_attestation',o.command_metadata->>'contributor_attestation')); + IF request->'default_context' IS DISTINCT FROM expected_context THEN + RAISE EXCEPTION 'selected PRE default context mismatch' USING ERRCODE='23514'; + END IF; END $$ """) @@ -124,7 +167,46 @@ def _update_guard(): raise exception 'selected PRE source is immutable' using errcode='55000'; end if; if row(old.id,""") - _replace(signature, " return new;", " perform public.require_selected_pre_source(new);\n return new;") + _replace(signature, " return new;", """ + if old.status='running' then + if row(old.lease_id,old.lease_generation,old.lease_expires_at,old.started_at,old.execute_evidence_id) + is distinct from + row(new.lease_id,new.lease_generation,new.lease_expires_at,new.started_at,new.execute_evidence_id) + then raise exception 'selected PRE committed claim is immutable' using errcode='55000'; end if; + if new.terminal_json-ARRAY['schema_version','reservation','request_digest','lease_id', + 'lease_generation','lease_expires_at','outcome','execution','infrastructure_failure_code', + 'queued_at','started_at','completed_at','queue_latency_ms','execution_latency_ms'] <> '{}'::jsonb + or new.terminal_json->>'schema_version' is distinct from 'workstream.selected_pre_submit_terminal.v2' + or new.terminal_digest is distinct from public.external_checker_registry_digest(new.terminal_json) + or new.terminal_json->'reservation' is distinct from new.request_json + or new.terminal_json->>'request_digest' is distinct from new.request_digest + or new.terminal_json->>'outcome' is distinct from new.status + or (new.terminal_json->>'lease_id')::uuid is distinct from new.lease_id + or (new.terminal_json->>'lease_generation')::bigint is distinct from new.lease_generation + or (new.terminal_json->>'lease_expires_at')::timestamptz is distinct from new.lease_expires_at + or (new.terminal_json->>'queued_at')::timestamptz is distinct from new.queued_at + or (new.terminal_json->>'started_at')::timestamptz is distinct from new.started_at + or (new.terminal_json->>'completed_at')::timestamptz is distinct from new.completed_at + or new.completed_at>'queue_latency_ms')::bigint is distinct from + trunc(extract(epoch from new.started_at-new.queued_at)*1000)::bigint + or (new.terminal_json->>'execution_latency_ms')::bigint is distinct from + trunc(extract(epoch from new.completed_at-new.started_at)*1000)::bigint + then raise exception 'selected PRE terminal binding mismatch' using errcode='23514'; end if; + if new.status='completed' then + if jsonb_typeof(new.terminal_json->'execution') is distinct from 'object' + or new.terminal_json->'infrastructure_failure_code' is distinct from 'null'::jsonb + or new.terminal_json->'execution'->>'policy_sha256' is distinct from new.policy_sha256 + or (new.terminal_json->'execution'->>'eligible')::boolean is distinct from new.eligible + or new.completed_at>new.lease_expires_at + then raise exception 'selected PRE terminal result mismatch' using errcode='23514'; end if; + elsif new.terminal_json->'execution' is distinct from 'null'::jsonb + or coalesce(new.terminal_json->>'infrastructure_failure_code','') not in + ('capacity_exceeded','deadline_exceeded','material_unavailable','implementation_unavailable','invalid_output') + then raise exception 'selected PRE terminal result mismatch' using errcode='23514'; end if; + end if; + perform public.require_selected_pre_source(new); + return new;""") signature = "public.selected_pre_submit_facts_digest(public.selected_pre_submit_runs,text)" for phase in ("execute", "finalize"): old = f"'workstream.selected_pre_submit_{phase}.v1'" diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py index 47ec3ef62..2777a56d4 100644 --- a/backend/app/modules/checkers/api/selected_pre_submit.py +++ b/backend/app/modules/checkers/api/selected_pre_submit.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import asdict, dataclass -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from contextlib import AbstractAsyncContextManager from typing import Literal, Protocol from uuid import UUID @@ -803,10 +803,8 @@ def canonical_body(self) -> dict[str, object]: "queued_at": self.queued_at.isoformat(), "started_at": self.started_at.isoformat(), "completed_at": self.completed_at.isoformat(), - "queue_latency_ms": int((self.started_at - self.queued_at).total_seconds() * 1000), - "execution_latency_ms": int( - (self.completed_at - self.started_at).total_seconds() * 1000 - ), + "queue_latency_ms": (self.started_at - self.queued_at) // timedelta(milliseconds=1), + "execution_latency_ms": (self.completed_at - self.started_at) // timedelta(milliseconds=1), } @classmethod diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 2cca38176..b6f9ee2ad 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -1052,10 +1052,12 @@ async def test_pre_source_custody_rejects_substitution_or_stale_owner(intake, ch @pytest.mark.parametrize("intake", [True], indirect=True) -@pytest.mark.parametrize("changed", [None, "source", "packet", "policy", "post_policy", "fence", "deadline", "actor"]) +@pytest.mark.parametrize("changed", [None, "source", "packet", "policy", "post_policy", "fence", "deadline", "actor", "rules", "predecessor", "predecessor_identity"]) async def test_selected_pre_sql_requires_exact_live_source(intake, changed): """Exercise the SQL source participant; not full PRE execution or T4 proof.""" from dataclasses import replace + from app.core.hashing import canonical_json_hash + from app.modules.tasks.api.transition_audit import TaskPolicyLineage from app.modules.checkers.api.external_policy import LockedExternalCheckerPolicies from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation @@ -1087,8 +1089,16 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): WHERE t.id=:task """), {"task": intake.task}) task = locked["task"] + locked_policy = TaskPolicyLineage.model_validate_json(json.dumps({ + key: task[key] for key in TaskPolicyLineage.model_fields + })) + rules = canonical_json_hash({ + "schema_version": "workstream.task_checker_rules.v1", + "task_policy": locked_policy.model_dump(mode="json"), + "external_checker_policies_sha256": policies.policies_sha256, + }) lineage = replace( - base.admission_lineage, effective_plan_sha256=policies.pre_submit.policy_sha256, + base.admission_lineage, rules_sha256=rules, effective_plan_sha256=policies.pre_submit.policy_sha256, guide_id=UUID(locked["guide_id"]), guide_version=task["locked_guide_version"], source_snapshot_id=UUID(task["locked_guide_source_snapshot_id"]), source_snapshot_sha256=task["locked_guide_source_snapshot_hash"], @@ -1107,12 +1117,17 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): metadata_sha256=row.metadata_sha256, locked_context_sha256=row.locked_context_sha256, foreground_lease_id=lease, foreground_lease_generation=1, pre_deadline_at=deadline, policy=policies.pre_submit, admission_lineage=lineage, + default_context=replace(base.default_context, current_rules_sha256=rules), ) body = request.canonical_body() if changed == "source": body["source"]["provider_generation"] = "substituted" + body["source_sha256"] = canonical_json_hash({ + "schema_version": "workstream.sealed_submission_source.v1", **body["source"], + }) elif changed == "packet": body["default_context"]["packet"]["summary"] = "substituted" + body["admission_lineage"]["packet_sha256"] = canonical_json_hash(body["default_context"]["packet"]) elif changed == "policy": body["policy"]["entries"] = [] elif changed == "post_policy": @@ -1121,6 +1136,15 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): body["foreground_lease_generation"] += 1 elif changed == "deadline": body["pre_deadline_at"] = (deadline + timedelta(seconds=1)).isoformat() + elif changed == "rules": + body["default_context"]["current_rules_sha256"] = "sha256:" + "f" * 64 + body["admission_lineage"]["rules_sha256"] = "sha256:" + "f" * 64 + elif changed == "predecessor": + body["default_context"]["predecessor_exists"] = True + elif changed == "predecessor_identity": + body["admission_lineage"]["predecessor_submission_id"] = str(new_record_id()) + body["admission_lineage"]["predecessor_submission_version"] = 1 + body["admission_lineage"]["checker_remediation_manifest_id"] = str(new_record_id()) value = { "source_operation_id": str(operation), "task_id": str(intake.task), "project_id": row.project_id, "assignment_id": str(intake.assignment), @@ -1134,22 +1158,30 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)))""") if changed is None: await session.execute(statement, {"value": json.dumps(value)}) - from app.modules.checkers.models import SelectedPreSubmitRun - session.add(SelectedPreSubmitRun( - id=str(request.attempt_id), source_operation_id=str(operation), - actor_profile_id=row.actor_profile_id, identity_link_id=row.identity_link_id, - project_id=row.project_id, task_id=str(intake.task), assignment_id=str(intake.assignment), - idempotency_key=row.idempotency_key, request_json=request.canonical_body(), - request_digest=request.request_digest, policy_sha256=request.policy_sha256, - default_behavior_sha256=request.default_behavior_sha256, - archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count, - execution_budget_ms=request.execution_budget_ms, status="queued", lease_generation=0, - )) - await session.flush() else: with pytest.raises(DBAPIError, match="selected PRE"): await session.execute(statement, {"value": json.dumps(value)}) await session.rollback() + from app.modules.checkers.models import SelectedPreSubmitRun + async with intake.factory.begin() as session: + session.add(SelectedPreSubmitRun( + id=str(request.attempt_id), source_operation_id=str(operation), + actor_profile_id=value["actor_profile_id"], identity_link_id=row.identity_link_id, + project_id=row.project_id, task_id=str(intake.task), assignment_id=str(intake.assignment), + idempotency_key=row.idempotency_key, request_json=body, + request_digest=canonical_json_hash(body), policy_sha256=request.policy_sha256, + default_behavior_sha256=request.default_behavior_sha256, + archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count, + execution_budget_ms=request.execution_budget_ms, status="queued", lease_generation=0, + )) + if changed is None: + await session.flush() + else: + with pytest.raises(DBAPIError, match="selected PRE"): + await session.flush() + await session.rollback() + if changed is None: + await _assert_pre_terminal_guards(intake, request) @pytest.mark.parametrize("version", ["v1", "v2"]) @@ -1187,3 +1219,77 @@ async def test_selected_pre_sql_audit_digest_keeps_versioned_custody(isolated_da assert actual == expected finally: await engine.dispose() + + +async def _assert_pre_terminal_guards(intake, request): + """Claim with real AUTH, reject rebound terminal updates, then finalize once.""" + from app.adapters.auth import selected_pre_submit_authority + from app.adapters.checkers import selected_pre_submit_coordinator + from app.core.hashing import canonical_json_hash + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitFinalizeFacts, SelectedPreSubmitTerminalFacts + from app.modules.checkers.models import SelectedPreSubmitRun + + async with intake.factory.begin() as session: + async with selected_pre_submit_authority(session).prepare_execution(request) as authority: + lease = await selected_pre_submit_coordinator(session).claim( + run_id=request.attempt_id, facts=request, authority=authority, + ) + finalize = SelectedPreSubmitFinalizeFacts( + lease=lease, execution=None, infrastructure_failure_code="capacity_exceeded", + ) + for changed in ("lease_id", "lease_expires_at", "started_at", "execute_evidence_id", + "schema_version", "reservation", "request_digest", "outcome", "terminal_digest", "extra"): + async with intake.factory.begin() as session: + async with selected_pre_submit_authority(session).prepare_finalization(finalize) as authority: + evidence = await authority.consume(finalize) + row = await session.get(SelectedPreSubmitRun, str(request.attempt_id)) + now = await session.scalar(text("select clock_timestamp()")) + terminal = SelectedPreSubmitTerminalFacts( + lease=lease, outcome="infrastructure_failed", execution=None, + infrastructure_failure_code="capacity_exceeded", queued_at=row.queued_at, + started_at=row.started_at, completed_at=now, + ).canonical_body() + values = dict( + id=request.attempt_id, lease_id=lease.lease_id, + lease_expires_at=lease.lease_expires_at, started_at=row.started_at, + execute_evidence_id=UUID(row.execute_evidence_id), completed_at=now, + finalize_evidence_id=evidence.evidence_id, + ) + claim_change = changed in {"lease_id", "lease_expires_at", "started_at", "execute_evidence_id"} + if changed in {"lease_id", "execute_evidence_id"}: + values[changed] = new_record_id() + if changed == "lease_id": + terminal[changed] = str(values[changed]) + elif changed in {"lease_expires_at", "started_at"}: + values[changed] -= timedelta(microseconds=1) + terminal[changed] = values[changed].isoformat() + elif changed == "schema_version": + terminal[changed] = "workstream.selected_pre_submit_terminal.v1" + elif changed == "reservation": + terminal[changed] = terminal[changed] | {"metadata_sha256": "sha256:" + "f" * 64} + elif changed == "request_digest": + terminal[changed] = "sha256:" + "f" * 64 + elif changed == "outcome": + terminal[changed] = "completed" + elif changed == "extra": + terminal["unexpected"] = True + values["terminal_json"] = json.dumps(terminal) + values["terminal_digest"] = ("sha256:" + "f" * 64 if changed == "terminal_digest" + else canonical_json_hash(terminal)) + message = "committed claim is immutable" if claim_change else "terminal binding mismatch" + with pytest.raises(DBAPIError, match=message): + await session.execute(text("""UPDATE selected_pre_submit_runs SET + status='infrastructure_failed', lease_id=:lease_id, lease_expires_at=:lease_expires_at, + started_at=:started_at, execute_evidence_id=:execute_evidence_id, + completed_at=:completed_at, finalize_evidence_id=:finalize_evidence_id, + terminal_json=CAST(:terminal_json AS jsonb), terminal_digest=:terminal_digest + WHERE id=:id"""), values) + await session.rollback() + async with intake.factory.begin() as session: + async with selected_pre_submit_authority(session).prepare_finalization(finalize) as authority: + completion = await selected_pre_submit_coordinator(session).finalize( + run_id=request.attempt_id, lease=lease, authority=authority, + execution=None, infrastructure_failure_code="capacity_exceeded", + ) + assert completion.terminal.outcome == "infrastructure_failed" + assert completion.capability is None diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index fc2f790fe..fee5e0668 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "dead223f93cd881dc9710b44c91a146bbba890073c857b88ff11b137a778460b" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "d12af28660d6d712d4c97828a39831c34e7c7bf2aec96efe0ba104cee1512b2a" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", From 15f3cd372f25f56ba945a3abb8ab071da3ef0ed4 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:09:48 +0100 Subject: [PATCH 055/513] Provision fixed PRE principal for SQL lifecycle proof --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++++++++++ .../tests/artifacts/test_submission_intake_custody.py | 3 +++ 2 files changed, 13 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8a1b086a5..d23522a0b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1319,3 +1319,13 @@ applies with measured schema fingerprint The repaired PostgreSQL lifecycle/negative/repeat-upgrade command will run after this candidate is committed, so its receipt can identify the actual head. Required re-review and full live caller/result/read/runtime cutover remain open. + +The repaired exact-head PostgreSQL run at `2910cdef5` completed with 13 passes, +one failure and cleanup confirmed. Source/packet/rules/predecessor substitutions, +versioned digest comparison and repeat migration passed. The positive lifecycle +case stopped before claim because its fixture lacked the fixed PRE service actor +(`ACTOR_NOT_FOUND`); no terminal-guard claim is credited from that run. Both +review tracks confirmed the prior code findings repaired but held proof pending +this fixture correction. The positive case now provisions only +`CHECKER_PRE_SUBMIT` through the existing real service-principal fixture helper, +without altering production authorization or resetting an existing principal. diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index b6f9ee2ad..121973f9e 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -1223,12 +1223,15 @@ async def test_selected_pre_sql_audit_digest_keeps_versioned_custody(isolated_da async def _assert_pre_terminal_guards(intake, request): """Claim with real AUTH, reject rebound terminal updates, then finalize once.""" + from app.modules.actors.api import ServiceIdentity + from tests.checkers.execution.support import provision_post_submit_service from app.adapters.auth import selected_pre_submit_authority from app.adapters.checkers import selected_pre_submit_coordinator from app.core.hashing import canonical_json_hash from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitFinalizeFacts, SelectedPreSubmitTerminalFacts from app.modules.checkers.models import SelectedPreSubmitRun + await provision_post_submit_service(intake.factory, ServiceIdentity.CHECKER_PRE_SUBMIT) async with intake.factory.begin() as session: async with selected_pre_submit_authority(session).prepare_execution(request) as authority: lease = await selected_pre_submit_coordinator(session).claim( From 7dd8ca6f5be17ce8eeb0aee51a746a20f9aa33df Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:12:49 +0100 Subject: [PATCH 056/513] Record reviewed source-first SQL custody proof --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d23522a0b..c7c89cd17 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1329,3 +1329,18 @@ review tracks confirmed the prior code findings repaired but held proof pending this fixture correction. The positive case now provisions only `CHECKER_PRE_SUBMIT` through the existing real service-principal fixture helper, without altering production authorization or resetting an existing principal. + +The corrected positive PostgreSQL lifecycle case passed at exact clean +`15f3cd372`, with cleanup confirmed. It provisions the fixed principal, claims +through real AUTH/coordinator composition, rejects ten committed-claim/terminal +substitutions and commits one valid infrastructure finalization. The 13 source, +digest and repeat-upgrade passes remain attributed to `2910cdef5`; production +code did not change between those heads. Both architecture/security and +QA/test-delta/CI passed the bounded SQL custody stage at `15f3cd372` with that +provenance distinction. Forty-nine contract tests, 229 ownership/lane checks, +Commitrail and changed Markdown links passed; the protected partition is unchanged. +These checks do not establish completed-result eligibility, a real revision +predecessor upgrade, the retained-row migration round trip or the public source +submission journey. The next implementation remains the live source-first +producer/result path and removal of its prepared-bundle consumers, followed by +the single-session runtime and the rest of the original end-to-end objective. From 61871924d552c785baa378f374c640d404e770b5 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:18:43 +0100 Subject: [PATCH 057/513] Build live PRE reservations from sealed source and locked context --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 20 +++ .../selected_pre_submit_admission.py | 139 ++++++++---------- .../test_submission_intake_custody.py | 94 ++++++------ 3 files changed, 132 insertions(+), 121 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c7c89cd17..71cb8878b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1344,3 +1344,23 @@ predecessor upgrade, the retained-row migration round trip or the public source submission journey. The next implementation remains the live source-first producer/result path and removal of its prepared-bundle consumers, followed by the single-session runtime and the rest of the original end-to-end objective. + +The live ART reservation producer is now source-first: it accepts locked ART +source facts and original metadata, compares TASK/PROJECT references and exact +approved policy/rules/packet, and produces v2 without current manifest, +prepared-generation or derived default-input facts. Its default-context binder +uses only locked policy and retained predecessor facts; it no longer inspects +or binds a current archive/change gate. The source-first PostgreSQL control now +commits sealing before opening the TASK/PROJECT/ART binding root and calls this +production builder instead of constructing a reservation from test row fields. +The initial positive source/SQL/real-AUTH lifecycle run passed with cleanup on +the dirty tree based at `7dd8ca6f5`; exact-head evidence is pending. Added builder +substitution probes cover metadata, actor/source custody, rules and packet. + +This is not the completed producer-to-runtime cutover. The old public preparation +caller still passes the removed inputs, and its prepared-bundle capability and +consumer chain still require coordinated removal when source execution/T4 replace +them. The old attempt-request hash helper is still referenced only by that chain +and its obsolete tests; it is not a second v2 request identity. No new route, +compatibility adapter, placeholder manifest or executable authority was added. +The existing reviewed L0 single-session plan and file/reviewer scope still apply. diff --git a/backend/app/modules/artifacts/selected_pre_submit_admission.py b/backend/app/modules/artifacts/selected_pre_submit_admission.py index 2ad0af672..c27f50fba 100644 --- a/backend/app/modules/artifacts/selected_pre_submit_admission.py +++ b/backend/app/modules/artifacts/selected_pre_submit_admission.py @@ -1,4 +1,4 @@ -"""Bind selected PRE policy and default inputs to locked TASK/PROJECT custody.""" +"""Bind sealed source and locked policy context before guest PRE.""" from __future__ import annotations @@ -6,31 +6,24 @@ from uuid import UUID from app.core.hashing import canonical_json_hash -from app.modules.artifacts.sources import ArtifactCommitment +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionIntakePreSourceFacts from app.modules.artifacts.submission_manifest import ( SubmissionCanonicalPredecessor, - semantic_manifest_identity, - SubmissionChangeGateResult, - SubmissionManifest, - bind_submission_change, ) from app.modules.checkers.api.default_checker import ( - WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - WorkstreamDefaultCheckerInput, WorkstreamDefaultContext, WorkstreamDefaultPredecessor, - workstream_default_input_body, ) from app.modules.checkers.api.external_policy import ( LockedExternalCheckerPolicies, LockedExternalPostSubmitPolicy, LockedExternalPreSubmitPolicy, ) -from app.modules.checkers.api.materialization import SubmissionMaterialEntry from app.modules.checkers.api.pre_submit_material import SubmissionPacketView from app.modules.checkers.api.selected_pre_submit import ( SelectedPreSubmitAdmissionLineage, SelectedPreSubmitReservationFacts, + SelectedPreSubmitRuntimeProfile, ) from app.modules.projects.api import ProjectLockedPolicyContextFacts from app.modules.tasks.api import TaskSubmissionContextFacts @@ -77,43 +70,71 @@ def selected_pre_submit_attempt_request_digest( @dataclass(frozen=True, slots=True) class SelectedPreSubmitAdmissionContext: - """Exact selected policy, default input and non-deciding change binding.""" + """Locked policy and default context known before source inspection.""" policy: LockedExternalPreSubmitPolicy post_policy: LockedExternalPostSubmitPolicy policies_sha256: str - default_input: WorkstreamDefaultCheckerInput - change_gate: SubmissionChangeGateResult + default_context: WorkstreamDefaultContext rules_sha256: str def build_selected_pre_submit_reservation( *, - actor_profile_id: UUID, - identity_link_id: UUID, + source: SubmissionIntakePreSourceFacts, + metadata: SubmissionIntakeMetadata, task: TaskSubmissionContextFacts, project: ProjectLockedPolicyContextFacts, - prepared_generation_id: UUID, attempt_id: UUID, idempotency_key: UUID, - attempt_request_digest: str, - commitment: ArtifactCommitment, - manifest: SubmissionManifest, - packet: SubmissionPacketView, selected: SelectedPreSubmitAdmissionContext, storage_scheme: str, - execution_budget_ms: int, + runtime_profile: SelectedPreSubmitRuntimeProfile, ) -> SelectedPreSubmitReservationFacts: - """Bind all later ART-admission facts into the selected durable request.""" + """Bind T3's locked source to policy/context without host ZIP inspection. + + The composition must hold the source port's root and AUTH custody. Detached + values are comparisons only; this builder grants neither reads nor execution. + """ + references = task.locked_project_context + packet = SubmissionPacketView(metadata.summary, metadata.contributor_attestation) if ( - task.contributor_id != actor_profile_id - or task.locked_project_context.project_id != project.project_id - or selected.policy.policy_sha256 - != canonical_json_hash( - selected.policy.model_dump(mode="json", exclude={"policy_sha256"}) - ) + type(source) is not SubmissionIntakePreSourceFacts + or source.task_id != task.task_id or source.assignment_id != task.assignment_id + or source.actor_profile_id != task.contributor_id + or source.project_id != project.project_id + or metadata.task_id != task.task_id or metadata.assignment_id != task.assignment_id + or metadata.metadata_sha256() != source.metadata_sha256 + or metadata.predecessor_submission_id != ( + task.predecessor.submission_id if task.predecessor else None) + or metadata.revision_preparation_id != ( + task.revision_context.preparation_id if task.revision_context else None) + or metadata.revision_preparation_sha256 != ( + task.revision_context.preparation_sha256 if task.revision_context else None) + or references.project_id != project.project_id + or references.guide_version != project.guide_version + or references.source_snapshot_id != project.source_snapshot_id + or references.source_snapshot_hash != project.source_snapshot_hash + or references.effective_policy_id != project.effective_policy_id + or references.effective_policy_hash != project.effective_policy_hash + or references.pre_submit_policy_id != project.pre_submit_policy_id + or references.pre_submit_policy_bundle_hash != project.pre_submit_policy_bundle_hash + or selected.default_context.packet != packet + or selected.default_context.predecessor_exists != (task.predecessor is not None) + or selected.default_context.current_predecessor != selected.default_context.predecessor ): raise ValueError("selected PRE reservation context differs") + policies = LockedExternalCheckerPolicies.model_validate_json(project.external_checker_policies.value) + expected_rules = canonical_json_hash({ + "schema_version": "workstream.task_checker_rules.v1", + "task_policy": task.locked_policy.model_dump(mode="json"), + "external_checker_policies_sha256": policies.policies_sha256, + }) + if (selected.policy != policies.pre_submit or selected.post_policy != policies.post_submit + or selected.policies_sha256 != policies.policies_sha256 + or selected.rules_sha256 != expected_rules + or selected.default_context.current_rules_sha256 != expected_rules): + raise ValueError("selected PRE policy context differs") predecessor = task.predecessor locked_guide_sha256 = canonical_json_hash( { @@ -162,8 +183,6 @@ def build_selected_pre_submit_reservation( post_submit_policy_sha256=selected.post_policy.policy_sha256, post_submit_policy_body=selected.post_policy.model_dump(mode="json"), locked_policy_context_hash=locked_policy_context_hash, - semantic_manifest_id=semantic_manifest_identity(manifest.sha256), - semantic_manifest_body=manifest.as_dict(), packet_sha256=packet.sha256, storage_scheme=storage_scheme, revision_preparation_id=( @@ -174,24 +193,14 @@ def build_selected_pre_submit_reservation( ), ) return SelectedPreSubmitReservationFacts( - actor_profile_id=actor_profile_id, - identity_link_id=identity_link_id, - project_id=project.project_id, - task_id=task.task_id, - assignment_id=task.assignment_id, - attempt_id=attempt_id, - idempotency_key=idempotency_key, - attempt_request_digest=attempt_request_digest, - prepared_generation_id=prepared_generation_id, - policy_sha256=selected.policy.policy_sha256, - default_behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - default_input_sha256=canonical_json_hash( - workstream_default_input_body(selected.default_input) - ), - archive_sha256=commitment.sha256, - archive_byte_count=commitment.byte_count, - semantic_manifest_sha256=manifest.sha256, - execution_budget_ms=execution_budget_ms, + actor_profile_id=source.actor_profile_id, identity_link_id=source.identity_link_id, + project_id=project.project_id, task_id=task.task_id, assignment_id=task.assignment_id, + attempt_id=attempt_id, idempotency_key=idempotency_key, + source=source.source, metadata_sha256=source.metadata_sha256, + locked_context_sha256=source.locked_context_sha256, + foreground_lease_id=source.lease_id, foreground_lease_generation=source.lease_generation, + pre_deadline_at=source.pre_deadline_at, policy=selected.policy, + default_context=selected.default_context, runtime_profile=runtime_profile, admission_lineage=lineage, ) @@ -200,8 +209,6 @@ def bind_selected_pre_submit_admission( *, task: TaskSubmissionContextFacts, project: ProjectLockedPolicyContextFacts, - commitment: ArtifactCommitment, - manifest: SubmissionManifest, predecessor: SubmissionCanonicalPredecessor | None, predecessor_rules_sha256: str | None, predecessor_exists: bool, @@ -232,42 +239,24 @@ def bind_selected_pre_submit_admission( ) if (predecessor_rules_sha256 is None) != (predecessor is None): raise ValueError("selected PRE predecessor rules are incomplete") - change_gate = bind_submission_change( - commitment=commitment, - manifest=manifest, - predecessor=predecessor, - predecessor_exists=predecessor_exists, - current_predecessor=predecessor, - ) - entries = tuple( - SubmissionMaterialEntry( - normalized_path=item.normalized_path, - entry_type=item.entry_type.value, - byte_count=item.byte_count, - sha256=item.sha256, - executable=item.executable, - ) - for item in manifest.entries - ) + if (predecessor_exists != (predecessor is not None) + or (predecessor.submission_id if predecessor else None) != ( + task.predecessor.submission_id if task.predecessor else None) + or (predecessor.submission_version if predecessor else None) != ( + task.predecessor.version if task.predecessor else None)): + raise ValueError("selected PRE predecessor differs from locked TASK") return SelectedPreSubmitAdmissionContext( policy=policies.pre_submit, post_policy=policies.post_submit, policies_sha256=policies.policies_sha256, - default_input=WorkstreamDefaultContext( + default_context=WorkstreamDefaultContext( predecessor=default_predecessor, predecessor_exists=predecessor_exists, current_predecessor=default_predecessor, current_rules_sha256=rules_sha256, predecessor_rules_sha256=predecessor_rules_sha256, packet=packet, - ).bind_verified_input( - archive_sha256=commitment.sha256, - archive_byte_count=commitment.byte_count, - archive_media_type=commitment.media_type, - semantic_manifest_sha256=manifest.sha256, - entries=entries, ), - change_gate=change_gate, rules_sha256=rules_sha256, ) diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 121973f9e..509449831 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -1057,9 +1057,15 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): """Exercise the SQL source participant; not full PRE execution or T4 proof.""" from dataclasses import replace from app.core.hashing import canonical_json_hash - from app.modules.tasks.api.transition_audit import TaskPolicyLineage - from app.modules.checkers.api.external_policy import LockedExternalCheckerPolicies from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + from app.adapters.projects import project_locked_policy_context_port + from app.adapters.artifacts import submission_intake_pre_source_port + from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest + from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + from app.modules.artifacts.selected_pre_submit_admission import ( + bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, + ) async with intake.factory.begin() as session: row = await reserve(intake, session) @@ -1070,55 +1076,51 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): operation, lease, 1, provider_generation="pre-source-generation", pre_deadline_at=deadline, lease_expires_at=deadline, ) - from app.adapters.artifacts import submission_intake_pre_source_port + async with intake.factory.begin() as session: + task = await task_submission_context_port(session).lock_submission_context( + TaskSubmissionContextRequest( + task_id=intake.task, assignment_id=intake.assignment, + contributor_id=intake.actor.actor_profile_id, predecessor_submission_id=None, + ) + ) + references = task.locked_project_context + project = await project_locked_policy_context_port(session).lock_locked_policy_context( + ProjectLockedPolicyContextRequest(**{ + name: getattr(references, name) for name in ( + "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", + "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", + "pre_submit_policy_bundle_hash", + ) + }) + ) guarded = await submission_intake_pre_source_port(session).lock_pre_source( source=source, lease_id=lease, generation=1, ) - assert guarded.source == source - policy_body = await session.scalar(text(""" - SELECT a.effective_pre_submit_plan FROM project_guide_proposal_approvals a - JOIN workstream_tasks t ON t.locked_pre_submit_checker_policy_id=a.pre_submit_policy_id - WHERE t.id=:task - """), {"task": intake.task}) - policies = LockedExternalCheckerPolicies.model_validate_json(json.dumps(policy_body)) - base = _source_reservation() - locked = await session.scalar(text(""" - SELECT jsonb_build_object('task',to_jsonb(t),'guide_id',g.id) - FROM workstream_tasks t JOIN project_guides g - ON g.project_id=t.project_id AND g.version=t.locked_guide_version - WHERE t.id=:task - """), {"task": intake.task}) - task = locked["task"] - locked_policy = TaskPolicyLineage.model_validate_json(json.dumps({ - key: task[key] for key in TaskPolicyLineage.model_fields - })) - rules = canonical_json_hash({ - "schema_version": "workstream.task_checker_rules.v1", - "task_policy": locked_policy.model_dump(mode="json"), - "external_checker_policies_sha256": policies.policies_sha256, - }) - lineage = replace( - base.admission_lineage, rules_sha256=rules, effective_plan_sha256=policies.pre_submit.policy_sha256, - guide_id=UUID(locked["guide_id"]), guide_version=task["locked_guide_version"], - source_snapshot_id=UUID(task["locked_guide_source_snapshot_id"]), - source_snapshot_sha256=task["locked_guide_source_snapshot_hash"], - effective_policy_id=UUID(task["locked_effective_project_submission_artifact_policy_id"]), - effective_policy_sha256=task["locked_effective_project_submission_artifact_policy_hash"], - pre_submit_policy_id=UUID(task["locked_pre_submit_checker_policy_id"]), - pre_submit_policy_sha256=task["locked_pre_submit_checker_bundle_hash"], - external_checker_policies_sha256=policies.policies_sha256, - post_submit_policy_body=policies.post_submit.model_dump(mode="json"), - post_submit_policy_sha256=policies.post_submit.policy_sha256, + metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + selected = bind_selected_pre_submit_admission( + task=task, project=project, predecessor=None, predecessor_rules_sha256=None, + predecessor_exists=False, + packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), ) - request = replace( - base, actor_profile_id=UUID(row.actor_profile_id), identity_link_id=UUID(row.identity_link_id), - project_id=UUID(row.project_id), task_id=intake.task, assignment_id=intake.assignment, - idempotency_key=UUID(row.idempotency_key), source=source, - metadata_sha256=row.metadata_sha256, locked_context_sha256=row.locked_context_sha256, - foreground_lease_id=lease, foreground_lease_generation=1, pre_deadline_at=deadline, - policy=policies.pre_submit, admission_lineage=lineage, - default_context=replace(base.default_context, current_rules_sha256=rules), + build_values = dict( + source=guarded, metadata=metadata, task=task, project=project, + attempt_id=new_record_id(), idempotency_key=UUID(row.idempotency_key), + selected=selected, storage_scheme="local", runtime_profile=_source_reservation().runtime_profile, ) + request = build_selected_pre_submit_reservation(**build_values) + if changed is None: + substitutions = ( + {"metadata": metadata.model_copy(update={"summary": "substituted"})}, + {"source": guarded.model_copy(update={"actor_profile_id": new_record_id()})}, + {"source": guarded.model_copy(update={"metadata_sha256": "sha256:" + "f" * 64})}, + {"selected": replace(selected, rules_sha256="sha256:" + "f" * 64)}, + {"selected": replace(selected, default_context=replace( + selected.default_context, packet=SubmissionPacketView("substituted", ""), + ))}, + ) + for replacement in substitutions: + with pytest.raises(ValueError, match="selected PRE .* context differs"): + build_selected_pre_submit_reservation(**(build_values | replacement)) body = request.canonical_body() if changed == "source": body["source"]["provider_generation"] = "substituted" From 63d025b19997bafd2a6619f17d9d05bf3b9ddab3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:23:38 +0100 Subject: [PATCH 058/513] Derive PRE storage lineage from sealed provider profile --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 ++++++++++++++ backend/alembic/versions/0071_source_first_pre.py | 5 ++++- .../artifacts/selected_pre_submit_admission.py | 6 +++++- .../artifacts/test_submission_intake_custody.py | 7 +++++-- backend/tests/conftest.py | 2 +- 5 files changed, 29 insertions(+), 5 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 71cb8878b..83fa89eb9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1364,3 +1364,17 @@ them. The old attempt-request hash helper is still referenced only by that chain and its obsolete tests; it is not a second v2 request identity. No new route, compatibility adapter, placeholder manifest or executable authority was added. The existing reviewed L0 single-session plan and file/reviewer scope still apply. + +The production-builder PostgreSQL run passed 13 cases at exact `61871924d`, +with cleanup confirmed, and 49 source-first/historical contract checks passed. +QA passed that bounded producer/proof scope. Architecture/security found one +remaining provenance gap: separately supplied lineage storage scheme could +contradict the sealed source profile. The builder now derives the scheme from +the same currently admitted `local-v2`/`minio-v1` profiles as T1 and refuses other +profiles; AWS qualification is not inferred. SQL source custody independently +requires the same profile/scheme relationship. A raw INSERT substitution changes +only the scheme and recomputes the request digest, preserving all source facts. +The repaired migration applies with measured fingerprint +`3b71e6b86dea2b6b525fc1fdc3a130b83c070e74e826ef65f4cf6976d1e58d01`. +Exact-head repaired proof and focused re-review are pending. The broader caller, +capability, completed result and one-session runtime replacement remains open. diff --git a/backend/alembic/versions/0071_source_first_pre.py b/backend/alembic/versions/0071_source_first_pre.py index fb592b4bd..c97295780 100644 --- a/backend/alembic/versions/0071_source_first_pre.py +++ b/backend/alembic/versions/0071_source_first_pre.py @@ -55,7 +55,10 @@ def _source_guard(): 'provider_generation',o.provider_generation,'raw_sha256',o.raw_sha256, 'raw_byte_count',o.raw_byte_count,'sealed_upload_fence',o.sealed_upload_fence, 'media_type','application/zip'); - IF request->'source' IS DISTINCT FROM source + IF o.provider_profile NOT IN ('local-v2','minio-v1') + OR request->'admission_lineage'->>'storage_scheme' IS DISTINCT FROM + CASE o.provider_profile WHEN 'local-v2' THEN 'local' WHEN 'minio-v1' THEN 's3' END + OR request->'source' IS DISTINCT FROM source OR request->>'source_sha256' IS DISTINCT FROM public.external_checker_registry_digest( source||jsonb_build_object('schema_version','workstream.sealed_submission_source.v1')) OR r.archive_sha256 IS DISTINCT FROM o.raw_sha256 diff --git a/backend/app/modules/artifacts/selected_pre_submit_admission.py b/backend/app/modules/artifacts/selected_pre_submit_admission.py index c27f50fba..fc07b32dd 100644 --- a/backend/app/modules/artifacts/selected_pre_submit_admission.py +++ b/backend/app/modules/artifacts/selected_pre_submit_admission.py @@ -88,7 +88,6 @@ def build_selected_pre_submit_reservation( attempt_id: UUID, idempotency_key: UUID, selected: SelectedPreSubmitAdmissionContext, - storage_scheme: str, runtime_profile: SelectedPreSubmitRuntimeProfile, ) -> SelectedPreSubmitReservationFacts: """Bind T3's locked source to policy/context without host ZIP inspection. @@ -135,6 +134,11 @@ def build_selected_pre_submit_reservation( or selected.rules_sha256 != expected_rules or selected.default_context.current_rules_sha256 != expected_rules): raise ValueError("selected PRE policy context differs") + storage_scheme = {"local-v2": "local", "minio-v1": "s3"}.get( + source.source.location.provider_profile + ) + if storage_scheme is None: + raise ValueError("selected PRE source profile is unavailable") predecessor = task.predecessor locked_guide_sha256 = canonical_json_hash( { diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 509449831..6d33f9023 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -1052,7 +1052,7 @@ async def test_pre_source_custody_rejects_substitution_or_stale_owner(intake, ch @pytest.mark.parametrize("intake", [True], indirect=True) -@pytest.mark.parametrize("changed", [None, "source", "packet", "policy", "post_policy", "fence", "deadline", "actor", "rules", "predecessor", "predecessor_identity"]) +@pytest.mark.parametrize("changed", [None, "source", "packet", "policy", "post_policy", "fence", "deadline", "actor", "rules", "predecessor", "predecessor_identity", "storage_scheme"]) async def test_selected_pre_sql_requires_exact_live_source(intake, changed): """Exercise the SQL source participant; not full PRE execution or T4 proof.""" from dataclasses import replace @@ -1105,9 +1105,10 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): build_values = dict( source=guarded, metadata=metadata, task=task, project=project, attempt_id=new_record_id(), idempotency_key=UUID(row.idempotency_key), - selected=selected, storage_scheme="local", runtime_profile=_source_reservation().runtime_profile, + selected=selected, runtime_profile=_source_reservation().runtime_profile, ) request = build_selected_pre_submit_reservation(**build_values) + assert request.admission_lineage.storage_scheme == "local" if changed is None: substitutions = ( {"metadata": metadata.model_copy(update={"summary": "substituted"})}, @@ -1138,6 +1139,8 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): body["foreground_lease_generation"] += 1 elif changed == "deadline": body["pre_deadline_at"] = (deadline + timedelta(seconds=1)).isoformat() + elif changed == "storage_scheme": + body["admission_lineage"]["storage_scheme"] = "s3" elif changed == "rules": body["default_context"]["current_rules_sha256"] = "sha256:" + "f" * 64 body["admission_lineage"]["rules_sha256"] = "sha256:" + "f" * 64 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index fee5e0668..cfc951f47 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "d12af28660d6d712d4c97828a39831c34e7c7bf2aec96efe0ba104cee1512b2a" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "3b71e6b86dea2b6b525fc1fdc3a130b83c070e74e826ef65f4cf6976d1e58d01" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", From 2798f370bb37a931d72d1e392810d32a5ec235fd Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:29:04 +0100 Subject: [PATCH 059/513] Correct PRE scheme guard expression and probe unsupported profiles --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 13 +++++++++++++ backend/alembic/versions/0071_source_first_pre.py | 2 +- .../artifacts/test_submission_intake_custody.py | 9 +++++++++ backend/tests/conftest.py | 2 +- 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 83fa89eb9..6c48bb9af 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1378,3 +1378,16 @@ The repaired migration applies with measured fingerprint `3b71e6b86dea2b6b525fc1fdc3a130b83c070e74e826ef65f4cf6976d1e58d01`. Exact-head repaired proof and focused re-review are pending. The broader caller, capability, completed result and one-session runtime replacement remains open. + +The `63d025b19` native run was red: twelve source cases reached a syntax error +in the new PL/pgSQL IF expression; two audit-digest cases passed. Migration +installation alone did not compile the exercised body. A minimal real-PostgreSQL +DO block reproduced the unparenthesized CASE/THEN parsing failure and passed +with the CASE parenthesized. The guard now uses that correction, without changing +its policy. A structurally revalidated `aws-s3-v1` source descriptor is also +submitted to the producer's explicit unsupported-profile refusal in the positive +fixture; this is data-validation proof, never AWS provider qualification. +The corrected fresh migration fingerprint is +`41e1b52d8d9807e8ca3c1d1975b73f1e338a519ab5b73ee40bfe1e086eb2700d`. +Native re-execution and renewed scoped reviews remain required before recording +the scheme fix as proven. diff --git a/backend/alembic/versions/0071_source_first_pre.py b/backend/alembic/versions/0071_source_first_pre.py index c97295780..fc8eefea2 100644 --- a/backend/alembic/versions/0071_source_first_pre.py +++ b/backend/alembic/versions/0071_source_first_pre.py @@ -57,7 +57,7 @@ def _source_guard(): 'media_type','application/zip'); IF o.provider_profile NOT IN ('local-v2','minio-v1') OR request->'admission_lineage'->>'storage_scheme' IS DISTINCT FROM - CASE o.provider_profile WHEN 'local-v2' THEN 'local' WHEN 'minio-v1' THEN 's3' END + (CASE o.provider_profile WHEN 'local-v2' THEN 'local' WHEN 'minio-v1' THEN 's3' END) OR request->'source' IS DISTINCT FROM source OR request->>'source_sha256' IS DISTINCT FROM public.external_checker_registry_digest( source||jsonb_build_object('schema_version','workstream.sealed_submission_source.v1')) diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 6d33f9023..08f1afd63 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -1122,6 +1122,15 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): for replacement in substitutions: with pytest.raises(ValueError, match="selected PRE .* context differs"): build_selected_pre_submit_reservation(**(build_values | replacement)) + from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakePreSourceFacts + unsupported_source = SealedSubmissionSource.model_validate(guarded.source.model_copy(update={ + "location": guarded.source.location.model_copy(update={"provider_profile": "aws-s3-v1"}), + })) + unsupported_facts = SubmissionIntakePreSourceFacts.model_validate( + guarded.model_copy(update={"source": unsupported_source}) + ) + with pytest.raises(ValueError, match="selected PRE source profile is unavailable"): + build_selected_pre_submit_reservation(**(build_values | {"source": unsupported_facts})) body = request.canonical_body() if changed == "source": body["source"]["provider_generation"] = "substituted" diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index cfc951f47..98ff1818e 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "3b71e6b86dea2b6b525fc1fdc3a130b83c070e74e826ef65f4cf6976d1e58d01" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "41e1b52d8d9807e8ca3c1d1975b73f1e338a519ab5b73ee40bfe1e086eb2700d" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", From 47a1b040815ca4802f454e1ef944e846e0814f1a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:32:27 +0100 Subject: [PATCH 060/513] Record reviewed source-first producer and native SQL proof --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6c48bb9af..43dfdd4b5 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1391,3 +1391,14 @@ The corrected fresh migration fingerprint is `41e1b52d8d9807e8ca3c1d1975b73f1e338a519ab5b73ee40bfe1e086eb2700d`. Native re-execution and renewed scoped reviews remain required before recording the scheme fix as proven. + +The corrected exact-head PostgreSQL run passed all 14 cases at `2798f370b`, +with database cleanup confirmed. It exercises the production source-first builder, +committed-source TASK/PROJECT/ART port sequence, metadata/source/rules/packet +substitution controls, supported-profile scheme forgery with recomputed request +hash, unsupported AWS descriptor refusal, real SQL INSERT and fixed-service AUTH +claim/finalization with terminal substitutions. Both architecture/security and +QA/test-delta/CI passed that bounded scope at the same clean head. The earlier +syntax-error run remains failed evidence, not a green migration proof. Nothing +in this result qualifies the unfinished public caller/capability/result/runtime +or accepted T4 path; those remain required by the original single-PR objective. From e8f6eef356ca37d712eed109c33dc27dd2459df3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:42:06 +0100 Subject: [PATCH 061/513] Bind live PRE results to the locked selected project check --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 22 +++++ backend/app/modules/checkers/api/external.py | 18 +++- .../checkers/api/selected_pre_submit.py | 33 ++++++- .../test_selected_pre_submit_coordination.py | 99 +++++++++++++++++++ 4 files changed, 163 insertions(+), 9 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 43dfdd4b5..8e2192391 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1402,3 +1402,25 @@ QA/test-delta/CI passed that bounded scope at the same clean head. The earlier syntax-error run remains failed evidence, not a green migration proof. Nothing in this result qualifies the unfinished public caller/capability/result/runtime or accepted T4 path; those remain required by the original single-PR objective. + +### Live result selection validation during execution replacement + +Tracing the old executor exposed an independent result-binding gap: finalization +and terminal reconstruction compared only the echoed policy digest, while the +result could declare zero required members or substitute a self-consistently +rehashable registry/phase/requirement/image. Live execution now requires exactly +one selected project check, verifies returned members against the reservation's +actual locked binding, and refuses a missing project result after defaults pass. +A blocking default still permits no project execution. Finalization and terminal +reconstruction share this validation; historical v1 read-only decoding is unchanged. +The existing external-result owner supplies registry schema and canonical output +size checks, reused by both request validation and selected-result validation. + +Focused contracts plus source-first/historical tests passed 88 cases. Removing +both selection-validation calls caused all six substitution/omission controls to +fail, while the positive control passed; the production code was restored. +This is structural selection proof only. It neither establishes observed source +custody nor reconstructs the derived project request. The combined response, +single-session runtime, SQL deep completed-result guard, old caller replacement +and T4 remain unfinished. This local change is part of the same coordinated PR, +not a publishable or merge-ready endpoint. Scoped reviewer evidence is pending. diff --git a/backend/app/modules/checkers/api/external.py b/backend/app/modules/checkers/api/external.py index c206e31fe..b4ac39225 100644 --- a/backend/app/modules/checkers/api/external.py +++ b/backend/app/modules/checkers/api/external.py @@ -616,12 +616,20 @@ def validate_request(self, request: ExternalCheckerExecutionRequest) -> None: request.identity.phase, ): raise ExternalCheckerContractError("external checker result request mismatch") - if result.outcome == "completed": - request.registry.output_schema.validate_instance( - result.model_dump(mode="json", exclude={"result_digest"}) + result.validate_registry(request.registry) + + def validate_registry(self, registry: ExternalCheckerRegistryEntry) -> None: + """Check selected registry identity, output schema and canonical byte limit.""" + if (self.registry_entry_id, self.registry_entry_digest, self.phase) != ( + registry.registry_entry_id, registry.entry_digest, registry.phase, + ): + raise ExternalCheckerContractError("external checker result registry mismatch") + if self.outcome == "completed": + registry.output_schema.validate_instance( + self.model_dump(mode="json", exclude={"result_digest"}) ) - if len(_canonical_bytes(result.model_dump(mode="json"))) > ( - request.registry.resources.maximum_output_bytes + if len(_canonical_bytes(self.model_dump(mode="json"))) > ( + registry.resources.maximum_output_bytes ): raise ExternalCheckerContractError("external checker result exceeds registry limit") diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py index 2777a56d4..c284c0eb9 100644 --- a/backend/app/modules/checkers/api/selected_pre_submit.py +++ b/backend/app/modules/checkers/api/selected_pre_submit.py @@ -272,7 +272,7 @@ def __post_init__(self) -> None: @dataclass(frozen=True, slots=True) class SelectedPreSubmitExecutionFacts: - """One default result followed by the executed required external prefix.""" + """Platform defaults and the single selected project PRE result, if run.""" policy_sha256: str workstream_default: WorkstreamDefaultCheckerResult @@ -286,7 +286,7 @@ def __post_init__(self) -> None: not self.policy_sha256.startswith("sha256:") or len(self.policy_sha256) != 71 or type(self.required_external_count) is not int - or self.required_external_count < 0 + or self.required_external_count != 1 or tuple(item.order for item in members) != tuple(range(len(members))) or len({item.requirement_id for item in members}) != len(members) or len(members) > self.required_external_count @@ -303,6 +303,31 @@ def __post_init__(self) -> None: ): raise ValueError("selected PRE execution continued after a blocker") + def validate_reservation(self, reservation: SelectedPreSubmitReservationFacts) -> None: + """Bind returned policy members to locked selection, independently of echoes. + + This is selection validation only. Source observation and the derived + project request must also be verified before accepted custody is issued. + """ + if ( + self.policy_sha256 != reservation.policy_sha256 + or self.workstream_default.behavior_sha256 != reservation.default_behavior_sha256 + or self.required_external_count != len(reservation.policy.entries) + or (self.workstream_default.eligible and len(self.external_members) != 1) + ): + raise ValueError("selected PRE execution selection is invalid") + for member, selected in zip(self.external_members, reservation.policy.entries, strict=False): + registry = selected.registry + if ( + member.requirement_id != selected.requirement_id + or member.registry_entry_id != registry.registry_entry_id + or member.registry_entry_digest != registry.entry_digest + or member.result.phase != "pre_submit" + or member.isolation.platform_manifest_digest != registry.image_digest + ): + raise ValueError("selected PRE execution selection is invalid") + member.result.validate_registry(registry) + def canonical_body(self) -> dict[str, object]: """Return the complete bounded result body retained by the durable owner.""" return { @@ -628,8 +653,7 @@ def __post_init__(self) -> None: if self.execution is not None: if type(self.execution) is not SelectedPreSubmitExecutionFacts: raise ValueError("selected PRE finalize execution is invalid") - if self.execution.policy_sha256 != self.lease.reservation.policy_sha256: - raise ValueError("selected PRE finalize policy is invalid") + self.execution.validate_reservation(self.lease.reservation) else: SelectedPreSubmitInfrastructureUnavailable(self.infrastructure_failure_code or "") @@ -778,6 +802,7 @@ def __post_init__(self) -> None: or self.execution.policy_sha256 != self.lease.reservation.policy_sha256 ): raise ValueError("selected PRE completed outcome is invalid") + self.execution.validate_reservation(self.lease.reservation) elif (self.outcome != "infrastructure_failed" or self.execution is not None or self.infrastructure_failure_code not in { "capacity_exceeded", diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index ddb29276d..e280ec0af 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -821,3 +821,102 @@ def test_source_first_profile_rejects_archive_time_beyond_aggregate() -> None: replace(request, runtime_profile=request.runtime_profile.model_copy(update={ "archive_limits": SubmissionArchiveLimits(maximum_inspection_seconds=121), })) + + +def _source_completed_execution(reservation): + """Build structural result evidence; this fixture does not attest a runtime.""" + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts + from app.modules.checkers.api.external import make_external_checker_execution_result + + execution = SelectedPreSubmitExecutionFacts.from_canonical_body( + _retained_v1("selected_pre_v1_completed")["terminal"]["execution"] + ) + selected = reservation.policy.entries[0] + member = execution.external_members[0] + result = make_external_checker_execution_result( + **(member.result.model_dump(exclude={"result_digest"}) | { + "registry_entry_id": selected.registry.registry_entry_id, + "registry_entry_digest": selected.registry.entry_digest, + }) + ) + return replace( + execution, policy_sha256=reservation.policy_sha256, + external_members=(replace( + member, requirement_id=selected.requirement_id, + registry_entry_id=selected.registry.registry_entry_id, + registry_entry_digest=selected.registry.entry_digest, result=result, + isolation=replace(member.isolation, + platform_manifest_digest=selected.registry.image_digest), + ),), + ) + + +@pytest.mark.parametrize("changed", [ + None, "requirement", "registry_id", "registry_digest", "phase", "image", "missing", +]) +def test_source_first_finalization_binds_actual_selected_member(changed): + from app.modules.checkers.api.external import make_external_checker_execution_result + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitTerminalFacts + + reservation = _source_reservation() + execution = _source_completed_execution(reservation) + member = execution.external_members[0] + if changed in {"registry_id", "registry_digest", "phase"}: + field = {"registry_id": "registry_entry_id", "registry_digest": "registry_entry_digest", + "phase": "phase"}[changed] + value = {"registry_id": new_record_id(), "registry_digest": "sha256:" + "f" * 64, + "phase": "post_submit"}[changed] + # Rehash the forged result and agree with its echoed member identity. + # Only the frozen reservation distinguishes it from valid evidence. + result = make_external_checker_execution_result( + **(member.result.model_dump(exclude={"result_digest"}) | {field: value}) + ) + member = replace(member, result=result, **({field: value} if changed != "phase" else {})) + elif changed == "requirement": + member = replace(member, requirement_id="another.requirement") + elif changed == "image": + member = replace(member, isolation=replace( + member.isolation, platform_manifest_digest="sha256:" + "f" * 64, + )) + execution = replace(execution, external_members=(member,)) + if changed == "missing": + execution = replace(execution, external_members=(), eligible=False) + now = datetime.now(UTC) + lease = SelectedPreSubmitLeaseFacts( + reservation=reservation, lease_id=new_record_id(), lease_generation=1, + lease_expires_at=reservation.pre_deadline_at, + ) + def finalize(): + return SelectedPreSubmitFinalizeFacts(lease, execution, None) + def terminal(): + return SelectedPreSubmitTerminalFacts(lease, "completed", execution, None, now, now, now) + if changed is None: + assert finalize().execution == execution + value = terminal() + assert SelectedPreSubmitTerminalFacts.from_canonical_body(value.canonical_body()) == value + else: + for construct in (finalize, terminal): + with pytest.raises(ValueError, match="execution selection"): + construct() + + +def test_source_first_execution_cannot_claim_zero_required_project_checks(): + execution = _source_completed_execution(_source_reservation()) + with pytest.raises(ValueError, match="execution facts"): + replace(execution, required_external_count=0, external_members=(), eligible=True) + + +def test_source_first_default_rejection_does_not_require_project_result(): + from app.modules.checkers.default_checker import evaluate_rejected_archive + + reservation = _source_reservation() + execution = replace( + _source_completed_execution(reservation), + workstream_default=evaluate_rejected_archive( + "submission_archive_malformed", packet=reservation.default_context.packet, + ), external_members=(), eligible=False, + ) + lease = SelectedPreSubmitLeaseFacts( + reservation, new_record_id(), 1, reservation.pre_deadline_at, + ) + assert SelectedPreSubmitFinalizeFacts(lease, execution, None).execution == execution From 1e151a388aacaafb868df65ab104e4128062cf36 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:44:11 +0100 Subject: [PATCH 062/513] Revalidate PRE result digests before terminal finalization --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++++ backend/app/modules/checkers/api/external.py | 10 ++++++---- .../test_selected_pre_submit_coordination.py | 20 +++++++++++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8e2192391..b0792f7f8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1424,3 +1424,11 @@ custody nor reconstructs the derived project request. The combined response, single-session runtime, SQL deep completed-result guard, old caller replacement and T4 remain unfinished. This local change is part of the same coordinated PR, not a publishable or merge-ready endpoint. Scoped reviewer evidence is pending. + +Architecture/security review found that direct shared-helper calls could accept +an in-memory Pydantic copy with a forged external result digest, even though +later JSON decoding would reject it. The helper now revalidates both result and +registry before selection/schema/size checks. New controls exercise rejection +before both finalization and terminal construction; the expanded focused suite +passes 90 cases. The earlier QA pass did not cover this reviewer-reproduced +integrity path. Renewed review of the repaired candidate is required. diff --git a/backend/app/modules/checkers/api/external.py b/backend/app/modules/checkers/api/external.py index b4ac39225..ff4afd0b9 100644 --- a/backend/app/modules/checkers/api/external.py +++ b/backend/app/modules/checkers/api/external.py @@ -620,15 +620,17 @@ def validate_request(self, request: ExternalCheckerExecutionRequest) -> None: def validate_registry(self, registry: ExternalCheckerRegistryEntry) -> None: """Check selected registry identity, output schema and canonical byte limit.""" - if (self.registry_entry_id, self.registry_entry_digest, self.phase) != ( + result = ExternalCheckerExecutionResult.model_validate(self) + registry = ExternalCheckerRegistryEntry.model_validate(registry) + if (result.registry_entry_id, result.registry_entry_digest, result.phase) != ( registry.registry_entry_id, registry.entry_digest, registry.phase, ): raise ExternalCheckerContractError("external checker result registry mismatch") - if self.outcome == "completed": + if result.outcome == "completed": registry.output_schema.validate_instance( - self.model_dump(mode="json", exclude={"result_digest"}) + result.model_dump(mode="json", exclude={"result_digest"}) ) - if len(_canonical_bytes(self.model_dump(mode="json"))) > ( + if len(_canonical_bytes(result.model_dump(mode="json"))) > ( registry.resources.maximum_output_bytes ): raise ExternalCheckerContractError("external checker result exceeds registry limit") diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index e280ec0af..376b6520e 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -920,3 +920,23 @@ def test_source_first_default_rejection_does_not_require_project_result(): reservation, new_record_id(), 1, reservation.pre_deadline_at, ) assert SelectedPreSubmitFinalizeFacts(lease, execution, None).execution == execution + + +@pytest.mark.parametrize("boundary", ["finalization", "terminal"]) +def test_source_first_result_digest_revalidated_before_terminal_write(boundary): + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitTerminalFacts + + reservation = _source_reservation() + execution = _source_completed_execution(reservation) + member = execution.external_members[0] + forged = member.result.model_copy(update={"result_digest": "sha256:" + "f" * 64}) + execution = replace(execution, external_members=(replace(member, result=forged),)) + lease = SelectedPreSubmitLeaseFacts( + reservation, new_record_id(), 1, reservation.pre_deadline_at, + ) + now = datetime.now(UTC) + with pytest.raises(ValueError, match="result digest mismatch"): + if boundary == "finalization": + SelectedPreSubmitFinalizeFacts(lease, execution, None) + else: + SelectedPreSubmitTerminalFacts(lease, "completed", execution, None, now, now, now) From 3397cca63a070603f3931eef7bb63687d4b756e9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:45:37 +0100 Subject: [PATCH 063/513] Record reviewed PRE result selection and digest evidence --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b0792f7f8..ee5586949 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1432,3 +1432,12 @@ registry before selection/schema/size checks. New controls exercise rejection before both finalization and terminal construction; the expanded focused suite passes 90 cases. The earlier QA pass did not cover this reviewer-reproduced integrity path. Renewed review of the repaired candidate is required. + +Both renewed scoped reviews passed the clean repaired candidate `1e151a388`. +Architecture/security replayed the original forged-digest probe and observed +rejection at finalization and terminal construction. QA independently substituted +the exact pre-repair helper in memory: both new boundary controls failed as +expected, then the helper was restored. Ownership/lane checks passed 229 cases; +the ownership partition is unchanged, and record/link checks pass. These reviews +close the selection/digest findings only, not the remaining combined-execution +or accepted-handoff requirements. From 52eb7f122b9108d4af5b9dabfc2c3830f1052eed Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 12:58:33 +0100 Subject: [PATCH 064/513] Replace PRE client execution with source-bound combined calls --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 42 +++++ backend/app/adapters/checkers/__init__.py | 68 ++------ .../app/adapters/checkers/external_service.py | 78 +++++++++ .../app/adapters/checkers/model_execution.py | 4 + .../interfaces/external_checker_execution.py | 21 +++ .../artifacts/api/submission_archive.py | 29 ++++ backend/app/modules/checkers/api/external.py | 26 ++- .../checkers/api/selected_pre_submit.py | 144 ++++++++++++++-- .../checkers/selected_pre_submit_execution.py | 143 +++------------ backend/tests/checkers/external/support.py | 6 +- .../tests/checkers/external/test_contracts.py | 27 ++- .../tests/checkers/external/test_runtime.py | 163 +++++++++++++++++- .../test_selected_pre_submit_coordination.py | 127 ++++++++++++-- external_checkers/fixtures/request.json | 2 +- external_checkers/fixtures/result.json | 2 +- .../workstream-checker-sdk/src/lib.rs | 61 ++++++- 16 files changed, 718 insertions(+), 225 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index ee5586949..642f70dd8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1441,3 +1441,45 @@ expected, then the helper was restored. Ownership/lane checks passed 229 cases; the ownership partition is unchanged, and record/link checks pass. These reviews close the selection/digest findings only, not the remaining combined-execution or accepted-handoff requirements. + +### Source-bound combined-result client and nested request derivation + +The CHECKERS PRE processor now invokes one typed `execute_pre` operation instead +of exporting an ART tree and dispatching a second project invocation. Its existing +factory and lazy configured adapter use the same external-service capability. +The Unix client streams an ART grant's exact source in at most 64 KiB frames, +checks count/SHA before EOF, bounds request/result framing and elapsed time by the +lease, and closes source/transport on cancellation. The grant is a separate +process-local port; no token or host path enters immutable request identity. + +Live nested Python/Rust PRE identity now binds operation, sealed-source digest, +run/request and execution lease/fence, with no prepared-generation field. Shared +wire fixtures were regenerated for this deliberate contract replacement. Live +execution evidence is v2 and retains observed source, fence, canonical manifest +and default-input digest. CHECKERS uses ART's existing canonical manifest parser +with the locked invocation limits and reconstructs default input plus the nested +project request from the reservation, then validates the returned project result +against that reconstructed request. Unsafe-archive default rejection may omit +manifest/project evidence; a passing default cannot. Historical v1 decoding and +its retained fixtures remain separate read-only data. + +The focused contract/transport selection passed 120 cases, including source, +lease, manifest and mutually rehashed request/result substitutions; source-short, +source-long and wrong-hash transport; trailing frames; expired lease before source +open; one invocation only; and cancellation closing source and socket. The Rust +SDK passed eight tests including rehashed source/fence substitutions. Ownership +and lane checks passed 229 cases. The entire runtime test module was also run: +29 passed and one obsolete prepared-ZIP grant test failed because its removed +prepared-generation identity is correctly refused. That failure is retained, +not skipped or adapted into a second PRE path. + +This is an intermediate local implementation in the coordinated single PR, not +a completed bounded-change or merge milestone. The actual ART source-grant issuer +and its materializer AUTH replacement, native service/guest `execute_pre` handler, +provider invocation/profile/conformance/cleanup envelope, old ART caller/tree-grant +removal, SQL deep-result guard and T4 remain required. The old ART materializer and +Rust PRE tree-grant service still refer to the superseded preparation identity; +they must be removed during the connected replacement, not made into compatibility +adapters. The current public path remains unfinished and these local commits must +not be pushed as a publishable cutover. No source grant authority, native guest +execution, provider qualification or accepted handoff is proved by a socket fake. diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py index 792c480c0..3a80f2de6 100644 --- a/backend/app/adapters/checkers/__init__.py +++ b/backend/app/adapters/checkers/__init__.py @@ -32,18 +32,15 @@ from app.modules.checkers.api.history import CheckerHistoryReadPort from app.modules.checkers.api.revision_feedback import RevisionFeedbackPort from app.modules.checkers.api.execution import EvaluationCoordinationPort -from typing import Any, Protocol from pathlib import Path from app.modules.checkers.api.external import ( ExternalCheckerExecutionRequest, - PreSubmitExternalCheckerIdentity, - PreSubmitExternalCheckerMaterial, ) from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitInfrastructureUnavailable, + SelectedPreSubmitLeaseFacts, ) @@ -181,6 +178,10 @@ def _resolve(self) -> ExternalCheckerExecutionAdapter: EXTERNAL_CHECKER_PROVIDER_KEY ) + async def execute_pre(self, lease, grant): + """Resolve the same provider for the source-bound single PRE session.""" + return await self._resolve().execute_pre(lease, grant) + async def locate_forge_change(self, request, grant): """Resolve the same provider for the isolated locator operation.""" return await self._resolve().locate_forge_change(request, grant) @@ -272,64 +273,15 @@ def selected_pre_submit_coordinator(session): ) -class _ExecutionRequest(Protocol): - project_id: Any - task_id: Any - assignment_id: Any - commitment: Any - inspection: Any - manifest: Any - change_gate: Any - packet: Any - prepared_generation_id: Any - storage_scheme: str - - class SelectedPreSubmitCheckerExecutionAdapter: - """Build the selected default-plus-external PRE processor from exact ART facts.""" + """Compose the source-bound PRE processor through the existing adapter factory.""" - def __init__(self, *, external_execution) -> None: + def __init__(self, *, external_execution: ExternalCheckerExecutionAdapter) -> None: self._external_execution = external_execution - def build(self, request: _ExecutionRequest) -> SelectedPreSubmitProcessor: - """Reject any incomplete pre-admission identity before projecting bytes.""" - policy = getattr(request, "external_policy", None) - default_input = getattr(request, "default_checker_input", None) - attempt_id = getattr(request, "attempt_id", None) - attempt_request_digest = getattr(request, "attempt_request_digest", None) - if ( - policy is None - or default_input is None - or attempt_id is None - or attempt_request_digest is None - ): - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - identity = PreSubmitExternalCheckerIdentity( - project_id=request.project_id, - task_id=request.task_id, - assignment_id=request.assignment_id, - prepared_generation_id=request.prepared_generation_id, - attempt_id=attempt_id, - attempt_request_digest=attempt_request_digest, - effective_plan_sha256=policy.policy_sha256, - ) - material = PreSubmitExternalCheckerMaterial( - role="submission_archive", - prepared_generation_id=request.prepared_generation_id, - attempt_id=attempt_id, - attempt_request_digest=attempt_request_digest, - archive_sha256=request.commitment.sha256, - archive_byte_count=request.commitment.byte_count, - semantic_manifest_sha256=request.manifest.sha256, - media_type="application/zip", - ) - return SelectedPreSubmitProcessor( - policy=policy, - default_input=default_input, - identity=identity, - material=material, - execution=self._external_execution, - ) + def build(self, lease: SelectedPreSubmitLeaseFacts) -> SelectedPreSubmitProcessor: + """Bind the single invocation to the committed CHECKERS lease.""" + return SelectedPreSubmitProcessor(lease=lease, execution=self._external_execution) def checker_history_repository(session) -> CheckerHistoryReadPort: diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py index 07789f631..db43489a1 100644 --- a/backend/app/adapters/checkers/external_service.py +++ b/backend/app/adapters/checkers/external_service.py @@ -4,13 +4,18 @@ import asyncio import json +import hashlib +from datetime import datetime, timezone from pathlib import Path import struct from pydantic import ValidationError +from app.core.cancellation import await_cancellation_resistant + from app.interfaces.external_checker_execution import ( ExternalCheckerExecutionResponse, + ExternalPreSubmitSourceGrant, ExternalCheckerForgeLocatorResponse, ExternalCheckerIsolationReceipt, ExternalCheckerMaterialGrant, @@ -30,6 +35,11 @@ ExternalCheckerExecutionResult, ) +from app.modules.checkers.api.selected_pre_submit import ( + SelectedPreSubmitLeaseFacts, SelectedPreSubmitExecutionFacts, + SelectedPreSubmitInfrastructureUnavailable, +) + from app.modules.checkers.api.forge_locator import ( FORGE_LOCATOR_STAGE_KEY, ExternalCheckerForgeLocator, @@ -67,6 +77,74 @@ def identity(self) -> ExternalServiceAdapterIdentity: """Return the exact explicitly registered provider identity.""" return self._identity + async def execute_pre( + self, lease: SelectedPreSubmitLeaseFacts, grant: ExternalPreSubmitSourceGrant, + ) -> SelectedPreSubmitExecutionFacts: + """Stream authorized source bytes into one PRE call without a host spool.""" + try: + if type(lease) is not SelectedPreSubmitLeaseFacts: + raise ValueError("PRE lease is invalid") + reservation = lease.reservation + payload = json.dumps({ + "protocol_version": _PROTOCOL, "operation": "execute_pre", + "reservation": reservation.canonical_body(), + "request_digest": reservation.request_digest, + "lease_id": str(lease.lease_id), "lease_generation": lease.lease_generation, + "lease_expires_at": lease.lease_expires_at.isoformat(), + }, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8") + if len(payload) > 2 * 1024 * 1024: + raise ValueError("PRE request is too large") + remaining = (lease.lease_expires_at - datetime.now(timezone.utc)).total_seconds() + timeout = min(remaining, reservation.execution_budget_ms / 1000, self._timeout_seconds) + if timeout <= 0: + raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded") + async with asyncio.timeout(timeout): + reader, writer = await asyncio.open_unix_connection(self._socket_path) + try: + writer.write(struct.pack(">I", len(payload)) + payload) + await writer.drain() + digest, count = hashlib.sha256(), 0 + stream = grant.open_source(lease=lease) + try: + async for chunk in stream: + if type(chunk) is not bytes: + raise ValueError("PRE source chunk is invalid") + count += len(chunk) + if count > reservation.source.raw_byte_count: + raise ValueError("PRE source identity differs") + digest.update(chunk) + for offset in range(0, len(chunk), 64 * 1024): + part = chunk[offset:offset + 64 * 1024] + writer.write(struct.pack(">I", len(part)) + part) + await writer.drain() + finally: + await await_cancellation_resistant(stream.aclose()) + if (count != reservation.source.raw_byte_count + or "sha256:" + digest.hexdigest() != reservation.source.raw_sha256): + raise ValueError("PRE source identity differs") + writer.write(struct.pack(">I", 0)) + await writer.drain() + size = struct.unpack(">I", await reader.readexactly(4))[0] + if size == 0 or size > 64 * 1024 * 1024: + raise ValueError("PRE response is too large") + raw = await reader.readexactly(size) + if await reader.read(1): + raise ValueError("PRE response contains trailing data") + finally: + writer.close() + await await_cancellation_resistant(writer.wait_closed()) + result = SelectedPreSubmitExecutionFacts.from_canonical_body(json.loads(raw)) + result.validate_lease(lease) + return result + except ExternalServiceProtocolError: + raise + except TimeoutError as exc: + raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded") from exc + except (OSError, asyncio.IncompleteReadError) as exc: + raise ExternalServiceUnavailableError(self._identity) from exc + except (TypeError, ValueError, KeyError, UnicodeError) as exc: + raise ExternalServiceProtocolError(self._identity) from exc + async def execute( self, request: ExternalCheckerExecutionRequest, diff --git a/backend/app/adapters/checkers/model_execution.py b/backend/app/adapters/checkers/model_execution.py index 733b10bf1..9aa9861d2 100644 --- a/backend/app/adapters/checkers/model_execution.py +++ b/backend/app/adapters/checkers/model_execution.py @@ -44,6 +44,10 @@ async def health(self): """Use the existing external execution health contract.""" return await self._execution.health() + async def execute_pre(self, lease, grant): + """PRE receives no model authority or paid slot from this POST wrapper.""" + return await self._execution.execute_pre(lease, grant) + async def locate_forge_change(self, request, grant): """Locator gets no model grant, paid slot or trial callback.""" return await self._execution.locate_forge_change(request, grant) diff --git a/backend/app/interfaces/external_checker_execution.py b/backend/app/interfaces/external_checker_execution.py index 2cf35bc1c..e9aeb0a71 100644 --- a/backend/app/interfaces/external_checker_execution.py +++ b/backend/app/interfaces/external_checker_execution.py @@ -3,10 +3,14 @@ from __future__ import annotations from dataclasses import dataclass, field +from collections.abc import AsyncGenerator import re from typing import Protocol from app.interfaces.external_services import ExternalServiceAdapter +from app.modules.checkers.api.selected_pre_submit import ( + SelectedPreSubmitLeaseFacts, SelectedPreSubmitExecutionFacts, +) from app.modules.checkers.api.forge_locator import ExternalCheckerForgeLocator from app.modules.checkers.api.external import ( ExternalCheckerExecutionRequest, @@ -143,9 +147,25 @@ def __post_init__(self) -> None: raise ValueError("external checker service health is invalid") +class ExternalPreSubmitSourceGrant(Protocol): + """ART-issued expiring read authority, separate from durable request identity. + + The issuer must consume the exact committed lease and authorize the immutable + source generation before returning this process-local capability. + """ + + def open_source(self, *, lease: SelectedPreSubmitLeaseFacts) -> AsyncGenerator[bytes, None]: + """Read only the bound source, outside a database transaction.""" + + class ExternalCheckerExecutionAdapter(ExternalServiceAdapter, Protocol): """Execute one normalized request through the trusted checker service.""" + async def execute_pre( + self, lease: SelectedPreSubmitLeaseFacts, grant: ExternalPreSubmitSourceGrant, + ) -> SelectedPreSubmitExecutionFacts: + """Run source verification, defaults and selected project in one session.""" + async def locate_forge_change( self, request: ExternalCheckerExecutionRequest, @@ -169,6 +189,7 @@ async def health(self) -> ExternalCheckerServiceHealth: __all__ = ( "ExternalCheckerExecutionAdapter", + "ExternalPreSubmitSourceGrant", "ExternalCheckerExecutionResponse", "ExternalCheckerIsolationReceipt", "ExternalCheckerMaterialGrant", diff --git a/backend/app/modules/artifacts/api/submission_archive.py b/backend/app/modules/artifacts/api/submission_archive.py index 2fb64f95c..1f0698be7 100644 --- a/backend/app/modules/artifacts/api/submission_archive.py +++ b/backend/app/modules/artifacts/api/submission_archive.py @@ -96,3 +96,32 @@ def __post_init__(self) -> None: or self.maximum_inspection_seconds <= 0 ): raise ValueError("submission archive deadline is invalid") + + +def validate_submission_manifest( + body: object, *, sha256: str, limits: SubmissionArchiveLimits, +) -> SubmissionArchiveInspectionResult: + """Validate reported canonical metadata without claiming observation of bytes. + + Reuse ART's manifest semantics and the invocation's stricter resource limits. + Source integrity still requires a trusted loader receipt. + """ + from app.modules.artifacts.submission_manifest import SubmissionManifest + from app.modules.artifacts.submission_archive import normalize_submission_archive_path + + manifest = SubmissionManifest.from_dict(body, sha256=sha256) + if (manifest.entry_count > limits.maximum_entries + or manifest.total_expanded_bytes > limits.maximum_expanded_bytes): + raise ValueError("submission manifest exceeds execution limits") + for entry in manifest.entries: + if entry.byte_count > limits.maximum_entry_bytes: + raise ValueError("submission manifest exceeds execution limits") + normalize_submission_archive_path( + entry.normalized_path, maximum_path_bytes=limits.maximum_path_bytes, + maximum_path_depth=limits.maximum_path_depth, + ) + return SubmissionArchiveInspectionResult( + entries=manifest.entries, entry_count=manifest.entry_count, + file_count=manifest.file_count, directory_count=manifest.directory_count, + total_expanded_bytes=manifest.total_expanded_bytes, + ) diff --git a/backend/app/modules/checkers/api/external.py b/backend/app/modules/checkers/api/external.py index ff4afd0b9..8cf4b78b7 100644 --- a/backend/app/modules/checkers/api/external.py +++ b/backend/app/modules/checkers/api/external.py @@ -362,11 +362,14 @@ def external_checker_registration_request_digest( class PreSubmitExternalCheckerMaterial(ExternalCheckerValue): - """Verified prepared bytes that exist before a Submission or ART binding.""" + """Guest-verified source and tree bound to one PRE execution fence.""" phase: Literal["pre_submit"] = "pre_submit" role: Identifier - prepared_generation_id: UUID = Field(strict=True) + operation_id: UUID = Field(strict=True) + source_sha256: Sha256 + lease_id: UUID = Field(strict=True) + lease_generation: Annotated[StrictInt, Field(ge=1)] attempt_id: UUID = Field(strict=True) attempt_request_digest: Sha256 archive_sha256: Sha256 @@ -407,13 +410,16 @@ class PostSubmitExternalCheckerMaterial(ExternalCheckerValue): class PreSubmitExternalCheckerIdentity(ExternalCheckerValue): - """Existing pre-submit preparation and attempt identity; no Submission exists.""" + """Sealed source operation and committed PRE lease; no Submission exists.""" phase: Literal["pre_submit"] = "pre_submit" project_id: UUID = Field(strict=True) task_id: UUID = Field(strict=True) assignment_id: UUID = Field(strict=True) - prepared_generation_id: UUID = Field(strict=True) + operation_id: UUID = Field(strict=True) + source_sha256: Sha256 + lease_id: UUID = Field(strict=True) + lease_generation: Annotated[StrictInt, Field(ge=1)] attempt_id: UUID = Field(strict=True) attempt_request_digest: Sha256 effective_plan_sha256: Sha256 @@ -469,16 +475,22 @@ def validate_request(self) -> Self: if self.identity.phase == "pre_submit": for material in self.materials: if not isinstance(material, PreSubmitExternalCheckerMaterial) or ( - material.prepared_generation_id, + material.operation_id, + material.source_sha256, + material.lease_id, + material.lease_generation, material.attempt_id, material.attempt_request_digest, ) != ( - self.identity.prepared_generation_id, + self.identity.operation_id, + self.identity.source_sha256, + self.identity.lease_id, + self.identity.lease_generation, self.identity.attempt_id, self.identity.attempt_request_digest, ): raise ExternalCheckerContractError( - "external checker prepared material identity mismatch" + "external checker source material identity mismatch" ) if self.configuration_sha256 != external_checker_json_hash(self.configuration): raise ExternalCheckerContractError("external checker configuration digest mismatch") diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py index c284c0eb9..4b27a2097 100644 --- a/backend/app/modules/checkers/api/selected_pre_submit.py +++ b/backend/app/modules/checkers/api/selected_pre_submit.py @@ -274,6 +274,13 @@ def __post_init__(self) -> None: class SelectedPreSubmitExecutionFacts: """Platform defaults and the single selected project PRE result, if run.""" + request_digest: str + lease_id: UUID + lease_generation: int + observed_source: SealedSubmissionSource + manifest_body: dict[str, object] | None + manifest_sha256: str | None + default_input_sha256: str | None policy_sha256: str workstream_default: WorkstreamDefaultCheckerResult required_external_count: int @@ -282,6 +289,21 @@ class SelectedPreSubmitExecutionFacts: def __post_init__(self) -> None: members = self.external_members + if ( + type(self.lease_id) is not UUID or type(self.lease_generation) is not int + or self.lease_generation < 1 or type(self.eligible) is not bool + or type(self.external_members) is not tuple + or type(self.observed_source) is not SealedSubmissionSource + or (self.manifest_body is None) != (self.manifest_sha256 is None) + or (self.manifest_body is None) != (self.default_input_sha256 is None) + ): + raise ValueError("selected PRE observed evidence is invalid") + SealedSubmissionSource.model_validate(self.observed_source) + for digest in (self.request_digest, self.manifest_sha256, self.default_input_sha256): + if digest is not None and (type(digest) is not str or len(digest) != 71 + or not digest.startswith("sha256:") + or any(character not in "0123456789abcdef" for character in digest[7:])): + raise ValueError("selected PRE observed evidence is invalid") if ( not self.policy_sha256.startswith("sha256:") or len(self.policy_sha256) != 71 @@ -303,12 +325,30 @@ def __post_init__(self) -> None: ): raise ValueError("selected PRE execution continued after a blocker") - def validate_reservation(self, reservation: SelectedPreSubmitReservationFacts) -> None: - """Bind returned policy members to locked selection, independently of echoes. - - This is selection validation only. Source observation and the derived - project request must also be verified before accepted custody is issued. - """ + def validate_lease(self, lease: SelectedPreSubmitLeaseFacts) -> None: + """Reconstruct expected derived input instead of trusting echoed digests.""" + from app.modules.checkers.api.default_checker import workstream_default_input_sha256 + + reservation = lease.reservation + if (self.request_digest != reservation.request_digest + or self.lease_id != lease.lease_id or self.lease_generation != lease.lease_generation + or self.observed_source != reservation.source): + raise ValueError("selected PRE source or execution fence differs") + WorkstreamDefaultCheckerResult.model_validate(self.workstream_default) + archive_safe = self.workstream_default.checks[0] + if self.manifest_body is None: + if (archive_safe.status != "failed" or self.external_members + or any(check.status != "not_run" for check in self.workstream_default.checks[1:])): + raise ValueError("selected PRE lacks inspected manifest evidence") + request = None + else: + if archive_safe.status != "passed" or self.workstream_default.checks[1].status != "passed": + raise ValueError("selected PRE inspected identity result is invalid") + value, request = derive_selected_pre_submit_input( + lease, manifest_body=self.manifest_body, manifest_sha256=self.manifest_sha256, + ) + if workstream_default_input_sha256(value) != self.default_input_sha256: + raise ValueError("selected PRE derived default input differs") if ( self.policy_sha256 != reservation.policy_sha256 or self.workstream_default.behavior_sha256 != reservation.default_behavior_sha256 @@ -327,11 +367,19 @@ def validate_reservation(self, reservation: SelectedPreSubmitReservationFacts) - ): raise ValueError("selected PRE execution selection is invalid") member.result.validate_registry(registry) + if request is None or member.request_digest != request.request_digest: + raise ValueError("selected PRE derived project request differs") + member.result.validate_request(request) def canonical_body(self) -> dict[str, object]: """Return the complete bounded result body retained by the durable owner.""" return { - "schema_version": "workstream.selected_pre_submit_execution.v1", + "schema_version": "workstream.selected_pre_submit_execution.v2", + "request_digest": self.request_digest, + "lease_id": str(self.lease_id), "lease_generation": self.lease_generation, + "observed_source": self.observed_source.model_dump(mode="json"), + "manifest_body": self.manifest_body, "manifest_sha256": self.manifest_sha256, + "default_input_sha256": self.default_input_sha256, "policy_sha256": self.policy_sha256, "workstream_default": self.workstream_default.model_dump(mode="json"), "required_external_count": self.required_external_count, @@ -357,20 +405,26 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitExecutionFacts: type(body) is not dict or set(body) != { - "schema_version", + "schema_version", "request_digest", "lease_id", "lease_generation", + "observed_source", "manifest_body", "manifest_sha256", "default_input_sha256", "policy_sha256", "workstream_default", "required_external_count", "external_members", "eligible", } - or body["schema_version"] != "workstream.selected_pre_submit_execution.v1" + or body["schema_version"] != "workstream.selected_pre_submit_execution.v2" ): raise ValueError("selected PRE execution facts are invalid") members = body["external_members"] if type(members) is not list: raise ValueError("selected PRE execution facts are invalid") - return cls( + value = cls( + request_digest=body["request_digest"], lease_id=UUID(body["lease_id"]), + lease_generation=body["lease_generation"], + observed_source=SealedSubmissionSource.model_validate_json(json.dumps(body["observed_source"])), + manifest_body=body["manifest_body"], manifest_sha256=body["manifest_sha256"], + default_input_sha256=body["default_input_sha256"], policy_sha256=body["policy_sha256"], workstream_default=WorkstreamDefaultCheckerResult.model_validate( body["workstream_default"] @@ -393,6 +447,9 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitExecutionFacts: ), eligible=body["eligible"], ) + if value.canonical_body() != body: + raise ValueError("selected PRE execution body is not canonical") + return value @property def result_digest(self) -> str: @@ -585,6 +642,69 @@ def __post_init__(self) -> None: raise ValueError("selected PRE lease facts are invalid") +def derive_selected_pre_submit_input( + lease: SelectedPreSubmitLeaseFacts, *, manifest_body: object, manifest_sha256: str, +): + """Derive default input and the project request from locked facts and metadata. + + Called independently by the trusted guest and backend verifier. This pure + derivation grants no source access and does not attest file observation. + """ + from app.modules.artifacts.api.submission_archive import validate_submission_manifest + from app.modules.checkers.api.material import SubmissionMaterialEntry + from app.modules.checkers.api.external import ( + PreSubmitExternalCheckerIdentity, PreSubmitExternalCheckerMaterial, + external_checker_json_hash, make_external_checker_execution_request, + ) + + reservation = lease.reservation + source = reservation.source + inspection = validate_submission_manifest( + manifest_body, sha256=manifest_sha256, limits=reservation.runtime_profile.archive_limits, + ) + value = reservation.default_context.bind_verified_input( + archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count, + archive_media_type=source.media_type, semantic_manifest_sha256=manifest_sha256, + entries=tuple(SubmissionMaterialEntry( + entry.normalized_path, entry.entry_type.value, entry.byte_count, + entry.sha256, entry.executable, + ) for entry in inspection.entries), + ) + custody = dict( + operation_id=source.location.operation_id, source_sha256=source.source_sha256(), + attempt_id=reservation.attempt_id, attempt_request_digest=reservation.request_digest, + lease_id=lease.lease_id, lease_generation=lease.lease_generation, + ) + identity = PreSubmitExternalCheckerIdentity( + project_id=reservation.project_id, task_id=reservation.task_id, + assignment_id=reservation.assignment_id, + effective_plan_sha256=reservation.admission_lineage.effective_plan_sha256, **custody, + ) + material = PreSubmitExternalCheckerMaterial( + role="submission_archive", archive_sha256=source.raw_sha256, + archive_byte_count=source.raw_byte_count, semantic_manifest_sha256=manifest_sha256, + media_type=source.media_type, **custody, + ) + selected = reservation.policy.entries[0] + input_body = { + "schema_version": "workstream.external_checker_pre_submit_input.v1", + "requirement_id": selected.requirement_id, + "project_id": str(reservation.project_id), "task_id": str(reservation.task_id), + "assignment_id": str(reservation.assignment_id), + "archive_sha256": source.raw_sha256, "archive_byte_count": source.raw_byte_count, + "semantic_manifest_sha256": manifest_sha256, + "manifest": [asdict(entry) for entry in value.entries], + "packet": {"summary": value.packet.summary, + "contributor_attestation": value.packet.contributor_attestation}, + } + request = make_external_checker_execution_request( + registry=selected.registry, identity=identity, configuration=selected.configuration, + configuration_sha256=selected.configuration_sha256, input=input_body, + input_sha256=external_checker_json_hash(input_body), materials=(material,), + ) + return value, request + + class SelectedPreSubmitExecutionAuthority(Protocol): """Process-local capability for one committed durable PRE lease.""" @@ -653,7 +773,7 @@ def __post_init__(self) -> None: if self.execution is not None: if type(self.execution) is not SelectedPreSubmitExecutionFacts: raise ValueError("selected PRE finalize execution is invalid") - self.execution.validate_reservation(self.lease.reservation) + self.execution.validate_lease(self.lease) else: SelectedPreSubmitInfrastructureUnavailable(self.infrastructure_failure_code or "") @@ -802,7 +922,7 @@ def __post_init__(self) -> None: or self.execution.policy_sha256 != self.lease.reservation.policy_sha256 ): raise ValueError("selected PRE completed outcome is invalid") - self.execution.validate_reservation(self.lease.reservation) + self.execution.validate_lease(self.lease) elif (self.outcome != "infrastructure_failed" or self.execution is not None or self.infrastructure_failure_code not in { "capacity_exceeded", diff --git a/backend/app/modules/checkers/selected_pre_submit_execution.py b/backend/app/modules/checkers/selected_pre_submit_execution.py index 44aea4816..f70c60f10 100644 --- a/backend/app/modules/checkers/selected_pre_submit_execution.py +++ b/backend/app/modules/checkers/selected_pre_submit_execution.py @@ -1,150 +1,59 @@ -"""Selected default-plus-external PRE execution over one ART callback.""" +"""One source-bound PRE invocation and independent combined-result validation.""" from __future__ import annotations import asyncio -from dataclasses import asdict -from app.interfaces.external_checker_execution import ExternalCheckerExecutionAdapter +from app.interfaces.external_checker_execution import ( + ExternalCheckerExecutionAdapter, + ExternalPreSubmitSourceGrant, +) from app.interfaces.external_services import ( ExternalServiceProtocolError, ExternalServiceUnavailableError, ) -from app.modules.checkers.api.default_checker import WorkstreamDefaultCheckerInput, WorkstreamDefaultCheckerResult -from app.modules.checkers.api.external import ( - PreSubmitExternalCheckerIdentity, - PreSubmitExternalCheckerMaterial, - external_checker_json_hash, - make_external_checker_execution_request, -) -from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy -from app.modules.checkers.api.materialization import PreSubmitMaterialView from app.modules.checkers.api.selected_pre_submit import ( - ExternalPreSubmitIsolationFacts, - ExternalPreSubmitMemberFacts, SelectedPreSubmitExecutionFacts, SelectedPreSubmitInfrastructureUnavailable, + SelectedPreSubmitLeaseFacts, ) - -def _input_body( - *, - requirement_id: str, - identity: PreSubmitExternalCheckerIdentity, - material: PreSubmitExternalCheckerMaterial, - value: WorkstreamDefaultCheckerInput, -) -> dict[str, object]: - """Build the one normalized public PRE image input from verified facts.""" - return { - "schema_version": "workstream.external_checker_pre_submit_input.v1", - "requirement_id": requirement_id, - "project_id": str(identity.project_id), - "task_id": str(identity.task_id), - "assignment_id": str(identity.assignment_id), - "archive_sha256": material.archive_sha256, - "archive_byte_count": material.archive_byte_count, - "semantic_manifest_sha256": material.semantic_manifest_sha256, - "manifest": [asdict(item) for item in value.entries], - "packet": { - "summary": value.packet.summary, - "contributor_attestation": value.packet.contributor_attestation, - }, - } - - class SelectedPreSubmitProcessor: - """Run the default and every required locked external PRE image in order.""" + """Run the platform defaults and selected project through one typed call.""" def __init__( - self, - *, - policy: LockedExternalPreSubmitPolicy, - default_input: WorkstreamDefaultCheckerInput, - identity: PreSubmitExternalCheckerIdentity, - material: PreSubmitExternalCheckerMaterial, - execution: ExternalCheckerExecutionAdapter, + self, *, lease: SelectedPreSubmitLeaseFacts, execution: ExternalCheckerExecutionAdapter, ) -> None: - self._policy, self._default_input = policy, default_input - self._identity, self._material = identity, material + self._lease = lease self._execution = execution self._aborted = False + self._started = False self._active: asyncio.Task | None = None def abort(self) -> None: - """Revoke callback access and cancel the active default/image invocation.""" + """Cancel the one invocation; runtime cleanup remains separately owned.""" self._aborted = True if self._active is not None: self._active.cancel() - async def process( - self, material: PreSubmitMaterialView, default: WorkstreamDefaultCheckerResult, - ) -> SelectedPreSubmitExecutionFacts: - """Consume ART's verified export/default after confirmed intake cleanup.""" + async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmitExecutionFacts: + """Validate returned source, fence and derived requests before finalization.""" + if self._aborted: + raise asyncio.CancelledError + if self._started: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + self._started = True try: - if self._aborted: - raise asyncio.CancelledError - members: list[ExternalPreSubmitMemberFacts] = [] - if default.eligible: - for order, binding in enumerate(self._policy.entries): - if self._aborted: - raise asyncio.CancelledError - input_value = _input_body( - requirement_id=binding.requirement_id, - identity=self._identity, - material=self._material, - value=self._default_input, - ) - request = make_external_checker_execution_request( - registry=binding.registry, - identity=self._identity, - configuration=binding.configuration, - configuration_sha256=binding.configuration_sha256, - input=input_value, - input_sha256=external_checker_json_hash(input_value), - materials=(self._material,), - ) - with material.external_checker_grant(request) as grant: - self._active = asyncio.create_task( - self._execution.execute(request, grant) - ) - response = await self._active - result = response.result - if result.outcome == "infrastructure_failed": - raise SelectedPreSubmitInfrastructureUnavailable( - result.infrastructure_failure_code or "invalid_output" - ) - if response.isolation is None: - raise SelectedPreSubmitInfrastructureUnavailable("invalid_output") - member = ExternalPreSubmitMemberFacts( - order=order, - requirement_id=binding.requirement_id, - registry_entry_id=binding.registry.registry_entry_id, - registry_entry_digest=binding.registry.entry_digest, - request_digest=request.request_digest, - result=result, - isolation=ExternalPreSubmitIsolationFacts( - **asdict(response.isolation) - ), - ) - members.append(member) - if result.verdict == "failed": - break - eligible = default.eligible and len(members) == len(self._policy.entries) and all( - item.result.verdict == "passed" for item in members - ) - return SelectedPreSubmitExecutionFacts( - policy_sha256=self._policy.policy_sha256, - workstream_default=default, - required_external_count=len(self._policy.entries), - external_members=tuple(members), - eligible=eligible, - ) + self._active = asyncio.create_task(self._execution.execute_pre(self._lease, grant)) + result = await self._active + if type(result) is not SelectedPreSubmitExecutionFacts: + raise ValueError("PRE result is invalid") + result.validate_lease(self._lease) + return result except ExternalServiceUnavailableError as exc: - raise SelectedPreSubmitInfrastructureUnavailable( - "implementation_unavailable" - ) from exc - except ExternalServiceProtocolError as exc: + raise SelectedPreSubmitInfrastructureUnavailable("implementation_unavailable") from exc + except (ExternalServiceProtocolError, ValueError, TypeError) as exc: raise SelectedPreSubmitInfrastructureUnavailable("invalid_output") from exc finally: self._active = None diff --git a/backend/tests/checkers/external/support.py b/backend/tests/checkers/external/support.py index a294f9b23..eeeeced8b 100644 --- a/backend/tests/checkers/external/support.py +++ b/backend/tests/checkers/external/support.py @@ -114,7 +114,8 @@ def execution_identity(phase: str = "pre_submit"): if phase == "pre_submit": return PreSubmitExternalCheckerIdentity( **common, - prepared_generation_id=uuid4(), + operation_id=uuid4(), source_sha256=SHA, + lease_id=uuid4(), lease_generation=1, attempt_id=uuid4(), attempt_request_digest=SHA, effective_plan_sha256=SHA, @@ -139,7 +140,8 @@ def execution_material(identity): if identity.phase == "pre_submit": return PreSubmitExternalCheckerMaterial( role="submission_archive", - prepared_generation_id=identity.prepared_generation_id, + operation_id=identity.operation_id, source_sha256=identity.source_sha256, + lease_id=identity.lease_id, lease_generation=identity.lease_generation, attempt_id=identity.attempt_id, attempt_request_digest=identity.attempt_request_digest, archive_sha256=SHA, diff --git a/backend/tests/checkers/external/test_contracts.py b/backend/tests/checkers/external/test_contracts.py index bbddf5720..85d16bbfe 100644 --- a/backend/tests/checkers/external/test_contracts.py +++ b/backend/tests/checkers/external/test_contracts.py @@ -161,7 +161,8 @@ def test_execution_request_rejects_duplicate_material_roles() -> None: identity = execution_identity() material = PreSubmitExternalCheckerMaterial( role="submission_archive", - prepared_generation_id=identity.prepared_generation_id, + operation_id=identity.operation_id, source_sha256=identity.source_sha256, + lease_id=identity.lease_id, lease_generation=identity.lease_generation, attempt_id=identity.attempt_id, attempt_request_digest=identity.attempt_request_digest, archive_sha256=SHA, @@ -341,3 +342,27 @@ def test_finding_paths_must_be_safe_relative_archive_paths(path) -> None: check_id="paths.check", code="paths.code", level="warning", message="m", path="src/naïve/main.rs", ).path == "src/naïve/main.rs" + + +@pytest.mark.parametrize("field", [ + "operation_id", "source_sha256", "lease_id", "lease_generation", "attempt_id", "attempt_request_digest", +]) +def test_pre_request_binds_source_and_execution_fence(field): + identity = execution_identity() + material = execution_material(identity) + value = (uuid4() if field.endswith("_id") else + 2 if field == "lease_generation" else "sha256:" + "f" * 64) + material = material.model_copy(update={field: value}) + with pytest.raises(ValueError, match="source material identity mismatch"): + make_external_checker_execution_request( + registry=registry_entry(), identity=identity, configuration={}, + configuration_sha256=external_checker_json_hash({}), input={"task_version": "v3"}, + input_sha256=external_checker_json_hash({"task_version": "v3"}), materials=(material,), + ) + + +def test_pre_request_refuses_prepared_bundle_identity(): + identity = execution_identity() + value = identity.model_dump() | {"prepared_generation_id": uuid4()} + with pytest.raises(ValueError, match="prepared_generation_id"): + type(identity).model_validate(value) diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py index ccc85d111..9d3c85e4e 100644 --- a/backend/tests/checkers/external/test_runtime.py +++ b/backend/tests/checkers/external/test_runtime.py @@ -25,6 +25,7 @@ from app.adapters.checkers.external_service import ( EXTERNAL_CHECKER_CAPABILITY_KEY, EXTERNAL_CHECKER_PROVIDER_KEY, + UnixSocketExternalCheckerAdapter, ) from app.core.config import Settings from app.core.hashing import canonical_json_hash @@ -90,7 +91,8 @@ def _request(*, identity=None, archive_sha256=SHA, archive_byte_count=4): materials=( PreSubmitExternalCheckerMaterial( role="submission_archive", - prepared_generation_id=identity.prepared_generation_id, + operation_id=identity.operation_id, source_sha256=identity.source_sha256, + lease_id=identity.lease_id, lease_generation=identity.lease_generation, attempt_id=identity.attempt_id, attempt_request_digest=identity.attempt_request_digest, archive_sha256=archive_sha256, @@ -112,7 +114,7 @@ def test_shared_rust_fixtures_preserve_python_contract_and_derived_digests(): result.validate_request(request) assert request.configuration == {"threshold": 1e-6} assert request.request_digest == ( - "sha256:a06707b14348ffe5ef22a55de8d4ec4845c9029da7180d5731fb2c120b5591f3" + "sha256:147cd4a72624caf97ec7ee167d00e1f76d2a9c89d0bda84134b6f1ac01a47a79" ) changed = request.model_dump(mode="json") changed["configuration"]["threshold"] = 2e-6 @@ -1115,3 +1117,160 @@ async def test_public_trace_preserves_execution_arguments(monkeypatch, tmp_path, assert [json.loads(line)["event"] for line in trace.read_text().splitlines()] == [ "project_started", "project_completed", ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing"]) +async def test_single_pre_transport_streams_source_and_validates_combined_result(tmp_path, changed): + from dataclasses import replace + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts + from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + from tests.checkers.external.test_selected_pre_submit_coordination import ( + _source_reservation, _source_completed_execution, + ) + + payload = b"controlled transport bytes" * 4000 + reservation = _source_reservation() + reservation = replace(reservation, source=reservation.source.model_copy(update={ + "raw_sha256": "sha256:" + hashlib.sha256(payload).hexdigest(), + "raw_byte_count": len(payload), + })) + execution = _source_completed_execution(reservation) + lease = SelectedPreSubmitLeaseFacts( + reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at, + ) + body = execution.canonical_body() + if changed == "result_fence": + body["lease_generation"] += 1 + received = bytearray() + sizes = [] + finished = asyncio.Event() + requests = [] + + async def handle(reader, writer): + try: + size = struct.unpack(">I", await reader.readexactly(4))[0] + requests.append(json.loads(await reader.readexactly(size))) + while True: + size = struct.unpack(">I", await reader.readexactly(4))[0] + if size == 0: + break + sizes.append(size) + received.extend(await reader.readexactly(size)) + response = json.dumps(body).encode() + writer.write(struct.pack(">I", len(response)) + response) + if changed == "trailing": + writer.write(b"extra") + await writer.drain() + except (asyncio.IncompleteReadError, ConnectionResetError): + pass # A refused source must close transport before the EOF marker. + finally: + writer.close() + await writer.wait_closed() + finished.set() + + class Grant: + closed = False + calls = 0 + + async def open_source(self, *, lease): + assert lease == expected_lease + self.calls += 1 + try: + yield (payload[:-1] if changed == "source_short" else + payload + b"!" if changed == "source_long" else + b"x" * len(payload) if changed == "source_hash" else payload) + finally: + self.closed = True + + expected_lease = lease + grant = Grant() + socket = tmp_path / "pre.sock" + server = await asyncio.start_unix_server(handle, socket) + adapter = UnixSocketExternalCheckerAdapter(socket_path=socket, timeout_seconds=5.0) + processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter) + try: + if changed is None: + assert await processor.process(grant) == execution + assert bytes(received) == payload + assert sizes and max(sizes) <= 64 * 1024 + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="material_unavailable"): + await processor.process(grant) + else: + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="invalid_output"): + await processor.process(grant) + await asyncio.wait_for(finished.wait(), 2) + assert grant.closed and grant.calls == 1 + assert len(requests) == 1 and requests[0]["operation"] == "execute_pre" + assert requests[0]["reservation"] == reservation.canonical_body() + assert "grant" not in requests[0] and "prepared_generation_id" not in requests[0] + finally: + server.close() + await server.wait_closed() + + +@pytest.mark.asyncio +async def test_single_pre_expired_lease_does_not_open_source_or_runtime(tmp_path): + from datetime import datetime, timedelta, timezone + from app.modules.checkers.api.selected_pre_submit import ( + SelectedPreSubmitLeaseFacts, SelectedPreSubmitInfrastructureUnavailable, + ) + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + lease = SelectedPreSubmitLeaseFacts( + _source_reservation(), uuid4(), 1, datetime.now(timezone.utc) - timedelta(seconds=1), + ) + class NoSource: + def open_source(self, **kwargs): + raise AssertionError("expired execution opened source") + + adapter = UnixSocketExternalCheckerAdapter(socket_path=tmp_path / "absent.sock", timeout_seconds=5.0) + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="deadline_exceeded"): + await adapter.execute_pre(lease, NoSource()) + + +@pytest.mark.asyncio +async def test_single_pre_cancellation_closes_source_and_transport(tmp_path): + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts + from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + entered, source_closed, connection_closed = asyncio.Event(), asyncio.Event(), asyncio.Event() + reservation = _source_reservation() + lease = SelectedPreSubmitLeaseFacts(reservation, uuid4(), 1, reservation.pre_deadline_at) + class Grant: + async def open_source(self, *, lease): + try: + entered.set() + await asyncio.Event().wait() + yield b"unreachable" + finally: + source_closed.set() + + async def handle(reader, writer): + try: + await reader.read() + finally: + writer.close() + await writer.wait_closed() + connection_closed.set() + + socket = tmp_path / "cancel.sock" + server = await asyncio.start_unix_server(handle, socket) + adapter = UnixSocketExternalCheckerAdapter(socket_path=socket, timeout_seconds=5.0) + processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter) + task = asyncio.create_task(processor.process(Grant())) + try: + await asyncio.wait_for(entered.wait(), 2) + processor.abort() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.wait_for(connection_closed.wait(), 2) + assert source_closed.is_set() + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + server.close() + await server.wait_closed() diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index 376b6520e..1a43d1f54 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -825,28 +825,44 @@ def test_source_first_profile_rejects_archive_time_beyond_aggregate() -> None: def _source_completed_execution(reservation): """Build structural result evidence; this fixture does not attest a runtime.""" - from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts + from app.modules.checkers.api.selected_pre_submit import ( + SelectedPreSubmitExecutionFacts, ExternalPreSubmitMemberFacts, + ExternalPreSubmitIsolationFacts, derive_selected_pre_submit_input, + ) + from app.modules.checkers.api.default_checker import ( + WorkstreamDefaultCheckerResult, workstream_default_input_sha256, + ) from app.modules.checkers.api.external import make_external_checker_execution_result - execution = SelectedPreSubmitExecutionFacts.from_canonical_body( - _retained_v1("selected_pre_v1_completed")["terminal"]["execution"] + retained = _retained_v1("selected_pre_v1_completed") + old = retained["terminal"]["execution"] + manifest = retained["request"]["admission_lineage"]["semantic_manifest_body"] + manifest_sha256 = canonical_json_hash(manifest) + lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at) + value, request = derive_selected_pre_submit_input( + lease, manifest_body=manifest, manifest_sha256=manifest_sha256, ) selected = reservation.policy.entries[0] - member = execution.external_members[0] result = make_external_checker_execution_result( - **(member.result.model_dump(exclude={"result_digest"}) | { - "registry_entry_id": selected.registry.registry_entry_id, - "registry_entry_digest": selected.registry.entry_digest, - }) - ) - return replace( - execution, policy_sha256=reservation.policy_sha256, - external_members=(replace( - member, requirement_id=selected.requirement_id, + request_digest=request.request_digest, registry_entry_id=selected.registry.registry_entry_id, + registry_entry_digest=selected.registry.entry_digest, phase="pre_submit", + outcome="completed", verdict="passed", findings=(), infrastructure_failure_code=None, + ) + return SelectedPreSubmitExecutionFacts( + request_digest=reservation.request_digest, lease_id=lease.lease_id, lease_generation=1, + observed_source=reservation.source, manifest_body=manifest, manifest_sha256=manifest_sha256, + default_input_sha256=workstream_default_input_sha256(value), + policy_sha256=reservation.policy_sha256, + workstream_default=WorkstreamDefaultCheckerResult.model_validate(old["workstream_default"]), + required_external_count=1, eligible=True, + external_members=(ExternalPreSubmitMemberFacts( + order=0, requirement_id=selected.requirement_id, registry_entry_id=selected.registry.registry_entry_id, - registry_entry_digest=selected.registry.entry_digest, result=result, - isolation=replace(member.isolation, - platform_manifest_digest=selected.registry.image_digest), + registry_entry_digest=selected.registry.entry_digest, request_digest=request.request_digest, + result=result, isolation=ExternalPreSubmitIsolationFacts(**( + old["external_members"][0]["isolation"] | + {"platform_manifest_digest": selected.registry.image_digest} + )), ),), ) @@ -883,7 +899,7 @@ def test_source_first_finalization_binds_actual_selected_member(changed): execution = replace(execution, external_members=(), eligible=False) now = datetime.now(UTC) lease = SelectedPreSubmitLeaseFacts( - reservation=reservation, lease_id=new_record_id(), lease_generation=1, + reservation=reservation, lease_id=execution.lease_id, lease_generation=execution.lease_generation, lease_expires_at=reservation.pre_deadline_at, ) def finalize(): @@ -915,9 +931,10 @@ def test_source_first_default_rejection_does_not_require_project_result(): workstream_default=evaluate_rejected_archive( "submission_archive_malformed", packet=reservation.default_context.packet, ), external_members=(), eligible=False, + manifest_body=None, manifest_sha256=None, default_input_sha256=None, ) lease = SelectedPreSubmitLeaseFacts( - reservation, new_record_id(), 1, reservation.pre_deadline_at, + reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at, ) assert SelectedPreSubmitFinalizeFacts(lease, execution, None).execution == execution @@ -932,7 +949,7 @@ def test_source_first_result_digest_revalidated_before_terminal_write(boundary): forged = member.result.model_copy(update={"result_digest": "sha256:" + "f" * 64}) execution = replace(execution, external_members=(replace(member, result=forged),)) lease = SelectedPreSubmitLeaseFacts( - reservation, new_record_id(), 1, reservation.pre_deadline_at, + reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at, ) now = datetime.now(UTC) with pytest.raises(ValueError, match="result digest mismatch"): @@ -940,3 +957,75 @@ def test_source_first_result_digest_revalidated_before_terminal_write(boundary): SelectedPreSubmitFinalizeFacts(lease, execution, None) else: SelectedPreSubmitTerminalFacts(lease, "completed", execution, None, now, now, now) + + +@pytest.mark.parametrize("changed", [ + "request", "lease_id", "lease_generation", "source_generation", "source_hash", + "source_count", "source_operation", "default_input", "manifest", "missing_manifest", + "project_request", +]) +def test_source_first_completed_evidence_rejects_substitution(changed): + from copy import deepcopy + from app.modules.checkers.api.external import make_external_checker_execution_result + + reservation = _source_reservation() + execution = _source_completed_execution(reservation) + lease = SelectedPreSubmitLeaseFacts( + reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at, + ) + if changed == "request": + execution = replace(execution, request_digest="sha256:" + "f" * 64) + elif changed == "lease_id": + execution = replace(execution, lease_id=new_record_id()) + elif changed == "lease_generation": + execution = replace(execution, lease_generation=execution.lease_generation + 1) + elif changed.startswith("source_"): + source = execution.observed_source + field, value = { + "source_generation": ("provider_generation", "different-generation"), + "source_hash": ("raw_sha256", "sha256:" + "f" * 64), + "source_count": ("raw_byte_count", source.raw_byte_count + 1), + "source_operation": ("location", source.location.model_copy(update={ + "operation_id": new_record_id(), + })), + }[changed] + execution = replace(execution, observed_source=source.model_copy(update={field: value})) + elif changed == "default_input": + execution = replace(execution, default_input_sha256="sha256:" + "f" * 64) + elif changed == "manifest": + body = deepcopy(execution.manifest_body) + body["entries"][0]["normalized_path"] = "../escape" + execution = replace(execution, manifest_body=body, manifest_sha256=canonical_json_hash(body)) + elif changed == "missing_manifest": + execution = replace(execution, manifest_body=None, manifest_sha256=None, default_input_sha256=None) + elif changed == "project_request": + member = execution.external_members[0] + # Echo agreement plus a valid result digest is insufficient: the owner + # reconstructs the request from its frozen context and parsed manifest. + result = make_external_checker_execution_result(**( + member.result.model_dump(exclude={"result_digest"}) | + {"request_digest": "sha256:" + "f" * 64} + )) + execution = replace(execution, external_members=(replace( + member, request_digest=result.request_digest, result=result, + ),)) + with pytest.raises(ValueError): + SelectedPreSubmitFinalizeFacts(lease, execution, None) + + +@pytest.mark.parametrize("limit", ["maximum_entries", "maximum_path_bytes", "maximum_entry_bytes"]) +def test_source_first_derived_manifest_obeys_locked_limits(limit): + from app.modules.checkers.api.selected_pre_submit import derive_selected_pre_submit_input + from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits + + reservation = _source_reservation() + execution = _source_completed_execution(reservation) + profile = reservation.runtime_profile.model_copy(update={ + "archive_limits": SubmissionArchiveLimits(**{limit: 1}, maximum_inspection_seconds=60), + }) + reservation = replace(reservation, runtime_profile=profile) + lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at) + with pytest.raises(ValueError): + derive_selected_pre_submit_input( + lease, manifest_body=execution.manifest_body, manifest_sha256=execution.manifest_sha256, + ) diff --git a/external_checkers/fixtures/request.json b/external_checkers/fixtures/request.json index 68571145f..69319d00a 100644 --- a/external_checkers/fixtures/request.json +++ b/external_checkers/fixtures/request.json @@ -1 +1 @@ -{"configuration":{"threshold":1e-06},"configuration_sha256":"sha256:3257714092b3dc613247191d82d6da4c22f789929cb50696ebb38a69cc8ef1ff","identity":{"assignment_id":"66666666-6666-4666-8666-666666666666","attempt_id":"88888888-8888-4888-8888-888888888888","attempt_request_digest":"sha256:2222222222222222222222222222222222222222222222222222222222222222","effective_plan_sha256":"sha256:3333333333333333333333333333333333333333333333333333333333333333","phase":"pre_submit","prepared_generation_id":"77777777-7777-4777-8777-777777777777","project_id":"44444444-4444-4444-8444-444444444444","task_id":"55555555-5555-4555-8555-555555555555"},"input":{"task_version":"v3"},"input_sha256":"sha256:7f9f19934f23f43e56d62005ba9fefb8af3a4b42df80103f475187f659ffe6cb","materials":[{"archive_byte_count":14,"archive_sha256":"sha256:4444444444444444444444444444444444444444444444444444444444444444","attempt_id":"88888888-8888-4888-8888-888888888888","attempt_request_digest":"sha256:2222222222222222222222222222222222222222222222222222222222222222","media_type":"application/zip","phase":"pre_submit","prepared_generation_id":"77777777-7777-4777-8777-777777777777","role":"submission_archive","semantic_manifest_sha256":"sha256:5555555555555555555555555555555555555555555555555555555555555555"}],"registry":{"authorization_decision_event_id":"33333333-3333-4333-8333-333333333333","capability_id":"acme.safe_archive","capability_version":"v1.2.3","configuration_schema":{"document":{"additionalProperties":false,"properties":{"threshold":{"type":"number"}},"required":["threshold"],"type":"object"},"schema_id":"acme.safe_archive.configuration","schema_sha256":"sha256:fd170dacd315270c71f33ff14eb2ae68ae2a6e57b1b6ce494e08e5b63797238b","schema_version":"v1"},"created_at":"2026-10-10T06:00:00Z","entry_digest":"sha256:00603847c6b55dcae9d1f03fed5cc55d0c2f8c05ba02ad35ce1b9eb7b7e0ade2","image_digest":"sha256:1111111111111111111111111111111111111111111111111111111111111111","input_schema":{"document":{"additionalProperties":false,"properties":{"task_version":{"type":"string"}},"required":["task_version"],"type":"object"},"schema_id":"external_checker_pre_submit_input","schema_sha256":"sha256:980c5b0d64a514c4d7e3c0061b99bf2281533296d9376bfdcbdefef3122e4186","schema_version":"v1"},"output_schema":{"document":{"type":"object"},"schema_id":"external_checker_result","schema_sha256":"sha256:a2c799262a3ce3c19ef5cdd983bf3d12b43ab3c426227091b909dcb7054738c0","schema_version":"v1"},"phase":"pre_submit","registered_by_actor_profile_id":"22222222-2222-4222-8222-222222222222","registration_operation_id":"11111111-1111-4111-8111-111111111111","registry_entry_id":"01890f12-3456-789a-8bcd-ef0123456789","resources":{"cpu_millis":500,"deadline_ms":30000,"maximum_output_bytes":32768,"memory_bytes":134217728}},"request_digest":"sha256:a06707b14348ffe5ef22a55de8d4ec4845c9029da7180d5731fb2c120b5591f3","schema_version":"external_checker_request.v1"} +{"configuration":{"threshold":1e-06},"configuration_sha256":"sha256:3257714092b3dc613247191d82d6da4c22f789929cb50696ebb38a69cc8ef1ff","identity":{"assignment_id":"66666666-6666-4666-8666-666666666666","attempt_id":"88888888-8888-4888-8888-888888888888","attempt_request_digest":"sha256:2222222222222222222222222222222222222222222222222222222222222222","effective_plan_sha256":"sha256:3333333333333333333333333333333333333333333333333333333333333333","lease_generation":3,"lease_id":"019b0000-0000-7000-8000-000000000002","operation_id":"019b0000-0000-7000-8000-000000000001","phase":"pre_submit","project_id":"44444444-4444-4444-8444-444444444444","source_sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","task_id":"55555555-5555-4555-8555-555555555555"},"input":{"task_version":"v3"},"input_sha256":"sha256:7f9f19934f23f43e56d62005ba9fefb8af3a4b42df80103f475187f659ffe6cb","materials":[{"archive_byte_count":14,"archive_sha256":"sha256:4444444444444444444444444444444444444444444444444444444444444444","attempt_id":"88888888-8888-4888-8888-888888888888","attempt_request_digest":"sha256:2222222222222222222222222222222222222222222222222222222222222222","lease_generation":3,"lease_id":"019b0000-0000-7000-8000-000000000002","media_type":"application/zip","operation_id":"019b0000-0000-7000-8000-000000000001","phase":"pre_submit","role":"submission_archive","semantic_manifest_sha256":"sha256:5555555555555555555555555555555555555555555555555555555555555555","source_sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}],"registry":{"authorization_decision_event_id":"33333333-3333-4333-8333-333333333333","capability_id":"acme.safe_archive","capability_version":"v1.2.3","configuration_schema":{"document":{"additionalProperties":false,"properties":{"threshold":{"type":"number"}},"required":["threshold"],"type":"object"},"schema_id":"acme.safe_archive.configuration","schema_sha256":"sha256:fd170dacd315270c71f33ff14eb2ae68ae2a6e57b1b6ce494e08e5b63797238b","schema_version":"v1"},"created_at":"2026-10-10T06:00:00Z","entry_digest":"sha256:00603847c6b55dcae9d1f03fed5cc55d0c2f8c05ba02ad35ce1b9eb7b7e0ade2","image_digest":"sha256:1111111111111111111111111111111111111111111111111111111111111111","input_schema":{"document":{"additionalProperties":false,"properties":{"task_version":{"type":"string"}},"required":["task_version"],"type":"object"},"schema_id":"external_checker_pre_submit_input","schema_sha256":"sha256:980c5b0d64a514c4d7e3c0061b99bf2281533296d9376bfdcbdefef3122e4186","schema_version":"v1"},"output_schema":{"document":{"type":"object"},"schema_id":"external_checker_result","schema_sha256":"sha256:a2c799262a3ce3c19ef5cdd983bf3d12b43ab3c426227091b909dcb7054738c0","schema_version":"v1"},"phase":"pre_submit","registered_by_actor_profile_id":"22222222-2222-4222-8222-222222222222","registration_operation_id":"11111111-1111-4111-8111-111111111111","registry_entry_id":"01890f12-3456-789a-8bcd-ef0123456789","resources":{"cpu_millis":500,"deadline_ms":30000,"maximum_output_bytes":32768,"memory_bytes":134217728}},"request_digest":"sha256:147cd4a72624caf97ec7ee167d00e1f76d2a9c89d0bda84134b6f1ac01a47a79","schema_version":"external_checker_request.v1"} diff --git a/external_checkers/fixtures/result.json b/external_checkers/fixtures/result.json index 282a0f5d5..68ae7683b 100644 --- a/external_checkers/fixtures/result.json +++ b/external_checkers/fixtures/result.json @@ -1 +1 @@ -{"findings":[],"infrastructure_failure_code":null,"outcome":"completed","phase":"pre_submit","registry_entry_digest":"sha256:00603847c6b55dcae9d1f03fed5cc55d0c2f8c05ba02ad35ce1b9eb7b7e0ade2","registry_entry_id":"01890f12-3456-789a-8bcd-ef0123456789","request_digest":"sha256:a06707b14348ffe5ef22a55de8d4ec4845c9029da7180d5731fb2c120b5591f3","result_digest":"sha256:2fdede489f609ba59017fe8da4a2f7ed31307700eb7663532d9944233d7ab82d","schema_version":"external_checker_result.v1","verdict":"passed"} +{"findings":[],"infrastructure_failure_code":null,"outcome":"completed","phase":"pre_submit","registry_entry_digest":"sha256:00603847c6b55dcae9d1f03fed5cc55d0c2f8c05ba02ad35ce1b9eb7b7e0ade2","registry_entry_id":"01890f12-3456-789a-8bcd-ef0123456789","request_digest":"sha256:147cd4a72624caf97ec7ee167d00e1f76d2a9c89d0bda84134b6f1ac01a47a79","result_digest":"sha256:b77141609a58030d02f5a34e956b4714179d09dc2e2350eed715db6867d4676d","schema_version":"external_checker_result.v1","verdict":"passed"} diff --git a/external_checkers/workstream-checker-sdk/src/lib.rs b/external_checkers/workstream-checker-sdk/src/lib.rs index 28c80aa6f..93e2571bd 100644 --- a/external_checkers/workstream-checker-sdk/src/lib.rs +++ b/external_checkers/workstream-checker-sdk/src/lib.rs @@ -207,7 +207,10 @@ pub fn parse_request(bytes: &[u8]) -> Result { &[ "phase", "role", - "prepared_generation_id", + "operation_id", + "source_sha256", + "lease_id", + "lease_generation", "attempt_id", "attempt_request_digest", "archive_sha256", @@ -222,8 +225,11 @@ pub fn parse_request(bytes: &[u8]) -> Result { digest(material, "attempt_request_digest")?; digest(material, "archive_sha256")?; digest(material, "semantic_manifest_sha256")?; - if string(material, "prepared_generation_id")? - != string(identity, "prepared_generation_id")? + if string(material, "operation_id")? != string(identity, "operation_id")? + || digest(material, "source_sha256")? != digest(identity, "source_sha256")? + || string(material, "lease_id")? != string(identity, "lease_id")? + || unsigned(material, "lease_generation")? + != unsigned(identity, "lease_generation")? || string(material, "attempt_id")? != string(identity, "attempt_id")? || digest(material, "attempt_request_digest")? != digest(identity, "attempt_request_digest")? @@ -581,7 +587,10 @@ fn validate_identity(identity: &Map, phase: &str) -> Result<(), C "project_id", "task_id", "assignment_id", - "prepared_generation_id", + "operation_id", + "source_sha256", + "lease_id", + "lease_generation", "attempt_id", "attempt_request_digest", "effective_plan_sha256", @@ -1295,6 +1304,48 @@ mod tests { request } + #[test] + fn pre_source_identity_and_fence_are_bound_to_material() { + let original: Value = + serde_json::from_slice(include_bytes!("../../fixtures/request.json")).unwrap(); + for field in [ + "operation_id", + "source_sha256", + "lease_id", + "lease_generation", + "attempt_id", + "attempt_request_digest", + ] { + let mut request = original.clone(); + request["materials"][0][field] = if field == "lease_generation" { + serde_json::json!(4) + } else if field.ends_with("_id") { + serde_json::json!("019b0000-0000-7000-8000-000000000003") + } else { + serde_json::json!(format!("sha256:{}", "f".repeat(64))) + }; + let request = resign_request(request); + assert!( + parse_request(&serde_json::to_vec(&request).unwrap()).is_err(), + "{field}" + ); + } + let mut request = original.clone(); + request["identity"]["prepared_generation_id"] = + serde_json::json!("019b0000-0000-7000-8000-000000000003"); + assert!(parse_request(&serde_json::to_vec(&resign_request(request)).unwrap()).is_err()); + for generation in [ + serde_json::json!(0), + serde_json::json!(-1), + serde_json::json!(true), + ] { + let mut request = original.clone(); + request["identity"]["lease_generation"] = generation.clone(); + request["materials"][0]["lease_generation"] = generation; + assert!(parse_request(&serde_json::to_vec(&resign_request(request)).unwrap()).is_err()); + } + } + fn post_context_request(kind: &str, selected_roles: &[&str]) -> Value { let digest = |byte: char| format!("sha256:{}", byte.to_string().repeat(64)); let id = |byte: char| format!("{0}{0}{0}{0}{0}{0}{0}{0}-0000-4000-8000-000000000000", byte); @@ -1555,7 +1606,7 @@ mod tests { .expect("Python request fixture must satisfy the Rust contract"); assert_eq!( request.request_digest, - "sha256:a06707b14348ffe5ef22a55de8d4ec4845c9029da7180d5731fb2c120b5591f3" + "sha256:147cd4a72624caf97ec7ee167d00e1f76d2a9c89d0bda84134b6f1ac01a47a79" ); let result: Value = serde_json::from_slice(include_bytes!("../../fixtures/result.json")) .expect("result fixture is JSON"); From e29c637aeafbfa8f1f939d2f981e6ceb973d2a3c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:09:14 +0100 Subject: [PATCH 065/513] Enforce PRE stream bounds and preserve default-only rejection --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 ++++++- .../app/adapters/checkers/external_service.py | 17 ++--- .../interfaces/external_checker_execution.py | 6 +- .../checkers/api/selected_pre_submit.py | 54 +++++++++++----- .../tests/checkers/external/test_runtime.py | 36 ++++++++--- .../test_selected_pre_submit_coordination.py | 62 +++++++++++++++++++ 6 files changed, 165 insertions(+), 34 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 642f70dd8..af5d02b13 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1448,8 +1448,8 @@ The CHECKERS PRE processor now invokes one typed `execute_pre` operation instead of exporting an ART tree and dispatching a second project invocation. Its existing factory and lazy configured adapter use the same external-service capability. The Unix client streams an ART grant's exact source in at most 64 KiB frames, -checks count/SHA before EOF, bounds request/result framing and elapsed time by the -lease, and closes source/transport on cancellation. The grant is a separate +checks count/SHA before EOF, bounds request/result framing, refuses success after +the lease/configured deadline, and closes source/transport on cancellation. The grant is a separate process-local port; no token or host path enters immutable request identity. Live nested Python/Rust PRE identity now binds operation, sealed-source digest, @@ -1483,3 +1483,23 @@ they must be removed during the connected replacement, not made into compatibili adapters. The current public path remains unfinished and these local commits must not be pushed as a publishable cutover. No source grant authority, native guest execution, provider qualification or accepted handoff is proved by a socket fake. + + +The first combined-client review found three defects: manifest-present default +rejection incorrectly validated an unrun project input schema; synchronous +response decoding could return success after the timeout; and upstream source +chunks had no byte ceiling before socket framing. The repair separates default +input derivation from conditional project request construction, checks monotonic +and lease deadlines after decode/validation, and requires nonempty source chunks +of at most 64 KiB before hashing or forwarding. The source-grant port declares +that ceiling for the forthcoming issuer. Synchronous bounded JSON parsing is +not physically preempted; its late result is refused. + +New regression cases use a real incompatible registered input schema for both +secret and unchanged-work default rejection (the latter with matching predecessor +and current-rule facts), slow decode after successful wire receipt, and a source +chunk larger than the cap. Removing each corresponding guard made the intended +controls fail: two default-blocker cases, one late-decode case and one oversized +chunk case. Production code was restored after each probe. The expanded focused +suite passes 124 cases; renewed review of these repairs remains pending. The +broader native/ART/T4 integration and the retained old-path failure are unchanged. diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py index db43489a1..b9848648c 100644 --- a/backend/app/adapters/checkers/external_service.py +++ b/backend/app/adapters/checkers/external_service.py @@ -16,6 +16,7 @@ from app.interfaces.external_checker_execution import ( ExternalCheckerExecutionResponse, ExternalPreSubmitSourceGrant, + MAXIMUM_PRE_SOURCE_CHUNK_BYTES, ExternalCheckerForgeLocatorResponse, ExternalCheckerIsolationReceipt, ExternalCheckerMaterialGrant, @@ -98,7 +99,8 @@ async def execute_pre( timeout = min(remaining, reservation.execution_budget_ms / 1000, self._timeout_seconds) if timeout <= 0: raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded") - async with asyncio.timeout(timeout): + deadline = asyncio.get_running_loop().time() + timeout + async with asyncio.timeout_at(deadline): reader, writer = await asyncio.open_unix_connection(self._socket_path) try: writer.write(struct.pack(">I", len(payload)) + payload) @@ -107,16 +109,14 @@ async def execute_pre( stream = grant.open_source(lease=lease) try: async for chunk in stream: - if type(chunk) is not bytes: + if type(chunk) is not bytes or not 0 < len(chunk) <= MAXIMUM_PRE_SOURCE_CHUNK_BYTES: raise ValueError("PRE source chunk is invalid") count += len(chunk) if count > reservation.source.raw_byte_count: raise ValueError("PRE source identity differs") digest.update(chunk) - for offset in range(0, len(chunk), 64 * 1024): - part = chunk[offset:offset + 64 * 1024] - writer.write(struct.pack(">I", len(part)) + part) - await writer.drain() + writer.write(struct.pack(">I", len(chunk)) + chunk) + await writer.drain() finally: await await_cancellation_resistant(stream.aclose()) if (count != reservation.source.raw_byte_count @@ -135,6 +135,9 @@ async def execute_pre( await await_cancellation_resistant(writer.wait_closed()) result = SelectedPreSubmitExecutionFacts.from_canonical_body(json.loads(raw)) result.validate_lease(lease) + if (asyncio.get_running_loop().time() >= deadline + or datetime.now(timezone.utc) >= lease.lease_expires_at): + raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded") return result except ExternalServiceProtocolError: raise @@ -142,7 +145,7 @@ async def execute_pre( raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded") from exc except (OSError, asyncio.IncompleteReadError) as exc: raise ExternalServiceUnavailableError(self._identity) from exc - except (TypeError, ValueError, KeyError, UnicodeError) as exc: + except (TypeError, ValueError, KeyError, UnicodeError, RecursionError) as exc: raise ExternalServiceProtocolError(self._identity) from exc async def execute( diff --git a/backend/app/interfaces/external_checker_execution.py b/backend/app/interfaces/external_checker_execution.py index e9aeb0a71..c6665ead0 100644 --- a/backend/app/interfaces/external_checker_execution.py +++ b/backend/app/interfaces/external_checker_execution.py @@ -20,6 +20,9 @@ ) +MAXIMUM_PRE_SOURCE_CHUNK_BYTES = 64 * 1024 + + _REPOSITORY = re.compile( r"[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?(?::[0-9]+)?" r"(?:/[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?)*" @@ -155,7 +158,7 @@ class ExternalPreSubmitSourceGrant(Protocol): """ def open_source(self, *, lease: SelectedPreSubmitLeaseFacts) -> AsyncGenerator[bytes, None]: - """Read only the bound source, outside a database transaction.""" + """Yield nonempty chunks up to MAXIMUM_PRE_SOURCE_CHUNK_BYTES outside DB roots.""" class ExternalCheckerExecutionAdapter(ExternalServiceAdapter, Protocol): @@ -190,6 +193,7 @@ async def health(self) -> ExternalCheckerServiceHealth: __all__ = ( "ExternalCheckerExecutionAdapter", "ExternalPreSubmitSourceGrant", + "MAXIMUM_PRE_SOURCE_CHUNK_BYTES", "ExternalCheckerExecutionResponse", "ExternalCheckerIsolationReceipt", "ExternalCheckerMaterialGrant", diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py index 4b27a2097..bd531dcfd 100644 --- a/backend/app/modules/checkers/api/selected_pre_submit.py +++ b/backend/app/modules/checkers/api/selected_pre_submit.py @@ -15,10 +15,10 @@ from app.core.hashing import canonical_json_hash from app.modules.artifacts.api.submission_intake import SealedSubmissionSource from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits -from app.modules.checkers.api.default_checker import WorkstreamDefaultContext +from app.modules.checkers.api.default_checker import WorkstreamDefaultContext, WorkstreamDefaultCheckerInput from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy from app.modules.checkers.api.default_checker import WorkstreamDefaultCheckerResult -from app.modules.checkers.api.external import ExternalCheckerExecutionResult +from app.modules.checkers.api.external import ExternalCheckerExecutionResult, ExternalCheckerExecutionRequest from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal @@ -344,9 +344,15 @@ def validate_lease(self, lease: SelectedPreSubmitLeaseFacts) -> None: else: if archive_safe.status != "passed" or self.workstream_default.checks[1].status != "passed": raise ValueError("selected PRE inspected identity result is invalid") - value, request = derive_selected_pre_submit_input( - lease, manifest_body=self.manifest_body, manifest_sha256=self.manifest_sha256, - ) + if self.workstream_default.eligible: + value, request = derive_selected_pre_submit_input( + lease, manifest_body=self.manifest_body, manifest_sha256=self.manifest_sha256, + ) + else: + value = derive_selected_pre_submit_default_input( + lease, manifest_body=self.manifest_body, manifest_sha256=self.manifest_sha256, + ) + request = None if workstream_default_input_sha256(value) != self.default_input_sha256: raise ValueError("selected PRE derived default input differs") if ( @@ -642,27 +648,20 @@ def __post_init__(self) -> None: raise ValueError("selected PRE lease facts are invalid") -def derive_selected_pre_submit_input( +def derive_selected_pre_submit_default_input( lease: SelectedPreSubmitLeaseFacts, *, manifest_body: object, manifest_sha256: str, -): - """Derive default input and the project request from locked facts and metadata. - - Called independently by the trusted guest and backend verifier. This pure - derivation grants no source access and does not attest file observation. - """ +) -> WorkstreamDefaultCheckerInput: + """Derive platform input without consulting an unrun project input schema.""" from app.modules.artifacts.api.submission_archive import validate_submission_manifest from app.modules.checkers.api.material import SubmissionMaterialEntry - from app.modules.checkers.api.external import ( - PreSubmitExternalCheckerIdentity, PreSubmitExternalCheckerMaterial, - external_checker_json_hash, make_external_checker_execution_request, - ) + reservation = lease.reservation source = reservation.source inspection = validate_submission_manifest( manifest_body, sha256=manifest_sha256, limits=reservation.runtime_profile.archive_limits, ) - value = reservation.default_context.bind_verified_input( + return reservation.default_context.bind_verified_input( archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count, archive_media_type=source.media_type, semantic_manifest_sha256=manifest_sha256, entries=tuple(SubmissionMaterialEntry( @@ -670,6 +669,25 @@ def derive_selected_pre_submit_input( entry.sha256, entry.executable, ) for entry in inspection.entries), ) + + +def derive_selected_pre_submit_input( + lease: SelectedPreSubmitLeaseFacts, *, manifest_body: object, manifest_sha256: str, +) -> tuple[WorkstreamDefaultCheckerInput, ExternalCheckerExecutionRequest]: + """Reconstruct the project request only after the platform defaults pass. + + This pure derivation grants no source access and does not attest observation. + """ + from app.modules.checkers.api.external import ( + PreSubmitExternalCheckerIdentity, PreSubmitExternalCheckerMaterial, + external_checker_json_hash, make_external_checker_execution_request, + ) + + value = derive_selected_pre_submit_default_input( + lease, manifest_body=manifest_body, manifest_sha256=manifest_sha256, + ) + reservation = lease.reservation + source = reservation.source custody = dict( operation_id=source.location.operation_id, source_sha256=source.source_sha256(), attempt_id=reservation.attempt_id, attempt_request_digest=reservation.request_digest, @@ -1109,6 +1127,8 @@ async def read_project_runs( __all__ = ( + "derive_selected_pre_submit_default_input", + "derive_selected_pre_submit_input", "ExternalPreSubmitIsolationFacts", "ExternalPreSubmitMemberFacts", "PreparedSelectedPreSubmitExecution", diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py index 9d3c85e4e..e8314d58c 100644 --- a/backend/tests/checkers/external/test_runtime.py +++ b/backend/tests/checkers/external/test_runtime.py @@ -1120,8 +1120,8 @@ async def test_public_trace_preserves_execution_arguments(monkeypatch, tmp_path, @pytest.mark.asyncio -@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing"]) -async def test_single_pre_transport_streams_source_and_validates_combined_result(tmp_path, changed): +@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing", "chunk_oversized", "slow_decode"]) +async def test_single_pre_transport_streams_source_and_validates_combined_result(tmp_path, monkeypatch, changed): from dataclasses import replace from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor @@ -1178,17 +1178,34 @@ async def open_source(self, *, lease): assert lease == expected_lease self.calls += 1 try: - yield (payload[:-1] if changed == "source_short" else - payload + b"!" if changed == "source_long" else - b"x" * len(payload) if changed == "source_hash" else payload) + data = (payload[:-1] if changed == "source_short" else + payload + b"!" if changed == "source_long" else + b"x" * len(payload) if changed == "source_hash" else payload) + if changed == "chunk_oversized": + yield data + else: + for offset in range(0, len(data), 16 * 1024): + yield data[offset:offset + 16 * 1024] finally: self.closed = True + decode_called = [] + if changed == "slow_decode": + import time + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts + decode = SelectedPreSubmitExecutionFacts.from_canonical_body + def delayed_decode(cls, value): + decode_called.append(True) + time.sleep(0.3) + return decode(value) + monkeypatch.setattr(SelectedPreSubmitExecutionFacts, "from_canonical_body", classmethod(delayed_decode)) expected_lease = lease grant = Grant() socket = tmp_path / "pre.sock" server = await asyncio.start_unix_server(handle, socket) - adapter = UnixSocketExternalCheckerAdapter(socket_path=socket, timeout_seconds=5.0) + adapter = UnixSocketExternalCheckerAdapter( + socket_path=socket, timeout_seconds=0.2 if changed == "slow_decode" else 5.0, + ) processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter) try: if changed is None: @@ -1198,8 +1215,13 @@ async def open_source(self, *, lease): with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="material_unavailable"): await processor.process(grant) else: - with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="invalid_output"): + code = "deadline_exceeded" if changed == "slow_decode" else "invalid_output" + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match=code): await processor.process(grant) + if changed == "slow_decode": + assert decode_called == [True] + if changed == "chunk_oversized": + assert not sizes await asyncio.wait_for(finished.wait(), 2) assert grant.closed and grant.calls == 1 assert len(requests) == 1 and requests[0]["operation"] == "execute_pre" diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index 1a43d1f54..e01c5e60d 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -2,6 +2,8 @@ from __future__ import annotations +import json + from dataclasses import replace from datetime import UTC, datetime, timedelta from types import SimpleNamespace @@ -1029,3 +1031,63 @@ def test_source_first_derived_manifest_obeys_locked_limits(limit): derive_selected_pre_submit_input( lease, manifest_body=execution.manifest_body, manifest_sha256=execution.manifest_sha256, ) + + +@pytest.mark.parametrize("failure", ["high_confidence_secret_detected", "submission_archive_unchanged"]) +def test_source_first_default_blocker_does_not_validate_unrun_project_schema(failure): + from app.modules.checkers.api.default_checker import ( + WorkstreamDefaultCheckerResult, workstream_default_input_sha256, + ) + from app.modules.checkers.api.external import external_checker_json_hash + from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy + from app.modules.checkers.api.selected_pre_submit import ( + derive_selected_pre_submit_default_input, derive_selected_pre_submit_input, + ) + from tests.checkers.external.support import registry_entry + + reservation = _source_reservation() + execution = _source_completed_execution(reservation) + # This registered schema requires task_version, which the PRE input does not + # contain. Its incompatibility matters only if the selected project runs. + binding = reservation.policy.entries[0].model_copy(update={"registry": registry_entry()}) + body = reservation.policy.model_dump(mode="json", exclude={"policy_sha256"}) + body["entries"] = [binding.model_dump(mode="json")] + policy = LockedExternalPreSubmitPolicy.model_validate_json(json.dumps( + body | {"policy_sha256": external_checker_json_hash(body)} + )) + reservation = replace(reservation, policy=policy, admission_lineage=replace( + reservation.admission_lineage, effective_plan_sha256=policy.policy_sha256, + )) + if failure == "submission_archive_unchanged": + from app.modules.checkers.api.default_checker import WorkstreamDefaultPredecessor + predecessor = WorkstreamDefaultPredecessor( + new_record_id(), 1, reservation.source.raw_sha256, execution.manifest_sha256, + ) + reservation = replace( + reservation, default_context=replace( + reservation.default_context, predecessor=predecessor, current_predecessor=predecessor, + predecessor_exists=True, predecessor_rules_sha256=reservation.default_context.current_rules_sha256, + ), admission_lineage=replace( + reservation.admission_lineage, predecessor_submission_id=predecessor.submission_id, + predecessor_submission_version=1, checker_remediation_manifest_id=new_record_id(), + ), + ) + lease = SelectedPreSubmitLeaseFacts(reservation, execution.lease_id, 1, reservation.pre_deadline_at) + default_input = derive_selected_pre_submit_default_input( + lease, manifest_body=execution.manifest_body, manifest_sha256=execution.manifest_sha256, + ) + with pytest.raises(ValueError): + derive_selected_pre_submit_input( + lease, manifest_body=execution.manifest_body, manifest_sha256=execution.manifest_sha256, + ) + default = execution.workstream_default.model_dump() + checks = list(default["checks"]) + index = 2 if failure == "high_confidence_secret_detected" else 3 + checks[index] = checks[index] | {"status": "failed", "failure_code": failure, "finding_count": 1} + default.update(checks=tuple(checks), eligible=False) + execution = replace( + execution, request_digest=reservation.request_digest, policy_sha256=policy.policy_sha256, + workstream_default=WorkstreamDefaultCheckerResult.model_validate(default), + default_input_sha256=workstream_default_input_sha256(default_input), external_members=(), eligible=False, + ) + assert SelectedPreSubmitFinalizeFacts(lease, execution, None).execution == execution From 09968bd45ccef86bb7679dc78b0f1a07d6e3e447 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:11:05 +0100 Subject: [PATCH 066/513] Record combined PRE client review and remaining integration --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index af5d02b13..a2282e042 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1503,3 +1503,14 @@ controls fail: two default-blocker cases, one late-decode case and one oversized chunk case. Production code was restored after each probe. The expanded focused suite passes 124 cases; renewed review of these repairs remains pending. The broader native/ART/T4 integration and the retained old-path failure are unchanged. + +Architecture/security and QA/test-delta passed the repaired client scope at clean +`e29c637ae`. The targeted mutations discriminate all three repaired defects; +late synchronous decode is refused, not physically interrupted. The full runtime +module rerun at this candidate reports 31 passed and the same one obsolete +prepared-grant identity failure. Record/link checks pass and the ownership +partition remains unchanged. The combined native execution boundary is still +unfinished; the next work is the exact ART source-read grant/AUTH issuer and the +native single-session handler, followed by removing their obsolete prepared +callers and completing SQL/T4 custody. This evidence does not authorize a push +or readiness claim for the incomplete public cutover. From 9516273058202697b581b82b4b54b39f017318b7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:31:21 +0100 Subject: [PATCH 067/513] Authorize committed PRE source reads with scoped one-use grants --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 21 ++ backend/app/adapters/artifacts/__init__.py | 8 +- backend/app/adapters/artifacts/local.py | 8 +- .../artifacts/local_submission_source.py | 4 +- .../app/adapters/artifacts/s3_compatible.py | 9 +- backend/app/interfaces/artifacts.py | 7 +- .../artifacts/api/submission_intake.py | 31 ++ .../app/modules/artifacts/authorization.py | 74 ++--- .../selected_pre_submit_execution.py | 295 ++++++++++++------ .../pre_submit_materialization.py | 22 +- backend/app/modules/authorization/runtime.py | 41 +-- .../test_submission_intake_custody.py | 111 +++++++ .../test_pre_submit_attempt_authority.py | 48 ++- backend/tests/test_authorization.py | 85 ++--- backend/tests/test_checker_materialization.py | 159 ++++++++++ backend/tests/test_local_artifact_store.py | 11 +- 16 files changed, 622 insertions(+), 312 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a2282e042..f968ba344 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1514,3 +1514,24 @@ unfinished; the next work is the exact ART source-read grant/AUTH issuer and the native single-session handler, followed by removing their obsolete prepared callers and completing SQL/T4 custody. This evidence does not authorize a push or readiness claim for the incomplete public cutover. + +The ART source-read implementation now projects exact sealed-source, foreground +and execution fences into the existing fixed-materializer AUTH action. Issuance +consumes committed CHECKERS authority, rechecks locked TASK/ART custody, commits +the independent materializer audit, and only then exposes a one-use stream. +Reads enforce the earlier foreground/execution deadline, exact byte count and +64 KiB chunk ceiling outside database transactions. The provider port accepts a +smaller explicit read cap without changing source identity. + +Real PostgreSQL/local-provider integration passed authorized and denied service +cases (two tests), including independent NOWAIT TASK/ART lock probes during I/O +and visibility of the committed materializer audit. The guest is deliberately +replaced by a capacity-failure consumer in this proof; no native guest or success +handoff is claimed. Three real authorization tests passed, including revocation. +Controlled tests cover failed commit acknowledgement and changed custody. +A new abandoned-reader regression exposed that callback revocation alone left +an opened provider generator suspended. Callback exit now closes that generator +with cancellation-resistant cleanup before closing the authority adapter. +Owner/lane checks passed 229 tests. This source-read work remains pending scoped +review, and the native handler and obsolete public caller replacement remain +required before the coordinated cutover can be published. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index dceb715dd..d95c9dda5 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -488,7 +488,7 @@ async def runtime(): from app.adapters.auth import selected_pre_submit_authority from app.adapters.checkers import selected_pre_submit_checker_execution from app.modules.artifacts.selected_pre_submit_execution import ( - SelectedPreSubmitExecutionService, + SelectedPreSubmitExecutionService, SelectedPreSubmitSourceReads, ) from app.adapters.checkers import selected_pre_submit_coordinator @@ -528,7 +528,11 @@ async def runtime(): session=session, coordinator=selected_coordinator, authority=selected_pre_submit_authority(session), - materialization=materialization, + source_reads=SelectedPreSubmitSourceReads( + session=session, sources=submission_intake_pre_source_port(session), + authority=materialization_authority, store=store, + ), + execution=checker_execution, ), storage_scheme=storage_scheme, artifact_deadline_ms=int( diff --git a/backend/app/adapters/artifacts/local.py b/backend/app/adapters/artifacts/local.py index 6af06f7d1..cdd2fa52b 100644 --- a/backend/app/adapters/artifacts/local.py +++ b/backend/app/adapters/artifacts/local.py @@ -3,7 +3,7 @@ from __future__ import annotations import asyncio -from collections.abc import AsyncIterator +from collections.abc import AsyncGenerator, AsyncIterator from contextlib import contextmanager import errno import fcntl @@ -251,7 +251,9 @@ async def request_source_abort(self, upload: SubmissionSourceUpload, *, operation_evidence: ArtifactProviderOperationEvidence | None = None) -> None: await self._source_io(LocalSubmissionSource(self).abort, upload) - def open_source(self, source: SealedSubmissionSource, *, operation_evidence: ArtifactProviderOperationEvidence | None = None) -> AsyncIterator[bytes]: + def open_source(self, source: SealedSubmissionSource, *, operation_evidence: ArtifactProviderOperationEvidence | None = None, maximum_chunk_bytes: int = 64 * 1024) -> AsyncGenerator[bytes, None]: + if type(maximum_chunk_bytes) is not int or not 1 <= maximum_chunk_bytes <= 64 * 1024: + raise ValueError("source read chunk bound is invalid") source = SealedSubmissionSource.model_validate(source) helper = LocalSubmissionSource(self) helper.location(source.location) @@ -260,7 +262,7 @@ async def iterate() -> AsyncIterator[bytes]: position = 0 digest = hashlib.sha256() while position < source.raw_byte_count: - chunk = await self._source_io(helper.chunk, source, position) + chunk = await self._source_io(helper.chunk, source, position, maximum_chunk_bytes) if not chunk: raise ArtifactIntegrityError("submission source was truncated") position += len(chunk) diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py index 55a3a41bd..dd04f192e 100644 --- a/backend/app/adapters/artifacts/local_submission_source.py +++ b/backend/app/adapters/artifacts/local_submission_source.py @@ -301,7 +301,7 @@ def seal(self, directory: int) -> tuple[SubmissionSourceCompletion, SealedSubmis SealedSubmissionSource.model_validate_json(json.dumps(value["source"])), ) - def chunk(self, source: SealedSubmissionSource, position: int) -> bytes: + def chunk(self, source: SealedSubmissionSource, position: int, maximum_chunk_bytes: int) -> bytes: source = SealedSubmissionSource.model_validate(source) with self.locked(source.location) as directory: completion, sealed = self.seal(directory) @@ -314,7 +314,7 @@ def chunk(self, source: SealedSubmissionSource, position: int) -> bytes: if (sealed != source or self.source(completion, info) != source or info.st_size != source.raw_byte_count or stat.S_IMODE(info.st_mode) != 0o400): raise ArtifactIntegrityError("submission source generation mismatch") - return os.pread(descriptor, min(self.store._buffer_bytes, source.raw_byte_count - position), position) + return os.pread(descriptor, min(self.store._buffer_bytes, maximum_chunk_bytes, source.raw_byte_count - position), position) finally: os.close(descriptor) diff --git a/backend/app/adapters/artifacts/s3_compatible.py b/backend/app/adapters/artifacts/s3_compatible.py index 120a1b9d5..64000925e 100644 --- a/backend/app/adapters/artifacts/s3_compatible.py +++ b/backend/app/adapters/artifacts/s3_compatible.py @@ -3,7 +3,7 @@ from __future__ import annotations import asyncio -from collections.abc import AsyncIterator, Callable, Mapping +from collections.abc import AsyncGenerator, AsyncIterator, Callable, Mapping from contextlib import asynccontextmanager import datetime import hashlib @@ -791,8 +791,11 @@ async def observe_source_upload( def open_source( self, source: SealedSubmissionSource, *, operation_evidence: ArtifactProviderOperationEvidence | None = None, - ) -> AsyncIterator[bytes]: + maximum_chunk_bytes: int = 64 * 1024, + ) -> AsyncGenerator[bytes, None]: """Read one immutable version; verify the original ZIP at stream exhaustion.""" + if type(maximum_chunk_bytes) is not int or not 1 <= maximum_chunk_bytes <= 64 * 1024: + raise ValueError("source read chunk bound is invalid") source = SealedSubmissionSource.model_validate(source) self._source_key(source.location) evidence = operation_evidence or ArtifactProviderOperationEvidence() @@ -808,7 +811,7 @@ async def iterate() -> AsyncIterator[bytes]: async with response["Body"] as body: self._check_source_response(source, response) while True: - chunk = await body.read(min(self._buffer_bytes, source.raw_byte_count - observed + 1)) + chunk = await body.read(min(self._buffer_bytes, maximum_chunk_bytes, source.raw_byte_count - observed + 1)) if not chunk: break if type(chunk) is not bytes or observed + len(chunk) > source.raw_byte_count: diff --git a/backend/app/interfaces/artifacts.py b/backend/app/interfaces/artifacts.py index 062b8bdc4..99b626896 100644 --- a/backend/app/interfaces/artifacts.py +++ b/backend/app/interfaces/artifacts.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import AsyncIterator +from collections.abc import AsyncGenerator, AsyncIterator from dataclasses import dataclass import re from typing import Protocol @@ -395,8 +395,9 @@ async def complete_source_upload( def open_source( self, source: SealedSubmissionSource, *, operation_evidence: ArtifactProviderOperationEvidence | None = None, - ) -> AsyncIterator[bytes]: - """Read the exact authorized version with bounded raw identity verification.""" + maximum_chunk_bytes: int = 64 * 1024, + ) -> AsyncGenerator[bytes, None]: + """Yield closable exact-version reads, capped by maximum_chunk_bytes (1..64 KiB).""" async def observe_source_upload( self, completion: SubmissionSourceCompletion, *, diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py index cb87ffaed..e245ac5ba 100644 --- a/backend/app/modules/artifacts/api/submission_intake.py +++ b/backend/app/modules/artifacts/api/submission_intake.py @@ -165,6 +165,37 @@ def bounded_lease(self) -> Self: return self +class PreSubmitSourceReadFacts(_IntakeValue): + """Exact ART read authorization, distinct from CHECKERS execution authority.""" + + schema_version: Literal["workstream.pre_submit_source_read.v1"] = "workstream.pre_submit_source_read.v1" + source: SealedSubmissionSource + project_id: UUID + task_id: UUID + assignment_id: UUID + actor_profile_id: UUID + identity_link_id: UUID + metadata_sha256: Sha256 + locked_context_sha256: Sha256 + foreground_lease_id: UUID + foreground_lease_generation: int = Field(ge=1) + pre_deadline_at: AwareDatetime + run_id: UUID + request_digest: Sha256 + policy_sha256: Sha256 + execution_lease_id: UUID + execution_lease_generation: int = Field(ge=1) + execution_lease_expires_at: AwareDatetime + + @model_validator(mode="after") + def bounded_execution(self) -> Self: + """Keep source upload fencing and the immutable PRE deadline intact.""" + if (self.foreground_lease_generation < self.source.sealed_upload_fence + or self.execution_lease_expires_at > self.pre_deadline_at): + raise ValueError("PRE source read bounds differ") + return self + + class SubmissionIntakePreSourcePort(Protocol): """ART exact source participation in an authorized, caller-owned T3 root.""" diff --git a/backend/app/modules/artifacts/authorization.py b/backend/app/modules/artifacts/authorization.py index 1db535b34..012400319 100644 --- a/backend/app/modules/artifacts/authorization.py +++ b/backend/app/modules/artifacts/authorization.py @@ -28,10 +28,8 @@ ArtifactPutAttemptAuthorityFacts, ArtifactVerificationAuthorityFacts, ) -from app.modules.artifacts.submission_materialization import ( - PreSubmitMaterializationAuthorityFacts, - PreSubmitMaterializationPreparationFacts, -) +from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts + from app.modules.artifacts.submission_bindings import SubmissionBindingAuthorityFacts from app.modules.artifacts.api import SubmissionAdmissionConsumptionError from app.modules.authorization.catalogue import ACTION_BY_ID, ActionAvailability, ActionId @@ -56,7 +54,6 @@ GuideSourceIngestResourceContext, GuideSourceReadResourceContext, PreSubmitCheckerInputResourceContext, - PreSubmitCheckerInputPreparationContext, HumanAuthorizationContext, PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported, @@ -546,8 +543,7 @@ def __init__( self._handle: PreparedAuthorizationHandle | None = None self._facts: ( GuideSourceReadAuthorityFacts - | PreSubmitMaterializationAuthorityFacts - | PreSubmitMaterializationPreparationFacts + | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts | None ) = None @@ -556,7 +552,7 @@ async def prepare( self, *, facts: GuideSourceReadAuthorityFacts - | PreSubmitMaterializationPreparationFacts + | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts, idempotency_key: UUID, ) -> PreparedAuthorizationHandle: @@ -617,7 +613,7 @@ async def consume( *, prepared_authorization: PreparedAuthorizationHandle, facts: GuideSourceReadAuthorityFacts - | PreSubmitMaterializationAuthorityFacts + | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts, ) -> UUID | None: """Consume only the exact handle and facts prepared by this adapter.""" @@ -763,7 +759,7 @@ def __init__(self, session: AsyncSession, *, request_id: UUID, correlation_id: U async def prepare( self, *, - facts: PreSubmitMaterializationPreparationFacts, + facts: PreSubmitSourceReadFacts, idempotency_key: UUID, ) -> PreparedAuthorizationHandle: """Prepare authority from the locked scalar facts before ZIP inspection.""" @@ -773,7 +769,7 @@ async def consume( self, *, prepared_authorization: object, - facts: PreSubmitMaterializationAuthorityFacts, + facts: PreSubmitSourceReadFacts, ) -> None: """Consume authority only for the exact materializer and final facts.""" await self._delegate.consume( @@ -787,61 +783,29 @@ def close(self) -> None: def _artifact_service_resource_context( - facts: GuideSourceReadAuthorityFacts - | PreSubmitMaterializationAuthorityFacts - | PreSubmitMaterializationPreparationFacts - | SubmissionBindingAuthorityFacts, -) -> ( - GuideSourceReadResourceContext - | PreSubmitCheckerInputResourceContext - | PreSubmitCheckerInputPreparationContext - | SubmissionBindingResourceContext -): - """Compose the canonical AUTH resource context for fixed ART service facts.""" - values = asdict(facts) - if isinstance(facts, PreSubmitMaterializationAuthorityFacts): - values = asdict(facts.preparation) + facts: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts, +) -> GuideSourceReadResourceContext | PreSubmitCheckerInputResourceContext | SubmissionBindingResourceContext: + """Compose AUTH context for the exact fixed ART service operation.""" + if type(facts) is PreSubmitSourceReadFacts: return PreSubmitCheckerInputResourceContext( - resource_type="pre_submit_checker_input", - resource_id=facts.preparation.prepared_generation_id, - semantic_manifest_sha256=facts.semantic_manifest_sha256, - **values, - ) - if isinstance(facts, PreSubmitMaterializationPreparationFacts): - return PreSubmitCheckerInputPreparationContext( - resource_type="pre_submit_checker_input", - resource_id=facts.prepared_generation_id, - **values, + resource_id=facts.source.location.operation_id, + scope_project_id=facts.project_id, facts=facts, ) if isinstance(facts, SubmissionBindingAuthorityFacts): return SubmissionBindingResourceContext( - resource_type="submission_binding", - resource_id=facts.admission_id, - **asdict(facts), + resource_type="submission_binding", resource_id=facts.admission_id, **asdict(facts), ) return GuideSourceReadResourceContext( - resource_type="guide_source_read", - resource_id=facts.guide_source_item_id, - **values, + resource_type="guide_source_read", resource_id=facts.guide_source_item_id, **asdict(facts), ) def _prepared_artifact_facts_match( - prepared: GuideSourceReadAuthorityFacts - | PreSubmitMaterializationPreparationFacts - | PreSubmitMaterializationAuthorityFacts - | SubmissionBindingAuthorityFacts, - final: GuideSourceReadAuthorityFacts - | PreSubmitMaterializationAuthorityFacts - | SubmissionBindingAuthorityFacts, + prepared: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts, + final: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts, ) -> bool: - """Require final facts to preserve every fact bound during preparation.""" - if isinstance(prepared, PreSubmitMaterializationPreparationFacts): - return ( - isinstance(final, PreSubmitMaterializationAuthorityFacts) - and prepared == final.preparation - ) - return prepared == final + """Require source, lease and every locked fact to remain exactly prepared.""" + return type(prepared) is type(final) and prepared == final class PreparedArtifactInternalAuthority: diff --git a/backend/app/modules/artifacts/selected_pre_submit_execution.py b/backend/app/modules/artifacts/selected_pre_submit_execution.py index 5157f31f1..d783c87b4 100644 --- a/backend/app/modules/artifacts/selected_pre_submit_execution.py +++ b/backend/app/modules/artifacts/selected_pre_submit_execution.py @@ -1,124 +1,225 @@ -"""Selected PRE lease execution across short authority and owner transactions.""" +"""Authorized sealed-source reads and one foreground PRE execution.""" from __future__ import annotations +import asyncio +from collections.abc import AsyncGenerator, AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime +from typing import Protocol from uuid import UUID +from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from app.modules.artifacts.submission_materialization import ( - PreparedBundleMaterializationRequest, - PreparedBundleMaterializationService, +from app.core.cancellation import await_cancellation_resistant +from app.interfaces.artifacts import ArtifactStore, ArtifactStoreError +from app.interfaces.external_checker_execution import ( + ExternalPreSubmitSourceGrant, MAXIMUM_PRE_SOURCE_CHUNK_BYTES, ) +from app.modules.artifacts.api.submission_intake import ( + PreSubmitSourceReadFacts, SubmissionIntakePreSourcePort, +) +from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError +from app.modules.artifacts.intake.repository import IntakeCustodyConflict +from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitAuthorityPort, - SelectedPreSubmitCompletion, - SelectedPreSubmitCoordinationPort, - SelectedPreSubmitExecutionFacts, - SelectedPreSubmitFinalizeFacts, - SelectedPreSubmitInfrastructureUnavailable, + SelectedPreSubmitAuthorityPort, SelectedPreSubmitCompletion, + SelectedPreSubmitCoordinationPort, SelectedPreSubmitExecutionAuthority, + SelectedPreSubmitExecutionFacts, SelectedPreSubmitFinalizeFacts, + SelectedPreSubmitInfrastructureUnavailable, SelectedPreSubmitLeaseFacts, SelectedPreSubmitReservationFacts, ) +class PreSubmitSourceReadAuthorization(Protocol): + """The fixed ART materializer's distinct transaction-bound AUTH boundary.""" + + async def prepare(self, *, facts: PreSubmitSourceReadFacts, idempotency_key: UUID) -> object: ... + async def consume(self, *, prepared_authorization: object, facts: PreSubmitSourceReadFacts) -> None: ... + def close(self) -> None: ... + + +class PreSubmitProcessor(Protocol): + """CHECKERS processor composed through its existing adapter factory.""" + + async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmitExecutionFacts: ... + + +class PreSubmitExecutionFactory(Protocol): + """Keep the CHECKERS implementation out of ART's owner imports.""" + + def build(self, lease: SelectedPreSubmitLeaseFacts) -> PreSubmitProcessor: ... + + +def source_read_facts(lease: SelectedPreSubmitLeaseFacts) -> PreSubmitSourceReadFacts: + """Project the exact committed request and execution fence for ART AUTH.""" + reservation = lease.reservation + return PreSubmitSourceReadFacts( + source=reservation.source, project_id=reservation.project_id, task_id=reservation.task_id, + assignment_id=reservation.assignment_id, actor_profile_id=reservation.actor_profile_id, + identity_link_id=reservation.identity_link_id, metadata_sha256=reservation.metadata_sha256, + locked_context_sha256=reservation.locked_context_sha256, + foreground_lease_id=reservation.foreground_lease_id, + foreground_lease_generation=reservation.foreground_lease_generation, + pre_deadline_at=reservation.pre_deadline_at, run_id=reservation.attempt_id, + request_digest=reservation.request_digest, policy_sha256=reservation.policy_sha256, + execution_lease_id=lease.lease_id, execution_lease_generation=lease.lease_generation, + execution_lease_expires_at=lease.lease_expires_at, + ) + + +class _PreSubmitSourceGrant: + """One-use, nonserializable read issued only after its AUTH root commits.""" + + def __init__(self, *args, **kwargs) -> None: + raise TypeError("PRE source grants are issuer-owned") + + @classmethod + def _issued(cls, issuer, lease, expires_at, deadline): + value = object.__new__(cls) + value._issuer, value._lease = issuer, lease + value._expires_at, value._deadline = expires_at, deadline + value._claimed = False + value._revoked = False + value._reader = None + return value + + def _require_current(self) -> None: + if (self._revoked or self._issuer._session.in_transaction() + or asyncio.get_running_loop().time() >= self._deadline + or datetime.now(UTC) >= self._expires_at): + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + + def open_source(self, *, lease: SelectedPreSubmitLeaseFacts) -> AsyncGenerator[bytes, None]: + """Consume once, then keep every provider read outside DB transactions.""" + self._require_current() + if self._claimed or lease != self._lease: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + self._claimed = True + self._reader = self._read() + return self._reader + + async def _read(self) -> AsyncGenerator[bytes, None]: + reader = None + count = 0 + try: + self._require_current() + reader = self._issuer._store.open_source( + self._lease.reservation.source, maximum_chunk_bytes=MAXIMUM_PRE_SOURCE_CHUNK_BYTES, + ) + while True: + self._require_current() + try: + async with asyncio.timeout_at(self._deadline): + chunk = await anext(reader) + except StopAsyncIteration: + break + self._require_current() + if type(chunk) is not bytes or not 0 < len(chunk) <= MAXIMUM_PRE_SOURCE_CHUNK_BYTES: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + count += len(chunk) + if count > self._lease.reservation.source.raw_byte_count: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + yield chunk + if count != self._lease.reservation.source.raw_byte_count: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + except (ArtifactStoreError, TimeoutError) as exc: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") from exc + finally: + if reader is not None: + await await_cancellation_resistant(reader.aclose()) + + +class SelectedPreSubmitSourceReads: + """Authorize current TASK/ART source custody, then issue a committed read.""" + + def __init__( + self, *, session: AsyncSession, sources: SubmissionIntakePreSourcePort, + authority: PreSubmitSourceReadAuthorization, store: ArtifactStore, + ) -> None: + self._session, self._sources, self._authority, self._store = session, sources, authority, store + + @asynccontextmanager + async def issue( + self, *, lease: SelectedPreSubmitLeaseFacts, execution_authority: SelectedPreSubmitExecutionAuthority, + ) -> AsyncIterator[ExternalPreSubmitSourceGrant]: + """Require committed CHECKERS authority and a fresh, separately authorized ART read.""" + if self._session.in_transaction(): + raise RuntimeError("PRE source issuance requires no transaction") + checked = execution_authority.consume(run_id=lease.reservation.attempt_id, lease=lease) + if checked != lease: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + facts = source_read_facts(lease) + started = asyncio.get_running_loop().time() + grant = None + try: + async with self._session.begin(): + handle = await self._authority.prepare(facts=facts, idempotency_key=facts.run_id) + live = await self._sources.lock_pre_source( + source=facts.source, lease_id=facts.foreground_lease_id, + generation=facts.foreground_lease_generation, + ) + names = ("source", "project_id", "task_id", "assignment_id", "actor_profile_id", + "identity_link_id", "metadata_sha256", "locked_context_sha256", "pre_deadline_at") + if (any(getattr(live, name) != getattr(facts, name) for name in names) + or live.lease_id != facts.foreground_lease_id + or live.lease_generation != facts.foreground_lease_generation): + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + expires_at = min(live.lease_expires_at, lease.lease_expires_at, live.pre_deadline_at) + now = await self._session.scalar(select(func.clock_timestamp())) + if now is None or expires_at <= now: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") + deadline = started + (expires_at - now).total_seconds() + await self._authority.consume(prepared_authorization=handle, facts=facts) + # No grant exists if commit fails, including a lost acknowledgement. + grant = _PreSubmitSourceGrant._issued(self, lease, expires_at, deadline) + grant._require_current() + yield grant + except (ArtifactAuthorityDeniedError, IntakeCustodyConflict, TaskSubmissionContextUnavailable) as exc: + raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") from exc + finally: + try: + if grant is not None: + grant._revoked = True + if grant._reader is not None: + await await_cancellation_resistant(grant._reader.aclose()) + finally: + self._authority.close() + + class SelectedPreSubmitExecutionService: - """Claim, execute and finalize one selected run without holding a DB root.""" + """Claim, authorize source, execute once and finalize using short roots.""" def __init__( - self, - *, - session: AsyncSession, - coordinator: SelectedPreSubmitCoordinationPort, - authority: SelectedPreSubmitAuthorityPort, - materialization: PreparedBundleMaterializationService, + self, *, session: AsyncSession, coordinator: SelectedPreSubmitCoordinationPort, + authority: SelectedPreSubmitAuthorityPort, source_reads: SelectedPreSubmitSourceReads, + execution: PreSubmitExecutionFactory, ) -> None: - self._session = session - self._coordinator = coordinator - self._authority = authority - self._materialization = materialization - - async def execute( - self, - *, - reservation: SelectedPreSubmitReservationFacts, - materialization: PreparedBundleMaterializationRequest, - ) -> SelectedPreSubmitCompletion: - """Use short claim/finalize roots around one process-local ART execution.""" + self._session, self._coordinator, self._authority = session, coordinator, authority + self._source_reads, self._execution = source_reads, execution + + async def execute(self, *, reservation: SelectedPreSubmitReservationFacts) -> SelectedPreSubmitCompletion: + """Use fresh fixed-service roots around one foreground source invocation.""" run_id = reservation.attempt_id async with self._session.begin(): - # Preparing the fixed principal precedes CHECKERS' TASK/run locks. async with self._authority.prepare_execution(reservation) as prepared: - lease = await self._coordinator.claim( - run_id=run_id, - facts=reservation, - authority=prepared, - ) - - execution: SelectedPreSubmitExecutionFacts | None = None - infrastructure_failure_code: str | None = None + lease = await self._coordinator.claim(run_id=run_id, facts=reservation, authority=prepared) + execution = None + failure = None try: - capability = await self._coordinator.committed_execution( - run_id=run_id, lease=lease - ) - execution = await self._materialization.materialize_selected_pre_submit( - materialization, - run_id=run_id, - lease=lease, - execution_authority=capability, - ) + capability = await self._coordinator.committed_execution(run_id=run_id, lease=lease) + async with self._source_reads.issue(lease=lease, execution_authority=capability) as grant: + execution = await self._execution.build(lease).process(grant) except SelectedPreSubmitInfrastructureUnavailable as exc: - infrastructure_failure_code = exc.code - - finalize_facts = SelectedPreSubmitFinalizeFacts( - lease=lease, - execution=execution, - infrastructure_failure_code=infrastructure_failure_code, - ) - async with self._session.begin(): - async with self._authority.prepare_finalization( - finalize_facts - ) as prepared: - return await self._coordinator.finalize( - run_id=run_id, - lease=lease, - authority=prepared, - execution=execution, - infrastructure_failure_code=infrastructure_failure_code, - ) - - async def recover_expired( - self, - *, - run_id: UUID, - reservation: SelectedPreSubmitReservationFacts, - ) -> SelectedPreSubmitCompletion: - """Finalize a crashed lease without recreating its process-local grant.""" - if run_id != reservation.attempt_id: - raise SelectedPreSubmitInfrastructureUnavailable( - "material_unavailable" - ) - async with self._session.begin(): - lease = await self._coordinator.read_expired_lease( - run_id=reservation.attempt_id, - facts=reservation, - ) - - finalize_facts = SelectedPreSubmitFinalizeFacts( - lease=lease, - execution=None, - infrastructure_failure_code="deadline_exceeded", - ) + failure = exc.code + facts = SelectedPreSubmitFinalizeFacts(lease=lease, execution=execution, infrastructure_failure_code=failure) async with self._session.begin(): - async with self._authority.prepare_finalization( - finalize_facts - ) as prepared: + async with self._authority.prepare_finalization(facts) as prepared: return await self._coordinator.finalize( - run_id=reservation.attempt_id, - lease=lease, - authority=prepared, - execution=None, - infrastructure_failure_code="deadline_exceeded", + run_id=run_id, lease=lease, authority=prepared, execution=execution, + infrastructure_failure_code=failure, ) -__all__ = ("SelectedPreSubmitExecutionService",) +__all__ = ("SelectedPreSubmitExecutionService", "SelectedPreSubmitSourceReads", "source_read_facts") diff --git a/backend/app/modules/authorization/pre_submit_materialization.py b/backend/app/modules/authorization/pre_submit_materialization.py index f7a21896a..554e02fb1 100644 --- a/backend/app/modules/authorization/pre_submit_materialization.py +++ b/backend/app/modules/authorization/pre_submit_materialization.py @@ -3,11 +3,10 @@ import json from uuid import UUID -from app.core.hashing import canonical_json_hash from app.modules.authorization.catalogue import ActionId from app.modules.authorization.domain.resource_digest import authorization_resource_digest from app.modules.authorization.runtime import ( - PreSubmitCheckerInputPreparationContext, TaskImportSourceResourceContext, + TaskImportSourceResourceContext, PreSubmitCheckerInputResourceContext, SubmissionBindingResourceContext, SubmissionCreationResourceContext, ) @@ -20,18 +19,11 @@ def parse_materialization_binding(raw: dict, invalid_error) -> tuple[dict, str]: """Parse and digest exact checker-materialization preparation facts.""" try: - value = dict(raw) - for field in ( - "resource_id", "task_id", "assignment_id", "project_id", "guide_id", - "source_snapshot_id", "submission_artifact_policy_id", "checker_policy_id", - "prepared_generation_id", - ): - value[field] = UUID(str(value[field])) - resource = PreSubmitCheckerInputPreparationContext.model_validate(value) - except (KeyError, TypeError, ValueError) as exc: + resource = PreSubmitCheckerInputResourceContext.model_validate_json(json.dumps(raw)) + except (TypeError, ValueError) as exc: raise invalid_error("invalid prepared authorization handle") from exc context = resource.model_dump(mode="json") - return context, canonical_json_hash({"pre_submit_checker_input_preparation": context}) + return context, authorization_resource_digest(resource) def parse_prepared_artifact_bindings(action_id: ActionId, raw: dict, invalid_error) -> dict: @@ -83,12 +75,6 @@ def exact_artifact_binding_matches( | SubmissionCreationResourceContext, ) -> bool: """Require every materialization fact to equal the prepared request.""" - if isinstance(resource, PreSubmitCheckerInputResourceContext): - context = resource.model_dump(mode="json", exclude={"semantic_manifest_sha256"}) - return prepared_context == context and ( - prepared_digest - == canonical_json_hash({"pre_submit_checker_input_preparation": context}) - ) context = resource.model_dump(mode="json") return prepared_context == context and ( prepared_digest == authorization_resource_digest(resource) diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py index 428fc8986..064cd4a16 100644 --- a/backend/app/modules/authorization/runtime.py +++ b/backend/app/modules/authorization/runtime.py @@ -7,6 +7,7 @@ from uuid import UUID from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator +from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts from app.modules.authorization.domain.guide_compilation import ProjectGuideCompilationExecuteResourceContext, ProjectGuideCompilationRequestResourceContext from app.modules.authorization.domain.resource_digest import authorization_resource_digest as authorization_resource_digest from app.modules.authorization.domain.guide_proposals import GuideProposalResourceContext @@ -1024,44 +1025,24 @@ class ProjectRoleGrantRevokeResourceContext(BaseModel): version: Literal[1, 2] -class PreSubmitCheckerInputPreparationContext(BaseModel): - """Pre-inspection facts used to lock materializer authority.""" +class PreSubmitCheckerInputResourceContext(BaseModel): + """Exact sealed source and PRE lease authorized for the ART materializer.""" model_config = _STRICT_FROZEN - resource_type: Literal["pre_submit_checker_input"] + resource_type: Literal["pre_submit_checker_input"] = "pre_submit_checker_input" resource_id: UUID - task_id: UUID - assignment_id: UUID - project_id: UUID - guide_id: UUID - guide_version: str = Field(min_length=1, max_length=50) - source_snapshot_id: UUID - source_snapshot_hash: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - submission_artifact_policy_id: UUID - submission_artifact_policy_hash: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - checker_policy_id: UUID - checker_policy_hash: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - prepared_generation_id: UUID - plan_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - catalogue_manifest_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - archive_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - archive_byte_count: int = Field(ge=0) - storage_scheme: Literal["local", "s3"] + scope_project_id: UUID + facts: PreSubmitSourceReadFacts @model_validator(mode="after") - def bind_prepared_generation(self): - """Use the process-local prepared generation as the opaque selector.""" - if self.resource_id != self.prepared_generation_id: - raise ValueError("pre-submit checker input resource must match generation") + def bind_source_operation(self): + """Use the operation-owned immutable source as the opaque read selector.""" + if (self.resource_id != self.facts.source.location.operation_id + or self.scope_project_id != self.facts.project_id): + raise ValueError("pre-submit checker input resource differs from source") return self -class PreSubmitCheckerInputResourceContext(PreSubmitCheckerInputPreparationContext): - """Exact inspected contributor bundle authorized for checker materialization.""" - - semantic_manifest_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - - AuthorizationResourceContext = ( ReviewLifecycleActivationContract | contribution_reads.ContributionSelfReadResourceContext | contribution_reads.ContributionProjectReadResourceContext | checker_models.CheckerModelCallResourceContext diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 08f1afd63..1c76164a5 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -1310,3 +1310,114 @@ async def _assert_pre_terminal_guards(intake, request): ) assert completion.terminal.outcome == "infrastructure_failed" assert completion.capability is None + + +@pytest.mark.parametrize("intake", [True], indirect=True) +@pytest.mark.parametrize("materializer_enabled", [True, False]) +async def test_source_pre_execution_uses_committed_authorized_local_read(intake, materializer_enabled): + """Real source/SQL/AUTH composition with an explicitly failing runtime double.""" + from contextlib import aclosing + from app.adapters.artifacts import submission_intake_pre_source_port + from app.adapters.auth import selected_pre_submit_authority + from app.adapters.checkers import selected_pre_submit_coordinator, SelectedPreSubmitCheckerExecutionAdapter + from app.adapters.projects import project_locked_policy_context_port + from app.modules.actors.api import ServiceIdentity + from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization + from app.modules.artifacts.selected_pre_submit_admission import ( + bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, + ) + from app.modules.artifacts.selected_pre_submit_execution import ( + SelectedPreSubmitSourceReads, SelectedPreSubmitExecutionService, + ) + from app.modules.authorization.catalogue import ActionId + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest + from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest + from tests.artifact_store_helpers import initialize_local_store + from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer + from tests.checkers.execution.support import provision_post_submit_service + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + store = initialize_local_store(root=intake.durable_root, buffer_bytes=256 * 1024) + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation, foreground_lease = UUID(row.id), UUID(row.lease_id) + metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + key = UUID(row.idempotency_key) + source = await foreground_upload(intake, store).receive( + operation, foreground_lease, 1, foreground_bytes(), **foreground_limits(), + ) + async with intake.factory.begin() as session: + task = await task_submission_context_port(session).lock_submission_context( + TaskSubmissionContextRequest(intake.task, intake.assignment, intake.actor.actor_profile_id, None), + ) + references = task.locked_project_context + project = await project_locked_policy_context_port(session).lock_locked_policy_context( + ProjectLockedPolicyContextRequest(**{name: getattr(references, name) for name in ( + "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", + "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", "pre_submit_policy_bundle_hash", + )}), + ) + custody = await submission_intake_pre_source_port(session).lock_pre_source( + source=source, lease_id=foreground_lease, generation=1, + ) + selected = bind_selected_pre_submit_admission( + task=task, project=project, predecessor=None, predecessor_rules_sha256=None, + predecessor_exists=False, packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + ) + request = build_selected_pre_submit_reservation( + source=custody, metadata=metadata, task=task, project=project, + attempt_id=new_record_id(), idempotency_key=key, selected=selected, + runtime_profile=_source_reservation().runtime_profile, + ) + await selected_pre_submit_coordinator(session).reserve(request) + await provision_post_submit_service(intake.factory, ServiceIdentity.CHECKER_PRE_SUBMIT) + if materializer_enabled: + await _seed_materializer(intake.factory) + observed = [] + async with intake.factory() as session: + class ObservedStore: + def open_source(self, actual, *, maximum_chunk_bytes): + assert actual == source and not session.in_transaction() + assert maximum_chunk_bytes == 64 * 1024 + async def chunks(): + async with intake.factory.begin() as probe: + # Independent NOWAIT locks prove provider reads do not + # retain TASK or intake locks from either AUTH root. + for sql, params in ( + ("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE NOWAIT", {"id": intake.task}), + ("SELECT id FROM submission_intake_operations WHERE id=:id FOR UPDATE NOWAIT", {"id": operation}), + ): + assert (await probe.execute(text(sql), params)).one() + assert await probe.scalar(text( + "SELECT count(*) FROM audit_events WHERE action_id=:action AND resource_id=:id" + ), {"action": ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE.value, "id": str(operation)}) == 1 + async with aclosing(store.open_source(actual, maximum_chunk_bytes=maximum_chunk_bytes)) as reader: + async for chunk in reader: + observed.append(chunk) + yield chunk + return chunks() + class RuntimeFailure: + async def execute_pre(self, lease, grant): + async with aclosing(grant.open_source(lease=lease)) as reader: + assert b"".join([chunk async for chunk in reader]) == b"original source bytes" + raise SelectedPreSubmitInfrastructureUnavailable("capacity_exceeded") + authority = PreparedPreSubmitMaterializationAuthorization( + session, request_id=new_record_id(), correlation_id=new_record_id(), + ) + service = SelectedPreSubmitExecutionService( + session=session, coordinator=selected_pre_submit_coordinator(session), + authority=selected_pre_submit_authority(session), + source_reads=SelectedPreSubmitSourceReads( + session=session, sources=submission_intake_pre_source_port(session), + authority=authority, store=ObservedStore(), + ), execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=RuntimeFailure()), + ) + result = await service.execute(reservation=request) + assert result.capability is None and result.terminal.outcome == "infrastructure_failed" + assert result.terminal.infrastructure_failure_code == ( + "capacity_exceeded" if materializer_enabled else "material_unavailable" + ) + assert bool(observed) == materializer_enabled + store.close() diff --git a/backend/tests/authorization/test_pre_submit_attempt_authority.py b/backend/tests/authorization/test_pre_submit_attempt_authority.py index e539dc0db..a909fa108 100644 --- a/backend/tests/authorization/test_pre_submit_attempt_authority.py +++ b/backend/tests/authorization/test_pre_submit_attempt_authority.py @@ -1,8 +1,7 @@ -"""Real AUTH custody across the three POL-07A materialization transactions.""" +"""Real fixed-service AUTH for exact sealed-source PRE reads.""" from __future__ import annotations -from dataclasses import replace from datetime import UTC, datetime from uuid import uuid4 @@ -15,25 +14,21 @@ from app.modules.actors.api import ServiceIdentity from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError -from app.modules.artifacts.submission_materialization import PreSubmitMaterializationAuthorityFacts +from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts from app.modules.authorization.catalogue import ActionId from app.modules.authorization.models import AuthorityIdempotencyRecord from app.modules.tasks.models import AuditEvent -def _facts() -> PreSubmitMaterializationAuthorityFacts: - return PreSubmitMaterializationAuthorityFacts( - task_id=uuid4(), assignment_id=uuid4(), project_id=uuid4(), guide_id=uuid4(), - guide_version="1", source_snapshot_id=uuid4(), - source_snapshot_hash="sha256:" + "1" * 64, - submission_artifact_policy_id=uuid4(), - submission_artifact_policy_hash="sha256:" + "2" * 64, - checker_policy_id=uuid4(), checker_policy_hash="sha256:" + "3" * 64, - prepared_generation_id=uuid4(), plan_sha256="sha256:" + "4" * 64, - catalogue_manifest_sha256="sha256:" + "5" * 64, - archive_sha256="sha256:" + "6" * 64, archive_byte_count=10, - storage_scheme="s3", semantic_manifest_sha256="sha256:" + "7" * 64, - ) +def _facts() -> PreSubmitSourceReadFacts: + from app.modules.artifacts.selected_pre_submit_execution import source_read_facts + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + reservation = _source_reservation() + return source_read_facts(SelectedPreSubmitLeaseFacts( + reservation, new_record_id(), 1, reservation.pre_deadline_at, + )) async def _seed_materializer(factory: async_sessionmaker) -> str: @@ -55,12 +50,12 @@ async def _seed_materializer(factory: async_sessionmaker) -> str: async def _consume(session, authority, facts, key, *, reject_wrong_generation=False): async with session.begin(): - handle = await authority.prepare(facts=facts.preparation, idempotency_key=key) + handle = await authority.prepare(facts=facts, idempotency_key=key) if reject_wrong_generation: with pytest.raises(ArtifactAuthorityDeniedError, match="invalid"): await authority.consume( prepared_authorization=handle, - facts=replace(facts, prepared_generation_id=uuid4()), + facts=facts.model_copy(update={"execution_lease_generation": facts.execution_lease_generation + 1}), ) await authority.consume(prepared_authorization=handle, facts=facts) return handle @@ -77,10 +72,10 @@ async def _revoke(factory: async_sessionmaker, link_id: str) -> None: ) -async def test_real_materializer_consumes_inspection_execution_and_original_replay_authority( +async def test_real_materializer_audits_each_exact_source_read_authorization( clean_postgres_database: str, ) -> None: - """One ART key authorizes three fresh AUTH consumes and three distinct audit events.""" + """Exact source read authority is rechecked and audited for every consume.""" engine = create_async_engine(clean_postgres_database) factory = async_sessionmaker(engine, expire_on_commit=False) try: @@ -97,12 +92,7 @@ async def test_real_materializer_consumes_inspection_execution_and_original_repl session, authority, original, key, reject_wrong_generation=True, ) execution_handle = await _consume(session, authority, original, key) - retry = replace(original, prepared_generation_id=uuid4()) - assert retry.prepared_generation_id != original.prepared_generation_id - replay_handle = await _consume( - session, authority, - replace(retry, prepared_generation_id=original.prepared_generation_id), key, - ) + replay_handle = await _consume(session, authority, original, key) finally: authority.close() assert len({id(inspected_handle), id(execution_handle), id(replay_handle)}) == 3 @@ -118,7 +108,7 @@ async def test_real_materializer_consumes_inspection_execution_and_original_repl # This fixed-service read authority audits every consume; ART owns # durable idempotency, so AUTH has no mutation reservation for key. assert all(event.idempotency_reference is None for event in events) - assert all(event.resource_id == str(original.prepared_generation_id) for event in events) + assert all(event.resource_id == str(original.source.location.operation_id) for event in events) assert len({event.id for event in events}) == 3 assert (await session.scalars(select(AuthorityIdempotencyRecord))).all() == [] finally: @@ -126,7 +116,7 @@ async def test_real_materializer_consumes_inspection_execution_and_original_repl @pytest.mark.parametrize("completed_consumes", (1, 2)) -async def test_real_materializer_revocation_denies_next_phase_or_completed_replay( +async def test_real_materializer_revocation_denies_next_source_read( clean_postgres_database: str, completed_consumes: int, ) -> None: """A committed earlier audit never carries authority past a revoked service link.""" @@ -145,7 +135,7 @@ async def test_real_materializer_revocation_denies_next_phase_or_completed_repla await _revoke(factory, link_id) async with session.begin(): with pytest.raises(ArtifactAuthorityDeniedError): - await authority.prepare(facts=facts.preparation, idempotency_key=key) + await authority.prepare(facts=facts, idempotency_key=key) finally: authority.close() async with factory() as session: diff --git a/backend/tests/test_authorization.py b/backend/tests/test_authorization.py index 66011119b..0731008a5 100644 --- a/backend/tests/test_authorization.py +++ b/backend/tests/test_authorization.py @@ -97,9 +97,6 @@ PreparedGuideSourceReadAuthorization, PreparedPreSubmitMaterializationAuthorization, ) -from app.modules.artifacts.submission_materialization import ( - PreSubmitMaterializationAuthorityFacts, -) from app.modules.artifacts.schemas import ( ArtifactAuthorityDeniedError, GuideSourceReadAuthorityFacts, @@ -214,7 +211,6 @@ ActorStatus, ArtifactVerificationJobResourceContext, GuideSourceReadResourceContext, - PreSubmitCheckerInputPreparationContext, PreSubmitCheckerInputResourceContext, AdminRoleDefinitionsResourceContext, AdminRoleGrantCollectionResourceContext, @@ -4739,7 +4735,7 @@ async def revalidate(current: ServiceAuthorizationContext, _action: ActionId): @pytest.mark.asyncio -async def test_real_prepared_materializer_binds_preflight_and_final_evidence() -> None: +async def test_real_prepared_materializer_binds_exact_source_read_evidence() -> None: context = _runtime_context( actor_kind=ActorKind.SERVICE, service_identity=ServiceIdentity.ARTIFACT_MATERIALIZER, @@ -4775,37 +4771,15 @@ async def lock_request_actor(self, identity_link_id, actor_profile_id): authorization, repository, ) - generation_id = new_record_id() - common = { - "resource_type": "pre_submit_checker_input", - "resource_id": generation_id, - "task_id": new_record_id(), - "assignment_id": new_record_id(), - "project_id": new_record_id(), - "guide_id": new_record_id(), - "guide_version": "v0.1", - "source_snapshot_id": new_record_id(), - "source_snapshot_hash": "sha256:" + "1" * 64, - "submission_artifact_policy_id": new_record_id(), - "submission_artifact_policy_hash": "sha256:" + "2" * 64, - "checker_policy_id": new_record_id(), - "checker_policy_hash": "sha256:" + "3" * 64, - "prepared_generation_id": generation_id, - "plan_sha256": "sha256:" + "4" * 64, - "catalogue_manifest_sha256": "sha256:" + "5" * 64, - "archive_sha256": "sha256:" + "6" * 64, - "archive_byte_count": 10, - "storage_scheme": "s3", - } - preflight = PreSubmitCheckerInputPreparationContext(**common) - assert preflight.guide_version == common["guide_version"] + from tests.authorization.test_pre_submit_attempt_authority import _facts + facts = _facts() + generation_id = facts.source.location.operation_id final = PreSubmitCheckerInputResourceContext( - **common, - semantic_manifest_sha256="sha256:" + "7" * 64, + resource_id=generation_id, scope_project_id=facts.project_id, facts=facts, ) caller = PreparedAuthorizationInput( idempotency_key=new_record_id(), - request_value=preflight.model_dump(mode="json"), + request_value=final.model_dump(mode="json"), ) scope = PreparedAuthorityScope( kind=PreparedAuthorityScopeKind.ARTIFACT_INTERNAL, @@ -4822,7 +4796,7 @@ async def lock_request_actor(self, identity_link_id, actor_profile_id): handle, ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE, caller, - final.model_copy(update={"assignment_id": new_record_id()}), + final.model_copy(update={"facts": facts.model_copy(update={"assignment_id": new_record_id()})}), ) decision = await prepared.consume( handle, @@ -4838,9 +4812,9 @@ async def lock_request_actor(self, identity_link_id, actor_profile_id): ) assert evidence.events[0].resource_type == "pre_submit_checker_input" assert evidence.events[0].resource_id == str(generation_id) - assert evidence.events[0].project_id == str(final.project_id) + assert evidence.events[0].project_id == str(final.scope_project_id) assert evidence.events[0].target_ref_kind == "project" - assert evidence.events[0].target_ref_id == str(final.project_id) + assert evidence.events[0].target_ref_id == str(final.scope_project_id) with pytest.raises(PreparedAuthorizationHandleInvalid): await prepared.consume( handle, @@ -5208,46 +5182,28 @@ def close(self) -> None: fixed_context, ) monkeypatch.setattr(artifact_authorization, "PreparedAuthorizationService", FakePrepared) - facts = PreSubmitMaterializationAuthorityFacts( - task_id=new_record_id(), - assignment_id=new_record_id(), - project_id=new_record_id(), - guide_id=new_record_id(), - guide_version="1", - source_snapshot_id=new_record_id(), - source_snapshot_hash="sha256:" + "1" * 64, - submission_artifact_policy_id=new_record_id(), - submission_artifact_policy_hash="sha256:" + "2" * 64, - checker_policy_id=new_record_id(), - checker_policy_hash="sha256:" + "3" * 64, - prepared_generation_id=new_record_id(), - plan_sha256="sha256:" + "4" * 64, - catalogue_manifest_sha256="sha256:" + "5" * 64, - archive_sha256="sha256:" + "6" * 64, - archive_byte_count=10, - semantic_manifest_sha256="sha256:" + "7" * 64, - storage_scheme="s3", - ) + from tests.authorization.test_pre_submit_attempt_authority import _facts + facts = _facts() authority = PreparedPreSubmitMaterializationAuthorization( session, # type: ignore[arg-type] request_id=new_record_id(), correlation_id=new_record_id(), ) - handle = await authority.prepare(facts=facts.preparation, idempotency_key=new_record_id()) + handle = await authority.prepare(facts=facts, idempotency_key=new_record_id()) prepared_instance = prepared_instances[0] prepared_action, caller_input, scope = prepared_instance.prepared_args assert prepared_action is ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE - assert caller_input.request_value == PreSubmitCheckerInputPreparationContext( + assert caller_input.request_value == PreSubmitCheckerInputResourceContext( resource_type="pre_submit_checker_input", - resource_id=facts.prepared_generation_id, - **asdict(facts.preparation), + resource_id=facts.source.location.operation_id, + scope_project_id=facts.project_id, facts=facts, ).model_dump(mode="json") assert scope == PreparedAuthorityScope( kind=PreparedAuthorityScopeKind.ARTIFACT_INTERNAL, artifact_resource_type="pre_submit_checker_input", - artifact_resource_id=facts.prepared_generation_id, + artifact_resource_id=facts.source.location.operation_id, ) - for field_name in facts.preparation.__dataclass_fields__: + for field_name in type(facts).model_fields: original = getattr(facts, field_name) changed = ( new_record_id() @@ -5257,7 +5213,7 @@ def close(self) -> None: with pytest.raises(ArtifactAuthorityDeniedError, match="invalid"): await authority.consume( prepared_authorization=handle, - facts=replace(facts, **{field_name: changed}), + facts=facts.model_copy(update={field_name: changed}), ) await authority.consume( prepared_authorization=handle, @@ -5268,9 +5224,8 @@ def close(self) -> None: assert consumed_input is caller_input assert consumed_resource == PreSubmitCheckerInputResourceContext( resource_type="pre_submit_checker_input", - resource_id=facts.prepared_generation_id, - **asdict(facts.preparation), - semantic_manifest_sha256=facts.semantic_manifest_sha256, + resource_id=facts.source.location.operation_id, + scope_project_id=facts.project_id, facts=facts, ) with pytest.raises(ArtifactAuthorityDeniedError, match="invalid"): await authority.consume( diff --git a/backend/tests/test_checker_materialization.py b/backend/tests/test_checker_materialization.py index 05ff9011c..5a4f5bacb 100644 --- a/backend/tests/test_checker_materialization.py +++ b/backend/tests/test_checker_materialization.py @@ -255,3 +255,162 @@ def fail(tree): assert escaped._content == {} assert list((tmp_path / "scratch" / "workspaces").iterdir()) == [] manager.close() + + +def _source_read_fixture(*, failure=None): + """Controlled commit/authority boundaries; provider I/O is explicitly simulated.""" + from contextlib import asynccontextmanager + from datetime import UTC, datetime + from types import SimpleNamespace + import hashlib + from app.core.identifiers import new_record_id + from app.modules.artifacts.api.submission_intake import SubmissionIntakePreSourceFacts + from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError + from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitSourceReads + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + events = [] + payload = b"authorized original bytes" + reservation = _source_reservation() + reservation = replace(reservation, source=reservation.source.model_copy(update={ + "raw_sha256": "sha256:" + hashlib.sha256(payload).hexdigest(), "raw_byte_count": len(payload), + })) + lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at) + class Session: + active = False + def in_transaction(self): + return self.active + @asynccontextmanager + async def begin(self): + assert not self.active + self.active = True + events.append("begin") + try: + yield self + if failure == "commit": + raise RuntimeError("commit acknowledgement lost") + events.append("commit") + finally: + self.active = False + async def scalar(self, query): + assert self.active + return datetime.now(UTC) + session = Session() + class Authority: + async def prepare(self, *, facts, idempotency_key): + assert session.active and facts.run_id == idempotency_key + events.append("prepare") + if failure == "authority": + raise ArtifactAuthorityDeniedError("source read denied") + return self + async def consume(self, *, prepared_authorization, facts): + assert prepared_authorization is self and session.active + events.append("consume") + def close(self): + events.append("close_authority") + class Sources: + async def lock_pre_source(self, **kwargs): + assert session.active + events.append("lock_source") + return SubmissionIntakePreSourceFacts( + source=reservation.source, project_id=reservation.project_id, + task_id=new_record_id() if failure == "source" else reservation.task_id, + assignment_id=reservation.assignment_id, actor_profile_id=reservation.actor_profile_id, + identity_link_id=reservation.identity_link_id, metadata_sha256=reservation.metadata_sha256, + locked_context_sha256=reservation.locked_context_sha256, + lease_id=reservation.foreground_lease_id, lease_generation=reservation.foreground_lease_generation, + lease_expires_at=reservation.pre_deadline_at, pre_deadline_at=reservation.pre_deadline_at, + ) + class Capability: + consumed = False + def consume(self, *, run_id, lease): + assert not self.consumed and run_id == lease.reservation.attempt_id + self.consumed = True + return lease + class Store: + def open_source(self, source, *, maximum_chunk_bytes): + assert not session.active and events.index("commit") > events.index("consume") + assert source == reservation.source and maximum_chunk_bytes == 64 * 1024 + events.append("open_source") + async def chunks(): + try: + yield payload + finally: + events.append("close_source") + return chunks() + return SimpleNamespace( + issuer=SelectedPreSubmitSourceReads(session=session, sources=Sources(), authority=Authority(), store=Store()), + session=session, lease=lease, capability=Capability(), events=events, payload=payload, + ) + + +@pytest.mark.asyncio +async def test_pre_source_grant_requires_commit_and_is_one_use_and_callback_scoped(): + from app.core.identifiers import new_record_id + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + + value = _source_read_fixture() + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant: + assert value.events == ["begin", "prepare", "lock_source", "consume", "commit"] + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable): + grant.open_source(lease=replace(value.lease, lease_id=new_record_id())) + reader = grant.open_source(lease=value.lease) + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable): + grant.open_source(lease=value.lease) + assert b"".join([chunk async for chunk in reader]) == value.payload + assert value.events[-2:] == ["close_source", "close_authority"] + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable): + grant.open_source(lease=value.lease) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["authority", "source", "commit"]) +async def test_pre_source_grant_never_exposes_bytes_before_authorized_commit(failure): + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + + value = _source_read_fixture(failure=failure) + error = RuntimeError if failure == "commit" else SelectedPreSubmitInfrastructureUnavailable + with pytest.raises(error): + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability): + raise AssertionError("uncommitted or unauthorized source grant escaped") + assert "open_source" not in value.events + assert "commit" not in value.events + if failure != "commit": + assert "consume" not in value.events + + +@pytest.mark.asyncio +async def test_pre_source_grant_refuses_reads_in_database_transaction(): + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + + value = _source_read_fixture() + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant: + async with value.session.begin(): + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable): + grant.open_source(lease=value.lease) + assert "open_source" not in value.events + + +@pytest.mark.asyncio +async def test_pre_source_grant_closes_abandoned_reader_when_callback_ends(): + value = _source_read_fixture() + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant: + reader = grant.open_source(lease=value.lease) + assert await anext(reader) == value.payload + assert "close_source" not in value.events + assert value.events[-2:] == ["close_source", "close_authority"] + with pytest.raises(StopAsyncIteration): + await anext(reader) + + +@pytest.mark.asyncio +async def test_pre_source_grant_cannot_start_escaped_reader_after_callback(): + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + + value = _source_read_fixture() + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant: + reader = grant.open_source(lease=value.lease) + with pytest.raises((StopAsyncIteration, SelectedPreSubmitInfrastructureUnavailable)): + await anext(reader) + assert "open_source" not in value.events diff --git a/backend/tests/test_local_artifact_store.py b/backend/tests/test_local_artifact_store.py index 7cb6720c0..8859b7dcd 100644 --- a/backend/tests/test_local_artifact_store.py +++ b/backend/tests/test_local_artifact_store.py @@ -895,10 +895,11 @@ async def local_source_completion(store, upload, data): @pytest.mark.asyncio -async def test_local_submission_source_keeps_one_inode_and_survives_late_abort_and_restart(tmp_path): +@pytest.mark.parametrize("read_cap", [4096, 65536]) +async def test_local_submission_source_keeps_one_inode_and_survives_late_abort_and_restart(tmp_path, read_cap): from app.interfaces.artifacts import ArtifactPreconditionFailedError root = tmp_path / "store" - store = initialize_local_store(root=root, buffer_bytes=65536) + store = initialize_local_store(root=root, buffer_bytes=256 * 1024) intent = local_source_intent(store) upload = await store.begin_source_upload(intent) path = root / "objects" / intent.location.object_ref @@ -914,10 +915,10 @@ async def test_local_submission_source_keeps_one_inode_and_survives_late_abort_a with pytest.raises(ArtifactPreconditionFailedError): await store.upload_source_part(upload, 1, b"replacement") store.close() - store = initialize_local_store(root=root, buffer_bytes=65536) + store = initialize_local_store(root=root, buffer_bytes=256 * 1024) try: - chunks = [chunk async for chunk in store.open_source(sealed)] - assert max(map(len, chunks)) <= 65536 and b"".join(chunks) == data + chunks = [chunk async for chunk in store.open_source(sealed, maximum_chunk_bytes=read_cap)] + assert max(map(len, chunks)) <= read_cap and b"".join(chunks) == data assert path.stat().st_ino == inode assert list(root.rglob("bundle.zip")) == [path] finally: From 3b98102c8585ac35b1e02a877046d2f2fa1bd84d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:36:20 +0100 Subject: [PATCH 068/513] Keep PRE source reads within their foreground callback task --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 20 +++++++++ .../interfaces/external_checker_execution.py | 4 +- .../selected_pre_submit_execution.py | 4 +- backend/tests/test_checker_materialization.py | 41 +++++++++++++++++++ 4 files changed, 67 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f968ba344..eed575ff6 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1535,3 +1535,23 @@ with cancellation-resistant cleanup before closing the authority adapter. Owner/lane checks passed 229 tests. This source-read work remains pending scoped review, and the native handler and obsolete public caller replacement remain required before the coordinated cutover can be published. + +Review of source-read candidate `951627305` passed architecture/security but QA +reproduced a concurrent-reader cleanup defect: a detached task could remain in a +provider read while callback exit attempted to close its running generator. +The repair binds grant consumption and every read resume to the issuing +foreground task. This matches the existing client's inline backpressured reads +and refuses detached consumption before provider I/O. Tests cover transferring +an already-created reader to a child task and expiry both before first read and +after the first chunk. All ten focused grant cases pass after the repair. + +The earlier integration receipt used the dirty tree's base SHA. A fresh isolated +run on clean `951627305` passed five PostgreSQL/local/AUTH cases and confirmed +cleanup; it does not cover the subsequent task-binding repair. Authorization +import validation and record/link checks passed. Structural validation separately +found new oversize custody-test debt and stale spans/hashes for the shrinking +existing authorization test file. These must be repaired by cohesive test +extraction and exact ledger/assertion-map reconciliation, not a new exception. +A full native workspace baseline reached the service tests: 114 passed and five +failed on removed prepared-generation fields in old fixtures. Those failures +remain required work in the native/public cutover; no full-suite pass is claimed. diff --git a/backend/app/interfaces/external_checker_execution.py b/backend/app/interfaces/external_checker_execution.py index c6665ead0..625924227 100644 --- a/backend/app/interfaces/external_checker_execution.py +++ b/backend/app/interfaces/external_checker_execution.py @@ -154,7 +154,9 @@ class ExternalPreSubmitSourceGrant(Protocol): """ART-issued expiring read authority, separate from durable request identity. The issuer must consume the exact committed lease and authorize the immutable - source generation before returning this process-local capability. + source generation before returning this process-local capability. Reads stay + in the issuing foreground task; the capability cannot be delegated to a + detached task beyond that callback lifetime. """ def open_source(self, *, lease: SelectedPreSubmitLeaseFacts) -> AsyncGenerator[bytes, None]: diff --git a/backend/app/modules/artifacts/selected_pre_submit_execution.py b/backend/app/modules/artifacts/selected_pre_submit_execution.py index d783c87b4..1f4528c42 100644 --- a/backend/app/modules/artifacts/selected_pre_submit_execution.py +++ b/backend/app/modules/artifacts/selected_pre_submit_execution.py @@ -83,10 +83,12 @@ def _issued(cls, issuer, lease, expires_at, deadline): value._claimed = False value._revoked = False value._reader = None + value._task = asyncio.current_task() return value def _require_current(self) -> None: - if (self._revoked or self._issuer._session.in_transaction() + if (asyncio.current_task() is not self._task + or self._revoked or self._issuer._session.in_transaction() or asyncio.get_running_loop().time() >= self._deadline or datetime.now(UTC) >= self._expires_at): raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") diff --git a/backend/tests/test_checker_materialization.py b/backend/tests/test_checker_materialization.py index 5a4f5bacb..8623f28c5 100644 --- a/backend/tests/test_checker_materialization.py +++ b/backend/tests/test_checker_materialization.py @@ -414,3 +414,44 @@ async def test_pre_source_grant_cannot_start_escaped_reader_after_callback(): with pytest.raises((StopAsyncIteration, SelectedPreSubmitInfrastructureUnavailable)): await anext(reader) assert "open_source" not in value.events + + +@pytest.mark.asyncio +async def test_pre_source_grant_refuses_reader_transferred_to_detached_task(): + import asyncio + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + + value = _source_read_fixture() + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant: + reader = grant.open_source(lease=value.lease) + detached = asyncio.create_task(anext(reader)) + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable): + await detached + assert "open_source" not in value.events + assert detached.done() + assert value.events[-1] == "close_authority" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("already_started", [False, True]) +async def test_pre_source_grant_refuses_expiry_after_issuance(monkeypatch, already_started): + from datetime import datetime, timedelta + from app.modules.artifacts import selected_pre_submit_execution as execution + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + + value = _source_read_fixture() + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant: + reader = grant.open_source(lease=value.lease) + if already_started: + assert await anext(reader) == value.payload + class ExpiredClock(datetime): + @classmethod + def now(cls, tz=None): + return value.lease.lease_expires_at + timedelta(seconds=1) + monkeypatch.setattr(execution, "datetime", ExpiredClock) + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable): + await anext(reader) + if already_started: + assert value.events[-2:] == ["close_source", "close_authority"] + else: + assert "open_source" not in value.events From d9d6351990591c4ba4a787fb073e8c9b90083454 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:38:43 +0100 Subject: [PATCH 069/513] Execute selected PRE in the source-owning foreground task --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++ .../checkers/selected_pre_submit_execution.py | 6 ++- backend/tests/test_checker_materialization.py | 49 +++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index eed575ff6..33e4b5558 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1555,3 +1555,14 @@ extraction and exact ledger/assertion-map reconciliation, not a new exception. A full native workspace baseline reached the service tests: 114 passed and five failed on removed prepared-generation fields in old fixtures. Those failures remain required work in the native/public cutover; no full-suite pass is claimed. + +The first task-binding repair was rejected on review: although the Unix client +reads inline, its CHECKERS processor created a child task. The earlier assertion +that task binding matched the complete existing call path was incorrect. A new +issuer-plus-production-processor regression failed with `material_unavailable` +before provider access. The processor now awaits execution inline and tracks the +foreground task for abort; a cancellation test proves abort unwinds the issuer +and closes the provider. Twelve focused source-grant/composition cases pass. +A broader old selected-PRE test module still fails 13 cases on the removed +`semantic_manifest_id` prepared-lineage argument; these remain pending connected +replacement, alongside the separately recorded Rust old-fixture failures. diff --git a/backend/app/modules/checkers/selected_pre_submit_execution.py b/backend/app/modules/checkers/selected_pre_submit_execution.py index f70c60f10..70eae9005 100644 --- a/backend/app/modules/checkers/selected_pre_submit_execution.py +++ b/backend/app/modules/checkers/selected_pre_submit_execution.py @@ -45,8 +45,10 @@ async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmi raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") self._started = True try: - self._active = asyncio.create_task(self._execution.execute_pre(self._lease, grant)) - result = await self._active + # The source grant belongs to this foreground callback task. + # Track it for abort without delegating source custody to a child. + self._active = asyncio.current_task() + result = await self._execution.execute_pre(self._lease, grant) if type(result) is not SelectedPreSubmitExecutionFacts: raise ValueError("PRE result is invalid") result.validate_lease(self._lease) diff --git a/backend/tests/test_checker_materialization.py b/backend/tests/test_checker_materialization.py index 8623f28c5..b9e2be81a 100644 --- a/backend/tests/test_checker_materialization.py +++ b/backend/tests/test_checker_materialization.py @@ -455,3 +455,52 @@ def now(cls, tz=None): assert value.events[-2:] == ["close_source", "close_authority"] else: assert "open_source" not in value.events + + +@pytest.mark.asyncio +async def test_pre_source_grant_is_consumed_by_production_processor_in_foreground(): + from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + + value = _source_read_fixture() + class Execution: + async def execute_pre(self, lease, grant): + assert b"".join([chunk async for chunk in grant.open_source(lease=lease)]) == value.payload + raise SelectedPreSubmitInfrastructureUnavailable("capacity_exceeded") + processor = SelectedPreSubmitProcessor(lease=value.lease, execution=Execution()) + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant: + with pytest.raises(SelectedPreSubmitInfrastructureUnavailable) as error: + await processor.process(grant) + assert error.value.code == "capacity_exceeded" + assert value.events[-2:] == ["close_source", "close_authority"] + + +@pytest.mark.asyncio +async def test_pre_source_processor_abort_unwinds_foreground_and_closes_provider(): + import asyncio + from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor + + value = _source_read_fixture() + started = asyncio.Event() + class Execution: + async def execute_pre(self, lease, grant): + reader = grant.open_source(lease=lease) + assert await anext(reader) == value.payload + started.set() + await asyncio.Event().wait() + processor = SelectedPreSubmitProcessor(lease=value.lease, execution=Execution()) + async def foreground(): + async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant: + await processor.process(grant) + task = asyncio.create_task(foreground()) + try: + async with asyncio.timeout(5): + await started.wait() + processor.abort() + with pytest.raises(asyncio.CancelledError): + await task + assert value.events[-2:] == ["close_source", "close_authority"] + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) From c4949e117bcf81a512e881ba0e578dc08c72aed2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:40:42 +0100 Subject: [PATCH 070/513] Record reviewed foreground source-read repair evidence --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 33e4b5558..75b266360 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1566,3 +1566,11 @@ and closes the provider. Twelve focused source-grant/composition cases pass. A broader old selected-PRE test module still fails 13 cases on the removed `semantic_manifest_id` prepared-lineage argument; these remain pending connected replacement, alongside the separately recorded Rust old-fixture failures. + +Architecture/security and QA/test-delta passed the repaired source-task scope at +clean `d9d635199`. The exact-head isolated PostgreSQL/local/AUTH replay passed +five cases with database and overall cleanup confirmed on migration 0071. Ten +single-PRE transport cases passed. QA's independent blocked-provider abort probe +also confirmed cancellation closes both provider and authority. This resolves +the concurrent-reader and processor-task findings; it does not resolve the +structural gate, obsolete native fixtures, public cutover or T4 requirements. From 38440d466fc652a4f61f8241f1265c8c0e693edf Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:47:18 +0100 Subject: [PATCH 071/513] Separate PRE source custody proof without adding structural debt --- .ci/auth-boundaries/TEST_STRUCTURE_DEBT.json | 54 +- .../WS-SUBMIT-001-source-custody.json | 535 ++++++++++++++++++ .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 27 + .../test_submission_intake_custody.py | 454 --------------- .../artifacts/test_submission_pre_source.py | 488 ++++++++++++++++ 5 files changed, 1077 insertions(+), 481 deletions(-) create mode 100644 .ci/auth-boundaries/assertion-maps/WS-SUBMIT-001-source-custody.json create mode 100644 backend/tests/artifacts/test_submission_pre_source.py diff --git a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json index 041c78b07..0b17d1959 100644 --- a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json +++ b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json @@ -98,11 +98,11 @@ }, { "capability": "oversized_authorization_structure", - "content_sha256": "775edb3946405d3a1098a5214e6e90edbe3f92cf33fd18d576f99a4183c40566", - "end_line": 10754, + "content_sha256": "83e22112a91dc19952da68aa220dd6a55d7834d2824cd3fd1fa8af20480c89be", + "end_line": 10709, "hard_limit": 1200, "kind": "test_file", - "observed_lines": 10754, + "observed_lines": 10709, "path": "backend/tests/test_authorization.py", "qualified_symbol": null, "removal_chunk": "WS-AUTH-003-CLOSE", @@ -231,134 +231,134 @@ { "capability": "oversized_authorization_structure", "content_sha256": "10003810b90ad8ea86434aaae1a38e650c5df4bebd09bb0577ac3ebb7a522351", - "end_line": 2657, + "end_line": 2653, "hard_limit": 120, "kind": "test_function", "observed_lines": 121, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_identity_link_lifecycle_route_preserves_outcome_transaction_contract", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 2537 + "start_line": 2533 }, { "capability": "oversized_authorization_structure", "content_sha256": "b4d58c998c9b8b2efedcdd67d1beb2e804c7f6dfca61b4818d6e95d8268c6f08", - "end_line": 6889, + "end_line": 6844, "hard_limit": 120, "kind": "test_function", "observed_lines": 122, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_identity_link_lifecycle_service_applies_success_and_guards_conflicts", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 6768 + "start_line": 6723 }, { "capability": "oversized_authorization_structure", "content_sha256": "0858a7b107e68244cd719c9521856944411f88442818ae491ebb58a45ef4f417", - "end_line": 5768, + "end_line": 5723, "hard_limit": 120, "kind": "test_function", "observed_lines": 126, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_prepared_actor_authority_crossed_mutations_complete_in_both_orders", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 5643 + "start_line": 5598 }, { "capability": "oversized_authorization_structure", "content_sha256": "56e6f85cc1b712b6410bee986d54e59e4dbad4c3f73c0599f12fe284587577a7", - "end_line": 6085, + "end_line": 6040, "hard_limit": 120, "kind": "test_function", "observed_lines": 312, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_prepared_crosses_real_lifecycle_service_transactions", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 5774 + "start_line": 5729 }, { "capability": "oversized_authorization_structure", "content_sha256": "5cbc72df2c822f2f57db164c0ea4aa2f2d76d591313f69d6496fc26b127b581e", - "end_line": 3755, + "end_line": 3751, "hard_limit": 120, "kind": "test_function", "observed_lines": 149, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_project_11c2_reads_require_exact_admin_context_and_role_allowlist", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 3607 + "start_line": 3603 }, { "capability": "oversized_authorization_structure", "content_sha256": "478d47861e68cfa6571199b0f69785c8f3f5a3483774cee0929b6a13dba6a648", - "end_line": 2134, + "end_line": 2130, "hard_limit": 120, "kind": "test_function", "observed_lines": 302, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_project_mutation_resources_and_prepared_scopes_are_closed", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 1833 + "start_line": 1829 }, { "capability": "oversized_authorization_structure", "content_sha256": "3d2a9843510cdb61b34500aa79a8ed3572df72723ab401f0245300e10c70044e", - "end_line": 9031, + "end_line": 8986, "hard_limit": 120, "kind": "test_function", "observed_lines": 174, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_project_read_permissions_have_postgresql_role_scope_matrix", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 8858 + "start_line": 8813 }, { "capability": "oversized_authorization_structure", "content_sha256": "0da4e29b29ebd44bd9049145ee4148531320bce53859ad5341e5f57261e5a884", - "end_line": 10467, + "end_line": 10422, "hard_limit": 120, "kind": "test_function", "observed_lines": 227, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_project_role_and_all_operation_mappings_commit_one_linked_pair", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 10241 + "start_line": 10196 }, { "capability": "oversized_authorization_structure", "content_sha256": "8deb42b92c936b62417f3bfe307b4a886612b8e217af8e5abc14a5ae3222452a", - "end_line": 1544, + "end_line": 1540, "hard_limit": 120, "kind": "test_function", "observed_lines": 195, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_project_role_mutation_routes_conceal_denials_and_preserve_self_guards_atomically", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 1350 + "start_line": 1346 }, { "capability": "oversized_authorization_structure", "content_sha256": "19e0d2a736a60fcd30e5c8e18f0641c6b66ed3a669e2d18dd5784195990d1752", - "end_line": 1780, + "end_line": 1776, "hard_limit": 120, "kind": "test_function", "observed_lines": 218, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_project_role_mutation_routes_enforce_project_lifecycle_without_disclosure", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 1563 + "start_line": 1559 }, { "capability": "oversized_authorization_structure", "content_sha256": "217ea21f4a2cbd31a4428ba1f01a9fcd90e73ee95fedb2587100a847e8921926", - "end_line": 9996, + "end_line": 9951, "hard_limit": 120, "kind": "test_function", "observed_lines": 154, "path": "backend/tests/test_authorization.py", "qualified_symbol": "test_service_actor_replay_fails_closed_on_committed_state_drift", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 9843 + "start_line": 9798 }, { "capability": "oversized_authorization_structure", @@ -399,14 +399,14 @@ { "capability": "oversized_authorization_structure", "content_sha256": "32083a125798736fa17533aaa767c0236ae3042de4f7d8debdce5f15e0a801fe", - "end_line": 9313, + "end_line": 9268, "hard_limit": 100, "kind": "test_helper", "observed_lines": 130, "path": "backend/tests/test_authorization.py", "qualified_symbol": "_operation_success", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 9184 + "start_line": 9139 } ], "exceptions": [], diff --git a/.ci/auth-boundaries/assertion-maps/WS-SUBMIT-001-source-custody.json b/.ci/auth-boundaries/assertion-maps/WS-SUBMIT-001-source-custody.json new file mode 100644 index 000000000..2336fa567 --- /dev/null +++ b/.ci/auth-boundaries/assertion-maps/WS-SUBMIT-001-source-custody.json @@ -0,0 +1,535 @@ +{ + "chunk_id": "WS-SUBMIT-001-source-custody", + "schema": "workstream.auth-assertion-map.v1", + "mappings": [ + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_returns_exact_locked_facts", + "old_assertion_id": "assertion:987:987:0975d2e0c5dd11b9e902659d270a97397178e4eb1e9a29154422f3fcb79a1e89", + "old_content_sha256": "0975d2e0c5dd11b9e902659d270a97397178e4eb1e9a29154422f3fcb79a1e89", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 987, + 987 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_returns_exact_locked_facts", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_returns_exact_locked_facts", + "old_assertion_id": "assertion:988:988:efdaf5aaf01607bb121900048d2d2a387814d7871c285047808185902dfa191c", + "old_content_sha256": "efdaf5aaf01607bb121900048d2d2a387814d7871c285047808185902dfa191c", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 988, + 988 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_returns_exact_locked_facts", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_returns_exact_locked_facts", + "old_assertion_id": "assertion:984:984:fb30df57f32ce33615700dc3bc4e66efda749aa79c23810e1a2c81ec71ddb7e7", + "old_content_sha256": "fb30df57f32ce33615700dc3bc4e66efda749aa79c23810e1a2c81ec71ddb7e7", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 984, + 984 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_returns_exact_locked_facts", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_returns_exact_locked_facts", + "old_assertion_id": "assertion:989:989:df0e791086ea0ee72e344d5921dd0a8724ea74acfe74d3fae1ee13c29dfdb1e0", + "old_content_sha256": "df0e791086ea0ee72e344d5921dd0a8724ea74acfe74d3fae1ee13c29dfdb1e0", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 989, + 989 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_returns_exact_locked_facts", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_returns_exact_locked_facts", + "old_assertion_id": "assertion:985:985:0875bbc9c80ef1b91d88c7c5674663d2173be5bb719e2793d3cbcd8894cc2839", + "old_content_sha256": "0875bbc9c80ef1b91d88c7c5674663d2173be5bb719e2793d3cbcd8894cc2839", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 985, + 985 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_returns_exact_locked_facts", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_returns_exact_locked_facts", + "old_assertion_id": "assertion:991:991:dd878c60276f22820221cc781814e30f3a24dde651a8a1cd1020fc2abaa01047", + "old_content_sha256": "dd878c60276f22820221cc781814e30f3a24dde651a8a1cd1020fc2abaa01047", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 991, + 991 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_returns_exact_locked_facts", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_returns_exact_locked_facts", + "old_assertion_id": "assertion:986:986:3ce9e4dd8fed0ea7e88e28da80ad0b9daad31e7eb9a28d3dcce11f65fcc695d2", + "old_content_sha256": "3ce9e4dd8fed0ea7e88e28da80ad0b9daad31e7eb9a28d3dcce11f65fcc695d2", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 986, + 986 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_returns_exact_locked_facts", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_returns_exact_locked_facts", + "old_assertion_id": "assertion:990:990:4548f3d952d65ddb8c074d8206c3897386deeb9547ebaefcefafda41959ad71d", + "old_content_sha256": "4548f3d952d65ddb8c074d8206c3897386deeb9547ebaefcefafda41959ad71d", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 990, + 990 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_returns_exact_locked_facts", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_pre_source_custody_rejects_substitution_or_stale_owner", + "old_assertion_id": "assertion:1045:1045:9a3da30e796d070dcec7e7ad51ed4fbc3559dd10ba6bafc72345ebcb40376cca", + "old_content_sha256": "9a3da30e796d070dcec7e7ad51ed4fbc3559dd10ba6bafc72345ebcb40376cca", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1045, + 1045 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_pre_source_custody_rejects_substitution_or_stale_owner", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_selected_pre_sql_requires_exact_live_source", + "old_assertion_id": "assertion:1132:1132:abed470232d18b3421d8c467d75f6933874b384212a7981e06b3675af26a3b10", + "old_content_sha256": "abed470232d18b3421d8c467d75f6933874b384212a7981e06b3675af26a3b10", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1132, + 1132 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_selected_pre_sql_requires_exact_live_source", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_selected_pre_sql_requires_exact_live_source", + "old_assertion_id": "assertion:1194:1194:7b86638791bf76b428e22c49edd3cd0a47e1bbe16a169b7732c24958c3c7ded8", + "old_content_sha256": "7b86638791bf76b428e22c49edd3cd0a47e1bbe16a169b7732c24958c3c7ded8", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1194, + 1194 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_selected_pre_sql_requires_exact_live_source", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_selected_pre_sql_requires_exact_live_source", + "old_assertion_id": "assertion:1111:1111:8775a3037ed0996fbc9c5787472ab900d1641b47d4589714ba84e8c8f1eb6cdb", + "old_content_sha256": "8775a3037ed0996fbc9c5787472ab900d1641b47d4589714ba84e8c8f1eb6cdb", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1111, + 1111 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_selected_pre_sql_requires_exact_live_source", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_selected_pre_sql_requires_exact_live_source", + "old_assertion_id": "assertion:1176:1176:7b86638791bf76b428e22c49edd3cd0a47e1bbe16a169b7732c24958c3c7ded8", + "old_content_sha256": "7b86638791bf76b428e22c49edd3cd0a47e1bbe16a169b7732c24958c3c7ded8", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1176, + 1176 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_selected_pre_sql_requires_exact_live_source", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_selected_pre_sql_requires_exact_live_source", + "old_assertion_id": "assertion:1123:1123:91fa96159a19f7da98d4c4a551546e2f03aa84b1412f3b074e3c45407115d8bf", + "old_content_sha256": "91fa96159a19f7da98d4c4a551546e2f03aa84b1412f3b074e3c45407115d8bf", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1123, + 1123 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_selected_pre_sql_requires_exact_live_source", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_selected_pre_sql_audit_digest_keeps_versioned_custody", + "old_assertion_id": "assertion:1233:1233:f9a0fe10928d2e579c412871119a833ac0b77e53e851ad1e9191448dd12c521b", + "old_content_sha256": "f9a0fe10928d2e579c412871119a833ac0b77e53e851ad1e9191448dd12c521b", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1233, + 1233 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_selected_pre_sql_audit_digest_keeps_versioned_custody", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read", + "old_assertion_id": "assertion:1383:1383:de345141f129cd6db67614d63eb5a1582c632a74a32c1f8f8683aa652f71733b", + "old_content_sha256": "de345141f129cd6db67614d63eb5a1582c632a74a32c1f8f8683aa652f71733b", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1383, + 1383 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_source_pre_execution_uses_committed_authorized_local_read", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read", + "old_assertion_id": "assertion:1418:1418:813ef7b28c1efad681560795de061e8340efad897338d62970d5c654676f10e7", + "old_content_sha256": "813ef7b28c1efad681560795de061e8340efad897338d62970d5c654676f10e7", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1418, + 1418 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_source_pre_execution_uses_committed_authorized_local_read", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read", + "old_assertion_id": "assertion:1382:1382:230107a72101dbd84d2cbf4484b5e196b6bc01545acefc0ec27d043b7c9b5a66", + "old_content_sha256": "230107a72101dbd84d2cbf4484b5e196b6bc01545acefc0ec27d043b7c9b5a66", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1382, + 1382 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_source_pre_execution_uses_committed_authorized_local_read", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read", + "old_assertion_id": "assertion:1392:1392:b58e0fe7ebe91a7bb46a3fbbfb0f16c0f666440ee7c08ed9733f225363872725", + "old_content_sha256": "b58e0fe7ebe91a7bb46a3fbbfb0f16c0f666440ee7c08ed9733f225363872725", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1392, + 1392 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_source_pre_execution_uses_committed_authorized_local_read", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read", + "old_assertion_id": "assertion:1419:1421:6217801e8d8d4afeb8e06e2c02240070d10c59e5df82cf337b56c5eb83e515e0", + "old_content_sha256": "6217801e8d8d4afeb8e06e2c02240070d10c59e5df82cf337b56c5eb83e515e0", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1419, + 1421 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_source_pre_execution_uses_committed_authorized_local_read", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read", + "old_assertion_id": "assertion:1422:1422:9c4d6810813eec30798d7c9f443e743011688d6c7c65c6860dce04e8f3ab07ed", + "old_content_sha256": "9c4d6810813eec30798d7c9f443e743011688d6c7c65c6860dce04e8f3ab07ed", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1422, + 1422 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_source_pre_execution_uses_committed_authorized_local_read", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read", + "old_assertion_id": "assertion:1393:1395:171121e0f1df392da213114e05c7ed7608782313226b622a77573c4ee78eba72", + "old_content_sha256": "171121e0f1df392da213114e05c7ed7608782313226b622a77573c4ee78eba72", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1393, + 1395 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_source_pre_execution_uses_committed_authorized_local_read", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + }, + { + "invariant_category": "Preserve exact PRE source, authority, lease and SQL custody assertions after test extraction", + "new_test_node": "tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read", + "old_assertion_id": "assertion:1404:1404:7a1cbd5c2235092db6a1542d8d8c1701cfcb0aec29dfad09cda6ad0bd5f98681", + "old_content_sha256": "7a1cbd5c2235092db6a1542d8d8c1701cfcb0aec29dfad09cda6ad0bd5f98681", + "old_revision": "c4949e117bcf81a512e881ba0e578dc08c72aed2", + "old_source_span": [ + 1404, + 1404 + ], + "old_test_node": "tests/artifacts/test_submission_intake_custody.py::test_source_pre_execution_uses_committed_authorized_local_read", + "security_dimensions": { + "concurrency": "preserved", + "lock_order": "preserved", + "denial_side_effects": "preserved", + "replay": "preserved", + "revocation": "preserved", + "evidence": "preserved", + "transaction_ownership": "preserved", + "concealment": "preserved" + }, + "target_layer": "integration" + } + ] +} diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 75b266360..796a93a7e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1574,3 +1574,30 @@ single-PRE transport cases passed. QA's independent blocked-provider abort probe also confirmed cancellation closes both provider and authority. This resolves the concurrent-reader and processor-task findings; it does not resolve the structural gate, obsolete native fixtures, public cutover or T4 requirements. + +The structural-gate repair extracts the five PRE source/SQL/execution tests from +`test_submission_intake_custody.py` into `test_submission_pre_source.py`. Upload, +quota and foreground lease tests keep their original module and fixtures; the +new module imports those exact fixtures rather than creating a second setup. +Source/request substitution helpers separate setup from SQL assertions without +changing the tested cases. The assertion map preserves all 23 direct assertions +from the prior five tests at ancestor `c4949e117`; helper assertions remain on +the same exercised path. This is a test-only repair within the existing source +custody scope, with QA/test-delta review required. Acceptance requires the same +29 collected PRE cases, real PostgreSQL replay, no new structural debt, and +unchanged ownership partition. No gate limits, product behavior, schema, fixture +policy or production authorization change is permitted by this repair. + +The refreshed structural ledger records only the earlier authorization test +file's shrinkage and shifted spans of otherwise unchanged functions. It adds no +oversize exception or new debt entry. The existing remaining oversized AUTH +files remain explicit debt; this repair does not claim to eliminate them. + +The extracted PRE module passed all 29 real PostgreSQL cases in 259.16 seconds; +its receipt records the pre-freeze worktree base `c4949e117`, so this is compatible +working-tree proof rather than an exact frozen-head receipt. Combined collection +retains all 85 cases. AST comparison after expanding the two helper calls and +ignoring import placement confirms identical executable statements for the five +moved tests and the existing terminal-guard helper. Structural validation passed, +as did its 29 regression tests, new-module undefined/unused-name checks, and +record/link checks. The ownership partition is byte-for-byte unchanged. diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 1c76164a5..e1094af1f 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -967,457 +967,3 @@ def command(*owner): with pytest.raises(IntakeCustodyConflict, match="renewal_expired"): await runner.run(operation, lease, 1, command) assert not called - - -async def test_pre_source_custody_returns_exact_locked_facts(intake): - async with intake.factory.begin() as session: - row = await reserve(intake, session) - operation, lease = UUID(row.id), UUID(row.lease_id) - await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) - deadline = datetime.now(UTC) + timedelta(minutes=2) - source = await repository(session).seal( - operation, lease, 1, provider_generation="pre-source-generation", - pre_deadline_at=deadline, lease_expires_at=deadline, - ) - async with intake.factory.begin() as session: - facts = await repository(session).lock_pre_source(source=source, lease_id=lease, generation=1) - assert facts.source == source - assert facts.task_id == intake.task and facts.assignment_id == intake.assignment - assert facts.actor_profile_id == intake.actor.actor_profile_id - assert facts.identity_link_id == intake.actor.identity_link_id - assert facts.lease_id == lease and facts.lease_generation == 1 - assert facts.lease_expires_at == facts.pre_deadline_at == deadline - assert facts.metadata_sha256 == row.metadata_sha256 - assert facts.locked_context_sha256 == row.locked_context_sha256 - - -@pytest.mark.parametrize("changed", [ - "generation", "raw_sha", "raw_count", "namespace", "profile", "lease", "fence", - "cleared_pointer", "foreign_pointer", "expired", "terminal", "unsealed", -]) -async def test_pre_source_custody_rejects_substitution_or_stale_owner(intake, changed): - async with intake.factory.begin() as session: - row = await reserve(intake, session) - operation, lease = UUID(row.id), UUID(row.lease_id) - await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) - deadline = datetime.now(UTC) + timedelta(minutes=2) - if changed == "unsealed": - from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceLocation - source = SealedSubmissionSource( - location=SubmissionSourceLocation( - operation_id=operation, namespace_id=row.namespace_id, - namespace_fingerprint=row.namespace_fingerprint, provider_profile=row.provider_profile, - ), provider_generation="pre-source-generation", raw_sha256=SHA, - raw_byte_count=100, sealed_upload_fence=1, - ) - else: - source = await repository(session).seal( - operation, lease, 1, provider_generation="pre-source-generation", - pre_deadline_at=deadline, lease_expires_at=deadline, - ) - values = source.model_dump(mode="python") - if changed == "generation": - values["provider_generation"] = "another-generation" - elif changed == "raw_sha": - values["raw_sha256"] = "sha256:" + "b" * 64 - elif changed == "raw_count": - values["raw_byte_count"] += 1 - elif changed == "namespace": - values["location"]["namespace_fingerprint"] = "sha256:" + "b" * 64 - elif changed == "profile": - values["location"]["provider_profile"] = "unqualified-profile" - supplied = type(source).model_validate(values) - async with intake.factory() as session: - await session.begin() - try: - if changed in {"cleared_pointer", "foreign_pointer"}: - # Deferrable SQL constraints do not replace the in-root owner - # check before another participant can consume custody. - await session.execute(text( - "UPDATE workstream_tasks SET active_submission_operation_id=:active WHERE id=:task" - ), {"active": None if changed == "cleared_pointer" else new_record_id(), "task": intake.task}) - elif changed == "expired": - await session.execute(text( - "UPDATE submission_intake_operations SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=:id" - ), {"id": operation}) - elif changed == "terminal": - await repository(session).terminalize(operation, lease, 1, state="rejected", failure_code="pre_failed") - with pytest.raises((IntakeCustodyConflict, TaskSubmissionContextUnavailable)): - await repository(session).lock_pre_source( - source=supplied, lease_id=new_record_id() if changed == "lease" else lease, - generation=2 if changed == "fence" else 1, - ) - finally: - await session.rollback() - - -@pytest.mark.parametrize("intake", [True], indirect=True) -@pytest.mark.parametrize("changed", [None, "source", "packet", "policy", "post_policy", "fence", "deadline", "actor", "rules", "predecessor", "predecessor_identity", "storage_scheme"]) -async def test_selected_pre_sql_requires_exact_live_source(intake, changed): - """Exercise the SQL source participant; not full PRE execution or T4 proof.""" - from dataclasses import replace - from app.core.hashing import canonical_json_hash - from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation - from app.adapters.projects import project_locked_policy_context_port - from app.adapters.artifacts import submission_intake_pre_source_port - from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest - from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest - from app.modules.checkers.api.pre_submit_material import SubmissionPacketView - from app.modules.artifacts.selected_pre_submit_admission import ( - bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, - ) - - async with intake.factory.begin() as session: - row = await reserve(intake, session) - operation, lease = UUID(row.id), UUID(row.lease_id) - await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) - deadline = datetime.now(UTC) + timedelta(minutes=2) - source = await repository(session).seal( - operation, lease, 1, provider_generation="pre-source-generation", - pre_deadline_at=deadline, lease_expires_at=deadline, - ) - async with intake.factory.begin() as session: - task = await task_submission_context_port(session).lock_submission_context( - TaskSubmissionContextRequest( - task_id=intake.task, assignment_id=intake.assignment, - contributor_id=intake.actor.actor_profile_id, predecessor_submission_id=None, - ) - ) - references = task.locked_project_context - project = await project_locked_policy_context_port(session).lock_locked_policy_context( - ProjectLockedPolicyContextRequest(**{ - name: getattr(references, name) for name in ( - "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", - "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", - "pre_submit_policy_bundle_hash", - ) - }) - ) - guarded = await submission_intake_pre_source_port(session).lock_pre_source( - source=source, lease_id=lease, generation=1, - ) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) - selected = bind_selected_pre_submit_admission( - task=task, project=project, predecessor=None, predecessor_rules_sha256=None, - predecessor_exists=False, - packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), - ) - build_values = dict( - source=guarded, metadata=metadata, task=task, project=project, - attempt_id=new_record_id(), idempotency_key=UUID(row.idempotency_key), - selected=selected, runtime_profile=_source_reservation().runtime_profile, - ) - request = build_selected_pre_submit_reservation(**build_values) - assert request.admission_lineage.storage_scheme == "local" - if changed is None: - substitutions = ( - {"metadata": metadata.model_copy(update={"summary": "substituted"})}, - {"source": guarded.model_copy(update={"actor_profile_id": new_record_id()})}, - {"source": guarded.model_copy(update={"metadata_sha256": "sha256:" + "f" * 64})}, - {"selected": replace(selected, rules_sha256="sha256:" + "f" * 64)}, - {"selected": replace(selected, default_context=replace( - selected.default_context, packet=SubmissionPacketView("substituted", ""), - ))}, - ) - for replacement in substitutions: - with pytest.raises(ValueError, match="selected PRE .* context differs"): - build_selected_pre_submit_reservation(**(build_values | replacement)) - from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakePreSourceFacts - unsupported_source = SealedSubmissionSource.model_validate(guarded.source.model_copy(update={ - "location": guarded.source.location.model_copy(update={"provider_profile": "aws-s3-v1"}), - })) - unsupported_facts = SubmissionIntakePreSourceFacts.model_validate( - guarded.model_copy(update={"source": unsupported_source}) - ) - with pytest.raises(ValueError, match="selected PRE source profile is unavailable"): - build_selected_pre_submit_reservation(**(build_values | {"source": unsupported_facts})) - body = request.canonical_body() - if changed == "source": - body["source"]["provider_generation"] = "substituted" - body["source_sha256"] = canonical_json_hash({ - "schema_version": "workstream.sealed_submission_source.v1", **body["source"], - }) - elif changed == "packet": - body["default_context"]["packet"]["summary"] = "substituted" - body["admission_lineage"]["packet_sha256"] = canonical_json_hash(body["default_context"]["packet"]) - elif changed == "policy": - body["policy"]["entries"] = [] - elif changed == "post_policy": - body["admission_lineage"]["post_submit_policy_body"] = {} - elif changed == "fence": - body["foreground_lease_generation"] += 1 - elif changed == "deadline": - body["pre_deadline_at"] = (deadline + timedelta(seconds=1)).isoformat() - elif changed == "storage_scheme": - body["admission_lineage"]["storage_scheme"] = "s3" - elif changed == "rules": - body["default_context"]["current_rules_sha256"] = "sha256:" + "f" * 64 - body["admission_lineage"]["rules_sha256"] = "sha256:" + "f" * 64 - elif changed == "predecessor": - body["default_context"]["predecessor_exists"] = True - elif changed == "predecessor_identity": - body["admission_lineage"]["predecessor_submission_id"] = str(new_record_id()) - body["admission_lineage"]["predecessor_submission_version"] = 1 - body["admission_lineage"]["checker_remediation_manifest_id"] = str(new_record_id()) - value = { - "source_operation_id": str(operation), "task_id": str(intake.task), - "project_id": row.project_id, "assignment_id": str(intake.assignment), - "actor_profile_id": str(new_record_id()) if changed == "actor" else row.actor_profile_id, - "identity_link_id": row.identity_link_id, "idempotency_key": row.idempotency_key, - "request_json": body, "archive_sha256": source.raw_sha256, - "archive_byte_count": source.raw_byte_count, "policy_sha256": request.policy_sha256, - } - async with intake.factory.begin() as session: - statement = text("""SELECT public.require_selected_pre_source( - jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)))""") - if changed is None: - await session.execute(statement, {"value": json.dumps(value)}) - else: - with pytest.raises(DBAPIError, match="selected PRE"): - await session.execute(statement, {"value": json.dumps(value)}) - await session.rollback() - from app.modules.checkers.models import SelectedPreSubmitRun - async with intake.factory.begin() as session: - session.add(SelectedPreSubmitRun( - id=str(request.attempt_id), source_operation_id=str(operation), - actor_profile_id=value["actor_profile_id"], identity_link_id=row.identity_link_id, - project_id=row.project_id, task_id=str(intake.task), assignment_id=str(intake.assignment), - idempotency_key=row.idempotency_key, request_json=body, - request_digest=canonical_json_hash(body), policy_sha256=request.policy_sha256, - default_behavior_sha256=request.default_behavior_sha256, - archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count, - execution_budget_ms=request.execution_budget_ms, status="queued", lease_generation=0, - )) - if changed is None: - await session.flush() - else: - with pytest.raises(DBAPIError, match="selected PRE"): - await session.flush() - await session.rollback() - if changed is None: - await _assert_pre_terminal_guards(intake, request) - - -@pytest.mark.parametrize("version", ["v1", "v2"]) -async def test_selected_pre_sql_audit_digest_keeps_versioned_custody(isolated_database_env, version): - from app.core.hashing import canonical_json_hash - from tests.checkers.external.test_selected_pre_submit_coordination import _retained_v1, _source_reservation - - retained = _retained_v1() - request = retained["request"] if version == "v1" else _source_reservation().canonical_body() - terminal = retained["terminal"] - execute = { - "schema_version": f"workstream.selected_pre_submit_execute.{version}", - "reservation": request, "lease_id": terminal["lease_id"], - "lease_generation": terminal["lease_generation"], "lease_expires_at": terminal["lease_expires_at"], - } - expected_execute = canonical_json_hash(execute) - expected_finalize = canonical_json_hash({ - "schema_version": f"workstream.selected_pre_submit_finalize.{version}", - "execute_facts_digest": expected_execute, - "execution": terminal["execution"], - "infrastructure_failure_code": terminal["infrastructure_failure_code"], - }) - value = { - "request_json": request, "lease_id": execute["lease_id"], - "lease_generation": execute["lease_generation"], "lease_expires_at": execute["lease_expires_at"], - "terminal_json": terminal, - } - engine = create_async_engine(isolated_database_env) - try: - async with engine.connect() as connection: - for phase, expected in (("execute", expected_execute), ("finalize", expected_finalize)): - actual = await connection.scalar(text("""SELECT public.selected_pre_submit_facts_digest( - jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)), - :phase)"""), {"value": json.dumps(value), "phase": phase}) - assert actual == expected - finally: - await engine.dispose() - - -async def _assert_pre_terminal_guards(intake, request): - """Claim with real AUTH, reject rebound terminal updates, then finalize once.""" - from app.modules.actors.api import ServiceIdentity - from tests.checkers.execution.support import provision_post_submit_service - from app.adapters.auth import selected_pre_submit_authority - from app.adapters.checkers import selected_pre_submit_coordinator - from app.core.hashing import canonical_json_hash - from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitFinalizeFacts, SelectedPreSubmitTerminalFacts - from app.modules.checkers.models import SelectedPreSubmitRun - - await provision_post_submit_service(intake.factory, ServiceIdentity.CHECKER_PRE_SUBMIT) - async with intake.factory.begin() as session: - async with selected_pre_submit_authority(session).prepare_execution(request) as authority: - lease = await selected_pre_submit_coordinator(session).claim( - run_id=request.attempt_id, facts=request, authority=authority, - ) - finalize = SelectedPreSubmitFinalizeFacts( - lease=lease, execution=None, infrastructure_failure_code="capacity_exceeded", - ) - for changed in ("lease_id", "lease_expires_at", "started_at", "execute_evidence_id", - "schema_version", "reservation", "request_digest", "outcome", "terminal_digest", "extra"): - async with intake.factory.begin() as session: - async with selected_pre_submit_authority(session).prepare_finalization(finalize) as authority: - evidence = await authority.consume(finalize) - row = await session.get(SelectedPreSubmitRun, str(request.attempt_id)) - now = await session.scalar(text("select clock_timestamp()")) - terminal = SelectedPreSubmitTerminalFacts( - lease=lease, outcome="infrastructure_failed", execution=None, - infrastructure_failure_code="capacity_exceeded", queued_at=row.queued_at, - started_at=row.started_at, completed_at=now, - ).canonical_body() - values = dict( - id=request.attempt_id, lease_id=lease.lease_id, - lease_expires_at=lease.lease_expires_at, started_at=row.started_at, - execute_evidence_id=UUID(row.execute_evidence_id), completed_at=now, - finalize_evidence_id=evidence.evidence_id, - ) - claim_change = changed in {"lease_id", "lease_expires_at", "started_at", "execute_evidence_id"} - if changed in {"lease_id", "execute_evidence_id"}: - values[changed] = new_record_id() - if changed == "lease_id": - terminal[changed] = str(values[changed]) - elif changed in {"lease_expires_at", "started_at"}: - values[changed] -= timedelta(microseconds=1) - terminal[changed] = values[changed].isoformat() - elif changed == "schema_version": - terminal[changed] = "workstream.selected_pre_submit_terminal.v1" - elif changed == "reservation": - terminal[changed] = terminal[changed] | {"metadata_sha256": "sha256:" + "f" * 64} - elif changed == "request_digest": - terminal[changed] = "sha256:" + "f" * 64 - elif changed == "outcome": - terminal[changed] = "completed" - elif changed == "extra": - terminal["unexpected"] = True - values["terminal_json"] = json.dumps(terminal) - values["terminal_digest"] = ("sha256:" + "f" * 64 if changed == "terminal_digest" - else canonical_json_hash(terminal)) - message = "committed claim is immutable" if claim_change else "terminal binding mismatch" - with pytest.raises(DBAPIError, match=message): - await session.execute(text("""UPDATE selected_pre_submit_runs SET - status='infrastructure_failed', lease_id=:lease_id, lease_expires_at=:lease_expires_at, - started_at=:started_at, execute_evidence_id=:execute_evidence_id, - completed_at=:completed_at, finalize_evidence_id=:finalize_evidence_id, - terminal_json=CAST(:terminal_json AS jsonb), terminal_digest=:terminal_digest - WHERE id=:id"""), values) - await session.rollback() - async with intake.factory.begin() as session: - async with selected_pre_submit_authority(session).prepare_finalization(finalize) as authority: - completion = await selected_pre_submit_coordinator(session).finalize( - run_id=request.attempt_id, lease=lease, authority=authority, - execution=None, infrastructure_failure_code="capacity_exceeded", - ) - assert completion.terminal.outcome == "infrastructure_failed" - assert completion.capability is None - - -@pytest.mark.parametrize("intake", [True], indirect=True) -@pytest.mark.parametrize("materializer_enabled", [True, False]) -async def test_source_pre_execution_uses_committed_authorized_local_read(intake, materializer_enabled): - """Real source/SQL/AUTH composition with an explicitly failing runtime double.""" - from contextlib import aclosing - from app.adapters.artifacts import submission_intake_pre_source_port - from app.adapters.auth import selected_pre_submit_authority - from app.adapters.checkers import selected_pre_submit_coordinator, SelectedPreSubmitCheckerExecutionAdapter - from app.adapters.projects import project_locked_policy_context_port - from app.modules.actors.api import ServiceIdentity - from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization - from app.modules.artifacts.selected_pre_submit_admission import ( - bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, - ) - from app.modules.artifacts.selected_pre_submit_execution import ( - SelectedPreSubmitSourceReads, SelectedPreSubmitExecutionService, - ) - from app.modules.authorization.catalogue import ActionId - from app.modules.checkers.api.pre_submit_material import SubmissionPacketView - from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable - from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest - from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest - from tests.artifact_store_helpers import initialize_local_store - from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer - from tests.checkers.execution.support import provision_post_submit_service - from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation - - store = initialize_local_store(root=intake.durable_root, buffer_bytes=256 * 1024) - async with intake.factory.begin() as session: - row = await reserve(intake, session, with_upload=False) - operation, foreground_lease = UUID(row.id), UUID(row.lease_id) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) - key = UUID(row.idempotency_key) - source = await foreground_upload(intake, store).receive( - operation, foreground_lease, 1, foreground_bytes(), **foreground_limits(), - ) - async with intake.factory.begin() as session: - task = await task_submission_context_port(session).lock_submission_context( - TaskSubmissionContextRequest(intake.task, intake.assignment, intake.actor.actor_profile_id, None), - ) - references = task.locked_project_context - project = await project_locked_policy_context_port(session).lock_locked_policy_context( - ProjectLockedPolicyContextRequest(**{name: getattr(references, name) for name in ( - "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", - "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", "pre_submit_policy_bundle_hash", - )}), - ) - custody = await submission_intake_pre_source_port(session).lock_pre_source( - source=source, lease_id=foreground_lease, generation=1, - ) - selected = bind_selected_pre_submit_admission( - task=task, project=project, predecessor=None, predecessor_rules_sha256=None, - predecessor_exists=False, packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), - ) - request = build_selected_pre_submit_reservation( - source=custody, metadata=metadata, task=task, project=project, - attempt_id=new_record_id(), idempotency_key=key, selected=selected, - runtime_profile=_source_reservation().runtime_profile, - ) - await selected_pre_submit_coordinator(session).reserve(request) - await provision_post_submit_service(intake.factory, ServiceIdentity.CHECKER_PRE_SUBMIT) - if materializer_enabled: - await _seed_materializer(intake.factory) - observed = [] - async with intake.factory() as session: - class ObservedStore: - def open_source(self, actual, *, maximum_chunk_bytes): - assert actual == source and not session.in_transaction() - assert maximum_chunk_bytes == 64 * 1024 - async def chunks(): - async with intake.factory.begin() as probe: - # Independent NOWAIT locks prove provider reads do not - # retain TASK or intake locks from either AUTH root. - for sql, params in ( - ("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE NOWAIT", {"id": intake.task}), - ("SELECT id FROM submission_intake_operations WHERE id=:id FOR UPDATE NOWAIT", {"id": operation}), - ): - assert (await probe.execute(text(sql), params)).one() - assert await probe.scalar(text( - "SELECT count(*) FROM audit_events WHERE action_id=:action AND resource_id=:id" - ), {"action": ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE.value, "id": str(operation)}) == 1 - async with aclosing(store.open_source(actual, maximum_chunk_bytes=maximum_chunk_bytes)) as reader: - async for chunk in reader: - observed.append(chunk) - yield chunk - return chunks() - class RuntimeFailure: - async def execute_pre(self, lease, grant): - async with aclosing(grant.open_source(lease=lease)) as reader: - assert b"".join([chunk async for chunk in reader]) == b"original source bytes" - raise SelectedPreSubmitInfrastructureUnavailable("capacity_exceeded") - authority = PreparedPreSubmitMaterializationAuthorization( - session, request_id=new_record_id(), correlation_id=new_record_id(), - ) - service = SelectedPreSubmitExecutionService( - session=session, coordinator=selected_pre_submit_coordinator(session), - authority=selected_pre_submit_authority(session), - source_reads=SelectedPreSubmitSourceReads( - session=session, sources=submission_intake_pre_source_port(session), - authority=authority, store=ObservedStore(), - ), execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=RuntimeFailure()), - ) - result = await service.execute(reservation=request) - assert result.capability is None and result.terminal.outcome == "infrastructure_failed" - assert result.terminal.infrastructure_failure_code == ( - "capacity_exceeded" if materializer_enabled else "material_unavailable" - ) - assert bool(observed) == materializer_enabled - store.close() diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py new file mode 100644 index 000000000..834567236 --- /dev/null +++ b/backend/tests/artifacts/test_submission_pre_source.py @@ -0,0 +1,488 @@ +"""Real PostgreSQL PRE source, SQL fence, and authorized execution custody.""" + +import json +from datetime import UTC, datetime, timedelta +from uuid import UUID + +import pytest +from sqlalchemy import text +from sqlalchemy.exc import DBAPIError +from sqlalchemy.ext.asyncio import create_async_engine + +from app.adapters.tasks import task_submission_context_port +from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata +from app.modules.artifacts.intake.repository import IntakeCustodyConflict +from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable +from tests.artifacts.test_submission_intake_custody import ( + SHA, capacity_limits as capacity_limits, intake as intake, + foreground_bytes, foreground_limits, foreground_upload, + record_eof, repository, reserve, +) + + +def _assert_pre_reservation_rejects_substitution(build_values, guarded, metadata, selected): + """Keep source/context substitution proof separate from SQL row custody.""" + from dataclasses import replace + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + from app.modules.artifacts.selected_pre_submit_admission import build_selected_pre_submit_reservation + substitutions = ( + {"metadata": metadata.model_copy(update={"summary": "substituted"})}, + {"source": guarded.model_copy(update={"actor_profile_id": new_record_id()})}, + {"source": guarded.model_copy(update={"metadata_sha256": "sha256:" + "f" * 64})}, + {"selected": replace(selected, rules_sha256="sha256:" + "f" * 64)}, + {"selected": replace(selected, default_context=replace( + selected.default_context, packet=SubmissionPacketView("substituted", ""), + ))}, + ) + for replacement in substitutions: + with pytest.raises(ValueError, match="selected PRE .* context differs"): + build_selected_pre_submit_reservation(**(build_values | replacement)) + from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakePreSourceFacts + unsupported_source = SealedSubmissionSource.model_validate(guarded.source.model_copy(update={ + "location": guarded.source.location.model_copy(update={"provider_profile": "aws-s3-v1"}), + })) + unsupported_facts = SubmissionIntakePreSourceFacts.model_validate( + guarded.model_copy(update={"source": unsupported_source}) + ) + with pytest.raises(ValueError, match="selected PRE source profile is unavailable"): + build_selected_pre_submit_reservation(**(build_values | {"source": unsupported_facts})) + + +def _substitute_pre_source_request(body, changed, deadline): + """Alter one locked request fact before exercising the SQL guard.""" + from app.core.hashing import canonical_json_hash + if changed == "source": + body["source"]["provider_generation"] = "substituted" + body["source_sha256"] = canonical_json_hash({ + "schema_version": "workstream.sealed_submission_source.v1", **body["source"], + }) + elif changed == "packet": + body["default_context"]["packet"]["summary"] = "substituted" + body["admission_lineage"]["packet_sha256"] = canonical_json_hash(body["default_context"]["packet"]) + elif changed == "policy": + body["policy"]["entries"] = [] + elif changed == "post_policy": + body["admission_lineage"]["post_submit_policy_body"] = {} + elif changed == "fence": + body["foreground_lease_generation"] += 1 + elif changed == "deadline": + body["pre_deadline_at"] = (deadline + timedelta(seconds=1)).isoformat() + elif changed == "storage_scheme": + body["admission_lineage"]["storage_scheme"] = "s3" + elif changed == "rules": + body["default_context"]["current_rules_sha256"] = "sha256:" + "f" * 64 + body["admission_lineage"]["rules_sha256"] = "sha256:" + "f" * 64 + elif changed == "predecessor": + body["default_context"]["predecessor_exists"] = True + elif changed == "predecessor_identity": + body["admission_lineage"]["predecessor_submission_id"] = str(new_record_id()) + body["admission_lineage"]["predecessor_submission_version"] = 1 + body["admission_lineage"]["checker_remediation_manifest_id"] = str(new_record_id()) + + +async def test_pre_source_custody_returns_exact_locked_facts(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + deadline = datetime.now(UTC) + timedelta(minutes=2) + source = await repository(session).seal( + operation, lease, 1, provider_generation="pre-source-generation", + pre_deadline_at=deadline, lease_expires_at=deadline, + ) + async with intake.factory.begin() as session: + facts = await repository(session).lock_pre_source(source=source, lease_id=lease, generation=1) + assert facts.source == source + assert facts.task_id == intake.task and facts.assignment_id == intake.assignment + assert facts.actor_profile_id == intake.actor.actor_profile_id + assert facts.identity_link_id == intake.actor.identity_link_id + assert facts.lease_id == lease and facts.lease_generation == 1 + assert facts.lease_expires_at == facts.pre_deadline_at == deadline + assert facts.metadata_sha256 == row.metadata_sha256 + assert facts.locked_context_sha256 == row.locked_context_sha256 + + +@pytest.mark.parametrize("changed", [ + "generation", "raw_sha", "raw_count", "namespace", "profile", "lease", "fence", + "cleared_pointer", "foreign_pointer", "expired", "terminal", "unsealed", +]) +async def test_pre_source_custody_rejects_substitution_or_stale_owner(intake, changed): + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + deadline = datetime.now(UTC) + timedelta(minutes=2) + if changed == "unsealed": + from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceLocation + source = SealedSubmissionSource( + location=SubmissionSourceLocation( + operation_id=operation, namespace_id=row.namespace_id, + namespace_fingerprint=row.namespace_fingerprint, provider_profile=row.provider_profile, + ), provider_generation="pre-source-generation", raw_sha256=SHA, + raw_byte_count=100, sealed_upload_fence=1, + ) + else: + source = await repository(session).seal( + operation, lease, 1, provider_generation="pre-source-generation", + pre_deadline_at=deadline, lease_expires_at=deadline, + ) + values = source.model_dump(mode="python") + if changed == "generation": + values["provider_generation"] = "another-generation" + elif changed == "raw_sha": + values["raw_sha256"] = "sha256:" + "b" * 64 + elif changed == "raw_count": + values["raw_byte_count"] += 1 + elif changed == "namespace": + values["location"]["namespace_fingerprint"] = "sha256:" + "b" * 64 + elif changed == "profile": + values["location"]["provider_profile"] = "unqualified-profile" + supplied = type(source).model_validate(values) + async with intake.factory() as session: + await session.begin() + try: + if changed in {"cleared_pointer", "foreign_pointer"}: + # Deferrable SQL constraints do not replace the in-root owner + # check before another participant can consume custody. + await session.execute(text( + "UPDATE workstream_tasks SET active_submission_operation_id=:active WHERE id=:task" + ), {"active": None if changed == "cleared_pointer" else new_record_id(), "task": intake.task}) + elif changed == "expired": + await session.execute(text( + "UPDATE submission_intake_operations SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=:id" + ), {"id": operation}) + elif changed == "terminal": + await repository(session).terminalize(operation, lease, 1, state="rejected", failure_code="pre_failed") + with pytest.raises((IntakeCustodyConflict, TaskSubmissionContextUnavailable)): + await repository(session).lock_pre_source( + source=supplied, lease_id=new_record_id() if changed == "lease" else lease, + generation=2 if changed == "fence" else 1, + ) + finally: + await session.rollback() + + +@pytest.mark.parametrize("intake", [True], indirect=True) +@pytest.mark.parametrize("changed", [None, "source", "packet", "policy", "post_policy", "fence", "deadline", "actor", "rules", "predecessor", "predecessor_identity", "storage_scheme"]) +async def test_selected_pre_sql_requires_exact_live_source(intake, changed): + """Exercise the SQL source participant; not full PRE execution or T4 proof.""" + from app.core.hashing import canonical_json_hash + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + from app.adapters.projects import project_locked_policy_context_port + from app.adapters.artifacts import submission_intake_pre_source_port + from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest + from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + from app.modules.artifacts.selected_pre_submit_admission import ( + bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, + ) + + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + deadline = datetime.now(UTC) + timedelta(minutes=2) + source = await repository(session).seal( + operation, lease, 1, provider_generation="pre-source-generation", + pre_deadline_at=deadline, lease_expires_at=deadline, + ) + async with intake.factory.begin() as session: + task = await task_submission_context_port(session).lock_submission_context( + TaskSubmissionContextRequest( + task_id=intake.task, assignment_id=intake.assignment, + contributor_id=intake.actor.actor_profile_id, predecessor_submission_id=None, + ) + ) + references = task.locked_project_context + project = await project_locked_policy_context_port(session).lock_locked_policy_context( + ProjectLockedPolicyContextRequest(**{ + name: getattr(references, name) for name in ( + "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", + "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", + "pre_submit_policy_bundle_hash", + ) + }) + ) + guarded = await submission_intake_pre_source_port(session).lock_pre_source( + source=source, lease_id=lease, generation=1, + ) + metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + selected = bind_selected_pre_submit_admission( + task=task, project=project, predecessor=None, predecessor_rules_sha256=None, + predecessor_exists=False, + packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + ) + build_values = dict( + source=guarded, metadata=metadata, task=task, project=project, + attempt_id=new_record_id(), idempotency_key=UUID(row.idempotency_key), + selected=selected, runtime_profile=_source_reservation().runtime_profile, + ) + request = build_selected_pre_submit_reservation(**build_values) + assert request.admission_lineage.storage_scheme == "local" + if changed is None: + _assert_pre_reservation_rejects_substitution(build_values, guarded, metadata, selected) + body = request.canonical_body() + _substitute_pre_source_request(body, changed, deadline) + value = { + "source_operation_id": str(operation), "task_id": str(intake.task), + "project_id": row.project_id, "assignment_id": str(intake.assignment), + "actor_profile_id": str(new_record_id()) if changed == "actor" else row.actor_profile_id, + "identity_link_id": row.identity_link_id, "idempotency_key": row.idempotency_key, + "request_json": body, "archive_sha256": source.raw_sha256, + "archive_byte_count": source.raw_byte_count, "policy_sha256": request.policy_sha256, + } + async with intake.factory.begin() as session: + statement = text("""SELECT public.require_selected_pre_source( + jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)))""") + if changed is None: + await session.execute(statement, {"value": json.dumps(value)}) + else: + with pytest.raises(DBAPIError, match="selected PRE"): + await session.execute(statement, {"value": json.dumps(value)}) + await session.rollback() + from app.modules.checkers.models import SelectedPreSubmitRun + async with intake.factory.begin() as session: + session.add(SelectedPreSubmitRun( + id=str(request.attempt_id), source_operation_id=str(operation), + actor_profile_id=value["actor_profile_id"], identity_link_id=row.identity_link_id, + project_id=row.project_id, task_id=str(intake.task), assignment_id=str(intake.assignment), + idempotency_key=row.idempotency_key, request_json=body, + request_digest=canonical_json_hash(body), policy_sha256=request.policy_sha256, + default_behavior_sha256=request.default_behavior_sha256, + archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count, + execution_budget_ms=request.execution_budget_ms, status="queued", lease_generation=0, + )) + if changed is None: + await session.flush() + else: + with pytest.raises(DBAPIError, match="selected PRE"): + await session.flush() + await session.rollback() + if changed is None: + await _assert_pre_terminal_guards(intake, request) + + +@pytest.mark.parametrize("version", ["v1", "v2"]) +async def test_selected_pre_sql_audit_digest_keeps_versioned_custody(isolated_database_env, version): + from app.core.hashing import canonical_json_hash + from tests.checkers.external.test_selected_pre_submit_coordination import _retained_v1, _source_reservation + + retained = _retained_v1() + request = retained["request"] if version == "v1" else _source_reservation().canonical_body() + terminal = retained["terminal"] + execute = { + "schema_version": f"workstream.selected_pre_submit_execute.{version}", + "reservation": request, "lease_id": terminal["lease_id"], + "lease_generation": terminal["lease_generation"], "lease_expires_at": terminal["lease_expires_at"], + } + expected_execute = canonical_json_hash(execute) + expected_finalize = canonical_json_hash({ + "schema_version": f"workstream.selected_pre_submit_finalize.{version}", + "execute_facts_digest": expected_execute, + "execution": terminal["execution"], + "infrastructure_failure_code": terminal["infrastructure_failure_code"], + }) + value = { + "request_json": request, "lease_id": execute["lease_id"], + "lease_generation": execute["lease_generation"], "lease_expires_at": execute["lease_expires_at"], + "terminal_json": terminal, + } + engine = create_async_engine(isolated_database_env) + try: + async with engine.connect() as connection: + for phase, expected in (("execute", expected_execute), ("finalize", expected_finalize)): + actual = await connection.scalar(text("""SELECT public.selected_pre_submit_facts_digest( + jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)), + :phase)"""), {"value": json.dumps(value), "phase": phase}) + assert actual == expected + finally: + await engine.dispose() + + +async def _assert_pre_terminal_guards(intake, request): + """Claim with real AUTH, reject rebound terminal updates, then finalize once.""" + from app.modules.actors.api import ServiceIdentity + from tests.checkers.execution.support import provision_post_submit_service + from app.adapters.auth import selected_pre_submit_authority + from app.adapters.checkers import selected_pre_submit_coordinator + from app.core.hashing import canonical_json_hash + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitFinalizeFacts, SelectedPreSubmitTerminalFacts + from app.modules.checkers.models import SelectedPreSubmitRun + + await provision_post_submit_service(intake.factory, ServiceIdentity.CHECKER_PRE_SUBMIT) + async with intake.factory.begin() as session: + async with selected_pre_submit_authority(session).prepare_execution(request) as authority: + lease = await selected_pre_submit_coordinator(session).claim( + run_id=request.attempt_id, facts=request, authority=authority, + ) + finalize = SelectedPreSubmitFinalizeFacts( + lease=lease, execution=None, infrastructure_failure_code="capacity_exceeded", + ) + for changed in ("lease_id", "lease_expires_at", "started_at", "execute_evidence_id", + "schema_version", "reservation", "request_digest", "outcome", "terminal_digest", "extra"): + async with intake.factory.begin() as session: + async with selected_pre_submit_authority(session).prepare_finalization(finalize) as authority: + evidence = await authority.consume(finalize) + row = await session.get(SelectedPreSubmitRun, str(request.attempt_id)) + now = await session.scalar(text("select clock_timestamp()")) + terminal = SelectedPreSubmitTerminalFacts( + lease=lease, outcome="infrastructure_failed", execution=None, + infrastructure_failure_code="capacity_exceeded", queued_at=row.queued_at, + started_at=row.started_at, completed_at=now, + ).canonical_body() + values = dict( + id=request.attempt_id, lease_id=lease.lease_id, + lease_expires_at=lease.lease_expires_at, started_at=row.started_at, + execute_evidence_id=UUID(row.execute_evidence_id), completed_at=now, + finalize_evidence_id=evidence.evidence_id, + ) + claim_change = changed in {"lease_id", "lease_expires_at", "started_at", "execute_evidence_id"} + if changed in {"lease_id", "execute_evidence_id"}: + values[changed] = new_record_id() + if changed == "lease_id": + terminal[changed] = str(values[changed]) + elif changed in {"lease_expires_at", "started_at"}: + values[changed] -= timedelta(microseconds=1) + terminal[changed] = values[changed].isoformat() + elif changed == "schema_version": + terminal[changed] = "workstream.selected_pre_submit_terminal.v1" + elif changed == "reservation": + terminal[changed] = terminal[changed] | {"metadata_sha256": "sha256:" + "f" * 64} + elif changed == "request_digest": + terminal[changed] = "sha256:" + "f" * 64 + elif changed == "outcome": + terminal[changed] = "completed" + elif changed == "extra": + terminal["unexpected"] = True + values["terminal_json"] = json.dumps(terminal) + values["terminal_digest"] = ("sha256:" + "f" * 64 if changed == "terminal_digest" + else canonical_json_hash(terminal)) + message = "committed claim is immutable" if claim_change else "terminal binding mismatch" + with pytest.raises(DBAPIError, match=message): + await session.execute(text("""UPDATE selected_pre_submit_runs SET + status='infrastructure_failed', lease_id=:lease_id, lease_expires_at=:lease_expires_at, + started_at=:started_at, execute_evidence_id=:execute_evidence_id, + completed_at=:completed_at, finalize_evidence_id=:finalize_evidence_id, + terminal_json=CAST(:terminal_json AS jsonb), terminal_digest=:terminal_digest + WHERE id=:id"""), values) + await session.rollback() + async with intake.factory.begin() as session: + async with selected_pre_submit_authority(session).prepare_finalization(finalize) as authority: + completion = await selected_pre_submit_coordinator(session).finalize( + run_id=request.attempt_id, lease=lease, authority=authority, + execution=None, infrastructure_failure_code="capacity_exceeded", + ) + assert completion.terminal.outcome == "infrastructure_failed" + assert completion.capability is None + + +@pytest.mark.parametrize("intake", [True], indirect=True) +@pytest.mark.parametrize("materializer_enabled", [True, False]) +async def test_source_pre_execution_uses_committed_authorized_local_read(intake, materializer_enabled): + """Real source/SQL/AUTH composition with an explicitly failing runtime double.""" + from contextlib import aclosing + from app.adapters.artifacts import submission_intake_pre_source_port + from app.adapters.auth import selected_pre_submit_authority + from app.adapters.checkers import selected_pre_submit_coordinator, SelectedPreSubmitCheckerExecutionAdapter + from app.adapters.projects import project_locked_policy_context_port + from app.modules.actors.api import ServiceIdentity + from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization + from app.modules.artifacts.selected_pre_submit_admission import ( + bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, + ) + from app.modules.artifacts.selected_pre_submit_execution import ( + SelectedPreSubmitSourceReads, SelectedPreSubmitExecutionService, + ) + from app.modules.authorization.catalogue import ActionId + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable + from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest + from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest + from tests.artifact_store_helpers import initialize_local_store + from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer + from tests.checkers.execution.support import provision_post_submit_service + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + store = initialize_local_store(root=intake.durable_root, buffer_bytes=256 * 1024) + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation, foreground_lease = UUID(row.id), UUID(row.lease_id) + metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + key = UUID(row.idempotency_key) + source = await foreground_upload(intake, store).receive( + operation, foreground_lease, 1, foreground_bytes(), **foreground_limits(), + ) + async with intake.factory.begin() as session: + task = await task_submission_context_port(session).lock_submission_context( + TaskSubmissionContextRequest(intake.task, intake.assignment, intake.actor.actor_profile_id, None), + ) + references = task.locked_project_context + project = await project_locked_policy_context_port(session).lock_locked_policy_context( + ProjectLockedPolicyContextRequest(**{name: getattr(references, name) for name in ( + "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", + "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", "pre_submit_policy_bundle_hash", + )}), + ) + custody = await submission_intake_pre_source_port(session).lock_pre_source( + source=source, lease_id=foreground_lease, generation=1, + ) + selected = bind_selected_pre_submit_admission( + task=task, project=project, predecessor=None, predecessor_rules_sha256=None, + predecessor_exists=False, packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + ) + request = build_selected_pre_submit_reservation( + source=custody, metadata=metadata, task=task, project=project, + attempt_id=new_record_id(), idempotency_key=key, selected=selected, + runtime_profile=_source_reservation().runtime_profile, + ) + await selected_pre_submit_coordinator(session).reserve(request) + await provision_post_submit_service(intake.factory, ServiceIdentity.CHECKER_PRE_SUBMIT) + if materializer_enabled: + await _seed_materializer(intake.factory) + observed = [] + async with intake.factory() as session: + class ObservedStore: + def open_source(self, actual, *, maximum_chunk_bytes): + assert actual == source and not session.in_transaction() + assert maximum_chunk_bytes == 64 * 1024 + async def chunks(): + async with intake.factory.begin() as probe: + # Independent NOWAIT locks prove provider reads do not + # retain TASK or intake locks from either AUTH root. + for sql, params in ( + ("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE NOWAIT", {"id": intake.task}), + ("SELECT id FROM submission_intake_operations WHERE id=:id FOR UPDATE NOWAIT", {"id": operation}), + ): + assert (await probe.execute(text(sql), params)).one() + assert await probe.scalar(text( + "SELECT count(*) FROM audit_events WHERE action_id=:action AND resource_id=:id" + ), {"action": ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE.value, "id": str(operation)}) == 1 + async with aclosing(store.open_source(actual, maximum_chunk_bytes=maximum_chunk_bytes)) as reader: + async for chunk in reader: + observed.append(chunk) + yield chunk + return chunks() + class RuntimeFailure: + async def execute_pre(self, lease, grant): + async with aclosing(grant.open_source(lease=lease)) as reader: + assert b"".join([chunk async for chunk in reader]) == b"original source bytes" + raise SelectedPreSubmitInfrastructureUnavailable("capacity_exceeded") + authority = PreparedPreSubmitMaterializationAuthorization( + session, request_id=new_record_id(), correlation_id=new_record_id(), + ) + service = SelectedPreSubmitExecutionService( + session=session, coordinator=selected_pre_submit_coordinator(session), + authority=selected_pre_submit_authority(session), + source_reads=SelectedPreSubmitSourceReads( + session=session, sources=submission_intake_pre_source_port(session), + authority=authority, store=ObservedStore(), + ), execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=RuntimeFailure()), + ) + result = await service.execute(reservation=request) + assert result.capability is None and result.terminal.outcome == "infrastructure_failed" + assert result.terminal.infrastructure_failure_code == ( + "capacity_exceeded" if materializer_enabled else "material_unavailable" + ) + assert bool(observed) == materializer_enabled + store.close() From 83467c478329f9d2e44d45aa8aec607d70de61b9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:49:59 +0100 Subject: [PATCH 072/513] Keep extracted PRE source tests in shared PostgreSQL CI lanes --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++++++++ backend/scripts/test_lane_catalogue.py | 1 + backend/tests/test_ci_lane_catalogue.py | 4 ++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 796a93a7e..727d99816 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1601,3 +1601,14 @@ ignoring import placement confirms identical executable statements for the five moved tests and the existing terminal-guard helper. Structural validation passed, as did its 29 regression tests, new-module undefined/unused-name checks, and record/link checks. The ownership partition is byte-for-byte unchanged. + +QA/test-delta and CI-integrity review of `38440d466` confirmed assertion fidelity +but found the extracted module missing from the explicit shared-foundation CI +catalogue. The existing inventory test reproduced that omission. The repair +registers the module in that same family and updates its independent membership +fingerprint from 272 to 273 modules. All 229 ownership/catalogue tests pass. +Mapping the real 85-node collection through the production lane manifest builder +selects every node once; the 29 moved cases distribute across the three shared +foundation lanes as 3, 13 and 13. This proves selection, not another PostgreSQL +execution. CI review also independently confirmed a corrupted assertion-map +hash is rejected, with the original mapping as the passing control. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 609cdf79c..5f069ddca 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -54,6 +54,7 @@ class TestLane: "tests/artifacts/test_selected_predecessor_rules.py", "tests/artifacts/test_submission_intake_contracts.py", "tests/artifacts/test_submission_intake_custody.py", + "tests/artifacts/test_submission_pre_source.py", "tests/artifacts/test_submission_intake_admission.py", "tests/authorization/post_submit/test_atomicity.py", "tests/authorization/post_submit/test_concurrency.py", diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index da76e2051..83d8571e8 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -317,8 +317,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 272, - "47631a336f437eb3d3ddffe79a0a9f5f6ea8b1d02a418965ddb75dd4aa842844", + 273, + "9310a4ccbe9b8d842190a644403c72683ce321f4f7ef83cf35545ab965e17bf1", ), "project": ( 255, From ef3cfe81635d5f371332139f184660731aedec6e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:51:15 +0100 Subject: [PATCH 073/513] Record reviewed PRE source test extraction and lane selection --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 727d99816..843ab3269 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1612,3 +1612,11 @@ selects every node once; the 29 moved cases distribute across the three shared foundation lanes as 3, 13 and 13. This proves selection, not another PostgreSQL execution. CI review also independently confirmed a corrupted assertion-map hash is rejected, with the original mapping as the passing control. + +QA/test-delta and CI-integrity replay passed the repaired selection at clean +`83467c478`. The source tests and assertion map are unchanged from the reviewed +extraction. A fresh manifest build on that exact head also selects the same 85 +collected nodes once, including all 29 moved cases; this remains selection proof, +not a second database execution. Record/link checks pass. The structural repair +is complete within its scope. Native one-session execution, obsolete prepared +callers/fixtures, SQL result custody and T4/public delivery remain unfinished. From 6f3a2dbe5aced0b02bf4306af71b27670f351ec0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:52:36 +0100 Subject: [PATCH 074/513] Define native single-session PRE replacement and proof boundary --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 843ab3269..691b8b7ce 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1620,3 +1620,60 @@ collected nodes once, including all 29 moved cases; this remains selection proof not a second database execution. Record/link checks pass. The structural repair is complete within its scope. Native one-session execution, obsolete prepared callers/fixtures, SQL result custody and T4/public delivery remain unfinished. + +### Native combined PRE implementation boundary + +The next runtime change replaces the PRE branch of trusted intake plus exported +host tree plus separate project execution with one `execute_pre` handler on the +existing checker socket/factory. It is L0 security-sensitive work. Allowed files +are the existing Rust service/Smol lifecycle, guest/bootstrap/confinement code, +trusted Python worker/image, CHECKERS result/profile contracts and existing +adapter composition, their tests/fixtures, and affected ownership/lane/docs +records. Shared POST/trial behavior and retained evidence must remain intact. +No second PRE VM, host ZIP/tree spool, compatibility PRE grant, general egress, +new adapter factory, invented qualification or deployment resource defaults are +allowed. Architecture/security and QA/test-delta plan and implementation reviews +are required; human review should focus on trusted/project separation and +uncertain-create/destroy custody, not only completed-result shape. + +The existing Smol `Machine` writes a private lease and starts its guardian before +provider creation. Extend that same custody with exact PRE operation/run/request +and execution fence, and retain unsettled capacity through its existing admission +quarantine. Boot the selected approved project image once with the independent +static Workstream bootstrap. Inject the independently pinned platform root using +the existing verified root-bundle reader, then stream the sealed source with +bounded frames directly into protected guest storage. Runtime/profile matching +must precede allocation and byte admission; all quantities remain explicit. + +Inside that guest, the protected supervisor invokes the canonical Python archive +and default-checker owners from the independent platform root. The worker derives +the manifest, default input and nested project request from the locked source +reservation and inspected tree. A default blocker returns without starting project +code. Otherwise the supervisor launches exactly the selected project command in +its own user/mount/cgroup boundary with a read-only verified input view and +separate writable scratch. Trusted worker/control descriptors must not survive +into project code; project stdout/stderr cannot become trusted framing. The +supervisor remains outside the project OOM group. The existing project runner +should be refactored where needed rather than copied into a second confinement +implementation. The trusted worker validates the bounded project result and +constructs the combined evidence; CHECKERS independently validates it again. + +Extend the same response to carry actual invocation identity, exact runtime/profile +and typed conformance evidence, stage timing and cleanup obligation/disposition. +Source/member results alone remain insufficient for T4. Cleanup uncertainty may +retain a captured valid result only with its independently persisted obligation; +it must not release unsettled capacity. Native handler errors and disconnects +must unwind the same lease/guardian path. Remove obsolete PRE export/grant/default +commands and their consumers as the connected replacement lands, preserving the +separate POST archive consumer rather than adding a compatibility PRE branch. + +Proof must include real ZIP/default/request derivation; default rejection without +project start; wrong source/root/profile/fence refusal; bounded source/output and +aggregate deadline; cancellation during receive/default/project/cleanup; exact +pre-create lease and uncertain-destroy accounting; and adversarial project attempts +to alter input, signal the supervisor or forge control output. Shared POST/trial +regressions remain required. Portable workers/socket fakes and Rust tests prove +only their exercised contracts. This workspace currently has neither a Smol +binary nor `/dev/kvm`, and hosted backend CI only collects native qualification +fixtures; actual one-guest isolation qualification remains a required distinct +execution prerequisite, not an inferred pass from portable tests. From e47c89a48bc7e8958ff235ff6608704383d560ad Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 13:59:38 +0100 Subject: [PATCH 075/513] Resolve native PRE storage control and cleanup plan boundaries --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 691b8b7ce..a02a50325 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1677,3 +1677,74 @@ only their exercised contracts. This workspace currently has neither a Smol binary nor `/dev/kvm`, and hosted backend CI only collects native qualification fixtures; actual one-guest isolation qualification remains a required distinct execution prerequisite, not an inferred pass from portable tests. + +The native plan review required the following concrete decisions before code: + +- PRE does not use `Resources::from(ValidatedRequest)` and its fixed 1 GiB disk. + Resolve the pinned root descriptor and qualified PRE envelope first. Checked + peak disk admission sums root bundle spool + expanded platform root + exact raw + ZIP + maximum expanded submission tree + explicit project scratch + image + overlay + filesystem overhead. Reject arithmetic overflow or a total above + the locked temporary-disk budget. Round provider storage and overlay separately + to GiB and charge their full rounded amounts to node admission before create. + Root, ZIP, tree, scratch, inode/entry and control-buffer caps are enforced at + their writers. Scratch/overlay/overhead bounds are explicit qualified values, + never inferred from the old 1 GiB path or supplied as new deployment defaults. +- The existing persisted `Lease.name` is the discoverable invocation and cleanup + obligation identity. Its pre-create record additionally binds PRE operation, + run, request, source, profile and execution fence. A captured valid result may + return with cleanup `pending` only if that exact durable obligation remains + verified and the existing guardian/reaper owns it; node admission stays + quarantined. Confirmed destruction yields `destroyed`. Missing or rebound + obligation custody fails closed. PRE uses one create attempt, not the generic + project path's three-attempt loop. Shared POST/trial semantics are unchanged. +- One supervisor stays outside both child roots and both workload OOM groups. + First run a trusted child chrooted into the verified platform root, with only + the exact read-only source/request and protected extraction workspace. Then, + only after passing defaults, run the project child in its private namespace, + cgroup and non-root identity. Refactor the existing project confinement/output + machinery for this second phase instead of duplicating its policy. Before + either exec, duplicate only intended stdin/stdout/stderr/control descriptors + and close all others. Project code receives no platform worker pipe, source + spool, platform root, supervisor control or storage credential. Explicit + control/default/project resource partitions must fit the qualified aggregate; + a project OOM cannot put the supervisor in the same killable group. +- The canonical projection's in-memory snapshot closes after defaults, while + its verified files remain. The supervisor walks only the exact manifest via + anchored no-follow descriptors, sets root-owned directories to 0555 and files + to 0444 (0555 for executable entries), and binds that view read-only into the + project namespace. Its private parent remains 0700 and inaccessible there. + Test readable exact bytes alongside denied writes, chmod and rename; no host + tree copy or export is involved. The supervisor owns final guest cleanup. +- Qualified PRE configuration points to the existing WSROOT1 producer bundle, + its `RootDescriptor`, and explicit `RootLimits`. Match the bundle digest to + the locked profile's platform-root digest. Transfer the bounded bundle to a + guest-private spool and call `trusted_root::stage_root` before trusted worker + launch, validating manifest/config/default pins and expanded size/entry limits. + A library verifier with no caller is not evidence of this path. +- Use separate trusted control and project output frames. Project output is + bounded by both selected registry and profile limits, logs by the profile log + ceiling; trusted frames remain within the existing 64 MiB protocol ceiling + and the explicit control memory budget. Refuse partial, oversized or trailing + frames. Only the trusted supervisor/worker constructs source/default/profile + evidence. Project output is parsed solely as its registered result. +- Before allocation/source reads, the Rust handler validates the closed header, + canonical reservation/request/source digests, lease/fence relationships, + selected cached image and exact configured runtime/profile/root pins. The + authenticated local caller and backend ART grant own command/read authority; + self-consistent hashes are not independent authorization. Negative controls + must distinguish inconsistencies/rebound configured pins (refused before + create) from raw-byte mismatch (provable only during actual input loading). + Do not claim that a new internally consistent run identity can be rejected + without an independent authority reference. Guest and CHECKERS bind all + captured evidence back to this exact invocation. +- Add a dedicated pinned native PRE qualification case/harness; the existing + trial qualifier is not suitable. It must observe exactly one machine name, + persisted lease and create, worker then optional project under that guest, + root/source/profile pins, adversarial isolation probes, and cleanup or retained + quarantine. Portable tests instead use real ZIPs and an independent expected + manifest/default/request vector, including secret/unchanged blockers with an + incompatible project schema and a project-start sentinel. They reject host + manifest/default-input/export/prepared-generation commands. Native Smol/KVM + qualification remains unavailable locally and must not be relabeled portable + proof. Existing shared POST/trial fixtures retain their own behavior coverage. From b3aefe5594805a7176cae2ab4d2b83758f3ecf06 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:08:07 +0100 Subject: [PATCH 076/513] Derive combined PRE worker evidence directly from sealed source --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 31 ++ backend/tests/test_trusted_intake.py | 269 ++++++++++++------ external_checkers/intake/worker.py | 238 +++++++++++----- 3 files changed, 381 insertions(+), 157 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a02a50325..2646bd4df 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1748,3 +1748,34 @@ The native plan review required the following concrete decisions before code: manifest/default-input/export/prepared-generation commands. Native Smol/KVM qualification remains unavailable locally and must not be relabeled portable proof. Existing shared POST/trial fixtures retain their own behavior coverage. + +Architecture/security and QA plan replay passed `e47c89a48` for implementation, +not runtime qualification. The first implementation replaces the trusted worker's +PRE export/default dialogue with a closed source-reservation `execute_pre` entry. +The old prepared worker now accepts POST only and retains its archive export. +The PRE worker checks source byte count/hash, uses canonical ZIP inspection and +default evaluation, derives the manifest/default input/project request itself, +and never requests a project result after a blocker. Its private supervisor +control exchange binds the lease and request; a project result is schema-, +registry- and request-validated before combined source evidence is emitted. +Expiry is checked against both monotonic budget and the absolute lease. The +supervisor must still enforce interruption during blocking pipe reads and guest +work; these checks alone are not physical preemption. + +The focused worker module passes 45 tests, including real ZIP independent +manifest/hash expectations, unsafe archives, source substitution before parsing, +host-derived input refusal, rebound project results, one-use execution and POST +export retention. Secret and unchanged-work blockers use an incompatible selected +project schema and a project-request sentinel. Removing the blocker branch made +both controls fail; the production branch was restored. Ownership/catalogue +checks passed 229 tests, the protected partition is unchanged, and undefined/ +unused-name checks pass. Removed worker tests exercised the superseded PRE +export/default dialogue; their required source/default identity and no-repeat +invariants are covered by the source-derived and one-use replacements. + +This is an intermediate worker candidate. The Rust native handler/supervisor, +protected tree handoff, actual runtime/profile/cleanup envelope, old ART/public +caller removal, trusted image/root rebuild and actual Smol/KVM qualification are +still required. The existing old PRE controller cannot use the now POST-only +prepared worker and must be replaced, not shimmed. No runnable public cutover or +T4/accepted result authority is claimed by these portable worker tests. diff --git a/backend/tests/test_trusted_intake.py b/backend/tests/test_trusted_intake.py index 179abdcd2..711b7fc6d 100644 --- a/backend/tests/test_trusted_intake.py +++ b/backend/tests/test_trusted_intake.py @@ -15,20 +15,18 @@ import threading import zipfile -from pydantic import TypeAdapter import pytest from app.adapters.artifacts.trusted_intake import UnixSocketTrustedIntakeAdapter from app.core.identifiers import new_record_id from app.interfaces.external_services import ExternalServiceProtocolError -from app.interfaces.trusted_submission_intake import TrustedDefaultBinding, TrustedIntakePreparation +from app.interfaces.trusted_submission_intake import TrustedIntakePreparation from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits from app.modules.artifacts.submission_archive import SubmissionArchiveInspector from app.modules.artifacts.submission_manifest import build_submission_manifest from app.modules.checkers.api.default_checker import ( WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, WorkstreamDefaultCheckerInput, - workstream_default_input_sha256, ) from app.modules.checkers.api.material import SubmissionMaterialEntry from app.modules.checkers.api.pre_submit_material import SubmissionPacketView @@ -91,28 +89,7 @@ def _default(data: bytes) -> WorkstreamDefaultCheckerInput: ) -def _binding(value: WorkstreamDefaultCheckerInput) -> TrustedDefaultBinding: - return TrustedDefaultBinding( - new_record_id(), - _POLICY, - _POLICY, - value.semantic_manifest_sha256, - workstream_default_input_sha256(value), - ) - - -def _default_command(value, binding=None): - binding = binding or _binding(value) - return _command( - "default", - { - "binding": {**asdict(binding), "attempt_id": str(binding.attempt_id)}, - "input": TypeAdapter(WorkstreamDefaultCheckerInput).dump_python(value, mode="json"), - }, - ) - - -def _run(tmp_path, data, commands=b"", phase="pre_submit"): +def _run(tmp_path, data, commands=b"", phase="post_submit"): archive = tmp_path / "archive.zip" archive.write_bytes(data) workspace = tmp_path / "workspace" @@ -142,17 +119,6 @@ def _export_result(output, expected: bytes): assert _read(output)["operation"] == "export" -def test_worker_inspects_exports_and_runs_canonical_default_once(tmp_path): - data = _archive() - value = _default(data) - worker, output = _run(tmp_path, data, _command("export", {}) + _default_command(value) * 2) - with pytest.raises(ValueError, match="out of sequence"): - worker.run() - _export_result(output, b"finished work") - result = _read(output) - assert result["operation"] == "default" - assert all(check["status"] == "passed" for check in result["payload"]["checks"]) - assert output.read() == b"" # No second default response can be accepted. @pytest.mark.parametrize( @@ -173,35 +139,6 @@ def test_worker_preserves_canonical_zip_rejection_without_export(tmp_path, data, assert not (tmp_path / "escape").exists() -@pytest.mark.parametrize( - "mutation", ["before_export", "post", "policy", "manifest", "packet", "lease"] -) -def test_default_requires_export_and_exact_pre_custody(tmp_path, mutation): - data = _archive() - value = _default(data) - binding = _binding(value) - prefix = _command("export", {}) - if mutation == "before_export": - prefix = b"" - elif mutation == "policy": - binding = replace(binding, policy_sha256=_IMAGE) - elif mutation == "manifest": - binding = replace(binding, semantic_manifest_sha256=_IMAGE) - elif mutation == "packet": - value = replace(value, packet=SubmissionPacketView("Substituted", "Authorized")) - command = _default_command(value, binding) - if mutation == "lease": - command = command.replace(_LEASE.encode(), b"f" * 128) - worker, output = _run( - tmp_path, - data, - prefix + command, - phase="post_submit" if mutation == "post" else "pre_submit", - ) - with pytest.raises(ValueError): - worker.run() - assert b'"operation": "default"' not in output.getvalue() - assert b'"operation":"default"' not in output.getvalue() @pytest.mark.asyncio @@ -468,25 +405,193 @@ def unexpected_inspector(*args, **kwargs): assert output.read() == b"" -def test_worker_rejects_rehashed_entries_before_default_evaluation(tmp_path, monkeypatch): - """Consistent supplied hashes cannot replace the guest's observed inventory.""" + + +def _pre_worker(tmp_path, data, *, extra_startup=None, stored_data=None, result_change=None, reservation_change=None): + """Real ZIP/worker with simulated supervisor project result; no VM claim.""" + from app.modules.checkers.api.external import make_external_checker_execution_result + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation, _retained_v1 + + reservation = _source_reservation() + reservation = replace(reservation, source=reservation.source.model_copy(update={ + "raw_sha256": "sha256:" + hashlib.sha256(data).hexdigest(), "raw_byte_count": len(data), + })) + if reservation_change: + reservation = reservation_change(reservation) + lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at) + startup = {"operation": "execute_pre", "request": { + "protocol_version": "external_checker_service.v1", "operation": "execute_pre", + "reservation": reservation.canonical_body(), "request_digest": reservation.request_digest, + "lease_id": str(lease.lease_id), "lease_generation": 1, + "lease_expires_at": lease.lease_expires_at.isoformat(), + }, "isolation": _retained_v1("selected_pre_v1_completed")["terminal"]["execution"]["external_members"][0]["isolation"] | { + "platform_manifest_digest": reservation.policy.entries[0].registry.image_digest, + }} + if extra_startup: + startup["request"].update(extra_startup) + archive = tmp_path / "pre.zip" + archive.write_bytes(data if stored_data is None else stored_data) + workspace = tmp_path / "pre-tree" + workspace.mkdir(mode=0o700) + output = BytesIO() + class ProjectReply: + def __init__(self): + self.reply = None + self.calls = 0 + def read(self, count): + if self.reply is None: + self.calls += 1 + # This simulated supervisor responds only to the worker's own + # derived project request; it cannot supply a manifest/default. + framed = BytesIO(output.getvalue()) + message = _read(framed) + assert message["operation"] == "project" + from app.modules.checkers.api.external import ExternalCheckerExecutionRequest + request = ExternalCheckerExecutionRequest.model_validate_json(json.dumps(message["payload"]["request"])) + selected = reservation.policy.entries[0].registry + result = make_external_checker_execution_result( + request_digest=request.request_digest, registry_entry_id=selected.registry_entry_id, + registry_entry_digest=selected.entry_digest, phase="pre_submit", outcome="completed", + verdict="passed", findings=(), infrastructure_failure_code=None, + ).model_dump(mode="json") + body = {"request_digest": reservation.request_digest, "lease_id": str(lease.lease_id), + "lease_generation": 1, "result": result} + if result_change: + result_change(body) + self.reply = BytesIO(_frame(body)) + return self.reply.read(count) + reply = ProjectReply() + worker = _WORKER.PreSubmitWorker(startup=startup, archive=archive, workspace=workspace, reader=reply, writer=output) + return worker, output, reply, lease + + +def test_pre_worker_derives_source_manifest_defaults_and_project_request(tmp_path): + from app.core.hashing import canonical_json_hash + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts data = _archive() - original = _default(data) - forged = replace( - original, - entries=(replace(original.entries[0], executable=not original.entries[0].executable),), - ) - assert workstream_default_input_sha256(forged) != workstream_default_input_sha256(original) - worker, output = _run( - tmp_path, data, - _command("export", {}) + _default_command(forged, _binding(forged)), - ) + worker, output, reply, lease = _pre_worker(tmp_path, data) + worker.run() + output.seek(0) + project, completed = _read(output), _read(output) + assert project["operation"] == "project" and completed["operation"] == "completed" + assert output.read() == b"" and reply.calls == 1 + execution = SelectedPreSubmitExecutionFacts.from_canonical_body(completed["payload"]) + execution.validate_lease(lease) + assert execution.eligible + expected_manifest = {"schema_version": "workstream.submission_bundle_manifest.v1", "entries": [{ + "normalized_path": "work.txt", "entry_type": "file", "byte_count": 13, + "sha256": "sha256:" + hashlib.sha256(b"finished work").hexdigest(), "executable": False, + }]} + assert execution.manifest_body == expected_manifest + assert execution.manifest_sha256 == canonical_json_hash(expected_manifest) + assert execution.observed_source.raw_sha256 == "sha256:" + hashlib.sha256(data).hexdigest() + assert project["payload"]["request"]["input"]["manifest"] == expected_manifest["entries"] + with pytest.raises(ValueError, match="already consumed"): + worker.run() + + +@pytest.mark.parametrize("data", [b"not a zip", _archive("../escape"), _archive(content=b"-----BEGIN RSA PRIVATE KEY-----\nsecret")]) +def test_pre_worker_default_blocker_never_requests_project(tmp_path, data): + worker, output, reply, lease = _pre_worker(tmp_path, data) + worker.run() + output.seek(0) + result = _read(output) + assert result["operation"] == "completed" and result["payload"]["eligible"] is False + assert reply.calls == 0 and result["payload"]["external_members"] == [] + assert output.read() == b"" and not (tmp_path / "escape").exists() + + +@pytest.mark.parametrize("field", ["manifest", "default_input", "prepared_generation_id"]) +def test_pre_worker_refuses_host_derived_inputs(tmp_path, field): + with pytest.raises(ValueError, match="protocol invalid"): + _pre_worker(tmp_path, _archive(), extra_startup={field: {}}) - def must_not_evaluate(*args): - pytest.fail("substituted observed entries reached the default evaluator") - monkeypatch.setattr(_WORKER, "evaluate_verified_archive", must_not_evaluate) - with pytest.raises(ValueError, match="default custody differs"): +@pytest.mark.parametrize("stored", [b"different", b"", _archive() + b"extra"]) +def test_pre_worker_refuses_source_substitution_before_inspection(tmp_path, monkeypatch, stored): + worker, output, reply, _ = _pre_worker(tmp_path, _archive(), stored_data=stored) + def forbidden(*args): + raise AssertionError("substituted source reached ZIP inspector") + monkeypatch.setattr(_WORKER, "SubmissionArchiveInspector", forbidden) + with pytest.raises(ValueError, match="source identity differs"): + worker.run() + assert output.getvalue() == b"" and reply.calls == 0 + + +def test_post_worker_export_remains_available_and_prepared_pre_is_refused(tmp_path): + worker, output = _run(tmp_path, _archive(), _command("export", {})) + with pytest.raises(EOFError): worker.run() _export_result(output, b"finished work") - assert output.read() == b"" + other = tmp_path / "pre" + other.mkdir() + with pytest.raises(ValueError, match="POST-only"): + _run(other, _archive(), phase="pre_submit") + + +@pytest.mark.parametrize("changed", ["lease_id", "lease_generation", "request_digest", "result_request", "export"]) +def test_pre_worker_refuses_rebound_project_result(tmp_path, changed): + from app.modules.checkers.api.external import external_checker_json_hash + def mutate(body): + if changed == "result_request": + body["result"]["request_digest"] = _POLICY + body["result"]["result_digest"] = external_checker_json_hash({ + k: v for k, v in body["result"].items() if k != "result_digest" + }) + elif changed == "export": + body["operation"] = "export" + else: + body[changed] = {"lease_id": str(new_record_id()), "lease_generation": 2, "request_digest": _POLICY}[changed] + worker, output, reply, _ = _pre_worker(tmp_path, _archive(), result_change=mutate) + with pytest.raises(ValueError): + worker.run() + output.seek(0) + assert _read(output)["operation"] == "project" + assert output.read() == b"" and reply.calls == 1 + + +@pytest.mark.parametrize("blocker", ["secret", "unchanged"]) +def test_pre_worker_blocker_bypasses_incompatible_selected_schema(tmp_path, blocker): + from app.modules.checkers.api.default_checker import WorkstreamDefaultPredecessor + from app.modules.checkers.api.external import external_checker_json_hash + from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy + from tests.checkers.external.support import registry_entry + data = _archive(content=b"-----BEGIN RSA PRIVATE KEY-----\nsecret") if blocker == "secret" else _archive() + def changed(reservation): + binding = reservation.policy.entries[0].model_copy(update={"registry": registry_entry()}) + body = reservation.policy.model_dump(mode="json", exclude={"policy_sha256"}) + body["entries"] = [binding.model_dump(mode="json")] + policy = LockedExternalPreSubmitPolicy.model_validate_json(json.dumps(body | {"policy_sha256": external_checker_json_hash(body)})) + reservation = replace(reservation, policy=policy, admission_lineage=replace( + reservation.admission_lineage, effective_plan_sha256=policy.policy_sha256, + )) + if blocker == "unchanged": + manifest = build_submission_manifest(SubmissionArchiveInspector(SubmissionArchiveLimits()).inspect(BytesIO(data))) + predecessor = WorkstreamDefaultPredecessor(new_record_id(), 1, reservation.source.raw_sha256, manifest.sha256) + reservation = replace(reservation, default_context=replace( + reservation.default_context, predecessor=predecessor, current_predecessor=predecessor, + predecessor_exists=True, predecessor_rules_sha256=reservation.default_context.current_rules_sha256, + ), admission_lineage=replace(reservation.admission_lineage, + predecessor_submission_id=predecessor.submission_id, predecessor_submission_version=1, + checker_remediation_manifest_id=new_record_id(), + )) + return reservation + worker, output, reply, _ = _pre_worker(tmp_path, data, reservation_change=changed) + worker.run() + output.seek(0) + completed = _read(output) + assert completed["operation"] == "completed" and reply.calls == 0 + checks = completed["payload"]["workstream_default"]["checks"] + expected = "high_confidence_secret_detected" if blocker == "secret" else "submission_archive_unchanged" + assert any(check["failure_code"] == expected for check in checks) + assert completed["payload"]["external_members"] == [] and output.read() == b"" + + +def test_pre_worker_expired_budget_never_reads_source_or_requests_project(tmp_path, monkeypatch): + worker, output, reply, _ = _pre_worker(tmp_path, _archive()) + monkeypatch.setattr(_WORKER.time, "monotonic", lambda: worker._deadline + 1) + worker._archive.unlink() + with pytest.raises(TimeoutError, match="deadline"): + worker.run() + assert reply.calls == 0 and output.getvalue() == b"" diff --git a/external_checkers/intake/worker.py b/external_checkers/intake/worker.py index 48c709ead..1eedd4112 100644 --- a/external_checkers/intake/worker.py +++ b/external_checkers/intake/worker.py @@ -13,12 +13,12 @@ from pathlib import Path import struct import sys +import time from typing import BinaryIO from pydantic import TypeAdapter from app.interfaces.trusted_submission_intake import ( - TrustedDefaultBinding, TrustedIntakePreparation, ) from app.modules.artifacts.api.submission_archive import ( @@ -32,8 +32,6 @@ from app.modules.artifacts.submission_manifest import build_submission_manifest from app.modules.checkers.api.default_checker import ( WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - WorkstreamDefaultCheckerInput, - WorkstreamDefaultContext, workstream_default_input_sha256, ) from app.modules.checkers.api.material import SubmissionMaterialEntry @@ -73,7 +71,7 @@ def read_file(self, normalized_path: str, *, maximum_bytes: int) -> bytes: class IntakeWorker: - """One archive and one default invocation inside one prepared VM lifetime.""" + """POST-only archive inspection/export; no PRE default or project commands.""" def __init__( self, @@ -91,6 +89,8 @@ def __init__( self._preparation = TypeAdapter(TrustedIntakePreparation).validate_json( json.dumps(startup["preparation"]), strict=True ) + if self._preparation.phase != "post_submit": + raise ValueError("prepared intake is POST-only") self._archive = archive self._workspace = workspace self._reader = reader @@ -161,7 +161,6 @@ def run(self) -> None: except SubmissionArchiveRejectedError as exc: self._reply("inspect", {"code": exc.code.value}, status="error") return - manifest = build_submission_manifest(inspection) self._reply( "inspect", { @@ -188,83 +187,172 @@ def run(self) -> None: self._writer.flush() self._reply("export", {}) self._state = "exported" - elif ( - operation == "default" - and self._state == "exported" - and self._preparation.phase == "pre_submit" - ): - _object(payload, {"binding", "input"}) - _object( - payload["binding"], - {field.name for field in fields(TrustedDefaultBinding)}, - ) - binding = TypeAdapter(TrustedDefaultBinding).validate_json( - json.dumps(payload["binding"]), strict=True - ) - raw = _object( - payload["input"], - {field.name for field in fields(WorkstreamDefaultCheckerInput)}, - ) - _object(raw["packet"], {"summary", "contributor_attestation"}) - for predecessor in (raw["predecessor"], raw["current_predecessor"]): - if predecessor is not None: - _object( - predecessor, - { - "submission_id", - "submission_version", - "archive_sha256", - "semantic_manifest_sha256", - }, - ) - if type(raw["entries"]) is not list: - raise ValueError("default entries invalid") - for entry in raw["entries"]: - _object( - entry, - {field.name for field in fields(SubmissionMaterialEntry)}, - ) - value = TypeAdapter(WorkstreamDefaultCheckerInput).validate_json( - json.dumps(raw), strict=True - ) - material = _Material(tree) - derived = WorkstreamDefaultContext( - predecessor=value.predecessor, - predecessor_exists=value.predecessor_exists, - current_predecessor=value.current_predecessor, - current_rules_sha256=value.current_rules_sha256, - predecessor_rules_sha256=value.predecessor_rules_sha256, - packet=value.packet, - ).bind_verified_input( - archive_sha256=self._startup["archive_sha256"], - archive_byte_count=size, - archive_media_type="application/zip", - semantic_manifest_sha256=manifest.sha256, - entries=material.entries, - ) - if ( - value != derived - or binding.policy_sha256 != self._preparation.policy_sha256 - or binding.semantic_manifest_sha256 != manifest.sha256 - or value.semantic_manifest_sha256 != manifest.sha256 - or value.archive_sha256 != self._startup["archive_sha256"] - or value.archive_byte_count != size - or binding.default_input_sha256 - != workstream_default_input_sha256(value) - ): - raise ValueError("default custody differs") - self._state = "evaluating" - result = evaluate_verified_archive(derived, material) - self._reply("default", result.model_dump(mode="json")) - self._state = "evaluated" else: raise ValueError("intake operation out of sequence") +class PreSubmitWorker: + """Trusted source-derived PRE stages; the guest supervisor owns project exec.""" + + def __init__(self, *, startup, archive, workspace, reader, writer): + from datetime import UTC, datetime + from uuid import UUID + from app.modules.checkers.api.selected_pre_submit import ( + ExternalPreSubmitIsolationFacts, SelectedPreSubmitLeaseFacts, + SelectedPreSubmitReservationFacts, + ) + _object(startup, {"operation", "request", "isolation"}) + if startup["operation"] != "execute_pre": + raise ValueError("PRE operation invalid") + header = _object(startup["request"], { + "protocol_version", "operation", "reservation", "request_digest", + "lease_id", "lease_generation", "lease_expires_at", + }) + if header["protocol_version"] != "external_checker_service.v1" or header["operation"] != "execute_pre": + raise ValueError("PRE request invalid") + reservation = SelectedPreSubmitReservationFacts.from_canonical_body(header["reservation"]) + if header["request_digest"] != reservation.request_digest: + raise ValueError("PRE request digest differs") + self._lease = SelectedPreSubmitLeaseFacts( + reservation, UUID(header["lease_id"]), header["lease_generation"], + datetime.fromisoformat(header["lease_expires_at"]), + ) + self._isolation = ExternalPreSubmitIsolationFacts(**_object( + startup["isolation"], {field.name for field in fields(ExternalPreSubmitIsolationFacts)}, + )) + selected = reservation.policy.entries[0].registry + if (self._isolation.platform_manifest_digest != selected.image_digest + or reservation.default_behavior_sha256 != WORKSTREAM_DEFAULT_BEHAVIOR_SHA256): + raise ValueError("PRE selected identity differs") + self._deadline = time.monotonic() + min( + (self._lease.lease_expires_at - datetime.now(UTC)).total_seconds(), + reservation.execution_budget_ms / 1000, + ) + self._archive, self._workspace = archive, workspace + self._reader, self._writer = reader, writer + self._started = False + + def _check(self): + from datetime import UTC, datetime + if time.monotonic() >= self._deadline or datetime.now(UTC) >= self._lease.lease_expires_at: + raise TimeoutError("PRE deadline exceeded") + + def _reply(self, operation, payload): + self._check() + raw = json.dumps({ + "protocol_version": "workstream.pre_submit_worker.v1", + "operation": operation, "request_digest": self._lease.reservation.request_digest, + "lease_id": str(self._lease.lease_id), "lease_generation": self._lease.lease_generation, + "payload": payload, + }, allow_nan=False, separators=(",", ":")).encode() + if len(raw) > _MAX_FRAME: + raise ValueError("PRE control frame exceeds limit") + self._writer.write(struct.pack(">I", len(raw))) + self._writer.write(raw) + self._writer.flush() + self._check() + + def _project_result(self, request): + from app.modules.checkers.api.external import ExternalCheckerExecutionResult + self._check() + size = struct.unpack(">I", _read_exact(self._reader, 4))[0] + if not 0 < size <= min(_MAX_FRAME, request.registry.resources.maximum_output_bytes + 1024): + raise ValueError("PRE project output exceeds limit") + body = _object(json.loads(_read_exact(self._reader, size)), { + "request_digest", "lease_id", "lease_generation", "result", + }) + if (body["request_digest"] != self._lease.reservation.request_digest + or body["lease_id"] != str(self._lease.lease_id) + or type(body["lease_generation"]) is not int + or body["lease_generation"] != self._lease.lease_generation): + raise ValueError("PRE project control binding differs") + result = ExternalCheckerExecutionResult.model_validate_json(json.dumps(body["result"])) + result.validate_request(request) + result.validate_registry(self._lease.reservation.policy.entries[0].registry) + self._check() + return result + + def _finish(self, default, manifest=None, default_input=None, members=()): + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts + reservation = self._lease.reservation + facts = SelectedPreSubmitExecutionFacts( + request_digest=reservation.request_digest, lease_id=self._lease.lease_id, + lease_generation=self._lease.lease_generation, observed_source=reservation.source, + manifest_body=manifest.as_dict() if manifest else None, + manifest_sha256=manifest.sha256 if manifest else None, + default_input_sha256=workstream_default_input_sha256(default_input) if default_input else None, + policy_sha256=reservation.policy_sha256, workstream_default=default, + required_external_count=1, external_members=members, + eligible=default.eligible and len(members) == 1 and members[0].result.verdict == "passed", + ) + facts.validate_lease(self._lease) + self._reply("completed", facts.canonical_body()) + + def run(self): + from app.modules.checkers.api.selected_pre_submit import ( + ExternalPreSubmitMemberFacts, derive_selected_pre_submit_default_input, + derive_selected_pre_submit_input, + ) + from app.modules.checkers.default_checker import evaluate_rejected_archive + if self._started: + raise ValueError("PRE worker already consumed") + self._started = True + self._check() + reservation = self._lease.reservation + source = reservation.source + with self._archive.open("rb") as archive: + digest, size = hashlib.sha256(), 0 + while chunk := archive.read(_CHUNK): + self._check() + size += len(chunk) + if size > source.raw_byte_count: + raise ValueError("PRE source identity differs") + digest.update(chunk) + if size != source.raw_byte_count or "sha256:" + digest.hexdigest() != source.raw_sha256: + raise ValueError("PRE source identity differs") + inspector = SubmissionArchiveInspector(reservation.runtime_profile.archive_limits) + try: + inspection = inspector.inspect(archive) + manifest = build_submission_manifest(inspection) + value = derive_selected_pre_submit_default_input( + self._lease, manifest_body=manifest.as_dict(), manifest_sha256=manifest.sha256, + ) + with inspector._projected_tree(archive, self._workspace, expected=inspection) as tree: + default = evaluate_verified_archive(value, _Material(tree)) + except SubmissionArchiveRejectedError as exc: + self._finish(evaluate_rejected_archive(exc.code.value, packet=reservation.default_context.packet)) + return + self._check() + # Closing the canonical snapshot releases its byte cache; the verified + # files remain for the supervisor's private read-only mount handoff. + if not default.eligible: + self._finish(default, manifest, value) + return + _, request = derive_selected_pre_submit_input( + self._lease, manifest_body=manifest.as_dict(), manifest_sha256=manifest.sha256, + ) + self._reply("project", { + "request": request.model_dump(mode="json"), "manifest": manifest.as_dict(), + }) + result = self._project_result(request) + if result.outcome != "completed": + self._reply("infrastructure_failed", {"code": result.infrastructure_failure_code}) + return + selected = reservation.policy.entries[0] + member = ExternalPreSubmitMemberFacts( + order=0, requirement_id=selected.requirement_id, + registry_entry_id=selected.registry.registry_entry_id, + registry_entry_digest=selected.registry.entry_digest, + request_digest=request.request_digest, result=result, isolation=self._isolation, + ) + self._finish(default, manifest, value, (member,)) + + def main() -> None: # Paths are fixed image/bootstrap contracts, never provided by a contributor. startup = json.loads(Path("/work/request.json").read_bytes()) - IntakeWorker( + worker = PreSubmitWorker if startup.get("operation") == "execute_pre" else IntakeWorker + worker( startup=startup, archive=Path("/work/input/archive.zip"), workspace=Path("/work/scratch"), From 7f7b5c122317466c1f7bf17fac76d5a94626fbb6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:12:30 +0100 Subject: [PATCH 077/513] Discriminate PRE source hashing and independently derived defaults --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++++++ backend/tests/test_trusted_intake.py | 23 ++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2646bd4df..12ed0fff3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1779,3 +1779,14 @@ caller removal, trusted image/root rebuild and actual Smol/KVM qualification are still required. The existing old PRE controller cannot use the now POST-only prepared worker and must be replaced, not shimmed. No runnable public cutover or T4/accepted result authority is claimed by these portable worker tests. + +Worker review at `b3aefe559` found no code defect but required two stronger proof +atoms. The positive ZIP case now builds the default-input body independently of +the production derivation/serializer and checks its digest plus all four exact +passing default outcomes. A same-length corrupt ZIP joins the source substitutions. +The expanded module passes 46 cases. Removing only the raw SHA comparison makes +exactly the same-length case fail while the three size controls pass. Changing +the shared default-input serializer's rules digest makes the independent expected +digest assertion fail even though production producer and validator agree with +each other. Both mutations were reverted. These probes establish portable source +and default derivation checks, not runtime/profile or native isolation evidence. diff --git a/backend/tests/test_trusted_intake.py b/backend/tests/test_trusted_intake.py index 711b7fc6d..4c1c30264 100644 --- a/backend/tests/test_trusted_intake.py +++ b/backend/tests/test_trusted_intake.py @@ -485,6 +485,27 @@ def test_pre_worker_derives_source_manifest_defaults_and_project_request(tmp_pat }]} assert execution.manifest_body == expected_manifest assert execution.manifest_sha256 == canonical_json_hash(expected_manifest) + # Build the expected default input independently of the production input + # derivation and serializer; only canonical JSON hashing is shared. + expected_default_input = { + "schema_version": "workstream.default_checker_input.v1", + "archive_sha256": "sha256:" + hashlib.sha256(data).hexdigest(), + "archive_byte_count": len(data), "archive_media_type": "application/zip", + "semantic_manifest_sha256": canonical_json_hash(expected_manifest), + "entries": expected_manifest["entries"], "predecessor": None, + "predecessor_exists": False, "current_predecessor": None, + "current_rules_sha256": lease.reservation.default_context.current_rules_sha256, + "predecessor_rules_sha256": None, + "packet_sha256": canonical_json_hash({"summary": "", "contributor_attestation": ""}), + } + assert execution.default_input_sha256 == canonical_json_hash(expected_default_input) + assert [(check.check_id, check.status, check.failure_code, check.finding_count) + for check in execution.workstream_default.checks] == [ + ("archive_safe", "passed", None, 0), + ("received_identity_exact", "passed", None, 0), + ("high_confidence_secrets_absent", "passed", None, 0), + ("submission_changed_for_current_rules", "passed", None, 0), + ] assert execution.observed_source.raw_sha256 == "sha256:" + hashlib.sha256(data).hexdigest() assert project["payload"]["request"]["input"]["manifest"] == expected_manifest["entries"] with pytest.raises(ValueError, match="already consumed"): @@ -508,7 +529,7 @@ def test_pre_worker_refuses_host_derived_inputs(tmp_path, field): _pre_worker(tmp_path, _archive(), extra_startup={field: {}}) -@pytest.mark.parametrize("stored", [b"different", b"", _archive() + b"extra"]) +@pytest.mark.parametrize("stored", [b"different", b"", _archive() + b"extra", b"Q" + _archive()[1:]]) def test_pre_worker_refuses_source_substitution_before_inspection(tmp_path, monkeypatch, stored): worker, output, reply, _ = _pre_worker(tmp_path, _archive(), stored_data=stored) def forbidden(*args): From ae38d839327976888d199a7fc84325b9bfc7bf2c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:13:25 +0100 Subject: [PATCH 078/513] Record reviewed source-derived PRE worker proof --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 12ed0fff3..7c0ea40f7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1790,3 +1790,10 @@ the shared default-input serializer's rules digest makes the independent expecte digest assertion fail even though production producer and validator agree with each other. Both mutations were reverted. These probes establish portable source and default derivation checks, not runtime/profile or native isolation evidence. + +Architecture/security and QA/test-delta replay passed the worker scope at clean +`7f7b5c122`. Both reviewers verified the independent default vector and the +same-length SHA negative control against the discriminating mutation logs. +Record/link checks pass. The next connected implementation is the native +single-guest supervisor/service path with the reviewed storage, FD, profile and +cleanup boundaries; the portable worker does not complete that path. From 2625b20625e8978bc191804614e2b268d82e63df Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:21:42 +0100 Subject: [PATCH 079/513] Return captured project evidence to the guest supervisor --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 27 +++ .../workstream-checker-guest/src/main.rs | 208 ++++++++++++++++-- 2 files changed, 213 insertions(+), 22 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 7c0ea40f7..6369ef45c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1797,3 +1797,30 @@ same-length SHA negative control against the discriminating mutation logs. Record/link checks pass. The next connected implementation is the native single-guest supervisor/service path with the reviewed storage, FD, profile and cleanup boundaries; the portable worker does not complete that path. + +The native guest's existing project runner now returns captured child evidence +instead of writing completion and exiting the trusted supervisor itself. Its +ordinary Project entry still emits the same completion header, opaque stdout/ +stderr bytes and classified exit code. This lets the combined PRE caller consume +the result in a later phase of the same guest without duplicating confinement or +starting another VM. Kernel OOM evidence remains authoritative; a project-chosen +capacity exit code still becomes infrastructure failure rather than forged OOM. + +Both existing workload exec sites now mark every non-stdio descriptor +close-on-exec in the forked child before the syscall filter and exec. Intended +stdio is installed by the existing `Command::exec` setup. This closes the future +trusted-worker/control descriptor inheritance boundary for PRE while preserving +the parent's live descriptors. Unsupported close-range enforcement fails closed. +A real local fork/exec test creates a deliberately inheritable high descriptor, +proves it is absent after exec, confirms redirected stdout still works, and +checks the parent descriptor remains inheritable. Replacing the guard with a +no-op makes that test fail; production code was restored. Separate framing tests +keep project-written fake completion JSON opaque under the trusted header and +preserve OOM/output-overflow classification. + +The guest crate passes 12 library and 27 binary tests; 38 shared Smol service +unit tests also pass. These are host-process/kernel and contract checks, not +native guest isolation qualification. The PRE service handler, two-child guest +orchestration, bounded root/source staging, resource/profile/cleanup envelope and +public cutover remain the connected implementation work. This supporting guest +refactor is not a new readiness or merge milestone. diff --git a/external_checkers/workstream-checker-guest/src/main.rs b/external_checkers/workstream-checker-guest/src/main.rs index 59a9d93a7..052d17666 100644 --- a/external_checkers/workstream-checker-guest/src/main.rs +++ b/external_checkers/workstream-checker-guest/src/main.rs @@ -285,11 +285,14 @@ fn create_capability_socket(path: &str, uid: u32, gid: u32) -> Result Result<()> { + write_guest_header_to(header, &mut std::io::stdout().lock()) +} + +fn write_guest_header_to(header: &GuestIoHeader, output: &mut impl Write) -> Result<()> { let bytes = serde_json::to_vec(header)?; if bytes.is_empty() || bytes.len() > 4096 { return Err("guest I/O header invalid".into()); } - let mut output = std::io::stdout().lock(); output.write_all(&(bytes.len() as u32).to_be_bytes())?; output.write_all(&bytes)?; output.flush()?; @@ -617,6 +620,25 @@ fn drop_privileges(uid: u32, gid: u32) -> Result<()> { syscall_ok(unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) })?; Ok(()) } +fn seal_exec_descriptors() -> Result<()> { + // Mark every non-stdio descriptor close-on-exec in the forked child. The + // command's intended stdin/stdout/stderr are duplicated onto 0/1/2 by exec. + // This also covers future trusted-worker pipes held by the PRE supervisor. + let result = unsafe { + libc::syscall( + libc::SYS_close_range, + 3u32, + u32::MAX, + libc::CLOSE_RANGE_CLOEXEC, + ) + }; + if result == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error().into()) + } +} + fn supervised_exit(status: i32, oom_kills: u64) -> i32 { if oom_kills > 0 { CAPACITY_EXIT_CODE @@ -647,6 +669,45 @@ fn finish_workload_cgroup() -> Result { Err("workload descendants did not stop".into()) } +/// Captured child evidence. Returning it leaves the trusted supervisor alive +/// for combined PRE validation; ordinary project execution emits its wire frame. +struct ProjectOutcome { + status: i32, + oom_kills: u64, + output_exceeded: bool, + stdout: Vec, + stderr: Vec, +} + +impl ProjectOutcome { + fn exit_code(&self) -> i32 { + if self.output_exceeded && self.oom_kills == 0 { + 125 + } else { + supervised_exit(self.status, self.oom_kills) + } + } + + fn write_completion(&self, output: &mut impl Write) -> Result<()> { + write_guest_header_to( + &GuestIoHeader::Completed { + protocol_version: GUEST_IO_PROTOCOL.into(), + exit_code: libc::WIFEXITED(self.status).then(|| libc::WEXITSTATUS(self.status)), + signal: libc::WIFSIGNALED(self.status).then(|| libc::WTERMSIG(self.status)), + oom_kills: self.oom_kills, + output_exceeded: self.output_exceeded, + stdout_bytes: u32::try_from(self.stdout.len())?, + stderr_bytes: u32::try_from(self.stderr.len())?, + }, + output, + )?; + output.write_all(&self.stdout)?; + output.write_all(&self.stderr)?; + output.flush()?; + Ok(()) + } +} + fn run_project( job: GuestJob, capabilities: GuestCapabilities, @@ -655,7 +716,7 @@ fn run_project( cpu: u64, memory: u64, maximum_output_bytes: usize, -) -> Result<()> { +) -> Result { bind_project_materials(&staged)?; let model = capabilities .model @@ -697,6 +758,7 @@ fn run_project( } drop(stdout_child); drop(stderr_child); + seal_exec_descriptors().map_err(|error| format!("descriptor policy: {error}"))?; install_workload_filter().map_err(|error| format!("syscall policy: {error}"))?; let mut command = Command::new(&job.command[0]); command @@ -806,32 +868,131 @@ fn run_project( } else { (stdout, stderr) }; - let exit_code = libc::WIFEXITED(status).then(|| libc::WEXITSTATUS(status)); - let signal = libc::WIFSIGNALED(status).then(|| libc::WTERMSIG(status)); - write_guest_header(&GuestIoHeader::Completed { - protocol_version: GUEST_IO_PROTOCOL.into(), - exit_code, - signal, + Ok(ProjectOutcome { + status, oom_kills, output_exceeded, - stdout_bytes: stdout.len() as u32, - stderr_bytes: stderr.len() as u32, - })?; - let mut output = std::io::stdout().lock(); - output.write_all(&stdout)?; - output.write_all(&stderr)?; - output.flush()?; - std::process::exit(if output_exceeded && oom_kills == 0 { - 125 - } else { - supervised_exit(status, oom_kills) - }); + stdout, + stderr, + }) } #[cfg(test)] mod tests { use super::*; use std::time::Instant; + #[test] + fn captured_project_output_stays_payload_under_trusted_completion() { + let untrusted = br#"{"kind":"completed","oom_kills":0,"exit_code":0}"#.to_vec(); + let outcome = ProjectOutcome { + status: 7 << 8, + oom_kills: 0, + output_exceeded: false, + stdout: untrusted.clone(), + stderr: b"diagnostic".to_vec(), + }; + let mut bytes = Vec::new(); + outcome.write_completion(&mut bytes).unwrap(); + let length = u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize; + let header: GuestIoHeader = serde_json::from_slice(&bytes[4..4 + length]).unwrap(); + let GuestIoHeader::Completed { + exit_code, + signal, + oom_kills, + output_exceeded, + stdout_bytes, + stderr_bytes, + .. + } = header + else { + panic!("wrong control frame") + }; + assert_eq!(exit_code, Some(7)); + assert_eq!(signal, None); + assert_eq!(oom_kills, 0); + assert!(!output_exceeded); + assert_eq!(stdout_bytes as usize, untrusted.len()); + assert_eq!(stderr_bytes, 10); + assert_eq!( + &bytes[4 + length..], + [untrusted, b"diagnostic".to_vec()].concat() + ); + assert_eq!(outcome.exit_code(), 125); + // Capturing/writing the outcome returns instead of exiting the supervisor. + assert_eq!(outcome.stdout.len(), stdout_bytes as usize); + } + + #[test] + fn captured_project_exit_preserves_trusted_oom_and_output_classification() { + for (status, oom_kills, output_exceeded, expected) in [ + (0, 0, false, 0), + (0, 0, true, 125), + (CAPACITY_EXIT_CODE << 8, 0, false, 125), + (libc::SIGKILL, 1, false, CAPACITY_EXIT_CODE), + (libc::SIGKILL, 1, true, CAPACITY_EXIT_CODE), + ] { + let outcome = ProjectOutcome { + status, + oom_kills, + output_exceeded, + stdout: Vec::new(), + stderr: Vec::new(), + }; + assert_eq!(outcome.exit_code(), expected); + } + } + + #[test] + fn exec_descriptor_sealing_is_child_local_and_keeps_stdio() { + let source = File::open("/dev/null").unwrap(); + // Deliberately inheritable, unlike Rust's normal CLOEXEC file opens. + let descriptor = unsafe { libc::fcntl(source.as_raw_fd(), libc::F_DUPFD, 200) }; + assert!(descriptor >= 200); + let owned = unsafe { File::from_raw_fd(descriptor) }; + assert_eq!( + unsafe { libc::fcntl(descriptor, libc::F_GETFD) } & libc::FD_CLOEXEC, + 0 + ); + let (mut output, child_output) = UnixStream::pair().unwrap(); + output + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut command = Command::new("/bin/sh"); + command + .arg("-c") + .arg(format!( + "test ! -e /proc/self/fd/{descriptor} && printf 'sealed'" + )) + .stdin(source) + .stdout(std::process::Stdio::from(File::from( + std::os::fd::OwnedFd::from(child_output), + ))) + .stderr(std::process::Stdio::null()); + let child = unsafe { libc::fork() }; + assert!(child >= 0); + if child == 0 { + if seal_exec_descriptors().is_err() { + unsafe { libc::_exit(1) }; + } + // Same Command::exec stdio setup used by the workload path. The + // high inherited descriptor must disappear, while stdout survives. + let _error = command.exec(); + unsafe { libc::_exit(2) }; + } + drop(command); + let mut status = 0; + assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child); + assert!(libc::WIFEXITED(status)); + assert_eq!(libc::WEXITSTATUS(status), 0); + let mut bytes = Vec::new(); + output.read_to_end(&mut bytes).unwrap(); + assert_eq!(bytes, b"sealed"); + assert_eq!( + unsafe { libc::fcntl(owned.as_raw_fd(), libc::F_GETFD) } & libc::FD_CLOEXEC, + 0 + ); + } + #[test] fn mount_targets_reject_image_symlinks_and_non_directories() { let root = std::env::temp_dir().join(format!("ws-guest-mounts-{}", std::process::id())); @@ -1176,7 +1337,7 @@ fn run() -> Result<()> { } if let GuestPurpose::Project { capabilities, .. } = &purpose { let request = parse_request(&serde_json::to_vec(&job.request)?)?; - return run_project( + let outcome = run_project( job, *capabilities, staged, @@ -1184,7 +1345,9 @@ fn run() -> Result<()> { cpu, memory, request.maximum_output_bytes, - ); + )?; + outcome.write_completion(&mut std::io::stdout().lock())?; + std::process::exit(outcome.exit_code()); } drop(input); bind_material_root(&staged, "archive", INPUT_ROOT)?; @@ -1242,6 +1405,7 @@ fn run() -> Result<()> { )?; } drop_privileges(job.uid, job.gid).map_err(|e| format!("privileges: {e}"))?; + seal_exec_descriptors().map_err(|e| format!("descriptor policy: {e}"))?; install_workload_filter().map_err(|e| format!("syscall policy: {e}"))?; let mut command = Command::new(&job.command[0]); command.args(&job.command[1..]).env_clear(); From 0a86d3184e3a234859782affae117d7cbed6afe8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:23:21 +0100 Subject: [PATCH 080/513] Record reviewed guest continuation and descriptor custody --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6369ef45c..579ce733e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1824,3 +1824,9 @@ native guest isolation qualification. The PRE service handler, two-child guest orchestration, bounded root/source staging, resource/profile/cleanup envelope and public cutover remain the connected implementation work. This supporting guest refactor is not a new readiness or merge milestone. + +Architecture/security and QA/test-delta passed this supporting guest refactor at +clean `2625b2062`. Both confirmed preserved ordinary Project framing/classification +and the real fork/exec descriptor negative control. Their verdict is limited to +captured-result continuation and child descriptor sealing; the combined PRE +orchestration and native isolation remain unproved. Record validation passes. From 4aebc604a076c0baf24d3b04904ed36f651b9030 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:35:50 +0100 Subject: [PATCH 081/513] Bound guest project resources and stop expired children --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 + .../workstream-checker-guest/src/main.rs | 283 ++++++++++++++++-- 2 files changed, 276 insertions(+), 23 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 579ce733e..59e1519ec 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1830,3 +1830,19 @@ clean `2625b2062`. Both confirmed preserved ordinary Project framing/classificat and the real fork/exec descriptor negative control. Their verdict is limited to captured-result continuation and child descriptor sealing; the combined PRE orchestration and native isolation remain unproved. Record validation passes. + +The same project runner now accepts explicit CPU, memory, process, scratch, +output/log and paired run/cleanup deadline bounds for the planned PRE caller. +Ordinary POST keeps its existing values and host-owned deadline. Local deadlines +refuse model/execution capabilities because those relays can block. On expiry +the supervisor issues cgroup kill and kills its unreaped owned PID, covering the +pre-membership race, then reaps before returning failure. A failed cgroup command +still kills/reaps the direct child and cannot produce successful evidence. + +The guest crate passes 12 library and 29 binary tests after restoring production +code. A real fork/pause child proves termination and reaping both with an +available command sink and a missing group path; the regular-file command sink +is expressly not kernel cgroup isolation proof. Disabling the direct PID kill +makes the regression fail on unreaped custody, and fallback test cleanup reaps +the child. Formatting and whitespace checks pass. This remains within the +approved native supervisor scope and does not qualify PRE or complete its wiring. diff --git a/external_checkers/workstream-checker-guest/src/main.rs b/external_checkers/workstream-checker-guest/src/main.rs index 052d17666..2266f6df1 100644 --- a/external_checkers/workstream-checker-guest/src/main.rs +++ b/external_checkers/workstream-checker-guest/src/main.rs @@ -12,7 +12,7 @@ use std::path::{Component, Path, PathBuf}; use std::process::Command; use std::sync::mpsc::{self, Sender, SyncSender}; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; use workstream_checker_guest::confinement::install_workload_filter; use workstream_checker_guest::{ GuestCapabilities, GuestIoChannel, GuestIoHeader, GuestJob, GuestPurpose, MaterialRoot, @@ -51,19 +51,22 @@ fn private_mounts() -> Result<()> { syscall_ok(unsafe { libc::unshare(libc::CLONE_NEWNS) })?; mount("", "/", "", libc::MS_REC | libc::MS_PRIVATE, "") } -fn cgroups(cpu: u64, memory: u64) -> Result<()> { +fn cgroups(cpu: u64, memory: u64, pids: u64) -> Result<()> { let root = Path::new("/sys/fs/cgroup"); fs::write(root.join("cgroup.subtree_control"), "+cpu +memory +pids")?; let group = root.join("workstream-checker"); fs::create_dir(&group)?; - fs::write(group.join("cpu.max"), format!("{} 100000", cpu * 100))?; + fs::write( + group.join("cpu.max"), + format!( + "{} 100000", + cpu.checked_mul(100).ok_or("CPU quota overflow")? + ), + )?; fs::write(group.join("memory.max"), memory.to_string())?; disable_swap(&group, Path::new("/proc/meminfo"))?; fs::write(group.join("memory.oom.group"), "1")?; - fs::write( - group.join("pids.max"), - (memory / (16 * 1024 * 1024)).clamp(16, 256).to_string(), - )?; + fs::write(group.join("pids.max"), pids.to_string())?; Ok(()) } // Some fixed guest kernels omit the swap controller. In that case only a @@ -534,7 +537,7 @@ fn confined_devices() -> Result<()> { Ok(()) } -fn readonly_filesystem() -> Result<()> { +fn readonly_filesystem(scratch_bytes: u64) -> Result<()> { // mount_setattr recursively freezes every existing mount, including image // overlays and material. Then install the sole writable, bounded scratch. #[repr(C)] @@ -589,7 +592,7 @@ fn readonly_filesystem() -> Result<()> { "/tmp", "tmpfs", libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, - "size=16777216,mode=1777", + &format!("size={scratch_bytes},mode=1777"), )?; // Hide the management filesystem, cgroup controls and agent storage. Mounts // are private, so the supervisor outside this namespace remains functional. @@ -649,12 +652,15 @@ fn supervised_exit(status: i32, oom_kills: u64) -> i32 { } } -fn finish_workload_cgroup() -> Result { +fn finish_workload_cgroup(deadline: Option) -> Result { let group = Path::new("/sys/fs/cgroup/workstream-checker"); if group.join("cgroup.kill").exists() { fs::write(group.join("cgroup.kill"), "1")?; } for _ in 0..5000 { + if deadline.is_some_and(|value| Instant::now() >= value) { + return Err("project cleanup deadline exceeded".into()); + } let events = fs::read_to_string(group.join("cgroup.events"))?; if events.lines().any(|line| line == "populated 0") { let memory = fs::read_to_string(group.join("memory.events"))?; @@ -708,15 +714,80 @@ impl ProjectOutcome { } } +/// Explicit project-child bounds. Ordinary Project retains its established +/// policy-derived controls; PRE supplies its qualified partition and deadlines. +#[derive(Clone, Copy)] +struct ProjectLimits { + cpu_millis: u64, + memory_bytes: u64, + maximum_processes: u64, + scratch_bytes: u64, + maximum_output_bytes: usize, + maximum_log_bytes: usize, + deadline: Option, + cleanup_deadline: Option, +} + +impl ProjectLimits { + fn validate(&self, capabilities: GuestCapabilities) -> Result<()> { + // PRE cannot enter a blocking model/trial relay while relying on this + // local deadline. Ordinary POST relays retain their host-owned budget. + if self.deadline.is_some() && (capabilities.model || capabilities.execution) { + return Err("deadline-controlled project capabilities invalid".into()); + } + if self.cpu_millis == 0 + || self.cpu_millis.checked_mul(100).is_none() + || self.memory_bytes == 0 + || self.maximum_processes == 0 + || self.scratch_bytes == 0 + || self.maximum_output_bytes == 0 + || self.maximum_log_bytes == 0 + || u32::try_from(self.maximum_output_bytes).is_err() + || u32::try_from(self.maximum_log_bytes).is_err() + { + return Err("project resource bounds invalid".into()); + } + match (self.deadline, self.cleanup_deadline) { + (None, None) => Ok(()), + (Some(run), Some(cleanup)) if Instant::now() < run && run <= cleanup => Ok(()), + _ => Err("project deadline bounds invalid".into()), + } + } +} + +fn stop_project(child: libc::pid_t, group: &Path, deadline: Instant) -> Result { + // Kill the owned PID as well: it may not have joined its cgroup yet. The + // unreaped child PID cannot be reused for an unrelated process. + let group_kill = fs::write(group.join("cgroup.kill"), "1"); + let killed = unsafe { libc::kill(child, libc::SIGKILL) }; + if killed != 0 && std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) { + return Err(std::io::Error::last_os_error().into()); + } + let mut status = 0; + loop { + let waited = unsafe { libc::waitpid(child, &mut status, libc::WNOHANG) }; + if waited == child { + group_kill?; + return Ok(status); + } + if waited < 0 && std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted { + return Err(std::io::Error::last_os_error().into()); + } + if Instant::now() >= deadline { + return Err("project cleanup deadline exceeded".into()); + } + thread::sleep(Duration::from_millis(2)); + } +} + fn run_project( job: GuestJob, capabilities: GuestCapabilities, staged: StagedJob, mut input: File, - cpu: u64, - memory: u64, - maximum_output_bytes: usize, + limits: ProjectLimits, ) -> Result { + limits.validate(capabilities)?; bind_project_materials(&staged)?; let model = capabilities .model @@ -728,7 +799,12 @@ fn run_project( .transpose()?; let (stdout_parent, stdout_child) = socket_pair()?; let (stderr_parent, stderr_child) = socket_pair()?; - cgroups(cpu, memory).map_err(|error| format!("cgroup: {error}"))?; + cgroups( + limits.cpu_millis, + limits.memory_bytes, + limits.maximum_processes, + ) + .map_err(|error| format!("cgroup: {error}"))?; // The supervisor retains the trusted stream and capability listeners. The // workload receives separate output pipes, so it cannot forge mux frames. let child = unsafe { libc::fork() }; @@ -747,7 +823,8 @@ fn run_project( std::process::id().to_string(), )?; confined_devices().map_err(|error| format!("devices: {error}"))?; - readonly_filesystem().map_err(|error| format!("filesystem: {error}"))?; + readonly_filesystem(limits.scratch_bytes) + .map_err(|error| format!("filesystem: {error}"))?; drop_privileges(job.uid, job.gid).map_err(|error| format!("privileges: {error}"))?; // SAFETY: both streams are live child-owned descriptors and dup2 // atomically replaces the conventional output descriptors. @@ -778,17 +855,37 @@ fn run_project( } drop(stdout_child); drop(stderr_child); - let stdout_reader = thread::spawn(move || read_bounded(stdout_parent, maximum_output_bytes)); - let stderr_reader = thread::spawn(move || read_bounded(stderr_parent, 64 * 1024)); + let stdout_reader = + thread::spawn(move || read_bounded(stdout_parent, limits.maximum_output_bytes)); + let stderr_reader = + thread::spawn(move || read_bounded(stderr_parent, limits.maximum_log_bytes)); let (exchange_sender, exchange_receiver) = mpsc::channel::(); let mut sessions = Vec::new(); let mut model_accepted = false; let mut execution_accepted = false; let mut sequence = 0_u32; let mut status = 0_i32; + let deadline_exceeded; loop { let waited = unsafe { libc::waitpid(child, &mut status, libc::WNOHANG) }; if waited == child { + deadline_exceeded = limits + .deadline + .is_some_and(|deadline| Instant::now() >= deadline); + break; + } + if limits + .deadline + .is_some_and(|deadline| Instant::now() >= deadline) + { + deadline_exceeded = true; + status = stop_project( + child, + Path::new("/sys/fs/cgroup/workstream-checker"), + limits + .cleanup_deadline + .ok_or("project cleanup deadline missing")?, + )?; break; } if waited < 0 && std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted { @@ -848,7 +945,7 @@ fn run_project( } drop(model); drop(execution); - let oom_kills = finish_workload_cgroup()?; + let oom_kills = finish_workload_cgroup(limits.cleanup_deadline)?; drop(exchange_receiver); drop(exchange_sender); for (_, session) in sessions { @@ -868,6 +965,15 @@ fn run_project( } else { (stdout, stderr) }; + if limits + .cleanup_deadline + .is_some_and(|value| Instant::now() >= value) + { + return Err("project cleanup deadline exceeded".into()); + } + if deadline_exceeded { + return Err("project deadline exceeded".into()); + } Ok(ProjectOutcome { status, oom_kills, @@ -993,6 +1099,129 @@ mod tests { ); } + #[test] + fn explicit_project_limits_refuse_zero_overflow_and_partial_deadlines() { + let valid = ProjectLimits { + cpu_millis: 1000, + memory_bytes: 1024, + maximum_processes: 3, + scratch_bytes: 4096, + maximum_output_bytes: 1024, + maximum_log_bytes: 512, + deadline: Some(Instant::now() + Duration::from_secs(5)), + cleanup_deadline: Some(Instant::now() + Duration::from_secs(6)), + }; + let closed = GuestCapabilities { + model: false, + execution: false, + }; + assert!(valid.validate(closed).is_ok()); + assert!(valid + .validate(GuestCapabilities { + model: true, + execution: false + }) + .is_err()); + assert!(valid + .validate(GuestCapabilities { + model: false, + execution: true + }) + .is_err()); + for limits in [ + ProjectLimits { + cpu_millis: u64::MAX, + ..valid + }, + ProjectLimits { + memory_bytes: 0, + ..valid + }, + ProjectLimits { + maximum_processes: 0, + ..valid + }, + ProjectLimits { + scratch_bytes: 0, + ..valid + }, + ProjectLimits { + maximum_output_bytes: 0, + ..valid + }, + ProjectLimits { + maximum_log_bytes: 0, + ..valid + }, + ProjectLimits { + deadline: None, + ..valid + }, + ProjectLimits { + cleanup_deadline: None, + ..valid + }, + ProjectLimits { + deadline: Some(Instant::now()), + ..valid + }, + ProjectLimits { + cleanup_deadline: Some(Instant::now()), + ..valid + }, + ] { + assert!(limits.validate(closed).is_err()); + } + } + + #[test] + fn project_stop_kills_and_reaps_child_before_cgroup_membership() { + // Real owned PID race; a file stands in only for the cgroup command + // sink. Neither case claims kernel cgroup isolation qualification. + let root = std::env::temp_dir().join(format!("ws-project-stop-{}", std::process::id())); + fs::create_dir(&root).unwrap(); + for group_available in [true, false] { + let child = unsafe { libc::fork() }; + assert!(child >= 0); + if child == 0 { + loop { + unsafe { + libc::pause(); + } + } + } + let group = if group_available { + root.clone() + } else { + root.join("missing") + }; + let stopped = stop_project(child, &group, Instant::now() + Duration::from_secs(5)); + // Observe custody before fallback cleanup: even a failed cgroup + // command must kill/reap the directly owned child and fail closed. + let reaped = unsafe { libc::waitpid(child, std::ptr::null_mut(), libc::WNOHANG) }; + let error = std::io::Error::last_os_error().raw_os_error(); + if reaped == 0 { + unsafe { + libc::kill(child, libc::SIGKILL); + libc::waitpid(child, std::ptr::null_mut(), 0); + } + } + if reaped != -1 || error != Some(libc::ECHILD) { + fs::remove_dir_all(&root).unwrap(); + panic!("owned project child was not reaped"); + } + if group_available { + let status = stopped.unwrap(); + assert!(libc::WIFSIGNALED(status)); + assert_eq!(libc::WTERMSIG(status), libc::SIGKILL); + assert_eq!(fs::read(group.join("cgroup.kill")).unwrap(), b"1"); + } else { + assert!(stopped.is_err()); + } + } + fs::remove_dir_all(root).unwrap(); + } + #[test] fn mount_targets_reject_image_symlinks_and_non_directories() { let root = std::env::temp_dir().join(format!("ws-guest-mounts-{}", std::process::id())); @@ -1342,9 +1571,16 @@ fn run() -> Result<()> { *capabilities, staged, input, - cpu, - memory, - request.maximum_output_bytes, + ProjectLimits { + cpu_millis: cpu, + memory_bytes: memory, + maximum_processes: (memory / (16 * 1024 * 1024)).clamp(16, 256), + scratch_bytes: 16 * 1024 * 1024, + maximum_output_bytes: request.maximum_output_bytes, + maximum_log_bytes: 64 * 1024, + deadline: None, + cleanup_deadline: None, + }, )?; outcome.write_completion(&mut std::io::stdout().lock())?; std::process::exit(outcome.exit_code()); @@ -1357,7 +1593,8 @@ fn run() -> Result<()> { syscall_ok(unsafe { libc::chown(c("/work/scratch")?.as_ptr(), job.uid, job.gid) })?; fs::set_permissions("/work/scratch", fs::Permissions::from_mode(0o700))?; } - cgroups(cpu, memory).map_err(|e| format!("cgroup: {e}"))?; + cgroups(cpu, memory, (memory / (16 * 1024 * 1024)).clamp(16, 256)) + .map_err(|e| format!("cgroup: {e}"))?; // The trusted, single-threaded supervisor stays outside the workload cgroup // so an OOM cannot destroy the kernel evidence before it is classified. // stdin's lock has been dropped and no other threads exist at this fork. @@ -1392,7 +1629,7 @@ fn run() -> Result<()> { std::process::id().to_string(), )?; confined_devices().map_err(|e| format!("devices: {e}"))?; - readonly_filesystem().map_err(|e| format!("filesystem: {e}"))?; + readonly_filesystem(16 * 1024 * 1024).map_err(|e| format!("filesystem: {e}"))?; if matches!(purpose, GuestPurpose::TrustedIntake { .. }) { // Only the trusted worker receives private VM-disk scratch. Project // workloads retain their existing bounded tmpfs-only writable surface. From d3975f59a5e1f6ccddb473b400eaaf0e194600cb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:37:49 +0100 Subject: [PATCH 082/513] Refuse project launch after setup exhausts its deadline --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++ .../workstream-checker-guest/src/main.rs | 72 +++++++++++++++++-- 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 59e1519ec..09bc50a6a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1846,3 +1846,12 @@ is expressly not kernel cgroup isolation proof. Disabling the direct PID kill makes the regression fail on unreaped custody, and fallback test cleanup reaps the child. Formatting and whitespace checks pass. This remains within the approved native supervisor scope and does not qualify PRE or complete its wiring. + +QA review of `4aebc604a` identified that setup could exhaust the deadline after +initial validation but before fork. The launch boundary now rechecks immediately +before fork, and the child rechecks before exec after confinement setup. A real +fork control plus an expired-during-setup case exercises the launch helper; +removing its deadline check makes the latter fail and reaps the unexpected child. +Production code was restored. The guest suite passes 12 library and 30 binary +tests. Architecture/security had passed the earlier scope; both tracks must +replay this repair before a scoped review claim applies to the new candidate. diff --git a/external_checkers/workstream-checker-guest/src/main.rs b/external_checkers/workstream-checker-guest/src/main.rs index 2266f6df1..6d8ba713a 100644 --- a/external_checkers/workstream-checker-guest/src/main.rs +++ b/external_checkers/workstream-checker-guest/src/main.rs @@ -729,6 +729,25 @@ struct ProjectLimits { } impl ProjectLimits { + fn check_run_deadline(&self) -> Result<()> { + if self + .deadline + .is_some_and(|deadline| Instant::now() >= deadline) + { + return Err("project deadline exceeded".into()); + } + Ok(()) + } + + fn fork_project(&self) -> Result { + self.check_run_deadline()?; + let child = unsafe { libc::fork() }; + if child < 0 { + return Err(std::io::Error::last_os_error().into()); + } + Ok(child) + } + fn validate(&self, capabilities: GuestCapabilities) -> Result<()> { // PRE cannot enter a blocking model/trial relay while relying on this // local deadline. Ordinary POST relays retain their host-owned budget. @@ -807,10 +826,7 @@ fn run_project( .map_err(|error| format!("cgroup: {error}"))?; // The supervisor retains the trusted stream and capability listeners. The // workload receives separate output pipes, so it cannot forge mux frames. - let child = unsafe { libc::fork() }; - if child < 0 { - return Err(std::io::Error::last_os_error().into()); - } + let child = limits.fork_project()?; if child == 0 { drop(stdout_parent); drop(stderr_parent); @@ -851,6 +867,7 @@ fn run_project( } else { &job.working_directory }); + limits.check_run_deadline()?; return Err(command.exec().into()); } drop(stdout_child); @@ -1174,6 +1191,53 @@ mod tests { } } + #[test] + fn project_launch_refuses_deadline_consumed_by_setup() { + let mut limits = ProjectLimits { + cpu_millis: 1000, + memory_bytes: 1024, + maximum_processes: 3, + scratch_bytes: 4096, + maximum_output_bytes: 1024, + maximum_log_bytes: 512, + deadline: None, + cleanup_deadline: None, + }; + let child = limits.fork_project().unwrap(); + if child == 0 { + unsafe { libc::_exit(0) }; + } + let mut status = 0; + assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child); + assert!(libc::WIFEXITED(status)); + assert_eq!(libc::WEXITSTATUS(status), 0); + + let deadline = Instant::now() + Duration::from_millis(50); + limits.deadline = Some(deadline); + limits.cleanup_deadline = Some(deadline + Duration::from_secs(1)); + limits + .validate(GuestCapabilities { + model: false, + execution: false, + }) + .unwrap(); + // Stand in for setup consuming the allowance after initial validation. + while Instant::now() < deadline { + thread::sleep(Duration::from_millis(1)); + } + match limits.fork_project() { + Err(error) => assert_eq!(error.to_string(), "project deadline exceeded"), + Ok(0) => unsafe { libc::_exit(0) }, + Ok(child) => { + unsafe { + libc::waitpid(child, std::ptr::null_mut(), 0); + } + panic!("expired setup launched a project child"); + } + } + assert!(limits.check_run_deadline().is_err()); + } + #[test] fn project_stop_kills_and_reaps_child_before_cgroup_membership() { // Real owned PID race; a file stands in only for the cgroup command From 55dd118de15698f21e6977370e0c26f36a6f4a94 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:38:41 +0100 Subject: [PATCH 083/513] Record reviewed project deadline enforcement evidence --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 09bc50a6a..d03183648 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1855,3 +1855,10 @@ removing its deadline check makes the latter fail and reaps the unexpected child Production code was restored. The guest suite passes 12 library and 30 binary tests. Architecture/security had passed the earlier scope; both tracks must replay this repair before a scoped review claim applies to the new candidate. + +Architecture/security and QA replay passed the repaired scope at clean +`d3975f59a`. Both verified the pre-fork deadline regression and its failing +guard-removal mutation. The child-side pre-exec check is code-inspected; this +is not hard real-time preemption or native cgroup qualification. The parent +still rejects late evidence. Record validation passes. Combined PRE guest +orchestration and service dispatch remain the next connected implementation. From f8596ed77a93df1a8b816439f39925c6325c84f0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:46:23 +0100 Subject: [PATCH 084/513] Implement in-guest PRE tree handoff to the project runner --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 30 + .../workstream-checker-guest/src/main.rs | 1 + .../workstream-checker-guest/src/pre.rs | 596 ++++++++++++++++++ 3 files changed, 627 insertions(+) create mode 100644 external_checkers/workstream-checker-guest/src/pre.rs diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d03183648..89d800d65 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1862,3 +1862,33 @@ guard-removal mutation. The child-side pre-exec check is code-inspected; this is not hard real-time preemption or native cgroup qualification. The parent still rejects late evidence. Record validation passes. Combined PRE guest orchestration and service dispatch remain the next connected implementation. + +The PRE guest module now implements the worker-to-project phase. It validates +the closed worker frame and the shared SDK request, binds source/lease/request/ +image/registry/configuration and manifest digest to bootstrap facts, then seals +the exact projected tree through anchored no-follow descriptors. It rejects +links, extra/missing entries, file-byte changes and expansion bounds; production +sealing transfers ownership to root and sets public read/execute modes under a +root-owned private parent. The mount source retains the verified directory FD. +The request is reopened read-only before being passed as project stdin. + +The phase calls the existing confined project runner with the tighter selected +and profile limits, validates only its opaque stdout as a registered result, and +returns a lease-bound private response for the trusted worker. No project bytes +construct default/profile/cleanup evidence. This module is compiled but still +needs its PRE bootstrap caller: trusted-root/source staging, worker launch and +control dialogue, service dispatch and runtime result envelope remain pending. +The dead-code annotation identifies that missing connection, not completion. + +Portable guest verification passes 12 library and 34 binary tests. Real local +filesystem tests cover readable exact content, readonly modes, same-length +content substitution, size changes, file/directory symlinks, hard links, extra +and missing files, missing manifest parents, ordering, bounds and deadline +refusal. Tests use the local owner for inode changes, not a simulated root +authority. This environment refuses unprivileged UID mapping and has no +passwordless privilege elevation; distinct project-UID chmod/rename denial and +actual readonly mounts remain native qualification work. Closed frame tests +include a positive shared SDK vector and rehashed foreign source requests. +Removing file hashing accepts a same-length substitution and fails its test; +removing the raw-source binding accepts a rehashed foreign request and fails its +test. Both mutations were restored. Formatting and whitespace checks pass. diff --git a/external_checkers/workstream-checker-guest/src/main.rs b/external_checkers/workstream-checker-guest/src/main.rs index 6d8ba713a..d4678c909 100644 --- a/external_checkers/workstream-checker-guest/src/main.rs +++ b/external_checkers/workstream-checker-guest/src/main.rs @@ -21,6 +21,7 @@ use workstream_checker_guest::{ }; use workstream_checker_sdk::parse_request; +mod pre; mod trial; type Result = std::result::Result>; diff --git a/external_checkers/workstream-checker-guest/src/pre.rs b/external_checkers/workstream-checker-guest/src/pre.rs new file mode 100644 index 000000000..d273d1baf --- /dev/null +++ b/external_checkers/workstream-checker-guest/src/pre.rs @@ -0,0 +1,596 @@ +//! In-guest PRE handoff. The source-derived worker owns defaults; only this +//! supervisor can turn its manifest into a project mount and launch a project. +use super::*; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::os::unix::fs::MetadataExt; +use workstream_checker_sdk::{canonical_hash, infrastructure_result, validate_result}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct WorkerFrame { + protocol_version: String, + operation: String, + request_digest: String, + lease_id: String, + lease_generation: u64, + payload: ProjectPayload, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ProjectPayload { + request: Value, + manifest: Value, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Manifest { + schema_version: String, + entries: Vec, +} + +#[derive(Deserialize)] +#[serde(tag = "entry_type", rename_all = "snake_case", deny_unknown_fields)] +enum Entry { + Directory { + normalized_path: String, + }, + File { + normalized_path: String, + sha256: String, + byte_count: u64, + executable: bool, + }, +} + +impl Entry { + fn path(&self) -> &str { + match self { + Self::Directory { normalized_path } + | Self::File { + normalized_path, .. + } => normalized_path, + } + } +} + +/// Derived from the validated PRE bootstrap, never from project stdout. +pub(super) struct ProjectBinding<'a> { + pub request_digest: &'a str, + pub lease_id: &'a str, + pub lease_generation: u64, + pub operation_id: &'a str, + pub source_sha256: &'a str, + pub archive_sha256: &'a str, + pub archive_byte_count: u64, + pub image_digest: &'a str, + pub configuration_digest: &'a str, + pub registry_entry_digest: &'a str, + pub maximum_control_bytes: usize, + pub maximum_entries: usize, + pub maximum_expanded_bytes: u64, +} + +fn open_at(parent: &File, name: &str, directory: bool) -> Result { + if name.is_empty() || name.contains('/') || matches!(name, "." | "..") { + return Err("PRE tree component invalid".into()); + } + let descriptor = unsafe { + libc::openat( + parent.as_raw_fd(), + c(name)?.as_ptr(), + libc::O_RDONLY + | libc::O_NOFOLLOW + | libc::O_CLOEXEC + | libc::O_NONBLOCK + | if directory { libc::O_DIRECTORY } else { 0 }, + ) + }; + if descriptor < 0 { + return Err(std::io::Error::last_os_error().into()); + } + Ok(unsafe { File::from_raw_fd(descriptor) }) +} + +fn own_readonly(file: &File, owner: u32, mode: u32) -> Result<()> { + syscall_ok(unsafe { libc::fchown(file.as_raw_fd(), owner, u32::MAX) })?; + syscall_ok(unsafe { libc::fchmod(file.as_raw_fd(), mode) }) +} + +fn seal_tree( + root: &File, + manifest: &Manifest, + maximum_entries: usize, + maximum_bytes: u64, + owner: u32, + check: &impl Fn() -> Result<()>, +) -> Result<()> { + check()?; + if manifest.schema_version != "workstream.submission_bundle_manifest.v1" + || manifest.entries.len() > maximum_entries + || maximum_entries == 0 + { + return Err("PRE manifest bound invalid".into()); + } + let mut entries = BTreeMap::new(); + let mut previous: Option<&str> = None; + let mut total = 0u64; + for entry in &manifest.entries { + check()?; + let path = entry.path(); + if path.len() > 4096 + || !material_path_is_relative(path) + || path + .split('/') + .any(|part| part.is_empty() || matches!(part, "." | "..")) + || previous.is_some_and(|value| value >= path) + { + return Err("PRE manifest path invalid".into()); + } + if let Entry::File { byte_count, .. } = entry { + total = total + .checked_add(*byte_count) + .ok_or("PRE expanded bytes overflow")?; + if total > maximum_bytes { + return Err("PRE expanded bytes exceeded".into()); + } + } + previous = Some(path); + entries.insert(path, entry); + } + for path in entries.keys() { + if let Some((parent, _)) = path.rsplit_once('/') { + if !matches!(entries.get(parent), Some(Entry::Directory { .. })) { + return Err("PRE manifest parent missing".into()); + } + } + } + if !root.metadata()?.is_dir() { + return Err("PRE tree root invalid".into()); + } + own_readonly(root, owner, 0o555)?; + // Directory handles anchor every lookup. No tree byte copy or host export. + let mut directories = BTreeMap::new(); + directories.insert(String::new(), root.try_clone()?); + let mut seen = HashSet::new(); + for (path, entry) in &entries { + check()?; + let (parent, name) = path.rsplit_once('/').unwrap_or(("", path)); + let directory = directories + .get(parent) + .ok_or("PRE tree parent unavailable")?; + let mut file = open_at(directory, name, matches!(entry, Entry::Directory { .. }))?; + let metadata = file.metadata()?; + match entry { + Entry::Directory { .. } => { + own_readonly(&file, owner, 0o555)?; + directories.insert((*path).to_owned(), file); + } + Entry::File { + sha256, + byte_count, + executable, + .. + } => { + if !metadata.is_file() || metadata.nlink() != 1 || metadata.len() != *byte_count { + return Err("PRE tree file identity differs".into()); + } + own_readonly(&file, owner, if *executable { 0o555 } else { 0o444 })?; + let mut hash = Sha256::new(); + let mut remaining = *byte_count; + let mut buffer = [0; 65536]; + while remaining > 0 { + check()?; + let count = remaining.min(buffer.len() as u64) as usize; + file.read_exact(&mut buffer[..count])?; + hash.update(&buffer[..count]); + remaining -= count as u64; + } + if format!("sha256:{:x}", hash.finalize()) != *sha256 + || file.read(&mut buffer[..1])? != 0 + { + return Err("PRE tree file content differs".into()); + } + } + } + seen.insert((*path).to_owned()); + } + // Exact inventory: otherwise an unmanifested file could enter the mount. + for (parent, directory) in &directories { + for child in fs::read_dir(format!("/proc/self/fd/{}", directory.as_raw_fd()))? { + check()?; + let name = child? + .file_name() + .into_string() + .map_err(|_| "PRE tree name invalid")?; + let path = if parent.is_empty() { + name + } else { + format!("{parent}/{name}") + }; + if !seen.remove(&path) { + return Err("PRE tree has unmanifested entry".into()); + } + } + } + if !seen.is_empty() { + return Err("PRE tree inventory differs".into()); + } + check() +} + +fn project_request( + binding: &ProjectBinding<'_>, + frame: &[u8], +) -> Result<(workstream_checker_sdk::ValidatedRequest, Manifest)> { + if frame.is_empty() || frame.len() > binding.maximum_control_bytes.min(64 * 1024 * 1024) { + return Err("PRE worker control frame unbounded".into()); + } + let frame: WorkerFrame = serde_json::from_slice(frame)?; + if frame.protocol_version != "workstream.pre_submit_worker.v1" + || frame.operation != "project" + || frame.request_digest != binding.request_digest + || frame.lease_id != binding.lease_id + || frame.lease_generation != binding.lease_generation + { + return Err("PRE worker project binding differs".into()); + } + let request = parse_request(&serde_json::to_vec(&frame.payload.request)?)?; + let manifest_digest = canonical_hash(&frame.payload.manifest)?; + let identity = &request.value["identity"]; + let materials = request.value["materials"] + .as_array() + .ok_or("PRE material missing")?; + if request.phase != "pre_submit" + || request.image_digest != binding.image_digest + || request.configuration_digest != binding.configuration_digest + || request.registry_entry_digest != binding.registry_entry_digest + || identity["operation_id"] != binding.operation_id + || identity["attempt_request_digest"] != binding.request_digest + || identity["source_sha256"] != binding.source_sha256 + || identity["lease_id"] != binding.lease_id + || identity["lease_generation"] != binding.lease_generation + || materials.len() != 1 + || materials[0]["archive_sha256"] != binding.archive_sha256 + || materials[0]["archive_byte_count"] != binding.archive_byte_count + || materials[0]["semantic_manifest_sha256"] != manifest_digest + { + return Err("PRE derived project identity differs".into()); + } + Ok((request, serde_json::from_value(frame.payload.manifest)?)) +} + +/// The worker is waiting on its private control pipe when this phase runs. +/// `workspace` is the supervisor's private directory containing its projection; +/// the caller retains that directory until the project and worker are stopped. +#[allow(dead_code)] // PRE bootstrap dispatch is the remaining caller; ordinary Project is unchanged. +pub(super) fn run_project_phase( + binding: &ProjectBinding<'_>, + frame: &[u8], + workspace: &Path, + mut job: GuestJob, + mut limits: ProjectLimits, +) -> Result { + limits.validate(GuestCapabilities { + model: false, + execution: false, + })?; + let (request, manifest) = project_request(binding, frame)?; + if request.cpu_millis > limits.cpu_millis || request.memory_bytes > limits.memory_bytes { + return Err("PRE selected project resources exceed partition".into()); + } + limits.cpu_millis = request.cpu_millis; + limits.memory_bytes = request.memory_bytes; + limits.maximum_output_bytes = limits + .maximum_output_bytes + .min(request.maximum_output_bytes); + let selected_deadline = Instant::now() + .checked_add(Duration::from_millis(request.deadline_ms)) + .ok_or("PRE selected deadline overflow")?; + limits.deadline = Some( + limits + .deadline + .ok_or("PRE deadline missing")? + .min(selected_deadline), + ); + let parent = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(workspace.parent().ok_or("PRE workspace parent missing")?)?; + let metadata = parent.metadata()?; + if !workspace.is_absolute() || metadata.uid() != 0 || metadata.mode() & 0o777 != 0o700 { + return Err("PRE workspace custody invalid".into()); + } + let name = workspace + .file_name() + .and_then(|name| name.to_str()) + .ok_or("PRE workspace name invalid")?; + let root = open_at(&parent, name, true)?; + seal_tree( + &root, + &manifest, + binding.maximum_entries, + binding.maximum_expanded_bytes, + 0, + &|| limits.check_run_deadline(), + )?; + // The open directory descriptor keeps the exact verified inode as mount source. + let root_path = PathBuf::from(format!("/proc/self/fd/{}", root.as_raw_fd())); + let descriptor = unsafe { + libc::openat( + parent.as_raw_fd(), + c("project-request.json")?.as_ptr(), + libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, + 0o400, + ) + }; + if descriptor < 0 { + return Err(std::io::Error::last_os_error().into()); + } + let mut writer = unsafe { File::from_raw_fd(descriptor) }; + writer.write_all(&serde_json::to_vec(&request.value)?)?; + // Reopen the same inode read-only; never give the project a writable stdin. + let request_file = File::open(format!("/proc/self/fd/{}", writer.as_raw_fd()))?; + drop(writer); + job.request = request.value.clone(); + let staged = StagedJob { + request: request_file, + roots: BTreeMap::from([("current".into(), root_path)]), + }; + let outcome = run_project( + job, + GuestCapabilities { + model: false, + execution: false, + }, + staged, + File::open("/dev/null")?, + limits, + )?; + let result = if outcome.oom_kills > 0 { + infrastructure_result(&request, "capacity_exceeded")? + } else if outcome.exit_code() != 0 { + infrastructure_result(&request, "implementation_unavailable")? + } else { + match serde_json::from_slice::(&outcome.stdout) { + Ok(value) if validate_result(&value, &request).is_ok() => value, + _ => infrastructure_result(&request, "invalid_output")?, + } + }; + limits.check_run_deadline()?; + Ok( + json!({"request_digest": binding.request_digest, "lease_id": binding.lease_id, + "lease_generation": binding.lease_generation, "result": result}), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + const ABC_SHA: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + + struct Tree(PathBuf); + impl Tree { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "ws-pre-tree-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + fs::create_dir(path.join("d")).unwrap(); + fs::write(path.join("d/a"), b"abc").unwrap(); + Self(path) + } + fn open(&self) -> File { + File::open(&self.0).unwrap() + } + } + impl Drop for Tree { + fn drop(&mut self) { + fn writable(path: &Path) { + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + for child in fs::read_dir(path).unwrap() { + let child = child.unwrap(); + if child.file_type().unwrap().is_dir() { + writable(&child.path()); + } + } + } + writable(&self.0); + fs::remove_dir_all(&self.0).unwrap(); + } + } + fn manifest() -> Manifest { + serde_json::from_value(json!({"schema_version":"workstream.submission_bundle_manifest.v1", + "entries":[{"normalized_path":"d","entry_type":"directory"}, + {"normalized_path":"d/a","entry_type":"file","byte_count":3,"sha256":ABC_SHA,"executable":false}]})).unwrap() + } + fn seal(tree: &Tree, manifest: &Manifest) -> Result<()> { + // Exercise the real inode operations as the local owner. Root ownership + // and denial to a distinct project UID require native qualification. + seal_tree( + &tree.open(), + manifest, + 10, + 1024, + unsafe { libc::geteuid() }, + &|| Ok(()), + ) + } + + #[test] + fn exact_tree_seals_readable_bytes_and_permissions() { + let tree = Tree::new(); + seal(&tree, &manifest()).unwrap(); + assert_eq!(fs::read(tree.0.join("d/a")).unwrap(), b"abc"); + for (path, mode) in [ + (&tree.0, 0o555), + (&tree.0.join("d"), 0o555), + (&tree.0.join("d/a"), 0o444), + ] { + assert_eq!(fs::metadata(path).unwrap().mode() & 0o777, mode); + } + if unsafe { libc::geteuid() } != 0 { + assert_eq!( + OpenOptions::new() + .write(true) + .open(tree.0.join("d/a")) + .unwrap_err() + .kind(), + std::io::ErrorKind::PermissionDenied + ); + } + } + + #[test] + fn projected_tree_rejects_substitution_links_and_unmanifested_files() { + for case in [ + "bytes", + "length", + "symlink", + "directory_link", + "hardlink", + "extra", + "missing", + ] { + let tree = Tree::new(); + match case { + "bytes" => fs::write(tree.0.join("d/a"), b"abd").unwrap(), + "length" => fs::write(tree.0.join("d/a"), b"abcd").unwrap(), + "symlink" => { + fs::remove_file(tree.0.join("d/a")).unwrap(); + std::os::unix::fs::symlink("../../outside", tree.0.join("d/a")).unwrap(); + } + "directory_link" => { + fs::rename(tree.0.join("d"), tree.0.join("real")).unwrap(); + std::os::unix::fs::symlink("real", tree.0.join("d")).unwrap(); + } + "hardlink" => fs::hard_link(tree.0.join("d/a"), tree.0.join("alias")).unwrap(), + "extra" => fs::write(tree.0.join("extra"), b"hidden").unwrap(), + "missing" => fs::remove_file(tree.0.join("d/a")).unwrap(), + _ => unreachable!(), + } + assert!(seal(&tree, &manifest()).is_err(), "accepted {case}"); + } + } + + #[test] + fn manifest_rejects_missing_parents_order_and_resource_overflow() { + let tree = Tree::new(); + let mut value = manifest(); + value.entries.remove(0); + assert!(seal(&tree, &value).is_err()); + let mut value = manifest(); + value.entries.reverse(); + assert!(seal(&tree, &value).is_err()); + let value = manifest(); + assert!(seal_tree( + &tree.open(), + &value, + 1, + 1024, + unsafe { libc::geteuid() }, + &|| Ok(()) + ) + .is_err()); + assert!(seal_tree( + &tree.open(), + &value, + 10, + 2, + unsafe { libc::geteuid() }, + &|| Ok(()) + ) + .is_err()); + assert!(seal_tree( + &tree.open(), + &value, + 10, + 1024, + unsafe { libc::geteuid() }, + &|| Err("expired".into()) + ) + .is_err()); + } + #[test] + fn worker_project_request_binds_source_fence_manifest_and_selected_configuration() { + let mut request: Value = + serde_json::from_str(include_str!("../../fixtures/request.json")).unwrap(); + let manifest = + json!({"schema_version":"workstream.submission_bundle_manifest.v1", "entries":[]}); + request["materials"][0]["semantic_manifest_sha256"] = + json!(canonical_hash(&manifest).unwrap()); + request.as_object_mut().unwrap().remove("request_digest"); + request["request_digest"] = json!(canonical_hash(&request).unwrap()); + let validated = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap(); + let identity = &request["identity"]; + let material = &request["materials"][0]; + let binding = ProjectBinding { + request_digest: identity["attempt_request_digest"].as_str().unwrap(), + lease_id: identity["lease_id"].as_str().unwrap(), + lease_generation: identity["lease_generation"].as_u64().unwrap(), + operation_id: identity["operation_id"].as_str().unwrap(), + source_sha256: identity["source_sha256"].as_str().unwrap(), + archive_sha256: material["archive_sha256"].as_str().unwrap(), + archive_byte_count: material["archive_byte_count"].as_u64().unwrap(), + image_digest: &validated.image_digest, + registry_entry_digest: &validated.registry_entry_digest, + configuration_digest: &validated.configuration_digest, + maximum_control_bytes: 1024 * 1024, + maximum_entries: 10, + maximum_expanded_bytes: 1024, + }; + let valid = json!({"protocol_version":"workstream.pre_submit_worker.v1", "operation":"project", + "request_digest":binding.request_digest, "lease_id":binding.lease_id, + "lease_generation":binding.lease_generation, + "payload":{"request":request,"manifest":manifest}}); + project_request(&binding, &serde_json::to_vec(&valid).unwrap()).unwrap(); + for field in [ + "request_digest", + "lease_id", + "lease_generation", + "operation", + "extra", + ] { + let mut changed = valid.clone(); + changed[field] = json!("foreign"); + assert!( + project_request(&binding, &serde_json::to_vec(&changed).unwrap()).is_err(), + "accepted {field}" + ); + } + let mut changed = valid.clone(); + changed["payload"]["manifest"]["schema_version"] = json!("foreign"); + assert!(project_request(&binding, &serde_json::to_vec(&changed).unwrap()).is_err()); + // Re-sign a valid foreign nested request: failure must be the locked + // binding, not a stale request hash rejected by the shared SDK. + for field in ["archive_sha256", "archive_byte_count"] { + let mut changed = valid.clone(); + changed["payload"]["request"]["materials"][0][field] = if field == "archive_byte_count" + { + json!(binding.archive_byte_count + 1) + } else { + json!(ABC_SHA) + }; + let nested = &mut changed["payload"]["request"]; + nested.as_object_mut().unwrap().remove("request_digest"); + nested["request_digest"] = json!(canonical_hash(nested).unwrap()); + parse_request(&serde_json::to_vec(nested).unwrap()).unwrap(); + assert!(project_request(&binding, &serde_json::to_vec(&changed).unwrap()).is_err()); + } + let mut trailing = serde_json::to_vec(&valid).unwrap(); + trailing.extend_from_slice(b"{}"); + assert!(project_request(&binding, &trailing).is_err()); + let narrow = ProjectBinding { + maximum_control_bytes: 1, + ..binding + }; + assert!(project_request(&narrow, &serde_json::to_vec(&valid).unwrap()).is_err()); + } +} From abbd94ee02b900e3d350dc1d6d3d21b7c2a81a97 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:51:33 +0100 Subject: [PATCH 085/513] Bind PRE project input and admission identity to the verified handoff --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 +++ .../workstream-checker-guest/src/pre.rs | 119 +++++++++++++++++- 2 files changed, 130 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 89d800d65..f3f5f3e4f 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1892,3 +1892,17 @@ include a positive shared SDK vector and rehashed foreign source requests. Removing file hashing accepts a same-length substitution and fails its test; removing the raw-source binding accepts a rehashed foreign request and fails its test. Both mutations were restored. Formatting and whitespace checks pass. + +Both reviews of `f8596ed77` found that the nested project input could disagree +with the bound material while retaining valid input/request hashes. The repair +compares input archive SHA/count, semantic digest and the complete directory/file +entry projection with the same locked source and frame manifest. It additionally +binds project/task/assignment/attempt, plan and selected requirement to explicit +bootstrap facts; the input identity is checked too. The portable positive vector +now includes both a directory and a file with independent expected input fields. +Rehashed foreign input and identity vectors first pass the SDK hash/shape check, +then fail the phase binding. Removing input-source, input-manifest or project-ID +comparison separately makes the corresponding vector fail its assertion. All +mutations were restored; 12 library and 34 binary tests and formatting checks +pass. These checks do not establish the selected image's JSON-schema behavior, +privileged launch or the still-missing bootstrap/service connection. diff --git a/external_checkers/workstream-checker-guest/src/pre.rs b/external_checkers/workstream-checker-guest/src/pre.rs index d273d1baf..c3540a079 100644 --- a/external_checkers/workstream-checker-guest/src/pre.rs +++ b/external_checkers/workstream-checker-guest/src/pre.rs @@ -58,6 +58,12 @@ impl Entry { /// Derived from the validated PRE bootstrap, never from project stdout. pub(super) struct ProjectBinding<'a> { + pub project_id: &'a str, + pub task_id: &'a str, + pub assignment_id: &'a str, + pub attempt_id: &'a str, + pub effective_plan_sha256: &'a str, + pub requirement_id: &'a str, pub request_digest: &'a str, pub lease_id: &'a str, pub lease_generation: u64, @@ -239,6 +245,24 @@ fn project_request( } let request = parse_request(&serde_json::to_vec(&frame.payload.request)?)?; let manifest_digest = canonical_hash(&frame.payload.manifest)?; + let manifest: Manifest = serde_json::from_value(frame.payload.manifest)?; + let input_entries: Vec = manifest + .entries + .iter() + .map(|entry| match entry { + Entry::Directory { normalized_path } => json!({"normalized_path":normalized_path, + "entry_type":"directory", "byte_count":0,"sha256":null,"executable":null}), + Entry::File { + normalized_path, + sha256, + byte_count, + executable, + } => json!({ + "normalized_path":normalized_path,"entry_type":"file","byte_count":byte_count, + "sha256":sha256,"executable":executable}), + }) + .collect(); + let input = &request.value["input"]; let identity = &request.value["identity"]; let materials = request.value["materials"] .as_array() @@ -247,6 +271,20 @@ fn project_request( || request.image_digest != binding.image_digest || request.configuration_digest != binding.configuration_digest || request.registry_entry_digest != binding.registry_entry_digest + || identity["project_id"] != binding.project_id + || identity["task_id"] != binding.task_id + || identity["assignment_id"] != binding.assignment_id + || identity["attempt_id"] != binding.attempt_id + || identity["effective_plan_sha256"] != binding.effective_plan_sha256 + || input["schema_version"] != "workstream.external_checker_pre_submit_input.v1" + || input["project_id"] != binding.project_id + || input["task_id"] != binding.task_id + || input["assignment_id"] != binding.assignment_id + || input["requirement_id"] != binding.requirement_id + || input["archive_sha256"] != binding.archive_sha256 + || input["archive_byte_count"] != binding.archive_byte_count + || input["semantic_manifest_sha256"] != manifest_digest + || input["manifest"] != Value::Array(input_entries) || identity["operation_id"] != binding.operation_id || identity["attempt_request_digest"] != binding.request_digest || identity["source_sha256"] != binding.source_sha256 @@ -259,7 +297,7 @@ fn project_request( { return Err("PRE derived project identity differs".into()); } - Ok((request, serde_json::from_value(frame.payload.manifest)?)) + Ok((request, manifest)) } /// The worker is waiting on its private control pipe when this phase runs. @@ -522,16 +560,38 @@ mod tests { fn worker_project_request_binds_source_fence_manifest_and_selected_configuration() { let mut request: Value = serde_json::from_str(include_str!("../../fixtures/request.json")).unwrap(); - let manifest = - json!({"schema_version":"workstream.submission_bundle_manifest.v1", "entries":[]}); + let manifest = json!({"schema_version":"workstream.submission_bundle_manifest.v1", "entries":[ + {"normalized_path":"d","entry_type":"directory"}, + {"normalized_path":"d/a","entry_type":"file","byte_count":3,"sha256":ABC_SHA,"executable":false}]}); request["materials"][0]["semantic_manifest_sha256"] = json!(canonical_hash(&manifest).unwrap()); + request["input"] = json!({ + "schema_version":"workstream.external_checker_pre_submit_input.v1", + "project_id":request["identity"]["project_id"], + "task_id":request["identity"]["task_id"], + "assignment_id":request["identity"]["assignment_id"], + "requirement_id":"selected_requirement", + "archive_sha256":request["materials"][0]["archive_sha256"], + "archive_byte_count":request["materials"][0]["archive_byte_count"], + "semantic_manifest_sha256":request["materials"][0]["semantic_manifest_sha256"], + "manifest":[ + {"normalized_path":"d","entry_type":"directory","byte_count":0,"sha256":null,"executable":null}, + {"normalized_path":"d/a","entry_type":"file","byte_count":3,"sha256":ABC_SHA,"executable":false} + ], "packet":{"summary":"fixture","contributor_attestation":"fixture"}, + }); + request["input_sha256"] = json!(canonical_hash(&request["input"]).unwrap()); request.as_object_mut().unwrap().remove("request_digest"); request["request_digest"] = json!(canonical_hash(&request).unwrap()); let validated = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap(); let identity = &request["identity"]; let material = &request["materials"][0]; let binding = ProjectBinding { + project_id: identity["project_id"].as_str().unwrap(), + task_id: identity["task_id"].as_str().unwrap(), + assignment_id: identity["assignment_id"].as_str().unwrap(), + attempt_id: identity["attempt_id"].as_str().unwrap(), + effective_plan_sha256: identity["effective_plan_sha256"].as_str().unwrap(), + requirement_id: "selected_requirement", request_digest: identity["attempt_request_digest"].as_str().unwrap(), lease_id: identity["lease_id"].as_str().unwrap(), lease_generation: identity["lease_generation"].as_u64().unwrap(), @@ -584,6 +644,59 @@ mod tests { parse_request(&serde_json::to_vec(nested).unwrap()).unwrap(); assert!(project_request(&binding, &serde_json::to_vec(&changed).unwrap()).is_err()); } + for field in [ + "archive_sha256", + "archive_byte_count", + "semantic_manifest_sha256", + "manifest", + "project_id", + "task_id", + "assignment_id", + "requirement_id", + ] { + let mut changed = valid.clone(); + let nested = &mut changed["payload"]["request"]; + nested["input"][field] = match field { + "archive_byte_count" => json!(binding.archive_byte_count + 1), + "manifest" => { + json!([{"normalized_path":"foreign","entry_type":"directory","byte_count":0,"sha256":null,"executable":null}]) + } + "archive_sha256" | "semantic_manifest_sha256" => json!(ABC_SHA), + "project_id" | "task_id" | "assignment_id" => { + json!("019b0000-0000-7000-8000-000000000099") + } + _ => json!("foreign"), + }; + nested["input_sha256"] = json!(canonical_hash(&nested["input"]).unwrap()); + nested.as_object_mut().unwrap().remove("request_digest"); + nested["request_digest"] = json!(canonical_hash(nested).unwrap()); + parse_request(&serde_json::to_vec(nested).unwrap()).unwrap(); + assert!( + project_request(&binding, &serde_json::to_vec(&changed).unwrap()).is_err(), + "accepted input {field}" + ); + } + for field in [ + "project_id", + "task_id", + "assignment_id", + "effective_plan_sha256", + ] { + let mut changed = valid.clone(); + let nested = &mut changed["payload"]["request"]; + nested["identity"][field] = if field == "effective_plan_sha256" { + json!(ABC_SHA) + } else { + json!("019b0000-0000-7000-8000-000000000099") + }; + nested.as_object_mut().unwrap().remove("request_digest"); + nested["request_digest"] = json!(canonical_hash(nested).unwrap()); + parse_request(&serde_json::to_vec(nested).unwrap()).unwrap(); + assert!( + project_request(&binding, &serde_json::to_vec(&changed).unwrap()).is_err(), + "accepted identity {field}" + ); + } let mut trailing = serde_json::to_vec(&valid).unwrap(); trailing.extend_from_slice(b"{}"); assert!(project_request(&binding, &trailing).is_err()); From cbc8ddd1aff06ca7aaa224f6c8944f3c97a64471 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 14:52:31 +0100 Subject: [PATCH 086/513] Record reviewed PRE project handoff and remaining bootstrap boundary --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f3f5f3e4f..c5ce32be7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1906,3 +1906,12 @@ comparison separately makes the corresponding vector fail its assertion. All mutations were restored; 12 library and 34 binary tests and formatting checks pass. These checks do not establish the selected image's JSON-schema behavior, privileged launch or the still-missing bootstrap/service connection. + +Architecture/security and QA replay passed the repaired handoff scope at clean +`abbd94ee0`, including all three discriminating binding mutations. Packet content +and other canonical default derivations still belong to the pinned worker; this +supervisor phase does not claim independent rederivation of the entire request. +The PRE bootstrap caller, early control envelope, staged trusted-root worker, +service/profile/cleanup envelope and native qualification remain necessary. +A fresh fetch confirms current main `94334ccf4` is already an ancestor; the +single draft PR remains the only PR, and this cutover has not been pushed. From 7ad19cb35293e1948700267b3532b4372d82e1af Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 15:10:23 +0100 Subject: [PATCH 087/513] Connect bounded PRE guest bootstrap to trusted worker and project phase --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 46 + external_checkers/fixtures/pre_startup.json | 1 + .../workstream-checker-guest/src/lib.rs | 3 +- .../workstream-checker-guest/src/main.rs | 130 +- .../workstream-checker-guest/src/pre.rs | 8 +- .../src/pre/bootstrap.rs | 1077 +++++++++++++++++ .../src/pre_bootstrap.rs | 47 + .../src/trusted_root.rs | 6 +- 8 files changed, 1270 insertions(+), 48 deletions(-) create mode 100644 external_checkers/fixtures/pre_startup.json create mode 100644 external_checkers/workstream-checker-guest/src/pre/bootstrap.rs create mode 100644 external_checkers/workstream-checker-guest/src/pre_bootstrap.rs diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c5ce32be7..d16461fe3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1915,3 +1915,49 @@ The PRE bootstrap caller, early control envelope, staged trusted-root worker, service/profile/cleanup envelope and native qualification remain necessary. A fresh fetch confirms current main `94334ccf4` is already an ancestor; the single draft PR remains the only PR, and this cutover has not been pushed. + +The PRE guest bootstrap now calls the reviewed project handoff. A separate +`--pre-limits` entry uses closed explicit control/default/project partitions, +source/control/output/log/scratch bounds, distinct worker UID/GID and paired +deadlines. It charges the supervisor to its own cgroup before allocating the job +body, verifies the repeated limits and canonical source/request/profile binding, +and refuses resource sums outside the locked profile. All quantities remain +explicit; no qualified deployment values or compatibility PRE path are added. + +The guest spools the bounded WSROOT1 bundle and invokes `stage_root`, then stages +the exact-count source and a closed transfer marker in a supervisor-private +directory. It runs the fixed trusted Python worker in the verified readonly +chroot with private source/request and extraction workspace, separate cgroup, +non-root identity, descriptor sealing and the existing syscall filter. After +defaults it permits at most one project request, calls the existing handoff/ +runner, and returns only its validated result on the private worker pipe. A +default blocker invokes no project phase. Worker frames/logs, source reads, +result writes and cleanup have finite bounds; completion requires worker exit, +empty cgroup, no worker OOM and no trailing control bytes. Final VM destruction +and quarantine remain the host lease guardian's responsibility. + +Connecting these scopes exposed a child-error unwinding hazard: a failed project +setup could return into the inherited supervisor worker guard. Both forked exec +paths now exit directly on setup/exec failure. A real fork regression places a +destructor sentinel outside the exec helper and proves that failed setup exits +125 without running supervisor cleanup. Ordinary POST still uses its existing +limits, framing and result classification; the PRE flag does not change trial +argument parsing. + +The guest passes 12 library and 40 binary tests, and 38 shared Smol tests pass. +New portable tests exercise the Python-owner-generated `pre_startup.json` +canonical source vector (schema-tagged source hashing), closed scalar limits, +profile/source/root/identity rejection before input, exact-count spool reads, +stalled input deadlines, truncated/oversized frames, log limits, foreign fences, +default blockers and repeat-project refusal. Removing source-digest binding or +forcing a project phase after default rejection makes its focused test fail; +both mutations were restored. The fixture is synthetic and its timestamp does +not prove live lease validity. The dialogue tests use local socket peers and a +project-phase sentinel; they are not a privileged worker or VM execution test. + +Formatting/whitespace checks pass. The environment still cannot run privileged +mount/cgroup/chroot or Smol/KVM qualification. Host `execute_pre` dispatch, exact +configured pins and lease admission, the invocation/profile/cleanup response +envelope, trusted-root rebuild, native qualification and public cutover remain +required. This is a connected guest code path, not a runnable end-to-end service +or accepted-submission claim. diff --git a/external_checkers/fixtures/pre_startup.json b/external_checkers/fixtures/pre_startup.json new file mode 100644 index 000000000..594abf022 --- /dev/null +++ b/external_checkers/fixtures/pre_startup.json @@ -0,0 +1 @@ +{"isolation":{"architecture":"amd64","config_image_id":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","isolation_mode":"gvisor","operating_system":"linux","platform_manifest_byte_count":1024,"platform_manifest_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","platform_manifest_media_type":"application/vnd.oci.image.manifest.v1+json","repository":"registry.example/workstream/checker","runtime":"runsc","sandbox_gid":65532,"sandbox_uid":65532},"operation":"execute_pre","request":{"lease_expires_at":"2026-11-12T14:03:17.297738+00:00","lease_generation":1,"lease_id":"01a1d010-14fa-7444-a807-ade92ac62129","operation":"execute_pre","protocol_version":"external_checker_service.v1","request_digest":"sha256:4867de6e0f032a474c7b8588821b7234917303cf5403ecb2578dcba955abb7cc","reservation":{"actor_profile_id":"01a1d010-14f1-7fbf-88f9-cf9cba7f44be","admission_lineage":{"checker_remediation_manifest_id":null,"effective_plan_sha256":"sha256:c4f4f4141a56b851473518ed8b88743d905589ee963c84bba29a7576b51577ed","effective_policy_id":"01a1cf4c-d6c6-7418-8bca-8e321bc3348e","effective_policy_sha256":"sha256:3333333333333333333333333333333333333333333333333333333333333333","external_checker_policies_sha256":"sha256:9999999999999999999999999999999999999999999999999999999999999999","guide_id":"01a1cf4c-d6c4-7ede-add7-f9bd12e64560","guide_version":"v2","locked_guide_sha256":"sha256:2222222222222222222222222222222222222222222222222222222222222222","locked_policy_context_hash":"sha256:6666666666666666666666666666666666666666666666666666666666666666","packet_sha256":"sha256:f2906043a657a5b513767cfd552c88301775c6f663c5d483765d499cb1b3192d","post_submit_policy_body":{"entries":[],"policy_sha256":"sha256:ffcd8b8e350f4d11a53731faf9b41c97e09562a78178bdbfb96c300b4994d401","schema_version":"external_post_submit_policy.v1"},"post_submit_policy_sha256":"sha256:ffcd8b8e350f4d11a53731faf9b41c97e09562a78178bdbfb96c300b4994d401","pre_submit_policy_id":"01a1cf4c-d6c7-777d-8bdf-eb0e12879148","pre_submit_policy_sha256":"sha256:4444444444444444444444444444444444444444444444444444444444444444","predecessor_submission_id":null,"predecessor_submission_version":null,"rules_sha256":"sha256:8888888888888888888888888888888888888888888888888888888888888888","source_snapshot_id":"01a1cf4c-d6c5-798a-98ae-e349ea3ac7e7","source_snapshot_sha256":"sha256:1111111111111111111111111111111111111111111111111111111111111111","storage_scheme":"s3"},"assignment_id":"01a1d010-14f5-7404-ad5e-597677da63cb","attempt_id":"01a1d010-14f6-7172-ad32-212ba2a13911","default_context":{"current_predecessor":null,"current_rules_sha256":"sha256:8888888888888888888888888888888888888888888888888888888888888888","packet":{"contributor_attestation":"","summary":""},"predecessor":null,"predecessor_exists":false,"predecessor_rules_sha256":null},"foreground_lease_generation":1,"foreground_lease_id":"01a1d010-14f9-7910-83f6-d6bb548acac2","idempotency_key":"01a1d010-14f7-7fdc-ae6e-771c776f0872","identity_link_id":"01a1d010-14f2-7573-ab35-7ea9de80c1c8","locked_context_sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","metadata_sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","policy":{"entries":[{"configuration":{},"configuration_sha256":"sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a","registry":{"authorization_decision_event_id":"2f7dc85f-7ab8-4605-a693-cf4ad64caff1","capability_id":"acme.safe_archive","capability_version":"v1.2.3","configuration_schema":{"document":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"schema_id":"acme.safe_archive.configuration","schema_sha256":"sha256:d746974fa9afd5e951f76f9af38954b0ad7f436f2120dc974da65e5ee39f856f","schema_version":"v1"},"created_at":"2026-11-12T14:01:17.286721Z","entry_digest":"sha256:2666891954c7e14a486c548a5395991ee5ff92a353495a43baee729779282e2d","image_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","input_schema":{"document":{"type":"object"},"schema_id":"external_checker_pre_submit_input","schema_sha256":"sha256:a2c799262a3ce3c19ef5cdd983bf3d12b43ab3c426227091b909dcb7054738c0","schema_version":"v1"},"output_schema":{"document":{"type":"object"},"schema_id":"external_checker_result","schema_sha256":"sha256:a2c799262a3ce3c19ef5cdd983bf3d12b43ab3c426227091b909dcb7054738c0","schema_version":"v1"},"phase":"pre_submit","registered_by_actor_profile_id":"fafd4e11-aaa2-432b-bff3-c60660c2ff05","registration_operation_id":"c739930b-0117-4a14-ba17-43ffc293261d","registry_entry_id":"01a1d010-14e6-7abc-887a-bdf96b037be3","resources":{"cpu_millis":500,"deadline_ms":30000,"maximum_output_bytes":32768,"memory_bytes":134217728}},"requirement_id":"project.archive_rules","stage":"pre_submit"}],"policy_sha256":"sha256:c4f4f4141a56b851473518ed8b88743d905589ee963c84bba29a7576b51577ed","schema_version":"external_pre_submit_policy.v1","workstream_default":{"behavior_sha256":"sha256:af2c604f792c4456d3b222036c772161b1503eace65ff90c3d3a23d9d348c28f","checker_id":"workstream.default","checker_version":"v1"}},"pre_deadline_at":"2026-11-12T14:03:17.297738+00:00","project_id":"01a1d010-14f3-7792-9bd8-e7c91e36f8c5","runtime_profile":{"aggregate_deadline_ms":120000,"archive_limits":{"maximum_central_directory_bytes":8388608,"maximum_compression_ratio":100,"maximum_entries":2000,"maximum_entry_bytes":134217728,"maximum_expanded_bytes":536870912,"maximum_inspection_seconds":60.0,"maximum_path_bytes":1024,"maximum_path_depth":32},"cpu_millis":2000,"maximum_log_bytes":1048576,"maximum_output_bytes":1048576,"maximum_processes":64,"memory_bytes":2147483648,"platform_root_sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","profile_id":"test-only","temporary_disk_bytes":4294967296},"schema_version":"workstream.selected_pre_submit_reservation.v2","source":{"location":{"namespace_fingerprint":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","namespace_id":"primary","operation_id":"01a1d010-14f8-741f-9647-a4d81b8b495a","provider_profile":"local-v2"},"media_type":"application/zip","provider_generation":"test-generation","raw_byte_count":1024,"raw_sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sealed_upload_fence":1},"source_sha256":"sha256:27cc2006f0ce614c60412b436e52e53bccfcdd3a7948aebc47ee872b7a93ec9c","task_id":"01a1d010-14f4-7366-88ec-d699bc373b36"}}} diff --git a/external_checkers/workstream-checker-guest/src/lib.rs b/external_checkers/workstream-checker-guest/src/lib.rs index 48aec1bfa..88cd9d7b9 100644 --- a/external_checkers/workstream-checker-guest/src/lib.rs +++ b/external_checkers/workstream-checker-guest/src/lib.rs @@ -2,6 +2,7 @@ use serde::{Deserialize, Serialize}; pub mod confinement; +pub mod pre_bootstrap; pub mod trusted_root; pub const MAX_JOB_BYTES: usize = 4 * 1024 * 1024; @@ -68,7 +69,7 @@ pub enum GuestPurpose { }, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct GuestJob { pub purpose: GuestPurpose, diff --git a/external_checkers/workstream-checker-guest/src/main.rs b/external_checkers/workstream-checker-guest/src/main.rs index d4678c909..fdace7824 100644 --- a/external_checkers/workstream-checker-guest/src/main.rs +++ b/external_checkers/workstream-checker-guest/src/main.rs @@ -800,6 +800,13 @@ fn stop_project(child: libc::pid_t, group: &Path, deadline: Instant) -> Result Result<()>) -> ! { + let _ = setup(); + // Failed exec/setup belongs only to this child. Do not unwind into the + // PRE supervisor's worker guard or emit a trusted supervisor completion. + unsafe { libc::_exit(125) } +} + fn run_project( job: GuestJob, capabilities: GuestCapabilities, @@ -829,47 +836,49 @@ fn run_project( // workload receives separate output pipes, so it cannot forge mux frames. let child = limits.fork_project()?; if child == 0 { - drop(stdout_parent); - drop(stderr_parent); - drop(model); - drop(execution); - drop(input); - private_mounts().map_err(|error| format!("workload mount namespace: {error}"))?; - fs::write( - "/sys/fs/cgroup/workstream-checker/cgroup.procs", - std::process::id().to_string(), - )?; - confined_devices().map_err(|error| format!("devices: {error}"))?; - readonly_filesystem(limits.scratch_bytes) - .map_err(|error| format!("filesystem: {error}"))?; - drop_privileges(job.uid, job.gid).map_err(|error| format!("privileges: {error}"))?; - // SAFETY: both streams are live child-owned descriptors and dup2 - // atomically replaces the conventional output descriptors. - if unsafe { libc::dup2(stdout_child.as_raw_fd(), 1) } < 0 - || unsafe { libc::dup2(stderr_child.as_raw_fd(), 2) } < 0 - { - return Err(std::io::Error::last_os_error().into()); - } - drop(stdout_child); - drop(stderr_child); - seal_exec_descriptors().map_err(|error| format!("descriptor policy: {error}"))?; - install_workload_filter().map_err(|error| format!("syscall policy: {error}"))?; - let mut command = Command::new(&job.command[0]); - command - .args(&job.command[1..]) - .env_clear() - .stdin(staged.request); - for entry in &job.environment { - let (key, value) = entry.split_once('=').ok_or("invalid image environment")?; - command.env(key, value); - } - command.current_dir(if job.working_directory.is_empty() { - "/" - } else { - &job.working_directory + exec_workload(|| { + drop(stdout_parent); + drop(stderr_parent); + drop(model); + drop(execution); + drop(input); + private_mounts().map_err(|error| format!("workload mount namespace: {error}"))?; + fs::write( + "/sys/fs/cgroup/workstream-checker/cgroup.procs", + std::process::id().to_string(), + )?; + confined_devices().map_err(|error| format!("devices: {error}"))?; + readonly_filesystem(limits.scratch_bytes) + .map_err(|error| format!("filesystem: {error}"))?; + drop_privileges(job.uid, job.gid).map_err(|error| format!("privileges: {error}"))?; + // SAFETY: both streams are live child-owned descriptors and dup2 + // atomically replaces the conventional output descriptors. + if unsafe { libc::dup2(stdout_child.as_raw_fd(), 1) } < 0 + || unsafe { libc::dup2(stderr_child.as_raw_fd(), 2) } < 0 + { + return Err(std::io::Error::last_os_error().into()); + } + drop(stdout_child); + drop(stderr_child); + seal_exec_descriptors().map_err(|error| format!("descriptor policy: {error}"))?; + install_workload_filter().map_err(|error| format!("syscall policy: {error}"))?; + let mut command = Command::new(&job.command[0]); + command + .args(&job.command[1..]) + .env_clear() + .stdin(staged.request); + for entry in &job.environment { + let (key, value) = entry.split_once('=').ok_or("invalid image environment")?; + command.env(key, value); + } + command.current_dir(if job.working_directory.is_empty() { + "/" + } else { + &job.working_directory + }); + limits.check_run_deadline()?; + Err(command.exec().into()) }); - limits.check_run_deadline()?; - return Err(command.exec().into()); } drop(stdout_child); drop(stderr_child); @@ -1192,6 +1201,37 @@ mod tests { } } + #[test] + fn failed_child_setup_cannot_unwind_supervisor_custody() { + struct Guard(i32); + impl Drop for Guard { + fn drop(&mut self) { + unsafe { + libc::write(self.0, b"x".as_ptr().cast(), 1); + } + } + } + let (mut parent, child_pipe) = socket_pair().unwrap(); + let child = unsafe { libc::fork() }; + assert!(child >= 0); + if child == 0 { + drop(parent); + let _guard = Guard(child_pipe.as_raw_fd()); + exec_workload(|| Err("controlled setup failure".into())); + } + drop(child_pipe); + let mut status = 0; + assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child); + let mut marker = [0]; + assert_eq!( + parent.read(&mut marker).unwrap(), + 0, + "child ran supervisor destructor" + ); + assert!(libc::WIFEXITED(status)); + assert_eq!(libc::WEXITSTATUS(status), 125); + } + #[test] fn project_launch_refuses_deadline_consumed_by_setup() { let mut limits = ProjectLimits { @@ -1542,7 +1582,15 @@ fn main() { } } fn run() -> Result<()> { - let bootstrap_limits = trial::parse_bootstrap_limits(std::env::args_os().skip(1))?; + let mut arguments = std::env::args_os().skip(1).peekable(); + if arguments + .peek() + .is_some_and(|value| value == workstream_checker_guest::pre_bootstrap::PRE_LIMITS_ARGUMENT) + { + arguments.next(); + return pre::bootstrap::run(arguments); + } + let bootstrap_limits = trial::parse_bootstrap_limits(arguments)?; let trial_envelope = bootstrap_limits .map(trial::TrialEnvelope::prepare) .transpose()?; diff --git a/external_checkers/workstream-checker-guest/src/pre.rs b/external_checkers/workstream-checker-guest/src/pre.rs index c3540a079..0772853ca 100644 --- a/external_checkers/workstream-checker-guest/src/pre.rs +++ b/external_checkers/workstream-checker-guest/src/pre.rs @@ -1,6 +1,7 @@ //! In-guest PRE handoff. The source-derived worker owns defaults; only this //! supervisor can turn its manifest into a project mount and launch a project. use super::*; +pub(super) mod bootstrap; use serde::Deserialize; use serde_json::{json, Value}; use std::os::unix::fs::MetadataExt; @@ -8,13 +9,13 @@ use workstream_checker_sdk::{canonical_hash, infrastructure_result, validate_res #[derive(Deserialize)] #[serde(deny_unknown_fields)] -struct WorkerFrame { +struct WorkerFrame { protocol_version: String, operation: String, request_digest: String, lease_id: String, lease_generation: u64, - payload: ProjectPayload, + payload: T, } #[derive(Deserialize)] @@ -234,7 +235,7 @@ fn project_request( if frame.is_empty() || frame.len() > binding.maximum_control_bytes.min(64 * 1024 * 1024) { return Err("PRE worker control frame unbounded".into()); } - let frame: WorkerFrame = serde_json::from_slice(frame)?; + let frame: WorkerFrame = serde_json::from_slice(frame)?; if frame.protocol_version != "workstream.pre_submit_worker.v1" || frame.operation != "project" || frame.request_digest != binding.request_digest @@ -303,7 +304,6 @@ fn project_request( /// The worker is waiting on its private control pipe when this phase runs. /// `workspace` is the supervisor's private directory containing its projection; /// the caller retains that directory until the project and worker are stopped. -#[allow(dead_code)] // PRE bootstrap dispatch is the remaining caller; ordinary Project is unchanged. pub(super) fn run_project_phase( binding: &ProjectBinding<'_>, frame: &[u8], diff --git a/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs b/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs new file mode 100644 index 000000000..bf965df2a --- /dev/null +++ b/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs @@ -0,0 +1,1077 @@ +//! One PRE guest: bounded input, pinned platform worker, then optional project. +use super::*; +use std::ffi::OsString; +use std::io::{Seek, SeekFrom}; +use workstream_checker_guest::pre_bootstrap::{ + PreBootstrapJob, PreBootstrapLimits, PrePartition, PRE_LIMITS_MAXIMUM_BYTES, +}; +use workstream_checker_guest::trusted_root::stage_root; + +const CONTROL: &str = "/sys/fs/cgroup/workstream-pre-control"; +const WORKER: &str = "/sys/fs/cgroup/workstream-pre-default"; + +fn validate_limits(limits: PreBootstrapLimits) -> Result<()> { + for partition in [limits.control, limits.worker, limits.project] { + if partition.cpu_millis == 0 + || partition.cpu_millis.checked_mul(100).is_none() + || partition.memory_bytes == 0 + || partition.processes == 0 + { + return Err("PRE partition invalid".into()); + } + } + if limits.control.processes < 3 + || limits.worker_uid == 0 + || limits.worker_gid == 0 + || limits.worker_scratch_bytes == 0 + || limits.maximum_source_bytes == 0 + || limits.project_scratch_bytes == 0 + || limits.maximum_control_bytes == 0 + || limits.maximum_control_bytes > 64 * 1024 * 1024 + || limits.maximum_control_bytes as u64 > limits.control.memory_bytes + || limits.maximum_output_bytes == 0 + || limits.maximum_log_bytes == 0 + || u32::try_from(limits.maximum_output_bytes).is_err() + || u32::try_from(limits.maximum_log_bytes).is_err() + || limits.timeout_ms == 0 + || limits.timeout_ms > 14_400_000 + || limits.cleanup_timeout_ms < limits.timeout_ms + || limits.cleanup_timeout_ms > 14_400_000 + || limits.overlay_bytes == 0 + || limits.filesystem_overhead_bytes == 0 + { + return Err("PRE bootstrap bounds invalid".into()); + } + Ok(()) +} + +fn parse_limits(mut arguments: impl Iterator) -> Result { + let value = arguments.next().ok_or("PRE bootstrap limits missing")?; + if value.len() > PRE_LIMITS_MAXIMUM_BYTES || arguments.next().is_some() { + return Err("PRE bootstrap limits unbounded".into()); + } + let limits = serde_json::from_str(value.to_str().ok_or("PRE limits encoding invalid")?)?; + validate_limits(limits)?; + Ok(limits) +} + +fn configure_group(path: &str, partition: PrePartition) -> Result<()> { + fs::create_dir(path)?; + let group = Path::new(path); + fs::write( + group.join("cpu.max"), + format!( + "{} 100000", + partition + .cpu_millis + .checked_mul(100) + .ok_or("PRE CPU overflow")? + ), + )?; + fs::write(group.join("memory.max"), partition.memory_bytes.to_string())?; + disable_swap(group, Path::new("/proc/meminfo"))?; + fs::write(group.join("memory.oom.group"), "1")?; + fs::write(group.join("pids.max"), partition.processes.to_string())?; + Ok(()) +} + +struct Envelope { + limits: PreBootstrapLimits, + deadline: Instant, + cleanup: Instant, +} +impl Envelope { + fn prepare(limits: PreBootstrapLimits) -> Result { + validate_limits(limits)?; + let started = Instant::now(); + let result = Self { + limits, + deadline: started + .checked_add(Duration::from_millis(limits.timeout_ms)) + .ok_or("PRE deadline overflow")?, + cleanup: started + .checked_add(Duration::from_millis(limits.cleanup_timeout_ms)) + .ok_or("PRE cleanup overflow")?, + }; + fs::write( + "/sys/fs/cgroup/cgroup.subtree_control", + "+cpu +memory +pids", + )?; + configure_group(CONTROL, limits.control)?; + configure_group(WORKER, limits.worker)?; + // Before allocating the job or input-dependent buffers, charge this + // supervisor to its own partition, never either workload's OOM group. + fs::write(Path::new(CONTROL).join("cgroup.procs"), "0")?; + result.check()?; + Ok(result) + } + fn check(&self) -> Result<()> { + if Instant::now() >= self.deadline { + return Err("PRE deadline exceeded".into()); + } + Ok(()) + } + fn cleanup_check(&self) -> Result<()> { + if Instant::now() >= self.cleanup { + return Err("PRE cleanup deadline exceeded".into()); + } + Ok(()) + } + fn project_limits(&self) -> ProjectLimits { + ProjectLimits { + cpu_millis: self.limits.project.cpu_millis, + memory_bytes: self.limits.project.memory_bytes, + maximum_processes: self.limits.project.processes, + scratch_bytes: self.limits.project_scratch_bytes, + maximum_output_bytes: self.limits.maximum_output_bytes, + maximum_log_bytes: self.limits.maximum_log_bytes, + deadline: Some(self.deadline), + cleanup_deadline: Some(self.cleanup), + } + } +} + +fn text<'a>(value: &'a Value, field: &str) -> Result<&'a str> { + value[field] + .as_str() + .ok_or_else(|| "PRE bootstrap text missing".into()) +} +fn number(value: &Value, field: &str) -> Result { + value[field] + .as_u64() + .ok_or_else(|| "PRE bootstrap number missing".into()) +} +fn sum(values: impl IntoIterator) -> Result { + values.into_iter().try_fold(0u64, |total, value| { + total + .checked_add(value) + .ok_or_else(|| "PRE resource overflow".into()) + }) +} +fn binding(job: &PreBootstrapJob) -> Result> { + let header = &job.startup["request"]; + let reservation = &header["reservation"]; + let source = &reservation["source"]; + let profile = &reservation["runtime_profile"]; + let mut source_body = source.as_object().ok_or("PRE source invalid")?.clone(); + source_body.insert( + "schema_version".into(), + json!("workstream.sealed_submission_source.v1"), + ); + let entries = reservation["policy"]["entries"] + .as_array() + .ok_or("PRE policy missing")?; + if entries.len() != 1 { + return Err("PRE cardinality invalid".into()); + } + let selected = &entries[0]; + let registry = &selected["registry"]; + if job.startup["operation"] != "execute_pre" + || header["operation"] != "execute_pre" + || header["protocol_version"] != "external_checker_service.v1" + || canonical_hash(reservation)? != text(header, "request_digest")? + || canonical_hash(&Value::Object(source_body))? != text(reservation, "source_sha256")? + || profile["platform_root_sha256"] != job.root.bundle_sha256 + || reservation["policy"]["workstream_default"]["behavior_sha256"] + != job.root.default_behavior_sha256 + || number(source, "raw_byte_count")? == 0 + || number(source, "raw_byte_count")? > job.limits.maximum_source_bytes + || job.root.bundle_byte_count == 0 + || job.root.bundle_byte_count > job.root_limits.maximum_bundle_bytes + || job.root.expanded_bytes > job.root_limits.maximum_root_bytes + || job.root.entries == 0 + || job.root.entries > job.root_limits.maximum_entries + || number(header, "lease_generation")? == 0 + || job.selected.uid == 0 + || job.selected.gid == 0 + || job.selected.uid == job.limits.worker_uid + || job.selected.gid == job.limits.worker_gid + || !job.selected.request.is_null() + || !job.selected.files.is_empty() + || !job.selected.directories.is_empty() + || !matches!(&job.selected.purpose, GuestPurpose::Project { capabilities, materials } + if !capabilities.model && !capabilities.execution && materials.is_empty()) + || job.selected.command.is_empty() + || job.selected.command.len() > 256 + || job.selected.environment.len() > 1024 + { + return Err("PRE bootstrap identity differs".into()); + } + for (field, amounts) in [ + ( + "cpu_millis", + [ + job.limits.control.cpu_millis, + job.limits.worker.cpu_millis, + job.limits.project.cpu_millis, + ], + ), + ( + "memory_bytes", + [ + job.limits.control.memory_bytes, + job.limits.worker.memory_bytes, + job.limits.project.memory_bytes, + ], + ), + ( + "maximum_processes", + [ + job.limits.control.processes, + job.limits.worker.processes, + job.limits.project.processes, + ], + ), + ] { + if sum(amounts)? > number(profile, field)? { + return Err("PRE partitions exceed profile".into()); + } + } + let archive_limits = &profile["archive_limits"]; + if sum([ + job.root.bundle_byte_count, + job.root.expanded_bytes, + number(source, "raw_byte_count")?, + number(archive_limits, "maximum_expanded_bytes")?, + job.limits.worker_scratch_bytes, + job.limits.project_scratch_bytes, + job.limits.overlay_bytes, + job.limits.filesystem_overhead_bytes, + ])? > number(profile, "temporary_disk_bytes")? + || job.limits.maximum_output_bytes as u64 > number(profile, "maximum_output_bytes")? + || job.limits.maximum_log_bytes as u64 > number(profile, "maximum_log_bytes")? + || job.limits.cleanup_timeout_ms > number(profile, "aggregate_deadline_ms")? + { + return Err("PRE envelope exceeds locked profile".into()); + } + Ok(ProjectBinding { + project_id: text(reservation, "project_id")?, + task_id: text(reservation, "task_id")?, + assignment_id: text(reservation, "assignment_id")?, + attempt_id: text(reservation, "attempt_id")?, + effective_plan_sha256: text(&reservation["admission_lineage"], "effective_plan_sha256")?, + requirement_id: text(selected, "requirement_id")?, + request_digest: text(header, "request_digest")?, + lease_id: text(header, "lease_id")?, + lease_generation: number(header, "lease_generation")?, + operation_id: text(&source["location"], "operation_id")?, + source_sha256: text(reservation, "source_sha256")?, + archive_sha256: text(source, "raw_sha256")?, + archive_byte_count: number(source, "raw_byte_count")?, + image_digest: text(registry, "image_digest")?, + configuration_digest: text(selected, "configuration_sha256")?, + registry_entry_digest: text(registry, "entry_digest")?, + maximum_control_bytes: job.limits.maximum_control_bytes, + maximum_entries: usize::try_from(number(archive_limits, "maximum_entries")?)?, + maximum_expanded_bytes: number(archive_limits, "maximum_expanded_bytes")?, + }) +} + +fn spool( + input: &mut File, + target: &Path, + count: u64, + maximum: u64, + envelope: &Envelope, +) -> Result { + if count == 0 || count > maximum { + return Err("PRE spool bound invalid".into()); + } + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(target)?; + let mut remaining = count; + let mut buffer = [0; 65536]; + while remaining > 0 { + envelope.check()?; + let size = remaining.min(buffer.len() as u64) as usize; + read_staged_bytes(input, &mut buffer[..size], &|| envelope.check())?; + file.write_all(&buffer[..size])?; + remaining -= size as u64; + } + envelope.check()?; + file.seek(SeekFrom::Start(0))?; + Ok(file) +} + +fn transfer_root_owner(path: &Path, uid: u32, gid: u32, envelope: &Envelope) -> Result<()> { + envelope.check()?; + let metadata = fs::symlink_metadata(path)?; + if metadata.is_dir() { + for entry in fs::read_dir(path)? { + transfer_root_owner(&entry?.path(), uid, gid, envelope)?; + } + } + // Only the verified, supervisor-private tree exists here. lchown never + // follows the platform root's pinned symlink targets into the host root. + syscall_ok(unsafe { + libc::lchown( + c(path.to_str().ok_or("PRE root path invalid")?)?.as_ptr(), + uid, + gid, + ) + }) +} + +struct Worker { + active: bool, + pid: Option, + control: UnixStream, + stderr: UnixStream, + log_bytes: usize, + cleanup: Instant, +} +impl Worker { + fn check_logs(&mut self, maximum: usize, deadline: Instant) -> Result<()> { + let mut buffer = [0u8; 8192]; + loop { + if Instant::now() >= deadline { + return Err("PRE log deadline exceeded".into()); + } + match self.stderr.read(&mut buffer) { + Ok(0) => return Ok(()), + Ok(count) => { + self.log_bytes = self + .log_bytes + .checked_add(count) + .ok_or("PRE log overflow")?; + if self.log_bytes > maximum { + return Err("PRE worker logs exceeded".into()); + } + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => return Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error.into()), + } + } + } + fn read_exact(&mut self, mut bytes: &mut [u8], envelope: &Envelope) -> Result<()> { + while !bytes.is_empty() { + envelope.check()?; + self.check_logs(envelope.limits.maximum_log_bytes, envelope.deadline)?; + let maximum = bytes.len().min(65536); + match self.control.read(&mut bytes[..maximum]) { + Ok(0) => return Err("PRE worker frame truncated".into()), + Ok(count) => bytes = &mut bytes[count..], + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(2)) + } + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => (), + Err(error) => return Err(error.into()), + } + } + envelope.check() + } + fn read_frame(&mut self, envelope: &Envelope) -> Result> { + let mut length = [0; 4]; + self.read_exact(&mut length, envelope)?; + let length = u32::from_be_bytes(length) as usize; + if length == 0 || length > envelope.limits.maximum_control_bytes { + return Err("PRE worker frame unbounded".into()); + } + let mut bytes = vec![0; length]; + self.read_exact(&mut bytes, envelope)?; + Ok(bytes) + } + fn reply(&mut self, result: &Value, envelope: &Envelope) -> Result<()> { + let bytes = serde_json::to_vec(result)?; + if bytes.is_empty() || bytes.len() > envelope.limits.maximum_control_bytes { + return Err("PRE worker reply unbounded".into()); + } + for mut remaining in [&(bytes.len() as u32).to_be_bytes()[..], &bytes[..]] { + while !remaining.is_empty() { + envelope.check()?; + self.check_logs(envelope.limits.maximum_log_bytes, envelope.deadline)?; + match self.control.write(&remaining[..remaining.len().min(65536)]) { + Ok(0) => return Err("PRE worker pipe closed".into()), + Ok(count) => remaining = &remaining[count..], + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(2)) + } + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => (), + Err(error) => return Err(error.into()), + } + } + } + envelope.check() + } + fn finish(&mut self, envelope: &Envelope) -> Result<()> { + let child = self.pid.ok_or("PRE worker already reaped")?; + let mut status = 0; + loop { + envelope.cleanup_check()?; + self.check_logs(envelope.limits.maximum_log_bytes, envelope.cleanup)?; + let waited = unsafe { libc::waitpid(child, &mut status, libc::WNOHANG) }; + if waited == child { + self.pid = None; + break; + } + if waited < 0 + && std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted + { + return Err(std::io::Error::last_os_error().into()); + } + thread::sleep(Duration::from_millis(2)); + } + fs::write(Path::new(WORKER).join("cgroup.kill"), "1")?; + loop { + envelope.cleanup_check()?; + if fs::read_to_string(Path::new(WORKER).join("cgroup.events"))? + .lines() + .any(|line| line == "populated 0") + { + break; + } + thread::sleep(Duration::from_millis(2)); + } + self.check_logs(envelope.limits.maximum_log_bytes, envelope.cleanup)?; + let mut trailing = [0]; + if self.control.read(&mut trailing)? != 0 { + return Err("PRE worker trailing frame".into()); + } + let memory = fs::read_to_string(Path::new(WORKER).join("memory.events"))?; + if !memory.lines().any(|line| line == "oom_kill 0") { + return Err("PRE worker memory limit exceeded".into()); + } + if !libc::WIFEXITED(status) || libc::WEXITSTATUS(status) != 0 { + return Err("PRE worker failed".into()); + } + self.active = false; + envelope.check() + } +} +impl Drop for Worker { + fn drop(&mut self) { + if !self.active { + return; + } + if let Some(child) = self.pid.take() { + let _ = stop_project(child, Path::new(WORKER), self.cleanup); + } else { + let _ = fs::write(Path::new(WORKER).join("cgroup.kill"), "1"); + } + } +} + +fn spawn_worker(root: &Path, view: &Path, envelope: &Envelope) -> Result { + let (parent, child) = socket_pair()?; + let (stderr, child_stderr) = socket_pair()?; + envelope.check()?; + let pid = unsafe { libc::fork() }; + if pid < 0 { + return Err(std::io::Error::last_os_error().into()); + } + if pid == 0 { + // No background threads exist at this fork. A child setup failure must + // exit here, never unwind into the supervisor's cleanup/response code. + exec_workload(|| -> Result<()> { + drop(parent); + drop(stderr); + private_mounts()?; + fs::write(Path::new(WORKER).join("cgroup.procs"), "0")?; + mount( + root.to_str().ok_or("PRE root invalid")?, + root.to_str().ok_or("PRE root invalid")?, + "", + libc::MS_BIND, + "", + )?; + mount( + view.to_str().ok_or("PRE worker view invalid")?, + root.join("work") + .to_str() + .ok_or("PRE worker mount invalid")?, + "", + libc::MS_BIND | libc::MS_REC, + "", + )?; + syscall_ok(unsafe { + libc::chroot(c(root.to_str().ok_or("PRE root invalid")?)?.as_ptr()) + })?; + std::env::set_current_dir("/")?; + confined_devices()?; + readonly_filesystem(envelope.limits.worker_scratch_bytes)?; + // The canonical ZIP projector alone writes this bounded tree. Root + // and source stay read-only; project code never enters this root. + mount( + "", + "/work/scratch", + "", + libc::MS_BIND + | libc::MS_REMOUNT + | libc::MS_NOSUID + | libc::MS_NODEV + | libc::MS_NOEXEC, + "", + )?; + drop_privileges(envelope.limits.worker_uid, envelope.limits.worker_gid)?; + syscall_ok(unsafe { libc::dup2(child.as_raw_fd(), 0) }.min(0))?; + syscall_ok(unsafe { libc::dup2(child.as_raw_fd(), 1) }.min(0))?; + syscall_ok(unsafe { libc::dup2(child_stderr.as_raw_fd(), 2) }.min(0))?; + seal_exec_descriptors()?; + install_workload_filter()?; + envelope.check()?; + let error = Command::new("/opt/venv/bin/python") + .args(["-I", "/opt/workstream/intake.py"]) + .env_clear() + .current_dir("/opt/workstream/backend") + .exec(); + Err(error.into()) + }); + } + drop(child); + drop(child_stderr); + let worker = Worker { + active: true, + pid: Some(pid), + control: parent, + stderr, + log_bytes: 0, + cleanup: envelope.cleanup, + }; + worker.control.set_nonblocking(true)?; + worker.stderr.set_nonblocking(true)?; + Ok(worker) +} + +fn terminal( + worker: &mut Worker, + envelope: &Envelope, + bound: &ProjectBinding<'_>, + project: impl FnOnce(&[u8]) -> Result, +) -> Result> { + let first = worker.read_frame(envelope)?; + let frame: WorkerFrame = serde_json::from_slice(&first)?; + if frame.protocol_version != "workstream.pre_submit_worker.v1" + || frame.request_digest != bound.request_digest + || frame.lease_id != bound.lease_id + || frame.lease_generation != bound.lease_generation + { + return Err("PRE initial worker binding differs".into()); + } + let ran_project = frame.operation == "project"; + let terminal = if ran_project { + let response = project(&first)?; + worker.reply(&response, envelope)?; + worker.read_frame(envelope)? + } else { + first + }; + let result: WorkerFrame = serde_json::from_slice(&terminal)?; + if result.protocol_version != "workstream.pre_submit_worker.v1" + || result.operation != "completed" + || result.request_digest != bound.request_digest + || result.lease_id != bound.lease_id + || result.lease_generation != bound.lease_generation + || (!ran_project && result.payload["workstream_default"]["eligible"] != false) + { + return Err("PRE terminal worker binding differs".into()); + } + Ok(terminal) +} + +pub(crate) fn run(arguments: impl Iterator) -> Result<()> { + let limits = parse_limits(arguments)?; + let envelope = Envelope::prepare(limits)?; + let descriptor = unsafe { libc::dup(0) }; + if descriptor < 0 { + return Err(std::io::Error::last_os_error().into()); + } + let mut input = unsafe { File::from_raw_fd(descriptor) }; + trial::set_nonblocking(&input)?; + let mut length = [0; 4]; + read_staged_bytes(&mut input, &mut length, &|| envelope.check())?; + let length = u32::from_be_bytes(length) as usize; + if length == 0 || length > MAX_JOB_BYTES { + return Err("PRE job unbounded".into()); + } + let mut bytes = vec![0; length]; + read_staged_bytes(&mut input, &mut bytes, &|| envelope.check())?; + let job: PreBootstrapJob = serde_json::from_slice(&bytes)?; + drop(bytes); + if job.limits != limits { + return Err("PRE early envelope differs".into()); + } + let bound = binding(&job)?; + envelope.check()?; + private_mounts()?; + mount_directory(Path::new("/work"))?; + let mut entropy = [0; 16]; + File::open("/dev/urandom")?.read_exact(&mut entropy)?; + let suffix: String = entropy.iter().map(|byte| format!("{byte:02x}")).collect(); + let private = PathBuf::from(format!("/.workstream-pre-{suffix}")); + fs::create_dir(&private)?; + fs::set_permissions(&private, fs::Permissions::from_mode(0o700))?; + let mut bundle = spool( + &mut input, + &private.join("root.bundle"), + job.root.bundle_byte_count, + job.root_limits.maximum_bundle_bytes, + &envelope, + )?; + let root = private.join("root"); + stage_root(&mut bundle, &root, &job.root, &job.root_limits, || { + envelope.check() + })?; + drop(bundle); + fs::remove_file(private.join("root.bundle"))?; + let view = private.join("worker-view"); + fs::create_dir(&view)?; + fs::set_permissions(&view, fs::Permissions::from_mode(0o755))?; + fs::create_dir(view.join("input"))?; + let archive_path = view.join("input/archive.zip"); + let archive = spool( + &mut input, + &archive_path, + bound.archive_byte_count, + limits.maximum_source_bytes, + &envelope, + )?; + own_readonly(&archive, limits.worker_uid, 0o400)?; + drop(archive); + // A closed transfer marker prevents extra source frames being interpreted as + // worker dialogue. The host owns framing and its own exact-source hash. + let mut end = [0; 4]; + read_staged_bytes(&mut input, &mut end, &|| envelope.check())?; + if end != [0; 4] { + return Err("PRE source transfer terminator invalid".into()); + } + drop(input); + let workspace = private.join("tree"); + fs::create_dir(&workspace)?; + let workspace_file = File::open(&workspace)?; + own_readonly(&workspace_file, limits.worker_uid, 0o700)?; + fs::create_dir(view.join("scratch"))?; + mount( + workspace.to_str().ok_or("PRE workspace invalid")?, + view.join("scratch").to_str().ok_or("PRE view invalid")?, + "", + libc::MS_BIND, + "", + )?; + fs::write(view.join("request.json"), serde_json::to_vec(&job.startup)?)?; + own_readonly( + &File::open(view.join("request.json"))?, + limits.worker_uid, + 0o400, + )?; + for name in ["work", "dev", "tmp"] { + mount_directory(&root.join(name))?; + } + transfer_root_owner(&root, limits.worker_uid, limits.worker_gid, &envelope)?; + // Mask image-owned /work for the later project mount. The private parent + // containing root/source/control material stays root-owned and mode 0700. + let project_view = private.join("project-view"); + fs::create_dir(&project_view)?; + mount( + project_view.to_str().ok_or("PRE project view invalid")?, + "/work", + "", + libc::MS_BIND, + "", + )?; + let mut worker = spawn_worker(&root, &view, &envelope)?; + let terminal = terminal(&mut worker, &envelope, &bound, |frame| { + run_project_phase( + &bound, + frame, + &workspace, + job.selected.clone(), + envelope.project_limits(), + ) + })?; + worker.finish(&envelope)?; + envelope.check()?; + let descriptor = unsafe { libc::dup(1) }; + if descriptor < 0 { + return Err(std::io::Error::last_os_error().into()); + } + let mut output = unsafe { File::from_raw_fd(descriptor) }; + trial::set_nonblocking(&output)?; + for mut remaining in [&(terminal.len() as u32).to_be_bytes()[..], &terminal[..]] { + while !remaining.is_empty() { + envelope.check()?; + match output.write(&remaining[..remaining.len().min(65536)]) { + Ok(0) => return Err("PRE result pipe closed".into()), + Ok(count) => remaining = &remaining[count..], + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(2)) + } + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => (), + Err(error) => return Err(error.into()), + } + } + } + envelope.check() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::fd::OwnedFd; + use std::sync::atomic::{AtomicU64, Ordering}; + use workstream_checker_guest::trusted_root::{RootDescriptor, RootLimits}; + static NEXT: AtomicU64 = AtomicU64::new(0); + + fn limits() -> PreBootstrapLimits { + // Test-only quantities: no provider qualification or deployment defaults. + PreBootstrapLimits { + control: PrePartition { + cpu_millis: 100, + memory_bytes: 64 * 1024 * 1024, + processes: 3, + }, + worker: PrePartition { + cpu_millis: 400, + memory_bytes: 512 * 1024 * 1024, + processes: 8, + }, + project: PrePartition { + cpu_millis: 1500, + memory_bytes: 256 * 1024 * 1024, + processes: 8, + }, + worker_uid: 12345, + worker_gid: 12345, + worker_scratch_bytes: 4 * 1024 * 1024, + project_scratch_bytes: 4 * 1024 * 1024, + maximum_source_bytes: 1024 * 1024, + maximum_control_bytes: 2 * 1024 * 1024, + maximum_output_bytes: 1024 * 1024, + maximum_log_bytes: 1024 * 1024, + timeout_ms: 1000, + cleanup_timeout_ms: 2000, + overlay_bytes: 1024 * 1024, + filesystem_overhead_bytes: 1024 * 1024, + } + } + fn envelope() -> Envelope { + let now = Instant::now(); + Envelope { + limits: limits(), + deadline: now + Duration::from_secs(2), + cleanup: now + Duration::from_secs(3), + } + } + fn job() -> PreBootstrapJob { + // Python owner canonical serializer, generated from _source_reservation + // in tests/checkers/external/test_selected_pre_submit_coordination.py. + let startup: Value = + serde_json::from_str(include_str!("../../../fixtures/pre_startup.json")).unwrap(); + let reservation = &startup["request"]["reservation"]; + PreBootstrapJob { + limits: limits(), + root: RootDescriptor { + schema_version: "workstream.trusted_root.v1".into(), + platform_manifest_digest: format!("sha256:{}", "1".repeat(64)), + config_image_id: format!("sha256:{}", "2".repeat(64)), + default_behavior_sha256: reservation["policy"]["workstream_default"] + ["behavior_sha256"] + .as_str() + .unwrap() + .into(), + expanded_bytes: 3, + entries: 1, + bundle_sha256: reservation["runtime_profile"]["platform_root_sha256"] + .as_str() + .unwrap() + .into(), + bundle_byte_count: 128, + }, + root_limits: RootLimits { + maximum_bundle_bytes: 128, + maximum_root_bytes: 3, + maximum_entries: 1, + }, + selected: GuestJob { + purpose: GuestPurpose::Project { + capabilities: GuestCapabilities { + model: false, + execution: false, + }, + materials: vec![], + }, + request: Value::Null, + command: vec!["/selected-project".into()], + environment: vec![], + working_directory: "/".into(), + uid: 12346, + gid: 12346, + directories: vec![], + files: vec![], + }, + startup, + } + } + #[test] + fn early_limits_are_closed_and_reject_unbounded_partitions() { + let valid = limits(); + parse_limits([OsString::from(serde_json::to_string(&valid).unwrap())].into_iter()).unwrap(); + assert!(parse_limits(std::iter::empty()).is_err()); + assert!(parse_limits([OsString::from("{}"), OsString::from("extra")].into_iter()).is_err()); + let mut extra = serde_json::to_value(valid).unwrap(); + extra["fallback"] = json!(true); + assert!(parse_limits([OsString::from(extra.to_string())].into_iter()).is_err()); + for invalid in [ + PreBootstrapLimits { + maximum_source_bytes: 0, + ..valid + }, + PreBootstrapLimits { + worker_uid: 0, + ..valid + }, + PreBootstrapLimits { + control: PrePartition { + processes: 2, + ..valid.control + }, + ..valid + }, + PreBootstrapLimits { + worker: PrePartition { + cpu_millis: u64::MAX, + ..valid.worker + }, + ..valid + }, + PreBootstrapLimits { + maximum_control_bytes: 64 * 1024 * 1024 + 1, + ..valid + }, + PreBootstrapLimits { + cleanup_timeout_ms: valid.timeout_ms - 1, + ..valid + }, + ] { + assert!(validate_limits(invalid).is_err()); + } + } + #[test] + fn python_source_request_binds_bootstrap_and_profile_before_input() { + let valid = job(); + let bound = binding(&valid).unwrap(); + assert_eq!(bound.archive_byte_count, 1024); + assert_eq!(bound.lease_generation, 1); + assert_eq!( + bound.request_digest, + valid.startup["request"]["request_digest"] + ); + for case in [ + "request", + "source", + "root", + "source_bound", + "disk", + "memory", + "uid", + "purpose", + ] { + let mut changed = job(); + match case { + "request" => changed.startup["request"]["request_digest"] = json!("foreign"), + "source" => { + changed.startup["request"]["reservation"]["source"]["provider_generation"] = + json!("foreign"); + changed.startup["request"]["request_digest"] = + json!(canonical_hash(&changed.startup["request"]["reservation"]).unwrap()); + } + "root" => changed.root.bundle_sha256 = format!("sha256:{}", "f".repeat(64)), + "source_bound" => changed.limits.maximum_source_bytes = 1023, + "disk" => changed.limits.overlay_bytes = u64::MAX, + "memory" => changed.limits.worker.memory_bytes = u64::MAX, + "uid" => changed.selected.uid = changed.limits.worker_uid, + "purpose" => { + changed.selected.purpose = GuestPurpose::TrustedIntake { + cpu_millis: 1000, + memory_bytes: 1024, + } + } + _ => unreachable!(), + } + assert!(binding(&changed).is_err(), "accepted {case}"); + } + } + + struct Scratch(PathBuf); + impl Scratch { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "ws-pre-spool-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Scratch { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + #[test] + fn source_spool_reads_exact_count_and_stalled_input_expires() { + let scratch = Scratch::new(); + let (reader, mut writer) = socket_pair().unwrap(); + reader.set_nonblocking(true).unwrap(); + let payload = vec![0x42; 130_000]; + let sent = payload.clone(); + let sender = thread::spawn(move || { + writer.write_all(&sent).unwrap(); + writer.write_all(b"END!").unwrap(); + }); + let mut input = File::from(OwnedFd::from(reader)); + let mut staged = spool( + &mut input, + &scratch.0.join("source"), + payload.len() as u64, + payload.len() as u64, + &envelope(), + ) + .unwrap(); + let mut actual = Vec::new(); + staged.read_to_end(&mut actual).unwrap(); + assert_eq!(actual, payload); + let mut end = [0; 4]; + read_staged_bytes(&mut input, &mut end, &|| Ok(())).unwrap(); + assert_eq!(&end, b"END!"); + sender.join().unwrap(); + assert!(spool(&mut input, &scratch.0.join("excess"), 4, 3, &envelope()).is_err()); + assert!(!scratch.0.join("excess").exists()); + let (reader, mut writer) = socket_pair().unwrap(); + reader.set_nonblocking(true).unwrap(); + writer.write_all(b"x").unwrap(); + let mut input = File::from(OwnedFd::from(reader)); + let mut finite = envelope(); + finite.deadline = Instant::now() + Duration::from_millis(30); + assert!(spool(&mut input, &scratch.0.join("partial"), 2, 2, &finite) + .unwrap_err() + .to_string() + .contains("deadline")); + assert!(fs::metadata(scratch.0.join("partial")).unwrap().len() <= 2); + } + + fn channel() -> (Worker, UnixStream, UnixStream) { + let (control, peer) = socket_pair().unwrap(); + let (stderr, logs) = socket_pair().unwrap(); + control.set_nonblocking(true).unwrap(); + stderr.set_nonblocking(true).unwrap(); + ( + Worker { + active: false, + pid: None, + control, + stderr, + log_bytes: 0, + cleanup: Instant::now() + Duration::from_secs(2), + }, + peer, + logs, + ) + } + fn frame(bound: &ProjectBinding<'_>, operation: &str, payload: Value) -> Value { + json!({"protocol_version":"workstream.pre_submit_worker.v1","operation":operation, + "request_digest":bound.request_digest,"lease_id":bound.lease_id,"lease_generation":bound.lease_generation,"payload":payload}) + } + fn send(peer: &mut UnixStream, value: &Value) { + let bytes = serde_json::to_vec(value).unwrap(); + peer.write_all(&(bytes.len() as u32).to_be_bytes()).unwrap(); + for chunk in bytes.chunks(3) { + peer.write_all(chunk).unwrap(); + } + } + #[test] + fn worker_dialogue_blocks_project_on_defaults_and_allows_only_one_project_phase() { + let job = job(); + let bound = binding(&job).unwrap(); + let blocked = frame( + &bound, + "completed", + json!({"workstream_default":{"eligible":false}}), + ); + let (mut worker, mut peer, _logs) = channel(); + send(&mut peer, &blocked); + let result = terminal(&mut worker, &envelope(), &bound, |_| { + panic!("project ran after default blocker") + }) + .unwrap(); + assert_eq!(serde_json::from_slice::(&result).unwrap(), blocked); + for terminal_operation in ["completed", "project"] { + let (mut worker, mut peer, _logs) = channel(); + let first = frame(&bound, "project", json!({"request":{},"manifest":{}})); + let last = frame( + &bound, + terminal_operation, + json!({"workstream_default":{"eligible":true}}), + ); + let peer = thread::spawn(move || { + send(&mut peer, &first); + let mut length = [0; 4]; + peer.read_exact(&mut length).unwrap(); + let mut reply = vec![0; u32::from_be_bytes(length) as usize]; + peer.read_exact(&mut reply).unwrap(); + assert_eq!( + serde_json::from_slice::(&reply).unwrap(), + json!({"phase_result":true}) + ); + send(&mut peer, &last); + }); + let mut called = 0; + let result = terminal(&mut worker, &envelope(), &bound, |_| { + called += 1; + Ok(json!({"phase_result":true})) + }); + assert_eq!(called, 1); + assert_eq!(result.is_ok(), terminal_operation == "completed"); + peer.join().unwrap(); + } + } + #[test] + fn worker_control_rejects_truncation_oversize_logs_and_rebound_fence() { + let (mut worker, mut peer, _logs) = channel(); + peer.write_all(&[0, 0]).unwrap(); + drop(peer); + assert!(worker + .read_frame(&envelope()) + .unwrap_err() + .to_string() + .contains("truncated")); + let (mut worker, mut peer, _logs) = channel(); + peer.write_all(&u32::MAX.to_be_bytes()).unwrap(); + assert!(worker + .read_frame(&envelope()) + .unwrap_err() + .to_string() + .contains("unbounded")); + let (mut worker, _peer, mut logs) = channel(); + logs.write_all(b"four").unwrap(); + assert!(worker + .check_logs(3, envelope().deadline) + .unwrap_err() + .to_string() + .contains("logs")); + let job = job(); + let bound = binding(&job).unwrap(); + let (mut worker, mut peer, _logs) = channel(); + let mut request = frame(&bound, "project", json!({})); + request["lease_generation"] = json!(2); + send(&mut peer, &request); + assert!(terminal(&mut worker, &envelope(), &bound, |_| panic!( + "foreign lease launched project" + )) + .is_err()); + let (mut worker, _peer, _logs) = channel(); + let mut finite = envelope(); + finite.deadline = Instant::now() + Duration::from_millis(30); + assert!(worker + .read_frame(&finite) + .unwrap_err() + .to_string() + .contains("deadline")); + } +} diff --git a/external_checkers/workstream-checker-guest/src/pre_bootstrap.rs b/external_checkers/workstream-checker-guest/src/pre_bootstrap.rs new file mode 100644 index 000000000..0283152b7 --- /dev/null +++ b/external_checkers/workstream-checker-guest/src/pre_bootstrap.rs @@ -0,0 +1,47 @@ +//! Private PRE bootstrap inputs, supplied only by the trusted node supervisor. +use crate::{ + trusted_root::{RootDescriptor, RootLimits}, + GuestJob, +}; +use serde::{Deserialize, Serialize}; + +pub const PRE_LIMITS_ARGUMENT: &str = "--pre-limits"; +pub const PRE_LIMITS_MAXIMUM_BYTES: usize = 4096; + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct PrePartition { + pub cpu_millis: u64, + pub memory_bytes: u64, + pub processes: u64, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct PreBootstrapLimits { + pub control: PrePartition, + pub worker: PrePartition, + pub project: PrePartition, + pub worker_uid: u32, + pub worker_gid: u32, + pub worker_scratch_bytes: u64, + pub project_scratch_bytes: u64, + pub maximum_source_bytes: u64, + pub maximum_control_bytes: usize, + pub maximum_output_bytes: usize, + pub maximum_log_bytes: usize, + pub timeout_ms: u64, + pub cleanup_timeout_ms: u64, + pub overlay_bytes: u64, + pub filesystem_overhead_bytes: u64, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct PreBootstrapJob { + pub limits: PreBootstrapLimits, + pub root: RootDescriptor, + pub root_limits: RootLimits, + pub selected: GuestJob, + pub startup: serde_json::Value, +} diff --git a/external_checkers/workstream-checker-guest/src/trusted_root.rs b/external_checkers/workstream-checker-guest/src/trusted_root.rs index e5aa62a8d..daade027c 100644 --- a/external_checkers/workstream-checker-guest/src/trusted_root.rs +++ b/external_checkers/workstream-checker-guest/src/trusted_root.rs @@ -1,6 +1,6 @@ //! Independently pinned platform-root staging. This does not execute a workload. //! The caller owns a private bounded spool and charges spool plus expanded root. -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::HashSet; use std::fs::{self, File, OpenOptions}; @@ -13,7 +13,7 @@ const MAGIC: &[u8] = b"WSROOT1\n"; const MAX_HEADER: usize = 16384; type Result = std::result::Result>; -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RootDescriptor { pub schema_version: String, @@ -26,6 +26,8 @@ pub struct RootDescriptor { pub bundle_byte_count: u64, } +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] pub struct RootLimits { pub maximum_bundle_bytes: u64, pub maximum_root_bytes: u64, From a7ee22f022eddf564ce7742e9e00f73d15e961a0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 15:14:36 +0100 Subject: [PATCH 088/513] Record scoped PRE bootstrap review and live dialogue proof gap --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d16461fe3..f1c636530 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1961,3 +1961,14 @@ configured pins and lease admission, the invocation/profile/cleanup response envelope, trusted-root rebuild, native qualification and public cutover remain required. This is a connected guest code path, not a runnable end-to-end service or accepted-submission claim. + +Architecture/security passed the guest bootstrap scope at clean `7ad19cb35`, +with no concrete defect found. QA passed the exercised local bootstrap contracts +at that same candidate while explicitly retaining a separate proof gap: run a +real Python `PreSubmitWorker` with a real ZIP through the Rust supervisor socket +dialogue, checking the exact project frame and typed completion. Synthetic +frames and phase sentinels do not establish that cross-language compatibility. +Neither verdict establishes privileged chroot/cgroup/UID behavior, a one-VM +provider run, host pin/lease authority or the complete PRE service. The next +connected proof is that portable real-worker exchange, followed by the native +host dispatch and full runtime/profile/cleanup envelope. From d6387472bd4f84776649b923ad39fb8b0cc92778 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 15:33:51 +0100 Subject: [PATCH 089/513] Prove live Python and Rust PRE dialogue in the required checker job --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 49 +++++ .github/workflows/backend.yml | 38 ++++ external_checkers/README.md | 24 ++- .../workstream-checker-guest/Cargo.toml | 4 + .../src/pre/bootstrap.rs | 6 +- .../src/pre/dialogue_proof.rs | 173 ++++++++++++++++++ .../tests/pre_dialogue.py | 139 ++++++++++++++ 7 files changed, 430 insertions(+), 3 deletions(-) create mode 100644 external_checkers/workstream-checker-guest/src/pre/dialogue_proof.rs create mode 100644 external_checkers/workstream-checker-guest/tests/pre_dialogue.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f1c636530..3373c39dd 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -1972,3 +1972,52 @@ Neither verdict establishes privileged chroot/cgroup/UID behavior, a one-VM provider run, host pin/lease authority or the complete PRE service. The next connected proof is that portable real-worker exchange, followed by the native host dispatch and full runtime/profile/cleanup envelope. + +The next proof closes the review's real-worker dialogue gap without claiming +privileged isolation. Allowed scope is guest test-only Cargo feature/test module, +a portable Python proof driver under external checker tests, the existing +checker CI job and its necessary scope selection, the matching README command, +and this record. It launches +the actual `PreSubmitWorker` on real ZIPs over Rust-owned sockets, invokes the +production Rust terminal/request validators, returns an SDK-constructed project +result, and validates the received completion with Python's typed owner contract. +Use a passing directory/file ZIP and canonical rejection cases with a project +start sentinel. Project execution is intentionally a protocol-test result, not +a substitute VM or confinement implementation. + +A test-only Cargo feature separates the backend Python dependency from ordinary +Rust unit tests. The existing checker CI job must explicitly install the frozen +backend dependencies and execute the exact feature test, with no ignored failure +or empty selection. Preserve existing gates, timeout and authority. Acceptance +requires actual exchange, typed completion, a discriminating mutation and traced +CI selection/exit propagation. QA/test-delta and CI-integrity review apply; no +new runtime mode, deployment default, public route or native qualification claim +is allowed. Human review focus is actual process/protocol custody and proof +selection rather than synthetic frame counts. + +The feature proof now runs the real Python worker and Rust terminal/request +validators over live sockets for passing, secret-bearing and malformed ZIPs. +The passing input includes an explicit directory and file; Rust checks their +exact projected input fields. The secret case uses an incompatible project +schema and both blockers assert zero project calls. Rust supplies a typed SDK +protocol result, and a separate Python process validates the exact received +completion through `SelectedPreSubmitExecutionFacts.validate_lease`, including +source bytes, independent expected manifest, default status and member count. +The helper's simulated reply is explicitly unused. Child guards own termination +and reaping; fixture cleanup begins only after successful directory creation. + +The live proof passes, along with the ordinary 12 library/40 binary guest tests +and 47 CI-scope tests. Rebinding the Rust reply's lease generation makes the +live passing case fail after exactly one project call; production transport was +restored. An earlier negative probe used a resolved base interpreter and failed +test-helper import before startup; it is excluded from mutation evidence. The +corrected probe preserves the frozen virtualenv interpreter path. + +The existing checker job now installs its frozen Python dependencies and runs +the feature proof. One shared exact Cargo selection is checked through `--list`, +then its result must report one passed and zero ignored tests. Local execution +of that workflow step passes. Executing the exact guard snippets rejects zero +or duplicate selection, missing results and ignored execution. Existing backend/ +checker/workflow changes already select full scope, so no selection policy was +changed. Formatting, name checks, record and link checks pass. This closes the +live dialogue proof gap, not native isolation or host/public integration. diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml index a99eab795..20c5363f4 100644 --- a/.github/workflows/backend.yml +++ b/.github/workflows/backend.yml @@ -271,6 +271,44 @@ jobs: - name: Verify trial qualification evidence guards run: python3 external_checkers/workstream-checker-service/tests/test_qualify_smol_script.py -v + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: "3.12" + + - name: Install frozen backend dependencies for the PRE dialogue proof + working-directory: backend + shell: bash + run: | + set -euo pipefail + python -m pip install "uv==0.10.7" + test "$(uv --version)" = "uv 0.10.7" + uv lock --check + uv sync --frozen --extra agents --extra dev + + - name: Verify the live Python and Rust PRE dialogue + working-directory: external_checkers + shell: bash + env: + WORKSTREAM_PRE_WORKER_PYTHON: ${{ github.workspace }}/backend/.venv/bin/python + PRE_DIALOGUE_TEST_NAME: pre::bootstrap::dialogue_proof::live_python_worker_dialogue + run: | + set -euo pipefail + proof=(cargo test --locked -p workstream-checker-guest --bin workstream-checker-guest --features pre-dialogue-proof "${PRE_DIALOGUE_TEST_NAME}") + "${proof[@]}" -- --list --exact > "${RUNNER_TEMP}/pre-dialogue-selection.txt" + python - <<'PYPROOF' + import os + from pathlib import Path + selected = Path(os.environ["RUNNER_TEMP"], "pre-dialogue-selection.txt").read_text().splitlines() + assert [line for line in selected if line.endswith(": test")] == [os.environ["PRE_DIALOGUE_TEST_NAME"] + ": test"] + PYPROOF + "${proof[@]}" -- --exact --test-threads=1 | tee "${RUNNER_TEMP}/pre-dialogue-result.txt" + python - <<'PYPROOF' + import os + from pathlib import Path + summaries = [line for line in Path(os.environ["RUNNER_TEMP"], "pre-dialogue-result.txt").read_text().splitlines() if line.startswith("test result:")] + assert len(summaries) == 1 and summaries[0].startswith("test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured;") + PYPROOF + lanes: needs: [scope, minio-image] if: >- diff --git a/external_checkers/README.md b/external_checkers/README.md index 24d234f80..5fd54a4ca 100644 --- a/external_checkers/README.md +++ b/external_checkers/README.md @@ -502,9 +502,29 @@ private parent without following its final symlink and anchors staging through that held directory descriptor. The caller must provide the private parent, aggregate deadline/cancellation checks, and capacity for both the spool and expanded root, then mount the root read-only before executing a -trusted child. Combined supervisor wiring and native isolation proof remain -required; this library alone does not authorize project execution. +trusted child. The PRE guest bootstrap calls this verifier; host dispatch and +native isolation proof remain required. This library alone does not authorize +project execution. Cleanup restores owned directory permissions after late staging failures; an underlying filesystem cleanup error is propagated and cannot establish released capacity. Relative and absolute symlink targets that traverse above the root are refused before installation. + +### Portable PRE dialogue proof + +With the frozen backend environment installed, run from the repository root: + +```bash +WORKSTREAM_PRE_WORKER_PYTHON="$PWD/backend/.venv/bin/python" \ + cargo +1.84.0 test --manifest-path external_checkers/Cargo.toml --locked \ + -p workstream-checker-guest --bin workstream-checker-guest \ + --features pre-dialogue-proof \ + pre::bootstrap::dialogue_proof::live_python_worker_dialogue -- --exact --test-threads=1 +``` + +This test runs the real Python worker on ZIP bytes through the Rust supervisor's +socket dialogue and validates the received completion with Python's typed owner +contract. The project result is a protocol sentinel; this does not qualify native +mounts, cgroups, root images or one-VM execution. The checker CI job requires this +test and rejects empty selection or ignored execution. The Cargo feature affects +only test code and introduces no runtime entry point. diff --git a/external_checkers/workstream-checker-guest/Cargo.toml b/external_checkers/workstream-checker-guest/Cargo.toml index 61c1141dc..2005da723 100644 --- a/external_checkers/workstream-checker-guest/Cargo.toml +++ b/external_checkers/workstream-checker-guest/Cargo.toml @@ -5,6 +5,10 @@ edition.workspace = true license.workspace = true rust-version.workspace = true +[features] +# Only enables the live Python/Rust protocol test; no runtime entry point. +pre-dialogue-proof = [] + [dependencies] serde.workspace = true serde_json.workspace = true diff --git a/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs b/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs index bf965df2a..c9573cad1 100644 --- a/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs +++ b/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs @@ -717,7 +717,7 @@ mod tests { use workstream_checker_guest::trusted_root::{RootDescriptor, RootLimits}; static NEXT: AtomicU64 = AtomicU64::new(0); - fn limits() -> PreBootstrapLimits { + pub(super) fn limits() -> PreBootstrapLimits { // Test-only quantities: no provider qualification or deployment defaults. PreBootstrapLimits { control: PrePartition { @@ -1075,3 +1075,7 @@ mod tests { .contains("deadline")); } } + +#[cfg(all(test, feature = "pre-dialogue-proof"))] +#[path = "dialogue_proof.rs"] +mod dialogue_proof; diff --git a/external_checkers/workstream-checker-guest/src/pre/dialogue_proof.rs b/external_checkers/workstream-checker-guest/src/pre/dialogue_proof.rs new file mode 100644 index 000000000..a58fd252c --- /dev/null +++ b/external_checkers/workstream-checker-guest/src/pre/dialogue_proof.rs @@ -0,0 +1,173 @@ +//! Feature-selected portable integration proof, explicitly run by checker CI. +use super::*; +use std::os::fd::OwnedFd; +use std::process::{Child, Stdio}; + +struct ChildGuard(Child); +impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} +struct Directory(PathBuf); +impl Drop for Directory { + fn drop(&mut self) { + // The real projector seals directories 0500. Restore only fixture + // directory permissions so the test owns cleanup even after failure. + fn writable(path: &Path) { + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + for entry in fs::read_dir(path).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_dir() { + writable(&entry.path()); + } + } + } + writable(&self.0); + fs::remove_dir_all(&self.0).unwrap(); + } +} +fn wait(child: &mut ChildGuard, deadline: Instant) -> std::process::ExitStatus { + loop { + if let Some(status) = child.0.try_wait().unwrap() { + return status; + } + assert!( + Instant::now() < deadline, + "Python proof process exceeded deadline" + ); + thread::sleep(Duration::from_millis(5)); + } +} + +#[test] +fn live_python_worker_dialogue() { + let python = std::env::var_os("WORKSTREAM_PRE_WORKER_PYTHON") + .expect("pre-dialogue-proof requires the frozen backend Python interpreter"); + let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/pre_dialogue.py"); + for case in ["passing", "secret", "unsafe"] { + let path = std::env::temp_dir().join(format!("ws-live-pre-{}-{case}", std::process::id())); + fs::create_dir(&path).unwrap(); + let directory = Directory(path); + fs::set_permissions(&directory.0, fs::Permissions::from_mode(0o700)).unwrap(); + let mut limits = super::tests::limits(); + limits.timeout_ms = 30_000; + limits.cleanup_timeout_ms = 45_000; + let now = Instant::now(); + let envelope = Envelope { + limits, + deadline: now + Duration::from_secs(30), + cleanup: now + Duration::from_secs(45), + }; + let (parent, child) = socket_pair().unwrap(); + let (stderr, child_stderr) = socket_pair().unwrap(); + let mut process = ChildGuard( + Command::new(&python) + .arg(&script) + .args(["worker", case]) + .arg(&directory.0) + .env( + "WORKSTREAM_PRE_PROOF_LIMITS", + serde_json::to_string(&limits).unwrap(), + ) + .stdin(Stdio::from(OwnedFd::from(child.try_clone().unwrap()))) + .stdout(Stdio::from(OwnedFd::from(child))) + .stderr(Stdio::from(OwnedFd::from(child_stderr))) + .spawn() + .unwrap(), + ); + parent.set_nonblocking(true).unwrap(); + stderr.set_nonblocking(true).unwrap(); + // ChildGuard owns this portable process; native cgroup cleanup is not + // simulated. Production Worker framing and terminal sequencing are used. + let mut worker = Worker { + active: false, + pid: None, + control: parent, + stderr, + log_bytes: 0, + cleanup: envelope.cleanup, + }; + let prefix = worker + .read_frame(&envelope) + .unwrap_or_else(|error| panic!("live worker startup {case}: {error}")); + let job: PreBootstrapJob = serde_json::from_slice(&prefix).unwrap(); + assert_eq!(job.limits, limits); + let bound = binding(&job).unwrap(); + let mut project_calls = 0; + let received = terminal(&mut worker, &envelope, &bound, |frame| { + project_calls += 1; + assert_eq!( + case, "passing", + "default blocker launched the project phase" + ); + let (request, manifest) = super::super::project_request(&bound, frame)?; + assert_eq!(manifest.entries.len(), 2); + assert_eq!(manifest.entries[0].path(), "nested"); + assert_eq!(manifest.entries[1].path(), "nested/work.txt"); + assert_eq!( + request.value["input"]["manifest"][0], + json!({"normalized_path":"nested", + "entry_type":"directory","byte_count":0,"sha256":null,"executable":null}) + ); + assert_eq!(request.value["input"]["manifest"][1]["byte_count"], 14); + assert_eq!( + request.value["input"]["manifest"][1]["sha256"], + format!("sha256:{:x}", Sha256::digest(b"finished work\n")) + ); + let result = workstream_checker_sdk::completed_result(&request, vec![])?; + Ok( + json!({"request_digest":bound.request_digest,"lease_id":bound.lease_id, + "lease_generation":bound.lease_generation,"result":result}), + ) + }); + let received = received.unwrap_or_else(|error| { + panic!("live case {case} failed after {project_calls} project calls: {error}") + }); + assert_eq!(project_calls, usize::from(case == "passing")); + assert!(wait(&mut process, envelope.cleanup).success()); + worker + .check_logs(limits.maximum_log_bytes, envelope.cleanup) + .unwrap(); + assert_eq!( + worker.log_bytes, 0, + "Python worker emitted unexpected diagnostics" + ); + let mut trailing = [0]; + assert_eq!(worker.control.read(&mut trailing).unwrap(), 0); + // A fresh Python decoder validates the exact received completion, not + // a re-created Rust expectation or the helper's simulated reply. + let completion = directory.0.join("received-completion.json"); + fs::write(&completion, &received).unwrap(); + let mut validator = ChildGuard( + Command::new(&python) + .arg(&script) + .args(["validate", case]) + .arg(&directory.0) + .stdin(Stdio::from(File::open(&completion).unwrap())) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(), + ); + assert!( + wait(&mut validator, envelope.cleanup).success(), + "typed completion rejected for {case}" + ); + let mut report = String::new(); + validator + .0 + .stdout + .take() + .unwrap() + .read_to_string(&mut report) + .unwrap(); + let report: Value = serde_json::from_str(&report).unwrap(); + assert_eq!(report["eligible"], case == "passing"); + assert!(report["result_digest"] + .as_str() + .unwrap() + .starts_with("sha256:")); + } +} diff --git a/external_checkers/workstream-checker-guest/tests/pre_dialogue.py b/external_checkers/workstream-checker-guest/tests/pre_dialogue.py new file mode 100644 index 000000000..e326ff6bb --- /dev/null +++ b/external_checkers/workstream-checker-guest/tests/pre_dialogue.py @@ -0,0 +1,139 @@ +"""Portable live-worker protocol proof; no mount, VM or execution qualification.""" +from __future__ import annotations + +from dataclasses import asdict, replace +from datetime import datetime +import hashlib +from io import BytesIO +import json +import os +from pathlib import Path +import struct +import sys +from uuid import UUID +import zipfile + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT / "backend")) + +from app.core.hashing import canonical_json_hash # noqa: E402 +from app.modules.checkers.api.selected_pre_submit import ( # noqa: E402 + SelectedPreSubmitExecutionFacts, + SelectedPreSubmitLeaseFacts, + SelectedPreSubmitReservationFacts, +) + +CONTENT = b"finished work\n" +SECRET = b"-----BEGIN RSA PRIVATE KEY-----\nsecret" + + +def zip_bytes(case: str) -> bytes: + """Create input bytes; only the actual worker inspects them in this proof.""" + if case == "unsafe": + return b"not a ZIP" + output = BytesIO() + with zipfile.ZipFile(output, "w") as archive: + archive.writestr("nested/", b"") + archive.writestr("nested/work.txt", SECRET if case == "secret" else CONTENT) + return output.getvalue() + + +def incompatible_schema(reservation): + """A default blocker must not enter this incompatible project contract.""" + from app.modules.checkers.api.external import external_checker_json_hash + from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy + from tests.checkers.external.support import registry_entry + binding = reservation.policy.entries[0].model_copy(update={"registry": registry_entry()}) + body = reservation.policy.model_dump(mode="json", exclude={"policy_sha256"}) + body["entries"] = [binding.model_dump(mode="json")] + policy = LockedExternalPreSubmitPolicy.model_validate_json(json.dumps( + body | {"policy_sha256": external_checker_json_hash(body)}, + )) + return replace(reservation, policy=policy, admission_lineage=replace( + reservation.admission_lineage, effective_plan_sha256=policy.policy_sha256, + )) + + +def worker_process(case: str, directory: Path) -> None: + """Use real stdin/stdout instead of the helper's simulated project reply.""" + from tests.test_trusted_intake import _pre_worker + worker, _, unused_reply, lease = _pre_worker( + directory, zip_bytes(case), + reservation_change=incompatible_schema if case == "secret" else None, + ) + assert unused_reply.calls == 0 + startup = {"operation": "execute_pre", "request": { + "protocol_version": "external_checker_service.v1", "operation": "execute_pre", + "reservation": lease.reservation.canonical_body(), + "request_digest": lease.reservation.request_digest, "lease_id": str(lease.lease_id), + "lease_generation": lease.lease_generation, "lease_expires_at": lease.lease_expires_at.isoformat(), + }, "isolation": asdict(worker._isolation)} + (directory / "startup.json").write_text(json.dumps(startup)) + # The prefix is test setup, consumed before production worker dialogue. Its + # root descriptor is synthetic and must never be used as qualification. + job = { + "limits": json.loads(os.environ["WORKSTREAM_PRE_PROOF_LIMITS"]), + "root": { + "schema_version": "workstream.trusted_root.v1", + "platform_manifest_digest": "sha256:" + "1" * 64, + "config_image_id": "sha256:" + "2" * 64, + "default_behavior_sha256": lease.reservation.default_behavior_sha256, + "expanded_bytes": 3, "entries": 1, "bundle_byte_count": 128, + "bundle_sha256": lease.reservation.runtime_profile.platform_root_sha256, + }, + "root_limits": {"maximum_bundle_bytes": 128, "maximum_root_bytes": 3, "maximum_entries": 1}, + "selected": {"purpose": {"kind": "project", "capabilities": {"model": False, "execution": False}, "materials": []}, + "request": None, "command": ["/protocol-result-sentinel"], "environment": [], + "working_directory": "/", "uid": 12346, "gid": 12346, "directories": [], "files": []}, + "startup": startup, + } + encoded = json.dumps(job).encode() + sys.stdout.buffer.write(struct.pack(">I", len(encoded)) + encoded) + sys.stdout.buffer.flush() + worker._reader, worker._writer = sys.stdin.buffer, sys.stdout.buffer + worker.run() + assert unused_reply.calls == 0, "simulated helper reply escaped into live dialogue" + + +def validate_completion(case: str, directory: Path) -> None: + """Validate exactly the frame Rust received, through the Python owner type.""" + startup = json.loads((directory / "startup.json").read_bytes()) + header = startup["request"] + reservation = SelectedPreSubmitReservationFacts.from_canonical_body(header["reservation"]) + lease = SelectedPreSubmitLeaseFacts(reservation, UUID(header["lease_id"]), + header["lease_generation"], datetime.fromisoformat(header["lease_expires_at"])) + terminal = json.loads(sys.stdin.buffer.read()) + assert terminal["operation"] == "completed" + execution = SelectedPreSubmitExecutionFacts.from_canonical_body(terminal["payload"]) + execution.validate_lease(lease) + archive = (directory / "pre.zip").read_bytes() + assert execution.observed_source.raw_sha256 == "sha256:" + hashlib.sha256(archive).hexdigest() + assert execution.observed_source.raw_byte_count == len(archive) + if case == "unsafe": + assert execution.manifest_body is None + assert execution.workstream_default.checks[0].status == "failed" + assert all(check.status == "not_run" for check in execution.workstream_default.checks[1:]) + else: + content = SECRET if case == "secret" else CONTENT + expected = {"schema_version": "workstream.submission_bundle_manifest.v1", "entries": [ + {"normalized_path": "nested", "entry_type": "directory"}, + {"normalized_path": "nested/work.txt", "entry_type": "file", "byte_count": len(content), + "sha256": "sha256:" + hashlib.sha256(content).hexdigest(), "executable": False}, + ]} + assert execution.manifest_body == expected + assert execution.manifest_sha256 == canonical_json_hash(expected) + if case == "secret": + assert execution.workstream_default.checks[2].status == "failed" + else: + assert all(check.status == "passed" for check in execution.workstream_default.checks) + assert execution.eligible == (case == "passing") + assert len(execution.external_members) == (1 if case == "passing" else 0) + if case == "passing": + assert execution.external_members[0].result.verdict == "passed" + print(json.dumps({"eligible": execution.eligible, "result_digest": execution.result_digest})) + + +if __name__ == "__main__": + mode, case, directory = sys.argv[1:] + assert case in {"passing", "secret", "unsafe"} + {"worker": worker_process, "validate": validate_completion}[mode](case, Path(directory)) From 6b6c307446155c78aca6e2443d6eeaf3c3f51447 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 15:35:36 +0100 Subject: [PATCH 090/513] Record reviewed live PRE dialogue proof and required CI execution --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3373c39dd..c7d5f39d8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -2021,3 +2021,11 @@ or duplicate selection, missing results and ignored execution. Existing backend/ checker/workflow changes already select full scope, so no selection policy was changed. Formatting, name checks, record and link checks pass. This closes the live dialogue proof gap, not native isolation or host/public integration. + +QA/test-delta, CI-integrity and documentation review passed this portable proof +at clean `d6387472b`. Reviewers confirmed the live Python/Rust exchange, the +corrected after-one-project-call mutation, exact CI selection/result guards and +required-status propagation. Hosted CI has not run on this unpushed cutover. +Native host `execute_pre` dispatch, independent configured pins and persisted +invocation custody, the runtime/profile/timing/cleanup response, public handoff +and actual VM qualification remain the next implementation and proof boundaries. From 9292eec4eab693f5b5d027b8123c0a7c19391972 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 15:50:28 +0100 Subject: [PATCH 091/513] Bind PRE invocation identity to the durable Smol cleanup journal --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 33 +++ .../workstream-checker-service/src/smol.rs | 24 +- .../src/smol/pre.rs | 138 +++++++++++ .../src/smol/pre/tests.rs | 217 ++++++++++++++++++ .../src/smol/tests.rs | 14 ++ 5 files changed, 425 insertions(+), 1 deletion(-) create mode 100644 external_checkers/workstream-checker-service/src/smol/pre.rs create mode 100644 external_checkers/workstream-checker-service/src/smol/pre/tests.rs diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c7d5f39d8..febffe4cf 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -2029,3 +2029,36 @@ required-status propagation. Hosted CI has not run on this unpushed cutover. Native host `execute_pre` dispatch, independent configured pins and persisted invocation custody, the runtime/profile/timing/cleanup response, public handoff and actual VM qualification remain the next implementation and proof boundaries. + +### Host PRE invocation journal + +This implements the pre-create custody portion of the reviewed native plan: +use the existing Smol lease and startup recovery owner, persisting PRE operation, +CHECKERS run ID (the reservation attempt ID), source operation, request/source/ +profile/image/configuration digests and execution fence before guardian or +provider creation. The allowed scope is the existing Smol service implementation, +its PRE module and tests, and this record. Public dispatch, response assembly, +policy decisions, source streaming and provider qualification are not claimed by +this step. Shared POST/trial creation and cleanup remain the same operations. + +This is architecture/security-sensitive L1 work under the prior native plan +review. Acceptance requires one PRE create attempt, malformed binding refusal +before persistence, and pending cleanup evidence only for the exact retained +private journal captured at creation. Node admission is quarantined even when +that evidence cannot be recovered. Recovery remains owned by the existing +lease guardian/startup reaper. Human and architecture/security review should +focus on pre-create ordering, identity binding, replaced-file refusal and the +absence of any inferred native qualification. QA/test-delta review should +exercise fence/source changes, inode replacement, links and permission loss, +plus the existing shared Smol tests. The public execute_pre handler and use of +this journal in its response remain required subsequent integration. + +The portable journal suite passes all 42 selected shared Smol tests, including +four PRE tests. Real filesystem probes reject changed source/fence, replacement +inode, symlink, hardlink and unsafe file/parent permissions. A failed guardian +handshake leaves one pre-bound journal; malformed input leaves none. Separate +probes prove quarantine both with retained custody and after journal loss. These +are journal/admission proofs, not successful guardian recovery or VM execution. +Formatting, diff, Commitrail and Markdown link checks pass. The new PRE entry +methods are not yet called by the public host dispatch; compiler dead-code +warnings reflect that unfinished integration rather than a runtime proof. diff --git a/external_checkers/workstream-checker-service/src/smol.rs b/external_checkers/workstream-checker-service/src/smol.rs index 23948a34f..2082aa5ed 100644 --- a/external_checkers/workstream-checker-service/src/smol.rs +++ b/external_checkers/workstream-checker-service/src/smol.rs @@ -34,6 +34,7 @@ pub(crate) mod trial; mod trial_io; pub(super) use intake::{serve as serve_intake, IntakeConfig}; mod io; +mod pre; pub(super) use io::{ProjectCallbacks, ProjectMaterials}; #[derive(Clone, Copy)] @@ -93,9 +94,12 @@ struct Lease { runtime: SmolConfig, #[serde(default)] private_home_root: Option, + #[serde(default)] + pre: Option, } struct Machine { lease: Lease, + journal: pre::Journal, guardian: Child, keeper: Option, consumed: bool, @@ -511,6 +515,10 @@ impl Lease { && root != &self.root && self.runtime.home == self.private_home_path() }) + && self + .pre + .as_ref() + .is_none_or(|invocation| self.private_home_root.is_none() && invocation.valid()) } fn inventory(&self, deadline: Instant) -> Result { let output = control( @@ -654,7 +662,7 @@ impl Machine { resources: Resources, deadline: Instant, ) -> Result { - Self::create_inner(config, resources, deadline, None) + Self::create_inner(config, resources, deadline, None, None) } pub(super) fn create_child( @@ -680,6 +688,7 @@ impl Machine { resources, deadline, Some(child_home_root.to_owned()), + None, ) } @@ -688,7 +697,16 @@ impl Machine { resources: Resources, deadline: Instant, private_home_root: Option, + pre: Option, ) -> Result { + if pre.as_ref().is_some_and(|invocation| !invocation.valid()) + || (pre.is_some() && private_home_root.is_some()) + { + return Err(ExecutionFailure::ordinary( + "implementation_unavailable", + false, + )); + } let mut s = settings(config) .map_err(|_| ExecutionFailure::ordinary("implementation_unavailable", false))? .clone(); @@ -745,6 +763,7 @@ impl Machine { root, runtime: s, private_home_root, + pre, }; let bytes = match serde_json::to_vec(&lease) { Ok(bytes) => bytes, @@ -786,6 +805,8 @@ impl Machine { File::open(&lease.root) .and_then(|f| f.sync_all()) .map_err(|_| ExecutionFailure::unsettled(false))?; + let journal = + pre::Journal::capture(&file, &bytes).map_err(|_| ExecutionFailure::unsettled(false))?; // Persist ownership before any runtime resource is created. The guardian // is a distinct exec with its own lifetime and only this lease's custody. let mut guardian = @@ -820,6 +841,7 @@ impl Machine { } let mut machine = Self { lease, + journal, guardian, keeper, consumed: false, diff --git a/external_checkers/workstream-checker-service/src/smol/pre.rs b/external_checkers/workstream-checker-service/src/smol/pre.rs new file mode 100644 index 000000000..a68b8f91d --- /dev/null +++ b/external_checkers/workstream-checker-service/src/smol/pre.rs @@ -0,0 +1,138 @@ +//! Host-owned PRE invocation and durable cleanup custody. +use super::*; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Invocation { + pub operation: Operation, + pub run_id: String, + pub source_operation_id: String, + pub request_digest: String, + pub source_sha256: String, + pub profile_sha256: String, + pub image_digest: String, + pub config_image_id: String, + pub lease_id: String, + pub lease_generation: u64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub(super) enum Operation { + #[serde(rename = "execute_pre")] + ExecutePre, +} + +impl Invocation { + pub(super) fn valid(&self) -> bool { + fn uuid(value: &str) -> bool { + value.len() == 36 + && value.bytes().enumerate().all(|(index, byte)| { + if matches!(index, 8 | 13 | 18 | 23) { + byte == b'-' + } else { + byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase() + } + }) + } + [&self.run_id, &self.source_operation_id, &self.lease_id] + .into_iter() + .all(|value| uuid(value)) + && [ + &self.request_digest, + &self.source_sha256, + &self.profile_sha256, + &self.image_digest, + &self.config_image_id, + ] + .into_iter() + .all(|value| valid_digest(value)) + && self.lease_generation > 0 + } +} + +// Captured from the fsynced descriptor before guardian or provider creation. +// Neither guest output nor a subsequently discovered pathname supplies this. +pub(super) struct Journal { + device: u64, + inode: u64, + sha256: String, +} + +impl Journal { + pub(super) fn capture(file: &File, bytes: &[u8]) -> Result { + let metadata = file.metadata().map_err(|_| "lease unavailable")?; + if !custody(&metadata) || metadata.len() != bytes.len() as u64 { + return Err("lease custody differs".into()); + } + Ok(Self { + device: metadata.dev(), + inode: metadata.ino(), + sha256: format!("sha256:{:x}", Sha256::digest(bytes)), + }) + } + + fn retained(&self, lease: &Lease) -> Result { + if lease.pre.is_none() || !lease.valid() { + return Err("PRE lease invalid".into()); + } + private_directory(&lease.root)?; + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK) + .open(lease.path()) + .map_err(|_| "lease unavailable")?; + let before = file.metadata().map_err(|_| "lease unavailable")?; + if !custody(&before) || before.dev() != self.device || before.ino() != self.inode { + return Err("lease custody differs".into()); + } + let mut bytes = Vec::new(); + Read::by_ref(&mut file) + .take(MAX_ENVELOPE_BYTES as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| "lease unavailable")?; + let expected = serde_json::to_vec(lease).map_err(|_| "lease invalid")?; + if bytes != expected || format!("sha256:{:x}", Sha256::digest(&bytes)) != self.sha256 { + return Err("lease binding differs".into()); + } + let after = fs::symlink_metadata(lease.path()).map_err(|_| "lease unavailable")?; + if !custody(&after) + || after.dev() != self.device + || after.ino() != self.inode + || after.len() != before.len() + { + return Err("lease custody differs".into()); + } + Ok(self.sha256.clone()) + } +} + +fn custody(metadata: &fs::Metadata) -> bool { + metadata.is_file() + && metadata.nlink() == 1 + && metadata.uid() == unsafe { libc::geteuid() } + && metadata.gid() == unsafe { libc::getegid() } + && metadata.mode() & 0o7777 == 0o600 + && metadata.len() <= MAX_ENVELOPE_BYTES as u64 +} + +impl Machine { + fn create_pre( + config: &ServiceConfig, + resources: Resources, + deadline: Instant, + invocation: Invocation, + ) -> Result { + // PRE has exactly one create attempt; never enter execute's retry loop. + Self::create_inner(config, resources, deadline, None, Some(invocation)) + } + + fn pending_pre_cleanup(&self, config: &ServiceConfig) -> Result { + // Refuse all further admission even if custody has been lost. The exact + // retained journal is recoverable by the guardian or startup reaper. + quarantine(config); + self.journal.retained(&self.lease) + } +} + +#[cfg(test)] +mod tests; diff --git a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs new file mode 100644 index 000000000..eb54fafb2 --- /dev/null +++ b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs @@ -0,0 +1,217 @@ +use super::*; + +fn invocation() -> Invocation { + Invocation { + operation: Operation::ExecutePre, + run_id: "01a1d010-14fa-7444-a807-ade92ac62129".into(), + source_operation_id: "01a1d010-14fa-7444-a807-ade92ac62130".into(), + request_digest: format!("sha256:{}", "a".repeat(64)), + source_sha256: format!("sha256:{}", "b".repeat(64)), + profile_sha256: format!("sha256:{}", "c".repeat(64)), + image_digest: format!("sha256:{}", "d".repeat(64)), + config_image_id: format!("sha256:{}", "e".repeat(64)), + lease_id: "01a1d010-14fa-7444-a807-ade92ac62131".into(), + lease_generation: 1, + } +} + +fn fixture() -> (PathBuf, ServiceConfig, Lease, Journal) { + let (root, mut config) = super::super::super::tests::test_config(); + let leases = root.join("leases"); + fs::create_dir(&leases).unwrap(); + fs::set_permissions(&leases, fs::Permissions::from_mode(0o700)).unwrap(); + let runtime = SmolConfig { + binary: root.join("unused-runtime"), + binary_sha256: format!("sha256:{}", "a".repeat(64)), + home: root.join("home"), + guest_binary: root.join("guest"), + guest_sha256: format!("sha256:{}", "b".repeat(64)), + cgroup_root: root.join("groups"), + maximum_parallel: 1, + maximum_storage_bytes: 4 * 1024 * 1024 * 1024, + }; + config.smol = Some(runtime.clone()); + config.smol_admission = Some(Arc::new( + Admission::new( + Capacity { + slots: 1, + memory_bytes: u64::MAX, + storage_bytes: u64::MAX, + }, + "e".repeat(64), + ) + .unwrap(), + )); + let lease = Lease { + name: format!("ws-{}", "0".repeat(32)), + owner: container_owner(&config).unwrap().to_owned(), + epoch: "e".repeat(64), + expires_ms: 1, + lifetime_ms: 1, + root: leases, + runtime, + private_home_root: None, + pre: Some(invocation()), + }; + let bytes = serde_json::to_vec(&lease).unwrap(); + let mut file = OpenOptions::new() + .create_new(true) + .write(true) + .mode(0o600) + .open(lease.path()) + .unwrap(); + file.write_all(&bytes).unwrap(); + file.sync_all().unwrap(); + let journal = Journal::capture(&file, &bytes).unwrap(); + (root, config, lease, journal) +} + +#[test] +fn pending_cleanup_requires_exact_pre_journal_and_quarantines_admission() { + let (root, config, lease, journal) = fixture(); + let mut machine = Machine { + lease, + journal, + guardian: Command::new("/bin/true").spawn().unwrap(), + keeper: None, + consumed: false, + }; + machine.guardian.wait().unwrap(); + let digest = machine.pending_pre_cleanup(&config).unwrap(); + assert_eq!( + digest, + format!( + "sha256:{:x}", + Sha256::digest(fs::read(machine.lease.path()).unwrap()) + ) + ); + assert!(config + .smol_admission + .as_ref() + .unwrap() + .reserve( + Capacity { + slots: 1, + memory_bytes: 1, + storage_bytes: 1, + }, + None + ) + .is_err()); + // A dead guardian does not erase the durable startup reaper obligation. + fs::remove_file(machine.lease.path()).unwrap(); + assert!(machine.pending_pre_cleanup(&config).is_err()); + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn lost_journal_still_quarantines_the_node() { + let (root, config, lease, journal) = fixture(); + let mut machine = Machine { + lease, + journal, + guardian: Command::new("/bin/true").spawn().unwrap(), + keeper: None, + consumed: false, + }; + machine.guardian.wait().unwrap(); + fs::remove_file(machine.lease.path()).unwrap(); + assert!(machine.pending_pre_cleanup(&config).is_err()); + assert!(config + .smol_admission + .as_ref() + .unwrap() + .reserve( + Capacity { + slots: 1, + memory_bytes: 1, + storage_bytes: 1, + }, + None + ) + .is_err()); + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn changed_or_rebound_cleanup_journal_is_never_a_receipt() { + for attack in [ + "fence", "source", "replace", "symlink", "hardlink", "mode", "parent", + ] { + let (root, _config, mut lease, journal) = fixture(); + let original = fs::read(lease.path()).unwrap(); + match attack { + "fence" => { + lease.pre.as_mut().unwrap().lease_generation += 1; + fs::write(lease.path(), serde_json::to_vec(&lease).unwrap()).unwrap(); + } + "source" => { + lease.pre.as_mut().unwrap().source_sha256 = format!("sha256:{}", "f".repeat(64)); + fs::write(lease.path(), serde_json::to_vec(&lease).unwrap()).unwrap(); + } + "replace" | "symlink" => { + let retained = root.join("retained"); + fs::rename(lease.path(), &retained).unwrap(); + if attack == "symlink" { + std::os::unix::fs::symlink(retained, lease.path()).unwrap(); + } else { + fs::write(lease.path(), original).unwrap(); + fs::set_permissions(lease.path(), fs::Permissions::from_mode(0o600)).unwrap(); + } + } + "hardlink" => fs::hard_link(lease.path(), root.join("alias")).unwrap(), + "mode" => fs::set_permissions(lease.path(), fs::Permissions::from_mode(0o644)).unwrap(), + "parent" => { + fs::set_permissions(&lease.root, fs::Permissions::from_mode(0o755)).unwrap() + } + _ => unreachable!(), + } + assert!(journal.retained(&lease).is_err(), "accepted {attack}"); + fs::remove_dir_all(root).unwrap(); + } +} + +#[test] +fn pre_creation_persists_binding_before_guardian_or_runtime() { + let (root, config, _lease, _journal) = fixture(); + let leases = config.socket_path.parent().unwrap().join("smol-leases"); + fs::create_dir(&leases).unwrap(); + fs::set_permissions(&leases, fs::Permissions::from_mode(0o700)).unwrap(); + let resources = Resources { + cpu_millis: 1000, + memory_bytes: 1024, + storage_gib: 1, + pids: 4, + }; + let mut invalid = invocation(); + invalid.lease_generation = 0; + assert!(Machine::create_pre( + &config, + resources, + Instant::now() + Duration::from_millis(100), + invalid + ) + .is_err()); + assert_eq!(fs::read_dir(&leases).unwrap().count(), 0); + // This test executable cannot run the production guardian entrypoint. Its + // failed handshake must leave exactly one already bound durable obligation. + assert!(Machine::create_pre( + &config, + resources, + Instant::now() + Duration::from_millis(100), + invocation() + ) + .is_err()); + let paths: Vec<_> = fs::read_dir(&leases) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(paths.len(), 1); + let saved: Lease = serde_json::from_slice(&fs::read(&paths[0]).unwrap()).unwrap(); + assert!(saved.valid()); + assert_eq!( + serde_json::to_value(saved.pre.unwrap()).unwrap(), + serde_json::to_value(invocation()).unwrap() + ); + fs::remove_dir_all(root).unwrap(); +} diff --git a/external_checkers/workstream-checker-service/src/smol/tests.rs b/external_checkers/workstream-checker-service/src/smol/tests.rs index ea738370e..a75b4a87c 100644 --- a/external_checkers/workstream-checker-service/src/smol/tests.rs +++ b/external_checkers/workstream-checker-service/src/smol/tests.rs @@ -99,6 +99,7 @@ fn foreign_lease_refuses_recovery_before_any_runtime_or_owned_cleanup() { root: leases.clone(), runtime, private_home_root: None, + pre: None, }; let owned = lease.path(); fs::write(&owned, serde_json::to_vec(&lease).unwrap()).unwrap(); @@ -261,6 +262,7 @@ fn private_child_home_is_derived_from_the_exact_lease() { root: lease_root, runtime, private_home_root: Some(child_home_root), + pre: None, }; assert!(lease.valid()); lease.runtime.home = root.join("shared-or-foreign-home"); @@ -346,12 +348,24 @@ fn intake_overlay_is_explicit_in_runtime_argv_and_project_creation_is_unchanged( root: root.join("leases"), runtime, private_home_root: None, + pre: None, }; fs::create_dir_all(lease.cgroup()).unwrap(); // A private ordinary file substitutes the cgroup control, with no host effect. fs::write(lease.cgroup().join("cgroup.procs"), b"").unwrap(); + fs::create_dir_all(&lease.root).unwrap(); + let bytes = serde_json::to_vec(&lease).unwrap(); + let mut file = OpenOptions::new() + .create_new(true) + .write(true) + .mode(0o600) + .open(lease.path()) + .unwrap(); + file.write_all(&bytes).unwrap(); + let journal = pre::Journal::capture(&file, &bytes).unwrap(); let mut machine = Machine { lease, + journal, guardian: Command::new("/bin/true").spawn().unwrap(), keeper: None, consumed: false, From 72a74be72e308d093f5f7ff2d77ef078f587b7d0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 15:52:06 +0100 Subject: [PATCH 092/513] Record scoped PRE invocation journal review and integration limits --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index febffe4cf..ecbe3cfc8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -2062,3 +2062,13 @@ are journal/admission proofs, not successful guardian recovery or VM execution. Formatting, diff, Commitrail and Markdown link checks pass. The new PRE entry methods are not yet called by the public host dispatch; compiler dead-code warnings reflect that unfinished integration rather than a runtime proof. + +Architecture/security and QA/test-delta review passed clean `9292eec4e` for +this custody scope. Reviewers inspected creation ordering and the exact +filesystem counterexamples; source/fence reserialization changes both the +in-memory expected lease and the on-disk body, thereby discriminating the +captured digest check. Replacement and link cases discriminate inode and +metadata custody. No additional mutation was claimed. Invocation validation is +structural only: the host handler must still compare it to locked source, +selection and configured runtime/profile facts. Successful PRE guardian recovery, +public dispatch, provider execution and native qualification are not proved. From 2f8eb812b880dd1a44b07b8dfd7baeb35dba6ed6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 16:02:47 +0100 Subject: [PATCH 093/513] Validate PRE host admission against configured runtime and resource pins --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 42 ++ .../src/pre/bootstrap.rs | 44 +- .../src/pre_bootstrap.rs | 38 ++ .../workstream-checker-sdk/src/lib.rs | 7 +- .../workstream-checker-service/src/main.rs | 3 + .../workstream-checker-service/src/smol.rs | 43 +- .../src/smol/pre.rs | 1 + .../src/smol/pre/admission.rs | 526 ++++++++++++++++++ .../src/smol/pre/admission/tests.rs | 272 +++++++++ .../src/smol/pre/tests.rs | 2 +- .../src/smol/tests.rs | 25 + 11 files changed, 953 insertions(+), 50 deletions(-) create mode 100644 external_checkers/workstream-checker-service/src/smol/pre/admission.rs create mode 100644 external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index ecbe3cfc8..5ad04eb1b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -2072,3 +2072,45 @@ metadata custody. No additional mutation was claimed. Invocation validation is structural only: the host handler must still compare it to locked source, selection and configured runtime/profile facts. Successful PRE guardian recovery, public dispatch, provider execution and native qualification are not proved. + +### Host PRE admission and configured envelope + +Continue the reviewed native host plan by binding the closed PRE header to the +exact configured runtime/profile/root and selected cached image before resource +allocation or source reads. Allowed files are the existing Rust service PRE +module/configuration/tests, shared image configuration reader, guest bootstrap +limits library/caller/tests, SDK registry validator and this record. Reuse the +SDK's registry check without inventing source input or evaluating an unrun +project's input schema. Reuse one early bootstrap limits validator on host and +guest. Shared image configuration parsing must consume the exact bounded bytes +whose digest was verified. No new deployment default, authority source, provider +qualification claim, host source spool, second VM or compatibility PRE path is +permitted. Host stream dispatch and the complete runtime response remain required. + +Acceptance for this architecture/security-sensitive L1 boundary is refusal of +mismatched request/source/configured pins, stale UTC deadlines, ambiguous selected +cache entries and unchecked capacity arithmetic before create; exact reservation +attempt/run identity; separate GiB rounding of storage and overlay; and bounded +bootstrap job construction with no project capabilities or fabricated input. +Tests must start from a passing control before each adverse mutation and retain +shared Smol/guest/SDK coverage. Architecture/security and QA/test-delta reviews +focus on configured-versus-self-consistent identities, refusal ordering, integer +arithmetic and the distinction between local admission proof and actual native +qualification. Structural configuration alone does not qualify a provider. + +The final portable checks pass 45 selected Smol tests, 52 guest tests and eight +SDK tests. Admission's 21 adverse cases each first pass an unchanged control; +mutation requests recompute registry/policy/request digests where necessary so +internally consistent rebinding reaches the relevant configured-pin checks. +UTC tests reject calendar normalization, leap seconds, unsupported offsets and +excess precision, flooring submillisecond expiry conservatively. Shared image +checks retain digest/platform and hardlink coverage and add bounded-size, +unsafe-mode and symlink refusal. The held root descriptor checks regular-file +custody and exact byte count; full root bytes remain verified by the guest's +existing WSROOT loader. No source bytes or provider calls occur in these tests. +An initial fixture inherited group-write permissions and failed before the +intended checks; that failed run is excluded, and fixtures now set explicit +permissions and require passing controls. Formatting, diff, record and link +checks pass. Host dispatch still does not call admission or stream the source; +these checks do not establish provider qualification, authorization independent +of the trusted caller, or a complete execution response. diff --git a/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs b/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs index c9573cad1..0d86284ef 100644 --- a/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs +++ b/external_checkers/workstream-checker-guest/src/pre/bootstrap.rs @@ -10,48 +10,14 @@ use workstream_checker_guest::trusted_root::stage_root; const CONTROL: &str = "/sys/fs/cgroup/workstream-pre-control"; const WORKER: &str = "/sys/fs/cgroup/workstream-pre-default"; -fn validate_limits(limits: PreBootstrapLimits) -> Result<()> { - for partition in [limits.control, limits.worker, limits.project] { - if partition.cpu_millis == 0 - || partition.cpu_millis.checked_mul(100).is_none() - || partition.memory_bytes == 0 - || partition.processes == 0 - { - return Err("PRE partition invalid".into()); - } - } - if limits.control.processes < 3 - || limits.worker_uid == 0 - || limits.worker_gid == 0 - || limits.worker_scratch_bytes == 0 - || limits.maximum_source_bytes == 0 - || limits.project_scratch_bytes == 0 - || limits.maximum_control_bytes == 0 - || limits.maximum_control_bytes > 64 * 1024 * 1024 - || limits.maximum_control_bytes as u64 > limits.control.memory_bytes - || limits.maximum_output_bytes == 0 - || limits.maximum_log_bytes == 0 - || u32::try_from(limits.maximum_output_bytes).is_err() - || u32::try_from(limits.maximum_log_bytes).is_err() - || limits.timeout_ms == 0 - || limits.timeout_ms > 14_400_000 - || limits.cleanup_timeout_ms < limits.timeout_ms - || limits.cleanup_timeout_ms > 14_400_000 - || limits.overlay_bytes == 0 - || limits.filesystem_overhead_bytes == 0 - { - return Err("PRE bootstrap bounds invalid".into()); - } - Ok(()) -} - fn parse_limits(mut arguments: impl Iterator) -> Result { let value = arguments.next().ok_or("PRE bootstrap limits missing")?; if value.len() > PRE_LIMITS_MAXIMUM_BYTES || arguments.next().is_some() { return Err("PRE bootstrap limits unbounded".into()); } - let limits = serde_json::from_str(value.to_str().ok_or("PRE limits encoding invalid")?)?; - validate_limits(limits)?; + let limits: PreBootstrapLimits = + serde_json::from_str(value.to_str().ok_or("PRE limits encoding invalid")?)?; + limits.validate()?; Ok(limits) } @@ -82,7 +48,7 @@ struct Envelope { } impl Envelope { fn prepare(limits: PreBootstrapLimits) -> Result { - validate_limits(limits)?; + limits.validate()?; let started = Instant::now(); let result = Self { limits, @@ -848,7 +814,7 @@ mod tests { ..valid }, ] { - assert!(validate_limits(invalid).is_err()); + assert!(invalid.validate().is_err()); } } #[test] diff --git a/external_checkers/workstream-checker-guest/src/pre_bootstrap.rs b/external_checkers/workstream-checker-guest/src/pre_bootstrap.rs index 0283152b7..01c9c05c6 100644 --- a/external_checkers/workstream-checker-guest/src/pre_bootstrap.rs +++ b/external_checkers/workstream-checker-guest/src/pre_bootstrap.rs @@ -45,3 +45,41 @@ pub struct PreBootstrapJob { pub selected: GuestJob, pub startup: serde_json::Value, } + +impl PreBootstrapLimits { + pub fn validate(&self) -> Result<(), String> { + let limits = *self; + for partition in [limits.control, limits.worker, limits.project] { + if partition.cpu_millis == 0 + || partition.cpu_millis.checked_mul(100).is_none() + || partition.memory_bytes == 0 + || partition.processes == 0 + { + return Err("PRE partition invalid".into()); + } + } + if limits.control.processes < 3 + || limits.worker_uid == 0 + || limits.worker_gid == 0 + || limits.worker_scratch_bytes == 0 + || limits.maximum_source_bytes == 0 + || limits.project_scratch_bytes == 0 + || limits.maximum_control_bytes == 0 + || limits.maximum_control_bytes > 64 * 1024 * 1024 + || limits.maximum_control_bytes as u64 > limits.control.memory_bytes + || limits.maximum_output_bytes == 0 + || limits.maximum_log_bytes == 0 + || u32::try_from(limits.maximum_output_bytes).is_err() + || u32::try_from(limits.maximum_log_bytes).is_err() + || limits.timeout_ms == 0 + || limits.timeout_ms > 14_400_000 + || limits.cleanup_timeout_ms < limits.timeout_ms + || limits.cleanup_timeout_ms > 14_400_000 + || limits.overlay_bytes == 0 + || limits.filesystem_overhead_bytes == 0 + { + return Err("PRE bootstrap bounds invalid".into()); + } + Ok(()) + } +} diff --git a/external_checkers/workstream-checker-sdk/src/lib.rs b/external_checkers/workstream-checker-sdk/src/lib.rs index 93e2571bd..ea6f0c099 100644 --- a/external_checkers/workstream-checker-sdk/src/lib.rs +++ b/external_checkers/workstream-checker-sdk/src/lib.rs @@ -489,7 +489,12 @@ pub fn completed_result( Ok(value) } -fn validate_registry(registry: &Map, phase: &str) -> Result<(), ContractError> { +/// Validate the immutable selection without requiring source-derived input. +/// PRE admission uses this before the guest can produce that input. +pub fn validate_registry(registry: &Map, phase: &str) -> Result<(), ContractError> { + if !matches!(phase, "pre_submit" | "post_submit") || string(registry, "phase")? != phase { + return Err(ContractError("registry phase differs")); + } exact_map( registry, &[ diff --git a/external_checkers/workstream-checker-service/src/main.rs b/external_checkers/workstream-checker-service/src/main.rs index 44d03da0b..424319835 100644 --- a/external_checkers/workstream-checker-service/src/main.rs +++ b/external_checkers/workstream-checker-service/src/main.rs @@ -83,6 +83,8 @@ struct ServiceConfig { smol: Option, #[serde(default)] trusted_intake: Option, + #[serde(default)] + pre: Option, runtime: String, isolation_mode: String, operating_system: String, @@ -3166,6 +3168,7 @@ mod tests { let config = ServiceConfig { smol: None, trusted_intake: None, + pre: None, smol_admission: None, container_owner: Some( load_container_owner(&File::open(&socket_root).unwrap()).unwrap(), diff --git a/external_checkers/workstream-checker-service/src/smol.rs b/external_checkers/workstream-checker-service/src/smol.rs index 2082aa5ed..ae08a56f6 100644 --- a/external_checkers/workstream-checker-service/src/smol.rs +++ b/external_checkers/workstream-checker-service/src/smol.rs @@ -36,6 +36,7 @@ pub(super) use intake::{serve as serve_intake, IntakeConfig}; mod io; mod pre; pub(super) use io::{ProjectCallbacks, ProjectMaterials}; +pub(super) use pre::admission::Config as PreConfig; #[derive(Clone, Copy)] struct Resources { @@ -322,18 +323,45 @@ pub(super) fn validate(config: &ServiceConfig) -> Result<(), String> { Ok(()) } pub(super) fn inspect_image(image: &CacheEntry) -> Result<(), String> { + image_configuration(image).map(|_| ()) +} +fn image_configuration(image: &CacheEntry) -> Result { let source = image.smol.as_ref().ok_or("Smol image missing")?; - hash_file(&source.image_config, &image.config_image_id)?; - let value: Value = - serde_json::from_slice(&read_bounded_file(&source.image_config, MAX_REQUEST_BYTES)?) - .map_err(|_| "image configuration invalid")?; + if !source.image_config.is_absolute() || !valid_digest(&image.config_image_id) { + return Err("image configuration identity invalid".into()); + } + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK) + .open(&source.image_config) + .map_err(|_| "image configuration unavailable")?; + let metadata = file + .metadata() + .map_err(|_| "image configuration unavailable")?; + if !metadata.is_file() + || metadata.mode() & 0o022 != 0 + || metadata.len() > MAX_REQUEST_BYTES as u64 + { + return Err("image configuration custody invalid".into()); + } + let mut bytes = Vec::new(); + Read::by_ref(&mut file) + .take(MAX_REQUEST_BYTES as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| "image configuration unavailable")?; + if bytes.len() > MAX_REQUEST_BYTES + || format!("sha256:{:x}", Sha256::digest(&bytes)) != image.config_image_id + { + return Err("image configuration identity differs".into()); + } + let value: Value = serde_json::from_slice(&bytes).map_err(|_| "image configuration invalid")?; if value["os"].as_str() != Some(&image.operating_system) || value["architecture"].as_str() != Some(&image.architecture) { return Err("image platform differs".into()); } image_command(&value)?; - Ok(()) + Ok(value) } fn image_command(value: &Value) -> Result, String> { let mut command = Vec::new(); @@ -964,10 +992,7 @@ impl Machine { .map_err(|_| "material_unavailable")?, ); } - let source = cache.smol.as_ref().ok_or("Smol image missing")?; - let value: Value = - serde_json::from_slice(&read_bounded_file(&source.image_config, MAX_REQUEST_BYTES)?) - .map_err(|_| "image configuration invalid")?; + let value = image_configuration(cache)?; let environment = match value["config"]["Env"].as_array() { Some(items) => items .iter() diff --git a/external_checkers/workstream-checker-service/src/smol/pre.rs b/external_checkers/workstream-checker-service/src/smol/pre.rs index a68b8f91d..151c4c691 100644 --- a/external_checkers/workstream-checker-service/src/smol/pre.rs +++ b/external_checkers/workstream-checker-service/src/smol/pre.rs @@ -1,5 +1,6 @@ //! Host-owned PRE invocation and durable cleanup custody. use super::*; +pub(super) mod admission; #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/external_checkers/workstream-checker-service/src/smol/pre/admission.rs b/external_checkers/workstream-checker-service/src/smol/pre/admission.rs new file mode 100644 index 000000000..1555d0444 --- /dev/null +++ b/external_checkers/workstream-checker-service/src/smol/pre/admission.rs @@ -0,0 +1,526 @@ +//! Validate configured PRE identities and bounds before allocation or source IO. +use super::*; +use workstream_checker_guest::pre_bootstrap::{PreBootstrapJob, PreBootstrapLimits}; +use workstream_checker_guest::trusted_root::{RootDescriptor, RootLimits}; + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct Config { + pub profile: Value, + pub profile_sha256: String, + pub root_bundle: PathBuf, + pub root: RootDescriptor, + pub root_limits: RootLimits, + pub limits: PreBootstrapLimits, + pub smol_binary_sha256: String, + pub guest_sha256: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Header { + protocol_version: String, + operation: String, + reservation: Value, + request_digest: String, + lease_id: String, + lease_generation: u64, + lease_expires_at: String, +} + +pub(super) struct Prepared<'a> { + pub cache: &'a CacheEntry, + pub root_bundle: File, + pub job: PreBootstrapJob, + pub invocation: Invocation, + pub resources: Resources, + pub overlay_gib: u64, + pub deadline: Instant, +} + +fn text<'a>(value: &'a Value, key: &str) -> Result<&'a str, String> { + value[key].as_str().ok_or_else(|| "PRE text invalid".into()) +} +fn number(value: &Value, key: &str) -> Result { + value[key] + .as_u64() + .filter(|value| *value > 0) + .ok_or_else(|| "PRE bound invalid".into()) +} +fn closed(value: &Value, fields: &[&str]) -> Result<(), String> { + let object = value.as_object().ok_or("PRE object invalid")?; + if object.len() != fields.len() || fields.iter().any(|field| !object.contains_key(*field)) { + return Err("PRE object fields differ".into()); + } + Ok(()) +} +fn sum(values: impl IntoIterator) -> Result { + values.into_iter().try_fold(0_u64, |total, value| { + total + .checked_add(value) + .ok_or("PRE capacity overflow".into()) + }) +} +fn hash(value: &Value) -> Result { + canonical_hash(value).map_err(|_| "PRE identity invalid".into()) +} + +// Backend durable UTC timestamps are serialized with Z or +00:00. Reject +// normalization (February 30, leap seconds, excess precision), rather than let +// libc silently move an invalid timestamp into a later admission window. +fn utc_millis(value: &str) -> Result { + let body = value + .strip_suffix('Z') + .or_else(|| value.strip_suffix("+00:00")) + .ok_or("PRE timestamp must be UTC")?; + let bytes = body.as_bytes(); + if bytes.len() < 19 + || bytes[4] != b'-' + || bytes[7] != b'-' + || bytes[10] != b'T' + || bytes[13] != b':' + || bytes[16] != b':' + { + return Err("PRE timestamp invalid".into()); + } + let parse = |start: usize, end: usize| -> Result { + let part = &bytes[start..end]; + if !part.iter().all(u8::is_ascii_digit) { + return Err("PRE timestamp invalid".into()); + } + Ok(part + .iter() + .fold(0, |total, digit| total * 10 + i32::from(digit - b'0'))) + }; + let mut tm: libc::tm = unsafe { std::mem::zeroed() }; + tm.tm_year = parse(0, 4)? - 1900; + tm.tm_mon = parse(5, 7)? - 1; + tm.tm_mday = parse(8, 10)?; + tm.tm_hour = parse(11, 13)?; + tm.tm_min = parse(14, 16)?; + tm.tm_sec = parse(17, 19)?; + let original = ( + tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, + ); + let seconds = unsafe { libc::timegm(&mut tm) }; + if seconds < 0 + || original + != ( + tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, + ) + { + return Err("PRE timestamp invalid".into()); + } + let fraction = &bytes[19..]; + let millis = if fraction.is_empty() { + 0 + } else { + if fraction[0] != b'.' + || !(2..=7).contains(&fraction.len()) + || !fraction[1..].iter().all(u8::is_ascii_digit) + { + return Err("PRE timestamp invalid".into()); + } + fraction[1..] + .iter() + .take(3) + .chain(std::iter::repeat(&b'0')) + .take(3) + .fold(0_u64, |total, digit| total * 10 + u64::from(digit - b'0')) + }; + (seconds as u64) + .checked_mul(1000) + .and_then(|value| value.checked_add(millis)) + .ok_or("PRE timestamp overflow".into()) +} + +pub(super) fn prepare<'a>(config: &'a ServiceConfig, bytes: &[u8]) -> Result, String> { + let started = Instant::now(); + let wall = now_ms()?; + if bytes.is_empty() || bytes.len() > 2 * 1024 * 1024 { + return Err("PRE header unbounded".into()); + } + let header: Header = serde_json::from_slice(bytes).map_err(|_| "PRE header invalid")?; + let configured = config.pre.as_ref().ok_or("PRE configuration unavailable")?; + configured.limits.validate()?; + let runtime = settings(config)?; + let reservation = &header.reservation; + closed( + reservation, + &[ + "schema_version", + "actor_profile_id", + "identity_link_id", + "project_id", + "task_id", + "assignment_id", + "attempt_id", + "idempotency_key", + "source", + "source_sha256", + "metadata_sha256", + "locked_context_sha256", + "foreground_lease_id", + "foreground_lease_generation", + "pre_deadline_at", + "policy", + "default_context", + "runtime_profile", + "admission_lineage", + ], + )?; + let profile = &reservation["runtime_profile"]; + closed( + profile, + &[ + "profile_id", + "platform_root_sha256", + "cpu_millis", + "memory_bytes", + "temporary_disk_bytes", + "maximum_processes", + "maximum_output_bytes", + "maximum_log_bytes", + "aggregate_deadline_ms", + "archive_limits", + ], + )?; + let archive_limits = &profile["archive_limits"]; + closed( + archive_limits, + &[ + "maximum_central_directory_bytes", + "maximum_compression_ratio", + "maximum_entries", + "maximum_entry_bytes", + "maximum_expanded_bytes", + "maximum_inspection_seconds", + "maximum_path_bytes", + "maximum_path_depth", + ], + )?; + for field in [ + "maximum_central_directory_bytes", + "maximum_compression_ratio", + "maximum_entries", + "maximum_entry_bytes", + "maximum_expanded_bytes", + "maximum_path_bytes", + "maximum_path_depth", + ] { + number(archive_limits, field)?; + } + let inspection = archive_limits["maximum_inspection_seconds"] + .as_f64() + .ok_or("PRE inspection bound invalid")?; + let profile_id = text(profile, "profile_id")?; + if !inspection.is_finite() + || inspection <= 0.0 + || profile_id.is_empty() + || profile_id.len() > 100 + || !profile_id.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-') + }) + { + return Err("PRE profile invalid".into()); + } + let source = &reservation["source"]; + closed( + source, + &[ + "location", + "media_type", + "provider_generation", + "raw_byte_count", + "raw_sha256", + "sealed_upload_fence", + ], + )?; + closed( + &source["location"], + &[ + "namespace_fingerprint", + "namespace_id", + "operation_id", + "provider_profile", + ], + )?; + let mut source_body = source.as_object().unwrap().clone(); + source_body.insert( + "schema_version".into(), + serde_json::json!("workstream.sealed_submission_source.v1"), + ); + let profile_digest = hash(profile)?; + if header.protocol_version != "external_checker_service.v1" + || header.operation != "execute_pre" + || reservation["schema_version"] != "workstream.selected_pre_submit_reservation.v2" + || hash(reservation)? != header.request_digest + || hash(&Value::Object(source_body))? != text(reservation, "source_sha256")? + || profile != &configured.profile + || profile_digest != configured.profile_sha256 + || config.runtime != "smolvm" + || config.isolation_mode != "smol-microvm" + || configured.smol_binary_sha256 != runtime.binary_sha256 + || configured.guest_sha256 != runtime.guest_sha256 + || !valid_digest(&configured.smol_binary_sha256) + || !valid_digest(&configured.guest_sha256) + || profile["platform_root_sha256"] != configured.root.bundle_sha256 + || source["media_type"] != "application/zip" + || !valid_digest(text(source, "raw_sha256")?) + || text(source, "provider_generation")?.is_empty() + || number(reservation, "foreground_lease_generation")? + < number(source, "sealed_upload_fence")? + || number(source, "raw_byte_count")? > configured.limits.maximum_source_bytes + { + return Err("PRE configured identity differs".into()); + } + let remaining = utc_millis(&header.lease_expires_at)? + .min(utc_millis(text(reservation, "pre_deadline_at")?)?) + .checked_sub(wall) + .filter(|value| *value > 0) + .ok_or("deadline_exceeded")?; + let budget = number(profile, "aggregate_deadline_ms")?; + if !(100..=14_400_000).contains(&budget) || configured.limits.cleanup_timeout_ms > budget { + return Err("PRE deadline bound differs".into()); + } + let deadline = started + Duration::from_millis(remaining.min(budget)); + let policy = &reservation["policy"]; + closed( + policy, + &[ + "schema_version", + "workstream_default", + "entries", + "policy_sha256", + ], + )?; + let mut policy_body = policy.as_object().unwrap().clone(); + policy_body.remove("policy_sha256"); + if policy["schema_version"] != "external_pre_submit_policy.v1" + || hash(&Value::Object(policy_body))? != text(policy, "policy_sha256")? + { + return Err("PRE policy digest differs".into()); + } + let entries = reservation["policy"]["entries"] + .as_array() + .ok_or("PRE policy invalid")?; + if entries.len() != 1 { + return Err("PRE cardinality invalid".into()); + } + let selected = &entries[0]; + closed( + selected, + &[ + "stage", + "requirement_id", + "configuration", + "configuration_sha256", + "registry", + ], + )?; + let registry = &selected["registry"]; + workstream_checker_sdk::validate_registry( + registry.as_object().ok_or("PRE registry invalid")?, + "pre_submit", + ) + .map_err(|_| "PRE registry invalid")?; + if selected["stage"] != "pre_submit" + || registry["phase"] != "pre_submit" + || hash(&selected["configuration"])? != text(selected, "configuration_sha256")? + || reservation["policy"]["workstream_default"]["behavior_sha256"] + != configured.root.default_behavior_sha256 + { + return Err("PRE selection differs".into()); + } + let matching: Vec<_> = config + .cache + .iter() + .filter(|entry| { + Some(entry.platform_manifest_digest.as_str()) == registry["image_digest"].as_str() + }) + .collect(); + if matching.len() != 1 { + return Err("PRE image unavailable or ambiguous".into()); + } + let cache = matching[0]; + if cache.operating_system != config.operating_system + || cache.architecture != config.architecture + { + return Err("PRE image platform differs".into()); + } + let image = image_configuration(cache)?; + let limits = configured.limits; + for (field, actual) in [ + ( + "cpu_millis", + sum([ + limits.control.cpu_millis, + limits.worker.cpu_millis, + limits.project.cpu_millis, + ])?, + ), + ( + "memory_bytes", + sum([ + limits.control.memory_bytes, + limits.worker.memory_bytes, + limits.project.memory_bytes, + ])?, + ), + ( + "maximum_processes", + sum([ + limits.control.processes, + limits.worker.processes, + limits.project.processes, + ])?, + ), + ("maximum_output_bytes", limits.maximum_output_bytes as u64), + ("maximum_log_bytes", limits.maximum_log_bytes as u64), + ] { + if actual > number(profile, field)? { + return Err("PRE partitions exceed profile".into()); + } + } + if configured.root.schema_version != "workstream.trusted_root.v1" + || [ + &configured.root.bundle_sha256, + &configured.root.platform_manifest_digest, + &configured.root.config_image_id, + &configured.root.default_behavior_sha256, + ] + .into_iter() + .any(|value| !valid_digest(value)) + || number(profile, "cpu_millis")?.checked_mul(100).is_none() + || !configured.root_bundle.is_absolute() + || configured.root.bundle_byte_count == 0 + || configured.root.bundle_byte_count > configured.root_limits.maximum_bundle_bytes + || configured.root.expanded_bytes == 0 + || configured.root.expanded_bytes > configured.root_limits.maximum_root_bytes + || configured.root.entries == 0 + || configured.root.entries > configured.root_limits.maximum_entries + { + return Err("PRE root bound differs".into()); + } + let root_bundle = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK) + .open(&configured.root_bundle) + .map_err(|_| "PRE root unavailable")?; + let root_metadata = root_bundle.metadata().map_err(|_| "PRE root unavailable")?; + if !root_metadata.is_file() + || root_metadata.mode() & 0o022 != 0 + || root_metadata.len() != configured.root.bundle_byte_count + { + return Err("PRE root custody differs".into()); + } + let storage = sum([ + configured.root.bundle_byte_count, + configured.root.expanded_bytes, + number(source, "raw_byte_count")?, + number(&profile["archive_limits"], "maximum_expanded_bytes")?, + limits.worker_scratch_bytes, + limits.project_scratch_bytes, + limits.filesystem_overhead_bytes, + ])?; + if sum([storage, limits.overlay_bytes])? > number(profile, "temporary_disk_bytes")? { + return Err("PRE disk exceeds profile".into()); + } + let gib = |bytes: u64| { + bytes + .checked_add((1 << 30) - 1) + .map(|n| n / (1 << 30)) + .ok_or("PRE capacity overflow") + }; + let resources = Resources { + cpu_millis: number(profile, "cpu_millis")?, + memory_bytes: number(profile, "memory_bytes")?, + pids: number(profile, "maximum_processes")?, + storage_gib: gib(storage)?, + }; + let overlay_gib = gib(limits.overlay_bytes)?; + resource_capacity(resources, Some(overlay_gib))?; + let invocation = Invocation { + operation: Operation::ExecutePre, + run_id: text(reservation, "attempt_id")?.into(), + source_operation_id: text(&source["location"], "operation_id")?.into(), + request_digest: header.request_digest, + source_sha256: text(reservation, "source_sha256")?.into(), + profile_sha256: profile_digest, + image_digest: cache.platform_manifest_digest.clone(), + config_image_id: cache.config_image_id.clone(), + lease_id: header.lease_id, + lease_generation: header.lease_generation, + }; + if !invocation.valid() { + return Err("PRE invocation invalid".into()); + } + let environment = match &image["config"]["Env"] { + Value::Null => Vec::new(), + Value::Array(items) => items + .iter() + .map(|value| { + value + .as_str() + .map(str::to_owned) + .ok_or("PRE image environment invalid") + }) + .collect::, _>>()?, + _ => return Err("PRE image environment invalid".into()), + }; + if config.sandbox_uid == 0 + || config.sandbox_gid == 0 + || config.sandbox_uid == limits.worker_uid + || config.sandbox_gid == limits.worker_gid + { + return Err("PRE workload identities overlap".into()); + } + let startup = serde_json::json!({"operation":"execute_pre", "request":serde_json::from_slice::(bytes).map_err(|_| "PRE header invalid")?, + "isolation": {"runtime":config.runtime,"isolation_mode":config.isolation_mode,"operating_system":config.operating_system, + "architecture":config.architecture,"sandbox_uid":config.sandbox_uid,"sandbox_gid":config.sandbox_gid, + "repository":cache.repository,"platform_manifest_digest":cache.platform_manifest_digest, + "platform_manifest_media_type":cache.platform_manifest_media_type,"platform_manifest_byte_count":cache.platform_manifest_byte_count,"config_image_id":cache.config_image_id}}); + let job = PreBootstrapJob { + limits, + root: configured.root.clone(), + root_limits: configured.root_limits.clone(), + startup, + selected: GuestJob { + purpose: GuestPurpose::Project { + capabilities: GuestCapabilities { + model: false, + execution: false, + }, + materials: Vec::new(), + }, + request: Value::Null, + command: image_command(&image)?, + environment, + working_directory: image["config"]["WorkingDir"].as_str().unwrap_or("/").into(), + uid: config.sandbox_uid, + gid: config.sandbox_gid, + directories: Vec::new(), + files: Vec::new(), + }, + }; + if serde_json::to_vec(&job) + .map_err(|_| "PRE job invalid")? + .len() + > MAX_JOB_BYTES + || Instant::now() >= deadline + { + return Err("PRE admission deadline or size exceeded".into()); + } + Ok(Prepared { + cache, + root_bundle, + job, + invocation, + resources, + overlay_gib, + deadline, + }) +} + +#[cfg(test)] +mod tests; diff --git a/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs new file mode 100644 index 000000000..a4248f657 --- /dev/null +++ b/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs @@ -0,0 +1,272 @@ +use super::*; +use serde_json::json; +use workstream_checker_guest::pre_bootstrap::PrePartition; + +fn fixture() -> (PathBuf, ServiceConfig, Value) { + let (root, mut config, _, _) = super::super::tests::fixture(); + let mut header: Value = + serde_json::from_str::(include_str!("../../../../../fixtures/pre_startup.json")) + .unwrap()["request"] + .clone(); + header["lease_expires_at"] = json!("2099-01-01T00:00:00Z"); + header["reservation"]["pre_deadline_at"] = json!("2099-01-01T00:00:00+00:00"); + header["request_digest"] = json!(hash(&header["reservation"]).unwrap()); + config.runtime = "smolvm".into(); + config.isolation_mode = "smol-microvm".into(); + config.sandbox_uid = 23456; + config.sandbox_gid = 23456; + let image = root.join("image.json"); + let bytes = serde_json::to_vec( + &json!({"os":"linux","architecture":"amd64","config":{"Cmd":["/checker"]}}), + ) + .unwrap(); + fs::write(&image, &bytes).unwrap(); + fs::set_permissions(&image, fs::Permissions::from_mode(0o644)).unwrap(); + config.cache[0].platform_manifest_digest = header["reservation"]["policy"]["entries"][0] + ["registry"]["image_digest"] + .as_str() + .unwrap() + .into(); + config.cache[0].config_image_id = format!("sha256:{:x}", Sha256::digest(bytes)); + config.cache[0].smol = Some(SmolImage { + archive: root.join("image.tar"), + archive_sha256: format!("sha256:{}", "d".repeat(64)), + image_config: image, + }); + let profile = header["reservation"]["runtime_profile"].clone(); + config.pre = Some(Config { + profile_sha256: hash(&profile).unwrap(), + profile, + root_bundle: root.join("root.bundle"), + root: RootDescriptor { + schema_version: "workstream.trusted_root.v1".into(), + platform_manifest_digest: format!("sha256:{}", "e".repeat(64)), + config_image_id: format!("sha256:{}", "f".repeat(64)), + default_behavior_sha256: header["reservation"]["policy"]["workstream_default"] + ["behavior_sha256"] + .as_str() + .unwrap() + .into(), + expanded_bytes: 1024, + entries: 3, + bundle_sha256: format!("sha256:{}", "a".repeat(64)), + bundle_byte_count: 1024, + }, + root_limits: RootLimits { + maximum_bundle_bytes: 2048, + maximum_root_bytes: 2048, + maximum_entries: 10, + }, + smol_binary_sha256: config.smol.as_ref().unwrap().binary_sha256.clone(), + guest_sha256: config.smol.as_ref().unwrap().guest_sha256.clone(), + limits: PreBootstrapLimits { + control: PrePartition { + cpu_millis: 100, + memory_bytes: 64 * 1024 * 1024, + processes: 3, + }, + worker: PrePartition { + cpu_millis: 400, + memory_bytes: 512 * 1024 * 1024, + processes: 8, + }, + project: PrePartition { + cpu_millis: 1500, + memory_bytes: 256 * 1024 * 1024, + processes: 8, + }, + worker_uid: 12345, + worker_gid: 12345, + worker_scratch_bytes: 4 * 1024 * 1024, + project_scratch_bytes: 4 * 1024 * 1024, + maximum_source_bytes: 1024 * 1024, + maximum_control_bytes: 2 * 1024 * 1024, + maximum_output_bytes: 1024 * 1024, + maximum_log_bytes: 1024 * 1024, + timeout_ms: 1000, + cleanup_timeout_ms: 2000, + overlay_bytes: 1024 * 1024, + filesystem_overhead_bytes: 1024 * 1024, + }, + }); + fs::write(root.join("root.bundle"), vec![0_u8; 1024]).unwrap(); + fs::set_permissions(root.join("root.bundle"), fs::Permissions::from_mode(0o644)).unwrap(); + (root, config, header) +} + +#[test] +fn pre_admission_binds_actual_run_and_charges_rounded_storage_and_overlay() { + let (root, config, header) = fixture(); + let prepared = prepare(&config, &serde_json::to_vec(&header).unwrap()).unwrap(); + assert_eq!( + prepared.invocation.run_id, + header["reservation"]["attempt_id"] + ); + assert_eq!( + prepared.invocation.source_operation_id, + header["reservation"]["source"]["location"]["operation_id"] + ); + assert_eq!(prepared.resources.storage_gib, 1); + assert_eq!(prepared.overlay_gib, 1); + assert_eq!( + resource_capacity(prepared.resources, Some(prepared.overlay_gib)) + .unwrap() + .storage_bytes, + 2 * 1024 * 1024 * 1024 + ); + assert_eq!( + prepared.cache.config_image_id, + prepared.invocation.config_image_id + ); + assert!(prepared.job.selected.request.is_null()); + assert!(prepared.deadline > Instant::now()); + assert_eq!(prepared.root_bundle.metadata().unwrap().len(), 1024); + // No runtime binary or image archive exists, and admission creates no lease. + assert!(!config + .socket_path + .parent() + .unwrap() + .join("smol-leases") + .exists()); + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn pre_admission_refuses_rebound_pins_fences_and_bounds_before_allocation() { + for attack in [ + "request", + "source", + "profile", + "image", + "binary", + "guest", + "root", + "default", + "count", + "fence", + "expired", + "unknown", + "partition", + "overflow", + "disk", + "uid", + "duplicate_image", + "missing_root", + "root_size", + "root_symlink", + "root_mode", + ] { + let (root, mut config, mut header) = fixture(); + prepare(&config, &serde_json::to_vec(&header).unwrap()) + .expect("valid control before mutation"); + match attack { + "request" => header["request_digest"] = json!(format!("sha256:{}", "0".repeat(64))), + "source" => header["reservation"]["source"]["raw_byte_count"] = json!(2), + "profile" => header["reservation"]["runtime_profile"]["memory_bytes"] = json!(3), + "image" => { + header["reservation"]["policy"]["entries"][0]["registry"]["image_digest"] = + json!(format!("sha256:{}", "0".repeat(64))) + } + "binary" => { + config.pre.as_mut().unwrap().smol_binary_sha256 = + format!("sha256:{}", "0".repeat(64)) + } + "guest" => { + config.pre.as_mut().unwrap().guest_sha256 = format!("sha256:{}", "0".repeat(64)) + } + "root" => { + config.pre.as_mut().unwrap().root.bundle_sha256 = + format!("sha256:{}", "0".repeat(64)) + } + "default" => { + config.pre.as_mut().unwrap().root.default_behavior_sha256 = + format!("sha256:{}", "0".repeat(64)) + } + "count" => { + let entry = header["reservation"]["policy"]["entries"][0].clone(); + header["reservation"]["policy"]["entries"] + .as_array_mut() + .unwrap() + .push(entry); + } + "fence" => header["lease_generation"] = json!(0), + "expired" => header["lease_expires_at"] = json!("2000-01-01T00:00:00Z"), + "unknown" => header["extra"] = json!(true), + "partition" => config.pre.as_mut().unwrap().limits.control.memory_bytes = u64::MAX, + "overflow" => config.pre.as_mut().unwrap().limits.worker_scratch_bytes = u64::MAX, + "disk" => { + config.pre.as_mut().unwrap().limits.worker_scratch_bytes = 4 * 1024 * 1024 * 1024 + } + "uid" => config.sandbox_uid = config.pre.as_ref().unwrap().limits.worker_uid, + "duplicate_image" => config.cache.push(config.cache[0].clone()), + "missing_root" => fs::remove_file(root.join("root.bundle")).unwrap(), + "root_size" => fs::write(root.join("root.bundle"), b"truncated").unwrap(), + "root_symlink" => { + fs::rename(root.join("root.bundle"), root.join("root.original")).unwrap(); + std::os::unix::fs::symlink(root.join("root.original"), root.join("root.bundle")) + .unwrap(); + } + "root_mode" => { + fs::set_permissions(root.join("root.bundle"), fs::Permissions::from_mode(0o666)) + .unwrap() + } + _ => unreachable!(), + } + for selected in header["reservation"]["policy"]["entries"] + .as_array_mut() + .unwrap() + { + let mut spec = selected["registry"].as_object().unwrap().clone(); + for key in [ + "registry_entry_id", + "entry_digest", + "registration_operation_id", + "registered_by_actor_profile_id", + "authorization_decision_event_id", + "created_at", + ] { + spec.remove(key); + } + selected["registry"]["entry_digest"] = json!(hash(&Value::Object(spec)).unwrap()); + } + let mut policy = header["reservation"]["policy"].as_object().unwrap().clone(); + policy.remove("policy_sha256"); + header["reservation"]["policy"]["policy_sha256"] = + json!(hash(&Value::Object(policy)).unwrap()); + if attack != "request" { + header["request_digest"] = json!(hash(&header["reservation"]).unwrap()); + } + assert!( + prepare(&config, &serde_json::to_vec(&header).unwrap()).is_err(), + "accepted {attack}" + ); + assert!(!config + .socket_path + .parent() + .unwrap() + .join("smol-leases") + .exists()); + fs::remove_dir_all(root).unwrap(); + } +} + +#[test] +fn utc_deadlines_refuse_normalization_and_floor_submillisecond_expiry() { + assert_eq!(utc_millis("2024-02-29T00:00:00Z").unwrap(), 1709164800000); + assert_eq!( + utc_millis("2024-02-29T00:00:00.123999+00:00").unwrap(), + 1709164800123 + ); + for invalid in [ + "2023-02-29T00:00:00Z", + "2024-13-01T00:00:00Z", + "2024-01-01T24:00:00Z", + "2024-01-01T00:00:60Z", + "2024-01-01T00:00:00.1234567Z", + "2024-01-01T00:00:00+01:00", + "2024-01-01T00:00:00.Z", + "2024-01-01T00:00:00", + ] { + assert!(utc_millis(invalid).is_err(), "accepted {invalid}"); + } +} diff --git a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs index eb54fafb2..bbb6d8eea 100644 --- a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs +++ b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs @@ -15,7 +15,7 @@ fn invocation() -> Invocation { } } -fn fixture() -> (PathBuf, ServiceConfig, Lease, Journal) { +pub(super) fn fixture() -> (PathBuf, ServiceConfig, Lease, Journal) { let (root, mut config) = super::super::super::tests::test_config(); let leases = root.join("leases"); fs::create_dir(&leases).unwrap(); diff --git a/external_checkers/workstream-checker-service/src/smol/tests.rs b/external_checkers/workstream-checker-service/src/smol/tests.rs index a75b4a87c..8ed7b0913 100644 --- a/external_checkers/workstream-checker-service/src/smol/tests.rs +++ b/external_checkers/workstream-checker-service/src/smol/tests.rs @@ -234,6 +234,31 @@ fn cached_image_config_must_match_its_pinned_digest_and_platform() { fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); fs::write(&path, b"{}").unwrap(); assert!(inspect_image(cache).is_err()); + fs::write(&path, raw).unwrap(); + assert_eq!( + image_configuration(cache).unwrap()["config"]["Cmd"], + serde_json::json!(["--json"]) + ); + OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(MAX_REQUEST_BYTES as u64 + 1) + .unwrap(); + assert_eq!( + inspect_image(cache).unwrap_err(), + "image configuration custody invalid" + ); + fs::write(&path, raw).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o666)).unwrap(); + assert_eq!( + inspect_image(cache).unwrap_err(), + "image configuration custody invalid" + ); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + fs::rename(&path, root.join("retained-image")).unwrap(); + std::os::unix::fs::symlink(root.join("retained-image"), &path).unwrap(); + assert!(inspect_image(cache).is_err()); fs::remove_dir_all(root).unwrap(); } From 95949369f82de5e8ce77ae206c564b99e5d261d9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 16:06:49 +0100 Subject: [PATCH 094/513] Prove PRE source count cap with consistent boundary identities --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 +++++++++ .../src/smol/pre/admission/tests.rs | 33 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 5ad04eb1b..a1bde9571 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -2114,3 +2114,19 @@ permissions and require passing controls. Formatting, diff, record and link checks pass. Host dispatch still does not call admission or stream the source; these checks do not establish provider qualification, authorization independent of the trusted caller, or a complete execution response. + +Architecture/security review passed clean `2f8eb812b` for admission and the shared +image reader. The broader service binary run passes 121 tests and retains the +same five obsolete prepared-PRE fixture failures as the earlier source-cutover +baseline; the full service suite is not green. The host's returned absolute +deadline must govern reservation, journal/create, streaming and reads. At actual +guest launch, the caller must shorten guest run/cleanup ceilings to the remaining +budget (and retain guardian lifetime enforcement); configured phase ceilings do +not independently establish the current lease's remaining lifetime. + +QA identified that the original source mutation proved stale-digest refusal, +not the configured source-count cap. A separate boundary test now recomputes +source and request digests: the exact configured maximum passes, one byte above +it fails, and neither allocates a lease. All 46 selected Smol tests pass after +this test-only repair. Guest/SDK implementation is unchanged from the 52/eight +passing run. No production guard or test expectation was weakened. diff --git a/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs index a4248f657..0eba4cd24 100644 --- a/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs +++ b/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs @@ -250,6 +250,39 @@ fn pre_admission_refuses_rebound_pins_fences_and_bounds_before_allocation() { } } +#[test] +fn source_cap_rejects_self_consistent_bytes_above_the_configured_maximum() { + let (root, config, mut header) = fixture(); + let maximum = config.pre.as_ref().unwrap().limits.maximum_source_bytes; + for (count, accepted) in [(maximum, true), (maximum + 1, false)] { + header["reservation"]["source"]["raw_byte_count"] = json!(count); + let mut source = header["reservation"]["source"].as_object().unwrap().clone(); + source.insert( + "schema_version".into(), + json!("workstream.sealed_submission_source.v1"), + ); + header["reservation"]["source_sha256"] = json!(hash(&Value::Object(source)).unwrap()); + header["request_digest"] = json!(hash(&header["reservation"]).unwrap()); + let result = prepare(&config, &serde_json::to_vec(&header).unwrap()); + if accepted { + let prepared = result.expect("the exact configured source maximum is admitted"); + assert_eq!( + prepared.job.startup["request"]["reservation"]["source"]["raw_byte_count"], + count + ); + } else { + assert!(matches!(result, Err(ref error) if error == "PRE configured identity differs")); + } + assert!(!config + .socket_path + .parent() + .unwrap() + .join("smol-leases") + .exists()); + } + fs::remove_dir_all(root).unwrap(); +} + #[test] fn utc_deadlines_refuse_normalization_and_floor_submillisecond_expiry() { assert_eq!(utc_millis("2024-02-29T00:00:00Z").unwrap(), 1709164800000); From 842ee6f229d64e777d143c99984ea440796026f9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 16:07:41 +0100 Subject: [PATCH 095/513] Record reviewed PRE admission proof and outstanding dispatch boundary --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a1bde9571..1b1ee5a5d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -2130,3 +2130,9 @@ source and request digests: the exact configured maximum passes, one byte above it fails, and neither allocates a lease. All 46 selected Smol tests pass after this test-only repair. Guest/SDK implementation is unchanged from the 52/eight passing run. No production guard or test expectation was weakened. + +QA/test-delta replay passed clean `95949369f`: the self-consistent source-cap +boundary test closes the reported gap. Architecture/security's `2f8eb812b` +production review remains compatible because the replay changes only that test +and this record. This establishes the portable admission boundary, not a callable +host PRE service, native provider qualification or end-to-end acceptance. From d5a4a9ffb9dfa9bb2801e29120a1b79e374cbfc9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 12 Nov 2026 16:23:38 +0100 Subject: [PATCH 096/513] Wire one-session PRE host dispatch and bounded source streaming --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 45 ++++ external_checkers/README.md | 10 +- .../workstream-checker-service/src/main.rs | 29 ++- .../workstream-checker-service/src/smol.rs | 126 ++++++--- .../src/smol/pre.rs | 195 ++++++++++++++ .../src/smol/pre/admission.rs | 2 +- .../src/smol/pre/admission/tests.rs | 2 +- .../src/smol/pre/tests.rs | 32 +++ .../src/smol/pre/transport.rs | 218 ++++++++++++++++ .../src/smol/pre/transport/tests.rs | 246 ++++++++++++++++++ 10 files changed, 859 insertions(+), 46 deletions(-) create mode 100644 external_checkers/workstream-checker-service/src/smol/pre/transport.rs create mode 100644 external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 1b1ee5a5d..4b9c3e8c6 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -2136,3 +2136,48 @@ boundary test closes the reported gap. Architecture/security's `2f8eb812b` production review remains compatible because the replay changes only that test and this record. This establishes the portable admission boundary, not a callable host PRE service, native provider qualification or end-to-end acceptance. + +### Host PRE dispatch and bounded guest transport + +Continue the approved native plan through the existing service connection owner, +Smol guardian and guest bootstrap. Allowed files are Rust service dispatch, +existing bounded command collection/Smol preparation, PRE admission fixtures and +PRE transport/tests, plus this record. Create once, retain pre-create journal +custody, charge rounded resources, permit already queued ZIP chunks during +preparation, enforce the absolute deadline and clamp both guest timer ceilings +at actual launch. Deliver root bytes and framed source chunks with bounded +buffers and simultaneous bounded stdout/stderr draining; never spool source or +export a tree on the host. Require exact counts/hashes, source terminator, +successful guest exit and one bound terminal frame. Preserve POST/trial's +existing refusal of unexpected queued bytes through the default connection +predicate. Prompt cleanup yields destroyed or independently retained pending +custody with quarantine; uncertain cleanup must never release an admitting node. + +This L1 architecture/security change requires those review tracks plus +QA/test-delta. Portable socket/process tests must discriminate buffered input +from disconnect, source truncation/overflow/hash/trailing data, root mutation, +output/log bounds and deadlines, and observe child reaping. Native creation, +privileged guest isolation and real provider qualification remain separate. +The host emits a versioned invocation envelope carrying worker facts, runtime +pins, stage timing and cleanup ownership. The existing Python adapter still +expects bare worker facts: it must be changed with CHECKERS durable evidence +retention before the cutover can accept this response. Qualification/conformance +receipt validation and complete cross-provider outcome contracts also remain +required; do not label this interim envelope fully qualified or merge-ready. + +Portable verification passes 51 selected Smol tests and 42 trial integration +checks. Full service binary verification passes 127 and retains the same five +obsolete prepared-PRE fixture failures; it is not a green end-to-end suite. +Real socket/process probes transfer a 128 KiB-plus source in multiple chunks and +verify received root/source hashes. Adverse cases cover changed/truncated root, +changed/short/excess source, oversized chunks, partial frames, disconnect, +stalled child, logs/output bounds, trailing/empty output and nonzero exit; owned +processes are reaped. A Python executable standing in for the runtime verifies +that host launch argv and the actual job carry identical lease-shortened limits, +that a second launch is refused, and that the first process is reaped. Its +cgroup.procs stand-in is an ordinary private file: no native cgroup or VM proof +is claimed. Worker/payload fence/source/policy probes test host binding only; +typed QC semantics remain CHECKERS' responsibility. Shared POST/trial retains +its original connection predicate. Formatting, diff, record and link checks +pass. The checker README is also updated to distinguish the now-wired host +caller from still-required backend receipt retention and native qualification. diff --git a/external_checkers/README.md b/external_checkers/README.md index 5fd54a4ca..15285ffa2 100644 --- a/external_checkers/README.md +++ b/external_checkers/README.md @@ -502,9 +502,13 @@ private parent without following its final symlink and anchors staging through that held directory descriptor. The caller must provide the private parent, aggregate deadline/cancellation checks, and capacity for both the spool and expanded root, then mount the root read-only before executing a -trusted child. The PRE guest bootstrap calls this verifier; host dispatch and -native isolation proof remain required. This library alone does not authorize -project execution. +trusted child. The PRE guest bootstrap calls this verifier. Host `execute_pre` +dispatch now admits an explicitly configured profile, creates one journaled +session and streams the root and ZIP into it with bounded buffers. Its invocation +response includes runtime pins, timing and cleanup custody. Python adapter and +CHECKERS retention of that envelope, the complete qualification/conformance +contract, and native isolation proof remain required before end-to-end use. +This library alone does not authorize project execution. Cleanup restores owned directory permissions after late staging failures; an underlying filesystem cleanup error is propagated and cannot establish released capacity. Relative and absolute symlink targets that traverse above the root are diff --git a/external_checkers/workstream-checker-service/src/main.rs b/external_checkers/workstream-checker-service/src/main.rs index 424319835..6bc6218b7 100644 --- a/external_checkers/workstream-checker-service/src/main.rs +++ b/external_checkers/workstream-checker-service/src/main.rs @@ -906,6 +906,15 @@ fn serve_connection( } let frame = read_frame_until(&mut stream, MAX_ENVELOPE_BYTES, Instant::now() + timeout); if let Ok(bytes) = &frame { + if serde_json::from_slice::(bytes) + .ok() + .is_some_and(|value| value["operation"] == "execute_pre") + { + return match smol::serve_pre(config, stream, bytes) { + Err(error) if error == UNSETTLED_RESOURCE_ERROR => Err(error), + _ => Ok(()), + }; + } if serde_json::from_slice::(bytes) .ok() .and_then(|v| v["protocol_version"].as_str().map(str::to_owned)) @@ -1326,11 +1335,29 @@ fn stop_command_group(child: &mut Child, deadline: Instant) -> Result, + cleanup: Option<&mut EmergencyCleanupBudget>, +) -> Result { + collect_bounded_command_with_connection( + child, + deadline, + maximum_output, + client, + cleanup, + client_is_connected, + ) +} + +fn collect_bounded_command_with_connection( mut child: Child, deadline: Instant, maximum_output: usize, client: Option<&UnixStream>, mut cleanup: Option<&mut EmergencyCleanupBudget>, + connected: fn(&UnixStream) -> bool, ) -> Result { let mut stdout = match child.stdout.take() { Some(stdout) => stdout, @@ -1353,7 +1380,7 @@ fn collect_bounded_command( let mut stdout_bytes = Vec::new(); let mut stderr_bytes = Vec::new(); loop { - if client.is_some_and(|stream| !client_is_connected(stream)) { + if client.is_some_and(|stream| !connected(stream)) { let _ = stop_command_group(&mut child, command_cleanup_deadline(&mut cleanup)); return Err("client disconnected".into()); } diff --git a/external_checkers/workstream-checker-service/src/smol.rs b/external_checkers/workstream-checker-service/src/smol.rs index ae08a56f6..6c5017dd9 100644 --- a/external_checkers/workstream-checker-service/src/smol.rs +++ b/external_checkers/workstream-checker-service/src/smol.rs @@ -37,6 +37,7 @@ mod io; mod pre; pub(super) use io::{ProjectCallbacks, ProjectMaterials}; pub(super) use pre::admission::Config as PreConfig; +pub(super) use pre::serve as serve_pre; #[derive(Clone, Copy)] struct Resources { @@ -468,13 +469,14 @@ fn collect( maximum: usize, client: Option<&UnixStream>, ) -> Result { - collect_bounded_command(child, deadline, maximum, client, None).map_err(|error| { - match error.as_str() { - "process deadline exceeded" => "deadline_exceeded".into(), - "process output unbounded" => "invalid_output".into(), - _ => "implementation_unavailable".into(), - } - }) + collect_bounded_command(child, deadline, maximum, client, None).map_err(command_failure) +} +fn command_failure(error: String) -> String { + match error.as_str() { + "process deadline exceeded" => "deadline_exceeded".into(), + "process output unbounded" => "invalid_output".into(), + _ => "implementation_unavailable".into(), + } } fn control( s: &SmolConfig, @@ -580,14 +582,27 @@ impl Lease { } Ok(false) } - fn verify_network_disabled(&self, deadline: Instant) -> Result<(), String> { - let output = control( - &self.runtime, - &["machine", "ls", "--json"], - None, + fn verify_network_disabled( + &self, + deadline: Instant, + client: &UnixStream, + connected: fn(&UnixStream) -> bool, + ) -> Result<(), String> { + if Instant::now() >= deadline { + return Err("deadline_exceeded".into()); + } + let child = command(&self.runtime, &["machine", "ls", "--json"], None)? + .spawn() + .map_err(|_| "runtime launch unavailable")?; + let output = collect_bounded_command_with_connection( + child, deadline, + CONTROL_OUTPUT, + Some(client), None, - )?; + connected, + ) + .map_err(command_failure)?; if !output.status.success() { return Err("runtime inventory unavailable".into()); } @@ -910,6 +925,24 @@ impl Machine { overlay_gib: Option, client: &UnixStream, deadline: Instant, + ) -> Result<(), String> { + self.prepare_with_connection( + cache, + resources, + overlay_gib, + client, + deadline, + client_is_connected, + ) + } + fn prepare_with_connection( + &self, + cache: &CacheEntry, + resources: Resources, + overlay_gib: Option, + client: &UnixStream, + deadline: Instant, + connected: fn(&UnixStream) -> bool, ) -> Result<(), String> { let lease = &self.lease; let s = &lease.runtime; @@ -941,30 +974,43 @@ impl Machine { if let Some(value) = overlay.as_deref() { args.extend(["--overlay", value]); } - checked(s, &args, Some(&group), deadline, Some(client))?; + let checked = |args: &[&str]| -> Result<(), String> { + if Instant::now() >= deadline { + return Err("deadline_exceeded".into()); + } + if !connected(client) { + return Err("implementation_unavailable".into()); + } + let child = command(s, args, Some(&group))? + .spawn() + .map_err(|_| "runtime launch unavailable")?; + let output = collect_bounded_command_with_connection( + child, + deadline, + CONTROL_OUTPUT, + Some(client), + None, + connected, + ) + .map_err(command_failure)?; + if output.status.success() { + Ok(()) + } else { + Err("runtime command failed".into()) + } + }; + checked(&args)?; // Closed argv omits network enablers; verify exact-owner state before start. - lease.verify_network_disabled(deadline)?; - checked( - s, - &["machine", "start", "--name", &lease.name, "--no-workload"], - Some(&group), - deadline, - Some(client), - )?; - checked( - s, - &[ - "machine", - "cp", - "--mode", - "0555", - s.guest_binary.to_str().ok_or("guest path invalid")?, - &format!("{}:/.workstream-guest", lease.name), - ], - Some(&group), - deadline, - Some(client), - ) + lease.verify_network_disabled(deadline, client, connected)?; + checked(&["machine", "start", "--name", &lease.name, "--no-workload"])?; + checked(&[ + "machine", + "cp", + "--mode", + "0555", + s.guest_binary.to_str().ok_or("guest path invalid")?, + &format!("{}:/.workstream-guest", lease.name), + ]) } fn run( &mut self, @@ -1070,12 +1116,12 @@ impl Machine { Ok(ExecutedChecker { value }) } fn close(&mut self) -> Result<(), String> { + self.close_until(Instant::now() + CLEANUP_TIMEOUT + SOCKET_IO_TIMEOUT) + } + fn close_until(&mut self, deadline: Instant) -> Result<(), String> { // EOF transfers cleanup to the guardian; wait for durable absence. drop(self.keeper.take()); - let status = reap_child( - &mut self.guardian, - Instant::now() + CLEANUP_TIMEOUT + SOCKET_IO_TIMEOUT, - )?; + let status = reap_child(&mut self.guardian, deadline)?; if status.success() && !self.lease.path().exists() && !self.lease.cgroup().exists() { Ok(()) } else { diff --git a/external_checkers/workstream-checker-service/src/smol/pre.rs b/external_checkers/workstream-checker-service/src/smol/pre.rs index 151c4c691..177c5181f 100644 --- a/external_checkers/workstream-checker-service/src/smol/pre.rs +++ b/external_checkers/workstream-checker-service/src/smol/pre.rs @@ -1,6 +1,151 @@ //! Host-owned PRE invocation and durable cleanup custody. use super::*; pub(super) mod admission; +mod transport; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct WorkerResult { + protocol_version: String, + operation: String, + request_digest: String, + lease_id: String, + lease_generation: u64, + payload: Value, +} + +fn completed(bytes: &[u8], prepared: &admission::Prepared<'_>) -> Result { + let result: WorkerResult = serde_json::from_slice(bytes).map_err(|_| "PRE result invalid")?; + let invocation = &prepared.invocation; + let expected = &prepared.job.startup["request"]["reservation"]; + if result.protocol_version != "workstream.pre_submit_worker.v1" + || result.operation != "completed" + || result.request_digest != invocation.request_digest + || result.lease_id != invocation.lease_id + || result.lease_generation != invocation.lease_generation + || result.payload["schema_version"] != "workstream.selected_pre_submit_execution.v2" + || result.payload["request_digest"] != invocation.request_digest + || result.payload["lease_id"] != invocation.lease_id + || result.payload["lease_generation"] != invocation.lease_generation + || result.payload["observed_source"] != expected["source"] + || result.payload["policy_sha256"] != expected["policy"]["policy_sha256"] + { + return Err("PRE result binding differs".into()); + } + Ok(result.payload) +} + +pub(crate) fn serve( + config: &ServiceConfig, + mut client: UnixStream, + bytes: &[u8], +) -> Result<(), String> { + let started = Instant::now(); + let mut prepared = admission::prepare(config, bytes)?; + let deadline = prepared.deadline; + let _reservation = reserve_capacity( + config, + resource_capacity(prepared.resources, Some(prepared.overlay_gib))?, + None, + )?; + if !transport::connected(&client) || Instant::now() >= deadline { + return Err("PRE cancelled or expired".into()); + } + let admission_ms = started.elapsed().as_millis() as u64; + let preparing = Instant::now(); + let mut machine = match Machine::create_pre( + config, + prepared.resources, + deadline, + prepared.invocation.clone(), + ) { + Ok(machine) => machine, + Err(error) => { + if error.cleanup_unsettled { + quarantine(config); + return Err(UNSETTLED_RESOURCE_ERROR.into()); + } + return Err(error.code.into()); + } + }; + let creation = machine.prepare_with_connection( + prepared.cache, + prepared.resources, + Some(prepared.overlay_gib), + &client, + deadline, + transport::connected, + ); + let preparation_ms = preparing.elapsed().as_millis() as u64; + let running = Instant::now(); + let result = creation + .and_then(|()| machine.run_pre(&mut prepared, &mut client)) + .and_then(|bytes| completed(&bytes, &prepared)); + let execution_ms = running.elapsed().as_millis() as u64; + let cleaning = Instant::now(); + let cleanup_deadline = deadline + .min(Instant::now() + Duration::from_millis(prepared.job.limits.cleanup_timeout_ms)); + let destroyed = machine.close_until(cleanup_deadline).is_ok(); + let journal_sha256 = if destroyed { + machine.journal.sha256.clone() + } else { + machine + .pending_pre_cleanup(config) + .map_err(|_| UNSETTLED_RESOURCE_ERROR)? + }; + let cleanup_ms = cleaning.elapsed().as_millis() as u64; + let (outcome, reason, execution) = match result { + Ok(value) => ("completed", Value::Null, value), + Err(error) => { + let outcome = if error == "deadline_exceeded" { + "deadline_exceeded" + } else if error == "cancelled" { + "cancelled" + } else { + "infrastructure_failure" + }; + ( + outcome, + Value::String( + if outcome == "infrastructure_failure" { + "implementation_unavailable" + } else { + outcome + } + .into(), + ), + Value::Null, + ) + } + }; + // Host custody stays outside the worker payload. The backend must retain + // this invocation envelope along with the typed checker facts at T4. + let response = serde_json::json!({ + "schema_version":"workstream.pre_submit_invocation.v1", "operation":"execute_pre", "phase":"pre_submit", + "invocation":prepared.invocation,"provider_invocation_id":machine.lease.name, + "outcome":outcome,"reason":reason,"execution":execution, + "runtime":{"provider":"smolvm","version":VERSION,"binary_sha256":machine.lease.runtime.binary_sha256, + "guest_sha256":machine.lease.runtime.guest_sha256,"profile":prepared.job.startup["request"]["reservation"]["runtime_profile"]}, + "timings_ms":{"admission":admission_ms,"preparation":preparation_ms,"execution":execution_ms,"cleanup":cleanup_ms,"total":started.elapsed().as_millis() as u64}, + "cleanup":{"obligation_id":machine.lease.name,"journal_sha256":journal_sha256,"disposition":if destroyed {"destroyed"} else {"pending"}} + }); + let response = serde_json::to_vec(&response).map_err(|_| "PRE response invalid")?; + let sent = if response.len() <= 64 * 1024 * 1024 + && Instant::now() < deadline + && client_is_connected(&client) + { + write_frame_until(&mut client, &response, deadline) + } else { + Err("deadline_exceeded".into()) + }; + // A pending receipt may be delivered, but admission stays quarantined and + // the service exits so recovery reconciles the durable journal on restart. + if !destroyed { + Err(UNSETTLED_RESOURCE_ERROR.into()) + } else { + sent + } +} #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -117,6 +262,56 @@ fn custody(metadata: &fs::Metadata) -> bool { } impl Machine { + fn run_pre( + &mut self, + prepared: &mut admission::Prepared<'_>, + client: &mut UnixStream, + ) -> Result, String> { + if self.consumed { + return Err("execution already consumed".into()); + } + self.consumed = true; + let remaining = prepared + .deadline + .saturating_duration_since(Instant::now()) + .as_millis() as u64; + if remaining == 0 { + return Err("deadline_exceeded".into()); + } + prepared.job.limits.timeout_ms = prepared.job.limits.timeout_ms.min(remaining); + prepared.job.limits.cleanup_timeout_ms = + prepared.job.limits.cleanup_timeout_ms.min(remaining); + prepared.job.limits.validate()?; + let limits = + serde_json::to_string(&prepared.job.limits).map_err(|_| "PRE limits invalid")?; + let mut cmd = command( + &self.lease.runtime, + &[ + "machine", + "exec", + "--name", + &self.lease.name, + "--user", + "0:0", + "--interactive", + "--stream", + "--", + "/.workstream-guest", + workstream_checker_guest::pre_bootstrap::PRE_LIMITS_ARGUMENT, + &limits, + ], + Some(&self.lease.cgroup()), + )?; + cmd.stdin(Stdio::piped()); + let child = cmd.spawn().map_err(|_| "PRE guest launch failed")?; + transport::exchange( + child, + client, + &mut prepared.root_bundle, + &prepared.job, + prepared.deadline, + ) + } fn create_pre( config: &ServiceConfig, resources: Resources, diff --git a/external_checkers/workstream-checker-service/src/smol/pre/admission.rs b/external_checkers/workstream-checker-service/src/smol/pre/admission.rs index 1555d0444..af5c3c92b 100644 --- a/external_checkers/workstream-checker-service/src/smol/pre/admission.rs +++ b/external_checkers/workstream-checker-service/src/smol/pre/admission.rs @@ -523,4 +523,4 @@ pub(super) fn prepare<'a>(config: &'a ServiceConfig, bytes: &[u8]) -> Result
 (PathBuf, ServiceConfig, Value) {
+pub(crate) fn fixture() -> (PathBuf, ServiceConfig, Value) {
     let (root, mut config, _, _) = super::super::tests::fixture();
     let mut header: Value =
         serde_json::from_str::(include_str!("../../../../../fixtures/pre_startup.json"))
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
index bbb6d8eea..571d5f824 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
@@ -1,5 +1,37 @@
 use super::*;
 
+#[test]
+fn host_completion_requires_both_worker_and_payload_invocation_bindings() {
+    let (root, config, header) = admission::tests::fixture();
+    let prepared = admission::prepare(&config, &serde_json::to_vec(&header).unwrap()).unwrap();
+    let valid = serde_json::json!({"protocol_version":"workstream.pre_submit_worker.v1","operation":"completed",
+        "request_digest":prepared.invocation.request_digest,"lease_id":prepared.invocation.lease_id,"lease_generation":prepared.invocation.lease_generation,
+        "payload":{"schema_version":"workstream.selected_pre_submit_execution.v2","request_digest":prepared.invocation.request_digest,
+            "lease_id":prepared.invocation.lease_id,"lease_generation":prepared.invocation.lease_generation,
+            "observed_source":header["reservation"]["source"],"policy_sha256":header["reservation"]["policy"]["policy_sha256"]}});
+    // This is an identity-envelope probe, not a fabricated complete QC result.
+    assert!(completed(&serde_json::to_vec(&valid).unwrap(), &prepared).is_ok());
+    for pointer in [
+        "/operation",
+        "/request_digest",
+        "/lease_id",
+        "/lease_generation",
+        "/payload/request_digest",
+        "/payload/lease_id",
+        "/payload/lease_generation",
+        "/payload/observed_source/provider_generation",
+        "/payload/policy_sha256",
+    ] {
+        let mut changed = valid.clone();
+        *changed.pointer_mut(pointer).unwrap() = serde_json::json!("rebound");
+        assert!(
+            completed(&serde_json::to_vec(&changed).unwrap(), &prepared).is_err(),
+            "accepted {pointer}"
+        );
+    }
+    fs::remove_dir_all(root).unwrap();
+}
+
 fn invocation() -> Invocation {
     Invocation {
         operation: Operation::ExecutePre,
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/transport.rs b/external_checkers/workstream-checker-service/src/smol/pre/transport.rs
new file mode 100644
index 000000000..971a7326a
--- /dev/null
+++ b/external_checkers/workstream-checker-service/src/smol/pre/transport.rs
@@ -0,0 +1,218 @@
+//! Bounded PRE input delivery. Source bytes never become a host file or tree.
+use super::*;
+use std::process::{ChildStderr, ChildStdin, ChildStdout};
+use workstream_checker_guest::pre_bootstrap::PreBootstrapJob;
+
+pub(super) fn connected(stream: &UnixStream) -> bool {
+    let mut descriptor = libc::pollfd {
+        fd: stream.as_raw_fd(),
+        events: libc::POLLRDHUP,
+        revents: 0,
+    };
+    let result = unsafe { libc::poll(&mut descriptor, 1, 0) };
+    result >= 0
+        && descriptor.revents & (libc::POLLRDHUP | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL)
+            == 0
+}
+
+struct Session {
+    child: Child,
+    input: Option,
+    output: ChildStdout,
+    errors: ChildStderr,
+    stdout: Vec,
+    stderr: Vec,
+    output_eof: bool,
+    errors_eof: bool,
+    reaped: bool,
+    deadline: Instant,
+    maximum_control: usize,
+    maximum_log: usize,
+}
+impl Drop for Session {
+    fn drop(&mut self) {
+        drop(self.input.take());
+        if !self.reaped {
+            // This process group belongs to this invocation only. VM recovery
+            // remains the persisted guardian's responsibility if stop fails.
+            let _ = stop_command_group(&mut self.child, Instant::now() + CLEANUP_TIMEOUT);
+        }
+    }
+}
+impl Session {
+    fn new(mut child: Child, job: &PreBootstrapJob, deadline: Instant) -> Result {
+        let descriptors = (child.stdin.take(), child.stdout.take(), child.stderr.take());
+        let (Some(input), Some(output), Some(errors)) = descriptors else {
+            let _ = stop_command_group(&mut child, Instant::now() + CLEANUP_TIMEOUT);
+            return Err("PRE process descriptors unavailable".into());
+        };
+        let result = Self {
+            child,
+            input: Some(input),
+            output,
+            errors,
+            stdout: Vec::new(),
+            stderr: Vec::new(),
+            output_eof: false,
+            errors_eof: false,
+            reaped: false,
+            deadline,
+            maximum_control: job.limits.maximum_control_bytes.saturating_add(4),
+            maximum_log: job.limits.maximum_log_bytes,
+        };
+        job.limits.validate()?;
+        set_nonblocking(result.input.as_ref().unwrap())?;
+        set_nonblocking(&result.output)?;
+        set_nonblocking(&result.errors)?;
+        Ok(result)
+    }
+    fn check(&mut self, client: &UnixStream) -> Result<(), String> {
+        if Instant::now() >= self.deadline {
+            return Err("deadline_exceeded".into());
+        }
+        if !connected(client) {
+            return Err("cancelled".into());
+        }
+        self.output_eof = read_available(&mut self.output, &mut self.stdout, self.maximum_control)?;
+        self.errors_eof = read_available(&mut self.errors, &mut self.stderr, self.maximum_log)?;
+        Ok(())
+    }
+    fn write(&mut self, client: &UnixStream, mut bytes: &[u8]) -> Result<(), String> {
+        while !bytes.is_empty() {
+            self.check(client)?;
+            match self
+                .input
+                .as_mut()
+                .ok_or("PRE input closed")?
+                .write(&bytes[..bytes.len().min(65536)])
+            {
+                Ok(0) => return Err("PRE input closed".into()),
+                Ok(count) => bytes = &bytes[count..],
+                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+                    thread::sleep(Duration::from_millis(2))
+                }
+                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => (),
+                Err(_) => return Err("PRE input failed".into()),
+            }
+        }
+        Ok(())
+    }
+    fn receive(&mut self, client: &mut UnixStream, mut bytes: &mut [u8]) -> Result<(), String> {
+        while !bytes.is_empty() {
+            self.check(client)?;
+            match client.read(bytes) {
+                Ok(0) => return Err("cancelled".into()),
+                Ok(count) => bytes = &mut bytes[count..],
+                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+                    thread::sleep(Duration::from_millis(2))
+                }
+                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => (),
+                Err(_) => return Err("PRE source transport failed".into()),
+            }
+        }
+        Ok(())
+    }
+    fn finish(mut self, client: &UnixStream) -> Result, String> {
+        drop(self.input.take());
+        loop {
+            self.check(client)?;
+            if !client_is_connected(client) {
+                return Err("PRE source contains trailing bytes".into());
+            }
+            if self.output_eof && self.errors_eof {
+                let Some(status) = self
+                    .child
+                    .try_wait()
+                    .map_err(|_| "PRE process wait failed")?
+                else {
+                    thread::sleep(Duration::from_millis(2));
+                    continue;
+                };
+                self.reaped = true;
+                if !status.success() {
+                    return Err("PRE guest failed".into());
+                }
+                if self.stdout.len() < 4 {
+                    return Err("PRE result truncated".into());
+                }
+                let size = u32::from_be_bytes(self.stdout[..4].try_into().unwrap()) as usize;
+                if size == 0 || size.checked_add(4) != Some(self.stdout.len()) {
+                    return Err("PRE result frame differs".into());
+                }
+                return Ok(self.stdout.split_off(4));
+            }
+            thread::sleep(Duration::from_millis(2));
+        }
+    }
+}
+
+pub(super) fn exchange(
+    child: Child,
+    client: &mut UnixStream,
+    root: &mut File,
+    job: &PreBootstrapJob,
+    deadline: Instant,
+) -> Result, String> {
+    let mut session = Session::new(child, job, deadline)?;
+    let bytes = serde_json::to_vec(job).map_err(|_| "PRE job invalid")?;
+    if bytes.is_empty() || bytes.len() > MAX_JOB_BYTES {
+        return Err("PRE job unbounded".into());
+    }
+    session.write(client, &(bytes.len() as u32).to_be_bytes())?;
+    session.write(client, &bytes)?;
+    let mut buffer = [0_u8; 65536];
+    let mut remaining = job.root.bundle_byte_count;
+    let mut digest = Sha256::new();
+    while remaining > 0 {
+        session.check(client)?;
+        let size = remaining.min(buffer.len() as u64) as usize;
+        root.read_exact(&mut buffer[..size])
+            .map_err(|_| "PRE root truncated")?;
+        digest.update(&buffer[..size]);
+        session.write(client, &buffer[..size])?;
+        remaining -= size as u64;
+    }
+    if root
+        .read(&mut buffer[..1])
+        .map_err(|_| "PRE root unavailable")?
+        != 0
+        || format!("sha256:{:x}", digest.finalize()) != job.root.bundle_sha256
+    {
+        return Err("PRE root identity differs".into());
+    }
+    let source = &job.startup["request"]["reservation"]["source"];
+    let expected = source["raw_byte_count"]
+        .as_u64()
+        .ok_or("PRE source count invalid")?;
+    let expected_digest = source["raw_sha256"]
+        .as_str()
+        .ok_or("PRE source digest invalid")?;
+    let mut count = 0_u64;
+    let mut digest = Sha256::new();
+    loop {
+        let mut header = [0; 4];
+        session.receive(client, &mut header)?;
+        let size = u32::from_be_bytes(header) as usize;
+        if size == 0 {
+            break;
+        }
+        if size > buffer.len() {
+            return Err("PRE source chunk unbounded".into());
+        }
+        count = count
+            .checked_add(size as u64)
+            .filter(|count| *count <= expected)
+            .ok_or("PRE source count differs")?;
+        session.receive(client, &mut buffer[..size])?;
+        digest.update(&buffer[..size]);
+        session.write(client, &buffer[..size])?;
+    }
+    if count != expected || format!("sha256:{:x}", digest.finalize()) != expected_digest {
+        return Err("PRE source identity differs".into());
+    }
+    session.write(client, &[0; 4])?;
+    session.finish(client)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs
new file mode 100644
index 000000000..79d93785d
--- /dev/null
+++ b/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs
@@ -0,0 +1,246 @@
+use super::*;
+use serde_json::json;
+
+const GUEST: &str = r#"
+import hashlib,json,struct,sys,time,os
+mode=sys.argv[1]
+if mode=='stall':
+    time.sleep(30)
+    sys.exit(1)
+def read(n):
+    b=b''
+    while len(b)I',read(4))[0]))
+if '--pre-limits' in sys.argv: assert json.loads(sys.argv[-1])==job['limits']
+root=read(job['root']['bundle_byte_count'])
+source=read(job['startup']['request']['reservation']['source']['raw_byte_count'])
+assert read(4)==b'\0'*4
+assert sys.stdin.buffer.read(1)==b''
+if mode=='logs':
+    sys.stderr.buffer.write(b'x'*(job['limits']['maximum_log_bytes']+1));sys.stderr.buffer.flush()
+payload=json.dumps({'root':hashlib.sha256(root).hexdigest(),'source':hashlib.sha256(source).hexdigest(),'bytes':len(source),'pid':os.getpid(),'limits':job['limits']}).encode()
+if mode=='zero':payload=b''
+if mode=='output':payload=b'x'*(job['limits']['maximum_control_bytes']+1)
+sys.stdout.buffer.write(struct.pack('>I',len(payload))+payload)
+if mode=='trailing':sys.stdout.buffer.write(b'x')
+sys.stdout.buffer.flush()
+if mode=='failure':sys.exit(9)
+"#;
+
+fn child(mode: &str) -> Child {
+    Command::new("/usr/bin/python3")
+        .args(["-I", "-c", GUEST, mode])
+        .env_clear()
+        .stdin(Stdio::piped())
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped())
+        .process_group(0)
+        .spawn()
+        .unwrap()
+}
+
+fn run_case(attack: &str) -> Result {
+    let (root, mut config, mut header) = admission::tests::fixture();
+    let source = vec![b'z'; 128 * 1024 + 3];
+    header["reservation"]["source"]["raw_byte_count"] = json!(source.len());
+    header["reservation"]["source"]["raw_sha256"] =
+        json!(format!("sha256:{:x}", Sha256::digest(&source)));
+    let mut body = header["reservation"]["source"].as_object().unwrap().clone();
+    body.insert(
+        "schema_version".into(),
+        json!("workstream.sealed_submission_source.v1"),
+    );
+    header["reservation"]["source_sha256"] = json!(canonical_hash(&Value::Object(body)).unwrap());
+    let root_digest = format!("sha256:{:x}", Sha256::digest(vec![0_u8; 1024]));
+    let pre = config.pre.as_mut().unwrap();
+    pre.root.bundle_sha256 = root_digest.clone();
+    pre.profile["platform_root_sha256"] = json!(root_digest);
+    pre.profile_sha256 = canonical_hash(&pre.profile).unwrap();
+    header["reservation"]["runtime_profile"] = pre.profile.clone();
+    header["request_digest"] = json!(canonical_hash(&header["reservation"]).unwrap());
+    if attack == "launch" {
+        let program = format!("#!/usr/bin/python3\n{GUEST}");
+        let path = root.join("runtime");
+        fs::write(&path, &program).unwrap();
+        fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
+        let digest = format!("sha256:{:x}", Sha256::digest(program.as_bytes()));
+        config.smol.as_mut().unwrap().binary = path;
+        config.smol.as_mut().unwrap().binary_sha256 = digest.clone();
+        config.pre.as_mut().unwrap().smol_binary_sha256 = digest;
+    }
+    let mut prepared = admission::prepare(&config, &serde_json::to_vec(&header).unwrap()).unwrap();
+    if attack == "root_truncated" {
+        fs::write(root.join("root.bundle"), b"short").unwrap();
+    }
+    if attack == "root" {
+        fs::write(root.join("root.bundle"), vec![1_u8; 1024]).unwrap();
+    }
+    let (mut client, mut producer) = UnixStream::pair().unwrap();
+    client.set_nonblocking(true).unwrap();
+    let attack = attack.to_owned();
+    let producer_attack = attack.clone();
+    let producer_thread = thread::spawn(move || {
+        if producer_attack == "disconnect" {
+            return;
+        }
+        let _ = (|| -> std::io::Result<()> {
+            if producer_attack == "partial" {
+                producer.write_all(&[0, 0])?;
+            } else if producer_attack == "chunk" {
+                producer.write_all(&65537_u32.to_be_bytes())?;
+            } else {
+                let mut payload = source;
+                if producer_attack == "hash" {
+                    payload[0] = b'q';
+                }
+                if producer_attack == "excess" {
+                    payload.push(0);
+                }
+                if producer_attack == "count" {
+                    payload.pop();
+                }
+                for chunk in payload.chunks(65536) {
+                    producer.write_all(&(chunk.len() as u32).to_be_bytes())?;
+                    producer.write_all(chunk)?;
+                }
+                producer.write_all(&[0; 4])?;
+                if producer_attack == "source_trailing" {
+                    producer.write_all(b"x")?;
+                }
+            }
+            let _ = producer.read(&mut [0]);
+            Ok(())
+        })();
+    });
+    let result = if attack == "launch" {
+        // A regular file stands in for cgroup.procs; this proves host argv and
+        // byte transport only, never cgroup enforcement or native VM creation.
+        let path = root
+            .join("leases")
+            .join(format!("ws-{}.json", "0".repeat(32)));
+        let mut lease: Lease = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
+        lease.runtime = config.smol.as_ref().unwrap().clone();
+        lease.pre = Some(prepared.invocation.clone());
+        fs::create_dir_all(lease.cgroup()).unwrap();
+        fs::write(lease.cgroup().join("cgroup.procs"), b"").unwrap();
+        let bytes = serde_json::to_vec(&lease).unwrap();
+        fs::write(&path, &bytes).unwrap();
+        let file = File::open(&path).unwrap();
+        let journal = Journal::capture(&file, &bytes).unwrap();
+        let mut machine = Machine {
+            lease,
+            journal,
+            guardian: Command::new("/bin/true").spawn().unwrap(),
+            keeper: None,
+            consumed: false,
+        };
+        machine.guardian.wait().unwrap();
+        prepared.deadline = Instant::now() + Duration::from_millis(500);
+        let result = machine.run_pre(&mut prepared, &mut client);
+        assert!(machine.run_pre(&mut prepared, &mut client).is_err());
+        result
+    } else {
+        let child = child(&attack);
+        let pid = child.id();
+        let deadline = Instant::now() + Duration::from_secs(2);
+        let result = exchange(
+            child,
+            &mut client,
+            &mut prepared.root_bundle,
+            &prepared.job,
+            deadline,
+        );
+        assert_eq!(
+            unsafe { libc::kill(pid as i32, 0) },
+            -1,
+            "child was not reaped"
+        );
+        result
+    }
+    .and_then(|bytes| serde_json::from_slice(&bytes).map_err(|_| "test output invalid".into()));
+    drop(client);
+    producer_thread.join().unwrap();
+    fs::remove_dir_all(root).unwrap();
+    result
+}
+
+#[test]
+fn streams_exact_root_and_multiple_source_chunks_without_a_host_spool() {
+    let result = run_case("good").unwrap();
+    assert_eq!(result["bytes"], 128 * 1024 + 3);
+    assert_eq!(
+        result["source"],
+        format!("{:x}", Sha256::digest(vec![b'z'; 128 * 1024 + 3]))
+    );
+    assert_eq!(
+        result["root"],
+        format!("{:x}", Sha256::digest(vec![0_u8; 1024]))
+    );
+}
+
+#[test]
+fn host_launch_passes_identical_clamped_limits_to_argv_and_job() {
+    let result = run_case("launch").unwrap();
+    let run = result["limits"]["timeout_ms"].as_u64().unwrap();
+    let cleanup = result["limits"]["cleanup_timeout_ms"].as_u64().unwrap();
+    assert!(run > 0 && run <= 500);
+    assert!(cleanup >= run && cleanup <= 500);
+    assert_eq!(
+        unsafe { libc::kill(result["pid"].as_u64().unwrap() as i32, 0) },
+        -1
+    );
+}
+
+#[test]
+fn invalid_streams_fail_and_reap_the_owned_process() {
+    for attack in [
+        "root",
+        "root_truncated",
+        "excess",
+        "zero",
+        "hash",
+        "count",
+        "chunk",
+        "source_trailing",
+        "partial",
+        "disconnect",
+        "stall",
+        "logs",
+        "output",
+        "trailing",
+        "failure",
+    ] {
+        assert!(run_case(attack).is_err(), "accepted {attack}");
+    }
+}
+
+#[test]
+fn streaming_connection_allows_queued_bytes_but_detects_disconnect() {
+    let (client, mut peer) = UnixStream::pair().unwrap();
+    peer.write_all(b"queued ZIP frame").unwrap();
+    assert!(connected(&client));
+    assert!(!client_is_connected(&client));
+    let process = Command::new("/bin/true")
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped())
+        .process_group(0)
+        .spawn()
+        .unwrap();
+    assert!(collect_bounded_command_with_connection(
+        process,
+        Instant::now() + Duration::from_secs(1),
+        100,
+        Some(&client),
+        None,
+        connected
+    )
+    .unwrap()
+    .status
+    .success());
+    drop(peer);
+    assert!(!connected(&client));
+}

From 3ba1cdf649af7d1053d2dd567318cc54b8fa8502 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 16:29:31 +0100
Subject: [PATCH 097/513] Discard PRE logs within bounded cancellable drain
 passes

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 13 ++++
 .../src/smol/pre/transport.rs                 | 60 +++++++++++++++++--
 .../src/smol/pre/transport/tests.rs           | 19 ++++++
 3 files changed, 87 insertions(+), 5 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 4b9c3e8c6..35fb14384 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2181,3 +2181,16 @@ typed QC semantics remain CHECKERS' responsibility. Shared POST/trial retains
 its original connection predicate. Formatting, diff, record and link checks
 pass. The checker README is also updated to distinguish the now-wired host
 caller from still-required backend receipt retention and native qualification.
+
+At clean `d5a4a9ffb`, QA/test-delta and documentation review passed their scoped
+transport and claim checks. Architecture/security found a concrete host-memory
+accounting defect: stderr retention could grow to a configured multi-GiB log
+allowance despite fixed host overhead, and continuous draining lacked an inner
+deadline check. The repair counts and discards logs with an 8 KiB scratch buffer,
+limits each drain pass to 64 KiB per pipe, and checks deadline/cancellation
+between reads. Control output still has its explicit retained-byte bound. A
+continuous-log child with a u32-maximum allowance expires and is reaped; another
+child writes exactly its 4 MiB allowance and completes successfully. All 52
+selected Smol tests pass after repair. The earlier 42 trial tests and 127-pass/
+five-failure full service run remain compatible prior evidence, not relabeled
+exact-head runs. Backend receipt retention and native qualification remain open.
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/transport.rs b/external_checkers/workstream-checker-service/src/smol/pre/transport.rs
index 971a7326a..51764a6ba 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/transport.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/transport.rs
@@ -21,7 +21,7 @@ struct Session {
     output: ChildStdout,
     errors: ChildStderr,
     stdout: Vec,
-    stderr: Vec,
+    stderr_bytes: usize,
     output_eof: bool,
     errors_eof: bool,
     reaped: bool,
@@ -52,7 +52,7 @@ impl Session {
             output,
             errors,
             stdout: Vec::new(),
-            stderr: Vec::new(),
+            stderr_bytes: 0,
             output_eof: false,
             errors_eof: false,
             reaped: false,
@@ -66,15 +66,65 @@ impl Session {
         set_nonblocking(&result.errors)?;
         Ok(result)
     }
-    fn check(&mut self, client: &UnixStream) -> Result<(), String> {
+    fn check_cancelled(&self, client: &UnixStream) -> Result<(), String> {
         if Instant::now() >= self.deadline {
             return Err("deadline_exceeded".into());
         }
         if !connected(client) {
             return Err("cancelled".into());
         }
-        self.output_eof = read_available(&mut self.output, &mut self.stdout, self.maximum_control)?;
-        self.errors_eof = read_available(&mut self.errors, &mut self.stderr, self.maximum_log)?;
+        Ok(())
+    }
+    fn check(&mut self, client: &UnixStream) -> Result<(), String> {
+        // Drain at most 64 KiB per pipe before yielding to input delivery. Logs
+        // are counted and discarded, regardless of the configured allowance.
+        // Check cancellation between reads even under continuous guest output.
+        let mut buffer = [0_u8; 8192];
+        for _ in 0..8 {
+            self.check_cancelled(client)?;
+            let mut progressed = false;
+            if !self.output_eof {
+                match self.output.read(&mut buffer) {
+                    Ok(0) => self.output_eof = true,
+                    Ok(count) => {
+                        self.stdout
+                            .len()
+                            .checked_add(count)
+                            .filter(|total| *total <= self.maximum_control)
+                            .ok_or("PRE output unbounded")?;
+                        self.stdout.extend_from_slice(&buffer[..count]);
+                        progressed = true;
+                    }
+                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => (),
+                    Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
+                        progressed = true
+                    }
+                    Err(_) => return Err("PRE output failed".into()),
+                }
+            }
+            self.check_cancelled(client)?;
+            if !self.errors_eof {
+                match self.errors.read(&mut buffer) {
+                    Ok(0) => self.errors_eof = true,
+                    Ok(count) => {
+                        self.stderr_bytes = self
+                            .stderr_bytes
+                            .checked_add(count)
+                            .filter(|total| *total <= self.maximum_log)
+                            .ok_or("PRE logs unbounded")?;
+                        progressed = true;
+                    }
+                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => (),
+                    Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
+                        progressed = true
+                    }
+                    Err(_) => return Err("PRE logs failed".into()),
+                }
+            }
+            if !progressed {
+                break;
+            }
+        }
         Ok(())
     }
     fn write(&mut self, client: &UnixStream, mut bytes: &[u8]) -> Result<(), String> {
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs
index 79d93785d..05215d29c 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs
@@ -4,6 +4,8 @@ use serde_json::json;
 const GUEST: &str = r#"
 import hashlib,json,struct,sys,time,os
 mode=sys.argv[1]
+if mode=='log_stall':
+    while True: os.write(2,b'x'*65536)
 if mode=='stall':
     time.sleep(30)
     sys.exit(1)
@@ -20,6 +22,8 @@ root=read(job['root']['bundle_byte_count'])
 source=read(job['startup']['request']['reservation']['source']['raw_byte_count'])
 assert read(4)==b'\0'*4
 assert sys.stdin.buffer.read(1)==b''
+if mode=='permitted_logs':
+    sys.stderr.buffer.write(b'x'*job['limits']['maximum_log_bytes']);sys.stderr.buffer.flush()
 if mode=='logs':
     sys.stderr.buffer.write(b'x'*(job['limits']['maximum_log_bytes']+1));sys.stderr.buffer.flush()
 payload=json.dumps({'root':hashlib.sha256(root).hexdigest(),'source':hashlib.sha256(source).hexdigest(),'bytes':len(source),'pid':os.getpid(),'limits':job['limits']}).encode()
@@ -57,6 +61,15 @@ fn run_case(attack: &str) -> Result {
     header["reservation"]["source_sha256"] = json!(canonical_hash(&Value::Object(body)).unwrap());
     let root_digest = format!("sha256:{:x}", Sha256::digest(vec![0_u8; 1024]));
     let pre = config.pre.as_mut().unwrap();
+    if attack == "log_stall" || attack == "permitted_logs" {
+        let maximum = if attack == "log_stall" {
+            u32::MAX as usize
+        } else {
+            4 * 1024 * 1024
+        };
+        pre.limits.maximum_log_bytes = maximum;
+        pre.profile["maximum_log_bytes"] = json!(maximum);
+    }
     pre.root.bundle_sha256 = root_digest.clone();
     pre.profile["platform_root_sha256"] = json!(root_digest);
     pre.profile_sha256 = canonical_hash(&pre.profile).unwrap();
@@ -195,6 +208,12 @@ fn host_launch_passes_identical_clamped_limits_to_argv_and_job() {
     );
 }
 
+#[test]
+fn large_log_allowances_do_not_prevent_deadline_or_successful_completion() {
+    assert_eq!(run_case("log_stall").unwrap_err(), "deadline_exceeded");
+    assert!(run_case("permitted_logs").is_ok());
+}
+
 #[test]
 fn invalid_streams_fail_and_reap_the_owned_process() {
     for attack in [

From 8877a5a4e645770439312b6522de1fd8d7af1509 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 16:30:42 +0100
Subject: [PATCH 098/513] Record reviewed PRE host transport and bounded-log
 repair

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md        | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 35fb14384..c403fd8b2 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2194,3 +2194,12 @@ child writes exactly its 4 MiB allowance and completes successfully. All 52
 selected Smol tests pass after repair. The earlier 42 trial tests and 127-pass/
 five-failure full service run remain compatible prior evidence, not relabeled
 exact-head runs. Backend receipt retention and native qualification remain open.
+
+Architecture/security and QA/test-delta replay passed clean `3ba1cdf64`, resolving
+the log-retention and inner-deadline finding. Reviewers confirmed fixed scratch
+space, checked byte counting, bounded per-pipe passes and the actual-process
+controls. Documentation review of `d5a4a9ffb` remains compatible with the repair's
+scope and limitations. The next required composition is Python adapter parsing
+and CHECKERS/AUTH-bound durable retention of invocation/runtime/timing/cleanup
+facts; returning only the worker payload would discard required ownership
+ evidence. Native qualification and the public submission cutover remain open.

From c94d6b06d6de837bd4d519f56c77e9362d69bc09 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 16:35:36 +0100
Subject: [PATCH 099/513] Plan durable PRE invocation receipt validation and
 finalization binding

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 44 +++++++++++++++++++
 1 file changed, 44 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index c403fd8b2..504354bd1 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2203,3 +2203,47 @@ scope and limitations. The next required composition is Python adapter parsing
 and CHECKERS/AUTH-bound durable retention of invocation/runtime/timing/cleanup
 facts; returning only the worker payload would discard required ownership
  evidence. Native qualification and the public submission cutover remain open.
+
+### Backend PRE invocation receipt retention plan
+
+The host now returns invocation/runtime/timing/cleanup evidence, while the Python
+adapter and CHECKERS currently accept only worker facts. Complete this owner
+composition without discarding metadata: introduce a closed invocation receipt
+and a typed result pairing that receipt with optional existing worker facts.
+The worker facts type and worker protocol remain separate and cannot manufacture
+host cleanup custody. Native runtime/cleanup evidence and a managed-style test
+variant have distinct closed provider evidence; shared ports require no host
+paths, file descriptors, local UIDs or Smol journal fields from every provider.
+Configured identities are evidence, not a claim of native qualification; complete
+qualification/conformance enforcement remains a separate explicit requirement.
+
+Validate exact operation/run/source/request/profile/image/fence, outcome/result
+presence, finite stage timing and cleanup disposition. Existing CHECKERS worker
+validation still derives and checks default input, manifest, registry and project
+result. The processor and ART foreground composition carry the typed response
+through finalization; transport failures may have no receipt, but a completed
+result must have one. Bind the receipt into AUTH finalization facts and CHECKERS
+terminal bytes/digest. Preserve typed infrastructure outcomes and do not convert
+cleanup pending into QC rejection or release local runtime capacity.
+
+Allowed changes: CHECKERS API receipt/terminal facts, existing external execution
+port/adapters/processor, ART source-execution composition, CHECKERS coordinator and
+retained reads, the next Alembic migration, affected owner/adapter/PG/read tests
+and fixtures, and this record. No new provider factory, compatibility execution
+path, default qualification values, public handoff shortcut, retained-data rewrite
+or migration-0071 edit is allowed. Use a new terminal/finalization schema version
+for receipt-bearing evidence; retain old source-terminal decoding strictly for
+reads, without inventing missing runtime custody. Existing prepared v1 retention
+continues. The SQL finalization facts digest and closed terminal guards must match
+Python, require bound receipts for completed new terminals, and preserve earlier
+immutable rows/digests. Replay cannot mint acceptance from a historical receipt.
+
+This is architecture/security-sensitive L1 work requiring plan review before
+implementation and architecture/security plus QA/test-delta after tests. Human
+review focus is authority-digest parity, exact receipt retention, historical read
+limits and provider-neutral ownership. Acceptance includes destroyed/pending
+receipts, receipt/source/fence/profile/runtime mismatch rejection, malformed
+outcome/timing refusal, AUTH digest sensitivity, actual PostgreSQL terminal
+retention/guard rejection, native wire decoding and a managed-style no-host-access
+contract test. Public T4, finalization/POST, qualification and full acceptance
+scenarios remain required subsequent work, not completion claims for this step.

From 58714d8fc96412e6a1715e86aefc888407646272 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 16:39:34 +0100
Subject: [PATCH 100/513] Resolve PRE receipt outcome provider and migration
 plan boundaries

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 36 +++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 504354bd1..c74e9c635 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2247,3 +2247,39 @@ outcome/timing refusal, AUTH digest sensitivity, actual PostgreSQL terminal
 retention/guard rejection, native wire decoding and a managed-style no-host-access
 contract test. Public T4, finalization/POST, qualification and full acceptance
 scenarios remain required subsequent work, not completion claims for this step.
+
+Plan-review resolutions:
+
+- Completed responses carry both receipt and typed worker facts. Received
+  `infrastructure_failure` and `deadline_exceeded` responses carry their receipt
+  through finalization with the corresponding closed infrastructure code;
+  transport failure before receipt delivery may carry none. Native `cancelled`
+  and task cancellation propagate `CancelledError`, without manufacturing QC or
+  a finalization decision. Independent runtime cleanup ownership still applies;
+  abandoned execution leases use the existing owner recovery path.
+- Migration 0072 takes the run-table lock and refuses upgrade if any source-v2
+  run is queued/running. Deployment must quiesce/drain those runs through their
+  current owner before migration; no migration fabricates a terminal outcome or
+  rewrites an immutable request. After upgrade, new source-v2 reservations still
+  use the current request contract but can finalize only to the receipt-bearing
+  terminal schema. Read dispatch explicitly handles prepared-v1, historical
+  source-v2 terminal, current source-v3 terminal, and source-v2 nonterminal rows.
+  Historical terminal evidence never enters current finalization/acceptance.
+- The concrete Unix-socket adapter accepts only native runtime/cleanup evidence.
+  It attaches its trusted factory `provider_key` to the retained receipt; that
+  key is not accepted from the native wire. The processor independently compares
+  it with the selected adapter identity. The managed-style test adapter uses its
+  own explicit factory key, configured deployment identity, provider invocation
+  and provider cleanup acknowledgement; native journal fields are not required
+  of it and it cannot substitute for a Unix-socket/Smol invocation.
+- Completed PostgreSQL proof uses a separate actual-ZIP source admitted through
+  ART and builds worker facts from the exact claimed database lease/source.
+  Existing non-ZIP infrastructure fixtures stay as failure-boundary coverage;
+  synthetic worker leases are never transplanted into real DB rows. Tests cover
+  retained queued/running/completed/infrastructure source-v2 reads and the
+  migration's refusal to proceed over in-flight v2 work.
+- Extract the native host's existing response serializer and emit a portable
+  Rust fixture through that same function for Python wire-decoding proof. Add
+  the serializer/test fixture files to scope; no fake native Machine creation
+  or qualification is claimed. A received infrastructure receipt with pending
+  cleanup must be retained, not collapsed into a code-only exception.

From a3748997fecb86ede090b88ea87f569d5555e8d9 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 17:15:31 +0100
Subject: [PATCH 101/513] Retain PRE invocation receipts through authorized
 finalization

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  23 ++
 .../versions/0072_pre_invocation_receipts.py  | 144 ++++++++
 .../app/adapters/checkers/external_service.py |  12 +-
 .../interfaces/external_checker_execution.py  |   4 +-
 .../selected_pre_submit_execution.py          |  16 +-
 .../checkers/api/selected_pre_submit.py       | 334 +++++++++++++++++-
 .../selected_pre_submit_coordination.py       |  34 +-
 .../checkers/selected_pre_submit_execution.py |  10 +-
 .../checkers/selected_pre_submit_reads.py     |  43 ++-
 .../checkers/selected_pre_submit_records.py   |  27 ++
 .../artifacts/test_submission_pre_source.py   | 193 ++++++++--
 .../checkers/external/test_pre_invocation.py  | 244 +++++++++++++
 .../tests/checkers/external/test_runtime.py   |  13 +-
 .../test_selected_pre_submit_coordination.py  |  25 +-
 backend/tests/conftest.py                     |   2 +-
 backend/tests/test_trusted_intake.py          |  28 +-
 .../src/smol/pre.rs                           |  38 +-
 .../src/smol/pre/tests.rs                     |  27 ++
 .../tests/fixtures/pre_invocation.json        | 326 +++++++++++++++++
 19 files changed, 1436 insertions(+), 107 deletions(-)
 create mode 100644 backend/alembic/versions/0072_pre_invocation_receipts.py
 create mode 100644 backend/app/modules/checkers/selected_pre_submit_records.py
 create mode 100644 backend/tests/checkers/external/test_pre_invocation.py
 create mode 100644 external_checkers/workstream-checker-service/tests/fixtures/pre_invocation.json

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index c74e9c635..59324138f 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2283,3 +2283,26 @@ Plan-review resolutions:
   the serializer/test fixture files to scope; no fake native Machine creation
   or qualification is claimed. A received infrastructure receipt with pending
   cleanup must be retained, not collapsed into a code-only exception.
+
+Receipt implementation now carries typed provider observations through the PRE
+adapter, processor, ART foreground owner and AUTH-bound terminal v3. Migration
+0072 adds a locked in-flight drain check, receipt guards and version-sensitive
+finalization digest; 0071 is unchanged. Source-first coordination contract tests
+pass (51), as do receipt substitution/timing/outcome, retained-read and managed
+port tests (35), and single-PRE socket tests (12). These are portable contract proofs, not native qualification.
+The migration applies to isolated PostgreSQL; all 12 SQL digest-parity and
+receipt-substitution probes pass. The broader source integration run passes
+41 cases, with a six-case affected replay after fixture extraction and addition
+of received-failure retention. The actual migration entry refuses queued and running source
+runs without row changes. A shared synthetic fixture matches the production Rust
+response serializer and Python decoder; 53 selected Smol tests and the live
+Python/Rust worker dialogue pass. None of these portable checks qualifies native
+VM operation. The real-ZIP database test initially expected a removed prepared
+handoff capability; source finalization correctly supplies no such capability.
+The corrected proof checks eligible worker facts and exact retained receipts,
+leaving T4 acceptance explicitly open. The six-case replay proves both completed real-ZIP receipt persistence and
+received infrastructure receipts with pending cleanup. Python also decodes the
+actual bytes emitted by the production Rust serializer in a separate portable
+probe. Structural validation and Markdown links pass. Implementation review
+remains required; public submission/acceptance and native qualification remain
+outstanding parts of the overall objective.
diff --git a/backend/alembic/versions/0072_pre_invocation_receipts.py b/backend/alembic/versions/0072_pre_invocation_receipts.py
new file mode 100644
index 000000000..e4567fb64
--- /dev/null
+++ b/backend/alembic/versions/0072_pre_invocation_receipts.py
@@ -0,0 +1,144 @@
+"""Retain provider invocation receipts in source PRE finalization evidence."""
+from alembic import op
+from sqlalchemy import text
+
+revision = "0072_pre_invocation_receipts"
+down_revision = "0071_source_first_pre"
+branch_labels = None
+depends_on = None
+
+
+def _replace(signature, old, new):
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))"
+    ), {"signature": signature}).scalar_one()
+    if body.count(old) != 1:
+        raise RuntimeError("PRE receipt predecessor shape changed: " + signature)
+    op.execute(body.replace(old, new))
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.selected_pre_submit_runs IN ACCESS EXCLUSIVE MODE")
+    op.execute("""DO $$ BEGIN
+      IF EXISTS(SELECT 1 FROM public.selected_pre_submit_runs
+        WHERE request_json->>'schema_version'='workstream.selected_pre_submit_reservation.v2'
+          AND status IN ('queued','running')) THEN
+        RAISE EXCEPTION 'drain source PRE runs before migrating invocation receipts'
+          USING ERRCODE='55000';
+      END IF;
+    END $$""")
+    op.execute(r"""
+CREATE FUNCTION public.require_selected_pre_invocation(r public.selected_pre_submit_runs)
+RETURNS void LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE receipt jsonb:=r.terminal_json->'invocation_receipt'; identity jsonb;
+ runtime jsonb; cleanup jsonb; timings jsonb; field text; stage_total bigint:=0;
+ member jsonb; native boolean;
+BEGIN
+ IF receipt='null'::jsonb AND r.status='infrastructure_failed' THEN RETURN; END IF;
+ IF jsonb_typeof(receipt) IS DISTINCT FROM 'object'
+    OR NOT receipt ?& ARRAY['schema_version','adapter_provider_key','operation','phase',
+      'invocation','provider_invocation_id','outcome','reason','runtime','timings_ms','cleanup']
+    OR receipt-ARRAY['schema_version','adapter_provider_key','operation','phase',
+      'invocation','provider_invocation_id','outcome','reason','runtime','timings_ms','cleanup']<>'{}'::jsonb
+    OR receipt->>'schema_version' IS DISTINCT FROM 'workstream.pre_submit_invocation.v1'
+    OR receipt->>'operation' IS DISTINCT FROM 'execute_pre'
+    OR receipt->>'phase' IS DISTINCT FROM 'pre_submit'
+    OR coalesce(receipt->>'adapter_provider_key','') !~ '^[a-z][a-z0-9_]{0,63}$'
+    OR jsonb_typeof(receipt->'provider_invocation_id') IS DISTINCT FROM 'string'
+    OR coalesce(receipt->>'provider_invocation_id','') !~ '^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,254}$'
+ THEN RAISE EXCEPTION 'selected PRE invocation shape mismatch' USING ERRCODE='23514'; END IF;
+ identity:=receipt->'invocation'; runtime:=receipt->'runtime';
+ cleanup:=receipt->'cleanup'; timings:=receipt->'timings_ms';
+ IF jsonb_typeof(identity) IS DISTINCT FROM 'object'
+    OR identity IS DISTINCT FROM jsonb_build_object(
+      'operation','execute_pre','run_id',r.id::text,'source_operation_id',r.source_operation_id::text,
+      'request_digest',r.request_digest,'source_sha256',r.request_json->>'source_sha256',
+      'profile_sha256',public.external_checker_registry_digest(r.request_json->'runtime_profile'),
+      'image_digest',r.request_json->'policy'->'entries'->0->'registry'->>'image_digest',
+      'config_image_id',identity->>'config_image_id','lease_id',r.lease_id::text,
+      'lease_generation',r.lease_generation)
+    OR coalesce(identity->>'config_image_id','') !~ '^sha256:[0-9a-f]{64}$'
+ THEN RAISE EXCEPTION 'selected PRE invocation identity mismatch' USING ERRCODE='23514'; END IF;
+ IF (r.status='completed' AND (receipt->>'outcome' IS DISTINCT FROM 'completed'
+       OR receipt->'reason' IS DISTINCT FROM 'null'::jsonb))
+    OR (r.status='infrastructure_failed' AND (
+      coalesce(receipt->>'outcome','') NOT IN ('infrastructure_failure','deadline_exceeded')
+      OR receipt->>'reason' IS DISTINCT FROM r.terminal_json->>'infrastructure_failure_code'
+      OR NOT ((receipt->>'outcome'='deadline_exceeded' AND receipt->>'reason'='deadline_exceeded')
+        OR (receipt->>'outcome'='infrastructure_failure' AND receipt->>'reason' IN
+          ('capacity_exceeded','material_unavailable','implementation_unavailable','invalid_output')))))
+ THEN RAISE EXCEPTION 'selected PRE invocation outcome mismatch' USING ERRCODE='23514'; END IF;
+ native:=runtime->>'provider'='smolvm';
+ IF jsonb_typeof(runtime) IS DISTINCT FROM 'object'
+    OR coalesce(runtime->>'provider','') NOT IN ('smolvm','managed')
+    OR jsonb_typeof(runtime->'version') IS DISTINCT FROM 'string'
+    OR length(runtime->>'version') NOT BETWEEN 1 AND 100
+    OR runtime->'profile' IS DISTINCT FROM r.request_json->'runtime_profile'
+    OR (native AND (runtime-ARRAY['provider','version','binary_sha256','guest_sha256','profile']<>'{}'::jsonb
+      OR coalesce(runtime->>'binary_sha256','') !~ '^sha256:[0-9a-f]{64}$'
+      OR coalesce(runtime->>'guest_sha256','') !~ '^sha256:[0-9a-f]{64}$'))
+    OR (NOT native AND (runtime-ARRAY['provider','version','deployment_sha256','profile']<>'{}'::jsonb
+      OR coalesce(runtime->>'deployment_sha256','') !~ '^sha256:[0-9a-f]{64}$'))
+    OR jsonb_typeof(cleanup) IS DISTINCT FROM 'object'
+    OR coalesce(cleanup->>'disposition','') NOT IN ('destroyed','pending')
+    OR jsonb_typeof(cleanup->'obligation_id') IS DISTINCT FROM 'string'
+    OR coalesce(cleanup->>'obligation_id','') !~ '^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,254}$'
+    OR (native AND (cleanup-ARRAY['obligation_id','journal_sha256','disposition']<>'{}'::jsonb
+      OR cleanup->>'obligation_id' IS DISTINCT FROM receipt->>'provider_invocation_id'
+      OR coalesce(cleanup->>'journal_sha256','') !~ '^sha256:[0-9a-f]{64}$'))
+    OR (NOT native AND (cleanup-ARRAY['obligation_id','provider_receipt_sha256','disposition']<>'{}'::jsonb
+      OR coalesce(cleanup->>'provider_receipt_sha256','') !~ '^sha256:[0-9a-f]{64}$'))
+ THEN RAISE EXCEPTION 'selected PRE invocation runtime mismatch' USING ERRCODE='23514'; END IF;
+ IF jsonb_typeof(timings) IS DISTINCT FROM 'object'
+    OR timings-ARRAY['admission','preparation','execution','cleanup','total']<>'{}'::jsonb
+ THEN RAISE EXCEPTION 'selected PRE invocation timings mismatch' USING ERRCODE='23514'; END IF;
+ FOREACH field IN ARRAY ARRAY['admission','preparation','execution','cleanup','total'] LOOP
+   IF jsonb_typeof(timings->field) IS DISTINCT FROM 'number'
+      OR coalesce(timings->>field,'') !~ '^[0-9]+$'
+      OR (timings->>field)::numeric>14400000
+   THEN RAISE EXCEPTION 'selected PRE invocation timing bound mismatch' USING ERRCODE='23514'; END IF;
+   IF field<>'total' THEN stage_total:=stage_total+(timings->>field)::bigint; END IF;
+ END LOOP;
+ IF stage_total>(timings->>'total')::bigint OR (timings->>'total')::bigint>
+    (r.request_json->'runtime_profile'->>'aggregate_deadline_ms')::bigint
+ THEN RAISE EXCEPTION 'selected PRE invocation deadline mismatch' USING ERRCODE='23514'; END IF;
+ IF r.status='completed' THEN
+   IF r.terminal_json->'execution'->>'request_digest' IS DISTINCT FROM r.request_digest
+      OR r.terminal_json->'execution'->>'lease_id' IS DISTINCT FROM r.lease_id::text
+      OR r.terminal_json->'execution'->'lease_generation' IS DISTINCT FROM to_jsonb(r.lease_generation)
+   THEN RAISE EXCEPTION 'selected PRE invocation worker fence mismatch' USING ERRCODE='23514'; END IF;
+   FOR member IN SELECT value FROM jsonb_array_elements(r.terminal_json->'execution'->'external_members') LOOP
+     IF member->'isolation'->>'config_image_id' IS DISTINCT FROM identity->>'config_image_id'
+        OR member->'isolation'->>'platform_manifest_digest' IS DISTINCT FROM identity->>'image_digest'
+        OR (native AND (member->'isolation'->>'runtime' IS DISTINCT FROM 'smolvm'
+          OR member->'isolation'->>'isolation_mode' IS DISTINCT FROM 'smol-microvm'))
+        OR (NOT native AND (member->'isolation'->>'provider' IS DISTINCT FROM 'managed'
+          OR member->'isolation'->>'deployment_sha256' IS DISTINCT FROM runtime->>'deployment_sha256'))
+     THEN RAISE EXCEPTION 'selected PRE invocation worker runtime mismatch' USING ERRCODE='23514'; END IF;
+   END LOOP;
+ END IF;
+END $$
+""")
+    signature = "public.guard_selected_pre_submit_run()"
+    _replace(signature, "'workstream.selected_pre_submit_terminal.v2'",
+             "'workstream.selected_pre_submit_terminal.v3'")
+    _replace(signature, "'outcome','execution','infrastructure_failure_code',",
+             "'outcome','execution','invocation_receipt','infrastructure_failure_code',")
+    _replace(signature, " perform public.require_selected_pre_source(new);",
+             " IF old.status='running' THEN PERFORM public.require_selected_pre_invocation(new); END IF;\n"
+             " perform public.require_selected_pre_source(new);")
+    signature = "public.selected_pre_submit_facts_digest(public.selected_pre_submit_runs,text)"
+    _replace(signature, "then 'workstream.selected_pre_submit_finalize.v2'",
+             "then CASE WHEN r.terminal_json->>'schema_version'='workstream.selected_pre_submit_terminal.v3' "
+             "THEN 'workstream.selected_pre_submit_finalize.v3' ELSE 'workstream.selected_pre_submit_finalize.v2' END")
+    _replace(signature,
+             "'infrastructure_failure_code',r.terminal_json->'infrastructure_failure_code'))",
+             "'infrastructure_failure_code',r.terminal_json->'infrastructure_failure_code') || "
+             "CASE WHEN r.terminal_json->>'schema_version'='workstream.selected_pre_submit_terminal.v3' "
+             "THEN jsonb_build_object('invocation_receipt',r.terminal_json->'invocation_receipt') "
+             "ELSE '{}'::jsonb END)")
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index b9848648c..4b74f8284 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -37,7 +37,7 @@
 )
 
 from app.modules.checkers.api.selected_pre_submit import (
-    SelectedPreSubmitLeaseFacts, SelectedPreSubmitExecutionFacts,
+    SelectedPreSubmitLeaseFacts, SelectedPreSubmitInvocationResult,
     SelectedPreSubmitInfrastructureUnavailable,
 )
 
@@ -80,7 +80,7 @@ def identity(self) -> ExternalServiceAdapterIdentity:
 
     async def execute_pre(
         self, lease: SelectedPreSubmitLeaseFacts, grant: ExternalPreSubmitSourceGrant,
-    ) -> SelectedPreSubmitExecutionFacts:
+    ) -> SelectedPreSubmitInvocationResult:
         """Stream authorized source bytes into one PRE call without a host spool."""
         try:
             if type(lease) is not SelectedPreSubmitLeaseFacts:
@@ -133,7 +133,13 @@ async def execute_pre(
                 finally:
                     writer.close()
                     await await_cancellation_resistant(writer.wait_closed())
-            result = SelectedPreSubmitExecutionFacts.from_canonical_body(json.loads(raw))
+            body = json.loads(raw)
+            if type(body) is not dict or "adapter_provider_key" in body:
+                raise ValueError("PRE provider context is invalid")
+            body["adapter_provider_key"] = self.identity.provider_key
+            result = SelectedPreSubmitInvocationResult.from_canonical_body(body)
+            if result.receipt.runtime.provider != "smolvm":
+                raise ValueError("PRE runtime provider differs")
             result.validate_lease(lease)
             if (asyncio.get_running_loop().time() >= deadline
                     or datetime.now(timezone.utc) >= lease.lease_expires_at):
diff --git a/backend/app/interfaces/external_checker_execution.py b/backend/app/interfaces/external_checker_execution.py
index 625924227..504d729e5 100644
--- a/backend/app/interfaces/external_checker_execution.py
+++ b/backend/app/interfaces/external_checker_execution.py
@@ -9,7 +9,7 @@
 
 from app.interfaces.external_services import ExternalServiceAdapter
 from app.modules.checkers.api.selected_pre_submit import (
-    SelectedPreSubmitLeaseFacts, SelectedPreSubmitExecutionFacts,
+    SelectedPreSubmitLeaseFacts, SelectedPreSubmitInvocationResult,
 )
 from app.modules.checkers.api.forge_locator import ExternalCheckerForgeLocator
 from app.modules.checkers.api.external import (
@@ -168,7 +168,7 @@ class ExternalCheckerExecutionAdapter(ExternalServiceAdapter, Protocol):
 
     async def execute_pre(
         self, lease: SelectedPreSubmitLeaseFacts, grant: ExternalPreSubmitSourceGrant,
-    ) -> SelectedPreSubmitExecutionFacts:
+    ) -> SelectedPreSubmitInvocationResult:
         """Run source verification, defaults and selected project in one session."""
 
     async def locate_forge_change(
diff --git a/backend/app/modules/artifacts/selected_pre_submit_execution.py b/backend/app/modules/artifacts/selected_pre_submit_execution.py
index 1f4528c42..bb297fa8b 100644
--- a/backend/app/modules/artifacts/selected_pre_submit_execution.py
+++ b/backend/app/modules/artifacts/selected_pre_submit_execution.py
@@ -26,7 +26,7 @@
 from app.modules.checkers.api.selected_pre_submit import (
     SelectedPreSubmitAuthorityPort, SelectedPreSubmitCompletion,
     SelectedPreSubmitCoordinationPort, SelectedPreSubmitExecutionAuthority,
-    SelectedPreSubmitExecutionFacts, SelectedPreSubmitFinalizeFacts,
+    SelectedPreSubmitInvocationResult, SelectedPreSubmitFinalizeFacts,
     SelectedPreSubmitInfrastructureUnavailable, SelectedPreSubmitLeaseFacts,
     SelectedPreSubmitReservationFacts,
 )
@@ -43,7 +43,7 @@ def close(self) -> None: ...
 class PreSubmitProcessor(Protocol):
     """CHECKERS processor composed through its existing adapter factory."""
 
-    async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmitExecutionFacts: ...
+    async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmitInvocationResult: ...
 
 
 class PreSubmitExecutionFactory(Protocol):
@@ -208,19 +208,25 @@ async def execute(self, *, reservation: SelectedPreSubmitReservationFacts) -> Se
             async with self._authority.prepare_execution(reservation) as prepared:
                 lease = await self._coordinator.claim(run_id=run_id, facts=reservation, authority=prepared)
         execution = None
+        receipt = None
         failure = None
         try:
             capability = await self._coordinator.committed_execution(run_id=run_id, lease=lease)
             async with self._source_reads.issue(lease=lease, execution_authority=capability) as grant:
-                execution = await self._execution.build(lease).process(grant)
+                result = await self._execution.build(lease).process(grant)
+                result.validate_lease(lease)
+                if result.receipt.outcome == "cancelled":
+                    raise asyncio.CancelledError
+                execution, receipt = result.execution, result.receipt
+                failure = receipt.reason if execution is None else None
         except SelectedPreSubmitInfrastructureUnavailable as exc:
             failure = exc.code
-        facts = SelectedPreSubmitFinalizeFacts(lease=lease, execution=execution, infrastructure_failure_code=failure)
+        facts = SelectedPreSubmitFinalizeFacts(lease=lease, execution=execution, invocation_receipt=receipt, infrastructure_failure_code=failure)
         async with self._session.begin():
             async with self._authority.prepare_finalization(facts) as prepared:
                 return await self._coordinator.finalize(
                     run_id=run_id, lease=lease, authority=prepared, execution=execution,
-                    infrastructure_failure_code=failure,
+                    infrastructure_failure_code=failure, invocation_receipt=receipt,
                 )
 
 
diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py
index bd531dcfd..cd5b69f17 100644
--- a/backend/app/modules/checkers/api/selected_pre_submit.py
+++ b/backend/app/modules/checkers/api/selected_pre_submit.py
@@ -5,12 +5,12 @@
 from dataclasses import asdict, dataclass
 from datetime import datetime, timedelta, timezone
 from contextlib import AbstractAsyncContextManager
-from typing import Literal, Protocol
+from typing import Annotated, Literal, Protocol
 from uuid import UUID
 
 import json
 
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict, Field, model_validator
 
 from app.core.hashing import canonical_json_hash
 from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
@@ -245,6 +245,24 @@ class ExternalPreSubmitIsolationFacts:
     sandbox_gid: int
 
 
+@dataclass(frozen=True, slots=True)
+class ExternalPreSubmitManagedIsolationFacts:
+    """Managed provider observation without local sandbox identifiers."""
+
+    provider: Literal["managed"]
+    platform_manifest_digest: str
+    config_image_id: str
+    deployment_sha256: str
+
+    def __post_init__(self) -> None:
+        if self.provider != "managed" or any(
+            type(value) is not str or len(value) != 71 or not value.startswith("sha256:")
+            or any(character not in "0123456789abcdef" for character in value[7:])
+            for value in (self.platform_manifest_digest, self.config_image_id, self.deployment_sha256)
+        ):
+            raise ValueError("managed PRE isolation is invalid")
+
+
 @dataclass(frozen=True, slots=True)
 class ExternalPreSubmitMemberFacts:
     """One completed required project PRE image in canonical policy order."""
@@ -255,7 +273,7 @@ class ExternalPreSubmitMemberFacts:
     registry_entry_digest: str
     request_digest: str
     result: ExternalCheckerExecutionResult
-    isolation: ExternalPreSubmitIsolationFacts
+    isolation: ExternalPreSubmitIsolationFacts | ExternalPreSubmitManagedIsolationFacts
 
     def __post_init__(self) -> None:
         if (
@@ -447,7 +465,9 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitExecutionFacts:
                         item["result"]
                         | {"registry_entry_id": UUID(str(item["result"]["registry_entry_id"]))}
                     ),
-                    isolation=ExternalPreSubmitIsolationFacts(**item["isolation"]),
+                    isolation=(ExternalPreSubmitManagedIsolationFacts(**item["isolation"])
+                               if item["isolation"].get("provider") == "managed"
+                               else ExternalPreSubmitIsolationFacts(**item["isolation"])),
                 )
                 for item in members
             ),
@@ -723,6 +743,168 @@ def derive_selected_pre_submit_input(
     return value, request
 
 
+_ReceiptDigest = Annotated[str, Field(pattern=r"^sha256:[0-9a-f]{64}$")]
+_ReceiptId = Annotated[str, Field(pattern=r"^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,254}$")]
+_ReceiptUUID = Annotated[str, Field(pattern=r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")]
+_ReceiptMilliseconds = Annotated[int, Field(ge=0, le=14_400_000)]
+
+
+class _PreReceiptValue(BaseModel):
+    model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
+
+
+class _PreInvocationIdentity(_PreReceiptValue):
+    operation: Literal["execute_pre"]
+    run_id: _ReceiptUUID
+    source_operation_id: _ReceiptUUID
+    request_digest: _ReceiptDigest
+    source_sha256: _ReceiptDigest
+    profile_sha256: _ReceiptDigest
+    image_digest: _ReceiptDigest
+    config_image_id: _ReceiptDigest
+    lease_id: _ReceiptUUID
+    lease_generation: int = Field(gt=0)
+
+
+class _NativePreRuntime(_PreReceiptValue):
+    provider: Literal["smolvm"]
+    version: str = Field(min_length=1, max_length=100)
+    binary_sha256: _ReceiptDigest
+    guest_sha256: _ReceiptDigest
+    profile: SelectedPreSubmitRuntimeProfile
+
+
+class _ManagedPreRuntime(_PreReceiptValue):
+    provider: Literal["managed"]
+    version: str = Field(min_length=1, max_length=100)
+    deployment_sha256: _ReceiptDigest
+    profile: SelectedPreSubmitRuntimeProfile
+
+
+class _NativePreCleanup(_PreReceiptValue):
+    obligation_id: _ReceiptId
+    journal_sha256: _ReceiptDigest
+    disposition: Literal["destroyed", "pending"]
+
+
+class _ManagedPreCleanup(_PreReceiptValue):
+    obligation_id: _ReceiptId
+    provider_receipt_sha256: _ReceiptDigest
+    disposition: Literal["destroyed", "pending"]
+
+
+class _PreStageTimings(_PreReceiptValue):
+    admission: _ReceiptMilliseconds
+    preparation: _ReceiptMilliseconds
+    execution: _ReceiptMilliseconds
+    cleanup: _ReceiptMilliseconds
+    total: _ReceiptMilliseconds
+
+
+class SelectedPreSubmitInvocationReceipt(_PreReceiptValue):
+    """Bound provider observations; structural validity is not qualification."""
+
+    schema_version: Literal["workstream.pre_submit_invocation.v1"]
+    adapter_provider_key: str = Field(pattern=r"^[a-z][a-z0-9_]{0,63}$")
+    operation: Literal["execute_pre"]
+    phase: Literal["pre_submit"]
+    invocation: _PreInvocationIdentity
+    provider_invocation_id: _ReceiptId
+    outcome: Literal["completed", "infrastructure_failure", "deadline_exceeded", "cancelled"]
+    reason: Literal["capacity_exceeded", "deadline_exceeded", "material_unavailable",
+                    "implementation_unavailable", "invalid_output", "cancelled"] | None
+    runtime: Annotated[_NativePreRuntime | _ManagedPreRuntime, Field(discriminator="provider")]
+    timings_ms: _PreStageTimings
+    cleanup: _NativePreCleanup | _ManagedPreCleanup
+
+    @model_validator(mode="after")
+    def validate_observations(self):
+        if ((self.outcome == "completed" and self.reason is not None)
+                or (self.outcome == "infrastructure_failure" and self.reason not in {
+                    "capacity_exceeded", "material_unavailable", "implementation_unavailable", "invalid_output"})
+                or (self.outcome in {"deadline_exceeded", "cancelled"} and self.reason != self.outcome)):
+            raise ValueError("PRE invocation outcome differs")
+        if ((self.runtime.provider == "smolvm") != (type(self.cleanup) is _NativePreCleanup)
+                or (self.runtime.provider == "smolvm" and self.cleanup.obligation_id != self.provider_invocation_id)):
+            raise ValueError("PRE cleanup authority differs")
+        timings = self.timings_ms
+        if (timings.admission + timings.preparation + timings.execution + timings.cleanup > timings.total
+                or timings.total > self.runtime.profile.aggregate_deadline_ms
+                or self.invocation.profile_sha256 != canonical_json_hash(self.runtime.profile.model_dump(mode="json"))):
+            raise ValueError("PRE invocation profile or timing differs")
+        return self
+
+    def canonical_body(self) -> dict[str, object]:
+        """Retain all provider and cleanup facts without transport credentials."""
+        return self.model_dump(mode="json")
+
+    def validate_lease(self, lease: SelectedPreSubmitLeaseFacts) -> None:
+        """Revalidate even adapter-created model instances before trusting them."""
+        checked = type(self).model_validate_json(json.dumps(self.canonical_body(), allow_nan=False))
+        request, identity = lease.reservation, checked.invocation
+        if (identity.run_id != str(request.attempt_id)
+                or identity.source_operation_id != str(request.source.location.operation_id)
+                or identity.request_digest != request.request_digest
+                or identity.source_sha256 != request.source.source_sha256()
+                or identity.lease_id != str(lease.lease_id) or identity.lease_generation != lease.lease_generation
+                or identity.image_digest != request.policy.entries[0].registry.image_digest
+                or checked.runtime.profile != request.runtime_profile):
+            raise ValueError("PRE invocation lease differs")
+
+
+@dataclass(frozen=True, slots=True)
+class SelectedPreSubmitInvocationResult:
+    """A provider receipt paired with worker facts only for completed checks."""
+
+    receipt: SelectedPreSubmitInvocationReceipt
+    execution: SelectedPreSubmitExecutionFacts | None
+
+    def __post_init__(self) -> None:
+        if (type(self.receipt) is not SelectedPreSubmitInvocationReceipt
+                or (self.receipt.outcome == "completed") != (type(self.execution) is SelectedPreSubmitExecutionFacts)
+                or (self.execution is not None and type(self.execution) is not SelectedPreSubmitExecutionFacts)):
+            raise ValueError("PRE invocation result differs")
+
+    def validate_lease(self, lease: SelectedPreSubmitLeaseFacts) -> None:
+        self.__post_init__()
+        self.receipt.validate_lease(lease)
+        if self.execution is None:
+            return
+        self.execution.validate_lease(lease)
+        for member in self.execution.external_members:
+            isolation = member.isolation
+            if isolation.config_image_id != self.receipt.invocation.config_image_id:
+                raise ValueError("PRE observed image configuration differs")
+            if self.receipt.runtime.provider == "smolvm":
+                if (type(isolation) is not ExternalPreSubmitIsolationFacts
+                        or isolation.runtime != "smolvm" or isolation.isolation_mode != "smol-microvm"
+                        or type(isolation.sandbox_uid) is not int or isolation.sandbox_uid <= 0
+                        or type(isolation.sandbox_gid) is not int or isolation.sandbox_gid <= 0):
+                    raise ValueError("PRE observed runtime differs")
+            elif (type(isolation) is not ExternalPreSubmitManagedIsolationFacts
+                  or isolation.deployment_sha256 != self.receipt.runtime.deployment_sha256):
+                raise ValueError("PRE observed managed runtime differs")
+
+    def canonical_body(self) -> dict[str, object]:
+        return self.receipt.canonical_body() | {
+            "execution": self.execution.canonical_body() if self.execution is not None else None,
+        }
+
+    @classmethod
+    def from_canonical_body(cls, body: object) -> SelectedPreSubmitInvocationResult:
+        if type(body) is not dict or "execution" not in body:
+            raise ValueError("PRE invocation body is invalid")
+        receipt = dict(body)
+        execution = receipt.pop("execution")
+        value = cls(
+            receipt=SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(receipt, allow_nan=False)),
+            execution=SelectedPreSubmitExecutionFacts.from_canonical_body(execution) if execution is not None else None,
+        )
+        if value.canonical_body() != body:
+            raise ValueError("PRE invocation body is not canonical")
+        return value
+
+
 class SelectedPreSubmitExecutionAuthority(Protocol):
     """Process-local capability for one committed durable PRE lease."""
 
@@ -781,6 +963,7 @@ class SelectedPreSubmitFinalizeFacts:
 
     lease: SelectedPreSubmitLeaseFacts
     execution: SelectedPreSubmitExecutionFacts | None
+    invocation_receipt: SelectedPreSubmitInvocationReceipt | None
     infrastructure_failure_code: str | None
 
     def __post_init__(self) -> None:
@@ -791,20 +974,26 @@ def __post_init__(self) -> None:
         if self.execution is not None:
             if type(self.execution) is not SelectedPreSubmitExecutionFacts:
                 raise ValueError("selected PRE finalize execution is invalid")
-            self.execution.validate_lease(self.lease)
+            SelectedPreSubmitInvocationResult(self.invocation_receipt, self.execution).validate_lease(self.lease)
         else:
             SelectedPreSubmitInfrastructureUnavailable(self.infrastructure_failure_code or "")
+            if self.invocation_receipt is not None:
+                SelectedPreSubmitInvocationResult(self.invocation_receipt, None).validate_lease(self.lease)
+                if (self.invocation_receipt.outcome not in {"infrastructure_failure", "deadline_exceeded"}
+                        or self.invocation_receipt.reason != self.infrastructure_failure_code):
+                    raise ValueError("PRE infrastructure receipt differs")
 
     @property
     def facts_digest(self) -> str:
         """Bind the lease to either exact results or one closed infrastructure code."""
         return canonical_json_hash(
             {
-                "schema_version": "workstream.selected_pre_submit_finalize.v2",
+                "schema_version": "workstream.selected_pre_submit_finalize.v3",
                 "execute_facts_digest": SelectedPreSubmitExecuteFacts(self.lease).facts_digest,
                 "execution": (
                     self.execution.canonical_body() if self.execution is not None else None
                 ),
+                "invocation_receipt": self.invocation_receipt.canonical_body() if self.invocation_receipt is not None else None,
                 "infrastructure_failure_code": self.infrastructure_failure_code,
             }
         )
@@ -903,6 +1092,7 @@ async def finalize(
         lease: SelectedPreSubmitLeaseFacts,
         authority: PreparedSelectedPreSubmitFinalization,
         execution: SelectedPreSubmitExecutionFacts | None,
+        invocation_receipt: SelectedPreSubmitInvocationReceipt | None,
         infrastructure_failure_code: str | None,
     ) -> SelectedPreSubmitCompletion:
         """Persist one terminal result and return pass authority when eligible."""
@@ -915,6 +1105,7 @@ class SelectedPreSubmitTerminalFacts:
     lease: SelectedPreSubmitLeaseFacts
     outcome: Literal["completed", "infrastructure_failed"]
     execution: SelectedPreSubmitExecutionFacts | None
+    invocation_receipt: SelectedPreSubmitInvocationReceipt | None
     infrastructure_failure_code: str | None
     queued_at: datetime
     started_at: datetime
@@ -933,6 +1124,7 @@ def __post_init__(self) -> None:
             )
         ) or not (self.queued_at <= self.started_at <= self.completed_at):
             raise ValueError("selected PRE terminal timing is invalid")
+        SelectedPreSubmitFinalizeFacts(self.lease, self.execution, self.invocation_receipt, self.infrastructure_failure_code)
         if self.outcome == "completed":
             if (
                 type(self.execution) is not SelectedPreSubmitExecutionFacts
@@ -954,7 +1146,7 @@ def __post_init__(self) -> None:
     def canonical_body(self) -> dict[str, object]:
         """Return persisted latency, lease and terminal facts without private paths."""
         return {
-            "schema_version": "workstream.selected_pre_submit_terminal.v2",
+            "schema_version": "workstream.selected_pre_submit_terminal.v3",
             "reservation": self.lease.reservation.canonical_body(),
             "request_digest": self.lease.reservation.request_digest,
             "lease_id": str(self.lease.lease_id),
@@ -962,6 +1154,7 @@ def canonical_body(self) -> dict[str, object]:
             "lease_expires_at": self.lease.lease_expires_at.isoformat(),
             "outcome": self.outcome,
             "execution": self.execution.canonical_body() if self.execution else None,
+            "invocation_receipt": self.invocation_receipt.canonical_body() if self.invocation_receipt is not None else None,
             "infrastructure_failure_code": self.infrastructure_failure_code,
             "queued_at": self.queued_at.isoformat(),
             "started_at": self.started_at.isoformat(),
@@ -972,6 +1165,127 @@ def canonical_body(self) -> dict[str, object]:
 
     @classmethod
     def from_canonical_body(cls, body: object) -> SelectedPreSubmitTerminalFacts:
+        """Parse and revalidate every persisted lease, result and timing fact."""
+        if (
+            type(body) is not dict
+            or set(body)
+            != {
+                "schema_version",
+                "reservation",
+                "request_digest",
+                "lease_id",
+                "lease_generation",
+                "lease_expires_at",
+                "outcome",
+                "execution",
+                "invocation_receipt",
+                "infrastructure_failure_code",
+                "queued_at",
+                "started_at",
+                "completed_at",
+                "queue_latency_ms",
+                "execution_latency_ms",
+            }
+            or body["schema_version"] != "workstream.selected_pre_submit_terminal.v3"
+        ):
+            raise ValueError("selected PRE terminal facts are invalid")
+        reservation = SelectedPreSubmitReservationFacts.from_canonical_body(body["reservation"])
+        if body["request_digest"] != reservation.request_digest:
+            raise ValueError("selected PRE terminal request is invalid")
+        execution_body = body["execution"]
+        value = cls(
+            lease=SelectedPreSubmitLeaseFacts(
+                reservation=reservation,
+                lease_id=UUID(str(body["lease_id"])),
+                lease_generation=body["lease_generation"],
+                lease_expires_at=datetime.fromisoformat(body["lease_expires_at"]),
+            ),
+            outcome=body["outcome"],
+            execution=(
+                SelectedPreSubmitExecutionFacts.from_canonical_body(execution_body)
+                if execution_body is not None
+                else None
+            ),
+            invocation_receipt=(SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body["invocation_receipt"], allow_nan=False)) if body["invocation_receipt"] is not None else None),
+            infrastructure_failure_code=body["infrastructure_failure_code"],
+            queued_at=datetime.fromisoformat(body["queued_at"]),
+            started_at=datetime.fromisoformat(body["started_at"]),
+            completed_at=datetime.fromisoformat(body["completed_at"]),
+        )
+        if value.canonical_body() != body:
+            raise ValueError("selected PRE terminal facts are invalid")
+        return value
+
+    @property
+    def terminal_digest(self) -> str:
+        """Bind the exact terminal body used by replay and admission."""
+        return canonical_json_hash(self.canonical_body())
+
+
+@dataclass(frozen=True, slots=True)
+class HistoricalSourcePreSubmitTerminal:
+    """Read-only source-v2 terminal evidence; never current finalization authority."""
+
+    lease: SelectedPreSubmitLeaseFacts
+    outcome: Literal["completed", "infrastructure_failed"]
+    execution: SelectedPreSubmitExecutionFacts | None
+    infrastructure_failure_code: str | None
+    queued_at: datetime
+    started_at: datetime
+    completed_at: datetime
+
+    def __post_init__(self) -> None:
+        """Keep work findings separate from recoverable infrastructure outcomes."""
+        if type(self.lease) is not SelectedPreSubmitLeaseFacts:
+            raise ValueError("selected PRE terminal lease is invalid")
+        if any(
+            value.tzinfo is None
+            for value in (
+                self.queued_at,
+                self.started_at,
+                self.completed_at,
+            )
+        ) or not (self.queued_at <= self.started_at <= self.completed_at):
+            raise ValueError("selected PRE terminal timing is invalid")
+        if self.outcome == "completed":
+            if (
+                type(self.execution) is not SelectedPreSubmitExecutionFacts
+                or self.infrastructure_failure_code is not None
+                or self.execution.policy_sha256 != self.lease.reservation.policy_sha256
+            ):
+                raise ValueError("selected PRE completed outcome is invalid")
+            self.execution.validate_lease(self.lease)
+        elif (self.outcome != "infrastructure_failed" or self.execution is not None
+              or self.infrastructure_failure_code not in {
+            "capacity_exceeded",
+            "deadline_exceeded",
+            "material_unavailable",
+            "implementation_unavailable",
+            "invalid_output",
+        }):
+            raise ValueError("selected PRE infrastructure outcome is invalid")
+
+    def canonical_body(self) -> dict[str, object]:
+        """Return persisted latency, lease and terminal facts without private paths."""
+        return {
+            "schema_version": "workstream.selected_pre_submit_terminal.v2",
+            "reservation": self.lease.reservation.canonical_body(),
+            "request_digest": self.lease.reservation.request_digest,
+            "lease_id": str(self.lease.lease_id),
+            "lease_generation": self.lease.lease_generation,
+            "lease_expires_at": self.lease.lease_expires_at.isoformat(),
+            "outcome": self.outcome,
+            "execution": self.execution.canonical_body() if self.execution else None,
+            "infrastructure_failure_code": self.infrastructure_failure_code,
+            "queued_at": self.queued_at.isoformat(),
+            "started_at": self.started_at.isoformat(),
+            "completed_at": self.completed_at.isoformat(),
+            "queue_latency_ms": (self.started_at - self.queued_at) // timedelta(milliseconds=1),
+            "execution_latency_ms": (self.completed_at - self.started_at) // timedelta(milliseconds=1),
+        }
+
+    @classmethod
+    def from_canonical_body(cls, body: object) -> HistoricalSourcePreSubmitTerminal:
         """Parse and revalidate every persisted lease, result and timing fact."""
         if (
             type(body) is not dict
@@ -1105,7 +1419,7 @@ class SelectedPreSubmitRunView:
     archive_byte_count: int
     queued_at: datetime
     completed_at: datetime | None
-    terminal: SelectedPreSubmitTerminalFacts | HistoricalSelectedPreSubmitTerminal | None
+    terminal: SelectedPreSubmitTerminalFacts | HistoricalSourcePreSubmitTerminal | HistoricalSelectedPreSubmitTerminal | None
 
 
 class SelectedPreSubmitRunReadPort(Protocol):
@@ -1130,6 +1444,10 @@ async def read_project_runs(
     "derive_selected_pre_submit_default_input",
     "derive_selected_pre_submit_input",
     "ExternalPreSubmitIsolationFacts",
+    "ExternalPreSubmitManagedIsolationFacts",
+    "HistoricalSourcePreSubmitTerminal",
+    "SelectedPreSubmitInvocationReceipt",
+    "SelectedPreSubmitInvocationResult",
     "ExternalPreSubmitMemberFacts",
     "PreparedSelectedPreSubmitExecution",
     "PreparedSelectedPreSubmitFinalization",
diff --git a/backend/app/modules/checkers/selected_pre_submit_coordination.py b/backend/app/modules/checkers/selected_pre_submit_coordination.py
index 5e8426df2..c86b377be 100644
--- a/backend/app/modules/checkers/selected_pre_submit_coordination.py
+++ b/backend/app/modules/checkers/selected_pre_submit_coordination.py
@@ -21,6 +21,7 @@
     SelectedPreSubmitCurrentFacts,
     SelectedPreSubmitExecuteFacts,
     SelectedPreSubmitExecutionFacts,
+    SelectedPreSubmitInvocationReceipt,
     SelectedPreSubmitFinalizeFacts,
     SelectedPreSubmitLeaseFacts,
     SelectedPreSubmitReservationFacts,
@@ -29,6 +30,7 @@
     SelectedPreSubmitUnavailable,
 )
 from app.modules.checkers.models import SelectedPreSubmitRun
+from app.modules.checkers.selected_pre_submit_records import matches_source_request
 
 
 class SelectedPreSubmitTaskGuard(Protocol):
@@ -183,27 +185,6 @@ def _require_root(session: AsyncSession) -> None:
         raise RuntimeError("selected PRE coordination requires one root transaction")
 
 
-def _matches(row: SelectedPreSubmitRun, facts: SelectedPreSubmitReservationFacts) -> bool:
-    return (
-        row.request_json == facts.canonical_body()
-        and row.request_digest == facts.request_digest
-        and row.id == str(facts.attempt_id)
-        and row.actor_profile_id == str(facts.actor_profile_id)
-        and row.identity_link_id == str(facts.identity_link_id)
-        and row.project_id == str(facts.project_id)
-        and row.task_id == str(facts.task_id)
-        and row.assignment_id == str(facts.assignment_id)
-        and row.idempotency_key == str(facts.idempotency_key)
-        and row.source_operation_id == str(facts.source.location.operation_id)
-        and row.prepared_generation_id is None
-        and row.policy_sha256 == facts.policy_sha256
-        and row.default_behavior_sha256 == facts.default_behavior_sha256
-        and row.default_input_sha256 is None
-        and row.archive_sha256 == facts.archive_sha256
-        and row.archive_byte_count == facts.archive_byte_count
-        and row.semantic_manifest_sha256 is None
-        and row.execution_budget_ms == facts.execution_budget_ms
-    )
 
 
 class SelectedPreSubmitCoordinator:
@@ -245,6 +226,8 @@ async def read_current(
             return None
         if row.request_json.get("schema_version") != "workstream.selected_pre_submit_reservation.v2":
             raise SelectedPreSubmitRequestConflict("selected_pre_submit_request_conflict")
+        if row.terminal_json is not None and row.terminal_json.get("schema_version") != "workstream.selected_pre_submit_terminal.v3":
+            raise SelectedPreSubmitRequestConflict("selected_pre_submit_request_conflict")
         try:
             stored = SelectedPreSubmitReservationFacts.from_canonical_body(
                 row.request_json
@@ -264,7 +247,7 @@ async def read_current(
             ) from None
         if (
             normalized != stored
-            or not _matches(row, stored)
+            or not matches_source_request(row, stored)
             or row.request_digest != stored.request_digest
             or (
                 terminal is not None
@@ -315,7 +298,7 @@ async def reserve(self, facts: SelectedPreSubmitReservationFacts) -> UUID:
             .execution_options(populate_existing=True)
         )
         if row is not None:
-            if not _matches(row, facts):
+            if not matches_source_request(row, facts):
                 raise SelectedPreSubmitUnavailable("selected_pre_submit_request_conflict")
             return UUID(row.id)
         row = SelectedPreSubmitRun(
@@ -441,6 +424,7 @@ async def finalize(
         lease: SelectedPreSubmitLeaseFacts,
         authority: PreparedSelectedPreSubmitFinalization,
         execution: SelectedPreSubmitExecutionFacts | None,
+        invocation_receipt: SelectedPreSubmitInvocationReceipt | None,
         infrastructure_failure_code: str | None,
     ) -> SelectedPreSubmitCompletion:
         """Fence the lease and persist one exact terminal value under fresh TASK custody."""
@@ -461,6 +445,7 @@ async def finalize(
         finalize_facts = SelectedPreSubmitFinalizeFacts(
             lease=lease,
             execution=execution,
+            invocation_receipt=invocation_receipt,
             infrastructure_failure_code=infrastructure_failure_code,
         )
         evidence = await authority.consume(finalize_facts)
@@ -470,6 +455,7 @@ async def finalize(
             lease=lease,
             outcome=outcome,
             execution=execution,
+            invocation_receipt=invocation_receipt,
             infrastructure_failure_code=infrastructure_failure_code,
             queued_at=row.queued_at,
             started_at=row.started_at,
@@ -526,7 +512,7 @@ async def _lock(
             .with_for_update()
             .execution_options(populate_existing=True)
         )
-        if row is None or not _matches(row, facts):
+        if row is None or not matches_source_request(row, facts):
             raise SelectedPreSubmitUnavailable("selected_pre_submit_run_unavailable")
         return row
 
diff --git a/backend/app/modules/checkers/selected_pre_submit_execution.py b/backend/app/modules/checkers/selected_pre_submit_execution.py
index 70eae9005..3751604f1 100644
--- a/backend/app/modules/checkers/selected_pre_submit_execution.py
+++ b/backend/app/modules/checkers/selected_pre_submit_execution.py
@@ -13,7 +13,7 @@
     ExternalServiceUnavailableError,
 )
 from app.modules.checkers.api.selected_pre_submit import (
-    SelectedPreSubmitExecutionFacts,
+    SelectedPreSubmitInvocationResult,
     SelectedPreSubmitInfrastructureUnavailable,
     SelectedPreSubmitLeaseFacts,
 )
@@ -37,7 +37,7 @@ def abort(self) -> None:
         if self._active is not None:
             self._active.cancel()
 
-    async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmitExecutionFacts:
+    async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmitInvocationResult:
         """Validate returned source, fence and derived requests before finalization."""
         if self._aborted:
             raise asyncio.CancelledError
@@ -49,9 +49,13 @@ async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmi
             # Track it for abort without delegating source custody to a child.
             self._active = asyncio.current_task()
             result = await self._execution.execute_pre(self._lease, grant)
-            if type(result) is not SelectedPreSubmitExecutionFacts:
+            if type(result) is not SelectedPreSubmitInvocationResult:
                 raise ValueError("PRE result is invalid")
             result.validate_lease(self._lease)
+            if result.receipt.adapter_provider_key != self._execution.identity.provider_key:
+                raise ValueError("PRE provider differs")
+            if result.receipt.outcome == "cancelled":
+                raise asyncio.CancelledError
             return result
         except ExternalServiceUnavailableError as exc:
             raise SelectedPreSubmitInfrastructureUnavailable("implementation_unavailable") from exc
diff --git a/backend/app/modules/checkers/selected_pre_submit_reads.py b/backend/app/modules/checkers/selected_pre_submit_reads.py
index c526b65a8..b1608404e 100644
--- a/backend/app/modules/checkers/selected_pre_submit_reads.py
+++ b/backend/app/modules/checkers/selected_pre_submit_reads.py
@@ -7,12 +7,14 @@
 
 from app.modules.checkers.api.selected_pre_submit import (
     SelectedPreSubmitRunStatus, SelectedPreSubmitRunView,
-    SelectedPreSubmitUnavailable,
+    SelectedPreSubmitUnavailable, SelectedPreSubmitReservationFacts,
+    SelectedPreSubmitTerminalFacts, HistoricalSourcePreSubmitTerminal, SelectedPreSubmitLeaseFacts,
 )
 from app.modules.checkers.api.historical_selected_pre_submit import (
     HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal,
 )
 from app.modules.checkers.models import SelectedPreSubmitRun
+from app.modules.checkers.selected_pre_submit_records import matches_source_request
 
 
 def _request_matches(row: SelectedPreSubmitRun, request: HistoricalSelectedPreSubmitReservation) -> bool:
@@ -39,6 +41,20 @@ def _request_matches(row: SelectedPreSubmitRun, request: HistoricalSelectedPreSu
 def _terminal_matches(row: SelectedPreSubmitRun, request, terminal) -> bool:
     """Check retained outcome/lease/timing without conferring current liveness."""
     if terminal is None:
+        if type(request) is SelectedPreSubmitReservationFacts:
+            if row.finalize_evidence_id is not None:
+                return False
+            if row.status == "queued":
+                if (row.lease_id is not None or row.lease_generation != 0
+                        or row.lease_expires_at is not None or row.started_at is not None
+                        or row.execute_evidence_id is not None):
+                    return False
+            elif row.status == "running":
+                SelectedPreSubmitLeaseFacts(request, UUID(str(row.lease_id)),
+                                            row.lease_generation, row.lease_expires_at)
+                if (row.execute_evidence_id is None or row.started_at is None
+                        or not row.queued_at <= row.started_at <= row.lease_expires_at):
+                    return False
         return (
             row.status in {"queued", "running"} and row.terminal_digest is None
             and row.eligible is None and row.completed_at is None
@@ -58,14 +74,25 @@ def _terminal_matches(row: SelectedPreSubmitRun, request, terminal) -> bool:
 
 
 def _view(row: SelectedPreSubmitRun) -> SelectedPreSubmitRunView:
-    """Refuse any divergence between read selectors and retained v1 evidence."""
+    """Decode each retained schema and bind it to the indexed row without issuing authority."""
     try:
-        request = HistoricalSelectedPreSubmitReservation.from_canonical_body(row.request_json)
-        terminal = (
-            HistoricalSelectedPreSubmitTerminal.from_canonical_body(row.terminal_json)
-            if row.terminal_json is not None else None
-        )
-        if not _request_matches(row, request) or not _terminal_matches(row, request, terminal):
+        if (type(row.request_json) is not dict
+                or (row.terminal_json is not None and type(row.terminal_json) is not dict)):
+            raise ValueError("retained PRE body is invalid")
+        if row.request_json.get("schema_version") == "workstream.selected_pre_submit_reservation.v1":
+            request = HistoricalSelectedPreSubmitReservation.from_canonical_body(row.request_json)
+            terminal = HistoricalSelectedPreSubmitTerminal.from_canonical_body(row.terminal_json) if row.terminal_json is not None else None
+            request_matches = _request_matches(row, request)
+        else:
+            request = SelectedPreSubmitReservationFacts.from_canonical_body(row.request_json)
+            if row.terminal_json is None:
+                terminal = None
+            elif row.terminal_json.get("schema_version") == "workstream.selected_pre_submit_terminal.v2":
+                terminal = HistoricalSourcePreSubmitTerminal.from_canonical_body(row.terminal_json)
+            else:
+                terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json)
+            request_matches = matches_source_request(row, request)
+        if not request_matches or not _terminal_matches(row, request, terminal):
             raise ValueError("retained PRE columns differ")
     except (KeyError, TypeError, ValueError):
         raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid") from None
diff --git a/backend/app/modules/checkers/selected_pre_submit_records.py b/backend/app/modules/checkers/selected_pre_submit_records.py
new file mode 100644
index 000000000..485c8a15a
--- /dev/null
+++ b/backend/app/modules/checkers/selected_pre_submit_records.py
@@ -0,0 +1,27 @@
+"""Shared CHECKERS source-row identity validation for writes and retained reads."""
+
+from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitReservationFacts
+from app.modules.checkers.models import SelectedPreSubmitRun
+
+
+def matches_source_request(row: SelectedPreSubmitRun, facts: SelectedPreSubmitReservationFacts) -> bool:
+    return (
+        row.request_json == facts.canonical_body()
+        and row.request_digest == facts.request_digest
+        and row.id == str(facts.attempt_id)
+        and row.actor_profile_id == str(facts.actor_profile_id)
+        and row.identity_link_id == str(facts.identity_link_id)
+        and row.project_id == str(facts.project_id)
+        and row.task_id == str(facts.task_id)
+        and row.assignment_id == str(facts.assignment_id)
+        and row.idempotency_key == str(facts.idempotency_key)
+        and row.source_operation_id == str(facts.source.location.operation_id)
+        and row.prepared_generation_id is None
+        and row.policy_sha256 == facts.policy_sha256
+        and row.default_behavior_sha256 == facts.default_behavior_sha256
+        and row.default_input_sha256 is None
+        and row.archive_sha256 == facts.archive_sha256
+        and row.archive_byte_count == facts.archive_byte_count
+        and row.semantic_manifest_sha256 is None
+        and row.execution_budget_ms == facts.execution_budget_ms
+    )
diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py
index 834567236..bd59b92bd 100644
--- a/backend/tests/artifacts/test_submission_pre_source.py
+++ b/backend/tests/artifacts/test_submission_pre_source.py
@@ -263,16 +263,20 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed):
         await _assert_pre_terminal_guards(intake, request)
 
 
-@pytest.mark.parametrize("version", ["v1", "v2"])
+@pytest.mark.parametrize("version", ["v1", "v2", "v3"])
 async def test_selected_pre_sql_audit_digest_keeps_versioned_custody(isolated_database_env, version):
     from app.core.hashing import canonical_json_hash
     from tests.checkers.external.test_selected_pre_submit_coordination import _retained_v1, _source_reservation
 
     retained = _retained_v1()
     request = retained["request"] if version == "v1" else _source_reservation().canonical_body()
-    terminal = retained["terminal"]
+    terminal = dict(retained["terminal"])
+    if version == "v3":
+        terminal["schema_version"] = "workstream.selected_pre_submit_terminal.v3"
+        # Digest parity is independent of receipt validation, tested by the write guards.
+        terminal["invocation_receipt"] = {"provider_invocation_id": "digest-sensitivity-probe"}
     execute = {
-        "schema_version": f"workstream.selected_pre_submit_execute.{version}",
+        "schema_version": f"workstream.selected_pre_submit_execute.{'v1' if version == 'v1' else 'v2'}",
         "reservation": request, "lease_id": terminal["lease_id"],
         "lease_generation": terminal["lease_generation"], "lease_expires_at": terminal["lease_expires_at"],
     }
@@ -282,7 +286,7 @@ async def test_selected_pre_sql_audit_digest_keeps_versioned_custody(isolated_da
         "execute_facts_digest": expected_execute,
         "execution": terminal["execution"],
         "infrastructure_failure_code": terminal["infrastructure_failure_code"],
-    })
+    } | ({"invocation_receipt": terminal["invocation_receipt"]} if version == "v3" else {}))
     value = {
         "request_json": request, "lease_id": execute["lease_id"],
         "lease_generation": execute["lease_generation"], "lease_expires_at": execute["lease_expires_at"],
@@ -300,6 +304,32 @@ async def test_selected_pre_sql_audit_digest_keeps_versioned_custody(isolated_da
         await engine.dispose()
 
 
+async def _assert_receipt_migration_refuses_inflight(intake, request, expected_status):
+    """Run the actual migration entry before its DDL over an existing live run."""
+    from pathlib import Path
+    import runpy
+    from alembic.migration import MigrationContext
+    from alembic.operations import Operations
+
+    def upgrade(connection):
+        migration = runpy.run_path(str(Path(__file__).resolve().parents[2] /
+                                      "alembic/versions/0072_pre_invocation_receipts.py"))
+        with Operations.context(MigrationContext.configure(connection)):
+            migration["upgrade"]()
+
+    async with intake.factory.begin() as session:
+        before = await session.scalar(text("SELECT to_jsonb(r) FROM selected_pre_submit_runs r WHERE id=:id"),
+                                      {"id": request.attempt_id})
+        assert before["status"] == expected_status
+        with pytest.raises(DBAPIError, match="drain source PRE runs"):
+            async with session.begin_nested():
+                connection = await session.connection()
+                await connection.run_sync(upgrade)
+        after = await session.scalar(text("SELECT to_jsonb(r) FROM selected_pre_submit_runs r WHERE id=:id"),
+                                     {"id": request.attempt_id})
+        assert after == before
+
+
 async def _assert_pre_terminal_guards(intake, request):
     """Claim with real AUTH, reject rebound terminal updates, then finalize once."""
     from app.modules.actors.api import ServiceIdentity
@@ -311,13 +341,15 @@ async def _assert_pre_terminal_guards(intake, request):
     from app.modules.checkers.models import SelectedPreSubmitRun
 
     await provision_post_submit_service(intake.factory, ServiceIdentity.CHECKER_PRE_SUBMIT)
+    await _assert_receipt_migration_refuses_inflight(intake, request, "queued")
     async with intake.factory.begin() as session:
         async with selected_pre_submit_authority(session).prepare_execution(request) as authority:
             lease = await selected_pre_submit_coordinator(session).claim(
                 run_id=request.attempt_id, facts=request, authority=authority,
             )
+    await _assert_receipt_migration_refuses_inflight(intake, request, "running")
     finalize = SelectedPreSubmitFinalizeFacts(
-        lease=lease, execution=None, infrastructure_failure_code="capacity_exceeded",
+        lease=lease, execution=None, invocation_receipt=None, infrastructure_failure_code="capacity_exceeded",
     )
     for changed in ("lease_id", "lease_expires_at", "started_at", "execute_evidence_id",
                     "schema_version", "reservation", "request_digest", "outcome", "terminal_digest", "extra"):
@@ -327,7 +359,7 @@ async def _assert_pre_terminal_guards(intake, request):
                 row = await session.get(SelectedPreSubmitRun, str(request.attempt_id))
                 now = await session.scalar(text("select clock_timestamp()"))
                 terminal = SelectedPreSubmitTerminalFacts(
-                    lease=lease, outcome="infrastructure_failed", execution=None,
+                    lease=lease, outcome="infrastructure_failed", execution=None, invocation_receipt=None,
                     infrastructure_failure_code="capacity_exceeded", queued_at=row.queued_at,
                     started_at=row.started_at, completed_at=now,
                 ).canonical_body()
@@ -371,16 +403,72 @@ async def _assert_pre_terminal_guards(intake, request):
         async with selected_pre_submit_authority(session).prepare_finalization(finalize) as authority:
             completion = await selected_pre_submit_coordinator(session).finalize(
                 run_id=request.attempt_id, lease=lease, authority=authority,
-                execution=None, infrastructure_failure_code="capacity_exceeded",
+                execution=None, invocation_receipt=None, infrastructure_failure_code="capacity_exceeded",
             )
             assert completion.terminal.outcome == "infrastructure_failed"
             assert completion.capability is None
 
 
+async def _assert_stored_receipt(factory, run_id, terminal):
+    from app.modules.checkers.models import SelectedPreSubmitRun
+    async with factory() as verify:
+        stored = await verify.get(SelectedPreSubmitRun, str(run_id))
+        assert stored.terminal_json == terminal.canonical_body()
+        assert stored.terminal_digest == terminal.terminal_digest
+        assert stored.finalize_evidence_id is not None
+
+
+def _source_runtime(payload, tmp_path, runtime_outcome):
+    """Real intake worker with an explicit simulated project reply or capacity failure."""
+    from contextlib import aclosing
+    from app.interfaces.external_services import ExternalServiceAdapterIdentity
+    from app.modules.checkers.api.selected_pre_submit import (
+        SelectedPreSubmitInfrastructureUnavailable, SelectedPreSubmitInvocationResult,
+    )
+    from tests.checkers.external.test_pre_invocation import receipt_body
+    from tests.test_trusted_intake import _pre_worker, _read
+
+    runtime_errors = []
+    class SourceRuntime:
+        identity = ExternalServiceAdapterIdentity(capability_key="external_checker_execution", provider_key="unix_socket")
+        async def execute_pre(self, lease, grant):
+            try:
+                return await self.run(lease, grant)
+            except Exception:
+                if runtime_outcome == "completed":
+                    import traceback
+                    runtime_errors.append(traceback.format_exc())
+                raise
+
+        async def run(self, lease, grant):
+            async with aclosing(grant.open_source(lease=lease)) as reader:
+                assert b"".join([chunk async for chunk in reader]) == payload
+            if runtime_outcome == "received_failure":
+                body = receipt_body(lease, outcome="infrastructure_failure", reason="capacity_exceeded")
+                body["cleanup"]["disposition"] = "pending"
+                return SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None})
+            if runtime_outcome == "completed":
+                worker, output, reply, actual_lease = _pre_worker(
+                    tmp_path, payload, lease=lease,
+                    isolation_override={"runtime": "smolvm", "isolation_mode": "smol-microvm"},
+                )
+                assert actual_lease is lease
+                worker.run()
+                output.seek(0)
+                project_frame, completion = _read(output), _read(output)
+                assert project_frame["operation"] == "project" and reply.calls == 1
+                assert completion["operation"] == "completed" and output.read() == b""
+                response = receipt_body(lease) | {"execution": completion["payload"]}
+                return SelectedPreSubmitInvocationResult.from_canonical_body(response)
+            raise SelectedPreSubmitInfrastructureUnavailable("capacity_exceeded")
+    return SourceRuntime(), runtime_errors
+
+
 @pytest.mark.parametrize("intake", [True], indirect=True)
 @pytest.mark.parametrize("materializer_enabled", [True, False])
-async def test_source_pre_execution_uses_committed_authorized_local_read(intake, materializer_enabled):
-    """Real source/SQL/AUTH composition with an explicitly failing runtime double."""
+@pytest.mark.parametrize("runtime_outcome", ["transport_failure", "completed", "received_failure"])
+async def test_source_pre_execution_uses_committed_authorized_local_read(intake, materializer_enabled, runtime_outcome, tmp_path):
+    """Real source/SQL/AUTH composition with a worker and simulated project runtime."""
     from contextlib import aclosing
     from app.adapters.artifacts import submission_intake_pre_source_port
     from app.adapters.auth import selected_pre_submit_authority
@@ -396,7 +484,6 @@ async def test_source_pre_execution_uses_committed_authorized_local_read(intake,
     )
     from app.modules.authorization.catalogue import ActionId
     from app.modules.checkers.api.pre_submit_material import SubmissionPacketView
-    from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable
     from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest
     from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest
     from tests.artifact_store_helpers import initialize_local_store
@@ -404,6 +491,12 @@ async def test_source_pre_execution_uses_committed_authorized_local_read(intake,
     from tests.checkers.execution.support import provision_post_submit_service
     from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation
 
+    from tests.test_trusted_intake import _archive
+
+    payload = _archive() if runtime_outcome == "completed" else b"original source bytes"
+    async def upload_bytes():
+        yield payload
+
     store = initialize_local_store(root=intake.durable_root, buffer_bytes=256 * 1024)
     async with intake.factory.begin() as session:
         row = await reserve(intake, session, with_upload=False)
@@ -411,7 +504,7 @@ async def test_source_pre_execution_uses_committed_authorized_local_read(intake,
         metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
         key = UUID(row.idempotency_key)
     source = await foreground_upload(intake, store).receive(
-        operation, foreground_lease, 1, foreground_bytes(), **foreground_limits(),
+        operation, foreground_lease, 1, upload_bytes(), **foreground_limits(),
     )
     async with intake.factory.begin() as session:
         task = await task_submission_context_port(session).lock_submission_context(
@@ -463,11 +556,7 @@ async def chunks():
                             observed.append(chunk)
                             yield chunk
                 return chunks()
-        class RuntimeFailure:
-            async def execute_pre(self, lease, grant):
-                async with aclosing(grant.open_source(lease=lease)) as reader:
-                    assert b"".join([chunk async for chunk in reader]) == b"original source bytes"
-                raise SelectedPreSubmitInfrastructureUnavailable("capacity_exceeded")
+        runtime, runtime_errors = _source_runtime(payload, tmp_path, runtime_outcome)
         authority = PreparedPreSubmitMaterializationAuthorization(
             session, request_id=new_record_id(), correlation_id=new_record_id(),
         )
@@ -477,12 +566,74 @@ async def execute_pre(self, lease, grant):
             source_reads=SelectedPreSubmitSourceReads(
                 session=session, sources=submission_intake_pre_source_port(session),
                 authority=authority, store=ObservedStore(),
-            ), execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=RuntimeFailure()),
+            ), execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime),
         )
         result = await service.execute(reservation=request)
-        assert result.capability is None and result.terminal.outcome == "infrastructure_failed"
-        assert result.terminal.infrastructure_failure_code == (
-            "capacity_exceeded" if materializer_enabled else "material_unavailable"
-        )
+        assert not runtime_errors, "\n".join(runtime_errors)
+        if runtime_outcome == "completed" and materializer_enabled:
+            assert result.terminal.outcome == "completed", result.terminal.infrastructure_failure_code
+            # Source receipt retention does not issue the removed prepared-bundle handoff.
+            assert result.capability is None
+            assert result.terminal.execution.eligible
+            assert result.terminal.invocation_receipt is not None
+            await _assert_stored_receipt(intake.factory, request.attempt_id, result.terminal)
+        else:
+            assert result.capability is None and result.terminal.outcome == "infrastructure_failed"
+            assert result.terminal.infrastructure_failure_code == (
+                "capacity_exceeded" if materializer_enabled else "material_unavailable"
+            )
+            if runtime_outcome == "received_failure" and materializer_enabled:
+                assert result.terminal.invocation_receipt.cleanup.disposition == "pending"
+                await _assert_stored_receipt(intake.factory, request.attempt_id, result.terminal)
     assert bool(observed) == materializer_enabled
     store.close()
+
+
+@pytest.mark.parametrize("changed", [None, "source", "fence", "profile", "outcome", "timing", "cleanup", "extra", "missing"])
+async def test_selected_pre_sql_validates_received_failure_receipt(isolated_database_env, changed):
+    """Exercise the SQL receipt guard directly; this is not a real worker proof."""
+    from app.core.identifiers import new_record_id
+    from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts
+    from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation
+    from tests.checkers.external.test_pre_invocation import receipt_body
+
+    request = _source_reservation()
+    lease = SelectedPreSubmitLeaseFacts(request, new_record_id(), 1, request.pre_deadline_at)
+    receipt = receipt_body(lease, outcome="infrastructure_failure", reason="capacity_exceeded")
+    if changed == "source":
+        receipt["invocation"]["source_sha256"] = "sha256:" + "f" * 64
+    elif changed == "fence":
+        receipt["invocation"]["lease_generation"] = 2
+    elif changed == "profile":
+        receipt["runtime"]["profile"]["aggregate_deadline_ms"] += 1
+    elif changed == "outcome":
+        receipt["outcome"] = None
+    elif changed == "timing":
+        receipt["timings_ms"]["total"] = 9
+    elif changed == "cleanup":
+        receipt["cleanup"]["obligation_id"] = "other-invocation"
+    elif changed == "extra":
+        receipt["cleanup"]["host_path"] = "/private"
+    terminal = {"invocation_receipt": receipt, "infrastructure_failure_code": "capacity_exceeded"}
+    if changed == "missing":
+        terminal.pop("invocation_receipt")
+    value = {
+        "id": str(request.attempt_id), "source_operation_id": str(request.source.location.operation_id),
+        "request_json": request.canonical_body(), "request_digest": request.request_digest,
+        "lease_id": str(lease.lease_id), "lease_generation": lease.lease_generation,
+        "status": "infrastructure_failed", "terminal_json": terminal,
+    }
+    engine = create_async_engine(isolated_database_env)
+    try:
+        async with engine.connect() as connection:
+            async def invoke():
+                await connection.execute(text("""SELECT public.require_selected_pre_invocation(
+                    jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)))"""),
+                    {"value": json.dumps(value)})
+            if changed is None:
+                await invoke()
+            else:
+                with pytest.raises(DBAPIError, match="selected PRE invocation"):
+                    await invoke()
+    finally:
+        await engine.dispose()
diff --git a/backend/tests/checkers/external/test_pre_invocation.py b/backend/tests/checkers/external/test_pre_invocation.py
new file mode 100644
index 000000000..dc46db16f
--- /dev/null
+++ b/backend/tests/checkers/external/test_pre_invocation.py
@@ -0,0 +1,244 @@
+"""Receipt contract proof with synthetic, unqualified provider observations."""
+import json
+from copy import deepcopy
+from dataclasses import replace
+
+import pytest
+
+from app.core.hashing import canonical_json_hash
+from app.core.identifiers import new_record_id
+from app.modules.checkers.api.selected_pre_submit import (
+    SelectedPreSubmitFinalizeFacts, SelectedPreSubmitInvocationReceipt,
+    SelectedPreSubmitInvocationResult, SelectedPreSubmitLeaseFacts,
+)
+from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation
+
+
+def receipt_body(lease, *, outcome="completed", reason=None, managed=False):
+    request = lease.reservation
+    profile = request.runtime_profile.model_dump(mode="json")
+    runtime = {"provider": "managed" if managed else "smolvm", "version": "test-only", "profile": profile}
+    cleanup = {"obligation_id": "test-invocation", "disposition": "destroyed"}
+    if managed:
+        runtime["deployment_sha256"] = "sha256:" + "b" * 64
+        cleanup["provider_receipt_sha256"] = "sha256:" + "c" * 64
+    else:
+        runtime.update(binary_sha256="sha256:" + "b" * 64, guest_sha256="sha256:" + "c" * 64)
+        cleanup["journal_sha256"] = "sha256:" + "d" * 64
+    return {
+        "schema_version": "workstream.pre_submit_invocation.v1",
+        "adapter_provider_key": "managed_test" if managed else "unix_socket",
+        "operation": "execute_pre", "phase": "pre_submit",
+        "invocation": {
+            "operation": "execute_pre", "run_id": str(request.attempt_id),
+            "source_operation_id": str(request.source.location.operation_id),
+            "request_digest": request.request_digest, "source_sha256": request.source.source_sha256(),
+            "profile_sha256": canonical_json_hash(profile),
+            "image_digest": request.policy.entries[0].registry.image_digest,
+            "config_image_id": "sha256:" + "a" * 64,
+            "lease_id": str(lease.lease_id), "lease_generation": lease.lease_generation,
+        },
+        "provider_invocation_id": "test-invocation", "outcome": outcome, "reason": reason,
+        "runtime": runtime, "cleanup": cleanup,
+        "timings_ms": {"admission": 1, "preparation": 2, "execution": 3, "cleanup": 4, "total": 10},
+    }
+
+
+@pytest.fixture
+def lease():
+    request = _source_reservation()
+    return SelectedPreSubmitLeaseFacts(request, new_record_id(), 1, request.pre_deadline_at)
+
+
+@pytest.mark.parametrize("managed", [False, True])
+@pytest.mark.parametrize("disposition", ["destroyed", "pending"])
+@pytest.mark.parametrize("outcome,reason", [
+    ("infrastructure_failure", "capacity_exceeded"), ("deadline_exceeded", "deadline_exceeded"),
+])
+def test_received_failure_retains_receipt_in_authority_digest(lease, managed, disposition, outcome, reason):
+    body = receipt_body(lease, outcome=outcome, reason=reason, managed=managed)
+    body["cleanup"]["disposition"] = disposition
+    receipt = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
+    result = SelectedPreSubmitInvocationResult(receipt, None)
+    result.validate_lease(lease)
+    assert SelectedPreSubmitInvocationResult.from_canonical_body(result.canonical_body()) == result
+    facts = SelectedPreSubmitFinalizeFacts(lease, None, receipt, reason)
+    assert facts.facts_digest != replace(facts, invocation_receipt=None).facts_digest
+    changed = deepcopy(body)
+    changed["cleanup"]["disposition"] = "pending" if disposition == "destroyed" else "destroyed"
+    other = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(changed))
+    assert replace(facts, invocation_receipt=other).facts_digest != facts.facts_digest
+
+
+@pytest.mark.parametrize("field", ["run_id", "source_operation_id", "request_digest", "source_sha256",
+                                   "profile_sha256", "image_digest", "lease_id", "lease_generation"])
+def test_invocation_cannot_move_between_requests_or_leases(lease, field):
+    body = receipt_body(lease, outcome="infrastructure_failure", reason="invalid_output")
+    body["invocation"][field] = (2 if field == "lease_generation" else str(new_record_id())
+                                 if field.endswith("_id") else "sha256:" + "f" * 64)
+    with pytest.raises(ValueError):
+        SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body)).validate_lease(lease)
+
+
+@pytest.mark.parametrize("change", ["negative", "boolean", "overflow", "sum", "extra", "wrong_cleanup", "outcome"])
+def test_receipt_rejects_malformed_observations(lease, change):
+    body = receipt_body(lease)
+    if change in {"negative", "boolean", "overflow"}:
+        body["timings_ms"]["total"] = {"negative": -1, "boolean": True, "overflow": 14400001}[change]
+    elif change == "sum":
+        body["timings_ms"]["total"] = 9
+    elif change == "extra":
+        body["cleanup"]["path"] = "/host/private"
+    elif change == "wrong_cleanup":
+        body["cleanup"]["obligation_id"] = "other-invocation"
+    else:
+        body["reason"] = "invalid_output"
+    with pytest.raises(ValueError):
+        SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
+
+
+@pytest.mark.parametrize("managed", [False, True])
+def test_completed_worker_is_bound_to_provider_receipt(managed):
+    from app.modules.checkers.api.selected_pre_submit import ExternalPreSubmitManagedIsolationFacts
+    from tests.checkers.external.test_selected_pre_submit_coordination import _source_completed_execution
+
+    request = _source_reservation()
+    execution = _source_completed_execution(request)
+    lease = SelectedPreSubmitLeaseFacts(request, execution.lease_id, execution.lease_generation, request.pre_deadline_at)
+    body = receipt_body(lease, managed=managed)
+    if managed:
+        member = execution.external_members[0]
+        isolation = ExternalPreSubmitManagedIsolationFacts(
+            provider="managed", platform_manifest_digest=member.isolation.platform_manifest_digest,
+            config_image_id=member.isolation.config_image_id, deployment_sha256=body["runtime"]["deployment_sha256"],
+        )
+        execution = replace(execution, external_members=(replace(member, isolation=isolation),))
+    receipt = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
+    SelectedPreSubmitInvocationResult(receipt, execution).validate_lease(lease)
+    assert SelectedPreSubmitFinalizeFacts(lease, execution, receipt, None).execution == execution
+    body["invocation"]["config_image_id"] = "sha256:" + "f" * 64
+    forged = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
+    with pytest.raises(ValueError, match="image configuration"):
+        SelectedPreSubmitInvocationResult(forged, execution).validate_lease(lease)
+    with pytest.raises(ValueError):
+        SelectedPreSubmitInvocationResult(receipt, None)
+
+
+@pytest.mark.parametrize("version,status", [
+    ("v2", "queued"), ("v2", "running"), ("v2", "completed"),
+    ("v2", "infrastructure_failed"), ("v3", "completed"), ("v3", "infrastructure_failed"),
+])
+def test_source_reads_preserve_schema_and_reject_rebound_columns(version, status):
+    from datetime import UTC, datetime
+    from types import SimpleNamespace
+    from app.modules.checkers.api.selected_pre_submit import (
+        HistoricalSourcePreSubmitTerminal, SelectedPreSubmitTerminalFacts, SelectedPreSubmitUnavailable,
+    )
+    from app.modules.checkers.selected_pre_submit_reads import _view
+    from tests.checkers.external.test_selected_pre_submit_coordination import _source_completed_execution
+
+    request = _source_reservation()
+    execution = _source_completed_execution(request)
+    lease = SelectedPreSubmitLeaseFacts(request, execution.lease_id, execution.lease_generation, request.pre_deadline_at)
+    now = datetime.now(UTC)
+    terminal = None
+    if status in {"completed", "infrastructure_failed"}:
+        failed = status == "infrastructure_failed"
+        values = dict(lease=lease, outcome=status, execution=None if failed else execution,
+                      infrastructure_failure_code="capacity_exceeded" if failed else None,
+                      queued_at=now, started_at=now, completed_at=now)
+        if version == "v2":
+            terminal = HistoricalSourcePreSubmitTerminal(**values)
+        else:
+            body = receipt_body(lease, outcome="infrastructure_failure" if failed else "completed",
+                                reason="capacity_exceeded" if failed else None)
+            terminal = SelectedPreSubmitTerminalFacts(**values,
+                invocation_receipt=SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body)))
+    row = SimpleNamespace(
+        **{key: str(getattr(request, key)) for key in (
+            "actor_profile_id", "identity_link_id", "project_id", "task_id", "assignment_id", "idempotency_key")},
+        **{key: getattr(request, key) for key in (
+            "policy_sha256", "default_behavior_sha256", "archive_sha256", "archive_byte_count", "execution_budget_ms")},
+        id=str(request.attempt_id), source_operation_id=str(request.source.location.operation_id),
+        request_json=request.canonical_body(), request_digest=request.request_digest,
+        prepared_generation_id=None, default_input_sha256=None, semantic_manifest_sha256=None,
+        execute_evidence_id=str(new_record_id()) if status != "queued" else None,
+        finalize_evidence_id=str(new_record_id()) if terminal else None,
+        status=status, terminal_json=terminal.canonical_body() if terminal else None,
+        terminal_digest=terminal.terminal_digest if terminal else None,
+        lease_id=str(lease.lease_id) if status != "queued" else None,
+        lease_generation=lease.lease_generation if status != "queued" else 0,
+        lease_expires_at=lease.lease_expires_at if status != "queued" else None,
+        eligible=True if status == "completed" else None,
+        queued_at=now, started_at=now if status != "queued" else None,
+        completed_at=now if terminal else None,
+    )
+    assert _view(row).terminal == terminal
+    if terminal is None:
+        original = row.lease_generation
+        row.lease_generation = -1
+        with pytest.raises(SelectedPreSubmitUnavailable):
+            _view(row)
+        row.lease_generation = original
+    row.source_operation_id = str(new_record_id())
+    with pytest.raises(SelectedPreSubmitUnavailable):
+        _view(row)
+
+
+def test_python_decodes_shared_production_rust_wire_fixture():
+    from datetime import datetime
+    from pathlib import Path
+    from uuid import UUID
+    from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitReservationFacts
+
+    path = Path(__file__).resolve().parents[4] / "external_checkers/workstream-checker-service/tests/fixtures/pre_invocation.json"
+    fixture = json.loads(path.read_text())
+    import os
+    emitted = os.environ.get("WORKSTREAM_PRE_RECEIPT_WIRE_FILE")
+    wire = json.loads(Path(emitted).read_bytes()) if emitted else fixture["wire"]
+    assert wire == fixture["wire"]
+    assert "adapter_provider_key" not in wire
+    request = SelectedPreSubmitReservationFacts.from_canonical_body(fixture["reservation"])
+    lease = SelectedPreSubmitLeaseFacts(
+        request, UUID(wire["invocation"]["lease_id"]), wire["invocation"]["lease_generation"],
+        datetime.fromisoformat(fixture["lease_expires_at"]),
+    )
+    # The real Unix-socket adapter attaches its trusted factory identity.
+    result = SelectedPreSubmitInvocationResult.from_canonical_body(wire | {"adapter_provider_key": "unix_socket"})
+    result.validate_lease(lease)
+    assert result.execution.eligible and result.receipt.cleanup.disposition == "destroyed"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("case", ["received_failure", "wrong_factory", "cancelled"])
+async def test_managed_port_retains_receipt_and_enforces_selected_factory(lease, case):
+    import asyncio
+    from app.interfaces.external_services import ExternalServiceAdapterIdentity
+    from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable
+    from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor
+
+    body = receipt_body(lease, managed=True,
+        outcome="cancelled" if case == "cancelled" else "infrastructure_failure",
+        reason="cancelled" if case == "cancelled" else "capacity_exceeded")
+    body["cleanup"]["disposition"] = "pending"
+    result = SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None})
+    grant = object()
+
+    class ManagedAdapter:
+        identity = ExternalServiceAdapterIdentity("external_checker_execution",
+            "other_provider" if case == "wrong_factory" else "managed_test")
+
+        async def execute_pre(self, actual_lease, actual_grant):
+            assert actual_lease == lease and actual_grant is grant
+            return result
+
+    processor = SelectedPreSubmitProcessor(lease=lease, execution=ManagedAdapter())
+    if case == "cancelled":
+        with pytest.raises(asyncio.CancelledError):
+            await processor.process(grant)
+    elif case == "wrong_factory":
+        with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="invalid_output"):
+            await processor.process(grant)
+    else:
+        assert await processor.process(grant) == result
+        assert "journal_sha256" not in result.receipt.canonical_body()["cleanup"]
diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py
index e8314d58c..8ad00ae83 100644
--- a/backend/tests/checkers/external/test_runtime.py
+++ b/backend/tests/checkers/external/test_runtime.py
@@ -1120,7 +1120,7 @@ async def test_public_trace_preserves_execution_arguments(monkeypatch, tmp_path,
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing", "chunk_oversized", "slow_decode"])
+@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing", "chunk_oversized", "slow_decode", "managed_runtime", "provider_from_wire"])
 async def test_single_pre_transport_streams_source_and_validates_combined_result(tmp_path, monkeypatch, changed):
     from dataclasses import replace
     from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts
@@ -1140,9 +1140,14 @@ async def test_single_pre_transport_streams_source_and_validates_combined_result
     lease = SelectedPreSubmitLeaseFacts(
         reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at,
     )
-    body = execution.canonical_body()
+    from tests.checkers.external.test_pre_invocation import receipt_body
+    body = receipt_body(lease, managed=changed == "managed_runtime")
+    body.pop("adapter_provider_key")
+    if changed == "provider_from_wire":
+        body["adapter_provider_key"] = "unix_socket"
+    body["execution"] = execution.canonical_body()
     if changed == "result_fence":
-        body["lease_generation"] += 1
+        body["invocation"]["lease_generation"] += 1
     received = bytearray()
     sizes = []
     finished = asyncio.Event()
@@ -1209,7 +1214,7 @@ def delayed_decode(cls, value):
     processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter)
     try:
         if changed is None:
-            assert await processor.process(grant) == execution
+            assert (await processor.process(grant)).execution == execution
             assert bytes(received) == payload
             assert sizes and max(sizes) <= 64 * 1024
             with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="material_unavailable"):
diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
index e01c5e60d..0850a569f 100644
--- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
+++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
@@ -825,6 +825,14 @@ def test_source_first_profile_rejects_archive_time_beyond_aggregate() -> None:
         }))
 
 
+def _source_receipt(lease):
+    import json
+    from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInvocationReceipt
+    from tests.checkers.external.test_pre_invocation import receipt_body
+
+    return SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(receipt_body(lease)))
+
+
 def _source_completed_execution(reservation):
     """Build structural result evidence; this fixture does not attest a runtime."""
     from app.modules.checkers.api.selected_pre_submit import (
@@ -863,7 +871,8 @@ def _source_completed_execution(reservation):
             registry_entry_digest=selected.registry.entry_digest, request_digest=request.request_digest,
             result=result, isolation=ExternalPreSubmitIsolationFacts(**(
                 old["external_members"][0]["isolation"] |
-                {"platform_manifest_digest": selected.registry.image_digest}
+                {"platform_manifest_digest": selected.registry.image_digest,
+                 "runtime": "smolvm", "isolation_mode": "smol-microvm"}
             )),
         ),),
     )
@@ -905,9 +914,9 @@ def test_source_first_finalization_binds_actual_selected_member(changed):
         lease_expires_at=reservation.pre_deadline_at,
     )
     def finalize():
-        return SelectedPreSubmitFinalizeFacts(lease, execution, None)
+        return SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None)
     def terminal():
-        return SelectedPreSubmitTerminalFacts(lease, "completed", execution, None, now, now, now)
+        return SelectedPreSubmitTerminalFacts(lease, "completed", execution, _source_receipt(lease), None, now, now, now)
     if changed is None:
         assert finalize().execution == execution
         value = terminal()
@@ -938,7 +947,7 @@ def test_source_first_default_rejection_does_not_require_project_result():
     lease = SelectedPreSubmitLeaseFacts(
         reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at,
     )
-    assert SelectedPreSubmitFinalizeFacts(lease, execution, None).execution == execution
+    assert SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None).execution == execution
 
 
 @pytest.mark.parametrize("boundary", ["finalization", "terminal"])
@@ -956,9 +965,9 @@ def test_source_first_result_digest_revalidated_before_terminal_write(boundary):
     now = datetime.now(UTC)
     with pytest.raises(ValueError, match="result digest mismatch"):
         if boundary == "finalization":
-            SelectedPreSubmitFinalizeFacts(lease, execution, None)
+            SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None)
         else:
-            SelectedPreSubmitTerminalFacts(lease, "completed", execution, None, now, now, now)
+            SelectedPreSubmitTerminalFacts(lease, "completed", execution, _source_receipt(lease), None, now, now, now)
 
 
 @pytest.mark.parametrize("changed", [
@@ -1012,7 +1021,7 @@ def test_source_first_completed_evidence_rejects_substitution(changed):
             member, request_digest=result.request_digest, result=result,
         ),))
     with pytest.raises(ValueError):
-        SelectedPreSubmitFinalizeFacts(lease, execution, None)
+        SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None)
 
 
 @pytest.mark.parametrize("limit", ["maximum_entries", "maximum_path_bytes", "maximum_entry_bytes"])
@@ -1090,4 +1099,4 @@ def test_source_first_default_blocker_does_not_validate_unrun_project_schema(fai
         workstream_default=WorkstreamDefaultCheckerResult.model_validate(default),
         default_input_sha256=workstream_default_input_sha256(default_input), external_members=(), eligible=False,
     )
-    assert SelectedPreSubmitFinalizeFacts(lease, execution, None).execution == execution
+    assert SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None).execution == execution
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 98ff1818e..04c18a954 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "41e1b52d8d9807e8ca3c1d1975b73f1e338a519ab5b73ee40bfe1e086eb2700d"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "a2fa516d47052e9d1177c15bb602a3d1547ea5fd424e2a9f903427caee6a945c"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/backend/tests/test_trusted_intake.py b/backend/tests/test_trusted_intake.py
index 4c1c30264..2855e0215 100644
--- a/backend/tests/test_trusted_intake.py
+++ b/backend/tests/test_trusted_intake.py
@@ -407,27 +407,35 @@ def unexpected_inspector(*args, **kwargs):
 
 
 
-def _pre_worker(tmp_path, data, *, extra_startup=None, stored_data=None, result_change=None, reservation_change=None):
+def _pre_worker(tmp_path, data, *, extra_startup=None, stored_data=None, result_change=None, reservation_change=None, lease=None, isolation_override=None):
     """Real ZIP/worker with simulated supervisor project result; no VM claim."""
     from app.modules.checkers.api.external import make_external_checker_execution_result
     from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts
     from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation, _retained_v1
 
-    reservation = _source_reservation()
-    reservation = replace(reservation, source=reservation.source.model_copy(update={
-        "raw_sha256": "sha256:" + hashlib.sha256(data).hexdigest(), "raw_byte_count": len(data),
-    }))
-    if reservation_change:
-        reservation = reservation_change(reservation)
-    lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at)
+    if lease is None:
+        reservation = _source_reservation()
+        reservation = replace(reservation, source=reservation.source.model_copy(update={
+            "raw_sha256": "sha256:" + hashlib.sha256(data).hexdigest(), "raw_byte_count": len(data),
+        }))
+        if reservation_change:
+            reservation = reservation_change(reservation)
+        lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at)
+    else:
+        assert reservation_change is None
+        reservation = lease.reservation
+        assert reservation.source.raw_sha256 == "sha256:" + hashlib.sha256(data).hexdigest()
+        assert reservation.source.raw_byte_count == len(data)
     startup = {"operation": "execute_pre", "request": {
         "protocol_version": "external_checker_service.v1", "operation": "execute_pre",
         "reservation": reservation.canonical_body(), "request_digest": reservation.request_digest,
-        "lease_id": str(lease.lease_id), "lease_generation": 1,
+        "lease_id": str(lease.lease_id), "lease_generation": lease.lease_generation,
         "lease_expires_at": lease.lease_expires_at.isoformat(),
     }, "isolation": _retained_v1("selected_pre_v1_completed")["terminal"]["execution"]["external_members"][0]["isolation"] | {
         "platform_manifest_digest": reservation.policy.entries[0].registry.image_digest,
     }}
+    if isolation_override:
+        startup["isolation"].update(isolation_override)
     if extra_startup:
         startup["request"].update(extra_startup)
     archive = tmp_path / "pre.zip"
@@ -456,7 +464,7 @@ def read(self, count):
                     verdict="passed", findings=(), infrastructure_failure_code=None,
                 ).model_dump(mode="json")
                 body = {"request_digest": reservation.request_digest, "lease_id": str(lease.lease_id),
-                        "lease_generation": 1, "result": result}
+                        "lease_generation": lease.lease_generation, "result": result}
                 if result_change:
                     result_change(body)
                 self.reply = BytesIO(_frame(body))
diff --git a/external_checkers/workstream-checker-service/src/smol/pre.rs b/external_checkers/workstream-checker-service/src/smol/pre.rs
index 177c5181f..c2f871a55 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre.rs
@@ -120,16 +120,13 @@ pub(crate) fn serve(
     };
     // Host custody stays outside the worker payload. The backend must retain
     // this invocation envelope along with the typed checker facts at T4.
-    let response = serde_json::json!({
-        "schema_version":"workstream.pre_submit_invocation.v1", "operation":"execute_pre", "phase":"pre_submit",
-        "invocation":prepared.invocation,"provider_invocation_id":machine.lease.name,
-        "outcome":outcome,"reason":reason,"execution":execution,
-        "runtime":{"provider":"smolvm","version":VERSION,"binary_sha256":machine.lease.runtime.binary_sha256,
-            "guest_sha256":machine.lease.runtime.guest_sha256,"profile":prepared.job.startup["request"]["reservation"]["runtime_profile"]},
-        "timings_ms":{"admission":admission_ms,"preparation":preparation_ms,"execution":execution_ms,"cleanup":cleanup_ms,"total":started.elapsed().as_millis() as u64},
-        "cleanup":{"obligation_id":machine.lease.name,"journal_sha256":journal_sha256,"disposition":if destroyed {"destroyed"} else {"pending"}}
-    });
-    let response = serde_json::to_vec(&response).map_err(|_| "PRE response invalid")?;
+    let response = serialize_response(
+        &prepared.invocation, &machine.lease,
+        &prepared.job.startup["request"]["reservation"]["runtime_profile"],
+        (outcome, reason, execution),
+        [admission_ms, preparation_ms, execution_ms, cleanup_ms, started.elapsed().as_millis() as u64],
+        (&journal_sha256, destroyed),
+    )?;
     let sent = if response.len() <= 64 * 1024 * 1024
         && Instant::now() < deadline
         && client_is_connected(&client)
@@ -147,6 +144,27 @@ pub(crate) fn serve(
     }
 }
 
+/// Keep provider custody outside worker facts; portable wire proof uses this serializer.
+fn serialize_response(
+    invocation: &Invocation,
+    lease: &Lease,
+    profile: &Value,
+    result: (&str, Value, Value),
+    timings: [u64; 5],
+    cleanup: (&str, bool),
+) -> Result, String> {
+    let response = serde_json::json!({
+        "schema_version":"workstream.pre_submit_invocation.v1", "operation":"execute_pre", "phase":"pre_submit",
+        "invocation":invocation,"provider_invocation_id":lease.name,
+        "outcome":result.0,"reason":result.1,"execution":result.2,
+        "runtime":{"provider":"smolvm","version":VERSION,"binary_sha256":lease.runtime.binary_sha256,
+            "guest_sha256":lease.runtime.guest_sha256,"profile":profile},
+        "timings_ms":{"admission":timings[0],"preparation":timings[1],"execution":timings[2],"cleanup":timings[3],"total":timings[4]},
+        "cleanup":{"obligation_id":lease.name,"journal_sha256":cleanup.0,"disposition":if cleanup.1 {"destroyed"} else {"pending"}}
+    });
+    serde_json::to_vec(&response).map_err(|_| "PRE response invalid".into())
+}
+
 #[derive(Clone, Debug, Serialize, Deserialize)]
 #[serde(deny_unknown_fields)]
 pub(super) struct Invocation {
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
index 571d5f824..fa0d0c7f2 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
@@ -247,3 +247,30 @@ fn pre_creation_persists_binding_before_guardian_or_runtime() {
     );
     fs::remove_dir_all(root).unwrap();
 }
+
+#[test]
+fn production_serializer_matches_python_receipt_fixture() {
+    // Synthetic provider observations: this proves the shared wire contract,
+    // not Machine creation, isolation, or cleanup on this host.
+    let document: Value = serde_json::from_str(include_str!(
+        "../../../tests/fixtures/pre_invocation.json"
+    )).unwrap();
+    let expected = &document["wire"];
+    let (root, _config, mut lease, _journal) = fixture();
+    lease.name = expected["provider_invocation_id"].as_str().unwrap().into();
+    lease.runtime.binary_sha256 = expected["runtime"]["binary_sha256"].as_str().unwrap().into();
+    lease.runtime.guest_sha256 = expected["runtime"]["guest_sha256"].as_str().unwrap().into();
+    let invocation: Invocation = serde_json::from_value(expected["invocation"].clone()).unwrap();
+    let bytes = serialize_response(
+        &invocation, &lease, &expected["runtime"]["profile"],
+        ("completed", Value::Null, expected["execution"].clone()),
+        [1, 2, 3, 4, 10],
+        (expected["cleanup"]["journal_sha256"].as_str().unwrap(), true),
+    ).unwrap();
+    assert_eq!(serde_json::from_slice::(&bytes).unwrap(), *expected);
+    if let Some(path) = std::env::var_os("WORKSTREAM_PRE_RECEIPT_WIRE_FILE") {
+        // Explicit local cross-language proof consumes these actual Rust bytes.
+        fs::write(path, &bytes).unwrap();
+    }
+    fs::remove_dir_all(root).unwrap();
+}
diff --git a/external_checkers/workstream-checker-service/tests/fixtures/pre_invocation.json b/external_checkers/workstream-checker-service/tests/fixtures/pre_invocation.json
new file mode 100644
index 000000000..54479438a
--- /dev/null
+++ b/external_checkers/workstream-checker-service/tests/fixtures/pre_invocation.json
@@ -0,0 +1,326 @@
+{
+  "reservation": {
+    "schema_version": "workstream.selected_pre_submit_reservation.v2",
+    "actor_profile_id": "01a1d081-9045-703e-b321-a3af5eb248e7",
+    "identity_link_id": "01a1d081-9046-7c5b-8d55-f69f5e2888ad",
+    "project_id": "01a1d081-9047-7565-b9b9-1c9a1b52be0c",
+    "task_id": "01a1d081-9048-7b57-a304-749722a193f5",
+    "assignment_id": "01a1d081-9049-7cba-ad30-ff0a6c524e68",
+    "attempt_id": "01a1d081-904a-7cd6-bf45-c036db3e8925",
+    "idempotency_key": "01a1d081-904b-7d1f-b6a0-02e08d816da2",
+    "foreground_lease_id": "01a1d081-904d-70de-8e80-4c3a59e856b3",
+    "source": {
+      "location": {
+        "operation_id": "01a1d081-904c-7af4-86de-39b1eaf72a71",
+        "namespace_id": "primary",
+        "namespace_fingerprint": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+        "provider_profile": "local-v2"
+      },
+      "provider_generation": "test-generation",
+      "raw_sha256": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+      "raw_byte_count": 1024,
+      "sealed_upload_fence": 1,
+      "media_type": "application/zip"
+    },
+    "source_sha256": "sha256:1367a097f9992e93c264eb38bed1ab998a8bd482b3490fe267341785bcfa32db",
+    "metadata_sha256": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+    "locked_context_sha256": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+    "foreground_lease_generation": 1,
+    "pre_deadline_at": "2026-11-12T16:07:14.438757+00:00",
+    "policy": {
+      "schema_version": "external_pre_submit_policy.v1",
+      "workstream_default": {
+        "checker_id": "workstream.default",
+        "checker_version": "v1",
+        "behavior_sha256": "sha256:af2c604f792c4456d3b222036c772161b1503eace65ff90c3d3a23d9d348c28f"
+      },
+      "entries": [
+        {
+          "requirement_id": "project.archive_rules",
+          "stage": "pre_submit",
+          "registry": {
+            "capability_id": "acme.safe_archive",
+            "capability_version": "v1.2.3",
+            "phase": "pre_submit",
+            "image_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+            "configuration_schema": {
+              "schema_id": "acme.safe_archive.configuration",
+              "schema_version": "v1",
+              "document": {
+                "type": "object",
+                "properties": {},
+                "required": [],
+                "additionalProperties": false
+              },
+              "schema_sha256": "sha256:d746974fa9afd5e951f76f9af38954b0ad7f436f2120dc974da65e5ee39f856f"
+            },
+            "input_schema": {
+              "schema_id": "external_checker_pre_submit_input",
+              "schema_version": "v1",
+              "document": {
+                "type": "object"
+              },
+              "schema_sha256": "sha256:a2c799262a3ce3c19ef5cdd983bf3d12b43ab3c426227091b909dcb7054738c0"
+            },
+            "output_schema": {
+              "schema_id": "external_checker_result",
+              "schema_version": "v1",
+              "document": {
+                "type": "object"
+              },
+              "schema_sha256": "sha256:a2c799262a3ce3c19ef5cdd983bf3d12b43ab3c426227091b909dcb7054738c0"
+            },
+            "resources": {
+              "cpu_millis": 500,
+              "memory_bytes": 134217728,
+              "deadline_ms": 30000,
+              "maximum_output_bytes": 32768
+            },
+            "registry_entry_id": "01a1d081-9007-7185-bd6f-999eb02663a5",
+            "entry_digest": "sha256:2666891954c7e14a486c548a5395991ee5ff92a353495a43baee729779282e2d",
+            "registration_operation_id": "400a1172-5796-4952-bed3-8e3b0904cc35",
+            "registered_by_actor_profile_id": "c27b8967-33ee-4cf9-bcf8-fe287aed107b",
+            "authorization_decision_event_id": "b871ca54-6c5f-4309-9a78-380bdd5c0cf6",
+            "created_at": "2026-11-12T16:05:14.377817Z"
+          },
+          "configuration": {},
+          "configuration_sha256": "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"
+        }
+      ],
+      "policy_sha256": "sha256:1a17480a855a29be12ce3e470fda2fed4b8d95226ed37e12bf29861b1796a7d2"
+    },
+    "default_context": {
+      "predecessor": null,
+      "predecessor_exists": false,
+      "current_predecessor": null,
+      "current_rules_sha256": "sha256:8888888888888888888888888888888888888888888888888888888888888888",
+      "predecessor_rules_sha256": null,
+      "packet": {
+        "summary": "",
+        "contributor_attestation": ""
+      }
+    },
+    "runtime_profile": {
+      "profile_id": "test-only",
+      "platform_root_sha256": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+      "cpu_millis": 2000,
+      "memory_bytes": 2147483648,
+      "temporary_disk_bytes": 4294967296,
+      "maximum_processes": 64,
+      "maximum_output_bytes": 1048576,
+      "maximum_log_bytes": 1048576,
+      "aggregate_deadline_ms": 120000,
+      "archive_limits": {
+        "maximum_entries": 2000,
+        "maximum_path_bytes": 1024,
+        "maximum_path_depth": 32,
+        "maximum_central_directory_bytes": 8388608,
+        "maximum_entry_bytes": 134217728,
+        "maximum_expanded_bytes": 536870912,
+        "maximum_compression_ratio": 100,
+        "maximum_inspection_seconds": 60.0
+      }
+    },
+    "admission_lineage": {
+      "predecessor_submission_id": null,
+      "predecessor_submission_version": null,
+      "checker_remediation_manifest_id": null,
+      "guide_id": "01a1cf4c-d6c4-7ede-add7-f9bd12e64560",
+      "guide_version": "v2",
+      "source_snapshot_id": "01a1cf4c-d6c5-798a-98ae-e349ea3ac7e7",
+      "source_snapshot_sha256": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
+      "locked_guide_sha256": "sha256:2222222222222222222222222222222222222222222222222222222222222222",
+      "effective_policy_id": "01a1cf4c-d6c6-7418-8bca-8e321bc3348e",
+      "effective_policy_sha256": "sha256:3333333333333333333333333333333333333333333333333333333333333333",
+      "pre_submit_policy_id": "01a1cf4c-d6c7-777d-8bdf-eb0e12879148",
+      "pre_submit_policy_sha256": "sha256:4444444444444444444444444444444444444444444444444444444444444444",
+      "effective_plan_sha256": "sha256:1a17480a855a29be12ce3e470fda2fed4b8d95226ed37e12bf29861b1796a7d2",
+      "rules_sha256": "sha256:8888888888888888888888888888888888888888888888888888888888888888",
+      "external_checker_policies_sha256": "sha256:9999999999999999999999999999999999999999999999999999999999999999",
+      "post_submit_policy_sha256": "sha256:ffcd8b8e350f4d11a53731faf9b41c97e09562a78178bdbfb96c300b4994d401",
+      "post_submit_policy_body": {
+        "entries": [],
+        "policy_sha256": "sha256:ffcd8b8e350f4d11a53731faf9b41c97e09562a78178bdbfb96c300b4994d401",
+        "schema_version": "external_post_submit_policy.v1"
+      },
+      "locked_policy_context_hash": "sha256:6666666666666666666666666666666666666666666666666666666666666666",
+      "packet_sha256": "sha256:f2906043a657a5b513767cfd552c88301775c6f663c5d483765d499cb1b3192d",
+      "storage_scheme": "s3"
+    }
+  },
+  "lease_expires_at": "2026-11-12T16:07:14.438757+00:00",
+  "wire": {
+    "schema_version": "workstream.pre_submit_invocation.v1",
+    "operation": "execute_pre",
+    "phase": "pre_submit",
+    "invocation": {
+      "operation": "execute_pre",
+      "run_id": "01a1d081-904a-7cd6-bf45-c036db3e8925",
+      "source_operation_id": "01a1d081-904c-7af4-86de-39b1eaf72a71",
+      "request_digest": "sha256:481aacdca19ea1b3dea7d6ad72c726cfc1ff33a23fb852d9eb09bc0de4b7f72f",
+      "source_sha256": "sha256:1367a097f9992e93c264eb38bed1ab998a8bd482b3490fe267341785bcfa32db",
+      "profile_sha256": "sha256:44c6f836848e2d7f1c500919dc24448ca9d17817b8914a03a185f449c62cdb3e",
+      "image_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+      "config_image_id": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+      "lease_id": "01a1d081-904e-76d9-8737-92b55ae577fc",
+      "lease_generation": 1
+    },
+    "provider_invocation_id": "test-invocation",
+    "outcome": "completed",
+    "reason": null,
+    "runtime": {
+      "provider": "smolvm",
+      "version": "1.31.4",
+      "profile": {
+        "profile_id": "test-only",
+        "platform_root_sha256": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+        "cpu_millis": 2000,
+        "memory_bytes": 2147483648,
+        "temporary_disk_bytes": 4294967296,
+        "maximum_processes": 64,
+        "maximum_output_bytes": 1048576,
+        "maximum_log_bytes": 1048576,
+        "aggregate_deadline_ms": 120000,
+        "archive_limits": {
+          "maximum_entries": 2000,
+          "maximum_path_bytes": 1024,
+          "maximum_path_depth": 32,
+          "maximum_central_directory_bytes": 8388608,
+          "maximum_entry_bytes": 134217728,
+          "maximum_expanded_bytes": 536870912,
+          "maximum_compression_ratio": 100,
+          "maximum_inspection_seconds": 60.0
+        }
+      },
+      "binary_sha256": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "guest_sha256": "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
+    },
+    "cleanup": {
+      "obligation_id": "test-invocation",
+      "disposition": "destroyed",
+      "journal_sha256": "sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
+    },
+    "timings_ms": {
+      "admission": 1,
+      "preparation": 2,
+      "execution": 3,
+      "cleanup": 4,
+      "total": 10
+    },
+    "execution": {
+      "schema_version": "workstream.selected_pre_submit_execution.v2",
+      "request_digest": "sha256:481aacdca19ea1b3dea7d6ad72c726cfc1ff33a23fb852d9eb09bc0de4b7f72f",
+      "lease_id": "01a1d081-904e-76d9-8737-92b55ae577fc",
+      "lease_generation": 1,
+      "observed_source": {
+        "location": {
+          "operation_id": "01a1d081-904c-7af4-86de-39b1eaf72a71",
+          "namespace_id": "primary",
+          "namespace_fingerprint": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+          "provider_profile": "local-v2"
+        },
+        "provider_generation": "test-generation",
+        "raw_sha256": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+        "raw_byte_count": 1024,
+        "sealed_upload_fence": 1,
+        "media_type": "application/zip"
+      },
+      "manifest_body": {
+        "entries": [
+          {
+            "entry_type": "directory",
+            "normalized_path": "evidence"
+          },
+          {
+            "byte_count": 9,
+            "entry_type": "file",
+            "executable": false,
+            "normalized_path": "evidence/results",
+            "sha256": "sha256:672eb8316fec83f94119a4193f9fc552513d56a147502f8be4830e017d817831"
+          },
+          {
+            "byte_count": 20,
+            "entry_type": "file",
+            "executable": false,
+            "normalized_path": "task.toml",
+            "sha256": "sha256:db827bb156a8942c9c3f6f9a6c734959f667f0e84a8682ad1827df1e9cfc0744"
+          }
+        ],
+        "schema_version": "workstream.submission_bundle_manifest.v1"
+      },
+      "manifest_sha256": "sha256:dc88d211b1a40342e06eaaed145c35a1b1e9ca18c000eaf74946677ecabc502e",
+      "default_input_sha256": "sha256:03f00a22258fbcce6665c5b3ab4b833022672b8233085919e67d59ab4cbdf74d",
+      "policy_sha256": "sha256:1a17480a855a29be12ce3e470fda2fed4b8d95226ed37e12bf29861b1796a7d2",
+      "workstream_default": {
+        "schema_version": "workstream.default_checker_result.v1",
+        "checker_id": "workstream.default",
+        "checker_version": "v1",
+        "behavior_sha256": "sha256:af2c604f792c4456d3b222036c772161b1503eace65ff90c3d3a23d9d348c28f",
+        "eligible": true,
+        "checks": [
+          {
+            "check_id": "archive_safe",
+            "status": "passed",
+            "failure_code": null,
+            "finding_count": 0
+          },
+          {
+            "check_id": "received_identity_exact",
+            "status": "passed",
+            "failure_code": null,
+            "finding_count": 0
+          },
+          {
+            "check_id": "high_confidence_secrets_absent",
+            "status": "passed",
+            "failure_code": null,
+            "finding_count": 0
+          },
+          {
+            "check_id": "submission_changed_for_current_rules",
+            "status": "passed",
+            "failure_code": null,
+            "finding_count": 0
+          }
+        ],
+        "warnings": []
+      },
+      "required_external_count": 1,
+      "external_members": [
+        {
+          "order": 0,
+          "requirement_id": "project.archive_rules",
+          "registry_entry_id": "01a1d081-9007-7185-bd6f-999eb02663a5",
+          "registry_entry_digest": "sha256:2666891954c7e14a486c548a5395991ee5ff92a353495a43baee729779282e2d",
+          "request_digest": "sha256:bcfe1e32990cc814b8471c2e0d2626f14fc6a6653bf4d92320d9a27dc01612b6",
+          "result": {
+            "schema_version": "external_checker_result.v1",
+            "request_digest": "sha256:bcfe1e32990cc814b8471c2e0d2626f14fc6a6653bf4d92320d9a27dc01612b6",
+            "registry_entry_id": "01a1d081-9007-7185-bd6f-999eb02663a5",
+            "registry_entry_digest": "sha256:2666891954c7e14a486c548a5395991ee5ff92a353495a43baee729779282e2d",
+            "phase": "pre_submit",
+            "outcome": "completed",
+            "verdict": "passed",
+            "findings": [],
+            "infrastructure_failure_code": null,
+            "result_digest": "sha256:15fbdcc75b46c4cbe09282128b87efb0163d02c364f86c44531bbcc3ce11fda0"
+          },
+          "isolation": {
+            "repository": "registry.example/workstream/checker",
+            "platform_manifest_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+            "platform_manifest_media_type": "application/vnd.oci.image.manifest.v1+json",
+            "platform_manifest_byte_count": 1024,
+            "operating_system": "linux",
+            "architecture": "amd64",
+            "config_image_id": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+            "runtime": "smolvm",
+            "isolation_mode": "smol-microvm",
+            "sandbox_uid": 65532,
+            "sandbox_gid": 65532
+          }
+        }
+      ],
+      "eligible": true
+    }
+  }
+}

From ceeccaaa6bfbeb91f06145031c224013778b8438 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 17:24:33 +0100
Subject: [PATCH 102/513] Bind PRE receipt family to selected adapter and
 register CI proof

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 +++++++++++++++++++
 .../app/adapters/checkers/external_service.py |  6 ++++++
 .../interfaces/external_checker_execution.py  |  7 ++++++-
 .../checkers/selected_pre_submit_execution.py |  3 ++-
 backend/scripts/test_lane_catalogue.py        |  1 +
 .../artifacts/test_submission_pre_source.py   |  4 ++++
 .../checkers/external/test_pre_invocation.py  | 11 +++++++---
 backend/tests/test_ci_lane_catalogue.py       |  9 +++++----
 8 files changed, 52 insertions(+), 9 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 59324138f..d9c7efd2a 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2306,3 +2306,23 @@ actual bytes emitted by the production Rust serializer in a separate portable
 probe. Structural validation and Markdown links pass. Implementation review
 remains required; public submission/acceptance and native qualification remain
 outstanding parts of the overall objective.
+
+Architecture/security and QA review of `a3748997f` found a selected-adapter
+contract gap: a managed adapter could label self-consistent native receipt facts
+with its own matching factory key. The repair adds a read-only expected PRE
+runtime family to the capability and native adapter, and checks both factory key
+and runtime family before AUTH finalization. A managed-port substitution test
+now rejects native evidence. SQL retains its structural/source/fence/profile/
+digest boundary; it cannot independently select a factory because the immutable
+v2 request carries no trusted provider-selection fact. No test-only key mapping
+is added to product SQL.
+
+QA also found the new receipt module missing from explicit CI ownership. It now
+belongs to the existing checker-delivery family, with the independent project
+membership and ownership fingerprints updated. Actual collection selects all
+36 receipt nodes exactly once across the project lifecycle partitions. The
+36 receipt and 12 socket cases pass; all 59 catalogue tests pass after updating
+the separate exact membership expectation. All six affected PostgreSQL outcome
+cases and structural validation also pass after the family-binding repair.
+These repairs require affected review replay. Documentation review passed the original candidate's scoped
+claims; public acceptance and native qualification remain open.
diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index 4b74f8284..87f6c948b 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -8,6 +8,7 @@
 from datetime import datetime, timezone
 from pathlib import Path
 import struct
+from typing import Literal
 
 from pydantic import ValidationError
 
@@ -78,6 +79,11 @@ def identity(self) -> ExternalServiceAdapterIdentity:
         """Return the exact explicitly registered provider identity."""
         return self._identity
 
+    @property
+    def pre_runtime_provider(self) -> Literal["smolvm"]:
+        """The native socket factory accepts only Smol runtime evidence."""
+        return "smolvm"
+
     async def execute_pre(
         self, lease: SelectedPreSubmitLeaseFacts, grant: ExternalPreSubmitSourceGrant,
     ) -> SelectedPreSubmitInvocationResult:
diff --git a/backend/app/interfaces/external_checker_execution.py b/backend/app/interfaces/external_checker_execution.py
index 504d729e5..749d11183 100644
--- a/backend/app/interfaces/external_checker_execution.py
+++ b/backend/app/interfaces/external_checker_execution.py
@@ -5,7 +5,7 @@
 from dataclasses import dataclass, field
 from collections.abc import AsyncGenerator
 import re
-from typing import Protocol
+from typing import Literal, Protocol
 
 from app.interfaces.external_services import ExternalServiceAdapter
 from app.modules.checkers.api.selected_pre_submit import (
@@ -166,6 +166,11 @@ def open_source(self, *, lease: SelectedPreSubmitLeaseFacts) -> AsyncGenerator[b
 class ExternalCheckerExecutionAdapter(ExternalServiceAdapter, Protocol):
     """Execute one normalized request through the trusted checker service."""
 
+    @property
+    def pre_runtime_provider(self) -> Literal["smolvm", "managed"]:
+        """Factory-owned expected PRE evidence family; never taken from a response."""
+        ...
+
     async def execute_pre(
         self, lease: SelectedPreSubmitLeaseFacts, grant: ExternalPreSubmitSourceGrant,
     ) -> SelectedPreSubmitInvocationResult:
diff --git a/backend/app/modules/checkers/selected_pre_submit_execution.py b/backend/app/modules/checkers/selected_pre_submit_execution.py
index 3751604f1..1637e0e86 100644
--- a/backend/app/modules/checkers/selected_pre_submit_execution.py
+++ b/backend/app/modules/checkers/selected_pre_submit_execution.py
@@ -52,7 +52,8 @@ async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmi
             if type(result) is not SelectedPreSubmitInvocationResult:
                 raise ValueError("PRE result is invalid")
             result.validate_lease(self._lease)
-            if result.receipt.adapter_provider_key != self._execution.identity.provider_key:
+            if (result.receipt.adapter_provider_key != self._execution.identity.provider_key
+                    or result.receipt.runtime.provider != self._execution.pre_runtime_provider):
                 raise ValueError("PRE provider differs")
             if result.receipt.outcome == "cancelled":
                 raise asyncio.CancelledError
diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py
index 5f069ddca..56b861a39 100644
--- a/backend/scripts/test_lane_catalogue.py
+++ b/backend/scripts/test_lane_catalogue.py
@@ -549,6 +549,7 @@ class TestLane:
     "tests/checkers/default/test_execution.py",
     "tests/checkers/external/test_contracts.py",
     "tests/checkers/external/test_runtime.py",
+    "tests/checkers/external/test_pre_invocation.py",
     "tests/checkers/external/test_migration.py",
     "tests/checkers/external/test_postgresql.py",
     "tests/checkers/external/test_public_api.py",
diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py
index bd59b92bd..c567e6aa3 100644
--- a/backend/tests/artifacts/test_submission_pre_source.py
+++ b/backend/tests/artifacts/test_submission_pre_source.py
@@ -430,6 +430,10 @@ def _source_runtime(payload, tmp_path, runtime_outcome):
 
     runtime_errors = []
     class SourceRuntime:
+        @property
+        def pre_runtime_provider(self):
+            return "smolvm"
+
         identity = ExternalServiceAdapterIdentity(capability_key="external_checker_execution", provider_key="unix_socket")
         async def execute_pre(self, lease, grant):
             try:
diff --git a/backend/tests/checkers/external/test_pre_invocation.py b/backend/tests/checkers/external/test_pre_invocation.py
index dc46db16f..3ab7848f5 100644
--- a/backend/tests/checkers/external/test_pre_invocation.py
+++ b/backend/tests/checkers/external/test_pre_invocation.py
@@ -210,21 +210,26 @@ def test_python_decodes_shared_production_rust_wire_fixture():
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize("case", ["received_failure", "wrong_factory", "cancelled"])
+@pytest.mark.parametrize("case", ["received_failure", "wrong_factory", "wrong_family", "cancelled"])
 async def test_managed_port_retains_receipt_and_enforces_selected_factory(lease, case):
     import asyncio
     from app.interfaces.external_services import ExternalServiceAdapterIdentity
     from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable
     from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor
 
-    body = receipt_body(lease, managed=True,
+    body = receipt_body(lease, managed=case != "wrong_family",
         outcome="cancelled" if case == "cancelled" else "infrastructure_failure",
         reason="cancelled" if case == "cancelled" else "capacity_exceeded")
+    body["adapter_provider_key"] = "managed_test"
     body["cleanup"]["disposition"] = "pending"
     result = SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None})
     grant = object()
 
     class ManagedAdapter:
+        @property
+        def pre_runtime_provider(self):
+            return "managed"
+
         identity = ExternalServiceAdapterIdentity("external_checker_execution",
             "other_provider" if case == "wrong_factory" else "managed_test")
 
@@ -236,7 +241,7 @@ async def execute_pre(self, actual_lease, actual_grant):
     if case == "cancelled":
         with pytest.raises(asyncio.CancelledError):
             await processor.process(grant)
-    elif case == "wrong_factory":
+    elif case in {"wrong_factory", "wrong_family"}:
         with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="invalid_output"):
             await processor.process(grant)
     else:
diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py
index 83d8571e8..cf65fc718 100644
--- a/backend/tests/test_ci_lane_catalogue.py
+++ b/backend/tests/test_ci_lane_catalogue.py
@@ -101,6 +101,7 @@ def test_checker_delivery_and_routing_preparation_partition_every_node_once() ->
         "tests/checkers/external/test_public_api.py",
         "tests/checkers/external/test_registry.py",
         "tests/checkers/external/test_runtime.py",
+        "tests/checkers/external/test_pre_invocation.py",
         "tests/checkers/external/test_policy.py",
         "tests/checkers/external/test_selected_post_submit.py",
         "tests/checkers/external/test_forge_locator.py",
@@ -321,8 +322,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None:
             "9310a4ccbe9b8d842190a644403c72683ce321f4f7ef83cf35545ab965e17bf1",
         ),
         "project": (
-            255,
-            "8e8f8155a5e3929613fb81e5b6bc8d5ac858aa2578dab559b8f403de6298d87a",
+            256,
+            "65376b7218792edcf026d5f851fb85d909a59ad7df363f6904e04e501ba5118d",
         ),
         "task": (
             94,
@@ -394,9 +395,9 @@ def test_project_lane_ownership_has_an_independent_fingerprint() -> None:
         )
         + "\n"
     )
-    assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 255
+    assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 256
     assert hashlib.sha256(canonical.encode()).hexdigest() == (
-        "3782b6f2df688f48755b50db0295f9660d9960ec7c58e1c1e3659f874f27f909"
+        "ed9527add277491e0b20f495767bdf844cecdffa518ce8854109e3b3bcfbe56b"
     )
 
 

From cbd445d4add98dc2f8e484d488ed75c87acf4843 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 17:30:25 +0100
Subject: [PATCH 103/513] Preserve PRE runtime identity through configured
 execution wrappers

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  9 +++++
 backend/app/adapters/checkers/__init__.py     |  7 ++++
 .../app/adapters/checkers/model_execution.py  |  7 ++++
 .../tests/checkers/external/test_runtime.py   | 38 +++++++++++++++----
 4 files changed, 54 insertions(+), 7 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index d9c7efd2a..86ea6f756 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2326,3 +2326,12 @@ the separate exact membership expectation. All six affected PostgreSQL outcome
 cases and structural validation also pass after the family-binding repair.
 These repairs require affected review replay. Documentation review passed the original candidate's scoped
 claims; public acceptance and native qualification remain open.
+
+Replay at `ceeccaaa6` found the expected-family property was missing from the
+configured execution wrapper and its model-aware wrapper. Both now preserve the
+family, and the socket proof builds the processor through the actual selected
+PRE factory and the configured model-aware factory, refusing any PRE model
+session. All 14 affected socket cases pass after fixture extraction; the earlier
+combined wrapper/receipt run passed 50 cases. Documentation independently ran all
+36 receipt cases on clean `ceeccaaa6`. The composition repair requires affected
+review replay before scoped readiness.
diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py
index 3a80f2de6..59a137d36 100644
--- a/backend/app/adapters/checkers/__init__.py
+++ b/backend/app/adapters/checkers/__init__.py
@@ -1,5 +1,7 @@
 """CHECKER-owned composition adapters."""
 
+from typing import Literal
+
 from app.adapters.checkers.external_service import (
     EXTERNAL_CHECKER_CAPABILITY_KEY,
     EXTERNAL_CHECKER_PROVIDER_KEY,
@@ -167,6 +169,11 @@ def identity(self) -> ExternalServiceAdapterIdentity:
         """Expose the sole provider identity without constructing its transport."""
         return self._identity
 
+    @property
+    def pre_runtime_provider(self) -> Literal["smolvm", "managed"]:
+        """The explicitly selected socket factory supplies native Smol evidence."""
+        return "smolvm"
+
     def _resolve(self) -> ExternalCheckerExecutionAdapter:
         """Create the fixed provider or report absent runtime configuration."""
         if (
diff --git a/backend/app/adapters/checkers/model_execution.py b/backend/app/adapters/checkers/model_execution.py
index 9aa9861d2..459cc1957 100644
--- a/backend/app/adapters/checkers/model_execution.py
+++ b/backend/app/adapters/checkers/model_execution.py
@@ -1,5 +1,7 @@
 """Compose optional project-image model callbacks into the sole POST execution path."""
 
+from typing import Literal
+
 from app.interfaces.external_services import ExternalServiceUnavailableError
 from app.modules.model_usage.api import (
     ModelCallExecutionFacts,
@@ -40,6 +42,11 @@ def identity(self):
         """Keep the same fixed Rust provider identity."""
         return self._execution.identity
 
+    @property
+    def pre_runtime_provider(self) -> Literal["smolvm", "managed"]:
+        """Preserve the selected execution adapter's PRE evidence family."""
+        return self._execution.pre_runtime_provider
+
     async def health(self):
         """Use the existing external execution health contract."""
         return await self._execution.health()
diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py
index 8ad00ae83..8b83d49c7 100644
--- a/backend/tests/checkers/external/test_runtime.py
+++ b/backend/tests/checkers/external/test_runtime.py
@@ -1119,12 +1119,39 @@ async def test_public_trace_preserves_execution_arguments(monkeypatch, tmp_path,
     ]
 
 
+def _pre_transport_processor(lease, socket, changed):
+    """Exercise direct transport and both real production composition wrappers."""
+    from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor
+    adapter = UnixSocketExternalCheckerAdapter(
+        socket_path=socket, timeout_seconds=0.2 if changed == "slow_decode" else 5.0,
+    )
+    if changed in {"configured", "model_wrapper"}:
+        from app.adapters.checkers import (
+            selected_pre_submit_checker_execution, configured_post_submit_external_execution,
+            SelectedPreSubmitCheckerExecutionAdapter,
+        )
+        settings = Settings(
+            external_checker_service_socket=socket,
+            external_checker_material_root=socket.parent / "scratch",
+            artifact_scratch_root=socket.parent / "scratch",
+        )
+        if changed == "configured":
+            processor = selected_pre_submit_checker_execution(settings=settings).build(lease)
+        else:
+            def forbidden_sessions():
+                raise AssertionError("PRE must not request model authority")
+            wrapped = configured_post_submit_external_execution(settings, sessions=forbidden_sessions)
+            processor = SelectedPreSubmitCheckerExecutionAdapter(external_execution=wrapped).build(lease)
+    else:
+        processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter)
+    return processor
+
+
 @pytest.mark.asyncio
-@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing", "chunk_oversized", "slow_decode", "managed_runtime", "provider_from_wire"])
+@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing", "chunk_oversized", "slow_decode", "managed_runtime", "provider_from_wire", "configured", "model_wrapper"])
 async def test_single_pre_transport_streams_source_and_validates_combined_result(tmp_path, monkeypatch, changed):
     from dataclasses import replace
     from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts
-    from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor
     from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInfrastructureUnavailable
     from tests.checkers.external.test_selected_pre_submit_coordination import (
         _source_reservation, _source_completed_execution,
@@ -1208,12 +1235,9 @@ def delayed_decode(cls, value):
     grant = Grant()
     socket = tmp_path / "pre.sock"
     server = await asyncio.start_unix_server(handle, socket)
-    adapter = UnixSocketExternalCheckerAdapter(
-        socket_path=socket, timeout_seconds=0.2 if changed == "slow_decode" else 5.0,
-    )
-    processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter)
+    processor = _pre_transport_processor(lease, socket, changed)
     try:
-        if changed is None:
+        if changed in {None, "configured", "model_wrapper"}:
             assert (await processor.process(grant)).execution == execution
             assert bytes(received) == payload
             assert sizes and max(sizes) <= 64 * 1024

From 58028c472b6f13e3e533883250d01ffe44e537c3 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 17:31:57 +0100
Subject: [PATCH 104/513] Record reviewed PRE receipt retention and composition
 repairs

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md    | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 86ea6f756..3a3d96e91 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2335,3 +2335,15 @@ session. All 14 affected socket cases pass after fixture extraction; the earlier
 combined wrapper/receipt run passed 50 cases. Documentation independently ran all
 36 receipt cases on clean `ceeccaaa6`. The composition repair requires affected
 review replay before scoped readiness.
+
+Architecture/security, QA/test-delta and documentation replay passed clean
+`cbd445d4a`, resolving the missing-wrapper-property finding. Architecture verified
+both configured compositions expose `unix_socket`/`smolvm`; the affected socket
+proof exercises both, including the prohibition on PRE model-session use.
+CI-integrity remains compatible with the unchanged catalogue repair. Earlier
+PostgreSQL and portable-runtime evidence remains scoped compatible evidence,
+not relabeled as exact-head reruns. This closes backend receipt retention and
+its reviewed repairs; it does not complete the initiative. The next concrete
+journey gap is the authorized T4 source-pass handoff, followed by accepted
+finalization/POST and the coordinated public API, CLI and MCP replacement.
+Native qualification/conformance and full acceptance verification remain open.

From 6e5bf08d5dfccb08f4f286d6d2213100a1371beb Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 17:35:14 +0100
Subject: [PATCH 105/513] Plan atomic authorized source submission handoff

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 85 +++++++++++++++++++
 1 file changed, 85 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 3a3d96e91..147ae323e 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2347,3 +2347,88 @@ its reviewed repairs; it does not complete the initiative. The next concrete
 journey gap is the authorized T4 source-pass handoff, followed by accepted
 finalization/POST and the coordinated public API, CLI and MCP replacement.
 Native qualification/conformance and full acceptance verification remain open.
+
+### Atomic accepted source handoff (T4) plan
+
+The reviewed PRE path now ends in an immutable, eligible source-bound terminal,
+but no owner can accept that work: ART permits only foreground/terminal failure
+states, TASK has no authorized intake-to-evaluation transition, and no durable
+finalization event exists. Close that concrete gap with one short composed T4
+transaction. This is a prerequisite for the required single public submission
+command, not a second contributor workflow or an acceptance-by-checker shortcut.
+T5 finalization and the coordinated public/CLI/MCP cutover remain required next
+steps in this same PR; this internal transaction is not exposed until its
+continuation is wired.
+
+Plan and owner boundaries:
+
+- Extend the existing ART intake owner with `finalization_pending`, immutable
+  accepted evidence and a stable accepted receipt. Preserve operation/source
+  identity, the original ZIP generation/SHA/count, command metadata, actor,
+  assignment, predecessor, frozen policies and capacity charges. No placeholder
+  Submission, retained artifact binding or POST dispatch is created at T4.
+- Acquire TASK, intake operation, then CHECKERS run custody in the established
+  order. Add a narrow CHECKERS port to lock and validate the exact current v3
+  completed/eligible run for this source and its lease. It returns immutable
+  facts for T4; raw detached terminal objects and historical v1/v2 evidence
+  cannot confer acceptance. Bind ART's source/manifest identity to those facts.
+- Revalidate current contributor/link/grant authority, task/assignment status,
+  active operation pointer, foreground lease/fence/deadline, predecessor,
+  revision acknowledgement/deadline/cap, locked TASK/PROJECT context and one
+  selected image per phase. Reuse existing canonical context and revision
+  checks; no alternate eligibility calculator or renewed foreground owner.
+- Retain action/permission identity `submission.create`, with a closed
+  operation-scoped acceptance resource and prepared/consumed AUTH facts. Extend
+  the existing AUTH exact-resource dispatch for this lifecycle boundary; do not
+  invent a submission UUID to satisfy the old creation resource. The old
+  prepared-admission public producer is superseded by the later coordinated
+  cutover in this PR, not preserved as a supported compatibility API. Its
+  retained audit/evidence decoding must remain valid.
+- TASK's existing intake custody participant gains a narrowly authorized
+  transition from `in_progress`/`needs_revision` to `evaluation_pending` while
+  preserving the exact pending operation pointer. ART writes accepted state,
+  receipt and authorization provenance; the existing outbox append port writes
+  one unique identifier/digest-only finalization event. These effects and the
+  exact CHECKERS terminal reference must commit or roll back together.
+- Already accepted replay validates immutable operation/evidence/receipt/event
+  associations under current own-operation read authority before returning the
+  stable receipt. It does not require the task to remain contributor-eligible,
+  mint new acceptance, rerun PRE, refresh a lease or consume another revision.
+  Lost commit acknowledgement resolves the same operation in a fresh root;
+  unresolved outcome remains unknown and cannot be reported as known failure.
+- Add migration 0073 without editing 0069–0072. Extend active-owner uniqueness,
+  deferred TASK/intake/assignment closure, state-transition guards and AUTH/
+  outbox closure to protect accepted pending work. Foreground expiration and
+  cleanup must not terminalize or release accepted work. Accepted source,
+  context, receipt, PRE reference and provenance are immutable. Finalizer lease
+  and actual Submission registration belong to T5, not a fabricated T4 result.
+
+Allowed files: ART intake APIs/owner/models/repository/replay and composition;
+TASK intake custody/context/lifecycle ports and composition; CHECKERS exact
+terminal-consumption API/coordinator; AUTH operation-scoped resource, evaluator,
+prepared-handle/audit integration and adapters; outbox event contract/append
+composition; migration 0073; affected real PostgreSQL/owner/AUTH tests and explicit
+CI catalogue/schema fingerprint; this record and directly affected contracts.
+No storage re-upload, host ZIP inspection, new checker factory, POST execution
+redesign, new public alias, retained-row rewrite, qualification default or
+provider deployment is allowed. The finalization event is an internal durable
+contract; registration of its real T5 handler and public exposure must occur
+before this PR is ready.
+
+Risk is L0 authorization/workflow/atomicity. Plan review precedes implementation;
+architecture/security and QA/test-delta review follow deterministic proof, with
+CI-integrity review for catalogue changes and docs review for capability claims.
+Human focus: fresh acceptance authority versus durable accepted continuation,
+exact source/run ownership, rollback/commit uncertainty and revision accounting.
+
+Acceptance proof uses actual ZIP upload, actual CHECKERS claim and receipt-bearing
+worker completion through the existing portable fixture, then T4 on PostgreSQL.
+Require one accepted receipt/event, task `evaluation_pending`, protected source
+and capacity, and no Submission/binding/POST rows. Probe forged/stale or consumed
+run/source/lease, historical terminal, changed packet/context, revoked authority,
+wrong assignment/predecessor/revision acknowledgement, expired deadline, rollback
+at participant boundaries, same-key replay, concurrent acceptance and lost commit
+acknowledgement. Direct SQL probes must reject detached accepted state, missing
+or mismatched decision/event/PRE evidence, accepted mutation and foreground
+cleanup of accepted work. Keep native-provider qualification and public journey
+completion explicitly unproven by these internal portable tests.

From 793598c2f559ef1e114a2aa7c9debcc29e8bf90c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 17:41:33 +0100
Subject: [PATCH 106/513] Clarify accepted authority lifetime and T4 commit
 custody

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 39 +++++++++++++++++++
 1 file changed, 39 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 147ae323e..0c15d9333 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2432,3 +2432,42 @@ acknowledgement. Direct SQL probes must reject detached accepted state, missing
 or mismatched decision/event/PRE evidence, accepted mutation and foreground
 cleanup of accepted work. Keep native-provider qualification and public journey
 completion explicitly unproven by these internal portable tests.
+
+T4 plan-review resolutions:
+
+- The receipt is acceptance of the source command for durable finalization. Its
+  operation ID and exact PRE terminal identify that accepted command; it is not
+  a formal Submission, POST verdict or final task acceptance. The snapshot fields
+  say `evaluation_pending`/`finalization_pending` at acceptance, never the task's
+  later current state. TASK gains a T4-specific authorized direct transition for
+  both initial `in_progress` and governed `needs_revision` work. Do not enable an
+  unguarded generic lifecycle shortcut or persist an intermediate `submitted`
+  state. Require successful initial and revision tests as well as denial cases.
+- The closed acceptance resource under `submission.create` has
+  `resource_id == operation_id`. Its exact canonical digest binds operation,
+  actor/link, project/task/assignment, command/context/source digests, selected
+  PRE run/request/terminal and manifest identities, and accepted policy lineage.
+  Prepared consumption and replay explicitly dispatch on this operation-scoped
+  resource shape; a Submission-creation resource, another operation or changed
+  digest must not replay it. Retained old audit facts remain readable, without
+  fabricating a Submission ID for the new action.
+- T4 performs fresh authority, revision and owner checks. After T4 commits, T5
+  relies on the immutable accepted receipt/source/run/decision/event under its
+  own continuation fence. It must not repeat foreground lease, revision
+  deadline/cap, submitter grant or contributor-eligibility checks which can expire
+  after valid acceptance. T4 tests prove later deadline/grant changes cannot
+  invalidate or expose accepted source to foreground cleanup; T5's required
+  proof must additionally finalize across those changes before overall completion.
+- The foreground composer must keep the existing heartbeat over PRE through T4.
+  T4 uses short SQL-only roots and rejects expiration at its final deferred commit
+  boundary, not merely when it initially read the lease. The accepted-state
+  transition check is distinct from later accepted custody: a later T5/read must
+  not reapply the old foreground expiry condition. No lease extension beyond the
+  absolute PRE deadline is allowed.
+- PostgreSQL concurrency proof uses independent sessions for both orders of
+  T4 versus expiry/abandonment. Acceptance winning leaves source/charge/pointer
+  protected and abandonment refused; expiry/abandonment winning prevents an
+  accepted receipt, event or task transition. Also race duplicate T4 commands
+  and prove one stable accepted result/event. Preserve the actual ZIP and real
+  database lease fixture while explicitly treating its simulated runtime/Smol
+  observations as portable transaction evidence only.

From 0e4d11f38b337f71d485e46187518577e2cc475e Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 18:13:59 +0100
Subject: [PATCH 107/513] Bind submission acceptance authority to exact intake
 custody

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 +++++
 .../authorization/api/submission_intake.py    | 22 ++++++
 .../artifact_project_authority.py             | 11 +--
 .../authorization/domain/action_groups.py     |  5 +-
 .../app/modules/authorization/domain/audit.py |  2 +
 .../authorization/domain/audit_targets.py     |  5 +-
 .../authorization/domain/submission_intake.py | 41 +++++++++-
 backend/app/modules/authorization/prepared.py |  7 +-
 backend/app/modules/authorization/runtime.py  |  3 +-
 .../authorization/submission_consumption.py   |  4 +
 .../authorization/submission_intake.py        | 79 ++++++++++++++++++-
 .../task_authority/test_intake_authority.py   | 79 ++++++++++++++++++-
 12 files changed, 260 insertions(+), 18 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 0c15d9333..da074d47b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2471,3 +2471,23 @@ T4 plan-review resolutions:
   and prove one stable accepted result/event. Preserve the actual ZIP and real
   database lease fixture while explicitly treating its simulated runtime/Smol
   observations as portable transaction evidence only.
+
+T4 authorization implementation checkpoint:
+
+- Added a closed operation-scoped `submission.create` acceptance resource and
+  exact prepared consumption binding for source, PRE request/terminal, lease,
+  context and receipt evidence. No formal Submission identifier is fabricated.
+  The persisted audit target uses the existing `submission_operation` identity.
+- Retained receipt validation checks the original immutable decision digest;
+  callers must first authorize a current own-operation read. This does not issue
+  a new acceptance handle or continuation authority.
+- Real PostgreSQL verification: 29 tests passed in
+  `/tmp/t4-auth-final.log` (isolated-run metadata `/tmp/t4-auth-final.json`).
+  Coverage includes exact acceptance/receipt, consumed-handle reuse, changed
+  custody evidence, and missing/reviewer/foreign/revoked/admin grant denial.
+  The tests exposed and drove repairs to the closed decision vocabulary and
+  prepared-denial audit dispatch. Structure validation and diff checks passed.
+- This checkpoint is AUTH participation only. ART accepted-state storage,
+  TASK transition, CHECKERS terminal consumption, atomic outbox/migration and
+  acceptance race/rollback proofs remain T4 work. It is not proof of public
+  exposure, T5 continuation, native qualification or end-to-end completion.
diff --git a/backend/app/modules/authorization/api/submission_intake.py b/backend/app/modules/authorization/api/submission_intake.py
index 430cf0c35..3020e3c6f 100644
--- a/backend/app/modules/authorization/api/submission_intake.py
+++ b/backend/app/modules/authorization/api/submission_intake.py
@@ -1,5 +1,6 @@
 """Operation-scoped intake authority; these facts are not a grant or acceptance."""
 from dataclasses import dataclass
+from datetime import datetime
 from typing import Literal, Protocol
 from uuid import UUID
 
@@ -24,6 +25,24 @@ class IntakeReservationAuthorityFacts(IntakeReservationPreflightFacts):
     task_status: Literal["in_progress", "needs_revision"]
 
 
+@dataclass(frozen=True, slots=True)
+class IntakeAcceptanceAuthorityFacts(IntakeReservationAuthorityFacts):
+    """Exact T4 command acceptance; no formal Submission or continuation authority."""
+    foreground_lease_id: UUID
+    foreground_lease_generation: int
+    selected_pre_submit_run_id: UUID
+    selected_pre_submit_request_sha256: str
+    selected_pre_submit_terminal_sha256: str
+    source_sha256: str
+    semantic_manifest_sha256: str
+    accepted_context_sha256: str
+    receipt_sha256: str
+    accepted_at: datetime
+    predecessor_submission_id: UUID | None
+    predecessor_submission_version: int | None
+    checker_remediation_manifest_id: UUID | None
+
+
 @dataclass(frozen=True, slots=True)
 class IntakeOperationReadFacts:
     """An actor-owned stored operation, resolved before current-task eligibility."""
@@ -43,6 +62,9 @@ async def lock_actor(self, actor_id: UUID, identity_link_id: UUID) -> None: ...
     async def preflight(self, facts: IntakeReservationPreflightFacts) -> None: ...
     async def prepare(self, facts: IntakeReservationAuthorityFacts) -> object: ...
     async def consume(self, handle: object, facts: IntakeReservationAuthorityFacts) -> UUID: ...
+    async def prepare_acceptance(self, facts: IntakeAcceptanceAuthorityFacts) -> object: ...
+    async def consume_acceptance(self, handle: object, facts: IntakeAcceptanceAuthorityFacts) -> UUID: ...
+    async def validate_acceptance_receipt(self, facts: IntakeAcceptanceAuthorityFacts, decision_id: UUID) -> None: ...
     async def authorize_read(self, facts: IntakeOperationReadFacts) -> UUID: ...
     async def restage_denial(self, error: IntakeAuthorityDenied) -> bool: ...
     def close(self) -> None: ...
diff --git a/backend/app/modules/authorization/artifact_project_authority.py b/backend/app/modules/authorization/artifact_project_authority.py
index 0bb5490dc..efbc055f6 100644
--- a/backend/app/modules/authorization/artifact_project_authority.py
+++ b/backend/app/modules/authorization/artifact_project_authority.py
@@ -4,7 +4,7 @@
 
 from uuid import UUID
 
-from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext
+from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeAcceptanceResourceContext
 from app.modules.authorization.catalogue import ActionAvailability, ActionId
 from app.modules.authorization.schemas import AdminRole
 from app.modules.authorization.domain.task_authority import (
@@ -189,10 +189,11 @@ def evaluate_submitter_authority(action, context, authority, resource, lifecycle
     if denial is None and action.availability is not ActionAvailability.ACTIVE:
         denial = AuthorizationDenialCode.ACTION_UNAVAILABLE
     elif denial is None and (
-        (action.action_id is ActionId.SUBMISSION_INTAKE_RESERVE
-         and type(resource) is not IntakeReservationResourceContext)
-        or (action.action_id is not ActionId.SUBMISSION_INTAKE_RESERVE
-            and not isinstance(resource, (SubmissionBundlePreparationResourceContext, SubmissionCreationResourceContext)))
+        type(resource) not in {
+            ActionId.SUBMISSION_INTAKE_RESERVE: (IntakeReservationResourceContext,),
+            ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE: (SubmissionBundlePreparationResourceContext,),
+            ActionId.SUBMISSION_CREATE: (SubmissionCreationResourceContext, IntakeAcceptanceResourceContext),
+        }.get(action.action_id, ())
     ):
         denial = AuthorizationDenialCode.RESOURCE_GUARD_DENIED
     elif denial is None and resource.scope_project_id != authority.scope_project_id:
diff --git a/backend/app/modules/authorization/domain/action_groups.py b/backend/app/modules/authorization/domain/action_groups.py
index 55cf3ea75..59ab73b26 100644
--- a/backend/app/modules/authorization/domain/action_groups.py
+++ b/backend/app/modules/authorization/domain/action_groups.py
@@ -72,7 +72,7 @@
 
 def supports_prepared_denial(action_id: ActionId, resource_context: object) -> bool:
     """Admit only the existing action/context pairs for prepare-time denial evidence."""
-    from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext
+    from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
     from app.modules.authorization.domain.task_authority import TASK_ACTIONS, TaskAuthorityResourceContext
     from app.modules.authorization.domain.project_create import ProjectCreateResourceContext
     from app.modules.authorization.domain.checker_retry import (
@@ -84,7 +84,8 @@ def supports_prepared_denial(action_id: ActionId, resource_context: object) -> b
         ProjectPolicyMutationPrepareDenialResourceContext, ProjectSubmissionArtifactPolicyMutationResourceContext,
     )
     return (
-        (action_id is ActionId.SUBMISSION_INTAKE_RESERVE and type(resource_context) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext})
+        (action_id is ActionId.SUBMISSION_CREATE and type(resource_context) is IntakeAcceptanceResourceContext)
+        or (action_id is ActionId.SUBMISSION_INTAKE_RESERVE and type(resource_context) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext})
         or (
             action_id in checker_outputs.CHECKER_OUTPUT_ACTIONS
             and type(resource_context) is checker_outputs.CheckerOutputResourceContext
diff --git a/backend/app/modules/authorization/domain/audit.py b/backend/app/modules/authorization/domain/audit.py
index cafe4acbf..c19dfb762 100644
--- a/backend/app/modules/authorization/domain/audit.py
+++ b/backend/app/modules/authorization/domain/audit.py
@@ -21,6 +21,7 @@
     "selected_pre_submit_run",
     "task_post_submit_routing_manifest",
     "submission_intake_reservation",
+    "submission_intake_acceptance",
     "submission_intake_preflight",
     "submission_operation_read",
     "task_authority",
@@ -89,6 +90,7 @@
     "selected_pre_submit_run",
     "task_post_submit_routing_manifest",
     "submission_intake_reservation",
+    "submission_intake_acceptance",
     "submission_intake_preflight",
     "submission_operation_read",
     "task_authority",
diff --git a/backend/app/modules/authorization/domain/audit_targets.py b/backend/app/modules/authorization/domain/audit_targets.py
index 8890e026d..8e737cb43 100644
--- a/backend/app/modules/authorization/domain/audit_targets.py
+++ b/backend/app/modules/authorization/domain/audit_targets.py
@@ -1,7 +1,7 @@
 """Exact project resource audit selectors, without raw product facts."""
 
 from uuid import UUID
-from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext
+from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
 from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext
 
 from app.modules.authorization.catalogue import ActionId
@@ -80,6 +80,9 @@ def _model_administration_target(resource):
 
 
 def _submission_operation_target(resource):
+    if type(resource) is IntakeAcceptanceResourceContext:
+        project_id = str(resource.scope_project_id)
+        return project_id, "submission_operation", str(resource.operation_id), "project", project_id
     if type(resource) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext} or (
         type(resource) is ContributorWorkReadResourceContext
         and resource.resource_type == "submission_operation_read"
diff --git a/backend/app/modules/authorization/domain/submission_intake.py b/backend/app/modules/authorization/domain/submission_intake.py
index aaecc20f3..13c3d656b 100644
--- a/backend/app/modules/authorization/domain/submission_intake.py
+++ b/backend/app/modules/authorization/domain/submission_intake.py
@@ -3,12 +3,12 @@
 from typing import Literal
 from uuid import UUID
 
-from pydantic import BaseModel, ConfigDict, Field, field_validator
+from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator, model_validator
 
 from app.modules.authorization.catalogue import ActionId
 
 
-class _IntakeReservationSelectors(BaseModel):
+class _IntakeOperationSelectors(BaseModel):
     """A source-custody reservation, never a prepared artifact or Submission."""
     model_config = ConfigDict(extra="forbid", frozen=True, strict=True, revalidate_instances="always")
     resource_id: UUID
@@ -29,18 +29,51 @@ def operation_record(cls, value: UUID) -> UUID:
 
 
 
-class IntakeReservationPreflightResourceContext(_IntakeReservationSelectors):
+class IntakeReservationPreflightResourceContext(_IntakeOperationSelectors):
     """Selector-only preflight; cannot become a prepared reservation handle."""
     resource_type: Literal["submission_intake_preflight"] = "submission_intake_preflight"
 
 
-class IntakeReservationResourceContext(_IntakeReservationSelectors):
+class IntakeReservationResourceContext(_IntakeOperationSelectors):
     """Complete locked reservation facts used only for prepare and consume."""
     resource_type: Literal["submission_intake_reservation"] = "submission_intake_reservation"
     locked_context_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
     task_status: Literal["in_progress", "needs_revision"]
 
 
+class IntakeAcceptanceResourceContext(_IntakeOperationSelectors):
+    """Closed human command acceptance, identified by operation rather than Submission."""
+    resource_type: Literal["submission_intake_acceptance"] = "submission_intake_acceptance"
+    operation_id: UUID
+    locked_context_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    task_status: Literal["in_progress", "needs_revision"]
+    foreground_lease_id: UUID
+    foreground_lease_generation: int = Field(gt=0)
+    selected_pre_submit_run_id: UUID
+    selected_pre_submit_request_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    selected_pre_submit_terminal_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    source_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    semantic_manifest_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    accepted_context_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    receipt_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    accepted_at: AwareDatetime
+    predecessor_submission_id: UUID | None
+    predecessor_submission_version: int | None = Field(ge=1)
+    checker_remediation_manifest_id: UUID | None
+
+    @model_validator(mode="after")
+    def exact_operation_and_revision(self):
+        if self.resource_id != self.operation_id:
+            raise ValueError("acceptance resource must match its operation")
+        initial = (self.task_status == "in_progress" and self.predecessor_submission_id is None
+                   and self.predecessor_submission_version is None and self.checker_remediation_manifest_id is None)
+        revision = (self.task_status == "needs_revision" and self.predecessor_submission_id is not None
+                    and self.predecessor_submission_version is not None and self.checker_remediation_manifest_id is not None)
+        if not (initial or revision):
+            raise ValueError("acceptance revision identity is inconsistent")
+        return self
+
+
 def intake_preflight_matches(caller_input, resource, scope) -> bool:
     """Match strict partial selectors and exact project/key without issuing custody."""
     from app.modules.authorization.runtime import PreparedAuthorityScopeKind
diff --git a/backend/app/modules/authorization/prepared.py b/backend/app/modules/authorization/prepared.py
index ff09ef68d..378176d00 100644
--- a/backend/app/modules/authorization/prepared.py
+++ b/backend/app/modules/authorization/prepared.py
@@ -99,6 +99,7 @@
     GuideSourceReadResourceContext,
     SubmissionBindingResourceContext,
     SubmissionCreationResourceContext,
+    IntakeAcceptanceResourceContext,
     GuideSourceIngestResourceContext,
     TaskImportSourceResourceContext,
     PreSubmitCheckerInputResourceContext,
@@ -574,6 +575,9 @@ def _validate_consumption(
         """Bind consumption to its issued request, root transaction and exact resource."""
         if expected_action_id is not issuance.binding.action_id:
             raise PreparedAuthorizationHandleInvalid("invalid prepared authorization handle")
+        if (type(final_resource_context) is IntakeAcceptanceResourceContext
+                and issuance.binding.idempotency_key != final_resource_context.idempotency_key):
+            raise PreparedAuthorizationHandleInvalid("invalid prepared acceptance key")
         rebound = self._binding(expected_action_id, caller_input, issuance.binding.scope)
         if rebound != issuance.binding:
             raise PreparedAuthorizationHandleInvalid("invalid prepared authorization handle")
@@ -705,6 +709,7 @@ async def consume(
                 PreSubmitCheckerInputResourceContext,
                 SubmissionBindingResourceContext,
                 SubmissionCreationResourceContext,
+                IntakeAcceptanceResourceContext,
                 TaskImportSourceResourceContext,
             ),
         ) and not exact_artifact_binding_matches(
@@ -1062,7 +1067,7 @@ def _scope_from_resource(
                 kind=PreparedAuthorityScopeKind.PROJECT,
                 project_id=resource.scope_project_id,
             )
-        if isinstance(resource, SubmissionCreationResourceContext):
+        if isinstance(resource, (SubmissionCreationResourceContext, IntakeAcceptanceResourceContext)):
             return PreparedAuthorityScope(
                 kind=PreparedAuthorityScopeKind.PROJECT,
                 project_id=resource.scope_project_id,
diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py
index 064cd4a16..e4a1587fd 100644
--- a/backend/app/modules/authorization/runtime.py
+++ b/backend/app/modules/authorization/runtime.py
@@ -65,6 +65,7 @@
 from app.modules.authorization.schemas import AdminRole, AdminScope, ProjectRole
 from app.modules.authorization.submission_preparation import SubmissionBundlePreparationPreflightResourceContext, SubmissionBundlePreparationResourceContext
 from app.modules.authorization.submission_consumption import SubmissionBindingResourceContext, SubmissionCreationResourceContext
+from app.modules.authorization.domain.submission_intake import IntakeAcceptanceResourceContext
 from app.modules.authorization.domain.task_authority import TaskImportBatchResourceContext as TaskImportBatchResourceContext
 
 _STRICT_FROZEN = ConfigDict(extra="forbid", frozen=True, strict=True)
@@ -1110,7 +1111,7 @@ def bind_source_operation(self):
     | ArtifactOperatorReadResourceContext
     | ArtifactOperatorRetryResourceContext
     | GuideSourceReadResourceContext
-    | SubmissionCreationResourceContext | SubmissionBindingResourceContext
+    | SubmissionCreationResourceContext | SubmissionBindingResourceContext | IntakeAcceptanceResourceContext
     | PreSubmitCheckerInputResourceContext
     | SubmissionBundlePreparationPreflightResourceContext
     | SubmissionBundlePreparationResourceContext
diff --git a/backend/app/modules/authorization/submission_consumption.py b/backend/app/modules/authorization/submission_consumption.py
index f7c1498fa..2362d4a4f 100644
--- a/backend/app/modules/authorization/submission_consumption.py
+++ b/backend/app/modules/authorization/submission_consumption.py
@@ -7,6 +7,7 @@
 from pydantic import BaseModel, ConfigDict, Field, model_validator
 
 from app.modules.authorization.catalogue import ActionId
+from app.modules.authorization.domain.submission_intake import IntakeAcceptanceResourceContext
 
 _STRICT_FROZEN = ConfigDict(extra="forbid", frozen=True, strict=True)
 
@@ -133,6 +134,9 @@ def bind_admission(self):
 def parse_consumption_binding(action_id: ActionId, value, invalid):
     """Parse exact submission facts into their canonical context and digest."""
     resource_type = RESOURCE_BY_ACTION.get(action_id)
+    if (action_id is ActionId.SUBMISSION_CREATE and type(value) is dict
+            and value.get("resource_type") == "submission_intake_acceptance"):
+        resource_type = IntakeAcceptanceResourceContext
     if resource_type is None:
         return None
     try:
diff --git a/backend/app/modules/authorization/submission_intake.py b/backend/app/modules/authorization/submission_intake.py
index d1d6cca60..391477264 100644
--- a/backend/app/modules/authorization/submission_intake.py
+++ b/backend/app/modules/authorization/submission_intake.py
@@ -8,10 +8,14 @@
 from app.core.hashing import canonical_json_hash
 from app.modules.authorization.api.submission_intake import (
     IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts,
+    IntakeAcceptanceAuthorityFacts,
 )
 from app.modules.authorization.catalogue import ActionId
 from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext
-from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext
+from app.modules.authorization.domain.submission_intake import (
+    IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext,
+)
+from app.modules.authorization.domain.resource_digest import authorization_resource_digest
 from app.modules.authorization.kernel import AuthorizationService
 from app.modules.authorization.prepared import PreparedAuthorizationService
 from app.modules.authorization.repository import AdminAuthorizationRepository
@@ -60,7 +64,7 @@ def _resource(self, facts: IntakeReservationAuthorityFacts) -> IntakeReservation
             raise IntakeAuthorityDenied("submission intake is unavailable") from exc
 
     @staticmethod
-    def _input(resource: IntakeReservationResourceContext) -> PreparedAuthorizationInput:
+    def _input(resource: IntakeReservationResourceContext | IntakeAcceptanceResourceContext) -> PreparedAuthorizationInput:
         return PreparedAuthorizationInput(idempotency_key=resource.idempotency_key,
                                           request_value=resource.model_dump(mode="json"))
 
@@ -108,6 +112,77 @@ async def consume(self, handle: object, facts: IntakeReservationAuthorityFacts)
         except (AuthorizationDenied, PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported) as exc:
             raise IntakeAuthorityDenied("submission intake is unavailable") from exc
 
+    @staticmethod
+    def _acceptance_resource(facts: IntakeAcceptanceAuthorityFacts) -> IntakeAcceptanceResourceContext:
+        if type(facts) is not IntakeAcceptanceAuthorityFacts:
+            raise IntakeAuthorityDenied("submission acceptance is unavailable")
+        values = asdict(facts)
+        values["resource_id"] = values["operation_id"]
+        values["scope_project_id"] = values.pop("project_id")
+        try:
+            return IntakeAcceptanceResourceContext(**values)
+        except ValidationError as exc:
+            raise IntakeAuthorityDenied("submission acceptance is unavailable") from exc
+
+    def _current_acceptance_resource(self, facts):
+        resource = self._acceptance_resource(facts)
+        if (not isinstance(self._context, HumanAuthorizationContext)
+                or resource.actor_profile_id != self._context.actor_profile_id
+                or resource.identity_link_id != self._context.identity_link_id):
+            raise IntakeAuthorityDenied("submission acceptance is unavailable")
+        return resource
+
+    async def prepare_acceptance(self, facts: IntakeAcceptanceAuthorityFacts) -> object:
+        """Prepare fresh submission.create authority for one exact source operation."""
+        resource = self._current_acceptance_resource(facts)
+        value = self._input(resource)
+        try:
+            try:
+                return await self._prepared.prepare(ActionId.SUBMISSION_CREATE, value,
+                    PreparedAuthorityScope(kind=PreparedAuthorityScopeKind.PROJECT,
+                                           project_id=resource.scope_project_id))
+            except PreparedAuthorizationUnsupported as exc:
+                await self._prepared.deny_unsupported(ActionId.SUBMISSION_CREATE, value, resource, exc)
+                raise
+        except (AuthorizationDenied, PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported) as exc:
+            raise IntakeAuthorityDenied("submission acceptance is unavailable") from exc
+
+    async def consume_acceptance(self, handle: object, facts: IntakeAcceptanceAuthorityFacts) -> UUID:
+        """Consume only the exact prepared acceptance; TASK and ART still own their writes."""
+        resource = self._current_acceptance_resource(facts)
+        try:
+            decision = await self._prepared.consume(handle, ActionId.SUBMISSION_CREATE,
+                                                    self._input(resource), resource)
+            return decision.decision_id
+        except (AuthorizationDenied, PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported) as exc:
+            raise IntakeAuthorityDenied("submission acceptance is unavailable") from exc
+
+    async def validate_acceptance_receipt(self, facts: IntakeAcceptanceAuthorityFacts, decision_id: UUID) -> None:
+        """Validate retained provenance after fresh read authority, never renew acceptance.
+
+        Original grant/link status and foreground deadlines may have changed.
+        This observation issues no handle and grants no continuation authority.
+        """
+        resource = self._acceptance_resource(facts)
+        if (not self._session.in_transaction() or self._session.in_nested_transaction()
+                or not isinstance(self._context, HumanAuthorizationContext)
+                or resource.actor_profile_id != self._context.actor_profile_id):
+            raise IntakeAuthorityDenied("submission acceptance is unavailable")
+        event = await self._kernel._audit.get_authority_event(decision_id)
+        expected = {
+            "id": str(decision_id), "event_domain": "authority",
+            "event_type": "SensitiveAuthorizationAllowed", "actor_ref_kind": "actor_profile",
+            "actor_id": str(resource.actor_profile_id), "action_id": ActionId.SUBMISSION_CREATE.value,
+            "permission_id": ActionId.SUBMISSION_CREATE.value,
+            "project_id": str(resource.scope_project_id), "resource_type": "submission_operation",
+            "resource_id": str(resource.operation_id), "target_ref_kind": "project",
+            "target_ref_id": str(resource.scope_project_id), "denial_code": None,
+            "after_facts": {"allowed": True, "resource_context_digest": authorization_resource_digest(resource)},
+        }
+        if (event is None or any(getattr(event, key, object()) != value for key, value in expected.items())
+                or event.matched_grant_id is None or event.request_id is None or event.correlation_id is None):
+            raise IntakeAuthorityDenied("submission acceptance is unavailable")
+
     async def authorize_read(self, facts: IntakeOperationReadFacts) -> UUID:
         """Read own recorded context under current grant, regardless of task status."""
         if (not self._session.in_transaction() or self._session.in_nested_transaction()
diff --git a/backend/tests/authorization/task_authority/test_intake_authority.py b/backend/tests/authorization/task_authority/test_intake_authority.py
index fa8a1999f..3668f4965 100644
--- a/backend/tests/authorization/task_authority/test_intake_authority.py
+++ b/backend/tests/authorization/task_authority/test_intake_authority.py
@@ -1,5 +1,6 @@
 """Real AUTH prepared/read evidence for intake operations, not ART T1 admission."""
-from dataclasses import fields, replace
+from dataclasses import asdict, fields, replace
+from datetime import datetime, timezone
 
 import pytest
 from sqlalchemy import select, text
@@ -8,6 +9,7 @@
 from app.db import session as db_session
 from app.modules.authorization.api.submission_intake import (
     IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts,
+    IntakeAcceptanceAuthorityFacts,
 )
 from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization
 from app.modules.tasks.models import AuditEvent
@@ -103,7 +105,9 @@ async def test_intake_reserve_and_read_require_exact_current_submitter(admin_acc
     ctx = await context(admin_access)
     facts = reservation(ctx, project)
     read = IntakeOperationReadFacts(facts.operation_id, project, facts.task_id, ctx.actor_profile_id)
-    for method, value in (("preflight", preflight_facts(facts)), ("prepare", facts), ("authorize_read", read)):
+    for method, value in (("preflight", preflight_facts(facts)), ("prepare", facts),
+                          ("prepare_acceptance", replace(acceptance(ctx, project), operation_id=facts.operation_id)),
+                          ("authorize_read", read)):
         async with db_session.get_session_factory()() as session:
             authority = SubmissionIntakeAuthorization(session, ctx)
             try:
@@ -196,3 +200,74 @@ async def test_intake_preflight_has_no_allow_or_consumable_handle(intake_authori
             assert row.after_facts["allowed"] is True
         finally:
             authority.close()
+
+
+def acceptance(ctx, project):
+    return IntakeAcceptanceAuthorityFacts(
+        **asdict(reservation(ctx, project)),
+        foreground_lease_id=new_record_id(), foreground_lease_generation=1,
+        selected_pre_submit_run_id=new_record_id(),
+        selected_pre_submit_request_sha256="sha256:" + "c" * 64,
+        selected_pre_submit_terminal_sha256="sha256:" + "d" * 64,
+        source_sha256="sha256:" + "e" * 64,
+        semantic_manifest_sha256="sha256:" + "f" * 64,
+        accepted_context_sha256="sha256:" + "1" * 64,
+        receipt_sha256="sha256:" + "2" * 64,
+        accepted_at=datetime.now(timezone.utc),
+        predecessor_submission_id=None, predecessor_submission_version=None,
+        checker_remediation_manifest_id=None,
+    )
+
+
+async def test_acceptance_authority_retains_exact_operation_receipt(intake_authority):
+    _, project, grant_id, ctx = intake_authority
+    facts = acceptance(ctx, project)
+    async with db_session.get_session_factory()() as session:
+        authority = SubmissionIntakeAuthorization(session, ctx)
+        try:
+            async with session.begin():
+                await authority.lock_actor(ctx.actor_profile_id, ctx.identity_link_id)
+                handle = await authority.prepare_acceptance(facts)
+                decision = await authority.consume_acceptance(handle, facts)
+            async with session.begin():
+                await authority.authorize_read(IntakeOperationReadFacts(
+                    facts.operation_id, project, facts.task_id, ctx.actor_profile_id))
+                await authority.validate_acceptance_receipt(facts, decision)
+                row = await session.get(AuditEvent, str(decision))
+                assert row.action_id == "submission.create"
+                assert row.matched_grant_id == grant_id
+                assert row.resource_id == str(facts.operation_id)
+            with pytest.raises(IntakeAuthorityDenied):
+                async with session.begin():
+                    await authority.consume_acceptance(handle, facts)
+            with pytest.raises(IntakeAuthorityDenied):
+                async with session.begin():
+                    await authority.validate_acceptance_receipt(
+                        replace(facts, receipt_sha256="sha256:" + "3" * 64), decision)
+        finally:
+            authority.close()
+
+
+@pytest.mark.parametrize("field", [
+    "operation_id", "idempotency_key", "foreground_lease_id", "foreground_lease_generation",
+    "selected_pre_submit_run_id", "selected_pre_submit_request_sha256",
+    "selected_pre_submit_terminal_sha256", "source_sha256", "semantic_manifest_sha256",
+    "accepted_context_sha256", "receipt_sha256",
+])
+async def test_acceptance_authority_rejects_changed_custody(intake_authority, field):
+    _, project, _, ctx = intake_authority
+    facts = acceptance(ctx, project)
+    changed_value = ("sha256:" + "9" * 64 if field.endswith("sha256") else
+                     2 if field == "foreground_lease_generation" else new_record_id())
+    async with db_session.get_session_factory()() as session:
+        authority = SubmissionIntakeAuthorization(session, ctx)
+        try:
+            async with session.begin():
+                handle = await authority.prepare_acceptance(facts)
+                with pytest.raises(IntakeAuthorityDenied):
+                    await authority.consume_acceptance(handle, replace(facts, **{field: changed_value}))
+                await session.rollback()
+            assert not list(await session.scalars(select(AuditEvent).where(
+                AuditEvent.request_id == str(ctx.request_id))))
+        finally:
+            authority.close()

From 0ca88b0b42b27c498354366a39cff237de9a68c6 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 18:22:56 +0100
Subject: [PATCH 108/513] Require exact current PRE evidence for submission
 handoff

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 +++++++
 .../checkers/api/selected_pre_submit.py       |  5 ++
 .../selected_pre_submit_coordination.py       | 36 ++++++++----
 .../checkers/selected_pre_submit_reads.py     | 39 +------------
 .../checkers/selected_pre_submit_records.py   | 39 ++++++++++++-
 .../artifacts/test_submission_pre_source.py   | 56 ++++++++++++++-----
 6 files changed, 134 insertions(+), 61 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index da074d47b..64a9a6288 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2491,3 +2491,23 @@ T4 authorization implementation checkpoint:
   TASK transition, CHECKERS terminal consumption, atomic outbox/migration and
   acceptance race/rollback proofs remain T4 work. It is not proof of public
   exposure, T5 continuation, native qualification or end-to-end completion.
+
+T4 CHECKERS participation checkpoint:
+
+- Added `lock_acceptance` on the existing coordinator: exact run/request/terminal,
+  completed eligible execution, invocation receipt and persisted execute/finalize
+  decision references under the existing live TASK/source/run locks. Actor/key
+  replay normalization cannot substitute another run for acceptance. ART must
+  still atomically consume the immutable reference in the accepted transaction.
+- Current and retained reads share indexed terminal/lease/timing validation.
+  Actual upload/PRE fixtures exercise eligible acceptance and reject infrastructure
+  outcomes, substituted run/request identities and terminal digests.
+- Final source/receipt verification: 79 passed in `/tmp/t4-pre-final.log`, metadata
+  `/tmp/t4-pre-final.json`; structure and diff checks passed. The simulated runtime
+  remains portable evidence, not native provider qualification.
+- Wider coordination regression: 115 passed and seven failed in
+  `/tmp/t4-pre-record-regression.log`; failures construct obsolete prepared
+  admission lineage with `semantic_manifest_id`. Those fixtures must be converted
+  to source contracts during the cutover; the wider suite is not green.
+- Accepted-state persistence, composed TASK/ART/outbox commit and T4 race/rollback
+  proof remain unfinished. No public acceptance or continuation is exposed here.
diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py
index cd5b69f17..a63a7cde5 100644
--- a/backend/app/modules/checkers/api/selected_pre_submit.py
+++ b/backend/app/modules/checkers/api/selected_pre_submit.py
@@ -1063,6 +1063,11 @@ async def read_current(
     ) -> SelectedPreSubmitCurrentFacts | None:
         """Read one exact actor/key result after TASK custody is locked."""
 
+    async def lock_acceptance(
+        self, *, run_id: UUID, facts: SelectedPreSubmitReservationFacts, terminal_digest: str,
+    ) -> SelectedPreSubmitTerminalFacts:
+        """Require the exact current eligible source terminal under T4 locks."""
+
     async def reserve(self, facts: SelectedPreSubmitReservationFacts) -> UUID:
         """Reserve one exact actor/key request after TASK custody is locked."""
 
diff --git a/backend/app/modules/checkers/selected_pre_submit_coordination.py b/backend/app/modules/checkers/selected_pre_submit_coordination.py
index c86b377be..0b54fc73e 100644
--- a/backend/app/modules/checkers/selected_pre_submit_coordination.py
+++ b/backend/app/modules/checkers/selected_pre_submit_coordination.py
@@ -30,7 +30,7 @@
     SelectedPreSubmitUnavailable,
 )
 from app.modules.checkers.models import SelectedPreSubmitRun
-from app.modules.checkers.selected_pre_submit_records import matches_source_request
+from app.modules.checkers.selected_pre_submit_records import matches_source_request, matches_terminal
 
 
 class SelectedPreSubmitTaskGuard(Protocol):
@@ -241,6 +241,7 @@ async def read_current(
                 if row.terminal_json is not None
                 else None
             )
+            terminal_matches = matches_terminal(row, stored, terminal)
         except (TypeError, ValueError):
             raise SelectedPreSubmitUnavailable(
                 "selected_pre_submit_stored_facts_invalid"
@@ -249,15 +250,7 @@ async def read_current(
             normalized != stored
             or not matches_source_request(row, stored)
             or row.request_digest != stored.request_digest
-            or (
-                terminal is not None
-                and (
-                    terminal.terminal_digest != row.terminal_digest
-                    or terminal.lease.reservation != stored
-                    or terminal.execution is not None
-                    and terminal.execution.eligible != row.eligible
-                )
-            )
+            or not terminal_matches
         ):
             raise SelectedPreSubmitRequestConflict(
                 "selected_pre_submit_request_conflict"
@@ -269,6 +262,29 @@ async def read_current(
             terminal=terminal,
         )
 
+    async def lock_acceptance(
+        self, *, run_id: UUID, facts: SelectedPreSubmitReservationFacts, terminal_digest: str,
+    ) -> SelectedPreSubmitTerminalFacts:
+        """Lock an exact current eligible terminal for the caller's T4 transaction.
+
+        Unlike ordinary actor/key replay, acceptance cannot normalize another run
+        identity. The ART accepted reference consumes this evidence atomically;
+        this read neither mutates immutable PRE facts nor issues a capability.
+        """
+        if type(facts) is not SelectedPreSubmitReservationFacts or facts.attempt_id != run_id:
+            raise SelectedPreSubmitRequestConflict("selected_pre_submit_request_conflict")
+        current = await self.read_current(facts)
+        if (current is None or current.run_id != run_id or current.reservation != facts
+                or current.status != "completed" or current.terminal is None
+                or current.terminal.terminal_digest != terminal_digest
+                or current.terminal.execution is None or current.terminal.execution.eligible is not True
+                or current.terminal.invocation_receipt is None):
+            raise SelectedPreSubmitUnavailable("selected_pre_submit_acceptance_unavailable")
+        row = await self._session.get(SelectedPreSubmitRun, str(run_id))
+        if row.execute_evidence_id is None or row.finalize_evidence_id is None:
+            raise SelectedPreSubmitUnavailable("selected_pre_submit_acceptance_unavailable")
+        return current.terminal
+
     async def reserve(self, facts: SelectedPreSubmitReservationFacts) -> UUID:
         """Acquire TASK custody before the CHECKERS key and exact request row."""
         _require_root(self._session)
diff --git a/backend/app/modules/checkers/selected_pre_submit_reads.py b/backend/app/modules/checkers/selected_pre_submit_reads.py
index b1608404e..c1e1582bd 100644
--- a/backend/app/modules/checkers/selected_pre_submit_reads.py
+++ b/backend/app/modules/checkers/selected_pre_submit_reads.py
@@ -14,7 +14,7 @@
     HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal,
 )
 from app.modules.checkers.models import SelectedPreSubmitRun
-from app.modules.checkers.selected_pre_submit_records import matches_source_request
+from app.modules.checkers.selected_pre_submit_records import matches_source_request, matches_terminal
 
 
 def _request_matches(row: SelectedPreSubmitRun, request: HistoricalSelectedPreSubmitReservation) -> bool:
@@ -38,41 +38,6 @@ def _request_matches(row: SelectedPreSubmitRun, request: HistoricalSelectedPreSu
     )
 
 
-def _terminal_matches(row: SelectedPreSubmitRun, request, terminal) -> bool:
-    """Check retained outcome/lease/timing without conferring current liveness."""
-    if terminal is None:
-        if type(request) is SelectedPreSubmitReservationFacts:
-            if row.finalize_evidence_id is not None:
-                return False
-            if row.status == "queued":
-                if (row.lease_id is not None or row.lease_generation != 0
-                        or row.lease_expires_at is not None or row.started_at is not None
-                        or row.execute_evidence_id is not None):
-                    return False
-            elif row.status == "running":
-                SelectedPreSubmitLeaseFacts(request, UUID(str(row.lease_id)),
-                                            row.lease_generation, row.lease_expires_at)
-                if (row.execute_evidence_id is None or row.started_at is None
-                        or not row.queued_at <= row.started_at <= row.lease_expires_at):
-                    return False
-        return (
-            row.status in {"queued", "running"} and row.terminal_digest is None
-            and row.eligible is None and row.completed_at is None
-        )
-    return (
-        terminal.lease.reservation == request
-        and terminal.terminal_digest == row.terminal_digest
-        and terminal.outcome == row.status
-        and str(terminal.lease.lease_id) == str(row.lease_id)
-        and terminal.lease.lease_generation == row.lease_generation
-        and terminal.lease.lease_expires_at == row.lease_expires_at
-        and terminal.queued_at == row.queued_at
-        and terminal.started_at == row.started_at
-        and terminal.completed_at == row.completed_at
-        and (terminal.execution.eligible if terminal.execution is not None else None) is row.eligible
-    )
-
-
 def _view(row: SelectedPreSubmitRun) -> SelectedPreSubmitRunView:
     """Decode each retained schema and bind it to the indexed row without issuing authority."""
     try:
@@ -92,7 +57,7 @@ def _view(row: SelectedPreSubmitRun) -> SelectedPreSubmitRunView:
             else:
                 terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json)
             request_matches = matches_source_request(row, request)
-        if not request_matches or not _terminal_matches(row, request, terminal):
+        if not request_matches or not matches_terminal(row, request, terminal):
             raise ValueError("retained PRE columns differ")
     except (KeyError, TypeError, ValueError):
         raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid") from None
diff --git a/backend/app/modules/checkers/selected_pre_submit_records.py b/backend/app/modules/checkers/selected_pre_submit_records.py
index 485c8a15a..9477e1888 100644
--- a/backend/app/modules/checkers/selected_pre_submit_records.py
+++ b/backend/app/modules/checkers/selected_pre_submit_records.py
@@ -1,6 +1,8 @@
 """Shared CHECKERS source-row identity validation for writes and retained reads."""
 
-from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitReservationFacts
+from uuid import UUID
+
+from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitReservationFacts, SelectedPreSubmitLeaseFacts
 from app.modules.checkers.models import SelectedPreSubmitRun
 
 
@@ -25,3 +27,38 @@ def matches_source_request(row: SelectedPreSubmitRun, facts: SelectedPreSubmitRe
         and row.semantic_manifest_sha256 is None
         and row.execution_budget_ms == facts.execution_budget_ms
     )
+
+
+def matches_terminal(row: SelectedPreSubmitRun, request, terminal) -> bool:
+    """Check retained outcome/lease/timing without conferring current liveness."""
+    if terminal is None:
+        if type(request) is SelectedPreSubmitReservationFacts:
+            if row.finalize_evidence_id is not None:
+                return False
+            if row.status == "queued":
+                if (row.lease_id is not None or row.lease_generation != 0
+                        or row.lease_expires_at is not None or row.started_at is not None
+                        or row.execute_evidence_id is not None):
+                    return False
+            elif row.status == "running":
+                SelectedPreSubmitLeaseFacts(request, UUID(str(row.lease_id)),
+                                            row.lease_generation, row.lease_expires_at)
+                if (row.execute_evidence_id is None or row.started_at is None
+                        or not row.queued_at <= row.started_at <= row.lease_expires_at):
+                    return False
+        return (
+            row.status in {"queued", "running"} and row.terminal_digest is None
+            and row.eligible is None and row.completed_at is None
+        )
+    return (
+        terminal.lease.reservation == request
+        and terminal.terminal_digest == row.terminal_digest
+        and terminal.outcome == row.status
+        and str(terminal.lease.lease_id) == str(row.lease_id)
+        and terminal.lease.lease_generation == row.lease_generation
+        and terminal.lease.lease_expires_at == row.lease_expires_at
+        and terminal.queued_at == row.queued_at
+        and terminal.started_at == row.started_at
+        and terminal.completed_at == row.completed_at
+        and (terminal.execution.eligible if terminal.execution is not None else None) is row.eligible
+    )
diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py
index c567e6aa3..aeb00ed03 100644
--- a/backend/tests/artifacts/test_submission_pre_source.py
+++ b/backend/tests/artifacts/test_submission_pre_source.py
@@ -468,6 +468,47 @@ async def run(self, lease, grant):
     return SourceRuntime(), runtime_errors
 
 
+async def _upload_pre_source(intake, payload):
+    from tests.artifact_store_helpers import initialize_local_store
+    async def upload_bytes():
+        yield payload
+
+    store = initialize_local_store(root=intake.durable_root, buffer_bytes=256 * 1024)
+    async with intake.factory.begin() as session:
+        row = await reserve(intake, session, with_upload=False)
+        operation, foreground_lease = UUID(row.id), UUID(row.lease_id)
+        metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
+        key = UUID(row.idempotency_key)
+    source = await foreground_upload(intake, store).receive(
+        operation, foreground_lease, 1, upload_bytes(), **foreground_limits(),
+    )
+    return store, operation, foreground_lease, metadata, key, source
+
+
+async def _assert_acceptance_terminal(factory, request, terminal):
+    """Use real source/TASK/run locks; a detached pass cannot select another run."""
+    from dataclasses import replace
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.modules.checkers.api.selected_pre_submit import (
+        SelectedPreSubmitUnavailable, SelectedPreSubmitRequestConflict,
+    )
+    eligible = terminal.execution is not None and terminal.execution.eligible
+    async with factory.begin() as session:
+        coordinator = selected_pre_submit_coordinator(session)
+        args = dict(run_id=request.attempt_id, facts=request, terminal_digest=terminal.terminal_digest)
+        if eligible:
+            assert await coordinator.lock_acceptance(**args) == terminal
+        else:
+            with pytest.raises(SelectedPreSubmitUnavailable):
+                await coordinator.lock_acceptance(**args)
+        with pytest.raises(SelectedPreSubmitRequestConflict):
+            await coordinator.lock_acceptance(**(args | {"run_id": new_record_id()}))
+        with pytest.raises(SelectedPreSubmitRequestConflict):
+            await coordinator.lock_acceptance(**(args | {"facts": replace(request, attempt_id=new_record_id())}))
+        with pytest.raises(SelectedPreSubmitUnavailable):
+            await coordinator.lock_acceptance(**(args | {"terminal_digest": "sha256:" + "f" * 64}))
+
+
 @pytest.mark.parametrize("intake", [True], indirect=True)
 @pytest.mark.parametrize("materializer_enabled", [True, False])
 @pytest.mark.parametrize("runtime_outcome", ["transport_failure", "completed", "received_failure"])
@@ -490,7 +531,6 @@ async def test_source_pre_execution_uses_committed_authorized_local_read(intake,
     from app.modules.checkers.api.pre_submit_material import SubmissionPacketView
     from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest
     from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest
-    from tests.artifact_store_helpers import initialize_local_store
     from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer
     from tests.checkers.execution.support import provision_post_submit_service
     from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation
@@ -498,18 +538,7 @@ async def test_source_pre_execution_uses_committed_authorized_local_read(intake,
     from tests.test_trusted_intake import _archive
 
     payload = _archive() if runtime_outcome == "completed" else b"original source bytes"
-    async def upload_bytes():
-        yield payload
-
-    store = initialize_local_store(root=intake.durable_root, buffer_bytes=256 * 1024)
-    async with intake.factory.begin() as session:
-        row = await reserve(intake, session, with_upload=False)
-        operation, foreground_lease = UUID(row.id), UUID(row.lease_id)
-        metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
-        key = UUID(row.idempotency_key)
-    source = await foreground_upload(intake, store).receive(
-        operation, foreground_lease, 1, upload_bytes(), **foreground_limits(),
-    )
+    store, operation, foreground_lease, metadata, key, source = await _upload_pre_source(intake, payload)
     async with intake.factory.begin() as session:
         task = await task_submission_context_port(session).lock_submission_context(
             TaskSubmissionContextRequest(intake.task, intake.assignment, intake.actor.actor_profile_id, None),
@@ -589,6 +618,7 @@ async def chunks():
             if runtime_outcome == "received_failure" and materializer_enabled:
                 assert result.terminal.invocation_receipt.cleanup.disposition == "pending"
                 await _assert_stored_receipt(intake.factory, request.attempt_id, result.terminal)
+    await _assert_acceptance_terminal(intake.factory, request, result.terminal)
     assert bool(observed) == materializer_enabled
     store.close()
 

From f07ddcbd0901b83778dc75efbf613b508368fd8f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 18:58:52 +0100
Subject: [PATCH 109/513] Compose accepted source handoff with task and outbox
 custody

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 125 +++++++
 .../versions/0073_submission_acceptance.py    | 253 ++++++++++++++
 .../modules/artifacts/intake/acceptance.py    |  87 +++++
 .../artifacts/intake/foreground_admission.py  | 106 +++++-
 .../app/modules/artifacts/intake/models.py    |  33 +-
 .../app/modules/tasks/api/intake_custody.py   |   6 +-
 backend/app/modules/tasks/intake_custody.py   |  13 +
 .../artifacts/intake_acceptance_support.py    |  78 +++++
 .../test_submission_intake_admission.py       | 311 ++++++++++++++++++
 backend/tests/conftest.py                     |   2 +-
 10 files changed, 1002 insertions(+), 12 deletions(-)
 create mode 100644 backend/alembic/versions/0073_submission_acceptance.py
 create mode 100644 backend/app/modules/artifacts/intake/acceptance.py
 create mode 100644 backend/tests/artifacts/intake_acceptance_support.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 64a9a6288..f2fb8fd21 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2511,3 +2511,128 @@ T4 CHECKERS participation checkpoint:
   to source contracts during the cutover; the wider suite is not green.
 - Accepted-state persistence, composed TASK/ART/outbox commit and T4 race/rollback
   proof remain unfinished. No public acceptance or continuation is exposed here.
+
+### Composed accepted handoff implementation and remaining proof
+
+The existing foreground admission owner now composes T4 under its root transaction:
+current own-read/Submitter authority, canonical TASK/PROJECT/revision context,
+exact locked eligible PRE, operation-scoped acceptance consumption, identifier-only
+finalization event, immutable receipt/context and the direct TASK pending transition.
+Replay validates the retained decision, receipt, PRE and event without rechecking
+foreground eligibility. Connection/acknowledgement uncertainty resolves the same
+operation in a fresh root. A PostgreSQL constraint rejection is a known rollback,
+not a transport-unknown outcome.
+
+Migration 0073 extends active custody to `finalization_pending`, retains unique
+PRE/decision/event references, and adds deferred exact context, receipt, authority,
+event and TASK closure. Only transition into accepted custody checks the current
+foreground deadline. Revision head/acknowledgement, cap, predecessor and deadline
+are also checked at that transition; accepted reads do not reapply them. Source
+charge and accepted fields remain immutable. No formal Submission, retained binding
+or POST event is created by T4.
+
+Evidence for this worktree:
+
+- `/tmp/t4-transaction-proofs.log`: five composed initial acceptance/replay,
+  outbox/TASK rollback, concurrent duplicate and lost-acknowledgement cases passed.
+- `/tmp/t4-all-admission.log`: 25 passed, including existing T1/replay behavior and
+  accepted mutation/cleanup refusal, revoked authority, both independent-session
+  acceptance/abandonment winner orders and expiry at the deferred commit boundary.
+- `/tmp/t4-lifetime-final.log`: six passed after adding cancellation/late revocation
+  and changing expiry fixtures to observe database time rather than infer it from
+  a host sleep. These replay the changed race/deadline cases as well.
+- Earlier runs exposed multi-statement asyncpg execution and deferred PL/pgSQL
+  expression errors in the draft migration; both were repaired before the above
+  passing runs. One composed run was rejected during sealing because observed
+  `sealed_at` preceded EOF. The guard was retained; subsequent composed runs
+  passed. None of this is native-provider qualification.
+
+The current schema fingerprint is
+`5a1f343869d5599158b74372e1a150fe913659313b03f71185a4360c8163e186`.
+The original seven obsolete prepared-coordination fixture failures remain open;
+these passing runs do not claim a green full backend suite.
+
+T4 is not declared complete: a real revision handoff, the foreground heartbeat
+across the whole composed command, all planned denial/SQL substitution cases and
+focused implementation review remain required. Current revision fixture setup
+calls the removed prepared-source producer (`submission_admission.py` still passes
+`commitment`/`manifest` and prepared-generation selectors to source-only builders).
+Restoring that obsolete execution path would move away from the requested contract.
+The new T5 path must create the predecessor for the actual revision proof. This
+changes proof sequencing, not the required revision behavior or completion bar.
+No public accepted route or live finalization handler is exposed by this checkpoint.
+
+### Durable accepted finalization (T5) plan
+
+Close the concrete remaining gap: an accepted source currently holds TASK/capacity
+and an outbox event but cannot become a formal Submission or start POST. Extend
+existing ART custody, TASK Submission construction and CHECKERS evaluation dispatch;
+do not implement a second independent Submission writer or restore prepared PRE.
+
+Required behavior:
+
+1. Register `SubmissionFinalizationRequested` with the existing durable outbox
+   composition and fixed-service authority. Claim a separately fenced accepted
+   continuation in a short transaction. Recognize and validate an already finalized
+   operation before requiring a pending TASK pointer or a new lease.
+2. Observe only the recorded immutable source generation/size outside TASK locks
+   through the existing typed ART provider composition. Combine observation with
+   committed ingress and exact PRE hash/manifest evidence; metadata alone cannot
+   authorize adopting an arbitrary object. Do not upload/copy/read the ZIP again
+   merely to create a retained identity; register the exact already stored object.
+3. Under TASK → operation owner locks, consume narrow service continuation
+   authority over immutable acceptance and the current continuation fence. Do not
+   call ordinary contributor creation with an `evaluation_pending` exception or
+   recheck the original bearer token, grant, revision cap/deadline or foreground
+   lease. Preserve accepted initial/revision status as historical dispatch evidence.
+4. Reuse logical ART content only for exact SHA/count identity, record a replica
+   for the actual source key/generation with trusted verification provenance, and
+   bind it to the actual newly allocated Submission. Reuse existing ART owners and
+   binding rules. Required schema extensions must distinguish source custody from
+   retained prepared receipts without fake put, prepared-generation or verifier IDs.
+5. Reuse `build_submission`, existing policy snapshots, global version allocation,
+   assignment revision-round accounting, selected POST request construction and
+   outbox append. One transaction commits formal Submission, exact ART binding,
+   evaluation/dispatch/reservation, POST event, finalized operation association and
+   pointer release. Retries return that immutable association; no duplicate version,
+   binding, revision round, dispatch or event is permitted.
+6. Keep the source retained/protected through failure, retry, lease loss and provider
+   uncertainty. Only separately authorized cleanup may later delete eligible data.
+   Do not invent administrative cancellation or silently reopen/reassign accepted
+   work on later grant changes.
+
+Allowed scope: ART intake/source/API/models/repository and retained material/binding
+owners; TASK Submission API/composition/participants/replay/dispatch and affected
+lineage readers; AUTH closed continuation/binding contracts and adapters/catalogue;
+existing CHECKERS POST content/reservation adapters; outbox handler registration;
+new forward migration 0074 and affected schema fingerprint; tests/CI selection and
+direct contracts/this record. Inspect shared consumers before changing retained
+admission/verification fields. Retained rows remain readable; new execution must
+use accepted source custody. Public raw-ZIP/API/CLI/MCP replacement remains required
+in this same PR after a real finalization handler is available.
+
+Prohibited: fresh human submission authorization in T5, renewed PRE or a second PRE
+VM, host ZIP inspection/spooling, whole-source re-upload/copy to a new key, arbitrary
+locator/hash adoption, fake legacy identifiers, parallel provider factories,
+replacing POST routing/review/contribution owners, source cleanup before retained
+custody, defaulting unqualified C-values, deployment or merge.
+
+Risk: L0/L1 authority, workflow and immutable evidence. Required review: ARCH/SEC
+for plan/continuation and storage closure, QA for transaction/race/public-journey
+proof, DOCS for exact exposure and qualification claims. Human merge review should
+focus on accepted authority lifetime, source-to-retained provenance, replay before
+currentness, revision accounting, and removal of superseded public producers.
+
+Verification: real PostgreSQL plus actual Local/MinIO source ownership where the
+provider behavior is claimed; actual ZIP and worker proof with explicitly simulated
+runtime observations until native qualification is available. Exercise accepted
+T4 → finalization → reserved POST and existing POST completion/routing, then create
+a real governed revision source and exercise T4/T5 again. Test rollback between
+participants, duplicate deliveries and claims, lease fencing, lost commit response,
+broker/observation failure and retry, exact finalized replay after TASK advances,
+and successful continuation after original foreground/revision windows and grants
+expire. Probe SQL association/provenance substitution and source deletion refusal.
+Run affected retained-reader and POST policy branches, including default human
+review and configured automatic final acceptance/contribution evidence. Finish the
+public API/CLI/MCP drill and A01–A35/C01–C07 audit before overall completion; internal
+T4/T5 tests alone cannot close the goal.
diff --git a/backend/alembic/versions/0073_submission_acceptance.py b/backend/alembic/versions/0073_submission_acceptance.py
new file mode 100644
index 000000000..f0c106c83
--- /dev/null
+++ b/backend/alembic/versions/0073_submission_acceptance.py
@@ -0,0 +1,253 @@
+"""Bind accepted source custody to TASK, immutable PRE, AUTH and finalization outbox."""
+import re
+
+from alembic import op
+from sqlalchemy import text
+
+revision = "0073_submission_acceptance"
+down_revision = "0072_pre_invocation_receipts"
+branch_labels = None
+depends_on = None
+
+_ACCEPTED = {
+    "accepted_at": "timestamptz", "acceptance_decision_id": "uuid",
+    "selected_pre_submit_run_id": "uuid", "selected_pre_submit_request_sha256": "varchar(71)",
+    "selected_pre_submit_terminal_sha256": "varchar(71)", "accepted_source_sha256": "varchar(71)",
+    "accepted_manifest_sha256": "varchar(71)", "accepted_context": "jsonb",
+    "accepted_context_sha256": "varchar(71)", "acceptance_receipt": "jsonb",
+    "acceptance_receipt_sha256": "varchar(71)", "finalization_event_id": "uuid",
+}
+
+
+def _replace(signature, old, new):
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))"
+    ), {"signature": signature}).scalar_one()
+    if body.count(old) != 1:
+        raise RuntimeError("acceptance predecessor shape changed: " + signature)
+    op.execute(body.replace(old, new))
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.workstream_tasks, public.submission_intake_operations, "
+               "public.selected_pre_submit_runs, public.outbox_events IN ACCESS EXCLUSIVE MODE")
+    for name, sql_type in _ACCEPTED.items():
+        op.execute(f"ALTER TABLE public.submission_intake_operations ADD COLUMN {name} {sql_type}")
+    for name, target, label in (
+        ("acceptance_decision_id", "audit_events(id)", "acceptance_decision"),
+        ("selected_pre_submit_run_id", "selected_pre_submit_runs(id)", "accepted_pre_run"),
+        ("finalization_event_id", "outbox_events(event_id)", "finalization_event"),
+    ):
+        op.execute(f"ALTER TABLE public.submission_intake_operations ADD CONSTRAINT fk_intake_{label} "
+                   f"FOREIGN KEY ({name}) REFERENCES public.{target} DEFERRABLE INITIALLY DEFERRED")
+        op.execute(f"ALTER TABLE public.submission_intake_operations ADD CONSTRAINT uq_intake_{label} UNIQUE ({name})")
+    conditions = {
+        "foreground_state": "state in ('receiving','pre_checking','finalization_pending','rejected','failed','abandoned','cancelled')",
+        "pre_requires_source": "state not in ('pre_checking','finalization_pending') or sealed_at is not null",
+        "terminal_shape": "(state in ('receiving','pre_checking','finalization_pending') and terminal_at is null and failure_code is null) or "
+                          "(state in ('rejected','failed','abandoned','cancelled') and terminal_at is not null and failure_code is not null)",
+    }
+    for name, condition in conditions.items():
+        op.execute(f"ALTER TABLE public.submission_intake_operations DROP CONSTRAINT ck_submission_intake_operations_{name}")
+        op.execute(f"ALTER TABLE public.submission_intake_operations ADD CONSTRAINT ck_submission_intake_operations_{name} CHECK ({condition})")
+    present = " AND ".join(f"{name} IS NOT NULL" for name in _ACCEPTED)
+    absent = " AND ".join(f"{name} IS NULL" for name in _ACCEPTED)
+    op.execute("ALTER TABLE public.submission_intake_operations ADD CONSTRAINT "
+               "ck_submission_intake_operations_acceptance_shape CHECK "
+               f"((state='finalization_pending' AND {present}) OR (state<>'finalization_pending' AND {absent}))")
+    op.execute("DROP INDEX public.uq_submission_intake_active_task")
+    op.execute("CREATE UNIQUE INDEX uq_submission_intake_active_task ON public.submission_intake_operations(task_id) "
+               "WHERE state IN ('receiving','pre_checking','finalization_pending')")
+    excluded = ",".join("'" + name + "'" for name in ("state", *_ACCEPTED))
+    anchor = "  IF (to_jsonb(NEW)-ARRAY['state','lease_generation','lease_expires_at','raw_sha256',"
+    handoff = f"""  IF OLD.state='pre_checking' AND NEW.state='finalization_pending' THEN
+    IF (to_jsonb(NEW)-ARRAY[{excluded}]) IS DISTINCT FROM (to_jsonb(OLD)-ARRAY[{excluded}])
+       OR OLD.lease_expires_at<=clock_timestamp() OR OLD.pre_deadline_at<=clock_timestamp()
+       OR NOT isfinite(NEW.accepted_at) OR NEW.accepted_atclock_timestamp() THEN
+      RAISE EXCEPTION 'invalid accepted intake transition' USING ERRCODE='23514';
+    END IF;
+    RETURN NEW;
+  END IF;
+"""
+    _replace("public.guard_submission_intake_mutation()", anchor, handoff + anchor)
+    _replace("public.check_submission_intake_custody()",
+             "WHERE task_id=task_key AND state IN ('receiving','pre_checking');",
+             "WHERE task_id=task_key AND state IN ('receiving','pre_checking','finalization_pending');")
+    _replace("public.check_submission_intake_custody()",
+             "OR t.status IS DISTINCT FROM o.eligible_task_status",
+             "OR t.status IS DISTINCT FROM (CASE WHEN o.state='finalization_pending' THEN 'evaluation_pending' ELSE o.eligible_task_status END)")
+    for statement in re.split(r"\n(?=CREATE (?:FUNCTION|CONSTRAINT TRIGGER))", _CLOSURE):
+        if statement.strip():
+            op.execute(statement)
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
+
+
+_CLOSURE = r"""
+CREATE FUNCTION public.submission_acceptance_context(o public.submission_intake_operations, r public.selected_pre_submit_runs)
+RETURNS jsonb LANGUAGE sql IMMUTABLE SET search_path=pg_catalog,public,pg_temp AS $$
+ SELECT jsonb_build_object(
+   'schema_version','workstream.submission_acceptance_context.v1','operation_id',o.id::text,
+   'metadata_sha256',o.metadata_sha256,'locked_context_sha256',o.locked_context_sha256,
+   'selected_pre_submit_run_id',r.id::text,'selected_pre_submit_request_sha256',r.request_digest,
+   'selected_pre_submit_terminal_sha256',r.terminal_digest,'source_sha256',r.request_json->>'source_sha256',
+   'semantic_manifest_sha256',r.terminal_json->'execution'->>'manifest_sha256',
+   'predecessor_submission_id',r.request_json->'admission_lineage'->'predecessor_submission_id',
+   'predecessor_submission_version',r.request_json->'admission_lineage'->'predecessor_submission_version',
+   'checker_remediation_manifest_id',r.request_json->'admission_lineage'->'checker_remediation_manifest_id')
+$$;
+
+CREATE FUNCTION public.submission_acceptance_results(execution jsonb)
+RETURNS jsonb LANGUAGE sql IMMUTABLE SET search_path=pg_catalog,public,pg_temp AS $$
+ SELECT coalesce(jsonb_agg(value ORDER BY section, ordinality),'[]'::jsonb) FROM (
+  SELECT 1 AS section, ordinality, jsonb_build_object('source','workstream_default',
+    'check_id',value->'check_id','status',value->'status','failure_code',value->'failure_code',
+    'finding_count',value->'finding_count') AS value
+  FROM jsonb_array_elements(execution->'workstream_default'->'checks') WITH ORDINALITY
+  UNION ALL
+  SELECT 2, ordinality, jsonb_build_object('source','workstream_default','status','warning','warning_code',value->'code')
+  FROM jsonb_array_elements(execution->'workstream_default'->'warnings') WITH ORDINALITY
+  UNION ALL
+  SELECT 3, ordinality, jsonb_build_object('source','project_external_checker',
+    'requirement_id',value->'requirement_id','registry_entry_id',value->'registry_entry_id',
+    'registry_entry_digest',value->'registry_entry_digest','status',value->'result'->'verdict',
+    'findings',value->'result'->'findings')
+  FROM jsonb_array_elements(execution->'external_members') WITH ORDINALITY
+ ) projected
+$$;
+
+CREATE FUNCTION public.require_submission_acceptance(o public.submission_intake_operations)
+RETURNS void LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE r public.selected_pre_submit_runs%ROWTYPE; a public.audit_events%ROWTYPE;
+ e public.outbox_events%ROWTYPE; context jsonb; resource jsonb; receipt jsonb; payload jsonb;
+BEGIN
+ SELECT * INTO r FROM public.selected_pre_submit_runs WHERE id=o.selected_pre_submit_run_id;
+ IF r.id IS NULL OR r.source_operation_id IS DISTINCT FROM o.id OR r.status<>'completed' OR r.eligible IS DISTINCT FROM true
+    OR r.execute_evidence_id IS NULL OR r.finalize_evidence_id IS NULL
+    OR r.request_json->>'schema_version' IS DISTINCT FROM 'workstream.selected_pre_submit_reservation.v2'
+    OR r.terminal_json->>'schema_version' IS DISTINCT FROM 'workstream.selected_pre_submit_terminal.v3'
+    OR r.request_digest IS DISTINCT FROM o.selected_pre_submit_request_sha256
+    OR r.terminal_digest IS DISTINCT FROM o.selected_pre_submit_terminal_sha256
+    OR r.request_json->>'source_sha256' IS DISTINCT FROM o.accepted_source_sha256
+    OR r.terminal_json->'execution'->>'manifest_sha256' IS DISTINCT FROM o.accepted_manifest_sha256
+    OR r.actor_profile_id IS DISTINCT FROM o.actor_profile_id OR r.identity_link_id IS DISTINCT FROM o.identity_link_id
+    OR r.task_id IS DISTINCT FROM o.task_id OR r.project_id IS DISTINCT FROM o.project_id
+    OR r.assignment_id IS DISTINCT FROM o.assignment_id OR r.idempotency_key IS DISTINCT FROM o.idempotency_key
+    OR r.request_json->>'foreground_lease_id' IS DISTINCT FROM o.lease_id::text
+    OR r.request_json->'foreground_lease_generation' IS DISTINCT FROM to_jsonb(o.lease_generation)
+    OR r.request_json->>'metadata_sha256' IS DISTINCT FROM o.metadata_sha256
+    OR r.request_json->>'locked_context_sha256' IS DISTINCT FROM o.locked_context_sha256
+    OR r.completed_at>o.accepted_at OR o.accepted_at>=o.lease_expires_at OR o.accepted_at>=o.pre_deadline_at
+ THEN RAISE EXCEPTION 'accepted PRE custody mismatch' USING ERRCODE='23514'; END IF;
+ PERFORM public.require_selected_pre_invocation(r);
+ context:=public.submission_acceptance_context(o,r);
+ IF o.accepted_context IS DISTINCT FROM context
+    OR o.accepted_context_sha256 IS DISTINCT FROM public.external_checker_registry_digest(context)
+ THEN RAISE EXCEPTION 'accepted context mismatch' USING ERRCODE='23514'; END IF;
+ receipt:=jsonb_build_object('operation_id',o.id::text,'task_id',o.task_id::text,'assignment_id',o.assignment_id::text,
+   'status','accepted','accepted_at',replace(public.outbox_dispatch_utc(o.accepted_at),'+00:00','Z'),
+   'task_status_at_acceptance','evaluation_pending','processing_stage_at_acceptance','finalization_pending',
+   'replayed',false,'pre_submission_results',public.submission_acceptance_results(r.terminal_json->'execution'));
+ IF o.acceptance_receipt IS DISTINCT FROM receipt
+    OR o.acceptance_receipt_sha256 IS DISTINCT FROM public.external_checker_registry_digest(receipt)
+ THEN RAISE EXCEPTION 'accepted receipt mismatch' USING ERRCODE='23514'; END IF;
+ resource:=jsonb_strip_nulls(jsonb_build_object(
+   'resource_type','submission_intake_acceptance','resource_id',o.id::text,'operation_id',o.id::text,
+   'scope_project_id',o.project_id::text,'task_id',o.task_id::text,'assignment_id',o.assignment_id::text,
+   'actor_profile_id',o.actor_profile_id::text,'identity_link_id',o.identity_link_id::text,
+   'idempotency_key',o.idempotency_key::text,'metadata_sha256',o.metadata_sha256,
+   'locked_context_sha256',o.locked_context_sha256,'task_status',o.eligible_task_status,
+   'foreground_lease_id',o.lease_id::text,'foreground_lease_generation',o.lease_generation,
+   'selected_pre_submit_run_id',r.id::text,'selected_pre_submit_request_sha256',r.request_digest,
+   'selected_pre_submit_terminal_sha256',r.terminal_digest,'source_sha256',o.accepted_source_sha256,
+   'semantic_manifest_sha256',o.accepted_manifest_sha256,'accepted_context_sha256',o.accepted_context_sha256,
+   'receipt_sha256',o.acceptance_receipt_sha256,'accepted_at',receipt->'accepted_at',
+   'predecessor_submission_id',context->'predecessor_submission_id',
+   'predecessor_submission_version',context->'predecessor_submission_version',
+   'checker_remediation_manifest_id',context->'checker_remediation_manifest_id'));
+ SELECT * INTO a FROM public.audit_events WHERE id=o.acceptance_decision_id;
+ IF a.id IS NULL OR a.event_domain IS DISTINCT FROM 'authority' OR a.event_type IS DISTINCT FROM 'SensitiveAuthorizationAllowed'
+    OR a.actor_ref_kind IS DISTINCT FROM 'actor_profile' OR a.actor_id IS DISTINCT FROM o.actor_profile_id::text
+    OR a.action_id IS DISTINCT FROM 'submission.create' OR a.permission_id IS DISTINCT FROM 'submission.create'
+    OR a.project_id IS DISTINCT FROM o.project_id OR a.resource_type IS DISTINCT FROM 'submission_operation'
+    OR a.resource_id IS DISTINCT FROM o.id::text OR a.target_ref_kind IS DISTINCT FROM 'project'
+    OR a.target_ref_id IS DISTINCT FROM o.project_id::text OR a.denial_code IS NOT NULL
+    OR a.matched_grant_id IS NULL OR a.request_id IS NULL OR a.correlation_id IS NULL
+    OR a.after_facts::jsonb IS DISTINCT FROM jsonb_build_object('allowed',true,'resource_context_digest',
+       public.external_checker_registry_digest(jsonb_build_object('resource_context',resource)))
+ THEN RAISE EXCEPTION 'accepted authority mismatch' USING ERRCODE='23514'; END IF;
+ payload:=jsonb_build_object('operation_id',o.id::text,'project_id',o.project_id::text,'task_id',o.task_id::text,
+   'acceptance_decision_id',o.acceptance_decision_id::text,'accepted_context_sha256',o.accepted_context_sha256,
+   'receipt_sha256',o.acceptance_receipt_sha256);
+ SELECT * INTO e FROM public.outbox_events WHERE event_id=o.finalization_event_id;
+ IF e.event_id IS NULL OR e.event_type<>'SubmissionFinalizationRequested' OR e.event_version<>1
+    OR e.aggregate_type<>'submission_operation' OR e.aggregate_id IS DISTINCT FROM o.id
+    OR e.project_id IS DISTINCT FROM o.project_id OR e.idempotency_key IS DISTINCT FROM 'submission-finalization:'||o.id::text
+    OR e.payload IS DISTINCT FROM payload OR e.correlation_id IS DISTINCT FROM o.id::text
+    OR e.causation_event_id IS NOT NULL
+ THEN RAISE EXCEPTION 'accepted finalization event mismatch' USING ERRCODE='23514'; END IF;
+END $$;
+
+CREATE FUNCTION public.require_submission_acceptance_current(o public.submission_intake_operations)
+RETURNS void LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE p public.task_revision_preparations%ROWTYPE;
+BEGIN
+ IF o.eligible_task_status='in_progress' THEN
+   IF o.accepted_context->'predecessor_submission_id' IS DISTINCT FROM 'null'::jsonb
+      OR o.accepted_context->'predecessor_submission_version' IS DISTINCT FROM 'null'::jsonb
+      OR o.accepted_context->'checker_remediation_manifest_id' IS DISTINCT FROM 'null'::jsonb
+      OR EXISTS(SELECT 1 FROM public.submissions WHERE task_assignment_id=o.assignment_id) THEN
+     RAISE EXCEPTION 'initial acceptance predecessor mismatch' USING ERRCODE='23514';
+   END IF;
+ ELSE
+   SELECT * INTO p FROM public.task_revision_preparations
+     WHERE id=(o.command_metadata->>'revision_preparation_id')::uuid;
+   IF p.id IS NULL OR p.task_id IS DISTINCT FROM o.task_id OR p.assignment_id IS DISTINCT FROM o.assignment_id
+      OR p.contributor_id IS DISTINCT FROM o.actor_profile_id
+      OR p.preparation_sha256 IS DISTINCT FROM o.command_metadata->>'revision_preparation_sha256'
+      OR p.submission_id::text IS DISTINCT FROM o.accepted_context->>'predecessor_submission_id'
+      OR to_jsonb(p.source_submission_version) IS DISTINCT FROM o.accepted_context->'predecessor_submission_version'
+      OR p.routing_manifest_id::text IS DISTINCT FROM o.accepted_context->>'checker_remediation_manifest_id'
+      OR p.blocked_reason IS NOT NULL OR p.outcome NOT IN ('kept','rebased')
+      OR p.deadline_at IS NULL OR p.deadline_at<=clock_timestamp()
+      OR p.next_revision_round>p.max_revision_rounds
+      OR EXISTS(SELECT 1 FROM public.task_revision_preparations WHERE predecessor_id=p.id)
+      OR EXISTS(SELECT 1 FROM public.submissions WHERE task_id=o.task_id AND version>p.source_submission_version) THEN
+     RAISE EXCEPTION 'revision acceptance is no longer eligible' USING ERRCODE='23514';
+   END IF;
+ END IF;
+END $$;
+
+CREATE FUNCTION public.check_submission_acceptance()
+RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE o public.submission_intake_operations%ROWTYPE;
+BEGIN
+ IF TG_TABLE_NAME='outbox_events' THEN
+   IF NEW.event_type<>'SubmissionFinalizationRequested' THEN RETURN NULL; END IF;
+   SELECT * INTO o FROM public.submission_intake_operations WHERE finalization_event_id=NEW.event_id;
+   IF o.id IS NULL OR o.state<>'finalization_pending' THEN
+     RAISE EXCEPTION 'finalization event has no accepted owner' USING ERRCODE='23514';
+   END IF;
+ ELSE
+   IF NEW.state<>'finalization_pending' THEN RETURN NULL; END IF;
+   SELECT * INTO o FROM public.submission_intake_operations WHERE id=NEW.id;
+   IF TG_OP='UPDATE' AND OLD.state<>'finalization_pending'
+      AND (o.lease_expires_at<=clock_timestamp() OR o.pre_deadline_at<=clock_timestamp()) THEN
+     RAISE EXCEPTION 'acceptance expired before commit' USING ERRCODE='23514';
+   END IF;
+   IF TG_OP='UPDATE' AND OLD.state<>'finalization_pending' THEN
+     PERFORM public.require_submission_acceptance_current(o);
+   END IF;
+ END IF;
+ PERFORM public.require_submission_acceptance(o);
+ RETURN NULL;
+END $$;
+CREATE CONSTRAINT TRIGGER submission_acceptance_closure AFTER INSERT OR UPDATE ON public.submission_intake_operations
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_acceptance();
+CREATE CONSTRAINT TRIGGER submission_finalization_event_closure AFTER INSERT OR UPDATE ON public.outbox_events
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_acceptance();
+"""
diff --git a/backend/app/modules/artifacts/intake/acceptance.py b/backend/app/modules/artifacts/intake/acceptance.py
new file mode 100644
index 000000000..2607fc093
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/acceptance.py
@@ -0,0 +1,87 @@
+"""Exact T4 receipt, accepted context and identifier-only finalization event."""
+from datetime import datetime
+from uuid import UUID
+
+from app.core.hashing import canonical_json_hash
+from app.modules.artifacts.api.submission_preparation import public_pre_submission_results
+from app.modules.authorization.api.submission_intake import IntakeAcceptanceAuthorityFacts
+from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitTerminalFacts
+from app.modules.outbox.api import OutboxAppendInput
+
+
+def acceptance_context(terminal: SelectedPreSubmitTerminalFacts) -> dict:
+    request = terminal.lease.reservation
+    lineage = request.admission_lineage
+    return {
+        "schema_version": "workstream.submission_acceptance_context.v1",
+        "operation_id": str(request.source.location.operation_id),
+        "metadata_sha256": request.metadata_sha256, "locked_context_sha256": request.locked_context_sha256,
+        "selected_pre_submit_run_id": str(request.attempt_id),
+        "selected_pre_submit_request_sha256": request.request_digest,
+        "selected_pre_submit_terminal_sha256": terminal.terminal_digest,
+        "source_sha256": request.source.source_sha256(),
+        "semantic_manifest_sha256": terminal.execution.manifest_sha256,
+        "predecessor_submission_id": str(lineage.predecessor_submission_id) if lineage.predecessor_submission_id else None,
+        "predecessor_submission_version": lineage.predecessor_submission_version,
+        "checker_remediation_manifest_id": str(lineage.checker_remediation_manifest_id) if lineage.checker_remediation_manifest_id else None,
+    }
+
+
+def acceptance_receipt(terminal: SelectedPreSubmitTerminalFacts, accepted_at: datetime) -> dict:
+    request = terminal.lease.reservation
+    return {
+        "operation_id": str(request.source.location.operation_id), "task_id": str(request.task_id),
+        "assignment_id": str(request.assignment_id), "status": "accepted",
+        "accepted_at": accepted_at.isoformat().replace("+00:00", "Z"),
+        "task_status_at_acceptance": "evaluation_pending",
+        "processing_stage_at_acceptance": "finalization_pending", "replayed": False,
+        "pre_submission_results": public_pre_submission_results(terminal.execution),
+    }
+
+
+def authority_facts(row) -> IntakeAcceptanceAuthorityFacts:
+    """Reconstruct exact immutable authority without consulting later eligibility."""
+    context = row.accepted_context
+    return IntakeAcceptanceAuthorityFacts(
+        operation_id=UUID(row.id), project_id=UUID(row.project_id), task_id=UUID(row.task_id),
+        assignment_id=UUID(row.assignment_id), actor_profile_id=UUID(row.actor_profile_id),
+        identity_link_id=UUID(row.identity_link_id), idempotency_key=UUID(row.idempotency_key),
+        metadata_sha256=row.metadata_sha256, locked_context_sha256=row.locked_context_sha256,
+        task_status=row.eligible_task_status, foreground_lease_id=UUID(row.lease_id),
+        foreground_lease_generation=row.lease_generation,
+        selected_pre_submit_run_id=UUID(row.selected_pre_submit_run_id),
+        selected_pre_submit_request_sha256=row.selected_pre_submit_request_sha256,
+        selected_pre_submit_terminal_sha256=row.selected_pre_submit_terminal_sha256,
+        source_sha256=row.accepted_source_sha256, semantic_manifest_sha256=row.accepted_manifest_sha256,
+        accepted_context_sha256=row.accepted_context_sha256, receipt_sha256=row.acceptance_receipt_sha256,
+        accepted_at=row.accepted_at,
+        predecessor_submission_id=UUID(context["predecessor_submission_id"]) if context["predecessor_submission_id"] else None,
+        predecessor_submission_version=context["predecessor_submission_version"],
+        checker_remediation_manifest_id=UUID(context["checker_remediation_manifest_id"]) if context["checker_remediation_manifest_id"] else None,
+    )
+
+
+def finalization_event(row) -> OutboxAppendInput:
+    return OutboxAppendInput(
+        event_type="SubmissionFinalizationRequested", event_version=1,
+        aggregate_type="submission_operation", aggregate_id=UUID(row.id), project_id=UUID(row.project_id),
+        correlation_id=row.id, idempotency_key="submission-finalization:" + row.id,
+        payload={"operation_id": row.id, "project_id": row.project_id, "task_id": row.task_id,
+                 "acceptance_decision_id": row.acceptance_decision_id,
+                 "accepted_context_sha256": row.accepted_context_sha256,
+                 "receipt_sha256": row.acceptance_receipt_sha256},
+    )
+
+
+def stage_acceptance(row, terminal: SelectedPreSubmitTerminalFacts, accepted_at: datetime) -> None:
+    """Stage evidence only; the composer must supply decision/event before flushing."""
+    row.accepted_at = accepted_at
+    row.selected_pre_submit_run_id = str(terminal.lease.reservation.attempt_id)
+    row.selected_pre_submit_request_sha256 = terminal.lease.reservation.request_digest
+    row.selected_pre_submit_terminal_sha256 = terminal.terminal_digest
+    row.accepted_source_sha256 = terminal.lease.reservation.source.source_sha256()
+    row.accepted_manifest_sha256 = terminal.execution.manifest_sha256
+    row.accepted_context = acceptance_context(terminal)
+    row.accepted_context_sha256 = canonical_json_hash(row.accepted_context)
+    row.acceptance_receipt = acceptance_receipt(terminal, accepted_at)
+    row.acceptance_receipt_sha256 = canonical_json_hash(row.acceptance_receipt)
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index 3a03e341d..00d038199 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -1,16 +1,18 @@
-"""Authorized T1 reservation and exact replay, without body/provider writes.
+"""Authorized T1 reservation, T4 accepted handoff and exact replay.
 
 Only a positively acknowledged reservation returns a foreground owner. A raced
 key or uncertain commit resolves the stored operation through current read
 authority and cannot acquire a replacement lease or start a second upload.
 """
+import json
+
 from collections.abc import AsyncIterator, Callable
 from contextlib import asynccontextmanager
 from dataclasses import asdict, dataclass
 from datetime import UTC, datetime, timedelta
 from uuid import UUID
 
-from sqlalchemy import func, select
+from sqlalchemy import func, select, text
 from sqlalchemy.exc import IntegrityError
 from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
 
@@ -28,6 +30,8 @@
     IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts,
 )
 from app.modules.checkers.api.external_policy import LockedExternalCheckerPolicies
+from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitCoordinationPort, SelectedPreSubmitReservationFacts
+from app.modules.outbox.api import OutboxAppendPort
 from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextPort, ProjectLockedPolicyContextRequest
 from app.modules.projects.api.policy_lineage import RevisionPolicySemantics
 from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort
@@ -64,7 +68,7 @@ class _ExistingKey(RuntimeError):
 
 
 class ForegroundIntakeAdmission:
-    """Reserve one authorized foreground owner or resolve its immutable retry key."""
+    """Own reservation and acceptance roots without body or provider I/O."""
     def __init__(
         self, sessions: async_sessionmaker[AsyncSession], *,
         tasks: Callable[[AsyncSession], IntakeTaskCustodyPort],
@@ -102,6 +106,10 @@ async def _root(self):
             else:
                 try:
                     await await_completion_preserving_cancellation(session.commit())
+                except IntegrityError:
+                    # PostgreSQL rejected this transaction; unlike transport loss,
+                    # a constraint failure positively proves no acceptance commit.
+                    raise
                 except Exception as exc:
                     raise IntakeCommitUnknown("intake commit acknowledgement unavailable") from exc
         finally:
@@ -185,6 +193,98 @@ async def _validate_context(self, session, metadata, actor_id):
             raise IntakeCustodyConflict("intake_namespace_unavailable")
         if namespace.provider_profile not in {"local-v2", "minio-v1"}:
             raise IntakeCustodyConflict("intake_source_provider_unqualified")
+        return task, project
+
+    async def accept(
+        self, owner: IntakeReservationOwner, request: SelectedPreSubmitReservationFacts, terminal_digest: str, *,
+        checkers: Callable[[AsyncSession], SelectedPreSubmitCoordinationPort],
+        outbox: Callable[[AsyncSession], OutboxAppendPort],
+    ) -> dict:
+        """Commit T4 or resolve an uncertain acknowledgement by the same operation.
+
+        checkers/outbox are transaction-local owner ports supplied by composition.
+        The surrounding foreground lease must continue heartbeating through here.
+        """
+        try:
+            async with self._root() as (session, authority):
+                repository = SubmissionIntakeRepository(session, self._tasks(session))
+                row = await repository._lock(owner.operation_id)
+                await authority.authorize_read(IntakeOperationReadFacts(
+                    UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id)))
+                self._match_acceptance_command(row, request, terminal_digest, accepted=row.state == "finalization_pending")
+                if row.state == "finalization_pending":
+                    return await self._accepted_receipt(session, authority, row)
+                receipt = await self._accept_new(session, authority, repository, row, owner,
+                                                 request, terminal_digest, checkers, outbox)
+            return receipt
+        except IntegrityError as exc:
+            raise IntakeCustodyConflict("intake_acceptance_conflict") from exc
+        except IntakeCommitUnknown:
+            async with self._root() as (session, authority):
+                row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(owner.operation_id)
+                await authority.authorize_read(IntakeOperationReadFacts(
+                    UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id)))
+                if row.state != "finalization_pending":
+                    raise IntakeCommitUnknown("submission acceptance outcome is unresolved")
+                self._match_acceptance_command(row, request, terminal_digest, accepted=True)
+                return await self._accepted_receipt(session, authority, row)
+
+    @staticmethod
+    def _match_acceptance_command(row, request, terminal_digest, *, accepted):
+        if (row.id != str(request.source.location.operation_id)
+                or row.actor_profile_id != str(request.actor_profile_id)
+                or row.idempotency_key != str(request.idempotency_key)
+                or row.metadata_sha256 != request.metadata_sha256
+                or row.locked_context_sha256 != request.locked_context_sha256
+                or (accepted and (row.selected_pre_submit_run_id != str(request.attempt_id)
+                    or row.selected_pre_submit_request_sha256 != request.request_digest
+                    or row.selected_pre_submit_terminal_sha256 != terminal_digest))):
+            raise IntakeCustodyConflict("intake_acceptance_conflict")
+
+    async def _accepted_receipt(self, session, authority, row):
+        from app.modules.artifacts.intake.acceptance import authority_facts
+        await authority.validate_acceptance_receipt(authority_facts(row), UUID(row.acceptance_decision_id))
+        await session.execute(text("SELECT public.require_submission_acceptance(o) "
+                                   "FROM public.submission_intake_operations o WHERE id=:id"), {"id": UUID(row.id)})
+        return dict(row.acceptance_receipt, replayed=True)
+
+    async def _accept_new(self, session, authority, repository, row, owner,
+                          request, terminal_digest, checkers, outbox):
+        from types import SimpleNamespace
+        from app.modules.artifacts.intake.acceptance import authority_facts, finalization_event, stage_acceptance
+        row = await repository._owned(owner.operation_id, owner.lease_id, owner.generation)
+        if row.state != "pre_checking":
+            raise IntakeCustodyConflict("intake_acceptance_conflict")
+        await authority.lock_actor(UUID(row.actor_profile_id), UUID(row.identity_link_id))
+        await authority.preflight(IntakeReservationPreflightFacts(
+            UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.assignment_id),
+            UUID(row.actor_profile_id), UUID(row.identity_link_id), UUID(row.idempotency_key), row.metadata_sha256))
+        metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
+        task, project = await self._validate_context(session, metadata, UUID(row.actor_profile_id))
+        lineage = request.admission_lineage
+        predecessor = task.predecessor
+        if (task.status != row.eligible_task_status
+                or (predecessor.submission_id if predecessor else None) != lineage.predecessor_submission_id
+                or (predecessor.version if predecessor else None) != lineage.predecessor_submission_version
+                or task.checker_remediation_manifest_id != lineage.checker_remediation_manifest_id
+                or LockedExternalCheckerPolicies.model_validate_json(project.external_checker_policies.value).pre_submit != request.policy):
+            raise IntakeCustodyConflict("intake_acceptance_context_changed")
+        terminal = await checkers(session).lock_acceptance(
+            run_id=request.attempt_id, facts=request, terminal_digest=terminal_digest)
+        draft = SimpleNamespace(**{name: getattr(row, name) for name in (
+            "id", "project_id", "task_id", "assignment_id", "actor_profile_id", "identity_link_id",
+            "idempotency_key", "metadata_sha256", "locked_context_sha256", "eligible_task_status",
+            "lease_id", "lease_generation")})
+        stage_acceptance(draft, terminal, await session.scalar(select(func.clock_timestamp())))
+        facts = authority_facts(draft)
+        draft.acceptance_decision_id = str(await authority.consume_acceptance(
+            await authority.prepare_acceptance(facts), facts))
+        draft.finalization_event_id = str((await outbox(session).append(finalization_event(draft))).event_id)
+        for name, value in vars(draft).items():
+            setattr(row, name, value)
+        row.state = "finalization_pending"
+        await self._tasks(session).accept(UUID(row.task_id), UUID(row.id), row.eligible_task_status)
+        return dict(row.acceptance_receipt)
 
     async def _read(self, metadata, actor_id, key, *, expected_operation_id=None):
         """Authorize the stored operation before comparing metadata or returning its state."""
diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py
index 54651f453..21ca9c8ad 100644
--- a/backend/app/modules/artifacts/intake/models.py
+++ b/backend/app/modules/artifacts/intake/models.py
@@ -1,4 +1,4 @@
-"""ART-owned durable foreground custody before submission acceptance."""
+"""ART-owned durable foreground and accepted source custody."""
 
 from datetime import datetime
 
@@ -16,8 +16,8 @@
 class SubmissionIntakeOperation(Base):
     """One immutable command/source with a fenced, non-resumable foreground owner.
 
-    Accepted states are deliberately unavailable until the accepted-authority
-    and outbox transaction is installed. This table grants no provider capability.
+    Accepted custody retains the source and task pointer for durable finalization.
+    This table grants no provider capability.
     """
 
     __tablename__ = "submission_intake_operations"
@@ -30,7 +30,7 @@ class SubmissionIntakeOperation(Base):
         ForeignKeyConstraint(["assignment_id", "task_id", "actor_profile_id"], ["task_assignments.id", "task_assignments.task_id", "task_assignments.contributor_id"], name="fk_submission_intake_assignment", deferrable=True, initially="DEFERRED"),
         ForeignKeyConstraint(["identity_link_id", "actor_profile_id"], ["actor_identity_links.id", "actor_identity_links.actor_profile_id"], name="fk_submission_intake_identity", deferrable=True, initially="DEFERRED"),
         ForeignKeyConstraint(["namespace_id", "namespace_fingerprint"], ["artifact_storage_namespaces.id", "artifact_storage_namespaces.namespace_fingerprint"], name="fk_submission_intake_namespace"),
-        CheckConstraint("state in ('receiving','pre_checking','rejected','failed','abandoned','cancelled')", name="foreground_state"),
+        CheckConstraint("state in ('receiving','pre_checking','finalization_pending','rejected','failed','abandoned','cancelled')", name="foreground_state"),
         CheckConstraint("eligible_task_status in ('in_progress','needs_revision')", name="eligible_status"),
         CheckConstraint("metadata_sha256 ~ '^sha256:[0-9a-f]{64}$' and locked_context_sha256 ~ '^sha256:[0-9a-f]{64}$'", name="identity_digests"),
         CheckConstraint("jsonb_typeof(command_metadata)='object' and jsonb_typeof(locked_task_context)='object'", name="command_shape"),
@@ -39,9 +39,16 @@ class SubmissionIntakeOperation(Base):
         CheckConstraint("lease_generation>0 and lease_expires_at<=coalesce(pre_deadline_at,upload_deadline_at) and upload_deadline_at>created_at", name="lease_bounds"),
         CheckConstraint("(raw_sha256 is null and raw_byte_count is null and eof_at is null) or (raw_sha256 is not null and raw_sha256 ~ '^sha256:[0-9a-f]{64}$' and raw_byte_count is not null and raw_byte_count between 1 and maximum_raw_bytes and eof_at is not null)", name="eof_identity"),
         CheckConstraint("(provider_generation is null and sealed_upload_fence is null and sealed_at is null and pre_deadline_at is null) or (provider_generation is not null and sealed_upload_fence is not null and sealed_upload_fence>0 and length(provider_generation)>0 and raw_sha256 is not null and sealed_at is not null and sealed_at>=eof_at and pre_deadline_at is not null and pre_deadline_at>sealed_at and (provider_profile<>'aws-s3-v1' or provider_generation<>'null'))", name="sealed_identity"),
-        CheckConstraint("state<>'pre_checking' or sealed_at is not null", name="pre_requires_source"),
-        CheckConstraint("(state in ('receiving','pre_checking') and terminal_at is null and failure_code is null) or (state in ('rejected','failed','abandoned','cancelled') and terminal_at is not null and failure_code is not null)", name="terminal_shape"),
-        Index("uq_submission_intake_active_task", "task_id", unique=True, postgresql_where=text("state in ('receiving','pre_checking')")),
+        CheckConstraint("state not in ('pre_checking','finalization_pending') or sealed_at is not null", name="pre_requires_source"),
+        CheckConstraint("(state in ('receiving','pre_checking','finalization_pending') and terminal_at is null and failure_code is null) or (state in ('rejected','failed','abandoned','cancelled') and terminal_at is not null and failure_code is not null)", name="terminal_shape"),
+        ForeignKeyConstraint(["acceptance_decision_id"], ["audit_events.id"], name="fk_intake_acceptance_decision", deferrable=True, initially="DEFERRED"),
+        ForeignKeyConstraint(["selected_pre_submit_run_id"], ["selected_pre_submit_runs.id"], name="fk_intake_accepted_pre_run", deferrable=True, initially="DEFERRED"),
+        ForeignKeyConstraint(["finalization_event_id"], ["outbox_events.event_id"], name="fk_intake_finalization_event", deferrable=True, initially="DEFERRED"),
+        CheckConstraint("(state='finalization_pending' and accepted_at is not null and acceptance_decision_id is not null and selected_pre_submit_run_id is not null and selected_pre_submit_request_sha256 is not null and selected_pre_submit_terminal_sha256 is not null and accepted_source_sha256 is not null and accepted_manifest_sha256 is not null and accepted_context is not null and accepted_context_sha256 is not null and acceptance_receipt is not null and acceptance_receipt_sha256 is not null and finalization_event_id is not null) or (state<>'finalization_pending' and accepted_at is null and acceptance_decision_id is null and selected_pre_submit_run_id is null and selected_pre_submit_request_sha256 is null and selected_pre_submit_terminal_sha256 is null and accepted_source_sha256 is null and accepted_manifest_sha256 is null and accepted_context is null and accepted_context_sha256 is null and acceptance_receipt is null and acceptance_receipt_sha256 is null and finalization_event_id is null)", name="acceptance_shape"),
+        UniqueConstraint("selected_pre_submit_run_id", name="uq_intake_accepted_pre_run"),
+        UniqueConstraint("acceptance_decision_id", name="uq_intake_acceptance_decision"),
+        UniqueConstraint("finalization_event_id", name="uq_intake_finalization_event"),
+        Index("uq_submission_intake_active_task", "task_id", unique=True, postgresql_where=text("state in ('receiving','pre_checking','finalization_pending')")),
         Index("ix_submission_intake_expiry", "lease_expires_at", "id", postgresql_where=text("state in ('receiving','pre_checking')")),
     )
 
@@ -76,6 +83,18 @@ class SubmissionIntakeOperation(Base):
     sealed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
     terminal_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
     failure_code: Mapped[str | None] = mapped_column(String(100))
+    accepted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+    acceptance_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
+    selected_pre_submit_run_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
+    selected_pre_submit_request_sha256: Mapped[str | None] = mapped_column(String(71))
+    selected_pre_submit_terminal_sha256: Mapped[str | None] = mapped_column(String(71))
+    accepted_source_sha256: Mapped[str | None] = mapped_column(String(71))
+    accepted_manifest_sha256: Mapped[str | None] = mapped_column(String(71))
+    accepted_context: Mapped[dict | None] = mapped_column(JSONB(none_as_null=True))
+    accepted_context_sha256: Mapped[str | None] = mapped_column(String(71))
+    acceptance_receipt: Mapped[dict | None] = mapped_column(JSONB(none_as_null=True))
+    acceptance_receipt_sha256: Mapped[str | None] = mapped_column(String(71))
+    finalization_event_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
     created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp())
 
 
diff --git a/backend/app/modules/tasks/api/intake_custody.py b/backend/app/modules/tasks/api/intake_custody.py
index 940a52e80..8fa56bfc2 100644
--- a/backend/app/modules/tasks/api/intake_custody.py
+++ b/backend/app/modules/tasks/api/intake_custody.py
@@ -17,7 +17,7 @@ class IntakeTaskSnapshot:
 
 
 class IntakeTaskCustodyPort(Protocol):
-    """Maintain the task pointer only; caller must supply authorized owner work."""
+    """Maintain the pointer and T4 pending state inside authorized owner work."""
 
     async def claim(self, request: TaskSubmissionContextRequest, operation_id: UUID) -> IntakeTaskSnapshot:
         """Lock canonical submission context and install its unique operation pointer."""
@@ -34,3 +34,7 @@ async def require_active(self, task_id: UUID, operation_id: UUID) -> UUID:
     async def release(self, task_id: UUID, operation_id: UUID) -> None:
         """Clear only this operation's pointer inside the terminal transaction."""
         ...
+
+    async def accept(self, task_id: UUID, operation_id: UUID, expected_status: str) -> None:
+        """T4-only direct transition; deferred custody requires exact accepted AUTH/event."""
+        ...
diff --git a/backend/app/modules/tasks/intake_custody.py b/backend/app/modules/tasks/intake_custody.py
index 079865064..e47d6e6f3 100644
--- a/backend/app/modules/tasks/intake_custody.py
+++ b/backend/app/modules/tasks/intake_custody.py
@@ -64,3 +64,16 @@ async def release(self, task_id: UUID, operation_id: UUID) -> None:
             raise TaskSubmissionContextUnavailable("task_submission_context_invalid")
         task.active_submission_operation_id = None
         await self._session.flush()
+
+    async def accept(self, task_id: UUID, operation_id: UUID, expected_status: str) -> None:
+        """Keep the pointer while accepted source work awaits formal finalization.
+
+        The deferred acceptance/custody constraints require the same transaction's
+        exact ART, AUTH, PRE and event records. This is not a generic transition.
+        """
+        await self.require_active(task_id, operation_id)
+        task = await self._tasks.get_task(str(task_id), for_update=True)
+        if expected_status not in {"in_progress", "needs_revision"} or task.status != expected_status:
+            raise TaskSubmissionContextUnavailable("task_submission_context_invalid")
+        task.status = "evaluation_pending"
+        await self._session.flush()
diff --git a/backend/tests/artifacts/intake_acceptance_support.py b/backend/tests/artifacts/intake_acceptance_support.py
new file mode 100644
index 000000000..fafbc2648
--- /dev/null
+++ b/backend/tests/artifacts/intake_acceptance_support.py
@@ -0,0 +1,78 @@
+"""Real T1/upload/PRE owners with the portable worker/runtime fixture for T4."""
+from app.adapters.artifacts import submission_intake_pre_source_port
+from app.adapters.auth import selected_pre_submit_authority
+from app.adapters.checkers import selected_pre_submit_coordinator, SelectedPreSubmitCheckerExecutionAdapter
+from app.core.identifiers import new_record_id
+from app.modules.actors.api import ServiceIdentity
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
+from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization
+from app.modules.artifacts.selected_pre_submit_admission import (
+    bind_selected_pre_submit_admission, build_selected_pre_submit_reservation,
+)
+from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitSourceReads, SelectedPreSubmitExecutionService
+from app.modules.checkers.api.pre_submit_material import SubmissionPacketView
+from tests.artifact_store_helpers import initialize_local_store
+from tests.artifacts.test_submission_intake_custody import foreground_upload, foreground_limits
+from tests.artifacts.test_submission_pre_source import _source_runtime
+from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer
+from tests.checkers.execution.support import provision_post_submit_service
+from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation
+from tests.test_trusted_intake import _archive
+
+
+async def completed_source(f, tmp_path):
+    """Return a real committed eligible PRE plus its exact original foreground owner."""
+    metadata = SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment)
+    key = new_record_id()
+    owner = await f.admission.admit(metadata, actor_id=f.actor.actor_profile_id,
+        identity_link_id=f.actor.identity_link_id, idempotency_key=key, declared_raw_bytes=None)
+    payload = _archive()
+    async def body():
+        yield payload
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    try:
+        source = await foreground_upload(f, store).receive(
+            owner.operation_id, owner.lease_id, owner.generation, body(), **foreground_limits())
+        async with f.factory.begin() as session:
+            task, project = await f.admission._validate_context(session, metadata, f.actor.actor_profile_id)
+            custody = await submission_intake_pre_source_port(session).lock_pre_source(
+                source=source, lease_id=owner.lease_id, generation=owner.generation)
+            selected = bind_selected_pre_submit_admission(
+                task=task, project=project, predecessor=None, predecessor_rules_sha256=None,
+                predecessor_exists=False, packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation))
+            request = build_selected_pre_submit_reservation(
+                source=custody, metadata=metadata, task=task, project=project, attempt_id=new_record_id(),
+                idempotency_key=key, selected=selected, runtime_profile=_source_reservation().runtime_profile)
+            await selected_pre_submit_coordinator(session).reserve(request)
+        await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_PRE_SUBMIT)
+        await _seed_materializer(f.factory)
+        runtime, errors = _source_runtime(payload, tmp_path, "completed")
+        async with f.factory() as session:
+            authority = PreparedPreSubmitMaterializationAuthorization(
+                session, request_id=new_record_id(), correlation_id=new_record_id())
+            service = SelectedPreSubmitExecutionService(
+                session=session, coordinator=selected_pre_submit_coordinator(session),
+                authority=selected_pre_submit_authority(session),
+                source_reads=SelectedPreSubmitSourceReads(session=session,
+                    sources=submission_intake_pre_source_port(session), authority=authority, store=store),
+                execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime))
+            result = await service.execute(reservation=request)
+        assert not errors, "\n".join(errors)
+        assert result.terminal.execution is not None and result.terminal.execution.eligible
+        return owner, request, result.terminal
+    finally:
+        store.close()
+
+
+async def wait_foreground_expired(session, operation_id):
+    """Observe the database deadline, rather than infer expiry from a host sleep."""
+    import asyncio
+    from sqlalchemy import text
+    async with asyncio.timeout(10):
+        while True:
+            remaining = float(await session.scalar(text("SELECT extract(epoch FROM "
+                "(lease_expires_at-clock_timestamp())) FROM submission_intake_operations WHERE id=:id"),
+                {"id": operation_id}))
+            if remaining <= 0:
+                return
+            await asyncio.sleep(min(remaining + 0.02, 0.25))
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 651434c7b..95cd09b41 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -425,3 +425,314 @@ async def body():
     async with f.factory() as session:
         row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
         assert row.state == "receiving" and row.lease_generation == owner.generation
+
+
+async def test_t4_accepts_exact_source_and_replays_one_receipt(admission_intake, tmp_path):
+    """T1/upload/PRE through the real atomic T4 owner; no formal Submission yet."""
+    from sqlalchemy import text
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from tests.artifacts.intake_acceptance_support import completed_source
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    kwargs = dict(checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    receipt = await f.admission.accept(owner, request, terminal.terminal_digest, **kwargs)
+    assert receipt["status"] == "accepted" and receipt["replayed"] is False
+    assert receipt["operation_id"] == str(owner.operation_id)
+    assert receipt["pre_submission_results"]
+    assert await f.admission.accept(owner, request, terminal.terminal_digest, **kwargs) == dict(receipt, replayed=True)
+    async with f.factory.begin() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        assert row.state == "finalization_pending" and row.acceptance_receipt == receipt
+        task = (await session.execute(text(
+            "SELECT status, active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": f.task})).one()
+        assert task.status == "evaluation_pending" and task.active_submission_operation_id == owner.operation_id
+        assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": f.task}) == 0
+        assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE aggregate_id=:id "
+                                         "AND event_type='SubmissionFinalizationRequested'"), {"id": owner.operation_id}) == 1
+        assert await session.scalar(text("SELECT count(*) FROM submission_source_charges WHERE operation_id=:id"),
+                                    {"id": owner.operation_id}) == 1
+
+
+@pytest.mark.parametrize("boundary", ["outbox", "task"])
+async def test_t4_rolls_back_all_participants_and_can_retry(admission_intake, tmp_path, boundary):
+    from sqlalchemy import text
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from tests.artifacts.intake_acceptance_support import completed_source
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    original_tasks = f.admission._tasks
+
+    class FailedOutbox:
+        def __init__(self, session):
+            self.delegate = outbox_append(session)
+        async def append(self, event):
+            await self.delegate.append(event)
+            raise RuntimeError("injected handoff failure")
+
+    class FailedTask(IntakeTaskCustody):
+        async def accept(self, task_id, operation_id, expected_status):
+            await super().accept(task_id, operation_id, expected_status)
+            raise RuntimeError("injected handoff failure")
+
+    if boundary == "task":
+        f.admission._tasks = lambda session: FailedTask(session, task_submission_context_port(session))
+    try:
+        with pytest.raises(RuntimeError, match="injected handoff failure"):
+            await f.admission.accept(owner, request, terminal.terminal_digest,
+                checkers=selected_pre_submit_coordinator, outbox=FailedOutbox if boundary == "outbox" else outbox_append)
+    finally:
+        f.admission._tasks = original_tasks
+    async with f.factory.begin() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        assert row.state == "pre_checking" and row.accepted_at is None and row.finalization_event_id is None
+        assert await session.scalar(text("SELECT status FROM workstream_tasks WHERE id=:id"), {"id": f.task}) == "in_progress"
+        assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE aggregate_id=:id"),
+                                    {"id": owner.operation_id}) == 0
+        assert await session.scalar(text("SELECT count(*) FROM audit_events WHERE resource_id=:id AND action_id='submission.create'"),
+                                    {"id": str(owner.operation_id)}) == 0
+    receipt = await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    assert receipt["status"] == "accepted" and receipt["replayed"] is False
+
+
+@pytest.mark.parametrize("case", ["concurrent", "lost_acknowledgement"])
+async def test_t4_resolves_one_acceptance_under_duplicate_or_lost_response(admission_intake, tmp_path, case):
+    from sqlalchemy import text
+    from sqlalchemy.ext.asyncio import AsyncSession
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from tests.artifacts.intake_acceptance_support import completed_source
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    kwargs = dict(checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    if case == "concurrent":
+        receipts = await asyncio.wait_for(asyncio.gather(*(
+            f.admission.accept(owner, request, terminal.terminal_digest, **kwargs) for _ in range(2))), 20)
+        assert sorted(receipt["replayed"] for receipt in receipts) == [False, True]
+        assert dict(receipts[0], replayed=False) == dict(receipts[1], replayed=False)
+    else:
+        lost = False
+        class LostAcknowledgement(AsyncSession):
+            async def commit(self):
+                nonlocal lost
+                await super().commit()
+                if not lost:
+                    lost = True
+                    raise ConnectionError("committed acceptance acknowledgement lost")
+        f.admission._sessions = async_sessionmaker(f.factory.kw["bind"], class_=LostAcknowledgement, expire_on_commit=False)
+        receipt = await f.admission.accept(owner, request, terminal.terminal_digest, **kwargs)
+        assert lost and receipt["status"] == "accepted" and receipt["replayed"] is True
+    async with f.factory.begin() as session:
+        assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE aggregate_id=:id "
+                                         "AND event_type='SubmissionFinalizationRequested'"), {"id": owner.operation_id}) == 1
+        assert await session.scalar(text("SELECT count(*) FROM audit_events WHERE resource_id=:id AND action_id='submission.create'"),
+                                    {"id": str(owner.operation_id)}) == 1
+
+
+async def test_t4_accepted_custody_cannot_be_mutated_or_abandoned(admission_intake, tmp_path):
+    from sqlalchemy import text
+    from sqlalchemy.exc import DBAPIError
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from tests.artifacts.intake_acceptance_support import completed_source
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    receipt = await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    async with f.factory.begin() as session:
+        assert await repository(session).abandon_expired(owner.operation_id) is False
+    for sql in (
+        "UPDATE submission_intake_operations SET state='abandoned' WHERE id=:id",
+        "UPDATE submission_intake_operations SET acceptance_receipt='{}'::jsonb WHERE id=:id",
+        "UPDATE submission_intake_operations SET acceptance_decision_id=NULL WHERE id=:id",
+        "UPDATE submission_intake_operations SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=:id",
+        "DELETE FROM submission_source_charges WHERE operation_id=:id",
+        "UPDATE workstream_tasks SET active_submission_operation_id=NULL WHERE active_submission_operation_id=:id",
+        "UPDATE workstream_tasks SET status='in_progress' WHERE active_submission_operation_id=:id",
+    ):
+        with pytest.raises(DBAPIError):
+            async with f.factory.begin() as session:
+                await session.execute(text(sql), {"id": owner.operation_id})
+    assert await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append) == dict(receipt, replayed=True)
+
+
+@pytest.mark.parametrize("when", ["before", "after"])
+async def test_t4_revocation_blocks_new_acceptance_but_preserves_accepted_custody(admission_intake, tmp_path, when):
+    from sqlalchemy import text
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied
+    from tests.artifacts.intake_acceptance_support import completed_source
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    if when == "after":
+        await f.admission.accept(owner, request, terminal.terminal_digest,
+            checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    response = await f.access.signed.client.post(
+        f"/api/v1/projects/{f.project}/role-grants/{f.grant_id}/revoke",
+        headers=f.manager.headers | {"Idempotency-Key": str(new_record_id())},
+        json={"reason": "Withdraw grant before accepted handoff"})
+    assert response.status_code == 200, response.text
+    with pytest.raises(IntakeAuthorityDenied):
+        await f.admission.accept(owner, request, terminal.terminal_digest,
+            checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    async with f.factory.begin() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        if when == "before":
+            assert row.state == "pre_checking" and row.acceptance_decision_id is None and row.finalization_event_id is None
+        else:
+            assert row.state == "finalization_pending" and row.acceptance_receipt["status"] == "accepted"
+            await session.execute(text("SELECT public.require_submission_acceptance(o) "
+                "FROM submission_intake_operations o WHERE id=:id"), {"id": owner.operation_id})
+            assert await repository(session).abandon_expired(owner.operation_id) is False
+
+
+@pytest.mark.parametrize("winner", ["acceptance", "abandonment"])
+async def test_t4_and_expiry_serialize_both_winner_orders(admission_intake, tmp_path, winner):
+    from sqlalchemy import text
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from tests.artifacts.intake_acceptance_support import completed_source
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    attempted, held, release = asyncio.Event(), asyncio.Event(), asyncio.Event()
+    original_tasks = f.admission._tasks
+
+    class ObservedTasks(IntakeTaskCustody):
+        async def lock(self, task_id):
+            attempted.set()
+            return await super().lock(task_id)
+
+    if winner == "abandonment":
+        async with f.factory.begin() as session:
+            await session.execute(text("UPDATE submission_intake_operations SET lease_expires_at="
+                "clock_timestamp()-interval '1 second' WHERE id=:id"), {"id": owner.operation_id})
+        f.admission._tasks = lambda session: ObservedTasks(session, task_submission_context_port(session))
+        async with f.factory() as session:
+            await session.begin()
+            assert await repository(session).abandon_expired(owner.operation_id)
+            command = asyncio.create_task(f.admission.accept(owner, request, terminal.terminal_digest,
+                checkers=selected_pre_submit_coordinator, outbox=outbox_append))
+            try:
+                await asyncio.wait_for(attempted.wait(), 10)
+                assert not command.done()
+                await session.commit()
+                with pytest.raises(IntakeCustodyConflict):
+                    await asyncio.wait_for(command, 10)
+            finally:
+                command.cancel()
+                await asyncio.gather(command, return_exceptions=True)
+                f.admission._tasks = original_tasks
+        expected = "abandoned"
+    else:
+        async with f.factory.begin() as session:
+            await session.execute(text("UPDATE submission_intake_operations SET lease_expires_at="
+                "clock_timestamp()+interval '5 seconds' WHERE id=:id"), {"id": owner.operation_id})
+        class PausedOutbox:
+            def __init__(self, session):
+                self.delegate = outbox_append(session)
+            async def append(self, event):
+                result = await self.delegate.append(event)
+                held.set()
+                await release.wait()
+                return result
+        async def expire():
+            from app.modules.artifacts.intake.repository import SubmissionIntakeRepository
+            async with f.factory.begin() as session:
+                tasks = ObservedTasks(session, task_submission_context_port(session))
+                await tasks.lock(f.task)
+                from tests.artifacts.intake_acceptance_support import wait_foreground_expired
+                await wait_foreground_expired(session, owner.operation_id)
+                return await SubmissionIntakeRepository(session, tasks).abandon_expired(owner.operation_id)
+        command = asyncio.create_task(f.admission.accept(owner, request, terminal.terminal_digest,
+            checkers=selected_pre_submit_coordinator, outbox=PausedOutbox))
+        recovery = None
+        try:
+            await asyncio.wait_for(held.wait(), 10)
+            recovery = asyncio.create_task(expire())
+            await asyncio.wait_for(attempted.wait(), 10)
+            assert not recovery.done()
+            release.set()
+            assert (await asyncio.wait_for(command, 10))["status"] == "accepted"
+            assert await asyncio.wait_for(recovery, 10) is False
+        finally:
+            release.set()
+            command.cancel()
+            if recovery is not None:
+                recovery.cancel()
+            await asyncio.gather(command, *( [recovery] if recovery is not None else []), return_exceptions=True)
+        expected = "finalization_pending"
+    async with f.factory.begin() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        assert row.state == expected
+        assert (row.acceptance_receipt is not None) == (winner == "acceptance")
+        assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE aggregate_id=:id"),
+                                    {"id": owner.operation_id}) == int(winner == "acceptance")
+
+
+async def test_t4_rejects_lease_expiry_at_commit_boundary(admission_intake, tmp_path):
+    from sqlalchemy import text
+    from sqlalchemy.ext.asyncio import AsyncSession
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from tests.artifacts.intake_acceptance_support import completed_source
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    async with f.factory.begin() as session:
+        await session.execute(text("UPDATE submission_intake_operations SET lease_expires_at="
+            "clock_timestamp()+interval '5 seconds' WHERE id=:id"), {"id": owner.operation_id})
+    delayed = False
+    class ExpiredCommit(AsyncSession):
+        async def commit(self):
+            nonlocal delayed
+            if not delayed:
+                delayed = True
+                from tests.artifacts.intake_acceptance_support import wait_foreground_expired
+                await wait_foreground_expired(self, owner.operation_id)
+            await super().commit()
+    f.admission._sessions = async_sessionmaker(f.factory.kw["bind"], class_=ExpiredCommit, expire_on_commit=False)
+    with pytest.raises(IntakeCustodyConflict, match="intake_acceptance_conflict"):
+        await f.admission.accept(owner, request, terminal.terminal_digest,
+            checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    assert delayed
+    async with f.factory.begin() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        assert row.state == "pre_checking" and row.acceptance_receipt is None
+        assert await session.scalar(text("SELECT status FROM workstream_tasks WHERE id=:id"), {"id": f.task}) == "in_progress"
+        assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE aggregate_id=:id"),
+                                    {"id": owner.operation_id}) == 0
+
+
+async def test_t4_cancellation_drains_commit_and_keeps_accepted_custody(admission_intake, tmp_path):
+    from sqlalchemy.ext.asyncio import AsyncSession
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from tests.artifacts.intake_acceptance_support import completed_source
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    committed, release = asyncio.Event(), asyncio.Event()
+    class DelayedAcknowledgement(AsyncSession):
+        async def commit(self):
+            await super().commit()
+            committed.set()
+            await release.wait()
+    f.admission._sessions = async_sessionmaker(f.factory.kw["bind"], class_=DelayedAcknowledgement, expire_on_commit=False)
+    kwargs = dict(checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    command = asyncio.create_task(f.admission.accept(owner, request, terminal.terminal_digest, **kwargs))
+    try:
+        await asyncio.wait_for(committed.wait(), 10)
+        command.cancel()
+        await asyncio.sleep(0)
+        assert not command.done()
+        release.set()
+        with pytest.raises(asyncio.CancelledError):
+            await asyncio.wait_for(command, 10)
+    finally:
+        release.set()
+        command.cancel()
+        await asyncio.gather(command, return_exceptions=True)
+    receipt = await f.admission.accept(owner, request, terminal.terminal_digest, **kwargs)
+    assert receipt["status"] == "accepted" and receipt["replayed"] is True
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 04c18a954..7b5c8a995 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "a2fa516d47052e9d1177c15bb602a3d1547ea5fd424e2a9f903427caee6a945c"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "5a1f343869d5599158b74372e1a150fe913659313b03f71185a4360c8163e186"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",

From 22755db21470fb9d416acb624b73c075184a134b Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 19:06:44 +0100
Subject: [PATCH 110/513] Clarify exact source observation and strengthen
 acceptance proof

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 37 ++++++++++++++++---
 .../test_submission_intake_admission.py       | 10 +++++
 2 files changed, 42 insertions(+), 5 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index f2fb8fd21..28239a0b3 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2575,11 +2575,23 @@ Required behavior:
    composition and fixed-service authority. Claim a separately fenced accepted
    continuation in a short transaction. Recognize and validate an already finalized
    operation before requiring a pending TASK pointer or a new lease.
-2. Observe only the recorded immutable source generation/size outside TASK locks
-   through the existing typed ART provider composition. Combine observation with
+2. Extend the existing typed ART provider interface and adapters with
+   `observe_sealed_source(source, operation_evidence=...)`, taking only the exact
+   committed `SealedSubmissionSource`. Return a frozen metadata observation of
+   location, provider generation and byte count, or absence; raise an integrity
+   error on mismatched ownership/generation/size. This is distinct from uncertain
+   upload completion recovery, which currently rehashes the ZIP. S3 must issue
+   version-pinned HEAD and validate VersionId, ContentLength and existing ownership
+   metadata. Local must use the existing directory lock, persisted seal and
+   no-follow descriptor, checking private regular-file permissions, device/inode
+   generation and size without reading the body. Do not use unversioned `head()`
+   or `observe_source_upload()` as this proof. Observe outside TASK locks, then
+   compare every observation field to immutable accepted custody again under the
+   T5 TASK/operation locks and current continuation fence. Combine observation with
    committed ingress and exact PRE hash/manifest evidence; metadata alone cannot
-   authorize adopting an arbitrary object. Do not upload/copy/read the ZIP again
-   merely to create a retained identity; register the exact already stored object.
+   authorize adopting an arbitrary object or prove its hash. Do not upload/copy/read
+   the ZIP again merely to create a retained identity; register the exact already
+   stored object. Retained reads must remain pinned to that same generation.
 3. Under TASK → operation owner locks, consume narrow service continuation
    authority over immutable acceptance and the current continuation fence. Do not
    call ordinary contributor creation with an `evaluation_pending` exception or
@@ -2602,7 +2614,7 @@ Required behavior:
    work on later grant changes.
 
 Allowed scope: ART intake/source/API/models/repository and retained material/binding
-owners; TASK Submission API/composition/participants/replay/dispatch and affected
+owners, `app/interfaces/artifacts.py` and existing Local/S3 provider adapters; TASK Submission API/composition/participants/replay/dispatch and affected
 lineage readers; AUTH closed continuation/binding contracts and adapters/catalogue;
 existing CHECKERS POST content/reservation adapters; outbox handler registration;
 new forward migration 0074 and affected schema fingerprint; tests/CI selection and
@@ -2636,3 +2648,18 @@ Run affected retained-reader and POST policy branches, including default human
 review and configured automatic final acceptance/contribution evidence. Finish the
 public API/CLI/MCP drill and A01–A35/C01–C07 audit before overall completion; internal
 T4/T5 tests alone cannot close the goal.
+
+T5 storage verification must reject an absent recorded version, a response naming
+another version, and replacement of the local inode. A newer S3 version at the same
+key must never be silently adopted: the recorded old version may still be observed
+if present; if absent, fail closed. Assert that observation makes no body-read or
+upload/copy calls. This observation is availability/provenance evidence combined
+with committed ingress/PRE, not a new content hash attestation or native provider
+qualification claim.
+
+Review repairs after f07ddcbd0: T4-QA-01 adds direct database assertions for zero
+Submission ART bindings, POST checker reservations, dispatches and request events
+at acceptance. T5-PLAN-01 is resolved in the plan above by explicitly extending the
+existing provider port for exact sealed-version metadata observation. Revision,
+whole-command heartbeat and substitution proof remain open; these repairs do not
+claim the complete T4/T5 or public journey.
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 95cd09b41..b82e226f0 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -448,6 +448,16 @@ async def test_t4_accepts_exact_source_and_replays_one_receipt(admission_intake,
             "SELECT status, active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": f.task})).one()
         assert task.status == "evaluation_pending" and task.active_submission_operation_id == owner.operation_id
         assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": f.task}) == 0
+        assert await session.scalar(text(
+            "SELECT count(*) FROM artifact_bindings WHERE project_id=:id "
+            "AND resource_type='submission'"), {"id": f.project}) == 0
+        assert await session.scalar(text(
+            "SELECT count(*) FROM submission_dispatches WHERE task_id=:id"), {"id": f.task}) == 0
+        assert await session.scalar(text(
+            "SELECT count(*) FROM checker_runs WHERE task_id=:id"), {"id": f.task}) == 0
+        assert await session.scalar(text(
+            "SELECT count(*) FROM outbox_events WHERE project_id=:id "
+            "AND event_type='PostSubmissionEvaluationRequested'"), {"id": f.project}) == 0
         assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE aggregate_id=:id "
                                          "AND event_type='SubmissionFinalizationRequested'"), {"id": owner.operation_id}) == 1
         assert await session.scalar(text("SELECT count(*) FROM submission_source_charges WHERE operation_id=:id"),

From 98bb2446eb76c37566f2595ed8152147992db845 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 19:12:52 +0100
Subject: [PATCH 111/513] Observe exact sealed source versions without reading
 ZIP bodies

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 24 +++++
 backend/app/adapters/artifacts/local.py       |  5 +
 .../artifacts/local_submission_source.py      | 26 ++++++
 .../app/adapters/artifacts/s3_compatible.py   | 22 +++++
 backend/app/interfaces/artifacts.py           | 17 ++++
 .../test_sealed_source_observation.py         | 93 +++++++++++++++++++
 backend/tests/test_artifact_architecture.py   |  3 +-
 .../tests/test_artifact_store_conformance.py  |  4 +-
 backend/tests/test_s3_artifact_store.py       |  2 +-
 9 files changed, 192 insertions(+), 4 deletions(-)
 create mode 100644 backend/tests/artifacts/test_sealed_source_observation.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 28239a0b3..91a91d4d8 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2663,3 +2663,27 @@ at acceptance. T5-PLAN-01 is resolved in the plan above by explicitly extending
 existing provider port for exact sealed-version metadata observation. Revision,
 whole-command heartbeat and substitution proof remain open; these repairs do not
 claim the complete T4/T5 or public journey.
+
+### Exact sealed-source observation implementation
+
+The existing ArtifactStore now exposes `observe_sealed_source`, returning a frozen
+location/generation/size/upload-fence observation or absence. S3 uses version-pinned
+HEAD with the existing ownership response validator. Local uses the existing
+operation directory lock, persisted seal and no-follow descriptor; it verifies
+private sealed permissions, inode generation and size without reading ZIP bytes.
+This is metadata evidence only, combined later with committed ingress and PRE;
+it is not a hash attestation, arbitrary adoption capability or provider qualification.
+
+Focused tests use real Local files and MinIO: same-size inode replacement is
+rejected, missing recorded objects/versions return absence, a newer same-key S3
+version cannot replace the recorded old version, and substituted response version,
+size or ownership metadata is rejected. The S3 test proxy exposes HEAD only; the
+Local test forbids body `pread`. Provider protocol and architecture guards include
+only this additional operation, without extending foreground upload authority.
+
+T4-QA-01's focused PostgreSQL regression passed (1 passed, 26 deselected;
+`/tmp/t4-review-repair.log`, metadata `/tmp/t4-review-repair.json`). This is scoped
+worktree evidence, not a complete T4 or exact frozen-head suite. The observation
+implementation still needs its test result and focused review; it has no T5 caller
+until accepted continuation, retained registration and atomic Submission/POST
+composition are implemented. Full original acceptance requirements remain open.
diff --git a/backend/app/adapters/artifacts/local.py b/backend/app/adapters/artifacts/local.py
index cdd2fa52b..a88de9776 100644
--- a/backend/app/adapters/artifacts/local.py
+++ b/backend/app/adapters/artifacts/local.py
@@ -28,6 +28,7 @@
 )
 from app.core.file_locks import acquire_exclusive_file_lock
 from app.interfaces.artifacts import (
+    SealedSourceObservation,
     ARTIFACT_STORE_CAPABILITY_KEY,
     ArtifactByteRange,
     ArtifactConfigurationError,
@@ -239,6 +240,10 @@ async def complete_source_upload(self, completion: SubmissionSourceCompletion, *
                                      operation_evidence: ArtifactProviderOperationEvidence | None = None) -> SealedSubmissionSource:
         return await self._source_io(LocalSubmissionSource(self).complete, completion)
 
+    async def observe_sealed_source(self, source: SealedSubmissionSource, *,
+                                    operation_evidence: ArtifactProviderOperationEvidence | None = None) -> SealedSourceObservation | None:
+        return await self._source_io(LocalSubmissionSource(self).observe_sealed, source)
+
     async def observe_source_upload(self, completion: SubmissionSourceCompletion, *,
                                     operation_evidence: ArtifactProviderOperationEvidence | None = None) -> SealedSubmissionSource | None:
         return await self._source_io(LocalSubmissionSource(self).observe, completion)
diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py
index dd04f192e..a53f82788 100644
--- a/backend/app/adapters/artifacts/local_submission_source.py
+++ b/backend/app/adapters/artifacts/local_submission_source.py
@@ -14,6 +14,7 @@
 
 from app.core.file_locks import acquire_exclusive_file_lock
 from app.interfaces.artifacts import (
+    SealedSourceObservation,
     ArtifactIntegrityError, ArtifactOperationConflictError,
     ArtifactPreconditionFailedError, ArtifactStoreUnavailableError,
     ArtifactInputMismatchError, ArtifactLimitExceededError,
@@ -231,6 +232,31 @@ def complete(self, completion: SubmissionSourceCompletion) -> SealedSubmissionSo
             finally:
                 os.close(descriptor)
 
+    def observe_sealed(self, source: SealedSubmissionSource) -> SealedSourceObservation | None:
+        """Check sealed ownership and inode metadata without hashing body bytes."""
+        source = SealedSubmissionSource.model_validate(source)
+        try:
+            with self.locked(source.location) as directory:
+                completion, sealed = self.seal(directory)
+                if sealed != source or self.exists(directory, "aborted.json"):
+                    raise ArtifactIntegrityError("submission source seal mismatch")
+                self.upload(directory, completion.upload)
+                descriptor = os.open("bundle.zip", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
+                try:
+                    info = self.store._assert_private_regular(descriptor)
+                    if (stat.S_IMODE(info.st_mode) != 0o400
+                            or info.st_size != source.raw_byte_count
+                            or self.source(completion, info) != source):
+                        raise ArtifactIntegrityError("submission source generation or size mismatch")
+                    return SealedSourceObservation(
+                        source.location, source.provider_generation, info.st_size,
+                        source.sealed_upload_fence,
+                    )
+                finally:
+                    os.close(descriptor)
+        except FileNotFoundError:
+            return None
+
     def observe(self, completion: SubmissionSourceCompletion) -> SealedSubmissionSource | None:
         completion = SubmissionSourceCompletion.model_validate(completion)
         try:
diff --git a/backend/app/adapters/artifacts/s3_compatible.py b/backend/app/adapters/artifacts/s3_compatible.py
index 64000925e..6c2c1d290 100644
--- a/backend/app/adapters/artifacts/s3_compatible.py
+++ b/backend/app/adapters/artifacts/s3_compatible.py
@@ -59,6 +59,7 @@
     is_canonical_s3_region,
 )
 from app.interfaces.artifacts import (
+    SealedSourceObservation,
     ARTIFACT_STORE_CAPABILITY_KEY,
     ArtifactByteRange,
     ArtifactConfigurationError,
@@ -759,6 +760,27 @@ def _check_source_response(source: SealedSubmissionSource, response: Mapping[str
         ):
             raise ArtifactIntegrityError("submission source response violates custody")
 
+    async def observe_sealed_source(
+        self, source: SealedSubmissionSource, *,
+        operation_evidence: ArtifactProviderOperationEvidence | None = None,
+    ) -> SealedSourceObservation | None:
+        """Observe only the retained version; metadata does not reprove its hash."""
+        source = SealedSubmissionSource.model_validate(source)
+        evidence = operation_evidence or ArtifactProviderOperationEvidence()
+        try:
+            async with self._source_client(source.location, evidence) as client:
+                response = await client.head_object(
+                    Bucket=self._bucket, Key=self._source_key(source.location),
+                    VersionId=source.provider_generation,
+                )
+        except ArtifactObjectMissingError:
+            return None
+        self._check_source_response(source, response)
+        return SealedSourceObservation(
+            source.location, response["VersionId"], response["ContentLength"],
+            source.sealed_upload_fence,
+        )
+
     async def observe_source_upload(
         self, completion: SubmissionSourceCompletion, *,
         operation_evidence: ArtifactProviderOperationEvidence | None = None,
diff --git a/backend/app/interfaces/artifacts.py b/backend/app/interfaces/artifacts.py
index 99b626896..e9ceb13b7 100644
--- a/backend/app/interfaces/artifacts.py
+++ b/backend/app/interfaces/artifacts.py
@@ -17,6 +17,7 @@
 from app.modules.artifacts.sources import ArtifactCommitment, CommittedArtifactSource
 from app.modules.artifacts.api.submission_intake import (
     SealedSubmissionSource,
+    SubmissionSourceLocation,
     SubmissionSourceCompletion,
     SubmissionSourcePart,
     SubmissionSourceUpload,
@@ -371,6 +372,16 @@ class ArtifactProviderLiveProofRequiredError(ArtifactConfigurationError):
     code = "artifact_provider_live_proof_required"
 
 
+@dataclass(frozen=True)
+class SealedSourceObservation:
+    """Exact provider metadata, not an independent attestation of content hash."""
+
+    location: SubmissionSourceLocation
+    provider_generation: str
+    raw_byte_count: int
+    sealed_upload_fence: int
+
+
 class ArtifactStore(ExternalServiceAdapter, Protocol):
     """Immutable byte-provider capability used only by artifact orchestration."""
 
@@ -399,6 +410,12 @@ def open_source(
     ) -> AsyncGenerator[bytes, None]:
         """Yield closable exact-version reads, capped by maximum_chunk_bytes (1..64 KiB)."""
 
+    async def observe_sealed_source(
+        self, source: SealedSubmissionSource, *,
+        operation_evidence: ArtifactProviderOperationEvidence | None = None,
+    ) -> SealedSourceObservation | None:
+        """Observe the recorded immutable version without reading its body."""
+
     async def observe_source_upload(
         self, completion: SubmissionSourceCompletion, *,
         operation_evidence: ArtifactProviderOperationEvidence | None = None,
diff --git a/backend/tests/artifacts/test_sealed_source_observation.py b/backend/tests/artifacts/test_sealed_source_observation.py
new file mode 100644
index 000000000..c1c8bbba3
--- /dev/null
+++ b/backend/tests/artifacts/test_sealed_source_observation.py
@@ -0,0 +1,93 @@
+"""Exact-version availability proof must not reread or adopt another ZIP."""
+from contextlib import asynccontextmanager
+import os
+
+import pytest
+
+from app.interfaces.artifacts import ArtifactIntegrityError, SealedSourceObservation
+from tests.test_local_artifact_store import (
+    initialize_local_store, local_source_completion, local_source_intent,
+)
+from tests.test_s3_artifact_store import (
+    MINIO_BUCKET, source_completion,
+    source_store as source_store,
+    provision_minio_bucket as provision_minio_bucket,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+async def test_local_observation_uses_seal_and_inode_without_body_read(tmp_path, monkeypatch):
+    store = initialize_local_store(root=tmp_path / "store")
+    try:
+        upload = await store.begin_source_upload(local_source_intent(store))
+        completion = await local_source_completion(store, upload, b"original")
+        source = await store.complete_source_upload(completion)
+        def forbid_body(*args, **kwargs):
+            pytest.fail("metadata observation read source bytes")
+        monkeypatch.setattr(os, "pread", forbid_body)
+        observed = await store.observe_sealed_source(source)
+        assert observed == SealedSourceObservation(
+            source.location, source.provider_generation, len(b"original"), source.sealed_upload_fence,
+        )
+        path = tmp_path / "store" / "objects" / source.location.object_ref
+        replacement = path.with_name("replacement")
+        replacement.write_bytes(b"original")
+        replacement.chmod(0o400)
+        replacement.replace(path)
+        with pytest.raises(ArtifactIntegrityError, match="generation"):
+            await store.observe_sealed_source(source)
+        path.unlink()
+        assert await store.observe_sealed_source(source) is None
+    finally:
+        store.close()
+
+
+async def test_s3_observation_pins_old_version_without_body_io(source_store, monkeypatch):
+    store = source_store
+    source = await store.complete_source_upload(await source_completion(store, b"original"))
+    original_client = store._client
+    async with original_client() as client:
+        await client.put_object(Bucket=MINIO_BUCKET, Key=store._source_key(source.location), Body=b"newer")
+    seen = []
+    class HeadOnly:
+        def __init__(self, client):
+            self.client = client
+        async def head_object(self, **kwargs):
+            seen.append(kwargs)
+            return await self.client.head_object(**kwargs)
+    @asynccontextmanager
+    async def head_only():
+        async with original_client() as client:
+            yield HeadOnly(client)
+    monkeypatch.setattr(store, "_client", head_only)
+    assert await store.observe_sealed_source(source) == SealedSourceObservation(
+        source.location, source.provider_generation, len(b"original"), source.sealed_upload_fence,
+    )
+    assert seen == [dict(Bucket=MINIO_BUCKET, Key=store._source_key(source.location),
+                         VersionId=source.provider_generation)]
+    async with original_client() as client:
+        await client.delete_object(Bucket=MINIO_BUCKET, Key=store._source_key(source.location),
+                                   VersionId=source.provider_generation)
+    assert await store.observe_sealed_source(source) is None
+
+
+@pytest.mark.parametrize("field,value", [("VersionId", "another-version"), ("ContentLength", 99),
+                                          ("Metadata", {"operation-id": "foreign"})])
+async def test_s3_observation_refuses_inconsistent_version_metadata(source_store, monkeypatch, field, value):
+    store = source_store
+    source = await store.complete_source_upload(await source_completion(store, b"original"))
+    original_client = store._client
+    class ChangedHead:
+        def __init__(self, client):
+            self.client = client
+        async def head_object(self, **kwargs):
+            response = await self.client.head_object(**kwargs)
+            return dict(response, **{field: value})
+    @asynccontextmanager
+    async def changed_client():
+        async with original_client() as client:
+            yield ChangedHead(client)
+    monkeypatch.setattr(store, "_client", changed_client)
+    with pytest.raises(ArtifactIntegrityError, match="custody"):
+        await store.observe_sealed_source(source)
diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py
index 5ec55a8bd..218a96b4f 100644
--- a/backend/tests/test_artifact_architecture.py
+++ b/backend/tests/test_artifact_architecture.py
@@ -93,7 +93,7 @@
 }
 PROVIDER_METHODS = {"put", "observe_put_result", "open", "head", "begin_source_upload",
                     "upload_source_part", "complete_source_upload", "open_source",
-                    "observe_source_upload", "discover_source_uploads", "request_source_abort"}
+                    "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort"}
 CONCRETE_ADAPTER_MODULES = {
     "app.adapters.artifacts.local",
     "app.adapters.artifacts.s3_compatible",
@@ -486,6 +486,7 @@ def test_s3_adapter_exposes_only_required_immutable_object_operations() -> None:
         "complete_source_upload": {"complete_multipart_upload", "head_object"},
         "open_source": {"get_object"},
         "observe_source_upload": {"head_object"},
+        "observe_sealed_source": {"head_object"},
         "discover_source_uploads": {"list_multipart_uploads"},
         "request_source_abort": {"abort_multipart_upload"},
     }
diff --git a/backend/tests/test_artifact_store_conformance.py b/backend/tests/test_artifact_store_conformance.py
index f4f7c7847..563b0e12e 100644
--- a/backend/tests/test_artifact_store_conformance.py
+++ b/backend/tests/test_artifact_store_conformance.py
@@ -218,7 +218,7 @@ class TestLocalArtifactStoreConformance(ArtifactStoreConformanceTests):
 
     expected_source_operations = frozenset({
         "begin_source_upload", "upload_source_part", "complete_source_upload",
-        "open_source", "observe_source_upload", "discover_source_uploads", "request_source_abort",
+        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort",
     })
 
     expected_identity = ExternalServiceAdapterIdentity("artifact_store", "local")
@@ -402,5 +402,5 @@ def test_artifact_store_protocol_declares_only_v2_operations() -> None:
     assert methods == {
         "head", "identity", "observe_put_result", "open", "put",
         "begin_source_upload", "upload_source_part", "complete_source_upload",
-        "open_source", "observe_source_upload", "discover_source_uploads", "request_source_abort",
+        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort",
     }
diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py
index 5262e6f2a..fead2f408 100644
--- a/backend/tests/test_s3_artifact_store.py
+++ b/backend/tests/test_s3_artifact_store.py
@@ -91,7 +91,7 @@ class TestMinioArtifactStoreConformance(ArtifactStoreConformanceTests):
     )
     expected_source_operations = frozenset({
         "begin_source_upload", "upload_source_part", "complete_source_upload",
-        "open_source", "observe_source_upload", "discover_source_uploads", "request_source_abort",
+        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort",
     })
 
     def make_store(self, root: Path) -> ArtifactStore:

From 1f328b545777751f63f984528626f112f6bc723e Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 19:16:57 +0100
Subject: [PATCH 112/513] Validate source observations and reconcile custody
 test boundaries

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 15 +++++++++++
 backend/app/interfaces/artifacts.py           | 14 ++++++++++
 backend/scripts/test_lane_catalogue.py        |  1 +
 .../test_sealed_source_observation.py         | 26 +++++++++++++++++++
 backend/tests/test_artifact_architecture.py   |  8 +++---
 5 files changed, 60 insertions(+), 4 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 91a91d4d8..eeeadf035 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2687,3 +2687,18 @@ worktree evidence, not a complete T4 or exact frozen-head suite. The observation
 implementation still needs its test result and focused review; it has no T5 caller
 until accepted continuation, retained registration and atomic Submission/POST
 composition are implemented. Full original acceptance requirements remain open.
+
+Observation verification: `/tmp/t5-source-observation.log` completed with 51 passed
+and 12 failed. All five new actual Local/MinIO observation cases passed; the failures
+were the source-PRE grant absent from the exact provider-owner inventory and two
+removed PRE consumers still listed as POST materialization importers (the latter
+also failed ten inventory mutation probes). Repairs name only the exact source
+reader/path and `open_source`, and remove only those obsolete POST imports; no
+broad provider allowance is added. The full affected command is being replayed.
+
+Focused architecture/security review found no new observation defect. QA identified
+that the Local test trapped only `pread`, and the frozen observation lacked runtime
+shape validation. Repairs add a descriptor-aware `read` trap while permitting seal
+metadata reads, strict generation/count/fence/location validation with malformed
+value cases, and explicit registration in the existing MinIO-enabled test lane.
+T5 integration remains open; this provider checkpoint does not complete finalization.
diff --git a/backend/app/interfaces/artifacts.py b/backend/app/interfaces/artifacts.py
index e9ceb13b7..4746b7d79 100644
--- a/backend/app/interfaces/artifacts.py
+++ b/backend/app/interfaces/artifacts.py
@@ -17,6 +17,7 @@
 from app.modules.artifacts.sources import ArtifactCommitment, CommittedArtifactSource
 from app.modules.artifacts.api.submission_intake import (
     SealedSubmissionSource,
+    MAXIMUM_SUBMISSION_ZIP_BYTES,
     SubmissionSourceLocation,
     SubmissionSourceCompletion,
     SubmissionSourcePart,
@@ -381,6 +382,19 @@ class SealedSourceObservation:
     raw_byte_count: int
     sealed_upload_fence: int
 
+    def __post_init__(self) -> None:
+        if type(self.location) is not SubmissionSourceLocation:
+            raise ValueError("sealed observation location is invalid")
+        SubmissionSourceLocation.model_validate(self.location)
+        if (type(self.provider_generation) is not str
+                or not 1 <= len(self.provider_generation) <= 2048
+                or self.provider_generation == "null"
+                or type(self.raw_byte_count) is not int
+                or not 1 <= self.raw_byte_count <= MAXIMUM_SUBMISSION_ZIP_BYTES
+                or type(self.sealed_upload_fence) is not int
+                or self.sealed_upload_fence < 1):
+            raise ValueError("sealed observation metadata is invalid")
+
 
 class ArtifactStore(ExternalServiceAdapter, Protocol):
     """Immutable byte-provider capability used only by artifact orchestration."""
diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py
index 56b861a39..cb021c7a7 100644
--- a/backend/scripts/test_lane_catalogue.py
+++ b/backend/scripts/test_lane_catalogue.py
@@ -820,6 +820,7 @@ class TestLane:
             "tests/test_openai_agents_sdk_unavailable.py",
             "tests/test_project_agent_sdk_installation.py",
             "tests/test_s3_artifact_store.py",
+            "tests/artifacts/test_sealed_source_observation.py",
         ),
         sdk_environment="omnicore",
     ),
diff --git a/backend/tests/artifacts/test_sealed_source_observation.py b/backend/tests/artifacts/test_sealed_source_observation.py
index c1c8bbba3..5a0eac98e 100644
--- a/backend/tests/artifacts/test_sealed_source_observation.py
+++ b/backend/tests/artifacts/test_sealed_source_observation.py
@@ -25,7 +25,16 @@ async def test_local_observation_uses_seal_and_inode_without_body_read(tmp_path,
         source = await store.complete_source_upload(completion)
         def forbid_body(*args, **kwargs):
             pytest.fail("metadata observation read source bytes")
+        path = tmp_path / "store" / "objects" / source.location.object_ref
+        bundle_stat = path.stat()
+        original_read = os.read
+        def guarded_read(descriptor, size):
+            info = os.fstat(descriptor)
+            if (info.st_dev, info.st_ino) == (bundle_stat.st_dev, bundle_stat.st_ino):
+                pytest.fail("metadata observation read source bytes")
+            return original_read(descriptor, size)
         monkeypatch.setattr(os, "pread", forbid_body)
+        monkeypatch.setattr(os, "read", guarded_read)
         observed = await store.observe_sealed_source(source)
         assert observed == SealedSourceObservation(
             source.location, source.provider_generation, len(b"original"), source.sealed_upload_fence,
@@ -91,3 +100,20 @@ async def changed_client():
     monkeypatch.setattr(store, "_client", changed_client)
     with pytest.raises(ArtifactIntegrityError, match="custody"):
         await store.observe_sealed_source(source)
+
+
+@pytest.mark.parametrize("field,value", [
+    ("location", {}), ("provider_generation", ""), ("provider_generation", "null"),
+    ("provider_generation", 1), ("raw_byte_count", True), ("raw_byte_count", 0),
+    ("raw_byte_count", 2**64), ("sealed_upload_fence", True), ("sealed_upload_fence", 0),
+])
+async def test_observation_rejects_malformed_metadata(tmp_path, field, value):
+    store = initialize_local_store(root=tmp_path / "store")
+    try:
+        fields = dict(location=local_source_intent(store).location,
+                      provider_generation="version", raw_byte_count=8, sealed_upload_fence=1)
+        fields[field] = value
+        with pytest.raises(ValueError):
+            SealedSourceObservation(**fields)
+    finally:
+        store.close()
diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py
index 218a96b4f..7f5221cf0 100644
--- a/backend/tests/test_artifact_architecture.py
+++ b/backend/tests/test_artifact_architecture.py
@@ -262,7 +262,9 @@ def test_only_artifact_custody_services_own_provider_execution() -> None:
                 "ScopedGuideDocumentGrant",
                 "PostSubmissionMaterializer",
             } or (node.name == "ForegroundSourceUpload"
-                  and path == APP_ROOT / "modules/artifacts/intake/foreground_upload.py"))
+                  and path == APP_ROOT / "modules/artifacts/intake/foreground_upload.py")
+                or (node.name == "_PreSubmitSourceGrant"
+                    and path == APP_ROOT / "modules/artifacts/selected_pre_submit_execution.py"))
         }
         for node in ast.walk(tree):
             if (
@@ -292,7 +294,7 @@ def test_only_artifact_custody_services_own_provider_execution() -> None:
                     and node.func.attr != "open"
                 ) or (owner.name == "ForegroundSourceUpload" and node.func.attr not in {
                     "begin_source_upload", "complete_source_upload", "observe_source_upload",
-                }):
+                }) or (owner.name == "_PreSubmitSourceGrant" and node.func.attr != "open_source"):
                     violations.append(f"{path.relative_to(BACKEND_ROOT)} calls {node.func.attr}")
     assert violations == []
 
@@ -819,11 +821,9 @@ def _assert_checker_custody_consumers(
             "app/adapters/artifacts/__init__.py",
             "app/modules/artifacts/post_submit_materialization.py",
             "app/modules/artifacts/post_submit_selection.py",
-            "app/modules/artifacts/selected_pre_submit_admission.py",
             "app/modules/artifacts/submission_materialization.py",
             "app/modules/checkers/default_checker.py",
             "app/modules/checkers/execution.py",
-            "app/modules/checkers/selected_pre_submit_execution.py",
         },
     }
     actual = {module: set() for module in expected}

From cdaf9c11186030026c9e0311eaa648cf49a479bd Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 19:21:30 +0100
Subject: [PATCH 113/513] Record verified sealed-source observation evidence

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md   | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index eeeadf035..a5172e239 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2702,3 +2702,16 @@ shape validation. Repairs add a descriptor-aware `read` trap while permitting se
 metadata reads, strict generation/count/fence/location validation with malformed
 value cases, and explicit registration in the existing MinIO-enabled test lane.
 T5 integration remains open; this provider checkpoint does not complete finalization.
+
+The repaired observation/architecture/conformance command completed with **72
+passed** (`/tmp/t5-observation-repair.log`); CI lane checks completed with **17
+passed** (`/tmp/t5-observation-lanes.log`). Structure validation, Commitrail and
+Markdown-link checks passed. Scoped ARCH/SEC and QA reviews passed at clean
+`1f328b545777751f63f984528626f112f6bc723e`. QA independently inserted an in-memory
+`os.read(bundle_fd, 1)` mutation and the targeted Local test failed specifically at
+its body-read trap; no repository mutation remained. An earlier unconfigured
+probe failed during MinIO setup and is excluded from evidence. The shared tests
+began on the corresponding worktree before freeze; do not attribute them as a new
+exact-commit full-suite execution. The next required change is accepted continuation
+and atomic retained registration/Submission/POST composition, not additional
+observation scaffolding. This checkpoint leaves the end-to-end goal incomplete.

From de615901275a0d3ad64b79ca557b77a06b2a31be Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 19:57:46 +0100
Subject: [PATCH 114/513] Continue accepted submission custody into atomic
 finalization and POST dispatch

---
 .ci/auth-boundaries/TEST_STRUCTURE_DEBT.json  |  16 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  47 +++
 .../versions/0074_submission_finalization.py  | 341 ++++++++++++++++++
 backend/app/adapters/tasks/__init__.py        |  13 +
 .../artifacts/api/submission_admission.py     |   1 +
 .../artifacts/api/submission_finalization.py  |  22 ++
 .../app/modules/artifacts/authorization.py    |  38 +-
 .../modules/artifacts/intake/finalization.py  | 181 ++++++++++
 .../artifacts/intake/foreground_admission.py  |   6 +-
 .../app/modules/artifacts/intake/models.py    |  24 +-
 .../modules/artifacts/intake/registration.py  |  63 ++++
 backend/app/modules/artifacts/models.py       |  27 +-
 .../modules/artifacts/submission_bindings.py  |  19 +-
 .../authorization/action_definitions.py       |   5 +
 .../app/modules/authorization/catalogue.py    |  10 +-
 .../authorization/domain/action_groups.py     |  90 ++++-
 .../app/modules/authorization/domain/audit.py |   2 +
 .../authorization/domain/audit_targets.py     |   5 +-
 .../domain/submission_finalization.py         |  38 ++
 backend/app/modules/authorization/kernel.py   |  90 +----
 backend/app/modules/authorization/prepared.py |  34 +-
 backend/app/modules/authorization/runtime.py  |   5 +-
 .../authorization/submission_consumption.py   |   2 +
 .../checkers/api/selected_pre_submit.py       |   4 +
 .../selected_pre_submit_coordination.py       |  23 ++
 .../app/modules/tasks/accepted_submission.py  |  56 +++
 .../modules/tasks/submission_composition.py   | 242 ++++++++-----
 .../modules/tasks/submission_participants.py  |   1 +
 backend/scripts/test_lane_catalogue.py        |   1 +
 .../test_submission_intake_admission.py       |  67 ++++
 .../tests/authorization/catalogue_fixtures.py |   3 +
 backend/tests/authorization/test_catalogue.py |   9 +-
 .../test_submission_finalization_authority.py |  83 +++++
 backend/tests/conftest.py                     |   2 +-
 34 files changed, 1335 insertions(+), 235 deletions(-)
 create mode 100644 backend/alembic/versions/0074_submission_finalization.py
 create mode 100644 backend/app/modules/artifacts/api/submission_finalization.py
 create mode 100644 backend/app/modules/artifacts/intake/finalization.py
 create mode 100644 backend/app/modules/artifacts/intake/registration.py
 create mode 100644 backend/app/modules/authorization/domain/submission_finalization.py
 create mode 100644 backend/app/modules/tasks/accepted_submission.py
 create mode 100644 backend/tests/authorization/test_submission_finalization_authority.py

diff --git a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
index 0b17d1959..b247d4369 100644
--- a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
+++ b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
@@ -1,17 +1,5 @@
 {
   "entries": [
-    {
-      "capability": "oversized_authorization_structure",
-      "content_sha256": "b4f2fe63f88cacf12830a5cc556f8dc627e74deac80c1b6183d13a8a1a4f52ce",
-      "end_line": 1265,
-      "hard_limit": 1200,
-      "kind": "production_file",
-      "observed_lines": 1265,
-      "path": "backend/app/modules/authorization/kernel.py",
-      "qualified_symbol": null,
-      "removal_chunk": "WS-AUTH-003-CLOSE",
-      "start_line": 1
-    },
     {
       "capability": "oversized_authorization_structure",
       "content_sha256": "a08fa6805d4c37ea4619c450cace685bc5ddffbd5b671506c4be68cd24365d8e",
@@ -27,14 +15,14 @@
     {
       "capability": "oversized_authorization_structure",
       "content_sha256": "bae6d1bf2568947ee4125b3389d861fb7c077a346da1efcef3167b68ce7cafd5",
-      "end_line": 818,
+      "end_line": 742,
       "hard_limit": 100,
       "kind": "production_function",
       "observed_lines": 105,
       "path": "backend/app/modules/authorization/kernel.py",
       "qualified_symbol": "AuthorizationService._require_prelocked",
       "removal_chunk": "WS-AUTH-003-CLOSE",
-      "start_line": 714
+      "start_line": 638
     },
     {
       "capability": "oversized_authorization_structure",
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index a5172e239..b2234acf6 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2715,3 +2715,50 @@ began on the corresponding worktree before freeze; do not attribute them as a ne
 exact-commit full-suite execution. The next required change is accepted continuation
 and atomic retained registration/Submission/POST composition, not additional
 observation scaffolding. This checkpoint leaves the end-to-end goal incomplete.
+
+### Accepted continuation and retained registration implementation
+
+T5 now has a fixed-service `artifact.submission.finalize` action, an exact accepted
+operation/context/source/receipt capability, and separate claim and commit decisions.
+The continuation lease is committed before metadata observation outside TASK locks.
+The final transaction registers the same sealed source as ART content/replica and a
+source-backed admission, then invokes the shared TASK Submission/binding/POST dispatch
+writer. It retains the original acceptance decision for creation provenance and a
+separate service decision for continuation. Finalized replay reads retained closure
+before any new lease or provider observation. No fabricated put or verification
+receipt substitutes for accepted ingress/PRE evidence.
+
+Migration 0074 extends the closed audit action/permission pair, discriminates source
+admissions from retained put/verification admissions, and enforces acceptance,
+continuation authority, finalized Submission/dispatch closure, and immutable source
+ownership. The AUTH kernel's action classifications move to the existing domain
+classification module; this removes its oversized-file debt without adding debt.
+
+Verification on the implementation worktree: five focused real-PostgreSQL AUTH
+cases passed (claim/commit exact consumption plus missing/wrong/revoked service).
+The first composed T5 run advanced through registration and shared Submission/POST
+creation to commit, then failed because a shared deferred trigger referenced intake
+fields on a replica row. The repair isolates intake-specific checks in nested table
+and operation branches. Known database failures now propagate directly rather than
+being mislabeled uncertain commit acknowledgement. This is diagnostic progress,
+not a passing T5 or POST execution claim. The composed test also checks replay,
+original acceptance receipt stability, one Submission/dispatch/POST reservation,
+same source key, retained charge, absent fabricated receipts, and rejected removal
+of replica source ownership. Its repaired result remains required.
+
+Still required: integrated T5 failure/retry/concurrency proofs, the finalization
+outbox handler and composition, POST reads from exact retained source generation,
+revision and public API/CLI/MCP journey, and the complete acceptance/deployment audit.
+The single PR remains the delivery unit; this implementation does not complete it.
+
+The repaired composed PostgreSQL T5 test passed (**1 passed, 27 deselected**,
+`/tmp/t5-composed-repaired.log`, isolation metadata `/tmp/t5-composed-repaired.json`,
+cleanup complete). It includes exact finalized replay, original acceptance replay,
+all registration/dispatch assertions, and the source-link removal rejection.
+Catalogue tests passed (**7 passed**, `/tmp/t5-catalogue-final.log`); changed Python
+files pass Ruff; Markdown links and structure validation passed. A subsequent
+unused-import removal shifts the unchanged kernel debt function by one line, with
+the ledger coordinates adjusted accordingly. These are worktree-scoped results,
+not full-suite or exact frozen-commit provenance. T5 crash/concurrency and POST
+execution/public integration remain open; focused implementation review follows
+this reproducible milestone.
diff --git a/backend/alembic/versions/0074_submission_finalization.py b/backend/alembic/versions/0074_submission_finalization.py
new file mode 100644
index 000000000..c5acd5576
--- /dev/null
+++ b/backend/alembic/versions/0074_submission_finalization.py
@@ -0,0 +1,341 @@
+"""Continue accepted custody into exact retained Submission and POST lineage."""
+import re
+from alembic import op
+from sqlalchemy import text
+
+revision = "0074_submission_finalization"
+down_revision = "0073_submission_acceptance"
+branch_labels = None
+depends_on = None
+
+
+def _replace(signature, old, new):
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))"
+    ), {"signature": signature}).scalar_one()
+    if body.count(old) != 1:
+        raise RuntimeError("finalization predecessor shape changed: " + signature)
+    op.execute(body.replace(old, new))
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    _extend_audit_action()
+    op.execute("LOCK TABLE public.workstream_tasks, public.submission_intake_operations, "
+               "public.submission_bundle_admissions, public.artifact_replicas, public.submissions, "
+               "public.submission_dispatches IN ACCESS EXCLUSIVE MODE")
+    for column, kind in {
+        "continuation_lease_id": "uuid", "continuation_generation": "bigint",
+        "continuation_expires_at": "timestamptz", "continuation_decision_id": "uuid",
+        "finalized_at": "timestamptz", "finalization_decision_id": "uuid",
+        "finalized_submission_id": "uuid", "finalized_admission_id": "uuid",
+    }.items():
+        op.execute(f"ALTER TABLE public.submission_intake_operations ADD COLUMN {column} {kind}")
+    for table in ("submission_bundle_admissions", "artifact_replicas"):
+        op.execute(f"ALTER TABLE public.{table} ADD COLUMN source_operation_id uuid")
+    for column in ("durable_intent_id", "put_attempt_id", "verification_receipt_id"):
+        op.execute(f"ALTER TABLE public.submission_bundle_admissions ALTER COLUMN {column} DROP NOT NULL")
+    for table, name, ddl in _CONSTRAINTS:
+        op.execute(f'ALTER TABLE public.{table} DROP CONSTRAINT IF EXISTS "{name}"')
+        op.execute(ddl)
+    for statement in re.split(r"\n(?=CREATE (?:FUNCTION|CONSTRAINT TRIGGER|TRIGGER))", _FUNCTIONS):
+        if statement.strip():
+            op.execute(statement)
+    _extend_existing_guards()
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
+
+
+def _extend_audit_action():
+    """Allow only the fixed finalization action/permission evidence pair."""
+    op.execute("LOCK TABLE public.audit_events IN ACCESS EXCLUSIVE MODE")
+    name = "ck_audit_events_authorization_action_evidence"
+    definition = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_constraintdef(oid) FROM pg_catalog.pg_constraint "
+        "WHERE conrelid='public.audit_events'::regclass AND conname=:name"
+    ), {"name": name}).scalar_one()
+    anchor = "(((action_id)::text = 'contribution.read_self'::text) AND ((permission_id)::text = 'contribution.read_self'::text))"
+    if definition.count(anchor) != 2 or "artifact.submission.finalize" in definition:
+        raise RuntimeError("finalization audit action constraint shape changed")
+    addition = " OR (((action_id)::text = 'artifact.submission.finalize'::text) AND ((permission_id)::text = 'artifact.binding.create'::text))"
+    op.execute("ALTER TABLE public.audit_events DROP CONSTRAINT " + name)
+    op.execute("ALTER TABLE public.audit_events ADD CONSTRAINT " + name + " "
+               + definition.replace(anchor, anchor + addition))
+
+
+_CONSTRAINTS = [('submission_intake_operations',
+  'ck_submission_intake_operations_pre_requires_source',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT '
+  'ck_submission_intake_operations_pre_requires_source CHECK (state not in '
+  "('pre_checking','finalization_pending','finalized') or sealed_at is not null)"),
+ ('submission_intake_operations',
+  'ck_submission_intake_operations_terminal_shape',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT ck_submission_intake_operations_terminal_shape '
+  "CHECK ((state in ('receiving','pre_checking','finalization_pending') and terminal_at is null and "
+  "failure_code is null) or (state='finalized' and terminal_at is not null and failure_code is null) or "
+  "(state in ('rejected','failed','abandoned','cancelled') and terminal_at is not null and failure_code is "
+  'not null))'),
+ ('submission_intake_operations',
+  'ck_submission_intake_operations_foreground_state',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT ck_submission_intake_operations_foreground_state '
+  'CHECK (state in '
+  "('receiving','pre_checking','finalization_pending','finalized','rejected','failed','abandoned','cancelled'))"),
+ ('submission_intake_operations',
+  'ck_submission_intake_operations_acceptance_shape',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT ck_submission_intake_operations_acceptance_shape '
+  "CHECK ((state in ('finalization_pending','finalized') and accepted_at is not null and "
+  'acceptance_decision_id is not null and selected_pre_submit_run_id is not null and '
+  'selected_pre_submit_request_sha256 is not null and selected_pre_submit_terminal_sha256 is not null and '
+  'accepted_source_sha256 is not null and accepted_manifest_sha256 is not null and accepted_context is not '
+  'null and accepted_context_sha256 is not null and acceptance_receipt is not null and '
+  'acceptance_receipt_sha256 is not null and finalization_event_id is not null) or (state not in '
+  "('finalization_pending','finalized') and accepted_at is null and acceptance_decision_id is null and "
+  'selected_pre_submit_run_id is null and selected_pre_submit_request_sha256 is null and '
+  'selected_pre_submit_terminal_sha256 is null and accepted_source_sha256 is null and '
+  'accepted_manifest_sha256 is null and accepted_context is null and accepted_context_sha256 is null and '
+  'acceptance_receipt is null and acceptance_receipt_sha256 is null and finalization_event_id is null))'),
+ ('submission_intake_operations',
+  'fk_intake_finalization_decision',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT fk_intake_finalization_decision FOREIGN '
+  'KEY(finalization_decision_id) REFERENCES audit_events (id) DEFERRABLE INITIALLY DEFERRED'),
+ ('submission_intake_operations',
+  'fk_intake_continuation_decision',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT fk_intake_continuation_decision FOREIGN '
+  'KEY(continuation_decision_id) REFERENCES audit_events (id) DEFERRABLE INITIALLY DEFERRED'),
+ ('submission_intake_operations',
+  'fk_intake_finalized_submission',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT fk_intake_finalized_submission FOREIGN '
+  'KEY(finalized_submission_id) REFERENCES submissions (id) DEFERRABLE INITIALLY DEFERRED'),
+ ('submission_intake_operations',
+  'fk_intake_finalized_admission',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT fk_intake_finalized_admission FOREIGN '
+  'KEY(finalized_admission_id) REFERENCES submission_bundle_admissions (id) DEFERRABLE INITIALLY DEFERRED'),
+ ('submission_intake_operations',
+  'uq_intake_finalized_submission',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT uq_intake_finalized_submission UNIQUE '
+  '(finalized_submission_id)'),
+ ('submission_intake_operations',
+  'uq_intake_finalized_admission',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT uq_intake_finalized_admission UNIQUE '
+  '(finalized_admission_id)'),
+ ('submission_intake_operations',
+  'ck_submission_intake_operations_continuation_shape',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT '
+  'ck_submission_intake_operations_continuation_shape CHECK ((continuation_lease_id is null and '
+  'continuation_generation is null and continuation_expires_at is null and continuation_decision_id is null) '
+  "or (state in ('finalization_pending','finalized') and continuation_lease_id is not null and "
+  'continuation_generation is not null and continuation_generation>0 and continuation_expires_at is not null '
+  'and continuation_decision_id is not null))'),
+ ('submission_intake_operations',
+  'ck_submission_intake_operations_finalization_shape',
+  'ALTER TABLE submission_intake_operations ADD CONSTRAINT '
+  "ck_submission_intake_operations_finalization_shape CHECK ((state='finalized' and finalized_at is not null "
+  'and finalized_at=terminal_at and finalization_decision_id is not null and finalized_submission_id is not '
+  "null and finalized_admission_id is not null and continuation_lease_id is not null) or (state<>'finalized' "
+  'and finalized_at is null and finalization_decision_id is null and finalized_submission_id is null and '
+  'finalized_admission_id is null))'),
+ ('submission_bundle_admissions',
+  'fk_submission_bundle_admissions_source_operation_id_submission_intake_operations',
+  'ALTER TABLE submission_bundle_admissions ADD CONSTRAINT '
+  'fk_submission_bundle_admissions_source_operation_id_sub_3f5f FOREIGN KEY(source_operation_id) REFERENCES '
+  'submission_intake_operations (id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED'),
+ ('submission_bundle_admissions',
+  'uq_submission_bundle_admissions_source_operation_id',
+  'ALTER TABLE submission_bundle_admissions ADD CONSTRAINT '
+  'uq_submission_bundle_admissions_source_operation_id UNIQUE (source_operation_id)'),
+ ('submission_bundle_admissions',
+  'ck_submission_bundle_admissions_write_receipt_shape',
+  'ALTER TABLE submission_bundle_admissions ADD CONSTRAINT '
+  'ck_submission_bundle_admissions_write_receipt_shape CHECK ((source_operation_id is null and '
+  'durable_intent_id is not null and put_attempt_id is not null and verification_receipt_id is not null and '
+  '((put_operation_receipt_id is not null)::int + (put_observation_receipt_id is not null)::int) = 1) or '
+  '(source_operation_id is not null and durable_intent_id is null and put_attempt_id is null and '
+  'verification_receipt_id is null and put_operation_receipt_id is null and put_observation_receipt_id is '
+  'null))'),
+ ('artifact_replicas',
+  'uq_artifact_replicas_source_operation_id',
+  'ALTER TABLE artifact_replicas ADD CONSTRAINT uq_artifact_replicas_source_operation_id UNIQUE '
+  '(source_operation_id)'),
+ ('artifact_replicas',
+  'fk_artifact_replicas_source_operation_id_submission_intake_operations',
+  'ALTER TABLE artifact_replicas ADD CONSTRAINT fk_artifact_replicas_source_operation_id_submission_int_1e83 '
+  'FOREIGN KEY(source_operation_id) REFERENCES submission_intake_operations (id) ON DELETE RESTRICT '
+  'DEFERRABLE INITIALLY DEFERRED')]
+
+
+def _extend_existing_guards():
+    anchor = "  IF OLD.state='pre_checking' AND NEW.state='finalization_pending' THEN"
+    _replace("public.guard_submission_intake_mutation()", anchor, _CONTINUATION_MUTATION + anchor)
+    _replace("public.check_submission_acceptance()", "o.state<>'finalization_pending'",
+             "o.state NOT IN ('finalization_pending','finalized')")
+    _replace("public.check_submission_acceptance()", "NEW.state<>'finalization_pending'",
+             "NEW.state NOT IN ('finalization_pending','finalized')")
+    _replace("public.guard_submission_bundle_admission_verified_lineage()",
+             "begin\n if new.pre_submit_evidence_set_id is not null",
+             "begin\n if new.source_operation_id is not null then\n"
+             "  perform public.require_source_submission_admission(new); return new;\n end if;\n"
+             " if new.pre_submit_evidence_set_id is not null")
+    original = "public.submission_authority_receipt_valid(d.creation_decision_id,public.submission_creation_resource(s.id),true)"
+    _replace("public.submission_dispatch_valid(public.submission_dispatches)", original,
+             "(CASE WHEN a.source_operation_id IS NULL THEN " + original + " ELSE EXISTS ("
+             "SELECT 1 FROM public.submission_intake_operations o WHERE o.id=a.source_operation_id "
+             "AND o.state='finalized' AND o.finalized_submission_id=s.id "
+             "AND o.finalized_admission_id=a.id AND o.acceptance_decision_id=d.creation_decision_id) END)")
+
+
+_CONTINUATION_MUTATION = """  IF OLD.state='finalization_pending' AND NEW.state='finalization_pending'
+     AND ROW(NEW.continuation_lease_id,NEW.continuation_generation,NEW.continuation_expires_at,NEW.continuation_decision_id)
+         IS DISTINCT FROM ROW(OLD.continuation_lease_id,OLD.continuation_generation,OLD.continuation_expires_at,OLD.continuation_decision_id) THEN
+    IF (to_jsonb(NEW)-ARRAY['continuation_lease_id','continuation_generation','continuation_expires_at','continuation_decision_id'])
+       IS DISTINCT FROM (to_jsonb(OLD)-ARRAY['continuation_lease_id','continuation_generation','continuation_expires_at','continuation_decision_id'])
+       OR NEW.continuation_generation IS DISTINCT FROM coalesce(OLD.continuation_generation,0)+1
+       OR NEW.continuation_lease_id IS NOT DISTINCT FROM OLD.continuation_lease_id
+       OR (OLD.continuation_expires_at IS NOT NULL AND OLD.continuation_expires_at>clock_timestamp())
+       OR NOT isfinite(NEW.continuation_expires_at) OR NEW.continuation_expires_at<=clock_timestamp() THEN
+      RAISE EXCEPTION 'invalid submission continuation claim' USING ERRCODE='23514';
+    END IF;
+    RETURN NEW;
+  END IF;
+  IF OLD.state='finalization_pending' AND NEW.state='finalized' THEN
+    IF (to_jsonb(NEW)-ARRAY['state','terminal_at','finalized_at','finalization_decision_id','finalized_submission_id','finalized_admission_id'])
+       IS DISTINCT FROM (to_jsonb(OLD)-ARRAY['state','terminal_at','finalized_at','finalization_decision_id','finalized_submission_id','finalized_admission_id'])
+       OR OLD.continuation_expires_at IS NULL OR OLD.continuation_expires_at<=clock_timestamp()
+       OR NOT isfinite(NEW.finalized_at) OR NEW.finalized_atclock_timestamp() THEN
+      RAISE EXCEPTION 'invalid submission finalization transition' USING ERRCODE='23514';
+    END IF;
+    RETURN NEW;
+  END IF;
+"""
+
+_FUNCTIONS = r"""
+CREATE FUNCTION public.submission_finalization_authority_valid(o public.submission_intake_operations, phase text)
+RETURNS boolean LANGUAGE sql STABLE SET search_path=pg_catalog,public,pg_temp AS $$
+ SELECT coalesce(EXISTS (
+  SELECT 1 FROM public.audit_events a JOIN public.actor_profiles p ON p.id::text=a.actor_id
+  WHERE a.id=(CASE WHEN phase='claim' THEN o.continuation_decision_id ELSE o.finalization_decision_id END)
+    AND phase IN ('claim','commit') AND a.event_domain='authority' AND a.event_type='SensitiveAuthorizationAllowed'
+    AND a.actor_ref_kind='actor_profile' AND p.actor_kind='service' AND p.service_identity='workstream.artifact.binding'
+    AND a.action_id='artifact.submission.finalize' AND a.permission_id='artifact.binding.create'
+    AND a.project_id=o.project_id AND a.resource_type='submission_operation' AND a.resource_id=o.id::text
+    AND a.target_ref_kind='project' AND a.target_ref_id=o.project_id::text AND a.matched_grant_id IS NULL
+    AND a.denial_code IS NULL AND a.request_id IS NOT NULL AND a.correlation_id IS NOT NULL
+    AND a.after_facts::jsonb=jsonb_build_object('allowed',true,'resource_context_digest',
+      public.external_checker_registry_digest(jsonb_build_object('resource_context',jsonb_strip_nulls(jsonb_build_object(
+        'resource_type','submission_finalization','resource_id',o.id::text,'operation_id',o.id::text,
+        'project_id',o.project_id::text,'task_id',o.task_id::text,'assignment_id',o.assignment_id::text,
+        'contributor_id',o.actor_profile_id::text,'acceptance_decision_id',o.acceptance_decision_id::text,
+        'accepted_context_sha256',o.accepted_context_sha256,'acceptance_receipt_sha256',o.acceptance_receipt_sha256,
+        'source_sha256',o.accepted_source_sha256,'continuation_lease_id',o.continuation_lease_id::text,
+        'continuation_generation',o.continuation_generation,'phase',phase,
+        'submission_id',CASE WHEN phase='commit' THEN o.finalized_submission_id::text ELSE NULL END,
+        'submission_version',CASE WHEN phase='commit' THEN
+          (SELECT version FROM public.submissions WHERE id=o.finalized_submission_id) ELSE NULL END)))))
+ ),false)
+$$;
+
+CREATE FUNCTION public.require_source_submission_admission(a public.submission_bundle_admissions)
+RETURNS void LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE o public.submission_intake_operations%ROWTYPE; r public.selected_pre_submit_runs%ROWTYPE;
+ v public.artifact_replicas%ROWTYPE; c public.artifact_contents%ROWTYPE; expected jsonb; actual jsonb;
+BEGIN
+ SELECT * INTO o FROM public.submission_intake_operations WHERE id=a.source_operation_id;
+ IF o.id IS NULL OR o.state NOT IN ('finalization_pending','finalized') THEN
+   RAISE EXCEPTION 'source admission has no accepted owner' USING ERRCODE='23514';
+ END IF;
+ PERFORM public.require_submission_acceptance(o);
+ SELECT * INTO r FROM public.selected_pre_submit_runs WHERE id=o.selected_pre_submit_run_id;
+ SELECT * INTO v FROM public.artifact_replicas WHERE id=a.verified_replica_id;
+ SELECT * INTO c FROM public.artifact_contents WHERE id=a.artifact_content_id;
+ IF a.selected_pre_submit_run_id IS DISTINCT FROM r.id OR a.pre_submit_evidence_set_id IS NOT NULL
+    OR v.id IS NULL OR c.id IS NULL OR v.source_operation_id IS DISTINCT FROM o.id
+    OR v.content_id IS DISTINCT FROM c.id OR v.storage_namespace_id IS DISTINCT FROM o.namespace_id
+    OR v.namespace_fingerprint IS DISTINCT FROM o.namespace_fingerprint OR v.provider_profile IS DISTINCT FROM o.provider_profile
+    OR v.provider_object_ref IS DISTINCT FROM o.object_ref OR c.sha256 IS DISTINCT FROM o.raw_sha256
+    OR c.byte_count IS DISTINCT FROM o.raw_byte_count OR c.media_type IS DISTINCT FROM 'application/zip'
+    OR v.verification_state IS DISTINCT FROM 'verified' OR v.integrity_state IS DISTINCT FROM 'valid'
+    OR a.actor_profile_id IS DISTINCT FROM o.actor_profile_id OR a.identity_link_id IS DISTINCT FROM o.identity_link_id
+    OR a.project_id IS DISTINCT FROM o.project_id OR a.task_id IS DISTINCT FROM o.task_id
+    OR a.assignment_id IS DISTINCT FROM o.assignment_id OR a.archive_sha256 IS DISTINCT FROM o.raw_sha256
+    OR a.archive_byte_count IS DISTINCT FROM o.raw_byte_count
+    OR a.semantic_manifest_body IS DISTINCT FROM r.terminal_json#>'{execution,manifest_body}'
+    OR a.semantic_manifest_sha256 IS DISTINCT FROM o.accepted_manifest_sha256
+    OR a.semantic_manifest_id IS NULL OR a.ready_at IS NULL OR a.ready_at>'revision_preparation_id'
+    OR a.revision_preparation_sha256 IS DISTINCT FROM o.command_metadata->>'revision_preparation_sha256' THEN
+   RAISE EXCEPTION 'source admission provenance mismatch' USING ERRCODE='23514';
+ END IF;
+ expected:=r.request_json->'admission_lineage';
+ actual:=jsonb_build_object(
+   'predecessor_submission_id',a.predecessor_submission_id,'predecessor_submission_version',a.predecessor_submission_version,
+   'checker_remediation_manifest_id',a.checker_remediation_manifest_id,
+   'guide_id',a.guide_id,'guide_version',a.guide_version,'source_snapshot_id',a.source_snapshot_id,
+   'source_snapshot_sha256',a.source_snapshot_sha256,'effective_policy_id',a.effective_policy_id,
+   'effective_policy_sha256',a.effective_policy_sha256,'pre_submit_policy_id',a.pre_submit_policy_id,
+   'pre_submit_policy_sha256',a.pre_submit_policy_sha256,'effective_plan_sha256',a.effective_plan_sha256,
+   'rules_sha256',a.selected_rules_sha256,'post_submit_policy_sha256',a.selected_post_submit_policy_sha256,
+   'post_submit_policy_body',a.selected_post_submit_policy_body,'locked_policy_context_hash',a.locked_policy_context_hash,
+   'packet_sha256',a.packet_sha256);
+ IF EXISTS(SELECT 1 FROM jsonb_each(actual) WHERE value IS DISTINCT FROM expected->key) THEN
+   RAISE EXCEPTION 'source admission locked lineage mismatch' USING ERRCODE='23514';
+ END IF;
+END $$;
+
+CREATE FUNCTION public.check_submission_finalization()
+RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE o public.submission_intake_operations%ROWTYPE; a public.submission_bundle_admissions%ROWTYPE;
+ d public.submission_dispatches%ROWTYPE; source_id uuid;
+BEGIN
+ IF TG_TABLE_NAME='submission_intake_operations' THEN
+   source_id:=NEW.id;
+ ELSE
+   IF TG_OP='UPDATE' AND OLD.source_operation_id IS DISTINCT FROM NEW.source_operation_id THEN
+     RAISE EXCEPTION 'retained source ownership is immutable' USING ERRCODE='23514';
+   END IF;
+   source_id:=CASE WHEN TG_OP='DELETE' THEN OLD.source_operation_id ELSE NEW.source_operation_id END;
+ END IF;
+ IF source_id IS NULL THEN RETURN NULL; END IF;
+ SELECT * INTO o FROM public.submission_intake_operations WHERE id=source_id;
+ IF o.continuation_lease_id IS NULL THEN
+   IF TG_TABLE_NAME<>'submission_intake_operations' THEN
+     RAISE EXCEPTION 'retained source has no continuation' USING ERRCODE='23514';
+   END IF;
+   RETURN NULL;
+ END IF;
+ PERFORM public.require_submission_acceptance(o);
+ IF NOT public.submission_finalization_authority_valid(o,'claim') THEN
+   RAISE EXCEPTION 'submission continuation authority mismatch' USING ERRCODE='23514';
+ END IF;
+ IF TG_TABLE_NAME='submission_intake_operations' THEN
+   IF TG_OP='UPDATE' THEN
+     IF (OLD.continuation_generation IS DISTINCT FROM NEW.continuation_generation OR OLD.state IS DISTINCT FROM NEW.state)
+        AND o.continuation_expires_at<=clock_timestamp() THEN
+       RAISE EXCEPTION 'submission continuation expired before commit' USING ERRCODE='23514';
+     END IF;
+   END IF;
+ END IF;
+ IF o.state='finalized' THEN
+   SELECT * INTO a FROM public.submission_bundle_admissions WHERE id=o.finalized_admission_id;
+   SELECT * INTO d FROM public.submission_dispatches WHERE submission_id=o.finalized_submission_id;
+   IF a.id IS NULL OR a.source_operation_id IS DISTINCT FROM o.id OR a.status<>'consumed'
+      OR a.consumed_by_submission_id IS DISTINCT FROM o.finalized_submission_id
+      OR d.submission_id IS NULL OR d.admission_id IS DISTINCT FROM a.id
+      OR d.creation_decision_id IS DISTINCT FROM o.acceptance_decision_id
+      OR NOT public.submission_dispatch_valid(d)
+      OR NOT public.submission_finalization_authority_valid(o,'commit') THEN
+     RAISE EXCEPTION 'submission finalization closure mismatch' USING ERRCODE='23514';
+   END IF;
+   PERFORM public.require_source_submission_admission(a);
+ ELSIF TG_TABLE_NAME<>'submission_intake_operations' THEN
+   RAISE EXCEPTION 'retained source requires finalized owner' USING ERRCODE='23514';
+ END IF;
+ RETURN NULL;
+END $$;
+CREATE CONSTRAINT TRIGGER submission_finalization_closure AFTER INSERT OR UPDATE ON public.submission_intake_operations
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_finalization();
+CREATE CONSTRAINT TRIGGER source_admission_finalization_closure AFTER INSERT OR UPDATE OR DELETE ON public.submission_bundle_admissions
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_finalization();
+CREATE CONSTRAINT TRIGGER source_replica_finalization_closure AFTER INSERT OR UPDATE OR DELETE ON public.artifact_replicas
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_submission_finalization();
+"""
diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py
index c51d62360..158019fbf 100644
--- a/backend/app/adapters/tasks/__init__.py
+++ b/backend/app/adapters/tasks/__init__.py
@@ -335,6 +335,7 @@ async def consume(
                 submission_version=request.submission_version,
                 task_context=request.task_context,
                 packet_sha256=request.packet.sha256,
+                accepted_operation_id=request.accepted_operation_id,
             )
         )
         if (
@@ -721,3 +722,15 @@ def intake_task_custody_port(session):
     from app.modules.tasks.intake_custody import IntakeTaskCustody
 
     return IntakeTaskCustody(session, task_submission_context_port(session))
+
+
+def accepted_submission_creation_service(session, *, settings, admissions):
+    """Compose accepted continuation with the existing sole Submission writer."""
+    from app.adapters.checkers import evaluation_coordinator
+    from app.adapters.outbox import outbox_append
+    return TaskSubmissionCreationService(
+        session, contexts=task_service(session, settings=settings),
+        submission_contexts=task_submission_context_port(session), authorization=None,
+        admissions=_ArtifactAdmissionAdapter(admissions), evaluations=evaluation_coordinator(session),
+        events=outbox_append(session),
+    )
diff --git a/backend/app/modules/artifacts/api/submission_admission.py b/backend/app/modules/artifacts/api/submission_admission.py
index 226d34d84..58a7aca98 100644
--- a/backend/app/modules/artifacts/api/submission_admission.py
+++ b/backend/app/modules/artifacts/api/submission_admission.py
@@ -39,6 +39,7 @@ class SubmissionAdmissionConsumptionRequest:
     submission_version: int
     task_context: TaskSubmissionContextFacts
     packet_sha256: str
+    accepted_operation_id: UUID | None = None
 
     def __post_init__(self) -> None:
         if type(self.submission_version) is not int or self.submission_version < 1:
diff --git a/backend/app/modules/artifacts/api/submission_finalization.py b/backend/app/modules/artifacts/api/submission_finalization.py
new file mode 100644
index 000000000..6c2a6731e
--- /dev/null
+++ b/backend/app/modules/artifacts/api/submission_finalization.py
@@ -0,0 +1,22 @@
+"""Exact accepted continuation selectors; values confer no authority themselves."""
+from dataclasses import dataclass
+from typing import Literal
+from uuid import UUID
+
+
+@dataclass(frozen=True, slots=True)
+class SubmissionFinalizationAuthorityFacts:
+    operation_id: UUID
+    project_id: UUID
+    task_id: UUID
+    assignment_id: UUID
+    contributor_id: UUID
+    acceptance_decision_id: UUID
+    accepted_context_sha256: str
+    acceptance_receipt_sha256: str
+    source_sha256: str
+    continuation_lease_id: UUID
+    continuation_generation: int
+    phase: Literal["claim", "commit"]
+    submission_id: UUID | None = None
+    submission_version: int | None = None
diff --git a/backend/app/modules/artifacts/authorization.py b/backend/app/modules/artifacts/authorization.py
index 012400319..d25f6cdb4 100644
--- a/backend/app/modules/artifacts/authorization.py
+++ b/backend/app/modules/artifacts/authorization.py
@@ -29,6 +29,8 @@
     ArtifactVerificationAuthorityFacts,
 )
 from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts
+from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationAuthorityFacts
+from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
 
 from app.modules.artifacts.submission_bindings import SubmissionBindingAuthorityFacts
 from app.modules.artifacts.api import SubmissionAdmissionConsumptionError
@@ -544,7 +546,7 @@ def __init__(
         self._facts: (
             GuideSourceReadAuthorityFacts
             | PreSubmitSourceReadFacts
-            | SubmissionBindingAuthorityFacts
+            | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts
             | None
         ) = None
 
@@ -553,7 +555,7 @@ async def prepare(
         *,
         facts: GuideSourceReadAuthorityFacts
         | PreSubmitSourceReadFacts
-        | SubmissionBindingAuthorityFacts,
+        | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
         idempotency_key: UUID,
     ) -> PreparedAuthorizationHandle:
         """Prepare one process-local capability bound to every canonical fact."""
@@ -614,7 +616,7 @@ async def consume(
         prepared_authorization: PreparedAuthorizationHandle,
         facts: GuideSourceReadAuthorityFacts
         | PreSubmitSourceReadFacts
-        | SubmissionBindingAuthorityFacts,
+        | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
     ) -> UUID | None:
         """Consume only the exact handle and facts prepared by this adapter."""
         if (
@@ -632,7 +634,7 @@ async def consume(
                 self._input,
                 _artifact_service_resource_context(facts),
             )
-            if self._action_id is ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE:
+            if self._action_id in {ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE, ActionId.ARTIFACT_SUBMISSION_FINALIZE}:
                 return decision.decision_id
             return None
         except (AuthorizationDenied, PreparedAuthorizationHandleInvalid, ValidationError) as exc:
@@ -671,6 +673,24 @@ def close(self) -> None:
         self._facts = None
 
 
+class PreparedSubmissionFinalizationAuthorization(_PreparedArtifactServiceAuthorization):
+    """Accepted continuation authority belongs only to the existing binding service."""
+
+    def __init__(self, session: AsyncSession, *, request_id: UUID, correlation_id: UUID) -> None:
+        super().__init__(session, service_identity=ServiceIdentity.ARTIFACT_BINDING,
+                         action_id=ActionId.ARTIFACT_SUBMISSION_FINALIZE,
+                         request_id=request_id, correlation_id=correlation_id)
+
+
+    async def authorize(self) -> None:
+        """Check the current fixed service before replay or provider observation."""
+        await fixed_service_action_context(
+            self._session, service_identity=ServiceIdentity.ARTIFACT_BINDING,
+            action_id=ActionId.ARTIFACT_SUBMISSION_FINALIZE,
+            request_id=self._request_id, correlation_id=self._correlation_id,
+        )
+
+
 class PreparedSubmissionBindingAuthorization:
     """Prepare and consume exact authority for the fixed artifact binding service."""
 
@@ -783,14 +803,16 @@ def close(self) -> None:
 
 
 def _artifact_service_resource_context(
-    facts: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts,
-) -> GuideSourceReadResourceContext | PreSubmitCheckerInputResourceContext | SubmissionBindingResourceContext:
+    facts: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
+) -> GuideSourceReadResourceContext | PreSubmitCheckerInputResourceContext | SubmissionBindingResourceContext | SubmissionFinalizationResourceContext:
     """Compose AUTH context for the exact fixed ART service operation."""
     if type(facts) is PreSubmitSourceReadFacts:
         return PreSubmitCheckerInputResourceContext(
             resource_id=facts.source.location.operation_id,
             scope_project_id=facts.project_id, facts=facts,
         )
+    if type(facts) is SubmissionFinalizationAuthorityFacts:
+        return SubmissionFinalizationResourceContext(resource_id=facts.operation_id, **asdict(facts))
     if isinstance(facts, SubmissionBindingAuthorityFacts):
         return SubmissionBindingResourceContext(
             resource_type="submission_binding", resource_id=facts.admission_id, **asdict(facts),
@@ -801,8 +823,8 @@ def _artifact_service_resource_context(
 
 
 def _prepared_artifact_facts_match(
-    prepared: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts,
-    final: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionBindingAuthorityFacts,
+    prepared: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
+    final: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
 ) -> bool:
     """Require source, lease and every locked fact to remain exactly prepared."""
     return type(prepared) is type(final) and prepared == final
diff --git a/backend/app/modules/artifacts/intake/finalization.py b/backend/app/modules/artifacts/intake/finalization.py
new file mode 100644
index 000000000..dc611c5f8
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/finalization.py
@@ -0,0 +1,181 @@
+"""Durable accepted continuation: observe the same source, then commit one T5."""
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+from datetime import timedelta
+from uuid import UUID
+
+from sqlalchemy import func, select, text
+from sqlalchemy.exc import DBAPIError
+
+from app.core.cancellation import await_completion_preserving_cancellation
+from app.core.identifiers import new_record_id
+from app.interfaces.artifacts import SealedSourceObservation
+from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationAuthorityFacts
+from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
+from app.modules.artifacts.intake.foreground_admission import IntakeCommitUnknown
+from app.modules.artifacts.intake.registration import register_accepted_source
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
+from app.modules.tasks.api import SubmissionCreationRequest, SubmissionCreationResult
+
+
+@dataclass(frozen=True, slots=True)
+class AcceptedContinuation:
+    source: SealedSubmissionSource
+    lease_id: UUID
+    generation: int
+
+
+def continuation_facts(row, lease_id, generation):
+    return SubmissionFinalizationAuthorityFacts(
+        operation_id=UUID(row.id), project_id=UUID(row.project_id), task_id=UUID(row.task_id),
+        assignment_id=UUID(row.assignment_id), contributor_id=UUID(row.actor_profile_id),
+        acceptance_decision_id=UUID(row.acceptance_decision_id),
+        accepted_context_sha256=row.accepted_context_sha256, acceptance_receipt_sha256=row.acceptance_receipt_sha256,
+        source_sha256=row.accepted_source_sha256, continuation_lease_id=lease_id,
+        continuation_generation=generation, phase="claim",
+    )
+
+
+class AcceptedSubmissionFinalization:
+    """Keep provider I/O outside TASK locks; finalized replay precedes new claims."""
+
+    def __init__(self, sessions, *, tasks, authorization, submissions, checkers, store, lease_duration):
+        if not isinstance(lease_duration, timedelta) or lease_duration <= timedelta(0):
+            raise ValueError("finalization lease duration must be explicit and positive")
+        self._sessions, self._tasks, self._authorization = sessions, tasks, authorization
+        self._submissions, self._store, self._duration = submissions, store, lease_duration
+        self._checkers = checkers
+
+    @asynccontextmanager
+    async def _root(self):
+        session = self._sessions()
+        authority = self._authorization(session)
+        try:
+            await session.begin()
+            yield session, authority
+            try:
+                await await_completion_preserving_cancellation(session.commit())
+            except DBAPIError as exc:
+                if not exc.connection_invalidated:
+                    raise
+                raise IntakeCommitUnknown("finalization commit acknowledgement unavailable") from exc
+            except Exception as exc:
+                raise IntakeCommitUnknown("finalization commit acknowledgement unavailable") from exc
+        finally:
+            authority.close()
+            await await_completion_preserving_cancellation(session.close())
+
+    async def run(self, operation_id: UUID) -> SubmissionCreationResult:
+        lease_id = new_record_id()
+        try:
+            claim = await self._claim(operation_id, lease_id)
+        except IntakeCommitUnknown:
+            claim = await self._recover_claim(operation_id, lease_id)
+        if isinstance(claim, SubmissionCreationResult):
+            return claim
+        observation = await self._store.observe_sealed_source(claim.source)
+        if observation is None:
+            raise IntakeCustodyConflict("finalization_source_unavailable")
+        try:
+            return await self._finalize(operation_id, claim, observation)
+        except IntakeCommitUnknown:
+            async with self._root() as (session, authority):
+                row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(operation_id)
+                await authority.authorize()
+                return await self._finalized(session, row)
+
+    async def _claim(self, operation_id, lease_id):
+        async with self._root() as (session, authority):
+            row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(operation_id)
+            await authority.authorize()
+            if row.state == "finalized":
+                return await self._finalized(session, row)
+            if row.state != "finalization_pending":
+                raise IntakeCustodyConflict("finalization_not_accepted")
+            await session.execute(text("SELECT public.require_submission_acceptance(o) "
+                "FROM public.submission_intake_operations o WHERE id=:id"), {"id": row.id})
+            now = await session.scalar(select(func.clock_timestamp()))
+            if row.continuation_expires_at is not None and row.continuation_expires_at > now:
+                raise IntakeCustodyConflict("finalization_lease_busy")
+            generation = (row.continuation_generation or 0) + 1
+            facts = continuation_facts(row, lease_id, generation)
+            handle = await authority.prepare(facts=facts, idempotency_key=lease_id)
+            decision = await authority.consume(prepared_authorization=handle, facts=facts)
+            if not isinstance(decision, UUID):
+                raise IntakeCustodyConflict("finalization_authority_unavailable")
+            row.continuation_lease_id, row.continuation_generation = str(lease_id), generation
+            row.continuation_expires_at, row.continuation_decision_id = now + self._duration, str(decision)
+            await session.flush()
+            return AcceptedContinuation(SubmissionIntakeRepository._sealed_source(row), lease_id, generation)
+
+    async def _recover_claim(self, operation_id, lease_id):
+        async with self._root() as (session, authority):
+            row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(operation_id)
+            await authority.authorize()
+            if row.state == "finalized":
+                return await self._finalized(session, row)
+            now = await session.scalar(select(func.clock_timestamp()))
+            if (row.state != "finalization_pending" or row.continuation_lease_id != str(lease_id)
+                    or row.continuation_expires_at is None or row.continuation_expires_at <= now):
+                raise IntakeCommitUnknown("finalization claim unavailable")
+            await session.execute(text("SELECT public.require_submission_acceptance(o) "
+                "FROM public.submission_intake_operations o WHERE id=:id"), {"id": row.id})
+            valid = await session.scalar(text("SELECT public.submission_finalization_authority_valid(o,'claim') "
+                "FROM public.submission_intake_operations o WHERE id=:id"), {"id": row.id})
+            if valid is not True:
+                raise IntakeCustodyConflict("finalization_authority_unavailable")
+            return AcceptedContinuation(SubmissionIntakeRepository._sealed_source(row), lease_id, row.continuation_generation)
+
+    async def _finalize(self, operation_id: UUID, claim: AcceptedContinuation, observation: SealedSourceObservation):
+        async with self._root() as (session, authority):
+            tasks = self._tasks(session)
+            row = await SubmissionIntakeRepository(session, tasks)._lock(operation_id)
+            await authority.authorize()
+            if row.state == "finalized":
+                return await self._finalized(session, row)
+            now = await session.scalar(select(func.clock_timestamp()))
+            if (row.state != "finalization_pending" or row.continuation_lease_id != str(claim.lease_id)
+                    or row.continuation_generation != claim.generation or row.continuation_expires_at <= now
+                    or SubmissionIntakeRepository._sealed_source(row) != claim.source):
+                raise IntakeCustodyConflict("finalization_lease_stale")
+            terminal = await self._checkers(session).read_accepted_terminal(
+                run_id=UUID(row.selected_pre_submit_run_id), source_operation_id=operation_id,
+                terminal_digest=row.selected_pre_submit_terminal_sha256,
+            )
+            admission_id = await register_accepted_source(session, row, observation, terminal)
+            metadata = row.command_metadata
+            result, decision = await self._submissions(session).create_accepted(
+                SubmissionCreationRequest(
+                    admission_id=admission_id, task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id),
+                    contributor_id=UUID(row.actor_profile_id),
+                    predecessor_submission_id=UUID(metadata["predecessor_submission_id"]) if metadata["predecessor_submission_id"] else None,
+                    summary=metadata["summary"], contributor_attestation=metadata["contributor_attestation"],
+                ), authority_facts=continuation_facts(row, claim.lease_id, claim.generation),
+                finalization_authority=authority, snapshot_sha256=row.locked_context_sha256,
+                eligible_status=row.eligible_task_status,
+                remediation_id=UUID(row.accepted_context["checker_remediation_manifest_id"])
+                if row.accepted_context["checker_remediation_manifest_id"] else None,
+            )
+            row.state = "finalized"
+            row.finalized_at = row.terminal_at = await session.scalar(select(func.clock_timestamp()))
+            row.finalized_submission_id, row.finalized_admission_id = str(result.submission_id), str(admission_id)
+            row.finalization_decision_id = str(decision)
+            await tasks.release(UUID(row.task_id), operation_id)
+            await session.flush()
+            return result
+
+    async def _finalized(self, session, row):
+        if row.state != "finalized":
+            raise IntakeCommitUnknown("finalization result unavailable")
+        await session.execute(text("SELECT public.require_submission_acceptance(o) "
+            "FROM public.submission_intake_operations o WHERE id=:id"), {"id": row.id})
+        valid = await session.scalar(text("SELECT public.submission_finalization_authority_valid(o,'claim') "
+            "AND public.submission_finalization_authority_valid(o,'commit') "
+            "FROM public.submission_intake_operations o WHERE id=:id"), {"id": row.id})
+        await session.execute(text("SELECT public.require_source_submission_admission(a) "
+            "FROM public.submission_bundle_admissions a WHERE id=:id"), {"id": row.finalized_admission_id})
+        if valid is not True:
+            raise IntakeCustodyConflict("finalization_result_mismatch")
+        return await self._submissions(session).read_finalized(
+            UUID(row.finalized_submission_id), UUID(row.finalized_admission_id), UUID(row.acceptance_decision_id),
+        )
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index 00d038199..3034c013e 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -211,8 +211,8 @@ async def accept(
                 row = await repository._lock(owner.operation_id)
                 await authority.authorize_read(IntakeOperationReadFacts(
                     UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id)))
-                self._match_acceptance_command(row, request, terminal_digest, accepted=row.state == "finalization_pending")
-                if row.state == "finalization_pending":
+                self._match_acceptance_command(row, request, terminal_digest, accepted=row.state in {"finalization_pending", "finalized"})
+                if row.state in {"finalization_pending", "finalized"}:
                     return await self._accepted_receipt(session, authority, row)
                 receipt = await self._accept_new(session, authority, repository, row, owner,
                                                  request, terminal_digest, checkers, outbox)
@@ -224,7 +224,7 @@ async def accept(
                 row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(owner.operation_id)
                 await authority.authorize_read(IntakeOperationReadFacts(
                     UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id)))
-                if row.state != "finalization_pending":
+                if row.state not in {"finalization_pending", "finalized"}:
                     raise IntakeCommitUnknown("submission acceptance outcome is unresolved")
                 self._match_acceptance_command(row, request, terminal_digest, accepted=True)
                 return await self._accepted_receipt(session, authority, row)
diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py
index 21ca9c8ad..438b7d1a6 100644
--- a/backend/app/modules/artifacts/intake/models.py
+++ b/backend/app/modules/artifacts/intake/models.py
@@ -30,7 +30,7 @@ class SubmissionIntakeOperation(Base):
         ForeignKeyConstraint(["assignment_id", "task_id", "actor_profile_id"], ["task_assignments.id", "task_assignments.task_id", "task_assignments.contributor_id"], name="fk_submission_intake_assignment", deferrable=True, initially="DEFERRED"),
         ForeignKeyConstraint(["identity_link_id", "actor_profile_id"], ["actor_identity_links.id", "actor_identity_links.actor_profile_id"], name="fk_submission_intake_identity", deferrable=True, initially="DEFERRED"),
         ForeignKeyConstraint(["namespace_id", "namespace_fingerprint"], ["artifact_storage_namespaces.id", "artifact_storage_namespaces.namespace_fingerprint"], name="fk_submission_intake_namespace"),
-        CheckConstraint("state in ('receiving','pre_checking','finalization_pending','rejected','failed','abandoned','cancelled')", name="foreground_state"),
+        CheckConstraint("state in ('receiving','pre_checking','finalization_pending','finalized','rejected','failed','abandoned','cancelled')", name="foreground_state"),
         CheckConstraint("eligible_task_status in ('in_progress','needs_revision')", name="eligible_status"),
         CheckConstraint("metadata_sha256 ~ '^sha256:[0-9a-f]{64}$' and locked_context_sha256 ~ '^sha256:[0-9a-f]{64}$'", name="identity_digests"),
         CheckConstraint("jsonb_typeof(command_metadata)='object' and jsonb_typeof(locked_task_context)='object'", name="command_shape"),
@@ -39,12 +39,20 @@ class SubmissionIntakeOperation(Base):
         CheckConstraint("lease_generation>0 and lease_expires_at<=coalesce(pre_deadline_at,upload_deadline_at) and upload_deadline_at>created_at", name="lease_bounds"),
         CheckConstraint("(raw_sha256 is null and raw_byte_count is null and eof_at is null) or (raw_sha256 is not null and raw_sha256 ~ '^sha256:[0-9a-f]{64}$' and raw_byte_count is not null and raw_byte_count between 1 and maximum_raw_bytes and eof_at is not null)", name="eof_identity"),
         CheckConstraint("(provider_generation is null and sealed_upload_fence is null and sealed_at is null and pre_deadline_at is null) or (provider_generation is not null and sealed_upload_fence is not null and sealed_upload_fence>0 and length(provider_generation)>0 and raw_sha256 is not null and sealed_at is not null and sealed_at>=eof_at and pre_deadline_at is not null and pre_deadline_at>sealed_at and (provider_profile<>'aws-s3-v1' or provider_generation<>'null'))", name="sealed_identity"),
-        CheckConstraint("state not in ('pre_checking','finalization_pending') or sealed_at is not null", name="pre_requires_source"),
-        CheckConstraint("(state in ('receiving','pre_checking','finalization_pending') and terminal_at is null and failure_code is null) or (state in ('rejected','failed','abandoned','cancelled') and terminal_at is not null and failure_code is not null)", name="terminal_shape"),
+        CheckConstraint("state not in ('pre_checking','finalization_pending','finalized') or sealed_at is not null", name="pre_requires_source"),
+        CheckConstraint("(state in ('receiving','pre_checking','finalization_pending') and terminal_at is null and failure_code is null) or (state='finalized' and terminal_at is not null and failure_code is null) or (state in ('rejected','failed','abandoned','cancelled') and terminal_at is not null and failure_code is not null)", name="terminal_shape"),
         ForeignKeyConstraint(["acceptance_decision_id"], ["audit_events.id"], name="fk_intake_acceptance_decision", deferrable=True, initially="DEFERRED"),
         ForeignKeyConstraint(["selected_pre_submit_run_id"], ["selected_pre_submit_runs.id"], name="fk_intake_accepted_pre_run", deferrable=True, initially="DEFERRED"),
         ForeignKeyConstraint(["finalization_event_id"], ["outbox_events.event_id"], name="fk_intake_finalization_event", deferrable=True, initially="DEFERRED"),
-        CheckConstraint("(state='finalization_pending' and accepted_at is not null and acceptance_decision_id is not null and selected_pre_submit_run_id is not null and selected_pre_submit_request_sha256 is not null and selected_pre_submit_terminal_sha256 is not null and accepted_source_sha256 is not null and accepted_manifest_sha256 is not null and accepted_context is not null and accepted_context_sha256 is not null and acceptance_receipt is not null and acceptance_receipt_sha256 is not null and finalization_event_id is not null) or (state<>'finalization_pending' and accepted_at is null and acceptance_decision_id is null and selected_pre_submit_run_id is null and selected_pre_submit_request_sha256 is null and selected_pre_submit_terminal_sha256 is null and accepted_source_sha256 is null and accepted_manifest_sha256 is null and accepted_context is null and accepted_context_sha256 is null and acceptance_receipt is null and acceptance_receipt_sha256 is null and finalization_event_id is null)", name="acceptance_shape"),
+        CheckConstraint("(state in ('finalization_pending','finalized') and accepted_at is not null and acceptance_decision_id is not null and selected_pre_submit_run_id is not null and selected_pre_submit_request_sha256 is not null and selected_pre_submit_terminal_sha256 is not null and accepted_source_sha256 is not null and accepted_manifest_sha256 is not null and accepted_context is not null and accepted_context_sha256 is not null and acceptance_receipt is not null and acceptance_receipt_sha256 is not null and finalization_event_id is not null) or (state not in ('finalization_pending','finalized') and accepted_at is null and acceptance_decision_id is null and selected_pre_submit_run_id is null and selected_pre_submit_request_sha256 is null and selected_pre_submit_terminal_sha256 is null and accepted_source_sha256 is null and accepted_manifest_sha256 is null and accepted_context is null and accepted_context_sha256 is null and acceptance_receipt is null and acceptance_receipt_sha256 is null and finalization_event_id is null)", name="acceptance_shape"),
+        ForeignKeyConstraint(["continuation_decision_id"], ["audit_events.id"], name="fk_intake_continuation_decision", deferrable=True, initially="DEFERRED"),
+        ForeignKeyConstraint(["finalization_decision_id"], ["audit_events.id"], name="fk_intake_finalization_decision", deferrable=True, initially="DEFERRED"),
+        ForeignKeyConstraint(["finalized_submission_id"], ["submissions.id"], name="fk_intake_finalized_submission", deferrable=True, initially="DEFERRED"),
+        ForeignKeyConstraint(["finalized_admission_id"], ["submission_bundle_admissions.id"], name="fk_intake_finalized_admission", deferrable=True, initially="DEFERRED"),
+        UniqueConstraint("finalized_submission_id", name="uq_intake_finalized_submission"),
+        UniqueConstraint("finalized_admission_id", name="uq_intake_finalized_admission"),
+        CheckConstraint("(continuation_lease_id is null and continuation_generation is null and continuation_expires_at is null and continuation_decision_id is null) or (state in ('finalization_pending','finalized') and continuation_lease_id is not null and continuation_generation is not null and continuation_generation>0 and continuation_expires_at is not null and continuation_decision_id is not null)", name="continuation_shape"),
+        CheckConstraint("(state='finalized' and finalized_at is not null and finalized_at=terminal_at and finalization_decision_id is not null and finalized_submission_id is not null and finalized_admission_id is not null and continuation_lease_id is not null) or (state<>'finalized' and finalized_at is null and finalization_decision_id is null and finalized_submission_id is null and finalized_admission_id is null)", name="finalization_shape"),
         UniqueConstraint("selected_pre_submit_run_id", name="uq_intake_accepted_pre_run"),
         UniqueConstraint("acceptance_decision_id", name="uq_intake_acceptance_decision"),
         UniqueConstraint("finalization_event_id", name="uq_intake_finalization_event"),
@@ -95,6 +103,14 @@ class SubmissionIntakeOperation(Base):
     acceptance_receipt: Mapped[dict | None] = mapped_column(JSONB(none_as_null=True))
     acceptance_receipt_sha256: Mapped[str | None] = mapped_column(String(71))
     finalization_event_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
+    continuation_lease_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
+    continuation_generation: Mapped[int | None] = mapped_column(BigInteger)
+    continuation_expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+    continuation_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
+    finalized_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+    finalization_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
+    finalized_submission_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
+    finalized_admission_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
     created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp())
 
 
diff --git a/backend/app/modules/artifacts/intake/registration.py b/backend/app/modules/artifacts/intake/registration.py
new file mode 100644
index 000000000..7621f1f6c
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/registration.py
@@ -0,0 +1,63 @@
+"""Register accepted source bytes in the existing retained ART identities."""
+from uuid import UUID
+from sqlalchemy import func, select
+
+from app.core.identifiers import new_record_id
+from app.interfaces.artifacts import SealedSourceObservation
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
+from app.modules.artifacts.models import ArtifactContent, ArtifactReplica, ArtifactStorageNamespace, SubmissionBundleAdmission
+from app.modules.artifacts.repository import ArtifactRepository
+
+
+async def register_accepted_source(session, row, observation, terminal):
+    """Caller holds accepted operation and continuation fence; never copy/upload bytes."""
+    source = SubmissionIntakeRepository._sealed_source(row)
+    if type(observation) is not SealedSourceObservation or observation != SealedSourceObservation(
+        source.location, source.provider_generation, source.raw_byte_count, source.sealed_upload_fence,
+    ):
+        raise IntakeCustodyConflict("finalization_source_observation_mismatch")
+    namespace = await session.get(ArtifactStorageNamespace, row.namespace_id)
+    if namespace is None or namespace.namespace_fingerprint != row.namespace_fingerprint:
+        raise IntakeCustodyConflict("finalization_source_unavailable")
+    content = await ArtifactRepository(session).get_or_create_content(ArtifactContent(
+        id=str(new_record_id()), sha256=row.raw_sha256, byte_count=row.raw_byte_count,
+        media_type="application/zip", normalized_display_name="submission.zip",
+    ))
+    if content.media_type != "application/zip":
+        raise IntakeCustodyConflict("finalization_content_type_mismatch")
+    replica = ArtifactReplica(
+        id=str(new_record_id()), content_id=content.id, source_operation_id=row.id,
+        storage_namespace_id=row.namespace_id, namespace_fingerprint=row.namespace_fingerprint,
+        adapter=namespace.adapter, provider_profile=row.provider_profile, provider_object_ref=row.object_ref,
+        verification_state="verified", availability_state="available", integrity_state="valid",
+    )
+    session.add(replica)
+    await session.flush()
+    lineage = terminal.lease.reservation.admission_lineage.canonical_body()
+    admission = SubmissionBundleAdmission(
+        id=str(new_record_id()), source_operation_id=row.id, durable_intent_id=None, put_attempt_id=None,
+        verification_receipt_id=None, pre_submit_evidence_set_id=None,
+        selected_pre_submit_run_id=row.selected_pre_submit_run_id, artifact_content_id=content.id, verified_replica_id=replica.id,
+        actor_profile_id=row.actor_profile_id, identity_link_id=row.identity_link_id,
+        project_id=row.project_id, task_id=row.task_id, assignment_id=row.assignment_id,
+        semantic_manifest_id=str(new_record_id()), semantic_manifest_sha256=row.accepted_manifest_sha256,
+        semantic_manifest_body=terminal.execution.manifest_body,
+        archive_sha256=row.raw_sha256, archive_byte_count=row.raw_byte_count,
+        status="ready", ready_at=await session.scalar(select(func.clock_timestamp())),
+        revision_preparation_id=(UUID(row.command_metadata["revision_preparation_id"])
+                                 if row.command_metadata["revision_preparation_id"] else None),
+        revision_preparation_sha256=row.command_metadata["revision_preparation_sha256"],
+    )
+    for name in ("predecessor_submission_id", "predecessor_submission_version", "guide_id", "guide_version",
+                 "source_snapshot_id", "source_snapshot_sha256", "effective_policy_id", "effective_policy_sha256",
+                 "pre_submit_policy_id", "pre_submit_policy_sha256", "effective_plan_sha256",
+                 "locked_policy_context_hash", "packet_sha256"):
+        setattr(admission, name, lineage[name])
+    admission.checker_remediation_manifest_id = (
+        UUID(lineage["checker_remediation_manifest_id"]) if lineage["checker_remediation_manifest_id"] else None)
+    admission.selected_rules_sha256 = lineage["rules_sha256"]
+    admission.selected_post_submit_policy_sha256 = lineage["post_submit_policy_sha256"]
+    admission.selected_post_submit_policy_body = lineage["post_submit_policy_body"]
+    session.add(admission)
+    await session.flush()
+    return UUID(admission.id)
diff --git a/backend/app/modules/artifacts/models.py b/backend/app/modules/artifacts/models.py
index ca4e2a009..33758536a 100644
--- a/backend/app/modules/artifacts/models.py
+++ b/backend/app/modules/artifacts/models.py
@@ -1687,8 +1687,11 @@ class SubmissionBundleAdmission(Base):
             name="revision_preparation_digest",
         ),
         CheckConstraint(
-            "((put_operation_receipt_id is not null)::int + "
-            "(put_observation_receipt_id is not null)::int) = 1",
+            "(source_operation_id is null and durable_intent_id is not null and put_attempt_id is not null "
+            "and verification_receipt_id is not null and ((put_operation_receipt_id is not null)::int + "
+            "(put_observation_receipt_id is not null)::int) = 1) or (source_operation_id is not null "
+            "and durable_intent_id is null and put_attempt_id is null and verification_receipt_id is null "
+            "and put_operation_receipt_id is null and put_observation_receipt_id is null)",
             name="write_receipt_shape",
         ),
         CheckConstraint(
@@ -1705,9 +1708,13 @@ class SubmissionBundleAdmission(Base):
         ),
     )
 
+    source_operation_id: Mapped[str | None] = mapped_column(
+        ForeignKey("submission_intake_operations.id", ondelete="RESTRICT", deferrable=True, initially="DEFERRED"),
+        unique=True,
+    )
     id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True)
-    durable_intent_id: Mapped[str] = mapped_column(
-        ForeignKey("submission_bundle_durable_intents.id", ondelete="RESTRICT"), nullable=False
+    durable_intent_id: Mapped[str | None] = mapped_column(
+        ForeignKey("submission_bundle_durable_intents.id", ondelete="RESTRICT"), nullable=True
     )
     pre_submit_evidence_set_id: Mapped[str | None] = mapped_column(
         ForeignKey("pre_submit_evidence_sets.id", ondelete="RESTRICT"), nullable=True, index=True
@@ -1715,8 +1722,8 @@ class SubmissionBundleAdmission(Base):
     selected_pre_submit_run_id: Mapped[str | None] = mapped_column(
         ForeignKey("selected_pre_submit_runs.id", ondelete="RESTRICT"), nullable=True, index=True
     )
-    put_attempt_id: Mapped[str] = mapped_column(
-        ForeignKey("artifact_put_attempts.id", ondelete="RESTRICT"), nullable=False
+    put_attempt_id: Mapped[str | None] = mapped_column(
+        ForeignKey("artifact_put_attempts.id", ondelete="RESTRICT"), nullable=True
     )
     artifact_content_id: Mapped[str] = mapped_column(
         ForeignKey("artifact_contents.id", ondelete="RESTRICT"), nullable=False, index=True
@@ -1724,8 +1731,8 @@ class SubmissionBundleAdmission(Base):
     verified_replica_id: Mapped[str] = mapped_column(
         ForeignKey("artifact_replicas.id", ondelete="RESTRICT"), nullable=False
     )
-    verification_receipt_id: Mapped[str] = mapped_column(
-        ForeignKey("artifact_verification_receipts.id", ondelete="RESTRICT"), nullable=False
+    verification_receipt_id: Mapped[str | None] = mapped_column(
+        ForeignKey("artifact_verification_receipts.id", ondelete="RESTRICT"), nullable=True
     )
     put_operation_receipt_id: Mapped[str | None] = mapped_column(
         ForeignKey("artifact_operation_receipts.id", ondelete="RESTRICT")
@@ -1837,6 +1844,10 @@ class ArtifactReplica(Base):
         ),
     )
 
+    source_operation_id: Mapped[str | None] = mapped_column(
+        ForeignKey("submission_intake_operations.id", ondelete="RESTRICT", deferrable=True, initially="DEFERRED"),
+        unique=True,
+    )
     id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True)
     content_id: Mapped[str] = mapped_column(
         ForeignKey("artifact_contents.id", ondelete="RESTRICT"), nullable=False, index=True
diff --git a/backend/app/modules/artifacts/submission_bindings.py b/backend/app/modules/artifacts/submission_bindings.py
index 580474b05..fd6facbc3 100644
--- a/backend/app/modules/artifacts/submission_bindings.py
+++ b/backend/app/modules/artifacts/submission_bindings.py
@@ -112,6 +112,13 @@ async def consume(
             raise SubmissionAdmissionConsumptionError(
                 "submission_bundle_admission_unavailable"
             )
+        if admission.source_operation_id != (
+            str(request.accepted_operation_id) if request.accepted_operation_id else None
+        ):
+            raise SubmissionAdmissionConsumptionError("submission_bundle_admission_unavailable")
+        if admission.source_operation_id is not None:
+            await self._session.execute(text("SELECT public.require_source_submission_admission(a) "
+                "FROM public.submission_bundle_admissions a WHERE id=:id"), {"id": admission.id})
         if admission.status == "stale":
             raise SubmissionAdmissionConsumptionError(
                 "submission_bundle_admission_stale"
@@ -314,17 +321,15 @@ def _task_lineage_matches(
             == (predecessor.version if predecessor is not None else None)
             and admission.checker_remediation_manifest_id
             == context.checker_remediation_manifest_id
-            and (predecessor is None or (
+            and (admission.source_operation_id is not None or predecessor is None or (
                 revision is not None and revision.disposition == "ready"
                 and revision.source_submission_id == predecessor.submission_id
                 and revision.source_routing_manifest_id == context.checker_remediation_manifest_id
             ))
-            and admission.revision_preparation_id == (
-                revision.preparation_id if revision is not None else None
-            )
-            and admission.revision_preparation_sha256 == (
-                revision.preparation_sha256 if revision is not None else None
-            )
+            and (admission.source_operation_id is not None or (
+                admission.revision_preparation_id == (revision.preparation_id if revision is not None else None)
+                and admission.revision_preparation_sha256 == (revision.preparation_sha256 if revision is not None else None)
+            ))
             and admission.guide_version == references.guide_version
             and admission.source_snapshot_id == str(references.source_snapshot_id)
             and admission.source_snapshot_sha256 == references.source_snapshot_hash
diff --git a/backend/app/modules/authorization/action_definitions.py b/backend/app/modules/authorization/action_definitions.py
index a83d11aa8..db53dcc9c 100644
--- a/backend/app/modules/authorization/action_definitions.py
+++ b/backend/app/modules/authorization/action_definitions.py
@@ -568,6 +568,11 @@
         PermissionId.SUBMISSION_CREATE,
         ActionOwner.XINT_002_05A,
     ),
+    _active(
+        ActionId.ARTIFACT_SUBMISSION_FINALIZE,
+        PermissionId.ARTIFACT_BINDING_CREATE,
+        ActionOwner.AUTH_ART_05,
+    ),
     _active(
         ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
         PermissionId.ARTIFACT_BINDING_CREATE,
diff --git a/backend/app/modules/authorization/catalogue.py b/backend/app/modules/authorization/catalogue.py
index 14804b7eb..43dbdaca7 100644
--- a/backend/app/modules/authorization/catalogue.py
+++ b/backend/app/modules/authorization/catalogue.py
@@ -272,6 +272,7 @@ class ActionId(StrEnum):
     ARTIFACT_TASK_IMPORT_SOURCE_READ = "artifact.task_import_source.read"
     ARTIFACT_GUIDE_SOURCE_READ = "artifact.guide_source.read"
     ARTIFACT_SUBMISSION_BUNDLE_PREPARE = "artifact.submission_bundle.prepare"
+    ARTIFACT_SUBMISSION_FINALIZE = "artifact.submission.finalize"
     ARTIFACT_SUBMISSION_BINDING_CREATE = "artifact.submission.binding.create"
     ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE = "artifact.checker_output.binding.create"
     ARTIFACT_VERIFICATION_EXECUTE = "artifact.verification.execute"
@@ -567,7 +568,7 @@ def _active(
 
 def _require_catalogue_counts() -> None:
     """Keep the closed action inventory and permission boundary exact."""
-    if len(PERMISSION_IDS) != 94 or len(ACTION_IDS) != 192:
+    if len(PERMISSION_IDS) != 94 or len(ACTION_IDS) != 193:
         raise RuntimeError("authorization catalogue count mismatch")
     if len(HISTORICAL_PERMISSION_IDS) != 49 or len(NEW_PERMISSION_IDS) != 45:
         raise RuntimeError("authorization permission boundary mismatch")
@@ -701,6 +702,7 @@ def _validate_action_definitions(definitions: tuple[ActionDefinition, ...]) -> N
         ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE,
         ActionId.SUBMISSION_CREATE,
         ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
+        ActionId.ARTIFACT_SUBMISSION_FINALIZE,
         ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE,
         ActionId.ARTIFACT_VERIFICATION_EXECUTE,
         ActionId.ARTIFACT_PENDING_WORK_SCAN,
@@ -814,6 +816,7 @@ def _index_actions(
     ServiceIdentity.ARTIFACT_BINDING: frozenset(
         {
             ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
+            ActionId.ARTIFACT_SUBMISSION_FINALIZE,
             ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE,
             ActionId.ARTIFACT_REVIEW_EVIDENCE_BINDING_CREATE,
         }
@@ -877,6 +880,7 @@ def _index_actions(
         (ServiceIdentity.ARTIFACT_PUT_RESOLVER, ActionId.ARTIFACT_PUT_ATTEMPT_RESOLVE),
         (ServiceIdentity.ARTIFACT_SCHEDULER, ActionId.ARTIFACT_PENDING_WORK_SCAN),
         (ServiceIdentity.ARTIFACT_BINDING, ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE),
+        (ServiceIdentity.ARTIFACT_BINDING, ActionId.ARTIFACT_SUBMISSION_FINALIZE),
         (ServiceIdentity.ARTIFACT_BINDING, ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE),
         (ServiceIdentity.ARTIFACT_BINDING, ActionId.ARTIFACT_REVIEW_EVIDENCE_BINDING_CREATE),
         (ServiceIdentity.ARTIFACT_GUIDE_READER, ActionId.ARTIFACT_GUIDE_SOURCE_READ),
@@ -943,6 +947,7 @@ def _index_actions(
     ActionId.ARTIFACT_PUT_ATTEMPT_RESOLVE,
     ActionId.ARTIFACT_PENDING_WORK_SCAN,
     ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
+    ActionId.ARTIFACT_SUBMISSION_FINALIZE,
     ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE,
     ActionId.ARTIFACT_GUIDE_SOURCE_READ,
     ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE,
@@ -1033,6 +1038,9 @@ def _index_actions(
         PermissionId.ARTIFACT_PENDING_WORK_SCAN,
         ActionOwner.AUTH_ART_02D_INTERNAL,
     ),
+    ActionId.ARTIFACT_SUBMISSION_FINALIZE: (
+        PermissionId.ARTIFACT_BINDING_CREATE, ActionOwner.AUTH_ART_05,
+    ),
     ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE: (
         PermissionId.ARTIFACT_BINDING_CREATE,
         ActionOwner.AUTH_ART_05,
diff --git a/backend/app/modules/authorization/domain/action_groups.py b/backend/app/modules/authorization/domain/action_groups.py
index 59ab73b26..d87b63a5b 100644
--- a/backend/app/modules/authorization/domain/action_groups.py
+++ b/backend/app/modules/authorization/domain/action_groups.py
@@ -8,6 +8,9 @@
     model_usage as checker_models,
     checker_outputs,
     checker_registry,
+    checker_retry,
+    post_submit_deliveries,
+    artifact_operator,
     contribution_policies,
 )
 from app.modules.authorization.domain.artifact_operator import ARTIFACT_OPERATOR_ACTIONS
@@ -70,8 +73,92 @@
 )
 
 
+ADMIN_ACTIONS = (
+    frozenset(
+        {
+            ActionId.REVIEW_LIFECYCLE_ACTIVATION_MANAGE,
+            ActionId.AUTHORIZATION_PERMISSION_CATALOGUE_READ,
+            ActionId.AUTHORIZATION_ADMIN_ROLE_DEFINITIONS_READ,
+            ActionId.ADMIN_ROLE_GRANT_LIST,
+            ActionId.ACTOR_ADMIN_ROLE_GRANT_HISTORY_READ,
+            ActionId.ADMIN_ROLE_GRANT_ISSUE,
+            ActionId.ADMIN_ROLE_GRANT_REVOKE,
+            ActionId.ADMIN_ROLE_GRANT_BOOTSTRAP,
+            ActionId.ACTOR_SERVICE_PROVISION,
+            ActionId.ACTOR_PROFILE_READ,
+            ActionId.ACTOR_IDENTITY_LINK_READ,
+            ActionId.ACTOR_PROFILE_SUSPEND,
+            ActionId.ACTOR_PROFILE_REACTIVATE,
+            ActionId.ACTOR_PROFILE_DEACTIVATE,
+            ActionId.ACTOR_IDENTITY_LINK_REVOKE,
+            ActionId.ACTOR_IDENTITY_LINK_REACTIVATE,
+            ActionId.PROJECT_ROLE_GRANT_ISSUE,
+            ActionId.PROJECT_ROLE_GRANT_REVOKE,
+            ActionId.PROJECT_CONTRIBUTOR_CANDIDATE_LIST,
+            ActionId.PROJECT_ROLE_GRANT_LIST,
+            ActionId.PROJECT_ROLE_GRANT_READ,
+            ActionId.PROJECT_SETUP_RUN_READ,
+            ActionId.PROJECT_GUIDE_SUFFICIENCY_REPORT_LIST,
+            ActionId.PROJECT_GUIDE_SUFFICIENCY_REPORT_READ,
+            ActionId.PROJECT_SUBMISSION_ARTIFACT_POLICY_LIST,
+            ActionId.PROJECT_SUBMISSION_ARTIFACT_POLICY_READ,
+            ActionId.PROJECT_EFFECTIVE_SUBMISSION_ARTIFACT_POLICY_READ,
+            ActionId.PROJECT_PRE_SUBMIT_CHECKER_POLICY_READ,
+            ActionId.PROJECT_ACTIVE_GUIDE_READ,
+        }
+    )
+    | adapter_bindings.ADAPTER_BINDING_READ_ACTIONS
+    | contribution_policies.CONTRIBUTION_POLICY_READ_ACTIONS
+    | checker_registry.CHECKER_REGISTRY_ACTIONS
+    | checker_models.MODEL_ADMIN_ACTIONS
+    | checker_retry.CHECKER_RETRY_ACTIONS
+    | post_submit_deliveries.POST_SUBMIT_DELIVERY_MUTATION_ACTIONS
+    | artifact_operator.ARTIFACT_OPERATOR_ACTIONS
+)
+SERIALIZED_ADMIN_READS = (
+    frozenset(
+        {
+            ActionId.ACTOR_PROFILE_READ,
+            ActionId.ACTOR_IDENTITY_LINK_READ,
+            ActionId.PROJECT_SETUP_RUN_READ,
+            ActionId.PROJECT_GUIDE_SUFFICIENCY_REPORT_LIST,
+            ActionId.PROJECT_GUIDE_SUFFICIENCY_REPORT_READ,
+            ActionId.PROJECT_SUBMISSION_ARTIFACT_POLICY_LIST,
+            ActionId.PROJECT_SUBMISSION_ARTIFACT_POLICY_READ,
+            ActionId.PROJECT_EFFECTIVE_SUBMISSION_ARTIFACT_POLICY_READ,
+            ActionId.PROJECT_PRE_SUBMIT_CHECKER_POLICY_READ,
+            ActionId.PROJECT_ACTIVE_GUIDE_READ,
+        }
+    )
+    | adapter_bindings.ADAPTER_BINDING_READ_ACTIONS
+    | contribution_policies.CONTRIBUTION_POLICY_READ_ACTIONS
+    | checker_registry.CHECKER_REGISTRY_READ_ACTIONS
+    | artifact_operator.ARTIFACT_OPERATOR_READ_ACTIONS
+)
+ADMIN_MUTATIONS = (
+    frozenset(
+        {
+            ActionId.REVIEW_LIFECYCLE_ACTIVATION_MANAGE,
+            ActionId.ADMIN_ROLE_GRANT_REVOKE,
+            ActionId.ACTOR_SERVICE_PROVISION,
+            ActionId.ACTOR_PROFILE_SUSPEND,
+            ActionId.ACTOR_PROFILE_REACTIVATE,
+            ActionId.ACTOR_PROFILE_DEACTIVATE,
+            ActionId.ACTOR_IDENTITY_LINK_REVOKE,
+            ActionId.ACTOR_IDENTITY_LINK_REACTIVATE,
+        }
+    )
+    | PROJECT_SCOPED_ADMIN_MUTATIONS
+    | checker_registry.CHECKER_REGISTRY_MUTATION_ACTIONS
+    | checker_models.MODEL_ADMIN_ACTIONS
+    | checker_retry.CHECKER_RETRY_ACTIONS
+    | post_submit_deliveries.POST_SUBMIT_DELIVERY_MUTATION_ACTIONS
+    | {ActionId.ARTIFACT_VERIFICATION_JOB_RETRY}
+)
+
 def supports_prepared_denial(action_id: ActionId, resource_context: object) -> bool:
     """Admit only the existing action/context pairs for prepare-time denial evidence."""
+    from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
     from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
     from app.modules.authorization.domain.task_authority import TASK_ACTIONS, TaskAuthorityResourceContext
     from app.modules.authorization.domain.project_create import ProjectCreateResourceContext
@@ -84,7 +171,8 @@ def supports_prepared_denial(action_id: ActionId, resource_context: object) -> b
         ProjectPolicyMutationPrepareDenialResourceContext, ProjectSubmissionArtifactPolicyMutationResourceContext,
     )
     return (
-        (action_id is ActionId.SUBMISSION_CREATE and type(resource_context) is IntakeAcceptanceResourceContext)
+        (action_id is ActionId.ARTIFACT_SUBMISSION_FINALIZE and type(resource_context) is SubmissionFinalizationResourceContext)
+        or (action_id is ActionId.SUBMISSION_CREATE and type(resource_context) is IntakeAcceptanceResourceContext)
         or (action_id is ActionId.SUBMISSION_INTAKE_RESERVE and type(resource_context) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext})
         or (
             action_id in checker_outputs.CHECKER_OUTPUT_ACTIONS
diff --git a/backend/app/modules/authorization/domain/audit.py b/backend/app/modules/authorization/domain/audit.py
index c19dfb762..cba98abea 100644
--- a/backend/app/modules/authorization/domain/audit.py
+++ b/backend/app/modules/authorization/domain/audit.py
@@ -22,6 +22,7 @@
     "task_post_submit_routing_manifest",
     "submission_intake_reservation",
     "submission_intake_acceptance",
+    "submission_finalization",
     "submission_intake_preflight",
     "submission_operation_read",
     "task_authority",
@@ -91,6 +92,7 @@
     "task_post_submit_routing_manifest",
     "submission_intake_reservation",
     "submission_intake_acceptance",
+    "submission_finalization",
     "submission_intake_preflight",
     "submission_operation_read",
     "task_authority",
diff --git a/backend/app/modules/authorization/domain/audit_targets.py b/backend/app/modules/authorization/domain/audit_targets.py
index 8e737cb43..8671d777d 100644
--- a/backend/app/modules/authorization/domain/audit_targets.py
+++ b/backend/app/modules/authorization/domain/audit_targets.py
@@ -1,6 +1,7 @@
 """Exact project resource audit selectors, without raw product facts."""
 
 from uuid import UUID
+from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
 from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
 from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext
 
@@ -80,8 +81,8 @@ def _model_administration_target(resource):
 
 
 def _submission_operation_target(resource):
-    if type(resource) is IntakeAcceptanceResourceContext:
-        project_id = str(resource.scope_project_id)
+    if type(resource) in {IntakeAcceptanceResourceContext, SubmissionFinalizationResourceContext}:
+        project_id = str(getattr(resource, "scope_project_id", None) or resource.project_id)
         return project_id, "submission_operation", str(resource.operation_id), "project", project_id
     if type(resource) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext} or (
         type(resource) is ContributorWorkReadResourceContext
diff --git a/backend/app/modules/authorization/domain/submission_finalization.py b/backend/app/modules/authorization/domain/submission_finalization.py
new file mode 100644
index 000000000..32afa3bba
--- /dev/null
+++ b/backend/app/modules/authorization/domain/submission_finalization.py
@@ -0,0 +1,38 @@
+"""Fixed-service continuation of immutable human submission acceptance."""
+from typing import Literal
+from uuid import UUID
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+
+class SubmissionFinalizationResourceContext(BaseModel):
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True, revalidate_instances="always")
+    resource_type: Literal["submission_finalization"] = "submission_finalization"
+    resource_id: UUID
+    operation_id: UUID
+    project_id: UUID
+    task_id: UUID
+    assignment_id: UUID
+    contributor_id: UUID
+    acceptance_decision_id: UUID
+    accepted_context_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    acceptance_receipt_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    source_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    continuation_lease_id: UUID
+    continuation_generation: int = Field(gt=0)
+    phase: Literal["claim", "commit"]
+    submission_id: UUID | None
+    submission_version: int | None = Field(ge=1)
+
+    @model_validator(mode="after")
+    def exact_continuation(self):
+        if self.resource_id != self.operation_id or self.operation_id.version != 7:
+            raise ValueError("finalization requires its exact operation")
+        if self.continuation_lease_id.version != 7:
+            raise ValueError("finalization requires a generated lease identity")
+        if self.phase == "claim":
+            if self.submission_id is not None or self.submission_version is not None:
+                raise ValueError("claim cannot authorize a Submission")
+        elif (self.submission_id is None or self.submission_id.version != 7
+              or self.submission_version is None):
+            raise ValueError("commit requires the exact Submission identity")
+        return self
diff --git a/backend/app/modules/authorization/kernel.py b/backend/app/modules/authorization/kernel.py
index 98edb7adc..4c60356c8 100644
--- a/backend/app/modules/authorization/kernel.py
+++ b/backend/app/modules/authorization/kernel.py
@@ -1,5 +1,6 @@
 """Deny-by-default request-scoped authorization kernel."""
 from __future__ import annotations
+from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
 from app.modules.authorization.domain.guide_proposals import GUIDE_PROPOSAL_RESOURCE_BY_ACTION
 from app.modules.authorization.catalogue import POST_POLICY_ACTION_IDS
 from app.modules.authorization.domain.post_policy import PostPolicyResourceContext
@@ -37,8 +38,10 @@
 from app.modules.authorization.domain.action_groups import (
     GUIDE_BOUND_PROJECT_MANAGER_ACTIONS as _GUIDE_BOUND_PROJECT_MANAGER_ACTIONS,
     CONTEXT_DIGEST_ACTIONS,
-    PROJECT_SCOPED_ADMIN_MUTATIONS,
     supports_prepared_denial,
+    ADMIN_ACTIONS as _ADMIN_ACTIONS,
+    SERIALIZED_ADMIN_READS as _SERIALIZED_ADMIN_READS,
+    ADMIN_MUTATIONS as _ADMIN_MUTATIONS,
 )
 from app.modules.authorization.domain.audit import CONTEXT_DIGEST_RESOURCE_TYPES
 from app.modules.authorization.domain.audit_targets import project_authority_audit_target
@@ -125,88 +128,6 @@
     [ServiceAuthorizationContext, ActionId],
     Awaitable[ServiceAuthorizationContext | None],
 ]
-_ADMIN_ACTIONS = (
-    frozenset(
-        {
-            ActionId.REVIEW_LIFECYCLE_ACTIVATION_MANAGE,
-            ActionId.AUTHORIZATION_PERMISSION_CATALOGUE_READ,
-            ActionId.AUTHORIZATION_ADMIN_ROLE_DEFINITIONS_READ,
-            ActionId.ADMIN_ROLE_GRANT_LIST,
-            ActionId.ACTOR_ADMIN_ROLE_GRANT_HISTORY_READ,
-            ActionId.ADMIN_ROLE_GRANT_ISSUE,
-            ActionId.ADMIN_ROLE_GRANT_REVOKE,
-            ActionId.ADMIN_ROLE_GRANT_BOOTSTRAP,
-            ActionId.ACTOR_SERVICE_PROVISION,
-            ActionId.ACTOR_PROFILE_READ,
-            ActionId.ACTOR_IDENTITY_LINK_READ,
-            ActionId.ACTOR_PROFILE_SUSPEND,
-            ActionId.ACTOR_PROFILE_REACTIVATE,
-            ActionId.ACTOR_PROFILE_DEACTIVATE,
-            ActionId.ACTOR_IDENTITY_LINK_REVOKE,
-            ActionId.ACTOR_IDENTITY_LINK_REACTIVATE,
-            ActionId.PROJECT_ROLE_GRANT_ISSUE,
-            ActionId.PROJECT_ROLE_GRANT_REVOKE,
-            ActionId.PROJECT_CONTRIBUTOR_CANDIDATE_LIST,
-            ActionId.PROJECT_ROLE_GRANT_LIST,
-            ActionId.PROJECT_ROLE_GRANT_READ,
-            ActionId.PROJECT_SETUP_RUN_READ,
-            ActionId.PROJECT_GUIDE_SUFFICIENCY_REPORT_LIST,
-            ActionId.PROJECT_GUIDE_SUFFICIENCY_REPORT_READ,
-            ActionId.PROJECT_SUBMISSION_ARTIFACT_POLICY_LIST,
-            ActionId.PROJECT_SUBMISSION_ARTIFACT_POLICY_READ,
-            ActionId.PROJECT_EFFECTIVE_SUBMISSION_ARTIFACT_POLICY_READ,
-            ActionId.PROJECT_PRE_SUBMIT_CHECKER_POLICY_READ,
-            ActionId.PROJECT_ACTIVE_GUIDE_READ,
-        }
-    )
-    | adapter_bindings.ADAPTER_BINDING_READ_ACTIONS
-    | contribution_policies.CONTRIBUTION_POLICY_READ_ACTIONS
-    | checker_registry.CHECKER_REGISTRY_ACTIONS
-    | checker_models.MODEL_ADMIN_ACTIONS
-    | checker_retry.CHECKER_RETRY_ACTIONS
-    | post_submit_deliveries.POST_SUBMIT_DELIVERY_MUTATION_ACTIONS
-    | artifact_operator.ARTIFACT_OPERATOR_ACTIONS
-)
-_SERIALIZED_ADMIN_READS = (
-    frozenset(
-        {
-            ActionId.ACTOR_PROFILE_READ,
-            ActionId.ACTOR_IDENTITY_LINK_READ,
-            ActionId.PROJECT_SETUP_RUN_READ,
-            ActionId.PROJECT_GUIDE_SUFFICIENCY_REPORT_LIST,
-            ActionId.PROJECT_GUIDE_SUFFICIENCY_REPORT_READ,
-            ActionId.PROJECT_SUBMISSION_ARTIFACT_POLICY_LIST,
-            ActionId.PROJECT_SUBMISSION_ARTIFACT_POLICY_READ,
-            ActionId.PROJECT_EFFECTIVE_SUBMISSION_ARTIFACT_POLICY_READ,
-            ActionId.PROJECT_PRE_SUBMIT_CHECKER_POLICY_READ,
-            ActionId.PROJECT_ACTIVE_GUIDE_READ,
-        }
-    )
-    | adapter_bindings.ADAPTER_BINDING_READ_ACTIONS
-    | contribution_policies.CONTRIBUTION_POLICY_READ_ACTIONS
-    | checker_registry.CHECKER_REGISTRY_READ_ACTIONS
-    | artifact_operator.ARTIFACT_OPERATOR_READ_ACTIONS
-)
-_ADMIN_MUTATIONS = (
-    frozenset(
-        {
-            ActionId.REVIEW_LIFECYCLE_ACTIVATION_MANAGE,
-            ActionId.ADMIN_ROLE_GRANT_REVOKE,
-            ActionId.ACTOR_SERVICE_PROVISION,
-            ActionId.ACTOR_PROFILE_SUSPEND,
-            ActionId.ACTOR_PROFILE_REACTIVATE,
-            ActionId.ACTOR_PROFILE_DEACTIVATE,
-            ActionId.ACTOR_IDENTITY_LINK_REVOKE,
-            ActionId.ACTOR_IDENTITY_LINK_REACTIVATE,
-        }
-    )
-    | PROJECT_SCOPED_ADMIN_MUTATIONS
-    | checker_registry.CHECKER_REGISTRY_MUTATION_ACTIONS
-    | checker_models.MODEL_ADMIN_ACTIONS
-    | checker_retry.CHECKER_RETRY_ACTIONS
-    | post_submit_deliveries.POST_SUBMIT_DELIVERY_MUTATION_ACTIONS
-    | {ActionId.ARTIFACT_VERIFICATION_JOB_RETRY}
-)
 def _prepared_admin_role_locker(action_id):
     """Select the only supported prepared admin-role authority locker."""
     if action_id in _ADMIN_MUTATIONS:
@@ -231,6 +152,9 @@ async def prelock_serialized_admin_read_actor(authorization: AuthorizationServic
         "pre_submit_checker_input",
         PreSubmitCheckerInputResourceContext,
     ),
+    ActionId.ARTIFACT_SUBMISSION_FINALIZE: (
+        "submission_finalization", SubmissionFinalizationResourceContext,
+    ),
     ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE: (
         "submission_binding",
         SubmissionBindingResourceContext,
diff --git a/backend/app/modules/authorization/prepared.py b/backend/app/modules/authorization/prepared.py
index 378176d00..3cf0ff18a 100644
--- a/backend/app/modules/authorization/prepared.py
+++ b/backend/app/modules/authorization/prepared.py
@@ -1,6 +1,7 @@
 """Transaction-bound, single-use authorization for sensitive mutations."""
 
 from __future__ import annotations
+from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
 from app.modules.authorization.prepared_preflight import preflight_authority
 from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, intake_preflight_matches, parse_intake_binding
 from app.modules.authorization.catalogue import GUIDE_PROPOSAL_ACTION_IDS, POST_POLICY_ACTION_IDS
@@ -196,6 +197,9 @@ def __reduce__(self) -> NoReturn:
         "pre_submit_checker_input",
         PreSubmitCheckerInputResourceContext,
     ),
+    ActionId.ARTIFACT_SUBMISSION_FINALIZE: (
+        "submission_finalization", SubmissionFinalizationResourceContext,
+    ),
     ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE: (
         "submission_binding",
         SubmissionBindingResourceContext,
@@ -642,6 +646,21 @@ def _validate_consumption(
         if checker_runtime_matches is False:
             raise PreparedAuthorizationHandleInvalid("invalid prepared checker runtime authority")
 
+    def _validate_artifact_consumption(self, issuance, final_resource_context):
+        """Require the exact artifact custody facts sealed at preparation."""
+        if isinstance(
+            final_resource_context,
+            (
+                PreSubmitCheckerInputResourceContext, SubmissionBindingResourceContext,
+                SubmissionCreationResourceContext, IntakeAcceptanceResourceContext,
+                SubmissionFinalizationResourceContext, TaskImportSourceResourceContext,
+            ),
+        ) and not exact_artifact_binding_matches(
+            issuance.binding.exact_artifact_context,
+            issuance.binding.exact_artifact_resource_digest, final_resource_context,
+        ):
+            raise PreparedAuthorizationHandleInvalid("invalid prepared authorization handle")
+
     async def consume(
         self,
         handle: PreparedAuthorizationHandle,
@@ -703,20 +722,7 @@ async def consume(
             final_resource_context, ProjectSubmissionArtifactPolicyMutationResourceContext
         ) and not _submission_policy_binding_matches(issuance.binding, final_resource_context):
             raise PreparedAuthorizationHandleInvalid("invalid prepared authorization handle")
-        if isinstance(
-            final_resource_context,
-            (
-                PreSubmitCheckerInputResourceContext,
-                SubmissionBindingResourceContext,
-                SubmissionCreationResourceContext,
-                IntakeAcceptanceResourceContext,
-                TaskImportSourceResourceContext,
-            ),
-        ) and not exact_artifact_binding_matches(
-            issuance.binding.exact_artifact_context,
-            issuance.binding.exact_artifact_resource_digest, final_resource_context,
-        ):
-            raise PreparedAuthorizationHandleInvalid("invalid prepared authorization handle")
+        self._validate_artifact_consumption(issuance, final_resource_context)
         if isinstance(
             final_resource_context, SubmissionBundlePreparationResourceContext
         ) and not _submission_preparation_binding_matches(issuance.binding, final_resource_context):
diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py
index e4a1587fd..7a3354959 100644
--- a/backend/app/modules/authorization/runtime.py
+++ b/backend/app/modules/authorization/runtime.py
@@ -8,6 +8,7 @@
 from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator
 
 from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts
+from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
 from app.modules.authorization.domain.guide_compilation import ProjectGuideCompilationExecuteResourceContext, ProjectGuideCompilationRequestResourceContext
 from app.modules.authorization.domain.resource_digest import authorization_resource_digest as authorization_resource_digest
 from app.modules.authorization.domain.guide_proposals import GuideProposalResourceContext
@@ -158,6 +159,7 @@ class PreparedAuthorityScope(BaseModel):
             "guide_source_read",
             "pre_submit_checker_input",
             "submission_binding",
+            "submission_finalization",
         ] | None = None
     artifact_resource_id: UUID | Literal["workstream:artifact_pending_work"] | None = None
 
@@ -213,7 +215,7 @@ def validate_selector(self):
                             "guide_source_binding",
                             "guide_source_read",
                             "pre_submit_checker_input",
-                            "submission_binding"}
+                            "submission_binding", "submission_finalization"}
                         and isinstance(self.artifact_resource_id, UUID)
                     )
                 )
@@ -1111,6 +1113,7 @@ def bind_source_operation(self):
     | ArtifactOperatorReadResourceContext
     | ArtifactOperatorRetryResourceContext
     | GuideSourceReadResourceContext
+    | SubmissionFinalizationResourceContext
     | SubmissionCreationResourceContext | SubmissionBindingResourceContext | IntakeAcceptanceResourceContext
     | PreSubmitCheckerInputResourceContext
     | SubmissionBundlePreparationPreflightResourceContext
diff --git a/backend/app/modules/authorization/submission_consumption.py b/backend/app/modules/authorization/submission_consumption.py
index 2362d4a4f..590430c71 100644
--- a/backend/app/modules/authorization/submission_consumption.py
+++ b/backend/app/modules/authorization/submission_consumption.py
@@ -7,6 +7,7 @@
 from pydantic import BaseModel, ConfigDict, Field, model_validator
 
 from app.modules.authorization.catalogue import ActionId
+from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
 from app.modules.authorization.domain.submission_intake import IntakeAcceptanceResourceContext
 
 _STRICT_FROZEN = ConfigDict(extra="forbid", frozen=True, strict=True)
@@ -126,6 +127,7 @@ def bind_admission(self):
 
 
 RESOURCE_BY_ACTION = {
+    ActionId.ARTIFACT_SUBMISSION_FINALIZE: SubmissionFinalizationResourceContext,
     ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE: SubmissionBindingResourceContext,
     ActionId.SUBMISSION_CREATE: SubmissionCreationResourceContext,
 }
diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py
index a63a7cde5..1b7f72702 100644
--- a/backend/app/modules/checkers/api/selected_pre_submit.py
+++ b/backend/app/modules/checkers/api/selected_pre_submit.py
@@ -1063,6 +1063,10 @@ async def read_current(
     ) -> SelectedPreSubmitCurrentFacts | None:
         """Read one exact actor/key result after TASK custody is locked."""
 
+    async def read_accepted_terminal(self, *, run_id: UUID, source_operation_id: UUID,
+                                     terminal_digest: str) -> SelectedPreSubmitTerminalFacts:
+        """Read retained source evidence without new PRE or current foreground eligibility."""
+
     async def lock_acceptance(
         self, *, run_id: UUID, facts: SelectedPreSubmitReservationFacts, terminal_digest: str,
     ) -> SelectedPreSubmitTerminalFacts:
diff --git a/backend/app/modules/checkers/selected_pre_submit_coordination.py b/backend/app/modules/checkers/selected_pre_submit_coordination.py
index 0b54fc73e..616bbbdeb 100644
--- a/backend/app/modules/checkers/selected_pre_submit_coordination.py
+++ b/backend/app/modules/checkers/selected_pre_submit_coordination.py
@@ -262,6 +262,29 @@ async def read_current(
             terminal=terminal,
         )
 
+    async def read_accepted_terminal(self, *, run_id: UUID, source_operation_id: UUID,
+                                     terminal_digest: str) -> SelectedPreSubmitTerminalFacts:
+        """Read exact retained v3 evidence; ART independently owns accepted custody."""
+        _require_root(self._session)
+        row = await self._session.get(SelectedPreSubmitRun, str(run_id))
+        if (row is None or row.source_operation_id != str(source_operation_id)
+                or row.status != "completed" or row.eligible is not True
+                or row.terminal_digest != terminal_digest or row.execute_evidence_id is None
+                or row.finalize_evidence_id is None
+                or row.request_json.get("schema_version") != "workstream.selected_pre_submit_reservation.v2"
+                or row.terminal_json.get("schema_version") != "workstream.selected_pre_submit_terminal.v3"):
+            raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid")
+        try:
+            request = SelectedPreSubmitReservationFacts.from_canonical_body(row.request_json)
+            terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json)
+            if not matches_source_request(row, request) or not matches_terminal(row, request, terminal):
+                raise ValueError("retained PRE differs")
+        except (TypeError, ValueError):
+            raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid") from None
+        await self._session.execute(text("SELECT public.require_selected_pre_invocation(r) "
+            "FROM public.selected_pre_submit_runs r WHERE id=:id"), {"id": row.id})
+        return terminal
+
     async def lock_acceptance(
         self, *, run_id: UUID, facts: SelectedPreSubmitReservationFacts, terminal_digest: str,
     ) -> SelectedPreSubmitTerminalFacts:
diff --git a/backend/app/modules/tasks/accepted_submission.py b/backend/app/modules/tasks/accepted_submission.py
new file mode 100644
index 000000000..0e9b2c330
--- /dev/null
+++ b/backend/app/modules/tasks/accepted_submission.py
@@ -0,0 +1,56 @@
+"""Recover historical acceptance context without renewing contributor eligibility."""
+import json
+from uuid import UUID
+from sqlalchemy import func, select, text
+
+from app.core.hashing import canonical_json_hash
+from app.modules.tasks.api import (
+    SubmissionCreationUnavailable, SubmissionPredecessorFacts,
+    TaskLockedProjectContextReferences, TaskPolicyLineage, TaskSubmissionContextFacts,
+)
+from app.modules.tasks.models import Submission, TaskAssignment
+from app.modules.tasks.submission_attempts import COVERAGE_RETURN_REASON
+
+
+async def accepted_submission_context(session, task, request, *, operation_id,
+                                      snapshot_sha256, eligible_status, remediation_id):
+    """Read immutable accepted lineage under TASK custody; deadlines were decided at T4."""
+    invalid = SubmissionCreationUnavailable("accepted submission custody differs")
+    snapshot = await session.scalar(text("SELECT public.submission_intake_task_snapshot(t) "
+        "FROM public.workstream_tasks t WHERE id=:id"), {"id": task.id})
+    assignment = await session.get(TaskAssignment, str(request.assignment_id))
+    if (task.status != "evaluation_pending" or task.active_submission_operation_id != str(operation_id)
+            or canonical_json_hash(snapshot) != snapshot_sha256 or assignment is None
+            or assignment.task_id != task.id or assignment.contributor_id != str(request.contributor_id)
+            or task.assigned_to != str(request.contributor_id)):
+        raise invalid
+    predecessor = None
+    if request.predecessor_submission_id:
+        previous = await session.get(Submission, str(request.predecessor_submission_id))
+        if (previous is None or previous.task_id != task.id
+                or previous.task_assignment_id != assignment.id or previous.contributor_id != assignment.contributor_id):
+            raise invalid
+        count = await session.scalar(select(func.count(Submission.id)).where(
+            Submission.task_assignment_id == assignment.id, Submission.version <= previous.version,
+            Submission.status_reason.is_distinct_from(COVERAGE_RETURN_REASON)))
+        predecessor = SubmissionPredecessorFacts(UUID(previous.id), previous.version, count)
+    policy = TaskPolicyLineage.model_validate_json(json.dumps({
+        name: str(value) if isinstance(value, UUID) else value
+        for name in TaskPolicyLineage.model_fields for value in (getattr(task, name),)
+    }))
+    refs = TaskLockedProjectContextReferences(
+        project_id=UUID(task.project_id), locked_contribution_policy_version_id=policy.locked_contribution_policy_version_id,
+        guide_version=policy.locked_guide_version, source_snapshot_id=policy.locked_guide_source_snapshot_id,
+        source_snapshot_hash=policy.locked_guide_source_snapshot_hash,
+        effective_policy_id=policy.locked_effective_project_submission_artifact_policy_id,
+        effective_policy_hash=policy.locked_effective_project_submission_artifact_policy_hash,
+        pre_submit_policy_id=policy.locked_pre_submit_checker_policy_id,
+        pre_submit_policy_bundle_hash=policy.locked_pre_submit_checker_bundle_hash,
+    )
+    return TaskSubmissionContextFacts(
+        task_id=request.task_id, assignment_id=request.assignment_id, contributor_id=request.contributor_id,
+        status=eligible_status, kind="checker_remediation" if predecessor else "initial", predecessor=predecessor,
+        submitter_contribution_policy_version_id=assignment.submitter_contribution_policy_version_id,
+        locked_project_context=refs, locked_policy=policy, acceptance_criteria=task.acceptance_criteria,
+        checker_remediation_manifest_id=remediation_id,
+    )
diff --git a/backend/app/modules/tasks/submission_composition.py b/backend/app/modules/tasks/submission_composition.py
index 9283a4891..113277edf 100644
--- a/backend/app/modules/tasks/submission_composition.py
+++ b/backend/app/modules/tasks/submission_composition.py
@@ -106,7 +106,7 @@ def __init__(
         self,
         session: AsyncSession,
         *,
-        authorization: SubmissionCreationAuthorizationPort,
+        authorization: SubmissionCreationAuthorizationPort | None,
         admissions: SubmissionArtifactAdmissionPort,
         contexts: TaskService,
         submission_contexts: TaskSubmissionContextPort,
@@ -124,6 +124,8 @@ def __init__(
 
     async def create(self, request: SubmissionCreationRequest) -> SubmissionCreationResult:
         """Create one Submission without opening or committing a transaction."""
+        if self._authorization is None:
+            raise SubmissionCreationUnavailable("submission creation authority is unavailable")
         if not self._session.in_transaction() or self._session.in_nested_transaction():
             raise RuntimeError("submission creation requires one root transaction")
         preliminary = SubmissionCreationPreparationFacts(
@@ -188,98 +190,170 @@ async def create(self, request: SubmissionCreationRequest) -> SubmissionCreation
                         project.facts.revision_policy.value,
                     ).max_revision_rounds,
                 )
-            submission = build_submission(
-                submission_id=str(submission_id), task=task,
-                contribution_policy_version_id=context.submitter_contribution_policy_version_id,
-                task_assignment_id=str(context.assignment_id),
-                contributor_id=str(request.contributor_id), version=version,
-                summary=request.summary, worker_attestation=request.contributor_attestation,
-                supersedes_submission_id=(str(context.predecessor.submission_id)
-                                          if context.predecessor else None),
+            async def authorize_creation():
+                return await self._authorization.consume(prepared_authorization, final)
+            receipt = await self._create_bound_submission(
+                request, task, context, project, submission_id, version, authorize_creation,
+                accepted_operation_id=None,
             )
-            submission.locked_at = await self._session.scalar(select(func.now()))
-            await self._repository.add_submission(submission)
-            consumed = await self._admissions.consume(
-                SubmissionArtifactAdmissionRequest(
-                    admission_id=request.admission_id,
-                    submission_id=submission_id,
-                    submission_version=version,
-                    task_context=context,
-                    project_context=project.facts,
-                    packet=SubmissionPacketView(
-                        request.summary, request.contributor_attestation,
-                    ),
-                )
-            )
-            if (
-                type(consumed) is not SubmissionArtifactAdmissionResult
-                or not isinstance(consumed.binding_id, UUID)
-                or not isinstance(consumed.content_id, UUID)
-                or consumed.selected_evaluation_content is None
-            ):
-                raise SubmissionCreationUnavailable("submission creation is unavailable")
-            submission.submission_bundle_admission_id = str(request.admission_id)
-            submission.artifact_binding_id = str(consumed.binding_id)
-            submission.artifact_content_id = str(consumed.content_id)
-            submission.selected_post_submit_policy_sha256 = (
-                consumed.selected_evaluation_content.policy.policy_sha256
-            )
-            submission.selected_post_submit_policy_body = (
-                consumed.selected_evaluation_content.policy.model_dump(mode="json")
+        finally:
+            self._authorization.close(prepared_authorization)
+        return receipt.result()
+
+    async def create_accepted(
+        self, request: SubmissionCreationRequest, *, authority_facts, finalization_authority,
+        snapshot_sha256: str, eligible_status: str, remediation_id: UUID | None,
+    ):
+        """Continue accepted service custody through the same Submission writer."""
+        from dataclasses import replace
+        from app.modules.tasks.accepted_submission import accepted_submission_context
+        if not self._session.in_transaction() or self._session.in_nested_transaction():
+            raise RuntimeError("accepted creation requires a root transaction")
+        task = await self._repository.get_task(str(request.task_id), for_update=True)
+        if task is None or (request.task_id, request.assignment_id, request.contributor_id) != (
+            authority_facts.task_id, authority_facts.assignment_id, authority_facts.contributor_id,
+        ):
+            raise SubmissionCreationUnavailable("accepted submission custody differs")
+        context = await accepted_submission_context(
+            self._session, task, request, operation_id=authority_facts.operation_id,
+            snapshot_sha256=snapshot_sha256, eligible_status=eligible_status, remediation_id=remediation_id,
+        )
+        latest = await self._repository.get_latest_submission_for_task(task.id)
+        version = latest.version + 1 if latest else 1
+        if context.predecessor is not None and context.predecessor.version + 1 != version:
+            raise SubmissionCreationUnavailable("accepted predecessor differs")
+        submission_id = new_record_id()
+        facts = replace(authority_facts, phase="commit", submission_id=submission_id, submission_version=version)
+        handle = await finalization_authority.prepare(facts=facts, idempotency_key=facts.continuation_lease_id)
+        decision_id = None
+        async def authorize_creation():
+            nonlocal decision_id
+            decision_id = await finalization_authority.consume(prepared_authorization=handle, facts=facts)
+            if not isinstance(decision_id, UUID):
+                raise SubmissionCreationUnavailable("finalization authority is unavailable")
+            return facts.acceptance_decision_id
+        try:
+            project = await self._contexts._load_locked_task_context(task)
+            receipt = await self._create_bound_submission(
+                request, task, context, project, submission_id, version, authorize_creation,
+                accepted_operation_id=facts.operation_id,
             )
-            await self._session.flush()
-            creation_decision_id = await self._authorization.consume(prepared_authorization, final)
-            if not isinstance(creation_decision_id, UUID):
-                raise SubmissionCreationUnavailable("submission creation is unavailable")
-            request_fields = dict(
-                evaluation_request_id=new_record_id(),
-                evaluation_generation=1,
-                task_id=request.task_id,
-                assignment_id=request.assignment_id,
+            return receipt.result(), decision_id
+        finally:
+            finalization_authority.close()
+
+    async def _create_bound_submission(
+        self, request, task, context, project, submission_id, version, authorize_creation,
+        *, accepted_operation_id,
+    ):
+        """The sole Submission/binding/POST writer for either authorized entry."""
+        submission = build_submission(
+            submission_id=str(submission_id), task=task,
+            contribution_policy_version_id=context.submitter_contribution_policy_version_id,
+            task_assignment_id=str(context.assignment_id),
+            contributor_id=str(request.contributor_id), version=version,
+            summary=request.summary, worker_attestation=request.contributor_attestation,
+            supersedes_submission_id=(str(context.predecessor.submission_id)
+                                      if context.predecessor else None),
+        )
+        submission.locked_at = await self._session.scalar(select(func.now()))
+        await self._repository.add_submission(submission)
+        consumed = await self._admissions.consume(
+            SubmissionArtifactAdmissionRequest(
+                admission_id=request.admission_id,
                 submission_id=submission_id,
                 submission_version=version,
-                content_id=consumed.content_id,
-                binding_id=consumed.binding_id,
-                content_sha256=consumed.archive_sha256,
-                byte_count=consumed.byte_count,
-            )
-            selected = consumed.selected_evaluation_content
-            evaluation = make_selected_post_submit_request(
-                project_id=selected.project_id,
-                expected_context=selected.expected_context,
-                policy=selected.policy,
-                **request_fields,
+                task_context=context,
+                project_context=project.facts,
+                accepted_operation_id=accepted_operation_id,
+                packet=SubmissionPacketView(
+                    request.summary, request.contributor_attestation,
+                ),
             )
+        )
+        if (
+            type(consumed) is not SubmissionArtifactAdmissionResult
+            or not isinstance(consumed.binding_id, UUID)
+            or not isinstance(consumed.content_id, UUID)
+            or consumed.selected_evaluation_content is None
+        ):
+            raise SubmissionCreationUnavailable("submission creation is unavailable")
+        submission.submission_bundle_admission_id = str(request.admission_id)
+        submission.artifact_binding_id = str(consumed.binding_id)
+        submission.artifact_content_id = str(consumed.content_id)
+        submission.selected_post_submit_policy_sha256 = (
+            consumed.selected_evaluation_content.policy.policy_sha256
+        )
+        submission.selected_post_submit_policy_body = (
+            consumed.selected_evaluation_content.policy.model_dump(mode="json")
+        )
+        await self._session.flush()
+        creation_decision_id = await authorize_creation()
+        if not isinstance(creation_decision_id, UUID):
+            raise SubmissionCreationUnavailable("submission creation is unavailable")
+        request_fields = dict(
+            evaluation_request_id=new_record_id(),
+            evaluation_generation=1,
+            task_id=request.task_id,
+            assignment_id=request.assignment_id,
+            submission_id=submission_id,
+            submission_version=version,
+            content_id=consumed.content_id,
+            binding_id=consumed.binding_id,
+            content_sha256=consumed.archive_sha256,
+            byte_count=consumed.byte_count,
+        )
+        selected = consumed.selected_evaluation_content
+        evaluation = make_selected_post_submit_request(
+            project_id=selected.project_id,
+            expected_context=selected.expected_context,
+            policy=selected.policy,
+            **request_fields,
+        )
+        if accepted_operation_id is None:
             ensure_allowed_transition(task.status, "submitted")
             task.status = "submitted"
             await self._session.flush()
-            reservation = await self._evaluations.reserve_current_evaluation(evaluation)
-            if (reservation.request_id != evaluation.evaluation_request_id
-                    or reservation.request_digest != evaluation.request_sha256
-                    or reservation.evaluation_generation != 1):
-                raise SubmissionCreationUnavailable("submission creation is unavailable")
-            receipt = SubmissionDispatch(
-                submission_id=str(submission_id), submission_version=version,
-                project_id=str(context.locked_project_context.project_id),
-                task_id=str(request.task_id), assignment_id=str(request.assignment_id),
-                contributor_id=str(request.contributor_id), admission_id=str(request.admission_id),
-                artifact_binding_id=str(consumed.binding_id), artifact_content_id=str(consumed.content_id),
-                creation_decision_id=str(creation_decision_id), binding_decision_id=str(consumed.binding_decision_id),
-                request_digest=creation_request_digest(request),
-                creation_kind=context.kind, creation_status=context.status,
-                checker_remediation_manifest_id=context.checker_remediation_manifest_id,
-                evaluation_request_id=str(reservation.request_id),
-                evaluation_request_digest=reservation.request_digest,
-                evaluation_attempt_id=str(reservation.attempt_id), evaluation_result_id=str(reservation.result_id),
-            )
-            event = await self._events.append(evaluation_request_event(receipt))
-            receipt.evaluation_event_id = event.event_id
-            self._session.add(receipt)
+        elif task.status != "evaluation_pending" or task.active_submission_operation_id != str(accepted_operation_id):
+            raise SubmissionCreationUnavailable("accepted task custody differs")
+        reservation = await self._evaluations.reserve_current_evaluation(evaluation)
+        if (reservation.request_id != evaluation.evaluation_request_id
+                or reservation.request_digest != evaluation.request_sha256
+                or reservation.evaluation_generation != 1):
+            raise SubmissionCreationUnavailable("submission creation is unavailable")
+        receipt = SubmissionDispatch(
+            submission_id=str(submission_id), submission_version=version,
+            project_id=str(context.locked_project_context.project_id),
+            task_id=str(request.task_id), assignment_id=str(request.assignment_id),
+            contributor_id=str(request.contributor_id), admission_id=str(request.admission_id),
+            artifact_binding_id=str(consumed.binding_id), artifact_content_id=str(consumed.content_id),
+            creation_decision_id=str(creation_decision_id), binding_decision_id=str(consumed.binding_decision_id),
+            request_digest=creation_request_digest(request),
+            creation_kind=context.kind, creation_status=context.status,
+            checker_remediation_manifest_id=context.checker_remediation_manifest_id,
+            evaluation_request_id=str(reservation.request_id),
+            evaluation_request_digest=reservation.request_digest,
+            evaluation_attempt_id=str(reservation.attempt_id), evaluation_result_id=str(reservation.result_id),
+        )
+        event = await self._events.append(evaluation_request_event(receipt))
+        receipt.evaluation_event_id = event.event_id
+        self._session.add(receipt)
+        if accepted_operation_id is None:
             ensure_allowed_transition(task.status, "evaluation_pending")
-            task.status = "evaluation_pending"
-            await self._session.flush()
-        finally:
-            self._authorization.close(prepared_authorization)
+        task.status = "evaluation_pending"
+        await self._session.flush()
+        return receipt
+
+    async def read_finalized(self, submission_id: UUID, admission_id: UUID, creation_decision_id: UUID):
+        """Read the exact retained dispatch without requiring today's TASK status."""
+        receipt = await self._session.get(SubmissionDispatch, str(submission_id))
+        if (receipt is None or receipt.admission_id != str(admission_id)
+                or receipt.creation_decision_id != str(creation_decision_id)):
+            raise SubmissionCreationUnavailable("finalized dispatch differs")
+        valid = await self._session.scalar(text("SELECT public.submission_dispatch_valid(d) "
+            "FROM public.submission_dispatches d WHERE submission_id=:id"), {"id": str(submission_id)})
+        if valid is not True:
+            raise SubmissionCreationUnavailable("finalized dispatch differs")
         return receipt.result()
 
     async def _replay(self, request, receipt, context) -> SubmissionCreationResult:
diff --git a/backend/app/modules/tasks/submission_participants.py b/backend/app/modules/tasks/submission_participants.py
index 9909faab9..22a494cc7 100644
--- a/backend/app/modules/tasks/submission_participants.py
+++ b/backend/app/modules/tasks/submission_participants.py
@@ -19,6 +19,7 @@ class SubmissionArtifactAdmissionRequest:
     task_context: TaskSubmissionContextFacts
     project_context: ProjectLockedPolicyContextFacts
     packet: SubmissionPacketView
+    accepted_operation_id: UUID | None = None
 
 
 @dataclass(frozen=True, slots=True)
diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py
index cb021c7a7..35dea3854 100644
--- a/backend/scripts/test_lane_catalogue.py
+++ b/backend/scripts/test_lane_catalogue.py
@@ -73,6 +73,7 @@ class TestLane:
     "tests/authorization/guide_activation/test_postgresql.py",
     "tests/authorization/guide_activation/test_concurrency.py",
     "tests/authorization/test_pre_submit_attempt_authority.py",
+    "tests/authorization/test_submission_finalization_authority.py",
     "tests/authorization/pre_submit/test_contracts.py",
     "tests/authorization/test_guide_metadata_contracts.py",
     "tests/authorization/post_policy/test_concurrency.py",
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index b82e226f0..bf12c246d 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -746,3 +746,70 @@ async def commit(self):
         await asyncio.gather(command, return_exceptions=True)
     receipt = await f.admission.accept(owner, request, terminal.terminal_digest, **kwargs)
     assert receipt["status"] == "accepted" and receipt["replayed"] is True
+
+
+async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(admission_intake, tmp_path):
+    from datetime import timedelta
+    from sqlalchemy import text
+    from app.adapters.artifacts import submission_admission_consumption_port
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append
+    from app.adapters.tasks import accepted_submission_creation_service
+    from app.modules.actors.api import ServiceIdentity
+    from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
+    from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
+    from tests.artifact_store_helpers import initialize_local_store
+    from tests.artifacts.intake_acceptance_support import completed_source
+    from tests.checkers.execution.support import provision_post_submit_service
+
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    accepted = await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_BINDING)
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    def submissions(session):
+        return accepted_submission_creation_service(session, settings=_settings(tmp_path),
+            admissions=submission_admission_consumption_port(session,
+                request_id=new_record_id(), correlation_id=owner.operation_id))
+    finalizer = AcceptedSubmissionFinalization(
+        f.factory, tasks=f.admission._tasks, submissions=submissions,
+        checkers=selected_pre_submit_coordinator, store=store, lease_duration=timedelta(seconds=60),
+        authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
+            session, request_id=new_record_id(), correlation_id=owner.operation_id),
+    )
+    try:
+        result = await finalizer.run(owner.operation_id)
+        assert await finalizer.run(owner.operation_id) == result
+        assert await f.admission.accept(owner, request, terminal.terminal_digest,
+            checkers=selected_pre_submit_coordinator, outbox=outbox_append) == dict(accepted, replayed=True)
+        async with f.factory() as session:
+            row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+            assert row.state == "finalized" and row.finalized_submission_id == str(result.submission_id)
+            task = (await session.execute(text("SELECT status, active_submission_operation_id "
+                "FROM workstream_tasks WHERE id=:id"), {"id": f.task})).one()
+            assert task.status == "evaluation_pending" and task.active_submission_operation_id is None
+            admission = (await session.execute(text("SELECT source_operation_id, durable_intent_id, put_attempt_id, "
+                "verification_receipt_id FROM submission_bundle_admissions WHERE id=:id"),
+                {"id": result.admission_id})).one()
+            assert admission.source_operation_id == owner.operation_id
+            assert admission.durable_intent_id is admission.put_attempt_id is admission.verification_receipt_id is None
+            replica = (await session.execute(text("SELECT provider_object_ref FROM artifact_replicas "
+                "WHERE source_operation_id=:id"), {"id": owner.operation_id})).one()
+            assert replica.provider_object_ref == request.source.location.object_ref
+            for table in ("submissions", "submission_dispatches", "checker_runs"):
+                assert await session.scalar(text(f"SELECT count(*) FROM {table} WHERE task_id=:id"), {"id": f.task}) == 1
+            assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE project_id=:id "
+                "AND event_type='PostSubmissionEvaluationRequested'"), {"id": f.project}) == 1
+            assert await session.scalar(text("SELECT count(*) FROM submission_source_charges WHERE operation_id=:id"),
+                {"id": owner.operation_id}) == 1
+        # Removing retained provenance must fail at commit even when all other
+        # replica coordinates remain unchanged.
+        from sqlalchemy.exc import IntegrityError
+        async with f.factory() as session:
+            with pytest.raises(IntegrityError, match="retained source ownership is immutable"):
+                async with session.begin():
+                    await session.execute(text("UPDATE artifact_replicas SET source_operation_id=NULL "
+                        "WHERE source_operation_id=:id"), {"id": owner.operation_id})
+    finally:
+        store.close()
diff --git a/backend/tests/authorization/catalogue_fixtures.py b/backend/tests/authorization/catalogue_fixtures.py
index 262e4875b..d2a4dcb39 100644
--- a/backend/tests/authorization/catalogue_fixtures.py
+++ b/backend/tests/authorization/catalogue_fixtures.py
@@ -13,6 +13,7 @@
     ServiceIdentity.ARTIFACT_SCHEDULER: {"artifact.pending_work.scan"},
     ServiceIdentity.ARTIFACT_BINDING: {
         "artifact.submission.binding.create",
+        "artifact.submission.finalize",
         "artifact.checker_output.binding.create",
         "artifact.review_evidence.binding.create",
     },
@@ -136,6 +137,7 @@
         "WS-XINT-002-06A",
         "active",
     ),
+    "artifact.submission.finalize": ("artifact.binding.create", "WS-AUTH-001-ART-05", "active"),
     "artifact.submission.binding.create": (
         "artifact.binding.create",
         "WS-AUTH-001-ART-05",
@@ -698,6 +700,7 @@
     "artifact.recovery_attempt.read",
     "artifact.replica.read",
     "artifact.submission.binding.create",
+    "artifact.submission.finalize",
     "artifact.submission_bundle.prepare",
     "artifact.verification.execute",
     "artifact.verification_job.read",
diff --git a/backend/tests/authorization/test_catalogue.py b/backend/tests/authorization/test_catalogue.py
index 1295e6b56..14c883e46 100644
--- a/backend/tests/authorization/test_catalogue.py
+++ b/backend/tests/authorization/test_catalogue.py
@@ -39,7 +39,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
     assert {item.value for item in HISTORICAL_PERMISSION_IDS} == historical_permissions
     assert {item.value for item in NEW_PERMISSION_IDS} == new_permissions
     assert {item.value for item in PERMISSION_IDS} == historical_permissions | new_permissions
-    assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 192
+    assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 193
     assert set(ACTION_BY_ID) == ACTION_IDS
     assert {definition.owner for definition in ACTION_DEFINITIONS} == set(ActionOwner)
     assert {
@@ -84,7 +84,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
         ActionOwner.AUTH_ART_02D_INTERNAL: 3,
         ActionOwner.XINT_002_04B: 1,
         ActionOwner.XINT_002_06A: 1,
-        ActionOwner.AUTH_ART_05: 1,
+        ActionOwner.AUTH_ART_05: 2,
         ActionOwner.AUTH_ART_06A: 1,
         ActionOwner.AUTH_ART_06B: 2,
         ActionOwner.XINT_002_04A: 1,
@@ -118,7 +118,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
     }
     assert all(not owner.value.startswith("WS-REV-") for owner in ActionOwner)
     assert Counter(definition.availability for definition in ACTION_DEFINITIONS) == {
-        ActionAvailability.ACTIVE: 167,
+        ActionAvailability.ACTIVE: 168,
         ActionAvailability.PLANNED: 25,
     }
     assert (
@@ -163,7 +163,7 @@ def test_fixed_service_action_matrix_and_activation_are_exact_and_immutable() ->
         identity: {action.value for action in actions}
         for identity, actions in SERVICE_ACTIONS_BY_IDENTITY.items()
     } == expected
-    assert sum(map(len, SERVICE_ACTIONS_BY_IDENTITY.values())) == 42
+    assert sum(map(len, SERVICE_ACTIONS_BY_IDENTITY.values())) == 43
     assert FUTURE_INTENT_REQUIRED_ACTIONS == {
         ActionId.REVIEW_FINDING_EVIDENCE_INGEST,
         ActionId.REVIEW_FINDING_RESPONSE_EVIDENCE_INGEST,
@@ -261,6 +261,7 @@ def test_active_fixed_service_actions_are_exact():
         ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE,
         ActionId.ARTIFACT_PENDING_WORK_SCAN,
         ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
+        ActionId.ARTIFACT_SUBMISSION_FINALIZE,
         ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE,
         ActionId.ARTIFACT_CHECKER_OUTPUT_WRITE,
         ActionId.ARTIFACT_GUIDE_SOURCE_READ,
diff --git a/backend/tests/authorization/test_submission_finalization_authority.py b/backend/tests/authorization/test_submission_finalization_authority.py
new file mode 100644
index 000000000..eb91ed247
--- /dev/null
+++ b/backend/tests/authorization/test_submission_finalization_authority.py
@@ -0,0 +1,83 @@
+"""Real fixed-service finalization authority, exact handles and rollback."""
+from dataclasses import replace
+from uuid import UUID
+
+import pytest
+from sqlalchemy import select, update
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.core.identifiers import new_record_id
+from app.modules.actors.api import ServiceIdentity
+from app.modules.actors.models import ActorIdentityLink
+from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationAuthorityFacts
+from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
+from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError
+from app.modules.tasks.models import AuditEvent
+from tests.checkers.execution.support import provision_post_submit_service
+
+
+def facts(phase="claim"):
+    return SubmissionFinalizationAuthorityFacts(
+        operation_id=new_record_id(), project_id=new_record_id(), task_id=new_record_id(),
+        assignment_id=new_record_id(), contributor_id=new_record_id(), acceptance_decision_id=new_record_id(),
+        accepted_context_sha256="sha256:"+"a"*64, acceptance_receipt_sha256="sha256:"+"b"*64,
+        source_sha256="sha256:"+"c"*64, continuation_lease_id=new_record_id(), continuation_generation=1,
+        phase=phase, submission_id=new_record_id() if phase=="commit" else None,
+        submission_version=1 if phase=="commit" else None,
+    )
+
+
+@pytest.mark.parametrize("phase", ["claim", "commit"])
+async def test_finalization_consumes_exact_service_authority(clean_postgres_database, phase):
+    engine = create_async_engine(clean_postgres_database)
+    factory = async_sessionmaker(engine, expire_on_commit=False)
+    try:
+        actor = await provision_post_submit_service(factory, ServiceIdentity.ARTIFACT_BINDING)
+        original = facts(phase)
+        async with factory.begin() as session:
+            authority = PreparedSubmissionFinalizationAuthorization(
+                session, request_id=new_record_id(), correlation_id=original.operation_id)
+            handle = await authority.prepare(facts=original, idempotency_key=original.continuation_lease_id)
+            for changed in [replace(original, continuation_generation=2),
+                            replace(original, acceptance_decision_id=new_record_id()),
+                            replace(original, source_sha256="sha256:"+"d"*64)]:
+                with pytest.raises(ArtifactAuthorityDeniedError):
+                    await authority.consume(prepared_authorization=handle, facts=changed)
+            decision = await authority.consume(prepared_authorization=handle, facts=original)
+            assert isinstance(decision, UUID)
+            with pytest.raises(ArtifactAuthorityDeniedError):
+                await authority.consume(prepared_authorization=handle, facts=original)
+        async with factory() as session:
+            event = await session.get(AuditEvent, str(decision))
+            assert event.actor_id == actor and event.matched_grant_id is None
+            assert event.action_id == "artifact.submission.finalize"
+            assert event.resource_type == "submission_operation" and event.resource_id == str(original.operation_id)
+            assert event.target_ref_id == str(original.project_id)
+    finally:
+        await engine.dispose()
+
+
+@pytest.mark.parametrize("principal", ["missing", "wrong", "revoked"])
+async def test_finalization_refuses_missing_wrong_or_revoked_service(clean_postgres_database, principal):
+    engine = create_async_engine(clean_postgres_database)
+    factory = async_sessionmaker(engine, expire_on_commit=False)
+    try:
+        if principal != "missing":
+            identity = ServiceIdentity.ARTIFACT_MATERIALIZER if principal == "wrong" else ServiceIdentity.ARTIFACT_BINDING
+            actor = await provision_post_submit_service(factory, identity)
+            if principal == "revoked":
+                async with factory.begin() as session:
+                    from sqlalchemy import func
+                    await session.execute(update(ActorIdentityLink).where(ActorIdentityLink.actor_profile_id==actor)
+                        .values(status="revoked", revoked_by="test", revoked_reason="test", revoked_at=func.now()))
+        async with factory.begin() as session:
+            authority = PreparedSubmissionFinalizationAuthorization(
+                session, request_id=new_record_id(), correlation_id=new_record_id())
+            with pytest.raises(ArtifactAuthorityDeniedError):
+                await authority.prepare(facts=facts(), idempotency_key=new_record_id())
+        async with factory() as session:
+            assert not (await session.scalars(select(AuditEvent).where(
+                AuditEvent.action_id=="artifact.submission.finalize",
+                AuditEvent.event_type=="SensitiveAuthorizationAllowed"))).all()
+    finally:
+        await engine.dispose()
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 7b5c8a995..c00342bde 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "5a1f343869d5599158b74372e1a150fe913659313b03f71185a4360c8163e186"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "a50cdb610c962d4d9be732549594c6eb77741c633c99472749f5301dcae70449"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",

From 15c8945f0bd42f398df1fed42c650c80dfbf5898 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 21:14:04 +0100
Subject: [PATCH 115/513] Execute POST from accepted sealed sources with exact
 retained custody

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  74 ++++++++++++
 .../versions/0074_submission_finalization.py  |  18 ++-
 .../versions/0075_source_post_custody.py      |  99 +++++++++++++++
 .../modules/artifacts/intake/finalization.py  |   6 +-
 .../artifacts/post_submit_materialization.py  |   9 +-
 .../artifacts/post_submit_selection.py        |  63 +++++++---
 backend/app/modules/artifacts/preparation.py  |  18 ++-
 .../checkers/api/evaluation_context.py        |   6 +-
 backend/app/modules/checkers/api/external.py  |   6 +-
 .../modules/checkers/api/materialization.py   |   8 +-
 .../checkers/api/post_material_custody.py     |  35 ++++++
 .../tests/artifacts/intake_post_support.py    |  83 +++++++++++++
 .../test_submission_intake_admission.py       |  32 ++++-
 .../tests/checkers/external/test_contracts.py |  41 +++++++
 .../tests/checkers/external/test_runtime.py   |   5 +-
 backend/tests/conftest.py                     |   2 +-
 backend/tests/test_artifact_architecture.py   |   9 +-
 .../workstream-checker-sdk/src/lib.rs         | 114 ++++++++++++++----
 .../workstream-checker-service/src/main.rs    |  77 +++++++-----
 19 files changed, 601 insertions(+), 104 deletions(-)
 create mode 100644 backend/alembic/versions/0075_source_post_custody.py
 create mode 100644 backend/app/modules/checkers/api/post_material_custody.py
 create mode 100644 backend/tests/artifacts/intake_post_support.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index b2234acf6..352e503b8 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2762,3 +2762,77 @@ the ledger coordinates adjusted accordingly. These are worktree-scoped results,
 not full-suite or exact frozen-commit provenance. T5 crash/concurrency and POST
 execution/public integration remain open; focused implementation review follows
 this reproducible milestone.
+
+### POST source custody continuation
+
+The next bounded extension follows the frozen T5 review: repair content/adapter
+immutability with direct SQL probes; bound continuation leases by the existing
+OUTBOX one-hour structural ceiling (no deployment default or C05 approval implied).
+Extend the existing POST selector/materializer and CHECKERS material contracts to
+carry exact accepted-operation custody without provider coordinates. Preserve
+retained verification-backed evidence and its canonical digests; new source-backed
+material carries operation, accepted-source and acceptance-receipt hashes instead
+of fabricated verification IDs. Both current and predecessor material use the same
+selector and version-pinned `open_source` capability. Update external checker SDK
+and service validation together. Do not widen generic object-key parsing.
+
+Allowed scope is ART selection/materialization, CHECKERS material facts and retained
+input custody, the external checker contract validators, focused tests and this
+record. Prohibited changes include weakening AUTH/currentness, exposing provider
+locators, copying/reuploading source bytes, and claiming production provider
+qualification. Acceptance requires real T5-to-POST material execution, exact source
+version substitution controls, and retained-evidence roundtrip tests. Risk is high;
+ARCH/SEC reviews custody and QA reviews execution/failure proof before readiness.
+
+Review repairs: source-linked content SHA/size/media changes now fail under a
+narrow content trigger, with source admission validation holding a content share
+lock through commit. Replica adapter must match its namespace. Direct SQL digest,
+size, media and adapter substitutions are rejected in the composed test. The
+continuation constructor and SQL claim transition reject durations above the
+existing OUTBOX one-hour structural ceiling; deployment must still supply an
+explicit measured duration. Three constructor bound cases pass; expired-claim
+recovery proof remains required.
+
+POST selection now resolves source-backed admissions from their finalized operation
+and uses exact sealed-generation `open_source`. CHECKERS facts, ART's aggregate grant,
+and the Rust SDK/service validators admit one complete source witness or one retained
+verification witness. Python contract tests pass (38); Rust SDK tests pass (9), and
+both targeted service grant tests pass. Artifact architecture tests pass (48).
+The integrated run passed the T5 SQL mutation probes and reached selected POST
+execution, exposing an additional closed field list in ART's grant builder; that
+list is now updated without importing CHECKERS internals. The rerun is pending.
+Historical revision-input SQL still requires extension for a source-backed
+predecessor, and actual MinIO POST version-substitution proof remains required.
+
+Migration 0075 extends both the current-input authorization digest reconstruction
+and the historical predecessor custody predicate for source-backed material. Its
+verification-backed branch preserves existing keys, values and optional revision
+context encoding. The composed test originally reached POST terminal publication
+and was correctly rejected by the old SQL receipt reconstruction; 0075 repairs
+that actual failure rather than bypassing the receipt guard.
+
+Integrated verification now passes: **5 passed, 27 deselected** in
+`/tmp/post-source-composed4.log` (metadata `/tmp/post-source-composed4.json`). Both
+normal T5 and worker death after a committed claim proceed through actual owner
+POST selection/materialization, controlled selected evaluation, terminal commit,
+and replay. The expired-claim case proves a live competitor is refused and a later
+independent transaction reclaims generation 2 without duplicate Submission/POST.
+The storage wrapper forbids generic unversioned reads and requires the exact
+sealed source; replay does not read it again. The three lease constructor bounds
+also pass. This uses real PostgreSQL and Local storage with explicit in-process
+intake/checker fixtures; it is not native Smol or hosted provider qualification.
+
+Runtime/contract verification passed **74 tests**; a further predecessor witness
+roundtrip brings the focused contract file to **39 passed**. The earlier scratch
+lifetime test incorrectly injected the retired `prepared_generation_id` into the
+current PRE wire identity; it now keeps that ID only in private ART scratch facts.
+Its shared scratch lifetime assertions remain. Rust SDK tests pass **9**, targeted
+Rust service grant tests pass **2**, artifact architecture passes **48**, structure,
+changed-file Ruff, and Markdown links pass. These are scoped worktree results.
+Fetched current `origin/main` remains `94334ccf4`, with no missing base commits.
+
+Remaining before end-to-end completion: MinIO source-version substitution during
+actual POST; real source-backed revision routing/preparation/POST; rollback/lost
+acknowledgement/concurrency expansions; durable finalization outbox/Celery wiring
+and operational stall projection; public API/CLI/MCP cutover and the complete
+A01–A35/C01–C07 audit. No merge or overall readiness is claimed by this checkpoint.
diff --git a/backend/alembic/versions/0074_submission_finalization.py b/backend/alembic/versions/0074_submission_finalization.py
index c5acd5576..f92b6c150 100644
--- a/backend/alembic/versions/0074_submission_finalization.py
+++ b/backend/alembic/versions/0074_submission_finalization.py
@@ -193,7 +193,8 @@ def _extend_existing_guards():
        OR NEW.continuation_generation IS DISTINCT FROM coalesce(OLD.continuation_generation,0)+1
        OR NEW.continuation_lease_id IS NOT DISTINCT FROM OLD.continuation_lease_id
        OR (OLD.continuation_expires_at IS NOT NULL AND OLD.continuation_expires_at>clock_timestamp())
-       OR NOT isfinite(NEW.continuation_expires_at) OR NEW.continuation_expires_at<=clock_timestamp() THEN
+       OR NOT isfinite(NEW.continuation_expires_at) OR NEW.continuation_expires_at<=clock_timestamp()
+       OR NEW.continuation_expires_at>clock_timestamp()+interval '1 hour' THEN
       RAISE EXCEPTION 'invalid submission continuation claim' USING ERRCODE='23514';
     END IF;
     RETURN NEW;
@@ -247,11 +248,12 @@ def _extend_existing_guards():
  PERFORM public.require_submission_acceptance(o);
  SELECT * INTO r FROM public.selected_pre_submit_runs WHERE id=o.selected_pre_submit_run_id;
  SELECT * INTO v FROM public.artifact_replicas WHERE id=a.verified_replica_id;
- SELECT * INTO c FROM public.artifact_contents WHERE id=a.artifact_content_id;
+ SELECT * INTO c FROM public.artifact_contents WHERE id=a.artifact_content_id FOR SHARE;
  IF a.selected_pre_submit_run_id IS DISTINCT FROM r.id OR a.pre_submit_evidence_set_id IS NOT NULL
     OR v.id IS NULL OR c.id IS NULL OR v.source_operation_id IS DISTINCT FROM o.id
     OR v.content_id IS DISTINCT FROM c.id OR v.storage_namespace_id IS DISTINCT FROM o.namespace_id
     OR v.namespace_fingerprint IS DISTINCT FROM o.namespace_fingerprint OR v.provider_profile IS DISTINCT FROM o.provider_profile
+    OR v.adapter IS DISTINCT FROM (SELECT adapter FROM public.artifact_storage_namespaces WHERE id=o.namespace_id)
     OR v.provider_object_ref IS DISTINCT FROM o.object_ref OR c.sha256 IS DISTINCT FROM o.raw_sha256
     OR c.byte_count IS DISTINCT FROM o.raw_byte_count OR c.media_type IS DISTINCT FROM 'application/zip'
     OR v.verification_state IS DISTINCT FROM 'verified' OR v.integrity_state IS DISTINCT FROM 'valid'
@@ -282,6 +284,18 @@ def _extend_existing_guards():
  END IF;
 END $$;
 
+CREATE FUNCTION public.guard_accepted_source_content()
+RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+BEGIN
+ IF ROW(OLD.sha256,OLD.byte_count,OLD.media_type) IS DISTINCT FROM ROW(NEW.sha256,NEW.byte_count,NEW.media_type)
+    AND EXISTS(SELECT 1 FROM public.artifact_replicas WHERE content_id=OLD.id AND source_operation_id IS NOT NULL) THEN
+   RAISE EXCEPTION 'accepted source content is immutable' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+END $$;
+CREATE TRIGGER accepted_source_content_immutable BEFORE UPDATE ON public.artifact_contents
+ FOR EACH ROW EXECUTE FUNCTION public.guard_accepted_source_content();
+
 CREATE FUNCTION public.check_submission_finalization()
 RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
 DECLARE o public.submission_intake_operations%ROWTYPE; a public.submission_bundle_admissions%ROWTYPE;
diff --git a/backend/alembic/versions/0075_source_post_custody.py b/backend/alembic/versions/0075_source_post_custody.py
new file mode 100644
index 000000000..6c9df6fa4
--- /dev/null
+++ b/backend/alembic/versions/0075_source_post_custody.py
@@ -0,0 +1,99 @@
+"""Retain source-backed predecessor custody in revision POST evidence."""
+from alembic import op
+from sqlalchemy import text
+
+revision = "0075_source_post_custody"
+down_revision = "0074_submission_finalization"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.checker_runs IN SHARE ROW EXCLUSIVE MODE")
+    op.execute(_CUSTODY)
+    _extend_input_authority_digest()
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef('public.checker_input_context_valid(public.checker_runs)'::regprocedure)"
+    )).scalar_one()
+    if body.count(_OLD_QUERY) != 1 or body.count("'verification_generation','namespace_fingerprint',") != 2:
+        raise RuntimeError("revision POST custody predecessor shape changed")
+    body = body.replace(_OLD_QUERY, "       OR NOT public.post_submission_material_custody_valid(prior_custody)")
+    body = body.replace("'verification_generation','namespace_fingerprint',",
+        "'verification_generation','source_operation_id','accepted_source_sha256','acceptance_receipt_sha256','namespace_fingerprint',")
+    op.execute(body)
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
+
+
+_OLD_QUERY = """       OR NOT EXISTS(
+         SELECT 1 FROM public.submission_bundle_admissions a
+         JOIN public.artifact_verification_receipts receipt
+           ON receipt.id=a.verification_receipt_id
+         JOIN public.artifact_replicas replica ON replica.id=a.verified_replica_id
+         JOIN public.artifact_storage_namespaces namespace
+           ON namespace.id=replica.storage_namespace_id
+         WHERE a.id=(prior_custody->>'admission_id')::uuid
+           AND prior_custody->>'evidence_id'=
+             coalesce(a.pre_submit_evidence_set_id,a.selected_pre_submit_run_id)::text
+           AND prior_custody->>'verification_receipt_id'=receipt.id::text
+           AND prior_custody->>'verification_job_id'=receipt.verification_job_id::text
+           AND prior_custody->>'verification_generation'=receipt.execution_generation::text
+           AND prior_custody->>'namespace_fingerprint'=namespace.namespace_fingerprint
+           AND prior_custody->>'semantic_manifest_id'=a.semantic_manifest_id::text)"""
+
+_CUSTODY = r"""
+CREATE FUNCTION public.post_submission_material_custody_valid(custody jsonb)
+RETURNS boolean LANGUAGE sql STABLE SET search_path=pg_catalog,public,pg_temp AS $$
+ SELECT coalesce(EXISTS (
+   SELECT 1 FROM public.submission_bundle_admissions a
+   JOIN public.artifact_replicas replica ON replica.id=a.verified_replica_id
+   JOIN public.artifact_storage_namespaces namespace ON namespace.id=replica.storage_namespace_id
+   LEFT JOIN public.artifact_verification_receipts receipt ON receipt.id=a.verification_receipt_id
+   LEFT JOIN public.submission_intake_operations o ON o.id=a.source_operation_id
+   WHERE a.id=(custody->>'admission_id')::uuid
+     AND custody->>'evidence_id'=coalesce(a.pre_submit_evidence_set_id,a.selected_pre_submit_run_id)::text
+     AND custody->>'namespace_fingerprint'=namespace.namespace_fingerprint
+     AND custody->>'semantic_manifest_id'=a.semantic_manifest_id::text
+     AND ((a.source_operation_id IS NULL
+           AND NOT custody ?| ARRAY['source_operation_id','accepted_source_sha256','acceptance_receipt_sha256']
+           AND custody->>'verification_receipt_id'=receipt.id::text
+           AND custody->>'verification_job_id'=receipt.verification_job_id::text
+           AND custody->>'verification_generation'=receipt.execution_generation::text)
+       OR (a.source_operation_id IS NOT NULL AND a.verification_receipt_id IS NULL
+           AND NOT custody ?| ARRAY['verification_receipt_id','verification_job_id','verification_generation']
+           AND o.state='finalized' AND o.finalized_admission_id=a.id
+           AND o.finalized_submission_id=a.consumed_by_submission_id
+           AND replica.source_operation_id=o.id
+           AND custody->>'source_operation_id'=o.id::text
+           AND custody->>'accepted_source_sha256'=o.accepted_source_sha256
+           AND custody->>'acceptance_receipt_sha256'=o.acceptance_receipt_sha256))
+ ),false)
+$$;
+"""
+
+
+def _extend_input_authority_digest():
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef('public.checker_input_authority_digest(public.checker_runs)'::regprocedure)"
+    )).scalar_one()
+    changes = (
+        ("jsonb_build_object('material',r.material_custody::jsonb,",
+         "(CASE WHEN a.source_operation_id IS NULL THEN jsonb_build_object('material',r.material_custody::jsonb,"),
+        ("'semantic_manifest_id',a.semantic_manifest_id::text)",
+         "'semantic_manifest_id',a.semantic_manifest_id::text) ELSE jsonb_build_object("
+         "'material',r.material_custody::jsonb,'evidence_id',a.selected_pre_submit_run_id::text,"
+         "'source_operation_id',o.id::text,'accepted_source_sha256',o.accepted_source_sha256,"
+         "'acceptance_receipt_sha256',o.acceptance_receipt_sha256,"
+         "'namespace_fingerprint',n.namespace_fingerprint,'semantic_manifest_id',a.semantic_manifest_id::text) END)"),
+        ("JOIN public.artifact_verification_receipts v ON v.id=a.verification_receipt_id",
+         "LEFT JOIN public.artifact_verification_receipts v ON v.id=a.verification_receipt_id "
+         "LEFT JOIN public.submission_intake_operations o ON o.id=a.source_operation_id"),
+    )
+    for old, new in changes:
+        if body.count(old) != 1:
+            raise RuntimeError("POST materialization digest predecessor shape changed")
+        body = body.replace(old, new)
+    op.execute(body)
diff --git a/backend/app/modules/artifacts/intake/finalization.py b/backend/app/modules/artifacts/intake/finalization.py
index dc611c5f8..55b4c3256 100644
--- a/backend/app/modules/artifacts/intake/finalization.py
+++ b/backend/app/modules/artifacts/intake/finalization.py
@@ -40,8 +40,10 @@ class AcceptedSubmissionFinalization:
     """Keep provider I/O outside TASK locks; finalized replay precedes new claims."""
 
     def __init__(self, sessions, *, tasks, authorization, submissions, checkers, store, lease_duration):
-        if not isinstance(lease_duration, timedelta) or lease_duration <= timedelta(0):
-            raise ValueError("finalization lease duration must be explicit and positive")
+        # Match the durable outbox's one-hour structural lease ceiling. This is
+        # not a deployment default; composition must still supply its profile.
+        if not isinstance(lease_duration, timedelta) or not timedelta(0) < lease_duration <= timedelta(hours=1):
+            raise ValueError("finalization lease duration must be explicit, positive and at most one hour")
         self._sessions, self._tasks, self._authorization = sessions, tasks, authorization
         self._submissions, self._store, self._duration = submissions, store, lease_duration
         self._checkers = checkers
diff --git a/backend/app/modules/artifacts/post_submit_materialization.py b/backend/app/modules/artifacts/post_submit_materialization.py
index 5765f6ed5..e0906cd9b 100644
--- a/backend/app/modules/artifacts/post_submit_materialization.py
+++ b/backend/app/modules/artifacts/post_submit_materialization.py
@@ -122,6 +122,9 @@ def _external_material(facts, media_type, role):
         verification_receipt_id=facts.verification_receipt_id,
         verification_job_id=facts.verification_job_id,
         verification_generation=facts.verification_generation,
+        source_operation_id=facts.source_operation_id,
+        accepted_source_sha256=facts.accepted_source_sha256,
+        acceptance_receipt_sha256=facts.acceptance_receipt_sha256,
         namespace_fingerprint=facts.namespace_fingerprint,
         semantic_manifest_sha256=material.semantic_manifest_sha256,
     )
@@ -519,6 +522,9 @@ def _material_facts(selected):
             verification_receipt_id=selected.verification_receipt_id,
             verification_job_id=selected.verification_job_id,
             verification_generation=selected.verification_generation,
+            source_operation_id=selected.sealed_source.location.operation_id if selected.sealed_source else None,
+            accepted_source_sha256=selected.accepted_source_sha256,
+            acceptance_receipt_sha256=selected.acceptance_receipt_sha256,
             namespace_fingerprint=selected.namespace_fingerprint,
             semantic_manifest_id=selected.semantic_manifest_id,
         )
@@ -698,7 +704,8 @@ async def materialize(
                         prepared_trusted_intake(
                             self._intake,
                             self._preparation.prepare(
-                                self._store.open(selection.provider_object_ref),
+                                (self._store.open_source(selection.sealed_source) if selection.sealed_source
+                                 else self._store.open(selection.provider_object_ref)),
                                 media_type=selection.media_type,
                                 expected_sha256=selection.sha256,
                                 expected_size=selection.byte_count,
diff --git a/backend/app/modules/artifacts/post_submit_selection.py b/backend/app/modules/artifacts/post_submit_selection.py
index c9a19bfcb..a5ab017c9 100644
--- a/backend/app/modules/artifacts/post_submit_selection.py
+++ b/backend/app/modules/artifacts/post_submit_selection.py
@@ -3,10 +3,13 @@
 from dataclasses import dataclass
 from uuid import UUID
 
-from sqlalchemy import select
+from sqlalchemy import select, text
 from sqlalchemy.ext.asyncio import AsyncSession
 
 from app.interfaces.artifacts import ArtifactStore, artifact_provider_object_ref
+from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
+from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+from app.modules.artifacts.intake.repository import SubmissionIntakeRepository
 from app.modules.checkers.api.materialization import PostSubmissionMaterializationUnavailable
 from app.modules.artifacts.models import (
     ArtifactBinding, ArtifactContent, ArtifactReplica, ArtifactStorageNamespace,
@@ -37,9 +40,9 @@ class PostSubmissionMaterialSelection:
     submission: SubmittedBundleFacts
     evidence_id: UUID
     replica_id: UUID
-    verification_receipt_id: UUID
-    verification_job_id: UUID
-    verification_generation: int
+    verification_receipt_id: UUID | None
+    verification_job_id: UUID | None
+    verification_generation: int | None
     namespace_fingerprint: str
     adapter: str
     provider_profile: str
@@ -51,6 +54,9 @@ class PostSubmissionMaterialSelection:
     semantic_manifest_sha256: str
     revision_preparation_id: UUID | None
     revision_preparation_sha256: str | None
+    sealed_source: SealedSubmissionSource | None = None
+    acceptance_receipt_sha256: str | None = None
+    accepted_source_sha256: str | None = None
 
 
 async def read_post_submission_facts(
@@ -172,8 +178,8 @@ async def select_admitted_post_material(
         .join(ArtifactBinding, ArtifactBinding.id == str(facts.binding_id))
         .join(ArtifactContent, ArtifactContent.id == SubmissionBundleAdmission.artifact_content_id)
         .join(ArtifactReplica, ArtifactReplica.id == SubmissionBundleAdmission.verified_replica_id)
-        .join(ArtifactVerificationReceipt, ArtifactVerificationReceipt.id == SubmissionBundleAdmission.verification_receipt_id)
-        .join(ArtifactVerificationJob, ArtifactVerificationJob.id == ArtifactVerificationReceipt.verification_job_id)
+        .outerjoin(ArtifactVerificationReceipt, ArtifactVerificationReceipt.id == SubmissionBundleAdmission.verification_receipt_id)
+        .outerjoin(ArtifactVerificationJob, ArtifactVerificationJob.id == ArtifactVerificationReceipt.verification_job_id)
         .join(ArtifactStorageNamespace, ArtifactStorageNamespace.id == ArtifactReplica.storage_namespace_id)
         .where(SubmissionBundleAdmission.id == str(facts.admission_id),
                SubmissionBundleAdmission.project_id == str(facts.project_id),
@@ -211,25 +217,20 @@ async def select_admitted_post_material(
         and replica.content_id == content.id
         and (replica.verification_state, replica.availability_state, replica.integrity_state)
         == ("verified", "available", "valid")
-        and receipt.outcome == "verified"
-        and receipt.observed_sha256 == content.sha256
-        and receipt.observed_byte_count == content.byte_count
-        and job.replica_id == replica.id
-        and job.originating_put_attempt_id == admission.put_attempt_id
     ):
         raise PostSubmissionMaterializationUnavailable("post_submit_material_identity_mismatch")
     validate_artifact_replica_execution_namespace(
         replica=replica, persisted=persisted, namespace=namespace, store=store,
     )
-    commitment = ArtifactCommitment(content.sha256, content.byte_count, content.media_type)
-    if replica.provider_object_ref != artifact_provider_object_ref(commitment):
-        raise PostSubmissionMaterializationUnavailable("post_submit_material_identity_mismatch")
+    source, accepted_source, acceptance_receipt = await _read_material_custody(
+        session, admission, content, replica, receipt, job,
+    )
     return PostSubmissionMaterialSelection(
         submission=facts,
         evidence_id=UUID(admission.selected_pre_submit_run_id),
         replica_id=UUID(replica.id),
-        verification_receipt_id=UUID(receipt.id), verification_job_id=UUID(job.id),
-        verification_generation=receipt.execution_generation,
+        verification_receipt_id=UUID(receipt.id) if receipt else None, verification_job_id=UUID(job.id) if job else None,
+        verification_generation=receipt.execution_generation if receipt else None,
         namespace_fingerprint=persisted.namespace_fingerprint, adapter=replica.adapter,
         provider_profile=replica.provider_profile, provider_object_ref=replica.provider_object_ref,
         sha256=content.sha256, byte_count=content.byte_count, media_type=content.media_type,
@@ -237,4 +238,34 @@ async def select_admitted_post_material(
         semantic_manifest_sha256=admission.semantic_manifest_sha256,
         revision_preparation_id=admission.revision_preparation_id,
         revision_preparation_sha256=admission.revision_preparation_sha256,
+        sealed_source=source, accepted_source_sha256=accepted_source, acceptance_receipt_sha256=acceptance_receipt,
     )
+
+
+async def _read_material_custody(session, admission, content, replica, receipt, job):
+    """Resolve exact retained source generation or verified-put evidence."""
+    invalid = PostSubmissionMaterializationUnavailable("post_submit_material_identity_mismatch")
+    if admission.source_operation_id is None:
+        commitment = ArtifactCommitment(content.sha256, content.byte_count, content.media_type)
+        if (receipt is None or job is None or replica.source_operation_id is not None
+                or receipt.outcome != "verified" or receipt.observed_sha256 != content.sha256
+                or receipt.observed_byte_count != content.byte_count or job.replica_id != replica.id
+                or job.originating_put_attempt_id != admission.put_attempt_id
+                or replica.provider_object_ref != artifact_provider_object_ref(commitment)):
+            raise invalid
+        return None, None, None
+    operation = await session.get(SubmissionIntakeOperation, admission.source_operation_id,
+                                  populate_existing=True)
+    if (receipt is not None or job is not None or operation is None or operation.state != "finalized"
+            or operation.finalized_admission_id != admission.id
+            or operation.finalized_submission_id != admission.consumed_by_submission_id
+            or replica.source_operation_id != operation.id):
+        raise invalid
+    await session.execute(text("SELECT public.require_source_submission_admission(a) "
+        "FROM public.submission_bundle_admissions a WHERE id=:id"), {"id": admission.id})
+    valid = await session.scalar(text("SELECT public.submission_finalization_authority_valid(o,'commit') "
+        "FROM public.submission_intake_operations o WHERE id=:id"), {"id": operation.id})
+    if valid is not True:
+        raise invalid
+    return (SubmissionIntakeRepository._sealed_source(operation), operation.accepted_source_sha256,
+            operation.acceptance_receipt_sha256)
diff --git a/backend/app/modules/artifacts/preparation.py b/backend/app/modules/artifacts/preparation.py
index 2fb301237..301b38e7b 100644
--- a/backend/app/modules/artifacts/preparation.py
+++ b/backend/app/modules/artifacts/preparation.py
@@ -98,6 +98,9 @@
         "semantic_manifest_sha256",
     }
 )
+_POST_SOURCE_MATERIAL_FIELDS = (_POST_MATERIAL_FIELDS - {
+    "verification_receipt_id", "verification_job_id", "verification_generation",
+}) | {"source_operation_id", "accepted_source_sha256", "acceptance_receipt_sha256"}
 
 
 class PreparedSubmissionProcessor(Protocol[_InspectionResultCo]):
@@ -274,9 +277,10 @@ class PostExternalMaterialGrantItem:
 
     def __post_init__(self) -> None:
         """Validate canonical role custody and the inventory before grant publication."""
+        source_backed = getattr(self.material, "source_operation_id", None) is not None
         material = _external_grant_json(
             self.material,
-            expected_fields=_POST_MATERIAL_FIELDS,
+            expected_fields=_POST_SOURCE_MATERIAL_FIELDS if source_backed else _POST_MATERIAL_FIELDS,
             label="material",
         )
         identifiers = (
@@ -285,17 +289,19 @@ def __post_init__(self) -> None:
             "content_id",
             "replica_id",
             "evidence_id",
-            "verification_receipt_id",
-            "verification_job_id",
-        )
+        ) + (("source_operation_id",) if source_backed else ("verification_receipt_id", "verification_job_id"))
+        if source_backed:
+            custody_valid = all(_valid_sha256(material[field]) for field in (
+                "accepted_source_sha256", "acceptance_receipt_sha256"))
+        else:
+            custody_valid = type(material["verification_generation"]) is int and material["verification_generation"] > 0
         if (
             material["phase"] != "post_submit"
             or material["role"] not in {"submission_archive", "predecessor_submission_archive"}
             or any(not _valid_resource_id(material[field]) for field in identifiers)
             or type(material["submission_version"]) is not int
             or material["submission_version"] <= 0
-            or type(material["verification_generation"]) is not int
-            or material["verification_generation"] <= 0
+            or not custody_valid
             or type(material["byte_count"]) is not int
             or not 0 <= material["byte_count"] <= HARD_MAXIMUM_ARTIFACT_BYTES
             or type(material["media_type"]) is not str
diff --git a/backend/app/modules/checkers/api/evaluation_context.py b/backend/app/modules/checkers/api/evaluation_context.py
index ec640864d..25451ae9f 100644
--- a/backend/app/modules/checkers/api/evaluation_context.py
+++ b/backend/app/modules/checkers/api/evaluation_context.py
@@ -1,6 +1,7 @@
 """Image-safe revision facts selected by an approved POST configuration."""
 
 import json
+from app.modules.checkers.api.post_material_custody import PostSubmitArtifactCustody
 from typing import Annotated, Literal, Self
 
 from pydantic import Field, model_validator
@@ -118,7 +119,7 @@ def exact_source(self) -> Self:
         return self
 
 
-class PostSubmitPredecessorCustody(PostSubmitEvaluationPredecessor):
+class PostSubmitPredecessorCustody(PostSubmitEvaluationPredecessor, PostSubmitArtifactCustody):
     """Verified prior ART custody retained with the exact input authority receipt."""
 
     admission_id: ResourceId
@@ -126,9 +127,6 @@ class PostSubmitPredecessorCustody(PostSubmitEvaluationPredecessor):
     content_id: ResourceId
     replica_id: ResourceId
     evidence_id: ResourceId
-    verification_receipt_id: ResourceId
-    verification_job_id: ResourceId
-    verification_generation: VersionNumber
     namespace_fingerprint: Sha256
     semantic_manifest_id: ResourceId
 
diff --git a/backend/app/modules/checkers/api/external.py b/backend/app/modules/checkers/api/external.py
index 8cf4b78b7..abb5a7efb 100644
--- a/backend/app/modules/checkers/api/external.py
+++ b/backend/app/modules/checkers/api/external.py
@@ -1,6 +1,7 @@
 """Normalized external-checker contracts; values never grant execution authority."""
 
 from __future__ import annotations
+from app.modules.checkers.api.post_material_custody import PostSubmitArtifactCustody
 
 import json
 import hashlib
@@ -380,7 +381,7 @@ class PreSubmitExternalCheckerMaterial(ExternalCheckerValue):
     ]
 
 
-class PostSubmitExternalCheckerMaterial(ExternalCheckerValue):
+class PostSubmitExternalCheckerMaterial(PostSubmitArtifactCustody, ExternalCheckerValue):
     """Verified native Submission and ART ancestry selected for POST execution."""
 
     phase: Literal["post_submit"] = "post_submit"
@@ -396,9 +397,6 @@ class PostSubmitExternalCheckerMaterial(ExternalCheckerValue):
         StrictStr, Field(min_length=1, max_length=255, pattern=r"^[^\s/]+/[^\s/]+$")
     ]
     evidence_id: UUID = Field(strict=True)
-    verification_receipt_id: UUID = Field(strict=True)
-    verification_job_id: UUID = Field(strict=True)
-    verification_generation: Annotated[StrictInt, Field(ge=1)]
     namespace_fingerprint: Sha256
     semantic_manifest_sha256: Sha256
 
diff --git a/backend/app/modules/checkers/api/materialization.py b/backend/app/modules/checkers/api/materialization.py
index ec2e95d6e..6cfd15d82 100644
--- a/backend/app/modules/checkers/api/materialization.py
+++ b/backend/app/modules/checkers/api/materialization.py
@@ -1,5 +1,6 @@
 """Exact post-submit byte access; neither durable execution nor live authority."""
 
+from app.modules.checkers.api.post_material_custody import PostSubmitArtifactCustody
 from dataclasses import dataclass
 from abc import ABC, abstractmethod
 from contextlib import AbstractAsyncContextManager, AbstractContextManager
@@ -14,10 +15,8 @@
 )
 from app.modules.checkers.api.material import SubmissionMaterialEntry
 from app.modules.checkers.api.canonical_values import (
-    CheckerValue,
     ResourceId,
     Sha256,
-    VersionNumber,
 )
 
 from app.modules.checkers.api.evaluation_contract import (
@@ -45,14 +44,11 @@ class PostSubmissionMaterializationFailure(RuntimeError):
     """Retain a known post-authorization material failure after successful cleanup."""
 
 
-class MaterializationMaterialFacts(CheckerValue):
+class MaterializationMaterialFacts(PostSubmitArtifactCustody):
     """Exact selected ancestry without provider coordinates or scratch authority."""
 
     material: VerifiedMaterialFacts
     evidence_id: ResourceId
-    verification_receipt_id: ResourceId
-    verification_job_id: ResourceId
-    verification_generation: VersionNumber
     namespace_fingerprint: Sha256
     semantic_manifest_id: ResourceId
 
diff --git a/backend/app/modules/checkers/api/post_material_custody.py b/backend/app/modules/checkers/api/post_material_custody.py
new file mode 100644
index 000000000..5f461bcf3
--- /dev/null
+++ b/backend/app/modules/checkers/api/post_material_custody.py
@@ -0,0 +1,35 @@
+"""Exact POST archive provenance, excluding provider coordinates and read authority."""
+from pydantic import model_serializer, model_validator
+
+from app.modules.checkers.api.canonical_values import CheckerValue, ResourceId, Sha256, VersionNumber
+
+
+class PostSubmitArtifactCustody(CheckerValue):
+    """One accepted source or retained verified-put witness, never a mixed lineage."""
+
+    verification_receipt_id: ResourceId | None = None
+    verification_job_id: ResourceId | None = None
+    verification_generation: VersionNumber | None = None
+    source_operation_id: ResourceId | None = None
+    accepted_source_sha256: Sha256 | None = None
+    acceptance_receipt_sha256: Sha256 | None = None
+
+    @model_validator(mode="after")
+    def exact_custody(self):
+        verified = (self.verification_receipt_id, self.verification_job_id, self.verification_generation)
+        source = (self.source_operation_id, self.accepted_source_sha256, self.acceptance_receipt_sha256)
+        if not ((all(v is not None for v in verified) and all(v is None for v in source))
+                or (all(v is None for v in verified) and all(v is not None for v in source))):
+            raise ValueError("POST material requires one complete custody witness")
+        return self
+
+    @model_serializer(mode="wrap")
+    def retained_custody_shape(self, handler):
+        """Keep retained canonical evidence byte-for-byte free of new null fields."""
+        body = handler(self)
+        absent = ("source_operation_id", "accepted_source_sha256", "acceptance_receipt_sha256")
+        if self.source_operation_id is not None:
+            absent = ("verification_receipt_id", "verification_job_id", "verification_generation")
+        for field in absent:
+            body.pop(field, None)
+        return body
diff --git a/backend/tests/artifacts/intake_post_support.py b/backend/tests/artifacts/intake_post_support.py
new file mode 100644
index 000000000..c1c83d47f
--- /dev/null
+++ b/backend/tests/artifacts/intake_post_support.py
@@ -0,0 +1,83 @@
+"""T5-to-POST owner integration with real storage and a controlled checker runtime."""
+from types import SimpleNamespace
+from uuid import UUID
+
+from app.adapters.artifacts import post_submission_materialization
+from app.adapters.checkers import evaluation_coordinator
+from app.modules.actors.api import ServiceIdentity
+from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits
+from app.modules.artifacts.preparation import ArtifactPreparationService, ArtifactScratchManager
+from tests.checkers.execution.support import ControlledSelectedExecution, live_executor, provision_post_submit_service
+from tests.test_checker_materialization import _limits
+from tests.trusted_intake_fixtures import LocalIntakeAdapter
+
+
+class ExactSourceStore:
+    def __init__(self, store, expected):
+        self.store, self.expected, self.opens = store, expected, []
+        self.identity = store.identity
+
+    def open(self, *args, **kwargs):
+        raise AssertionError("accepted POST must never use an unversioned object read")
+
+    def open_source(self, source, **kwargs):
+        assert source == self.expected
+        self.opens.append(source)
+        return self.store.open_source(source, **kwargs)
+
+
+async def exercise_source_post(f, created, store, source, tmp_path):
+    """Execute and retain POST with fresh AUTH, exact source I/O and replay."""
+    await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_POST_SUBMIT)
+    await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_MATERIALIZER)
+    async with f.factory.begin() as session:
+        reserved = await evaluation_coordinator(session).read_reserved_evaluation(
+            project_id=UUID(str(f.project)), task_id=UUID(str(f.task)),
+            submission_id=created.submission_id, request_id=created.evaluation_request_id)
+    counted = ExactSourceStore(store, source)
+    scratch = ArtifactScratchManager(root=tmp_path / "post-scratch", limits=_limits())
+    try:
+        service = post_submission_materialization(
+            sessions=f.factory, store=counted, namespace=f.namespace,
+            preparation=ArtifactPreparationService(scratch), intake=LocalIntakeAdapter(),
+            archive_limits=SubmissionArchiveLimits(), artifact_deadline_ms=30_000)
+        runtime = ControlledSelectedExecution()
+        harness = SimpleNamespace(factory=f.factory, service=service, request=reserved.request)
+        executor = live_executor(harness, selected_execution=runtime)
+        result = await executor.evaluate_post_submission(reserved.request)
+        assert result.outcome == "completed"
+        assert len(counted.opens) == len(runtime.requests) == 1
+        material = runtime.requests[0].materials[0]
+        assert material.source_operation_id == source.location.operation_id
+        assert material.verification_receipt_id is None
+        assert "verification_receipt_id" not in material.model_dump(mode="json")
+        assert await executor.evaluate_post_submission(reserved.request) == result
+        assert len(counted.opens) == len(runtime.requests) == 1
+    finally:
+        scratch.close()
+
+
+async def leave_expired_finalizer_claim(f, finalizer, operation_id):
+    """Simulate worker death after claim; a separate delivery cannot compete live."""
+    import asyncio
+    from datetime import timedelta
+    import pytest
+    from sqlalchemy import text
+    from app.core.identifiers import new_record_id
+    from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+
+    finalizer._duration = timedelta(seconds=3)
+    first = await finalizer._claim(operation_id, new_record_id())
+    assert first.generation == 1
+    with pytest.raises(IntakeCustodyConflict, match="finalization_lease_busy"):
+        await finalizer._claim(operation_id, new_record_id())
+    async with asyncio.timeout(15):
+        while True:
+            async with f.factory() as session:
+                remaining = float(await session.scalar(text("SELECT extract(epoch FROM "
+                    "(continuation_expires_at-clock_timestamp())) FROM submission_intake_operations WHERE id=:id"),
+                    {"id": operation_id}))
+            if remaining <= 0:
+                break
+            await asyncio.sleep(min(remaining + 0.02, 0.25))
+    finalizer._duration = timedelta(seconds=60)
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index bf12c246d..dd70de012 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -748,7 +748,8 @@ async def commit(self):
     assert receipt["status"] == "accepted" and receipt["replayed"] is True
 
 
-async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(admission_intake, tmp_path):
+@pytest.mark.parametrize("expired_claim", [False, True])
+async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(admission_intake, tmp_path, expired_claim):
     from datetime import timedelta
     from sqlalchemy import text
     from app.adapters.artifacts import submission_admission_consumption_port
@@ -779,6 +780,9 @@ def submissions(session):
             session, request_id=new_record_id(), correlation_id=owner.operation_id),
     )
     try:
+        if expired_claim:
+            from tests.artifacts.intake_post_support import leave_expired_finalizer_claim
+            await leave_expired_finalizer_claim(f, finalizer, owner.operation_id)
         result = await finalizer.run(owner.operation_id)
         assert await finalizer.run(owner.operation_id) == result
         assert await f.admission.accept(owner, request, terminal.terminal_digest,
@@ -786,6 +790,7 @@ def submissions(session):
         async with f.factory() as session:
             row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
             assert row.state == "finalized" and row.finalized_submission_id == str(result.submission_id)
+            assert row.continuation_generation == (2 if expired_claim else 1)
             task = (await session.execute(text("SELECT status, active_submission_operation_id "
                 "FROM workstream_tasks WHERE id=:id"), {"id": f.task})).one()
             assert task.status == "evaluation_pending" and task.active_submission_operation_id is None
@@ -811,5 +816,30 @@ def submissions(session):
                 async with session.begin():
                     await session.execute(text("UPDATE artifact_replicas SET source_operation_id=NULL "
                         "WHERE source_operation_id=:id"), {"id": owner.operation_id})
+        substitutions = (
+            ("UPDATE artifact_contents SET sha256='sha256:' || repeat('f',64) WHERE id=:id",
+             result.artifact_content_id, "accepted source content is immutable"),
+            ("UPDATE artifact_contents SET byte_count=byte_count+1 WHERE id=:id",
+             result.artifact_content_id, "accepted source content is immutable"),
+            ("UPDATE artifact_contents SET media_type='application/octet-stream' WHERE id=:id",
+             result.artifact_content_id, "accepted source content is immutable"),
+            ("UPDATE artifact_replicas SET adapter='substituted' WHERE source_operation_id=:id",
+             owner.operation_id, "source admission provenance mismatch"),
+        )
+        for statement, identity, message in substitutions:
+            async with f.factory() as session:
+                with pytest.raises(IntegrityError, match=message):
+                    async with session.begin():
+                        await session.execute(text(statement), {"id": identity})
+        from tests.artifacts.intake_post_support import exercise_source_post
+        await exercise_source_post(f, result, store, request.source, tmp_path)
     finally:
         store.close()
+
+
+@pytest.mark.parametrize("duration", [timedelta(0), timedelta(days=3650), timedelta(hours=1, microseconds=1)])
+def test_finalization_rejects_unbounded_or_empty_lease(duration):
+    from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
+    with pytest.raises(ValueError, match="at most one hour"):
+        AcceptedSubmissionFinalization(None, tasks=None, authorization=None, submissions=None,
+            checkers=None, store=None, lease_duration=duration)
diff --git a/backend/tests/checkers/external/test_contracts.py b/backend/tests/checkers/external/test_contracts.py
index 85d16bbfe..d95fb1eb2 100644
--- a/backend/tests/checkers/external/test_contracts.py
+++ b/backend/tests/checkers/external/test_contracts.py
@@ -366,3 +366,44 @@ def test_pre_request_refuses_prepared_bundle_identity():
     value = identity.model_dump() | {"prepared_generation_id": uuid4()}
     with pytest.raises(ValueError, match="prepared_generation_id"):
         type(identity).model_validate(value)
+
+
+def test_post_source_custody_preserves_retained_material_and_closes_new_witness():
+    import json
+    from pathlib import Path
+    from app.modules.checkers.api.external import PostSubmitExternalCheckerMaterial
+    from app.modules.checkers.api.post_material_custody import PostSubmitArtifactCustody
+
+    fixture = Path(__file__).resolve().parents[4] / "external_checkers/fixtures/post_request.json"
+    retained = json.loads(fixture.read_text())["materials"][0]
+    original = PostSubmitExternalCheckerMaterial.model_validate_json(json.dumps(retained))
+    assert original.model_dump(mode="json") == retained
+    source = {k: v for k, v in retained.items() if not k.startswith("verification_")}
+    source.update(source_operation_id=str(new_record_id()), accepted_source_sha256=SHA,
+                  acceptance_receipt_sha256="sha256:" + "b" * 64)
+    material = PostSubmitExternalCheckerMaterial.model_validate_json(json.dumps(source))
+    assert material.model_dump(mode="json") == source
+    assert PostSubmitExternalCheckerMaterial.model_validate_json(material.model_dump_json()) == material
+    witness = {k: v for k, v in source.items() if k in PostSubmitArtifactCustody.model_fields}
+    assert PostSubmitArtifactCustody.model_validate_json(json.dumps(witness)).model_dump(mode="json") == witness
+    for field in witness:
+        with pytest.raises(ValidationError):
+            PostSubmitExternalCheckerMaterial.model_validate_json(json.dumps({k: v for k, v in source.items() if k != field}))
+    for field in ("verification_receipt_id", "verification_job_id", "verification_generation"):
+        with pytest.raises(ValidationError):
+            PostSubmitExternalCheckerMaterial.model_validate_json(json.dumps(source | {field: retained[field]}))
+
+
+def test_source_predecessor_custody_keeps_exact_witness_on_roundtrip():
+    from app.modules.checkers.api.evaluation_context import PostSubmitPredecessorCustody
+    custody = PostSubmitPredecessorCustody(
+        submission_id=new_record_id(), submission_version=1, content_sha256=SHA,
+        byte_count=4, semantic_manifest_sha256=SHA, admission_id=new_record_id(),
+        binding_id=new_record_id(), content_id=new_record_id(), replica_id=new_record_id(),
+        evidence_id=new_record_id(), namespace_fingerprint=SHA, semantic_manifest_id=new_record_id(),
+        source_operation_id=new_record_id(), accepted_source_sha256=SHA, acceptance_receipt_sha256=SHA,
+    )
+    body = custody.model_dump(mode="json")
+    assert not any(key.startswith("verification_") for key in body)
+    assert body["source_operation_id"] == str(custody.source_operation_id)
+    assert PostSubmitPredecessorCustody.model_validate_json(custody.model_dump_json()) == custody
diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py
index 8b83d49c7..3f2d40690 100644
--- a/backend/tests/checkers/external/test_runtime.py
+++ b/backend/tests/checkers/external/test_runtime.py
@@ -422,9 +422,8 @@ async def test_prepared_zip_issues_request_bound_grant_only_inside_callback(tmp_
     )
     inspection = await prepared.inspect(inspector)
     manifest = build_submission_manifest(inspection)
-    identity = execution_identity().model_copy(
-        update={"prepared_generation_id": prepared.generation_id}
-    )
+    # Scratch lifetime is private ART custody, not part of the source PRE wire identity.
+    identity = execution_identity()
     request = _request(
         identity=identity,
         archive_sha256=prepared.commitment.sha256,
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index c00342bde..8c52e8ae3 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "a50cdb610c962d4d9be732549594c6eb77741c633c99472749f5301dcae70449"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "902c5a7b2a0ccbf2a64fadc205db9d69aed03a641e04d8a88ec84bb99b880fe5"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py
index 7f5221cf0..3cd123e39 100644
--- a/backend/tests/test_artifact_architecture.py
+++ b/backend/tests/test_artifact_architecture.py
@@ -264,7 +264,9 @@ def test_only_artifact_custody_services_own_provider_execution() -> None:
             } or (node.name == "ForegroundSourceUpload"
                   and path == APP_ROOT / "modules/artifacts/intake/foreground_upload.py")
                 or (node.name == "_PreSubmitSourceGrant"
-                    and path == APP_ROOT / "modules/artifacts/selected_pre_submit_execution.py"))
+                    and path == APP_ROOT / "modules/artifacts/selected_pre_submit_execution.py")
+                or (node.name == "AcceptedSubmissionFinalization"
+                    and path == APP_ROOT / "modules/artifacts/intake/finalization.py"))
         }
         for node in ast.walk(tree):
             if (
@@ -289,12 +291,13 @@ def test_only_artifact_custody_services_own_provider_execution() -> None:
                     in {
                         "CheckerArtifactOutputService",
                         "ScopedGuideDocumentGrant",
-                        "PostSubmissionMaterializer",
                     }
                     and node.func.attr != "open"
                 ) or (owner.name == "ForegroundSourceUpload" and node.func.attr not in {
                     "begin_source_upload", "complete_source_upload", "observe_source_upload",
-                }) or (owner.name == "_PreSubmitSourceGrant" and node.func.attr != "open_source"):
+                }) or (owner.name == "_PreSubmitSourceGrant" and node.func.attr != "open_source"
+                ) or (owner.name == "PostSubmissionMaterializer" and node.func.attr not in {"open", "open_source"}
+                ) or (owner.name == "AcceptedSubmissionFinalization" and node.func.attr != "observe_sealed_source"):
                     violations.append(f"{path.relative_to(BACKEND_ROOT)} calls {node.func.attr}")
     assert violations == []
 
diff --git a/external_checkers/workstream-checker-sdk/src/lib.rs b/external_checkers/workstream-checker-sdk/src/lib.rs
index ea6f0c099..f9d45a67c 100644
--- a/external_checkers/workstream-checker-sdk/src/lib.rs
+++ b/external_checkers/workstream-checker-sdk/src/lib.rs
@@ -237,30 +237,9 @@ pub fn parse_request(bytes: &[u8]) -> Result {
                 return Err(ContractError("request material identity differs"));
             }
         } else {
-            exact_map(
-                material,
-                &[
-                    "phase",
-                    "role",
-                    "submission_id",
-                    "submission_version",
-                    "binding_id",
-                    "content_id",
-                    "replica_id",
-                    "content_sha256",
-                    "byte_count",
-                    "media_type",
-                    "evidence_id",
-                    "verification_receipt_id",
-                    "verification_job_id",
-                    "verification_generation",
-                    "namespace_fingerprint",
-                    "semantic_manifest_sha256",
-                ],
-            )?;
+            validate_post_material_custody(material)?;
             if unsigned(material, "byte_count")? > i64::MAX as u64
                 || unsigned(material, "submission_version")? == 0
-                || unsigned(material, "verification_generation")? == 0
             {
                 return Err(ContractError("request material is invalid"));
             }
@@ -1239,6 +1218,59 @@ fn exact_object<'a>(
     Ok(object)
 }
 
+/// Validate the closed POST material shape and its one complete custody witness.
+pub fn validate_post_material_custody(material: &Map) -> Result<(), ContractError> {
+    let mut fields = vec![
+        "phase",
+        "role",
+        "submission_id",
+        "submission_version",
+        "binding_id",
+        "content_id",
+        "replica_id",
+        "content_sha256",
+        "byte_count",
+        "media_type",
+        "evidence_id",
+        "namespace_fingerprint",
+        "semantic_manifest_sha256",
+    ];
+    if material.contains_key("source_operation_id") {
+        fields.extend([
+            "source_operation_id",
+            "accepted_source_sha256",
+            "acceptance_receipt_sha256",
+        ]);
+        let operation = string(material, "source_operation_id")?;
+        if operation.len() != 36
+            || !operation.bytes().enumerate().all(|(index, byte)| {
+                if [8, 13, 18, 23].contains(&index) {
+                    byte == b'-'
+                } else {
+                    byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()
+                }
+            })
+        {
+            return Err(ContractError("source operation is invalid"));
+        }
+        digest(material, "accepted_source_sha256")?;
+        digest(material, "acceptance_receipt_sha256")?;
+    } else {
+        fields.extend([
+            "verification_receipt_id",
+            "verification_job_id",
+            "verification_generation",
+        ]);
+        if string(material, "verification_receipt_id")?.is_empty()
+            || string(material, "verification_job_id")?.is_empty()
+            || unsigned(material, "verification_generation")? == 0
+        {
+            return Err(ContractError("verified custody is invalid"));
+        }
+    }
+    exact_map(material, &fields)
+}
+
 fn exact_map(object: &Map, fields: &[&str]) -> Result<(), ContractError> {
     let expected: BTreeSet<_> = fields.iter().copied().collect();
     let actual: BTreeSet<_> = object.keys().map(String::as_str).collect();
@@ -1701,6 +1733,44 @@ mod tests {
         assert!(validate_result(&resign(uppercase_check), &request).is_err());
     }
 
+    #[test]
+    fn post_source_custody_requires_one_complete_witness_for_each_archive() {
+        let mut request = post_context_request("checker_remediation", &[PREDECESSOR_ARCHIVE_ROLE]);
+        for material in request["materials"].as_array_mut().unwrap() {
+            let material = material.as_object_mut().unwrap();
+            for key in [
+                "verification_receipt_id",
+                "verification_job_id",
+                "verification_generation",
+            ] {
+                material.remove(key);
+            }
+            material.insert(
+                "source_operation_id".into(),
+                Value::String("018f6f49-66b8-7d2a-bf4d-0e2eeaa00001".into()),
+            );
+            material.insert(
+                "accepted_source_sha256".into(),
+                Value::String(format!("sha256:{}", "a".repeat(64))),
+            );
+            material.insert(
+                "acceptance_receipt_sha256".into(),
+                Value::String(format!("sha256:{}", "b".repeat(64))),
+            );
+        }
+        let request = resign_request(request);
+        assert!(parse_request(&serde_json::to_vec(&request).unwrap()).is_ok());
+        let mut mixed = request.clone();
+        mixed["materials"][1]["verification_generation"] = Value::from(1);
+        assert!(parse_request(&serde_json::to_vec(&resign_request(mixed)).unwrap()).is_err());
+        let mut incomplete = request;
+        incomplete["materials"][0]
+            .as_object_mut()
+            .unwrap()
+            .remove("acceptance_receipt_sha256");
+        assert!(parse_request(&serde_json::to_vec(&resign_request(incomplete)).unwrap()).is_err());
+    }
+
     #[test]
     fn post_context_closes_roles_source_feedback_and_predecessor_material() {
         let request = post_context_request(
diff --git a/external_checkers/workstream-checker-service/src/main.rs b/external_checkers/workstream-checker-service/src/main.rs
index 6bc6218b7..8030a0f23 100644
--- a/external_checkers/workstream-checker-service/src/main.rs
+++ b/external_checkers/workstream-checker-service/src/main.rs
@@ -1724,33 +1724,9 @@ fn validate_post_grant_material(item: &PostGrantMaterial) -> Result<&str, String
         .material
         .as_object()
         .ok_or("POST grant material invalid")?;
-    let expected: std::collections::BTreeSet<_> = [
-        "phase",
-        "role",
-        "submission_id",
-        "submission_version",
-        "binding_id",
-        "content_id",
-        "replica_id",
-        "content_sha256",
-        "byte_count",
-        "media_type",
-        "evidence_id",
-        "verification_receipt_id",
-        "verification_job_id",
-        "verification_generation",
-        "namespace_fingerprint",
-        "semantic_manifest_sha256",
-    ]
-    .into_iter()
-    .collect();
-    if material
-        .keys()
-        .map(String::as_str)
-        .collect::>()
-        != expected
-        || material.get("phase").and_then(Value::as_str) != Some("post_submit")
-    {
+    workstream_checker_sdk::validate_post_material_custody(material)
+        .map_err(|_| "POST grant material custody invalid")?;
+    if material.get("phase").and_then(Value::as_str) != Some("post_submit") {
         return Err("POST grant material invalid".into());
     }
     let role = material
@@ -1759,10 +1735,6 @@ fn validate_post_grant_material(item: &PostGrantMaterial) -> Result<&str, String
         .ok_or("POST grant material role invalid")?;
     if !matches!(role, CURRENT_ARCHIVE_ROLE | PREDECESSOR_ARCHIVE_ROLE)
         || material.get("submission_version").and_then(Value::as_u64) == Some(0)
-        || material
-            .get("verification_generation")
-            .and_then(Value::as_u64)
-            == Some(0)
         || !material
             .get("byte_count")
             .and_then(Value::as_u64)
@@ -1780,8 +1752,6 @@ fn validate_post_grant_material(item: &PostGrantMaterial) -> Result<&str, String
         "content_id",
         "replica_id",
         "evidence_id",
-        "verification_receipt_id",
-        "verification_job_id",
     ] {
         if !material
             .get(field)
@@ -4897,6 +4867,47 @@ exit 2
         }
     }
 
+    #[test]
+    fn post_grant_source_custody_rejects_mixed_or_missing_evidence() {
+        let (_, mut manifest) = post_grant_fixture(false, false, false);
+        let item = &mut manifest.materials[0];
+        let material = item.material.as_object_mut().unwrap();
+        for key in [
+            "verification_receipt_id",
+            "verification_job_id",
+            "verification_generation",
+        ] {
+            material.remove(key);
+        }
+        material.insert(
+            "source_operation_id".into(),
+            Value::String("018f6f49-66b8-7d2a-bf4d-0e2eeaa00001".into()),
+        );
+        material.insert(
+            "accepted_source_sha256".into(),
+            Value::String(format!("sha256:{}", "a".repeat(64))),
+        );
+        material.insert(
+            "acceptance_receipt_sha256".into(),
+            Value::String(format!("sha256:{}", "b".repeat(64))),
+        );
+        assert_eq!(
+            validate_post_grant_material(item).unwrap(),
+            CURRENT_ARCHIVE_ROLE
+        );
+        item.material["verification_generation"] = Value::from(1);
+        assert!(validate_post_grant_material(item).is_err());
+        item.material
+            .as_object_mut()
+            .unwrap()
+            .remove("verification_generation");
+        item.material
+            .as_object_mut()
+            .unwrap()
+            .remove("accepted_source_sha256");
+        assert!(validate_post_grant_material(item).is_err());
+    }
+
     #[test]
     fn post_grant_v2_binds_context_roles_and_all_aggregate_inventories() {
         let (root, config) = test_config();

From 06fe9027efbc9d0404bd850a3982aae0beac1400 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 21:25:53 +0100
Subject: [PATCH 116/513] Prove source-backed POST uses the sealed MinIO object
 version

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 39 ++++++++++
 backend/scripts/test_lane_catalogue.py        |  1 +
 .../artifacts/intake_acceptance_support.py    |  3 +-
 .../tests/artifacts/intake_post_support.py    | 42 ++++++++--
 .../test_submission_intake_admission.py       |  7 +-
 .../test_submission_source_post_minio.py      | 77 +++++++++++++++++++
 backend/tests/test_ci_lane_catalogue.py       |  4 +-
 7 files changed, 161 insertions(+), 12 deletions(-)
 create mode 100644 backend/tests/artifacts/test_submission_source_post_minio.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 352e503b8..0e2c92f2f 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2836,3 +2836,42 @@ actual POST; real source-backed revision routing/preparation/POST; rollback/lost
 acknowledgement/concurrency expansions; durable finalization outbox/Celery wiring
 and operational stall projection; public API/CLI/MCP cutover and the complete
 A01–A35/C01–C07 audit. No merge or overall readiness is claimed by this checkpoint.
+
+Scoped ARCH/SEC and QA review passed for committed `15c8945f0`, including the
+content/adapter repairs, exact source POST path, lease ceiling and generation-2
+recovery. Reviewers inspected the frozen commit; later parent-authored MinIO test
+edits did not enter that verdict. No native or complete-goal qualification follows.
+
+The provider integration extension reuses the same T1/PRE/T5/POST owners with a
+versioned real MinIO namespace. After T5 it writes different invalid ZIP bytes to
+the same key. The positive case must GET the recorded VersionId and complete POST;
+the negative removes that recorded version and must retain infrastructure failure
+without invoking the checker or falling back to the newer version. Both must replay
+without another read. The test is registered in the existing MinIO-enabled lane.
+The first local launch collided with that lane's fixed bucket before tests started;
+read-only health/credential probes established a healthy provider and existing
+bucket. The rerun uses the runner's unique-bucket mode rather than deleting shared
+storage. This setup failure is excluded from behavioral evidence.
+
+The MinIO rerun passed both scenarios (**2 passed**, `/tmp/post-source-minio2.log`;
+metadata `/tmp/post-source-minio2.json` records database and bucket cleanup).
+The positive path executed POST against the original version after replacement;
+the missing-original path persisted infrastructure failure with zero checker
+invocations. Each made exactly one version-qualified GET; POST and finalization
+replay added no reads. This proves real MinIO storage behavior with controlled
+checker execution, not native Smol or AWS qualification. CI lane/catalogue checks
+pass **76 tests** after updating the independent shared-family fingerprint for
+the one newly registered module.
+
+The next implementation boundary is durable delivery of the already committed
+`SubmissionFinalizationRequested` event. Allowed scope: ART finalization and its
+delivery adapter, existing OUTBOX composition/worker routing, focused integration
+tests and this record. Preserve the single T5 operation and existing delivery
+owner; prohibit provider-body I/O in finalization, contributor-token reuse,
+publication-only acknowledgement and fabricated deployment defaults. Acceptance
+requires committed invocation observation, exact event/evidence matching, a
+transactional invocation fence on claim and effect, bounded continuation custody,
+and replay after committed T5 without another provider observation. Worker routing
+and stalled progress must subsequently be proved through the durable owners.
+This is high-risk workflow/authorization work requiring architecture/security and
+QA review, with human review focused on lock order, expiry and acknowledgement.
diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py
index 35dea3854..2119ec6d9 100644
--- a/backend/scripts/test_lane_catalogue.py
+++ b/backend/scripts/test_lane_catalogue.py
@@ -822,6 +822,7 @@ class TestLane:
             "tests/test_project_agent_sdk_installation.py",
             "tests/test_s3_artifact_store.py",
             "tests/artifacts/test_sealed_source_observation.py",
+            "tests/artifacts/test_submission_source_post_minio.py",
         ),
         sdk_environment="omnicore",
     ),
diff --git a/backend/tests/artifacts/intake_acceptance_support.py b/backend/tests/artifacts/intake_acceptance_support.py
index fafbc2648..9871bc1de 100644
--- a/backend/tests/artifacts/intake_acceptance_support.py
+++ b/backend/tests/artifacts/intake_acceptance_support.py
@@ -29,7 +29,8 @@ async def completed_source(f, tmp_path):
     payload = _archive()
     async def body():
         yield payload
-    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    store = (f.source_store_factory() if getattr(f, "source_store_factory", None) else
+             initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024))
     try:
         source = await foreground_upload(f, store).receive(
             owner.operation_id, owner.lease_id, owner.generation, body(), **foreground_limits())
diff --git a/backend/tests/artifacts/intake_post_support.py b/backend/tests/artifacts/intake_post_support.py
index c1c83d47f..c3fbe6886 100644
--- a/backend/tests/artifacts/intake_post_support.py
+++ b/backend/tests/artifacts/intake_post_support.py
@@ -26,7 +26,7 @@ def open_source(self, source, **kwargs):
         return self.store.open_source(source, **kwargs)
 
 
-async def exercise_source_post(f, created, store, source, tmp_path):
+async def exercise_source_post(f, created, store, source, tmp_path, *, missing=False):
     """Execute and retain POST with fresh AUTH, exact source I/O and replay."""
     await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_POST_SUBMIT)
     await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_MATERIALIZER)
@@ -45,14 +45,17 @@ async def exercise_source_post(f, created, store, source, tmp_path):
         harness = SimpleNamespace(factory=f.factory, service=service, request=reserved.request)
         executor = live_executor(harness, selected_execution=runtime)
         result = await executor.evaluate_post_submission(reserved.request)
-        assert result.outcome == "completed"
-        assert len(counted.opens) == len(runtime.requests) == 1
-        material = runtime.requests[0].materials[0]
-        assert material.source_operation_id == source.location.operation_id
-        assert material.verification_receipt_id is None
-        assert "verification_receipt_id" not in material.model_dump(mode="json")
+        assert result.outcome == ("infrastructure_failed" if missing else "completed")
+        assert len(counted.opens) == 1
+        assert len(runtime.requests) == (0 if missing else 1)
+        if not missing:
+            material = runtime.requests[0].materials[0]
+            assert material.source_operation_id == source.location.operation_id
+            assert material.verification_receipt_id is None
+            assert "verification_receipt_id" not in material.model_dump(mode="json")
         assert await executor.evaluate_post_submission(reserved.request) == result
-        assert len(counted.opens) == len(runtime.requests) == 1
+        assert len(counted.opens) == 1
+        assert len(runtime.requests) == (0 if missing else 1)
     finally:
         scratch.close()
 
@@ -81,3 +84,26 @@ async def leave_expired_finalizer_claim(f, finalizer, operation_id):
                 break
             await asyncio.sleep(min(remaining + 0.02, 0.25))
     finalizer._duration = timedelta(seconds=60)
+
+
+async def minio_source_fixture():
+    """Create a versioned test namespace and a reopenable provider factory."""
+    from app.adapters.artifacts import create_artifact_store_bootstrap
+    from app.core.identifiers import new_record_id
+    from app.interfaces.artifacts import ArtifactStoreNamespaceClaim
+    from app.modules.artifacts.service import artifact_storage_namespace_spec
+    from tests.test_s3_artifact_store import MINIO_BUCKET, minio_settings, provision_minio_bucket
+    await provision_minio_bucket.__wrapped__()
+    settings = minio_settings(private_prefix=f"post-source/{new_record_id()}", buffer_bytes=65536)
+    bootstrap = create_artifact_store_bootstrap(settings, activation_guard=None)
+    namespace = artifact_storage_namespace_spec(settings, bootstrap)
+    def factory():
+        return bootstrap.initialize_after_namespace_claim(ArtifactStoreNamespaceClaim(
+            bootstrap.identity, bootstrap.namespace_identity, namespace.namespace_fingerprint))
+    store = factory()
+    try:
+        async with store._client() as client:
+            await client.put_bucket_versioning(Bucket=MINIO_BUCKET, VersioningConfiguration={"Status": "Enabled"})
+    finally:
+        store.close()
+    return namespace, factory
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index dd70de012..c9abca4af 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -39,6 +39,10 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
     engine = create_async_engine(isolated_database_env)
     factory = async_sessionmaker(engine, expire_on_commit=False)
     namespace = _namespace(_settings(tmp_path))
+    source_store_factory = None
+    if getattr(request, "param", None) == "minio":
+        from tests.artifacts.intake_post_support import minio_source_fixture
+        namespace, source_store_factory = await minio_source_fixture()
     if getattr(request, "param", None) == "aws":
         from app.interfaces.artifacts import ArtifactStoreNamespaceIdentity, artifact_store_namespace_material
         from app.interfaces.external_services import ExternalServiceAdapterIdentity
@@ -77,7 +81,8 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
         )
         yield SimpleNamespace(factory=factory, actor=actor, task=task, assignment=assignment,
                               admission=admission, project=project, namespace=namespace,
-                              access=admin_access, manager=manager, grant_id=grant_id)
+                              access=admin_access, manager=manager, grant_id=grant_id,
+                              source_store_factory=source_store_factory)
     finally:
         await engine.dispose()
 
diff --git a/backend/tests/artifacts/test_submission_source_post_minio.py b/backend/tests/artifacts/test_submission_source_post_minio.py
new file mode 100644
index 000000000..f6efc165a
--- /dev/null
+++ b/backend/tests/artifacts/test_submission_source_post_minio.py
@@ -0,0 +1,77 @@
+"""Real MinIO T1/PRE/T5/POST proof excludes newer same-key source versions."""
+from contextlib import asynccontextmanager
+from datetime import timedelta
+
+import pytest
+
+from app.adapters.artifacts import submission_admission_consumption_port
+from app.adapters.checkers import selected_pre_submit_coordinator
+from app.adapters.outbox import outbox_append
+from app.adapters.tasks import accepted_submission_creation_service
+from app.core.identifiers import new_record_id
+from app.modules.actors.api import ServiceIdentity
+from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
+from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
+from tests.artifacts.intake_acceptance_support import completed_source
+from tests.artifacts.intake_post_support import exercise_source_post
+from tests.artifacts.test_submission_intake_admission import (
+    admission_intake as admission_intake,
+    admin_access as admin_access,
+    auth_database_env as auth_database_env,
+    clear_settings_cache as clear_settings_cache,
+    rsa_signing_material as rsa_signing_material,
+    signed_access as signed_access,
+)
+from tests.checkers.execution.support import provision_post_submit_service
+from tests.test_artifact_admission import _settings
+from tests.test_s3_artifact_store import MINIO_BUCKET
+
+
+@pytest.mark.parametrize("admission_intake", ["minio"], indirect=True)
+@pytest.mark.parametrize("remove_original", [False, True])
+async def test_post_uses_recorded_version_despite_newer_same_key(admission_intake, tmp_path, monkeypatch, remove_original):
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_BINDING)
+    store = f.source_store_factory()
+    def submissions(session):
+        return accepted_submission_creation_service(session, settings=_settings(tmp_path),
+            admissions=submission_admission_consumption_port(session,
+                request_id=new_record_id(), correlation_id=owner.operation_id))
+    finalizer = AcceptedSubmissionFinalization(
+        f.factory, tasks=f.admission._tasks, submissions=submissions,
+        checkers=selected_pre_submit_coordinator, store=store, lease_duration=timedelta(seconds=60),
+        authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
+            session, request_id=new_record_id(), correlation_id=owner.operation_id))
+    try:
+        created = await finalizer.run(owner.operation_id)
+        source = request.source
+        original_client = store._client
+        async with original_client() as client:
+            newer = await client.put_object(Bucket=MINIO_BUCKET, Key=store._source_key(source.location),
+                                           Body=b"a different, invalid ZIP")
+            assert newer["VersionId"] != source.provider_generation
+            if remove_original:
+                await client.delete_object(Bucket=MINIO_BUCKET, Key=store._source_key(source.location),
+                                           VersionId=source.provider_generation)
+        reads = []
+        class ReadOnlyClient:
+            def __init__(self, client):
+                self.client = client
+            async def get_object(self, **kwargs):
+                reads.append(kwargs)
+                return await self.client.get_object(**kwargs)
+        @asynccontextmanager
+        async def recorded_reads():
+            async with original_client() as client:
+                yield ReadOnlyClient(client)
+        monkeypatch.setattr(store, "_client", recorded_reads)
+        await exercise_source_post(f, created, store, source, tmp_path, missing=remove_original)
+        assert reads == [dict(Bucket=MINIO_BUCKET, Key=store._source_key(source.location),
+                              VersionId=source.provider_generation)]
+        assert await finalizer.run(owner.operation_id) == created
+        assert len(reads) == 1
+    finally:
+        store.close()
diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py
index cf65fc718..45582f7da 100644
--- a/backend/tests/test_ci_lane_catalogue.py
+++ b/backend/tests/test_ci_lane_catalogue.py
@@ -318,8 +318,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None:
     """A catalogue-internal move across semantic families must fail this contract."""
     expected = {
         "shared": (
-            273,
-            "9310a4ccbe9b8d842190a644403c72683ce321f4f7ef83cf35545ab965e17bf1",
+            274,
+            "70b7428794e138bb1f58e9506a5e68ff87c9822bd3c7dc0132d52a1beecf559d",
         ),
         "project": (
             256,

From a8662f03fa5025f1a6b18c9da50fcefbec06f997 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 22:09:57 +0100
Subject: [PATCH 117/513] Clarify MinIO proof and CI fingerprint provenance

---
 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 0e2c92f2f..65edda7ba 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2860,8 +2860,12 @@ the missing-original path persisted infrastructure failure with zero checker
 invocations. Each made exactly one version-qualified GET; POST and finalization
 replay added no reads. This proves real MinIO storage behavior with controlled
 checker execution, not native Smol or AWS qualification. CI lane/catalogue checks
-pass **76 tests** after updating the independent shared-family fingerprint for
-the one newly registered module.
+pass **76 tests** after correcting a pre-existing stale shared-family fingerprint.
+The new MinIO module belongs only to `omnicore_sdk`; it did not change shared-family
+membership. Scoped QA and CI integrity review of `06fe9027e` found no blocking
+defect and confirmed both cases are collected; removing the module from the lane
+triggers `missing_lane_modules`. The provider run is worktree evidence based on
+`15c8945f0`, not an exact-head rerun of `06fe9027e`.
 
 The next implementation boundary is durable delivery of the already committed
 `SubmissionFinalizationRequested` event. Allowed scope: ART finalization and its

From 3fdbc820a8d1d91d295bd93fbd7bc0dd5fd09e9c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 22:22:35 +0100
Subject: [PATCH 118/513] Deliver accepted finalization through fenced durable
 outbox invocations

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 39 +++++++++
 .../0076_submission_delivery_retry.py         | 26 ++++++
 .../app/adapters/artifacts/finalization.py    | 56 +++++++++++++
 backend/app/adapters/outbox/__init__.py       | 14 +++-
 .../modules/artifacts/intake/finalization.py  | 27 +++---
 .../artifacts/intake/finalization_delivery.py | 61 ++++++++++++++
 .../test_submission_intake_admission.py       | 83 +++++++++++++++++++
 backend/tests/conftest.py                     |  2 +-
 8 files changed, 295 insertions(+), 13 deletions(-)
 create mode 100644 backend/alembic/versions/0076_submission_delivery_retry.py
 create mode 100644 backend/app/adapters/artifacts/finalization.py
 create mode 100644 backend/app/modules/artifacts/intake/finalization_delivery.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 65edda7ba..22e3b231a 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2879,3 +2879,42 @@ and replay after committed T5 without another provider observation. Worker routi
 and stalled progress must subsequently be proved through the durable owners.
 This is high-risk workflow/authorization work requiring architecture/security and
 QA review, with human review focused on lock order, expiry and acknowledgement.
+
+The delivery implementation now registers the accepted event with the existing
+production OUTBOX owner. Its handler requires an independently committed current
+invocation. Every finalization claim, effect and unknown-commit recovery locks
+TASK/operation, authorizes the fixed service, validates the exact accepted event
+and acquires the existing OUTBOX invocation fence in that transaction. Continuation
+expiry cannot exceed the delivery claim. Finalized replay validates retained
+associations before provider access; the worker adapter initializes storage lazily
+only for source metadata observation. UNKNOWN delivery uses OUTBOX's existing
+explicit replay-safe registration and bounded retry machinery.
+
+The composition reuses the existing `DeliveryOptions` convention (300-second lease,
+240-second handler timeout, five attempts, 5-second exponential retry base capped
+at 300 seconds) for this bounded metadata/SQL operation. These values are not a
+new measured deployment qualification. Separate finalization capacity, visible
+operation stalls and operator retry authority remain required under C04/C05.
+The focused PostgreSQL test exercises the same adapter through actual OUTBOX
+claim/invoke/finalize, simulates failure after T5 commits, and requires a second
+delivery to acknowledge without another provider observation.
+
+The first integrated run reached committed T5 but SQL refused retry of UNKNOWN
+for this event: Python registration alone did not satisfy the database's closed
+feature list. Migration 0076 extends that exact list only for version-1 submission
+finalization. The public schema fingerprint was updated from the actual migrated
+database; no schema guard was bypassed.
+
+The repaired real PostgreSQL run passed **2 tests** (`/tmp/t5-delivery2.log`, metadata
+`/tmp/t5-delivery2.json`). Loss after T5 commits replays the same Submission with one
+provider observation. Loss during observation fences the first finalizer before
+T5, retains pending custody, and allows generation-2 recovery after lease expiry.
+Both acknowledge only the replacement invocation; stale invocation replay is
+rejected. Production candidate discovery includes the accepted event. The existing
+generic-event SQL refusal test also passed (`/tmp/t5-delivery-negative.log`, matching
+metadata JSON), proving UNKNOWN retry remains closed for unregistered events.
+Earlier ordinary/expired-claim T5 cases passed in `/tmp/t5-delivery1.log`; its new
+delivery case failed before the migration and is not counted as a success.
+Architecture/outbox contracts/topology passed **117 tests**; changed-file Ruff,
+structure and Markdown-link checks passed. These are scoped worktree results,
+not complete durable-worker or public-journey qualification.
diff --git a/backend/alembic/versions/0076_submission_delivery_retry.py b/backend/alembic/versions/0076_submission_delivery_retry.py
new file mode 100644
index 000000000..682d94137
--- /dev/null
+++ b/backend/alembic/versions/0076_submission_delivery_retry.py
@@ -0,0 +1,26 @@
+"""Permit uncertain accepted-finalization delivery to replay exact T5 custody."""
+
+from alembic import op
+from sqlalchemy import text
+
+revision = "0076_submission_delivery_retry"
+down_revision = "0075_source_post_custody"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.outbox_events IN SHARE ROW EXCLUSIVE MODE")
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef('public.check_outbox_delivery_projection()'::regprocedure)"
+    )).scalar_one()
+    old = "e.event_type not in ('TaskRevisionExpiryRequested','TaskRevisionExpired')"
+    new = "e.event_type not in ('TaskRevisionExpiryRequested','TaskRevisionExpired','SubmissionFinalizationRequested')"
+    if body.count(old) != 1:
+        raise RuntimeError("submission delivery retry predecessor shape changed")
+    op.execute(body.replace(old, new))
+
+
+def downgrade():
+    raise RuntimeError("Retained finalization retry custody cannot be downgraded")
diff --git a/backend/app/adapters/artifacts/finalization.py b/backend/app/adapters/artifacts/finalization.py
new file mode 100644
index 000000000..e17b80957
--- /dev/null
+++ b/backend/app/adapters/artifacts/finalization.py
@@ -0,0 +1,56 @@
+"""Compose accepted finalization through the existing TASK/ART/CHECKERS owners."""
+
+from datetime import timedelta
+
+from app.core.identifiers import new_record_id
+from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
+from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
+from app.modules.artifacts.intake.finalization_delivery import (
+    FinalizationInvocation, SubmissionFinalizationHandler,
+)
+
+
+def submission_finalization_handler(*, sessions, settings, store, lease_duration):
+    from app.adapters.artifacts import submission_admission_consumption_port
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import committed_invocation_reader, outbox_invocation_fence
+    from app.adapters.tasks import accepted_submission_creation_service, intake_task_custody_port
+
+    def finalizer(envelope):
+        operation_id = envelope.aggregate_id
+        def submissions(session):
+            return accepted_submission_creation_service(session, settings=settings,
+                admissions=submission_admission_consumption_port(session,
+                    request_id=new_record_id(), correlation_id=operation_id))
+        return AcceptedSubmissionFinalization(
+            sessions, tasks=intake_task_custody_port, submissions=submissions,
+            checkers=selected_pre_submit_coordinator, store=store, lease_duration=lease_duration,
+            authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
+                session, request_id=new_record_id(), correlation_id=operation_id),
+            delivery=FinalizationInvocation(envelope, outbox_invocation_fence),
+        )
+    return SubmissionFinalizationHandler(
+        observer=committed_invocation_reader(sessions), finalizer=finalizer,
+    )
+
+
+class _WorkerSourceObservation:
+    """Initialize the provider only when an unfinalized operation needs metadata."""
+
+    async def observe_sealed_source(self, source):
+        from app.adapters.artifacts.internal_workers import (
+            _artifact_internal_runtime, _artifact_worker_database,
+            initialize_artifact_internal_runtime,
+        )
+        async with _artifact_worker_database():
+            await initialize_artifact_internal_runtime()
+            with _artifact_internal_runtime() as (store, _namespace):
+                return await store.observe_sealed_source(source)
+
+
+def worker_submission_finalization_handler(*, sessions, delivery_options):
+    from app.core.config import get_settings
+    return submission_finalization_handler(
+        sessions=sessions, settings=get_settings(), store=_WorkerSourceObservation(),
+        lease_duration=timedelta(seconds=delivery_options.lease_seconds),
+    )
diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py
index 4567eb84c..14978dcd1 100644
--- a/backend/app/adapters/outbox/__init__.py
+++ b/backend/app/adapters/outbox/__init__.py
@@ -44,8 +44,9 @@ def outbox_delivery(
 
 
 def production_outbox_delivery(session_factory):
-    """Install exact assignment and selected evaluation handlers."""
+    """Install assignment, accepted finalization and selected evaluation handlers."""
     from app.adapters.artifacts import worker_post_submission_materialization
+    from app.adapters.artifacts.finalization import worker_submission_finalization_handler
     from app.adapters.auth import (
         outbox_dispatch_authorization,
         assignment_invalidation_authorization,
@@ -75,11 +76,19 @@ def production_outbox_delivery(session_factory):
         REVISION_EXPIRY_EVENT, REVISION_EXPIRED_EVENT, REVISION_CONTEXT_BLOCKED_EVENT,
     )
 
+    finalization_options = DeliveryOptions()
     return outbox_delivery(
         session_factory,
         authorization_factory=outbox_dispatch_authorization,
         registry=HandlerRegistry(
             [
+                (
+                    "SubmissionFinalizationRequested",
+                    1,
+                    worker_submission_finalization_handler(
+                        sessions=session_factory, delivery_options=finalization_options,
+                    ),
+                ),
                 (
                     ASSIGNMENT_INVALIDATION_EVENT,
                     1,
@@ -148,10 +157,11 @@ def production_outbox_delivery(session_factory):
                     ),
                 ),
             ],
-            replay_safe=frozenset({(REVISION_EXPIRY_EVENT, 1), (REVISION_EXPIRED_EVENT, 1), (REVISION_CONTEXT_BLOCKED_EVENT, 1), (REVISION_EXHAUSTED_EVENT, 1)}),
+            replay_safe=frozenset({("SubmissionFinalizationRequested", 1), (REVISION_EXPIRY_EVENT, 1), (REVISION_EXPIRED_EVENT, 1), (REVISION_CONTEXT_BLOCKED_EVENT, 1), (REVISION_EXHAUSTED_EVENT, 1)}),
         ),
         options=DeliveryOptions(),
         event_options={
+            ("SubmissionFinalizationRequested", 1): finalization_options,
             (REQUEST_EVENT, 1): DeliveryOptions(
                 lease_seconds=SELECTED_POST_DELIVERY_LEASE_SECONDS,
                 handler_timeout_seconds=SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
diff --git a/backend/app/modules/artifacts/intake/finalization.py b/backend/app/modules/artifacts/intake/finalization.py
index 55b4c3256..47bf99bfe 100644
--- a/backend/app/modules/artifacts/intake/finalization.py
+++ b/backend/app/modules/artifacts/intake/finalization.py
@@ -39,7 +39,7 @@ def continuation_facts(row, lease_id, generation):
 class AcceptedSubmissionFinalization:
     """Keep provider I/O outside TASK locks; finalized replay precedes new claims."""
 
-    def __init__(self, sessions, *, tasks, authorization, submissions, checkers, store, lease_duration):
+    def __init__(self, sessions, *, tasks, authorization, submissions, checkers, store, lease_duration, delivery=None):
         # Match the durable outbox's one-hour structural lease ceiling. This is
         # not a deployment default; composition must still supply its profile.
         if not isinstance(lease_duration, timedelta) or not timedelta(0) < lease_duration <= timedelta(hours=1):
@@ -47,6 +47,7 @@ def __init__(self, sessions, *, tasks, authorization, submissions, checkers, sto
         self._sessions, self._tasks, self._authorization = sessions, tasks, authorization
         self._submissions, self._store, self._duration = submissions, store, lease_duration
         self._checkers = checkers
+        self._delivery = delivery
 
     @asynccontextmanager
     async def _root(self):
@@ -82,14 +83,19 @@ async def run(self, operation_id: UUID) -> SubmissionCreationResult:
             return await self._finalize(operation_id, claim, observation)
         except IntakeCommitUnknown:
             async with self._root() as (session, authority):
-                row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(operation_id)
-                await authority.authorize()
+                row = await self._lock(session, authority, operation_id)
                 return await self._finalized(session, row)
 
+    async def _lock(self, session, authority, operation_id):
+        row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(operation_id)
+        await authority.authorize()
+        if self._delivery is not None:
+            await self._delivery.fence(session, row)
+        return row
+
     async def _claim(self, operation_id, lease_id):
         async with self._root() as (session, authority):
-            row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(operation_id)
-            await authority.authorize()
+            row = await self._lock(session, authority, operation_id)
             if row.state == "finalized":
                 return await self._finalized(session, row)
             if row.state != "finalization_pending":
@@ -106,14 +112,16 @@ async def _claim(self, operation_id, lease_id):
             if not isinstance(decision, UUID):
                 raise IntakeCustodyConflict("finalization_authority_unavailable")
             row.continuation_lease_id, row.continuation_generation = str(lease_id), generation
-            row.continuation_expires_at, row.continuation_decision_id = now + self._duration, str(decision)
+            expires_at = now + self._duration
+            if self._delivery is not None:
+                expires_at = min(expires_at, self._delivery.envelope.claim.claim_expires_at)
+            row.continuation_expires_at, row.continuation_decision_id = expires_at, str(decision)
             await session.flush()
             return AcceptedContinuation(SubmissionIntakeRepository._sealed_source(row), lease_id, generation)
 
     async def _recover_claim(self, operation_id, lease_id):
         async with self._root() as (session, authority):
-            row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(operation_id)
-            await authority.authorize()
+            row = await self._lock(session, authority, operation_id)
             if row.state == "finalized":
                 return await self._finalized(session, row)
             now = await session.scalar(select(func.clock_timestamp()))
@@ -131,8 +139,7 @@ async def _recover_claim(self, operation_id, lease_id):
     async def _finalize(self, operation_id: UUID, claim: AcceptedContinuation, observation: SealedSourceObservation):
         async with self._root() as (session, authority):
             tasks = self._tasks(session)
-            row = await SubmissionIntakeRepository(session, tasks)._lock(operation_id)
-            await authority.authorize()
+            row = await self._lock(session, authority, operation_id)
             if row.state == "finalized":
                 return await self._finalized(session, row)
             now = await session.scalar(select(func.clock_timestamp()))
diff --git a/backend/app/modules/artifacts/intake/finalization_delivery.py b/backend/app/modules/artifacts/intake/finalization_delivery.py
new file mode 100644
index 000000000..f0dbb40e4
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/finalization_delivery.py
@@ -0,0 +1,61 @@
+"""Exact accepted-event custody for the existing finalization operation."""
+
+from dataclasses import dataclass
+from collections.abc import Callable
+import json
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.hashing import canonical_json_hash
+from app.modules.artifacts.intake.acceptance import finalization_event
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+from app.modules.outbox.api import HandlerOutcome, InvocationFencePort, OutboxEventEnvelope
+
+
+@dataclass(frozen=True)
+class FinalizationInvocation:
+    """An invocation is evidence to recheck, never feature authorization."""
+
+    envelope: OutboxEventEnvelope
+    fence_factory: Callable[[AsyncSession], InvocationFencePort]
+
+    async def fence(self, session, row):
+        expected = finalization_event(row)
+        envelope = self.envelope
+        if (
+            str(envelope.claim.event_id) != row.finalization_event_id
+            or str(envelope.claim.project_id) != row.project_id
+            or any(getattr(envelope, key) != getattr(expected, key) for key in (
+                "event_type", "event_version", "aggregate_type", "aggregate_id",
+                "correlation_id", "causation_event_id", "idempotency_key",
+            ))
+            or envelope.payload_json != json.dumps(expected.payload, sort_keys=True,
+                separators=(",", ":"), ensure_ascii=False, allow_nan=False)
+            or envelope.claim.payload_digest != canonical_json_hash(expected.payload)
+        ):
+            raise IntakeCustodyConflict("finalization_delivery_mismatch")
+        observed = await self.fence_factory(session).fence_invocation(envelope)
+        if observed is None or observed.claim != envelope.claim:
+            raise IntakeCustodyConflict("finalization_delivery_stale")
+
+
+class SubmissionFinalizationHandler:
+    """Acknowledge only after T5 or its exact committed replay succeeds."""
+
+    def __init__(self, *, observer, finalizer):
+        self._observer, self._finalizer = observer, finalizer
+
+    async def __call__(self, envelope):
+        try:
+            envelope = OutboxEventEnvelope.model_validate(envelope.model_dump())
+        except (AttributeError, TypeError, ValueError):
+            return HandlerOutcome.REJECT
+        if envelope.event_type != "SubmissionFinalizationRequested" or envelope.event_version != 1:
+            return HandlerOutcome.REJECT
+        observed = await self._observer.observe_invocation(envelope)
+        if observed is None or observed.claim != envelope.claim:
+            return HandlerOutcome.REJECT
+        # Exceptions remain uncertain to OUTBOX; replay uses the same accepted
+        # evidence and observes a committed T5 before any provider access.
+        await self._finalizer(envelope).run(envelope.aggregate_id)
+        return HandlerOutcome.ACKNOWLEDGE
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index c9abca4af..6a1613fae 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -848,3 +848,86 @@ def test_finalization_rejects_unbounded_or_empty_lease(duration):
     with pytest.raises(ValueError, match="at most one hour"):
         AcceptedSubmissionFinalization(None, tasks=None, authorization=None, submissions=None,
             checkers=None, store=None, lease_duration=duration)
+
+
+@pytest.mark.parametrize("lost_at", ["after_commit", "during_observation"])
+async def test_finalization_outbox_recovers_lost_ack_without_provider_replay(admission_intake, tmp_path, lost_at):
+    from uuid import UUID
+    from sqlalchemy import select, func
+    from app.adapters.artifacts.finalization import submission_finalization_handler
+    from app.adapters.auth import outbox_dispatch_authorization
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append, outbox_delivery, production_outbox_delivery
+    from app.modules.actors.api import ServiceIdentity
+    from app.modules.outbox.api import DeliveryOptions, FinalizationCause, HandlerOutcome
+    from app.modules.outbox.models import OutboxEvent
+    from app.modules.outbox.registry import HandlerRegistry
+    from tests.artifact_store_helpers import initialize_local_store
+    from tests.artifacts.intake_acceptance_support import completed_source
+    from tests.checkers.execution.support import provision_post_submit_service
+
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER):
+        await provision_post_submit_service(f.factory, identity)
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    observations, invocations = [], []
+    class ObservedStore:
+        async def observe_sealed_source(self, source):
+            observations.append(source)
+            if lost_at == "during_observation" and len(observations) == 1:
+                await delivery.finalize(invocations[0].claim, FinalizationCause.UNKNOWN)
+            assert len(observations) <= (2 if lost_at == "during_observation" else 1)
+            return await store.observe_sealed_source(source)
+    handler = submission_finalization_handler(sessions=f.factory, settings=_settings(tmp_path),
+        store=ObservedStore(), lease_duration=timedelta(seconds=30))
+    async def lose_ack(envelope):
+        invocations.append(envelope)
+        assert await handler(envelope.model_copy(update={"aggregate_id": new_record_id()})) == HandlerOutcome.REJECT
+        result = await handler(envelope)
+        assert result == HandlerOutcome.ACKNOWLEDGE
+        if len(invocations) == 1 and lost_at == "after_commit":
+            raise RuntimeError("worker lost after committed T5")
+        return result
+    event_type = "SubmissionFinalizationRequested"
+    delivery = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
+        registry=HandlerRegistry([(event_type, 1, lose_ack)], replay_safe=frozenset({(event_type, 1)})),
+        options=DeliveryOptions(lease_seconds=10, handler_timeout_seconds=9,
+                                retry_base_seconds=1, retry_cap_seconds=1))
+    try:
+        async with f.factory() as session:
+            row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+            event_id = UUID(row.finalization_event_id)
+        candidates = await production_outbox_delivery(f.factory).candidates()
+        assert event_id in {item.event_id for item in candidates.items}
+        assert await delivery.deliver(event_id, f.project, "first-worker") is not None
+        async with f.factory() as session:
+            row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+            event = await session.get(OutboxEvent, event_id)
+            assert row.state == ("finalized" if lost_at == "after_commit" else "finalization_pending")
+            assert event.delivery_state == "retryable"
+            submission_id = row.finalized_submission_id
+            assert row.continuation_expires_at <= invocations[0].claim.claim_expires_at
+            ready_at = event.next_attempt_at
+            if lost_at == "during_observation":
+                assert submission_id is None
+                ready_at = max(ready_at, row.continuation_expires_at)
+            remaining = (ready_at - await session.scalar(select(func.clock_timestamp()))).total_seconds()
+        await asyncio.sleep(max(0, remaining) + 0.05)
+        assert await delivery.deliver(event_id, f.project, "replacement-worker") is not None
+        async with f.factory() as session:
+            row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+            event = await session.get(OutboxEvent, event_id)
+            assert row.state == "finalized"
+            if lost_at == "after_commit":
+                assert row.finalized_submission_id == submission_id and row.continuation_generation == 1
+            else:
+                assert row.finalized_submission_id is not None and row.continuation_generation == 2
+            assert event.delivery_state == "acknowledged" and event.attempt_count == 2
+        assert len(observations) == (1 if lost_at == "after_commit" else 2)
+        assert len(invocations) == 2
+        assert await handler(invocations[0]) == HandlerOutcome.REJECT
+    finally:
+        store.close()
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 8c52e8ae3..2f2f74c73 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "902c5a7b2a0ccbf2a64fadc205db9d69aed03a641e04d8a88ec84bb99b880fe5"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "86ac9cfc2ea48543d5084a4b47c3fd985cde4be1e13f25c06da613c371f94cc4"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",

From cc38dc34fa3bdfec24ba0a1a44791fe9e949438b Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 22:28:53 +0100
Subject: [PATCH 119/513] Prove finalization recovery retains one downstream
 dispatch

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 27 ++++++++++++++++++-
 .../test_submission_intake_admission.py       |  7 ++++-
 2 files changed, 32 insertions(+), 2 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 22e3b231a..38dac71e3 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -15,7 +15,23 @@ The first stage gives database, upload and execution owners one representation
 of the original command and sealed source, separate from credentials and later
 manifest facts.
 
-## Current behavior
+## Implementation snapshot
+
+This branch has tested internal source contracts/custody, physical reservations,
+bounded Local/MinIO streaming, foreground upload/lease owners, source-bound PRE
+contracts/runtime implementation, atomic T4 acceptance, T5 registration and
+source-backed POST. Controlled/portable PRE tests do not qualify native Smol;
+MinIO tests do not qualify AWS. Detailed evidence below belongs to its stated
+commit or worktree, not automatically to every later head.
+
+Finalization now has production OUTBOX registration and invocation fencing, with
+real PostgreSQL recovery proof. Full Celery/provider execution, independent worker
+capacity, stalled-operation projection and operator recovery remain unfinished.
+Next: close those durable-worker gaps, then complete cleanup and public API/CLI/MCP
+cutover, real revision/review/ContributionRecord journeys, policy cardinality and
+the A01–A35/C01–C07 completion audit. No public end-to-end readiness is claimed.
+
+## Original behavior being replaced
 
 `artifacts/submission_admission.py` consumes process-local prepared ZIPs;
 `interfaces/artifacts.py` derives keys from content SHA. The new design needs
@@ -2918,3 +2934,12 @@ delivery case failed before the migration and is not counted as a success.
 Architecture/outbox contracts/topology passed **117 tests**; changed-file Ruff,
 structure and Markdown-link checks passed. These are scoped worktree results,
 not complete durable-worker or public-journey qualification.
+
+Scoped architecture/security review passed clean `3fdbc820a`. QA/test-delta found
+no production defect but requested explicit downstream row counts in each lost
+invocation branch. Both recovery cases now assert exactly one Submission,
+SubmissionDispatch, checker run and initial POST event. The strengthened run
+passed **2 tests** (`/tmp/t5-delivery3.log`, metadata `/tmp/t5-delivery3.json`), with
+database cleanup confirmed. This remains controlled-store handler proof through
+real OUTBOX; production composition is exercised for discovery, not native Celery
+execution or lazy provider startup. No scope expansion follows from the review.
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 6a1613fae..76ecfb07c 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -853,7 +853,7 @@ def test_finalization_rejects_unbounded_or_empty_lease(duration):
 @pytest.mark.parametrize("lost_at", ["after_commit", "during_observation"])
 async def test_finalization_outbox_recovers_lost_ack_without_provider_replay(admission_intake, tmp_path, lost_at):
     from uuid import UUID
-    from sqlalchemy import select, func
+    from sqlalchemy import select, func, text
     from app.adapters.artifacts.finalization import submission_finalization_handler
     from app.adapters.auth import outbox_dispatch_authorization
     from app.adapters.checkers import selected_pre_submit_coordinator
@@ -926,6 +926,11 @@ async def lose_ack(envelope):
             else:
                 assert row.finalized_submission_id is not None and row.continuation_generation == 2
             assert event.delivery_state == "acknowledged" and event.attempt_count == 2
+            for table in ("submissions", "submission_dispatches", "checker_runs"):
+                assert await session.scalar(text(f"SELECT count(*) FROM {table} WHERE task_id=:id"),
+                                            {"id": f.task}) == 1
+            assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE project_id=:id "
+                "AND event_type='PostSubmissionEvaluationRequested'"), {"id": f.project}) == 1
         assert len(observations) == (1 if lost_at == "after_commit" else 2)
         assert len(invocations) == 2
         assert await handler(invocations[0]) == HandlerOutcome.REJECT

From 263393c34a0e73f6ba40d077e4c5016da251a92a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 22:45:34 +0100
Subject: [PATCH 120/513] Isolate submission finalization delivery on a
 dedicated worker queue

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  48 +++++
 .env.example                                  |   3 +
 backend/app/adapters/outbox/__init__.py       | 172 +++++++++---------
 .../artifacts/api/submission_finalization.py  |   4 +
 backend/app/modules/outbox/api.py             |   1 +
 backend/app/modules/outbox/delivery.py        |   7 +-
 .../app/modules/outbox/delivery_repository.py |   4 +-
 backend/app/workers/celery_app.py             |  10 +-
 backend/app/workers/outbox.py                 |  30 ++-
 backend/app/workers/outbox_topology.py        |  21 ++-
 .../tests/outbox/test_delivery_topology.py    |  58 ++++++
 .../tests/outbox/test_recovery_postgresql.py  |   4 +-
 .../tests/outbox/test_worker_postgresql.py    |  31 +++-
 deploy/hosted/compose.yml                     |   1 +
 deploy/hosted/preflight.py                    |   7 +-
 docker-compose.yml                            |  21 ++-
 docs/engineering/developer-setup.md           |  11 ++
 scripts/test_hosted_release_config.py         |  13 ++
 scripts/test_local_guide_runtime.py           |  30 ++-
 19 files changed, 363 insertions(+), 113 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 38dac71e3..cedd27b51 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2943,3 +2943,51 @@ passed **2 tests** (`/tmp/t5-delivery3.log`, metadata `/tmp/t5-delivery3.json`),
 database cleanup confirmed. This remains controlled-store handler proof through
 real OUTBOX; production composition is exercised for discovery, not native Celery
 execution or lazy provider startup. No scope expansion follows from the review.
+
+### Finalization worker capacity boundary
+
+Route accepted finalization selectors to a separate static Celery task/queue while
+retaining the same OUTBOX claim/invoke/finalize owner. Discovery carries event type
+only as a routing hint; worker composition independently limits registered handlers
+to its assigned event group. A finalization consumer must be prefork and must not
+consume other queues. Existing general workers explicitly select their current
+queues, so adding the finalization queue cannot silently share their capacity.
+No deployment concurrency default is introduced: enabling the separate consumer
+and qualifying its resource allocation remains C04 work before public cutover.
+
+Allowed changes are OUTBOX candidate projection/composition, Celery routes and thin
+entrypoints/topology, affected Compose queue selectors and existing worker tests.
+No new lifecycle/retry owner, broad retry authority or broker-owned business truth.
+Acceptance requires routing tests, real worker topology rejection, wrong-group
+delivery refusal and retained scan/publication recovery behavior. Workflow risk
+requires architecture/security and QA review; human focus is actual queue/pool
+selection and preservation of the database dispatch barrier.
+
+The queue split uses `workstream.submission_finalization` and a thin bounded
+`workstream.outbox.finalize_submission` entrypoint. Discovery selects its queue by
+stored event type; delivery rechecks the immutable stored type against the worker's
+filtered registry before even recovering an expired claim. The same OUTBOX owner
+still owns all receipts and backoff. Finalization workers reject mixed queues;
+general and finalization entrypoints reject the opposite worker group. The existing
+300-second lease is shared through ART's public contract with a 360-second process
+bound; no direct OUTBOX import was added to topology code.
+
+Local Compose has an opt-in consumer profile with required positive concurrency;
+no value is chosen by the implementation. A rendered-config check caught `extends`
+merging the general backend profile into that consumer; explicit YAML mapping
+inheritance now keeps the consumer out of ordinary backend startup. General hosted
+workers also select their queues explicitly, and hosted preflight permits only
+that exact selection. Hosted finalization consumer provisioning through the release
+wrapper, measured capacity/saturation proof and operational recovery remain work.
+
+Verification: **30 PostgreSQL worker/recovery tests passed**
+(`/tmp/t5-queues-pg.log`, metadata `/tmp/t5-queues-pg.json`, cleanup confirmed),
+including wrong-group refusal for pending and expired POST work and the existing
+real prefork cancellation-resistant process bound. Static topology/contracts/
+observability checks passed **81 tests**, with the existing real-Redis observability
+test skipped because no test broker was supplied (`/tmp/t5-queues-static2.log`).
+Local Compose tests passed **6**, hosted configuration tests passed **2**, and the
+expanded short-queue-option refusal passed a further focused rerun. These prove
+configuration/owner boundaries, not finalization saturation or live broker delivery.
+Changed-file Ruff and Markdown links passed; structure validation is recorded with
+the candidate checks. All test receipts are worktree evidence based on `cc38dc34f`.
diff --git a/.env.example b/.env.example
index b70a86abc..44307c486 100644
--- a/.env.example
+++ b/.env.example
@@ -32,3 +32,6 @@ WORKSTREAM_PROJECT_AGENT_MODEL_API=chat_completions
 WORKSTREAM_PROJECT_AGENT_MODEL=openai/gpt-5.6-terra
 WORKSTREAM_PROJECT_AGENT_RUNTIME_OPTIONS={}
 WORKSTREAM_CELERY_WORKER_CONCURRENCY=2
+# Required only when enabling the separate submission-intake worker profile.
+# Supply a qualified positive value; no deployment default is selected.
+WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY=
diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py
index 14978dcd1..f8da21083 100644
--- a/backend/app/adapters/outbox/__init__.py
+++ b/backend/app/adapters/outbox/__init__.py
@@ -43,10 +43,11 @@ def outbox_delivery(
     )
 
 
-def production_outbox_delivery(session_factory):
-    """Install assignment, accepted finalization and selected evaluation handlers."""
+def production_outbox_delivery(session_factory, *, finalization_worker: bool | None = None):
+    """Compose all handlers for discovery, or one explicit worker group for delivery."""
     from app.adapters.artifacts import worker_post_submission_materialization
     from app.adapters.artifacts.finalization import worker_submission_finalization_handler
+    from app.modules.artifacts.api.submission_finalization import SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS
     from app.adapters.auth import (
         outbox_dispatch_authorization,
         assignment_invalidation_authorization,
@@ -76,97 +77,104 @@ def production_outbox_delivery(session_factory):
         REVISION_EXPIRY_EVENT, REVISION_EXPIRED_EVENT, REVISION_CONTEXT_BLOCKED_EVENT,
     )
 
-    finalization_options = DeliveryOptions()
-    return outbox_delivery(
-        session_factory,
-        authorization_factory=outbox_dispatch_authorization,
-        registry=HandlerRegistry(
-            [
-                (
-                    "SubmissionFinalizationRequested",
-                    1,
-                    worker_submission_finalization_handler(
-                        sessions=session_factory, delivery_options=finalization_options,
-                    ),
+    finalization_options = DeliveryOptions(lease_seconds=SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS)
+    registry = HandlerRegistry(
+        [
+            (
+                "SubmissionFinalizationRequested",
+                1,
+                worker_submission_finalization_handler(
+                    sessions=session_factory, delivery_options=finalization_options,
                 ),
-                (
-                    ASSIGNMENT_INVALIDATION_EVENT,
-                    1,
-                    TransactionalAssignmentInvalidationHandler(
-                        session_factory,
-                        observer=CommittedInvocationReader(session_factory),
-                        authorization_factory=assignment_invalidation_authorization,
-                    ),
+            ),
+            (
+                ASSIGNMENT_INVALIDATION_EVENT,
+                1,
+                TransactionalAssignmentInvalidationHandler(
+                    session_factory,
+                    observer=CommittedInvocationReader(session_factory),
+                    authorization_factory=assignment_invalidation_authorization,
                 ),
-                (
-                    REVISION_EXPIRY_EVENT,
-                    1,
-                    TransactionalTaskRevisionExpiryHandler(
-                        session_factory,
-                        observer=CommittedInvocationReader(session_factory),
-                        authorization_factory=revision_expiry_authorization,
-                    ),
+            ),
+            (
+                REVISION_EXPIRY_EVENT,
+                1,
+                TransactionalTaskRevisionExpiryHandler(
+                    session_factory,
+                    observer=CommittedInvocationReader(session_factory),
+                    authorization_factory=revision_expiry_authorization,
                 ),
-                (
-                    REVISION_EXPIRED_EVENT,
-                    1,
-                    TransactionalTaskRevisionExpiredNoticeHandler(
-                        session_factory,
-                        observer=CommittedInvocationReader(session_factory),
-                    ),
+            ),
+            (
+                REVISION_EXPIRED_EVENT,
+                1,
+                TransactionalTaskRevisionExpiredNoticeHandler(
+                    session_factory,
+                    observer=CommittedInvocationReader(session_factory),
                 ),
-                (
-                    REVISION_CONTEXT_BLOCKED_EVENT,
-                    1,
-                    TransactionalTaskRevisionBlockedNoticeHandler(
-                        session_factory,
-                        observer=CommittedInvocationReader(session_factory),
-                    ),
+            ),
+            (
+                REVISION_CONTEXT_BLOCKED_EVENT,
+                1,
+                TransactionalTaskRevisionBlockedNoticeHandler(
+                    session_factory,
+                    observer=CommittedInvocationReader(session_factory),
                 ),
-                (
-                    REVISION_EXHAUSTED_EVENT,
-                    1,
-                    TransactionalTaskRevisionExhaustedNoticeHandler(
-                        session_factory,
-                        observer=CommittedInvocationReader(session_factory),
-                    ),
+            ),
+            (
+                REVISION_EXHAUSTED_EVENT,
+                1,
+                TransactionalTaskRevisionExhaustedNoticeHandler(
+                    session_factory,
+                    observer=CommittedInvocationReader(session_factory),
                 ),
-                (
-                    REQUEST_EVENT,
-                    1,
-                    evaluation_request_handler(
-                        sessions=session_factory,
-                        materialization=worker_post_submission_materialization(
-                            sessions=session_factory
-                        ),
+            ),
+            (
+                REQUEST_EVENT,
+                1,
+                evaluation_request_handler(
+                    sessions=session_factory,
+                    materialization=worker_post_submission_materialization(
+                        sessions=session_factory
                     ),
                 ),
-                (
-                    COMPLETION_EVENT,
-                    1,
-                    evaluation_completion_handler(sessions=session_factory),
-                ),
-                (
-                    RECONCILIATION_EVENT,
-                    1,
-                    post_submit_delivery_reconciliation_handler(
-                        sessions=session_factory,
-                        materialization=worker_post_submission_materialization(
-                            sessions=session_factory
-                        ),
+            ),
+            (
+                COMPLETION_EVENT,
+                1,
+                evaluation_completion_handler(sessions=session_factory),
+            ),
+            (
+                RECONCILIATION_EVENT,
+                1,
+                post_submit_delivery_reconciliation_handler(
+                    sessions=session_factory,
+                    materialization=worker_post_submission_materialization(
+                        sessions=session_factory
                     ),
                 ),
-            ],
-            replay_safe=frozenset({("SubmissionFinalizationRequested", 1), (REVISION_EXPIRY_EVENT, 1), (REVISION_EXPIRED_EVENT, 1), (REVISION_CONTEXT_BLOCKED_EVENT, 1), (REVISION_EXHAUSTED_EVENT, 1)}),
+            ),
+        ],
+        replay_safe=frozenset({("SubmissionFinalizationRequested", 1), (REVISION_EXPIRY_EVENT, 1), (REVISION_EXPIRED_EVENT, 1), (REVISION_CONTEXT_BLOCKED_EVENT, 1), (REVISION_EXHAUSTED_EVENT, 1)}),
+    )
+    if finalization_worker is not None:
+        keys = tuple(key for key in registry.keys
+                     if (key[0] == "SubmissionFinalizationRequested") == finalization_worker)
+        registry = HandlerRegistry(
+            [(kind, version, registry.get(kind, version)) for kind, version in keys],
+            replay_safe=frozenset(key for key in keys if registry.can_retry_unknown(*key)),
+        )
+    event_options = {
+        ("SubmissionFinalizationRequested", 1): finalization_options,
+        (REQUEST_EVENT, 1): DeliveryOptions(
+            lease_seconds=SELECTED_POST_DELIVERY_LEASE_SECONDS,
+            handler_timeout_seconds=SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
         ),
-        options=DeliveryOptions(),
-        event_options={
-            ("SubmissionFinalizationRequested", 1): finalization_options,
-            (REQUEST_EVENT, 1): DeliveryOptions(
-                lease_seconds=SELECTED_POST_DELIVERY_LEASE_SECONDS,
-                handler_timeout_seconds=SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
-            )
-        },
+    }
+    return outbox_delivery(
+        session_factory, authorization_factory=outbox_dispatch_authorization,
+        registry=registry, options=DeliveryOptions(),
+        event_options={key: value for key, value in event_options.items() if key in registry.keys},
     )
 
 
diff --git a/backend/app/modules/artifacts/api/submission_finalization.py b/backend/app/modules/artifacts/api/submission_finalization.py
index 6c2a6731e..968d4452d 100644
--- a/backend/app/modules/artifacts/api/submission_finalization.py
+++ b/backend/app/modules/artifacts/api/submission_finalization.py
@@ -3,6 +3,10 @@
 from typing import Literal
 from uuid import UUID
 
+# Existing durable OUTBOX lease convention, shared with the worker hard bound.
+# Deployment qualification and independent admission sizing remain separate.
+SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS = 300
+
 
 @dataclass(frozen=True, slots=True)
 class SubmissionFinalizationAuthorityFacts:
diff --git a/backend/app/modules/outbox/api.py b/backend/app/modules/outbox/api.py
index f99627638..a7ebe6262 100644
--- a/backend/app/modules/outbox/api.py
+++ b/backend/app/modules/outbox/api.py
@@ -182,6 +182,7 @@ class DeliveryCandidate(DeliveryValue):
 
     event_id: UUID
     project_id: UUID
+    event_type: str
 
 
 class DeliveryCandidatePage(DeliveryValue):
diff --git a/backend/app/modules/outbox/delivery.py b/backend/app/modules/outbox/delivery.py
index 989b45d2c..b568f70f1 100644
--- a/backend/app/modules/outbox/delivery.py
+++ b/backend/app/modules/outbox/delivery.py
@@ -202,8 +202,13 @@ async def candidates(self, *, after: UUID | None = None, limit: int = 100) -> De
         async with self._sessions() as session:
             return await DeliveryRepository(session).candidates(self._registry.keys, after=after, limit=limit)
 
-    async def deliver(self, event_id: UUID, project_id: UUID, owner: str) -> DeliveryReceipt | None:
+    async def deliver(self, event_id: UUID, project_id: UUID, owner: str, *, registered_only: bool = False) -> DeliveryReceipt | None:
         """Reuse recovery and claim/invoke; duplicate transport cannot bypass custody."""
+        if registered_only:
+            async with self._sessions() as session:
+                event = await DeliveryRepository(session).event(event_id, project_id)
+                if event is None or self._registry.get(event.event_type, event.event_version) is None:
+                    return None
         recovered = await self.recover(event_id, project_id)
         if recovered is not None:
             return recovered
diff --git a/backend/app/modules/outbox/delivery_repository.py b/backend/app/modules/outbox/delivery_repository.py
index a5da3d939..11e7e5c52 100644
--- a/backend/app/modules/outbox/delivery_repository.py
+++ b/backend/app/modules/outbox/delivery_repository.py
@@ -120,7 +120,7 @@ async def candidates(self, registered, *, after: UUID | None, limit: int) -> Del
         """One nonlocking statement includes due supported work and all expired claims."""
         e = OutboxEvent
         now = func.statement_timestamp()
-        query = select(e.event_id, e.project_id).where(or_(
+        query = select(e.event_id, e.project_id, e.event_type).where(or_(
             and_(e.delivery_state.in_(("pending", "retryable")), e.next_attempt_at <= now,
                  tuple_(e.event_type, e.event_version).in_(sorted(registered))),
             and_(e.delivery_state == "claimed", e.claim_expires_at <= now),
@@ -128,7 +128,7 @@ async def candidates(self, registered, *, after: UUID | None, limit: int) -> Del
         if after is not None:
             query = query.where(e.event_id > after)
         rows = (await self.session.execute(query.order_by(e.event_id).limit(limit + 1))).all()
-        items = tuple(DeliveryCandidate(event_id=UUID(str(row.event_id)), project_id=UUID(row.project_id))
+        items = tuple(DeliveryCandidate(event_id=UUID(str(row.event_id)), project_id=UUID(row.project_id), event_type=row.event_type)
                       for row in rows[:limit])
         return DeliveryCandidatePage(items=items, next_after=items[-1].event_id if len(rows) > limit else None)
 
diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py
index fd180363b..4bbf761bf 100644
--- a/backend/app/workers/celery_app.py
+++ b/backend/app/workers/celery_app.py
@@ -4,7 +4,9 @@
 
 from celery import Celery
 from kombu import Queue
-from app.workers.outbox_topology import OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE
+from app.workers.outbox_topology import (
+    OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE, FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE,
+)
 from app.workers.project_setup_topology import (
     CELERY_VISIBILITY_TIMEOUT_SECONDS,
     PROJECT_GUIDE_CONSUMER_MARKER,
@@ -39,6 +41,7 @@
 OBSERVED_TASK_NAMES = frozenset(
     {
         OUTBOX_DELIVERY_TASK,
+        FINALIZATION_DELIVERY_TASK,
         "workstream.outbox.scan_pending",
         "workstream.tasks.scan_retained_revisions",
         "workstream.project_setup.derive_post_policy",
@@ -121,8 +124,9 @@ def create_celery_app() -> Celery:
         ],
     )
     celery_app.conf.update(
-        task_queues=(Queue("celery"), Queue(OUTBOX_QUEUE)),
-        task_routes={OUTBOX_DELIVERY_TASK: {"queue": OUTBOX_QUEUE}},
+        task_queues=(Queue("celery"), Queue(OUTBOX_QUEUE), Queue(FINALIZATION_QUEUE)),
+        task_routes={OUTBOX_DELIVERY_TASK: {"queue": OUTBOX_QUEUE},
+                     FINALIZATION_DELIVERY_TASK: {"queue": FINALIZATION_QUEUE}},
         accept_content=["json"],
         result_serializer="json",
         task_always_eager=settings.celery_task_always_eager,
diff --git a/backend/app/workers/outbox.py b/backend/app/workers/outbox.py
index f904aee14..59b9548bc 100644
--- a/backend/app/workers/outbox.py
+++ b/backend/app/workers/outbox.py
@@ -9,7 +9,9 @@
 from app.db.session import get_database_url
 from app.workers.async_runner import run_async_task
 from app.workers.celery_app import celery_app
-from app.workers.outbox_topology import require_outbox_worker, OUTBOX_HARD_LIMIT_SECONDS
+from app.workers.outbox_topology import (
+    require_outbox_worker, OUTBOX_HARD_LIMIT_SECONDS, FINALIZATION_HARD_LIMIT_SECONDS,
+)
 
 logger = get_task_logger(__name__)
 
@@ -30,13 +32,26 @@ def _uuid(value):
 )
 def deliver_event(self, event_id, project_id):
     """Run under prefork: its hard limit also bounds async shutdown after UNKNOWN."""
-    require_outbox_worker(self)
+    return _run_delivery(self, event_id, project_id, finalization=False)
+
+
+@celery_app.task(
+    name="workstream.outbox.finalize_submission", bind=True, acks_late=True,
+    reject_on_worker_lost=True, acks_on_failure_or_timeout=True, time_limit=FINALIZATION_HARD_LIMIT_SECONDS,
+)
+def finalize_submission(self, event_id, project_id):
+    """Use reserved finalization workers and the same durable delivery owner."""
+    return _run_delivery(self, event_id, project_id, finalization=True)
+
+
+def _run_delivery(self, event_id, project_id, *, finalization):
+    require_outbox_worker(self, finalization=finalization)
     try:
         event, project, task = _uuid(event_id), _uuid(project_id), _uuid(self.request.id)
     except (TypeError, ValueError):
         return {"status": "delivery_rejected"}
     try:
-        return run_async_task(lambda: _deliver(event, project, task))
+        return run_async_task(lambda: _deliver(event, project, task, finalization))
     except Exception:
         logger.warning("outbox delivery unavailable")
         raise self.retry(
@@ -46,13 +61,13 @@ def deliver_event(self, event_id, project_id):
         ) from None
 
 
-async def _deliver(event_id, project_id, task_id):
+async def _deliver(event_id, project_id, task_id, finalization=False):
     """Compose once; shared delivery owns short transactions and invocation custody."""
     engine = create_async_engine(get_database_url(), pool_pre_ping=True)
     try:
         receipt = await production_outbox_delivery(
-            async_sessionmaker(engine, expire_on_commit=False)
-        ).deliver(event_id, project_id, "celery:" + str(task_id))
+            async_sessionmaker(engine, expire_on_commit=False), finalization_worker=finalization,
+        ).deliver(event_id, project_id, "celery:" + str(task_id), registered_only=True)
         return {"status": "delivery_recorded" if receipt is not None else "delivery_unavailable"}
     finally:
         await engine.dispose()
@@ -77,7 +92,8 @@ def scan_pending(self, after=None):
     published = 0
     for candidate in page.items:
         try:
-            deliver_event.apply_async(args=(str(candidate.event_id), str(candidate.project_id)))
+            task = finalize_submission if candidate.event_type == "SubmissionFinalizationRequested" else deliver_event
+            task.apply_async(args=(str(candidate.event_id), str(candidate.project_id)))
             published += 1
         except Exception:
             logger.warning("outbox publication unavailable")
diff --git a/backend/app/workers/outbox_topology.py b/backend/app/workers/outbox_topology.py
index 3f18fcf22..14237d56e 100644
--- a/backend/app/workers/outbox_topology.py
+++ b/backend/app/workers/outbox_topology.py
@@ -7,6 +7,7 @@
 from celery.exceptions import WorkerShutdown
 from celery.signals import worker_init
 from app.modules.checkers.api.external_policy import SELECTED_POST_DELIVERY_LEASE_SECONDS
+from app.modules.artifacts.api.submission_finalization import SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS
 
 OUTBOX_PROCESS_SHUTDOWN_MARGIN_SECONDS = 60
 OUTBOX_HARD_LIMIT_SECONDS = (
@@ -14,15 +15,23 @@
 )
 OUTBOX_QUEUE = "workstream.outbox"
 OUTBOX_DELIVERY_TASK = "workstream.outbox.deliver_event"
+FINALIZATION_QUEUE = "workstream.submission_finalization"
+FINALIZATION_DELIVERY_TASK = "workstream.outbox.finalize_submission"
+FINALIZATION_HARD_LIMIT_SECONDS = SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS + OUTBOX_PROCESS_SHUTDOWN_MARGIN_SECONDS
 _validated_parent: int | None = None
+_validated_finalization = False
 
 
 @worker_init.connect
 def validate_outbox_worker(sender, **_kwargs):
     """Validate the actual selected queues and pool before the worker starts."""
-    global _validated_parent
+    global _validated_parent, _validated_finalization
     _validated_parent = None
-    if OUTBOX_QUEUE not in sender.app.amqp.queues.consume_from:
+    queues = set(sender.app.amqp.queues.consume_from)
+    _validated_finalization = FINALIZATION_QUEUE in queues
+    if _validated_finalization and queues != {FINALIZATION_QUEUE}:
+        raise WorkerShutdown("submission finalization requires an exclusive worker queue")
+    if OUTBOX_QUEUE not in queues and not _validated_finalization:
         return
     pool = sender.pool_cls
     if isinstance(pool, str):
@@ -32,18 +41,20 @@ def validate_outbox_worker(sender, **_kwargs):
     _validated_parent = os.getpid()
 
 
-def require_outbox_worker(task):
+def require_outbox_worker(task, *, finalization=False):
     """Reject direct/eager delivery and consumers not validated for this queue."""
     if (
         _validated_parent is None or os.getppid() != _validated_parent
         or task.app.conf.task_always_eager or task.request.is_eager
         or task.request.called_directly
+        or finalization != _validated_finalization
     ):
         raise RuntimeError("OUTBOX delivery requires a validated prefork worker")
     message_limit = (task.request.timelimit or (None, None))[0]
+    expected_limit = FINALIZATION_HARD_LIMIT_SECONDS if finalization else OUTBOX_HARD_LIMIT_SECONDS
     if (
-        type(task.time_limit) is not int or task.time_limit != OUTBOX_HARD_LIMIT_SECONDS
+        type(task.time_limit) is not int or task.time_limit != expected_limit
         or message_limit is not None
-        and (type(message_limit) is not int or message_limit != OUTBOX_HARD_LIMIT_SECONDS)
+        and (type(message_limit) is not int or message_limit != expected_limit)
     ):
         raise RuntimeError("OUTBOX delivery requires a bounded hard time limit")
diff --git a/backend/tests/outbox/test_delivery_topology.py b/backend/tests/outbox/test_delivery_topology.py
index b928ba568..0f4192a98 100644
--- a/backend/tests/outbox/test_delivery_topology.py
+++ b/backend/tests/outbox/test_delivery_topology.py
@@ -24,6 +24,7 @@ def restore_process_state(monkeypatch):
 
     original_join_guard = task_join_will_block()
     monkeypatch.setattr(topology, "_validated_parent", None)
+    monkeypatch.setattr(topology, "_validated_finalization", False)
     try:
         yield
     finally:
@@ -150,3 +151,60 @@ def test_actual_other_queue_worker_allows_solo(monkeypatch):
     finally:
         app.close()
         get_settings.cache_clear()
+
+
+@pytest.mark.parametrize("extra", [topology.OUTBOX_QUEUE, "celery"])
+def test_finalization_worker_cannot_share_capacity_with_other_queues(extra):
+    with pytest.raises(WorkerShutdown, match="exclusive worker queue"):
+        topology.validate_outbox_worker(worker(queues=(topology.FINALIZATION_QUEUE, extra)))
+    assert topology._validated_parent is None
+
+
+def test_finalization_prefork_worker_rejects_general_delivery(monkeypatch):
+    configured = worker(queues=(topology.FINALIZATION_QUEUE,))
+    topology.validate_outbox_worker(configured)
+    monkeypatch.setattr(topology.os, "getppid", os.getpid)
+    task = SimpleNamespace(app=configured.app, time_limit=topology.FINALIZATION_HARD_LIMIT_SECONDS,
+        request=SimpleNamespace(is_eager=False, called_directly=False, timelimit=None))
+    topology.require_outbox_worker(task, finalization=True)
+    with pytest.raises(RuntimeError, match="validated prefork"):
+        topology.require_outbox_worker(task)
+
+
+def test_finalization_task_routes_to_reserved_queue(monkeypatch):
+    from app.core.config import get_settings
+    monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true")
+    get_settings.cache_clear()
+    from app.workers.celery_app import create_celery_app
+    app = create_celery_app()
+    try:
+        assert app.amqp.router.route({}, topology.FINALIZATION_DELIVERY_TASK)["queue"].name == topology.FINALIZATION_QUEUE
+        app.conf.task_always_eager = False
+        with pytest.raises(WorkerShutdown, match="exclusive worker queue"):
+            app.Worker(pool="prefork", queues=[topology.FINALIZATION_QUEUE, topology.OUTBOX_QUEUE])
+    finally:
+        app.close()
+        get_settings.cache_clear()
+
+
+def test_scan_routes_each_event_group_without_acknowledging(monkeypatch):
+    from app.core.config import get_settings
+    from app.core.identifiers import new_record_id
+    from app.modules.outbox.api import DeliveryCandidate, DeliveryCandidatePage
+    monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true")
+    get_settings.cache_clear()
+    from app.workers import outbox
+    items = tuple(DeliveryCandidate(event_id=new_record_id(), project_id=new_record_id(), event_type=kind)
+                  for kind in ("PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested"))
+    async def candidates(_after):
+        return DeliveryCandidatePage(items=items, next_after=None)
+    published = []
+    monkeypatch.setattr(outbox, "_candidates", candidates)
+    monkeypatch.setattr(outbox.deliver_event, "apply_async", lambda **kwargs: published.append(("post", kwargs)))
+    monkeypatch.setattr(outbox.finalize_submission, "apply_async", lambda **kwargs: published.append(("final", kwargs)))
+    try:
+        assert outbox.scan_pending.apply(task_id=str(new_record_id()), throw=True).get() == {"selected": 2, "published": 2}
+        assert published == [(kind, {"args": (str(item.event_id), str(item.project_id))})
+                             for kind, item in zip(("post", "final"), items, strict=True)]
+    finally:
+        get_settings.cache_clear()
diff --git a/backend/tests/outbox/test_recovery_postgresql.py b/backend/tests/outbox/test_recovery_postgresql.py
index e95fb7d52..196a2d810 100644
--- a/backend/tests/outbox/test_recovery_postgresql.py
+++ b/backend/tests/outbox/test_recovery_postgresql.py
@@ -75,11 +75,11 @@ def _configure_recovery_worker(h, monkeypatch: pytest.MonkeyPatch):
     get_settings.cache_clear()
     from app.workers import outbox as worker
 
-    monkeypatch.setattr(worker, "require_outbox_worker", lambda _task: None)
+    monkeypatch.setattr(worker, "require_outbox_worker", lambda _task, **_kwargs: None)
     monkeypatch.setattr(worker, "get_database_url", lambda: h.factory.kw["bind"].url)
     worker_factories = []
 
-    def compose_delivery(factory):
+    def compose_delivery(factory, **_kwargs):
         worker_factories.append(factory)
         return outbox_delivery(
             factory,
diff --git a/backend/tests/outbox/test_worker_postgresql.py b/backend/tests/outbox/test_worker_postgresql.py
index 248ab641e..e33633768 100644
--- a/backend/tests/outbox/test_worker_postgresql.py
+++ b/backend/tests/outbox/test_worker_postgresql.py
@@ -22,12 +22,12 @@ def worker(delivery_harness, monkeypatch):
     from app.workers import outbox as worker
 
     # Shared SQL/timeout proofs isolate topology, covered by the real broker drill.
-    monkeypatch.setattr(worker, "require_outbox_worker", lambda _task: None)
+    monkeypatch.setattr(worker, "require_outbox_worker", lambda _task, **_kwargs: None)
     monkeypatch.setattr(worker, "get_database_url", lambda: h.factory.kw["bind"].url)
     monkeypatch.setattr(
         worker,
         "production_outbox_delivery",
-        lambda factory: outbox_delivery(
+        lambda factory, **_kwargs: outbox_delivery(
             factory,
             authorization_factory=outbox_dispatch_authorization,
             registry=HandlerRegistry([("ContributionRecorded", 1, h.handle)]),
@@ -165,7 +165,7 @@ async def failed(*args):
 async def test_worker_scan_continues_after_failed_publication(worker, monkeypatch):
     from app.modules.outbox.api import DeliveryCandidate, DeliveryCandidatePage
 
-    selectors = (DeliveryCandidate(event_id=new_record_id(), project_id=new_record_id()),)
+    selectors = (DeliveryCandidate(event_id=new_record_id(), project_id=new_record_id(), event_type="ContributionRecorded"),)
     cursor = selectors[-1].event_id
 
     async def page(after):
@@ -198,6 +198,7 @@ async def test_production_registry_claims_only_registered_features(delivery_harn
     event = await h.append()
     production = production_outbox_delivery(h.factory)
     assert production._registry.keys == (
+        ("SubmissionFinalizationRequested", 1),
         ("TaskAssignmentAuthorityInvalidationRequested", 1),
         ("TaskRevisionExpiryRequested", 1),
         ("TaskRevisionExpired", 1),
@@ -350,3 +351,27 @@ def test_delivery_task_has_independent_hard_limit(worker):
     assert task.acks_late and task.acks_on_failure_or_timeout
     assert task.reject_on_worker_lost is True
     assert task.soft_time_limit is None
+
+
+@pytest.mark.parametrize("expired", [False, True])
+async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery_harness, expired):
+    from app.adapters.outbox import production_outbox_delivery
+    h = delivery_harness
+    kind = "PostSubmissionEvaluationRequested"
+    event = await h.append(event_type=kind)
+    if expired:
+        owner = h.build(HandlerRegistry([(kind, 1, h.handle)]))
+        assert await owner.claim(event.event_id, h.project, "post-worker") is not None
+        async with h.factory() as session:
+            await session.execute(text("select pg_sleep(3.05)"))
+    finalization = production_outbox_delivery(h.factory, finalization_worker=True)
+    assert finalization._registry.keys == (("SubmissionFinalizationRequested", 1),)
+    assert await finalization.deliver(event.event_id, h.project, "wrong-worker", registered_only=True) is None
+    async with h.factory() as session:
+        stored = await session.get(OutboxEvent, event.event_id)
+        assert stored.delivery_state == ("claimed" if expired else "pending")
+        attempts = list(await session.scalars(select(OutboxDeliveryAttempt)))
+        assert len(attempts) == int(expired)
+        if expired:
+            assert attempts[0].stage == "claimed"
+    assert h.handled == []
diff --git a/deploy/hosted/compose.yml b/deploy/hosted/compose.yml
index 6d5cb4403..8d83615bd 100644
--- a/deploy/hosted/compose.yml
+++ b/deploy/hosted/compose.yml
@@ -237,6 +237,7 @@ services:
       - --pool=prefork
       - --concurrency=${WORKSTREAM_CELERY_WORKER_CONCURRENCY:-1}
       - --hostname=worker@%h
+      - --queues=celery,workstream.outbox
       - --pidfile=/tmp/celery-worker.pid
       - --loglevel=INFO
     volumes:
diff --git a/deploy/hosted/preflight.py b/deploy/hosted/preflight.py
index 632f2e218..be28c5e1d 100644
--- a/deploy/hosted/preflight.py
+++ b/deploy/hosted/preflight.py
@@ -2156,10 +2156,9 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None:
         worker.get("stop_grace_period") not in {"7320s", "2h2m0s"}
         or not isinstance(worker_command, list)
         or "--pool=prefork" not in worker_command
-        or any(
-            value == "-Q" or str(value).startswith("--queues")
-            for value in worker_command
-        )
+        or [value for value in worker_command
+            if str(value).startswith(("-Q", "--queues"))]
+        != ["--queues=celery,workstream.outbox"]
     ):
         raise PreflightError("project guide worker delivery profile is invalid")
     if model_proxy_enabled:
diff --git a/docker-compose.yml b/docker-compose.yml
index b7e7a8a31..1db420c87 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -80,10 +80,10 @@ services:
       retries: 20
       start_period: 15s
 
-  worker:
+  worker: &general-worker
     <<: *backend-runtime
     group_add: ["10001"]
-    environment:
+    environment: &worker-environment
       <<: *backend-environment
       WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET: /var/lib/workstream/guide-runtime/guide.sock
     volumes:
@@ -100,6 +100,7 @@ services:
       - --pool=prefork
       - --concurrency=${WORKSTREAM_CELERY_WORKER_CONCURRENCY:-2}
       - --hostname=worker@%h
+      - --queues=celery,workstream.outbox
       - --pidfile=/tmp/celery-worker.pid
       - --loglevel=INFO
     depends_on:
@@ -120,6 +121,22 @@ services:
       retries: 12
       start_period: 20s
 
+  submission-finalizer:
+    <<: *general-worker
+    profiles: ["submission-intake"]
+    environment:
+      <<: *worker-environment
+      WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY: ${WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY:-}
+    command:
+      - /bin/sh
+      - -ec
+      - |
+        n="$${WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY:?set an approved finalization concurrency}"
+        case "$$n" in *[!0-9]*|0) echo "finalization concurrency must be positive" >&2; exit 1;; esac
+        test "$$n" -gt 0
+        exec python -m celery -A app.workers.celery_app worker --pool=prefork --concurrency="$$n" --queues=workstream.submission_finalization --hostname=submission-finalizer@%h --pidfile=/tmp/celery-worker.pid --loglevel=INFO
+    stop_grace_period: 420s
+
   model-proxy:
     <<: *backend-runtime
     profiles: ["model-proxy"]
diff --git a/docs/engineering/developer-setup.md b/docs/engineering/developer-setup.md
index 6b0ac3781..74f29b504 100644
--- a/docs/engineering/developer-setup.md
+++ b/docs/engineering/developer-setup.md
@@ -149,6 +149,17 @@ uploaded rules compilation at the same prefix's `requirements/compile` suffix.
 Both require a UUID `Idempotency-Key` and no body; manager review and separate
 approvals remain required. See the [local pilot](local-pilot.md#declare-and-upload-a-real-guide-document).
 
+The single-request submission implementation has an opt-in `submission-intake`
+worker profile in local Compose. Its `submission-finalizer` service
+consumes only `workstream.submission_finalization`; the general worker consumes
+`celery,workstream.outbox`. Set `WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY`
+to an approved positive integer before enabling the profile. Missing or invalid
+values stop that consumer before Celery starts. No concurrency default or native
+runtime qualification is implied. Hosted consumer provisioning, public submission
+cutover and the complete
+deployment qualification remain unfinished; see the
+[execution record](../../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md).
+
 ## Logs, Shutdown, And Reset
 
 The API and prefork Celery process emit privacy-bounded structured logs and can export
diff --git a/scripts/test_hosted_release_config.py b/scripts/test_hosted_release_config.py
index af543ce7f..d1f803072 100644
--- a/scripts/test_hosted_release_config.py
+++ b/scripts/test_hosted_release_config.py
@@ -576,6 +576,19 @@ def test_roles_anywhere_timer_is_bounded_and_five_minute(self) -> None:
     def tearDown(self) -> None:
         self.temporary.cleanup()
 
+    def test_worker_cannot_consume_finalization_or_omit_its_queue_selection(self) -> None:
+        rendered = preflight.render_compose(self.environment_path, self.environment)
+        for selection in (None, "--queues=celery", "-Qworkstream.submission_finalization",
+                          "--queues=celery,workstream.outbox,workstream.submission_finalization"):
+            with self.subTest(selection=selection):
+                changed = copy.deepcopy(rendered)
+                command = changed["services"]["worker"]["command"]
+                command.remove("--queues=celery,workstream.outbox")
+                if selection:
+                    command.append(selection)
+                with self.assertRaisesRegex(preflight.PreflightError, "worker delivery profile"):
+                    preflight.validate_compose(changed, self.environment)
+
     def test_valid_configuration_and_rendered_topology(self) -> None:
         self.assertEqual(
             str(preflight.deployment_paths(self.environment).socket_root),
diff --git a/scripts/test_local_guide_runtime.py b/scripts/test_local_guide_runtime.py
index 3df91a846..e77d6da9e 100644
--- a/scripts/test_local_guide_runtime.py
+++ b/scripts/test_local_guide_runtime.py
@@ -82,7 +82,7 @@ def test_parser_has_no_secrets_network_or_source_mount(self):
         self.assertIn("--healthcheck", parser["healthcheck"]["test"])
 
     def test_only_model_proxy_receives_provider_keys(self):
-        for name in ("backend", "worker", "beat", "guide-document-parser"):
+        for name in ("backend", "worker", "submission-finalizer", "beat", "guide-document-parser"):
             service = self.services[name]
             self.assertFalse(
                 {"OPENAI_API_KEY", "OPENROUTER_API_KEY"} & set(service.get("environment", {})),
@@ -103,6 +103,30 @@ def test_worker_receives_readonly_parser_socket(self):
         self.assertIn("guide_parser_socket:/var/lib/workstream/guide-runtime:ro", worker["volumes"])
         self.assertEqual(worker["depends_on"]["guide-document-parser"]["condition"], "service_healthy")
 
+    def test_finalization_consumer_requires_explicit_positive_capacity(self):
+        service = self.services["submission-finalizer"]
+        self.assertEqual(service["profiles"], ["submission-intake"])
+        self.assertIn("--queues=celery,workstream.outbox", self.services["worker"]["command"])
+        # Compose turns escaped dollars into shell variables at container launch.
+        script = service["command"][2].replace("$$", "$")
+        with tempfile.TemporaryDirectory() as directory:
+            executable = Path(directory) / "python"
+            executable.write_text('#!/bin/sh\nprintf "%s\\n" "$@"\n')
+            executable.chmod(0o700)
+            for value in ("", "0", "00", "-1", "1.5", "two", "2"):
+                with self.subTest(value=value):
+                    result = subprocess.run(["/bin/sh", "-ec", script], text=True, capture_output=True,
+                        env={"PATH": directory, "WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY": value})
+                    if value != "2":
+                        self.assertNotEqual(result.returncode, 0)
+                        self.assertEqual(result.stdout, "")
+                    else:
+                        self.assertEqual(result.returncode, 0, result.stderr)
+                        arguments = result.stdout.splitlines()
+                        self.assertIn("--concurrency=2", arguments)
+                        self.assertIn("--pool=prefork", arguments)
+                        self.assertIn("--queues=workstream.submission_finalization", arguments)
+
     def test_images_create_private_directory_without_exposing_local_env(self):
         for name in ("dev", "release"):
             dockerfile = (ROOT / f"docker/backend/Dockerfile.{name}").read_text()
@@ -134,7 +158,9 @@ def test_rendered_default_model_tuple_constructs_registered_adapter(self):
              "config", "--format", "json"],
             cwd=ROOT, env=environment, text=True, capture_output=True, check=True,
         )
-        worker = json.loads(rendered.stdout)["services"]["worker"]["environment"]
+        services = json.loads(rendered.stdout)["services"]
+        self.assertNotIn("submission-finalizer", services)
+        worker = services["worker"]["environment"]
         settings = Settings(
             project_agent_runtime=worker["WORKSTREAM_PROJECT_AGENT_RUNTIME"],
             project_agent_model_provider=worker["WORKSTREAM_PROJECT_AGENT_MODEL_PROVIDER"],

From cb09fd84c50ce390f35f67fafe402ebb88525ed2 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 22:50:35 +0100
Subject: [PATCH 121/513] Defer finalization worker storage startup until
 source observation

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 11 ++++++++
 backend/app/workers/celery_app.py             |  5 ++++
 backend/app/workers/outbox_topology.py        |  6 +++++
 .../tests/outbox/test_delivery_topology.py    | 27 +++++++++++++++++++
 4 files changed, 49 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index cedd27b51..fdae75bf2 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -2991,3 +2991,14 @@ expanded short-queue-option refusal passed a further focused rerun. These prove
 configuration/owner boundaries, not finalization saturation or live broker delivery.
 Changed-file Ruff and Markdown links passed; structure validation is recorded with
 the candidate checks. All test receipts are worktree evidence based on `cc38dc34f`.
+
+Architecture/security and documentation review passed clean `263393c34`; QA passed
+the queue split and identified a provider-startup dependency in the existing global
+Celery child initialization hook. A validated exclusive finalization child now
+defers that hook; unfinalized work still initializes the canonical provider on
+demand, while finalized replay can reach SQL without provider startup. General
+workers retain their original initialization. Two discriminating startup cases
+prove provider unavailability prevents general startup but is not consulted by the
+finalization child. The combined static rerun passed **83 tests**, with the same
+existing no-broker observability skip (`/tmp/t5-queues-startup.log`). This repairs
+the identified hook dependency without claiming a live broker/provider replay drill.
diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py
index 4bbf761bf..220379e85 100644
--- a/backend/app/workers/celery_app.py
+++ b/backend/app/workers/celery_app.py
@@ -6,6 +6,7 @@
 from kombu import Queue
 from app.workers.outbox_topology import (
     OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE, FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE,
+    is_finalization_worker_process,
 )
 from app.workers.project_setup_topology import (
     CELERY_VISIBILITY_TIMEOUT_SECONDS,
@@ -61,6 +62,10 @@
 @worker_process_init.connect
 def initialize_artifact_runtime_for_process(**_kwargs: object) -> None:
     """Claim and initialize the artifact provider once per Celery child."""
+    if is_finalization_worker_process():
+        # Finalized replay needs retained SQL facts only. Unfinished finalization
+        # leases/initializes the same provider through _WorkerSourceObservation.
+        return
     run_async_task(initialize_artifact_internal_runtime)
 
 
diff --git a/backend/app/workers/outbox_topology.py b/backend/app/workers/outbox_topology.py
index 14237d56e..0f74ad444 100644
--- a/backend/app/workers/outbox_topology.py
+++ b/backend/app/workers/outbox_topology.py
@@ -41,6 +41,12 @@ def validate_outbox_worker(sender, **_kwargs):
     _validated_parent = os.getpid()
 
 
+def is_finalization_worker_process() -> bool:
+    """Identify only a child of the validated exclusive finalization consumer."""
+    return (_validated_finalization and _validated_parent is not None
+            and os.getppid() == _validated_parent)
+
+
 def require_outbox_worker(task, *, finalization=False):
     """Reject direct/eager delivery and consumers not validated for this queue."""
     if (
diff --git a/backend/tests/outbox/test_delivery_topology.py b/backend/tests/outbox/test_delivery_topology.py
index 0f4192a98..f4b7fcc2a 100644
--- a/backend/tests/outbox/test_delivery_topology.py
+++ b/backend/tests/outbox/test_delivery_topology.py
@@ -208,3 +208,30 @@ async def candidates(_after):
                              for kind, item in zip(("post", "final"), items, strict=True)]
     finally:
         get_settings.cache_clear()
+
+
+@pytest.mark.parametrize("finalization", [False, True])
+def test_finalization_child_defers_provider_startup_for_sql_only_replay(monkeypatch, finalization):
+    import importlib
+    from app.core.config import get_settings
+    monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true")
+    get_settings.cache_clear()
+    module = importlib.import_module("app.workers.celery_app")
+    configured = worker(queues=(topology.FINALIZATION_QUEUE if finalization else topology.OUTBOX_QUEUE,))
+    topology.validate_outbox_worker(configured)
+    monkeypatch.setattr(topology.os, "getppid", os.getpid)
+    calls = []
+    def unavailable(callback):
+        calls.append(callback)
+        raise RuntimeError("provider startup unavailable")
+    monkeypatch.setattr(module, "run_async_task", unavailable)
+    try:
+        if finalization:
+            module.initialize_artifact_runtime_for_process()
+            assert calls == []
+        else:
+            with pytest.raises(RuntimeError, match="provider startup unavailable"):
+                module.initialize_artifact_runtime_for_process()
+            assert calls == [module.initialize_artifact_internal_runtime]
+    finally:
+        get_settings.cache_clear()

From 82452d5f314d163b44c43fa6063ac44a6f60b033 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 23:07:28 +0100
Subject: [PATCH 122/513] Expose authorized finalization progress from exact
 outbox custody

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 31 +++++++
 .../artifacts/api/submission_finalization.py  | 13 +++
 .../artifacts/intake/foreground_admission.py  |  8 +-
 .../app/modules/artifacts/intake/progress.py  | 27 ++++++
 backend/app/modules/outbox/api.py             | 15 ++++
 backend/app/modules/outbox/service.py         | 20 ++++-
 .../test_submission_intake_admission.py       | 82 +++++++++++++++++++
 .../tests/outbox/test_delivery_postgresql.py  | 34 ++++++++
 8 files changed, 226 insertions(+), 4 deletions(-)
 create mode 100644 backend/app/modules/artifacts/intake/progress.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index fdae75bf2..80658b179 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3002,3 +3002,34 @@ prove provider unavailability prevents general startup but is not consulted by t
 finalization child. The combined static rerun passed **83 tests**, with the same
 existing no-broker observability skip (`/tmp/t5-queues-startup.log`). This repairs
 the identified hook dependency without claiming a live broker/provider replay drill.
+
+### Owner-backed finalization stall observation
+
+Expose exact delivery progress from the existing OUTBOX append/custody participant,
+requiring the same immutable event facts as `require_existing`. Extend ART's
+authorized own-operation read with finalization progress. A pending accepted
+operation is stalled only when its exact durable event is dead-lettered; age and
+lease expiry alone do not imply a stall. Finalized operation facts take precedence
+over delayed transport acknowledgement. Reads do not release source charges,
+change task/operation state, invoke storage, or grant retry authority.
+
+Allowed scope: OUTBOX public observation value/port and its existing service;
+ART finalization progress value/reader and the existing foreground read owner;
+focused real PostgreSQL/auth and custody tests. Preserve exact event binding,
+current contributor read authorization and sanitized errors. Verify pending,
+claimed, exhausted and finalized states, substitution refusal and no read effects.
+This is an internal read boundary for the pending public cutover, not the full
+API progress contract. The existing `operations.submission_gate.repair` action is
+registered but planned/unavailable; its applicability to finalization recovery
+needs assessment before activation. C05 requires a concrete authority decision
+before inventing a new business/admin capability. Risk remains authorization/workflow;
+architecture/security and QA review are required.
+
+The exact exhausted/finalized progress cases passed on real PostgreSQL
+(`/tmp/t5-progress2.log`: **2 passed**, isolated database/role cleanup confirmed).
+Exact OUTBOX identity substitution and pending/claimed/acknowledged observation
+passed separately (`/tmp/t5-progress-custody.log`: **1 passed**). Related OUTBOX
+contracts and ART architecture checks passed (`/tmp/t5-progress-static.log`:
+**94 passed**). Evidence is for the working tree based on `cb09fd84c`; it does
+not prove public operation reads or operator retry. Ruff passed for all changed
+Python files.
diff --git a/backend/app/modules/artifacts/api/submission_finalization.py b/backend/app/modules/artifacts/api/submission_finalization.py
index 968d4452d..619f57e9e 100644
--- a/backend/app/modules/artifacts/api/submission_finalization.py
+++ b/backend/app/modules/artifacts/api/submission_finalization.py
@@ -1,5 +1,6 @@
 """Exact accepted continuation selectors; values confer no authority themselves."""
 from dataclasses import dataclass
+from datetime import datetime
 from typing import Literal
 from uuid import UUID
 
@@ -8,6 +9,18 @@
 SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS = 300
 
 
+@dataclass(frozen=True, slots=True)
+class SubmissionFinalizationProgress:
+    """Internal owner facts; not the complete public operation-read response."""
+
+    operation_id: UUID
+    finalized: bool
+    operationally_stalled: bool
+    stalled_at: datetime | None
+    next_retry_at: datetime | None
+    attempt_count: int
+
+
 @dataclass(frozen=True, slots=True)
 class SubmissionFinalizationAuthorityFacts:
     operation_id: UUID
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index 3034c013e..9e67f1e33 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -22,6 +22,8 @@
 from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
 from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
+from app.modules.artifacts.intake.progress import finalization_progress
+from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
 from app.modules.artifacts.intake.streaming import hash_submission_replay
 from app.modules.artifacts.models import ArtifactStorageNamespace
 from app.modules.artifacts.service import ArtifactStorageNamespaceSpec
@@ -57,6 +59,7 @@ class IntakeReplay:
     maximum_raw_bytes: int
     raw_sha256: str | None
     raw_byte_count: int | None
+    finalization: SubmissionFinalizationProgress | None
 
 
 class IntakeCommitUnknown(RuntimeError):
@@ -75,6 +78,7 @@ def __init__(
         task_contexts: Callable[[AsyncSession], TaskSubmissionContextPort],
         projects: Callable[[AsyncSession], ProjectLockedPolicyContextPort],
         authorization: Callable[[AsyncSession], IntakeAuthorizationPort],
+        events: Callable[[AsyncSession], OutboxAppendPort],
         namespace: ArtifactStorageNamespaceSpec, capacity_limits: SubmissionSourceCapacityLimits,
         maximum_raw_bytes: int, upload_duration: timedelta, lease_duration: timedelta,
     ) -> None:
@@ -85,6 +89,7 @@ def __init__(
             raise ValueError("intake reservation limits are invalid")
         self._sessions, self._tasks, self._contexts = sessions, tasks, task_contexts
         self._projects, self._authorization = projects, authorization
+        self._events = events
         self._namespace = namespace
         self._capacity = SubmissionSourceCapacityLimits.model_validate(capacity_limits)
         self._maximum, self._upload_duration, self._lease_duration = maximum_raw_bytes, upload_duration, lease_duration
@@ -302,7 +307,8 @@ async def _read(self, metadata, actor_id, key, *, expected_operation_id=None):
             if expected_operation_id is not None and UUID(row.id) != expected_operation_id:
                 raise IntakeCustodyConflict("submission_idempotency_conflict")
             result = IntakeReplay(UUID(row.id), row.state, row.failure_code,
-                                  row.maximum_raw_bytes, row.raw_sha256, row.raw_byte_count)
+                                  row.maximum_raw_bytes, row.raw_sha256, row.raw_byte_count,
+                                  await finalization_progress(row, self._events(session)))
         return result
 
     async def replay(
diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py
new file mode 100644
index 000000000..6335bdb9b
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/progress.py
@@ -0,0 +1,27 @@
+"""Derive accepted finalization progress from its exact durable delivery owner."""
+
+from uuid import UUID
+
+from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
+from app.modules.artifacts.intake.acceptance import finalization_event
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+from app.modules.outbox.api import OutboxAppendPort, OutboxIdempotencyConflict
+
+
+async def finalization_progress(row, events: OutboxAppendPort) -> SubmissionFinalizationProgress | None:
+    if row.state not in {"finalization_pending", "finalized"}:
+        return None
+    try:
+        delivery = await events.observe_delivery(UUID(row.finalization_event_id), finalization_event(row))
+    except OutboxIdempotencyConflict as exc:
+        raise IntakeCustodyConflict("submission_finalization_progress_unavailable") from exc
+    finalized = row.state == "finalized"
+    if not finalized and delivery.state in {"acknowledged", "cancelled"}:
+        raise IntakeCustodyConflict("submission_finalization_progress_inconsistent")
+    stalled = not finalized and delivery.state == "dead_letter"
+    return SubmissionFinalizationProgress(
+        operation_id=UUID(row.id), finalized=finalized, operationally_stalled=stalled,
+        stalled_at=delivery.finalized_at if stalled else None,
+        next_retry_at=delivery.next_attempt_at if not finalized else None,
+        attempt_count=delivery.attempt_count,
+    )
diff --git a/backend/app/modules/outbox/api.py b/backend/app/modules/outbox/api.py
index a7ebe6262..825a79b68 100644
--- a/backend/app/modules/outbox/api.py
+++ b/backend/app/modules/outbox/api.py
@@ -493,11 +493,26 @@ class OutboxAppendResult(BaseModel):
     occurred_at: datetime
 
 
+class OutboxDeliveryObservation(DeliveryValue):
+    """Detached operational facts for an exactly matched feature-owned event."""
+
+    event_id: UUID
+    state: Literal["pending", "claimed", "retryable", "acknowledged", "dead_letter", "cancelled"]
+    attempt_count: int = Field(ge=0)
+    next_attempt_at: datetime | None
+    finalized_at: datetime | None
+    error_code: str | None = Field(pattern=r"^[A-Z][A-Z0-9_]{0,79}$")
+
+
 class OutboxAppendPort(Protocol):
     async def require_existing(self, event_id: UUID | None, value: OutboxAppendInput) -> UUID:
         """Require exact retained custody by logical key and optional record ID."""
         ...
 
+    async def observe_delivery(self, event_id: UUID, value: OutboxAppendInput) -> OutboxDeliveryObservation:
+        """Read delivery facts only after exact immutable feature custody matches."""
+        ...
+
     async def append(self, value: OutboxAppendInput) -> OutboxAppendResult:
         """Flush an exact event in the caller transaction without committing."""
         ...
diff --git a/backend/app/modules/outbox/service.py b/backend/app/modules/outbox/service.py
index 70a225ddd..facadaedd 100644
--- a/backend/app/modules/outbox/service.py
+++ b/backend/app/modules/outbox/service.py
@@ -18,6 +18,7 @@
     OutboxIdempotencyConflict,
     OutboxInputError,
     OutboxPersistenceError,
+    OutboxDeliveryObservation,
 )
 
 
@@ -77,8 +78,8 @@ def __init__(self, session: AsyncSession) -> None:
         """Bind the participant to one caller session; never commit or publish."""
         self._repository = OutboxRepository(session)
 
-    async def require_existing(self, event_id: UUID | None, value: OutboxAppendInput) -> UUID:
-        """Validate exact immutable custody without inserting or locking delivery state."""
+    async def _require_record(self, event_id: UUID | None, value: OutboxAppendInput) -> OutboxEvent:
+        """One exact custody check shared by identity and operational reads."""
         validated = _validated_input(value)
         digest = canonical_json_hash(validated.payload)
         try:
@@ -87,7 +88,20 @@ async def require_existing(self, event_id: UUID | None, value: OutboxAppendInput
             _raise_persistence_error()
         if record is None or not _matches(record, validated, digest):
             _raise_idempotency_conflict()
-        return UUID(str(record.event_id))
+        return record
+
+    async def require_existing(self, event_id: UUID | None, value: OutboxAppendInput) -> UUID:
+        """Validate exact immutable custody without inserting or locking delivery state."""
+        return UUID(str((await self._require_record(event_id, value)).event_id))
+
+    async def observe_delivery(self, event_id: UUID, value: OutboxAppendInput) -> OutboxDeliveryObservation:
+        """Observe durable progress without claiming, retrying or publishing work."""
+        record = await self._require_record(event_id, value)
+        return OutboxDeliveryObservation(
+            event_id=UUID(str(record.event_id)), state=record.delivery_state,
+            attempt_count=record.attempt_count, next_attempt_at=record.next_attempt_at,
+            finalized_at=record.finalized_at, error_code=record.last_error_code,
+        )
 
     async def append(self, value: OutboxAppendInput) -> OutboxAppendResult:
         """Create one event or return its exact idempotent replay."""
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 76ecfb07c..12345a22f 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -31,6 +31,7 @@
 
 @pytest.fixture
 async def admission_intake(tmp_path, isolated_database_env, admin_access, request):
+    from app.adapters.outbox import outbox_append
     from app.adapters.projects import project_locked_policy_context_port
     from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission
     from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization
@@ -76,6 +77,7 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
             factory, tasks=lambda session: IntakeTaskCustody(session, task_submission_context_port(session)),
             task_contexts=task_submission_context_port, projects=project_locked_policy_context_port,
             authorization=lambda session: SubmissionIntakeAuthorization(session, actor), namespace=namespace,
+            events=outbox_append,
             capacity_limits=SubmissionSourceCapacityLimits(maximum_total_bytes=1_000_000), maximum_raw_bytes=1024,
             upload_duration=timedelta(seconds=300), lease_duration=timedelta(seconds=60),
         )
@@ -936,3 +938,83 @@ async def lose_ack(envelope):
         assert await handler(invocations[0]) == HandlerOutcome.REJECT
     finally:
         store.close()
+
+
+@pytest.mark.parametrize("effect_committed", [False, True])
+async def test_authorized_progress_reports_exact_exhaustion_without_reopening_intake(
+    admission_intake, tmp_path, monkeypatch, effect_committed,
+):
+    import json
+    from uuid import UUID
+    from sqlalchemy import select, func
+    from app.adapters.artifacts.finalization import submission_finalization_handler
+    from app.adapters.auth import outbox_dispatch_authorization
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append, outbox_delivery
+    from app.modules.actors.api import ServiceIdentity
+    from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied
+    from app.modules.outbox.api import DeliveryOptions
+    from app.modules.outbox.models import OutboxEvent, OutboxDeliveryAttempt
+    from app.modules.outbox.registry import HandlerRegistry
+    from app.modules.tasks.models import WorkstreamTask
+    from tests.artifact_store_helpers import initialize_local_store
+    from tests.artifacts.intake_acceptance_support import completed_source
+    from tests.checkers.execution.support import provision_post_submit_service
+
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER):
+        await provision_post_submit_service(f.factory, identity)
+    async with f.factory() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        key, event_id = UUID(row.idempotency_key), UUID(row.finalization_event_id)
+        metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
+    async def read():
+        return await f.admission._read(metadata, f.actor.actor_profile_id, key)
+    initial = await read()
+    assert initial.finalization.attempt_count == 0 and not initial.finalization.operationally_stalled
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    handler = submission_finalization_handler(sessions=f.factory, settings=_settings(tmp_path),
+        store=store, lease_duration=timedelta(seconds=30))
+    async def fail(envelope):
+        active = await read()
+        assert active.finalization.attempt_count == 1 and not active.finalization.operationally_stalled
+        if effect_committed:
+            await handler(envelope)
+        raise RuntimeError("simulated worker loss")
+    kind = "SubmissionFinalizationRequested"
+    delivery = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
+        registry=HandlerRegistry([(kind, 1, fail)], replay_safe=frozenset({(kind, 1)})),
+        options=DeliveryOptions(lease_seconds=30, handler_timeout_seconds=25, max_attempts=1))
+    try:
+        assert await delivery.deliver(event_id, f.project, "exhausted-worker") is not None
+        progress = await read()
+        assert progress.failure_code is None
+        assert progress.state == ("finalized" if effect_committed else "finalization_pending")
+        assert progress.finalization.finalized is effect_committed
+        assert progress.finalization.operationally_stalled is not effect_committed
+        assert progress.finalization.next_retry_at is None and progress.finalization.attempt_count == 1
+        assert (await read()).finalization == progress.finalization
+        async with f.factory() as session:
+            event = await session.get(OutboxEvent, event_id)
+            task = await session.get(WorkstreamTask, str(f.task))
+            assert event.delivery_state == "dead_letter" and event.last_error_code == "INVOKE_OUTCOME_UNKNOWN"
+            assert progress.finalization.stalled_at == (None if effect_committed else event.finalized_at)
+            assert task.status == "evaluation_pending"
+            assert task.active_submission_operation_id == (None if effect_committed else str(owner.operation_id))
+            assert await session.scalar(select(func.count()).select_from(OutboxDeliveryAttempt)) == 1
+        revoked = await f.access.signed.client.post(
+            f"/api/v1/projects/{f.project}/role-grants/{f.grant_id}/revoke",
+            headers=f.manager.headers | {"Idempotency-Key": str(new_record_id())},
+            json={"reason": "Withdraw progress read grant"},
+        )
+        assert revoked.status_code == 200, revoked.text
+        def forbidden(_session):
+            pytest.fail("denied read consulted delivery facts")
+        monkeypatch.setattr(f.admission, "_events", forbidden)
+        with pytest.raises(IntakeAuthorityDenied):
+            await read()
+    finally:
+        store.close()
diff --git a/backend/tests/outbox/test_delivery_postgresql.py b/backend/tests/outbox/test_delivery_postgresql.py
index 53b836559..0affeac03 100644
--- a/backend/tests/outbox/test_delivery_postgresql.py
+++ b/backend/tests/outbox/test_delivery_postgresql.py
@@ -396,3 +396,37 @@ async def finalize():
         async with session.begin():
             assert await DeliveryRepository(session).fence_invocation(envelope) is None
             assert await DeliveryRepository(session).fence_invocation(object()) is None
+
+
+async def test_delivery_observation_requires_exact_feature_custody(delivery_harness):
+    from app.modules.outbox.api import OutboxAppendInput, OutboxIdempotencyConflict
+    from app.modules.outbox.service import OutboxService
+    h = delivery_harness
+    event = await h.append()
+    value = OutboxAppendInput(**{name: getattr(event, name) for name in OutboxAppendInput.model_fields})
+    async with h.factory() as session:
+        service = OutboxService(session)
+        pending = await service.observe_delivery(event.event_id, value)
+        assert pending.state == "pending" and pending.attempt_count == 0
+        assert pending.finalized_at is pending.error_code is None
+        for changes in (
+            {"project_id": new_record_id()}, {"aggregate_id": new_record_id()},
+            {"aggregate_type": "other"}, {"event_type": "DifferentEvent"}, {"event_version": 2},
+            {"correlation_id": "different"}, {"causation_event_id": new_record_id()},
+            {"idempotency_key": "different"}, {"payload": {"different": True}},
+            {"not_before_at": pending.next_attempt_at + timedelta(seconds=1)},
+        ):
+            with pytest.raises(OutboxIdempotencyConflict):
+                await service.observe_delivery(event.event_id, value.model_copy(update=changes))
+        with pytest.raises(OutboxIdempotencyConflict):
+            await service.observe_delivery(new_record_id(), value)
+        assert (await session.get(OutboxEvent, event.event_id)).attempt_count == 0
+        assert list(await session.scalars(select(OutboxDeliveryAttempt))) == []
+        claim = await h.delivery.claim(event.event_id, h.project, "observed-worker")
+        active = await service.observe_delivery(event.event_id, value)
+        assert active.state == "claimed" and active.attempt_count == 1
+        assert active.next_attempt_at is None
+        assert await h.delivery.invoke(claim) is not None
+        acknowledged = await service.observe_delivery(event.event_id, value)
+        assert acknowledged.state == "acknowledged" and acknowledged.finalized_at is not None
+        assert acknowledged.attempt_count == 1

From d036edfc927ea33b2b38c264be521b5b399ac03e Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 23:14:51 +0100
Subject: [PATCH 123/513] Record finalization progress review and recovery
 constraints

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 25 +++++++++++++++++--
 1 file changed, 23 insertions(+), 2 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 80658b179..149e3dcec 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -25,8 +25,9 @@ MinIO tests do not qualify AWS. Detailed evidence below belongs to its stated
 commit or worktree, not automatically to every later head.
 
 Finalization now has production OUTBOX registration and invocation fencing, with
-real PostgreSQL recovery proof. Full Celery/provider execution, independent worker
-capacity, stalled-operation projection and operator recovery remain unfinished.
+real PostgreSQL recovery proof. A dedicated local worker queue and internal
+authorized stall projection are implemented. Full Celery/provider execution,
+independent worker capacity, public progress and operator recovery remain unfinished.
 Next: close those durable-worker gaps, then complete cleanup and public API/CLI/MCP
 cutover, real revision/review/ContributionRecord journeys, policy cardinality and
 the A01–A35/C01–C07 completion audit. No public end-to-end readiness is claimed.
@@ -3033,3 +3034,23 @@ contracts and ART architecture checks passed (`/tmp/t5-progress-static.log`:
 **94 passed**). Evidence is for the working tree based on `cb09fd84c`; it does
 not prove public operation reads or operator retry. Ruff passed for all changed
 Python files.
+
+Scoped architecture/security and QA/test-delta reviews passed on clean
+`82452d5f314d163b44c43fa6063ac44a6f60b033`, against `cb09fd84c`. Reviewers checked
+current authorization before observer construction, exact immutable event custody,
+finalized precedence, refusal of inconsistent terminal delivery, and absence of
+provider/retry effects. Structure, Commitrail and Markdown-link checks also passed.
+A fresh fetch found no missing `origin/main` commits.
+
+Recovery follow-up must reuse the registered, currently planned
+`operations.submission_gate.repair` action only for its narrow recovery purpose.
+Current AUTH specifications require a system Operator grant, exact resource,
+reason and append-only evidence. Existing POST delivery reconciliation is a
+reference for retaining the original terminal attempt and authorizing a bounded
+child; its current UNKNOWN-only contract cannot simply be relabelled as general
+finalization recovery. Any implementation must qualify exact accepted operation,
+source, event and current retry ownership, preserve original outcomes, and reuse
+T5 rather than create another Submission path. In particular, finalizer lease
+expiry currently uses the original envelope: a recovery child must supply its
+verified live lease bound while retaining the original accepted event identity.
+No recovery action has been activated by this checkpoint.

From a32a870f8f5b2d8309551fac12940a0aea77389c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 12 Nov 2026 23:47:28 +0100
Subject: [PATCH 124/513] Add audited recovery for accepted submission
 finalization

---
 .ci/auth-boundaries/TEST_STRUCTURE_DEBT.json  |   4 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  69 ++++++++++
 .../versions/0077_submission_recovery.py      |  96 ++++++++++++++
 .../app/adapters/artifacts/finalization.py    |  59 ++++++---
 backend/app/adapters/auth/__init__.py         |  14 +++
 backend/app/adapters/outbox/__init__.py       |  17 ++-
 .../artifacts/api/submission_finalization.py  |   1 +
 .../artifacts/api/submission_recovery.py      |  75 +++++++++++
 .../modules/artifacts/intake/finalization.py  |   2 +-
 .../artifacts/intake/finalization_delivery.py |  33 +++--
 .../artifacts/intake/foreground_admission.py  |   7 +-
 .../app/modules/artifacts/intake/progress.py  |  32 ++++-
 .../app/modules/artifacts/intake/recovery.py  |  84 +++++++++++++
 .../artifacts/intake/recovery_delivery.py     |  79 ++++++++++++
 .../authorization/action_definitions.py       |   2 +-
 .../app/modules/authorization/catalogue.py    |   1 +
 .../authorization/domain/action_groups.py     |   3 +
 .../app/modules/authorization/domain/audit.py |   2 +
 .../authorization/domain/audit_targets.py     |   4 +
 .../domain/submission_recovery.py             |  26 ++++
 backend/app/modules/authorization/kernel.py   |  14 ++-
 backend/app/modules/authorization/runtime.py  |   2 +
 .../authorization/submission_recovery.py      |  74 +++++++++++
 backend/app/modules/outbox/models.py          |   4 +
 backend/app/workers/outbox.py                 |   2 +-
 .../test_submission_intake_admission.py       | 118 +++++++++++++++++-
 .../tests/authorization/catalogue_fixtures.py |   1 +
 backend/tests/authorization/test_catalogue.py |   4 +-
 backend/tests/conftest.py                     |   2 +-
 .../tests/outbox/test_delivery_topology.py    |   6 +-
 .../tests/outbox/test_worker_postgresql.py    |   3 +-
 docs/architecture_checker_framework.md        |   7 +-
 docs/operations_authorization_service.md      |   2 +-
 docs/operations_roles_permissions.md          |   2 +-
 docs/roles_permissions.md                     |   8 +-
 docs/spec_authorization_service.md            |   7 +-
 36 files changed, 804 insertions(+), 62 deletions(-)
 create mode 100644 backend/alembic/versions/0077_submission_recovery.py
 create mode 100644 backend/app/modules/artifacts/api/submission_recovery.py
 create mode 100644 backend/app/modules/artifacts/intake/recovery.py
 create mode 100644 backend/app/modules/artifacts/intake/recovery_delivery.py
 create mode 100644 backend/app/modules/authorization/domain/submission_recovery.py
 create mode 100644 backend/app/modules/authorization/submission_recovery.py

diff --git a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
index b247d4369..5ddb6ce00 100644
--- a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
+++ b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
@@ -15,14 +15,14 @@
     {
       "capability": "oversized_authorization_structure",
       "content_sha256": "bae6d1bf2568947ee4125b3389d861fb7c077a346da1efcef3167b68ce7cafd5",
-      "end_line": 742,
+      "end_line": 744,
       "hard_limit": 100,
       "kind": "production_function",
       "observed_lines": 105,
       "path": "backend/app/modules/authorization/kernel.py",
       "qualified_symbol": "AuthorizationService._require_prelocked",
       "removal_chunk": "WS-AUTH-003-CLOSE",
-      "start_line": 638
+      "start_line": 640
     },
     {
       "capability": "oversized_authorization_structure",
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 149e3dcec..ee4669b76 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3054,3 +3054,72 @@ T5 rather than create another Submission path. In particular, finalizer lease
 expiry currently uses the original envelope: a recovery child must supply its
 verified live lease bound while retaining the original accepted event identity.
 No recovery action has been activated by this checkpoint.
+
+### Accepted-finalization operator recovery
+
+Close C05's recovery gap using existing `operations.submission_gate.repair` and
+OUTBOX finalized-UNKNOWN reconciliation custody. The first recovery uses the
+existing one-child-per-original convention: a failed child remains visibly held;
+there is no implicit new contributor command or unlimited retry loop. The original
+accepted event and completed attempts remain immutable. Recovery must invoke the
+same T5, retain its current service authority, and bind its lease to the live
+child rather than the expired original.
+
+Allowed scope: ART recovery values, owner and existing finalizer/handler; AUTH
+resource/action activation and audit verification; existing OUTBOX reconciliation
+ports; composition, worker routing, narrow SQL custody migration, corresponding
+real PostgreSQL tests and current recovery documentation. No broadening of
+Operator authority, QC override, source rewrite, new Submission writer, retained
+data deletion or deployment defaults. Risk is authorization/workflow (L0).
+
+Acceptance evidence: authorized exact retry and replay after revoked grant;
+concurrent commands produce one child; reason/key/source substitutions fail;
+failed authority rolls back child creation; worker verifies retained decision and
+live child fence; successful recovery creates exactly one Submission/dispatch;
+expired or substituted child cannot act; exhausted child is visible and keeps
+source protection. Required reviews: architecture/security and QA/test delta,
+plus documentation for public exposure claims. Human review focus is the exact
+recovery authority and preservation of accepted evidence. This scope remains
+unexposed until its composed behavior and custody checks pass.
+
+The broader intake regression run completed: `/tmp/t5-progress-full.log` reports
+**36 passed in 705.07s**; metadata records launch head `82452d5f3` and successful
+database/role cleanup. Recovery development overlapped the tail of this run, so
+this is regression evidence for the progress work, not a frozen recovery proof.
+
+Recovery implementation is in progress. The first focused run caught the closed
+active-action catalogue boundary; the second reached the command but caught the
+missing authorization-decision resource literal. Both were repaired without
+weakening either registry. Migration execution caught a multi-statement prepared
+query; function and trigger creation now use separate statements. No successful
+recovery end-to-end claim is made until the composed PostgreSQL test passes.
+
+The composed recovery run `/tmp/t5-recovery4.log` passed **4 PostgreSQL tests**
+(92.90s; isolated database/role cleanup confirmed). It covers current Operator
+authority, concurrent requests producing one child, exact replay, reason conflict,
+direct-SQL forged reason/decision refusal, revoked-grant denial, live recovery
+progress, one Submission and POST event, and production worker registration and
+group isolation. The original delivery remains dead-lettered and immutable.
+
+Related static checks passed **84 tests**; the sole stale active/planned-count
+assertion was updated from 168/25 to 169/24 for activation of the existing action,
+and its focused rerun passed (`/tmp/t5-recovery-catalogue.log`). No action or
+permission was added. OUTBOX rejected the initial `request_key` payload field
+under its existing privacy guard; recovery now names its persisted command
+identity `request_id`, with no guard exception or compatibility alias.
+
+Migration 0077 adds one unique recovery-parent index, one custody function and
+one insert trigger, and extends only the existing exact UNKNOWN-retry allowlist.
+The PostgreSQL-observed schema fingerprint is
+`1d0060750a195d348606ae5eaf9ae9a47462e1cf6062f278c9f2b408b707f8b2`
+(`/tmp/t5-recovery-schema3.log`); the subsequent passing run validated it. The
+structure ledger updates only the two-line source offset for unchanged
+`AuthorizationService._require_prelocked`; its size and hash are preserved and
+structure validation passed. No new debt or exception was introduced.
+
+Additional regression in progress explicitly waits for the original delivery
+lease to expire before successful recovery and rejects a stale child invocation
+after acknowledgement. This must complete before claiming the recovery checkpoint
+verified. The one-child limit follows existing reconciliation: exhaustion remains
+held, not an automatic contributor retry. Public operator discovery/command
+routes and the full public operation progress contract remain outstanding.
diff --git a/backend/alembic/versions/0077_submission_recovery.py b/backend/alembic/versions/0077_submission_recovery.py
new file mode 100644
index 000000000..cf84b7cb6
--- /dev/null
+++ b/backend/alembic/versions/0077_submission_recovery.py
@@ -0,0 +1,96 @@
+"""Bind one finalization recovery child to accepted custody and Operator evidence."""
+
+from alembic import op
+from sqlalchemy import text
+
+revision = "0077_submission_recovery"
+down_revision = "0076_submission_delivery_retry"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.outbox_events IN SHARE ROW EXCLUSIVE MODE")
+    op.execute("""CREATE UNIQUE INDEX uq_submission_finalization_recovery_original
+        ON public.outbox_events(causation_event_id)
+        WHERE event_type='SubmissionFinalizationRecoveryRequested'""")
+    op.execute(r"""
+CREATE FUNCTION public.require_submission_recovery_child() RETURNS trigger
+LANGUAGE plpgsql AS $$
+DECLARE o public.submission_intake_operations%ROWTYPE;
+        e public.outbox_events%ROWTYPE;
+        a public.outbox_delivery_attempts%ROWTYPE;
+        d public.audit_events%ROWTYPE;
+        p jsonb; c jsonb; s jsonb; authority jsonb; resource jsonb; expected_source jsonb;
+        expected_command jsonb; expected_authority jsonb; digest text;
+BEGIN
+ IF NEW.event_type<>'SubmissionFinalizationRecoveryRequested' THEN RETURN NEW; END IF;
+ p := NEW.payload; c := p->'command'; s := p->'source'; authority := p->'authority';
+ SELECT * INTO o FROM public.submission_intake_operations WHERE id=(s->>'operation_id')::uuid;
+ IF NOT FOUND OR o.state<>'finalization_pending' THEN
+   RAISE EXCEPTION 'recovery requires accepted pending operation' USING ERRCODE='23514'; END IF;
+ PERFORM public.require_submission_acceptance(o);
+ SELECT * INTO e FROM public.outbox_events WHERE event_id=o.finalization_event_id;
+ SELECT * INTO a FROM public.outbox_delivery_attempts
+   WHERE event_id=e.event_id AND claim_generation=e.claim_generation;
+ IF e.event_type IS DISTINCT FROM 'SubmissionFinalizationRequested' OR e.event_version<>1
+   OR e.delivery_state IS DISTINCT FROM 'dead_letter'
+   OR e.last_error_code IS DISTINCT FROM 'INVOKE_OUTCOME_UNKNOWN'
+   OR a.stage IS DISTINCT FROM 'completed'
+   OR (a.outcome_json::jsonb->>'invocation_unknown') IS DISTINCT FROM 'true'
+   OR NEW.event_version<>1 OR NEW.aggregate_type<>'outbox_delivery'
+   OR NEW.aggregate_id IS DISTINCT FROM e.event_id OR NEW.causation_event_id IS DISTINCT FROM e.event_id
+   OR NEW.project_id IS DISTINCT FROM o.project_id
+   OR NEW.idempotency_key IS DISTINCT FROM 'submission-finalization-recovery:'||e.event_id::text
+   OR NEW.correlation_id IS DISTINCT FROM c->>'request_id' THEN
+   RAISE EXCEPTION 'recovery original delivery differs' USING ERRCODE='23514'; END IF;
+ expected_source := jsonb_build_object('operation_id',o.id::text,'project_id',o.project_id::text,
+   'task_id',o.task_id::text,'original_event_id',e.event_id::text,
+   'original_claim_generation',e.claim_generation,'original_payload_digest',e.payload_digest,
+   'acceptance_receipt_sha256',o.acceptance_receipt_sha256);
+ expected_command := jsonb_build_object('operation_id',o.id::text,'project_id',o.project_id::text,
+   'actor_profile_id',(c->>'actor_profile_id')::uuid::text,
+   'request_id',(c->>'request_id')::uuid::text,'reason',c->>'reason');
+ IF s IS DISTINCT FROM expected_source OR c IS DISTINCT FROM expected_command
+   OR c->>'reason' IS NULL OR length(c->>'reason') NOT BETWEEN 1 AND 500
+   OR c->>'reason' IS DISTINCT FROM btrim(c->>'reason') OR (c->>'reason') ~ '[[:cntrl:]]' THEN
+   RAISE EXCEPTION 'recovery exact source or command differs' USING ERRCODE='23514'; END IF;
+ resource := jsonb_build_object('resource_type','submission_operation','resource_id',o.id::text,
+   'scope_project_id',o.project_id::text,'identity_link_id',(authority->>'identity_link_id')::uuid::text,
+   'command',c,'source',s);
+ digest := public.external_checker_registry_digest(jsonb_build_object('resource_context',resource));
+ expected_authority := jsonb_build_object('decision_id',(authority->>'decision_id')::uuid::text,
+   'identity_link_id',(authority->>'identity_link_id')::uuid::text,'resource_digest',digest);
+ IF authority IS DISTINCT FROM expected_authority OR p IS DISTINCT FROM
+   jsonb_build_object('command',c,'source',s,'authority',authority) THEN
+   RAISE EXCEPTION 'recovery authority shape differs' USING ERRCODE='23514'; END IF;
+ SELECT * INTO d FROM public.audit_events WHERE id=(authority->>'decision_id')::uuid;
+ IF NOT FOUND OR d.event_type<>'SensitiveAuthorizationAllowed'
+   OR d.action_id IS DISTINCT FROM 'operations.submission_gate.repair'
+   OR d.permission_id IS DISTINCT FROM 'operations.submission_gate.repair'
+   OR d.actor_id IS DISTINCT FROM c->>'actor_profile_id'
+   OR d.project_id IS DISTINCT FROM o.project_id
+   OR d.resource_type IS DISTINCT FROM 'submission_operation' OR d.resource_id IS DISTINCT FROM o.id::text
+   OR d.request_id::text IS DISTINCT FROM c->>'request_id'
+   OR d.correlation_id::text IS DISTINCT FROM c->>'request_id' OR d.denial_code IS NOT NULL
+   OR d.after_facts::jsonb IS DISTINCT FROM jsonb_build_object('allowed',true,'resource_context_digest',digest) THEN
+   RAISE EXCEPTION 'recovery retained Operator cause differs' USING ERRCODE='23514'; END IF;
+ RETURN NEW;
+END $$;
+""")
+    op.execute("""CREATE TRIGGER submission_recovery_child_custody BEFORE INSERT ON public.outbox_events
+ FOR EACH ROW EXECUTE FUNCTION public.require_submission_recovery_child();
+""")
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef('public.check_outbox_delivery_projection()'::regprocedure)"
+    )).scalar_one()
+    old = "'TaskRevisionExpired','SubmissionFinalizationRequested')"
+    new = "'TaskRevisionExpired','SubmissionFinalizationRequested','SubmissionFinalizationRecoveryRequested')"
+    if body.count(old) != 1:
+        raise RuntimeError("submission recovery retry predecessor shape changed")
+    op.execute(body.replace(old, new))
+
+
+def downgrade():
+    raise RuntimeError("Retained finalization recovery cannot be downgraded")
diff --git a/backend/app/adapters/artifacts/finalization.py b/backend/app/adapters/artifacts/finalization.py
index e17b80957..124d7d247 100644
--- a/backend/app/adapters/artifacts/finalization.py
+++ b/backend/app/adapters/artifacts/finalization.py
@@ -10,27 +10,46 @@
 )
 
 
-def submission_finalization_handler(*, sessions, settings, store, lease_duration):
+def accepted_submission_finalizer(*, sessions, settings, store, lease_duration, invocation):
+    """One T5 composition for original delivery and authorized recovery."""
     from app.adapters.artifacts import submission_admission_consumption_port
     from app.adapters.checkers import selected_pre_submit_coordinator
-    from app.adapters.outbox import committed_invocation_reader, outbox_invocation_fence
     from app.adapters.tasks import accepted_submission_creation_service, intake_task_custody_port
 
-    def finalizer(envelope):
-        operation_id = envelope.aggregate_id
-        def submissions(session):
-            return accepted_submission_creation_service(session, settings=settings,
-                admissions=submission_admission_consumption_port(session,
-                    request_id=new_record_id(), correlation_id=operation_id))
-        return AcceptedSubmissionFinalization(
-            sessions, tasks=intake_task_custody_port, submissions=submissions,
-            checkers=selected_pre_submit_coordinator, store=store, lease_duration=lease_duration,
-            authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
-                session, request_id=new_record_id(), correlation_id=operation_id),
-            delivery=FinalizationInvocation(envelope, outbox_invocation_fence),
-        )
+    operation_id = invocation.envelope.aggregate_id
+    def submissions(session):
+        return accepted_submission_creation_service(session, settings=settings,
+            admissions=submission_admission_consumption_port(session,
+                request_id=new_record_id(), correlation_id=operation_id))
+    return AcceptedSubmissionFinalization(
+        sessions, tasks=intake_task_custody_port, submissions=submissions,
+        checkers=selected_pre_submit_coordinator, store=store, lease_duration=lease_duration,
+        authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
+            session, request_id=new_record_id(), correlation_id=operation_id),
+        delivery=invocation,
+    )
+
+
+def submission_finalization_handler(*, sessions, settings, store, lease_duration):
+    from app.adapters.outbox import committed_invocation_reader, outbox_invocation_fence
     return SubmissionFinalizationHandler(
-        observer=committed_invocation_reader(sessions), finalizer=finalizer,
+        observer=committed_invocation_reader(sessions),
+        finalizer=lambda envelope: accepted_submission_finalizer(
+            sessions=sessions, settings=settings, store=store, lease_duration=lease_duration,
+            invocation=FinalizationInvocation(envelope, outbox_invocation_fence)),
+    )
+
+
+def submission_finalization_recovery_handler(*, sessions, settings, store, lease_duration):
+    from app.adapters.auth import submission_recovery_cause_authorization
+    from app.adapters.outbox import finalized_unknown_deliveries
+    from app.modules.artifacts.intake.recovery_delivery import SubmissionFinalizationRecoveryHandler
+    return SubmissionFinalizationRecoveryHandler(
+        sessions=sessions, deliveries=finalized_unknown_deliveries,
+        authorization=submission_recovery_cause_authorization,
+        finalizer=lambda invocation: accepted_submission_finalizer(
+            sessions=sessions, settings=settings, store=store, lease_duration=lease_duration,
+            invocation=invocation),
     )
 
 
@@ -54,3 +73,11 @@ def worker_submission_finalization_handler(*, sessions, delivery_options):
         sessions=sessions, settings=get_settings(), store=_WorkerSourceObservation(),
         lease_duration=timedelta(seconds=delivery_options.lease_seconds),
     )
+
+
+def worker_submission_finalization_recovery_handler(*, sessions, delivery_options):
+    from app.core.config import get_settings
+    return submission_finalization_recovery_handler(
+        sessions=sessions, settings=get_settings(), store=_WorkerSourceObservation(),
+        lease_duration=timedelta(seconds=delivery_options.lease_seconds),
+    )
diff --git a/backend/app/adapters/auth/__init__.py b/backend/app/adapters/auth/__init__.py
index 2cfc6966d..8939f63cf 100644
--- a/backend/app/adapters/auth/__init__.py
+++ b/backend/app/adapters/auth/__init__.py
@@ -620,3 +620,17 @@ async def validate_replay(self, source, retained, effects, authorized_generation
 def task_routing_authorization(session):
     """Compose canonical router AUTH through the designated AUTH composition root."""
     return _TaskRoutingAuthorizationAdapter(session)
+
+
+def submission_recovery_authorization(session: AsyncSession, context: AuthorizationContext):
+    """Compose exact finalization gate repair under current system Operator authority."""
+    from app.modules.authorization.submission_recovery import SubmissionRecoveryAuthorization
+    repository = AdminAuthorizationRepository(session)
+    kernel = AuthorizationService(session, context, admin_repository=repository)
+    return SubmissionRecoveryAuthorization(session, context, kernel)
+
+
+def submission_recovery_cause_authorization(session: AsyncSession):
+    """Validate retained recovery cause; grants no fresh human authority."""
+    from app.modules.authorization.submission_recovery import SubmissionRecoveryAuthorization
+    return SubmissionRecoveryAuthorization(session, None, None)
diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py
index f8da21083..6cb333dcb 100644
--- a/backend/app/adapters/outbox/__init__.py
+++ b/backend/app/adapters/outbox/__init__.py
@@ -46,7 +46,10 @@ def outbox_delivery(
 def production_outbox_delivery(session_factory, *, finalization_worker: bool | None = None):
     """Compose all handlers for discovery, or one explicit worker group for delivery."""
     from app.adapters.artifacts import worker_post_submission_materialization
-    from app.adapters.artifacts.finalization import worker_submission_finalization_handler
+    from app.adapters.artifacts.finalization import (
+        worker_submission_finalization_handler, worker_submission_finalization_recovery_handler,
+    )
+    from app.modules.artifacts.api.submission_recovery import FINALIZATION_RECOVERY_EVENT
     from app.modules.artifacts.api.submission_finalization import SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS
     from app.adapters.auth import (
         outbox_dispatch_authorization,
@@ -87,6 +90,13 @@ def production_outbox_delivery(session_factory, *, finalization_worker: bool | N
                     sessions=session_factory, delivery_options=finalization_options,
                 ),
             ),
+            (
+                FINALIZATION_RECOVERY_EVENT,
+                1,
+                worker_submission_finalization_recovery_handler(
+                    sessions=session_factory, delivery_options=finalization_options,
+                ),
+            ),
             (
                 ASSIGNMENT_INVALIDATION_EVENT,
                 1,
@@ -155,17 +165,18 @@ def production_outbox_delivery(session_factory, *, finalization_worker: bool | N
                 ),
             ),
         ],
-        replay_safe=frozenset({("SubmissionFinalizationRequested", 1), (REVISION_EXPIRY_EVENT, 1), (REVISION_EXPIRED_EVENT, 1), (REVISION_CONTEXT_BLOCKED_EVENT, 1), (REVISION_EXHAUSTED_EVENT, 1)}),
+        replay_safe=frozenset({("SubmissionFinalizationRequested", 1), (FINALIZATION_RECOVERY_EVENT, 1), (REVISION_EXPIRY_EVENT, 1), (REVISION_EXPIRED_EVENT, 1), (REVISION_CONTEXT_BLOCKED_EVENT, 1), (REVISION_EXHAUSTED_EVENT, 1)}),
     )
     if finalization_worker is not None:
         keys = tuple(key for key in registry.keys
-                     if (key[0] == "SubmissionFinalizationRequested") == finalization_worker)
+                     if (key[0] in {"SubmissionFinalizationRequested", FINALIZATION_RECOVERY_EVENT}) == finalization_worker)
         registry = HandlerRegistry(
             [(kind, version, registry.get(kind, version)) for kind, version in keys],
             replay_safe=frozenset(key for key in keys if registry.can_retry_unknown(*key)),
         )
     event_options = {
         ("SubmissionFinalizationRequested", 1): finalization_options,
+        (FINALIZATION_RECOVERY_EVENT, 1): finalization_options,
         (REQUEST_EVENT, 1): DeliveryOptions(
             lease_seconds=SELECTED_POST_DELIVERY_LEASE_SECONDS,
             handler_timeout_seconds=SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
diff --git a/backend/app/modules/artifacts/api/submission_finalization.py b/backend/app/modules/artifacts/api/submission_finalization.py
index 619f57e9e..907708d27 100644
--- a/backend/app/modules/artifacts/api/submission_finalization.py
+++ b/backend/app/modules/artifacts/api/submission_finalization.py
@@ -17,6 +17,7 @@ class SubmissionFinalizationProgress:
     finalized: bool
     operationally_stalled: bool
     stalled_at: datetime | None
+    stalled_reason: str | None
     next_retry_at: datetime | None
     attempt_count: int
 
diff --git a/backend/app/modules/artifacts/api/submission_recovery.py b/backend/app/modules/artifacts/api/submission_recovery.py
new file mode 100644
index 000000000..fdc2d1edc
--- /dev/null
+++ b/backend/app/modules/artifacts/api/submission_recovery.py
@@ -0,0 +1,75 @@
+"""Exact accepted-finalization recovery values; none confer authority."""
+
+from typing import Literal, Protocol
+from uuid import UUID
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+
+
+FINALIZATION_RECOVERY_EVENT = "SubmissionFinalizationRecoveryRequested"
+FINALIZATION_RECOVERY_SOURCES = (("SubmissionFinalizationRequested", 1),)
+
+
+class RecoveryValue(BaseModel):
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True,
+                              revalidate_instances="always", hide_input_in_errors=True)
+
+
+class SubmissionRecoveryCommand(RecoveryValue):
+    operation_id: UUID
+    project_id: UUID
+    actor_profile_id: UUID
+    request_id: UUID
+    reason: str = Field(min_length=1, max_length=500)
+
+    @field_validator("reason")
+    @classmethod
+    def bounded_reason(cls, value):
+        if value != value.strip() or any(ord(c) < 32 or ord(c) == 127 for c in value):
+            raise ValueError("invalid finalization recovery reason")
+        return value
+
+
+class SubmissionRecoverySource(RecoveryValue):
+    operation_id: UUID
+    project_id: UUID
+    task_id: UUID
+    original_event_id: UUID
+    original_claim_generation: int = Field(gt=0)
+    original_payload_digest: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    acceptance_receipt_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+
+
+class SubmissionRecoveryAuthority(RecoveryValue):
+    decision_id: UUID
+    identity_link_id: UUID
+    resource_digest: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+
+
+class SubmissionRecoveryPayload(RecoveryValue):
+    command: SubmissionRecoveryCommand
+    source: SubmissionRecoverySource
+    authority: SubmissionRecoveryAuthority
+
+    @model_validator(mode="after")
+    def exact_source(self):
+        if (self.command.operation_id != self.source.operation_id
+                or self.command.project_id != self.source.project_id):
+            raise ValueError("finalization recovery source differs")
+        return self
+
+
+class SubmissionRecoveryResult(RecoveryValue):
+    operation_id: UUID
+    recovery_event_id: UUID
+    state: Literal["pending", "active", "acknowledged", "unknown", "held"]
+
+
+class SubmissionRecoveryUnavailable(RuntimeError):
+    """Absent, denied, conflicting or unqualified recovery; no provider detail."""
+
+
+class SubmissionRecoveryAuthorizationPort(Protocol):
+    async def authorize(self, command: SubmissionRecoveryCommand,
+                        source: SubmissionRecoverySource) -> SubmissionRecoveryAuthority: ...
+    async def validate_cause(self, payload: SubmissionRecoveryPayload) -> None: ...
diff --git a/backend/app/modules/artifacts/intake/finalization.py b/backend/app/modules/artifacts/intake/finalization.py
index 47bf99bfe..e5be2d663 100644
--- a/backend/app/modules/artifacts/intake/finalization.py
+++ b/backend/app/modules/artifacts/intake/finalization.py
@@ -114,7 +114,7 @@ async def _claim(self, operation_id, lease_id):
             row.continuation_lease_id, row.continuation_generation = str(lease_id), generation
             expires_at = now + self._duration
             if self._delivery is not None:
-                expires_at = min(expires_at, self._delivery.envelope.claim.claim_expires_at)
+                expires_at = min(expires_at, self._delivery.lease_expires_at)
             row.continuation_expires_at, row.continuation_decision_id = expires_at, str(decision)
             await session.flush()
             return AcceptedContinuation(SubmissionIntakeRepository._sealed_source(row), lease_id, generation)
diff --git a/backend/app/modules/artifacts/intake/finalization_delivery.py b/backend/app/modules/artifacts/intake/finalization_delivery.py
index f0dbb40e4..213a13dc6 100644
--- a/backend/app/modules/artifacts/intake/finalization_delivery.py
+++ b/backend/app/modules/artifacts/intake/finalization_delivery.py
@@ -12,6 +12,21 @@
 from app.modules.outbox.api import HandlerOutcome, InvocationFencePort, OutboxEventEnvelope
 
 
+def require_finalization_event(row, envelope):
+    expected = finalization_event(row)
+    if (
+        str(envelope.claim.event_id) != row.finalization_event_id
+        or str(envelope.claim.project_id) != row.project_id
+        or any(getattr(envelope, key) != getattr(expected, key) for key in (
+            "event_type", "event_version", "aggregate_type", "aggregate_id",
+            "correlation_id", "causation_event_id", "idempotency_key",
+        ))
+        or envelope.payload_json != json.dumps(expected.payload, sort_keys=True,
+            separators=(",", ":"), ensure_ascii=False, allow_nan=False)
+        or envelope.claim.payload_digest != canonical_json_hash(expected.payload)
+    ):
+        raise IntakeCustodyConflict("finalization_delivery_mismatch")
+
 @dataclass(frozen=True)
 class FinalizationInvocation:
     """An invocation is evidence to recheck, never feature authorization."""
@@ -19,21 +34,13 @@ class FinalizationInvocation:
     envelope: OutboxEventEnvelope
     fence_factory: Callable[[AsyncSession], InvocationFencePort]
 
+    @property
+    def lease_expires_at(self):
+        return self.envelope.claim.claim_expires_at
+
     async def fence(self, session, row):
-        expected = finalization_event(row)
+        require_finalization_event(row, self.envelope)
         envelope = self.envelope
-        if (
-            str(envelope.claim.event_id) != row.finalization_event_id
-            or str(envelope.claim.project_id) != row.project_id
-            or any(getattr(envelope, key) != getattr(expected, key) for key in (
-                "event_type", "event_version", "aggregate_type", "aggregate_id",
-                "correlation_id", "causation_event_id", "idempotency_key",
-            ))
-            or envelope.payload_json != json.dumps(expected.payload, sort_keys=True,
-                separators=(",", ":"), ensure_ascii=False, allow_nan=False)
-            or envelope.claim.payload_digest != canonical_json_hash(expected.payload)
-        ):
-            raise IntakeCustodyConflict("finalization_delivery_mismatch")
         observed = await self.fence_factory(session).fence_invocation(envelope)
         if observed is None or observed.claim != envelope.claim:
             raise IntakeCustodyConflict("finalization_delivery_stale")
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index 9e67f1e33..aaa068825 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -33,7 +33,7 @@
 )
 from app.modules.checkers.api.external_policy import LockedExternalCheckerPolicies
 from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitCoordinationPort, SelectedPreSubmitReservationFacts
-from app.modules.outbox.api import OutboxAppendPort
+from app.modules.outbox.api import OutboxAppendPort, FinalizedUnknownDeliveryPort
 from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextPort, ProjectLockedPolicyContextRequest
 from app.modules.projects.api.policy_lineage import RevisionPolicySemantics
 from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort
@@ -79,6 +79,7 @@ def __init__(
         projects: Callable[[AsyncSession], ProjectLockedPolicyContextPort],
         authorization: Callable[[AsyncSession], IntakeAuthorizationPort],
         events: Callable[[AsyncSession], OutboxAppendPort],
+        deliveries: Callable[[AsyncSession], FinalizedUnknownDeliveryPort],
         namespace: ArtifactStorageNamespaceSpec, capacity_limits: SubmissionSourceCapacityLimits,
         maximum_raw_bytes: int, upload_duration: timedelta, lease_duration: timedelta,
     ) -> None:
@@ -89,7 +90,7 @@ def __init__(
             raise ValueError("intake reservation limits are invalid")
         self._sessions, self._tasks, self._contexts = sessions, tasks, task_contexts
         self._projects, self._authorization = projects, authorization
-        self._events = events
+        self._events, self._deliveries = events, deliveries
         self._namespace = namespace
         self._capacity = SubmissionSourceCapacityLimits.model_validate(capacity_limits)
         self._maximum, self._upload_duration, self._lease_duration = maximum_raw_bytes, upload_duration, lease_duration
@@ -308,7 +309,7 @@ async def _read(self, metadata, actor_id, key, *, expected_operation_id=None):
                 raise IntakeCustodyConflict("submission_idempotency_conflict")
             result = IntakeReplay(UUID(row.id), row.state, row.failure_code,
                                   row.maximum_raw_bytes, row.raw_sha256, row.raw_byte_count,
-                                  await finalization_progress(row, self._events(session)))
+                                  await finalization_progress(row, self._events(session), self._deliveries(session)))
         return result
 
     async def replay(
diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py
index 6335bdb9b..35235b0a8 100644
--- a/backend/app/modules/artifacts/intake/progress.py
+++ b/backend/app/modules/artifacts/intake/progress.py
@@ -5,10 +5,14 @@
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
 from app.modules.artifacts.intake.acceptance import finalization_event
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict
-from app.modules.outbox.api import OutboxAppendPort, OutboxIdempotencyConflict
+from app.modules.artifacts.intake.recovery import recovery_event
+from app.modules.artifacts.api.submission_recovery import (
+    FINALIZATION_RECOVERY_EVENT, FINALIZATION_RECOVERY_SOURCES, SubmissionRecoveryPayload,
+)
+from app.modules.outbox.api import OutboxAppendPort, OutboxIdempotencyConflict, DeliveryUnavailable
 
 
-async def finalization_progress(row, events: OutboxAppendPort) -> SubmissionFinalizationProgress | None:
+async def finalization_progress(row, events: OutboxAppendPort, deliveries) -> SubmissionFinalizationProgress | None:
     if row.state not in {"finalization_pending", "finalized"}:
         return None
     try:
@@ -16,6 +20,28 @@ async def finalization_progress(row, events: OutboxAppendPort) -> SubmissionFina
     except OutboxIdempotencyConflict as exc:
         raise IntakeCustodyConflict("submission_finalization_progress_unavailable") from exc
     finalized = row.state == "finalized"
+    attempt_count = delivery.attempt_count
+    try:
+        if delivery.state == "dead_letter" and delivery.error_code == "INVOKE_OUTCOME_UNKNOWN":
+            retained = await deliveries.read_finalized_unknown(
+                project_id=UUID(row.project_id), event_id=UUID(row.finalization_event_id),
+                event_types=FINALIZATION_RECOVERY_SOURCES,
+                child_event_type=FINALIZATION_RECOVERY_EVENT, lock=False,
+            )
+            if retained is not None and retained.child is not None:
+                payload = SubmissionRecoveryPayload.model_validate_json(retained.child.payload_json)
+                source = payload.source
+                if (source.operation_id != UUID(row.id) or source.project_id != UUID(row.project_id)
+                        or source.task_id != UUID(row.task_id)
+                        or source.original_event_id != UUID(row.finalization_event_id)
+                        or source.original_claim_generation != retained.envelope.claim.claim_generation
+                        or source.original_payload_digest != retained.envelope.claim.payload_digest
+                        or source.acceptance_receipt_sha256 != row.acceptance_receipt_sha256):
+                    raise IntakeCustodyConflict("submission_finalization_progress_inconsistent")
+                delivery = await events.observe_delivery(retained.child.event_id, recovery_event(payload))
+                attempt_count += delivery.attempt_count
+    except (OutboxIdempotencyConflict, DeliveryUnavailable, ValueError) as exc:
+        raise IntakeCustodyConflict("submission_finalization_progress_unavailable") from exc
     if not finalized and delivery.state in {"acknowledged", "cancelled"}:
         raise IntakeCustodyConflict("submission_finalization_progress_inconsistent")
     stalled = not finalized and delivery.state == "dead_letter"
@@ -23,5 +49,5 @@ async def finalization_progress(row, events: OutboxAppendPort) -> SubmissionFina
         operation_id=UUID(row.id), finalized=finalized, operationally_stalled=stalled,
         stalled_at=delivery.finalized_at if stalled else None,
         next_retry_at=delivery.next_attempt_at if not finalized else None,
-        attempt_count=delivery.attempt_count,
+        attempt_count=attempt_count, stalled_reason=delivery.error_code if stalled else None,
     )
diff --git a/backend/app/modules/artifacts/intake/recovery.py b/backend/app/modules/artifacts/intake/recovery.py
new file mode 100644
index 000000000..1944c0676
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/recovery.py
@@ -0,0 +1,84 @@
+"""One audited follow-up for the original uncertain accepted-finalization event."""
+
+from uuid import UUID
+
+from sqlalchemy import text
+
+from app.modules.artifacts.api.submission_recovery import (
+    FINALIZATION_RECOVERY_EVENT, FINALIZATION_RECOVERY_SOURCES,
+    SubmissionRecoveryCommand, SubmissionRecoveryPayload, SubmissionRecoveryResult,
+    SubmissionRecoverySource, SubmissionRecoveryUnavailable,
+)
+from app.modules.artifacts.intake.acceptance import finalization_event
+from app.modules.artifacts.intake.repository import SubmissionIntakeRepository
+from app.modules.outbox.api import OutboxAppendInput
+
+
+def recovery_event(payload: SubmissionRecoveryPayload) -> OutboxAppendInput:
+    source, command = payload.source, payload.command
+    return OutboxAppendInput(
+        event_type=FINALIZATION_RECOVERY_EVENT, event_version=1,
+        aggregate_type="outbox_delivery", aggregate_id=source.original_event_id,
+        project_id=command.project_id, correlation_id=str(command.request_id),
+        causation_event_id=source.original_event_id,
+        idempotency_key="submission-finalization-recovery:" + str(source.original_event_id),
+        payload=payload.model_dump(mode="json"),
+    )
+
+
+class SubmissionFinalizationRecovery:
+    """Participate in a caller root; TASK lock precedes AUTH and OUTBOX locks."""
+
+    def __init__(self, session, *, tasks, events, deliveries, authorization):
+        self._session = session
+        self._repository = SubmissionIntakeRepository(session, tasks)
+        self._events, self._deliveries, self._authorization = events, deliveries, authorization
+
+    async def request(self, command: SubmissionRecoveryCommand) -> SubmissionRecoveryResult:
+        if not self._session.in_transaction() or self._session.in_nested_transaction():
+            raise SubmissionRecoveryUnavailable("submission_recovery_transaction_required")
+        command = SubmissionRecoveryCommand.model_validate(command)
+        row = await self._repository._lock(command.operation_id)
+        if row.project_id != str(command.project_id) or row.state not in {"finalization_pending", "finalized"}:
+            raise SubmissionRecoveryUnavailable("submission_recovery_unavailable")
+        await self._session.execute(text(
+            "SELECT public.require_submission_acceptance(o) "
+            "FROM public.submission_intake_operations o WHERE id=:id"
+        ), {"id": row.id})
+        original_id = UUID(row.finalization_event_id)
+        await self._events.require_existing(original_id, finalization_event(row))
+        original = await self._read(command.project_id, original_id, lock=False)
+        if original is None:
+            raise SubmissionRecoveryUnavailable("submission_recovery_unavailable")
+        source = SubmissionRecoverySource(
+            operation_id=command.operation_id, project_id=command.project_id,
+            task_id=UUID(row.task_id), original_event_id=original_id,
+            original_claim_generation=original.envelope.claim.claim_generation,
+            original_payload_digest=original.envelope.claim.payload_digest,
+            acceptance_receipt_sha256=row.acceptance_receipt_sha256,
+        )
+        # Current authority is mandatory even for a previously accepted recovery key.
+        authority = await self._authorization.authorize(command, source)
+        locked = await self._read(command.project_id, original_id, lock=True)
+        if locked is None or locked.envelope != original.envelope:
+            raise SubmissionRecoveryUnavailable("submission_recovery_source_changed")
+        if locked.child is not None:
+            payload = SubmissionRecoveryPayload.model_validate_json(locked.child.payload_json)
+            if payload.command != command or payload.source != source:
+                raise SubmissionRecoveryUnavailable("submission_recovery_conflict")
+            await self._authorization.validate_cause(payload)
+            return SubmissionRecoveryResult(operation_id=command.operation_id,
+                recovery_event_id=locked.child.event_id, state=locked.child.state)
+        if row.state != "finalization_pending":
+            raise SubmissionRecoveryUnavailable("submission_recovery_already_finalized")
+        payload = SubmissionRecoveryPayload(command=command, source=source, authority=authority)
+        appended = await self._events.append(recovery_event(payload))
+        return SubmissionRecoveryResult(operation_id=command.operation_id,
+            recovery_event_id=appended.event_id, state="pending")
+
+    async def _read(self, project_id, event_id, *, lock):
+        return await self._deliveries.read_finalized_unknown(
+            project_id=project_id, event_id=event_id,
+            event_types=FINALIZATION_RECOVERY_SOURCES,
+            child_event_type=FINALIZATION_RECOVERY_EVENT, lock=lock,
+        )
diff --git a/backend/app/modules/artifacts/intake/recovery_delivery.py b/backend/app/modules/artifacts/intake/recovery_delivery.py
new file mode 100644
index 000000000..d85af8c23
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/recovery_delivery.py
@@ -0,0 +1,79 @@
+"""Replay T5 under a live recovery child while preserving the accepted event."""
+
+from dataclasses import dataclass
+from uuid import UUID
+
+from app.modules.artifacts.api.submission_recovery import (
+    FINALIZATION_RECOVERY_EVENT, FINALIZATION_RECOVERY_SOURCES,
+    SubmissionRecoveryPayload, SubmissionRecoveryUnavailable,
+)
+from app.modules.artifacts.intake.finalization_delivery import require_finalization_event
+from app.modules.outbox.api import HandlerOutcome, OutboxEventEnvelope
+
+
+@dataclass(frozen=True)
+class FinalizationRecoveryInvocation:
+    envelope: OutboxEventEnvelope
+    child: OutboxEventEnvelope
+    payload: SubmissionRecoveryPayload
+    deliveries: object
+    authorization: object
+
+    @property
+    def lease_expires_at(self):
+        return self.child.claim.claim_expires_at
+
+    async def fence(self, session, row):
+        require_finalization_event(row, self.envelope)
+        source = self.payload.source
+        if (source.operation_id != UUID(row.id) or source.project_id != UUID(row.project_id)
+                or source.task_id != UUID(row.task_id)
+                or source.acceptance_receipt_sha256 != row.acceptance_receipt_sha256):
+            raise SubmissionRecoveryUnavailable("submission_recovery_source_changed")
+        await self.authorization(session).validate_cause(self.payload)
+        observed = await self.deliveries(session).fence_reconciliation(
+            original=self.envelope, child=self.child,
+            event_types=FINALIZATION_RECOVERY_SOURCES,
+            child_event_type=FINALIZATION_RECOVERY_EVENT,
+        )
+        if observed is None or observed.claim != self.child.claim:
+            raise SubmissionRecoveryUnavailable("submission_recovery_stale")
+
+
+class SubmissionFinalizationRecoveryHandler:
+    def __init__(self, *, sessions, deliveries, authorization, finalizer):
+        self._sessions, self._deliveries = sessions, deliveries
+        self._authorization, self._finalizer = authorization, finalizer
+
+    async def __call__(self, child):
+        try:
+            child = OutboxEventEnvelope.model_validate(child.model_dump())
+            payload = SubmissionRecoveryPayload.model_validate_json(child.payload_json)
+        except (AttributeError, TypeError, ValueError):
+            return HandlerOutcome.REJECT
+        source, command = payload.source, payload.command
+        if (child.event_type != FINALIZATION_RECOVERY_EVENT or child.event_version != 1
+                or child.aggregate_type != "outbox_delivery"
+                or child.aggregate_id != source.original_event_id
+                or child.causation_event_id != source.original_event_id
+                or child.claim.project_id != source.project_id
+                or child.correlation_id != str(command.request_id)
+                or child.idempotency_key != "submission-finalization-recovery:" + str(source.original_event_id)):
+            return HandlerOutcome.REJECT
+        async with self._sessions() as session:
+            retained = await self._deliveries(session).read_finalized_unknown(
+                project_id=source.project_id, event_id=source.original_event_id,
+                event_types=FINALIZATION_RECOVERY_SOURCES,
+                child_event_type=FINALIZATION_RECOVERY_EVENT, lock=False,
+            )
+            if (retained is None or retained.child is None
+                    or retained.child.event_id != child.claim.event_id
+                    or retained.envelope.aggregate_id != source.operation_id
+                    or retained.envelope.claim.claim_generation != source.original_claim_generation
+                    or retained.envelope.claim.payload_digest != source.original_payload_digest):
+                return HandlerOutcome.REJECT
+            await self._authorization(session).validate_cause(payload)
+        invocation = FinalizationRecoveryInvocation(retained.envelope, child, payload,
+            self._deliveries, self._authorization)
+        await self._finalizer(invocation).run(source.operation_id)
+        return HandlerOutcome.ACKNOWLEDGE
diff --git a/backend/app/modules/authorization/action_definitions.py b/backend/app/modules/authorization/action_definitions.py
index db53dcc9c..47f55c789 100644
--- a/backend/app/modules/authorization/action_definitions.py
+++ b/backend/app/modules/authorization/action_definitions.py
@@ -395,7 +395,7 @@
         PermissionId.PROJECT_TASK_MANAGE,
         ActionOwner.TASK_PROJECT_GRANT,
     ),
-    _planned(
+    _active(
         ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR,
         PermissionId.OPERATIONS_SUBMISSION_GATE_REPAIR,
         ActionOwner.AUTH_14,
diff --git a/backend/app/modules/authorization/catalogue.py b/backend/app/modules/authorization/catalogue.py
index 43dbdaca7..03ef05dd5 100644
--- a/backend/app/modules/authorization/catalogue.py
+++ b/backend/app/modules/authorization/catalogue.py
@@ -771,6 +771,7 @@ def _index_actions(
         ActionId.PROJECT_TASK_SUBMISSION_REQUIREMENTS_READ,
         ActionId.AUDIT_TASK_EVIDENCE_READ,
         ActionId.OPERATIONS_CHECKER_RETRY,
+        ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR,
         ActionId.OPERATIONS_CHECKER_RETRY_SOURCE_LIST,
         ActionId.OPERATIONS_POST_SUBMIT_DELIVERY_LIST,
         ActionId.OPERATIONS_POST_SUBMIT_DELIVERY_RECONCILE,
diff --git a/backend/app/modules/authorization/domain/action_groups.py b/backend/app/modules/authorization/domain/action_groups.py
index d87b63a5b..a8ec7b4c3 100644
--- a/backend/app/modules/authorization/domain/action_groups.py
+++ b/backend/app/modules/authorization/domain/action_groups.py
@@ -61,6 +61,7 @@
         ActionId.TASK_QUEUE_READ, ActionId.PROJECT_TASK_QUEUE_READ, ActionId.OPERATIONS_TASK_QUEUE_READ,
         ActionId.PROJECT_CREATE,
         ActionId.OPERATIONS_POST_SUBMIT_DELIVERY_RECONCILE,
+        ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR,
         *GUIDE_BOUND_PROJECT_MANAGER_ACTIONS,
         *SUBMISSION_POLICY_MUTATIONS,
         *POST_POLICY_MUTATION_ACTION_IDS,
@@ -111,6 +112,7 @@
     | contribution_policies.CONTRIBUTION_POLICY_READ_ACTIONS
     | checker_registry.CHECKER_REGISTRY_ACTIONS
     | checker_models.MODEL_ADMIN_ACTIONS
+    | {ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR}
     | checker_retry.CHECKER_RETRY_ACTIONS
     | post_submit_deliveries.POST_SUBMIT_DELIVERY_MUTATION_ACTIONS
     | artifact_operator.ARTIFACT_OPERATOR_ACTIONS
@@ -151,6 +153,7 @@
     | PROJECT_SCOPED_ADMIN_MUTATIONS
     | checker_registry.CHECKER_REGISTRY_MUTATION_ACTIONS
     | checker_models.MODEL_ADMIN_ACTIONS
+    | {ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR}
     | checker_retry.CHECKER_RETRY_ACTIONS
     | post_submit_deliveries.POST_SUBMIT_DELIVERY_MUTATION_ACTIONS
     | {ActionId.ARTIFACT_VERIFICATION_JOB_RETRY}
diff --git a/backend/app/modules/authorization/domain/audit.py b/backend/app/modules/authorization/domain/audit.py
index cba98abea..1591b7a14 100644
--- a/backend/app/modules/authorization/domain/audit.py
+++ b/backend/app/modules/authorization/domain/audit.py
@@ -25,6 +25,7 @@
     "submission_finalization",
     "submission_intake_preflight",
     "submission_operation_read",
+    "submission_operation",
     "task_authority",
     "task_submission_history",
     "submission_history",
@@ -95,6 +96,7 @@
     "submission_finalization",
     "submission_intake_preflight",
     "submission_operation_read",
+    "submission_operation",
     "task_authority",
     "task_submission_history",
     "submission_history",
diff --git a/backend/app/modules/authorization/domain/audit_targets.py b/backend/app/modules/authorization/domain/audit_targets.py
index 8671d777d..0ad3ddfb1 100644
--- a/backend/app/modules/authorization/domain/audit_targets.py
+++ b/backend/app/modules/authorization/domain/audit_targets.py
@@ -81,6 +81,10 @@ def _model_administration_target(resource):
 
 
 def _submission_operation_target(resource):
+    from app.modules.authorization.domain.submission_recovery import SubmissionRecoveryResourceContext
+    if type(resource) is SubmissionRecoveryResourceContext:
+        return (str(resource.scope_project_id), "submission_operation", str(resource.resource_id),
+                "submission_operation", str(resource.resource_id))
     if type(resource) in {IntakeAcceptanceResourceContext, SubmissionFinalizationResourceContext}:
         project_id = str(getattr(resource, "scope_project_id", None) or resource.project_id)
         return project_id, "submission_operation", str(resource.operation_id), "project", project_id
diff --git a/backend/app/modules/authorization/domain/submission_recovery.py b/backend/app/modules/authorization/domain/submission_recovery.py
new file mode 100644
index 000000000..e0b93c50a
--- /dev/null
+++ b/backend/app/modules/authorization/domain/submission_recovery.py
@@ -0,0 +1,26 @@
+"""Existing Operator gate-repair authority narrowed to accepted finalization."""
+
+from typing import Literal
+from uuid import UUID
+
+from pydantic import BaseModel, ConfigDict, model_validator
+
+from app.modules.artifacts.api.submission_recovery import SubmissionRecoveryCommand, SubmissionRecoverySource
+
+
+class SubmissionRecoveryResourceContext(BaseModel):
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True, revalidate_instances="always")
+    resource_type: Literal["submission_operation"] = "submission_operation"
+    resource_id: UUID
+    scope_project_id: UUID
+    identity_link_id: UUID
+    command: SubmissionRecoveryCommand
+    source: SubmissionRecoverySource
+
+    @model_validator(mode="after")
+    def exact_source(self):
+        if (self.resource_id != self.command.operation_id or self.resource_id != self.source.operation_id
+                or self.scope_project_id != self.command.project_id
+                or self.scope_project_id != self.source.project_id):
+            raise ValueError("finalization recovery authority source differs")
+        return self
diff --git a/backend/app/modules/authorization/kernel.py b/backend/app/modules/authorization/kernel.py
index 4c60356c8..6fefd807b 100644
--- a/backend/app/modules/authorization/kernel.py
+++ b/backend/app/modules/authorization/kernel.py
@@ -1,6 +1,7 @@
 """Deny-by-default request-scoped authorization kernel."""
 from __future__ import annotations
 from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.domain.submission_recovery import SubmissionRecoveryResourceContext
 from app.modules.authorization.domain.guide_proposals import GUIDE_PROPOSAL_RESOURCE_BY_ACTION
 from app.modules.authorization.catalogue import POST_POLICY_ACTION_IDS
 from app.modules.authorization.domain.post_policy import PostPolicyResourceContext
@@ -208,6 +209,7 @@ async def prelock_serialized_admin_read_actor(authorization: AuthorizationServic
         **checker_registry.CHECKER_REGISTRY_RESOURCE_BY_ACTION,
         **checker_models.MODEL_ADMIN_RESOURCE_BY_ACTION,
         ActionId.OPERATIONS_CHECKER_RETRY: checker_retry.CheckerRetryResourceContext,
+        ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR: SubmissionRecoveryResourceContext,
         **post_submit_deliveries.POST_SUBMIT_DELIVERY_RESOURCE_BY_ACTION,
         **artifact_operator.ARTIFACT_OPERATOR_RESOURCE_BY_ACTION,
         **PROJECT_MUTATION_RESOURCE_BY_ACTION,
@@ -867,7 +869,7 @@ async def _admin_denial(
                 return lifecycle, context, None, None, True
 
         project_id = self._resource_project_id(resource)
-        system_only = project_id is None
+        system_only = project_id is None or action.action_id is ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR
         grant_filters: dict[str, object] = {}
         if action.action_id is ActionId.PROJECT_ACTIVE_GUIDE_READ:
             grant_filters["allowed_roles"] = ACTIVE_GUIDE_ADMIN_ROLES
@@ -879,7 +881,7 @@ async def _admin_denial(
                 **checker_registry.checker_registry_grant_filters(action.action_id),
             }
         )
-        if action.action_id in checker_retry.CHECKER_RETRY_ACTIONS | post_submit_deliveries.POST_SUBMIT_DELIVERY_MUTATION_ACTIONS | checker_models.MODEL_ADMIN_ACTIONS | artifact_operator.ARTIFACT_OPERATOR_ACTIONS:
+        if action.action_id in {ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR} | checker_retry.CHECKER_RETRY_ACTIONS | post_submit_deliveries.POST_SUBMIT_DELIVERY_MUTATION_ACTIONS | checker_models.MODEL_ADMIN_ACTIONS | artifact_operator.ARTIFACT_OPERATOR_ACTIONS:
             grant_filters["allowed_roles"] = (AdminRole.OPERATOR,)
         matched = await self._admin.find_effective_grant(
             context.actor_profile_id,
@@ -968,6 +970,14 @@ async def _admin_guard(
                 return AuthorizationDenialCode.RESOURCE_GUARD_DENIED
             if await self._admin.lock_identity_link_lifecycle_target(resource.resource_id) is None:
                 return AuthorizationDenialCode.RESOURCE_NOT_FOUND
+        elif type(resource) is SubmissionRecoveryResourceContext:
+            if (resource.command.actor_profile_id != context.actor_profile_id
+                    or resource.identity_link_id != context.identity_link_id
+                    or resource.command.request_id != context.request_id
+                    or context.request_id != context.correlation_id):
+                return AuthorizationDenialCode.RESOURCE_GUARD_DENIED
+            if not await self._admin.project_exists(resource.scope_project_id, for_update=True):
+                return AuthorizationDenialCode.RESOURCE_NOT_FOUND
         elif type(resource) is post_submit_deliveries.PostSubmitDeliveryResourceContext and not await self._admin.project_exists(resource.scope_project_id, for_update=True):
             return AuthorizationDenialCode.RESOURCE_NOT_FOUND
         elif type(resource) is checker_models.ProjectModelAdministrationResourceContext:
diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py
index 7a3354959..b96977a2b 100644
--- a/backend/app/modules/authorization/runtime.py
+++ b/backend/app/modules/authorization/runtime.py
@@ -9,6 +9,7 @@
 
 from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts
 from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.domain.submission_recovery import SubmissionRecoveryResourceContext
 from app.modules.authorization.domain.guide_compilation import ProjectGuideCompilationExecuteResourceContext, ProjectGuideCompilationRequestResourceContext
 from app.modules.authorization.domain.resource_digest import authorization_resource_digest as authorization_resource_digest
 from app.modules.authorization.domain.guide_proposals import GuideProposalResourceContext
@@ -1114,6 +1115,7 @@ def bind_source_operation(self):
     | ArtifactOperatorRetryResourceContext
     | GuideSourceReadResourceContext
     | SubmissionFinalizationResourceContext
+    | SubmissionRecoveryResourceContext
     | SubmissionCreationResourceContext | SubmissionBindingResourceContext | IntakeAcceptanceResourceContext
     | PreSubmitCheckerInputResourceContext
     | SubmissionBundlePreparationPreflightResourceContext
diff --git a/backend/app/modules/authorization/submission_recovery.py b/backend/app/modules/authorization/submission_recovery.py
new file mode 100644
index 000000000..66114c9bb
--- /dev/null
+++ b/backend/app/modules/authorization/submission_recovery.py
@@ -0,0 +1,74 @@
+"""Current Operator decisions and exact retained causes for finalization recovery."""
+
+from sqlalchemy import text
+
+from app.modules.artifacts.api.submission_recovery import (
+    SubmissionRecoveryAuthority, SubmissionRecoveryCommand, SubmissionRecoveryPayload,
+    SubmissionRecoverySource, SubmissionRecoveryUnavailable,
+)
+from app.modules.authorization.catalogue import ActionId, PermissionId
+from app.modules.authorization.domain.submission_recovery import SubmissionRecoveryResourceContext
+from app.modules.authorization.runtime import (
+    AuthorizationDenied, HumanAuthorizationContext, authorization_resource_digest,
+)
+
+
+class SubmissionRecoveryAuthorization:
+    def __init__(self, session, context, kernel):
+        self._session, self._context, self._kernel = session, context, kernel
+
+    @staticmethod
+    def _resource(command, source, link_id):
+        return SubmissionRecoveryResourceContext(
+            resource_id=source.operation_id, scope_project_id=source.project_id,
+            identity_link_id=link_id, command=command, source=source,
+        )
+
+    async def authorize(self, command, source):
+        command = SubmissionRecoveryCommand.model_validate(command)
+        source = SubmissionRecoverySource.model_validate(source)
+        context = self._context
+        if (not isinstance(context, HumanAuthorizationContext)
+                or context.actor_profile_id != command.actor_profile_id
+                or context.request_id != command.request_id
+                or context.correlation_id != command.request_id):
+            raise SubmissionRecoveryUnavailable("submission_recovery_authority_unavailable")
+        resource = self._resource(command, source, context.identity_link_id)
+        try:
+            decision = await self._kernel.require(ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR, resource)
+        except AuthorizationDenied as exc:
+            raise SubmissionRecoveryUnavailable("submission_recovery_authority_unavailable") from exc
+        digest = authorization_resource_digest(resource)
+        if decision.resource_context_digest != digest:
+            raise SubmissionRecoveryUnavailable("submission_recovery_authority_unavailable")
+        return SubmissionRecoveryAuthority(decision_id=decision.decision_id,
+            identity_link_id=context.identity_link_id, resource_digest=digest)
+
+    async def validate_cause(self, payload):
+        payload = SubmissionRecoveryPayload.model_validate(payload)
+        command, source, authority = payload.command, payload.source, payload.authority
+        digest = authorization_resource_digest(self._resource(command, source, authority.identity_link_id))
+        event = (await self._session.execute(text(
+            "SELECT event_type, actor_id, action_id, permission_id, project_id, resource_type, "
+            "resource_id, request_id, correlation_id, denial_code, after_facts "
+            "FROM public.audit_events WHERE id=:decision_id"
+        ), {"decision_id": authority.decision_id})).mappings().one_or_none()
+        if not (event is not None and authority.resource_digest == digest
+                and event["event_type"] == "SensitiveAuthorizationAllowed"
+                and event["actor_id"] == str(command.actor_profile_id)
+                and event["action_id"] == ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR.value
+                and event["permission_id"] == PermissionId.OPERATIONS_SUBMISSION_GATE_REPAIR.value
+                and str(event["project_id"]) == str(source.project_id)
+                and event["resource_type"] == "submission_operation"
+                and event["resource_id"] == str(source.operation_id)
+                and str(event["request_id"]) == str(command.request_id)
+                and str(event["correlation_id"]) == str(command.request_id)
+                and event["denial_code"] is None
+                and event["after_facts"] == {"allowed": True, "resource_context_digest": digest}):
+            raise SubmissionRecoveryUnavailable("submission_recovery_cause_unavailable")
+
+    async def restage_denial(self, error):
+        if isinstance(error.__cause__, AuthorizationDenied):
+            await self._kernel.restage_denial(error.__cause__.decision)
+            return True
+        return False
diff --git a/backend/app/modules/outbox/models.py b/backend/app/modules/outbox/models.py
index f855ba5f2..e9e3471d6 100644
--- a/backend/app/modules/outbox/models.py
+++ b/backend/app/modules/outbox/models.py
@@ -119,6 +119,10 @@ class OutboxEvent(Base):
             "and attempt_count = 0 and last_attempt_at is null and last_error_code is null)",
             name="delivery_state_shape",
         ),
+        Index(
+            "uq_submission_finalization_recovery_original", "causation_event_id", unique=True,
+            postgresql_where=text("event_type='SubmissionFinalizationRecoveryRequested'"),
+        ),
         Index(
             "ix_outbox_events_eligible",
             "event_type",
diff --git a/backend/app/workers/outbox.py b/backend/app/workers/outbox.py
index 59b9548bc..6a712d932 100644
--- a/backend/app/workers/outbox.py
+++ b/backend/app/workers/outbox.py
@@ -92,7 +92,7 @@ def scan_pending(self, after=None):
     published = 0
     for candidate in page.items:
         try:
-            task = finalize_submission if candidate.event_type == "SubmissionFinalizationRequested" else deliver_event
+            task = finalize_submission if candidate.event_type in {"SubmissionFinalizationRequested", "SubmissionFinalizationRecoveryRequested"} else deliver_event
             task.apply_async(args=(str(candidate.event_id), str(candidate.project_id)))
             published += 1
         except Exception:
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 12345a22f..bee4faa1c 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -31,7 +31,7 @@
 
 @pytest.fixture
 async def admission_intake(tmp_path, isolated_database_env, admin_access, request):
-    from app.adapters.outbox import outbox_append
+    from app.adapters.outbox import outbox_append, finalized_unknown_deliveries
     from app.adapters.projects import project_locked_policy_context_port
     from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission
     from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization
@@ -77,7 +77,7 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
             factory, tasks=lambda session: IntakeTaskCustody(session, task_submission_context_port(session)),
             task_contexts=task_submission_context_port, projects=project_locked_policy_context_port,
             authorization=lambda session: SubmissionIntakeAuthorization(session, actor), namespace=namespace,
-            events=outbox_append,
+            events=outbox_append, deliveries=finalized_unknown_deliveries,
             capacity_limits=SubmissionSourceCapacityLimits(maximum_total_bytes=1_000_000), maximum_raw_bytes=1024,
             upload_duration=timedelta(seconds=300), lease_duration=timedelta(seconds=60),
         )
@@ -844,6 +844,120 @@ def submissions(session):
         store.close()
 
 
+async def test_operator_recovers_same_accepted_finalization_once(admission_intake, tmp_path):
+    import asyncio
+    import json
+    from uuid import UUID
+    from sqlalchemy import select, func, text
+    from sqlalchemy.exc import IntegrityError
+    from app.core.hashing import canonical_json_hash
+    from app.adapters.artifacts.finalization import submission_finalization_recovery_handler
+    from app.adapters.auth import outbox_dispatch_authorization, submission_recovery_authorization
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.outbox import outbox_append, outbox_delivery, finalized_unknown_deliveries
+    from app.modules.actors.api import ServiceIdentity
+    from app.modules.artifacts.api.submission_recovery import (
+        FINALIZATION_RECOVERY_EVENT, SubmissionRecoveryCommand, SubmissionRecoveryUnavailable,
+    )
+    from app.modules.artifacts.intake.recovery import SubmissionFinalizationRecovery
+    from app.modules.outbox.api import DeliveryOptions
+    from app.modules.outbox.models import OutboxEvent
+    from app.modules.outbox.registry import HandlerRegistry
+    from app.modules.tasks.models import Submission
+    from tests.artifact_store_helpers import initialize_local_store
+    from tests.artifacts.intake_acceptance_support import completed_source
+    from tests.checkers.execution.support import provision_post_submit_service
+
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER):
+        await provision_post_submit_service(f.factory, identity)
+    async with f.factory() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        event_id = UUID(row.finalization_event_id)
+        metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
+        intake_key = UUID(row.idempotency_key)
+    async def lost(_envelope):
+        raise RuntimeError("lost original finalizer")
+    options = DeliveryOptions(lease_seconds=30, handler_timeout_seconds=25, max_attempts=1)
+    delivery = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
+        registry=HandlerRegistry([("SubmissionFinalizationRequested", 1, lost)],
+            replay_safe=frozenset({("SubmissionFinalizationRequested", 1)})),
+        options=DeliveryOptions(lease_seconds=5, handler_timeout_seconds=4, max_attempts=1))
+    await delivery.deliver(event_id, f.project, "lost-finalizer")
+    await asyncio.sleep(5.05)  # Recovery must use its live child, not this expired original lease.
+    key = new_record_id()
+    context = f.actor.model_copy(update={"request_id": key, "correlation_id": key})
+    command = SubmissionRecoveryCommand(operation_id=owner.operation_id, project_id=f.project,
+        actor_profile_id=f.actor.actor_profile_id, request_id=key, reason="Restore unavailable finalizer")
+    async def recover(value=command):
+        async with f.factory.begin() as session:
+            return await SubmissionFinalizationRecovery(session,
+                tasks=IntakeTaskCustody(session, task_submission_context_port(session)),
+                events=outbox_append(session), deliveries=finalized_unknown_deliveries(session),
+                authorization=submission_recovery_authorization(session, context)).request(value)
+    with pytest.raises(SubmissionRecoveryUnavailable):
+        await recover()
+    grant_id = await f.access.signed.grant(f.access.admin, f.access.target)
+    created, raced = await asyncio.gather(recover(), recover())
+    assert raced == created and await recover() == created
+    with pytest.raises(SubmissionRecoveryUnavailable, match="submission_recovery_conflict"):
+        await recover(command.model_copy(update={"reason": "Different recovery reason"}))
+    async with f.factory() as session:
+        original_payload = (await session.get(OutboxEvent, created.recovery_event_id)).payload
+    for field, value, message in (
+        ("reason", "Forged reason", "recovery authority shape differs"),
+        ("decision_id", str(new_record_id()), "recovery retained Operator cause differs"),
+    ):
+        forged = json.loads(json.dumps(original_payload))
+        forged["command" if field == "reason" else "authority"][field] = value
+        with pytest.raises(IntegrityError, match=message):
+            async with f.factory.begin() as session:
+                await session.execute(text("""INSERT INTO outbox_events(event_id,event_type,event_version,
+                    aggregate_type,aggregate_id,project_id,correlation_id,causation_event_id,
+                    idempotency_key,payload,payload_digest)
+                    SELECT :id,event_type,event_version,aggregate_type,aggregate_id,project_id,
+                    correlation_id,causation_event_id,idempotency_key,cast(:payload as jsonb),:digest
+                    FROM outbox_events WHERE event_id=:original"""),
+                    {"id": new_record_id(), "payload": json.dumps(forged),
+                     "digest": canonical_json_hash(forged), "original": created.recovery_event_id})
+    progress = await f.admission._read(metadata, f.actor.actor_profile_id, intake_key)
+    assert not progress.finalization.operationally_stalled and progress.finalization.next_retry_at is not None
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    try:
+        handler = submission_finalization_recovery_handler(sessions=f.factory,
+            settings=_settings(tmp_path), store=store, lease_duration=timedelta(seconds=30))
+        invocations = []
+        async def invoke(envelope):
+            invocations.append(envelope)
+            return await handler(envelope)
+        retry = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
+            registry=HandlerRegistry([(FINALIZATION_RECOVERY_EVENT, 1, invoke)]), options=options)
+        await retry.deliver(created.recovery_event_id, f.project, "recovery-finalizer")
+        with pytest.raises(SubmissionRecoveryUnavailable, match="submission_recovery_stale"):
+            await handler(invocations[0])
+        replayed = await recover()
+        assert replayed.recovery_event_id == created.recovery_event_id and replayed.state == "acknowledged"
+        async with f.factory() as session:
+            row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+            assert row.state == "finalized" and row.finalization_event_id == str(event_id)
+            assert await session.scalar(select(func.count()).select_from(Submission).where(
+                Submission.task_id == str(f.task))) == 1
+            assert await session.scalar(select(func.count()).select_from(OutboxEvent).where(
+                OutboxEvent.event_type == "PostSubmissionEvaluationRequested")) == 1
+            assert (await session.get(OutboxEvent, event_id)).delivery_state == "dead_letter"
+            assert await session.scalar(select(func.count()).select_from(OutboxEvent).where(
+                OutboxEvent.event_type == FINALIZATION_RECOVERY_EVENT)) == 1
+        revoked = await f.access.signed.revoke(f.access.admin, grant_id)
+        assert revoked.status_code == 200, revoked.text
+        with pytest.raises(SubmissionRecoveryUnavailable):
+            await recover()
+    finally:
+        store.close()
+
+
 @pytest.mark.parametrize("duration", [timedelta(0), timedelta(days=3650), timedelta(hours=1, microseconds=1)])
 def test_finalization_rejects_unbounded_or_empty_lease(duration):
     from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
diff --git a/backend/tests/authorization/catalogue_fixtures.py b/backend/tests/authorization/catalogue_fixtures.py
index d2a4dcb39..04f5f3774 100644
--- a/backend/tests/authorization/catalogue_fixtures.py
+++ b/backend/tests/authorization/catalogue_fixtures.py
@@ -603,6 +603,7 @@
     "checker.pre_submit.execute",
     "checker.pre_submit.finalize",
     "operations.checker.retry",
+    "operations.submission_gate.repair",
     "operations.checker_retry_source.list",
     "operations.artifact_storage_admission.read",
     "operations.post_submit_delivery.list",
diff --git a/backend/tests/authorization/test_catalogue.py b/backend/tests/authorization/test_catalogue.py
index 14c883e46..4dcd30a25 100644
--- a/backend/tests/authorization/test_catalogue.py
+++ b/backend/tests/authorization/test_catalogue.py
@@ -118,8 +118,8 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
     }
     assert all(not owner.value.startswith("WS-REV-") for owner in ActionOwner)
     assert Counter(definition.availability for definition in ACTION_DEFINITIONS) == {
-        ActionAvailability.ACTIVE: 168,
-        ActionAvailability.PLANNED: 25,
+        ActionAvailability.ACTIVE: 169,
+        ActionAvailability.PLANNED: 24,
     }
     assert (
         resolve_executable_action(ActionId.ACTOR_PROFILE_READ_SELF).permission_id
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 2f2f74c73..d8d439010 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "86ac9cfc2ea48543d5084a4b47c3fd985cde4be1e13f25c06da613c371f94cc4"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "1d0060750a195d348606ae5eaf9ae9a47462e1cf6062f278c9f2b408b707f8b2"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/backend/tests/outbox/test_delivery_topology.py b/backend/tests/outbox/test_delivery_topology.py
index f4b7fcc2a..6548a9f42 100644
--- a/backend/tests/outbox/test_delivery_topology.py
+++ b/backend/tests/outbox/test_delivery_topology.py
@@ -195,7 +195,7 @@ def test_scan_routes_each_event_group_without_acknowledging(monkeypatch):
     get_settings.cache_clear()
     from app.workers import outbox
     items = tuple(DeliveryCandidate(event_id=new_record_id(), project_id=new_record_id(), event_type=kind)
-                  for kind in ("PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested"))
+                  for kind in ("PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested", "SubmissionFinalizationRecoveryRequested"))
     async def candidates(_after):
         return DeliveryCandidatePage(items=items, next_after=None)
     published = []
@@ -203,9 +203,9 @@ async def candidates(_after):
     monkeypatch.setattr(outbox.deliver_event, "apply_async", lambda **kwargs: published.append(("post", kwargs)))
     monkeypatch.setattr(outbox.finalize_submission, "apply_async", lambda **kwargs: published.append(("final", kwargs)))
     try:
-        assert outbox.scan_pending.apply(task_id=str(new_record_id()), throw=True).get() == {"selected": 2, "published": 2}
+        assert outbox.scan_pending.apply(task_id=str(new_record_id()), throw=True).get() == {"selected": 3, "published": 3}
         assert published == [(kind, {"args": (str(item.event_id), str(item.project_id))})
-                             for kind, item in zip(("post", "final"), items, strict=True)]
+                             for kind, item in zip(("post", "final", "final"), items, strict=True)]
     finally:
         get_settings.cache_clear()
 
diff --git a/backend/tests/outbox/test_worker_postgresql.py b/backend/tests/outbox/test_worker_postgresql.py
index e33633768..fa8173f6f 100644
--- a/backend/tests/outbox/test_worker_postgresql.py
+++ b/backend/tests/outbox/test_worker_postgresql.py
@@ -199,6 +199,7 @@ async def test_production_registry_claims_only_registered_features(delivery_harn
     production = production_outbox_delivery(h.factory)
     assert production._registry.keys == (
         ("SubmissionFinalizationRequested", 1),
+        ("SubmissionFinalizationRecoveryRequested", 1),
         ("TaskAssignmentAuthorityInvalidationRequested", 1),
         ("TaskRevisionExpiryRequested", 1),
         ("TaskRevisionExpired", 1),
@@ -365,7 +366,7 @@ async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery
         async with h.factory() as session:
             await session.execute(text("select pg_sleep(3.05)"))
     finalization = production_outbox_delivery(h.factory, finalization_worker=True)
-    assert finalization._registry.keys == (("SubmissionFinalizationRequested", 1),)
+    assert finalization._registry.keys == (("SubmissionFinalizationRequested", 1), ("SubmissionFinalizationRecoveryRequested", 1))
     assert await finalization.deliver(event.event_id, h.project, "wrong-worker", registered_only=True) is None
     async with h.factory() as session:
         stored = await session.get(OutboxEvent, event.event_id)
diff --git a/docs/architecture_checker_framework.md b/docs/architecture_checker_framework.md
index e825676be..0ad5449a4 100644
--- a/docs/architecture_checker_framework.md
+++ b/docs/architecture_checker_framework.md
@@ -983,13 +983,16 @@ ARCH-04C adds neither full-log reads nor retry/repair controls.
 
 `operations.checker.retry` has a hidden reason-bound Operator owner with fresh
 authority and immutable attempt/audit custody. `operations.submission_gate.repair`
-remains unavailable. Neither grants a public override or bypasses checker results.
+has an internal accepted-finalization recovery owner with exact operation/event,
+reason and current system Operator authority. It retains the original attempt and
+runs the same finalizer through one bounded recovery child. Neither grants a
+public override or bypasses checker results.
 
 Critical- and high-severity checker failures cannot be converted into review
 readiness by an administrative grant. Covered Project Manager authority under
 `project.task.manage` remains limited to existing lifecycle/context-repair
 operations; it does not implement the future post-submit setup-fault hold.
-Future Operator submission-gate repair and current hidden checker retry must
+Operator accepted-finalization recovery and checker retry must
 remain limited to their exact registered recovery purposes.
 
 Recovery requires:
diff --git a/docs/operations_authorization_service.md b/docs/operations_authorization_service.md
index 9b8c95f34..c883482e6 100644
--- a/docs/operations_authorization_service.md
+++ b/docs/operations_authorization_service.md
@@ -958,7 +958,7 @@ their canonical 401/503 and 429/503 behavior before private lookup.
 | Operation | Authority | Required controls |
 |---|---|---|
 | Normal covered task/setup repair | Covered Project Manager `project.task.manage` | Exact project, lifecycle guard, reason/evidence where mutation is corrective. |
-| Submission gate repair (planned; unavailable) | Operator `operations.submission_gate.repair` | No submission/review rewrite; reason, matched authority, immutable checker evidence. |
+| Accepted-finalization recovery (internal owner; no public endpoint) | Operator `operations.submission_gate.repair` | Exact accepted operation and exhausted UNKNOWN event; reason and current system grant; one audited recovery child, preserving original attempts and PRE/source evidence. |
 | Checker retry (planned; unavailable) | Operator `operations.checker.retry` | New attempt/supersession evidence; no prior result deletion. |
 | Review lease force release | Operator `review.lease.force_release` under WS-REV-001 | Review-owned lease guards and evidence; no review decision. |
 
diff --git a/docs/operations_roles_permissions.md b/docs/operations_roles_permissions.md
index 636873ea2..e62d24ad4 100644
--- a/docs/operations_roles_permissions.md
+++ b/docs/operations_roles_permissions.md
@@ -172,7 +172,7 @@ Recovery is a separate, reasoned, audited path.
 | Operation | Permission | Actor |
 |---|---|---|
 | Normal covered task/setup repair | `project.task.manage` | Covered Project Manager |
-| Submission gate repair (planned; unavailable) | `operations.submission_gate.repair` | Operator |
+| Accepted-finalization recovery (internal owner; no public endpoint) | `operations.submission_gate.repair` | Operator |
 | Checker recovery-source discovery (active public read) | `operations.status.read` via `operations.checker_retry_source.list` | System Operator for one exact project |
 | Checker terminal-failure retry (active public operation) | `operations.checker.retry` | System Operator under exact terminal-failure guards |
 | Immutable project model profile provisioning | `project.model_profile.manage` via `project.model_profile.provision` | System Operator for the exact project; approved POST policy separately binds the registered image |
diff --git a/docs/roles_permissions.md b/docs/roles_permissions.md
index c1d8f768d..03611d244 100644
--- a/docs/roles_permissions.md
+++ b/docs/roles_permissions.md
@@ -50,9 +50,11 @@ and legacy-close actions remain unavailable until their owning hidden behavior,
 AUTH activation and release. REV-12A4A activates internal lifecycle control for
 live system Operators, binding the exact singleton, generation and manifest.
 It supplies no public endpoint, human-review, acceptance or payment authority. Claim starts work atomically; no Operator start action exists. Submission-gate repair
-(`operations.submission_gate.repair`) and checker retry
-(`operations.checker.retry`) are planned and unavailable; their old routes and
-Celery worker were removed. Review lease release remains governed by the separately
+(`operations.submission_gate.repair`) has an internal, reason-bound recovery owner
+for the same accepted finalization operation and exact exhausted UNKNOWN delivery.
+It authorizes one bounded recovery child under a current system Operator grant;
+child exhaustion remains held. Checker retry (`operations.checker.retry`) has its
+separate current owner. Neither grants a checker-content override. Review lease release remains governed by the separately
 owned WS-REV contract.
 
 Recovery requires exact resource scope, a reason, matched grant/permission, and
diff --git a/docs/spec_authorization_service.md b/docs/spec_authorization_service.md
index e1bb0a2cc..5d3411bd1 100644
--- a/docs/spec_authorization_service.md
+++ b/docs/spec_authorization_service.md
@@ -558,7 +558,12 @@ request event commit together. New requests require the exact current terminal
 `infrastructure_failed` run; fresh-authorized replay validates the historical
 TASK/Submission and original receipt even after later routing. This is neither a
 public route nor a registered production handler. `task_setup_blocked` is not
-eligible for this retry, and `operations.submission_gate.repair` remains planned.
+eligible for checker retry. `operations.submission_gate.repair` now has an internal
+accepted-finalization recovery owner: a current system Operator may authorize one
+reason-bound recovery child for an exact exhausted UNKNOWN finalization event.
+The child retains the same operation, accepted PRE/source evidence and original
+attempt; T5 remains the sole Submission writer. Replay rechecks current authority.
+This supplies no public repair endpoint or checker-content override.
 
 The v0.1 baseline is availability-neutral for this surface. PostgreSQL enforces the closed
 ActionId set, authorization-decision event shape, exact ActionId-to-PermissionId

From 852fbf326c25e828d9d408185e55fa994c122eee Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:08:31 +0100
Subject: [PATCH 125/513] Close finalization recovery audit and payload custody
 gaps

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  40 +++++
 .../versions/0077_submission_recovery.py      |  21 ++-
 .../authorization/submission_recovery.py      |  21 ++-
 .../artifacts/intake_recovery_support.py      | 106 +++++++++++++
 .../test_submission_intake_admission.py       | 145 ++++++++++--------
 backend/tests/conftest.py                     |   2 +-
 docs/operations_authorization_service.md      |   2 +-
 7 files changed, 262 insertions(+), 75 deletions(-)
 create mode 100644 backend/tests/artifacts/intake_recovery_support.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index ee4669b76..69d209c03 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3123,3 +3123,43 @@ after acknowledgement. This must complete before claiming the recovery checkpoin
 verified. The one-child limit follows existing reconciliation: exhaustion remains
 held, not an automatic contributor retry. Public operator discovery/command
 routes and the full public operation progress contract remain outstanding.
+
+### Recovery review repair
+
+The additional original-expiry/stale-child run completed successfully:
+`/tmp/t5-recovery5.log` reports **3 passed**, with database/role cleanup confirmed.
+Frozen review of `a32a870f8` nevertheless found direct-SQL custody gaps; typed
+command success was not sufficient proof of those guards. Architecture/security
+required exact retained system Operator grant, actor/link and target binding,
+canonical child payload digest parity, and reason-whitespace parity with the typed
+command. QA also requested a rehashed source substitution and a final authorized
+progress read after child acknowledgement. Documentation identified the adjacent
+stale checker-retry availability label; CI integrity found no guard weakening.
+
+The repair adds those SQL predicates and historical cause checks in AUTH. SQL
+creation checks current active actor/grant/link; worker cause validation preserves
+the accepted decision after later human grant revocation, while still requiring
+its immutable system Operator/actor/link/target associations. Reason trimming uses
+the explicit Python whitespace set and C0/DEL control exclusion rather than a
+locale-dependent SQL character class. The observed repaired schema fingerprint is
+`98e8a90037368efa975e8807d2191da466756e46421f89f114424c6a0d3694cf`
+(`/tmp/t5-recovery-schema4.log`).
+
+The composed test's existing raw SQL reason/nonexistent-decision probes move to
+`test_recovery_sql_requires_exact_source_and_real_operator_cause`, alongside
+source, payload-digest, absent/wrong grant, identity-link, target and Unicode-edge
+reason forgeries. For relevant cases the test first inserts a self-consistent
+forged allow-audit row with recomputed resource digest and proves that row exists
+before attempting the forbidden child; a valid child is the positive control.
+The original journey retains its denial/race/replay/revocation, single Submission
+and dispatch, expired-original and stale-child assertions; it now loses the
+child acknowledgement after T5 and verifies replay plus final contributor progress.
+A shared real setup fixture keeps both tests cohesive, without adding test debt.
+The repaired journey and both progress tests passed in `/tmp/t5-recovery6.log`
+(**3 passed**); its SQL test first failed because the forged fixture copied the
+old audit `entity_id`, so generic audit shape rejected it before the new guard.
+The fixture now gives the forged audit its own matching id/entity id, without
+changing any guard. The focused `/tmp/t5-recovery7.log` run passed (**1 passed**,
+41.18s), exercising all nine SQL forgeries plus valid-child positive control;
+isolated database/role cleanup completed for both runs. Ruff, structure and link
+checks passed. Frozen repair review remains pending.
diff --git a/backend/alembic/versions/0077_submission_recovery.py b/backend/alembic/versions/0077_submission_recovery.py
index cf84b7cb6..94a45008f 100644
--- a/backend/alembic/versions/0077_submission_recovery.py
+++ b/backend/alembic/versions/0077_submission_recovery.py
@@ -54,7 +54,9 @@ def upgrade():
    'request_id',(c->>'request_id')::uuid::text,'reason',c->>'reason');
  IF s IS DISTINCT FROM expected_source OR c IS DISTINCT FROM expected_command
    OR c->>'reason' IS NULL OR length(c->>'reason') NOT BETWEEN 1 AND 500
-   OR c->>'reason' IS DISTINCT FROM btrim(c->>'reason') OR (c->>'reason') ~ '[[:cntrl:]]' THEN
+   OR c->>'reason' IS DISTINCT FROM btrim(c->>'reason',
+       U&'\0009\000a\000b\000c\000d\001c\001d\001e\001f\0020\0085\00a0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200a\2028\2029\202f\205f\3000')
+   OR (c->>'reason') ~ ('['||chr(1)||'-'||chr(31)||chr(127)||']') THEN
    RAISE EXCEPTION 'recovery exact source or command differs' USING ERRCODE='23514'; END IF;
  resource := jsonb_build_object('resource_type','submission_operation','resource_id',o.id::text,
    'scope_project_id',o.project_id::text,'identity_link_id',(authority->>'identity_link_id')::uuid::text,
@@ -62,19 +64,32 @@ def upgrade():
  digest := public.external_checker_registry_digest(jsonb_build_object('resource_context',resource));
  expected_authority := jsonb_build_object('decision_id',(authority->>'decision_id')::uuid::text,
    'identity_link_id',(authority->>'identity_link_id')::uuid::text,'resource_digest',digest);
+ IF NEW.payload_digest IS DISTINCT FROM public.external_checker_registry_digest(p) THEN
+   RAISE EXCEPTION 'recovery payload digest differs' USING ERRCODE='23514'; END IF;
  IF authority IS DISTINCT FROM expected_authority OR p IS DISTINCT FROM
    jsonb_build_object('command',c,'source',s,'authority',authority) THEN
    RAISE EXCEPTION 'recovery authority shape differs' USING ERRCODE='23514'; END IF;
  SELECT * INTO d FROM public.audit_events WHERE id=(authority->>'decision_id')::uuid;
- IF NOT FOUND OR d.event_type<>'SensitiveAuthorizationAllowed'
+ IF NOT FOUND OR d.event_domain IS DISTINCT FROM 'authority'
+   OR d.event_type IS DISTINCT FROM 'SensitiveAuthorizationAllowed'
+   OR d.actor_ref_kind IS DISTINCT FROM 'actor_profile'
    OR d.action_id IS DISTINCT FROM 'operations.submission_gate.repair'
    OR d.permission_id IS DISTINCT FROM 'operations.submission_gate.repair'
    OR d.actor_id IS DISTINCT FROM c->>'actor_profile_id'
    OR d.project_id IS DISTINCT FROM o.project_id
    OR d.resource_type IS DISTINCT FROM 'submission_operation' OR d.resource_id IS DISTINCT FROM o.id::text
+   OR d.target_ref_kind IS DISTINCT FROM 'submission_operation' OR d.target_ref_id IS DISTINCT FROM o.id::text
    OR d.request_id::text IS DISTINCT FROM c->>'request_id'
    OR d.correlation_id::text IS DISTINCT FROM c->>'request_id' OR d.denial_code IS NOT NULL
-   OR d.after_facts::jsonb IS DISTINCT FROM jsonb_build_object('allowed',true,'resource_context_digest',digest) THEN
+   OR d.after_facts::jsonb IS DISTINCT FROM jsonb_build_object('allowed',true,'resource_context_digest',digest)
+   OR NOT EXISTS (SELECT 1 FROM public.actor_profiles actor
+     WHERE actor.id=(c->>'actor_profile_id')::uuid AND actor.actor_kind='human' AND actor.status='active')
+   OR NOT EXISTS (SELECT 1 FROM public.admin_role_grants g
+     WHERE g.id::text=d.matched_grant_id AND g.target_actor_profile_id=(c->>'actor_profile_id')::uuid
+       AND g.role='operator' AND g.scope_type='system' AND g.scope_project_id IS NULL AND g.status='active')
+   OR NOT EXISTS (SELECT 1 FROM public.actor_identity_links link
+     WHERE link.id=(authority->>'identity_link_id')::uuid
+       AND link.actor_profile_id=(c->>'actor_profile_id')::uuid AND link.status='active') THEN
    RAISE EXCEPTION 'recovery retained Operator cause differs' USING ERRCODE='23514'; END IF;
  RETURN NEW;
 END $$;
diff --git a/backend/app/modules/authorization/submission_recovery.py b/backend/app/modules/authorization/submission_recovery.py
index 66114c9bb..d6232436b 100644
--- a/backend/app/modules/authorization/submission_recovery.py
+++ b/backend/app/modules/authorization/submission_recovery.py
@@ -49,11 +49,24 @@ async def validate_cause(self, payload):
         command, source, authority = payload.command, payload.source, payload.authority
         digest = authorization_resource_digest(self._resource(command, source, authority.identity_link_id))
         event = (await self._session.execute(text(
-            "SELECT event_type, actor_id, action_id, permission_id, project_id, resource_type, "
-            "resource_id, request_id, correlation_id, denial_code, after_facts "
-            "FROM public.audit_events WHERE id=:decision_id"
-        ), {"decision_id": authority.decision_id})).mappings().one_or_none()
+            "SELECT d.event_domain, d.event_type, d.actor_ref_kind, d.actor_id, d.action_id, "
+            "d.permission_id, d.project_id, d.resource_type, d.resource_id, d.request_id, "
+            "d.correlation_id, d.denial_code, d.after_facts, d.target_ref_kind, d.target_ref_id, "
+            "EXISTS (SELECT 1 FROM public.admin_role_grants g WHERE g.id::text=d.matched_grant_id "
+            "AND g.target_actor_profile_id=:actor AND g.role='operator' AND g.scope_type='system' "
+            "AND g.scope_project_id IS NULL) AS operator_grant, "
+            "EXISTS (SELECT 1 FROM public.actor_profiles p WHERE p.id=:actor "
+            "AND p.actor_kind='human') AS human_actor, "
+            "EXISTS (SELECT 1 FROM public.actor_identity_links l WHERE l.id=:link "
+            "AND l.actor_profile_id=:actor) AS identity_link "
+            "FROM public.audit_events d WHERE d.id=:decision_id"
+        ), {"decision_id": authority.decision_id, "actor": command.actor_profile_id,
+            "link": authority.identity_link_id})).mappings().one_or_none()
         if not (event is not None and authority.resource_digest == digest
+                and event["event_domain"] == "authority" and event["actor_ref_kind"] == "actor_profile"
+                and event["operator_grant"] and event["human_actor"] and event["identity_link"]
+                and event["target_ref_kind"] == "submission_operation"
+                and event["target_ref_id"] == str(source.operation_id)
                 and event["event_type"] == "SensitiveAuthorizationAllowed"
                 and event["actor_id"] == str(command.actor_profile_id)
                 and event["action_id"] == ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR.value
diff --git a/backend/tests/artifacts/intake_recovery_support.py b/backend/tests/artifacts/intake_recovery_support.py
new file mode 100644
index 000000000..5b5e46cd8
--- /dev/null
+++ b/backend/tests/artifacts/intake_recovery_support.py
@@ -0,0 +1,106 @@
+"""Real accepted and exhausted source setup for finalization recovery proofs."""
+
+import asyncio
+import json
+from types import SimpleNamespace
+from uuid import UUID
+
+import pytest
+from sqlalchemy import text
+
+from app.adapters.auth import outbox_dispatch_authorization, submission_recovery_authorization
+from app.adapters.checkers import selected_pre_submit_coordinator
+from app.adapters.outbox import outbox_append, outbox_delivery, finalized_unknown_deliveries
+from app.adapters.tasks import task_submission_context_port
+from app.core.identifiers import new_record_id
+from app.core.hashing import canonical_json_hash
+from app.modules.actors.api import ServiceIdentity
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
+from app.modules.artifacts.api.submission_recovery import SubmissionRecoveryCommand, SubmissionRecoverySource
+from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+from app.modules.artifacts.intake.recovery import SubmissionFinalizationRecovery
+from app.modules.outbox.api import DeliveryOptions
+from app.modules.outbox.models import OutboxEvent
+from app.modules.outbox.registry import HandlerRegistry
+from app.modules.tasks.intake_custody import IntakeTaskCustody
+from tests.artifacts.intake_acceptance_support import completed_source
+from tests.checkers.execution.support import provision_post_submit_service
+
+
+@pytest.fixture
+async def recovery_intake(admission_intake, tmp_path):
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER):
+        await provision_post_submit_service(f.factory, identity)
+    async with f.factory() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        event_id = UUID(row.finalization_event_id)
+        metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
+        intake_key = UUID(row.idempotency_key)
+    async def lost(_envelope):
+        raise RuntimeError("lost original finalizer")
+    delivery = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
+        registry=HandlerRegistry([("SubmissionFinalizationRequested", 1, lost)],
+            replay_safe=frozenset({("SubmissionFinalizationRequested", 1)})),
+        options=DeliveryOptions(lease_seconds=5, handler_timeout_seconds=4, max_attempts=1))
+    await delivery.deliver(event_id, f.project, "lost-finalizer")
+    await asyncio.sleep(5.05)  # The later finalizer must use the live child's lease.
+    key = new_record_id()
+    context = f.actor.model_copy(update={"request_id": key, "correlation_id": key})
+    command = SubmissionRecoveryCommand(operation_id=owner.operation_id, project_id=f.project,
+        actor_profile_id=f.actor.actor_profile_id, request_id=key, reason="Restore unavailable finalizer")
+    async def recover(value=command):
+        async with f.factory.begin() as session:
+            return await SubmissionFinalizationRecovery(session,
+                tasks=IntakeTaskCustody(session, task_submission_context_port(session)),
+                events=outbox_append(session), deliveries=finalized_unknown_deliveries(session),
+                authorization=submission_recovery_authorization(session, context)).request(value)
+    async with f.factory() as session:
+        event = await session.get(OutboxEvent, event_id)
+        assert event.delivery_state == "dead_letter" and event.last_error_code == "INVOKE_OUTCOME_UNKNOWN"
+        source = SubmissionRecoverySource(operation_id=owner.operation_id, project_id=f.project,
+            task_id=f.task, original_event_id=event_id, original_claim_generation=event.claim_generation,
+            original_payload_digest=event.payload_digest,
+            acceptance_receipt_sha256=row.acceptance_receipt_sha256)
+    return SimpleNamespace(f=f, owner=owner, event_id=event_id, metadata=metadata, intake_key=intake_key,
+                           context=context, command=command, source=source, recover=recover)
+
+
+async def insert_recovery_payload(session, payload, *, digest=None):
+    """Raw SQL positive/negative control; deliberately bypass typed command admission."""
+    source, command = payload["source"], payload["command"]
+    event_id = new_record_id()
+    await session.execute(text("""INSERT INTO outbox_events(event_id,event_type,event_version,
+        aggregate_type,aggregate_id,project_id,correlation_id,causation_event_id,
+        idempotency_key,payload,payload_digest)
+        VALUES (:id,'SubmissionFinalizationRecoveryRequested',1,'outbox_delivery',:original,
+        :project,:request,:original,:key,cast(:payload as jsonb),:digest)"""),
+        {"id": event_id, "original": UUID(source["original_event_id"]),
+         "project": UUID(source["project_id"]), "request": command["request_id"],
+         "key": "submission-finalization-recovery:" + source["original_event_id"],
+         "payload": json.dumps(payload), "digest": digest or canonical_json_hash(payload)})
+    return event_id
+
+
+async def forge_recovery_audit(session, reference_id, payload, overrides):
+    """Prove an existing self-consistent allow row cannot substitute exact authority."""
+    source, command, authority = payload["source"], payload["command"], payload["authority"]
+    digest = canonical_json_hash({"resource_context": {
+        "resource_type": "submission_operation", "resource_id": source["operation_id"],
+        "scope_project_id": source["project_id"], "identity_link_id": authority["identity_link_id"],
+        "command": command, "source": source,
+    }})
+    decision_id = new_record_id()
+    patch = {"id": str(decision_id), "entity_id": str(decision_id), "after_facts": {"allowed": True, "resource_context_digest": digest},
+             **overrides}
+    await session.execute(text("""INSERT INTO audit_events
+        SELECT (jsonb_populate_record(NULL::public.audit_events,
+            to_jsonb(a) || cast(:patch as jsonb))).*
+        FROM audit_events a WHERE id=:reference"""),
+        {"patch": json.dumps(patch), "reference": reference_id})
+    assert await session.scalar(text("SELECT count(*) FROM audit_events WHERE id=:id"),
+                                {"id": decision_id}) == 1
+    authority.update(decision_id=str(decision_id), resource_digest=digest)
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index bee4faa1c..c28885ca7 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -23,6 +23,7 @@
     clear_settings_cache as clear_settings_cache,
     rsa_signing_material as rsa_signing_material,
 )
+from tests.artifacts.intake_recovery_support import recovery_intake as recovery_intake
 from tests.authorization.admin_access.fixtures import (
     signed_access as signed_access,
     admin_access as admin_access,
@@ -844,60 +845,22 @@ def submissions(session):
         store.close()
 
 
-async def test_operator_recovers_same_accepted_finalization_once(admission_intake, tmp_path):
+async def test_operator_recovers_same_accepted_finalization_once(recovery_intake, tmp_path):
     import asyncio
-    import json
-    from uuid import UUID
-    from sqlalchemy import select, func, text
-    from sqlalchemy.exc import IntegrityError
-    from app.core.hashing import canonical_json_hash
+    from sqlalchemy import select, func
     from app.adapters.artifacts.finalization import submission_finalization_recovery_handler
-    from app.adapters.auth import outbox_dispatch_authorization, submission_recovery_authorization
-    from app.adapters.checkers import selected_pre_submit_coordinator
-    from app.adapters.outbox import outbox_append, outbox_delivery, finalized_unknown_deliveries
-    from app.modules.actors.api import ServiceIdentity
-    from app.modules.artifacts.api.submission_recovery import (
-        FINALIZATION_RECOVERY_EVENT, SubmissionRecoveryCommand, SubmissionRecoveryUnavailable,
-    )
-    from app.modules.artifacts.intake.recovery import SubmissionFinalizationRecovery
+    from app.adapters.auth import outbox_dispatch_authorization
+    from app.adapters.outbox import outbox_delivery
+    from app.modules.artifacts.api.submission_recovery import FINALIZATION_RECOVERY_EVENT, SubmissionRecoveryUnavailable
     from app.modules.outbox.api import DeliveryOptions
     from app.modules.outbox.models import OutboxEvent
     from app.modules.outbox.registry import HandlerRegistry
     from app.modules.tasks.models import Submission
     from tests.artifact_store_helpers import initialize_local_store
-    from tests.artifacts.intake_acceptance_support import completed_source
-    from tests.checkers.execution.support import provision_post_submit_service
 
-    f = admission_intake
-    owner, request, terminal = await completed_source(f, tmp_path)
-    await f.admission.accept(owner, request, terminal.terminal_digest,
-        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
-    for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER):
-        await provision_post_submit_service(f.factory, identity)
-    async with f.factory() as session:
-        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
-        event_id = UUID(row.finalization_event_id)
-        metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
-        intake_key = UUID(row.idempotency_key)
-    async def lost(_envelope):
-        raise RuntimeError("lost original finalizer")
-    options = DeliveryOptions(lease_seconds=30, handler_timeout_seconds=25, max_attempts=1)
-    delivery = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
-        registry=HandlerRegistry([("SubmissionFinalizationRequested", 1, lost)],
-            replay_safe=frozenset({("SubmissionFinalizationRequested", 1)})),
-        options=DeliveryOptions(lease_seconds=5, handler_timeout_seconds=4, max_attempts=1))
-    await delivery.deliver(event_id, f.project, "lost-finalizer")
-    await asyncio.sleep(5.05)  # Recovery must use its live child, not this expired original lease.
-    key = new_record_id()
-    context = f.actor.model_copy(update={"request_id": key, "correlation_id": key})
-    command = SubmissionRecoveryCommand(operation_id=owner.operation_id, project_id=f.project,
-        actor_profile_id=f.actor.actor_profile_id, request_id=key, reason="Restore unavailable finalizer")
-    async def recover(value=command):
-        async with f.factory.begin() as session:
-            return await SubmissionFinalizationRecovery(session,
-                tasks=IntakeTaskCustody(session, task_submission_context_port(session)),
-                events=outbox_append(session), deliveries=finalized_unknown_deliveries(session),
-                authorization=submission_recovery_authorization(session, context)).request(value)
+    r = recovery_intake
+    f, owner, event_id = r.f, r.owner, r.event_id
+    metadata, intake_key, command, recover = r.metadata, r.intake_key, r.command, r.recover
     with pytest.raises(SubmissionRecoveryUnavailable):
         await recover()
     grant_id = await f.access.signed.grant(f.access.admin, f.access.target)
@@ -905,24 +868,6 @@ async def recover(value=command):
     assert raced == created and await recover() == created
     with pytest.raises(SubmissionRecoveryUnavailable, match="submission_recovery_conflict"):
         await recover(command.model_copy(update={"reason": "Different recovery reason"}))
-    async with f.factory() as session:
-        original_payload = (await session.get(OutboxEvent, created.recovery_event_id)).payload
-    for field, value, message in (
-        ("reason", "Forged reason", "recovery authority shape differs"),
-        ("decision_id", str(new_record_id()), "recovery retained Operator cause differs"),
-    ):
-        forged = json.loads(json.dumps(original_payload))
-        forged["command" if field == "reason" else "authority"][field] = value
-        with pytest.raises(IntegrityError, match=message):
-            async with f.factory.begin() as session:
-                await session.execute(text("""INSERT INTO outbox_events(event_id,event_type,event_version,
-                    aggregate_type,aggregate_id,project_id,correlation_id,causation_event_id,
-                    idempotency_key,payload,payload_digest)
-                    SELECT :id,event_type,event_version,aggregate_type,aggregate_id,project_id,
-                    correlation_id,causation_event_id,idempotency_key,cast(:payload as jsonb),:digest
-                    FROM outbox_events WHERE event_id=:original"""),
-                    {"id": new_record_id(), "payload": json.dumps(forged),
-                     "digest": canonical_json_hash(forged), "original": created.recovery_event_id})
     progress = await f.admission._read(metadata, f.actor.actor_profile_id, intake_key)
     assert not progress.finalization.operationally_stalled and progress.finalization.next_retry_at is not None
     store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
@@ -932,10 +877,18 @@ async def recover(value=command):
         invocations = []
         async def invoke(envelope):
             invocations.append(envelope)
-            return await handler(envelope)
+            result = await handler(envelope)
+            if len(invocations) == 1:
+                raise RuntimeError("lost recovery acknowledgement after T5")
+            return result
+        options = DeliveryOptions(lease_seconds=30, handler_timeout_seconds=25, max_attempts=2,
+                                  retry_base_seconds=1, retry_cap_seconds=1)
         retry = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
-            registry=HandlerRegistry([(FINALIZATION_RECOVERY_EVENT, 1, invoke)]), options=options)
+            registry=HandlerRegistry([(FINALIZATION_RECOVERY_EVENT, 1, invoke)],
+                replay_safe=frozenset({(FINALIZATION_RECOVERY_EVENT, 1)})), options=options)
         await retry.deliver(created.recovery_event_id, f.project, "recovery-finalizer")
+        await asyncio.sleep(1.05)
+        await retry.deliver(created.recovery_event_id, f.project, "recovery-replay")
         with pytest.raises(SubmissionRecoveryUnavailable, match="submission_recovery_stale"):
             await handler(invocations[0])
         replayed = await recover()
@@ -950,6 +903,9 @@ async def invoke(envelope):
             assert (await session.get(OutboxEvent, event_id)).delivery_state == "dead_letter"
             assert await session.scalar(select(func.count()).select_from(OutboxEvent).where(
                 OutboxEvent.event_type == FINALIZATION_RECOVERY_EVENT)) == 1
+        final = await f.admission._read(metadata, f.actor.actor_profile_id, intake_key)
+        assert final.finalization.finalized and not final.finalization.operationally_stalled
+        assert final.finalization.attempt_count == 3 and final.finalization.next_retry_at is None
         revoked = await f.access.signed.revoke(f.access.admin, grant_id)
         assert revoked.status_code == 200, revoked.text
         with pytest.raises(SubmissionRecoveryUnavailable):
@@ -966,6 +922,63 @@ def test_finalization_rejects_unbounded_or_empty_lease(duration):
             checkers=None, store=None, lease_duration=duration)
 
 
+async def test_recovery_sql_requires_exact_source_and_real_operator_cause(recovery_intake):
+    import json
+    from sqlalchemy import text
+    from sqlalchemy.exc import IntegrityError
+    from app.adapters.auth import submission_recovery_authorization
+    from app.modules.artifacts.api.submission_recovery import SubmissionRecoveryPayload
+    from tests.artifacts.intake_recovery_support import insert_recovery_payload, forge_recovery_audit
+
+    r, f = recovery_intake, recovery_intake.f
+    await f.access.signed.grant(f.access.admin, f.access.target)
+    async with f.factory.begin() as session:
+        authority = await submission_recovery_authorization(session, r.context).authorize(r.command, r.source)
+        foreign_link = await session.scalar(text(
+            "SELECT id FROM actor_identity_links WHERE actor_profile_id=:actor"), {"actor": f.access.admin.id})
+    original = SubmissionRecoveryPayload(command=r.command, source=r.source, authority=authority).model_dump(mode="json")
+    cases = (
+        ("reason", "recovery authority shape differs"),
+        ("decision", "recovery retained Operator cause differs"),
+        ("source", "recovery exact source or command differs"),
+        ("digest", "recovery payload digest differs"),
+        ("grant", "recovery retained Operator cause differs"),
+        ("wrong_grant", "recovery retained Operator cause differs"),
+        ("link", "recovery retained Operator cause differs"),
+        ("target", "recovery retained Operator cause differs"),
+        ("unicode_reason", "recovery exact source or command differs"),
+    )
+    for case, message in cases:
+        payload, patch = json.loads(json.dumps(original)), {}
+        if case == "reason":
+            payload["command"]["reason"] = "Forged reason"
+        elif case == "decision":
+            payload["authority"]["decision_id"] = str(new_record_id())
+        elif case == "source":
+            payload["source"]["task_id"] = str(new_record_id())
+        elif case == "grant":
+            patch["matched_grant_id"] = None
+        elif case == "wrong_grant":
+            patch["matched_grant_id"] = f.access.bootstrap_grant_id
+        elif case == "link":
+            payload["authority"]["identity_link_id"] = str(foreign_link)
+        elif case == "target":
+            patch.update(target_ref_kind="project", target_ref_id=str(f.project))
+        elif case == "unicode_reason":
+            payload["command"]["reason"] = "\u00a0"
+        with pytest.raises(IntegrityError, match=message):
+            async with f.factory.begin() as session:
+                if case not in {"reason", "decision", "digest"}:
+                    await forge_recovery_audit(session, authority.decision_id, payload, patch)
+                await insert_recovery_payload(session, payload,
+                    digest="sha256:" + "0" * 64 if case == "digest" else None)
+    async with f.factory.begin() as session:
+        assert await session.scalar(text("SELECT count(*) FROM outbox_events "
+            "WHERE event_type='SubmissionFinalizationRecoveryRequested'")) == 0
+        valid_id = await insert_recovery_payload(session, original)
+    assert (await r.recover()).recovery_event_id == valid_id
+
+
 @pytest.mark.parametrize("lost_at", ["after_commit", "during_observation"])
 async def test_finalization_outbox_recovers_lost_ack_without_provider_replay(admission_intake, tmp_path, lost_at):
     from uuid import UUID
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index d8d439010..9b00120fd 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "1d0060750a195d348606ae5eaf9ae9a47462e1cf6062f278c9f2b408b707f8b2"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "98e8a90037368efa975e8807d2191da466756e46421f89f114424c6a0d3694cf"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/docs/operations_authorization_service.md b/docs/operations_authorization_service.md
index c883482e6..d37ff3fef 100644
--- a/docs/operations_authorization_service.md
+++ b/docs/operations_authorization_service.md
@@ -959,7 +959,7 @@ their canonical 401/503 and 429/503 behavior before private lookup.
 |---|---|---|
 | Normal covered task/setup repair | Covered Project Manager `project.task.manage` | Exact project, lifecycle guard, reason/evidence where mutation is corrective. |
 | Accepted-finalization recovery (internal owner; no public endpoint) | Operator `operations.submission_gate.repair` | Exact accepted operation and exhausted UNKNOWN event; reason and current system grant; one audited recovery child, preserving original attempts and PRE/source evidence. |
-| Checker retry (planned; unavailable) | Operator `operations.checker.retry` | New attempt/supersession evidence; no prior result deletion. |
+| Checker terminal-failure retry (active public operation) | Operator `operations.checker.retry` | New attempt/supersession evidence; no prior result deletion. |
 | Review lease force release | Operator `review.lease.force_release` under WS-REV-001 | Review-owned lease guards and evidence; no review decision. |
 
 Conceptual historical “admin override” statements are not operations. No

From 225455a2b3c6bbfa129cab28e215f9fc43896966 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:11:25 +0100
Subject: [PATCH 126/513] Record verified finalization recovery checkpoint

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md    | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 69d209c03..2d8888a87 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -27,7 +27,9 @@ commit or worktree, not automatically to every later head.
 Finalization now has production OUTBOX registration and invocation fencing, with
 real PostgreSQL recovery proof. A dedicated local worker queue and internal
 authorized stall projection are implemented. Full Celery/provider execution,
-independent worker capacity, public progress and operator recovery remain unfinished.
+independent worker capacity and public progress/operator endpoints remain unfinished.
+Internal audited finalization recovery now reuses the existing Operator gate-repair
+action, preserves the original delivery and runs the same T5 under a live child lease.
 Next: close those durable-worker gaps, then complete cleanup and public API/CLI/MCP
 cutover, real revision/review/ContributionRecord journeys, policy cardinality and
 the A01–A35/C01–C07 completion audit. No public end-to-end readiness is claimed.
@@ -3163,3 +3165,11 @@ changing any guard. The focused `/tmp/t5-recovery7.log` run passed (**1 passed**
 41.18s), exercising all nine SQL forgeries plus valid-child positive control;
 isolated database/role cleanup completed for both runs. Ruff, structure and link
 checks passed. Frozen repair review remains pending.
+
+Frozen repair review on clean `852fbf326c25e828d9d408185e55fa994c122eee` passed
+architecture/security, QA/test-delta, documentation and CI integrity. Reviewers
+confirmed the three SQL findings and both QA proof gaps were closed; architecture
+independently compared the explicit SQL whitespace set with Python's 29 whitespace
+code points. Evidence remains the declared worktree runs, not an exact-head native
+or public-API drill. Public operator routes, cleanup and single-request API/client
+cutover remain required for the full goal.

From 4c101c6e72b31e5951e7487c2e6fda69563df67f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:21:26 +0100
Subject: [PATCH 127/513] Update checker image samples to source-bound PRE
 identity

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 29 +++++++++++++++++++
 backend/scripts/checker_image_samples.py      | 10 +++++--
 2 files changed, 37 insertions(+), 2 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 2d8888a87..2003a7036 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3173,3 +3173,32 @@ independently compared the explicit SQL whitespace set with Python's 29 whitespa
 code points. Evidence remains the declared worktree runs, not an exact-head native
 or public-API drill. Public operator routes, cleanup and single-request API/client
 cutover remain required for the full goal.
+
+## Checker image qualification caller repair
+
+Current-head hosted run 43326850205 builds the PRE image but fails before its
+first sample executes. Inspection found the sample request builder still emits
+`prepared_generation_id`, superseded by the operation/source/lease PRE contract.
+This shared consumer must migrate with the source-first contract; no compatibility
+alias or production validator relaxation is allowed.
+
+Bounded scope: `backend/scripts/checker_image_samples.py`, existing
+`backend/tests/test_checker_image.py` proof, and this record. Acceptance: both PRE
+and POST dry-run qualification construct valid canonical requests; PRE material
+matches operation/source/lease and attempt identity; existing publication and
+cleanup failure protections remain effective. Risk: architecture/contract caller
+repair, no new authority or product state. Verification: reproduce the existing
+two-phase regression before repair, run the complete checker-image suite, then
+run the actual Terminal Systems PRE image. Required review: architecture and
+QA/test delta, with human focus on synthetic identities versus real custody and
+unchanged production validation. Cleanup implementation remains the next feature
+boundary; this discovered integrated proof failure is repaired first.
+
+The existing two-phase dry-run regression reproduced the exact failure before
+repair (PRE failed, POST passed). After replacing the retired synthetic field
+with matching operation/source/lease identities, the full existing
+`tests/test_checker_image.py` suite passed: 25 tests in 14.25 seconds, captured in
+`/tmp/submission-checker-image-repair.log`. Ruff and diff whitespace checks pass.
+No test assertions, production validators, CI selection or permissions changed.
+The actual image drill is separate evidence and must finish before qualification
+is claimed. Latest fetch confirms zero commits missing from origin/main.
diff --git a/backend/scripts/checker_image_samples.py b/backend/scripts/checker_image_samples.py
index bbfc887cc..be7b51c8d 100644
--- a/backend/scripts/checker_image_samples.py
+++ b/backend/scripts/checker_image_samples.py
@@ -182,14 +182,20 @@ def sample_request(descriptor: Descriptor, sample: Sample, image_id: str, sample
     }
     if descriptor.phase == "pre_submit":
         identity.update(
-            prepared_generation_id=uuid4(),
+            operation_id=uuid4(),
+            source_sha256=sample_digest,
+            lease_id=uuid4(),
+            lease_generation=1,
             attempt_request_digest=sample_digest,
             effective_plan_sha256=sample_digest,
         )
         material.update(
             {
                 key: identity[key]
-                for key in ("prepared_generation_id", "attempt_id", "attempt_request_digest")
+                for key in (
+                    "operation_id", "source_sha256", "lease_id", "lease_generation",
+                    "attempt_id", "attempt_request_digest",
+                )
             }
         )
         material.update(archive_sha256=sample_digest, archive_byte_count=0)

From 8f256f1f9baa5ff380660a2d2663463e9eba0e98 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:24:54 +0100
Subject: [PATCH 128/513] Record caller repair review and image drill cleanup
 gap

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md           | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 2003a7036..07b3dff58 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3202,3 +3202,20 @@ with matching operation/source/lease identities, the full existing
 No test assertions, production validators, CI selection or permissions changed.
 The actual image drill is separate evidence and must finish before qualification
 is claimed. Latest fetch confirms zero commits missing from origin/main.
+
+Architecture and QA/test-delta independently passed the clean caller repair at
+4c101c6e7. Architecture also confirmed that mismatched material operation and the
+retired identity field remain rejected. Commitrail validation passed.
+
+Actual Docker qualification remains unproven: the first local attempt timed out
+executing its first sample. A diagnostic rerun instrumenting command durations
+(without changing repository code, deadlines, or sandbox settings) passed six
+samples, then exhausted the 30-second budget during creation of the seventh.
+Logs: `/tmp/submission-pre-image-repair.log` and
+`/tmp/submission-pre-image-timing.log`. The second run also exposed a late-create
+cleanup gap: despite immediate removal and absence observation, the Docker create
+subsequently left owned container `workstream-image-test-41d80d4bd7e4485599d986bbc87da211`.
+Its exact image/name were inspected and it was explicitly removed. This is an
+unresolved image-runner cleanup obligation, not evidence of successful complete
+qualification; it must be addressed without weakening deadlines. No AWS/native
+runtime qualification or full current-head CI success is claimed.

From 9ec01ecc3824356247e8cc25d20e0919c37466fc Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:28:23 +0100
Subject: [PATCH 129/513] Persist image sample cleanup custody before Docker
 creation

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 32 +++++++++++++++
 backend/scripts/checker_image.py              | 27 ++++++++++--
 backend/tests/test_checker_image.py           | 41 +++++++++++++++++++
 3 files changed, 97 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 07b3dff58..d7b51f84d 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3219,3 +3219,35 @@ Its exact image/name were inspected and it was explicitly removed. This is an
 unresolved image-runner cleanup obligation, not evidence of successful complete
 qualification; it must be addressed without weakening deadlines. No AWS/native
 runtime qualification or full current-head CI success is claimed.
+
+## Image runner uncertain-create custody
+
+Bounded scope: `backend/scripts/checker_image.py`, its existing test module, and
+this record. Before a Docker create, persist the exact owned container name and
+image in the existing private receipt. Keep create uncertainty distinct from a
+confirmed created container; a failed create followed by empty LIST cannot close
+that obligation. Persist confirmation only after acknowledged creation and scoped
+removal/absence. This closes lost cleanup identity, not the Docker daemon's ability
+to finish an outstanding request. Uncertain receipts require reconciliation of
+the named container and remain failed; no automatic retry/publication is allowed.
+
+Acceptance: the on-disk receipt exists before create; simulated late create after
+an empty cleanup observation retains its exact name and unresolved state; a
+successful sample ends with confirmed cleanup; cleanup failure retains an open
+obligation. Existing deadlines, output bounds, isolation and publication guards
+remain unchanged. Risk: runtime resource custody. Verification: existing full
+image-runner suite plus focused late-create regression and actual image drill.
+Reviewers: architecture and QA/test delta. Human focus: whether retained receipt
+truthfully distinguishes request settlement from point-in-time absence. Do not
+claim an automatic daemon reaper or native runtime qualification from this repair.
+
+Verification: the final existing suite plus custody regression passed 26 tests
+in 8.25 seconds (`/tmp/image-cleanup-custody-tests-final.log`). Loading the previous
+script implementation in memory and running the new regression failed with the
+missing `sample_cleanup` receipt (`/tmp/image-cleanup-prefixed-regression.log`);
+no worktree replacement or test weakening was used. Ruff and diff checks pass.
+The actual unchanged Terminal Systems PRE image passed all seven configured
+positive/negative samples, with confirmed cleanup in receipt
+`.checker-images/bd8859524a454b358ef56dd02586ce25/receipt.json`; full output is
+`/tmp/image-cleanup-live.log`. This is local Docker compatibility evidence only,
+not AWS/native Smol qualification or a complete public submission journey.
diff --git a/backend/scripts/checker_image.py b/backend/scripts/checker_image.py
index 688d4de4e..e42425715 100644
--- a/backend/scripts/checker_image.py
+++ b/backend/scripts/checker_image.py
@@ -100,7 +100,8 @@ def inspect(self, image: str, **kwargs) -> dict:
         return value
 
 
-def test_sample(docker: Docker, image_id: str, request, directory: Path, runtime: str) -> bytes:
+def test_sample(docker: Docker, image_id: str, request, directory: Path, runtime: str,
+                evidence: dict, checkpoint) -> bytes:
     """Exercise image compatibility under the closed sandbox profile, then confirm cleanup."""
     limits = request.registry.resources
     name = "workstream-image-test-" + uuid4().hex
@@ -110,8 +111,12 @@ def test_sample(docker: Docker, image_id: str, request, directory: Path, runtime
         time.monotonic() + limits.deadline_ms / 1000, limits.maximum_output_bytes
     )
     cleaned = False
+    created = False
+    cleanup = {"container_name": name, "image_id": image_id, "state": "create_pending"}
     try:
         docker.inspect(image_id, budget=budget)
+        evidence["sample_cleanup"] = cleanup
+        checkpoint()
         docker.call(
             "create",
             "--name",
@@ -145,6 +150,9 @@ def test_sample(docker: Docker, image_id: str, request, directory: Path, runtime
             budget=budget,
             timeout=limits.deadline_ms / 1000,
         )
+        created = True
+        cleanup["state"] = "removal_pending"
+        checkpoint()
         raw = docker.call(
             "start",
             "--attach",
@@ -170,11 +178,18 @@ def test_sample(docker: Docker, image_id: str, request, directory: Path, runtime
             raise ImageError("sample did not exit cleanly")
         remove_sample(docker, name, budget)
         cleaned = True
+        cleanup["state"] = "confirmed"
+        checkpoint()
         return raw
     finally:
         if not cleaned:
             # Emergency cleanup cannot turn an over-budget sample into a passing one.
             remove_sample(docker, name, ExecutionBudget(time.monotonic() + 30, 65536))
+            if created:
+                cleanup["state"] = "confirmed"
+                checkpoint()
+            # Without a create acknowledgement, absence is only a snapshot. The
+            # daemon may still publish this name; preserve its durable obligation.
 
 
 def remove_sample(docker: Docker, name: str, budget: ExecutionBudget) -> None:
@@ -210,13 +225,15 @@ def run_samples(
     image_id: str,
     request_image_digest: str,
     runtime: str,
+    evidence: dict,
+    checkpoint,
 ) -> list[dict]:
     """Check expected work outcomes and exact findings using canonical CHECKERS validation."""
     observations = []
     for sample, path, digest in samples:
         print(f"Testing {sample.name} ({sample.expected})…", file=sys.stderr)
         request = sample_request(descriptor, sample, request_image_digest, digest)
-        raw = test_sample(docker, image_id, request, path, runtime)
+        raw = test_sample(docker, image_id, request, path, runtime, evidence, checkpoint)
         result = ExternalCheckerExecutionResult.model_validate_json(raw)
         result.validate_request(request)
         if (
@@ -431,7 +448,9 @@ def execute(args, evidence: dict, checkpoint) -> dict:
         if f"{image['Os']}/{image['Architecture']}" != args.platform or image["Id"] != image_id:
             raise ImageError("built image platform/identity differs")
         evidence["tested_image_id"] = image_id
-        evidence["samples"] = run_samples(docker, descriptor, samples, image_id, image_id, runtime)
+        evidence["samples"] = run_samples(
+            docker, descriptor, samples, image_id, image_id, runtime, evidence, checkpoint,
+        )
         if not args.publish:
             return {}
         print("Publishing tested image to ECR…", file=sys.stderr)
@@ -447,6 +466,8 @@ def execute(args, evidence: dict, checkpoint) -> dict:
             image_id,
             cache["platform_manifest_digest"],
             runtime,
+            evidence,
+            checkpoint,
         )
         evidence["publication"] = "verified"
         return {
diff --git a/backend/tests/test_checker_image.py b/backend/tests/test_checker_image.py
index 48ef553d9..2320770ee 100644
--- a/backend/tests/test_checker_image.py
+++ b/backend/tests/test_checker_image.py
@@ -226,6 +226,45 @@ def test_dry_run_validates_both_phases_without_any_aws(project, transport, tmp_p
         item["verdict"] for item in json.loads((output / "receipt.json").read_text())["samples"]
     ] == ["passed", "failed"]
     assert sorted(p.name for p in output.iterdir()) == ["receipt.json"]
+    assert json.loads((output / "receipt.json").read_text())["sample_cleanup"]["state"] == "confirmed"
+
+
+def test_late_create_keeps_durable_obligation_after_empty_cleanup_observation(
+    project, transport, tmp_path, monkeypatch,
+):
+    """An empty LIST cannot settle a daemon create whose acknowledgement was lost."""
+    docker, aws_calls = transport
+    output = tmp_path / "release"
+    original = docker.response
+    late_containers = []
+    owned_name = None
+
+    def response(*args, **kwargs):
+        nonlocal owned_name
+        if args[0] == "create":
+            owned_name = args[args.index("--name") + 1]
+            persisted = json.loads((output / "receipt.json").read_text())
+            assert persisted["sample_cleanup"] == {
+                "container_name": owned_name, "image_id": IMAGE, "state": "create_pending",
+            }
+            raise ImageError("create sample container: deadline exceeded")
+        if args[:2] == ("container", "ls"):
+            # Daemon finishes only after the cleanup query captured absence.
+            late_containers.append(owned_name)
+            return b""
+        return original(*args, **kwargs)
+
+    monkeypatch.setattr(docker, "response", response)
+    assert cli.main([
+        str(project), "--publish", "--account-id", "123456789012", "--out", str(output),
+    ]) == 1
+    receipt = json.loads((output / "receipt.json").read_text())
+    assert receipt["status"] == "failed"
+    assert receipt["sample_cleanup"]["state"] == "create_pending"
+    assert late_containers == [receipt["sample_cleanup"]["container_name"]]
+    assert not aws_calls
+    assert not any(args[0] == "start" for args, _ in docker.calls)
+    assert not (output / "registry.json").exists()
 
 
 def test_publish_verifies_exact_image_and_rechecks_digest_before_outputs(
@@ -271,6 +310,8 @@ def test_failed_sample_or_cleanup_prevents_all_aws_calls(project, transport, tmp
     assert not aws_calls
     assert any(c[0:2] == ("rm", "--force") for c, _ in docker.calls)
     assert not (output / "registry.json").exists()
+    cleanup = json.loads((output / "receipt.json").read_text())["sample_cleanup"]
+    assert cleanup["state"] == ("removal_pending" if failure == "cleanup" else "confirmed")
 
 
 @pytest.mark.parametrize("failure", ["push", "digest_branch"])

From e31200fc4f4d996ba83eedf567dc5519c15de8ca Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:32:25 +0100
Subject: [PATCH 130/513] Sync cleanup receipt directories before external
 creation

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 ++++++++++++
 backend/scripts/checker_image.py              | 13 ++++++++
 backend/tests/test_checker_image.py           | 32 ++++++++++++++++++-
 docs/engineering/developer-setup.md           |  4 +--
 4 files changed, 66 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index d7b51f84d..d71f71f6d 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3251,3 +3251,23 @@ positive/negative samples, with confirmed cleanup in receipt
 `.checker-images/bd8859524a454b358ef56dd02586ce25/receipt.json`; full output is
 `/tmp/image-cleanup-live.log`. This is local Docker compatibility evidence only,
 not AWS/native Smol qualification or a complete public submission journey.
+
+Review repair IMAGE-CLEANUP-DURABILITY-01: sync the receipt directory after its
+atomic rename and sync output-directory ancestry before external calls. Added
+injected directory-fsync failure cases at output creation and receipt publication;
+both must prevent Docker create. Do not narrow durability to process visibility.
+
+Adjacent hosted Agent Gates failure 43328703870 identifies unqualified technical
+worker wording at developer-setup.md:153–154. Extend editorial scope only to those
+two references, identifying them as Celery workers; retain the vocabulary gate
+unchanged and rerun it. Documentation review covers this wording correction.
+
+The directory-sync repair's first suite run had 24 passes and four sample-budget
+failures: synchronous real filesystem fsync exceeded the fake Docker fixture's
+one-second sample budget. The fixture now uses a 30-second sample deadline;
+production limits are unchanged, injected timeout refusal and real process
+0.2-second deadline tests remain. The repaired suite passes all 28 tests in
+12.10 seconds (`/tmp/image-cleanup-sync-tests2.log`). Both directory-sync failure
+boundaries forbid Docker creation. Ruff, stale authorization documentation and
+Markdown link checks pass. Actual-image and structure rechecks are tracked
+separately; the earlier seven-sample result does not attest these later edits.
diff --git a/backend/scripts/checker_image.py b/backend/scripts/checker_image.py
index e42425715..b8c821448 100644
--- a/backend/scripts/checker_image.py
+++ b/backend/scripts/checker_image.py
@@ -478,6 +478,15 @@ def execute(args, evidence: dict, checkpoint) -> dict:
         }
 
 
+def sync_directory(path: Path) -> None:
+    """Persist directory entries before relying on a published cleanup receipt."""
+    descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
+    try:
+        os.fsync(descriptor)
+    finally:
+        os.close(descriptor)
+
+
 def write_json(path: Path, value: dict) -> None:
     """Replace one owned receipt atomically; no credentials or raw checker text are stored."""
     temporary = path.with_suffix(".tmp")
@@ -487,6 +496,7 @@ def write_json(path: Path, value: dict) -> None:
         handle.flush()
         os.fsync(handle.fileno())
     temporary.replace(path)
+    sync_directory(path.parent)
 
 
 def main(argv: list[str] | None = None) -> int:
@@ -527,6 +537,9 @@ def main(argv: list[str] | None = None) -> int:
     try:
         output.mkdir(mode=0o700, parents=True, exist_ok=False)
         owned_output = True
+        # Persist newly created ancestors too, including the default receipt root.
+        for directory in (output, *output.parents):
+            sync_directory(directory)
         outputs = execute(args, evidence, lambda: write_json(output / "receipt.json", evidence))
         for name, value in outputs.items():
             write_json(output / name, value)
diff --git a/backend/tests/test_checker_image.py b/backend/tests/test_checker_image.py
index 2320770ee..338c6e4fd 100644
--- a/backend/tests/test_checker_image.py
+++ b/backend/tests/test_checker_image.py
@@ -4,7 +4,9 @@
 
 import hashlib
 import json
+import os
 from pathlib import Path
+import stat
 import sys
 import time
 
@@ -42,7 +44,10 @@ def project(tmp_path: Path) -> Path:
         "resources": {
             "cpu_millis": 500,
             "memory_bytes": 134217728,
-            "deadline_ms": 1000,
+            # Receipt fsync uses the real filesystem even with fake Docker.
+            # Deadline refusal is exercised separately with injected timeout
+            # and real bounded child-process tests, not host disk latency.
+            "deadline_ms": 30000,
             "maximum_output_bytes": 32768,
         },
         "samples": [
@@ -267,6 +272,31 @@ def response(*args, **kwargs):
     assert not (output / "registry.json").exists()
 
 
+@pytest.mark.parametrize("boundary", ["output_creation", "receipt_publication"])
+def test_directory_sync_failure_prevents_container_creation(
+    project, transport, tmp_path, monkeypatch, boundary,
+):
+    """Both the output ancestry and renamed receipt must survive before create."""
+    output = tmp_path / "new-parent" / "release"
+    original = os.fsync
+    rejected = []
+
+    def fsync(descriptor):
+        if stat.S_ISDIR(os.fstat(descriptor).st_mode):
+            published = (output / "receipt.json").exists()
+            if (boundary == "receipt_publication") == published:
+                rejected.append(boundary)
+                raise OSError("injected directory sync failure")
+        return original(descriptor)
+
+    monkeypatch.setattr(cli.os, "fsync", fsync)
+    assert cli.main([str(project), "--out", str(output)]) == 1
+    assert rejected
+    docker, aws_calls = transport
+    assert not any(args[0] == "create" for args, _ in docker.calls)
+    assert not aws_calls
+
+
 def test_publish_verifies_exact_image_and_rechecks_digest_before_outputs(
     project, transport, tmp_path, capsys
 ):
diff --git a/docs/engineering/developer-setup.md b/docs/engineering/developer-setup.md
index 74f29b504..d5ce4faf1 100644
--- a/docs/engineering/developer-setup.md
+++ b/docs/engineering/developer-setup.md
@@ -150,8 +150,8 @@ Both require a UUID `Idempotency-Key` and no body; manager review and separate
 approvals remain required. See the [local pilot](local-pilot.md#declare-and-upload-a-real-guide-document).
 
 The single-request submission implementation has an opt-in `submission-intake`
-worker profile in local Compose. Its `submission-finalizer` service
-consumes only `workstream.submission_finalization`; the general worker consumes
+Celery worker profile in local Compose. Its `submission-finalizer` service
+consumes only `workstream.submission_finalization`; the general Celery worker consumes
 `celery,workstream.outbox`. Set `WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY`
 to an approved positive integer before enabling the profile. Missing or invalid
 values stop that consumer before Celery starts. No concurrency default or native

From da3ff9dc18a91b84584d8abd628e9d28f4dcf561 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:34:07 +0100
Subject: [PATCH 131/513] Record verified image cleanup custody repair

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md     | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index d71f71f6d..3b13557a5 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3271,3 +3271,14 @@ production limits are unchanged, injected timeout refusal and real process
 boundaries forbid Docker creation. Ruff, stale authorization documentation and
 Markdown link checks pass. Actual-image and structure rechecks are tracked
 separately; the earlier seven-sample result does not attest these later edits.
+
+Final repair evidence: architecture, QA/test-delta and documentation passed clean
+e31200fc4. IMAGE-CLEANUP-DURABILITY-01 is closed. QA additionally disabled
+`sync_directory` in memory and both injected-failure tests failed, confirming
+they discriminate missing synchronization. No actual power-cut drill is claimed.
+The post-sync actual Docker run passed all seven samples with confirmed cleanup
+(`/tmp/image-cleanup-sync-live.log`, receipt
+`.checker-images/5250510b3df74e588192121327ae6c3f/receipt.json`). Structure validation
+passed (`/tmp/image-cleanup-sync-structure.log`), and Commitrail passed. An
+unacknowledged daemon create remains an explicit unresolved receipt obligation;
+this engineering command still does not supply an automatic daemon reaper.

From 8d5780f660ca956d41cde246bb708a2b9e56cd31 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:40:24 +0100
Subject: [PATCH 132/513] Observe exact multipart reclamation without releasing
 source charges

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 51 +++++++++++++++
 backend/app/adapters/artifacts/local.py       |  4 ++
 .../artifacts/local_submission_source.py      | 12 ++++
 .../app/adapters/artifacts/s3_compatible.py   | 19 ++++++
 backend/app/interfaces/artifacts.py           | 10 +++
 .../test_sealed_source_observation.py         | 64 ++++++++++++++++++-
 backend/tests/test_artifact_architecture.py   |  7 +-
 .../tests/test_artifact_store_conformance.py  |  4 +-
 backend/tests/test_local_artifact_store.py    |  2 +
 backend/tests/test_s3_artifact_store.py       |  7 +-
 10 files changed, 172 insertions(+), 8 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 3b13557a5..3276a612a 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3282,3 +3282,54 @@ The post-sync actual Docker run passed all seven samples with confirmed cleanup
 passed (`/tmp/image-cleanup-sync-structure.log`), and Commitrail passed. An
 unacknowledged daemon create remains an explicit unresolved receipt obligation;
 this engineering command still does not supply an automatic daemon reaper.
+
+## Source cleanup observation prerequisite
+
+Existing adapters can request abort, but cannot confirm the exact multipart
+handle's absence. Add a read-only `source_upload_parts_absent` capability to the
+ArtifactStore interface, Local helper/adapter and S3 adapter; update existing
+adapter conformance declarations and source tests. This observation is a necessary
+input to the durable cleanup owner, never charge-release authority: it says
+nothing about outstanding calls or an object produced by completion. Only exact
+NoSuchUpload may confirm S3 handle absence; an empty successful ListParts keeps a
+live handle unresolved, and bucket/access/transport errors fail closed. Local
+abort currently retains bundle bytes, so it cannot be called reclaimed.
+
+Allowed scope: those interface/adapters, existing Local/S3/conformance test
+modules, and this record. No deletion, quota release, IAM broadening or public
+route is introduced in this prerequisite. Acceptance: live empty and populated
+handles remain unresolved; exact aborted handle confirms absence on real MinIO;
+other handle remains untouched; malformed/foreign/provider failures never count
+as absence; Local abort with retained bundle remains unresolved. Verification:
+focused Local/MinIO behavior, existing conformance coverage, Ruff and structure.
+Risk: storage cleanup proof boundary. Reviewers: architecture/security and
+QA/test delta. Human focus: distinction between absence of multipart parts and
+settlement of all writes/completed objects. The full cleanup owner, tombstones,
+exact deletion and charge release remain required immediately after this port.
+
+Place provider failure/namespace probes in existing selected
+`backend/tests/artifacts/test_sealed_source_observation.py` alongside the current
+exact-source observation proofs. This avoids growing the near-limit S3 test
+module or introducing a new test lane; its existing MinIO selection is retained.
+
+Extend the existing architecture proof's exact provider-method set for the new
+observation and permit `ListParts` only inside that typed source method. Keep
+all deletion/copy/global-list prohibitions and cross-owner call restrictions.
+This requires the existing `backend/tests/test_artifact_architecture.py` file;
+review includes CI integrity for this exact allowlist extension.
+
+First isolated integration run: 89 passed, one Local fixture failure; database
+and MinIO cleanup both completed (`/tmp/source-cleanup-observation.json`). Lost
+initiation was injected after metadata publication but before staging-file
+creation, so uploading into that fixture was invalid. Corrected it to assert
+confirmed absent parts after abort; a separate successful-initiation test writes
+real staging bytes and proves abort does not reclaim them. A direct focused run
+passed the corrected initiation case but the other module's MinIO autouse fixture
+used the wrong default port (9000), so that run is excluded from green evidence.
+The full corrected run uses the isolated runner and explicit59043 endpoint.
+
+Architecture tests passed48 cases (`/tmp/source-cleanup-architecture.log`);
+structure validation and Ruff passed before the final small Local test repair.
+The initial fixture edits overlapped the first integration run, so that receipt
+is not frozen-head proof. The corrected run and final review establish the
+candidate evidence separately; no cleanup or charge-release readiness is claimed.
diff --git a/backend/app/adapters/artifacts/local.py b/backend/app/adapters/artifacts/local.py
index a88de9776..b4af68b6d 100644
--- a/backend/app/adapters/artifacts/local.py
+++ b/backend/app/adapters/artifacts/local.py
@@ -256,6 +256,10 @@ async def request_source_abort(self, upload: SubmissionSourceUpload, *,
                                    operation_evidence: ArtifactProviderOperationEvidence | None = None) -> None:
         await self._source_io(LocalSubmissionSource(self).abort, upload)
 
+    async def source_upload_parts_absent(self, upload: SubmissionSourceUpload, *,
+                                        operation_evidence: ArtifactProviderOperationEvidence | None = None) -> bool:
+        return await self._source_io(LocalSubmissionSource(self).parts_absent, upload)
+
     def open_source(self, source: SealedSubmissionSource, *, operation_evidence: ArtifactProviderOperationEvidence | None = None, maximum_chunk_bytes: int = 64 * 1024) -> AsyncGenerator[bytes, None]:
         if type(maximum_chunk_bytes) is not int or not 1 <= maximum_chunk_bytes <= 64 * 1024:
             raise ValueError("source read chunk bound is invalid")
diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py
index a53f82788..7581e4dbc 100644
--- a/backend/app/adapters/artifacts/local_submission_source.py
+++ b/backend/app/adapters/artifacts/local_submission_source.py
@@ -318,6 +318,18 @@ def abort(self, upload: SubmissionSourceUpload) -> None:
         except FileNotFoundError:
             return
 
+    def parts_absent(self, upload: SubmissionSourceUpload) -> bool:
+        """An abort marker alone does not reclaim the local staging inode."""
+        upload = SubmissionSourceUpload.model_validate(upload)
+        try:
+            with self.locked(upload.intent.location) as directory:
+                self.upload(directory, upload)
+                return (self.exists(directory, "aborted.json")
+                        and not self.exists(directory, "bundle.zip"))
+        except FileNotFoundError:
+            # A missing metadata file is not proof the staging bytes are gone.
+            return False
+
     def seal(self, directory: int) -> tuple[SubmissionSourceCompletion, SealedSubmissionSource]:
         value = json.loads(self.read(directory, "seal.json"))
         if not isinstance(value, dict) or set(value) != {"completion", "source"}:
diff --git a/backend/app/adapters/artifacts/s3_compatible.py b/backend/app/adapters/artifacts/s3_compatible.py
index 6c2c1d290..1dbaed34e 100644
--- a/backend/app/adapters/artifacts/s3_compatible.py
+++ b/backend/app/adapters/artifacts/s3_compatible.py
@@ -711,6 +711,25 @@ async def request_source_abort(
         except ArtifactObjectMissingError:
             return
 
+    async def source_upload_parts_absent(
+        self, upload: SubmissionSourceUpload, *,
+        operation_evidence: ArtifactProviderOperationEvidence | None = None,
+    ) -> bool:
+        """Only exact NoSuchUpload confirms absence; an empty live handle cannot."""
+        upload = SubmissionSourceUpload.model_validate(upload)
+        evidence = operation_evidence or ArtifactProviderOperationEvidence()
+        async with self._source_client(upload.intent.location, evidence) as client:
+            try:
+                await client.list_parts(
+                    Bucket=self._bucket, Key=self._source_key(upload.intent.location),
+                    UploadId=upload.provider_upload_id, MaxParts=1,
+                )
+            except ClientError as error:
+                if _provider_http_status(error) == 404 and _provider_error_code(error) == "NoSuchUpload":
+                    return True
+                raise
+        return False
+
     async def complete_source_upload(
         self, completion: SubmissionSourceCompletion, *,
         operation_evidence: ArtifactProviderOperationEvidence | None = None,
diff --git a/backend/app/interfaces/artifacts.py b/backend/app/interfaces/artifacts.py
index 4746b7d79..b7a0589c8 100644
--- a/backend/app/interfaces/artifacts.py
+++ b/backend/app/interfaces/artifacts.py
@@ -448,6 +448,16 @@ async def request_source_abort(
     ) -> None:
         """Request scoped abort; acknowledgement alone never releases a charge."""
 
+    async def source_upload_parts_absent(
+        self, upload: SubmissionSourceUpload, *,
+        operation_evidence: ArtifactProviderOperationEvidence | None = None,
+    ) -> bool:
+        """Observe exact handle reclamation, not settlement of late calls or objects.
+
+        True alone never authorizes charge release. The owner must also reconcile
+        outstanding writes and any exact generation produced by completion.
+        """
+
     async def put(
         self,
         source: CommittedArtifactSource,
diff --git a/backend/tests/artifacts/test_sealed_source_observation.py b/backend/tests/artifacts/test_sealed_source_observation.py
index 5a0eac98e..c1f43c491 100644
--- a/backend/tests/artifacts/test_sealed_source_observation.py
+++ b/backend/tests/artifacts/test_sealed_source_observation.py
@@ -4,12 +4,16 @@
 
 import pytest
 
-from app.interfaces.artifacts import ArtifactIntegrityError, SealedSourceObservation
+from app.interfaces.artifacts import (
+    ArtifactIntegrityError, ArtifactObjectMissingError, ArtifactOperationConflictError,
+    ArtifactStoreUnavailableError, SealedSourceObservation,
+)
+from app.modules.artifacts.api.submission_intake import SubmissionSourceUpload
 from tests.test_local_artifact_store import (
     initialize_local_store, local_source_completion, local_source_intent,
 )
 from tests.test_s3_artifact_store import (
-    MINIO_BUCKET, source_completion,
+    MINIO_BUCKET, source_completion, source_intent, _client_error,
     source_store as source_store,
     provision_minio_bucket as provision_minio_bucket,
 )
@@ -17,6 +21,62 @@
 pytestmark = pytest.mark.asyncio
 
 
+async def test_local_abort_does_not_confirm_retained_staging_bytes(tmp_path):
+    root = tmp_path / "store"
+    store = initialize_local_store(root=root)
+    try:
+        upload = await store.begin_source_upload(local_source_intent(store))
+        await store.upload_source_part(upload, 1, b"retained-part")
+        await store.request_source_abort(upload)
+        assert await store.source_upload_parts_absent(upload) is False
+        assert (root / "objects" / upload.intent.location.object_ref).read_bytes() == b"retained-part"
+        foreign = upload.model_copy(update={"provider_upload_id": "foreign"})
+        with pytest.raises(ArtifactOperationConflictError):
+            await store.source_upload_parts_absent(foreign)
+    finally:
+        store.close()
+
+
+@pytest.mark.parametrize("code,status,expected", [
+    ("NoSuchUpload", 404, True),
+    ("NoSuchUpload", 403, ArtifactStoreUnavailableError),
+    ("NoSuchBucket", 404, ArtifactStoreUnavailableError),
+    ("NoSuchKey", 404, ArtifactObjectMissingError),
+    ("AccessDenied", 403, ArtifactStoreUnavailableError),
+    (None, None, False),
+])
+async def test_parts_absence_requires_exact_upload_missing(source_store, monkeypatch, code, status, expected):
+    store = source_store
+    upload = SubmissionSourceUpload(intent=source_intent(store), provider_upload_id="owned-upload")
+    seen = []
+
+    class PartsOnly:
+        async def list_parts(self, **kwargs):
+            seen.append(kwargs)
+            if code:
+                raise _client_error(code, status)
+            return {"Parts": [], "IsTruncated": False}
+
+    @asynccontextmanager
+    async def client():
+        yield PartsOnly()
+
+    monkeypatch.setattr(store, "_client", client)
+    if isinstance(expected, type):
+        with pytest.raises(expected):
+            await store.source_upload_parts_absent(upload)
+    else:
+        assert await store.source_upload_parts_absent(upload) is expected
+    assert seen == [dict(Bucket=MINIO_BUCKET, Key=store._source_key(upload.intent.location),
+                         UploadId="owned-upload", MaxParts=1)]
+    foreign = upload.model_copy(update={"intent": upload.intent.model_copy(update={
+        "location": upload.intent.location.model_copy(update={"namespace_fingerprint": "sha256:" + "0" * 64}),
+    })})
+    with pytest.raises(ArtifactOperationConflictError):
+        await store.source_upload_parts_absent(foreign)
+    assert len(seen) == 1
+
+
 async def test_local_observation_uses_seal_and_inode_without_body_read(tmp_path, monkeypatch):
     store = initialize_local_store(root=tmp_path / "store")
     try:
diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py
index 3cd123e39..47b1fdc94 100644
--- a/backend/tests/test_artifact_architecture.py
+++ b/backend/tests/test_artifact_architecture.py
@@ -93,7 +93,7 @@
 }
 PROVIDER_METHODS = {"put", "observe_put_result", "open", "head", "begin_source_upload",
                     "upload_source_part", "complete_source_upload", "open_source",
-                    "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort"}
+                    "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort", "source_upload_parts_absent"}
 CONCRETE_ADAPTER_MODULES = {
     "app.adapters.artifacts.local",
     "app.adapters.artifacts.s3_compatible",
@@ -464,7 +464,7 @@ def test_s3_adapter_exposes_only_required_immutable_object_operations() -> None:
     """Permit multipart only at typed source methods; preserve unrelated objects."""
     allowed = {"get_object", "head_object", "put_object", "get_bucket_versioning",
                "create_multipart_upload", "upload_part", "complete_multipart_upload",
-               "list_multipart_uploads", "abort_multipart_upload"}
+               "list_multipart_uploads", "abort_multipart_upload", "list_parts"}
     forbidden = {
         "copy_object",
         "delete_object",
@@ -494,9 +494,10 @@ def test_s3_adapter_exposes_only_required_immutable_object_operations() -> None:
         "observe_sealed_source": {"head_object"},
         "discover_source_uploads": {"list_multipart_uploads"},
         "request_source_abort": {"abort_multipart_upload"},
+        "source_upload_parts_absent": {"list_parts"},
     }
     source_only = {"get_bucket_versioning", "create_multipart_upload", "upload_part",
-                   "complete_multipart_upload", "list_multipart_uploads", "abort_multipart_upload"}
+                   "complete_multipart_upload", "list_multipart_uploads", "abort_multipart_upload", "list_parts"}
     store = next(node for node in _tree(S3_ADAPTER_MODULE).body
                  if isinstance(node, ast.ClassDef) and node.name == "S3CompatibleArtifactStore")
     for method in store.body:
diff --git a/backend/tests/test_artifact_store_conformance.py b/backend/tests/test_artifact_store_conformance.py
index 563b0e12e..47168e211 100644
--- a/backend/tests/test_artifact_store_conformance.py
+++ b/backend/tests/test_artifact_store_conformance.py
@@ -218,7 +218,7 @@ class TestLocalArtifactStoreConformance(ArtifactStoreConformanceTests):
 
     expected_source_operations = frozenset({
         "begin_source_upload", "upload_source_part", "complete_source_upload",
-        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort",
+        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort", "source_upload_parts_absent",
     })
 
     expected_identity = ExternalServiceAdapterIdentity("artifact_store", "local")
@@ -402,5 +402,5 @@ def test_artifact_store_protocol_declares_only_v2_operations() -> None:
     assert methods == {
         "head", "identity", "observe_put_result", "open", "put",
         "begin_source_upload", "upload_source_part", "complete_source_upload",
-        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort",
+        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort", "source_upload_parts_absent",
     }
diff --git a/backend/tests/test_local_artifact_store.py b/backend/tests/test_local_artifact_store.py
index 8859b7dcd..9008b5f1d 100644
--- a/backend/tests/test_local_artifact_store.py
+++ b/backend/tests/test_local_artifact_store.py
@@ -1087,7 +1087,9 @@ def lost_ack(self, directory, name, value):
     try:
         uploads = await store.discover_source_uploads(intent)
         assert len(uploads) == 1 and uploads[0].intent == intent
+        assert await store.source_upload_parts_absent(uploads[0]) is False
         await store.request_source_abort(uploads[0])
+        assert await store.source_upload_parts_absent(uploads[0]) is True
         assert await store.discover_source_uploads(intent) == ()
         with pytest.raises(ArtifactPreconditionFailedError):
             await store.begin_source_upload(intent)
diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py
index fead2f408..d8fedcf9f 100644
--- a/backend/tests/test_s3_artifact_store.py
+++ b/backend/tests/test_s3_artifact_store.py
@@ -91,7 +91,7 @@ class TestMinioArtifactStoreConformance(ArtifactStoreConformanceTests):
     )
     expected_source_operations = frozenset({
         "begin_source_upload", "upload_source_part", "complete_source_upload",
-        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort",
+        "open_source", "observe_source_upload", "observe_sealed_source", "discover_source_uploads", "request_source_abort", "source_upload_parts_absent",
     })
 
     def make_store(self, root: Path) -> ArtifactStore:
@@ -1169,8 +1169,13 @@ async def interrupted_client():
     monkeypatch.setattr(store, "_client", original_client)
     discovered = await store.discover_source_uploads(intent)
     assert len(discovered) == 1
+    assert await store.source_upload_parts_absent(discovered[0]) is False
+    await store.upload_source_part(discovered[0], 1, b"retained-part")
+    assert await store.source_upload_parts_absent(discovered[0]) is False
     await store.request_source_abort(discovered[0])
     await store.request_source_abort(discovered[0])  # NoSuchUpload is safe to repeat.
+    assert await store.source_upload_parts_absent(discovered[0]) is True
+    assert await store.source_upload_parts_absent(other) is False
     assert await store.discover_source_uploads(intent) == ()
     assert await store.discover_source_uploads(other.intent) == (other,)
     await store.request_source_abort(other)

From f916044011b552d9ae72381a416cb96b648c603f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:43:54 +0100
Subject: [PATCH 133/513] Bound backend cache regression to the actual
 preflight job

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++
 scripts/test_lightweight_agent_gates.py           |  2 +-
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 3276a612a..c0475a492 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3333,3 +3333,18 @@ structure validation and Ruff passed before the final small Local test repair.
 The initial fixture edits overlapped the first integration run, so that receipt
 is not frozen-head proof. The corrected run and final review establish the
 candidate evidence separately; no cleanup or charge-release readiness is claimed.
+
+Corrected observation run passed91 tests in31.71seconds with PostgreSQL and MinIO
+cleanup complete (`/tmp/source-cleanup-observation2.log/json`). It launched at
+base da3ff9dc1 with all final product edits present; committing8d5780f66 mid-run
+changed no product files. This is worktree evidence, not exact-head launch proof.
+Architecture/security, QA/test-delta and docs/CI-integrity passed clean8d5780f66.
+Final structure validation passed (`/tmp/source-cleanup-structure-final.log`).
+
+Hosted Agent Gates run43329967178 exposed an adjacent test-selector bug:
+`test_backend_uv_cache_keeps_fresh_frozen_installs_and_exact_inputs` splits the
+preflight job through `lanes`, accidentally including the newer independent
+external-checker-runtime job and counting its installer twice. Extend scope to
+that existing test's extraction delimiter only, ending at the actual next job.
+Keep all exact installer/cache assertions and workflow files unchanged. Verify
+all108 lightweight/stale-review tests; CI-integrity reviewer checks this repair.
diff --git a/scripts/test_lightweight_agent_gates.py b/scripts/test_lightweight_agent_gates.py
index 8b5f5486e..4c10de916 100644
--- a/scripts/test_lightweight_agent_gates.py
+++ b/scripts/test_lightweight_agent_gates.py
@@ -645,7 +645,7 @@ def test_backend_uv_cache_keeps_fresh_frozen_installs_and_exact_inputs(self) ->
         cache_env = 'echo "UV_CACHE_DIR=${RUNNER_TEMP}/backend-uv-cache" >> "${GITHUB_ENV}"'
         job_blocks = (
             (
-                workflow.split("\n  auth-boundary-preflight:\n", 1)[1].split("\n  lanes:\n", 1)[0],
+                workflow.split("\n  auth-boundary-preflight:\n", 1)[1].split("\n  external-checker-runtime:\n", 1)[0],
                 "uv sync --frozen --extra agents --extra dev",
             ),
             (

From be554d33d38bf5a2fa1a74b8cde3add72e4127f7 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:44:41 +0100
Subject: [PATCH 134/513] Account for frozen installs in the external checker
 runtime job

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md    |  8 ++++++++
 scripts/test_lightweight_agent_gates.py              | 12 +++++++++---
 2 files changed, 17 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index c0475a492..d6c010853 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3348,3 +3348,11 @@ external-checker-runtime job and counting its installer twice. Extend scope to
 that existing test's extraction delimiter only, ending at the actual next job.
 Keep all exact installer/cache assertions and workflow files unchanged. Verify
 all108 lightweight/stale-review tests; CI-integrity reviewer checks this repair.
+
+The first targeted gate rerun (35 tests) exposed the same stale assumption in
+workflow-wide totals after fixing job extraction. Include the actual fourth
+installer/lock-check and third agents frozen sync in those exact totals, and
+add explicit one-each/order assertions for the independent runtime job. The
+three cached jobs' exact cache/install assertions remain unchanged. This is a
+complete test-model correction for the existing fourth job, not permission to
+skip or loosen installs. Run the workflow's complete six-module108-test command.
diff --git a/scripts/test_lightweight_agent_gates.py b/scripts/test_lightweight_agent_gates.py
index 4c10de916..7cefb9a6b 100644
--- a/scripts/test_lightweight_agent_gates.py
+++ b/scripts/test_lightweight_agent_gates.py
@@ -668,10 +668,16 @@ def test_backend_uv_cache_keeps_fresh_frozen_installs_and_exact_inputs(self) ->
             self.assertLess(job.index("Restore exact backend uv downloads"), job.index(cache_env))
             self.assertLess(job.index(cache_env), job.index(tool_install))
             self.assertLess(job.index(tool_install), job.index(frozen_install))
-        self.assertEqual(workflow.count(tool_install), 3)
-        self.assertEqual(workflow.count(lock_check), 3)
+        runtime_job = workflow.split("\n  external-checker-runtime:\n", 1)[1].split("\n  lanes:\n", 1)[0]
+        self.assertEqual(runtime_job.count(tool_install), 1)
+        self.assertEqual(runtime_job.count(lock_check), 1)
+        self.assertEqual(runtime_job.count("uv sync --frozen --extra agents --extra dev"), 1)
+        self.assertLess(runtime_job.index(tool_install), runtime_job.index(lock_check))
+        self.assertLess(runtime_job.index(lock_check), runtime_job.index("uv sync --frozen"))
+        self.assertEqual(workflow.count(tool_install), 4)
+        self.assertEqual(workflow.count(lock_check), 4)
         self.assertEqual(
-            workflow.count("uv sync --frozen --extra agents --extra dev"), 2
+            workflow.count("uv sync --frozen --extra agents --extra dev"), 3
         )
         self.assertEqual(
             workflow.count(

From b41501f6c051d85b55299f7e89b1d2d9f7492d9d Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:45:21 +0100
Subject: [PATCH 135/513] Keep virtual environment cache guard scoped to cache
 steps

---
 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++++
 scripts/test_lightweight_agent_gates.py                   | 8 +++++---
 2 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index d6c010853..955751e53 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3356,3 +3356,11 @@ add explicit one-each/order assertions for the independent runtime job. The
 three cached jobs' exact cache/install assertions remain unchanged. This is a
 complete test-model correction for the existing fourth job, not permission to
 skip or loosen installs. Run the workflow's complete six-module108-test command.
+
+The complete gate run exposed the final outdated global assertion: `.venv` was
+forbidden anywhere in the workflow, including the runtime job's legitimate
+frozen interpreter path. Restrict that prohibition to every cache restore/save
+step (the behavior this cache test owns), preserving the ban on cached virtual
+environments. Correct the remaining preflight/save extraction boundaries too.
+No workflow or production command changes. Earlier failed35/108-test runs remain
+failed evidence; only the final rerun can establish the repair.
diff --git a/scripts/test_lightweight_agent_gates.py b/scripts/test_lightweight_agent_gates.py
index 7cefb9a6b..2e5f89f8c 100644
--- a/scripts/test_lightweight_agent_gates.py
+++ b/scripts/test_lightweight_agent_gates.py
@@ -691,21 +691,23 @@ def test_backend_uv_cache_keeps_fresh_frozen_installs_and_exact_inputs(self) ->
         self.assertNotIn("runner.", root_env)
         uv_save = workflow.split(
             "      - name: Save verified backend uv downloads to trusted cache\n", 1
-        )[1].split("\n  lanes:\n", 1)[0]
+        )[1].split("\n  external-checker-runtime:\n", 1)[0]
         self.assertIn(
             "if: github.event_name == 'push' && github.ref == 'refs/heads/main' "
             "&& steps.uv-cache.outputs.cache-hit != 'true'",
             uv_save,
         )
         preflight = workflow.split("\n  auth-boundary-preflight:\n", 1)[1].split(
-            "\n  lanes:\n", 1
+            "\n  external-checker-runtime:\n", 1
         )[0]
         self.assertLess(
             preflight.index("      - name: Validate module, AUTH, and test boundaries"),
             preflight.index("      - name: Save verified backend uv downloads to trusted cache"),
         )
         self.assertNotIn("restore-keys:", workflow)
-        self.assertNotIn(".venv", workflow)
+        for step in workflow.split("\n      - "):
+            if "uses: actions/cache/" in step:
+                self.assertNotIn(".venv", step)
 
     def test_backend_python_commands_stay_in_the_frozen_uv_environment(self) -> None:
         workflow = Path(".github/workflows/backend.yml").read_text(encoding="utf-8")

From 7151bc8c1c88d4f7586ec880dbb40e57b18a60a8 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:46:52 +0100
Subject: [PATCH 136/513] Record reviewed source cleanup observation and CI
 repair

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md        | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 955751e53..bcbb6c833 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3364,3 +3364,12 @@ step (the behavior this cache test owns), preserving the ban on cached virtual
 environments. Correct the remaining preflight/save extraction boundaries too.
 No workflow or production command changes. Earlier failed35/108-test runs remain
 failed evidence; only the final rerun can establish the repair.
+
+Final CI test repair: all 108 workflow-selected lightweight regression tests pass
+(`/tmp/source-cleanup-agent-gates3.log`, 5.747 seconds). CI-integrity review passed
+clean b41501f6c; an independent in-memory `.venv` cache-path injection still fails
+the exact guard. No workflow file changed. Commitrail, stale authorization docs
+and Markdown links passed. Hosted results for the next push remain unverified.
+The next product boundary is the durable source cleanup claim/tombstone and
+exact eligible deletion, followed by confirmed charge release; the observation
+port by itself intentionally grants none of those operations.

From f29335f896be26794aa156758a09375318991292 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 00:58:12 +0100
Subject: [PATCH 137/513] Persist fenced sealed-source cleanup claims and
 atomic quota release

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  50 +++++
 .../versions/0078_submission_cleanup.py       | 173 ++++++++++++++++++
 backend/app/db/models.py                      |   2 +-
 .../app/modules/artifacts/intake/capacity.py  |  13 ++
 .../app/modules/artifacts/intake/cleanup.py   | 103 +++++++++++
 .../app/modules/artifacts/intake/models.py    |  30 ++-
 backend/scripts/identifier_inventory.py       |   1 +
 backend/scripts/test_lane_catalogue.py        |   1 +
 .../test_submission_intake_admission.py       |  18 ++
 .../test_submission_intake_custody.py         |   4 +-
 .../test_submission_source_cleanup.py         | 168 +++++++++++++++++
 backend/tests/conftest.py                     |   4 +-
 .../tests/test_checker_evidence_migrations.py |   2 +-
 13 files changed, 561 insertions(+), 8 deletions(-)
 create mode 100644 backend/alembic/versions/0078_submission_cleanup.py
 create mode 100644 backend/app/modules/artifacts/intake/cleanup.py
 create mode 100644 backend/tests/artifacts/test_submission_source_cleanup.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index bcbb6c833..84e701fe2 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3373,3 +3373,53 @@ and Markdown links passed. Hosted results for the next push remain unverified.
 The next product boundary is the durable source cleanup claim/tombstone and
 exact eligible deletion, followed by confirmed charge release; the observation
 port by itself intentionally grants none of those operations.
+
+## Durable sealed-source cleanup custody
+
+Implement the next cleanup boundary in existing ART intake ownership: a retained
+claim/tombstone for an exact sealed terminal source, generation-fenced retries,
+and atomic confirmed charge release. Claim under existing TASK/operation locks;
+require at least two hours since terminal/seal activity and reject every accepted,
+retained, active or ambiguous source. Provider deletion will consume this exact
+claim outside transactions; confirmation must compare the current generation.
+Unsealed/uncertain upload reconciliation remains conservative until its outstanding
+write obligations are resolved, and cannot use this sealed-source path.
+
+Allowed scope: intake models/repository/capacity and cohesive cleanup owner/API,
+next migration0078, canonical model/identifier/reset registries, existing custody
+fixtures plus a selected cleanup test module, provider adapter integration and
+architecture guards, this record. No accepted-evidence deletion, generic key-only
+admin deletion, schema guard bypass in production, invented business/admin retry
+capability or quota release on abort ACK. Risk L0: retention, resource accounting
+and concurrency. Required reviews architecture/security, QA/test delta, and CI
+integrity/docs for affected guards/evidence. Human review focus: exact target,
+current ownership, retained-reference barriers, late writes, once-only release.
+Acceptance: positive eligible cleanup plus recent/live/accepted/retained denial,
+SQL forgery/immutability, stale claim and concurrent replay, uncertain delete
+retains charge, confirmed absence releases once. Verify with real PostgreSQL and
+Local/MinIO; any historical timestamp fixture is setup only, never a disabled
+cleanup guard. Public cleanup scheduling/authority and orphan reconciliation
+remain required for full feature completion.
+
+Initial custody candidate: migration 0078 adds one operation-owned cleanup table,
+its pending index, three cleanup functions/three triggers, extends the two existing
+charge/accounting guards and three charge constraints. No retained rows are
+rewritten. The fresh PostgreSQL migration completed; the observed schema fingerprint
+is `8dd976d22e0ea2e8c65a0ee47f0bc418a6315ddb67786876b16afbf92eecad5e`.
+The canonical expectation and model/reset/identifier registries are updated for
+that intended delta; model parity is part of the real database test run.
+
+The flush-only cleanup owner remains private and uncomposed. Its confirmation
+inputs must come from the forthcoming trusted provider coordinator; they are not
+public client assertions or a deletion capability. No scheduler, AUTH service
+boundary, provider deletion or unsealed reclamation is claimed by this candidate.
+Historical fixture aging is restricted to the isolated `workstream_test_` database
+and restores the foreground immutability trigger in the same setup transaction;
+cleanup/charge guards are never disabled. Positive owner accounting tests therefore
+prove database custody, not external deletion. Add the stalled accepted denial
+probe to the existing admission module that already owns its real AUTH/T4 fixture.
+
+Ruff, initial structure, migration application and whitespace checks passed.
+The first custody run began before two additional cleanup tests were added;
+its collection/output and the final focused rerun will be reported distinctly.
+Do not use that initial launch as frozen final test evidence.
diff --git a/backend/alembic/versions/0078_submission_cleanup.py b/backend/alembic/versions/0078_submission_cleanup.py
new file mode 100644
index 000000000..8ff5c418b
--- /dev/null
+++ b/backend/alembic/versions/0078_submission_cleanup.py
@@ -0,0 +1,173 @@
+"""Retain exact sealed-source cleanup claims and guard confirmed charge release."""
+import re
+
+from alembic import op
+from sqlalchemy import text
+
+revision = "0078_submission_cleanup"
+down_revision = "0077_submission_recovery"
+branch_labels = None
+depends_on = None
+
+
+def _replace(signature, old, new):
+    """Extend the installed owner guard only at its exact predecessor boundary."""
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))"
+    ), {"signature": signature}).scalar_one()
+    if body.count(old) != 1:
+        raise RuntimeError("cleanup predecessor shape changed: " + signature)
+    op.execute(body.replace(old, new))
+
+
+def upgrade():
+    """Add tombstones without rewriting any source or retained evidence."""
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.submission_intake_operations, public.submission_source_charges, "
+               "public.artifact_replicas, public.submission_bundle_admissions IN ACCESS EXCLUSIVE MODE")
+    op.execute(_TABLE)
+    op.execute("CREATE INDEX ix_source_cleanup_pending ON public.submission_source_cleanup_claims "
+               "(lease_expires_at) WHERE confirmed_at IS NULL")
+    for statement in re.split(r"\n(?=CREATE (?:FUNCTION|CONSTRAINT TRIGGER|TRIGGER))", _GUARDS):
+        if statement.strip():
+            op.execute(statement)
+    for name, expression in {
+        "positive_charge": "reserved_bytes>0 and accounted_bytes>=0 and accounted_bytes<=reserved_bytes",
+        "charge_state": "state in ('reserved','sealed','released')",
+        "charge_shape": "(state='reserved' and accounted_bytes=reserved_bytes and sealed_at is null) "
+                        "or (state='sealed' and sealed_at is not null and accounted_bytes>0) "
+                        "or (state='released' and sealed_at is not null and accounted_bytes=0)",
+    }.items():
+        op.execute(f"ALTER TABLE public.submission_source_charges DROP CONSTRAINT "
+                   f"ck_submission_source_charges_{name}")
+        op.execute(f"ALTER TABLE public.submission_source_charges ADD CONSTRAINT "
+                   f"ck_submission_source_charges_{name} CHECK ({expression})")
+    _replace("public.guard_submission_source_charge()", "  IF TG_OP='INSERT' THEN", _RELEASE + "\n  IF TG_OP='INSERT' THEN")
+    _replace("public.check_submission_source_accounting()", "  IF o.id IS NULL OR c.operation_id IS NULL",
+             _RELEASE_ACCOUNTING + "\n  IF o.id IS NULL OR c.operation_id IS NULL")
+
+
+def downgrade():
+    """Never discard retained cleanup custody through a downgrade."""
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
+
+
+_TABLE = """
+CREATE TABLE public.submission_source_cleanup_claims (
+ operation_id uuid NOT NULL,
+ claim_id uuid NOT NULL,
+ generation bigint NOT NULL,
+ source jsonb NOT NULL,
+ claimed_at timestamptz NOT NULL,
+ lease_expires_at timestamptz NOT NULL,
+ confirmed_at timestamptz,
+ CONSTRAINT pk_submission_source_cleanup_claims PRIMARY KEY(operation_id),
+ CONSTRAINT fk_source_cleanup_operation FOREIGN KEY(operation_id) REFERENCES public.submission_intake_operations(id),
+ CONSTRAINT ck_submission_source_cleanup_claims_claim_bounds CHECK (generation>0 AND lease_expires_at>claimed_at),
+ CONSTRAINT ck_submission_source_cleanup_claims_source_shape CHECK (jsonb_typeof(source)='object'),
+ CONSTRAINT ck_submission_source_cleanup_claims_claim_uuid7 CHECK
+   ((get_byte(uuid_send(claim_id),6)>>4)=7 AND (get_byte(uuid_send(claim_id),8)&192)=128)
+)
+"""
+
+_GUARDS = """
+CREATE FUNCTION public.require_sealed_source_cleanup(o public.submission_intake_operations)
+RETURNS void LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+BEGIN
+ IF o.id IS NULL OR o.state NOT IN ('rejected','failed','abandoned','cancelled')
+    OR o.accepted_at IS NOT NULL OR o.provider_generation IS NULL OR o.sealed_at IS NULL
+    OR o.terminal_at IS NULL OR greatest(o.terminal_at,o.sealed_at)>clock_timestamp()-interval '2 hours'
+    OR EXISTS(SELECT 1 FROM public.workstream_tasks WHERE id=o.task_id AND active_submission_operation_id=o.id)
+    OR EXISTS(SELECT 1 FROM public.artifact_replicas WHERE source_operation_id=o.id
+       OR (storage_namespace_id=o.namespace_id AND namespace_fingerprint=o.namespace_fingerprint
+           AND provider_object_ref=o.object_ref))
+    OR EXISTS(SELECT 1 FROM public.submission_bundle_admissions WHERE source_operation_id=o.id) THEN
+   RAISE EXCEPTION 'source cleanup is protected' USING ERRCODE='23514';
+ END IF;
+END $$;
+CREATE FUNCTION public.guard_submission_source_cleanup()
+RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE o public.submission_intake_operations%ROWTYPE; task_key uuid; expected jsonb;
+BEGIN
+ IF TG_OP IN ('DELETE','TRUNCATE') THEN
+   RAISE EXCEPTION 'source cleanup tombstone is retained' USING ERRCODE='23514'; END IF;
+ SELECT task_id INTO task_key FROM public.submission_intake_operations WHERE id=NEW.operation_id;
+ PERFORM 1 FROM public.workstream_tasks WHERE id=task_key FOR UPDATE;
+ SELECT * INTO o FROM public.submission_intake_operations WHERE id=NEW.operation_id FOR UPDATE;
+ PERFORM public.require_sealed_source_cleanup(o);
+ expected:=jsonb_build_object('location',jsonb_build_object('operation_id',o.id::text,
+   'namespace_id',o.namespace_id,'namespace_fingerprint',o.namespace_fingerprint,'provider_profile',o.provider_profile),
+   'provider_generation',o.provider_generation,'raw_sha256',o.raw_sha256,'raw_byte_count',o.raw_byte_count,
+   'sealed_upload_fence',o.sealed_upload_fence,'media_type','application/zip');
+ IF NEW.source IS DISTINCT FROM expected THEN
+   RAISE EXCEPTION 'source cleanup target differs' USING ERRCODE='23514'; END IF;
+ IF TG_OP='INSERT' THEN
+   IF NEW.generation<>1 OR NEW.confirmed_at IS NOT NULL THEN
+     RAISE EXCEPTION 'source cleanup initial claim differs' USING ERRCODE='23514'; END IF;
+   NEW.claimed_at:=clock_timestamp();
+ ELSE
+   IF OLD.confirmed_at IS NOT NULL THEN
+     IF NEW IS DISTINCT FROM OLD THEN
+       RAISE EXCEPTION 'confirmed source cleanup is immutable' USING ERRCODE='23514'; END IF;
+     RETURN NEW;
+   END IF;
+   IF NEW.operation_id IS DISTINCT FROM OLD.operation_id OR NEW.source IS DISTINCT FROM OLD.source THEN
+     RAISE EXCEPTION 'source cleanup identity is immutable' USING ERRCODE='23514'; END IF;
+   IF NEW.claim_id=OLD.claim_id THEN
+     IF (to_jsonb(NEW)-'confirmed_at') IS DISTINCT FROM (to_jsonb(OLD)-'confirmed_at')
+        OR OLD.lease_expires_at<=clock_timestamp() OR NEW.confirmed_at IS NULL THEN
+       RAISE EXCEPTION 'source cleanup fence is stale' USING ERRCODE='23514'; END IF;
+     NEW.confirmed_at:=clock_timestamp();
+   ELSE
+     IF OLD.lease_expires_at>clock_timestamp() OR NEW.generation<>OLD.generation+1 OR NEW.confirmed_at IS NOT NULL THEN
+       RAISE EXCEPTION 'source cleanup claim is busy' USING ERRCODE='23514'; END IF;
+     NEW.claimed_at:=clock_timestamp();
+   END IF;
+ END IF;
+ IF NEW.lease_expires_at<=clock_timestamp() THEN
+   RAISE EXCEPTION 'source cleanup lease expired' USING ERRCODE='23514'; END IF;
+ RETURN NEW;
+END $$;
+CREATE TRIGGER submission_source_cleanup_guard
+BEFORE INSERT OR UPDATE OR DELETE ON public.submission_source_cleanup_claims
+FOR EACH ROW EXECUTE FUNCTION public.guard_submission_source_cleanup();
+CREATE TRIGGER submission_source_cleanup_no_truncate BEFORE TRUNCATE ON public.submission_source_cleanup_claims
+FOR EACH STATEMENT EXECUTE FUNCTION public.guard_submission_source_cleanup();
+CREATE FUNCTION public.check_source_cleanup_release()
+RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE c public.submission_source_cleanup_claims%ROWTYPE; s public.submission_source_charges%ROWTYPE;
+BEGIN
+ SELECT * INTO c FROM public.submission_source_cleanup_claims WHERE operation_id=NEW.operation_id;
+ SELECT * INTO s FROM public.submission_source_charges WHERE operation_id=NEW.operation_id;
+ IF s.operation_id IS NULL OR (c.confirmed_at IS NOT NULL) IS DISTINCT FROM (s.state='released') THEN
+   RAISE EXCEPTION 'source cleanup release must be atomic' USING ERRCODE='23514'; END IF;
+ RETURN NULL;
+END $$;
+CREATE CONSTRAINT TRIGGER source_cleanup_release_atomic AFTER INSERT OR UPDATE ON public.submission_source_cleanup_claims
+DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_source_cleanup_release();
+"""
+
+_RELEASE = """
+  IF TG_OP='UPDATE' AND OLD.state='released' AND NEW.state<>'released' THEN
+    RAISE EXCEPTION 'released source charge is immutable' USING ERRCODE='23514'; END IF;
+  IF TG_OP='UPDATE' AND NEW.state='released' THEN
+    IF OLD.state NOT IN ('sealed','released') OR NEW.accounted_bytes<>0
+       OR (to_jsonb(NEW)-ARRAY['state','accounted_bytes']) IS DISTINCT FROM
+          (to_jsonb(OLD)-ARRAY['state','accounted_bytes'])
+       OR NOT EXISTS(SELECT 1 FROM public.submission_source_cleanup_claims
+          WHERE operation_id=o.id AND confirmed_at IS NOT NULL) THEN
+      RAISE EXCEPTION 'source charge requires confirmed cleanup' USING ERRCODE='23514'; END IF;
+    PERFORM public.require_sealed_source_cleanup(o);
+    RETURN NEW;
+  END IF;
+"""
+
+_RELEASE_ACCOUNTING = """
+  IF c.state='released' THEN
+    PERFORM public.require_sealed_source_cleanup(o);
+    IF c.accounted_bytes<>0 OR NOT EXISTS(SELECT 1 FROM public.submission_source_cleanup_claims
+       WHERE operation_id=o.id AND confirmed_at IS NOT NULL) THEN
+      RAISE EXCEPTION 'source charge requires confirmed cleanup' USING ERRCODE='23514'; END IF;
+    RETURN NULL;
+  END IF;
+"""
diff --git a/backend/app/db/models.py b/backend/app/db/models.py
index b7a86ef09..0cbe305d8 100644
--- a/backend/app/db/models.py
+++ b/backend/app/db/models.py
@@ -9,7 +9,7 @@
 from app.modules.api_controls.models import ApiRateControlCounter  # noqa: F401
 from app.modules.artifacts.intake.models import (  # noqa: F401
     SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge,
-    SubmissionSourceUploadReceipt,
+    SubmissionSourceUploadReceipt, SubmissionSourceCleanupClaim,
 )
 from app.modules.artifacts.models import (  # noqa: F401
     ArtifactBinding,
diff --git a/backend/app/modules/artifacts/intake/capacity.py b/backend/app/modules/artifacts/intake/capacity.py
index 7429b0700..27266e472 100644
--- a/backend/app/modules/artifacts/intake/capacity.py
+++ b/backend/app/modules/artifacts/intake/capacity.py
@@ -82,6 +82,19 @@ async def reserve(
         await self._session.flush()
         return row
 
+    async def release_confirmed(self, operation: SubmissionIntakeOperation) -> None:
+        """Release only against the same transaction's confirmed cleanup tombstone."""
+        from app.modules.artifacts.intake.models import SubmissionSourceCleanupClaim
+        await self._profile(operation, None)
+        claim = await self._session.get(SubmissionSourceCleanupClaim, operation.id)
+        charge = await self._session.scalar(select(SubmissionSourceCharge).where(
+            SubmissionSourceCharge.operation_id == operation.id,
+        ).with_for_update().execution_options(populate_existing=True))
+        if claim is None or claim.confirmed_at is None or charge is None or charge.state not in {"sealed", "released"}:
+            raise SubmissionSourceCapacityConflict("source_cleanup_unconfirmed")
+        charge.state, charge.accounted_bytes = "released", 0
+        await self._session.flush()
+
     async def seal(self, operation: SubmissionIntakeOperation) -> None:
         """Convert only unused allowance; terminal failures never reclaim bytes."""
         await self._profile(operation, None)
diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py
new file mode 100644
index 000000000..15f0870a0
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/cleanup.py
@@ -0,0 +1,103 @@
+"""Private sealed-source cleanup custody; no provider I/O or service authority.
+
+The composition root must authorize cleanup and act only on a committed claim.
+This owner retains uncertain targets and releases charges only with both exact
+object absence and settled upload-part obligations supplied by that coordinator.
+"""
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from uuid import UUID
+
+from sqlalchemy import func, select, text
+
+from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
+from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity
+from app.modules.artifacts.intake.models import SubmissionSourceCleanupClaim
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
+
+
+@dataclass(frozen=True, slots=True)
+class SealedSourceCleanupClaim:
+    """Exact durable deletion target; a copied value grants no deletion authority."""
+
+    claim_id: UUID
+    generation: int
+    source: SealedSubmissionSource
+    lease_expires_at: datetime
+    confirmed: bool
+
+
+def _claim_value(row: SubmissionSourceCleanupClaim) -> SealedSourceCleanupClaim:
+    """Recover typed source facts from persisted canonical JSON."""
+    import json
+    return SealedSourceCleanupClaim(
+        UUID(row.claim_id), row.generation,
+        SealedSubmissionSource.model_validate_json(json.dumps(row.source)),
+        row.lease_expires_at, row.confirmed_at is not None,
+    )
+
+
+class SealedSourceCleanup:
+    """Flush-only ownership: caller supplies current authority and root commits."""
+
+    def __init__(self, session, tasks):
+        self._session = session
+        self._intake = SubmissionIntakeRepository(session, tasks)
+
+    async def _locked(self, operation_id):
+        operation = await self._intake._lock(operation_id)
+        await self._session.execute(text(
+            "SELECT public.require_sealed_source_cleanup(o) "
+            "FROM public.submission_intake_operations o WHERE id=:id"
+        ), {"id": operation.id})
+        row = await self._session.scalar(select(SubmissionSourceCleanupClaim).where(
+            SubmissionSourceCleanupClaim.operation_id == operation.id,
+        ).with_for_update().execution_options(populate_existing=True))
+        return operation, row
+
+    async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: timedelta) -> SealedSourceCleanupClaim:
+        """Claim only a stable eligible source; never resume foreground work."""
+        if (type(claim_id) is not UUID or claim_id.version != 7
+                or type(lease_duration) is not timedelta or lease_duration <= timedelta(0)):
+            raise ValueError("source cleanup lease is invalid")
+        operation, row = await self._locked(operation_id)
+        now = await self._session.scalar(select(func.clock_timestamp()))
+        if row is not None:
+            if row.confirmed_at is not None:
+                return _claim_value(row)
+            if row.claim_id == str(claim_id):
+                if row.lease_expires_at <= now:
+                    raise IntakeCustodyConflict("source_cleanup_stale")
+                return _claim_value(row)
+            if row.lease_expires_at > now:
+                raise IntakeCustodyConflict("source_cleanup_busy")
+            row.claim_id, row.generation = str(claim_id), row.generation + 1
+            row.claimed_at, row.lease_expires_at = now, now + lease_duration
+        else:
+            row = SubmissionSourceCleanupClaim(
+                operation_id=operation.id, claim_id=str(claim_id), generation=1,
+                source=self._intake._sealed_source(operation).model_dump(mode="json"),
+                claimed_at=now, lease_expires_at=now + lease_duration,
+            )
+            self._session.add(row)
+        await self._session.flush()
+        await self._session.refresh(row)
+        return _claim_value(row)
+
+    async def confirm(self, claim: SealedSourceCleanupClaim, *, object_absent: bool,
+                      writes_settled: bool, parts_absent: bool) -> None:
+        """Commit exact absence and charge release together, never on an ACK."""
+        if object_absent is not True or writes_settled is not True or parts_absent is not True:
+            raise IntakeCustodyConflict("source_cleanup_unresolved")
+        operation, row = await self._locked(claim.source.location.operation_id)
+        if (row is None or row.claim_id != str(claim.claim_id) or row.generation != claim.generation
+                or row.source != claim.source.model_dump(mode="json")):
+            raise IntakeCustodyConflict("source_cleanup_stale")
+        if row.confirmed_at is not None:
+            return
+        now = await self._session.scalar(select(func.clock_timestamp()))
+        if row.lease_expires_at <= now:
+            raise IntakeCustodyConflict("source_cleanup_stale")
+        row.confirmed_at = now
+        await self._session.flush()
+        await SubmissionSourceCapacity(self._session).release_confirmed(operation)
diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py
index 438b7d1a6..6aa48d1fe 100644
--- a/backend/app/modules/artifacts/intake/models.py
+++ b/backend/app/modules/artifacts/intake/models.py
@@ -144,12 +144,13 @@ class SubmissionSourceCharge(Base):
     __table_args__ = (
         ForeignKeyConstraint(["operation_id"], ["submission_intake_operations.id"],
                              name="fk_submission_source_charge_operation"),
-        CheckConstraint("reserved_bytes>0 and accounted_bytes>0 and accounted_bytes<=reserved_bytes",
+        CheckConstraint("reserved_bytes>0 and accounted_bytes>=0 and accounted_bytes<=reserved_bytes",
                         name="positive_charge"),
         CheckConstraint("declared_raw_bytes is null or declared_raw_bytes=reserved_bytes", name="declared_reservation"),
-        CheckConstraint("state in ('reserved','sealed')", name="charge_state"),
+        CheckConstraint("state in ('reserved','sealed','released')", name="charge_state"),
         CheckConstraint("(state='reserved' and accounted_bytes=reserved_bytes and sealed_at is null) "
-                        "or (state='sealed' and sealed_at is not null)", name="charge_shape"),
+                        "or (state='sealed' and sealed_at is not null and accounted_bytes>0) "
+                        "or (state='released' and sealed_at is not null and accounted_bytes=0)", name="charge_shape"),
     )
 
     operation_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True)
@@ -160,6 +161,29 @@ class SubmissionSourceCharge(Base):
     sealed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
 
 
+class SubmissionSourceCleanupClaim(Base):
+    """Retained exact-source claim; confirmation and charge release commit together."""
+
+    __tablename__ = "submission_source_cleanup_claims"
+    __table_args__ = (
+        ForeignKeyConstraint(["operation_id"], ["submission_intake_operations.id"],
+                             name="fk_source_cleanup_operation"),
+        CheckConstraint("generation>0 and lease_expires_at>claimed_at", name="claim_bounds"),
+        CheckConstraint("jsonb_typeof(source)='object'", name="source_shape"),
+        CheckConstraint("(get_byte(uuid_send(claim_id),6)>>4)=7 and (get_byte(uuid_send(claim_id),8)&192)=128",
+                        name="claim_uuid7"),
+        Index("ix_source_cleanup_pending", "lease_expires_at", postgresql_where=text("confirmed_at is null")),
+    )
+
+    operation_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True)
+    claim_id: Mapped[str] = mapped_column(Uuid(as_uuid=False))
+    generation: Mapped[int] = mapped_column(BigInteger)
+    source: Mapped[dict] = mapped_column(JSONB)
+    claimed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
+    lease_expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
+    confirmed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+
+
 class SubmissionSourceUploadReceipt(Base):
     """Operation-owned initiation and completion facts across provider I/O."""
 
diff --git a/backend/scripts/identifier_inventory.py b/backend/scripts/identifier_inventory.py
index 94d613e7f..d1a7a120b 100644
--- a/backend/scripts/identifier_inventory.py
+++ b/backend/scripts/identifier_inventory.py
@@ -20,6 +20,7 @@
 GENERATION_CLASSIFICATION_FORMAT = "workstream-uuid-generation-classifications-1"
 GENERATION_CLASSIFICATIONS = "identifier_generation_classifications.json"
 SEMANTIC_KEYS = {
+    "submission_source_cleanup_claims": ("intake-operation-owned cleanup tombstone", ("operation_id",)),
     "submission_source_upload_receipts": ("intake-operation-owned upload receipt", ("operation_id",)),
     "submission_source_capacity_profiles": ("ART namespace-owned source allocation", ("namespace_id",)),
     "submission_source_charges": ("intake-operation-owned physical obligation", ("operation_id",)),
diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py
index 2119ec6d9..04e85c9b0 100644
--- a/backend/scripts/test_lane_catalogue.py
+++ b/backend/scripts/test_lane_catalogue.py
@@ -54,6 +54,7 @@ class TestLane:
     "tests/artifacts/test_selected_predecessor_rules.py",
     "tests/artifacts/test_submission_intake_contracts.py",
     "tests/artifacts/test_submission_intake_custody.py",
+    "tests/artifacts/test_submission_source_cleanup.py",
     "tests/artifacts/test_submission_pre_source.py",
     "tests/artifacts/test_submission_intake_admission.py",
     "tests/authorization/post_submit/test_atomicity.py",
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index c28885ca7..a0076f698 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -30,6 +30,24 @@
 )
 
 
+async def test_stalled_accepted_source_is_protected_from_cleanup(recovery_intake):
+    """Exhausted finalizer delivery never turns accepted input into garbage."""
+    from sqlalchemy.exc import DBAPIError
+    from sqlalchemy import text
+    from app.adapters.tasks import intake_task_custody_port
+    from app.modules.artifacts.intake.cleanup import SealedSourceCleanup
+    f, operation = recovery_intake.f, recovery_intake.owner.operation_id
+    with pytest.raises(DBAPIError, match="cleanup is protected"):
+        async with f.factory.begin() as session:
+            await SealedSourceCleanup(session, intake_task_custody_port(session)).claim(
+                operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    async with f.factory() as session:
+        assert await session.scalar(text("SELECT state FROM submission_intake_operations WHERE id=:id"),
+                                    {"id": operation}) == "finalization_pending"
+        assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"),
+                                    {"id": operation}) > 0
+
+
 @pytest.fixture
 async def admission_intake(tmp_path, isolated_database_env, admin_access, request):
     from app.adapters.outbox import outbox_append, finalized_unknown_deliveries
diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py
index e1094af1f..9fd10054e 100644
--- a/backend/tests/artifacts/test_submission_intake_custody.py
+++ b/backend/tests/artifacts/test_submission_intake_custody.py
@@ -363,7 +363,7 @@ async def test_recorded_source_identity_is_immutable(intake):
 async def test_intake_model_matches_installed_schema(isolated_database_env):
     from sqlalchemy import inspect
     from app.modules.artifacts.intake.models import (
-        SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge,
+        SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge, SubmissionSourceCleanupClaim,
     )
 
     engine = create_async_engine(isolated_database_env)
@@ -372,7 +372,7 @@ async def test_intake_model_matches_installed_schema(isolated_database_env):
             def compare(sync):
                 inspector = inspect(sync)
                 for owner in (SubmissionIntakeOperation, SubmissionSourceCapacityProfile, SubmissionSourceCharge,
-                              SubmissionSourceUploadReceipt):
+                              SubmissionSourceUploadReceipt, SubmissionSourceCleanupClaim):
                     table = owner.__table__
                     assert {
                         (c["name"], str(c["type"].compile(dialect=sync.dialect)), c["nullable"])
diff --git a/backend/tests/artifacts/test_submission_source_cleanup.py b/backend/tests/artifacts/test_submission_source_cleanup.py
new file mode 100644
index 000000000..cde13536f
--- /dev/null
+++ b/backend/tests/artifacts/test_submission_source_cleanup.py
@@ -0,0 +1,168 @@
+"""Real database cleanup fencing; historical fixture timestamps are setup only."""
+from dataclasses import replace
+import asyncio
+from datetime import timedelta
+import os
+from uuid import UUID
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.engine import make_url
+from sqlalchemy.exc import DBAPIError
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from app.adapters.tasks import intake_task_custody_port
+from app.core.identifiers import new_record_id
+from app.modules.artifacts.intake.cleanup import SealedSourceCleanup
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+from tests.artifacts.test_submission_intake_custody import (
+    SHA, reserve, record_eof, repository,
+    intake as intake, capacity_limits as capacity_limits,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+def owner(session):
+    """Use the same TASK custody adapter as foreground and finalization."""
+    return SealedSourceCleanup(session, intake_task_custody_port(session))
+
+
+async def terminal_source(intake):
+    """Create a real sealed rejected operation through existing owners."""
+    from datetime import UTC, datetime
+    async with intake.factory.begin() as session:
+        row = await reserve(intake, session)
+        operation, lease = UUID(row.id), UUID(row.lease_id)
+    async with intake.factory.begin() as session:
+        await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100)
+        deadline = datetime.now(UTC) + timedelta(minutes=2)
+        await repository(session).seal(operation, lease, 1, provider_generation="exact-generation",
+                                      pre_deadline_at=deadline, lease_expires_at=deadline)
+    async with intake.factory.begin() as session:
+        await repository(session).terminalize(operation, lease, 1, state="rejected", failure_code="pre_failed")
+    return operation
+
+
+async def age_fixture(intake, operation):
+    """Seed historical timestamps in an isolated test DB; all cleanup guards stay enabled."""
+    database = intake.engine.url.database
+    assert database.startswith("workstream_test_")
+    url = make_url(os.environ["WORKSTREAM_TEST_ADMIN_DATABASE_URL"]).set(database=database)
+    engine = create_async_engine(url)
+    try:
+        async with engine.begin() as connection:
+            # Only timestamp fixture setup bypasses the immutable foreground
+            # history guard, restored in this transaction before cleanup runs.
+            await connection.execute(text("ALTER TABLE submission_intake_operations DISABLE TRIGGER submission_intake_mutation"))
+            await connection.execute(text("UPDATE submission_intake_operations SET " + ",".join(
+                f"{column}={column}-interval '3 hours'" for column in (
+                    "created_at", "upload_deadline_at", "lease_expires_at", "pre_deadline_at",
+                    "eof_at", "sealed_at", "terminal_at",
+                )
+            ) + " WHERE id=:id"), {"id": operation})
+            await connection.execute(text("ALTER TABLE submission_intake_operations ENABLE TRIGGER submission_intake_mutation"))
+    finally:
+        await engine.dispose()
+
+
+async def test_cleanup_requires_age_then_confirms_charge_once(intake):
+    operation = await terminal_source(intake)
+    claim_id = new_record_id()
+    with pytest.raises(DBAPIError, match="cleanup is protected"):
+        async with intake.factory.begin() as session:
+            await owner(session).claim(operation, claim_id, lease_duration=timedelta(minutes=5))
+    await age_fixture(intake, operation)
+    async with intake.factory.begin() as session:
+        claim = await owner(session).claim(operation, claim_id, lease_duration=timedelta(minutes=5))
+    with pytest.raises(IntakeCustodyConflict, match="cleanup_busy"):
+        async with intake.factory.begin() as session:
+            await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    for field in ("object_absent", "writes_settled", "parts_absent"):
+        facts = dict(object_absent=True, writes_settled=True, parts_absent=True)
+        facts[field] = False
+        with pytest.raises(IntakeCustodyConflict, match="cleanup_unresolved"):
+            async with intake.factory.begin() as session:
+                await owner(session).confirm(claim, **facts)
+    async with intake.factory() as session:
+        assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": operation}) == 100
+    with pytest.raises(IntakeCustodyConflict, match="cleanup_stale"):
+        async with intake.factory.begin() as session:
+            await owner(session).confirm(replace(claim, generation=claim.generation+1),
+                                         object_absent=True, writes_settled=True, parts_absent=True)
+    for _ in range(2):
+        async with intake.factory.begin() as session:
+            await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True)
+    async with intake.factory() as session:
+        row = (await session.execute(text("SELECT state,accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": operation})).one()
+        assert tuple(row) == ("released", 0)
+    with pytest.raises(DBAPIError, match="tombstone is retained"):
+        async with intake.factory.begin() as session:
+            await session.execute(text("DELETE FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation})
+
+
+async def test_cleanup_sql_rejects_release_without_confirmation_and_target_substitution(intake):
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    async with intake.factory.begin() as session:
+        claim = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    for sql, error in (
+        ("UPDATE submission_source_charges SET state='released',accounted_bytes=0 WHERE operation_id=:id", "confirmed cleanup"),
+        ("UPDATE submission_source_cleanup_claims SET source=jsonb_set(source,'{provider_generation}','\"foreign\"') WHERE operation_id=:id", "target differs"),
+        ("UPDATE submission_source_cleanup_claims SET confirmed_at=clock_timestamp() WHERE operation_id=:id", "release must be atomic"),
+    ):
+        with pytest.raises(DBAPIError, match=error):
+            async with intake.factory.begin() as session:
+                await session.execute(text(sql), {"id": operation})
+    async with intake.factory.begin() as session:
+        replay = await owner(session).claim(operation, claim.claim_id, lease_duration=timedelta(minutes=5))
+        assert replay == claim
+
+
+async def test_cleanup_rejects_live_input_and_serializes_competing_claims(intake):
+    async with intake.factory.begin() as session:
+        row = await reserve(intake, session)
+        operation = UUID(row.id)
+    with pytest.raises(DBAPIError, match="cleanup is protected"):
+        async with intake.factory.begin() as session:
+            await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    async with intake.factory.begin() as session:
+        await repository(session).terminalize(operation, UUID(row.lease_id), 1, state="failed", failure_code="upload_failed")
+    # Unsealed terminal input cannot enter the sealed cleanup/release path.
+    await age_fixture(intake, operation)
+    with pytest.raises(DBAPIError, match="cleanup is protected"):
+        async with intake.factory.begin() as session:
+            await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+
+    async def claim():
+        try:
+            async with intake.factory.begin() as session:
+                return await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+        except IntakeCustodyConflict as exc:
+            return str(exc)
+
+    results = await asyncio.gather(claim(), claim())
+    assert sum(result == "source_cleanup_busy" for result in results) == 1
+    assert sum(not isinstance(result, str) for result in results) == 1
+
+
+async def test_expired_cleanup_claim_cannot_confirm_after_takeover(intake):
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    async with intake.factory.begin() as session:
+        first = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(seconds=3))
+    await asyncio.sleep(3.1)
+    with pytest.raises(IntakeCustodyConflict, match="cleanup_stale"):
+        async with intake.factory.begin() as session:
+            await owner(session).claim(operation, first.claim_id, lease_duration=timedelta(minutes=5))
+    async with intake.factory.begin() as session:
+        second = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+        assert second.generation == first.generation + 1
+        assert second.source == first.source
+    with pytest.raises(IntakeCustodyConflict, match="cleanup_stale"):
+        async with intake.factory.begin() as session:
+            await owner(session).confirm(first, object_absent=True, writes_settled=True, parts_absent=True)
+    async with intake.factory.begin() as session:
+        await owner(session).confirm(second, object_absent=True, writes_settled=True, parts_absent=True)
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 9b00120fd..5a08afe18 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "98e8a90037368efa975e8807d2191da466756e46421f89f114424c6a0d3694cf"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "8dd976d22e0ea2e8c65a0ee47f0bc418a6315ddb67786876b16afbf92eecad5e"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
@@ -31,6 +31,7 @@
 )
 RESETTABLE_TEST_TABLES = (
     "submission_source_upload_receipts",
+    "submission_source_cleanup_claims",
     "submission_source_capacity_profiles",
     "submission_source_charges",
     "submission_intake_operations",
@@ -171,6 +172,7 @@
     "submission_source_capacity_profiles",
     "submission_source_charges",
     "submission_source_upload_receipts",
+    "submission_source_cleanup_claims",
     "artifact_provider_activations",
     "artifact_provider_probe_results",
     "artifact_task_import_sources",
diff --git a/backend/tests/test_checker_evidence_migrations.py b/backend/tests/test_checker_evidence_migrations.py
index faa44da1c..aec0e4e5c 100644
--- a/backend/tests/test_checker_evidence_migrations.py
+++ b/backend/tests/test_checker_evidence_migrations.py
@@ -81,7 +81,7 @@ async def _assert_exact_0062_schema(database_url: str, monkeypatch) -> None:
         if table not in {
             "checker_trial_evidence", "submission_intake_operations",
             "submission_source_capacity_profiles", "submission_source_charges",
-            "submission_source_upload_receipts",
+            "submission_source_upload_receipts", "submission_source_cleanup_claims",
         }
     )
     with monkeypatch.context() as patch:

From 59783a1a5e8447f69dca5517ffdf1f852cba1114 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 01:09:02 +0100
Subject: [PATCH 138/513] Bound cleanup recovery leases and prevent retention
 after claims

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 22 +++++
 .../versions/0078_submission_cleanup.py       | 27 +++++-
 .../app/modules/artifacts/intake/cleanup.py   |  6 +-
 .../app/modules/artifacts/intake/models.py    |  2 +-
 .../test_submission_source_cleanup.py         | 86 ++++++++++++++-----
 backend/tests/conftest.py                     |  2 +-
 backend/tests/test_ci_lane_catalogue.py       |  4 +-
 7 files changed, 123 insertions(+), 26 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 84e701fe2..2cbce836e 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3423,3 +3423,25 @@ Ruff, initial structure, migration application and whitespace checks passed.
 The first custody run began before two additional cleanup tests were added;
 its collection/output and the final focused rerun will be reported distinctly.
 Do not use that initial launch as frozen final test evidence.
+
+Review repair batch: CLEANUP-LEASE-01 bounds cleanup leases to the existing
+300-second durable delivery upper bound in Python and SQL; callers still supply
+an explicit duration. QA's retained-reference gap led to a reachable generic
+replica conflict test (same namespace/key, no source-operation pointer). Add a
+retention-side guard for replicas/admissions, locking TASK/operation and refusing
+new references once a cleanup claim exists; checking only at claim/confirm would
+leave a deletion race. All matching operation identities are checked, including
+ambiguous pointer/key combinations. These add one function and two triggers.
+The repaired migration fingerprint observed on fresh PostgreSQL is
+`9f3d2ac2ea97b956a262561e272aeb41ff7fdf03c9e0e265ad76da63ca3946eb`.
+
+CI-CLEANUP-01 updates only shared semantic-family count274→275 and its exact
+verified digest for the new cleanup module; independent fingerprint enforcement
+remains. Initial static run:106 passed/1 failed, not a green run.
+Initial database run:56 passed/2 failed in669.51seconds, cleanup complete. Both
+new tests failed before cleanup claims because the isolated runner deliberately
+removes server-admin credentials. Historical fixture setup now uses the restricted
+role that owns only its asserted `workstream_test_` database, and drains deferred
+checks before restoring the immutable-history trigger. No runner permissions or
+credential exposure changes. The focused final run includes all new cleanup
+cases, model parity, stalled accepted protection and existing T5 finalization.
diff --git a/backend/alembic/versions/0078_submission_cleanup.py b/backend/alembic/versions/0078_submission_cleanup.py
index 8ff5c418b..32ce10056 100644
--- a/backend/alembic/versions/0078_submission_cleanup.py
+++ b/backend/alembic/versions/0078_submission_cleanup.py
@@ -63,7 +63,8 @@ def downgrade():
  confirmed_at timestamptz,
  CONSTRAINT pk_submission_source_cleanup_claims PRIMARY KEY(operation_id),
  CONSTRAINT fk_source_cleanup_operation FOREIGN KEY(operation_id) REFERENCES public.submission_intake_operations(id),
- CONSTRAINT ck_submission_source_cleanup_claims_claim_bounds CHECK (generation>0 AND lease_expires_at>claimed_at),
+ CONSTRAINT ck_submission_source_cleanup_claims_claim_bounds CHECK
+   (generation>0 AND lease_expires_at>claimed_at AND lease_expires_at<=claimed_at+interval '300 seconds'),
  CONSTRAINT ck_submission_source_cleanup_claims_source_shape CHECK (jsonb_typeof(source)='object'),
  CONSTRAINT ck_submission_source_cleanup_claims_claim_uuid7 CHECK
    ((get_byte(uuid_send(claim_id),6)>>4)=7 AND (get_byte(uuid_send(claim_id),8)&192)=128)
@@ -145,6 +146,30 @@ def downgrade():
 END $$;
 CREATE CONSTRAINT TRIGGER source_cleanup_release_atomic AFTER INSERT OR UPDATE ON public.submission_source_cleanup_claims
 DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.check_source_cleanup_release();
+CREATE FUNCTION public.guard_cleanup_retention_barrier()
+RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE candidate record; namespace_key text; fingerprint text; object_key text;
+BEGIN
+ IF TG_TABLE_NAME='artifact_replicas' THEN
+   namespace_key:=NEW.storage_namespace_id;
+   fingerprint:=NEW.namespace_fingerprint;
+   object_key:=NEW.provider_object_ref;
+ END IF;
+ FOR candidate IN SELECT id,task_id FROM public.submission_intake_operations
+     WHERE id=NEW.source_operation_id OR (namespace_id=namespace_key
+       AND namespace_fingerprint=fingerprint AND object_ref=object_key)
+     ORDER BY task_id,id LOOP
+   PERFORM 1 FROM public.workstream_tasks WHERE id=candidate.task_id FOR UPDATE;
+   PERFORM 1 FROM public.submission_intake_operations WHERE id=candidate.id FOR UPDATE;
+   IF EXISTS(SELECT 1 FROM public.submission_source_cleanup_claims WHERE operation_id=candidate.id) THEN
+     RAISE EXCEPTION 'cleanup claimed source cannot become retained' USING ERRCODE='23514'; END IF;
+ END LOOP;
+ RETURN NEW;
+END $$;
+CREATE TRIGGER source_cleanup_replica_retention BEFORE INSERT OR UPDATE ON public.artifact_replicas
+FOR EACH ROW EXECUTE FUNCTION public.guard_cleanup_retention_barrier();
+CREATE TRIGGER source_cleanup_admission_retention BEFORE INSERT OR UPDATE ON public.submission_bundle_admissions
+FOR EACH ROW EXECUTE FUNCTION public.guard_cleanup_retention_barrier();
 """
 
 _RELEASE = """
diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py
index 15f0870a0..7a35bed09 100644
--- a/backend/app/modules/artifacts/intake/cleanup.py
+++ b/backend/app/modules/artifacts/intake/cleanup.py
@@ -15,6 +15,9 @@
 from app.modules.artifacts.intake.models import SubmissionSourceCleanupClaim
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
 
+# Match the existing bounded durable finalization delivery lease, not a default.
+MAXIMUM_CLEANUP_LEASE = timedelta(seconds=300)
+
 
 @dataclass(frozen=True, slots=True)
 class SealedSourceCleanupClaim:
@@ -58,7 +61,8 @@ async def _locked(self, operation_id):
     async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: timedelta) -> SealedSourceCleanupClaim:
         """Claim only a stable eligible source; never resume foreground work."""
         if (type(claim_id) is not UUID or claim_id.version != 7
-                or type(lease_duration) is not timedelta or lease_duration <= timedelta(0)):
+                or type(lease_duration) is not timedelta
+                or not timedelta(0) < lease_duration <= MAXIMUM_CLEANUP_LEASE):
             raise ValueError("source cleanup lease is invalid")
         operation, row = await self._locked(operation_id)
         now = await self._session.scalar(select(func.clock_timestamp()))
diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py
index 6aa48d1fe..29a3dc605 100644
--- a/backend/app/modules/artifacts/intake/models.py
+++ b/backend/app/modules/artifacts/intake/models.py
@@ -168,7 +168,7 @@ class SubmissionSourceCleanupClaim(Base):
     __table_args__ = (
         ForeignKeyConstraint(["operation_id"], ["submission_intake_operations.id"],
                              name="fk_source_cleanup_operation"),
-        CheckConstraint("generation>0 and lease_expires_at>claimed_at", name="claim_bounds"),
+        CheckConstraint("generation>0 and lease_expires_at>claimed_at and lease_expires_at<=claimed_at+interval '300 seconds'", name="claim_bounds"),
         CheckConstraint("jsonb_typeof(source)='object'", name="source_shape"),
         CheckConstraint("(get_byte(uuid_send(claim_id),6)>>4)=7 and (get_byte(uuid_send(claim_id),8)&192)=128",
                         name="claim_uuid7"),
diff --git a/backend/tests/artifacts/test_submission_source_cleanup.py b/backend/tests/artifacts/test_submission_source_cleanup.py
index cde13536f..09a06860a 100644
--- a/backend/tests/artifacts/test_submission_source_cleanup.py
+++ b/backend/tests/artifacts/test_submission_source_cleanup.py
@@ -2,14 +2,11 @@
 from dataclasses import replace
 import asyncio
 from datetime import timedelta
-import os
 from uuid import UUID
 
 import pytest
 from sqlalchemy import text
-from sqlalchemy.engine import make_url
 from sqlalchemy.exc import DBAPIError
-from sqlalchemy.ext.asyncio import create_async_engine
 
 from app.adapters.tasks import intake_task_custody_port
 from app.core.identifiers import new_record_id
@@ -48,23 +45,20 @@ async def age_fixture(intake, operation):
     """Seed historical timestamps in an isolated test DB; all cleanup guards stay enabled."""
     database = intake.engine.url.database
     assert database.startswith("workstream_test_")
-    url = make_url(os.environ["WORKSTREAM_TEST_ADMIN_DATABASE_URL"]).set(database=database)
-    engine = create_async_engine(url)
-    try:
-        async with engine.begin() as connection:
-            # Only timestamp fixture setup bypasses the immutable foreground
-            # history guard, restored in this transaction before cleanup runs.
-            await connection.execute(text("ALTER TABLE submission_intake_operations DISABLE TRIGGER submission_intake_mutation"))
-            await connection.execute(text("UPDATE submission_intake_operations SET " + ",".join(
-                f"{column}={column}-interval '3 hours'" for column in (
-                    "created_at", "upload_deadline_at", "lease_expires_at", "pre_deadline_at",
-                    "eof_at", "sealed_at", "terminal_at",
-                )
-            ) + " WHERE id=:id"), {"id": operation})
-            await connection.execute(text("ALTER TABLE submission_intake_operations ENABLE TRIGGER submission_intake_mutation"))
-    finally:
-        await engine.dispose()
-
+    # The isolated runner's restricted role owns only this test database. It can
+    # prepare history without exposing the runner's server administrator secret.
+    async with intake.engine.begin() as connection:
+        # Only timestamp fixture setup bypasses the immutable foreground
+        # history guard, restored in this transaction before cleanup runs.
+        await connection.execute(text("ALTER TABLE submission_intake_operations DISABLE TRIGGER submission_intake_mutation"))
+        await connection.execute(text("UPDATE submission_intake_operations SET " + ",".join(
+            f"{column}={column}-interval '3 hours'" for column in (
+                "created_at", "upload_deadline_at", "lease_expires_at", "pre_deadline_at",
+                "eof_at", "sealed_at", "terminal_at",
+            )
+        ) + " WHERE id=:id"), {"id": operation})
+        await connection.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
+        await connection.execute(text("ALTER TABLE submission_intake_operations ENABLE TRIGGER submission_intake_mutation"))
 
 async def test_cleanup_requires_age_then_confirms_charge_once(intake):
     operation = await terminal_source(intake)
@@ -166,3 +160,55 @@ async def test_expired_cleanup_claim_cannot_confirm_after_takeover(intake):
             await owner(session).confirm(first, object_absent=True, writes_settled=True, parts_absent=True)
     async with intake.factory.begin() as session:
         await owner(session).confirm(second, object_absent=True, writes_settled=True, parts_absent=True)
+
+
+async def test_cleanup_lease_bound_is_enforced_by_owner_and_database(intake):
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    with pytest.raises(ValueError, match="lease is invalid"):
+        async with intake.factory.begin() as session:
+            await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(days=3650))
+    from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+    async with intake.factory() as session:
+        row = await session.get(SubmissionIntakeOperation, str(operation))
+        source = repository(session)._sealed_source(row).model_dump_json()
+    with pytest.raises(DBAPIError, match="claim_bounds"):
+        async with intake.factory.begin() as session:
+            await session.execute(text("INSERT INTO submission_source_cleanup_claims "
+                "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at) "
+                "VALUES (:id,:claim,1,CAST(:source AS jsonb),clock_timestamp(),clock_timestamp()+interval '10 years')"),
+                {"id": operation, "claim": new_record_id(), "source": source})
+
+
+async def retain_exact_key(session, operation):
+    """Create an ordinary generic replica referencing the managed key, without bypassing guards."""
+    from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+    from app.modules.artifacts.models import ArtifactContent, ArtifactReplica, ArtifactStorageNamespace
+    from app.modules.artifacts.repository import ArtifactRepository
+    row = await session.get(SubmissionIntakeOperation, str(operation))
+    namespace = await session.get(ArtifactStorageNamespace, row.namespace_id)
+    content = await ArtifactRepository(session).get_or_create_content(ArtifactContent(
+        id=str(new_record_id()), sha256=row.raw_sha256, byte_count=row.raw_byte_count,
+        media_type="application/zip", normalized_display_name="submission.zip"))
+    session.add(ArtifactReplica(id=str(new_record_id()), content_id=content.id, source_operation_id=None,
+        storage_namespace_id=row.namespace_id, namespace_fingerprint=row.namespace_fingerprint,
+        adapter=namespace.adapter, provider_profile=row.provider_profile, provider_object_ref=row.object_ref,
+        verification_state="pending", availability_state="unknown", integrity_state="unknown"))
+    await session.flush()
+
+
+async def test_retained_key_blocks_claim_and_claim_blocks_new_retention(intake):
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    async with intake.factory.begin() as session:
+        await retain_exact_key(session, operation)
+    with pytest.raises(DBAPIError, match="cleanup is protected"):
+        async with intake.factory.begin() as session:
+            await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    other = await terminal_source(intake)
+    await age_fixture(intake, other)
+    async with intake.factory.begin() as session:
+        await owner(session).claim(other, new_record_id(), lease_duration=timedelta(minutes=5))
+    with pytest.raises(DBAPIError, match="claimed source cannot become retained"):
+        async with intake.factory.begin() as session:
+            await retain_exact_key(session, other)
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 5a08afe18..b7ca759dc 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "8dd976d22e0ea2e8c65a0ee47f0bc418a6315ddb67786876b16afbf92eecad5e"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "9f3d2ac2ea97b956a262561e272aeb41ff7fdf03c9e0e265ad76da63ca3946eb"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py
index 45582f7da..68b980fb5 100644
--- a/backend/tests/test_ci_lane_catalogue.py
+++ b/backend/tests/test_ci_lane_catalogue.py
@@ -318,8 +318,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None:
     """A catalogue-internal move across semantic families must fail this contract."""
     expected = {
         "shared": (
-            274,
-            "70b7428794e138bb1f58e9506a5e68ff87c9822bd3c7dc0132d52a1beecf559d",
+            275,
+            "d59b427b71f98d981bd188dbc4d1690498481d5a93c9cf74c382f748600dc609",
         ),
         "project": (
             256,

From 5cbb19c9063734c9ba69b64d2ca074d46db6fd48 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 01:16:38 +0100
Subject: [PATCH 139/513] Anchor cleanup lease duration and test retention lock
 races

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 17 ++++++
 .../versions/0078_submission_cleanup.py       |  6 +-
 .../test_submission_source_cleanup.py         | 58 ++++++++++++++++++-
 backend/tests/conftest.py                     |  2 +-
 4 files changed, 80 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 2cbce836e..ab9c6ac7b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3445,3 +3445,20 @@ role that owns only its asserted `workstream_test_` database, and drains deferre
 checks before restoring the immutable-history trigger. No runner permissions or
 credential exposure changes. The focused final run includes all new cleanup
 cases, model parity, stalled accepted protection and existing T5 finalization.
+
+Focused repair run:9 passed/1 failed in225.63seconds, database cleanup complete
+(`/tmp/source-cleanup-custody2.log/json`). Stalled acceptance, both existing T5
+cases, serial retention barriers and the other cleanup paths passed. The failure
+occurred on a valid300-second claim: owner clock sample00:08:32.832117 preceded
+a trigger sample00:08:32.354489, so resetting only claimed_at made the duration
+appear overlong. Rebase both timestamps from one trigger sample while preserving
+the requested interval; the SQL300-second constraint still rejects long spans.
+A raw shifted-timestamp regression proves this correction. The new actual schema
+fingerprint is `ea88b39d4ba01e345a6ea036184cda3194d1aa95f303555bad005243acde50ca`.
+
+Add two-session races for both claim-first and retention-first, waiting for actual
+`pg_blocking_pids` evidence before committing the winner and asserting rejection
+of the loser. Lease-expiry tests likewise observe database time before takeover.
+The separate admission-pointer trigger remains code-inspected rather than directly
+race-tested; source acceptance/finalization protection is covered independently.
+No full admission-retention or provider-cleanup qualification claim follows.
diff --git a/backend/alembic/versions/0078_submission_cleanup.py b/backend/alembic/versions/0078_submission_cleanup.py
index 32ce10056..63728c7c5 100644
--- a/backend/alembic/versions/0078_submission_cleanup.py
+++ b/backend/alembic/versions/0078_submission_cleanup.py
@@ -88,7 +88,7 @@ def downgrade():
 END $$;
 CREATE FUNCTION public.guard_submission_source_cleanup()
 RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
-DECLARE o public.submission_intake_operations%ROWTYPE; task_key uuid; expected jsonb;
+DECLARE o public.submission_intake_operations%ROWTYPE; task_key uuid; expected jsonb; lease_span interval;
 BEGIN
  IF TG_OP IN ('DELETE','TRUNCATE') THEN
    RAISE EXCEPTION 'source cleanup tombstone is retained' USING ERRCODE='23514'; END IF;
@@ -105,7 +105,9 @@ def downgrade():
  IF TG_OP='INSERT' THEN
    IF NEW.generation<>1 OR NEW.confirmed_at IS NOT NULL THEN
      RAISE EXCEPTION 'source cleanup initial claim differs' USING ERRCODE='23514'; END IF;
+   lease_span:=NEW.lease_expires_at-NEW.claimed_at;
    NEW.claimed_at:=clock_timestamp();
+   NEW.lease_expires_at:=NEW.claimed_at+lease_span;
  ELSE
    IF OLD.confirmed_at IS NOT NULL THEN
      IF NEW IS DISTINCT FROM OLD THEN
@@ -122,7 +124,9 @@ def downgrade():
    ELSE
      IF OLD.lease_expires_at>clock_timestamp() OR NEW.generation<>OLD.generation+1 OR NEW.confirmed_at IS NOT NULL THEN
        RAISE EXCEPTION 'source cleanup claim is busy' USING ERRCODE='23514'; END IF;
+     lease_span:=NEW.lease_expires_at-NEW.claimed_at;
      NEW.claimed_at:=clock_timestamp();
+     NEW.lease_expires_at:=NEW.claimed_at+lease_span;
    END IF;
  END IF;
  IF NEW.lease_expires_at<=clock_timestamp() THEN
diff --git a/backend/tests/artifacts/test_submission_source_cleanup.py b/backend/tests/artifacts/test_submission_source_cleanup.py
index 09a06860a..49ad7b6f9 100644
--- a/backend/tests/artifacts/test_submission_source_cleanup.py
+++ b/backend/tests/artifacts/test_submission_source_cleanup.py
@@ -147,7 +147,10 @@ async def test_expired_cleanup_claim_cannot_confirm_after_takeover(intake):
     await age_fixture(intake, operation)
     async with intake.factory.begin() as session:
         first = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(seconds=3))
-    await asyncio.sleep(3.1)
+    async with intake.factory() as session:
+        async with asyncio.timeout(15):
+            while not await session.scalar(text("SELECT clock_timestamp()>:expiry"), {"expiry": first.lease_expires_at}):
+                await asyncio.sleep(0.05)
     with pytest.raises(IntakeCustodyConflict, match="cleanup_stale"):
         async with intake.factory.begin() as session:
             await owner(session).claim(operation, first.claim_id, lease_duration=timedelta(minutes=5))
@@ -178,6 +181,17 @@ async def test_cleanup_lease_bound_is_enforced_by_owner_and_database(intake):
                 "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at) "
                 "VALUES (:id,:claim,1,CAST(:source AS jsonb),clock_timestamp(),clock_timestamp()+interval '10 years')"),
                 {"id": operation, "claim": new_record_id(), "source": source})
+    # Caller clock samples are not authoritative. Preserve the finite duration,
+    # but rebase BOTH timestamps onto the trigger's single authoritative sample.
+    async with intake.factory.begin() as session:
+        await session.execute(text("INSERT INTO submission_source_cleanup_claims "
+            "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at) "
+            "VALUES (:id,:claim,1,CAST(:source AS jsonb),statement_timestamp()+interval '1 hour',"
+            "statement_timestamp()+interval '1 hour 1 minute')"),
+            {"id": operation, "claim": new_record_id(), "source": source})
+        assert await session.scalar(text("SELECT claimed_at<=clock_timestamp() "
+            "AND lease_expires_at=claimed_at+interval '1 minute' "
+            "FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation})
 
 
 async def retain_exact_key(session, operation):
@@ -212,3 +226,45 @@ async def test_retained_key_blocks_claim_and_claim_blocks_new_retention(intake):
     with pytest.raises(DBAPIError, match="claimed source cannot become retained"):
         async with intake.factory.begin() as session:
             await retain_exact_key(session, other)
+
+
+@pytest.mark.parametrize("first", ["claim", "retain"])
+async def test_claim_and_retention_serialize_at_database_lock(intake, first):
+    """Observe the competing SQL blocked on custody, then commit the winner."""
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    pid_ready = asyncio.get_running_loop().create_future()
+
+    async def act(session, action):
+        if action == "claim":
+            await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+        else:
+            await retain_exact_key(session, operation)
+
+    async def competing():
+        try:
+            async with intake.factory.begin() as session:
+                pid_ready.set_result(await session.scalar(text("SELECT pg_backend_pid()")))
+                await act(session, "retain" if first == "claim" else "claim")
+        except DBAPIError as error:
+            return str(error)
+        return "unexpected success"
+
+    competitor = None
+    try:
+        async with intake.factory.begin() as session:
+            await act(session, first)
+            competitor = asyncio.create_task(competing())
+            async with asyncio.timeout(15):
+                pid = await pid_ready
+                while not await session.scalar(text("SELECT cardinality(pg_blocking_pids(:pid))"), {"pid": pid}):
+                    assert not competitor.done(), "competing operation escaped custody lock"
+                    await asyncio.sleep(0.01)
+            assert not competitor.done()
+        result = await asyncio.wait_for(competitor, timeout=15)
+        expected = "claimed source cannot become retained" if first == "claim" else "cleanup is protected"
+        assert expected in result
+    finally:
+        if competitor is not None and not competitor.done():
+            competitor.cancel()
+            await asyncio.gather(competitor, return_exceptions=True)
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index b7ca759dc..815ab1f16 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "9f3d2ac2ea97b956a262561e272aeb41ff7fdf03c9e0e265ad76da63ca3946eb"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "ea88b39d4ba01e345a6ea036184cda3194d1aa95f303555bad005243acde50ca"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",

From e66dd64575d9e5e984bb39b4515c93134f86033c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 01:19:49 +0100
Subject: [PATCH 140/513] Record verified cleanup custody and remaining
 provider integration

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md          | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index ab9c6ac7b..802262390 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -30,7 +30,10 @@ authorized stall projection are implemented. Full Celery/provider execution,
 independent worker capacity and public progress/operator endpoints remain unfinished.
 Internal audited finalization recovery now reuses the existing Operator gate-repair
 action, preserves the original delivery and runs the same T5 under a live child lease.
-Next: close those durable-worker gaps, then complete cleanup and public API/CLI/MCP
+Private sealed-source cleanup claims, retention barriers and atomic charge-release
+custody are now implemented and database-tested. Provider deletion, cleanup service
+authority, scheduling and uncertain/unsealed reconciliation remain uncomposed.
+Remaining work includes durable-worker deployment, complete cleanup, public API/CLI/MCP
 cutover, real revision/review/ContributionRecord journeys, policy cardinality and
 the A01–A35/C01–C07 completion audit. No public end-to-end readiness is claimed.
 
@@ -3462,3 +3465,16 @@ of the loser. Lease-expiry tests likewise observe database time before takeover.
 The separate admission-pointer trigger remains code-inspected rather than directly
 race-tested; source acceptance/finalization protection is covered independently.
 No full admission-retention or provider-cleanup qualification claim follows.
+
+Final custody repair proof: all nine focused PostgreSQL tests passed in120.01
+seconds (`/tmp/source-cleanup-custody3.log/json`), with database cleanup complete
+and schema0078. This covers the shifted-timestamp regression, bounded leases,
+exact target, atomic release/replay, live/unsealed refusal, retained key barrier,
+both blocked two-session race orders and model parity. Launch metadata records
+59783a1a5 with final worktree content; it is not exact-head launch evidence.
+Architecture/security and QA/test-delta passed clean5cbb19c90; CI integrity passed.
+The final passing result closes DOC-CLEANUP-CLOCK-01's premature wording concern.
+Final structure and Commitrail checks passed. Earlier partial/red runs remain
+separately recorded and are not relabeled green. Provider deletion, current cleanup
+service authority, scheduling, unsealed reconciliation and direct admission-pointer
+race proof remain required; the full goal is not complete.

From 482062fd5ed7f301aa58b0ecc820f65f6ae42b4a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 01:35:46 +0100
Subject: [PATCH 141/513] feat(auth): bind source cleanup authority to exact
 claim facts

---
 .ci/auth-boundaries/TEST_STRUCTURE_DEBT.json  |  4 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 59 +++++++++++++++
 .../versions/0079_cleanup_authority.py        | 38 ++++++++++
 .../modules/actors/api/service_identities.py  |  1 +
 .../artifacts/api/submission_cleanup.py       | 15 ++++
 .../app/modules/artifacts/authorization.py    | 29 +++++---
 .../authorization/action_definitions.py       |  5 ++
 .../modules/authorization/admin_schemas.py    |  2 +-
 .../app/modules/authorization/catalogue.py    | 14 +++-
 .../authorization/domain/action_groups.py     |  4 +-
 .../app/modules/authorization/domain/audit.py |  2 +
 .../authorization/domain/audit_targets.py     |  3 +-
 .../authorization/domain/prepared_service.py  | 49 +++++++++++++
 .../domain/submission_cleanup.py              | 26 +++++++
 backend/app/modules/authorization/kernel.py   | 34 +--------
 backend/app/modules/authorization/prepared.py | 24 ++-----
 backend/app/modules/authorization/runtime.py  |  5 +-
 .../authorization/submission_consumption.py   |  2 +
 .../tests/authorization/catalogue_fixtures.py |  5 +-
 backend/tests/authorization/test_catalogue.py | 11 +--
 .../test_submission_finalization_authority.py | 72 +++++++++++++++++++
 backend/tests/conftest.py                     |  2 +-
 22 files changed, 331 insertions(+), 75 deletions(-)
 create mode 100644 backend/alembic/versions/0079_cleanup_authority.py
 create mode 100644 backend/app/modules/artifacts/api/submission_cleanup.py
 create mode 100644 backend/app/modules/authorization/domain/submission_cleanup.py

diff --git a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
index 5ddb6ce00..117d503e8 100644
--- a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
+++ b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
@@ -15,14 +15,14 @@
     {
       "capability": "oversized_authorization_structure",
       "content_sha256": "bae6d1bf2568947ee4125b3389d861fb7c077a346da1efcef3167b68ce7cafd5",
-      "end_line": 744,
+      "end_line": 712,
       "hard_limit": 100,
       "kind": "production_function",
       "observed_lines": 105,
       "path": "backend/app/modules/authorization/kernel.py",
       "qualified_symbol": "AuthorizationService._require_prelocked",
       "removal_chunk": "WS-AUTH-003-CLOSE",
-      "start_line": 640
+      "start_line": 608
     },
     {
       "capability": "oversized_authorization_structure",
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 802262390..5ac836b6c 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3478,3 +3478,62 @@ Final structure and Commitrail checks passed. Earlier partial/red runs remain
 separately recorded and are not relabeled green. Provider deletion, current cleanup
 service authority, scheduling, unsealed reconciliation and direct admission-pointer
 race proof remain required; the full goal is not complete.
+
+## Cleanup service authority integration scope
+
+The remaining concrete gap is that private cleanup custody cannot yet authorize
+provider deletion. Extend the existing prepared ART service authorization with a
+dedicated fixed cleanup identity/action/permission and exact operation, project,
+task, source digest, claim ID/generation and claim/confirm phase facts. Then bind
+claim and confirmation custody to those audited decisions before composing any
+provider deletion. Allowed files are ACTORS service identity vocabulary, AUTH
+catalogue/context/prepared/audit owners, ART API/authorization/cleanup owners,
+required migrations and their focused tests/catalogues, plus this record.
+Provider capability/adapters and composition may follow under this same scope
+only with committed-claim validation and exact-generation retention protection.
+No general delete-by-key route, human cleanup grant, retained-source deletion,
+quota release from an acknowledgement, or AWS qualification claim is permitted.
+
+Risk is L0 (authorization and deletion). Acceptance requires wrong/missing/revoked
+service denial, exact fact/phase/generation binding, one-use transaction-bound
+handles, audit target/digest proof, database enforcement of matching decisions,
+and uncertainty retaining the charge. Run focused AUTH and cleanup PostgreSQL
+proof, catalogue/boundary/lint/docs checks; review the frozen candidate through
+architecture/security, QA/test-delta and affected docs/CI tracks. Human review
+focus is authority-to-durable-claim continuity and retained-object exclusion.
+This scope remains incomplete until the authority and provider composition are
+proved; adding an action alone does not enable cleanup.
+
+### Cleanup authority implementation checkpoint (not composed)
+
+The dedicated cleanup service now has one exact action/permission, a strict
+phase-bound resource context and an ART prepared-authorization adapter. Existing
+binding and scheduler principals receive no cleanup membership. Audit targets
+remain the submission operation/project and bind every cleanup fact by digest.
+Migration 0079 extends only the actor service-identity constraint and the two
+closed audit permission/action constraints; no retained row is rewritten.
+The measured migrated schema fingerprint is
+`c7cb5c74bf2ff569927f804af635572743c76b3cc2dd9ae376d348c72d3ae423`.
+The kernel/prepared resource maps moved into the existing fixed-service guard
+owner, sharing the common entries without changing the prepared subset. This
+keeps both files within structural limits; the debt ledger only relocates the
+unchanged 105-line kernel function, with its content hash preserved.
+
+Evidence: `/tmp/source-cleanup-authority.log` had 7 passing and 3 failing tests
+because the initial implementation lacked the database service-identity change.
+`/tmp/source-cleanup-authority-schema2.log` measured the expected new fingerprint;
+its runner metadata confirms database cleanup and Alembic 0079. An earlier schema
+attempt launched before the migration file existed and ended with a head
+mismatch; it is not positive evidence. After the migration and exact catalogue
+count repairs, `/tmp/source-cleanup-authority2.log` passed all 17 selected tests
+in 17.03 seconds, with database cleanup confirmed. The tests cover both phases,
+all seven changed fact selectors, single consumption, exact audit digest and
+missing/binding-only/revoked service denial, alongside existing finalization
+proof. That run precedes the resource-map refactor; the refactor replay is
+recorded separately when finished. Ruff, catalogue, Commitrail, stale AUTH docs
+and Markdown link checks passed at their recorded worktree states.
+
+This checkpoint does not yet require these decisions in cleanup claims or
+confirmations, expose provider deletion, or provision a cleanup principal.
+Database decision binding and provider composition remain required work under
+the active full objective; no cleanup end-to-end completion is claimed.
diff --git a/backend/alembic/versions/0079_cleanup_authority.py b/backend/alembic/versions/0079_cleanup_authority.py
new file mode 100644
index 000000000..6c76b5b67
--- /dev/null
+++ b/backend/alembic/versions/0079_cleanup_authority.py
@@ -0,0 +1,38 @@
+"""Register the dedicated source-cleanup principal and exact audit action."""
+from alembic import op
+from sqlalchemy import text
+
+revision = "0079_cleanup_authority"
+down_revision = "0078_submission_cleanup"
+branch_labels = None
+depends_on = None
+
+
+def _extend(table, name, anchor, addition, occurrences):
+    definition = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_constraintdef(oid) FROM pg_catalog.pg_constraint "
+        "WHERE conrelid=CAST(:table AS regclass) AND conname=:name"
+    ), {"table": "public." + table, "name": name}).scalar_one()
+    if definition.count(anchor) != occurrences or "source_cleanup" in definition or "submission_source.cleanup" in definition:
+        raise RuntimeError("cleanup authority predecessor constraint changed: " + name)
+    op.execute(f"ALTER TABLE public.{table} DROP CONSTRAINT {name}")
+    op.execute(f"ALTER TABLE public.{table} ADD CONSTRAINT {name} " + definition.replace(anchor, anchor + addition))
+
+
+def upgrade():
+    """Preserve all retained rows and every preceding closed authority entry."""
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.actor_profiles, public.audit_events IN ACCESS EXCLUSIVE MODE")
+    _extend("actor_profiles", "ck_actor_profiles_kind_service_identity",
+            "('workstream.artifact.binding'::character varying)::text",
+            ", ('workstream.artifact.source_cleanup'::character varying)::text", 1)
+    _extend("audit_events", "ck_audit_events_authority_registries",
+            "('artifact.binding.create'::character varying)::text",
+            ", ('artifact.submission_source.cleanup'::character varying)::text", 1)
+    _extend("audit_events", "ck_audit_events_authorization_action_evidence",
+            "(((action_id)::text = 'artifact.submission.finalize'::text) AND ((permission_id)::text = 'artifact.binding.create'::text))",
+            " OR (((action_id)::text = 'artifact.submission_source.cleanup'::text) AND ((permission_id)::text = 'artifact.submission_source.cleanup'::text))", 2)
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
diff --git a/backend/app/modules/actors/api/service_identities.py b/backend/app/modules/actors/api/service_identities.py
index 0ce70ee68..9d13a5989 100644
--- a/backend/app/modules/actors/api/service_identities.py
+++ b/backend/app/modules/actors/api/service_identities.py
@@ -10,6 +10,7 @@ class ServiceIdentity(StrEnum):
     ARTIFACT_VERIFIER = "workstream.artifact.verifier"
     ARTIFACT_PUT_RESOLVER = "workstream.artifact.put_resolver"
     ARTIFACT_SCHEDULER = "workstream.artifact.scheduler"
+    ARTIFACT_SOURCE_CLEANUP = "workstream.artifact.source_cleanup"
     ARTIFACT_BINDING = "workstream.artifact.binding"
     ARTIFACT_GUIDE_READER = "workstream.artifact.guide_reader"
     ARTIFACT_MATERIALIZER = "workstream.artifact.materializer"
diff --git a/backend/app/modules/artifacts/api/submission_cleanup.py b/backend/app/modules/artifacts/api/submission_cleanup.py
new file mode 100644
index 000000000..fc57dcb33
--- /dev/null
+++ b/backend/app/modules/artifacts/api/submission_cleanup.py
@@ -0,0 +1,15 @@
+"""Exact source cleanup selectors; values alone grant no deletion authority."""
+from dataclasses import dataclass
+from typing import Literal
+from uuid import UUID
+
+
+@dataclass(frozen=True, slots=True)
+class SubmissionSourceCleanupAuthorityFacts:
+    operation_id: UUID
+    project_id: UUID
+    task_id: UUID
+    source_sha256: str
+    claim_id: UUID
+    claim_generation: int
+    phase: Literal["claim", "confirm"]
diff --git a/backend/app/modules/artifacts/authorization.py b/backend/app/modules/artifacts/authorization.py
index d25f6cdb4..d537018ed 100644
--- a/backend/app/modules/artifacts/authorization.py
+++ b/backend/app/modules/artifacts/authorization.py
@@ -29,6 +29,8 @@
     ArtifactVerificationAuthorityFacts,
 )
 from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts
+from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts
+from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationAuthorityFacts
 from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
 
@@ -546,7 +548,7 @@ def __init__(
         self._facts: (
             GuideSourceReadAuthorityFacts
             | PreSubmitSourceReadFacts
-            | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts
+            | SubmissionSourceCleanupAuthorityFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts
             | None
         ) = None
 
@@ -555,7 +557,7 @@ async def prepare(
         *,
         facts: GuideSourceReadAuthorityFacts
         | PreSubmitSourceReadFacts
-        | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
+        | SubmissionSourceCleanupAuthorityFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
         idempotency_key: UUID,
     ) -> PreparedAuthorizationHandle:
         """Prepare one process-local capability bound to every canonical fact."""
@@ -616,7 +618,7 @@ async def consume(
         prepared_authorization: PreparedAuthorizationHandle,
         facts: GuideSourceReadAuthorityFacts
         | PreSubmitSourceReadFacts
-        | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
+        | SubmissionSourceCleanupAuthorityFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
     ) -> UUID | None:
         """Consume only the exact handle and facts prepared by this adapter."""
         if (
@@ -634,7 +636,7 @@ async def consume(
                 self._input,
                 _artifact_service_resource_context(facts),
             )
-            if self._action_id in {ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE, ActionId.ARTIFACT_SUBMISSION_FINALIZE}:
+            if self._action_id in {ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE, ActionId.ARTIFACT_SUBMISSION_FINALIZE, ActionId.ARTIFACT_SOURCE_CLEANUP}:
                 return decision.decision_id
             return None
         except (AuthorizationDenied, PreparedAuthorizationHandleInvalid, ValidationError) as exc:
@@ -673,6 +675,15 @@ def close(self) -> None:
         self._facts = None
 
 
+class PreparedSubmissionSourceCleanupAuthorization(_PreparedArtifactServiceAuthorization):
+    """Only the dedicated cleanup service can authorize an exact cleanup phase."""
+
+    def __init__(self, session: AsyncSession, *, request_id: UUID, correlation_id: UUID) -> None:
+        super().__init__(session, service_identity=ServiceIdentity.ARTIFACT_SOURCE_CLEANUP,
+                         action_id=ActionId.ARTIFACT_SOURCE_CLEANUP,
+                         request_id=request_id, correlation_id=correlation_id)
+
+
 class PreparedSubmissionFinalizationAuthorization(_PreparedArtifactServiceAuthorization):
     """Accepted continuation authority belongs only to the existing binding service."""
 
@@ -803,14 +814,16 @@ def close(self) -> None:
 
 
 def _artifact_service_resource_context(
-    facts: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
-) -> GuideSourceReadResourceContext | PreSubmitCheckerInputResourceContext | SubmissionBindingResourceContext | SubmissionFinalizationResourceContext:
+    facts: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionSourceCleanupAuthorityFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
+) -> GuideSourceReadResourceContext | PreSubmitCheckerInputResourceContext | SubmissionBindingResourceContext | SubmissionFinalizationResourceContext | SubmissionSourceCleanupResourceContext:
     """Compose AUTH context for the exact fixed ART service operation."""
     if type(facts) is PreSubmitSourceReadFacts:
         return PreSubmitCheckerInputResourceContext(
             resource_id=facts.source.location.operation_id,
             scope_project_id=facts.project_id, facts=facts,
         )
+    if type(facts) is SubmissionSourceCleanupAuthorityFacts:
+        return SubmissionSourceCleanupResourceContext(resource_id=facts.operation_id, **asdict(facts))
     if type(facts) is SubmissionFinalizationAuthorityFacts:
         return SubmissionFinalizationResourceContext(resource_id=facts.operation_id, **asdict(facts))
     if isinstance(facts, SubmissionBindingAuthorityFacts):
@@ -823,8 +836,8 @@ def _artifact_service_resource_context(
 
 
 def _prepared_artifact_facts_match(
-    prepared: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
-    final: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
+    prepared: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionSourceCleanupAuthorityFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
+    final: GuideSourceReadAuthorityFacts | PreSubmitSourceReadFacts | SubmissionSourceCleanupAuthorityFacts | SubmissionFinalizationAuthorityFacts | SubmissionBindingAuthorityFacts,
 ) -> bool:
     """Require source, lease and every locked fact to remain exactly prepared."""
     return type(prepared) is type(final) and prepared == final
diff --git a/backend/app/modules/authorization/action_definitions.py b/backend/app/modules/authorization/action_definitions.py
index 47f55c789..f43b5f024 100644
--- a/backend/app/modules/authorization/action_definitions.py
+++ b/backend/app/modules/authorization/action_definitions.py
@@ -568,6 +568,11 @@
         PermissionId.SUBMISSION_CREATE,
         ActionOwner.XINT_002_05A,
     ),
+    _active(
+        ActionId.ARTIFACT_SOURCE_CLEANUP,
+        PermissionId.ARTIFACT_SOURCE_CLEANUP,
+        ActionOwner.AUTH_ART_02D_INTERNAL,
+    ),
     _active(
         ActionId.ARTIFACT_SUBMISSION_FINALIZE,
         PermissionId.ARTIFACT_BINDING_CREATE,
diff --git a/backend/app/modules/authorization/admin_schemas.py b/backend/app/modules/authorization/admin_schemas.py
index 7cd5e1fb1..6d526baf9 100644
--- a/backend/app/modules/authorization/admin_schemas.py
+++ b/backend/app/modules/authorization/admin_schemas.py
@@ -35,7 +35,7 @@ class PermissionDefinitionsResponse(BaseModel):
 
     model_config = _STRICT
     items: tuple[PermissionDefinitionResponse, ...]
-    total: Literal[94]
+    total: Literal[95]
 
 
 class AdminRoleDefinitionResponse(BaseModel):
diff --git a/backend/app/modules/authorization/catalogue.py b/backend/app/modules/authorization/catalogue.py
index 03ef05dd5..bbca8495b 100644
--- a/backend/app/modules/authorization/catalogue.py
+++ b/backend/app/modules/authorization/catalogue.py
@@ -97,6 +97,7 @@ class PermissionId(StrEnum):
     ARTIFACT_RECOVERY_ATTEMPT_READ = "artifact.recovery_attempt.read"
     ARTIFACT_AUDIT_READ = "artifact.audit.read"
     ARTIFACT_GUIDE_SOURCE_INGEST = "artifact.guide_source.ingest"
+    ARTIFACT_SOURCE_CLEANUP = "artifact.submission_source.cleanup"
     ARTIFACT_BINDING_CREATE = "artifact.binding.create"
     ARTIFACT_VERIFICATION_EXECUTE = "artifact.verification.execute"
     ARTIFACT_PENDING_WORK_SCAN = "artifact.pending_work.scan"
@@ -272,6 +273,7 @@ class ActionId(StrEnum):
     ARTIFACT_TASK_IMPORT_SOURCE_READ = "artifact.task_import_source.read"
     ARTIFACT_GUIDE_SOURCE_READ = "artifact.guide_source.read"
     ARTIFACT_SUBMISSION_BUNDLE_PREPARE = "artifact.submission_bundle.prepare"
+    ARTIFACT_SOURCE_CLEANUP = "artifact.submission_source.cleanup"
     ARTIFACT_SUBMISSION_FINALIZE = "artifact.submission.finalize"
     ARTIFACT_SUBMISSION_BINDING_CREATE = "artifact.submission.binding.create"
     ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE = "artifact.checker_output.binding.create"
@@ -553,6 +555,7 @@ def _active(
         PermissionId.ARTIFACT_AUDIT_READ,
         PermissionId.TASK_POST_SUBMIT_ROUTE,
         PermissionId.ARTIFACT_GUIDE_SOURCE_INGEST,
+        PermissionId.ARTIFACT_SOURCE_CLEANUP,
         PermissionId.ARTIFACT_BINDING_CREATE,
         PermissionId.ARTIFACT_VERIFICATION_EXECUTE,
         PermissionId.ARTIFACT_PENDING_WORK_SCAN,
@@ -568,9 +571,9 @@ def _active(
 
 def _require_catalogue_counts() -> None:
     """Keep the closed action inventory and permission boundary exact."""
-    if len(PERMISSION_IDS) != 94 or len(ACTION_IDS) != 193:
+    if len(PERMISSION_IDS) != 95 or len(ACTION_IDS) != 194:
         raise RuntimeError("authorization catalogue count mismatch")
-    if len(HISTORICAL_PERMISSION_IDS) != 49 or len(NEW_PERMISSION_IDS) != 45:
+    if len(HISTORICAL_PERMISSION_IDS) != 49 or len(NEW_PERMISSION_IDS) != 46:
         raise RuntimeError("authorization permission boundary mismatch")
 
 
@@ -702,6 +705,7 @@ def _validate_action_definitions(definitions: tuple[ActionDefinition, ...]) -> N
         ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE,
         ActionId.SUBMISSION_CREATE,
         ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
+        ActionId.ARTIFACT_SOURCE_CLEANUP,
         ActionId.ARTIFACT_SUBMISSION_FINALIZE,
         ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE,
         ActionId.ARTIFACT_VERIFICATION_EXECUTE,
@@ -814,6 +818,7 @@ def _index_actions(
     ServiceIdentity.ARTIFACT_VERIFIER: frozenset({ActionId.ARTIFACT_VERIFICATION_EXECUTE}),
     ServiceIdentity.ARTIFACT_PUT_RESOLVER: frozenset({ActionId.ARTIFACT_PUT_ATTEMPT_RESOLVE}),
     ServiceIdentity.ARTIFACT_SCHEDULER: frozenset({ActionId.ARTIFACT_PENDING_WORK_SCAN}),
+    ServiceIdentity.ARTIFACT_SOURCE_CLEANUP: frozenset({ActionId.ARTIFACT_SOURCE_CLEANUP}),
     ServiceIdentity.ARTIFACT_BINDING: frozenset(
         {
             ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
@@ -881,6 +886,7 @@ def _index_actions(
         (ServiceIdentity.ARTIFACT_PUT_RESOLVER, ActionId.ARTIFACT_PUT_ATTEMPT_RESOLVE),
         (ServiceIdentity.ARTIFACT_SCHEDULER, ActionId.ARTIFACT_PENDING_WORK_SCAN),
         (ServiceIdentity.ARTIFACT_BINDING, ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE),
+        (ServiceIdentity.ARTIFACT_SOURCE_CLEANUP, ActionId.ARTIFACT_SOURCE_CLEANUP),
         (ServiceIdentity.ARTIFACT_BINDING, ActionId.ARTIFACT_SUBMISSION_FINALIZE),
         (ServiceIdentity.ARTIFACT_BINDING, ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE),
         (ServiceIdentity.ARTIFACT_BINDING, ActionId.ARTIFACT_REVIEW_EVIDENCE_BINDING_CREATE),
@@ -948,6 +954,7 @@ def _index_actions(
     ActionId.ARTIFACT_PUT_ATTEMPT_RESOLVE,
     ActionId.ARTIFACT_PENDING_WORK_SCAN,
     ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
+    ActionId.ARTIFACT_SOURCE_CLEANUP,
     ActionId.ARTIFACT_SUBMISSION_FINALIZE,
     ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE,
     ActionId.ARTIFACT_GUIDE_SOURCE_READ,
@@ -1039,6 +1046,9 @@ def _index_actions(
         PermissionId.ARTIFACT_PENDING_WORK_SCAN,
         ActionOwner.AUTH_ART_02D_INTERNAL,
     ),
+    ActionId.ARTIFACT_SOURCE_CLEANUP: (
+        PermissionId.ARTIFACT_SOURCE_CLEANUP, ActionOwner.AUTH_ART_02D_INTERNAL,
+    ),
     ActionId.ARTIFACT_SUBMISSION_FINALIZE: (
         PermissionId.ARTIFACT_BINDING_CREATE, ActionOwner.AUTH_ART_05,
     ),
diff --git a/backend/app/modules/authorization/domain/action_groups.py b/backend/app/modules/authorization/domain/action_groups.py
index a8ec7b4c3..a6978f4ff 100644
--- a/backend/app/modules/authorization/domain/action_groups.py
+++ b/backend/app/modules/authorization/domain/action_groups.py
@@ -162,6 +162,7 @@
 def supports_prepared_denial(action_id: ActionId, resource_context: object) -> bool:
     """Admit only the existing action/context pairs for prepare-time denial evidence."""
     from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+    from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
     from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
     from app.modules.authorization.domain.task_authority import TASK_ACTIONS, TaskAuthorityResourceContext
     from app.modules.authorization.domain.project_create import ProjectCreateResourceContext
@@ -174,7 +175,8 @@ def supports_prepared_denial(action_id: ActionId, resource_context: object) -> b
         ProjectPolicyMutationPrepareDenialResourceContext, ProjectSubmissionArtifactPolicyMutationResourceContext,
     )
     return (
-        (action_id is ActionId.ARTIFACT_SUBMISSION_FINALIZE and type(resource_context) is SubmissionFinalizationResourceContext)
+        (action_id is ActionId.ARTIFACT_SOURCE_CLEANUP and type(resource_context) is SubmissionSourceCleanupResourceContext)
+        or (action_id is ActionId.ARTIFACT_SUBMISSION_FINALIZE and type(resource_context) is SubmissionFinalizationResourceContext)
         or (action_id is ActionId.SUBMISSION_CREATE and type(resource_context) is IntakeAcceptanceResourceContext)
         or (action_id is ActionId.SUBMISSION_INTAKE_RESERVE and type(resource_context) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext})
         or (
diff --git a/backend/app/modules/authorization/domain/audit.py b/backend/app/modules/authorization/domain/audit.py
index 1591b7a14..e1214477f 100644
--- a/backend/app/modules/authorization/domain/audit.py
+++ b/backend/app/modules/authorization/domain/audit.py
@@ -23,6 +23,7 @@
     "submission_intake_reservation",
     "submission_intake_acceptance",
     "submission_finalization",
+    "submission_source_cleanup",
     "submission_intake_preflight",
     "submission_operation_read",
     "submission_operation",
@@ -94,6 +95,7 @@
     "submission_intake_reservation",
     "submission_intake_acceptance",
     "submission_finalization",
+    "submission_source_cleanup",
     "submission_intake_preflight",
     "submission_operation_read",
     "submission_operation",
diff --git a/backend/app/modules/authorization/domain/audit_targets.py b/backend/app/modules/authorization/domain/audit_targets.py
index 0ad3ddfb1..1a6dff193 100644
--- a/backend/app/modules/authorization/domain/audit_targets.py
+++ b/backend/app/modules/authorization/domain/audit_targets.py
@@ -2,6 +2,7 @@
 
 from uuid import UUID
 from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
 from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext
 
@@ -85,7 +86,7 @@ def _submission_operation_target(resource):
     if type(resource) is SubmissionRecoveryResourceContext:
         return (str(resource.scope_project_id), "submission_operation", str(resource.resource_id),
                 "submission_operation", str(resource.resource_id))
-    if type(resource) in {IntakeAcceptanceResourceContext, SubmissionFinalizationResourceContext}:
+    if type(resource) in {IntakeAcceptanceResourceContext, SubmissionFinalizationResourceContext, SubmissionSourceCleanupResourceContext}:
         project_id = str(getattr(resource, "scope_project_id", None) or resource.project_id)
         return project_id, "submission_operation", str(resource.operation_id), "project", project_id
     if type(resource) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext} or (
diff --git a/backend/app/modules/authorization/domain/prepared_service.py b/backend/app/modules/authorization/domain/prepared_service.py
index 11e71762b..e4a1b613e 100644
--- a/backend/app/modules/authorization/domain/prepared_service.py
+++ b/backend/app/modules/authorization/domain/prepared_service.py
@@ -58,7 +58,15 @@
 from app.modules.authorization.domain.project_setup_finalization import (
     ProjectSetupFinalizationResourceContext,
 )
+from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.runtime import (
+    ArtifactPendingWorkResourceContext,
+    ArtifactPutAttemptResourceContext,
+    ArtifactVerificationJobResourceContext,
+    GuideSourceReadResourceContext,
+    SubmissionBindingResourceContext,
+    PreSubmitCheckerInputResourceContext,
     AuthorizationResourceContext,
     PreparedAuthorityScope,
     PreparedAuthorityScopeKind,
@@ -66,6 +74,47 @@
     ProjectSubmissionArtifactPolicyMutationResourceContext,
 )
 
+ARTIFACT_INTERNAL_RESOURCES = {
+    ActionId.ARTIFACT_GUIDE_SOURCE_READ: ("guide_source_read", GuideSourceReadResourceContext),
+    ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE: (
+        "pre_submit_checker_input",
+        PreSubmitCheckerInputResourceContext,
+    ),
+    ActionId.ARTIFACT_SOURCE_CLEANUP: (
+        "submission_source_cleanup", SubmissionSourceCleanupResourceContext,
+    ),
+    ActionId.ARTIFACT_SUBMISSION_FINALIZE: (
+        "submission_finalization", SubmissionFinalizationResourceContext,
+    ),
+    ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE: (
+        "submission_binding",
+        SubmissionBindingResourceContext,
+    ),
+    ActionId.ARTIFACT_PUT_ATTEMPT_RESOLVE: (
+        "artifact_put_attempt",
+        ArtifactPutAttemptResourceContext,
+    ),
+    ActionId.ARTIFACT_VERIFICATION_EXECUTE: (
+        "artifact_verification_job",
+        ArtifactVerificationJobResourceContext,
+    ),
+    ActionId.ARTIFACT_PENDING_WORK_SCAN: (
+        "artifact_pending_work",
+        ArtifactPendingWorkResourceContext,
+    ),
+}
+
+EXACT_ARTIFACT_RESOURCE_BY_ACTION = {
+    action: ARTIFACT_INTERNAL_RESOURCES[action]
+    for action in (
+        ActionId.ARTIFACT_GUIDE_SOURCE_READ,
+        ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE,
+        ActionId.ARTIFACT_SOURCE_CLEANUP,
+        ActionId.ARTIFACT_SUBMISSION_FINALIZE,
+        ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
+    )
+}
+
 _PROJECT_SETUP_ACTIONS = frozenset(
     {
         ActionId.PROJECT_GUIDE_SUFFICIENCY_RUN,
diff --git a/backend/app/modules/authorization/domain/submission_cleanup.py b/backend/app/modules/authorization/domain/submission_cleanup.py
new file mode 100644
index 000000000..8e06ed0ed
--- /dev/null
+++ b/backend/app/modules/authorization/domain/submission_cleanup.py
@@ -0,0 +1,26 @@
+"""Fixed-service authority for one immutable source cleanup obligation."""
+from typing import Literal
+from uuid import UUID
+
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+
+class SubmissionSourceCleanupResourceContext(BaseModel):
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True, revalidate_instances="always")
+    resource_type: Literal["submission_source_cleanup"] = "submission_source_cleanup"
+    resource_id: UUID
+    operation_id: UUID
+    project_id: UUID
+    task_id: UUID
+    source_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+    claim_id: UUID
+    claim_generation: int = Field(gt=0)
+    phase: Literal["claim", "confirm"]
+
+    @model_validator(mode="after")
+    def exact_cleanup(self):
+        if self.resource_id != self.operation_id or self.operation_id.version != 7:
+            raise ValueError("cleanup requires its exact operation")
+        if self.claim_id.version != 7:
+            raise ValueError("cleanup requires a generated claim identity")
+        return self
diff --git a/backend/app/modules/authorization/kernel.py b/backend/app/modules/authorization/kernel.py
index 6fefd807b..f5e2d6753 100644
--- a/backend/app/modules/authorization/kernel.py
+++ b/backend/app/modules/authorization/kernel.py
@@ -1,6 +1,5 @@
 """Deny-by-default request-scoped authorization kernel."""
 from __future__ import annotations
-from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
 from app.modules.authorization.domain.submission_recovery import SubmissionRecoveryResourceContext
 from app.modules.authorization.domain.guide_proposals import GUIDE_PROPOSAL_RESOURCE_BY_ACTION
 from app.modules.authorization.catalogue import POST_POLICY_ACTION_IDS
@@ -48,6 +47,7 @@
 from app.modules.authorization.domain.audit_targets import project_authority_audit_target
 from app.modules.authorization.domain.lifecycle import ReviewLifecycleActivationContract
 from app.modules.authorization.domain.prepared_service import (
+    ARTIFACT_INTERNAL_RESOURCES as _ARTIFACT_INTERNAL_RESOURCES,
     fixed_service_scope_project,
     fixed_service_resource_matches,
 )
@@ -77,12 +77,6 @@
     ActorProfileLifecycleResourceContext,
     ActorSelfResourceContext,
     ActorStatus,
-    ArtifactPendingWorkResourceContext,
-    ArtifactPutAttemptResourceContext,
-    ArtifactVerificationJobResourceContext,
-    GuideSourceReadResourceContext,
-    SubmissionBindingResourceContext,
-    PreSubmitCheckerInputResourceContext,
     AdminRoleDefinitionsResourceContext,
     AdminRoleGrantCollectionResourceContext,
     AdminRoleGrantIssueResourceContext,
@@ -147,32 +141,6 @@ async def prelock_serialized_admin_read_actor(authorization: AuthorizationServic
             authorization._context.actor_profile_id,
         )
 
-_ARTIFACT_INTERNAL_RESOURCES = {
-    ActionId.ARTIFACT_GUIDE_SOURCE_READ: ("guide_source_read", GuideSourceReadResourceContext),
-    ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE: (
-        "pre_submit_checker_input",
-        PreSubmitCheckerInputResourceContext,
-    ),
-    ActionId.ARTIFACT_SUBMISSION_FINALIZE: (
-        "submission_finalization", SubmissionFinalizationResourceContext,
-    ),
-    ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE: (
-        "submission_binding",
-        SubmissionBindingResourceContext,
-    ),
-    ActionId.ARTIFACT_PUT_ATTEMPT_RESOLVE: (
-        "artifact_put_attempt",
-        ArtifactPutAttemptResourceContext,
-    ),
-    ActionId.ARTIFACT_VERIFICATION_EXECUTE: (
-        "artifact_verification_job",
-        ArtifactVerificationJobResourceContext,
-    ),
-    ActionId.ARTIFACT_PENDING_WORK_SCAN: (
-        "artifact_pending_work",
-        ArtifactPendingWorkResourceContext,
-    ),
-}
 
 _ADMIN_EXPECTED_RESOURCES = MappingProxyType(
     {
diff --git a/backend/app/modules/authorization/prepared.py b/backend/app/modules/authorization/prepared.py
index 3cf0ff18a..4da99827d 100644
--- a/backend/app/modules/authorization/prepared.py
+++ b/backend/app/modules/authorization/prepared.py
@@ -2,6 +2,10 @@
 
 from __future__ import annotations
 from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+from app.modules.authorization.domain.prepared_service import (
+    EXACT_ARTIFACT_RESOURCE_BY_ACTION as _EXACT_ARTIFACT_RESOURCE_BY_ACTION,
+)
 from app.modules.authorization.prepared_preflight import preflight_authority
 from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, intake_preflight_matches, parse_intake_binding
 from app.modules.authorization.catalogue import GUIDE_PROPOSAL_ACTION_IDS, POST_POLICY_ACTION_IDS
@@ -97,7 +101,6 @@
     ArtifactPendingWorkResourceContext,
     ArtifactPutAttemptResourceContext,
     ArtifactVerificationJobResourceContext,
-    GuideSourceReadResourceContext,
     SubmissionBindingResourceContext,
     SubmissionCreationResourceContext,
     IntakeAcceptanceResourceContext,
@@ -188,23 +191,6 @@ def __reduce__(self) -> NoReturn:
 
 _HANDLE_CONSTRUCTOR_TOKEN = object()
 
-_EXACT_ARTIFACT_RESOURCE_BY_ACTION = {
-    ActionId.ARTIFACT_GUIDE_SOURCE_READ: (
-        "guide_source_read",
-        GuideSourceReadResourceContext,
-    ),
-    ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE: (
-        "pre_submit_checker_input",
-        PreSubmitCheckerInputResourceContext,
-    ),
-    ActionId.ARTIFACT_SUBMISSION_FINALIZE: (
-        "submission_finalization", SubmissionFinalizationResourceContext,
-    ),
-    ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE: (
-        "submission_binding",
-        SubmissionBindingResourceContext,
-    ),
-}
 
 
 @dataclass(frozen=True, slots=True)
@@ -653,7 +639,7 @@ def _validate_artifact_consumption(self, issuance, final_resource_context):
             (
                 PreSubmitCheckerInputResourceContext, SubmissionBindingResourceContext,
                 SubmissionCreationResourceContext, IntakeAcceptanceResourceContext,
-                SubmissionFinalizationResourceContext, TaskImportSourceResourceContext,
+                SubmissionSourceCleanupResourceContext, SubmissionFinalizationResourceContext, TaskImportSourceResourceContext,
             ),
         ) and not exact_artifact_binding_matches(
             issuance.binding.exact_artifact_context,
diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py
index b96977a2b..5250dfaa9 100644
--- a/backend/app/modules/authorization/runtime.py
+++ b/backend/app/modules/authorization/runtime.py
@@ -9,6 +9,7 @@
 
 from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts
 from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.domain.submission_recovery import SubmissionRecoveryResourceContext
 from app.modules.authorization.domain.guide_compilation import ProjectGuideCompilationExecuteResourceContext, ProjectGuideCompilationRequestResourceContext
 from app.modules.authorization.domain.resource_digest import authorization_resource_digest as authorization_resource_digest
@@ -161,6 +162,7 @@ class PreparedAuthorityScope(BaseModel):
             "pre_submit_checker_input",
             "submission_binding",
             "submission_finalization",
+            "submission_source_cleanup",
         ] | None = None
     artifact_resource_id: UUID | Literal["workstream:artifact_pending_work"] | None = None
 
@@ -216,7 +218,7 @@ def validate_selector(self):
                             "guide_source_binding",
                             "guide_source_read",
                             "pre_submit_checker_input",
-                            "submission_binding", "submission_finalization"}
+                            "submission_binding", "submission_finalization", "submission_source_cleanup"}
                         and isinstance(self.artifact_resource_id, UUID)
                     )
                 )
@@ -1114,6 +1116,7 @@ def bind_source_operation(self):
     | ArtifactOperatorReadResourceContext
     | ArtifactOperatorRetryResourceContext
     | GuideSourceReadResourceContext
+    | SubmissionSourceCleanupResourceContext
     | SubmissionFinalizationResourceContext
     | SubmissionRecoveryResourceContext
     | SubmissionCreationResourceContext | SubmissionBindingResourceContext | IntakeAcceptanceResourceContext
diff --git a/backend/app/modules/authorization/submission_consumption.py b/backend/app/modules/authorization/submission_consumption.py
index 590430c71..420f3125d 100644
--- a/backend/app/modules/authorization/submission_consumption.py
+++ b/backend/app/modules/authorization/submission_consumption.py
@@ -8,6 +8,7 @@
 
 from app.modules.authorization.catalogue import ActionId
 from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.domain.submission_intake import IntakeAcceptanceResourceContext
 
 _STRICT_FROZEN = ConfigDict(extra="forbid", frozen=True, strict=True)
@@ -127,6 +128,7 @@ def bind_admission(self):
 
 
 RESOURCE_BY_ACTION = {
+    ActionId.ARTIFACT_SOURCE_CLEANUP: SubmissionSourceCleanupResourceContext,
     ActionId.ARTIFACT_SUBMISSION_FINALIZE: SubmissionFinalizationResourceContext,
     ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE: SubmissionBindingResourceContext,
     ActionId.SUBMISSION_CREATE: SubmissionCreationResourceContext,
diff --git a/backend/tests/authorization/catalogue_fixtures.py b/backend/tests/authorization/catalogue_fixtures.py
index 04f5f3774..1486a7681 100644
--- a/backend/tests/authorization/catalogue_fixtures.py
+++ b/backend/tests/authorization/catalogue_fixtures.py
@@ -11,6 +11,7 @@
     ServiceIdentity.ARTIFACT_VERIFIER: {"artifact.verification.execute"},
     ServiceIdentity.ARTIFACT_PUT_RESOLVER: {"artifact.put_attempt.resolve"},
     ServiceIdentity.ARTIFACT_SCHEDULER: {"artifact.pending_work.scan"},
+    ServiceIdentity.ARTIFACT_SOURCE_CLEANUP: {"artifact.submission_source.cleanup"},
     ServiceIdentity.ARTIFACT_BINDING: {
         "artifact.submission.binding.create",
         "artifact.submission.finalize",
@@ -137,6 +138,7 @@
         "WS-XINT-002-06A",
         "active",
     ),
+    "artifact.submission_source.cleanup": ("artifact.submission_source.cleanup", "WS-AUTH-001-ART-02D-INTERNAL", "active"),
     "artifact.submission.finalize": ("artifact.binding.create", "WS-AUTH-001-ART-05", "active"),
     "artifact.submission.binding.create": (
         "artifact.binding.create",
@@ -280,7 +282,7 @@
     operations.checker.retry artifact.binding.read artifact.replica.read
     artifact.receipt.read artifact.verification_job.read
     artifact.verification_job.retry artifact.recovery_attempt.read artifact.audit.read
-    artifact.guide_source.ingest artifact.binding.create
+    artifact.guide_source.ingest artifact.binding.create artifact.submission_source.cleanup
     artifact.verification.execute artifact.pending_work.scan artifact.put_attempt.resolve
     artifact.guide_source.read artifact.checker_input.materialize
     artifact.checker_output.write artifact.review_packet.materialize
@@ -702,6 +704,7 @@
     "artifact.replica.read",
     "artifact.submission.binding.create",
     "artifact.submission.finalize",
+    "artifact.submission_source.cleanup",
     "artifact.submission_bundle.prepare",
     "artifact.verification.execute",
     "artifact.verification_job.read",
diff --git a/backend/tests/authorization/test_catalogue.py b/backend/tests/authorization/test_catalogue.py
index 4dcd30a25..3dfdfcb74 100644
--- a/backend/tests/authorization/test_catalogue.py
+++ b/backend/tests/authorization/test_catalogue.py
@@ -39,7 +39,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
     assert {item.value for item in HISTORICAL_PERMISSION_IDS} == historical_permissions
     assert {item.value for item in NEW_PERMISSION_IDS} == new_permissions
     assert {item.value for item in PERMISSION_IDS} == historical_permissions | new_permissions
-    assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 193
+    assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 194
     assert set(ACTION_BY_ID) == ACTION_IDS
     assert {definition.owner for definition in ACTION_DEFINITIONS} == set(ActionOwner)
     assert {
@@ -81,7 +81,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
         }
     } == {
         ActionOwner.AUTH_ART_02D_OPERATOR: 8,
-        ActionOwner.AUTH_ART_02D_INTERNAL: 3,
+        ActionOwner.AUTH_ART_02D_INTERNAL: 4,
         ActionOwner.XINT_002_04B: 1,
         ActionOwner.XINT_002_06A: 1,
         ActionOwner.AUTH_ART_05: 2,
@@ -118,7 +118,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
     }
     assert all(not owner.value.startswith("WS-REV-") for owner in ActionOwner)
     assert Counter(definition.availability for definition in ACTION_DEFINITIONS) == {
-        ActionAvailability.ACTIVE: 169,
+        ActionAvailability.ACTIVE: 170,
         ActionAvailability.PLANNED: 24,
     }
     assert (
@@ -148,7 +148,7 @@ def test_proposal_actions_have_exact_executable_authority(action):
 
 def test_permission_definition_response_is_exact() -> None:
     permission_response = AdminRoleGrantService.permission_definitions()
-    assert permission_response.total == 94
+    assert permission_response.total == 95
     assert [item.permission_id.value for item in permission_response.items] == sorted(
         permission.value for permission in PermissionId
     )
@@ -163,7 +163,7 @@ def test_fixed_service_action_matrix_and_activation_are_exact_and_immutable() ->
         identity: {action.value for action in actions}
         for identity, actions in SERVICE_ACTIONS_BY_IDENTITY.items()
     } == expected
-    assert sum(map(len, SERVICE_ACTIONS_BY_IDENTITY.values())) == 43
+    assert sum(map(len, SERVICE_ACTIONS_BY_IDENTITY.values())) == 44
     assert FUTURE_INTENT_REQUIRED_ACTIONS == {
         ActionId.REVIEW_FINDING_EVIDENCE_INGEST,
         ActionId.REVIEW_FINDING_RESPONSE_EVIDENCE_INGEST,
@@ -261,6 +261,7 @@ def test_active_fixed_service_actions_are_exact():
         ActionId.ARTIFACT_PRE_SUBMIT_CHECKER_INPUT_MATERIALIZE,
         ActionId.ARTIFACT_PENDING_WORK_SCAN,
         ActionId.ARTIFACT_SUBMISSION_BINDING_CREATE,
+        ActionId.ARTIFACT_SOURCE_CLEANUP,
         ActionId.ARTIFACT_SUBMISSION_FINALIZE,
         ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE,
         ActionId.ARTIFACT_CHECKER_OUTPUT_WRITE,
diff --git a/backend/tests/authorization/test_submission_finalization_authority.py b/backend/tests/authorization/test_submission_finalization_authority.py
index eb91ed247..b4fda20a9 100644
--- a/backend/tests/authorization/test_submission_finalization_authority.py
+++ b/backend/tests/authorization/test_submission_finalization_authority.py
@@ -81,3 +81,75 @@ async def test_finalization_refuses_missing_wrong_or_revoked_service(clean_postg
                 AuditEvent.event_type=="SensitiveAuthorizationAllowed"))).all()
     finally:
         await engine.dispose()
+
+
+def cleanup_facts(phase="claim"):
+    from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts
+    return SubmissionSourceCleanupAuthorityFacts(
+        operation_id=new_record_id(), project_id=new_record_id(), task_id=new_record_id(),
+        source_sha256="sha256:" + "c" * 64, claim_id=new_record_id(), claim_generation=1, phase=phase,
+    )
+
+
+@pytest.mark.parametrize("phase", ["claim", "confirm"])
+async def test_cleanup_authority_binds_every_target_fact(clean_postgres_database, phase):
+    from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization
+    from app.modules.authorization.domain.resource_digest import authorization_resource_digest
+    from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+    from dataclasses import asdict
+    engine = create_async_engine(clean_postgres_database)
+    factory = async_sessionmaker(engine, expire_on_commit=False)
+    try:
+        actor = await provision_post_submit_service(factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP)
+        original = cleanup_facts(phase)
+        async with factory.begin() as session:
+            authority = PreparedSubmissionSourceCleanupAuthorization(
+                session, request_id=new_record_id(), correlation_id=original.operation_id)
+            handle = await authority.prepare(facts=original, idempotency_key=original.claim_id)
+            mutations = dict(operation_id=new_record_id(), project_id=new_record_id(), task_id=new_record_id(),
+                             source_sha256="sha256:" + "d" * 64, claim_id=new_record_id(), claim_generation=2,
+                             phase="confirm" if phase == "claim" else "claim")
+            for name, value in mutations.items():
+                with pytest.raises(ArtifactAuthorityDeniedError):
+                    await authority.consume(prepared_authorization=handle, facts=replace(original, **{name: value}))
+            decision = await authority.consume(prepared_authorization=handle, facts=original)
+            assert isinstance(decision, UUID)
+            with pytest.raises(ArtifactAuthorityDeniedError):
+                await authority.consume(prepared_authorization=handle, facts=original)
+        async with factory() as session:
+            event = await session.get(AuditEvent, str(decision))
+            assert event.actor_id == actor and event.matched_grant_id is None
+            assert event.action_id == event.permission_id == "artifact.submission_source.cleanup"
+            assert event.resource_type == "submission_operation" and event.resource_id == str(original.operation_id)
+            assert event.target_ref_id == str(original.project_id)
+            context = SubmissionSourceCleanupResourceContext(resource_id=original.operation_id, **asdict(original))
+            assert event.after_facts["resource_context_digest"] == authorization_resource_digest(context)
+    finally:
+        await engine.dispose()
+
+
+@pytest.mark.parametrize("principal", ["missing", "binding", "revoked"])
+async def test_cleanup_refuses_missing_binding_or_revoked_service(clean_postgres_database, principal):
+    from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization
+    engine = create_async_engine(clean_postgres_database)
+    factory = async_sessionmaker(engine, expire_on_commit=False)
+    try:
+        if principal != "missing":
+            identity = ServiceIdentity.ARTIFACT_BINDING if principal == "binding" else ServiceIdentity.ARTIFACT_SOURCE_CLEANUP
+            actor = await provision_post_submit_service(factory, identity)
+            if principal == "revoked":
+                async with factory.begin() as session:
+                    from sqlalchemy import func
+                    await session.execute(update(ActorIdentityLink).where(ActorIdentityLink.actor_profile_id == actor)
+                        .values(status="revoked", revoked_by="test", revoked_reason="test", revoked_at=func.now()))
+        async with factory.begin() as session:
+            authority = PreparedSubmissionSourceCleanupAuthorization(
+                session, request_id=new_record_id(), correlation_id=new_record_id())
+            with pytest.raises(ArtifactAuthorityDeniedError):
+                await authority.prepare(facts=cleanup_facts(), idempotency_key=new_record_id())
+        async with factory() as session:
+            assert not (await session.scalars(select(AuditEvent).where(
+                AuditEvent.action_id == "artifact.submission_source.cleanup",
+                AuditEvent.event_type == "SensitiveAuthorizationAllowed"))).all()
+    finally:
+        await engine.dispose()
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 815ab1f16..d6187ec20 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "ea88b39d4ba01e345a6ea036184cda3194d1aa95f303555bad005243acde50ca"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "c7cb5c74bf2ff569927f804af635572743c76b3cc2dd9ae376d348c72d3ae423"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",

From 5fe3443a50f82acf2a560b1a41e70e4cb3a04cbb Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 01:38:29 +0100
Subject: [PATCH 142/513] docs(auth): reconcile cleanup service inventory and
 proof limits

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md            | 16 ++++++++++++++++
 docs/operations_authorization_service.md         | 14 +++++++++-----
 2 files changed, 25 insertions(+), 5 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 5ac836b6c..1abd8e6bf 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3537,3 +3537,19 @@ This checkpoint does not yet require these decisions in cleanup claims or
 confirmations, expose provider deletion, or provision a cleanup principal.
 Database decision binding and provider composition remain required work under
 the active full objective; no cleanup end-to-end completion is claimed.
+
+The post-refactor replay `/tmp/source-cleanup-authority3.log` passed all 17 tests
+in 28.71 seconds, with Alembic0079 and database cleanup confirmed in its JSON.
+It launched at e66dd6457 with final worktree content and is scope-compatible,
+not an exact-head launch receipt. Structure validation
+`/tmp/source-cleanup-authority-structure2.log` exited zero. After fetching origin,
+`git rev-list --count HEAD..origin/main` returned zero.
+At frozen clean 482062fd5, architecture/security and QA/test-delta passed this
+preparatory authority scope; CI integrity passed. Review independently compared
+all seven existing resource mappings and the four-action prepared subset with
+their predecessors, and the unchanged 105-line debt function. Documentation
+found DOC-CLEANUP-AUTH-01: a current operations page had obsolete service counts.
+The repair states the actual 22 identities, 21 action-bearing identities,
+44 memberships and eight ART identities, names cleanup's sole action and keeps
+uncomposed custody/provider work explicit. Review replay remains scoped to that
+repair; the full objective remains active and incomplete.
diff --git a/docs/operations_authorization_service.md b/docs/operations_authorization_service.md
index d37ff3fef..a7261fc88 100644
--- a/docs/operations_authorization_service.md
+++ b/docs/operations_authorization_service.md
@@ -733,12 +733,16 @@ actor, project, role, and cause event before a consumer changes product state.
 Revoking one role must leave the other project roles and all AdminRoleGrants
 unchanged.
 
-The closed registry now has seventeen fixed-service identities: sixteen
-action-bearing identities with twenty-five matrix memberships, plus the
+The closed registry has twenty-two fixed-service identities: twenty-one
+action-bearing identities with forty-four matrix memberships, plus the
 target-only `workstream.compensation.adapter` identity. The action-bearing
-set comprises seven ART identities, project setup, six exact REV identities,
-the active shared outbox dispatcher, and the task assignment reconciler. Missing
-provisioned rows deny without stopping the application.
+set comprises eight ART identities, project setup, six exact REV identities,
+the shared outbox dispatcher, three TASK identities and two CHECKER identities.
+The dedicated `workstream.artifact.source_cleanup` identity has only the
+`artifact.submission_source.cleanup` action. Its prepared authority binds the
+operation, project, task, source digest, claim ID/generation and cleanup phase;
+provider deletion and binding decisions to durable cleanup custody remain
+uncomposed. Missing provisioned rows deny without stopping the application.
 The target-only identity has no matrix membership, and the REV actions remain
 unavailable. Dispatcher authority grants no feature permission. Do not create a
 shared review service or a database service-grant table.

From 735f165b44de94b71f2700bbf0ecb9219a4ff371 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 01:39:27 +0100
Subject: [PATCH 143/513] docs(submission): record cleanup authority review
 closure

---
 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 1abd8e6bf..eef9b4bc5 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3553,3 +3553,8 @@ The repair states the actual 22 identities, 21 action-bearing identities,
 44 memberships and eight ART identities, names cleanup's sole action and keeps
 uncomposed custody/provider work explicit. Review replay remains scoped to that
 repair; the full objective remains active and incomplete.
+
+Documentation replay closed DOC-CLEANUP-AUTH-01 at clean 5fe3443a5, independently
+confirming the registry counts and incomplete cleanup-composition boundary.
+No scoped review finding remains for the authority prerequisite. Durable claim
+and confirmation decision enforcement is the next implementation step.

From 2407d522b9c72155f2ed6af2b46f889848ed795d Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 01:51:59 +0100
Subject: [PATCH 144/513] feat(artifacts): enforce audited source cleanup
 custody

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  52 ++++++-
 .../versions/0080_cleanup_decisions.py        |  74 ++++++++++
 .../app/modules/artifacts/authorization.py    |   9 ++
 .../app/modules/artifacts/intake/cleanup.py   |  39 ++++-
 .../app/modules/artifacts/intake/models.py    |   4 +
 ...identifier_generation_classifications.json |   3 +-
 .../test_submission_intake_admission.py       |   8 +-
 .../test_submission_source_cleanup.py         | 136 ++++++++++++++++--
 backend/tests/conftest.py                     |   2 +-
 docs/operations_authorization_service.md      |   4 +-
 10 files changed, 310 insertions(+), 21 deletions(-)
 create mode 100644 backend/alembic/versions/0080_cleanup_decisions.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index eef9b4bc5..c1ecb8384 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -31,8 +31,8 @@ independent worker capacity and public progress/operator endpoints remain unfini
 Internal audited finalization recovery now reuses the existing Operator gate-repair
 action, preserves the original delivery and runs the same T5 under a live child lease.
 Private sealed-source cleanup claims, retention barriers and atomic charge-release
-custody are now implemented and database-tested. Provider deletion, cleanup service
-authority, scheduling and uncertain/unsealed reconciliation remain uncomposed.
+custody are now implemented and database-tested. Cleanup claims and confirmations now require exact audited service decisions.
+Provider deletion, scheduling and uncertain/unsealed reconciliation remain uncomposed.
 Remaining work includes durable-worker deployment, complete cleanup, public API/CLI/MCP
 cutover, real revision/review/ContributionRecord journeys, policy cardinality and
 the A01–A35/C01–C07 completion audit. No public end-to-end readiness is claimed.
@@ -3558,3 +3558,51 @@ Documentation replay closed DOC-CLEANUP-AUTH-01 at clean 5fe3443a5, independentl
 confirming the registry counts and incomplete cleanup-composition boundary.
 No scoped review finding remains for the authority prerequisite. Durable claim
 and confirmation decision enforcement is the next implementation step.
+
+### Durable cleanup decision binding
+
+Continue the declared L0 cleanup scope by requiring current fixed-service
+resolution before locked custody/replay and consuming exact phase facts before
+claim/takeover/confirmation mutations. Persist separate claim/confirmation audit
+IDs; extend the database guard to validate action, principal, target and full
+context digest. Existing retained claims are not rewritten: unaudited pending
+claims must expire and be taken over with fresh authority; historical confirmed
+tombstones remain immutable. Update the existing cleanup/custody tests and the
+accepted-stall protection test to use real cleanup authorization. Prove denied
+and substituted decisions cannot acquire cleanup custody or release charges,
+while successful confirmation/replay, rollback, retention and lease protections
+remain intact. Provider I/O remains the following required composition step.
+
+The identifier inventory check exposed a stale classification from the earlier
+checker-image PRE sample repair: its removed prepared-generation expression was
+still listed while the new synthetic operation/lease expressions were not.
+Repair only those exact entries in
+`backend/scripts/identifier_generation_classifications.json`, preserving the
+existing synthetic-protocol-fixture category and all production classifications.
+The sample helper explicitly creates isolated wire envelopes, not product rows.
+This is a branch regression repair, not permission to relax the identifier gate.
+
+Durable cleanup authority evidence: migration0080 adds two nullable audit FKs
+without backfilling authority, one exact audit validation function and a narrowly
+extended existing cleanup trigger. The measured canonical schema is
+`847165363b1b89c72011b450992ab83512f5984faa6def5e751eb019423b7370`
+(`/tmp/source-cleanup-decisions-schema2.log/json`, migrated0080, cleanup true).
+An earlier invocation ran from the repository root and failed importing the
+migration helper; it supplies no schema evidence. Owner mutations obtain the
+audit decision before dirtying the claim, so audit flushing cannot prematurely
+publish an unaudited target. Live replay checks current service and the persisted
+claim decision; preexisting unaudited pending claims require expiry/takeover.
+Confirmed historical tombstones remain unchanged and protected.
+
+`/tmp/source-cleanup-decisions.log` passed all 20 selected PostgreSQL tests in
+332.14 seconds: cleanup authority substitutions (missing, phase, claim ID,
+generation, source digest and task), revoked service at claim/confirmation/replay,
+audit+claim/charge rollback, existing leases and both retention race orders,
+model/schema parity and stalled accepted-source protection. Existing raw-SQL
+charge release, source substitution and atomic confirmation proof remain: the
+atomicity probe now supplies valid confirmation authority before intentionally
+omitting charge release. Ruff and structure validation passed. Identifier
+inventory initially failed on the three stale sample classifications noted above;
+the precise repair passed (`/tmp/source-cleanup-decisions-inventory2.log`, 18.80s).
+This worktree proof precedes its frozen review commit, not exact-head launch
+proof. Provider deletion, settlement evidence and scheduling are still required.
diff --git a/backend/alembic/versions/0080_cleanup_decisions.py b/backend/alembic/versions/0080_cleanup_decisions.py
new file mode 100644
index 000000000..28e549e51
--- /dev/null
+++ b/backend/alembic/versions/0080_cleanup_decisions.py
@@ -0,0 +1,74 @@
+"""Require exact audited service decisions for cleanup claim and confirmation."""
+from alembic import op
+from sqlalchemy import text
+
+revision = "0080_cleanup_decisions"
+down_revision = "0079_cleanup_authority"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+    """Add audit references without inventing authority for historical claims."""
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.submission_source_cleanup_claims IN ACCESS EXCLUSIVE MODE")
+    for column, constraint in (
+        ("claim_decision_id", "fk_source_cleanup_claim_decision"),
+        ("confirmation_decision_id", "fk_source_cleanup_confirmation_decision"),
+    ):
+        op.execute(f"ALTER TABLE public.submission_source_cleanup_claims ADD COLUMN {column} uuid")
+        op.execute(f"ALTER TABLE public.submission_source_cleanup_claims ADD CONSTRAINT {constraint} "
+                   f"FOREIGN KEY ({column}) REFERENCES public.audit_events(id)")
+    op.execute(_AUTHORITY)
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef('public.guard_submission_source_cleanup()'::regprocedure)"
+    )).scalar_one()
+    replacements = {
+        "IF NEW.generation<>1 OR NEW.confirmed_at IS NOT NULL THEN":
+            "IF NEW.generation<>1 OR NEW.confirmed_at IS NOT NULL OR NEW.confirmation_decision_id IS NOT NULL THEN",
+        "IF (to_jsonb(NEW)-'confirmed_at') IS DISTINCT FROM (to_jsonb(OLD)-'confirmed_at')":
+            "IF (to_jsonb(NEW)-ARRAY['confirmed_at','confirmation_decision_id']) IS DISTINCT FROM "
+            "(to_jsonb(OLD)-ARRAY['confirmed_at','confirmation_decision_id'])",
+        "IF OLD.lease_expires_at>clock_timestamp() OR NEW.generation<>OLD.generation+1 OR NEW.confirmed_at IS NOT NULL THEN":
+            "IF OLD.lease_expires_at>clock_timestamp() OR NEW.generation<>OLD.generation+1 "
+            "OR NEW.confirmed_at IS NOT NULL OR NEW.confirmation_decision_id IS NOT NULL THEN",
+        " IF NEW.lease_expires_at<=clock_timestamp() THEN":
+            " IF NOT public.source_cleanup_authority_valid(NEW,'claim') OR "
+            "(NEW.confirmed_at IS NOT NULL AND NOT public.source_cleanup_authority_valid(NEW,'confirm')) THEN\n"
+            "   RAISE EXCEPTION 'source cleanup authority differs' USING ERRCODE='23514'; END IF;\n"
+            " IF NEW.lease_expires_at<=clock_timestamp() THEN",
+    }
+    for old, new in replacements.items():
+        if body.count(old) != 1:
+            raise RuntimeError("cleanup decision predecessor guard changed")
+        body = body.replace(old, new)
+    op.execute(body)
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
+
+
+_AUTHORITY = """
+CREATE FUNCTION public.source_cleanup_authority_valid(c public.submission_source_cleanup_claims, phase text)
+RETURNS boolean LANGUAGE sql STABLE SET search_path=pg_catalog,public,pg_temp AS $$
+ SELECT coalesce(EXISTS (
+  SELECT 1 FROM public.audit_events a JOIN public.actor_profiles p ON p.id::text=a.actor_id
+  JOIN public.submission_intake_operations o ON o.id=c.operation_id
+  WHERE a.id=(CASE WHEN phase='claim' THEN c.claim_decision_id ELSE c.confirmation_decision_id END)
+    AND phase IN ('claim','confirm') AND a.event_domain='authority' AND a.event_type='SensitiveAuthorizationAllowed'
+    AND a.actor_ref_kind='actor_profile' AND p.actor_kind='service' AND p.service_identity='workstream.artifact.source_cleanup'
+    AND a.action_id='artifact.submission_source.cleanup' AND a.permission_id='artifact.submission_source.cleanup'
+    AND a.project_id=o.project_id AND a.resource_type='submission_operation' AND a.resource_id=o.id::text
+    AND a.target_ref_kind='project' AND a.target_ref_id=o.project_id::text AND a.matched_grant_id IS NULL
+    AND a.denial_code IS NULL AND a.request_id IS NOT NULL AND a.correlation_id IS NOT NULL
+    AND a.after_facts::jsonb=jsonb_build_object('allowed',true,'resource_context_digest',
+      public.external_checker_registry_digest(jsonb_build_object('resource_context',jsonb_build_object(
+        'resource_type','submission_source_cleanup','resource_id',o.id::text,'operation_id',o.id::text,
+        'project_id',o.project_id::text,'task_id',o.task_id::text,
+        'source_sha256',public.external_checker_registry_digest(
+          c.source || jsonb_build_object('schema_version','workstream.sealed_submission_source.v1')),
+        'claim_id',c.claim_id::text,'claim_generation',c.generation,'phase',phase))))
+ ),false)
+$$
+"""
diff --git a/backend/app/modules/artifacts/authorization.py b/backend/app/modules/artifacts/authorization.py
index d537018ed..c6a601c3b 100644
--- a/backend/app/modules/artifacts/authorization.py
+++ b/backend/app/modules/artifacts/authorization.py
@@ -684,6 +684,15 @@ def __init__(self, session: AsyncSession, *, request_id: UUID, correlation_id: U
                          request_id=request_id, correlation_id=correlation_id)
 
 
+    async def authorize(self) -> None:
+        """Resolve current cleanup service before custody reads, including replay."""
+        await fixed_service_action_context(
+            self._session, service_identity=ServiceIdentity.ARTIFACT_SOURCE_CLEANUP,
+            action_id=ActionId.ARTIFACT_SOURCE_CLEANUP,
+            request_id=self._request_id, correlation_id=self._correlation_id,
+        )
+
+
 class PreparedSubmissionFinalizationAuthorization(_PreparedArtifactServiceAuthorization):
     """Accepted continuation authority belongs only to the existing binding service."""
 
diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py
index 7a35bed09..3e6eb2f76 100644
--- a/backend/app/modules/artifacts/intake/cleanup.py
+++ b/backend/app/modules/artifacts/intake/cleanup.py
@@ -1,6 +1,6 @@
-"""Private sealed-source cleanup custody; no provider I/O or service authority.
+"""Authorized sealed-source cleanup custody; provider I/O stays outside this owner.
 
-The composition root must authorize cleanup and act only on a committed claim.
+The composition root must supply current authority and act only on a committed claim.
 This owner retains uncertain targets and releases charges only with both exact
 object absence and settled upload-part obligations supplied by that coordinator.
 """
@@ -11,6 +11,7 @@
 from sqlalchemy import func, select, text
 
 from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
+from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts
 from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity
 from app.modules.artifacts.intake.models import SubmissionSourceCleanupClaim
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
@@ -43,11 +44,13 @@ def _claim_value(row: SubmissionSourceCleanupClaim) -> SealedSourceCleanupClaim:
 class SealedSourceCleanup:
     """Flush-only ownership: caller supplies current authority and root commits."""
 
-    def __init__(self, session, tasks):
+    def __init__(self, session, tasks, authorization):
         self._session = session
+        self._authorization = authorization
         self._intake = SubmissionIntakeRepository(session, tasks)
 
     async def _locked(self, operation_id):
+        await self._authorization.authorize()
         operation = await self._intake._lock(operation_id)
         await self._session.execute(text(
             "SELECT public.require_sealed_source_cleanup(o) "
@@ -58,6 +61,27 @@ async def _locked(self, operation_id):
         ).with_for_update().execution_options(populate_existing=True))
         return operation, row
 
+    async def _decision(self, operation, claim_id, generation, phase):
+        source = self._intake._sealed_source(operation)
+        facts = SubmissionSourceCleanupAuthorityFacts(
+            operation_id=UUID(operation.id), project_id=UUID(operation.project_id),
+            task_id=UUID(operation.task_id), source_sha256=source.source_sha256(),
+            claim_id=claim_id, claim_generation=generation, phase=phase,
+        )
+        handle = await self._authorization.prepare(facts=facts, idempotency_key=facts.claim_id)
+        decision = await self._authorization.consume(prepared_authorization=handle, facts=facts)
+        if type(decision) is not UUID:
+            raise IntakeCustodyConflict("source_cleanup_authority_unavailable")
+        return str(decision)
+
+    async def _require_claim_authority(self, operation_id):
+        valid = await self._session.scalar(text(
+            "SELECT public.source_cleanup_authority_valid(c,'claim') "
+            "FROM public.submission_source_cleanup_claims c WHERE operation_id=:id"
+        ), {"id": operation_id})
+        if valid is not True:
+            raise IntakeCustodyConflict("source_cleanup_authority_unavailable")
+
     async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: timedelta) -> SealedSourceCleanupClaim:
         """Claim only a stable eligible source; never resume foreground work."""
         if (type(claim_id) is not UUID or claim_id.version != 7
@@ -72,10 +96,14 @@ async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: tim
             if row.claim_id == str(claim_id):
                 if row.lease_expires_at <= now:
                     raise IntakeCustodyConflict("source_cleanup_stale")
+                await self._require_claim_authority(operation.id)
                 return _claim_value(row)
             if row.lease_expires_at > now:
                 raise IntakeCustodyConflict("source_cleanup_busy")
-            row.claim_id, row.generation = str(claim_id), row.generation + 1
+        generation = row.generation + 1 if row is not None else 1
+        decision = await self._decision(operation, claim_id, generation, "claim")
+        if row is not None:
+            row.claim_id, row.generation = str(claim_id), generation
             row.claimed_at, row.lease_expires_at = now, now + lease_duration
         else:
             row = SubmissionSourceCleanupClaim(
@@ -84,6 +112,7 @@ async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: tim
                 claimed_at=now, lease_expires_at=now + lease_duration,
             )
             self._session.add(row)
+        row.claim_decision_id = decision
         await self._session.flush()
         await self._session.refresh(row)
         return _claim_value(row)
@@ -102,6 +131,8 @@ async def confirm(self, claim: SealedSourceCleanupClaim, *, object_absent: bool,
         now = await self._session.scalar(select(func.clock_timestamp()))
         if row.lease_expires_at <= now:
             raise IntakeCustodyConflict("source_cleanup_stale")
+        await self._require_claim_authority(operation.id)
+        row.confirmation_decision_id = await self._decision(operation, claim.claim_id, claim.generation, "confirm")
         row.confirmed_at = now
         await self._session.flush()
         await SubmissionSourceCapacity(self._session).release_confirmed(operation)
diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py
index 29a3dc605..8a8429c91 100644
--- a/backend/app/modules/artifacts/intake/models.py
+++ b/backend/app/modules/artifacts/intake/models.py
@@ -166,6 +166,8 @@ class SubmissionSourceCleanupClaim(Base):
 
     __tablename__ = "submission_source_cleanup_claims"
     __table_args__ = (
+        ForeignKeyConstraint(["claim_decision_id"], ["audit_events.id"], name="fk_source_cleanup_claim_decision"),
+        ForeignKeyConstraint(["confirmation_decision_id"], ["audit_events.id"], name="fk_source_cleanup_confirmation_decision"),
         ForeignKeyConstraint(["operation_id"], ["submission_intake_operations.id"],
                              name="fk_source_cleanup_operation"),
         CheckConstraint("generation>0 and lease_expires_at>claimed_at and lease_expires_at<=claimed_at+interval '300 seconds'", name="claim_bounds"),
@@ -182,6 +184,8 @@ class SubmissionSourceCleanupClaim(Base):
     claimed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
     lease_expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
     confirmed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+    claim_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
+    confirmation_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
 
 
 class SubmissionSourceUploadReceipt(Base):
diff --git a/backend/scripts/identifier_generation_classifications.json b/backend/scripts/identifier_generation_classifications.json
index 4fa261e35..be8649368 100644
--- a/backend/scripts/identifier_generation_classifications.json
+++ b/backend/scripts/identifier_generation_classifications.json
@@ -213,7 +213,8 @@
     "scripts/checker_image_samples.py|sample_request|Assign:b5fdcb88b055f9c1|0": "uuid4:call:synthetic_protocol_fixture",
     "scripts/checker_image_samples.py|sample_request|Assign:a9a91ac5e37b2e68|0": "uuid4:call:synthetic_protocol_fixture",
     "scripts/checker_image_samples.py|sample_request|Assign:344d67fefe7152c0|0": "uuid4:call:synthetic_protocol_fixture",
-    "scripts/checker_image_samples.py|sample_request|Expr:32afbeb659a0a911|0": "uuid4:call:synthetic_protocol_fixture",
+    "scripts/checker_image_samples.py|sample_request|Expr:4b2813203bee28fd|0": "uuid4:call:synthetic_protocol_fixture",
+    "scripts/checker_image_samples.py|sample_request|Expr:f5f331b2ab22dcea|0": "uuid4:call:synthetic_protocol_fixture",
     "scripts/checker_image_samples.py|sample_request|Expr:50b3cf825c497aba|0": "uuid4:call:synthetic_protocol_fixture",
     "scripts/checker_image_samples.py|sample_request|Expr:698050182355b577|0": "uuid4:call:synthetic_protocol_fixture",
     "scripts/checker_image_samples.py|sample_request|Expr:0239e27dc8db7aa2|0": "uuid4:call:synthetic_protocol_fixture",
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index a0076f698..25ba4290c 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -34,12 +34,14 @@ async def test_stalled_accepted_source_is_protected_from_cleanup(recovery_intake
     """Exhausted finalizer delivery never turns accepted input into garbage."""
     from sqlalchemy.exc import DBAPIError
     from sqlalchemy import text
-    from app.adapters.tasks import intake_task_custody_port
-    from app.modules.artifacts.intake.cleanup import SealedSourceCleanup
+    from tests.artifacts.test_submission_source_cleanup import owner
+    from tests.checkers.execution.support import provision_post_submit_service
+    from app.modules.actors.api import ServiceIdentity
     f, operation = recovery_intake.f, recovery_intake.owner.operation_id
+    await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP)
     with pytest.raises(DBAPIError, match="cleanup is protected"):
         async with f.factory.begin() as session:
-            await SealedSourceCleanup(session, intake_task_custody_port(session)).claim(
+            await owner(session).claim(
                 operation, new_record_id(), lease_duration=timedelta(minutes=5))
     async with f.factory() as session:
         assert await session.scalar(text("SELECT state FROM submission_intake_operations WHERE id=:id"),
diff --git a/backend/tests/artifacts/test_submission_source_cleanup.py b/backend/tests/artifacts/test_submission_source_cleanup.py
index 49ad7b6f9..2ed3103c0 100644
--- a/backend/tests/artifacts/test_submission_source_cleanup.py
+++ b/backend/tests/artifacts/test_submission_source_cleanup.py
@@ -20,9 +20,37 @@
 pytestmark = pytest.mark.asyncio
 
 
+@pytest.fixture(autouse=True)
+async def provision_cleanup_identity(intake):
+    from app.modules.actors.api import ServiceIdentity
+    from tests.checkers.execution.support import provision_post_submit_service
+    return await provision_post_submit_service(intake.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP)
+
+
 def owner(session):
     """Use the same TASK custody adapter as foreground and finalization."""
-    return SealedSourceCleanup(session, intake_task_custody_port(session))
+    from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization
+    return SealedSourceCleanup(session, intake_task_custody_port(session),
+        PreparedSubmissionSourceCleanupAuthorization(session, request_id=new_record_id(), correlation_id=new_record_id()))
+
+
+async def cleanup_decision(session, operation, claim_id, *, phase="claim", generation=1, changes=None):
+    """Issue a real exact decision for SQL boundary counterprobes."""
+    from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts
+    from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization
+    from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+    row = await session.get(SubmissionIntakeOperation, str(operation))
+    facts = SubmissionSourceCleanupAuthorityFacts(
+        operation_id=operation, project_id=UUID(row.project_id), task_id=UUID(row.task_id),
+        source_sha256=repository(session)._sealed_source(row).source_sha256(),
+        claim_id=claim_id, claim_generation=generation, phase=phase,
+    )
+    if changes:
+        facts = replace(facts, **changes)
+    authority = PreparedSubmissionSourceCleanupAuthorization(
+        session, request_id=new_record_id(), correlation_id=new_record_id())
+    handle = await authority.prepare(facts=facts, idempotency_key=claim_id)
+    return await authority.consume(prepared_authorization=handle, facts=facts)
 
 
 async def terminal_source(intake):
@@ -103,11 +131,17 @@ async def test_cleanup_sql_rejects_release_without_confirmation_and_target_subst
     for sql, error in (
         ("UPDATE submission_source_charges SET state='released',accounted_bytes=0 WHERE operation_id=:id", "confirmed cleanup"),
         ("UPDATE submission_source_cleanup_claims SET source=jsonb_set(source,'{provider_generation}','\"foreign\"') WHERE operation_id=:id", "target differs"),
-        ("UPDATE submission_source_cleanup_claims SET confirmed_at=clock_timestamp() WHERE operation_id=:id", "release must be atomic"),
+        ("UPDATE submission_source_cleanup_claims SET confirmed_at=clock_timestamp() WHERE operation_id=:id", "authority differs"),
     ):
         with pytest.raises(DBAPIError, match=error):
             async with intake.factory.begin() as session:
                 await session.execute(text(sql), {"id": operation})
+    with pytest.raises(DBAPIError, match="release must be atomic"):
+        async with intake.factory.begin() as session:
+            decision = await cleanup_decision(session, operation, claim.claim_id, phase="confirm")
+            await session.execute(text("UPDATE submission_source_cleanup_claims "
+                "SET confirmed_at=clock_timestamp(),confirmation_decision_id=:decision WHERE operation_id=:id"),
+                {"id": operation, "decision": decision})
     async with intake.factory.begin() as session:
         replay = await owner(session).claim(operation, claim.claim_id, lease_duration=timedelta(minutes=5))
         assert replay == claim
@@ -175,20 +209,23 @@ async def test_cleanup_lease_bound_is_enforced_by_owner_and_database(intake):
     async with intake.factory() as session:
         row = await session.get(SubmissionIntakeOperation, str(operation))
         source = repository(session)._sealed_source(row).model_dump_json()
+    claim_id = new_record_id()
     with pytest.raises(DBAPIError, match="claim_bounds"):
         async with intake.factory.begin() as session:
+            decision = await cleanup_decision(session, operation, claim_id)
             await session.execute(text("INSERT INTO submission_source_cleanup_claims "
-                "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at) "
-                "VALUES (:id,:claim,1,CAST(:source AS jsonb),clock_timestamp(),clock_timestamp()+interval '10 years')"),
-                {"id": operation, "claim": new_record_id(), "source": source})
+                "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at,claim_decision_id) "
+                "VALUES (:id,:claim,1,CAST(:source AS jsonb),clock_timestamp(),clock_timestamp()+interval '10 years',:decision)"),
+                {"id": operation, "claim": claim_id, "source": source, "decision": decision})
     # Caller clock samples are not authoritative. Preserve the finite duration,
     # but rebase BOTH timestamps onto the trigger's single authoritative sample.
     async with intake.factory.begin() as session:
+        decision = await cleanup_decision(session, operation, claim_id)
         await session.execute(text("INSERT INTO submission_source_cleanup_claims "
-            "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at) "
+            "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at,claim_decision_id) "
             "VALUES (:id,:claim,1,CAST(:source AS jsonb),statement_timestamp()+interval '1 hour',"
-            "statement_timestamp()+interval '1 hour 1 minute')"),
-            {"id": operation, "claim": new_record_id(), "source": source})
+            "statement_timestamp()+interval '1 hour 1 minute',:decision)"),
+            {"id": operation, "claim": claim_id, "source": source, "decision": decision})
         assert await session.scalar(text("SELECT claimed_at<=clock_timestamp() "
             "AND lease_expires_at=claimed_at+interval '1 minute' "
             "FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation})
@@ -268,3 +305,86 @@ async def competing():
         if competitor is not None and not competitor.done():
             competitor.cancel()
             await asyncio.gather(competitor, return_exceptions=True)
+
+
+@pytest.mark.parametrize("substitution", ["missing", "phase", "claim", "generation", "source", "task"])
+async def test_database_cleanup_claim_requires_exact_decision(intake, substitution):
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    claim_id = new_record_id()
+    from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+    with pytest.raises(DBAPIError, match="authority differs"):
+        async with intake.factory.begin() as session:
+            row = await session.get(SubmissionIntakeOperation, str(operation))
+            source = repository(session)._sealed_source(row).model_dump_json()
+            changes = {
+                "phase": {"phase": "confirm"}, "claim": {"claim_id": new_record_id()},
+                "generation": {"claim_generation": 2}, "source": {"source_sha256": "sha256:" + "f" * 64},
+                "task": {"task_id": new_record_id()}, "missing": {},
+            }[substitution]
+            decision = None if substitution == "missing" else await cleanup_decision(
+                session, operation, claim_id, changes=changes)
+            await session.execute(text("INSERT INTO submission_source_cleanup_claims "
+                "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at,claim_decision_id) "
+                "VALUES (:id,:claim,1,CAST(:source AS jsonb),clock_timestamp(),clock_timestamp()+interval '5 minutes',:decision)"),
+                {"id": operation, "claim": claim_id, "source": source, "decision": decision})
+    async with intake.factory() as session:
+        assert await session.scalar(text("SELECT count(*) FROM submission_source_cleanup_claims WHERE operation_id=:id"),
+                                    {"id": operation}) == 0
+        assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"),
+                                    {"id": operation}) == 100
+
+
+@pytest.mark.parametrize("stage", ["claim", "confirm", "replay"])
+async def test_cleanup_owner_requires_current_service_even_on_replay(intake, provision_cleanup_identity, stage):
+    from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError
+    from app.modules.authorization.runtime import PreparedAuthorizationUnsupported
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    claim_id = new_record_id()
+    if stage != "claim":
+        async with intake.factory.begin() as session:
+            claim = await owner(session).claim(operation, claim_id, lease_duration=timedelta(minutes=5))
+        if stage == "replay":
+            async with intake.factory.begin() as session:
+                await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True)
+    async with intake.factory.begin() as session:
+        await session.execute(text("UPDATE actor_identity_links SET status='revoked',revoked_by='test',"
+            "revoked_reason='test',revoked_at=clock_timestamp() WHERE actor_profile_id=:actor"),
+            {"actor": provision_cleanup_identity})
+    with pytest.raises((ArtifactAuthorityDeniedError, PreparedAuthorizationUnsupported)):
+        async with intake.factory.begin() as session:
+            if stage == "claim":
+                await owner(session).claim(operation, claim_id, lease_duration=timedelta(minutes=5))
+            else:
+                await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True)
+    async with intake.factory() as session:
+        assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"),
+                                    {"id": operation}) == (0 if stage == "replay" else 100)
+
+
+async def test_cleanup_decisions_and_mutations_rollback_together(intake):
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    with pytest.raises(RuntimeError, match="rollback probe"):
+        async with intake.factory.begin() as session:
+            await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+            raise RuntimeError("rollback probe")
+    async with intake.factory() as session:
+        assert await session.scalar(text("SELECT count(*) FROM submission_source_cleanup_claims WHERE operation_id=:id"),
+                                    {"id": operation}) == 0
+        assert await session.scalar(text("SELECT count(*) FROM audit_events WHERE resource_id=:id "
+            "AND action_id='artifact.submission_source.cleanup'"), {"id": str(operation)}) == 0
+    async with intake.factory.begin() as session:
+        claim = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    with pytest.raises(RuntimeError, match="rollback probe"):
+        async with intake.factory.begin() as session:
+            await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True)
+            raise RuntimeError("rollback probe")
+    async with intake.factory() as session:
+        assert await session.scalar(text("SELECT confirmed_at IS NULL AND confirmation_decision_id IS NULL "
+            "FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation}) is True
+        assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"),
+                                    {"id": operation}) == 100
+        assert await session.scalar(text("SELECT count(*) FROM audit_events WHERE resource_id=:id "
+            "AND action_id='artifact.submission_source.cleanup'"), {"id": str(operation)}) == 1
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index d6187ec20..602f56424 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "c7cb5c74bf2ff569927f804af635572743c76b3cc2dd9ae376d348c72d3ae423"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "847165363b1b89c72011b450992ab83512f5984faa6def5e751eb019423b7370"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/docs/operations_authorization_service.md b/docs/operations_authorization_service.md
index a7261fc88..db86c09da 100644
--- a/docs/operations_authorization_service.md
+++ b/docs/operations_authorization_service.md
@@ -741,8 +741,8 @@ the shared outbox dispatcher, three TASK identities and two CHECKER identities.
 The dedicated `workstream.artifact.source_cleanup` identity has only the
 `artifact.submission_source.cleanup` action. Its prepared authority binds the
 operation, project, task, source digest, claim ID/generation and cleanup phase;
-provider deletion and binding decisions to durable cleanup custody remain
-uncomposed. Missing provisioned rows deny without stopping the application.
+claim and confirmation mutations require matching persisted audit decisions.
+Provider deletion remains uncomposed. Missing provisioned rows deny without stopping the application.
 The target-only identity has no matrix membership, and the REV actions remain
 unavailable. Dispatcher authority grants no feature permission. Do not create a
 shared review service or a database service-grant table.

From 4fa19c88bc0a67a2b9deb99e80507373e25456ab Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 02:02:29 +0100
Subject: [PATCH 145/513] fix(artifacts): revalidate cleanup replay after
 custody waits

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 13 ++++
 .../app/modules/artifacts/authorization.py    | 17 +++++
 .../app/modules/artifacts/intake/cleanup.py   |  1 +
 .../test_submission_source_cleanup.py         | 72 +++++++++++++++++++
 4 files changed, 103 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index c1ecb8384..0a23d0c48 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3606,3 +3606,16 @@ inventory initially failed on the three stale sample classifications noted above
 the precise repair passed (`/tmp/source-cleanup-decisions-inventory2.log`, 18.80s).
 This worktree proof precedes its frozen review commit, not exact-head launch
 proof. Provider deletion, settlement evidence and scheduling are still required.
+
+Review at frozen2407d522b found CLEANUP-AUTH-RACE-01: unlocked service preflight
+could become stale while replay waited for TASK custody. The new two-session
+regression waits until the exact TASK holder blocks replay, commits identity-link
+revocation, then releases custody. Both existing-claim and confirmed replay
+failed before the fix (`/tmp/source-cleanup-replay-red.log`: 2 failed, 50.79s),
+reproducing receipt return after revocation. The repair revalidates and locks
+fresh actor/link facts after TASK/operation locks, matching prepared consumption
+lock order and retaining those locks until the root transaction ends.
+QA also requested wrong non-null confirmation decisions with a complete attempted
+charge-release transaction. Added phase, generation and source-digest probes;
+all must leave confirmation empty and charge unchanged. Replay proof is pending
+for this repair; the prior 20-pass result does not prove the new race guard.
diff --git a/backend/app/modules/artifacts/authorization.py b/backend/app/modules/artifacts/authorization.py
index c6a601c3b..b986dc790 100644
--- a/backend/app/modules/artifacts/authorization.py
+++ b/backend/app/modules/artifacts/authorization.py
@@ -693,6 +693,23 @@ async def authorize(self) -> None:
         )
 
 
+    async def revalidate(self) -> None:
+        """Lock fresh service lifecycle facts after TASK/operation custody."""
+        from app.modules.authorization.runtime import ActorStatus, IdentityLinkStatus
+        context = await fixed_service_action_context(
+            self._session, service_identity=ServiceIdentity.ARTIFACT_SOURCE_CLEANUP,
+            action_id=ActionId.ARTIFACT_SOURCE_CLEANUP,
+            request_id=self._request_id, correlation_id=self._correlation_id,
+        )
+        revalidate = fixed_service_context_revalidator(
+            AdminAuthorizationRepository(self._session), ServiceIdentity.ARTIFACT_SOURCE_CLEANUP,
+        )
+        current = await revalidate(context, ActionId.ARTIFACT_SOURCE_CLEANUP)
+        if (current is None or current.actor_status is not ActorStatus.ACTIVE
+                or current.identity_link_status is not IdentityLinkStatus.ACTIVE):
+            raise ArtifactAuthorityDeniedError("artifact cleanup service is unavailable")
+
+
 class PreparedSubmissionFinalizationAuthorization(_PreparedArtifactServiceAuthorization):
     """Accepted continuation authority belongs only to the existing binding service."""
 
diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py
index 3e6eb2f76..7ab3fd0dc 100644
--- a/backend/app/modules/artifacts/intake/cleanup.py
+++ b/backend/app/modules/artifacts/intake/cleanup.py
@@ -52,6 +52,7 @@ def __init__(self, session, tasks, authorization):
     async def _locked(self, operation_id):
         await self._authorization.authorize()
         operation = await self._intake._lock(operation_id)
+        await self._authorization.revalidate()
         await self._session.execute(text(
             "SELECT public.require_sealed_source_cleanup(o) "
             "FROM public.submission_intake_operations o WHERE id=:id"
diff --git a/backend/tests/artifacts/test_submission_source_cleanup.py b/backend/tests/artifacts/test_submission_source_cleanup.py
index 2ed3103c0..122b31020 100644
--- a/backend/tests/artifacts/test_submission_source_cleanup.py
+++ b/backend/tests/artifacts/test_submission_source_cleanup.py
@@ -388,3 +388,75 @@ async def test_cleanup_decisions_and_mutations_rollback_together(intake):
                                     {"id": operation}) == 100
         assert await session.scalar(text("SELECT count(*) FROM audit_events WHERE resource_id=:id "
             "AND action_id='artifact.submission_source.cleanup'"), {"id": str(operation)}) == 1
+
+
+@pytest.mark.parametrize("phase", ["claim", "confirmed_replay"])
+async def test_cleanup_replay_rechecks_revocation_after_task_wait(intake, provision_cleanup_identity, phase):
+    """Revocation commits after preflight but before replay acquires custody."""
+    from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError
+    from app.modules.authorization.runtime import PreparedAuthorizationUnsupported
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    async with intake.factory.begin() as session:
+        claim = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    if phase == "confirmed_replay":
+        async with intake.factory.begin() as session:
+            await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True)
+    waiting_pid = asyncio.Queue()
+
+    async def replay():
+        async with intake.factory.begin() as session:
+            await waiting_pid.put(await session.scalar(text("SELECT pg_backend_pid()")))
+            with pytest.raises((ArtifactAuthorityDeniedError, PreparedAuthorizationUnsupported)):
+                if phase == "claim":
+                    await owner(session).claim(operation, claim.claim_id, lease_duration=timedelta(minutes=5))
+                else:
+                    await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True)
+
+    contender = None
+    try:
+        async with intake.factory.begin() as blocker:
+            winner_pid = await blocker.scalar(text("SELECT pg_backend_pid()"))
+            await blocker.execute(text("SELECT id FROM workstream_tasks WHERE id=:task FOR UPDATE"),
+                                  {"task": intake.task})
+            contender = asyncio.create_task(replay())
+            async with asyncio.timeout(15):
+                pid = await waiting_pid.get()
+                async with intake.factory() as observer:
+                    while not await observer.scalar(text("SELECT :winner=ANY(pg_blocking_pids(:waiter))"),
+                                                    {"winner": winner_pid, "waiter": pid}):
+                        await asyncio.sleep(0.02)
+            assert not contender.done()
+            async with intake.factory.begin() as revoker:
+                await revoker.execute(text("UPDATE actor_identity_links SET status='revoked',revoked_by='test',"
+                    "revoked_reason='test',revoked_at=clock_timestamp() WHERE actor_profile_id=:actor"),
+                    {"actor": provision_cleanup_identity})
+        async with asyncio.timeout(15):
+            await contender
+    finally:
+        if contender is not None and not contender.done():
+            contender.cancel()
+            await asyncio.gather(contender, return_exceptions=True)
+
+
+@pytest.mark.parametrize("substitution", ["phase", "generation", "source"])
+async def test_confirmation_rejects_wrong_decision_even_with_atomic_release(intake, substitution):
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    async with intake.factory.begin() as session:
+        claim = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5))
+    changes = {"phase": {"phase": "claim"}, "generation": {"claim_generation": 2},
+               "source": {"source_sha256": "sha256:" + "e" * 64}}[substitution]
+    with pytest.raises(DBAPIError, match="authority differs"):
+        async with intake.factory.begin() as session:
+            decision = await cleanup_decision(session, operation, claim.claim_id, phase="confirm", changes=changes)
+            await session.execute(text("UPDATE submission_source_cleanup_claims "
+                "SET confirmed_at=clock_timestamp(),confirmation_decision_id=:decision WHERE operation_id=:id"),
+                {"id": operation, "decision": decision})
+            await session.execute(text("UPDATE submission_source_charges SET state='released',accounted_bytes=0 "
+                                       "WHERE operation_id=:id"), {"id": operation})
+    async with intake.factory() as session:
+        assert await session.scalar(text("SELECT confirmed_at IS NULL AND confirmation_decision_id IS NULL "
+            "FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation}) is True
+        assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"),
+                                    {"id": operation}) == 100

From 9bee67a12cc3f25909eee39001101e85ee094c40 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 13 Nov 2026 02:06:31 +0100
Subject: [PATCH 146/513] docs(submission): record cleanup custody proof and
 remaining CI failures

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 29 +++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 0a23d0c48..f9edf03f5 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3619,3 +3619,32 @@ QA also requested wrong non-null confirmation decisions with a complete attempte
 charge-release transaction. Added phase, generation and source-digest probes;
 all must leave confirmation empty and charge unchanged. Replay proof is pending
 for this repair; the prior 20-pass result does not prove the new race guard.
+
+The repaired full cleanup module passed 23 tests in 336.82 seconds
+(`/tmp/source-cleanup-decisions2.log/json`, Alembic0080, database cleanup true).
+The receipt launched at2407d522b with final worktree content; it is not an
+exact-head launch. Architecture/security and QA/test-delta replay passed frozen
+clean4fa19c88b and closed the replay race and confirmation-proof findings.
+Docs/CI replay found no gate or scope-claim defect. Structure validation2 and
+shared Ruff/Commitrail/stale AUTH docs/Markdown checks passed. Provider deletion,
+late-write/part settlement and scheduling remain unimplemented.
+
+Hosted CI inspection of the previous pushed735f165b4 (PR merge execution
+b083aa86e92a9b36ce306d27003a8d4202a6887d, Backend run43338819788) is NOT green:
+- AUTH preflight fails the reflection gate at `vars(draft)` in foreground
+  acceptance; replace it with explicit acceptance-field publication, not a gate
+  exemption. Evidence `/tmp/submission-ci-auth-preflight.log`.
+- Checker runtime stops at rustfmt differences in `src/smol/pre.rs` and
+  `src/smol/pre/tests.rs`; no native runtime qualification result follows that
+  failure. Evidence `/tmp/submission-ci-runtime.log`.
+- CLI API contract run has 10 failures/15 passes: its permission catalogue still
+  expects94 instead of95, and remaining old PRE callers use removed preparation
+  facts or the removed `materialization` constructor argument. Evidence
+  `/tmp/submission-ci-cli-api.log`.
+- Task lifecycle C artifact has47 failures/259 passes, likewise identifying old
+  PRE/retained-fixture consumers that require coordinated source-first cutover.
+  Evidence `/tmp/submission-task-c-pytest.log`, downloaded exact lane artifact
+  13999330936. Do not restore a parallel obsolete PRE implementation to hide them.
+Repair bounded count/format/reflection regressions, then continue provider cleanup
+and the already-required public/client/downstream cutover. No full-suite readiness
+or merge request is implied by the focused cleanup proof.

From 8f7e5eae3b5c2242a4a4bd5593f200c04c41ecd4 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 11:18:36 +0100
Subject: [PATCH 147/513] fix(submission): enforce owner boundaries and
 explicit PRE validation

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 207 ++++++++++++++++++
 backend/app/adapters/artifacts/__init__.py    |  94 ++++++++
 .../app/adapters/artifacts/finalization.py    |  83 -------
 backend/app/adapters/checkers/__init__.py     |  14 +-
 .../app/adapters/checkers/external_service.py |   9 +-
 backend/app/adapters/outbox/__init__.py       |   2 +-
 backend/app/core/hashing.py                   |  11 +
 .../artifacts/api/submission_archive.py       |  73 +++---
 .../artifacts/api/submission_manifest.py      | 198 +++++++++++++++++
 .../app/modules/artifacts/authorization.py    |   4 +-
 .../artifacts/intake/foreground_admission.py  |   9 +-
 .../artifacts/post_submit_materialization.py  |   4 +-
 backend/app/modules/artifacts/preparation.py  |   7 +-
 .../selected_pre_submit_admission.py          |   3 +
 .../selected_pre_submit_execution.py          |   6 +-
 .../selected_pre_submit_source_contracts.py   |  51 +++++
 .../selected_pre_submit_source_custody.py     |  37 ++++
 backend/app/modules/artifacts/sources.py      |  16 +-
 .../modules/artifacts/submission_admission.py |  12 +-
 .../modules/artifacts/submission_archive.py   |  34 +--
 .../modules/artifacts/submission_bindings.py  |   4 +-
 .../modules/artifacts/submission_manifest.py  | 179 +--------------
 .../artifacts/submission_materialization.py   |   6 +-
 .../{domain => api}/submission_cleanup.py     |   0
 .../submission_finalization.py                |   0
 .../authorization/domain/action_groups.py     |   4 +-
 .../authorization/domain/audit_targets.py     |   4 +-
 .../authorization/domain/prepared_service.py  |   4 +-
 backend/app/modules/authorization/prepared.py |   5 +-
 backend/app/modules/authorization/runtime.py  |   4 +-
 .../authorization/submission_consumption.py   |   4 +-
 .../checkers/api/selected_pre_submit.py       | 136 +++++++-----
 .../modules/checkers/api/source_contracts.py  | 135 ++++++++++++
 .../selected_pre_submit_coordination.py       |  40 ++--
 .../checkers/selected_pre_submit_execution.py |   6 +-
 .../checkers/selected_pre_submit_reads.py     |  17 +-
 backend/scripts/external_api_drill.py         |   4 +-
 .../test_submission_intake_admission.py       |   8 +-
 .../test_submission_intake_contracts.py       |  48 ++++
 .../artifacts/test_submission_pre_source.py   |  14 +-
 .../pre_submit/test_contracts.py              |   6 +-
 .../test_submission_finalization_authority.py |   2 +-
 .../tests/checkers/default/test_execution.py  |   5 +-
 .../checkers/external/test_pre_invocation.py  |  53 ++---
 .../tests/checkers/external/test_runtime.py   |  20 +-
 .../external/test_selected_pre_submit.py      |  24 +-
 .../test_selected_pre_submit_coordination.py  | 155 ++++++++-----
 .../test_selected_pre_submit_service.py       |   6 +-
 .../contributor_reads/test_projection.py      |   4 +-
 .../post_submit_materialization_helpers.py    |   4 +-
 backend/tests/reviews/decision/support.py     |   4 +-
 .../tests/selected_predecessor_fixtures.py    |   6 +-
 backend/tests/test_checker_materialization.py |  10 +-
 ..._submission_bundle_preparation_recovery.py |   4 +-
 backend/tests/test_submission_change_gate.py  |   4 +-
 backend/tests/test_submission_manifest.py     |  28 ++-
 backend/tests/test_trusted_intake.py          |  22 +-
 cli/internal/api/admin_inspection.go          |   4 +-
 .../integration/test_admin_inspection_http.py |   6 +-
 .../test_admin_inspection_public_api.py       |   2 +-
 external_checkers/intake/worker.py            |  13 +-
 .../tests/pre_dialogue.py                     |   9 +-
 .../src/smol/pre.rs                           |  11 +-
 .../src/smol/pre/tests.rs                     |  22 +-
 .../tests/trusted_intake.py                   |   2 +-
 mcp_server/contracts/permissions_list.json    |   7 +-
 .../tests/integration/test_access_reads.py    |   2 +-
 mcp_server/tests/test_access_reads.py         |   4 +-
 scripts/test_external_api_drill.py            |   7 +-
 69 files changed, 1318 insertions(+), 624 deletions(-)
 delete mode 100644 backend/app/adapters/artifacts/finalization.py
 create mode 100644 backend/app/modules/artifacts/api/submission_manifest.py
 create mode 100644 backend/app/modules/artifacts/selected_pre_submit_source_contracts.py
 create mode 100644 backend/app/modules/artifacts/selected_pre_submit_source_custody.py
 rename backend/app/modules/authorization/{domain => api}/submission_cleanup.py (100%)
 rename backend/app/modules/authorization/{domain => api}/submission_finalization.py (100%)
 create mode 100644 backend/app/modules/checkers/api/source_contracts.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index f9edf03f5..bcbe32450 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3648,3 +3648,210 @@ b083aa86e92a9b36ce306d27003a8d4202a6887d, Backend run43338819788) is NOT green:
 Repair bounded count/format/reflection regressions, then continue provider cleanup
 and the already-required public/client/downstream cutover. No full-suite readiness
 or merge request is implied by the focused cleanup proof.
+
+### Bounded CI regression repair
+
+Repair the observed preflight/runtime/catalogue failures before further cleanup
+composition. Allowed changes: explicit accepted-evidence field publication in
+ART foreground admission; CLI permission response validation and its HTTP/API
+fixtures; MCP catalogue fixtures; the independent external API drill permission
+oracle and tests; rustfmt on the two changed PRE Rust files; this record.
+Preserve the full accepted decision/event/receipt transaction and all input
+identity fields. Keep the closed permission count exact at95 and add only the
+new cleanup permission to the drill oracle. Do not relax response validation,
+module-boundary gates, tests or lanes, or restore the obsolete PRE flow.
+Risk is L0 for acceptance atomicity and L1 for client catalogue/format fixes.
+Verify boundary/structure checks, real PostgreSQL T4 acceptance and rollback,
+CLI HTTP and real API catalogue behavior, MCP catalogue behavior, drill oracle
+unit proof and cargo fmt. Review architecture/security and QA for acceptance,
+docs/CI for unchanged gate and proof scope. Human review focus is the explicit
+publication field set and unchanged authorization/OUTBOX atomicity. Native Smol
+qualification and remaining old PRE consumers are outside this repair's proof.
+
+Once reflection is removed, preflight reports two added private AUTH edges:
+ART's authorization adapter imports the cleanup and finalization resource fact
+models from AUTH's domain package. These are strict, immutable selector-only
+models that the caller must construct; relocate their definitions into AUTH's
+public API, update all internal and external consumers, and remove the superseded
+domain files. This exposes the actual typed fact contract rather than adding a
+private-module re-export or ledger exception. The same models, validation,
+audit digests and authority checks remain; no executable capability is granted
+by constructing values. Include the two moves and consumer imports in this
+scope's architecture/security review and replay existing exact-authority tests.
+
+Further gate inspection finds four private ART imports in the new finalization
+adapter submodule. Move that actual composition into the canonical ART adapter
+root, update OUTBOX and test callers, and remove the superseded submodule. This
+uses the repository's existing owner-composition boundary and adds no ledger
+entry. Include original/recovery finalizer composition tests in verification.
+MCP's permission schema snapshot also still fixes94 and its closed enum omits
+cleanup; regenerate that one transitive fragment from current backend OpenAPI,
+retain the snapshot digest check, and verify the installed contract behavior.
+
+The public API leak gate additionally identifies manifest validation importing
+private ART implementations. Move the actual canonical manifest value, builder
+and reported-manifest validator into `artifacts/api/submission_manifest.py`, and
+pure path/inventory rules into the existing archive API. Keep ZIP I/O and change
+policy private; update all affected consumers without compatibility re-exports.
+Extract the existing digest-format validator into `core/hashing.py` and update
+its consumers so public values do not depend on private source capabilities.
+This scope includes those files and their existing tests. Preserve closed shape,
+digest, normalization, collision, ancestry and resource-limit rejection behavior;
+verify existing archive/manifest/change-gate and selected PRE contract tests,
+plus the full boundary gate. Include this relocation in architecture/QA review.
+
+The concrete manifest relocation clears the public-private leak stage. The full
+boundary run now reaches `cyclic_public_dependency` (boundaries4 log). A direct
+edge inventory identifies CHECKERS -> ART in `checkers/api/selected_pre_submit.py`
+(source values, archive limits and manifest validation) and
+`checkers/selected_pre_submit_coordination.py` (source custody port), against the
+existing ART -> CHECKERS dependency. This requires a real consumer-port design
+repair; the relocation alone does not establish a passing boundary gate.
+Archive/manifest/change-gate regression run: 76 passed, 5 failed in 121.63s.
+All five failures are preparation-deadline errors before inspection in the
+scratch-backed archive tests; preserve the deadline and diagnose independently.
+Evidence: `/tmp/submission-ci-repair-manifest.log`. No passing-suite claim.
+
+The regenerated MCP permission snapshot and updated fixtures passed all 21
+selected permission-list cases (210 deselected, 215.33s), including the three
+previously failing schema/wire/revocation cases. Evidence:
+`/tmp/submission-ci-repair-mcp-permissions.log`. This proves source-package
+permission behavior only; installed-wheel API integration remains separate.
+
+The unchanged single scratch-preparation case also fails independently with
+`ArtifactPreparationDeadlineError` (1 failed, 28.67s;
+`/tmp/submission-ci-repair-archive-deadline-probe.log`). Thus parallel pytest
+contention alone is not an adequate explanation. Next diagnose preparation I/O
+and compare the same case before relocation, preserving its ten-second bound.
+
+Scratch diagnosis continued without changing production behavior or limits.
+Temporary timing instrumentation outside the repository reproduced successful
+preparation in 5.02s: 64 ledger writes, 61 reserve-byte calls; ledger writes took
+3.46s. The test buffer is two bytes and the sample ZIP is 122 bytes. The same
+five failing cases then passed unchanged (5 passed, 38 deselected, 36.61s;
+`/tmp/submission-ci-repair-archive-preparation-replay.log`). Together these show
+variable preparation I/O latency, not a demonstrated manifest-validation defect;
+retain the original timeout failures as evidence rather than claiming reliable
+full-suite passage. Cargo fmt --check passed for the Rust service.
+
+Further dirty-worktree verification after the public contract relocations:
+- Exact finalization/cleanup authorization module: 10 passed in 56.17s,
+  Alembic0080, isolated database cleanup true
+  (`/tmp/submission-ci-repair-authority.log/json`).
+- Selected PRE derived-manifest, completed-evidence and default-blocker cases:
+  17 passed, 69 deselected in 15.91s
+  (`/tmp/submission-ci-repair-derived-manifest.log`).
+- Test structure boundary validation and Ruff on all changed backend Python
+  files passed; git diff --check passed.
+These receipts validate their affected scope, not the unresolved dependency
+cycle, obsolete PRE callers or public end-to-end behavior.
+
+Architecture consultation confirms two explicit CHECKERS consumer boundaries:
+pure source-contract validation and session-bound live custody. Keep actual
+source and limits values ART-owned; do not move them into core/interfaces or
+add parallel models. Thread pure validation explicitly through constructors,
+canonical decoding and nested invocation receipts; missing decoder context must
+fail closed. This consultation is not frozen candidate approval.
+First implement the independent custody boundary: add CHECKERS' source guard
+protocol, move exact source/lease/context comparison into an ART-owned guard,
+compose it through ART's adapter root, and update coordinator callers and
+existing source-substitution tests. Keep TASK-before-ART-before-CHECKERS order,
+all compared fields, and current refusal category. Allowed files include those
+two owners, adapter roots and the existing coordination test module. Risk L0;
+verify live-custody substitution cases and historical refusal, then include real
+PostgreSQL acceptance/recovery coverage in final review. Pure decoding remains
+an explicit remaining edge, not hidden by this first step.
+
+The custody-port step passed the existing exact live-source substitution,
+lease-cap and historical-refusal cases: 12 passed, 74 deselected in 3.05s
+(`/tmp/submission-ci-repair-source-guard.log`). The tests now exercise ART's
+real comparison guard with controlled custody facts; every original comparison
+is preserved. CHECKERS' coordinator no longer imports ART. The selected-PRE API
+still imports ART for pure source/limits/manifest validation; the full dependency
+cycle therefore remains open. The next implementation step must explicitly
+thread pure validation through constructor/decoder and nested receipt paths;
+consumer inventory is `/tmp/submission-source-codec-consumers.txt`. Architecture
+consultation completed without edits and is not final candidate approval.
+
+Pure-contract repair scope: add a small CHECKERS API declaring read-only source
+and archive-limit views plus strict parsing/validation methods. ART implements
+those methods with its existing source, archive and manifest definitions; only
+ART's canonical adapter root constructs the implementation. The port carries
+no session, credentials or provider read capability. Add a canonical body method
+to the existing archive-limits value for exact JSON preservation. Then replace
+CHECKERS' concrete ART dependencies and thread the port through affected owner
+services, adapters, constructors and decoders. Existing substitution, resource
+limit and canonical-wire tests remain the proof; add only missing port-boundary
+failure cases. Never store the port in persisted facts, use a global codec,
+weaken strict source typing or permit context-free JSON decoding. Allowed files
+include the two owners' APIs/implementations, their adapter roots and traced
+callers/tests. Risk remains L0; frozen architecture/security and QA review is
+required after the complete call-path cutover, not for an unused interface alone.
+
+Pure validation port and ART implementation added, preserving concrete owner
+values and delegating canonical manifest validation to the existing implementation.
+The port tests passed 11 cases (137 deselected, 29.44s;
+`/tmp/submission-source-contract-port.log`): reject forged/non-owner source
+objects, missing/extra/coercive/overflow limits, omitted canonical source fields,
+wrong manifest digest, stricter entry limits and malformed manifest fields.
+Ruff and diff whitespace checks passed. This is boundary implementation evidence,
+not completed runtime wiring or a passing module DAG. Production decoding still
+uses the original concrete imports until the coordinated signature cutover.
+Call-path inventory identifies coordinator replay, retained-run reader, ART
+admission recovery, checker external-service response decoding, and nested
+receipt decoding/validate_lease as required consumers. Do not wire only the
+foreground constructor and leave historical or replay paths unvalidated.
+
+The pure port is now explicitly threaded through CHECKERS source/execution
+constructors (keyword-only InitVar, excluded from retained dataclass fields),
+canonical decoders, derivation and nested receipt validation. Runtime-profile
+JSON parsing requires an explicit owner context and preserves existing limits
+serialization. Coordinator, retained reader, processor and socket transport get
+the dependency through composition; ART callers use their owner implementation.
+Pydantic also traverses these dataclasses inside AUTH resource values, requiring
+explicit structural-view validation hooks; no arbitrary source decoding fallback
+was added. Direct and fixture callers were updated together.
+The first focused run after schema-hook repair passed87/failed1 because one
+`dataclasses.replace` test omitted the required InitVar. After fixing that caller
+and adding missing-context/non-retention tests, all90 selected cases passed
+(34 deselected, 18.42s; `/tmp/submission-source-codec-wiring3.log`). The earlier
+full module-boundary run passed (`/tmp/submission-ci-repair-boundaries5.log`),
+and a repeat after complete wiring is underway. PostgreSQL T4, structure and
+OpenAPI verification remain pending; no final frozen review or commit yet.
+
+Complete call-path inspection also includes the separate trusted guest entry
+point and portable guest/service drills under `external_checkers/`. Update their
+manifest imports and explicit pure-validator construction with the backend
+callers. The guest already composes the private ZIP inspector and default checker;
+it constructs ART's pure validator at that application boundary without pulling
+API/session adapter roots into execution. Include these paths in architecture
+review; a backend-only import scan does not prove the guest is wired.
+The first T4 replay stopped during collection on the missed guest manifest import;
+that import and the guest's decoder/derivation calls are repaired. No T4 pass is
+claimed for that run. A direct old-HEAD/new-profile wire comparison then exposed
+integer versus float inspection-second serialization. Preserve Pydantic's prior
+float output in the existing limits canonical projection; the corrected comparison
+passes for integer, fractional and default seconds
+(`/tmp/submission-profile-wire-compare.log`). Added a focused wire-representation
+regression. Current repeated full module-boundary and structure gates passed;
+OpenAPI generation succeeded (822091-byte document). T4 and portable worker
+verification are still running, and candidate review remains pending.
+
+Portable guest PRE proof passed19 cases (27 deselected, 18.68s;
+`/tmp/submission-source-codec-worker.log`). The combined source/receipt/port/wire
+regression selection passed105 cases (168 deselected, 25.32s;
+`/tmp/submission-source-codec-final-pure.log`). This includes the owner-context
+requirement, omission of the InitVar from retained request fields and the prior
+float serialization representation. The original failed T4 collection run did
+clean its isolated database; its metadata is not a pass receipt. The repaired
+T4 replay remains in progress under `/tmp/submission-source-codec-t4-replay.*`.
+
+The CI-repair implementation is being frozen as a review candidate after passing
+module-boundary, structure, Ruff, OpenAPI and documentation checks, 105 focused
+source/receipt cases and 19 portable PRE-worker cases. Latest fetched main is
+94334ccf4 with zero missing upstream commits. PostgreSQL T4 replay is still live;
+original/recovery finalizer composition tests and frozen architecture/security,
+QA/test-delta and docs/CI reviews remain required before pushing this repair.
+This candidate commit does not mark the full submission initiative complete or
+the single draft PR ready. The public API/client/downstream/cleanup/provider
+work listed in the implementation snapshot remains in scope.
diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py
index d95c9dda5..ba3bd1f1a 100644
--- a/backend/app/adapters/artifacts/__init__.py
+++ b/backend/app/adapters/artifacts/__init__.py
@@ -908,3 +908,97 @@ def submission_intake_pre_source_port(session):
     from app.modules.artifacts.intake.repository import SubmissionIntakeRepository
 
     return SubmissionIntakeRepository(session, intake_task_custody_port(session))
+
+
+def selected_pre_submit_source_contracts():
+    """Construct ART's pure validator for CHECKERS without storage authority."""
+    from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts
+
+    return ArtifactPreSubmitSourceContracts()
+
+
+def selected_pre_submit_source_guard(session):
+    """Compose CHECKERS' consumer guard using ART's current custody owner."""
+    from app.modules.artifacts.selected_pre_submit_source_custody import SelectedPreSubmitSourceCustody
+
+    return SelectedPreSubmitSourceCustody(submission_intake_pre_source_port(session))
+
+
+def accepted_submission_finalizer(*, sessions, settings, store, lease_duration, invocation):
+    """One T5 composition for original delivery and authorized recovery."""
+    from app.core.identifiers import new_record_id
+    from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
+    from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from app.adapters.tasks import accepted_submission_creation_service, intake_task_custody_port
+
+    operation_id = invocation.envelope.aggregate_id
+    def submissions(session):
+        return accepted_submission_creation_service(session, settings=settings,
+            admissions=submission_admission_consumption_port(session,
+                request_id=new_record_id(), correlation_id=operation_id))
+    return AcceptedSubmissionFinalization(
+        sessions, tasks=intake_task_custody_port, submissions=submissions,
+        checkers=selected_pre_submit_coordinator, store=store, lease_duration=lease_duration,
+        authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
+            session, request_id=new_record_id(), correlation_id=operation_id),
+        delivery=invocation,
+    )
+
+
+def submission_finalization_handler(*, sessions, settings, store, lease_duration):
+    from app.modules.artifacts.intake.finalization_delivery import (
+        FinalizationInvocation, SubmissionFinalizationHandler,
+    )
+    from app.adapters.outbox import committed_invocation_reader, outbox_invocation_fence
+    return SubmissionFinalizationHandler(
+        observer=committed_invocation_reader(sessions),
+        finalizer=lambda envelope: accepted_submission_finalizer(
+            sessions=sessions, settings=settings, store=store, lease_duration=lease_duration,
+            invocation=FinalizationInvocation(envelope, outbox_invocation_fence)),
+    )
+
+
+def submission_finalization_recovery_handler(*, sessions, settings, store, lease_duration):
+    from app.adapters.auth import submission_recovery_cause_authorization
+    from app.adapters.outbox import finalized_unknown_deliveries
+    from app.modules.artifacts.intake.recovery_delivery import SubmissionFinalizationRecoveryHandler
+    return SubmissionFinalizationRecoveryHandler(
+        sessions=sessions, deliveries=finalized_unknown_deliveries,
+        authorization=submission_recovery_cause_authorization,
+        finalizer=lambda invocation: accepted_submission_finalizer(
+            sessions=sessions, settings=settings, store=store, lease_duration=lease_duration,
+            invocation=invocation),
+    )
+
+
+class _WorkerSourceObservation:
+    """Initialize the provider only when an unfinalized operation needs metadata."""
+
+    async def observe_sealed_source(self, source):
+        from app.adapters.artifacts.internal_workers import (
+            _artifact_internal_runtime, _artifact_worker_database,
+            initialize_artifact_internal_runtime,
+        )
+        async with _artifact_worker_database():
+            await initialize_artifact_internal_runtime()
+            with _artifact_internal_runtime() as (store, _namespace):
+                return await store.observe_sealed_source(source)
+
+
+def worker_submission_finalization_handler(*, sessions, delivery_options):
+    from datetime import timedelta
+    from app.core.config import get_settings
+    return submission_finalization_handler(
+        sessions=sessions, settings=get_settings(), store=_WorkerSourceObservation(),
+        lease_duration=timedelta(seconds=delivery_options.lease_seconds),
+    )
+
+
+def worker_submission_finalization_recovery_handler(*, sessions, delivery_options):
+    from datetime import timedelta
+    from app.core.config import get_settings
+    return submission_finalization_recovery_handler(
+        sessions=sessions, settings=get_settings(), store=_WorkerSourceObservation(),
+        lease_duration=timedelta(seconds=delivery_options.lease_seconds),
+    )
diff --git a/backend/app/adapters/artifacts/finalization.py b/backend/app/adapters/artifacts/finalization.py
deleted file mode 100644
index 124d7d247..000000000
--- a/backend/app/adapters/artifacts/finalization.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""Compose accepted finalization through the existing TASK/ART/CHECKERS owners."""
-
-from datetime import timedelta
-
-from app.core.identifiers import new_record_id
-from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
-from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
-from app.modules.artifacts.intake.finalization_delivery import (
-    FinalizationInvocation, SubmissionFinalizationHandler,
-)
-
-
-def accepted_submission_finalizer(*, sessions, settings, store, lease_duration, invocation):
-    """One T5 composition for original delivery and authorized recovery."""
-    from app.adapters.artifacts import submission_admission_consumption_port
-    from app.adapters.checkers import selected_pre_submit_coordinator
-    from app.adapters.tasks import accepted_submission_creation_service, intake_task_custody_port
-
-    operation_id = invocation.envelope.aggregate_id
-    def submissions(session):
-        return accepted_submission_creation_service(session, settings=settings,
-            admissions=submission_admission_consumption_port(session,
-                request_id=new_record_id(), correlation_id=operation_id))
-    return AcceptedSubmissionFinalization(
-        sessions, tasks=intake_task_custody_port, submissions=submissions,
-        checkers=selected_pre_submit_coordinator, store=store, lease_duration=lease_duration,
-        authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
-            session, request_id=new_record_id(), correlation_id=operation_id),
-        delivery=invocation,
-    )
-
-
-def submission_finalization_handler(*, sessions, settings, store, lease_duration):
-    from app.adapters.outbox import committed_invocation_reader, outbox_invocation_fence
-    return SubmissionFinalizationHandler(
-        observer=committed_invocation_reader(sessions),
-        finalizer=lambda envelope: accepted_submission_finalizer(
-            sessions=sessions, settings=settings, store=store, lease_duration=lease_duration,
-            invocation=FinalizationInvocation(envelope, outbox_invocation_fence)),
-    )
-
-
-def submission_finalization_recovery_handler(*, sessions, settings, store, lease_duration):
-    from app.adapters.auth import submission_recovery_cause_authorization
-    from app.adapters.outbox import finalized_unknown_deliveries
-    from app.modules.artifacts.intake.recovery_delivery import SubmissionFinalizationRecoveryHandler
-    return SubmissionFinalizationRecoveryHandler(
-        sessions=sessions, deliveries=finalized_unknown_deliveries,
-        authorization=submission_recovery_cause_authorization,
-        finalizer=lambda invocation: accepted_submission_finalizer(
-            sessions=sessions, settings=settings, store=store, lease_duration=lease_duration,
-            invocation=invocation),
-    )
-
-
-class _WorkerSourceObservation:
-    """Initialize the provider only when an unfinalized operation needs metadata."""
-
-    async def observe_sealed_source(self, source):
-        from app.adapters.artifacts.internal_workers import (
-            _artifact_internal_runtime, _artifact_worker_database,
-            initialize_artifact_internal_runtime,
-        )
-        async with _artifact_worker_database():
-            await initialize_artifact_internal_runtime()
-            with _artifact_internal_runtime() as (store, _namespace):
-                return await store.observe_sealed_source(source)
-
-
-def worker_submission_finalization_handler(*, sessions, delivery_options):
-    from app.core.config import get_settings
-    return submission_finalization_handler(
-        sessions=sessions, settings=get_settings(), store=_WorkerSourceObservation(),
-        lease_duration=timedelta(seconds=delivery_options.lease_seconds),
-    )
-
-
-def worker_submission_finalization_recovery_handler(*, sessions, delivery_options):
-    from app.core.config import get_settings
-    return submission_finalization_recovery_handler(
-        sessions=sessions, settings=get_settings(), store=_WorkerSourceObservation(),
-        lease_duration=timedelta(seconds=delivery_options.lease_seconds),
-    )
diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py
index 59a137d36..ebe3ece1f 100644
--- a/backend/app/adapters/checkers/__init__.py
+++ b/backend/app/adapters/checkers/__init__.py
@@ -57,6 +57,7 @@ def external_checker_execution_factory(
     *, socket_path: Path, timeout_seconds: float
 ) -> ExternalServiceAdapterFactory[UnixSocketExternalCheckerAdapter]:
     """Compose the sole instance-local external checker adapter factory."""
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
     factory = ExternalServiceAdapterFactory[UnixSocketExternalCheckerAdapter](
         EXTERNAL_CHECKER_CAPABILITY_KEY
     )
@@ -65,6 +66,7 @@ def external_checker_execution_factory(
         lambda: UnixSocketExternalCheckerAdapter(
             socket_path=socket_path,
             timeout_seconds=timeout_seconds,
+            source_contracts=selected_pre_submit_source_contracts(),
         ),
     )
     return factory
@@ -267,8 +269,9 @@ def external_checker_registry_service(session, authority):
 
 def selected_pre_submit_coordinator(session):
     """Compose selected PRE custody through CHECKERS' public adapter root."""
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
     from app.adapters.tasks import selected_pre_submit_task_guard
-    from app.adapters.artifacts import submission_intake_pre_source_port
+    from app.adapters.artifacts import selected_pre_submit_source_guard
     from app.modules.checkers.selected_pre_submit_coordination import (
         SelectedPreSubmitCoordinator,
     )
@@ -276,7 +279,8 @@ def selected_pre_submit_coordinator(session):
     return SelectedPreSubmitCoordinator(
         session,
         tasks=selected_pre_submit_task_guard(session),
-        sources=submission_intake_pre_source_port(session),
+        sources=selected_pre_submit_source_guard(session),
+        source_contracts=selected_pre_submit_source_contracts(),
     )
 
 
@@ -288,7 +292,8 @@ def __init__(self, *, external_execution: ExternalCheckerExecutionAdapter) -> No
 
     def build(self, lease: SelectedPreSubmitLeaseFacts) -> SelectedPreSubmitProcessor:
         """Bind the single invocation to the committed CHECKERS lease."""
-        return SelectedPreSubmitProcessor(lease=lease, execution=self._external_execution)
+        from app.adapters.artifacts import selected_pre_submit_source_contracts
+        return SelectedPreSubmitProcessor(lease=lease, execution=self._external_execution, source_contracts=selected_pre_submit_source_contracts())
 
 
 def checker_history_repository(session) -> CheckerHistoryReadPort:
@@ -658,9 +663,10 @@ def executor(child, original, payload, request):
 
 def selected_pre_submit_run_reader(session):
     """Read retained selected PRE runs for their own contributor; the caller authorizes."""
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
     from app.modules.checkers.selected_pre_submit_reads import SelectedPreSubmitRunReader
 
-    return SelectedPreSubmitRunReader(session)
+    return SelectedPreSubmitRunReader(session, source_contracts=selected_pre_submit_source_contracts())
 
 
 def trial_evidence_reservations(session, request, profiles):
diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index 87f6c948b..223a7b07e 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.modules.checkers.api.source_contracts import SelectedPreSubmitSourceContracts
+
 import asyncio
 import json
 import hashlib
@@ -58,7 +60,7 @@
 class UnixSocketExternalCheckerAdapter:
     """Speak one length-framed strict request over a private Unix socket."""
 
-    def __init__(self, *, socket_path: Path, timeout_seconds: float) -> None:
+    def __init__(self, *, socket_path: Path, timeout_seconds: float, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         """Validate immutable local transport settings without opening the socket."""
         if (
             not socket_path.is_absolute()
@@ -67,6 +69,7 @@ def __init__(self, *, socket_path: Path, timeout_seconds: float) -> None:
             or not 0.1 <= timeout_seconds <= 3_700.0
         ):
             raise ValueError("external checker service configuration is invalid")
+        self._source_contracts = source_contracts
         self._socket_path = socket_path
         self._timeout_seconds = timeout_seconds
         self._identity = ExternalServiceAdapterIdentity(
@@ -143,10 +146,10 @@ async def execute_pre(
             if type(body) is not dict or "adapter_provider_key" in body:
                 raise ValueError("PRE provider context is invalid")
             body["adapter_provider_key"] = self.identity.provider_key
-            result = SelectedPreSubmitInvocationResult.from_canonical_body(body)
+            result = SelectedPreSubmitInvocationResult.from_canonical_body(body, source_contracts=self._source_contracts)
             if result.receipt.runtime.provider != "smolvm":
                 raise ValueError("PRE runtime provider differs")
-            result.validate_lease(lease)
+            result.validate_lease(lease, source_contracts=self._source_contracts)
             if (asyncio.get_running_loop().time() >= deadline
                     or datetime.now(timezone.utc) >= lease.lease_expires_at):
                 raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded")
diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py
index 6cb333dcb..1d410cbf0 100644
--- a/backend/app/adapters/outbox/__init__.py
+++ b/backend/app/adapters/outbox/__init__.py
@@ -46,7 +46,7 @@ def outbox_delivery(
 def production_outbox_delivery(session_factory, *, finalization_worker: bool | None = None):
     """Compose all handlers for discovery, or one explicit worker group for delivery."""
     from app.adapters.artifacts import worker_post_submission_materialization
-    from app.adapters.artifacts.finalization import (
+    from app.adapters.artifacts import (
         worker_submission_finalization_handler, worker_submission_finalization_recovery_handler,
     )
     from app.modules.artifacts.api.submission_recovery import FINALIZATION_RECOVERY_EVENT
diff --git a/backend/app/core/hashing.py b/backend/app/core/hashing.py
index 4e90eccf5..88bfafacd 100644
--- a/backend/app/core/hashing.py
+++ b/backend/app/core/hashing.py
@@ -24,3 +24,14 @@ def canonical_json_hash(value: dict[str, Any]) -> str:
         allow_nan=False,
     ).encode("utf-8")
     return f"sha256:{hashlib.sha256(encoded).hexdigest()}"
+
+
+def validate_sha256(sha256: str) -> None:
+    """Require one canonical lower-case SHA-256 commitment."""
+    if (
+        not isinstance(sha256, str)
+        or len(sha256) != 71
+        or not sha256.startswith("sha256:")
+        or any(character not in "0123456789abcdef" for character in sha256[7:])
+    ):
+        raise ValueError("artifact commitment digest is invalid")
diff --git a/backend/app/modules/artifacts/api/submission_archive.py b/backend/app/modules/artifacts/api/submission_archive.py
index 1f0698be7..40fc309b1 100644
--- a/backend/app/modules/artifacts/api/submission_archive.py
+++ b/backend/app/modules/artifacts/api/submission_archive.py
@@ -5,6 +5,7 @@
 from dataclasses import dataclass
 from enum import StrEnum
 import math
+import unicodedata
 
 
 # Compressed intake ceiling; expanded content has its own inspection limit.
@@ -97,31 +98,47 @@ def __post_init__(self) -> None:
         ):
             raise ValueError("submission archive deadline is invalid")
 
-
-def validate_submission_manifest(
-    body: object, *, sha256: str, limits: SubmissionArchiveLimits,
-) -> SubmissionArchiveInspectionResult:
-    """Validate reported canonical metadata without claiming observation of bytes.
-
-    Reuse ART's manifest semantics and the invocation's stricter resource limits.
-    Source integrity still requires a trusted loader receipt.
-    """
-    from app.modules.artifacts.submission_manifest import SubmissionManifest
-    from app.modules.artifacts.submission_archive import normalize_submission_archive_path
-
-    manifest = SubmissionManifest.from_dict(body, sha256=sha256)
-    if (manifest.entry_count > limits.maximum_entries
-            or manifest.total_expanded_bytes > limits.maximum_expanded_bytes):
-        raise ValueError("submission manifest exceeds execution limits")
-    for entry in manifest.entries:
-        if entry.byte_count > limits.maximum_entry_bytes:
-            raise ValueError("submission manifest exceeds execution limits")
-        normalize_submission_archive_path(
-            entry.normalized_path, maximum_path_bytes=limits.maximum_path_bytes,
-            maximum_path_depth=limits.maximum_path_depth,
-        )
-    return SubmissionArchiveInspectionResult(
-        entries=manifest.entries, entry_count=manifest.entry_count,
-        file_count=manifest.file_count, directory_count=manifest.directory_count,
-        total_expanded_bytes=manifest.total_expanded_bytes,
-    )
+    def canonical_body(self) -> dict[str, int | float]:
+        """Serialize all bounds with the existing invocation-wire field names."""
+        return {
+            "maximum_entries": self.maximum_entries,
+            "maximum_path_bytes": self.maximum_path_bytes,
+            "maximum_path_depth": self.maximum_path_depth,
+            "maximum_central_directory_bytes": self.maximum_central_directory_bytes,
+            "maximum_entry_bytes": self.maximum_entry_bytes,
+            "maximum_expanded_bytes": self.maximum_expanded_bytes,
+            "maximum_compression_ratio": self.maximum_compression_ratio,
+            "maximum_inspection_seconds": float(self.maximum_inspection_seconds),
+        }
+
+
+def normalize_submission_archive_path(
+    path: str, *, maximum_path_bytes: int, maximum_path_depth: int,
+) -> str:
+    """Apply the same path rules to inspected and recovered manifest entries."""
+    parts = path.split("/")
+    normalized = unicodedata.normalize("NFC", path)
+    if (
+        not path or "\\" in path or path.startswith("/")
+        or any(ord(character) < 32 or ord(character) == 127 for character in path)
+        or any(part in {"", ".", ".."} or part.endswith((" ", ".")) for part in parts)
+        or ":" in parts[0] or len(parts) > maximum_path_depth
+        or max(len(path.encode("utf-8")), len(normalized.encode("utf-8"))) > maximum_path_bytes
+    ):
+        raise SubmissionArchiveRejectedError(SubmissionArchiveFailureCode.UNSAFE_ENTRY)
+    return normalized
+
+
+def validate_submission_archive_inventory(entries: tuple[SubmissionArchiveEntry, ...]) -> None:
+    """Require one unambiguous path per entry and exact directory ancestry."""
+    kinds = {entry.normalized_path: entry.entry_type for entry in entries}
+    folded_paths: set[str] = set()
+    for entry in entries:
+        folded = unicodedata.normalize("NFC", entry.normalized_path).casefold()
+        if folded in folded_paths:
+            raise SubmissionArchiveRejectedError(SubmissionArchiveFailureCode.COLLISION)
+        folded_paths.add(folded)
+        parts = entry.normalized_path.split("/")
+        for depth in range(1, len(parts)):
+            if kinds.get("/".join(parts[:depth])) is not SubmissionArchiveEntryType.DIRECTORY:
+                raise SubmissionArchiveRejectedError(SubmissionArchiveFailureCode.COLLISION)
diff --git a/backend/app/modules/artifacts/api/submission_manifest.py b/backend/app/modules/artifacts/api/submission_manifest.py
new file mode 100644
index 000000000..837b6b0a0
--- /dev/null
+++ b/backend/app/modules/artifacts/api/submission_manifest.py
@@ -0,0 +1,198 @@
+"""Canonical manifest facts and validation shared with trusted intake."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from app.core.hashing import canonical_json_hash, validate_sha256
+from app.modules.artifacts.api.submission_admission import SubmissionBundleFile
+from app.modules.artifacts.api.submission_archive import (
+    SubmissionArchiveEntry, SubmissionArchiveEntryType,
+    SubmissionArchiveInspectionResult, SubmissionArchiveLimits,
+    normalize_submission_archive_path, validate_submission_archive_inventory,
+)
+
+SUBMISSION_MANIFEST_SCHEMA_VERSION = "workstream.submission_bundle_manifest.v1"
+
+
+@dataclass(frozen=True, slots=True)
+class SubmissionManifest:
+    """Closed canonical semantic manifest derived from inspected bytes."""
+
+    sha256: str
+    entries: tuple[SubmissionArchiveEntry, ...]
+    entry_count: int
+    file_count: int
+    directory_count: int
+    total_expanded_bytes: int
+
+    def __post_init__(self) -> None:
+        """Reject mutable, incomplete, or self-inconsistent manifest facts."""
+        if type(self.entries) is not tuple or tuple(
+            sorted(self.entries, key=lambda entry: entry.normalized_path)
+        ) != self.entries:
+            raise ValueError("submission manifest entries are not canonical")
+        for entry in self.entries:
+            if type(entry) is not SubmissionArchiveEntry:
+                raise ValueError("submission manifest entry is invalid")
+            if entry.entry_type is SubmissionArchiveEntryType.DIRECTORY:
+                if entry.byte_count != 0 or entry.sha256 is not None or entry.executable is not None:
+                    raise ValueError("submission directory identity is invalid")
+            elif (
+                entry.entry_type is not SubmissionArchiveEntryType.FILE
+                or entry.byte_count < 0
+                or type(entry.executable) is not bool
+                or entry.sha256 is None
+            ):
+                raise ValueError("submission file identity is incomplete")
+            else:
+                validate_sha256(entry.sha256)
+        validate_submission_archive_inventory(self.entries)
+        files = sum(
+            entry.entry_type is SubmissionArchiveEntryType.FILE for entry in self.entries
+        )
+        if (
+            self.entry_count != len(self.entries)
+            or self.file_count != files
+            or self.directory_count != len(self.entries) - files
+            or self.total_expanded_bytes
+            != sum(entry.byte_count for entry in self.entries)
+        ):
+            raise ValueError("submission manifest aggregates are inconsistent")
+        validate_sha256(self.sha256)
+        if canonical_json_hash(self.as_dict()) != self.sha256:
+            raise ValueError("submission manifest digest is inconsistent")
+
+    def file_facts(self) -> tuple[SubmissionBundleFile, ...]:
+        """Project every verified file for both capacity preflight and consumption."""
+        return tuple(SubmissionBundleFile(
+            normalized_path=item.normalized_path, sha256=item.sha256, byte_count=item.byte_count,
+        ) for item in self.entries if item.entry_type is SubmissionArchiveEntryType.FILE)
+
+    @property
+    def schema_version(self) -> str:
+        """Return the fixed closed-schema version."""
+        return SUBMISSION_MANIFEST_SCHEMA_VERSION
+
+    def as_dict(self) -> dict[str, Any]:
+        """Return a fresh JSON-compatible closed manifest body."""
+        return _manifest_body(self.entries)
+
+    @classmethod
+    def from_dict(cls, body: object, *, sha256: str) -> SubmissionManifest:
+        """Recover the sole canonical manifest, checking closed stored metadata."""
+        if (
+            type(body) is not dict
+            or set(body) != {"schema_version", "entries"}
+            or body["schema_version"] != SUBMISSION_MANIFEST_SCHEMA_VERSION
+            or type(body["entries"]) is not list
+            or len(body["entries"]) > 100_000
+        ):
+            raise ValueError("submission manifest body is invalid")
+        entries = []
+        paths = set()
+        for value in body["entries"]:
+            if type(value) is not dict:
+                raise ValueError("submission manifest entry is invalid")
+            kind = value.get("entry_type")
+            fields = {"normalized_path", "entry_type"}
+            if kind == "file":
+                fields |= {"sha256", "byte_count", "executable"}
+            elif kind != "directory":
+                raise ValueError("submission manifest entry is invalid")
+            path = value.get("normalized_path")
+            if set(value) != fields or type(path) is not str or not path or path in paths:
+                raise ValueError("submission manifest entry is invalid")
+            if normalize_submission_archive_path(
+                path, maximum_path_bytes=4096, maximum_path_depth=256,
+            ) != path:
+                raise ValueError("submission manifest path is not normalized")
+            paths.add(path)
+            size = value["byte_count"] if kind == "file" else 0
+            if type(size) is not int or not 0 <= size <= 512 * 1024 * 1024:
+                raise ValueError("submission manifest file size is invalid")
+            entries.append(SubmissionArchiveEntry(
+                normalized_path=path, entry_type=SubmissionArchiveEntryType(kind),
+                byte_count=size, sha256=value.get("sha256"), executable=value.get("executable"),
+            ))
+        files = sum(entry.entry_type is SubmissionArchiveEntryType.FILE for entry in entries)
+        expanded = sum(entry.byte_count for entry in entries)
+        if expanded > 512 * 1024 * 1024:
+            raise ValueError("submission manifest expansion is invalid")
+        return cls(
+            sha256=sha256, entries=tuple(entries), entry_count=len(entries),
+            file_count=files, directory_count=len(entries) - files,
+            total_expanded_bytes=expanded,
+        )
+
+
+def build_submission_manifest(
+    inspection: SubmissionArchiveInspectionResult,
+) -> SubmissionManifest:
+    """Build the sole canonical JSON identity from a validated archive read."""
+    entries = tuple(sorted(inspection.entries, key=lambda entry: entry.normalized_path))
+    for entry in entries:
+        if entry.entry_type is SubmissionArchiveEntryType.FILE and (
+            entry.sha256 is None or entry.executable is None
+        ):
+            raise ValueError("submission file identity is incomplete")
+    body = _manifest_body(entries)
+    return SubmissionManifest(
+        sha256=canonical_json_hash(body),
+        entries=entries,
+        entry_count=inspection.entry_count,
+        file_count=inspection.file_count,
+        directory_count=inspection.directory_count,
+        total_expanded_bytes=inspection.total_expanded_bytes,
+    )
+
+
+def _manifest_body(entries: tuple[SubmissionArchiveEntry, ...]) -> dict[str, Any]:
+    """Project immutable entries into the one closed canonical JSON shape."""
+    body_entries: list[dict[str, object]] = []
+    for entry in entries:
+        if entry.entry_type is SubmissionArchiveEntryType.DIRECTORY:
+            body_entries.append(
+                {"normalized_path": entry.normalized_path, "entry_type": "directory"}
+            )
+            continue
+        body_entries.append(
+            {
+                "normalized_path": entry.normalized_path,
+                "entry_type": "file",
+                "sha256": entry.sha256,
+                "byte_count": entry.byte_count,
+                "executable": entry.executable,
+            }
+        )
+    return {
+        "schema_version": SUBMISSION_MANIFEST_SCHEMA_VERSION,
+        "entries": body_entries,
+    }
+
+
+def validate_submission_manifest(
+    body: object, *, sha256: str, limits: SubmissionArchiveLimits,
+) -> SubmissionArchiveInspectionResult:
+    """Validate reported canonical metadata without claiming observation of bytes.
+
+    Reuse ART's manifest semantics and the invocation's stricter resource limits.
+    Source integrity still requires a trusted loader receipt.
+    """
+
+    manifest = SubmissionManifest.from_dict(body, sha256=sha256)
+    if (manifest.entry_count > limits.maximum_entries
+            or manifest.total_expanded_bytes > limits.maximum_expanded_bytes):
+        raise ValueError("submission manifest exceeds execution limits")
+    for entry in manifest.entries:
+        if entry.byte_count > limits.maximum_entry_bytes:
+            raise ValueError("submission manifest exceeds execution limits")
+        normalize_submission_archive_path(
+            entry.normalized_path, maximum_path_bytes=limits.maximum_path_bytes,
+            maximum_path_depth=limits.maximum_path_depth,
+        )
+    return SubmissionArchiveInspectionResult(
+        entries=manifest.entries, entry_count=manifest.entry_count,
+        file_count=manifest.file_count, directory_count=manifest.directory_count,
+        total_expanded_bytes=manifest.total_expanded_bytes,
+    )
diff --git a/backend/app/modules/artifacts/authorization.py b/backend/app/modules/artifacts/authorization.py
index b986dc790..9ead6ae5d 100644
--- a/backend/app/modules/artifacts/authorization.py
+++ b/backend/app/modules/artifacts/authorization.py
@@ -30,9 +30,9 @@
 )
 from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts
 from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts
-from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationAuthorityFacts
-from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.api.submission_finalization import SubmissionFinalizationResourceContext
 
 from app.modules.artifacts.submission_bindings import SubmissionBindingAuthorityFacts
 from app.modules.artifacts.api import SubmissionAdmissionConsumptionError
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index aaa068825..e88bf4fab 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -286,8 +286,13 @@ async def _accept_new(self, session, authority, repository, row, owner,
         draft.acceptance_decision_id = str(await authority.consume_acceptance(
             await authority.prepare_acceptance(facts), facts))
         draft.finalization_event_id = str((await outbox(session).append(finalization_event(draft))).event_id)
-        for name, value in vars(draft).items():
-            setattr(row, name, value)
+        for name in (
+            "accepted_at", "selected_pre_submit_run_id", "selected_pre_submit_request_sha256",
+            "selected_pre_submit_terminal_sha256", "accepted_source_sha256", "accepted_manifest_sha256",
+            "accepted_context", "accepted_context_sha256", "acceptance_receipt", "acceptance_receipt_sha256",
+            "acceptance_decision_id", "finalization_event_id",
+        ):
+            setattr(row, name, getattr(draft, name))
         row.state = "finalization_pending"
         await self._tasks(session).accept(UUID(row.task_id), UUID(row.id), row.eligible_task_status)
         return dict(row.acceptance_receipt)
diff --git a/backend/app/modules/artifacts/post_submit_materialization.py b/backend/app/modules/artifacts/post_submit_materialization.py
index e0906cd9b..a2ba6e26b 100644
--- a/backend/app/modules/artifacts/post_submit_materialization.py
+++ b/backend/app/modules/artifacts/post_submit_materialization.py
@@ -66,7 +66,9 @@
 from app.modules.artifacts.submission_archive import (
     exported_submission_tree,
 )
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 from app.modules.checkers.api.evaluation_contract import (
     PostSubmissionExecutionResult,
     validate_execution_result,
diff --git a/backend/app/modules/artifacts/preparation.py b/backend/app/modules/artifacts/preparation.py
index 301b38e7b..0392b8a3e 100644
--- a/backend/app/modules/artifacts/preparation.py
+++ b/backend/app/modules/artifacts/preparation.py
@@ -39,7 +39,10 @@
     PreparedArtifact,
     PreparedArtifactInspector,
 )
-from app.modules.artifacts.submission_manifest import SubmissionManifest
+from app.core.hashing import validate_sha256
+from app.modules.artifacts.api.submission_manifest import (
+    SubmissionManifest,
+)
 
 
 HARD_MAXIMUM_ARTIFACT_BYTES = 512 * 1024 * 1024
@@ -2732,7 +2735,7 @@ def _validate_client_commitment(
             raise ArtifactInputMismatchError("artifact media type is invalid") from None
         if expected_sha256 is not None:
             try:
-                ArtifactCommitment.validate_sha256(expected_sha256)
+                validate_sha256(expected_sha256)
             except ValueError:
                 raise ArtifactInputMismatchError("artifact expected digest is invalid") from None
         if expected_size is not None:
diff --git a/backend/app/modules/artifacts/selected_pre_submit_admission.py b/backend/app/modules/artifacts/selected_pre_submit_admission.py
index fc07b32dd..c966d7300 100644
--- a/backend/app/modules/artifacts/selected_pre_submit_admission.py
+++ b/backend/app/modules/artifacts/selected_pre_submit_admission.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts
+
 from dataclasses import dataclass
 from uuid import UUID
 
@@ -206,6 +208,7 @@ def build_selected_pre_submit_reservation(
         pre_deadline_at=source.pre_deadline_at, policy=selected.policy,
         default_context=selected.default_context, runtime_profile=runtime_profile,
         admission_lineage=lineage,
+        source_contracts=ArtifactPreSubmitSourceContracts(),
     )
 
 
diff --git a/backend/app/modules/artifacts/selected_pre_submit_execution.py b/backend/app/modules/artifacts/selected_pre_submit_execution.py
index bb297fa8b..d1c08814a 100644
--- a/backend/app/modules/artifacts/selected_pre_submit_execution.py
+++ b/backend/app/modules/artifacts/selected_pre_submit_execution.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts
+
 import asyncio
 from collections.abc import AsyncGenerator, AsyncIterator
 from contextlib import asynccontextmanager
@@ -214,14 +216,14 @@ async def execute(self, *, reservation: SelectedPreSubmitReservationFacts) -> Se
             capability = await self._coordinator.committed_execution(run_id=run_id, lease=lease)
             async with self._source_reads.issue(lease=lease, execution_authority=capability) as grant:
                 result = await self._execution.build(lease).process(grant)
-                result.validate_lease(lease)
+                result.validate_lease(lease, source_contracts=ArtifactPreSubmitSourceContracts())
                 if result.receipt.outcome == "cancelled":
                     raise asyncio.CancelledError
                 execution, receipt = result.execution, result.receipt
                 failure = receipt.reason if execution is None else None
         except SelectedPreSubmitInfrastructureUnavailable as exc:
             failure = exc.code
-        facts = SelectedPreSubmitFinalizeFacts(lease=lease, execution=execution, invocation_receipt=receipt, infrastructure_failure_code=failure)
+        facts = SelectedPreSubmitFinalizeFacts(lease=lease, execution=execution, invocation_receipt=receipt, infrastructure_failure_code=failure, source_contracts=ArtifactPreSubmitSourceContracts())
         async with self._session.begin():
             async with self._authority.prepare_finalization(facts) as prepared:
                 return await self._coordinator.finalize(
diff --git a/backend/app/modules/artifacts/selected_pre_submit_source_contracts.py b/backend/app/modules/artifacts/selected_pre_submit_source_contracts.py
new file mode 100644
index 000000000..390e32b6f
--- /dev/null
+++ b/backend/app/modules/artifacts/selected_pre_submit_source_contracts.py
@@ -0,0 +1,51 @@
+"""ART's pure validation implementation for the CHECKERS consumer port."""
+
+import json
+
+from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits
+from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
+from app.modules.artifacts.api.submission_manifest import validate_submission_manifest
+from app.modules.checkers.api.material import SubmissionMaterialEntry
+from app.modules.checkers.api.source_contracts import SubmissionArchiveLimitsView, SelectedPreSubmitSourceContracts
+
+
+class ArtifactPreSubmitSourceContracts(SelectedPreSubmitSourceContracts):
+    """Retain one canonical source, limits and manifest validator."""
+
+    def parse_source(self, body: object) -> SealedSubmissionSource:
+        value = SealedSubmissionSource.model_validate_json(json.dumps(body, allow_nan=False))
+        if value.model_dump(mode="json") != body:
+            raise ValueError("selected PRE source is not canonical")
+        return value
+
+    def require_source(self, source: object) -> SealedSubmissionSource:
+        if type(source) is not SealedSubmissionSource:
+            raise ValueError("selected PRE source type is invalid")
+        return SealedSubmissionSource.model_validate(source)
+
+    def parse_limits(self, body: object) -> SubmissionArchiveLimits:
+        if type(body) is not dict:
+            raise ValueError("selected PRE archive limits are invalid")
+        try:
+            limits = SubmissionArchiveLimits(**body)
+        except TypeError as exc:
+            raise ValueError("selected PRE archive limits are invalid") from exc
+        if limits.canonical_body() != body:
+            raise ValueError("selected PRE archive limits are not canonical")
+        return limits
+
+    def require_limits(self, limits: object) -> SubmissionArchiveLimits:
+        if type(limits) is not SubmissionArchiveLimits:
+            raise ValueError("selected PRE archive limits type is invalid")
+        return self.parse_limits(limits.canonical_body())
+
+    def validate_manifest(
+        self, body: object, *, sha256: str, limits: SubmissionArchiveLimitsView,
+    ) -> tuple[SubmissionMaterialEntry, ...]:
+        inspection = validate_submission_manifest(
+            body, sha256=sha256, limits=self.require_limits(limits),
+        )
+        return tuple(SubmissionMaterialEntry(
+            entry.normalized_path, entry.entry_type.value, entry.byte_count,
+            entry.sha256, entry.executable,
+        ) for entry in inspection.entries)
diff --git a/backend/app/modules/artifacts/selected_pre_submit_source_custody.py b/backend/app/modules/artifacts/selected_pre_submit_source_custody.py
new file mode 100644
index 000000000..a61e332cd
--- /dev/null
+++ b/backend/app/modules/artifacts/selected_pre_submit_source_custody.py
@@ -0,0 +1,37 @@
+"""ART implementation of CHECKERS' exact live-source consumer boundary."""
+
+from app.modules.artifacts.api.submission_intake import SubmissionIntakePreSourcePort
+from app.modules.checkers.api.selected_pre_submit import (
+    SelectedPreSubmitReservationFacts, SelectedPreSubmitUnavailable,
+)
+
+
+class SelectedPreSubmitSourceCustody:
+    """Compare immutable request facts while holding ART's current source lease."""
+
+    def __init__(self, sources: SubmissionIntakePreSourcePort) -> None:
+        self._sources = sources
+
+    async def lock_selected_pre_submit_source(
+        self, facts: SelectedPreSubmitReservationFacts,
+    ) -> None:
+        """Caller already holds TASK; preserve exact ART checks before CHECKERS."""
+        current = await self._sources.lock_pre_source(
+            source=facts.source, lease_id=facts.foreground_lease_id,
+            generation=facts.foreground_lease_generation,
+        )
+        if (
+            current.source != facts.source
+            or current.project_id != facts.project_id
+            or current.task_id != facts.task_id
+            or current.assignment_id != facts.assignment_id
+            or current.actor_profile_id != facts.actor_profile_id
+            or current.identity_link_id != facts.identity_link_id
+            or current.metadata_sha256 != facts.metadata_sha256
+            or current.locked_context_sha256 != facts.locked_context_sha256
+            or current.lease_id != facts.foreground_lease_id
+            or current.lease_generation != facts.foreground_lease_generation
+            or current.pre_deadline_at != facts.pre_deadline_at
+        ):
+            raise SelectedPreSubmitUnavailable("selected_pre_submit_source_changed")
+
diff --git a/backend/app/modules/artifacts/sources.py b/backend/app/modules/artifacts/sources.py
index bdb82f6da..85aad2258 100644
--- a/backend/app/modules/artifacts/sources.py
+++ b/backend/app/modules/artifacts/sources.py
@@ -7,6 +7,7 @@
 from dataclasses import dataclass
 from typing import BinaryIO, Protocol, TypeVar, final
 from uuid import UUID
+from app.core.hashing import validate_sha256
 from app.core.identifiers import new_record_id
 
 from app.core.cancellation import await_cancellation_resistant
@@ -24,8 +25,6 @@ def inspect(self, reader: BinaryIO) -> _InspectionResultCo:
         """Return bounded structural facts without retaining the reader."""
 
 
-
-
 class _PreparedArtifactOwner(Protocol):
     """Private lifecycle operations retained by one preparation service."""
 
@@ -78,21 +77,10 @@ class ArtifactCommitment:
 
     def __post_init__(self) -> None:
         """Reject noncanonical commitment facts."""
-        self.validate_sha256(self.sha256)
+        validate_sha256(self.sha256)
         self.validate_byte_count(self.byte_count)
         self.validate_media_type(self.media_type)
 
-    @staticmethod
-    def validate_sha256(sha256: str) -> None:
-        """Require one canonical lower-case SHA-256 commitment."""
-        if (
-            not isinstance(sha256, str)
-            or len(sha256) != 71
-            or not sha256.startswith("sha256:")
-            or any(character not in "0123456789abcdef" for character in sha256[7:])
-        ):
-            raise ValueError("artifact commitment digest is invalid")
-
     @staticmethod
     def validate_byte_count(byte_count: int) -> None:
         """Require one exact nonnegative byte count."""
diff --git a/backend/app/modules/artifacts/submission_admission.py b/backend/app/modules/artifacts/submission_admission.py
index cdad22c49..a8b857610 100644
--- a/backend/app/modules/artifacts/submission_admission.py
+++ b/backend/app/modules/artifacts/submission_admission.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts
+
 from collections.abc import Callable
 from contextlib import AbstractAsyncContextManager, AsyncExitStack
 import asyncio
@@ -60,9 +62,11 @@
     SubmissionBundlePreparationAuthorization,
 )
 from app.modules.artifacts.submission_custody import SubmissionBundlePreparedCustody
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 from app.modules.artifacts.submission_manifest import (
     SubmissionCanonicalPredecessor,
-    build_submission_manifest,
 )
 from app.modules.artifacts.submission_materialization import (
     PreparedBundleMaterializationRequest,
@@ -335,7 +339,8 @@ async def lock_retained_submission_parents(
             raise RuntimeError("submission verification TASK composition is unavailable")
         try:
             selected = SelectedPreSubmitReservationFacts.from_canonical_body(
-                row.selected_request_json
+                row.selected_request_json,
+                source_contracts=ArtifactPreSubmitSourceContracts(),
             )
         except (TypeError, ValueError) as exc:
             raise SubmissionBundleAdmissionPublicationError(
@@ -393,7 +398,8 @@ async def publish_verified(
             raise SubmissionBundleAdmissionPublicationError("external PRE durable intent is unavailable")
         try:
             selected = SelectedPreSubmitReservationFacts.from_canonical_body(
-                intent.selected_request_json
+                intent.selected_request_json,
+                source_contracts=ArtifactPreSubmitSourceContracts(),
             )
         except (TypeError, ValueError) as exc:
             raise SubmissionBundleAdmissionPublicationError(
diff --git a/backend/app/modules/artifacts/submission_archive.py b/backend/app/modules/artifacts/submission_archive.py
index a093b24d8..4d731d4dd 100644
--- a/backend/app/modules/artifacts/submission_archive.py
+++ b/backend/app/modules/artifacts/submission_archive.py
@@ -18,6 +18,8 @@
 
 from app.core.zip_safety import zip_directory_layout
 from app.modules.artifacts.api.submission_archive import (
+    normalize_submission_archive_path,
+    validate_submission_archive_inventory,
     SubmissionArchiveEntry,
     SubmissionArchiveEntryType,
     SubmissionArchiveFailureCode,
@@ -31,38 +33,6 @@
 _ProjectionResult = TypeVar("_ProjectionResult")
 
 
-def normalize_submission_archive_path(
-    path: str, *, maximum_path_bytes: int, maximum_path_depth: int,
-) -> str:
-    """Apply the same path rules to inspected and recovered manifest entries."""
-    parts = path.split("/")
-    normalized = unicodedata.normalize("NFC", path)
-    if (
-        not path or "\\" in path or path.startswith("/")
-        or any(ord(character) < 32 or ord(character) == 127 for character in path)
-        or any(part in {"", ".", ".."} or part.endswith((" ", ".")) for part in parts)
-        or ":" in parts[0] or len(parts) > maximum_path_depth
-        or max(len(path.encode("utf-8")), len(normalized.encode("utf-8"))) > maximum_path_bytes
-    ):
-        raise SubmissionArchiveRejectedError(SubmissionArchiveFailureCode.UNSAFE_ENTRY)
-    return normalized
-
-
-def validate_submission_archive_inventory(entries: tuple[SubmissionArchiveEntry, ...]) -> None:
-    """Require one unambiguous path per entry and exact directory ancestry."""
-    kinds = {entry.normalized_path: entry.entry_type for entry in entries}
-    folded_paths: set[str] = set()
-    for entry in entries:
-        folded = unicodedata.normalize("NFC", entry.normalized_path).casefold()
-        if folded in folded_paths:
-            raise SubmissionArchiveRejectedError(SubmissionArchiveFailureCode.COLLISION)
-        folded_paths.add(folded)
-        parts = entry.normalized_path.split("/")
-        for depth in range(1, len(parts)):
-            if kinds.get("/".join(parts[:depth])) is not SubmissionArchiveEntryType.DIRECTORY:
-                raise SubmissionArchiveRejectedError(SubmissionArchiveFailureCode.COLLISION)
-
-
 def _read_projected_file(
     root_fd: int,
     entries: tuple[SubmissionArchiveEntry, ...],
diff --git a/backend/app/modules/artifacts/submission_bindings.py b/backend/app/modules/artifacts/submission_bindings.py
index fd6facbc3..48f27de9a 100644
--- a/backend/app/modules/artifacts/submission_bindings.py
+++ b/backend/app/modules/artifacts/submission_bindings.py
@@ -18,7 +18,9 @@
     SubmissionAdmissionMaterial,
 )
 from app.modules.artifacts.api.submission_admission import ConsumedSubmissionAdmissionRequest
-from app.modules.artifacts.submission_manifest import SubmissionManifest
+from app.modules.artifacts.api.submission_manifest import (
+    SubmissionManifest,
+)
 from app.modules.checkers.api.external_policy import validate_stored_external_post_policy
 from app.modules.artifacts.models import (
     ArtifactBinding,
diff --git a/backend/app/modules/artifacts/submission_manifest.py b/backend/app/modules/artifacts/submission_manifest.py
index f9a9cfd39..b5ab4a51f 100644
--- a/backend/app/modules/artifacts/submission_manifest.py
+++ b/backend/app/modules/artifacts/submission_manifest.py
@@ -4,29 +4,16 @@
 
 from dataclasses import dataclass
 from enum import StrEnum
-from typing import Any
 from uuid import NAMESPACE_URL, UUID, uuid5
 
-from app.core.hashing import canonical_json_hash
-from app.modules.artifacts.api.submission_admission import SubmissionBundleFile
+from app.core.hashing import validate_sha256
+from app.modules.artifacts.api.submission_manifest import SubmissionManifest
 from app.modules.artifacts.sources import ArtifactCommitment
-from app.modules.artifacts.api.submission_archive import (
-    SubmissionArchiveEntry,
-    SubmissionArchiveEntryType,
-    SubmissionArchiveInspectionResult,
-)
-from app.modules.artifacts.submission_archive import (
-    normalize_submission_archive_path,
-    validate_submission_archive_inventory,
-)
-
-
-SUBMISSION_MANIFEST_SCHEMA_VERSION = "workstream.submission_bundle_manifest.v1"
 
 
 def semantic_manifest_identity(semantic_manifest_sha256: str) -> UUID:
     """Derive one provider-neutral identity from the canonical manifest digest."""
-    ArtifactCommitment.validate_sha256(semantic_manifest_sha256)
+    validate_sha256(semantic_manifest_sha256)
     return uuid5(
         NAMESPACE_URL,
         f"workstream:submission-semantic-manifest:v1:{semantic_manifest_sha256}",
@@ -72,119 +59,8 @@ def __post_init__(self) -> None:
             raise ValueError("submission predecessor id is invalid")
         if type(self.submission_version) is not int or self.submission_version <= 0:
             raise ValueError("submission predecessor version is invalid")
-        ArtifactCommitment.validate_sha256(self.archive_sha256)
-        ArtifactCommitment.validate_sha256(self.semantic_manifest_sha256)
-
-
-@dataclass(frozen=True, slots=True)
-class SubmissionManifest:
-    """Closed canonical semantic manifest derived from inspected bytes."""
-
-    sha256: str
-    entries: tuple[SubmissionArchiveEntry, ...]
-    entry_count: int
-    file_count: int
-    directory_count: int
-    total_expanded_bytes: int
-
-    def __post_init__(self) -> None:
-        """Reject mutable, incomplete, or self-inconsistent manifest facts."""
-        if type(self.entries) is not tuple or tuple(
-            sorted(self.entries, key=lambda entry: entry.normalized_path)
-        ) != self.entries:
-            raise ValueError("submission manifest entries are not canonical")
-        for entry in self.entries:
-            if type(entry) is not SubmissionArchiveEntry:
-                raise ValueError("submission manifest entry is invalid")
-            if entry.entry_type is SubmissionArchiveEntryType.DIRECTORY:
-                if entry.byte_count != 0 or entry.sha256 is not None or entry.executable is not None:
-                    raise ValueError("submission directory identity is invalid")
-            elif (
-                entry.entry_type is not SubmissionArchiveEntryType.FILE
-                or entry.byte_count < 0
-                or type(entry.executable) is not bool
-                or entry.sha256 is None
-            ):
-                raise ValueError("submission file identity is incomplete")
-            else:
-                ArtifactCommitment.validate_sha256(entry.sha256)
-        validate_submission_archive_inventory(self.entries)
-        files = sum(
-            entry.entry_type is SubmissionArchiveEntryType.FILE for entry in self.entries
-        )
-        if (
-            self.entry_count != len(self.entries)
-            or self.file_count != files
-            or self.directory_count != len(self.entries) - files
-            or self.total_expanded_bytes
-            != sum(entry.byte_count for entry in self.entries)
-        ):
-            raise ValueError("submission manifest aggregates are inconsistent")
-        ArtifactCommitment.validate_sha256(self.sha256)
-        if canonical_json_hash(self.as_dict()) != self.sha256:
-            raise ValueError("submission manifest digest is inconsistent")
-
-    def file_facts(self) -> tuple[SubmissionBundleFile, ...]:
-        """Project every verified file for both capacity preflight and consumption."""
-        return tuple(SubmissionBundleFile(
-            normalized_path=item.normalized_path, sha256=item.sha256, byte_count=item.byte_count,
-        ) for item in self.entries if item.entry_type is SubmissionArchiveEntryType.FILE)
-
-    @property
-    def schema_version(self) -> str:
-        """Return the fixed closed-schema version."""
-        return SUBMISSION_MANIFEST_SCHEMA_VERSION
-
-    def as_dict(self) -> dict[str, Any]:
-        """Return a fresh JSON-compatible closed manifest body."""
-        return _manifest_body(self.entries)
-
-    @classmethod
-    def from_dict(cls, body: object, *, sha256: str) -> SubmissionManifest:
-        """Recover the sole canonical manifest, checking closed stored metadata."""
-        if (
-            type(body) is not dict
-            or set(body) != {"schema_version", "entries"}
-            or body["schema_version"] != SUBMISSION_MANIFEST_SCHEMA_VERSION
-            or type(body["entries"]) is not list
-            or len(body["entries"]) > 100_000
-        ):
-            raise ValueError("submission manifest body is invalid")
-        entries = []
-        paths = set()
-        for value in body["entries"]:
-            if type(value) is not dict:
-                raise ValueError("submission manifest entry is invalid")
-            kind = value.get("entry_type")
-            fields = {"normalized_path", "entry_type"}
-            if kind == "file":
-                fields |= {"sha256", "byte_count", "executable"}
-            elif kind != "directory":
-                raise ValueError("submission manifest entry is invalid")
-            path = value.get("normalized_path")
-            if set(value) != fields or type(path) is not str or not path or path in paths:
-                raise ValueError("submission manifest entry is invalid")
-            if normalize_submission_archive_path(
-                path, maximum_path_bytes=4096, maximum_path_depth=256,
-            ) != path:
-                raise ValueError("submission manifest path is not normalized")
-            paths.add(path)
-            size = value["byte_count"] if kind == "file" else 0
-            if type(size) is not int or not 0 <= size <= 512 * 1024 * 1024:
-                raise ValueError("submission manifest file size is invalid")
-            entries.append(SubmissionArchiveEntry(
-                normalized_path=path, entry_type=SubmissionArchiveEntryType(kind),
-                byte_count=size, sha256=value.get("sha256"), executable=value.get("executable"),
-            ))
-        files = sum(entry.entry_type is SubmissionArchiveEntryType.FILE for entry in entries)
-        expanded = sum(entry.byte_count for entry in entries)
-        if expanded > 512 * 1024 * 1024:
-            raise ValueError("submission manifest expansion is invalid")
-        return cls(
-            sha256=sha256, entries=tuple(entries), entry_count=len(entries),
-            file_count=files, directory_count=len(entries) - files,
-            total_expanded_bytes=expanded,
-        )
+        validate_sha256(self.archive_sha256)
+        validate_sha256(self.semantic_manifest_sha256)
 
 
 @dataclass(frozen=True, slots=True)
@@ -198,51 +74,6 @@ class SubmissionChangeGateResult:
     predecessor: SubmissionCanonicalPredecessor | None
 
 
-def build_submission_manifest(
-    inspection: SubmissionArchiveInspectionResult,
-) -> SubmissionManifest:
-    """Build the sole canonical JSON identity from a validated archive read."""
-    entries = tuple(sorted(inspection.entries, key=lambda entry: entry.normalized_path))
-    for entry in entries:
-        if entry.entry_type is SubmissionArchiveEntryType.FILE and (
-            entry.sha256 is None or entry.executable is None
-        ):
-            raise ValueError("submission file identity is incomplete")
-    body = _manifest_body(entries)
-    return SubmissionManifest(
-        sha256=canonical_json_hash(body),
-        entries=entries,
-        entry_count=inspection.entry_count,
-        file_count=inspection.file_count,
-        directory_count=inspection.directory_count,
-        total_expanded_bytes=inspection.total_expanded_bytes,
-    )
-
-
-def _manifest_body(entries: tuple[SubmissionArchiveEntry, ...]) -> dict[str, Any]:
-    """Project immutable entries into the one closed canonical JSON shape."""
-    body_entries: list[dict[str, object]] = []
-    for entry in entries:
-        if entry.entry_type is SubmissionArchiveEntryType.DIRECTORY:
-            body_entries.append(
-                {"normalized_path": entry.normalized_path, "entry_type": "directory"}
-            )
-            continue
-        body_entries.append(
-            {
-                "normalized_path": entry.normalized_path,
-                "entry_type": "file",
-                "sha256": entry.sha256,
-                "byte_count": entry.byte_count,
-                "executable": entry.executable,
-            }
-        )
-    return {
-        "schema_version": SUBMISSION_MANIFEST_SCHEMA_VERSION,
-        "entries": body_entries,
-    }
-
-
 def evaluate_submission_change(
     *,
     commitment: ArtifactCommitment,
diff --git a/backend/app/modules/artifacts/submission_materialization.py b/backend/app/modules/artifacts/submission_materialization.py
index e0a72f659..e846cf3a4 100644
--- a/backend/app/modules/artifacts/submission_materialization.py
+++ b/backend/app/modules/artifacts/submission_materialization.py
@@ -32,11 +32,13 @@
     SubmissionArchiveInspectionResult,
     SubmissionArchiveLimits,
 )
-from app.modules.artifacts.submission_manifest import (
-    SubmissionChangeGateResult,
+from app.modules.artifacts.api.submission_manifest import (
     SubmissionManifest,
     build_submission_manifest,
 )
+from app.modules.artifacts.submission_manifest import (
+    SubmissionChangeGateResult,
+)
 from app.modules.checkers.api.pre_submit_material import (
     ALLOWED_PRE_SUBMIT_STORAGE_SCHEMES,
     SubmissionPacketView,
diff --git a/backend/app/modules/authorization/domain/submission_cleanup.py b/backend/app/modules/authorization/api/submission_cleanup.py
similarity index 100%
rename from backend/app/modules/authorization/domain/submission_cleanup.py
rename to backend/app/modules/authorization/api/submission_cleanup.py
diff --git a/backend/app/modules/authorization/domain/submission_finalization.py b/backend/app/modules/authorization/api/submission_finalization.py
similarity index 100%
rename from backend/app/modules/authorization/domain/submission_finalization.py
rename to backend/app/modules/authorization/api/submission_finalization.py
diff --git a/backend/app/modules/authorization/domain/action_groups.py b/backend/app/modules/authorization/domain/action_groups.py
index a6978f4ff..4b0b6b07d 100644
--- a/backend/app/modules/authorization/domain/action_groups.py
+++ b/backend/app/modules/authorization/domain/action_groups.py
@@ -161,8 +161,8 @@
 
 def supports_prepared_denial(action_id: ActionId, resource_context: object) -> bool:
     """Admit only the existing action/context pairs for prepare-time denial evidence."""
-    from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
-    from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+    from app.modules.authorization.api.submission_finalization import SubmissionFinalizationResourceContext
+    from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
     from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
     from app.modules.authorization.domain.task_authority import TASK_ACTIONS, TaskAuthorityResourceContext
     from app.modules.authorization.domain.project_create import ProjectCreateResourceContext
diff --git a/backend/app/modules/authorization/domain/audit_targets.py b/backend/app/modules/authorization/domain/audit_targets.py
index 1a6dff193..dbc977244 100644
--- a/backend/app/modules/authorization/domain/audit_targets.py
+++ b/backend/app/modules/authorization/domain/audit_targets.py
@@ -1,8 +1,8 @@
 """Exact project resource audit selectors, without raw product facts."""
 
 from uuid import UUID
-from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
-from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+from app.modules.authorization.api.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
 from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext
 
diff --git a/backend/app/modules/authorization/domain/prepared_service.py b/backend/app/modules/authorization/domain/prepared_service.py
index e4a1b613e..1295544e3 100644
--- a/backend/app/modules/authorization/domain/prepared_service.py
+++ b/backend/app/modules/authorization/domain/prepared_service.py
@@ -58,8 +58,8 @@
 from app.modules.authorization.domain.project_setup_finalization import (
     ProjectSetupFinalizationResourceContext,
 )
-from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
-from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+from app.modules.authorization.api.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.runtime import (
     ArtifactPendingWorkResourceContext,
     ArtifactPutAttemptResourceContext,
diff --git a/backend/app/modules/authorization/prepared.py b/backend/app/modules/authorization/prepared.py
index 4da99827d..74550473e 100644
--- a/backend/app/modules/authorization/prepared.py
+++ b/backend/app/modules/authorization/prepared.py
@@ -1,8 +1,8 @@
 """Transaction-bound, single-use authorization for sensitive mutations."""
 
 from __future__ import annotations
-from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
-from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+from app.modules.authorization.api.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.domain.prepared_service import (
     EXACT_ARTIFACT_RESOURCE_BY_ACTION as _EXACT_ARTIFACT_RESOURCE_BY_ACTION,
 )
@@ -192,7 +192,6 @@ def __reduce__(self) -> NoReturn:
 _HANDLE_CONSTRUCTOR_TOKEN = object()
 
 
-
 @dataclass(frozen=True, slots=True)
 class _PreparedAuthorizationBinding:
     action_id: ActionId
diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py
index 5250dfaa9..81ca18cfb 100644
--- a/backend/app/modules/authorization/runtime.py
+++ b/backend/app/modules/authorization/runtime.py
@@ -8,8 +8,8 @@
 from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator
 
 from app.modules.artifacts.api.submission_intake import PreSubmitSourceReadFacts
-from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
-from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+from app.modules.authorization.api.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.domain.submission_recovery import SubmissionRecoveryResourceContext
 from app.modules.authorization.domain.guide_compilation import ProjectGuideCompilationExecuteResourceContext, ProjectGuideCompilationRequestResourceContext
 from app.modules.authorization.domain.resource_digest import authorization_resource_digest as authorization_resource_digest
diff --git a/backend/app/modules/authorization/submission_consumption.py b/backend/app/modules/authorization/submission_consumption.py
index 420f3125d..6bcdca1dd 100644
--- a/backend/app/modules/authorization/submission_consumption.py
+++ b/backend/app/modules/authorization/submission_consumption.py
@@ -7,8 +7,8 @@
 from pydantic import BaseModel, ConfigDict, Field, model_validator
 
 from app.modules.authorization.catalogue import ActionId
-from app.modules.authorization.domain.submission_finalization import SubmissionFinalizationResourceContext
-from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+from app.modules.authorization.api.submission_finalization import SubmissionFinalizationResourceContext
+from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.domain.submission_intake import IntakeAcceptanceResourceContext
 
 _STRICT_FROZEN = ConfigDict(extra="forbid", frozen=True, strict=True)
diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py
index 1b7f72702..8df0a8a10 100644
--- a/backend/app/modules/checkers/api/selected_pre_submit.py
+++ b/backend/app/modules/checkers/api/selected_pre_submit.py
@@ -2,7 +2,7 @@
 
 from __future__ import annotations
 
-from dataclasses import asdict, dataclass
+from dataclasses import InitVar, asdict, dataclass, field
 from datetime import datetime, timedelta, timezone
 from contextlib import AbstractAsyncContextManager
 from typing import Annotated, Literal, Protocol
@@ -10,11 +10,13 @@
 
 import json
 
-from pydantic import BaseModel, ConfigDict, Field, model_validator
+from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_serializer, field_validator, model_validator
 
 from app.core.hashing import canonical_json_hash
-from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
-from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits
+from app.modules.checkers.api.source_contracts import (
+    SealedSubmissionSourceView, SubmissionArchiveLimitsView, SelectedPreSubmitSourceContracts,
+    source_contracts_context, source_contracts_from_context,
+)
 from app.modules.checkers.api.default_checker import WorkstreamDefaultContext, WorkstreamDefaultCheckerInput
 from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy
 from app.modules.checkers.api.default_checker import WorkstreamDefaultCheckerResult
@@ -295,7 +297,7 @@ class SelectedPreSubmitExecutionFacts:
     request_digest: str
     lease_id: UUID
     lease_generation: int
-    observed_source: SealedSubmissionSource
+    observed_source: SealedSubmissionSourceView
     manifest_body: dict[str, object] | None
     manifest_sha256: str | None
     default_input_sha256: str | None
@@ -305,18 +307,19 @@ class SelectedPreSubmitExecutionFacts:
     external_members: tuple[ExternalPreSubmitMemberFacts, ...]
     eligible: bool
 
-    def __post_init__(self) -> None:
+    source_contracts: InitVar[SelectedPreSubmitSourceContracts] = field(kw_only=True)
+
+    def __post_init__(self, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         members = self.external_members
         if (
             type(self.lease_id) is not UUID or type(self.lease_generation) is not int
             or self.lease_generation < 1 or type(self.eligible) is not bool
             or type(self.external_members) is not tuple
-            or type(self.observed_source) is not SealedSubmissionSource
             or (self.manifest_body is None) != (self.manifest_sha256 is None)
             or (self.manifest_body is None) != (self.default_input_sha256 is None)
         ):
             raise ValueError("selected PRE observed evidence is invalid")
-        SealedSubmissionSource.model_validate(self.observed_source)
+        source_contracts.require_source(self.observed_source)
         for digest in (self.request_digest, self.manifest_sha256, self.default_input_sha256):
             if digest is not None and (type(digest) is not str or len(digest) != 71
                     or not digest.startswith("sha256:")
@@ -343,7 +346,7 @@ def __post_init__(self) -> None:
         ):
             raise ValueError("selected PRE execution continued after a blocker")
 
-    def validate_lease(self, lease: SelectedPreSubmitLeaseFacts) -> None:
+    def validate_lease(self, lease: SelectedPreSubmitLeaseFacts, *, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         """Reconstruct expected derived input instead of trusting echoed digests."""
         from app.modules.checkers.api.default_checker import workstream_default_input_sha256
 
@@ -365,10 +368,12 @@ def validate_lease(self, lease: SelectedPreSubmitLeaseFacts) -> None:
             if self.workstream_default.eligible:
                 value, request = derive_selected_pre_submit_input(
                     lease, manifest_body=self.manifest_body, manifest_sha256=self.manifest_sha256,
+                    source_contracts=source_contracts,
                 )
             else:
                 value = derive_selected_pre_submit_default_input(
                     lease, manifest_body=self.manifest_body, manifest_sha256=self.manifest_sha256,
+                    source_contracts=source_contracts,
                 )
                 request = None
             if workstream_default_input_sha256(value) != self.default_input_sha256:
@@ -423,7 +428,7 @@ def canonical_body(self) -> dict[str, object]:
         }
 
     @classmethod
-    def from_canonical_body(cls, body: object) -> SelectedPreSubmitExecutionFacts:
+    def from_canonical_body(cls, body: object, *, source_contracts: SelectedPreSubmitSourceContracts) -> SelectedPreSubmitExecutionFacts:
         """Parse the exact bounded result retained for idempotent work replay."""
         if (
             type(body) is not dict
@@ -446,7 +451,7 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitExecutionFacts:
         value = cls(
             request_digest=body["request_digest"], lease_id=UUID(body["lease_id"]),
             lease_generation=body["lease_generation"],
-            observed_source=SealedSubmissionSource.model_validate_json(json.dumps(body["observed_source"])),
+            observed_source=source_contracts.parse_source(body["observed_source"]),
             manifest_body=body["manifest_body"], manifest_sha256=body["manifest_sha256"],
             default_input_sha256=body["default_input_sha256"],
             policy_sha256=body["policy_sha256"],
@@ -472,6 +477,7 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitExecutionFacts:
                 for item in members
             ),
             eligible=body["eligible"],
+            source_contracts=source_contracts,
         )
         if value.canonical_body() != body:
             raise ValueError("selected PRE execution body is not canonical")
@@ -486,7 +492,7 @@ def result_digest(self) -> str:
 class SelectedPreSubmitRuntimeProfile(BaseModel):
     """Explicit deployment bounds; structural validity is not qualification."""
 
-    model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
+    model_config = ConfigDict(extra="forbid", strict=True, frozen=True, arbitrary_types_allowed=True)
     profile_id: str = Field(min_length=1, max_length=100, pattern=r"^[a-z0-9_-]+$")
     platform_root_sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
     cpu_millis: int = Field(gt=0)
@@ -496,7 +502,18 @@ class SelectedPreSubmitRuntimeProfile(BaseModel):
     maximum_output_bytes: int = Field(gt=0)
     maximum_log_bytes: int = Field(gt=0)
     aggregate_deadline_ms: int = Field(ge=100, le=14_400_000)
-    archive_limits: SubmissionArchiveLimits
+    archive_limits: SubmissionArchiveLimitsView
+
+
+    @field_validator("archive_limits", mode="before")
+    @classmethod
+    def validate_archive_limits(cls, value: object, info: ValidationInfo) -> SubmissionArchiveLimitsView:
+        contracts = source_contracts_from_context(info.context)
+        return contracts.parse_limits(value) if type(value) is dict else contracts.require_limits(value)
+
+    @field_serializer("archive_limits")
+    def serialize_archive_limits(self, value: SubmissionArchiveLimitsView) -> dict[str, int | float]:
+        return value.canonical_body()
 
 
 @dataclass(frozen=True, slots=True)
@@ -510,7 +527,7 @@ class SelectedPreSubmitReservationFacts:
     assignment_id: UUID
     attempt_id: UUID
     idempotency_key: UUID
-    source: SealedSubmissionSource
+    source: SealedSubmissionSourceView
     metadata_sha256: str
     locked_context_sha256: str
     foreground_lease_id: UUID
@@ -521,8 +538,11 @@ class SelectedPreSubmitReservationFacts:
     runtime_profile: SelectedPreSubmitRuntimeProfile
     admission_lineage: SelectedPreSubmitAdmissionLineage
 
-    def __post_init__(self) -> None:
+    source_contracts: InitVar[SelectedPreSubmitSourceContracts] = field(kw_only=True)
+
+    def __post_init__(self, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         """Reject missing source, locked context, selected image or fence facts."""
+        source_contracts.require_source(self.source)
         identifiers = (self.actor_profile_id, self.identity_link_id, self.project_id,
                        self.task_id, self.assignment_id, self.attempt_id,
                        self.idempotency_key, self.foreground_lease_id)
@@ -533,7 +553,6 @@ def __post_init__(self) -> None:
                    or not value.startswith("sha256:")
                    or any(char not in "0123456789abcdef" for char in value[7:])
                    for value in digests)
-            or type(self.source) is not SealedSubmissionSource
             or type(self.policy) is not LockedExternalPreSubmitPolicy
             or type(self.default_context) is not WorkstreamDefaultContext
             or type(self.runtime_profile) is not SelectedPreSubmitRuntimeProfile
@@ -544,6 +563,7 @@ def __post_init__(self) -> None:
             or self.pre_deadline_at.utcoffset() is None
         ):
             raise ValueError("selected PRE reservation facts are invalid")
+        source_contracts.require_limits(self.runtime_profile.archive_limits)
         lineage = self.admission_lineage
         predecessor = self.default_context.predecessor
         if (
@@ -610,7 +630,7 @@ def canonical_body(self) -> dict[str, object]:
         }
 
     @classmethod
-    def from_canonical_body(cls, body: object) -> SelectedPreSubmitReservationFacts:
+    def from_canonical_body(cls, body: object, *, source_contracts: SelectedPreSubmitSourceContracts) -> SelectedPreSubmitReservationFacts:
         """Decode only the live source-first schema; historical data is read-only."""
         if type(body) is not dict or body.get("schema_version") != (
             "workstream.selected_pre_submit_reservation.v2"
@@ -621,7 +641,7 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitReservationFacts:
                 **{name: UUID(body[name]) for name in (
                     "actor_profile_id", "identity_link_id", "project_id", "task_id",
                     "assignment_id", "attempt_id", "idempotency_key", "foreground_lease_id")},
-                source=SealedSubmissionSource.model_validate_json(json.dumps(body["source"])),
+                source=source_contracts.parse_source(body["source"]),
                 metadata_sha256=body["metadata_sha256"],
                 locked_context_sha256=body["locked_context_sha256"],
                 foreground_lease_generation=body["foreground_lease_generation"],
@@ -629,9 +649,10 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitReservationFacts:
                 policy=LockedExternalPreSubmitPolicy.model_validate_json(json.dumps(body["policy"])),
                 default_context=WorkstreamDefaultContext.from_canonical_body(body["default_context"]),
                 runtime_profile=SelectedPreSubmitRuntimeProfile.model_validate_json(
-                    json.dumps(body["runtime_profile"])),
+                    json.dumps(body["runtime_profile"]), context=source_contracts_context(source_contracts)),
                 admission_lineage=SelectedPreSubmitAdmissionLineage.from_canonical_body(
                     body["admission_lineage"]),
+                source_contracts=source_contracts,
             )
             if value.canonical_body() != body:
                 raise ValueError("selected PRE reservation facts are not canonical")
@@ -670,29 +691,26 @@ def __post_init__(self) -> None:
 
 def derive_selected_pre_submit_default_input(
     lease: SelectedPreSubmitLeaseFacts, *, manifest_body: object, manifest_sha256: str,
+    source_contracts: SelectedPreSubmitSourceContracts,
 ) -> WorkstreamDefaultCheckerInput:
     """Derive platform input without consulting an unrun project input schema."""
-    from app.modules.artifacts.api.submission_archive import validate_submission_manifest
-    from app.modules.checkers.api.material import SubmissionMaterialEntry
 
 
     reservation = lease.reservation
     source = reservation.source
-    inspection = validate_submission_manifest(
+    entries = source_contracts.validate_manifest(
         manifest_body, sha256=manifest_sha256, limits=reservation.runtime_profile.archive_limits,
     )
     return reservation.default_context.bind_verified_input(
         archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count,
         archive_media_type=source.media_type, semantic_manifest_sha256=manifest_sha256,
-        entries=tuple(SubmissionMaterialEntry(
-            entry.normalized_path, entry.entry_type.value, entry.byte_count,
-            entry.sha256, entry.executable,
-        ) for entry in inspection.entries),
+        entries=entries,
     )
 
 
 def derive_selected_pre_submit_input(
     lease: SelectedPreSubmitLeaseFacts, *, manifest_body: object, manifest_sha256: str,
+    source_contracts: SelectedPreSubmitSourceContracts,
 ) -> tuple[WorkstreamDefaultCheckerInput, ExternalCheckerExecutionRequest]:
     """Reconstruct the project request only after the platform defaults pass.
 
@@ -705,6 +723,7 @@ def derive_selected_pre_submit_input(
 
     value = derive_selected_pre_submit_default_input(
         lease, manifest_body=manifest_body, manifest_sha256=manifest_sha256,
+        source_contracts=source_contracts,
     )
     reservation = lease.reservation
     source = reservation.source
@@ -838,9 +857,9 @@ def canonical_body(self) -> dict[str, object]:
         """Retain all provider and cleanup facts without transport credentials."""
         return self.model_dump(mode="json")
 
-    def validate_lease(self, lease: SelectedPreSubmitLeaseFacts) -> None:
+    def validate_lease(self, lease: SelectedPreSubmitLeaseFacts, *, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         """Revalidate even adapter-created model instances before trusting them."""
-        checked = type(self).model_validate_json(json.dumps(self.canonical_body(), allow_nan=False))
+        checked = type(self).model_validate_json(json.dumps(self.canonical_body(), allow_nan=False), context=source_contracts_context(source_contracts))
         request, identity = lease.reservation, checked.invocation
         if (identity.run_id != str(request.attempt_id)
                 or identity.source_operation_id != str(request.source.location.operation_id)
@@ -865,12 +884,12 @@ def __post_init__(self) -> None:
                 or (self.execution is not None and type(self.execution) is not SelectedPreSubmitExecutionFacts)):
             raise ValueError("PRE invocation result differs")
 
-    def validate_lease(self, lease: SelectedPreSubmitLeaseFacts) -> None:
+    def validate_lease(self, lease: SelectedPreSubmitLeaseFacts, *, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         self.__post_init__()
-        self.receipt.validate_lease(lease)
+        self.receipt.validate_lease(lease, source_contracts=source_contracts)
         if self.execution is None:
             return
-        self.execution.validate_lease(lease)
+        self.execution.validate_lease(lease, source_contracts=source_contracts)
         for member in self.execution.external_members:
             isolation = member.isolation
             if isolation.config_image_id != self.receipt.invocation.config_image_id:
@@ -891,14 +910,14 @@ def canonical_body(self) -> dict[str, object]:
         }
 
     @classmethod
-    def from_canonical_body(cls, body: object) -> SelectedPreSubmitInvocationResult:
+    def from_canonical_body(cls, body: object, *, source_contracts: SelectedPreSubmitSourceContracts) -> SelectedPreSubmitInvocationResult:
         if type(body) is not dict or "execution" not in body:
             raise ValueError("PRE invocation body is invalid")
         receipt = dict(body)
         execution = receipt.pop("execution")
         value = cls(
-            receipt=SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(receipt, allow_nan=False)),
-            execution=SelectedPreSubmitExecutionFacts.from_canonical_body(execution) if execution is not None else None,
+            receipt=SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(receipt, allow_nan=False), context=source_contracts_context(source_contracts)),
+            execution=SelectedPreSubmitExecutionFacts.from_canonical_body(execution, source_contracts=source_contracts) if execution is not None else None,
         )
         if value.canonical_body() != body:
             raise ValueError("PRE invocation body is not canonical")
@@ -966,7 +985,9 @@ class SelectedPreSubmitFinalizeFacts:
     invocation_receipt: SelectedPreSubmitInvocationReceipt | None
     infrastructure_failure_code: str | None
 
-    def __post_init__(self) -> None:
+    source_contracts: InitVar[SelectedPreSubmitSourceContracts] = field(kw_only=True)
+
+    def __post_init__(self, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         if type(self.lease) is not SelectedPreSubmitLeaseFacts:
             raise ValueError("selected PRE finalize lease is invalid")
         if (self.execution is None) == (self.infrastructure_failure_code is None):
@@ -974,11 +995,11 @@ def __post_init__(self) -> None:
         if self.execution is not None:
             if type(self.execution) is not SelectedPreSubmitExecutionFacts:
                 raise ValueError("selected PRE finalize execution is invalid")
-            SelectedPreSubmitInvocationResult(self.invocation_receipt, self.execution).validate_lease(self.lease)
+            SelectedPreSubmitInvocationResult(self.invocation_receipt, self.execution).validate_lease(self.lease, source_contracts=source_contracts)
         else:
             SelectedPreSubmitInfrastructureUnavailable(self.infrastructure_failure_code or "")
             if self.invocation_receipt is not None:
-                SelectedPreSubmitInvocationResult(self.invocation_receipt, None).validate_lease(self.lease)
+                SelectedPreSubmitInvocationResult(self.invocation_receipt, None).validate_lease(self.lease, source_contracts=source_contracts)
                 if (self.invocation_receipt.outcome not in {"infrastructure_failure", "deadline_exceeded"}
                         or self.invocation_receipt.reason != self.infrastructure_failure_code):
                     raise ValueError("PRE infrastructure receipt differs")
@@ -1033,6 +1054,16 @@ async def consume(
         """Consume the exact result or infrastructure outcome once."""
 
 
+class SelectedPreSubmitSourceGuard(Protocol):
+    """Require exact live source custody inside the caller-owned transaction."""
+
+    async def lock_selected_pre_submit_source(
+        self, facts: SelectedPreSubmitReservationFacts,
+    ) -> None:
+        """Lock ART after TASK and reject changed source, context or lease facts."""
+        ...
+
+
 class SelectedPreSubmitAuthorityPort(Protocol):
     """Prepare separate execute and finalize authority before owner locks."""
 
@@ -1120,7 +1151,9 @@ class SelectedPreSubmitTerminalFacts:
     started_at: datetime
     completed_at: datetime
 
-    def __post_init__(self) -> None:
+    source_contracts: InitVar[SelectedPreSubmitSourceContracts] = field(kw_only=True)
+
+    def __post_init__(self, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         """Keep work findings separate from recoverable infrastructure outcomes."""
         if type(self.lease) is not SelectedPreSubmitLeaseFacts:
             raise ValueError("selected PRE terminal lease is invalid")
@@ -1133,7 +1166,7 @@ def __post_init__(self) -> None:
             )
         ) or not (self.queued_at <= self.started_at <= self.completed_at):
             raise ValueError("selected PRE terminal timing is invalid")
-        SelectedPreSubmitFinalizeFacts(self.lease, self.execution, self.invocation_receipt, self.infrastructure_failure_code)
+        SelectedPreSubmitFinalizeFacts(self.lease, self.execution, self.invocation_receipt, self.infrastructure_failure_code, source_contracts=source_contracts)
         if self.outcome == "completed":
             if (
                 type(self.execution) is not SelectedPreSubmitExecutionFacts
@@ -1141,7 +1174,7 @@ def __post_init__(self) -> None:
                 or self.execution.policy_sha256 != self.lease.reservation.policy_sha256
             ):
                 raise ValueError("selected PRE completed outcome is invalid")
-            self.execution.validate_lease(self.lease)
+            self.execution.validate_lease(self.lease, source_contracts=source_contracts)
         elif (self.outcome != "infrastructure_failed" or self.execution is not None
               or self.infrastructure_failure_code not in {
             "capacity_exceeded",
@@ -1173,7 +1206,7 @@ def canonical_body(self) -> dict[str, object]:
         }
 
     @classmethod
-    def from_canonical_body(cls, body: object) -> SelectedPreSubmitTerminalFacts:
+    def from_canonical_body(cls, body: object, *, source_contracts: SelectedPreSubmitSourceContracts) -> SelectedPreSubmitTerminalFacts:
         """Parse and revalidate every persisted lease, result and timing fact."""
         if (
             type(body) is not dict
@@ -1198,7 +1231,7 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitTerminalFacts:
             or body["schema_version"] != "workstream.selected_pre_submit_terminal.v3"
         ):
             raise ValueError("selected PRE terminal facts are invalid")
-        reservation = SelectedPreSubmitReservationFacts.from_canonical_body(body["reservation"])
+        reservation = SelectedPreSubmitReservationFacts.from_canonical_body(body["reservation"], source_contracts=source_contracts)
         if body["request_digest"] != reservation.request_digest:
             raise ValueError("selected PRE terminal request is invalid")
         execution_body = body["execution"]
@@ -1211,15 +1244,16 @@ def from_canonical_body(cls, body: object) -> SelectedPreSubmitTerminalFacts:
             ),
             outcome=body["outcome"],
             execution=(
-                SelectedPreSubmitExecutionFacts.from_canonical_body(execution_body)
+                SelectedPreSubmitExecutionFacts.from_canonical_body(execution_body, source_contracts=source_contracts)
                 if execution_body is not None
                 else None
             ),
-            invocation_receipt=(SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body["invocation_receipt"], allow_nan=False)) if body["invocation_receipt"] is not None else None),
+            invocation_receipt=(SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body["invocation_receipt"], allow_nan=False), context=source_contracts_context(source_contracts)) if body["invocation_receipt"] is not None else None),
             infrastructure_failure_code=body["infrastructure_failure_code"],
             queued_at=datetime.fromisoformat(body["queued_at"]),
             started_at=datetime.fromisoformat(body["started_at"]),
             completed_at=datetime.fromisoformat(body["completed_at"]),
+            source_contracts=source_contracts,
         )
         if value.canonical_body() != body:
             raise ValueError("selected PRE terminal facts are invalid")
@@ -1243,7 +1277,9 @@ class HistoricalSourcePreSubmitTerminal:
     started_at: datetime
     completed_at: datetime
 
-    def __post_init__(self) -> None:
+    source_contracts: InitVar[SelectedPreSubmitSourceContracts] = field(kw_only=True)
+
+    def __post_init__(self, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         """Keep work findings separate from recoverable infrastructure outcomes."""
         if type(self.lease) is not SelectedPreSubmitLeaseFacts:
             raise ValueError("selected PRE terminal lease is invalid")
@@ -1263,7 +1299,7 @@ def __post_init__(self) -> None:
                 or self.execution.policy_sha256 != self.lease.reservation.policy_sha256
             ):
                 raise ValueError("selected PRE completed outcome is invalid")
-            self.execution.validate_lease(self.lease)
+            self.execution.validate_lease(self.lease, source_contracts=source_contracts)
         elif (self.outcome != "infrastructure_failed" or self.execution is not None
               or self.infrastructure_failure_code not in {
             "capacity_exceeded",
@@ -1294,7 +1330,7 @@ def canonical_body(self) -> dict[str, object]:
         }
 
     @classmethod
-    def from_canonical_body(cls, body: object) -> HistoricalSourcePreSubmitTerminal:
+    def from_canonical_body(cls, body: object, *, source_contracts: SelectedPreSubmitSourceContracts) -> HistoricalSourcePreSubmitTerminal:
         """Parse and revalidate every persisted lease, result and timing fact."""
         if (
             type(body) is not dict
@@ -1318,7 +1354,7 @@ def from_canonical_body(cls, body: object) -> HistoricalSourcePreSubmitTerminal:
             or body["schema_version"] != "workstream.selected_pre_submit_terminal.v2"
         ):
             raise ValueError("selected PRE terminal facts are invalid")
-        reservation = SelectedPreSubmitReservationFacts.from_canonical_body(body["reservation"])
+        reservation = SelectedPreSubmitReservationFacts.from_canonical_body(body["reservation"], source_contracts=source_contracts)
         if body["request_digest"] != reservation.request_digest:
             raise ValueError("selected PRE terminal request is invalid")
         execution_body = body["execution"]
@@ -1331,7 +1367,7 @@ def from_canonical_body(cls, body: object) -> HistoricalSourcePreSubmitTerminal:
             ),
             outcome=body["outcome"],
             execution=(
-                SelectedPreSubmitExecutionFacts.from_canonical_body(execution_body)
+                SelectedPreSubmitExecutionFacts.from_canonical_body(execution_body, source_contracts=source_contracts)
                 if execution_body is not None
                 else None
             ),
@@ -1339,6 +1375,7 @@ def from_canonical_body(cls, body: object) -> HistoricalSourcePreSubmitTerminal:
             queued_at=datetime.fromisoformat(body["queued_at"]),
             started_at=datetime.fromisoformat(body["started_at"]),
             completed_at=datetime.fromisoformat(body["completed_at"]),
+            source_contracts=source_contracts,
         )
         if value.canonical_body() != body:
             raise ValueError("selected PRE terminal facts are invalid")
@@ -1464,6 +1501,7 @@ async def read_project_runs(
     "SelectedPreSubmitAuthorityEvidence",
     "SelectedPreSubmitAuthorityUnavailable",
     "SelectedPreSubmitAuthorityPort",
+    "SelectedPreSubmitSourceGuard",
     "SelectedPreSubmitCompletion",
     "SelectedPreSubmitCoordinationPort",
     "SelectedPreSubmitCurrentFacts",
diff --git a/backend/app/modules/checkers/api/source_contracts.py b/backend/app/modules/checkers/api/source_contracts.py
new file mode 100644
index 000000000..02020d90b
--- /dev/null
+++ b/backend/app/modules/checkers/api/source_contracts.py
@@ -0,0 +1,135 @@
+"""Consumer contracts for ART-owned PRE source and archive validation.
+
+Views describe existing immutable owner values; they grant no read authority.
+The injected validator must enforce the concrete owner's exact type and schema.
+"""
+
+from typing import Literal, Protocol, runtime_checkable
+from uuid import UUID
+
+from pydantic_core import core_schema
+
+from app.modules.checkers.api.material import SubmissionMaterialEntry
+
+
+class SubmissionSourceLocationView(Protocol):
+    @property
+    def operation_id(self) -> UUID: ...
+
+    @property
+    def namespace_id(self) -> str: ...
+
+    @property
+    def namespace_fingerprint(self) -> str: ...
+
+    @property
+    def provider_profile(self) -> str: ...
+
+    @property
+    def object_ref(self) -> str: ...
+
+
+@runtime_checkable
+class SealedSubmissionSourceView(Protocol):
+    """Read-only access to the owner's exact sealed source identity."""
+
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source_type, handler):
+        def validate(value, info):
+            contracts = source_contracts_from_context(info.context)
+            return contracts.parse_source(value) if type(value) is dict else contracts.require_source(value)
+        return core_schema.with_info_plain_validator_function(validate)
+
+    @property
+    def location(self) -> SubmissionSourceLocationView: ...
+
+    @property
+    def provider_generation(self) -> str: ...
+
+    @property
+    def raw_sha256(self) -> str: ...
+
+    @property
+    def raw_byte_count(self) -> int: ...
+
+    @property
+    def sealed_upload_fence(self) -> int: ...
+
+    @property
+    def media_type(self) -> str: ...
+
+    def model_dump(self, *, mode: Literal["json"]) -> dict[str, object]: ...
+
+    def source_sha256(self) -> str: ...
+
+
+@runtime_checkable
+class SubmissionArchiveLimitsView(Protocol):
+    """Exact configured inspection bounds, validated by their owner."""
+
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source_type, handler):
+        def validate(value, info):
+            contracts = source_contracts_from_context(info.context)
+            return contracts.parse_limits(value) if type(value) is dict else contracts.require_limits(value)
+        return core_schema.with_info_plain_validator_function(validate)
+
+    @property
+    def maximum_entries(self) -> int: ...
+
+    @property
+    def maximum_path_bytes(self) -> int: ...
+
+    @property
+    def maximum_path_depth(self) -> int: ...
+
+    @property
+    def maximum_central_directory_bytes(self) -> int: ...
+
+    @property
+    def maximum_entry_bytes(self) -> int: ...
+
+    @property
+    def maximum_expanded_bytes(self) -> int: ...
+
+    @property
+    def maximum_compression_ratio(self) -> int: ...
+
+    @property
+    def maximum_inspection_seconds(self) -> float: ...
+
+    def canonical_body(self) -> dict[str, int | float]: ...
+
+
+@runtime_checkable
+class SelectedPreSubmitSourceContracts(Protocol):
+    """Pure owner validation; separate from transaction-bound live custody."""
+
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source_type, handler):
+        return core_schema.is_instance_schema(cls)
+
+    def parse_source(self, body: object) -> SealedSubmissionSourceView: ...
+
+    def require_source(self, source: object) -> SealedSubmissionSourceView: ...
+
+    def parse_limits(self, body: object) -> SubmissionArchiveLimitsView: ...
+
+    def require_limits(self, limits: object) -> SubmissionArchiveLimitsView: ...
+
+    def validate_manifest(
+        self, body: object, *, sha256: str, limits: SubmissionArchiveLimitsView,
+    ) -> tuple[SubmissionMaterialEntry, ...]: ...
+
+
+def source_contracts_context(contracts: SelectedPreSubmitSourceContracts) -> dict[str, object]:
+    """Explicit context for nested Pydantic parsing, never a global registry."""
+    return {"submission_source_contracts": contracts}
+
+
+def source_contracts_from_context(context: object) -> SelectedPreSubmitSourceContracts:
+    """Refuse decoding without the owner validator selected by composition."""
+    contracts = context.get("submission_source_contracts") if type(context) is dict else None
+    if not isinstance(contracts, SelectedPreSubmitSourceContracts):
+        raise ValueError("selected PRE source contracts are required")
+    return contracts
diff --git a/backend/app/modules/checkers/selected_pre_submit_coordination.py b/backend/app/modules/checkers/selected_pre_submit_coordination.py
index 616bbbdeb..266d9a50f 100644
--- a/backend/app/modules/checkers/selected_pre_submit_coordination.py
+++ b/backend/app/modules/checkers/selected_pre_submit_coordination.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.modules.checkers.api.source_contracts import SelectedPreSubmitSourceContracts
+
 import threading
 from dataclasses import replace
 from datetime import timedelta
@@ -13,7 +15,7 @@
 from sqlalchemy.ext.asyncio import AsyncSession
 
 from app.core.identifiers import new_record_id
-from app.modules.artifacts.api.submission_intake import SubmissionIntakePreSourcePort
+from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitSourceGuard
 from app.modules.checkers.api.selected_pre_submit import (
     PreparedSelectedPreSubmitExecution,
     PreparedSelectedPreSubmitFinalization,
@@ -195,10 +197,12 @@ def __init__(
         session: AsyncSession,
         *,
         tasks: SelectedPreSubmitTaskGuard,
-        sources: SubmissionIntakePreSourcePort,
+        sources: SelectedPreSubmitSourceGuard,
+        source_contracts: SelectedPreSubmitSourceContracts,
     ) -> None:
         self._session = session
         self._tasks = tasks
+        self._source_contracts = source_contracts
         self._sources = sources
         self._capability: SelectedPreSubmitAdmissionCapability | None = None
         self._execution_capability: SelectedPreSubmitExecutionCapability | None = None
@@ -230,14 +234,15 @@ async def read_current(
             raise SelectedPreSubmitRequestConflict("selected_pre_submit_request_conflict")
         try:
             stored = SelectedPreSubmitReservationFacts.from_canonical_body(
-                row.request_json
+                row.request_json,
+                source_contracts=self._source_contracts,
             )
             normalized = replace(
-                facts,
+                facts, source_contracts=self._source_contracts,
                 attempt_id=stored.attempt_id,
             )
             terminal = (
-                SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json)
+                SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json, source_contracts=self._source_contracts)
                 if row.terminal_json is not None
                 else None
             )
@@ -275,8 +280,8 @@ async def read_accepted_terminal(self, *, run_id: UUID, source_operation_id: UUI
                 or row.terminal_json.get("schema_version") != "workstream.selected_pre_submit_terminal.v3"):
             raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid")
         try:
-            request = SelectedPreSubmitReservationFacts.from_canonical_body(row.request_json)
-            terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json)
+            request = SelectedPreSubmitReservationFacts.from_canonical_body(row.request_json, source_contracts=self._source_contracts)
+            terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json, source_contracts=self._source_contracts)
             if not matches_source_request(row, request) or not matches_terminal(row, request, terminal):
                 raise ValueError("retained PRE differs")
         except (TypeError, ValueError):
@@ -486,6 +491,7 @@ async def finalize(
             execution=execution,
             invocation_receipt=invocation_receipt,
             infrastructure_failure_code=infrastructure_failure_code,
+            source_contracts=self._source_contracts,
         )
         evidence = await authority.consume(finalize_facts)
         if evidence.facts_digest != finalize_facts.facts_digest:
@@ -499,6 +505,7 @@ async def finalize(
             queued_at=row.queued_at,
             started_at=row.started_at,
             completed_at=completed_at,
+            source_contracts=self._source_contracts,
         )
         row.status = outcome
         row.terminal_json = terminal.canonical_body()
@@ -514,24 +521,7 @@ async def finalize(
     async def _lock_source(self, facts: SelectedPreSubmitReservationFacts) -> None:
         """Hold TASK then exact live ART custody before any CHECKERS row lock."""
         await self._tasks.lock_selected_pre_submit_scope(facts)
-        current = await self._sources.lock_pre_source(
-            source=facts.source, lease_id=facts.foreground_lease_id,
-            generation=facts.foreground_lease_generation,
-        )
-        if (
-            current.source != facts.source
-            or current.project_id != facts.project_id
-            or current.task_id != facts.task_id
-            or current.assignment_id != facts.assignment_id
-            or current.actor_profile_id != facts.actor_profile_id
-            or current.identity_link_id != facts.identity_link_id
-            or current.metadata_sha256 != facts.metadata_sha256
-            or current.locked_context_sha256 != facts.locked_context_sha256
-            or current.lease_id != facts.foreground_lease_id
-            or current.lease_generation != facts.foreground_lease_generation
-            or current.pre_deadline_at != facts.pre_deadline_at
-        ):
-            raise SelectedPreSubmitUnavailable("selected_pre_submit_source_changed")
+        await self._sources.lock_selected_pre_submit_source(facts)
 
     async def _lock(
         self, *, run_id: UUID, facts: SelectedPreSubmitReservationFacts
diff --git a/backend/app/modules/checkers/selected_pre_submit_execution.py b/backend/app/modules/checkers/selected_pre_submit_execution.py
index 1637e0e86..ed4e27d5b 100644
--- a/backend/app/modules/checkers/selected_pre_submit_execution.py
+++ b/backend/app/modules/checkers/selected_pre_submit_execution.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.modules.checkers.api.source_contracts import SelectedPreSubmitSourceContracts
+
 import asyncio
 
 from app.interfaces.external_checker_execution import (
@@ -24,7 +26,9 @@ class SelectedPreSubmitProcessor:
 
     def __init__(
         self, *, lease: SelectedPreSubmitLeaseFacts, execution: ExternalCheckerExecutionAdapter,
+        source_contracts: SelectedPreSubmitSourceContracts,
     ) -> None:
+        self._source_contracts = source_contracts
         self._lease = lease
         self._execution = execution
         self._aborted = False
@@ -51,7 +55,7 @@ async def process(self, grant: ExternalPreSubmitSourceGrant) -> SelectedPreSubmi
             result = await self._execution.execute_pre(self._lease, grant)
             if type(result) is not SelectedPreSubmitInvocationResult:
                 raise ValueError("PRE result is invalid")
-            result.validate_lease(self._lease)
+            result.validate_lease(self._lease, source_contracts=self._source_contracts)
             if (result.receipt.adapter_provider_key != self._execution.identity.provider_key
                     or result.receipt.runtime.provider != self._execution.pre_runtime_provider):
                 raise ValueError("PRE provider differs")
diff --git a/backend/app/modules/checkers/selected_pre_submit_reads.py b/backend/app/modules/checkers/selected_pre_submit_reads.py
index c1e1582bd..1f244ad97 100644
--- a/backend/app/modules/checkers/selected_pre_submit_reads.py
+++ b/backend/app/modules/checkers/selected_pre_submit_reads.py
@@ -1,5 +1,7 @@
 """Read retained selected PRE runs without leasing or finalizing; the caller owns authority."""
 
+from app.modules.checkers.api.source_contracts import SelectedPreSubmitSourceContracts
+
 from uuid import UUID
 
 from sqlalchemy import select, tuple_
@@ -8,7 +10,7 @@
 from app.modules.checkers.api.selected_pre_submit import (
     SelectedPreSubmitRunStatus, SelectedPreSubmitRunView,
     SelectedPreSubmitUnavailable, SelectedPreSubmitReservationFacts,
-    SelectedPreSubmitTerminalFacts, HistoricalSourcePreSubmitTerminal, SelectedPreSubmitLeaseFacts,
+    SelectedPreSubmitTerminalFacts, HistoricalSourcePreSubmitTerminal,
 )
 from app.modules.checkers.api.historical_selected_pre_submit import (
     HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal,
@@ -38,7 +40,7 @@ def _request_matches(row: SelectedPreSubmitRun, request: HistoricalSelectedPreSu
     )
 
 
-def _view(row: SelectedPreSubmitRun) -> SelectedPreSubmitRunView:
+def _view(row: SelectedPreSubmitRun, *, source_contracts: SelectedPreSubmitSourceContracts) -> SelectedPreSubmitRunView:
     """Decode each retained schema and bind it to the indexed row without issuing authority."""
     try:
         if (type(row.request_json) is not dict
@@ -49,13 +51,13 @@ def _view(row: SelectedPreSubmitRun) -> SelectedPreSubmitRunView:
             terminal = HistoricalSelectedPreSubmitTerminal.from_canonical_body(row.terminal_json) if row.terminal_json is not None else None
             request_matches = _request_matches(row, request)
         else:
-            request = SelectedPreSubmitReservationFacts.from_canonical_body(row.request_json)
+            request = SelectedPreSubmitReservationFacts.from_canonical_body(row.request_json, source_contracts=source_contracts)
             if row.terminal_json is None:
                 terminal = None
             elif row.terminal_json.get("schema_version") == "workstream.selected_pre_submit_terminal.v2":
-                terminal = HistoricalSourcePreSubmitTerminal.from_canonical_body(row.terminal_json)
+                terminal = HistoricalSourcePreSubmitTerminal.from_canonical_body(row.terminal_json, source_contracts=source_contracts)
             else:
-                terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json)
+                terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json, source_contracts=source_contracts)
             request_matches = matches_source_request(row, request)
         if not request_matches or not matches_terminal(row, request, terminal):
             raise ValueError("retained PRE columns differ")
@@ -72,8 +74,9 @@ def _view(row: SelectedPreSubmitRun) -> SelectedPreSubmitRunView:
 class SelectedPreSubmitRunReader:
     """Fixed columns and revalidated terminal bodies, newest first by ``(queued_at, id)``."""
 
-    def __init__(self, session: AsyncSession) -> None:
+    def __init__(self, session: AsyncSession, *, source_contracts: SelectedPreSubmitSourceContracts) -> None:
         """Read in the caller's response transaction."""
+        self._source_contracts = source_contracts
         self._session = session
 
     async def _page(self, statement, limit, before):
@@ -84,7 +87,7 @@ async def _page(self, statement, limit, before):
         rows = (await self._session.scalars(
             statement.order_by(run.queued_at.desc(), run.id.desc()).limit(limit + 1),
         )).all()
-        return tuple(_view(row) for row in rows[:limit]), len(rows) > limit
+        return tuple(_view(row, source_contracts=self._source_contracts) for row in rows[:limit]), len(rows) > limit
 
     async def read_contributor_runs(self, *, actor_profile_id, task_id, run_id, limit, before):
         """One contributor's runs for one task, optionally one exact run."""
diff --git a/backend/scripts/external_api_drill.py b/backend/scripts/external_api_drill.py
index 4f18f9dfc..138fdc4c3 100644
--- a/backend/scripts/external_api_drill.py
+++ b/backend/scripts/external_api_drill.py
@@ -115,7 +115,7 @@ def guide_metadata(response):
 operations.projection.rebuild operations.submission_gate.repair
 operations.checker.retry artifact.binding.read artifact.replica.read artifact.receipt.read
 artifact.verification_job.read artifact.verification_job.retry artifact.recovery_attempt.read
-artifact.audit.read artifact.guide_source.ingest artifact.binding.create artifact.verification.execute
+artifact.audit.read artifact.guide_source.ingest artifact.binding.create artifact.submission_source.cleanup artifact.verification.execute
 artifact.pending_work.scan artifact.put_attempt.resolve artifact.guide_source.read
 artifact.checker_input.materialize artifact.checker_output.write artifact.review_packet.materialize
 project.model_profile.manage project.model_budget.manage project.model_call.recovery_child.authorize
@@ -147,7 +147,7 @@ def guide_metadata(response):
 def catalogue_expectations():
     """Fresh expected JSON objects; callers cannot mutate the frozen oracle."""
     return {
-        "permissions": {"items": [{"permission_id": value} for value in EXPECTED_PERMISSIONS], "total": 94},
+        "permissions": {"items": [{"permission_id": value} for value in EXPECTED_PERMISSIONS], "total": 95},
         "admin-role-definitions": {"items": [
             {"role": role, "allowed_scopes": list(scopes), "permission_ids": permissions.split()}
             for role, scopes, permissions in EXPECTED_ROLE_CONTRACT], "total": 5},
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 25ba4290c..aa0fbcaaa 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -178,7 +178,6 @@ async def body(value):
         assert (row.lease_id, row.lease_generation) == (str(owner.lease_id), owner.generation)
 
 
-
     async with f.factory.begin() as session:
         await repository(session).terminalize(owner.operation_id, owner.lease_id, owner.generation,
                                               state="failed", failure_code="upload_failed")
@@ -337,7 +336,6 @@ async def record_intake_eof(f, owner, payload):
                          raw_sha256="sha256:" + hashlib.sha256(payload).hexdigest(), raw_byte_count=len(payload))
 
 
-
 @pytest.mark.parametrize("admission_intake", ["no_pre", "no_post"], indirect=True)
 async def test_t1_requires_one_selected_checker_in_each_phase(admission_intake):
     from sqlalchemy import func, select
@@ -868,7 +866,7 @@ def submissions(session):
 async def test_operator_recovers_same_accepted_finalization_once(recovery_intake, tmp_path):
     import asyncio
     from sqlalchemy import select, func
-    from app.adapters.artifacts.finalization import submission_finalization_recovery_handler
+    from app.adapters.artifacts import submission_finalization_recovery_handler
     from app.adapters.auth import outbox_dispatch_authorization
     from app.adapters.outbox import outbox_delivery
     from app.modules.artifacts.api.submission_recovery import FINALIZATION_RECOVERY_EVENT, SubmissionRecoveryUnavailable
@@ -1003,7 +1001,7 @@ async def test_recovery_sql_requires_exact_source_and_real_operator_cause(recove
 async def test_finalization_outbox_recovers_lost_ack_without_provider_replay(admission_intake, tmp_path, lost_at):
     from uuid import UUID
     from sqlalchemy import select, func, text
-    from app.adapters.artifacts.finalization import submission_finalization_handler
+    from app.adapters.artifacts import submission_finalization_handler
     from app.adapters.auth import outbox_dispatch_authorization
     from app.adapters.checkers import selected_pre_submit_coordinator
     from app.adapters.outbox import outbox_append, outbox_delivery, production_outbox_delivery
@@ -1094,7 +1092,7 @@ async def test_authorized_progress_reports_exact_exhaustion_without_reopening_in
     import json
     from uuid import UUID
     from sqlalchemy import select, func
-    from app.adapters.artifacts.finalization import submission_finalization_handler
+    from app.adapters.artifacts import submission_finalization_handler
     from app.adapters.auth import outbox_dispatch_authorization
     from app.adapters.checkers import selected_pre_submit_coordinator
     from app.adapters.outbox import outbox_append, outbox_delivery
diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py
index 8511d4be5..863aaac25 100644
--- a/backend/tests/artifacts/test_submission_intake_contracts.py
+++ b/backend/tests/artifacts/test_submission_intake_contracts.py
@@ -529,3 +529,51 @@ async def chunks():
         await receive_submission_source(BufferedStore(), upload_value(
             upload_deadline_at=datetime.now(UTC) + timedelta(seconds=0.01),
         ), chunks())
+
+
+@pytest.mark.parametrize("changed", ["none", "mapping", "forged", "subclass"])
+def test_checker_source_contracts_reject_non_owner_or_unvalidated_values(changed):
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
+
+    contracts = selected_pre_submit_source_contracts()
+    original = source()
+    class SourceSubclass(SealedSubmissionSource):
+        pass
+    invalid = {
+        "none": None,
+        "mapping": original.model_dump(mode="json"),
+        "forged": original.model_copy(update={"raw_byte_count": True}),
+        "subclass": SourceSubclass.model_validate_json(original.model_dump_json()),
+    }[changed]
+    with pytest.raises(ValueError):
+        contracts.require_source(invalid)
+    recovered = contracts.parse_source(original.model_dump(mode="json"))
+    assert recovered == original
+    assert recovered.source_sha256() == original.source_sha256()
+    assert contracts.require_source(recovered) == original
+
+
+@pytest.mark.parametrize("changed", ["missing", "extra", "coercion", "overflow"])
+def test_checker_source_contracts_preserve_closed_limits_and_source_wire(changed):
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
+    from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits
+
+    contracts = selected_pre_submit_source_contracts()
+    limits = SubmissionArchiveLimits()
+    body = limits.canonical_body()
+    assert contracts.parse_limits(body) == limits
+    assert contracts.require_limits(limits).canonical_body() == body
+    if changed == "missing":
+        del body["maximum_entries"]
+    elif changed == "extra":
+        body["unbounded"] = True
+    elif changed == "coercion":
+        body["maximum_entries"] = "2000"
+    else:
+        body["maximum_expanded_bytes"] = 512 * 1024 * 1024 + 1
+    with pytest.raises(ValueError):
+        contracts.parse_limits(body)
+    source_body = source().model_dump(mode="json")
+    del source_body["media_type"]
+    with pytest.raises(ValueError, match="not canonical"):
+        contracts.parse_source(source_body)
diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py
index aeb00ed03..77634a8a4 100644
--- a/backend/tests/artifacts/test_submission_pre_source.py
+++ b/backend/tests/artifacts/test_submission_pre_source.py
@@ -1,5 +1,7 @@
 """Real PostgreSQL PRE source, SQL fence, and authorized execution custody."""
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 import json
 from datetime import UTC, datetime, timedelta
 from uuid import UUID
@@ -16,7 +18,7 @@
 from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable
 from tests.artifacts.test_submission_intake_custody import (
     SHA, capacity_limits as capacity_limits, intake as intake,
-    foreground_bytes, foreground_limits, foreground_upload,
+    foreground_limits, foreground_upload,
     record_eof, repository, reserve,
 )
 
@@ -350,7 +352,7 @@ async def _assert_pre_terminal_guards(intake, request):
     await _assert_receipt_migration_refuses_inflight(intake, request, "running")
     finalize = SelectedPreSubmitFinalizeFacts(
         lease=lease, execution=None, invocation_receipt=None, infrastructure_failure_code="capacity_exceeded",
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     for changed in ("lease_id", "lease_expires_at", "started_at", "execute_evidence_id",
                     "schema_version", "reservation", "request_digest", "outcome", "terminal_digest", "extra"):
         async with intake.factory.begin() as session:
@@ -362,7 +364,7 @@ async def _assert_pre_terminal_guards(intake, request):
                     lease=lease, outcome="infrastructure_failed", execution=None, invocation_receipt=None,
                     infrastructure_failure_code="capacity_exceeded", queued_at=row.queued_at,
                     started_at=row.started_at, completed_at=now,
-                ).canonical_body()
+                 source_contracts=selected_pre_submit_source_contracts()).canonical_body()
                 values = dict(
                     id=request.attempt_id, lease_id=lease.lease_id,
                     lease_expires_at=lease.lease_expires_at, started_at=row.started_at,
@@ -450,7 +452,7 @@ async def run(self, lease, grant):
             if runtime_outcome == "received_failure":
                 body = receipt_body(lease, outcome="infrastructure_failure", reason="capacity_exceeded")
                 body["cleanup"]["disposition"] = "pending"
-                return SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None})
+                return SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None}, source_contracts=selected_pre_submit_source_contracts())
             if runtime_outcome == "completed":
                 worker, output, reply, actual_lease = _pre_worker(
                     tmp_path, payload, lease=lease,
@@ -463,7 +465,7 @@ async def run(self, lease, grant):
                 assert project_frame["operation"] == "project" and reply.calls == 1
                 assert completion["operation"] == "completed" and output.read() == b""
                 response = receipt_body(lease) | {"execution": completion["payload"]}
-                return SelectedPreSubmitInvocationResult.from_canonical_body(response)
+                return SelectedPreSubmitInvocationResult.from_canonical_body(response, source_contracts=selected_pre_submit_source_contracts())
             raise SelectedPreSubmitInfrastructureUnavailable("capacity_exceeded")
     return SourceRuntime(), runtime_errors
 
@@ -504,7 +506,7 @@ async def _assert_acceptance_terminal(factory, request, terminal):
         with pytest.raises(SelectedPreSubmitRequestConflict):
             await coordinator.lock_acceptance(**(args | {"run_id": new_record_id()}))
         with pytest.raises(SelectedPreSubmitRequestConflict):
-            await coordinator.lock_acceptance(**(args | {"facts": replace(request, attempt_id=new_record_id())}))
+            await coordinator.lock_acceptance(**(args | {"facts": replace(request, attempt_id=new_record_id(), source_contracts=selected_pre_submit_source_contracts())}))
         with pytest.raises(SelectedPreSubmitUnavailable):
             await coordinator.lock_acceptance(**(args | {"terminal_digest": "sha256:" + "f" * 64}))
 
diff --git a/backend/tests/authorization/pre_submit/test_contracts.py b/backend/tests/authorization/pre_submit/test_contracts.py
index 80217b081..23e0e1f1d 100644
--- a/backend/tests/authorization/pre_submit/test_contracts.py
+++ b/backend/tests/authorization/pre_submit/test_contracts.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 from dataclasses import replace
 from datetime import UTC, datetime, timedelta
 
@@ -59,7 +61,7 @@ def _reservation() -> SelectedPreSubmitReservationFacts:
         archive_byte_count=100,
         semantic_manifest_sha256="sha256:" + "4" * 64,
         execution_budget_ms=60_000,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
 
 
 def _execute() -> SelectedPreSubmitExecuteFacts:
@@ -148,7 +150,7 @@ def test_selected_pre_finalize_and_prepare_parser_are_closed() -> None:
         lease=execute.lease,
         execution=None,
         infrastructure_failure_code="deadline_exceeded",
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     resource = pre_submit_resource(FINALIZE, final)
     prepared = pre_submit_prepare_values(execute.lease.reservation)
 
diff --git a/backend/tests/authorization/test_submission_finalization_authority.py b/backend/tests/authorization/test_submission_finalization_authority.py
index b4fda20a9..507a706d5 100644
--- a/backend/tests/authorization/test_submission_finalization_authority.py
+++ b/backend/tests/authorization/test_submission_finalization_authority.py
@@ -95,7 +95,7 @@ def cleanup_facts(phase="claim"):
 async def test_cleanup_authority_binds_every_target_fact(clean_postgres_database, phase):
     from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization
     from app.modules.authorization.domain.resource_digest import authorization_resource_digest
-    from app.modules.authorization.domain.submission_cleanup import SubmissionSourceCleanupResourceContext
+    from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
     from dataclasses import asdict
     engine = create_async_engine(clean_postgres_database)
     factory = async_sessionmaker(engine, expire_on_commit=False)
diff --git a/backend/tests/checkers/default/test_execution.py b/backend/tests/checkers/default/test_execution.py
index 8160f8d30..3be95f4d2 100644
--- a/backend/tests/checkers/default/test_execution.py
+++ b/backend/tests/checkers/default/test_execution.py
@@ -20,7 +20,9 @@
 from app.modules.artifacts.submission_archive import (
     SubmissionArchiveInspector,
 )
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 from app.modules.checkers.api.default_checker import (
     WorkstreamDefaultCheckerInput,
     WorkstreamDefaultContext,
@@ -99,7 +101,6 @@ def _input(
     )
 
 
-
 def _evaluate(value: bytes, request: WorkstreamDefaultCheckerInput, workspace: Path):
     inspector, inspection, _, _ = _facts(value)
     workspace.mkdir(mode=0o700)
diff --git a/backend/tests/checkers/external/test_pre_invocation.py b/backend/tests/checkers/external/test_pre_invocation.py
index 3ab7848f5..eba3f54d7 100644
--- a/backend/tests/checkers/external/test_pre_invocation.py
+++ b/backend/tests/checkers/external/test_pre_invocation.py
@@ -1,4 +1,7 @@
 """Receipt contract proof with synthetic, unqualified provider observations."""
+
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+from app.modules.checkers.api.source_contracts import source_contracts_context
 import json
 from copy import deepcopy
 from dataclasses import replace
@@ -58,16 +61,16 @@ def lease():
 def test_received_failure_retains_receipt_in_authority_digest(lease, managed, disposition, outcome, reason):
     body = receipt_body(lease, outcome=outcome, reason=reason, managed=managed)
     body["cleanup"]["disposition"] = disposition
-    receipt = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
+    receipt = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body), context=source_contracts_context(selected_pre_submit_source_contracts()))
     result = SelectedPreSubmitInvocationResult(receipt, None)
-    result.validate_lease(lease)
-    assert SelectedPreSubmitInvocationResult.from_canonical_body(result.canonical_body()) == result
-    facts = SelectedPreSubmitFinalizeFacts(lease, None, receipt, reason)
-    assert facts.facts_digest != replace(facts, invocation_receipt=None).facts_digest
+    result.validate_lease(lease, source_contracts=selected_pre_submit_source_contracts())
+    assert SelectedPreSubmitInvocationResult.from_canonical_body(result.canonical_body(), source_contracts=selected_pre_submit_source_contracts()) == result
+    facts = SelectedPreSubmitFinalizeFacts(lease, None, receipt, reason, source_contracts=selected_pre_submit_source_contracts())
+    assert facts.facts_digest != replace(facts, invocation_receipt=None, source_contracts=selected_pre_submit_source_contracts()).facts_digest
     changed = deepcopy(body)
     changed["cleanup"]["disposition"] = "pending" if disposition == "destroyed" else "destroyed"
-    other = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(changed))
-    assert replace(facts, invocation_receipt=other).facts_digest != facts.facts_digest
+    other = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(changed), context=source_contracts_context(selected_pre_submit_source_contracts()))
+    assert replace(facts, invocation_receipt=other, source_contracts=selected_pre_submit_source_contracts()).facts_digest != facts.facts_digest
 
 
 @pytest.mark.parametrize("field", ["run_id", "source_operation_id", "request_digest", "source_sha256",
@@ -77,7 +80,7 @@ def test_invocation_cannot_move_between_requests_or_leases(lease, field):
     body["invocation"][field] = (2 if field == "lease_generation" else str(new_record_id())
                                  if field.endswith("_id") else "sha256:" + "f" * 64)
     with pytest.raises(ValueError):
-        SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body)).validate_lease(lease)
+        SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body), context=source_contracts_context(selected_pre_submit_source_contracts())).validate_lease(lease, source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.parametrize("change", ["negative", "boolean", "overflow", "sum", "extra", "wrong_cleanup", "outcome"])
@@ -94,7 +97,7 @@ def test_receipt_rejects_malformed_observations(lease, change):
     else:
         body["reason"] = "invalid_output"
     with pytest.raises(ValueError):
-        SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
+        SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body), context=source_contracts_context(selected_pre_submit_source_contracts()))
 
 
 @pytest.mark.parametrize("managed", [False, True])
@@ -112,14 +115,14 @@ def test_completed_worker_is_bound_to_provider_receipt(managed):
             provider="managed", platform_manifest_digest=member.isolation.platform_manifest_digest,
             config_image_id=member.isolation.config_image_id, deployment_sha256=body["runtime"]["deployment_sha256"],
         )
-        execution = replace(execution, external_members=(replace(member, isolation=isolation),))
-    receipt = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
-    SelectedPreSubmitInvocationResult(receipt, execution).validate_lease(lease)
-    assert SelectedPreSubmitFinalizeFacts(lease, execution, receipt, None).execution == execution
+        execution = replace(execution, external_members=(replace(member, isolation=isolation),), source_contracts=selected_pre_submit_source_contracts())
+    receipt = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body), context=source_contracts_context(selected_pre_submit_source_contracts()))
+    SelectedPreSubmitInvocationResult(receipt, execution).validate_lease(lease, source_contracts=selected_pre_submit_source_contracts())
+    assert SelectedPreSubmitFinalizeFacts(lease, execution, receipt, None, source_contracts=selected_pre_submit_source_contracts()).execution == execution
     body["invocation"]["config_image_id"] = "sha256:" + "f" * 64
-    forged = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
+    forged = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body), context=source_contracts_context(selected_pre_submit_source_contracts()))
     with pytest.raises(ValueError, match="image configuration"):
-        SelectedPreSubmitInvocationResult(forged, execution).validate_lease(lease)
+        SelectedPreSubmitInvocationResult(forged, execution).validate_lease(lease, source_contracts=selected_pre_submit_source_contracts())
     with pytest.raises(ValueError):
         SelectedPreSubmitInvocationResult(receipt, None)
 
@@ -148,12 +151,12 @@ def test_source_reads_preserve_schema_and_reject_rebound_columns(version, status
                       infrastructure_failure_code="capacity_exceeded" if failed else None,
                       queued_at=now, started_at=now, completed_at=now)
         if version == "v2":
-            terminal = HistoricalSourcePreSubmitTerminal(**values)
+            terminal = HistoricalSourcePreSubmitTerminal(**values, source_contracts=selected_pre_submit_source_contracts())
         else:
             body = receipt_body(lease, outcome="infrastructure_failure" if failed else "completed",
                                 reason="capacity_exceeded" if failed else None)
             terminal = SelectedPreSubmitTerminalFacts(**values,
-                invocation_receipt=SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body)))
+                invocation_receipt=SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body), context=source_contracts_context(selected_pre_submit_source_contracts())), source_contracts=selected_pre_submit_source_contracts())
     row = SimpleNamespace(
         **{key: str(getattr(request, key)) for key in (
             "actor_profile_id", "identity_link_id", "project_id", "task_id", "assignment_id", "idempotency_key")},
@@ -173,16 +176,16 @@ def test_source_reads_preserve_schema_and_reject_rebound_columns(version, status
         queued_at=now, started_at=now if status != "queued" else None,
         completed_at=now if terminal else None,
     )
-    assert _view(row).terminal == terminal
+    assert _view(row, source_contracts=selected_pre_submit_source_contracts()).terminal == terminal
     if terminal is None:
         original = row.lease_generation
         row.lease_generation = -1
         with pytest.raises(SelectedPreSubmitUnavailable):
-            _view(row)
+            _view(row, source_contracts=selected_pre_submit_source_contracts())
         row.lease_generation = original
     row.source_operation_id = str(new_record_id())
     with pytest.raises(SelectedPreSubmitUnavailable):
-        _view(row)
+        _view(row, source_contracts=selected_pre_submit_source_contracts())
 
 
 def test_python_decodes_shared_production_rust_wire_fixture():
@@ -198,14 +201,14 @@ def test_python_decodes_shared_production_rust_wire_fixture():
     wire = json.loads(Path(emitted).read_bytes()) if emitted else fixture["wire"]
     assert wire == fixture["wire"]
     assert "adapter_provider_key" not in wire
-    request = SelectedPreSubmitReservationFacts.from_canonical_body(fixture["reservation"])
+    request = SelectedPreSubmitReservationFacts.from_canonical_body(fixture["reservation"], source_contracts=selected_pre_submit_source_contracts())
     lease = SelectedPreSubmitLeaseFacts(
         request, UUID(wire["invocation"]["lease_id"]), wire["invocation"]["lease_generation"],
         datetime.fromisoformat(fixture["lease_expires_at"]),
     )
     # The real Unix-socket adapter attaches its trusted factory identity.
-    result = SelectedPreSubmitInvocationResult.from_canonical_body(wire | {"adapter_provider_key": "unix_socket"})
-    result.validate_lease(lease)
+    result = SelectedPreSubmitInvocationResult.from_canonical_body(wire | {"adapter_provider_key": "unix_socket"}, source_contracts=selected_pre_submit_source_contracts())
+    result.validate_lease(lease, source_contracts=selected_pre_submit_source_contracts())
     assert result.execution.eligible and result.receipt.cleanup.disposition == "destroyed"
 
 
@@ -222,7 +225,7 @@ async def test_managed_port_retains_receipt_and_enforces_selected_factory(lease,
         reason="cancelled" if case == "cancelled" else "capacity_exceeded")
     body["adapter_provider_key"] = "managed_test"
     body["cleanup"]["disposition"] = "pending"
-    result = SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None})
+    result = SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None}, source_contracts=selected_pre_submit_source_contracts())
     grant = object()
 
     class ManagedAdapter:
@@ -237,7 +240,7 @@ async def execute_pre(self, actual_lease, actual_grant):
             assert actual_lease == lease and actual_grant is grant
             return result
 
-    processor = SelectedPreSubmitProcessor(lease=lease, execution=ManagedAdapter())
+    processor = SelectedPreSubmitProcessor(lease=lease, execution=ManagedAdapter(), source_contracts=selected_pre_submit_source_contracts())
     if case == "cancelled":
         with pytest.raises(asyncio.CancelledError):
             await processor.process(grant)
diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py
index 3f2d40690..58ca6ee1b 100644
--- a/backend/tests/checkers/external/test_runtime.py
+++ b/backend/tests/checkers/external/test_runtime.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 import asyncio
 from dataclasses import replace
 import hashlib
@@ -57,8 +59,12 @@
 from app.modules.artifacts.submission_archive import (
     SubmissionArchiveInspector,
 )
-from app.modules.artifacts.submission_manifest import build_submission_manifest
-from app.modules.artifacts.submission_manifest import SUBMISSION_MANIFEST_SCHEMA_VERSION
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
+from app.modules.artifacts.api.submission_manifest import (
+    SUBMISSION_MANIFEST_SCHEMA_VERSION,
+)
 from app.modules.checkers.api.external import (
     ExternalCheckerContractError,
     ExternalCheckerExecutionRequest,
@@ -1123,7 +1129,7 @@ def _pre_transport_processor(lease, socket, changed):
     from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor
     adapter = UnixSocketExternalCheckerAdapter(
         socket_path=socket, timeout_seconds=0.2 if changed == "slow_decode" else 5.0,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     if changed in {"configured", "model_wrapper"}:
         from app.adapters.checkers import (
             selected_pre_submit_checker_execution, configured_post_submit_external_execution,
@@ -1142,7 +1148,7 @@ def forbidden_sessions():
             wrapped = configured_post_submit_external_execution(settings, sessions=forbidden_sessions)
             processor = SelectedPreSubmitCheckerExecutionAdapter(external_execution=wrapped).build(lease)
     else:
-        processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter)
+        processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter, source_contracts=selected_pre_submit_source_contracts())
     return processor
 
 
@@ -1275,7 +1281,7 @@ class NoSource:
         def open_source(self, **kwargs):
             raise AssertionError("expired execution opened source")
 
-    adapter = UnixSocketExternalCheckerAdapter(socket_path=tmp_path / "absent.sock", timeout_seconds=5.0)
+    adapter = UnixSocketExternalCheckerAdapter(socket_path=tmp_path / "absent.sock", timeout_seconds=5.0, source_contracts=selected_pre_submit_source_contracts())
     with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="deadline_exceeded"):
         await adapter.execute_pre(lease, NoSource())
 
@@ -1308,8 +1314,8 @@ async def handle(reader, writer):
 
     socket = tmp_path / "cancel.sock"
     server = await asyncio.start_unix_server(handle, socket)
-    adapter = UnixSocketExternalCheckerAdapter(socket_path=socket, timeout_seconds=5.0)
-    processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter)
+    adapter = UnixSocketExternalCheckerAdapter(socket_path=socket, timeout_seconds=5.0, source_contracts=selected_pre_submit_source_contracts())
+    processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter, source_contracts=selected_pre_submit_source_contracts())
     task = asyncio.create_task(processor.process(Grant()))
     try:
         await asyncio.wait_for(entered.wait(), 2)
diff --git a/backend/tests/checkers/external/test_selected_pre_submit.py b/backend/tests/checkers/external/test_selected_pre_submit.py
index 075f6ccf3..cbb9ea2cd 100644
--- a/backend/tests/checkers/external/test_selected_pre_submit.py
+++ b/backend/tests/checkers/external/test_selected_pre_submit.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 from tests.trusted_intake_fixtures import LocalIntakeSession
 from app.modules.artifacts.trusted_intake import TrustedArchiveInspector
 from app.modules.artifacts.submission_materialization import _TrustedPreSubmitProcessor
@@ -81,9 +83,11 @@
 from app.modules.artifacts.submission_archive import (
     SubmissionArchiveInspector,
 )
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 from app.modules.artifacts.submission_manifest import (
     SubmissionCanonicalPredecessor,
-    build_submission_manifest,
     semantic_manifest_identity,
     evaluate_submission_change,
 )
@@ -163,7 +167,7 @@ def _selected_admission_reservation():
         semantic_manifest_sha256=canonical_json_hash(manifest),
         execution_budget_ms=120_000,
         admission_lineage=lineage,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     return manifest, post_policy, selected
 
 
@@ -171,7 +175,7 @@ def test_revision_acknowledgement_changes_selected_request_and_retains_old_bytes
     """A new acknowledgement is frozen; old selected requests keep their digest."""
     _, _, retained = _selected_admission_reservation()
     old_body = retained.canonical_body()
-    assert SelectedPreSubmitReservationFacts.from_canonical_body(old_body).canonical_body() == old_body
+    assert SelectedPreSubmitReservationFacts.from_canonical_body(old_body, source_contracts=selected_pre_submit_source_contracts()).canonical_body() == old_body
     assert "revision_preparation_id" not in old_body["admission_lineage"]
 
     predecessor_id, manifest_id, preparation_id = (
@@ -189,12 +193,12 @@ def test_revision_acknowledgement_changes_selected_request_and_retains_old_bytes
     body = selected.canonical_body()
     assert body["admission_lineage"]["revision_preparation_id"] == str(preparation_id)
     assert body["admission_lineage"]["revision_preparation_sha256"] == _hex_sha("b")
-    assert SelectedPreSubmitReservationFacts.from_canonical_body(body).request_digest == selected.request_digest
+    assert SelectedPreSubmitReservationFacts.from_canonical_body(body, source_contracts=selected_pre_submit_source_contracts()).request_digest == selected.request_digest
     null_ack = dict(body)
     null_ack["admission_lineage"] = dict(body["admission_lineage"])
     null_ack["admission_lineage"]["revision_preparation_id"] = None
     with pytest.raises(ValueError, match="selected PRE admission lineage is invalid"):
-        SelectedPreSubmitReservationFacts.from_canonical_body(null_ack)
+        SelectedPreSubmitReservationFacts.from_canonical_body(null_ack, source_contracts=selected_pre_submit_source_contracts())
 
     request = dict(
         actor_profile_id=selected.actor_profile_id,
@@ -428,7 +432,7 @@ def _processor(*, request, policy, default_input, identity, material, grants, ex
     checker = SelectedPreSubmitProcessor(
         policy=policy, default_input=default_input, identity=identity,
         material=material, execution=execution,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     request = replace(request, default_checker_input=default_input, external_policy=policy,
                       selected_reservation=replace(request.selected_reservation,
                           policy_sha256=policy.policy_sha256,
@@ -650,7 +654,7 @@ def _assert_terminal_round_trip(identity, policy, default_input, material, resul
         archive_byte_count=material.archive_byte_count,
         semantic_manifest_sha256=material.semantic_manifest_sha256,
         execution_budget_ms=120_000,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     lease = SelectedPreSubmitLeaseFacts(
         reservation=reservation,
         lease_id=new_record_id(),
@@ -665,15 +669,15 @@ def _assert_terminal_round_trip(identity, policy, default_input, material, resul
         queued_at=now,
         started_at=now + timedelta(milliseconds=25),
         completed_at=now + timedelta(milliseconds=75),
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     assert terminal.canonical_body()["queue_latency_ms"] == 25
     assert terminal.canonical_body()["execution_latency_ms"] == 50
     assert terminal.canonical_body()["request_digest"] == reservation.request_digest
     assert terminal.terminal_digest == canonical_json_hash(terminal.canonical_body())
-    assert SelectedPreSubmitTerminalFacts.from_canonical_body(terminal.canonical_body()) == terminal
+    assert SelectedPreSubmitTerminalFacts.from_canonical_body(terminal.canonical_body(), source_contracts=selected_pre_submit_source_contracts()) == terminal
     changed_terminal = terminal.canonical_body() | {"queue_latency_ms": 26}
     with pytest.raises(ValueError, match="terminal facts"):
-        SelectedPreSubmitTerminalFacts.from_canonical_body(changed_terminal)
+        SelectedPreSubmitTerminalFacts.from_canonical_body(changed_terminal, source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.asyncio
diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
index 0850a569f..6b1cf5497 100644
--- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
+++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
@@ -2,6 +2,11 @@
 
 from __future__ import annotations
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+from app.modules.checkers.api.source_contracts import source_contracts_context
+
+from app.modules.artifacts.selected_pre_submit_source_custody import SelectedPreSubmitSourceCustody
+
 import json
 
 from dataclasses import replace
@@ -69,7 +74,7 @@ def _reservation() -> SelectedPreSubmitReservationFacts:
         archive_byte_count=1024,
         semantic_manifest_sha256="sha256:" + "4" * 64,
         execution_budget_ms=120_000,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
 
 
 def _queued_row(reservation: SelectedPreSubmitReservationFacts) -> SimpleNamespace:
@@ -109,7 +114,7 @@ async def test_selected_pre_current_replays_only_stable_actor_key_facts() -> Non
         scalar=AsyncMock(return_value=row),
     )
     tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock())
-    coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks)
+    coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, source_contracts=selected_pre_submit_source_contracts())
     fresh = replace(
         stored,
         attempt_id=new_record_id(),
@@ -147,7 +152,7 @@ async def test_selected_pre_expired_lease_read_keeps_task_first_custody() -> Non
         scalar=AsyncMock(side_effect=[row, now]),
     )
     tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock())
-    coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks)
+    coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, source_contracts=selected_pre_submit_source_contracts())
 
     lease = await coordinator.read_expired_lease(
         run_id=reservation.attempt_id,
@@ -349,7 +354,7 @@ def test_selected_pre_authority_digests_bind_lease_and_infrastructure_outcome()
         lease=lease,
         execution=None,
         infrastructure_failure_code="deadline_exceeded",
-    )
+     source_contracts=selected_pre_submit_source_contracts())
 
     assert execution.facts_digest != changed.facts_digest
     assert (
@@ -358,14 +363,14 @@ def test_selected_pre_authority_digests_bind_lease_and_infrastructure_outcome()
             lease=lease,
             execution=None,
             infrastructure_failure_code="material_unavailable",
-        ).facts_digest
+         source_contracts=selected_pre_submit_source_contracts()).facts_digest
     )
     with pytest.raises(ValueError, match="outcome"):
         SelectedPreSubmitFinalizeFacts(
             lease=lease,
             execution=None,
             infrastructure_failure_code=None,
-        )
+         source_contracts=selected_pre_submit_source_contracts())
 
 
 def test_selected_pre_request_binds_complete_later_admission_lineage() -> None:
@@ -404,7 +409,7 @@ def test_selected_pre_request_binds_complete_later_admission_lineage() -> None:
 
     assert reservation.canonical_body()["admission_lineage"] == lineage.canonical_body()
     assert (
-        SelectedPreSubmitReservationFacts.from_canonical_body(reservation.canonical_body())
+        SelectedPreSubmitReservationFacts.from_canonical_body(reservation.canonical_body(), source_contracts=selected_pre_submit_source_contracts())
         == reservation
     )
     assert (
@@ -528,12 +533,12 @@ def test_historical_pre_decoder_preserves_exact_request_and_terminal_bytes(name)
     assert terminal.canonical_body() == retained["terminal"]
     assert terminal.terminal_digest == retained["terminal_digest"]
     row = _retained_row(retained)
-    view = _view(row)
+    view = _view(row, source_contracts=selected_pre_submit_source_contracts())
     assert type(view.terminal) is HistoricalSelectedPreSubmitTerminal
     assert view.terminal.canonical_body() == retained["terminal"]
     row.terminal_digest = "sha256:" + "f" * 64
     with pytest.raises(SelectedPreSubmitUnavailable):
-        _view(row)
+        _view(row, source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.asyncio
@@ -546,7 +551,7 @@ async def test_historical_pre_values_cannot_become_live_reservation_or_lease():
     tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock())
     sources = SimpleNamespace(lock_pre_source=AsyncMock())
     async with AsyncSession() as session, session.begin():
-        coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, sources=sources)
+        coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, sources=SelectedPreSubmitSourceCustody(sources), source_contracts=selected_pre_submit_source_contracts())
         with pytest.raises(TypeError, match="reservation facts are invalid"):
             await coordinator.reserve(request)
     tasks.lock_selected_pre_submit_scope.assert_not_awaited()
@@ -586,7 +591,7 @@ def test_historical_pre_read_rejects_foreign_row_selectors_and_facts(field, valu
     row = _retained_row(_retained_v1())
     setattr(row, field, value)
     with pytest.raises(SelectedPreSubmitUnavailable):
-        _view(row)
+        _view(row, source_contracts=selected_pre_submit_source_contracts())
 
 
 def test_historical_pre_decoder_rejects_an_unknown_outcome():
@@ -608,7 +613,7 @@ def test_historical_nonterminal_pre_remains_readable_without_inventing_an_outcom
     if status == "queued":
         row.started_at = row.lease_id = row.lease_expires_at = None
         row.lease_generation = 0
-    view = _view(row)
+    view = _view(row, source_contracts=selected_pre_submit_source_contracts())
     assert view.status == status and view.terminal is None and view.completed_at is None
 
 
@@ -672,20 +677,20 @@ def _source_reservation() -> SelectedPreSubmitReservationFacts:
             current_rules_sha256=lineage.rules_sha256, predecessor_rules_sha256=None,
             packet=packet,
         ),
-        runtime_profile=SelectedPreSubmitRuntimeProfile(
+        runtime_profile=SelectedPreSubmitRuntimeProfile.model_validate(dict(
             profile_id="test-only", platform_root_sha256=SHA, cpu_millis=2000,
             memory_bytes=2 * 1024**3, temporary_disk_bytes=4 * 1024**3,
             maximum_processes=64, maximum_output_bytes=1024 * 1024,
             maximum_log_bytes=1024 * 1024, aggregate_deadline_ms=120_000,
             archive_limits=SubmissionArchiveLimits(maximum_inspection_seconds=60),
-        ), admission_lineage=lineage,
-    )
+        ), context=source_contracts_context(selected_pre_submit_source_contracts())), admission_lineage=lineage,
+     source_contracts=selected_pre_submit_source_contracts())
 
 
 def test_source_first_reservation_round_trip_without_derived_inputs() -> None:
     request = _source_reservation()
     body = request.canonical_body()
-    assert SelectedPreSubmitReservationFacts.from_canonical_body(body) == request
+    assert SelectedPreSubmitReservationFacts.from_canonical_body(body, source_contracts=selected_pre_submit_source_contracts()) == request
     assert body["source_sha256"] == request.source.source_sha256()
     assert not {"prepared_generation_id", "default_input_sha256", "semantic_manifest_sha256"} & body.keys()
     assert "semantic_manifest_body" not in body["admission_lineage"]
@@ -703,7 +708,7 @@ def test_source_first_reservation_rejects_substituted_source(field: str) -> None
         "raw_byte_count": 1025, "sealed_upload_fence": 2,
     }[field]
     with pytest.raises(ValueError):
-        SelectedPreSubmitReservationFacts.from_canonical_body(body)
+        SelectedPreSubmitReservationFacts.from_canonical_body(body, source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.parametrize("field", [
@@ -714,19 +719,19 @@ def test_source_first_reservation_rejects_unobserved_or_mutable_facts(field: str
     body = _source_reservation().canonical_body()
     body[field] = SHA
     with pytest.raises(ValueError):
-        SelectedPreSubmitReservationFacts.from_canonical_body(body)
+        SelectedPreSubmitReservationFacts.from_canonical_body(body, source_contracts=selected_pre_submit_source_contracts())
 
 
 def test_source_first_reservation_binds_packet_and_hard_deadline() -> None:
     request = _source_reservation()
-    assert replace(request, pre_deadline_at=request.pre_deadline_at + timedelta(seconds=1)).request_digest != request.request_digest
+    assert replace(request, pre_deadline_at=request.pre_deadline_at + timedelta(seconds=1), source_contracts=selected_pre_submit_source_contracts()).request_digest != request.request_digest
     with pytest.raises(ValueError):
-        replace(request, pre_deadline_at=datetime.now())
+        replace(request, pre_deadline_at=datetime.now(), source_contracts=selected_pre_submit_source_contracts())
     from app.modules.checkers.api.pre_submit_material import SubmissionPacketView
     with pytest.raises(ValueError):
         replace(request, default_context=replace(
             request.default_context, packet=SubmissionPacketView("substituted", ""),
-        ))
+        ), source_contracts=selected_pre_submit_source_contracts())
 
 
 def _source_guard(request):
@@ -761,7 +766,7 @@ async def test_source_first_reserve_checks_live_custody_before_checker_rows(fiel
         in_nested_transaction=lambda: False, scalar=AsyncMock(), execute=AsyncMock(),
     )
     tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock())
-    coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, sources=sources)
+    coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, sources=SelectedPreSubmitSourceCustody(sources), source_contracts=selected_pre_submit_source_contracts())
     with pytest.raises(SelectedPreSubmitUnavailable, match="source_changed"):
         await coordinator.reserve(request)
     tasks.lock_selected_pre_submit_scope.assert_awaited_once_with(request)
@@ -793,8 +798,8 @@ async def consume(facts):
         return SimpleNamespace(facts_digest=facts.facts_digest, evidence_id=new_record_id())
     coordinator = SelectedPreSubmitCoordinator(
         session, tasks=SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock()),
-        sources=_source_guard(request),
-    )
+        sources=SelectedPreSubmitSourceCustody(_source_guard(request)),
+     source_contracts=selected_pre_submit_source_contracts())
     authority = SimpleNamespace(consume=AsyncMock(side_effect=consume))
     lease = await coordinator.claim(run_id=request.attempt_id, facts=request, authority=authority)
     assert lease.lease_expires_at == request.pre_deadline_at
@@ -813,7 +818,7 @@ def test_source_first_lease_cannot_extend_aggregate_deadline() -> None:
 def test_source_first_policy_requires_exactly_one_project_image() -> None:
     from tests.checkers.external.test_selected_pre_submit import _empty_policy
     with pytest.raises(ValueError, match="locked context"):
-        replace(_source_reservation(), policy=_empty_policy())
+        replace(_source_reservation(), policy=_empty_policy(), source_contracts=selected_pre_submit_source_contracts())
 
 
 def test_source_first_profile_rejects_archive_time_beyond_aggregate() -> None:
@@ -822,7 +827,7 @@ def test_source_first_profile_rejects_archive_time_beyond_aggregate() -> None:
     with pytest.raises(ValueError, match="locked context"):
         replace(request, runtime_profile=request.runtime_profile.model_copy(update={
             "archive_limits": SubmissionArchiveLimits(maximum_inspection_seconds=121),
-        }))
+        }), source_contracts=selected_pre_submit_source_contracts())
 
 
 def _source_receipt(lease):
@@ -830,7 +835,7 @@ def _source_receipt(lease):
     from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInvocationReceipt
     from tests.checkers.external.test_pre_invocation import receipt_body
 
-    return SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(receipt_body(lease)))
+    return SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(receipt_body(lease)), context=source_contracts_context(selected_pre_submit_source_contracts()))
 
 
 def _source_completed_execution(reservation):
@@ -851,7 +856,7 @@ def _source_completed_execution(reservation):
     lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at)
     value, request = derive_selected_pre_submit_input(
         lease, manifest_body=manifest, manifest_sha256=manifest_sha256,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     selected = reservation.policy.entries[0]
     result = make_external_checker_execution_result(
         request_digest=request.request_digest, registry_entry_id=selected.registry.registry_entry_id,
@@ -875,7 +880,7 @@ def _source_completed_execution(reservation):
                  "runtime": "smolvm", "isolation_mode": "smol-microvm"}
             )),
         ),),
-    )
+     source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.parametrize("changed", [
@@ -905,22 +910,22 @@ def test_source_first_finalization_binds_actual_selected_member(changed):
         member = replace(member, isolation=replace(
             member.isolation, platform_manifest_digest="sha256:" + "f" * 64,
         ))
-    execution = replace(execution, external_members=(member,))
+    execution = replace(execution, external_members=(member,), source_contracts=selected_pre_submit_source_contracts())
     if changed == "missing":
-        execution = replace(execution, external_members=(), eligible=False)
+        execution = replace(execution, external_members=(), eligible=False, source_contracts=selected_pre_submit_source_contracts())
     now = datetime.now(UTC)
     lease = SelectedPreSubmitLeaseFacts(
         reservation=reservation, lease_id=execution.lease_id, lease_generation=execution.lease_generation,
         lease_expires_at=reservation.pre_deadline_at,
     )
     def finalize():
-        return SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None)
+        return SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None, source_contracts=selected_pre_submit_source_contracts())
     def terminal():
-        return SelectedPreSubmitTerminalFacts(lease, "completed", execution, _source_receipt(lease), None, now, now, now)
+        return SelectedPreSubmitTerminalFacts(lease, "completed", execution, _source_receipt(lease), None, now, now, now, source_contracts=selected_pre_submit_source_contracts())
     if changed is None:
         assert finalize().execution == execution
         value = terminal()
-        assert SelectedPreSubmitTerminalFacts.from_canonical_body(value.canonical_body()) == value
+        assert SelectedPreSubmitTerminalFacts.from_canonical_body(value.canonical_body(), source_contracts=selected_pre_submit_source_contracts()) == value
     else:
         for construct in (finalize, terminal):
             with pytest.raises(ValueError, match="execution selection"):
@@ -930,7 +935,7 @@ def terminal():
 def test_source_first_execution_cannot_claim_zero_required_project_checks():
     execution = _source_completed_execution(_source_reservation())
     with pytest.raises(ValueError, match="execution facts"):
-        replace(execution, required_external_count=0, external_members=(), eligible=True)
+        replace(execution, required_external_count=0, external_members=(), eligible=True, source_contracts=selected_pre_submit_source_contracts())
 
 
 def test_source_first_default_rejection_does_not_require_project_result():
@@ -939,6 +944,7 @@ def test_source_first_default_rejection_does_not_require_project_result():
     reservation = _source_reservation()
     execution = replace(
         _source_completed_execution(reservation),
+        source_contracts=selected_pre_submit_source_contracts(),
         workstream_default=evaluate_rejected_archive(
             "submission_archive_malformed", packet=reservation.default_context.packet,
         ), external_members=(), eligible=False,
@@ -947,7 +953,7 @@ def test_source_first_default_rejection_does_not_require_project_result():
     lease = SelectedPreSubmitLeaseFacts(
         reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at,
     )
-    assert SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None).execution == execution
+    assert SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None, source_contracts=selected_pre_submit_source_contracts()).execution == execution
 
 
 @pytest.mark.parametrize("boundary", ["finalization", "terminal"])
@@ -958,16 +964,16 @@ def test_source_first_result_digest_revalidated_before_terminal_write(boundary):
     execution = _source_completed_execution(reservation)
     member = execution.external_members[0]
     forged = member.result.model_copy(update={"result_digest": "sha256:" + "f" * 64})
-    execution = replace(execution, external_members=(replace(member, result=forged),))
+    execution = replace(execution, external_members=(replace(member, result=forged),), source_contracts=selected_pre_submit_source_contracts())
     lease = SelectedPreSubmitLeaseFacts(
         reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at,
     )
     now = datetime.now(UTC)
     with pytest.raises(ValueError, match="result digest mismatch"):
         if boundary == "finalization":
-            SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None)
+            SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None, source_contracts=selected_pre_submit_source_contracts())
         else:
-            SelectedPreSubmitTerminalFacts(lease, "completed", execution, _source_receipt(lease), None, now, now, now)
+            SelectedPreSubmitTerminalFacts(lease, "completed", execution, _source_receipt(lease), None, now, now, now, source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.parametrize("changed", [
@@ -985,11 +991,11 @@ def test_source_first_completed_evidence_rejects_substitution(changed):
         reservation, execution.lease_id, execution.lease_generation, reservation.pre_deadline_at,
     )
     if changed == "request":
-        execution = replace(execution, request_digest="sha256:" + "f" * 64)
+        execution = replace(execution, request_digest="sha256:" + "f" * 64, source_contracts=selected_pre_submit_source_contracts())
     elif changed == "lease_id":
-        execution = replace(execution, lease_id=new_record_id())
+        execution = replace(execution, lease_id=new_record_id(), source_contracts=selected_pre_submit_source_contracts())
     elif changed == "lease_generation":
-        execution = replace(execution, lease_generation=execution.lease_generation + 1)
+        execution = replace(execution, lease_generation=execution.lease_generation + 1, source_contracts=selected_pre_submit_source_contracts())
     elif changed.startswith("source_"):
         source = execution.observed_source
         field, value = {
@@ -1000,15 +1006,15 @@ def test_source_first_completed_evidence_rejects_substitution(changed):
                 "operation_id": new_record_id(),
             })),
         }[changed]
-        execution = replace(execution, observed_source=source.model_copy(update={field: value}))
+        execution = replace(execution, observed_source=source.model_copy(update={field: value}), source_contracts=selected_pre_submit_source_contracts())
     elif changed == "default_input":
-        execution = replace(execution, default_input_sha256="sha256:" + "f" * 64)
+        execution = replace(execution, default_input_sha256="sha256:" + "f" * 64, source_contracts=selected_pre_submit_source_contracts())
     elif changed == "manifest":
         body = deepcopy(execution.manifest_body)
         body["entries"][0]["normalized_path"] = "../escape"
-        execution = replace(execution, manifest_body=body, manifest_sha256=canonical_json_hash(body))
+        execution = replace(execution, manifest_body=body, manifest_sha256=canonical_json_hash(body), source_contracts=selected_pre_submit_source_contracts())
     elif changed == "missing_manifest":
-        execution = replace(execution, manifest_body=None, manifest_sha256=None, default_input_sha256=None)
+        execution = replace(execution, manifest_body=None, manifest_sha256=None, default_input_sha256=None, source_contracts=selected_pre_submit_source_contracts())
     elif changed == "project_request":
         member = execution.external_members[0]
         # Echo agreement plus a valid result digest is insufficient: the owner
@@ -1019,9 +1025,9 @@ def test_source_first_completed_evidence_rejects_substitution(changed):
         ))
         execution = replace(execution, external_members=(replace(
             member, request_digest=result.request_digest, result=result,
-        ),))
+        ),), source_contracts=selected_pre_submit_source_contracts())
     with pytest.raises(ValueError):
-        SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None)
+        SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None, source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.parametrize("limit", ["maximum_entries", "maximum_path_bytes", "maximum_entry_bytes"])
@@ -1034,12 +1040,12 @@ def test_source_first_derived_manifest_obeys_locked_limits(limit):
     profile = reservation.runtime_profile.model_copy(update={
         "archive_limits": SubmissionArchiveLimits(**{limit: 1}, maximum_inspection_seconds=60),
     })
-    reservation = replace(reservation, runtime_profile=profile)
+    reservation = replace(reservation, runtime_profile=profile, source_contracts=selected_pre_submit_source_contracts())
     lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at)
     with pytest.raises(ValueError):
         derive_selected_pre_submit_input(
             lease, manifest_body=execution.manifest_body, manifest_sha256=execution.manifest_sha256,
-        )
+         source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.parametrize("failure", ["high_confidence_secret_detected", "submission_archive_unchanged"])
@@ -1066,7 +1072,7 @@ def test_source_first_default_blocker_does_not_validate_unrun_project_schema(fai
     ))
     reservation = replace(reservation, policy=policy, admission_lineage=replace(
         reservation.admission_lineage, effective_plan_sha256=policy.policy_sha256,
-    ))
+    ), source_contracts=selected_pre_submit_source_contracts())
     if failure == "submission_archive_unchanged":
         from app.modules.checkers.api.default_checker import WorkstreamDefaultPredecessor
         predecessor = WorkstreamDefaultPredecessor(
@@ -1080,15 +1086,15 @@ def test_source_first_default_blocker_does_not_validate_unrun_project_schema(fai
                 reservation.admission_lineage, predecessor_submission_id=predecessor.submission_id,
                 predecessor_submission_version=1, checker_remediation_manifest_id=new_record_id(),
             ),
-        )
+         source_contracts=selected_pre_submit_source_contracts())
     lease = SelectedPreSubmitLeaseFacts(reservation, execution.lease_id, 1, reservation.pre_deadline_at)
     default_input = derive_selected_pre_submit_default_input(
         lease, manifest_body=execution.manifest_body, manifest_sha256=execution.manifest_sha256,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
     with pytest.raises(ValueError):
         derive_selected_pre_submit_input(
             lease, manifest_body=execution.manifest_body, manifest_sha256=execution.manifest_sha256,
-        )
+         source_contracts=selected_pre_submit_source_contracts())
     default = execution.workstream_default.model_dump()
     checks = list(default["checks"])
     index = 2 if failure == "high_confidence_secret_detected" else 3
@@ -1098,5 +1104,44 @@ def test_source_first_default_blocker_does_not_validate_unrun_project_schema(fai
         execution, request_digest=reservation.request_digest, policy_sha256=policy.policy_sha256,
         workstream_default=WorkstreamDefaultCheckerResult.model_validate(default),
         default_input_sha256=workstream_default_input_sha256(default_input), external_members=(), eligible=False,
+     source_contracts=selected_pre_submit_source_contracts())
+    assert SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None, source_contracts=selected_pre_submit_source_contracts()).execution == execution
+
+
+def test_source_validation_dependency_is_not_retained_in_request():
+    from dataclasses import fields
+
+    request = _source_reservation()
+    assert "source_contracts" not in {item.name for item in fields(request)}
+    assert "source_contracts" not in request.canonical_body()
+    with pytest.raises(TypeError, match="source_contracts"):
+        SelectedPreSubmitReservationFacts.from_canonical_body(request.canonical_body())
+
+
+def test_nested_receipt_requires_explicit_source_validation_context():
+    from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitInvocationReceipt
+
+    reservation = _source_reservation()
+    lease = SelectedPreSubmitLeaseFacts(
+        reservation, new_record_id(), 1, reservation.pre_deadline_at,
+    )
+    body = _source_receipt(lease).canonical_body()
+    with pytest.raises(ValueError, match="source contracts are required"):
+        SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body))
+    context = source_contracts_context(selected_pre_submit_source_contracts())
+    recovered = SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body), context=context)
+    assert recovered.canonical_body() == body
+    body["runtime"]["profile"]["archive_limits"]["maximum_entries"] = True
+    with pytest.raises(ValueError):
+        SelectedPreSubmitInvocationReceipt.model_validate_json(json.dumps(body), context=context)
+
+
+def test_source_profile_preserves_float_wire_representation():
+    request = _source_reservation()
+    profile = request.runtime_profile.model_dump(mode="json")
+    assert type(profile["archive_limits"]["maximum_inspection_seconds"]) is float
+    assert profile["archive_limits"]["maximum_inspection_seconds"] == 60.0
+    restored = SelectedPreSubmitReservationFacts.from_canonical_body(
+        request.canonical_body(), source_contracts=selected_pre_submit_source_contracts(),
     )
-    assert SelectedPreSubmitFinalizeFacts(lease, execution, _source_receipt(lease), None).execution == execution
+    assert restored.request_digest == request.request_digest
diff --git a/backend/tests/checkers/external/test_selected_pre_submit_service.py b/backend/tests/checkers/external/test_selected_pre_submit_service.py
index cf9f8469a..efd693a4c 100644
--- a/backend/tests/checkers/external/test_selected_pre_submit_service.py
+++ b/backend/tests/checkers/external/test_selected_pre_submit_service.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 from contextlib import asynccontextmanager
 from datetime import UTC, datetime, timedelta
 from types import SimpleNamespace
@@ -101,7 +103,7 @@ async def finalize(self, *, authority, execution, infrastructure_failure_code, *
             lease=self.lease,
             execution=execution,
             infrastructure_failure_code=infrastructure_failure_code,
-        )
+         source_contracts=selected_pre_submit_source_contracts())
         await authority.consume(facts)
         return SimpleNamespace(terminal=facts, capability=None)
 
@@ -135,7 +137,7 @@ def _reservation() -> SelectedPreSubmitReservationFacts:
         archive_byte_count=100,
         semantic_manifest_sha256="sha256:" + "4" * 64,
         execution_budget_ms=60_000,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
 
 
 @pytest.mark.asyncio
diff --git a/backend/tests/contributor_reads/test_projection.py b/backend/tests/contributor_reads/test_projection.py
index ef8cf1a4d..6953121a4 100644
--- a/backend/tests/contributor_reads/test_projection.py
+++ b/backend/tests/contributor_reads/test_projection.py
@@ -1,5 +1,7 @@
 """A Submitter reads their own claim, attempt, preparation and totals through public routes."""
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 from datetime import UTC, datetime, timedelta
 from decimal import Decimal
 from types import SimpleNamespace
@@ -146,7 +148,7 @@ def _execution(eligible):
         workstream_default=WorkstreamDefaultCheckerResult(
             behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, eligible=eligible, checks=checks, warnings=(),
         ),
-    )
+     source_contracts=selected_pre_submit_source_contracts())
 
 
 _ADMISSION, _SUBMISSION = uuid4(), uuid4()
diff --git a/backend/tests/post_submit_materialization_helpers.py b/backend/tests/post_submit_materialization_helpers.py
index f26b9569a..efc6f13c6 100644
--- a/backend/tests/post_submit_materialization_helpers.py
+++ b/backend/tests/post_submit_materialization_helpers.py
@@ -29,7 +29,9 @@
 from app.modules.artifacts.submission_archive import (
     SubmissionArchiveInspector,
 )
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 from app.modules.authorization.api import ActorIdentityFacts, ActorKind
 from app.modules.tasks.api import SubmissionCreationRequest
 from app.modules.tasks.api.submitted_bundle import SubmittedBundleRequest
diff --git a/backend/tests/reviews/decision/support.py b/backend/tests/reviews/decision/support.py
index e16661aae..176fa7aa8 100644
--- a/backend/tests/reviews/decision/support.py
+++ b/backend/tests/reviews/decision/support.py
@@ -13,7 +13,9 @@
 from app.core.identifiers import new_record_id
 from app.modules.actors.models import ActorIdentityLink
 from app.modules.artifacts.api import SubmissionBundlePreparationRequest
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 from app.modules.authorization.api import ActorIdentityFacts, ActorKind
 from app.modules.checkers.models import CheckerRun
 from app.modules.reviews.decision.models import (
diff --git a/backend/tests/selected_predecessor_fixtures.py b/backend/tests/selected_predecessor_fixtures.py
index 61da9ecaf..64bbdd264 100644
--- a/backend/tests/selected_predecessor_fixtures.py
+++ b/backend/tests/selected_predecessor_fixtures.py
@@ -1,5 +1,7 @@
 """Selected PRE replacement evidence fixtures; no alternate execution owner."""
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 from dataclasses import replace
 from io import BytesIO
 from uuid import UUID
@@ -75,7 +77,7 @@ async def _assert_default_failure(h, request, failure, before, code: str) -> Non
                 )
             )
         ).one()
-        terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(run.terminal_json)
+        terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(run.terminal_json, source_contracts=selected_pre_submit_source_contracts())
         reservation = terminal.lease.reservation
         assert run.status == terminal.outcome == "completed"
         assert run.eligible is False and terminal.execution == failure.facts
@@ -113,7 +115,7 @@ async def _queued_selected_body(h, admission_id, *, cause=None) -> dict:
             {"id": admission_id},
         )
     assert body is not None and body["status"] == "completed" and body["eligible"] is True
-    facts = SelectedPreSubmitReservationFacts.from_canonical_body(body["request_json"])
+    facts = SelectedPreSubmitReservationFacts.from_canonical_body(body["request_json"], source_contracts=selected_pre_submit_source_contracts())
     lineage = facts.admission_lineage
     assert lineage is not None
     key = new_record_id()
diff --git a/backend/tests/test_checker_materialization.py b/backend/tests/test_checker_materialization.py
index b9e2be81a..f474856d1 100644
--- a/backend/tests/test_checker_materialization.py
+++ b/backend/tests/test_checker_materialization.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 from io import BytesIO
 from dataclasses import replace
 import os
@@ -26,7 +28,9 @@
 from app.modules.artifacts.submission_archive import (
     SubmissionArchiveInspector,
 )
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 
 
 def _zip(*, executable: bool = False) -> bytes:
@@ -467,7 +471,7 @@ class Execution:
         async def execute_pre(self, lease, grant):
             assert b"".join([chunk async for chunk in grant.open_source(lease=lease)]) == value.payload
             raise SelectedPreSubmitInfrastructureUnavailable("capacity_exceeded")
-    processor = SelectedPreSubmitProcessor(lease=value.lease, execution=Execution())
+    processor = SelectedPreSubmitProcessor(lease=value.lease, execution=Execution(), source_contracts=selected_pre_submit_source_contracts())
     async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant:
         with pytest.raises(SelectedPreSubmitInfrastructureUnavailable) as error:
             await processor.process(grant)
@@ -488,7 +492,7 @@ async def execute_pre(self, lease, grant):
             assert await anext(reader) == value.payload
             started.set()
             await asyncio.Event().wait()
-    processor = SelectedPreSubmitProcessor(lease=value.lease, execution=Execution())
+    processor = SelectedPreSubmitProcessor(lease=value.lease, execution=Execution(), source_contracts=selected_pre_submit_source_contracts())
     async def foreground():
         async with value.issuer.issue(lease=value.lease, execution_authority=value.capability) as grant:
             await processor.process(grant)
diff --git a/backend/tests/test_submission_bundle_preparation_recovery.py b/backend/tests/test_submission_bundle_preparation_recovery.py
index 6bed6ca19..9d3a51e7d 100644
--- a/backend/tests/test_submission_bundle_preparation_recovery.py
+++ b/backend/tests/test_submission_bundle_preparation_recovery.py
@@ -1,5 +1,7 @@
 """Command recovery distinguishes checked failure, unavailable custody and authority."""
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 from tests.trusted_intake_fixtures import LocalIntakeAdapter
 from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits
 
@@ -64,7 +66,7 @@ def _feedback_facts(*, eligible: bool = False) -> SelectedPreSubmitExecutionFact
     return SelectedPreSubmitExecutionFacts(
         policy_sha256="sha256:" + "1" * 64, workstream_default=default,
         required_external_count=0, external_members=(), eligible=eligible,
-    )
+     source_contracts=selected_pre_submit_source_contracts())
 
 
 async def _mounted_preparation_response(error: RuntimeError):
diff --git a/backend/tests/test_submission_change_gate.py b/backend/tests/test_submission_change_gate.py
index b0e5cac56..a4aaf09a9 100644
--- a/backend/tests/test_submission_change_gate.py
+++ b/backend/tests/test_submission_change_gate.py
@@ -13,13 +13,15 @@
 from app.modules.artifacts.submission_archive import (
     SubmissionArchiveInspector,
 )
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 from app.modules.artifacts.submission_manifest import (
     SubmissionCanonicalPredecessor,
     SubmissionChangeFailureCode,
     SubmissionChangeOutcome,
     SubmissionChangeRejectedError,
     bind_submission_change,
-    build_submission_manifest,
     evaluate_submission_change,
 )
 
diff --git a/backend/tests/test_submission_manifest.py b/backend/tests/test_submission_manifest.py
index 0cb839e7e..893046128 100644
--- a/backend/tests/test_submission_manifest.py
+++ b/backend/tests/test_submission_manifest.py
@@ -13,7 +13,10 @@
 from app.modules.artifacts.submission_archive import (
     SubmissionArchiveInspector,
 )
-from app.modules.artifacts.submission_manifest import SubmissionManifest, build_submission_manifest
+from app.modules.artifacts.api.submission_manifest import (
+    SubmissionManifest,
+    build_submission_manifest,
+)
 from app.core.hashing import canonical_json_hash
 
 
@@ -211,3 +214,26 @@ def test_inspector_rejects_case_aliases_of_implicit_directories(paths):
 def test_inventory_preserves_distinct_unicode_and_exact_directory_parents():
     manifest = _manifest(_archive([('café/', b''), ('café/a', b'x'), ('cafe', b'y')]))
     assert SubmissionManifest.from_dict(manifest.as_dict(), sha256=manifest.sha256) == manifest
+
+
+@pytest.mark.parametrize("changed", ["digest", "limit", "shape"])
+def test_checker_manifest_port_rejects_invalid_evidence(changed):
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
+
+    contracts = selected_pre_submit_source_contracts()
+    manifest = _manifest(_archive([("a.txt", b"abc")]))
+    body = manifest.as_dict()
+    digest = manifest.sha256
+    limits = SubmissionArchiveLimits()
+    entries = contracts.validate_manifest(body, sha256=digest, limits=limits)
+    assert len(entries) == 1
+    assert (entries[0].normalized_path, entries[0].byte_count) == ("a.txt", 3)
+    if changed == "digest":
+        digest = "sha256:" + "f" * 64
+    elif changed == "limit":
+        limits = replace(limits, maximum_entry_bytes=2)
+    else:
+        body["entries"][0]["byte_count"] = True
+        digest = canonical_json_hash(body)
+    with pytest.raises(ValueError):
+        contracts.validate_manifest(body, sha256=digest, limits=limits)
diff --git a/backend/tests/test_trusted_intake.py b/backend/tests/test_trusted_intake.py
index 2855e0215..397fc5e9f 100644
--- a/backend/tests/test_trusted_intake.py
+++ b/backend/tests/test_trusted_intake.py
@@ -2,6 +2,8 @@
 
 from __future__ import annotations
 
+from app.adapters.artifacts import selected_pre_submit_source_contracts
+
 import asyncio
 from dataclasses import asdict, replace
 import hashlib
@@ -23,7 +25,9 @@
 from app.interfaces.trusted_submission_intake import TrustedIntakePreparation
 from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits
 from app.modules.artifacts.submission_archive import SubmissionArchiveInspector
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.api.submission_manifest import (
+    build_submission_manifest,
+)
 from app.modules.checkers.api.default_checker import (
     WORKSTREAM_DEFAULT_BEHAVIOR_SHA256,
     WorkstreamDefaultCheckerInput,
@@ -119,8 +123,6 @@ def _export_result(output, expected: bytes):
     assert _read(output)["operation"] == "export"
 
 
-
-
 @pytest.mark.parametrize(
     "data,code",
     [
@@ -139,8 +141,6 @@ def test_worker_preserves_canonical_zip_rejection_without_export(tmp_path, data,
     assert not (tmp_path / "escape").exists()
 
 
-
-
 @pytest.mark.asyncio
 async def test_cancelled_prepare_closes_connection_and_drains_blocking_io(tmp_path):
     path = tmp_path / "node.sock"
@@ -405,8 +405,6 @@ def unexpected_inspector(*args, **kwargs):
     assert output.read() == b""
 
 
-
-
 def _pre_worker(tmp_path, data, *, extra_startup=None, stored_data=None, result_change=None, reservation_change=None, lease=None, isolation_override=None):
     """Real ZIP/worker with simulated supervisor project result; no VM claim."""
     from app.modules.checkers.api.external import make_external_checker_execution_result
@@ -415,7 +413,7 @@ def _pre_worker(tmp_path, data, *, extra_startup=None, stored_data=None, result_
 
     if lease is None:
         reservation = _source_reservation()
-        reservation = replace(reservation, source=reservation.source.model_copy(update={
+        reservation = replace(reservation, source_contracts=selected_pre_submit_source_contracts(), source=reservation.source.model_copy(update={
             "raw_sha256": "sha256:" + hashlib.sha256(data).hexdigest(), "raw_byte_count": len(data),
         }))
         if reservation_change:
@@ -484,8 +482,8 @@ def test_pre_worker_derives_source_manifest_defaults_and_project_request(tmp_pat
     project, completed = _read(output), _read(output)
     assert project["operation"] == "project" and completed["operation"] == "completed"
     assert output.read() == b"" and reply.calls == 1
-    execution = SelectedPreSubmitExecutionFacts.from_canonical_body(completed["payload"])
-    execution.validate_lease(lease)
+    execution = SelectedPreSubmitExecutionFacts.from_canonical_body(completed["payload"], source_contracts=selected_pre_submit_source_contracts())
+    execution.validate_lease(lease, source_contracts=selected_pre_submit_source_contracts())
     assert execution.eligible
     expected_manifest = {"schema_version": "workstream.submission_bundle_manifest.v1", "entries": [{
         "normalized_path": "work.txt", "entry_type": "file", "byte_count": 13,
@@ -592,13 +590,13 @@ def changed(reservation):
         body = reservation.policy.model_dump(mode="json", exclude={"policy_sha256"})
         body["entries"] = [binding.model_dump(mode="json")]
         policy = LockedExternalPreSubmitPolicy.model_validate_json(json.dumps(body | {"policy_sha256": external_checker_json_hash(body)}))
-        reservation = replace(reservation, policy=policy, admission_lineage=replace(
+        reservation = replace(reservation, source_contracts=selected_pre_submit_source_contracts(), policy=policy, admission_lineage=replace(
             reservation.admission_lineage, effective_plan_sha256=policy.policy_sha256,
         ))
         if blocker == "unchanged":
             manifest = build_submission_manifest(SubmissionArchiveInspector(SubmissionArchiveLimits()).inspect(BytesIO(data)))
             predecessor = WorkstreamDefaultPredecessor(new_record_id(), 1, reservation.source.raw_sha256, manifest.sha256)
-            reservation = replace(reservation, default_context=replace(
+            reservation = replace(reservation, source_contracts=selected_pre_submit_source_contracts(), default_context=replace(
                 reservation.default_context, predecessor=predecessor, current_predecessor=predecessor,
                 predecessor_exists=True, predecessor_rules_sha256=reservation.default_context.current_rules_sha256,
             ), admission_lineage=replace(reservation.admission_lineage,
diff --git a/cli/internal/api/admin_inspection.go b/cli/internal/api/admin_inspection.go
index 3f41ac0f0..19e5aa1af 100644
--- a/cli/internal/api/admin_inspection.go
+++ b/cli/internal/api/admin_inspection.go
@@ -303,8 +303,8 @@ func (c *Client) AdminPermissions(ctx context.Context) (Result[PermissionCatalog
 	}
 	var value PermissionCatalogue
 	fields, err := contextObject(raw, &value, []string{"items", "total"}, nil)
-	// The public PermissionDefinitionsResponse schema fixes total to Literal[94].
-	if err != nil || value.Items == nil || value.Total != 94 || len(value.Items) != value.Total || !c.safeMutationResponse(raw) {
+	// The public PermissionDefinitionsResponse schema fixes total to Literal[95].
+	if err != nil || value.Items == nil || value.Total != 95 || len(value.Items) != value.Total || !c.safeMutationResponse(raw) {
 		return result, &Failure{Code: "invalid_api_response"}
 	}
 	var members []json.RawMessage
diff --git a/cli/tests/integration/test_admin_inspection_http.py b/cli/tests/integration/test_admin_inspection_http.py
index 6cd247be8..2fe473e11 100644
--- a/cli/tests/integration/test_admin_inspection_http.py
+++ b/cli/tests/integration/test_admin_inspection_http.py
@@ -59,8 +59,8 @@
     "revoked_at": None,
 }
 PERMISSIONS = {
-    "items": [{"permission_id": f"test.permission_{i}"} for i in range(94)],
-    "total": 94,
+    "items": [{"permission_id": f"test.permission_{i}"} for i in range(95)],
+    "total": 95,
 }
 DEFINITIONS = {
     "items": [
@@ -456,7 +456,7 @@ def test_admin_rejects_malformed_and_mismatched_success(cli):
                 },
             ),
             ("permissions", PERMISSIONS | {"unknown": True}),
-            ("permissions", PERMISSIONS | {"items": [PERMISSIONS["items"][0]] * 94}),
+            ("permissions", PERMISSIONS | {"items": [PERMISSIONS["items"][0]] * 95}),
             ("role-definitions", DEFINITIONS | {"items": DEFINITIONS["items"][:-1]}),
             (
                 "role-definitions",
diff --git a/cli/tests/integration/test_admin_inspection_public_api.py b/cli/tests/integration/test_admin_inspection_public_api.py
index 4f3934877..ed144f5cd 100644
--- a/cli/tests/integration/test_admin_inspection_public_api.py
+++ b/cli/tests/integration/test_admin_inspection_public_api.py
@@ -195,7 +195,7 @@ async def issue(
                     assert value == expected.json()
                 assert (
                     inspected(cli, origin, tokens["auditor"], "permissions")["total"]
-                    == 94
+                    == 95
                 )
                 assert (
                     inspected(cli, origin, tokens["auditor"], "role-definitions")[
diff --git a/external_checkers/intake/worker.py b/external_checkers/intake/worker.py
index 1eedd4112..e5d1b057b 100644
--- a/external_checkers/intake/worker.py
+++ b/external_checkers/intake/worker.py
@@ -29,7 +29,8 @@
     SealedSubmissionTree,
     SubmissionArchiveInspector,
 )
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts
+from app.modules.artifacts.api.submission_manifest import build_submission_manifest
 from app.modules.checkers.api.default_checker import (
     WORKSTREAM_DEFAULT_BEHAVIOR_SHA256,
     workstream_default_input_sha256,
@@ -210,7 +211,7 @@ def __init__(self, *, startup, archive, workspace, reader, writer):
         })
         if header["protocol_version"] != "external_checker_service.v1" or header["operation"] != "execute_pre":
             raise ValueError("PRE request invalid")
-        reservation = SelectedPreSubmitReservationFacts.from_canonical_body(header["reservation"])
+        reservation = SelectedPreSubmitReservationFacts.from_canonical_body(header["reservation"], source_contracts=ArtifactPreSubmitSourceContracts())
         if header["request_digest"] != reservation.request_digest:
             raise ValueError("PRE request digest differs")
         self._lease = SelectedPreSubmitLeaseFacts(
@@ -284,8 +285,8 @@ def _finish(self, default, manifest=None, default_input=None, members=()):
             policy_sha256=reservation.policy_sha256, workstream_default=default,
             required_external_count=1, external_members=members,
             eligible=default.eligible and len(members) == 1 and members[0].result.verdict == "passed",
-        )
-        facts.validate_lease(self._lease)
+         source_contracts=ArtifactPreSubmitSourceContracts())
+        facts.validate_lease(self._lease, source_contracts=ArtifactPreSubmitSourceContracts())
         self._reply("completed", facts.canonical_body())
 
     def run(self):
@@ -316,7 +317,7 @@ def run(self):
                 manifest = build_submission_manifest(inspection)
                 value = derive_selected_pre_submit_default_input(
                     self._lease, manifest_body=manifest.as_dict(), manifest_sha256=manifest.sha256,
-                )
+                 source_contracts=ArtifactPreSubmitSourceContracts())
                 with inspector._projected_tree(archive, self._workspace, expected=inspection) as tree:
                     default = evaluate_verified_archive(value, _Material(tree))
             except SubmissionArchiveRejectedError as exc:
@@ -330,7 +331,7 @@ def run(self):
             return
         _, request = derive_selected_pre_submit_input(
             self._lease, manifest_body=manifest.as_dict(), manifest_sha256=manifest.sha256,
-        )
+         source_contracts=ArtifactPreSubmitSourceContracts())
         self._reply("project", {
             "request": request.model_dump(mode="json"), "manifest": manifest.as_dict(),
         })
diff --git a/external_checkers/workstream-checker-guest/tests/pre_dialogue.py b/external_checkers/workstream-checker-guest/tests/pre_dialogue.py
index e326ff6bb..d1cbcf6d9 100644
--- a/external_checkers/workstream-checker-guest/tests/pre_dialogue.py
+++ b/external_checkers/workstream-checker-guest/tests/pre_dialogue.py
@@ -16,6 +16,7 @@
 ROOT = Path(__file__).resolve().parents[3]
 sys.path.insert(0, str(ROOT / "backend"))
 
+from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts  # noqa: E402
 from app.core.hashing import canonical_json_hash  # noqa: E402
 from app.modules.checkers.api.selected_pre_submit import (  # noqa: E402
     SelectedPreSubmitExecutionFacts,
@@ -49,7 +50,7 @@ def incompatible_schema(reservation):
     policy = LockedExternalPreSubmitPolicy.model_validate_json(json.dumps(
         body | {"policy_sha256": external_checker_json_hash(body)},
     ))
-    return replace(reservation, policy=policy, admission_lineage=replace(
+    return replace(reservation, source_contracts=ArtifactPreSubmitSourceContracts(), policy=policy, admission_lineage=replace(
         reservation.admission_lineage, effective_plan_sha256=policy.policy_sha256,
     ))
 
@@ -99,13 +100,13 @@ def validate_completion(case: str, directory: Path) -> None:
     """Validate exactly the frame Rust received, through the Python owner type."""
     startup = json.loads((directory / "startup.json").read_bytes())
     header = startup["request"]
-    reservation = SelectedPreSubmitReservationFacts.from_canonical_body(header["reservation"])
+    reservation = SelectedPreSubmitReservationFacts.from_canonical_body(header["reservation"], source_contracts=ArtifactPreSubmitSourceContracts())
     lease = SelectedPreSubmitLeaseFacts(reservation, UUID(header["lease_id"]),
                                        header["lease_generation"], datetime.fromisoformat(header["lease_expires_at"]))
     terminal = json.loads(sys.stdin.buffer.read())
     assert terminal["operation"] == "completed"
-    execution = SelectedPreSubmitExecutionFacts.from_canonical_body(terminal["payload"])
-    execution.validate_lease(lease)
+    execution = SelectedPreSubmitExecutionFacts.from_canonical_body(terminal["payload"], source_contracts=ArtifactPreSubmitSourceContracts())
+    execution.validate_lease(lease, source_contracts=ArtifactPreSubmitSourceContracts())
     archive = (directory / "pre.zip").read_bytes()
     assert execution.observed_source.raw_sha256 == "sha256:" + hashlib.sha256(archive).hexdigest()
     assert execution.observed_source.raw_byte_count == len(archive)
diff --git a/external_checkers/workstream-checker-service/src/smol/pre.rs b/external_checkers/workstream-checker-service/src/smol/pre.rs
index c2f871a55..e63eadb5f 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre.rs
@@ -121,10 +121,17 @@ pub(crate) fn serve(
     // Host custody stays outside the worker payload. The backend must retain
     // this invocation envelope along with the typed checker facts at T4.
     let response = serialize_response(
-        &prepared.invocation, &machine.lease,
+        &prepared.invocation,
+        &machine.lease,
         &prepared.job.startup["request"]["reservation"]["runtime_profile"],
         (outcome, reason, execution),
-        [admission_ms, preparation_ms, execution_ms, cleanup_ms, started.elapsed().as_millis() as u64],
+        [
+            admission_ms,
+            preparation_ms,
+            execution_ms,
+            cleanup_ms,
+            started.elapsed().as_millis() as u64,
+        ],
         (&journal_sha256, destroyed),
     )?;
     let sent = if response.len() <= 64 * 1024 * 1024
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
index fa0d0c7f2..97958ea91 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
@@ -252,21 +252,29 @@ fn pre_creation_persists_binding_before_guardian_or_runtime() {
 fn production_serializer_matches_python_receipt_fixture() {
     // Synthetic provider observations: this proves the shared wire contract,
     // not Machine creation, isolation, or cleanup on this host.
-    let document: Value = serde_json::from_str(include_str!(
-        "../../../tests/fixtures/pre_invocation.json"
-    )).unwrap();
+    let document: Value =
+        serde_json::from_str(include_str!("../../../tests/fixtures/pre_invocation.json")).unwrap();
     let expected = &document["wire"];
     let (root, _config, mut lease, _journal) = fixture();
     lease.name = expected["provider_invocation_id"].as_str().unwrap().into();
-    lease.runtime.binary_sha256 = expected["runtime"]["binary_sha256"].as_str().unwrap().into();
+    lease.runtime.binary_sha256 = expected["runtime"]["binary_sha256"]
+        .as_str()
+        .unwrap()
+        .into();
     lease.runtime.guest_sha256 = expected["runtime"]["guest_sha256"].as_str().unwrap().into();
     let invocation: Invocation = serde_json::from_value(expected["invocation"].clone()).unwrap();
     let bytes = serialize_response(
-        &invocation, &lease, &expected["runtime"]["profile"],
+        &invocation,
+        &lease,
+        &expected["runtime"]["profile"],
         ("completed", Value::Null, expected["execution"].clone()),
         [1, 2, 3, 4, 10],
-        (expected["cleanup"]["journal_sha256"].as_str().unwrap(), true),
-    ).unwrap();
+        (
+            expected["cleanup"]["journal_sha256"].as_str().unwrap(),
+            true,
+        ),
+    )
+    .unwrap();
     assert_eq!(serde_json::from_slice::(&bytes).unwrap(), *expected);
     if let Some(path) = std::env::var_os("WORKSTREAM_PRE_RECEIPT_WIRE_FILE") {
         // Explicit local cross-language proof consumes these actual Rust bytes.
diff --git a/external_checkers/workstream-checker-service/tests/trusted_intake.py b/external_checkers/workstream-checker-service/tests/trusted_intake.py
index 8393a0489..4069cfec1 100644
--- a/external_checkers/workstream-checker-service/tests/trusted_intake.py
+++ b/external_checkers/workstream-checker-service/tests/trusted_intake.py
@@ -39,7 +39,7 @@
     ExternalMaterialGrantRequest,
 )
 from app.modules.artifacts.submission_archive import exported_submission_tree
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.api.submission_manifest import build_submission_manifest
 from app.modules.artifacts.trusted_intake import TrustedArchiveInspector
 from app.modules.checkers.api.default_checker import (
     WorkstreamDefaultCheckerInput,
diff --git a/mcp_server/contracts/permissions_list.json b/mcp_server/contracts/permissions_list.json
index 76107ade1..8f1f9a301 100644
--- a/mcp_server/contracts/permissions_list.json
+++ b/mcp_server/contracts/permissions_list.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "27d1c2a2dd5e54168106be3f7ffc2b569e5215e7c6ce18a590f86d8a589b628e",
+  "canonical_sha256": "8edc55cc3e4b504c2ac7616b2815b594c182605816072b5c047faed9d19d0d67",
   "components": {
     "schemas": {
       "ApiError": {
@@ -87,7 +87,7 @@
             "type": "array"
           },
           "total": {
-            "const": 94,
+            "const": 95,
             "title": "Total",
             "type": "integer"
           }
@@ -186,6 +186,7 @@
           "artifact.recovery_attempt.read",
           "artifact.audit.read",
           "artifact.guide_source.ingest",
+          "artifact.submission_source.cleanup",
           "artifact.binding.create",
           "artifact.verification.execute",
           "artifact.pending_work.scan",
@@ -405,7 +406,7 @@
   "schema_version": 1,
   "source": {
     "action_id": "authorization.permission_catalogue.read",
-    "backend_git_sha": "8b068f2b788f159b1085d47f162c39ce3323d5b6",
+    "backend_git_sha": "9bee67a12cc3f25909eee39001101e85ee094c40",
     "method": "GET",
     "openapi_version": "3.1.0",
     "path": "/api/v1/authorization/permissions"
diff --git a/mcp_server/tests/integration/test_access_reads.py b/mcp_server/tests/integration/test_access_reads.py
index e76e0b7fb..12adb38f0 100644
--- a/mcp_server/tests/integration/test_access_reads.py
+++ b/mcp_server/tests/integration/test_access_reads.py
@@ -203,7 +203,7 @@ async def _exercise_access_reads(
             if allowed and "items" in body:
                 assert body["items"] and body["total"] >= len(body["items"])
             if allowed and name == "workstream_permissions_list":
-                assert body["total"] == len(body["items"]) == 94
+                assert body["total"] == len(body["items"]) == 95
                 assert {
                     "task.revision.expire",
                     "task.revision.recover",
diff --git a/mcp_server/tests/test_access_reads.py b/mcp_server/tests/test_access_reads.py
index 6f93618df..d05248aa2 100644
--- a/mcp_server/tests/test_access_reads.py
+++ b/mcp_server/tests/test_access_reads.py
@@ -52,7 +52,7 @@ def _arguments(name: str) -> dict[str, Any]:
 def _response(name: str) -> dict[str, Any]:
     # Representative entries use the backend's frozen catalogue totals.
     if name == "workstream_permissions_list":
-        return {"items": [{"permission_id": "actor.profile.read_any"}], "total": 94}
+        return {"items": [{"permission_id": "actor.profile.read_any"}], "total": 95}
     if name == "workstream_admin_roles_list":
         return {
             "items": [
@@ -219,7 +219,7 @@ def test_permission_catalogue_drift_still_fails_closed(
             {"permission_id": "task.revision.expire"},
             {"permission_id": "task.revision.recover"},
         ],
-        "total": 94,
+        "total": 95,
     }
     if malformation == "unknown_permission":
         payload["items"][0]["permission_id"] = "task.revision.unknown"
diff --git a/scripts/test_external_api_drill.py b/scripts/test_external_api_drill.py
index 7f30be042..cc7ec2e9b 100644
--- a/scripts/test_external_api_drill.py
+++ b/scripts/test_external_api_drill.py
@@ -200,9 +200,10 @@ def matches(rows):
     def test_catalogue_oracle_rejects_nested_changes_and_duplicates(self):
         """Reject changed or duplicate permission and role facts against independent expectations."""
         expected = drill.catalogue_expectations()
-        self.assertEqual(len(drill.EXPECTED_PERMISSIONS), 94)
-        self.assertEqual(len(set(drill.EXPECTED_PERMISSIONS)), 94)
+        self.assertEqual(len(drill.EXPECTED_PERMISSIONS), 95)
+        self.assertEqual(len(set(drill.EXPECTED_PERMISSIONS)), 95)
         self.assertEqual(expected["permissions"]["total"], len(expected["permissions"]["items"]))
+        self.assertIn("artifact.submission_source.cleanup", drill.EXPECTED_PERMISSIONS)
         self.assertIn("outbox.dispatch", drill.EXPECTED_PERMISSIONS)
         self.assertIn("task.assignment.authority_reconcile", drill.EXPECTED_PERMISSIONS)
         for name, body in expected.items():
@@ -227,7 +228,7 @@ def test_catalogue_oracle_rejects_nested_changes_and_duplicates(self):
                 with self.subTest(name=name, mutant=mutant), self.assertRaises(drill.ProbeFailure):
                     drill.verify_response(httpx.Response(200, json=mutant), 200, body, exact_fields=body.keys())
         expected["permissions"]["items"].clear()
-        self.assertEqual(len(drill.catalogue_expectations()["permissions"]["items"]), 94)
+        self.assertEqual(len(drill.catalogue_expectations()["permissions"]["items"]), 95)
 
     def test_validation_retryability_is_strict(self):
         expected = {"error.code": "invalid_request", "error.retryable": False}

From f0d40a1998b38df5cbdbb48eb69e7e36b05e80ee Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 11:40:10 +0100
Subject: [PATCH 148/513] docs(submission): record exact-head repair proof and
 review closure

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 52 +++++++++++++++++++
 1 file changed, 52 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index bcbe32450..ce6dcd1fb 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -3855,3 +3855,55 @@ QA/test-delta and docs/CI reviews remain required before pushing this repair.
 This candidate commit does not mark the full submission initiative complete or
 the single draft PR ready. The public API/client/downstream/cleanup/provider
 work listed in the implementation snapshot remains in scope.
+
+### CI repair proof closure
+
+Frozen implementation8f7e5eae3 has these completed receipts:
+- Source/receipt/manifest/port/wire selection:105 passed,168 deselected,54.22s;
+  `/tmp/submission-source-codec-frozen-pure.log` and `.head` bind the exact commit.
+- Atomic acceptance/rollback/concurrent replay:12 passed,27 deselected,580.68s;
+  `/tmp/submission-source-codec-frozen-t4.log/json` binds that commit, Alembic0080
+  and completed isolated database cleanup.
+- Original finalization and Operator/lost-ack recovery:5 passed,34 deselected,
+  460.51s; `/tmp/submission-source-codec-finalization.log/json` has the same
+  exact-commit/database custody. This proves retained Submission/POST dispatch
+  composition, not the entire governed contribution journey.
+- Installed MCP wheel/public-API access-read parity on Python3.12.13:1 passed,
+  100.39s; `/tmp/submission-mcp-wheel-py312.log/json` binds the exact commit and
+  database cleanup. `/tmp/submission-mcp-py312-provenance.json` records the
+  isolated site-packages path and wheel SHA256
+  35f1574d1649e2d72d8c329613f8d1a95552b37b3e54d9c9cc830ee44981afe0.
+
+Pure selection command (backend cwd): pytest
+`tests/checkers/external/test_selected_pre_submit_coordination.py`
+`tests/checkers/external/test_pre_invocation.py`
+`tests/artifacts/test_submission_intake_contracts.py`
+`tests/test_submission_manifest.py`, with `-k 'source_first or historical_pre_values or receipt or invocation or completed_worker or source_validation_dependency or source_profile_preserves or checker_source_contracts or checker_manifest_port' -q --tb=short`.
+T4/T5 used `scripts/run_isolated_tests.py` on
+`tests/artifacts/test_submission_intake_admission.py`, respectively `-k t4` and
+`-k 't5_finalizes or operator_recovers_same or finalization_outbox_recovers'`.
+The wheel proof used the same isolated runner with MCP's test interpreter on
+`mcp_server/tests/integration/test_access_reads.py` and the separately installed
+wheel executable. A temporary diagnostic plugin only enabled API faulthandler
+and copied subprocess logs before fixture cleanup; assertions were unchanged.
+
+The initial wheel attempt failed before API readiness with backend process
+SIGSEGV; its temporary logs had already been removed. A diagnostic replay passed,
+but its accidentally selected Python3.14 wheel environment is excluded from the
+supported-runtime claim. The explicit Python3.12 replay above passed. The first
+startup crash is unreproduced and unroot-caused, not silently declared fixed.
+Keep its `/tmp/submission-mcp-wheel-parity.log/json` failure and later captured
+subprocess diagnostics as an outstanding stability observation for full CI.
+
+ARCH/SEC and QA/test-delta reviewers independently closed PASS on clean8f7e5eae3
+once exact-commit T4/T5/pure receipts were available. Both inspected the relevant
+unchanged owners; adversarial probes rejected forged source facts and detected
+restoring the integer-seconds serialization defect. Documentation/CI review
+passed with no gate suppression or snapshot mismatch. No code changes followed
+those reviews. The earlier19-case portable worker proof does not qualify native
+Smol or AWS. Main was fetched at94334ccf4 with zero missing commits.
+
+This closes only the bounded CI-repair implementation. Full hosted CI, existing
+obsolete PRE consumers, provider cleanup/qualification, public API/client cutover,
+revision/contribution journeys and the specification acceptance audit remain.
+Keep the single PR draft; no merge or complete-initiative claim is authorized.

From 4de63467b272b8915427f447daff13f949241969 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 12:14:06 +0100
Subject: [PATCH 149/513] feat(artifacts): execute audited sealed source
 cleanup

---
 .ci/behavior-ownership/partition.v1.json      |  98 ++++++++-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 189 +++++++++++++++-
 backend/app/adapters/artifacts/__init__.py    |  49 +++++
 .../artifacts/local_submission_source.py      |  54 ++++-
 .../app/adapters/artifacts/source_cleanup.py  | 109 ++++++++++
 .../artifacts/api/submission_cleanup.py       |  25 ++-
 .../app/modules/artifacts/intake/cleanup.py   |  21 +-
 .../artifacts/intake/cleanup_execution.py     |  50 +++++
 backend/scripts/behavior_ownership.py         |  24 +++
 .../test_submission_source_cleanup.py         | 100 ++++++++-
 backend/tests/test_behavior_ownership.py      |  24 +++
 backend/tests/test_local_artifact_store.py    |  94 ++++++++
 backend/tests/test_s3_artifact_store.py       | 203 ++++++++++++++++++
 .../run_probe.py                              |   6 +-
 14 files changed, 1033 insertions(+), 13 deletions(-)
 create mode 100644 backend/app/adapters/artifacts/source_cleanup.py
 create mode 100644 backend/app/modules/artifacts/intake/cleanup_execution.py

diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json
index 5bd595059..bdcd1a5c7 100644
--- a/.ci/behavior-ownership/partition.v1.json
+++ b/.ci/behavior-ownership/partition.v1.json
@@ -28,6 +28,10 @@
       "group": "artifacts",
       "target": "backend/app/adapters/artifacts/s3_compatible.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/adapters/artifacts/source_cleanup.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/adapters/artifacts/trusted_intake.py"
@@ -556,14 +560,30 @@
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/api/submission_archive.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/api/submission_cleanup.py"
+    },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/api/submission_finalization.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/api/submission_intake.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/api/submission_manifest.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/api/submission_preparation.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/api/submission_recovery.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/api/task_import_source.py"
@@ -600,10 +620,30 @@
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/guide_formats.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/acceptance.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/intake/capacity.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/cleanup.py"
+    },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/cleanup_execution.py"
+    },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/finalization.py"
+    },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/finalization_delivery.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/intake/foreground_admission.py"
@@ -620,6 +660,22 @@
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/intake/models.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/progress.py"
+    },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/recovery.py"
+    },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/recovery_delivery.py"
+    },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/registration.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/intake/repository.py"
@@ -680,6 +736,14 @@
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/selected_pre_submit_execution.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/selected_pre_submit_source_contracts.py"
+    },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/selected_pre_submit_source_custody.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/service.py"
@@ -840,6 +904,14 @@
       "group": "auth",
       "target": "backend/app/modules/authorization/api/project_setup_finalization.py"
     },
+    {
+      "group": "auth",
+      "target": "backend/app/modules/authorization/api/submission_cleanup.py"
+    },
+    {
+      "group": "auth",
+      "target": "backend/app/modules/authorization/api/submission_finalization.py"
+    },
     {
       "group": "auth",
       "target": "backend/app/modules/authorization/api/submission_intake.py"
@@ -1076,6 +1148,10 @@
       "group": "auth",
       "target": "backend/app/modules/authorization/domain/submission_intake.py"
     },
+    {
+      "group": "auth",
+      "target": "backend/app/modules/authorization/domain/submission_recovery.py"
+    },
     {
       "group": "auth",
       "target": "backend/app/modules/authorization/domain/task_authority.py"
@@ -1292,6 +1368,10 @@
       "group": "auth",
       "target": "backend/app/modules/authorization/submission_preparation.py"
     },
+    {
+      "group": "auth",
+      "target": "backend/app/modules/authorization/submission_recovery.py"
+    },
     {
       "group": "auth",
       "target": "backend/app/modules/authorization/task_authorization.py"
@@ -1372,6 +1452,10 @@
       "group": "artifacts",
       "target": "backend/app/modules/checkers/api/policy_custody.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/checkers/api/post_material_custody.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/checkers/api/pre_submit_material.py"
@@ -1388,6 +1472,10 @@
       "group": "artifacts",
       "target": "backend/app/modules/checkers/api/selected_pre_submit.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/checkers/api/source_contracts.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/checkers/api/trial_evidence.py"
@@ -1476,6 +1564,10 @@
       "group": "artifacts",
       "target": "backend/app/modules/checkers/selected_pre_submit_reads.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/checkers/selected_pre_submit_records.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/checkers/trial_evidence.py"
@@ -2140,6 +2232,10 @@
       "group": "lifecycle",
       "target": "backend/app/modules/tasks/accepted_effects.py"
     },
+    {
+      "group": "lifecycle",
+      "target": "backend/app/modules/tasks/accepted_submission.py"
+    },
     {
       "group": "lifecycle",
       "target": "backend/app/modules/tasks/api/accepted_effects.py"
@@ -2665,7 +2761,7 @@
       "target": "backend/scripts/validate_test_lane_evidence.py"
     }
   ],
-  "authority_digest": "b6cc06f83827bf37427589437c71a084255f91a27b66bcc4109eebe8ba0160b2",
+  "authority_digest": "f904ce88d1dce00fdba24e8504521f25d6f01dca0ec46b90d5065f1f605c2236",
   "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6",
   "schema": "workstream.behavior-ownership-partition.v1"
 }
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index ce6dcd1fb..da4422639 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -32,7 +32,11 @@ Internal audited finalization recovery now reuses the existing Operator gate-rep
 action, preserves the original delivery and runs the same T5 under a live child lease.
 Private sealed-source cleanup claims, retention barriers and atomic charge-release
 custody are now implemented and database-tested. Cleanup claims and confirmations now require exact audited service decisions.
-Provider deletion, scheduling and uncertain/unsealed reconciliation remain uncomposed.
+Internal Local/S3 exact-generation deletion now composes committed audited claims
+with separately observed settlement and charge release. Local database/provider
+and MinIO protocol/principal tests cover that private path; native AWS cleanup is
+not qualified. Worker startup/scheduling and uncertain/unsealed reconciliation
+remain uncomposed.
 Remaining work includes durable-worker deployment, complete cleanup, public API/CLI/MCP
 cutover, real revision/review/ContributionRecord journeys, policy cardinality and
 the A01–A35/C01–C07 completion audit. No public end-to-end readiness is claimed.
@@ -3907,3 +3911,186 @@ This closes only the bounded CI-repair implementation. Full hosted CI, existing
 obsolete PRE consumers, provider cleanup/qualification, public API/client cutover,
 revision/contribution journeys and the specification acceptance audit remain.
 Keep the single PR draft; no merge or complete-initiative claim is authorized.
+
+## Exact-generation provider cleanup implementation scope
+
+The remaining concrete gap is physical removal after the existing audited,
+committed cleanup claim. Implement exact Local and S3 generation removal and
+compose it with claim/confirmation outside database transactions. Preserve the
+separate cleanup capability/credentials requirement; never expose a general
+administrative delete-by-key path or treat provider acknowledgement as settlement.
+
+Allowed files: existing ART source adapters and their composition root, typed
+artifact provider/cleanup contracts, ART cleanup owner/coordinator, required
+configuration and provider qualification owners, existing source/cleanup tests
+and their lane registration if needed, and this record. Begin with the private
+Local primitive and its regression proof; it grants no authority and is not a
+public deletion endpoint. The coordinator must validate a committed audited claim
+before invoking any deletion capability.
+
+Prohibited: retained/accepted generation deletion, upload-role deletion authority,
+charge release on timeout/abort acknowledgement, broad bucket deletion, provider
+qualification claims without live proof, gate weakening and unrelated cleanup.
+Acceptance: exact source generation only; durable tombstone before unlink; replay
+and crash recovery preserve ownership; changed inode/source refuses deletion;
+provider I/O outside database locks; current audited claim and confirmation;
+separate credentials; uncertain object/part/writer outcomes retain charges.
+Risk: L0. Verify Local failure/replay/substitution cases, real MinIO VersionId
+isolation, PostgreSQL claim/confirmation and accepted-retention races, applicable
+boundary/lint/docs gates, then architecture/security, QA/test-delta and docs/CI
+review of the frozen candidate. Human review focus is deletion authority,
+retention barriers, late writes and conservative accounting. Full public cutover,
+worker deployment and complete acceptance audit remain part of the same PR.
+
+Local primitive worktree evidence (base f0d40a199): full existing Local storage
+suite plus five cleanup cases passed, 64 tests in 19.93s
+(`/tmp/submission-local-cleanup.log`). Cases exercise normal/repeated cleanup,
+interruption before and after unlink, retained provenance/reinitialization,
+late begin/part refusal and missing/replaced-generation rejection. Initial new
+test execution failed three cases due to a missing exception import; fixed the
+import before the full run. Ruff for both changed Python files and diff whitespace
+checks passed. This is private primitive proof only: no composed authority,
+provider settlement, S3 deletion or end-to-end cleanup claim is made. Candidate
+review remains pending until the bounded cleanup integration is assembled.
+
+Cleanup coordinator worktree progress: the owner now recovers the immutable upload
+under a live exact audited claim; root composition commits before invoking the
+separate provider capability and confirms only an exact-source observation with
+all three settlement facts. A confirmed replay performs no provider call.
+Local cleanup validates the upload before deletion and observes the retained
+source tombstone for part settlement. No deletion method was added to the upload
+ArtifactStore interface.
+
+Verification: four isolated PostgreSQL coordinator cases passed in46.74s
+(`/tmp/submission-cleanup-execution-replay.log/json`, Alembic0080, database cleanup
+complete). A separate connection obtains TASK/operation locks during provider I/O
+and reads the committed claim. Unsettled writes, substituted source and provider
+exception retain the charge; exact settled replay invokes the provider once.
+The initial four-case run failed on an incorrect test SQL table name (`tasks`);
+corrected to the inspected `workstream_tasks`. The test charge oracle was also
+corrected to the existing state/accounted_bytes columns before replay. Local full
+suite passed65 tests in37.26s (`/tmp/submission-local-cleanup-full.log`); six focused
+cleanup cases passed in4.60s. Ruff passed for all current Python changes. These
+are dirty-worktree results, not frozen-candidate review. S3 scoped deletion,
+separate credentials, scheduler and unsealed/uncertain reconciliation remain open.
+
+Combined PostgreSQL/Local proof passed: one test in34.26s
+(`/tmp/submission-cleanup-local-db.log/json`,0080, database cleanup complete).
+The test writes actual Local bytes through durable initiation/EOF/seal custody,
+terminalizes, ages only fixture history (preserving the actual provider upload
+deadline), invokes audited cleanup, observes removal and retained tombstone,
+verifies zero accounted bytes and replays the confirmed operation. This proves
+the internal Local cleanup composition, not public submission or S3 deployment.
+Current module-boundary gate also passed
+(`/tmp/submission-cleanup-boundaries-current.log`).
+
+S3 deletion primitive progress: private cleanup capability checks the exact sealed
+upload handle, refuses unresolved multipart handles, deletes only the supplied
+VersionId and separately observes absence. HEAD's generic404 requires a successful
+bucket observation; missing bucket/denied access is not confirmed absence. After
+deletion, any remaining version/delete marker keeps writes unsettled and therefore
+retains the charge. The source capability AWS qualification guard remains intact.
+The constructor currently requires a cleanup store by contract; production
+construction and proof of separate credentials are still unimplemented. Tests use
+administrative MinIO credentials and do not qualify role isolation or AWS.
+
+Real MinIO protocol proof: five version-isolation/lost-delete-acknowledgement/
+unresolved-upload cases passed in21.45s
+(`/tmp/submission-s3-cleanup-versions.log`). Includes no-newer-version settlement,
+newer-version preservation with conservative charge outcome, and replay after a
+successful deletion whose response timed out. Four denied/missing-bucket HEAD
+counterprobes passed in8.41s (`/tmp/submission-s3-cleanup-absence.log`). The initial
+three protocol cases passed before review identified the remaining-version
+settlement gap; current five cases supersede that narrower claim. Ruff and diff
+whitespace checks passed. These results belong to the uncommitted worktree;
+frozen-candidate reviews remain pending for the complete cleanup integration.
+
+Cleanup provider construction now follows the typed ExternalServiceAdapterFactory
+contract with explicit Local/S3 registration. It constructs its own store from
+the cleanup worker's redacted Settings and requires the existing exact namespace
+claim. MinIO construction rejects the upload access-key identity; native AWS
+construction fails closed pending source-cleanup role qualification. The upload
+process receives no new deletion method or cleanup credential setting. Separate
+worker startup/scheduling still needs composition.
+
+Restricted MinIO principal investigation: the first live STS-session test passed
+upload and negative-role checks but failed version deletion with only
+DeleteObjectVersion. The server's DeleteObject handler checks DeleteObject as
+well (upstream source: https://github.com/minio/minio/blob/master/cmd/auth-handler.go).
+A discriminating replay added a VersionId condition, but this build rejected that
+condition as invalid during STS issuance. The current test therefore uses a
+prefix-scoped MinIO DeleteObject grant, retains upload-deletion and cleanup-upload
+denials, and checks out-of-prefix deletion denial. This is principal/prefix proof,
+not IAM-level version-only deletion proof. Exact-version calls remain enforced by
+the adapter and verified by the existing call-capture tests; retained-source
+protection remains the audited ART gate as required by specification17.5. Do not
+transfer this MinIO policy assumption to AWS qualification. Both failed evidence
+logs are retained at `/tmp/submission-s3-cleanup-principals.log` and
+`/tmp/submission-s3-cleanup-principals-replay.log`.
+
+Restricted-principal proof now passes (1 test,14.86s;
+`/tmp/submission-s3-cleanup-principals-final.log`). Distinct short-lived MinIO STS
+sessions have separate upload versus cleanup policies. Real upload succeeds;
+upload-principal version deletion, cleanup-principal upload and out-of-prefix
+cleanup deletion are denied. The exact-version cleanup succeeds. Factory reuse of
+the upload principal and a mismatched namespace claim are rejected. A test oracle
+initially expected ArtifactConfigurationError for the latter, but the shared
+factory intentionally wraps constructor failures in ExternalServiceConfigurationError;
+the corrected oracle preserves that existing error contract.
+
+The combined prior S3 run reported9 passed/1 failed and then exited139
+(`/tmp/submission-s3-cleanup-all.log`). The process-level crash remains unexplained;
+the focused replay with PYTHONFAULTHANDLER=1 exited0. Do not represent that replay
+as a root-cause fix for process stability. Current lint, whitespace and module
+boundary checks pass (`/tmp/submission-cleanup-factory-boundaries.log`). The full
+PostgreSQL cleanup suite is still under verification; no frozen-candidate or full
+initiative completion claim is made.
+
+Current-head hosted CI correction scope: f0d40a199's image-proof job exposes a
+missed manifest-owner import in experiments/pilot04_external_checker_runtime/run_probe.py.
+Auth preflight reports behavior_ownership_error:partition_target_mismatch; local
+inventory identifies22 missing tracked targets and no stale targets. Allow the
+probe's canonical import correction, additive partition registration for delivered
+owners/new cleanup files and existing behavior-ownership verification. Do not
+change protected ownership, drop assertions or relax gates. External runtime also
+has five obsolete prepared-PRE fixture failures (main.rs:3350); retain as pending
+source-first caller cutover, never restore the obsolete implementation to pass.
+Artifacts: `/tmp/submission-f0-ci-image.log`, `-preflight.log`, `-runtime.log` and
+`-shared-a.log`. Full hosted CI remains failing; sampled database constraint log
+messages alone are not classified as defects because many are expected negative
+assertions. Lane-bundle pytest reports still need inspection.
+The additive ownership repair also updates the explicit SUBMISSION_INTAKE_TARGETS
+set in backend/scripts/behavior_ownership.py and its existing exact-set test in
+backend/tests/test_behavior_ownership.py. Register24 concrete paths (22 previously
+missing plus the new cleanup capability/coordinator). Preserve existing assignments,
+protected base, digest validation and rejection of removed or unrelated targets.
+
+Hosted-CI corrective verification: the canonical import repair passed all17
+scripts.test_public_hosted_attachment tests in40.388s
+(`/tmp/submission-probe-import-repair.log`). Additive ownership registration passed
+all170 test_behavior_ownership tests in7.89s
+(`/tmp/submission-cleanup-ownership-tests.log`), validated690 targets against
+origin/main and passed Ruff. Existing assignments and protected base are unchanged;
+only the24 named missing additions and canonical digest were added. This closes
+the reproduced import/partition defects locally, not the other hosted CI failures.
+
+Full cleanup suite result:28 tests passed,1 teardown error in439.87s
+(`/tmp/submission-cleanup-full-db.log/json`,0080, runner database cleanup complete).
+The error followed test_confirmation_rejects_wrong_decision_even_with_atomic_release[source]
+in clean_postgres_database -> _verify_test_database_schema -> canonical schema
+inventory: asyncpg text decoding raised UnicodeDecodeError (byte0x90 at position145).
+The test assertions passed; this is not a passing full-suite result. The original
+isolated database was removed, so do not claim its wire bytes were recovered.
+An exact-case replay with PYTHONFAULTHANDLER=1 and PYTHONMALLOC=debug is the next
+native-runtime diagnostic; no fixture/gate/assertion was weakened. Process139
+observations remain independently unresolved. Full behavior_ownership validate
+also passed after additive partition correction.
+
+The exact teardown case replay passed in17.60s with both native diagnostics enabled
+(`/tmp/submission-cleanup-teardown-diagnostic.log/json`,0080, database cleanup
+complete). The earlier UnicodeDecodeError is unreproduced, not root-caused or
+fixed. Review must preserve that limitation rather than combine these runs into a
+fabricated clean full-suite receipt. All28 original test assertions passed in the
+full run; its independent teardown gate did not. Sealed cleanup is ready for
+bounded code review; the complete initiative, full hosted CI, unsealed cleanup,
+scheduling and public cutover remain unfinished.
diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py
index ba3bd1f1a..997d6bc09 100644
--- a/backend/app/adapters/artifacts/__init__.py
+++ b/backend/app/adapters/artifacts/__init__.py
@@ -1002,3 +1002,52 @@ def worker_submission_finalization_recovery_handler(*, sessions, delivery_option
         sessions=sessions, settings=get_settings(), store=_WorkerSourceObservation(),
         lease_duration=timedelta(seconds=delivery_options.lease_seconds),
     )
+
+
+def submission_source_cleanup_execution(*, sessions, provider, lease_duration):
+    """Compose deletion with the fixed cleanup service and TASK custody owner."""
+    from app.adapters.tasks import intake_task_custody_port
+    from app.core.identifiers import new_record_id
+    from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization
+    from app.modules.artifacts.intake.cleanup_execution import SubmissionSourceCleanupExecution
+
+    return SubmissionSourceCleanupExecution(
+        sessions, tasks=intake_task_custody_port, provider=provider, lease_duration=lease_duration,
+        authorization=lambda session: PreparedSubmissionSourceCleanupAuthorization(
+            session, request_id=new_record_id(), correlation_id=new_record_id()),
+    )
+
+
+def create_submission_source_cleanup_provider(*, settings, namespace_claim, upload_principal):
+    """Build a cleanup-only capability from its worker's dedicated configuration.
+
+    upload_principal identifies the upload credential/role, never its secret.
+    Credentials use the existing redacted Settings loader in the cleanup worker;
+    no deletion credentials are added to the foreground ArtifactStore instance.
+    """
+    from app.adapters.artifacts.source_cleanup import LocalSubmissionSourceCleanup, S3SubmissionSourceCleanup
+    from app.modules.artifacts.api.submission_cleanup import (
+        SUBMISSION_SOURCE_CLEANUP_CAPABILITY, SubmissionSourceCleanupProvider,
+    )
+
+    if settings.artifact_store_backend == "s3_compatible":
+        if settings.artifact_s3_provider_profile == "aws_s3":
+            raise ArtifactProviderLiveProofRequiredError("source cleanup requires native AWS role qualification")
+        if (type(upload_principal) is not str or not upload_principal
+                or settings.artifact_s3_access_key_id is None
+                or settings.artifact_s3_access_key_id.get_secret_value() == upload_principal):
+            raise ArtifactConfigurationError("source cleanup requires a separate provider principal")
+    factory = ExternalServiceAdapterFactory[SubmissionSourceCleanupProvider](SUBMISSION_SOURCE_CLEANUP_CAPABILITY)
+
+    def construct(adapter):
+        bootstrap = create_artifact_store_bootstrap(settings, activation_guard=None)
+        try:
+            store = bootstrap.initialize_after_namespace_claim(namespace_claim)
+            return adapter(store)
+        except BaseException:
+            bootstrap.close()
+            raise
+
+    factory.register("local", lambda: construct(LocalSubmissionSourceCleanup))
+    factory.register("s3_compatible", lambda: construct(S3SubmissionSourceCleanup))
+    return factory.create(settings.artifact_store_backend)
diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py
index 7581e4dbc..53a871307 100644
--- a/backend/app/adapters/artifacts/local_submission_source.py
+++ b/backend/app/adapters/artifacts/local_submission_source.py
@@ -25,8 +25,8 @@
 )
 
 _METADATA_LIMIT = 256 * 1024
-_TEMP = re.compile(r"^\.(?:upload|seal|aborted)\.[0-9a-f]{32}\.tmp$")
-_FILES = frozenset({"upload.json", "seal.json", "aborted.json", "bundle.zip"})
+_TEMP = re.compile(r"^\.(?:upload|seal|aborted|deleted)\.[0-9a-f]{32}\.tmp$")
+_FILES = frozenset({"upload.json", "seal.json", "aborted.json", "deleted.json", "bundle.zip"})
 
 
 class LocalSubmissionSource:
@@ -324,12 +324,60 @@ def parts_absent(self, upload: SubmissionSourceUpload) -> bool:
         try:
             with self.locked(upload.intent.location) as directory:
                 self.upload(directory, upload)
+                if self.exists(directory, "deleted.json"):
+                    completion, sealed = self.seal(directory)
+                    if (completion.upload != upload
+                            or json.loads(self.read(directory, "deleted.json")) != sealed.model_dump(mode="json")):
+                        raise ArtifactIntegrityError("submission source deletion identity mismatch")
+                    return not self.exists(directory, "bundle.zip")
                 return (self.exists(directory, "aborted.json")
                         and not self.exists(directory, "bundle.zip"))
         except FileNotFoundError:
             # A missing metadata file is not proof the staging bytes are gone.
             return False
 
+    def delete_sealed(self, source: SealedSubmissionSource, upload: SubmissionSourceUpload) -> None:
+        """Private cleanup primitive; caller must hold committed cleanup authority.
+
+        Preserve all provenance and a durable tombstone before removing bytes.
+        The operation lock settles local writers; the open descriptor pins the
+        generation until unlink completes. Missing bytes without our tombstone
+        are an integrity failure, not evidence of successful cleanup.
+        """
+        source = SealedSubmissionSource.model_validate(source)
+        upload = SubmissionSourceUpload.model_validate(upload)
+        with self.locked(source.location) as directory:
+            completion, sealed = self.seal(directory)
+            self.upload(directory, completion.upload)
+            if sealed != source or completion.upload != upload:
+                raise ArtifactIntegrityError("submission source seal mismatch")
+            tombstone = source.model_dump(mode="json")
+            deleted = self.exists(directory, "deleted.json")
+            if deleted and json.loads(self.read(directory, "deleted.json")) != tombstone:
+                raise ArtifactIntegrityError("submission source deletion identity mismatch")
+            try:
+                descriptor = os.open("bundle.zip", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
+            except FileNotFoundError:
+                if not deleted:
+                    raise ArtifactIntegrityError("submission source disappeared before cleanup") from None
+                os.fsync(directory)
+                return
+            try:
+                info = self.store._assert_private_regular(descriptor)
+                if (self.source(completion, info) != source
+                        or info.st_size != source.raw_byte_count
+                        or stat.S_IMODE(info.st_mode) != 0o400):
+                    raise ArtifactIntegrityError("submission source generation or size mismatch")
+                if not deleted:
+                    self.publish(directory, "deleted.json", tombstone)
+                current = os.stat("bundle.zip", dir_fd=directory, follow_symlinks=False)
+                if (current.st_dev, current.st_ino) != (info.st_dev, info.st_ino):
+                    raise ArtifactIntegrityError("submission source generation changed during cleanup")
+                os.unlink("bundle.zip", dir_fd=directory)
+                os.fsync(directory)
+            finally:
+                os.close(descriptor)
+
     def seal(self, directory: int) -> tuple[SubmissionSourceCompletion, SealedSubmissionSource]:
         value = json.loads(self.read(directory, "seal.json"))
         if not isinstance(value, dict) or set(value) != {"completion", "source"}:
@@ -344,7 +392,7 @@ def chunk(self, source: SealedSubmissionSource, position: int, maximum_chunk_byt
         with self.locked(source.location) as directory:
             completion, sealed = self.seal(directory)
             self.upload(directory, completion.upload)
-            if self.exists(directory, "aborted.json"):
+            if self.exists(directory, "aborted.json") or self.exists(directory, "deleted.json"):
                 raise ArtifactIntegrityError("submission source was aborted")
             descriptor = os.open("bundle.zip", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
             try:
diff --git a/backend/app/adapters/artifacts/source_cleanup.py b/backend/app/adapters/artifacts/source_cleanup.py
new file mode 100644
index 000000000..2d06b31db
--- /dev/null
+++ b/backend/app/adapters/artifacts/source_cleanup.py
@@ -0,0 +1,109 @@
+"""Private deletion capabilities, kept off the upload/read ArtifactStore port."""
+from app.adapters.artifacts.local_submission_source import LocalSubmissionSource
+from app.interfaces.external_services import ExternalServiceAdapterIdentity
+from app.modules.artifacts.api.submission_cleanup import SUBMISSION_SOURCE_CLEANUP_CAPABILITY, SubmissionSourceRemoval
+
+
+class LocalSubmissionSourceCleanup:
+    """Separate composition-owned capability over the pinned Local namespace."""
+
+    def __init__(self, store):
+        self._store = store
+        self._source = LocalSubmissionSource(store)
+
+    @property
+    def identity(self):
+        return ExternalServiceAdapterIdentity(SUBMISSION_SOURCE_CLEANUP_CAPABILITY, "local")
+
+    def close(self):
+        self._store.close()
+
+    async def remove(self, source, upload):
+        await self._store._source_io(self._source.delete_sealed, source, upload)
+        # The shared operation lock drains Local writers. Retained seal/upload
+        # metadata prevent subsequent begin/part/complete from reopening the key.
+        parts_absent = await self._store.source_upload_parts_absent(upload)
+        absent = await self._store.observe_sealed_source(source) is None
+        return SubmissionSourceRemoval(source, absent, True, parts_absent)
+
+
+class S3SubmissionSourceCleanup:
+    """Exact-version capability over a separately credentialed cleanup store.
+
+    Construction belongs to the cleanup composition root; never pass the upload
+    store here. Native AWS remains subject to the source capability proof gate.
+    """
+
+    def __init__(self, cleanup_store):
+        self._store = cleanup_store
+
+    @property
+    def identity(self):
+        return ExternalServiceAdapterIdentity(SUBMISSION_SOURCE_CLEANUP_CAPABILITY, "s3_compatible")
+
+    def close(self):
+        self._store.close()
+
+    async def _absent(self, source):
+        from botocore.exceptions import ClientError
+        from app.interfaces.artifacts import ArtifactProviderOperationEvidence
+
+        async with self._store._source_client(source.location, ArtifactProviderOperationEvidence()) as client:
+            try:
+                response = await client.head_object(
+                    Bucket=self._store._bucket, Key=self._store._source_key(source.location),
+                    VersionId=source.provider_generation,
+                )
+            except ClientError as error:
+                # A missing bucket or a denied observation is never source
+                # absence. Do not use the general reader's broader missing map.
+                if (error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") == 404
+                        and error.response.get("Error", {}).get("Code") in {"NoSuchKey", "NoSuchVersion"}):
+                    return True
+                if (error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") == 404
+                        and error.response.get("Error", {}).get("Code") == "404"):
+                    # HEAD may omit an XML error body. Require an independent
+                    # successful bucket observation before accepting that code.
+                    await client.head_bucket(Bucket=self._store._bucket)
+                    return True
+                raise
+        self._store._check_source_response(source, response)
+        return False
+
+    async def remove(self, source, upload):
+        from app.interfaces.artifacts import ArtifactOperationConflictError, ArtifactProviderOperationEvidence
+        from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceUpload
+
+        source = SealedSubmissionSource.model_validate(source)
+        upload = SubmissionSourceUpload.model_validate(upload)
+        if (upload.intent.location != source.location
+                or upload.intent.upload_fence != source.sealed_upload_fence):
+            raise ArtifactOperationConflictError("source cleanup upload identity mismatch")
+        # Sealed custody records successful completion of this exact upload.
+        # NoSuchUpload proves its handle cannot accept a late part or completion;
+        # an empty live handle or any other discovered handle is unresolved.
+        parts_absent = await self._store.source_upload_parts_absent(upload)
+        handles = await self._store.discover_source_uploads(upload.intent)
+        if not parts_absent or handles:
+            return SubmissionSourceRemoval(source, False, False, parts_absent)
+        if not await self._absent(source):
+            async with self._store._source_client(source.location, ArtifactProviderOperationEvidence()) as client:
+                await client.delete_object(
+                    Bucket=self._store._bucket, Key=self._store._source_key(source.location),
+                    VersionId=source.provider_generation,
+                )
+        # A successful delete response is not the confirmation observation.
+        absent = await self._absent(source)
+        parts_absent = await self._store.source_upload_parts_absent(upload)
+        handles = await self._store.discover_source_uploads(upload.intent)
+        # Any additional generation or delete marker remains an operation-owned
+        # reconciliation obligation. Removing our exact version cannot release
+        # its charge while other bytes at the same managed key are unexplained.
+        async with self._store._source_client(source.location, ArtifactProviderOperationEvidence()) as client:
+            versions = await client.list_object_versions(
+                Bucket=self._store._bucket, Prefix=self._store._source_key(source.location), MaxKeys=1,
+            )
+        versions_absent = (versions.get("IsTruncated") is False
+                           and versions.get("Versions", []) == []
+                           and versions.get("DeleteMarkers", []) == [])
+        return SubmissionSourceRemoval(source, absent, parts_absent and not handles and versions_absent, parts_absent)
diff --git a/backend/app/modules/artifacts/api/submission_cleanup.py b/backend/app/modules/artifacts/api/submission_cleanup.py
index fc57dcb33..0a393c447 100644
--- a/backend/app/modules/artifacts/api/submission_cleanup.py
+++ b/backend/app/modules/artifacts/api/submission_cleanup.py
@@ -1,8 +1,13 @@
 """Exact source cleanup selectors; values alone grant no deletion authority."""
 from dataclasses import dataclass
-from typing import Literal
+from typing import Literal, Protocol
 from uuid import UUID
 
+from app.interfaces.external_services import ExternalServiceAdapter
+from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceUpload
+
+SUBMISSION_SOURCE_CLEANUP_CAPABILITY = "submission_source_cleanup"
+
 
 @dataclass(frozen=True, slots=True)
 class SubmissionSourceCleanupAuthorityFacts:
@@ -13,3 +18,21 @@ class SubmissionSourceCleanupAuthorityFacts:
     claim_id: UUID
     claim_generation: int
     phase: Literal["claim", "confirm"]
+
+
+@dataclass(frozen=True, slots=True)
+class SubmissionSourceRemoval:
+    """Trusted provider observations; no field by itself releases a charge."""
+
+    source: SealedSubmissionSource
+    object_absent: bool
+    writes_settled: bool
+    parts_absent: bool
+
+
+class SubmissionSourceCleanupProvider(ExternalServiceAdapter, Protocol):
+    """Separate deletion capability supplied only to the audited coordinator."""
+
+    async def remove(self, source: SealedSubmissionSource, upload: SubmissionSourceUpload) -> SubmissionSourceRemoval: ...
+
+    def close(self) -> None: ...
diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py
index 7ab3fd0dc..88209c430 100644
--- a/backend/app/modules/artifacts/intake/cleanup.py
+++ b/backend/app/modules/artifacts/intake/cleanup.py
@@ -10,10 +10,10 @@
 
 from sqlalchemy import func, select, text
 
-from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
+from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceUpload
 from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts
 from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity
-from app.modules.artifacts.intake.models import SubmissionSourceCleanupClaim
+from app.modules.artifacts.intake.models import SubmissionSourceCleanupClaim, SubmissionSourceUploadReceipt
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
 
 # Match the existing bounded durable finalization delivery lease, not a default.
@@ -137,3 +137,20 @@ async def confirm(self, claim: SealedSourceCleanupClaim, *, object_absent: bool,
         row.confirmed_at = now
         await self._session.flush()
         await SubmissionSourceCapacity(self._session).release_confirmed(operation)
+
+    async def upload_for_claim(self, claim: SealedSourceCleanupClaim) -> SubmissionSourceUpload:
+        """Recover the exact upload under the same live audited deletion claim."""
+        operation, row = await self._locked(claim.source.location.operation_id)
+        now = await self._session.scalar(select(func.clock_timestamp()))
+        if (row is None or row.claim_id != str(claim.claim_id) or row.generation != claim.generation
+                or row.source != claim.source.model_dump(mode="json")
+                or row.confirmed_at is not None or row.lease_expires_at <= now):
+            raise IntakeCustodyConflict("source_cleanup_stale")
+        await self._require_claim_authority(operation.id)
+        receipt = await self._session.get(SubmissionSourceUploadReceipt, operation.id)
+        if receipt is None or receipt.provider_upload_id is None or receipt.completion_parts is None:
+            raise IntakeCustodyConflict("source_cleanup_unresolved")
+        return SubmissionSourceUpload(
+            intent=await self._intake._upload_intent(operation, receipt),
+            provider_upload_id=receipt.provider_upload_id,
+        )
diff --git a/backend/app/modules/artifacts/intake/cleanup_execution.py b/backend/app/modules/artifacts/intake/cleanup_execution.py
new file mode 100644
index 000000000..ab8f97204
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/cleanup_execution.py
@@ -0,0 +1,50 @@
+"""Commit cleanup authority before provider I/O, then confirm exact settlement."""
+from contextlib import asynccontextmanager
+from datetime import timedelta
+from uuid import UUID
+
+from app.core.cancellation import await_completion_preserving_cancellation
+from app.modules.artifacts.api.submission_cleanup import (
+    SubmissionSourceCleanupProvider, SubmissionSourceRemoval,
+)
+from app.modules.artifacts.intake.cleanup import MAXIMUM_CLEANUP_LEASE, SealedSourceCleanup
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+
+
+class SubmissionSourceCleanupExecution:
+    """One operation per invocation; uncertain outcomes retain durable charges."""
+
+    def __init__(self, sessions, *, tasks, authorization,
+                 provider: SubmissionSourceCleanupProvider, lease_duration: timedelta):
+        if type(lease_duration) is not timedelta or not timedelta(0) < lease_duration <= MAXIMUM_CLEANUP_LEASE:
+            raise ValueError("source cleanup lease is invalid")
+        self._sessions, self._tasks, self._authorization = sessions, tasks, authorization
+        self._provider, self._duration = provider, lease_duration
+
+    @asynccontextmanager
+    async def _root(self):
+        session = self._sessions()
+        authority = self._authorization(session)
+        try:
+            await session.begin()
+            yield SealedSourceCleanup(session, self._tasks(session), authority)
+            # If acknowledgement is lost, propagate uncertainty and retain the
+            # same claim ID for replay. Never proceed to deletion on that path.
+            await await_completion_preserving_cancellation(session.commit())
+        finally:
+            authority.close()
+            await await_completion_preserving_cancellation(session.close())
+
+    async def run(self, operation_id: UUID, claim_id: UUID) -> None:
+        async with self._root() as owner:
+            claim = await owner.claim(operation_id, claim_id, lease_duration=self._duration)
+            upload = None if claim.confirmed else await owner.upload_for_claim(claim)
+        if claim.confirmed:
+            return
+        observed = await self._provider.remove(claim.source, upload)
+        if type(observed) is not SubmissionSourceRemoval or observed.source != claim.source:
+            raise IntakeCustodyConflict("source_cleanup_observation_mismatch")
+        async with self._root() as owner:
+            await owner.confirm(claim, object_absent=observed.object_absent,
+                                writes_settled=observed.writes_settled,
+                                parts_absent=observed.parts_absent)
diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py
index 8c50a5329..c0bdf3a6f 100644
--- a/backend/scripts/behavior_ownership.py
+++ b/backend/scripts/behavior_ownership.py
@@ -936,6 +936,30 @@
     "backend/app/modules/authorization/project_catalogue.py",
 })
 SUBMISSION_INTAKE_TARGETS = frozenset({
+    "backend/app/adapters/artifacts/source_cleanup.py",
+    "backend/app/modules/artifacts/api/submission_cleanup.py",
+    "backend/app/modules/artifacts/api/submission_finalization.py",
+    "backend/app/modules/artifacts/api/submission_manifest.py",
+    "backend/app/modules/artifacts/api/submission_recovery.py",
+    "backend/app/modules/artifacts/intake/acceptance.py",
+    "backend/app/modules/artifacts/intake/cleanup.py",
+    "backend/app/modules/artifacts/intake/cleanup_execution.py",
+    "backend/app/modules/artifacts/intake/finalization.py",
+    "backend/app/modules/artifacts/intake/finalization_delivery.py",
+    "backend/app/modules/artifacts/intake/progress.py",
+    "backend/app/modules/artifacts/intake/recovery.py",
+    "backend/app/modules/artifacts/intake/recovery_delivery.py",
+    "backend/app/modules/artifacts/intake/registration.py",
+    "backend/app/modules/artifacts/selected_pre_submit_source_contracts.py",
+    "backend/app/modules/artifacts/selected_pre_submit_source_custody.py",
+    "backend/app/modules/authorization/api/submission_cleanup.py",
+    "backend/app/modules/authorization/api/submission_finalization.py",
+    "backend/app/modules/authorization/domain/submission_recovery.py",
+    "backend/app/modules/authorization/submission_recovery.py",
+    "backend/app/modules/checkers/api/post_material_custody.py",
+    "backend/app/modules/checkers/api/source_contracts.py",
+    "backend/app/modules/checkers/selected_pre_submit_records.py",
+    "backend/app/modules/tasks/accepted_submission.py",
     "backend/app/modules/artifacts/api/submission_intake.py",
     "backend/app/modules/artifacts/intake/models.py",
     "backend/app/modules/artifacts/intake/capacity.py",
diff --git a/backend/tests/artifacts/test_submission_source_cleanup.py b/backend/tests/artifacts/test_submission_source_cleanup.py
index 122b31020..2dd824f29 100644
--- a/backend/tests/artifacts/test_submission_source_cleanup.py
+++ b/backend/tests/artifacts/test_submission_source_cleanup.py
@@ -69,7 +69,7 @@ async def terminal_source(intake):
     return operation
 
 
-async def age_fixture(intake, operation):
+async def age_fixture(intake, operation, *, preserve_upload_deadline=False):
     """Seed historical timestamps in an isolated test DB; all cleanup guards stay enabled."""
     database = intake.engine.url.database
     assert database.startswith("workstream_test_")
@@ -83,7 +83,7 @@ async def age_fixture(intake, operation):
             f"{column}={column}-interval '3 hours'" for column in (
                 "created_at", "upload_deadline_at", "lease_expires_at", "pre_deadline_at",
                 "eof_at", "sealed_at", "terminal_at",
-            )
+            ) if not (preserve_upload_deadline and column == "upload_deadline_at")
         ) + " WHERE id=:id"), {"id": operation})
         await connection.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
         await connection.execute(text("ALTER TABLE submission_intake_operations ENABLE TRIGGER submission_intake_mutation"))
@@ -460,3 +460,99 @@ async def test_confirmation_rejects_wrong_decision_even_with_atomic_release(inta
             "FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation}) is True
         assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"),
                                     {"id": operation}) == 100
+
+
+@pytest.mark.parametrize("outcome", ["settled", "uncertain", "wrong_source", "exception"])
+async def test_cleanup_execution_commits_before_provider_and_retains_uncertainty(intake, outcome):
+    from app.adapters.artifacts import submission_source_cleanup_execution
+    from app.modules.artifacts.api.submission_cleanup import SubmissionSourceRemoval
+
+    operation = await terminal_source(intake)
+    await age_fixture(intake, operation)
+    claim_id = new_record_id()
+    calls = []
+
+    class Provider:
+        async def remove(self, source, upload):
+            calls.append(source)
+            assert upload.intent.location == source.location
+            # Separate connection sees the committed claim and can lock TASK
+            # and operation immediately: provider I/O holds no custody locks.
+            async with intake.factory.begin() as session:
+                await session.execute(text("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE NOWAIT"),
+                                      {"id": intake.task})
+                await session.execute(text("SELECT id FROM submission_intake_operations WHERE id=:id FOR UPDATE NOWAIT"),
+                                      {"id": operation})
+                persisted = (await session.execute(text(
+                    "SELECT claim_id FROM submission_source_cleanup_claims WHERE operation_id=:id"
+                ), {"id": operation})).scalar_one()
+                assert str(persisted) == str(claim_id)
+            if outcome == "exception":
+                raise OSError("uncertain deletion")
+            return SubmissionSourceRemoval(
+                source.model_copy(update={"provider_generation": "foreign"}) if outcome == "wrong_source" else source,
+                True, outcome != "uncertain", True,
+            )
+
+    execution = submission_source_cleanup_execution(
+        sessions=intake.factory, provider=Provider(), lease_duration=timedelta(minutes=5))
+    if outcome == "settled":
+        await execution.run(operation, claim_id)
+        await execution.run(operation, claim_id)
+        assert len(calls) == 1
+    else:
+        with pytest.raises((IntakeCustodyConflict, OSError)):
+            await execution.run(operation, claim_id)
+    async with intake.factory() as session:
+        confirmed = (await session.execute(text(
+            "SELECT confirmed_at IS NOT NULL FROM submission_source_cleanup_claims WHERE operation_id=:id"
+        ), {"id": operation})).scalar_one()
+        assert confirmed is (outcome == "settled")
+        released = (await session.execute(text(
+            "SELECT state='released' AND accounted_bytes=0 FROM submission_source_charges WHERE operation_id=:id"
+        ), {"id": operation})).scalar_one()
+        assert released is (outcome == "settled")
+
+
+async def test_cleanup_execution_removes_real_local_source_and_releases_charge(intake):
+    from datetime import UTC, datetime
+    from app.adapters.artifacts import submission_source_cleanup_execution
+    from app.adapters.artifacts.source_cleanup import LocalSubmissionSourceCleanup
+    from tests.test_local_artifact_store import initialize_local_store, local_source_completion
+
+    store = initialize_local_store(root=intake.durable_root)
+    try:
+        async with intake.factory.begin() as session:
+            row = await reserve(intake, session, with_upload=False)
+            operation, lease = UUID(row.id), UUID(row.lease_id)
+            intent = await repository(session).prepare_upload(
+                operation, lease, 1, part_bytes=5 * 1024 * 1024, idle_timeout_seconds=20.0)
+        upload = await store.begin_source_upload(intent)
+        async with intake.factory.begin() as session:
+            await repository(session).record_upload(operation, lease, 1, upload=upload)
+        completion = await local_source_completion(store, upload, b"real-terminal-source")
+        async with intake.factory.begin() as session:
+            await repository(session).record_eof(operation, lease, 1, completion=completion)
+        source = await store.complete_source_upload(completion)
+        async with intake.factory.begin() as session:
+            deadline = datetime.now(UTC) + timedelta(minutes=2)
+            await repository(session).seal(operation, lease, 1, provider_generation=source.provider_generation,
+                                          pre_deadline_at=deadline, lease_expires_at=deadline)
+        async with intake.factory.begin() as session:
+            await repository(session).terminalize(operation, lease, 1, state="rejected", failure_code="pre_failed")
+        await age_fixture(intake, operation, preserve_upload_deadline=True)
+        execution = submission_source_cleanup_execution(
+            sessions=intake.factory, provider=LocalSubmissionSourceCleanup(store),
+            lease_duration=timedelta(minutes=5))
+        claim_id = new_record_id()
+        await execution.run(operation, claim_id)
+        await execution.run(operation, claim_id)
+        assert await store.observe_sealed_source(source) is None
+        assert await store.source_upload_parts_absent(upload) is True
+        assert (intake.durable_root / "objects" / source.location.object_ref).with_name("deleted.json").exists()
+        async with intake.factory() as session:
+            assert await session.scalar(text(
+                "SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"
+            ), {"id": operation}) == 0
+    finally:
+        store.close()
diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py
index f353af671..99ac9ccfc 100644
--- a/backend/tests/test_behavior_ownership.py
+++ b/backend/tests/test_behavior_ownership.py
@@ -2764,6 +2764,30 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ
     target = "backend/app/modules/artifacts/api/submission_intake.py"
     additions = {
         target, "backend/app/modules/artifacts/intake/models.py",
+        "backend/app/adapters/artifacts/source_cleanup.py",
+        "backend/app/modules/artifacts/api/submission_cleanup.py",
+        "backend/app/modules/artifacts/api/submission_finalization.py",
+        "backend/app/modules/artifacts/api/submission_manifest.py",
+        "backend/app/modules/artifacts/api/submission_recovery.py",
+        "backend/app/modules/artifacts/intake/acceptance.py",
+        "backend/app/modules/artifacts/intake/cleanup.py",
+        "backend/app/modules/artifacts/intake/cleanup_execution.py",
+        "backend/app/modules/artifacts/intake/finalization.py",
+        "backend/app/modules/artifacts/intake/finalization_delivery.py",
+        "backend/app/modules/artifacts/intake/progress.py",
+        "backend/app/modules/artifacts/intake/recovery.py",
+        "backend/app/modules/artifacts/intake/recovery_delivery.py",
+        "backend/app/modules/artifacts/intake/registration.py",
+        "backend/app/modules/artifacts/selected_pre_submit_source_contracts.py",
+        "backend/app/modules/artifacts/selected_pre_submit_source_custody.py",
+        "backend/app/modules/authorization/api/submission_cleanup.py",
+        "backend/app/modules/authorization/api/submission_finalization.py",
+        "backend/app/modules/authorization/domain/submission_recovery.py",
+        "backend/app/modules/authorization/submission_recovery.py",
+        "backend/app/modules/checkers/api/post_material_custody.py",
+        "backend/app/modules/checkers/api/source_contracts.py",
+        "backend/app/modules/checkers/selected_pre_submit_records.py",
+        "backend/app/modules/tasks/accepted_submission.py",
         "backend/app/modules/artifacts/intake/capacity.py",
         "backend/app/modules/artifacts/intake/streaming.py",
         "backend/app/modules/authorization/api/submission_intake.py",
diff --git a/backend/tests/test_local_artifact_store.py b/backend/tests/test_local_artifact_store.py
index 9008b5f1d..7924e5835 100644
--- a/backend/tests/test_local_artifact_store.py
+++ b/backend/tests/test_local_artifact_store.py
@@ -20,6 +20,7 @@
     ArtifactInputMismatchError,
     ArtifactIntegrityError,
     ArtifactOperationConflictError,
+    ArtifactPreconditionFailedError,
     ArtifactStoreUnavailableError,
     ArtifactStoreNamespaceClaim,
     artifact_provider_object_ref,
@@ -1151,3 +1152,96 @@ def fail_sync(_descriptor):
             except OSError:
                 pass
         store.close()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("interruption", [None, "before_unlink", "after_unlink"])
+async def test_local_sealed_cleanup_retains_tombstone_and_recovers(tmp_path, monkeypatch, interruption):
+    from app.adapters.artifacts.local_submission_source import LocalSubmissionSource
+
+    root = tmp_path / "store"
+    store = initialize_local_store(root=root)
+    try:
+        upload = await store.begin_source_upload(local_source_intent(store))
+        completion = await local_source_completion(store, upload, b"owned-source")
+        source = await store.complete_source_upload(completion)
+        primitive = LocalSubmissionSource(store)
+        path = root / "objects" / source.location.object_ref
+        original_unlink = os.unlink
+
+        def interrupted_unlink(name, **kwargs):
+            if name != "bundle.zip":
+                return original_unlink(name, **kwargs)
+            if interruption == "after_unlink":
+                original_unlink(name, **kwargs)
+            raise OSError("injected cleanup crash")
+
+        if interruption:
+            with monkeypatch.context() as patch:
+                patch.setattr(os, "unlink", interrupted_unlink)
+                with pytest.raises(OSError, match="injected cleanup crash"):
+                    primitive.delete_sealed(source, upload)
+            assert path.with_name("deleted.json").exists()
+        primitive.delete_sealed(source, upload)
+        primitive.delete_sealed(source, upload)
+        assert not path.exists()
+        assert path.with_name("deleted.json").exists()
+        assert path.with_name("seal.json").exists()
+        assert path.with_name("upload.json").exists()
+        with pytest.raises(ArtifactPreconditionFailedError):
+            await store.begin_source_upload(upload.intent)
+        with pytest.raises(ArtifactPreconditionFailedError):
+            await store.upload_source_part(upload, 1, b"late")
+        assert await store.observe_sealed_source(source) is None
+        assert await store.source_upload_parts_absent(upload) is True
+    finally:
+        store.close()
+    reopened = initialize_local_store(root=root)
+    reopened.close()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("replacement", [False, True])
+async def test_local_sealed_cleanup_refuses_missing_or_replaced_generation(tmp_path, replacement):
+    from app.adapters.artifacts.local_submission_source import LocalSubmissionSource
+
+    root = tmp_path / "store"
+    store = initialize_local_store(root=root)
+    try:
+        upload = await store.begin_source_upload(local_source_intent(store))
+        source = await store.complete_source_upload(await local_source_completion(store, upload, b"original"))
+        path = root / "objects" / source.location.object_ref
+        if replacement:
+            other = path.with_name("replacement")
+            other.write_bytes(b"original")
+            other.chmod(0o400)
+            other.replace(path)
+        else:
+            path.unlink()
+        with pytest.raises(ArtifactIntegrityError):
+            LocalSubmissionSource(store).delete_sealed(source, upload)
+        assert not path.with_name("deleted.json").exists()
+        if replacement:
+            assert path.read_bytes() == b"original"
+    finally:
+        store.close()
+
+
+@pytest.mark.asyncio
+async def test_local_cleanup_capability_rejects_foreign_upload_before_deletion(tmp_path):
+    from app.adapters.artifacts.source_cleanup import LocalSubmissionSourceCleanup
+
+    store = initialize_local_store(root=tmp_path / "store")
+    try:
+        upload = await store.begin_source_upload(local_source_intent(store))
+        source = await store.complete_source_upload(await local_source_completion(store, upload, b"original"))
+        cleanup = LocalSubmissionSourceCleanup(store)
+        with pytest.raises(ArtifactIntegrityError):
+            await cleanup.remove(source, upload.model_copy(update={"provider_upload_id": "foreign"}))
+        assert await store.observe_sealed_source(source) is not None
+        for _ in range(2):
+            result = await cleanup.remove(source, upload)
+            assert result.source == source
+            assert result.object_absent is result.writes_settled is result.parts_absent is True
+    finally:
+        store.close()
diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py
index d8fedcf9f..c1067c06f 100644
--- a/backend/tests/test_s3_artifact_store.py
+++ b/backend/tests/test_s3_artifact_store.py
@@ -105,6 +105,7 @@ def minio_settings(
     private_prefix: str,
     access_key: str = MINIO_ACCESS_KEY,
     secret_key: str = MINIO_SECRET_KEY,
+    session_token: str | None = None,
     buffer_bytes: int = 2,
 ) -> Settings:
     """Return one complete local-only MinIO configuration."""
@@ -122,6 +123,7 @@ def minio_settings(
         artifact_s3_credential_mode="local_static",
         artifact_s3_access_key_id=access_key,
         artifact_s3_secret_access_key=secret_key,
+        artifact_s3_session_token=session_token,
         artifact_stream_buffer_bytes=buffer_bytes,
         artifact_s3_operation_total_timeout_seconds=20,
         artifact_s3_write_timeout_seconds=20,
@@ -1179,3 +1181,204 @@ async def interrupted_client():
     assert await store.discover_source_uploads(intent) == ()
     assert await store.discover_source_uploads(other.intent) == (other,)
     await store.request_source_abort(other)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("lost_ack", [False, True])
+@pytest.mark.parametrize("newer_version", [False, True])
+async def test_source_cleanup_deletes_exact_version_and_recovers_lost_ack(source_store, monkeypatch, lost_ack, newer_version):
+    from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup
+
+    # Admin protocol fixture only: this test does not qualify production role isolation.
+    store = source_store
+    completion = await source_completion(store, b"original")
+    source = await store.complete_source_upload(completion)
+    cleanup_store = initialize_minio_store(private_prefix=store._private_prefix, buffer_bytes=65536)
+    cleanup = S3SubmissionSourceCleanup(cleanup_store)
+    try:
+        if newer_version:
+            async with store._client() as client:
+                newer = await client.put_object(Bucket=MINIO_BUCKET, Key=store._source_key(source.location), Body=b"newer")
+        original_client = cleanup_store._client
+        deletes = []
+
+        class Client:
+            def __init__(self, inner):
+                self.inner = inner
+
+            async def head_object(self, **kwargs):
+                assert kwargs["VersionId"] == source.provider_generation
+                return await self.inner.head_object(**kwargs)
+
+            async def head_bucket(self, **kwargs):
+                return await self.inner.head_bucket(**kwargs)
+
+            async def list_parts(self, **kwargs):
+                assert kwargs["UploadId"] == completion.upload.provider_upload_id
+                return await self.inner.list_parts(**kwargs)
+
+            async def list_multipart_uploads(self, **kwargs):
+                return await self.inner.list_multipart_uploads(**kwargs)
+
+            async def list_object_versions(self, **kwargs):
+                return await self.inner.list_object_versions(**kwargs)
+
+            async def delete_object(self, **kwargs):
+                deletes.append(kwargs)
+                result = await self.inner.delete_object(**kwargs)
+                if lost_ack and len(deletes) == 1:
+                    raise TimeoutError("lost deletion acknowledgement")
+                return result
+
+        @asynccontextmanager
+        async def client():
+            async with original_client() as inner:
+                yield Client(inner)
+
+        monkeypatch.setattr(cleanup_store, "_client", client)
+        if lost_ack:
+            with pytest.raises(ArtifactStoreUnavailableError):
+                await cleanup.remove(source, completion.upload)
+        result = await cleanup.remove(source, completion.upload)
+        assert result.source == source
+        assert result.object_absent is result.parts_absent is True
+        assert result.writes_settled is (not newer_version)
+        assert (await cleanup.remove(source, completion.upload)) == result
+        assert deletes == [dict(Bucket=MINIO_BUCKET, Key=store._source_key(source.location),
+                                VersionId=source.provider_generation)]
+        if newer_version:
+            async with store._client() as client:
+                retained = await client.get_object(Bucket=MINIO_BUCKET, Key=store._source_key(source.location),
+                                                   VersionId=newer["VersionId"])
+                async with retained["Body"] as body:
+                    assert await body.read() == b"newer"
+    finally:
+        cleanup_store.close()
+
+
+@pytest.mark.asyncio
+async def test_source_cleanup_keeps_source_when_another_upload_is_unresolved(source_store):
+    from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup
+
+    store = source_store
+    completion = await source_completion(store, b"original")
+    source = await store.complete_source_upload(completion)
+    extra = await store.begin_source_upload(completion.upload.intent)
+    cleanup_store = initialize_minio_store(private_prefix=store._private_prefix)
+    try:
+        result = await S3SubmissionSourceCleanup(cleanup_store).remove(source, completion.upload)
+        assert result.object_absent is result.writes_settled is False
+        assert await store.observe_sealed_source(source) is not None
+    finally:
+        await store.request_source_abort(extra)
+        cleanup_store.close()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("code,status,bucket_error", [
+    ("NoSuchBucket", 404, None),
+    ("AccessDenied", 403, None),
+    ("404", 404, "NoSuchBucket"),
+    ("404", 404, "AccessDenied"),
+])
+async def test_source_cleanup_never_calls_bucket_or_permission_failure_absence(source_store, monkeypatch, code, status, bucket_error):
+    from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup
+    from app.interfaces.artifacts import ArtifactStoreError
+    from app.modules.artifacts.api.submission_intake import SealedSubmissionSource
+
+    source = SealedSubmissionSource(location=source_intent(source_store).location,
+        provider_generation="exact-version", raw_sha256="sha256:" + "a" * 64,
+        raw_byte_count=10, sealed_upload_fence=1)
+
+    class Observation:
+        async def head_object(self, **kwargs):
+            assert kwargs["VersionId"] == source.provider_generation
+            raise _client_error(code, status)
+
+        async def head_bucket(self, **kwargs):
+            assert bucket_error is not None
+            raise _client_error(bucket_error, 403 if bucket_error == "AccessDenied" else 404)
+
+    @asynccontextmanager
+    async def client():
+        yield Observation()
+
+    monkeypatch.setattr(source_store, "_client", client)
+    with pytest.raises(ArtifactStoreError):
+        await S3SubmissionSourceCleanup(source_store)._absent(source)
+
+
+@pytest.mark.asyncio
+async def test_source_cleanup_uses_separate_restricted_principal(source_store):
+    from dataclasses import replace
+    import json
+    from app.adapters.artifacts import create_submission_source_cleanup_provider
+    from app.interfaces.external_services import ExternalServiceConfigurationError
+
+    prefix = source_store._private_prefix
+    bucket_resource = f"arn:aws:s3:::{MINIO_BUCKET}"
+    object_resource = f"{bucket_resource}/{prefix}/*"
+    session = AioSession()
+    session.set_credentials(MINIO_ACCESS_KEY, MINIO_SECRET_KEY)
+
+    async def credentials(name, object_actions, bucket_actions):
+        policy = {"Version": "2012-10-17", "Statement": [
+            {"Effect": "Allow", "Action": object_actions, "Resource": [object_resource]},
+            {"Effect": "Allow", "Action": bucket_actions, "Resource": [bucket_resource]},
+        ]}
+        async with session.create_client("sts", endpoint_url=MINIO_ENDPOINT, region_name=MINIO_REGION) as client:
+            result = await client.assume_role(
+                RoleArn="arn:aws:iam::123456789012:role/submission-cleanup-test",
+                RoleSessionName=name, DurationSeconds=900, Policy=json.dumps(policy))
+            return result["Credentials"]
+
+    uploader = await credentials("source-uploader", ["s3:PutObject", "s3:GetObjectVersion"], ["s3:GetBucketVersioning"])
+    cleaner = await credentials("source-cleaner", [
+        # This MinIO build requires DeleteObject even with VersionId and rejects
+        # a VersionId policy condition. Exact-version enforcement remains in
+        # the cleanup capability; this proves principal/prefix separation only.
+        "s3:GetObjectVersion", "s3:DeleteObject", "s3:DeleteObjectVersion", "s3:ListMultipartUploadParts",
+    ], ["s3:ListBucket", "s3:ListBucketVersions", "s3:ListBucketMultipartUploads"])
+
+    def settings(value):
+        return minio_settings(private_prefix=prefix, access_key=value["AccessKeyId"],
+                              secret_key=value["SecretAccessKey"], session_token=value["SessionToken"],
+                              buffer_bytes=65536)
+
+    upload_settings, cleanup_settings = settings(uploader), settings(cleaner)
+    bootstrap = create_artifact_store_bootstrap(upload_settings, activation_guard=None)
+    _, fingerprint = artifact_store_namespace_material(
+        backend="s3_compatible", adapter_identity=bootstrap.identity,
+        namespace_identity=bootstrap.namespace_identity)
+    claim = ArtifactStoreNamespaceClaim(bootstrap.identity, bootstrap.namespace_identity, fingerprint)
+    upload_store = bootstrap.initialize_after_namespace_claim(claim)
+    cleanup = create_submission_source_cleanup_provider(
+        settings=cleanup_settings, namespace_claim=claim, upload_principal=uploader["AccessKeyId"])
+    try:
+        completion = await source_completion(upload_store, b"restricted-source")
+        source = await upload_store.complete_source_upload(completion)
+        with pytest.raises(ArtifactConfigurationError, match="separate provider principal"):
+            create_submission_source_cleanup_provider(
+                settings=upload_settings, namespace_claim=claim, upload_principal=uploader["AccessKeyId"])
+        with pytest.raises(ExternalServiceConfigurationError):
+            create_submission_source_cleanup_provider(
+                settings=cleanup_settings, namespace_claim=replace(claim, namespace_fingerprint="sha256:" + "0" * 64),
+                upload_principal=uploader["AccessKeyId"])
+        async with upload_store._client() as client:
+            with pytest.raises(ClientError) as denied:
+                await client.delete_object(Bucket=MINIO_BUCKET, Key=upload_store._source_key(source.location),
+                                           VersionId=source.provider_generation)
+            assert denied.value.response["Error"]["Code"] == "AccessDenied"
+        async with cleanup._store._client() as client:
+            with pytest.raises(ClientError) as denied:
+                await client.put_object(Bucket=MINIO_BUCKET, Key=upload_store._source_key(source.location), Body=b"forbidden")
+            assert denied.value.response["Error"]["Code"] == "AccessDenied"
+            with pytest.raises(ClientError) as denied:
+                await client.delete_object(Bucket=MINIO_BUCKET, Key=f"unrelated/{uuid4().hex}",
+                                           VersionId=source.provider_generation)
+            assert denied.value.response["Error"]["Code"] == "AccessDenied"
+        result = await cleanup.remove(source, completion.upload)
+        assert result.object_absent is result.parts_absent is result.writes_settled is True
+    finally:
+        cleanup.close()
+        upload_store.close()
diff --git a/experiments/pilot04_external_checker_runtime/run_probe.py b/experiments/pilot04_external_checker_runtime/run_probe.py
index d56916919..3ed54decf 100644
--- a/experiments/pilot04_external_checker_runtime/run_probe.py
+++ b/experiments/pilot04_external_checker_runtime/run_probe.py
@@ -27,12 +27,12 @@
     ExternalMaterialFile,
     ExternalMaterialGrantRequest,
 )
-from app.modules.artifacts.submission_archive import (
+from app.modules.artifacts.api.submission_archive import (
     SubmissionArchiveEntryType,
-    SubmissionArchiveInspector,
     SubmissionArchiveLimits,
 )
-from app.modules.artifacts.submission_manifest import build_submission_manifest
+from app.modules.artifacts.submission_archive import SubmissionArchiveInspector
+from app.modules.artifacts.api.submission_manifest import build_submission_manifest
 from app.modules.checkers.api.external import (
     PreSubmitExternalCheckerMaterial,
     ExternalCheckerRegistryEntry,

From 250d8af70cd7939b2806de5af8e3dd0d45ca4405 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 12:25:09 +0100
Subject: [PATCH 150/513] docs(submission): record frozen sealed cleanup proof
 and reviews

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 45 +++++++++++++++++++
 1 file changed, 45 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index da4422639..37b601938 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4094,3 +4094,48 @@ fabricated clean full-suite receipt. All28 original test assertions passed in th
 full run; its independent teardown gate did not. Sealed cleanup is ready for
 bounded code review; the complete initiative, full hosted CI, unsealed cleanup,
 scheduling and public cutover remain unfinished.
+
+## Frozen sealed-cleanup proof and review closure
+
+Implementation target:4de63467b272b8915427f447daff13f949241969, base and merge base
+f0d40a1998b38df5cbdbb48eb69e7e36b05e80ee. All14 paths were frozen clean throughout
+these executions and review snapshots. origin/main was fetched again; this branch
+has zero missing main commits. No merge readiness is claimed.
+
+All three frozen commands used backend/.venv Python3.12.13 with
+PYTHONFAULTHANDLER=1 and PYTHONMALLOC=debug. PostgreSQL used the restricted isolated
+runner against the owned local test server; S3 used the owned local MinIO endpoint.
+
+- Full PostgreSQL cleanup suite:28 passed in340.97s, exit0. Command from backend:
+  `.venv/bin/python scripts/run_isolated_tests.py --metadata-json /tmp/submission-cleanup-frozen-db.json -- .venv/bin/python -m pytest tests/artifacts/test_submission_source_cleanup.py -q --tb=short`.
+  `/tmp/submission-cleanup-frozen-db.log/json/head` records exact4de, Alembic0080
+  and completed database cleanup, including teardown.
+- Full Local store suite:65 passed in42.81s, exit0. Command:
+  `.venv/bin/python -m pytest tests/test_local_artifact_store.py -q --tb=short`.
+  Artifact: `/tmp/submission-cleanup-frozen-local.log`.
+- S3 cleanup suite:10 passed,47 deselected in42.84s, exit0. Command:
+  `.venv/bin/python -m pytest tests/test_s3_artifact_store.py -k source_cleanup -q --tb=short`.
+  Artifact: `/tmp/submission-cleanup-frozen-s3.log`.
+- `/tmp/submission-cleanup-frozen-provenance.json` records the clean implementation
+  head, Python interpreter, diagnostic settings and MinIO image digest
+  sha256:1033251d858d3f89f14d9e095e8dd0c8ada3360124ab33cca994655e579fdbf6.
+
+Required bounded reviews closed on that unchanged target:
+
+- Architecture/security:PASS, including authority before provider I/O, exact
+  generation/tombstone custody and atomic audited confirmation.
+- QA/test_delta:PASS WITH LOW RISKS, no findings or repairs. Exact frozen receipts
+  close previously provisional runtime rows. The in-memory omitted-tombstone
+  mutant fails the intended before-unlink assertion; repository stays unchanged.
+- Documentation/CI integrity:PASS. Independent partition comparison preserves all666
+  prior assignments/protected base and adds only24 exact paths. Recomputed-digest
+  mutants that remove/reassign prior targets, add unrelated targets or alter the
+  protected base are rejected. Actual CI selection remains full suite/all lanes.
+
+The earlier exit139 and UTF-8 schema-inventory teardown error remain unexplained.
+This clean frozen replay does not erase those failures or claim a root-cause fix.
+MinIO principal/prefix separation and adapter VersionId enforcement do not qualify
+AWS or IAM-level version-only deletion. Worker startup/scheduling, unsealed and
+uncertain reconciliation, public API/CLI/MCP cutover, downstream journeys, remaining
+hosted-CI failures, deployment values and complete A01–A35 proof remain required in
+this same PR before readiness. The full thread goal stays active and incomplete.

From 87d8cbafb9b6c990be8d528804764bd88078aeaf Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 12:41:50 +0100
Subject: [PATCH 151/513] feat(submission): prepare strict HTTP intake and
 source PRE reservation

---
 .ci/behavior-ownership/partition.v1.json      |  6 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 86 +++++++++++++++++
 backend/app/api/submission_intake.py          | 70 ++++++++++++++
 .../artifacts/intake/foreground_admission.py  | 71 +++++++++++++-
 backend/scripts/behavior_ownership.py         |  1 +
 .../artifacts/intake_acceptance_support.py    | 19 +---
 .../test_submission_intake_admission.py       | 45 +++++++++
 backend/tests/test_api_controls.py            | 95 +++++++++++++++++++
 backend/tests/test_behavior_ownership.py      |  1 +
 9 files changed, 374 insertions(+), 20 deletions(-)
 create mode 100644 backend/app/api/submission_intake.py

diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json
index bdcd1a5c7..9482b03a9 100644
--- a/.ci/behavior-ownership/partition.v1.json
+++ b/.ci/behavior-ownership/partition.v1.json
@@ -344,6 +344,10 @@
       "group": "lifecycle",
       "target": "backend/app/api/routes/project_work_reads.py"
     },
+    {
+      "group": "lifecycle",
+      "target": "backend/app/api/submission_intake.py"
+    },
     {
       "group": "shared",
       "target": "backend/app/core/api_controls.py"
@@ -2761,7 +2765,7 @@
       "target": "backend/scripts/validate_test_lane_evidence.py"
     }
   ],
-  "authority_digest": "f904ce88d1dce00fdba24e8504521f25d6f01dca0ec46b90d5065f1f605c2236",
+  "authority_digest": "3b48cdabc1b0032b10e371e55cf72142c19ab69447741bd173fd78c0da4b692b",
   "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6",
   "schema": "workstream.behavior-ownership-partition.v1"
 }
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 37b601938..3a99d2015 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4139,3 +4139,89 @@ AWS or IAM-level version-only deletion. Worker startup/scheduling, unsealed and
 uncertain reconciliation, public API/CLI/MCP cutover, downstream journeys, remaining
 hosted-CI failures, deployment values and complete A01–A35 proof remain required in
 this same PR before readiness. The full thread goal stays active and incomplete.
+
+## Coordinated public submission cutover scope
+
+The next gap is the public journey: internal T1/upload/PRE/T4 owners exist, while
+API/CLI/MCP still expose preparation followed by admission-consuming creation.
+Reuse those owners and replace that obsolete public contract together. Begin with
+strict request parsing, then compose foreground execution, authorized operation
+reads and clients. Do not expose a second supported mutation or restore obsolete
+prepared-PRE interfaces merely to satisfy old fixtures.
+
+Allowed: backend/app/api/submission_intake.py and existing artifact/task routes;
+ART public intake/command contracts and private foreground orchestration; canonical
+ART/TASK/CHECKERS adapter roots and narrow read/continuation owner ports; required
+Settings transport/resource profiles; existing backend submission/API/fixture tests;
+cli/internal/api/submission*.go, cli/internal/command/submission.go and affected CLI
+tests; mcp_server/workstream_mcp task-execution schemas/tools/gateway, corresponding
+contracts/tests; affected OpenAPI/catalogue/docs and exact CI ownership registration.
+The Rust/guest obsolete PRE consumers and fixtures are within the same source-first
+cutover scope where required by real execution. Each repair retains its named
+behavior proof; no policy or assertion is discarded just to make CI pass.
+
+Prohibited: unaudited handoff, database locks across provider I/O, renamed legacy
+aliases, client-supplied authority/checksums, implicit background PRE, fabricated
+Submission IDs before T5, changed review/revision policy, default deployment values
+for unresolved C01–C07, new paid provider selection or retained-data deletion.
+Acceptance: exactly one raw-ZIP submission mutation, strict duplicate/framing/
+packet validation before body consumption, actor-key replay, stable post-T4 receipt,
+correct cancellation/unknown-outcome handling, owner-backed progress, coordinated
+CLI/MCP upload/replay/revision behavior and removal of superseded public paths.
+Risk:L0. Verify header refusal without reading body, real PostgreSQL/Local and
+MinIO command/acceptance paths, public HTTP and CLI/MCP contract journeys, durable
+continuation and all governed downstream branches, plus full relevant CI gates.
+Required reviews:architecture/security, QA/test_delta and documentation/CI integrity;
+human focus is authority, exact identity, transport limits, retained lineage and
+truthful client progress. Full unsealed cleanup/scheduling/provider qualification
+and the complete acceptance/deployment audit remain required before PR readiness.
+
+### Public request parsing worktree proof
+
+Added strict HTTP parsing in backend/app/api/submission_intake.py and proof in
+existing backend/tests/test_api_controls.py. Reject duplicate packet/selector and
+framing headers, conflicting length/transfer framing, unsupported media/encoding,
+invalid UUID/packet/revision values and excessive declared length before consuming
+the body. Preserve exact packet text, empty omission semantics, valid revision
+acknowledgements and the permitted declared-byte boundary using canonical ART
+metadata validation.
+
+The complete API-controls module passed:43 tests in40.10s, run from backend with
+`.venv/bin/python -m pytest tests/test_api_controls.py -q --tb=short`.
+Ruff passed for both changed Python files. This is uncommitted worktree evidence,
+not frozen-commit or public journey proof. The parser remains unwired; command and
+route composition, clients, ownership registration and reviews remain pending.
+Inspection confirms obsolete preparation orchestration still calls replaced PRE
+builder signatures; remove that path during coordinated cutover rather than
+restore superseded signatures. The full goal remains active and incomplete.
+
+### Public command owner composition progress
+
+ForegroundIntakeAdmission now owns reserve_pre: lock the original operation and
+lease, recheck contributor authority and locked context, bind exact sealed source
+and retained predecessor facts, and commit CHECKERS reservation before execution.
+The shared acceptance fixture now uses this owner instead of privately rebuilding
+T3. Actor/key replay now includes the stable accepted receipt only after its
+existing authorization and database evidence validation; matching replay bytes
+remain required before returning that result to the command caller.
+
+Worktree verification on the unchanged Python implementation: six PostgreSQL tests
+passed in142.03s, covering T4 receipt replay, three source/owner substitutions and
+both revocation orders. Command from backend used PYTHONFAULTHANDLER=1,
+PYTHONMALLOC=debug and the owned PostgreSQL55440 isolated runner:
+`.venv/bin/python scripts/run_isolated_tests.py --metadata-json /tmp/submission-public-t3-db.json -- .venv/bin/python -m pytest tests/artifacts/test_submission_intake_admission.py -k 't3_reservation or t4_accepts_exact_source_and_replays_one_receipt or t4_revocation_blocks' -q --tb=short`.
+Log:/tmp/submission-public-t3-db.log; metadata confirms0080 and complete database
+cleanup. These are worktree receipts; tree_sha identifies the parent commit and
+must not be represented as a clean committed candidate. Earlier actor/key replay
+selection also passed2 tests. Ruff and module-boundary validation passed.
+
+Registered exactly backend/app/api/submission_intake.py in the existing explicit
+CI addition set and partition. Preserved all690 previous assignments and protected
+base; new total691. Exact-addition regression passed and full ownership validation
+passed. No CI lane was narrowed. The complete API-controls proof remains43passed.
+
+Public command orchestration, lifecycle failure terminalization, HTTP wiring,
+client cutover, revision-path integration and full acceptance proof remain pending.
+This intermediate commit is part of the same PR, not a merge checkpoint. Focused
+architecture/security, QA and docs/CI review remains required before claiming this
+public cutover stage complete. The full goal stays active.
diff --git a/backend/app/api/submission_intake.py b/backend/app/api/submission_intake.py
new file mode 100644
index 000000000..cf16afbfc
--- /dev/null
+++ b/backend/app/api/submission_intake.py
@@ -0,0 +1,70 @@
+"""Exact HTTP command metadata for the single raw-ZIP submission mutation."""
+from dataclasses import dataclass
+from typing import NoReturn
+from uuid import UUID
+
+from starlette.requests import Request
+
+from app.core.api_controls import StructuredHTTPException
+from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
+
+
+@dataclass(frozen=True, slots=True)
+class SubmissionIntakeHeaders:
+    metadata: SubmissionIntakeMetadata
+    idempotency_key: UUID
+    declared_raw_bytes: int | None
+
+
+_PACKET_HEADERS = (
+    "x-task-assignment-id", "idempotency-key", "x-submission-summary",
+    "x-contributor-attestation", "x-predecessor-submission-id",
+    "x-revision-preparation-id", "x-revision-preparation-sha256",
+    "content-type", "content-encoding", "content-length", "transfer-encoding",
+)
+
+
+def _reject(code: str, status_code: int, message: str) -> NoReturn:
+    raise StructuredHTTPException(status_code=status_code, detail=message,
+                                  error_code=code, error_message=message)
+
+
+def submission_intake_headers(request: Request, task_id: UUID) -> SubmissionIntakeHeaders:
+    """Parse once without reading, trimming or otherwise rewriting packet bytes."""
+    headers = request.headers
+    for name in _PACKET_HEADERS:
+        if len(headers.getlist(name)) > 1:
+            _reject("submission_packet_invalid", 422, "Submission headers are ambiguous")
+    if any(len(headers.getlist(name)) != 1 for name in ("idempotency-key", "x-task-assignment-id")):
+        _reject("submission_packet_invalid", 422, "Submission selectors are required")
+    if (headers.get("content-type", "").strip().lower() != "application/zip"
+            or headers.get("content-encoding", "identity").strip().lower() != "identity"):
+        _reject("submission_media_type_unsupported", 415, "Submission requires an unencoded ZIP body")
+    length, transfer = headers.get("content-length"), headers.get("transfer-encoding")
+    if transfer is not None and (length is not None or transfer.strip().lower() != "chunked"):
+        _reject("submission_packet_invalid", 422, "Submission framing is invalid")
+    declared = None
+    if length is not None:
+        if not length or len(length) > 20 or any(char not in "0123456789" for char in length):
+            _reject("submission_packet_invalid", 422, "Submission length is invalid")
+        declared = int(length)
+        if declared > MAXIMUM_SUBMISSION_ZIP_BYTES:
+            _reject("submission_archive_limit_exceeded", 413, "Submission ZIP exceeds the raw limit")
+        if declared == 0:
+            _reject("submission_packet_invalid", 422, "Submission ZIP must be nonempty")
+    try:
+        predecessor = headers.get("x-predecessor-submission-id")
+        revision = headers.get("x-revision-preparation-id")
+        metadata = SubmissionIntakeMetadata(
+            task_id=task_id, assignment_id=UUID(headers["x-task-assignment-id"]),
+            predecessor_submission_id=UUID(predecessor) if predecessor is not None else None,
+            summary=headers.get("x-submission-summary", ""),
+            contributor_attestation=headers.get("x-contributor-attestation", ""),
+            revision_preparation_id=UUID(revision) if revision is not None else None,
+            revision_preparation_sha256=headers.get("x-revision-preparation-sha256"),
+        )
+        key = UUID(headers["idempotency-key"])
+    except ValueError:
+        _reject("submission_packet_invalid", 422, "Submission packet is invalid")
+    return SubmissionIntakeHeaders(metadata, key, declared)
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index e88bf4fab..58963711e 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -20,19 +20,22 @@
 from app.core.identifiers import new_record_id
 from app.db.errors import integrity_constraint_name
 from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
-from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
+from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
 from app.modules.artifacts.intake.progress import finalization_progress
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
 from app.modules.artifacts.intake.streaming import hash_submission_replay
-from app.modules.artifacts.models import ArtifactStorageNamespace
+from app.modules.artifacts.models import ArtifactStorageNamespace, SubmissionBundleAdmission
+from app.modules.artifacts.selected_pre_submit_admission import bind_selected_pre_submit_admission, build_selected_pre_submit_reservation
+from app.modules.artifacts.submission_manifest import SubmissionCanonicalPredecessor
 from app.modules.artifacts.service import ArtifactStorageNamespaceSpec
 from app.modules.authorization.api.submission_intake import (
     IntakeAuthorizationPort, IntakeAuthorityDenied, IntakeOperationReadFacts,
     IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts,
 )
 from app.modules.checkers.api.external_policy import LockedExternalCheckerPolicies
-from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitCoordinationPort, SelectedPreSubmitReservationFacts
+from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitCoordinationPort, SelectedPreSubmitReservationFacts, SelectedPreSubmitRuntimeProfile
+from app.modules.checkers.api.pre_submit_material import SubmissionPacketView
 from app.modules.outbox.api import OutboxAppendPort, FinalizedUnknownDeliveryPort
 from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextPort, ProjectLockedPolicyContextRequest
 from app.modules.projects.api.policy_lineage import RevisionPolicySemantics
@@ -60,6 +63,7 @@ class IntakeReplay:
     raw_sha256: str | None
     raw_byte_count: int | None
     finalization: SubmissionFinalizationProgress | None
+    acceptance_receipt: dict | None
 
 
 class IntakeCommitUnknown(RuntimeError):
@@ -201,6 +205,63 @@ async def _validate_context(self, session, metadata, actor_id):
             raise IntakeCustodyConflict("intake_source_provider_unqualified")
         return task, project
 
+    async def reserve_pre(
+        self, owner: IntakeReservationOwner, source: SealedSubmissionSource, *,
+        runtime_profile: SelectedPreSubmitRuntimeProfile,
+        checkers: Callable[[AsyncSession], SelectedPreSubmitCoordinationPort],
+    ) -> SelectedPreSubmitReservationFacts:
+        """Commit one source-bound PRE reservation under fresh contributor authority.
+
+        The original operation supplies every command selector. No body or provider
+        I/O occurs under these locks; execution starts only after this commit.
+        An uncertain commit never grants permission to start the guest.
+        """
+        async with self._root() as (session, authority):
+            repository = SubmissionIntakeRepository(session, self._tasks(session))
+            row = await repository._owned(owner.operation_id, owner.lease_id, owner.generation)
+            if source.location.operation_id != owner.operation_id:
+                raise IntakeCustodyConflict("intake_pre_source_mismatch")
+            await authority.lock_actor(UUID(row.actor_profile_id), UUID(row.identity_link_id))
+            await authority.preflight(IntakeReservationPreflightFacts(
+                UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.assignment_id),
+                UUID(row.actor_profile_id), UUID(row.identity_link_id), UUID(row.idempotency_key),
+                row.metadata_sha256,
+            ))
+            metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
+            task, project = await self._validate_context(session, metadata, UUID(row.actor_profile_id))
+            custody = await repository.lock_pre_source(
+                source=source, lease_id=owner.lease_id, generation=owner.generation)
+            predecessor, predecessor_rules = None, None
+            if task.predecessor is not None:
+                admission = await session.scalar(select(SubmissionBundleAdmission).where(
+                    SubmissionBundleAdmission.consumed_by_submission_id == str(task.predecessor.submission_id),
+                    SubmissionBundleAdmission.status == "consumed",
+                ))
+                if (admission is None or admission.selected_pre_submit_run_id is None
+                        or admission.pre_submit_evidence_set_id is not None
+                        or admission.selected_rules_sha256 is None):
+                    raise IntakeCustodyConflict("submission_canonical_predecessor_unavailable")
+                predecessor = SubmissionCanonicalPredecessor(
+                    submission_id=task.predecessor.submission_id,
+                    submission_version=task.predecessor.version,
+                    archive_sha256=admission.archive_sha256,
+                    semantic_manifest_sha256=admission.semantic_manifest_sha256,
+                )
+                predecessor_rules = admission.selected_rules_sha256
+            selected = bind_selected_pre_submit_admission(
+                task=task, project=project, predecessor=predecessor,
+                predecessor_rules_sha256=predecessor_rules,
+                predecessor_exists=task.predecessor is not None,
+                packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation),
+            )
+            reservation = build_selected_pre_submit_reservation(
+                source=custody, metadata=metadata, task=task, project=project,
+                attempt_id=new_record_id(), idempotency_key=UUID(row.idempotency_key),
+                selected=selected, runtime_profile=runtime_profile,
+            )
+            await checkers(session).reserve(reservation)
+        return reservation
+
     async def accept(
         self, owner: IntakeReservationOwner, request: SelectedPreSubmitReservationFacts, terminal_digest: str, *,
         checkers: Callable[[AsyncSession], SelectedPreSubmitCoordinationPort],
@@ -314,7 +375,9 @@ async def _read(self, metadata, actor_id, key, *, expected_operation_id=None):
                 raise IntakeCustodyConflict("submission_idempotency_conflict")
             result = IntakeReplay(UUID(row.id), row.state, row.failure_code,
                                   row.maximum_raw_bytes, row.raw_sha256, row.raw_byte_count,
-                                  await finalization_progress(row, self._events(session), self._deliveries(session)))
+                                  await finalization_progress(row, self._events(session), self._deliveries(session)),
+                                  await self._accepted_receipt(session, authority, row)
+                                  if row.state in {"finalization_pending", "finalized"} else None)
         return result
 
     async def replay(
diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py
index c0bdf3a6f..b407bbc07 100644
--- a/backend/scripts/behavior_ownership.py
+++ b/backend/scripts/behavior_ownership.py
@@ -936,6 +936,7 @@
     "backend/app/modules/authorization/project_catalogue.py",
 })
 SUBMISSION_INTAKE_TARGETS = frozenset({
+    "backend/app/api/submission_intake.py",
     "backend/app/adapters/artifacts/source_cleanup.py",
     "backend/app/modules/artifacts/api/submission_cleanup.py",
     "backend/app/modules/artifacts/api/submission_finalization.py",
diff --git a/backend/tests/artifacts/intake_acceptance_support.py b/backend/tests/artifacts/intake_acceptance_support.py
index 9871bc1de..8695f89c7 100644
--- a/backend/tests/artifacts/intake_acceptance_support.py
+++ b/backend/tests/artifacts/intake_acceptance_support.py
@@ -6,11 +6,7 @@
 from app.modules.actors.api import ServiceIdentity
 from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
 from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization
-from app.modules.artifacts.selected_pre_submit_admission import (
-    bind_selected_pre_submit_admission, build_selected_pre_submit_reservation,
-)
 from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitSourceReads, SelectedPreSubmitExecutionService
-from app.modules.checkers.api.pre_submit_material import SubmissionPacketView
 from tests.artifact_store_helpers import initialize_local_store
 from tests.artifacts.test_submission_intake_custody import foreground_upload, foreground_limits
 from tests.artifacts.test_submission_pre_source import _source_runtime
@@ -34,17 +30,10 @@ async def body():
     try:
         source = await foreground_upload(f, store).receive(
             owner.operation_id, owner.lease_id, owner.generation, body(), **foreground_limits())
-        async with f.factory.begin() as session:
-            task, project = await f.admission._validate_context(session, metadata, f.actor.actor_profile_id)
-            custody = await submission_intake_pre_source_port(session).lock_pre_source(
-                source=source, lease_id=owner.lease_id, generation=owner.generation)
-            selected = bind_selected_pre_submit_admission(
-                task=task, project=project, predecessor=None, predecessor_rules_sha256=None,
-                predecessor_exists=False, packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation))
-            request = build_selected_pre_submit_reservation(
-                source=custody, metadata=metadata, task=task, project=project, attempt_id=new_record_id(),
-                idempotency_key=key, selected=selected, runtime_profile=_source_reservation().runtime_profile)
-            await selected_pre_submit_coordinator(session).reserve(request)
+        request = await f.admission.reserve_pre(
+            owner, source, runtime_profile=_source_reservation().runtime_profile,
+            checkers=selected_pre_submit_coordinator,
+        )
         await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_PRE_SUBMIT)
         await _seed_materializer(f.factory)
         runtime, errors = _source_runtime(payload, tmp_path, "completed")
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index aa0fbcaaa..d28572bd4 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -467,6 +467,18 @@ async def test_t4_accepts_exact_source_and_replays_one_receipt(admission_intake,
     assert receipt["operation_id"] == str(owner.operation_id)
     assert receipt["pre_submission_results"]
     assert await f.admission.accept(owner, request, terminal.terminal_digest, **kwargs) == dict(receipt, replayed=True)
+    # A new HTTP request has only actor/key, packet and bytes, not the private
+    # PRE reservation/terminal values used by the original foreground owner.
+    from tests.test_trusted_intake import _archive
+    async def repeated_body():
+        yield _archive()
+    replay = await f.admission.replay(
+        SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment),
+        repeated_body(), actor_id=f.actor.actor_profile_id,
+        idempotency_key=request.idempotency_key, declared_raw_bytes=None,
+        idle_timeout_seconds=1, replay_duration=timedelta(seconds=10),
+    )
+    assert replay.acceptance_receipt == dict(receipt, replayed=True)
     async with f.factory.begin() as session:
         row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
         assert row.state == "finalization_pending" and row.acceptance_receipt == receipt
@@ -490,6 +502,33 @@ async def test_t4_accepts_exact_source_and_replays_one_receipt(admission_intake,
                                     {"id": owner.operation_id}) == 1
 
 
+@pytest.mark.parametrize("substitution", ["operation", "generation", "lease"])
+async def test_t3_reservation_rejects_substituted_source_or_owner(admission_intake, tmp_path, substitution):
+    from dataclasses import replace
+    from sqlalchemy import text
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from tests.artifacts.intake_acceptance_support import completed_source
+
+    f = admission_intake
+    owner, request, _ = await completed_source(f, tmp_path)
+    source = request.source
+    if substitution == "operation":
+        source = source.model_copy(update={"location": source.location.model_copy(
+            update={"operation_id": new_record_id()})})
+    elif substitution == "generation":
+        source = source.model_copy(update={"provider_generation": "another-generation"})
+    else:
+        owner = replace(owner, lease_id=new_record_id())
+    with pytest.raises(IntakeCustodyConflict):
+        await f.admission.reserve_pre(
+            owner, source, runtime_profile=request.runtime_profile,
+            checkers=selected_pre_submit_coordinator,
+        )
+    async with f.factory() as session:
+        assert await session.scalar(text(
+            "SELECT count(*) FROM selected_pre_submit_runs WHERE task_id=:id"), {"id": f.task}) == 1
+
+
 @pytest.mark.parametrize("boundary", ["outbox", "task"])
 async def test_t4_rolls_back_all_participants_and_can_retry(admission_intake, tmp_path, boundary):
     from sqlalchemy import text
@@ -612,6 +651,12 @@ async def test_t4_revocation_blocks_new_acceptance_but_preserves_accepted_custod
         headers=f.manager.headers | {"Idempotency-Key": str(new_record_id())},
         json={"reason": "Withdraw grant before accepted handoff"})
     assert response.status_code == 200, response.text
+    if when == "before":
+        with pytest.raises(IntakeAuthorityDenied):
+            await f.admission.reserve_pre(
+                owner, request.source, runtime_profile=request.runtime_profile,
+                checkers=selected_pre_submit_coordinator,
+            )
     with pytest.raises(IntakeAuthorityDenied):
         await f.admission.accept(owner, request, terminal.terminal_digest,
             checkers=selected_pre_submit_coordinator, outbox=outbox_append)
diff --git a/backend/tests/test_api_controls.py b/backend/tests/test_api_controls.py
index d8e247a75..41aaa7c81 100644
--- a/backend/tests/test_api_controls.py
+++ b/backend/tests/test_api_controls.py
@@ -908,3 +908,98 @@ def test_openapi_documents_request_error_and_response_context() -> None:
                 assert {"X-Request-ID", "X-Correlation-ID"} <= set(response["headers"])
                 assert response["headers"]["X-Request-ID"]["required"] is True
                 assert response["headers"]["X-Correlation-ID"]["required"] is True
+def _raw_submission_request(extra=(), *, omit=()):
+    from starlette.requests import Request
+
+    async def unread_body():
+        raise AssertionError("Header validation must not consume the ZIP body")
+
+    headers = [
+        (b"content-type", b"application/zip"),
+        (b"idempotency-key", b"019a0000-0000-7000-8000-000000000001"),
+        (b"x-task-assignment-id", b"019a0000-0000-7000-8000-000000000002"),
+    ]
+    return Request(
+        {"type": "http", "headers": [pair for pair in headers if pair[0] not in omit] + list(extra)},
+        receive=unread_body,
+    )
+
+
+def test_raw_submission_headers_preserve_packet_without_consuming_body():
+    from uuid import UUID
+    from app.api.submission_intake import submission_intake_headers
+
+    task = UUID("019a0000-0000-7000-8000-000000000003")
+    parsed = submission_intake_headers(_raw_submission_request([
+        (b"x-submission-summary", b"Exact  spacing"),
+        (b"x-contributor-attestation", b"x" * 65536),
+        (b"transfer-encoding", b"chunked"),
+    ]), task)
+    assert parsed.metadata.task_id == task
+    assert parsed.metadata.summary == "Exact  spacing"
+    assert parsed.metadata.contributor_attestation == "x" * 65536
+    assert parsed.declared_raw_bytes is None
+
+
+def test_raw_submission_rejects_every_duplicate_packet_or_framing_header():
+    from uuid import UUID
+    from app.api.submission_intake import submission_intake_headers
+    from app.core.api_controls import StructuredHTTPException
+
+    # Deliberately independent of the parser's list: additions cannot silently
+    # remove a required ambiguity check from this contract proof.
+    names = (
+        b"idempotency-key", b"x-task-assignment-id", b"x-submission-summary",
+        b"x-contributor-attestation", b"x-predecessor-submission-id",
+        b"x-revision-preparation-id", b"x-revision-preparation-sha256",
+        b"content-type", b"content-encoding", b"content-length", b"transfer-encoding",
+    )
+    for name in names:
+        request = _raw_submission_request([(name, b"same"), (name, b"same")], omit=(name,))
+        with pytest.raises(StructuredHTTPException) as caught:
+            submission_intake_headers(request, UUID(int=3))
+        assert (caught.value.status_code, caught.value.error_code) == (422, "submission_packet_invalid")
+
+
+def test_raw_submission_headers_preserve_revision_and_declared_limit():
+    from app.api.submission_intake import submission_intake_headers
+    from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
+
+    predecessor, revision = uuid4(), uuid4()
+    parsed = submission_intake_headers(_raw_submission_request([
+        (b"content-length", str(MAXIMUM_SUBMISSION_ZIP_BYTES).encode()),
+        (b"content-encoding", b"identity"),
+        (b"x-predecessor-submission-id", str(predecessor).encode()),
+        (b"x-revision-preparation-id", str(revision).encode()),
+        (b"x-revision-preparation-sha256", b"sha256:" + b"a" * 64),
+    ]), uuid4())
+    assert parsed.declared_raw_bytes == MAXIMUM_SUBMISSION_ZIP_BYTES
+    assert parsed.metadata.predecessor_submission_id == predecessor
+    assert parsed.metadata.revision_preparation_id == revision
+    assert parsed.metadata.revision_preparation_sha256 == "sha256:" + "a" * 64
+    assert parsed.metadata.summary == parsed.metadata.contributor_attestation == ""
+
+
+@pytest.mark.parametrize("extra,omit,status,code", [
+    ([], [b"idempotency-key"], 422, "submission_packet_invalid"),
+    ([], [b"x-task-assignment-id"], 422, "submission_packet_invalid"),
+    ([(b"content-type", b"multipart/form-data")], [b"content-type"], 415, "submission_media_type_unsupported"),
+    ([(b"content-encoding", b"gzip")], [], 415, "submission_media_type_unsupported"),
+    ([(b"content-length", b"12"), (b"transfer-encoding", b"chunked")], [], 422, "submission_packet_invalid"),
+    ([(b"transfer-encoding", b"gzip, chunked")], [], 422, "submission_packet_invalid"),
+    ([(b"content-length", b"+12")], [], 422, "submission_packet_invalid"),
+    ([(b"content-length", b"0")], [], 422, "submission_packet_invalid"),
+    ([(b"content-length", b"524288001")], [], 413, "submission_archive_limit_exceeded"),
+    ([(b"x-submission-summary", b" trimmed ")], [], 422, "submission_packet_invalid"),
+    ([(b"x-contributor-attestation", b"\xff")], [], 422, "submission_packet_invalid"),
+    ([(b"x-submission-summary", b"x" * 65537)], [], 422, "submission_packet_invalid"),
+    ([(b"x-revision-preparation-sha256", b"sha256:" + b"a" * 64)], [], 422, "submission_packet_invalid"),
+])
+def test_raw_submission_invalid_headers_refuse_before_body(extra, omit, status, code):
+    from uuid import UUID
+    from app.api.submission_intake import submission_intake_headers
+    from app.core.api_controls import StructuredHTTPException
+
+    with pytest.raises(StructuredHTTPException) as caught:
+        submission_intake_headers(_raw_submission_request(extra, omit=omit), UUID(int=3))
+    assert (caught.value.status_code, caught.value.error_code) == (status, code)
diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py
index 99ac9ccfc..8d2ea726d 100644
--- a/backend/tests/test_behavior_ownership.py
+++ b/backend/tests/test_behavior_ownership.py
@@ -2763,6 +2763,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ
     retained = "backend/app/core/config.py"
     target = "backend/app/modules/artifacts/api/submission_intake.py"
     additions = {
+        "backend/app/api/submission_intake.py",
         target, "backend/app/modules/artifacts/intake/models.py",
         "backend/app/adapters/artifacts/source_cleanup.py",
         "backend/app/modules/artifacts/api/submission_cleanup.py",

From b2d7dd325ff41643dd0f898f53f80596b0da480f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 12:57:40 +0100
Subject: [PATCH 152/513] feat(submission): compose foreground source execution
 and exact failure replay

---
 .ci/behavior-ownership/partition.v1.json      |   6 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  56 ++++++
 .../artifacts/api/submission_intake.py        |   9 +
 .../artifacts/intake/foreground_admission.py  |  61 ++++++-
 .../artifacts/intake/foreground_command.py    | 157 +++++++++++++++++
 .../app/modules/artifacts/intake/streaming.py |  12 +-
 .../checkers/api/selected_pre_submit.py       |   4 +
 .../selected_pre_submit_coordination.py       |  26 +++
 backend/scripts/behavior_ownership.py         |   1 +
 backend/scripts/test_lane_catalogue.py        |   1 +
 .../artifacts/intake_acceptance_support.py    |  47 +++++
 .../test_submission_foreground_command.py     | 166 ++++++++++++++++++
 .../test_submission_intake_admission.py       |  31 +---
 .../test_submission_intake_contracts.py       |   8 +-
 .../artifacts/test_submission_pre_source.py   |  12 +-
 backend/tests/test_behavior_ownership.py      |   1 +
 backend/tests/test_ci_lane_catalogue.py       |   4 +-
 17 files changed, 561 insertions(+), 41 deletions(-)
 create mode 100644 backend/app/modules/artifacts/intake/foreground_command.py
 create mode 100644 backend/tests/artifacts/test_submission_foreground_command.py

diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json
index 9482b03a9..15a32df63 100644
--- a/.ci/behavior-ownership/partition.v1.json
+++ b/.ci/behavior-ownership/partition.v1.json
@@ -652,6 +652,10 @@
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/intake/foreground_admission.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/intake/foreground_command.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/intake/foreground_lease.py"
@@ -2765,7 +2769,7 @@
       "target": "backend/scripts/validate_test_lane_evidence.py"
     }
   ],
-  "authority_digest": "3b48cdabc1b0032b10e371e55cf72142c19ab69447741bd173fd78c0da4b692b",
+  "authority_digest": "f559788ce2965bb7683b1c637c730130937fce9964084a3adc27974fb1976420",
   "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6",
   "schema": "workstream.behavior-ownership-partition.v1"
 }
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 3a99d2015..60a4c0533 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4225,3 +4225,59 @@ client cutover, revision-path integration and full acceptance proof remain pendi
 This intermediate commit is part of the same PR, not a merge checkpoint. Focused
 architecture/security, QA and docs/CI review remains required before claiming this
 public cutover stage complete. The full goal stays active.
+
+### Foreground command composition implementation
+
+The coordinated cutover now composes existing admission/upload/lease/PRE/T4
+owners in intake/foreground_command.py. Explicit transport/runtime values are
+injected; no production defaults or provider qualification are introduced.
+Accepted actor/key replays discard/hash bytes and return the original receipt.
+Known failed foreground work is terminalized only after the lease runner drains
+its child tasks. Accepted, expired or superseded ownership cannot be overwritten.
+Unknown acceptance or terminalization commit outcomes remain unresolved for
+same-key observation instead of inviting new work. Physical charges stay retained.
+
+QC rejection replay uses CHECKERS' retained source-operation terminal evidence,
+with fresh ART read authority, original packet/key/source comparison and existing
+bounded public findings. This reuses immutable stored evidence rather than create
+another findings copy. Read authorization commits before returning QC feedback.
+The command remains private and unwired pending HTTP composition/client cutover.
+
+Initial integration attempts found two test composition mistakes: missing TASK
+context port, then a Local store root differing from the registered namespace.
+Both were corrected without weakening custody checks. Logs remain at
+/tmp/submission-foreground-command-db.log and
+/tmp/submission-foreground-command-full-db.log. Neither run is passing evidence.
+The corrected five-scenario run uses /tmp/submission-foreground-command-corrected-db.log/json;
+its result is pending at this record entry. Scenarios are acceptance/replay,
+infrastructure-failure replay, unsafe-ZIP QC rejection/replay, cancellation and
+unknown accepted-response replay. Portable worker execution is not native Smol.
+
+CI registration adds only intake/foreground_command.py, preserving all691 existing
+assignments and protected base. Full ownership validation and exact-addition test
+passed. Required specialist review, upload-timeout HTTP classification, deployment
+configuration/readiness, public routes, clients and full end-to-end proof remain.
+
+The corrected command selection passed5 tests in83.45s with database cleanup
+complete. Test-structure validation then identified admission-suite growth above
+1200 lines. Moved the three new command test functions and the committed T3
+substitution function into tests/artifacts/test_submission_foreground_command.py.
+The T3 function AST, including decorators and every assertion, is identical to
+87d8cbafb; this is relocation, not weakened/decomposed behavior. The relocated
+module passed all8 parameterized cases in188.95s, isolated PostgreSQL0080 cleanup
+complete (/tmp/submission-foreground-final-db.log/json). Runtime implementation
+was unchanged for those eight scenarios; a later added upload-timeout classification
+has its own supplemental regression, currently pending.
+
+Upload/replay deadline expiration now has a distinct typed streaming exception,
+normalized by the command to submission_upload_timeout. Existing deadline/drain
+assertions now require that type. The complete intake-contract suite passed113
+in9.02s (/tmp/submission-foreground-contracts.log). The dedicated database timeout
+case uses /tmp/submission-foreground-timeout-db.log/json and remains pending here.
+
+Structure validation passes after relocation. The new module remains in the
+shared-foundations family; independent hashing confirmed exactly the previous275
+members plus the new module before updating the276-member fingerprint. All59 CI
+lane catalogue tests passed in6.59s. Ownership validation/exact-addition proof,
+module boundaries, Ruff, Commitrail records, markdown links and diff checks passed.
+These are scoped worktree receipts, not full CI or public end-to-end readiness.
diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py
index e245ac5ba..62ed581c5 100644
--- a/backend/app/modules/artifacts/api/submission_intake.py
+++ b/backend/app/modules/artifacts/api/submission_intake.py
@@ -20,6 +20,15 @@
 Sha256 = Annotated[str, Field(pattern=r"^sha256:[0-9a-f]{64}$")]
 
 
+class SubmissionIntakeFailure(RuntimeError):
+    """Bounded public failure classification; never raw provider diagnostics."""
+
+    def __init__(self, code: str, *, pre_submission_results: list[dict[str, object]] | None = None):
+        super().__init__(code)
+        self.code = code
+        self.pre_submission_results = pre_submission_results
+
+
 class _IntakeValue(BaseModel):
     """Closed, frozen values accepting typed Python or canonical JSON input."""
 
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index 58963711e..3ae209c29 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -20,7 +20,8 @@
 from app.core.identifiers import new_record_id
 from app.db.errors import integrity_constraint_name
 from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
-from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
+from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakeFailure, SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
+from app.modules.artifacts.api.submission_preparation import public_pre_submission_results
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
 from app.modules.artifacts.intake.progress import finalization_progress
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
@@ -296,6 +297,24 @@ async def accept(
                 self._match_acceptance_command(row, request, terminal_digest, accepted=True)
                 return await self._accepted_receipt(session, authority, row)
 
+    async def finish(self, owner: IntakeReservationOwner, *, state: str, failure_code: str) -> bool:
+        """End drained foreground work, retaining all physical source obligations.
+
+        A committed acceptance, another generation or an expired owner cannot be
+        overwritten by a late request exception. Expiry remains the reaper's job.
+        """
+        async with self._root() as (session, _authority):
+            repository = SubmissionIntakeRepository(session, self._tasks(session))
+            try:
+                await repository._owned(owner.operation_id, owner.lease_id, owner.generation)
+            except IntakeCustodyConflict:
+                return False
+            await repository.terminalize(
+                owner.operation_id, owner.lease_id, owner.generation,
+                state=state, failure_code=failure_code,
+            )
+        return True
+
     @staticmethod
     def _match_acceptance_command(row, request, terminal_digest, *, accepted):
         if (row.id != str(request.source.location.operation_id)
@@ -380,6 +399,46 @@ async def _read(self, metadata, actor_id, key, *, expected_operation_id=None):
                                   if row.state in {"finalization_pending", "finalized"} else None)
         return result
 
+    async def replay_failure(
+        self, metadata: SubmissionIntakeMetadata, *, actor_id: UUID, idempotency_key: UUID,
+        operation_id: UUID, checkers: Callable[[AsyncSession], SelectedPreSubmitCoordinationPort],
+    ) -> dict:
+        """Project retained failure after verified-byte replay and fresh read authority."""
+        async with self._root() as (session, authority):
+            repository = SubmissionIntakeRepository(session, self._tasks(session))
+            row = await repository._lock(operation_id)
+            await authority.authorize_read(IntakeOperationReadFacts(
+                UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id)))
+            if (row.actor_profile_id != str(actor_id) or row.idempotency_key != str(idempotency_key)
+                    or row.metadata_sha256 != metadata.metadata_sha256()):
+                raise IntakeCustodyConflict("submission_idempotency_conflict")
+            if row.state in {"finalization_pending", "finalized"}:
+                return await self._accepted_receipt(session, authority, row)
+            if row.state in {"receiving", "pre_checking"}:
+                raise IntakeCustodyConflict("submission_operation_in_progress")
+            if row.raw_sha256 is None or row.raw_byte_count is None:
+                raise IntakeCustodyConflict("submission_operation_terminal")
+            if row.state == "rejected" and row.failure_code == "pre_submission_checker_failed":
+                terminal = await checkers(session).read_source_terminal(source_operation_id=operation_id)
+                if (terminal is None or terminal.execution is None or terminal.execution.eligible
+                        or terminal.lease.reservation.metadata_sha256 != row.metadata_sha256
+                        or terminal.lease.reservation.actor_profile_id != actor_id
+                        or terminal.lease.reservation.idempotency_key != idempotency_key
+                        or terminal.lease.reservation.source != repository._sealed_source(row)):
+                    raise IntakeCustodyConflict("intake_pre_result_mismatch")
+                failure = SubmissionIntakeFailure(
+                    "pre_submission_checker_failed",
+                    pre_submission_results=public_pre_submission_results(terminal.execution),
+                )
+            else:
+                code = row.failure_code if row.failure_code in {
+                    "submission_packet_invalid", "submission_archive_limit_exceeded",
+                    "submission_upload_timeout", "submission_infrastructure_unavailable",
+                } else "submission_operation_terminal"
+                failure = SubmissionIntakeFailure(code)
+        # Commit the current read authorization before returning QC feedback.
+        raise failure
+
     async def replay(
         self, metadata: SubmissionIntakeMetadata, chunks: AsyncIterator[bytes], *,
         actor_id: UUID, idempotency_key: UUID, declared_raw_bytes: int | None,
diff --git a/backend/app/modules/artifacts/intake/foreground_command.py b/backend/app/modules/artifacts/intake/foreground_command.py
new file mode 100644
index 000000000..2a2de1cc6
--- /dev/null
+++ b/backend/app/modules/artifacts/intake/foreground_command.py
@@ -0,0 +1,157 @@
+"""One foreground upload/PRE/acceptance invocation under the original lease."""
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator, Awaitable, Callable
+from dataclasses import dataclass
+from datetime import timedelta
+import logging
+import math
+from uuid import UUID
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.cancellation import await_cancellation_resistant
+from app.interfaces.artifacts import ArtifactInputMismatchError, ArtifactLimitExceededError
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure, SubmissionIntakeMetadata
+from app.modules.artifacts.api.submission_preparation import public_pre_submission_results
+from app.modules.artifacts.intake.foreground_admission import (
+    ForegroundIntakeAdmission, IntakeCommitUnknown, IntakeReplay, IntakeReservationOwner,
+)
+from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease
+from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+from app.modules.artifacts.intake.streaming import SubmissionUploadTimeout
+from app.modules.checkers.api.selected_pre_submit import (
+    SelectedPreSubmitCompletion, SelectedPreSubmitCoordinationPort,
+    SelectedPreSubmitReservationFacts, SelectedPreSubmitRuntimeProfile,
+)
+from app.modules.outbox.api import OutboxAppendPort
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True, slots=True)
+class SubmissionForegroundLimits:
+    """Explicit transport bounds; no production deployment values are inferred."""
+
+    part_bytes: int
+    idle_timeout_seconds: float
+    pre_lease_seconds: float
+    replay_duration: timedelta
+
+    def __post_init__(self) -> None:
+        if type(self.part_bytes) is not int or not 5 * 1024**2 <= self.part_bytes <= 16 * 1024**2:
+            raise ValueError("submission part size is invalid")
+        for value in (self.idle_timeout_seconds, self.pre_lease_seconds):
+            if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
+                raise ValueError("submission time limit is invalid")
+        if not isinstance(self.replay_duration, timedelta) or self.replay_duration <= timedelta(0):
+            raise ValueError("submission replay duration is invalid")
+
+
+class ForegroundSubmissionCommand:
+    """Compose existing owners; provider/runtime lifetime belongs to the root."""
+
+    def __init__(
+        self, *, admission: ForegroundIntakeAdmission, upload: ForegroundSourceUpload,
+        lease: ForegroundIntakeLease, limits: SubmissionForegroundLimits,
+        runtime_profile: SelectedPreSubmitRuntimeProfile,
+        execute: Callable[[SelectedPreSubmitReservationFacts], Awaitable[SelectedPreSubmitCompletion]],
+        checkers: Callable[[AsyncSession], SelectedPreSubmitCoordinationPort],
+        outbox: Callable[[AsyncSession], OutboxAppendPort],
+    ) -> None:
+        if limits.pre_lease_seconds * 1000 > runtime_profile.aggregate_deadline_ms:
+            raise ValueError("submission PRE lease exceeds its aggregate deadline")
+        self._admission, self._upload, self._lease = admission, upload, lease
+        self._limits, self._profile, self._execute = limits, runtime_profile, execute
+        self._checkers, self._outbox = checkers, outbox
+
+    async def submit(
+        self, metadata: SubmissionIntakeMetadata, chunks: AsyncIterator[bytes], *,
+        actor_id: UUID, identity_link_id: UUID, idempotency_key: UUID,
+        declared_raw_bytes: int | None,
+    ) -> dict:
+        """Return only a positively committed T4 receipt; never wait for T5."""
+        owner = await self._admission.admit(
+            metadata, actor_id=actor_id, identity_link_id=identity_link_id,
+            idempotency_key=idempotency_key, declared_raw_bytes=declared_raw_bytes,
+        )
+        if isinstance(owner, IntakeReplay):
+            try:
+                replay = await self._admission.replay(
+                    metadata, chunks, actor_id=actor_id, idempotency_key=idempotency_key,
+                    declared_raw_bytes=declared_raw_bytes,
+                    idle_timeout_seconds=self._limits.idle_timeout_seconds,
+                    replay_duration=self._limits.replay_duration,
+                )
+            except SubmissionUploadTimeout:
+                raise SubmissionIntakeFailure("submission_upload_timeout") from None
+            if replay.acceptance_receipt is not None:
+                return replay.acceptance_receipt
+            return await self._admission.replay_failure(
+                metadata, actor_id=actor_id, idempotency_key=idempotency_key,
+                operation_id=replay.operation_id, checkers=self._checkers,
+            )
+
+        async def run(_operation_id, _lease_id, _generation):
+            return await self._run(owner, chunks)
+
+        try:
+            return await self._lease.run(owner.operation_id, owner.lease_id, owner.generation, run)
+        except IntakeCommitUnknown:
+            # No failure mutation after an unacknowledged commit. Same-key
+            # observation/replay or expiry resolves durable ownership.
+            raise
+        except BaseException as exc:
+            state = "cancelled" if isinstance(exc, asyncio.CancelledError) else "failed"
+            code = "submission_cancelled" if state == "cancelled" else "submission_infrastructure_unavailable"
+            if isinstance(exc, SubmissionIntakeFailure):
+                code = exc.code
+                if code == "pre_submission_checker_failed":
+                    state = "rejected"
+            elif isinstance(exc, ArtifactLimitExceededError):
+                code = "submission_archive_limit_exceeded"
+            elif isinstance(exc, ArtifactInputMismatchError):
+                code = "submission_packet_invalid"
+            elif isinstance(exc, SubmissionUploadTimeout):
+                code = "submission_upload_timeout"
+            try:
+                finished = await await_cancellation_resistant(self._admission.finish(owner, state=state, failure_code=code))
+            except BaseException:
+                logger.exception("Submission foreground terminalization failed", extra={"operation_id": str(owner.operation_id)})
+                if not isinstance(exc, asyncio.CancelledError):
+                    raise IntakeCommitUnknown("submission terminal outcome is unresolved") from None
+            else:
+                if not finished and not isinstance(exc, asyncio.CancelledError):
+                    raise IntakeCommitUnknown("submission foreground ownership has changed") from None
+            if isinstance(exc, SubmissionUploadTimeout):
+                raise SubmissionIntakeFailure(code) from None
+            raise
+
+    async def _run(self, owner: IntakeReservationOwner, chunks: AsyncIterator[bytes]) -> dict:
+        source = await self._upload.receive(
+            owner.operation_id, owner.lease_id, owner.generation, chunks,
+            part_bytes=self._limits.part_bytes,
+            idle_timeout_seconds=self._limits.idle_timeout_seconds,
+            pre_timeout_seconds=self._profile.aggregate_deadline_ms / 1000,
+            pre_lease_seconds=self._limits.pre_lease_seconds,
+        )
+        reservation = await self._admission.reserve_pre(
+            owner, source, runtime_profile=self._profile, checkers=self._checkers,
+        )
+        completion = await self._execute(reservation)
+        terminal = completion.terminal
+        if terminal.lease.reservation != reservation:
+            raise IntakeCustodyConflict("intake_pre_result_mismatch")
+        if terminal.execution is None:
+            raise SubmissionIntakeFailure("submission_infrastructure_unavailable")
+        if not terminal.execution.eligible:
+            raise SubmissionIntakeFailure(
+                "pre_submission_checker_failed",
+                pre_submission_results=public_pre_submission_results(terminal.execution),
+            )
+        return await self._admission.accept(
+            owner, reservation, terminal.terminal_digest,
+            checkers=self._checkers, outbox=self._outbox,
+        )
diff --git a/backend/app/modules/artifacts/intake/streaming.py b/backend/app/modules/artifacts/intake/streaming.py
index 72bc220e9..927216583 100644
--- a/backend/app/modules/artifacts/intake/streaming.py
+++ b/backend/app/modules/artifacts/intake/streaming.py
@@ -30,6 +30,10 @@
 MAXIMUM_INGRESS_CHUNK_BYTES = 1024 * 1024
 
 
+class SubmissionUploadTimeout(ArtifactStoreUnavailableError):
+    """The request's idle/aggregate upload envelope expired, not a QC verdict."""
+
+
 @dataclass(frozen=True, slots=True)
 class RawSubmissionIdentity:
     raw_sha256: str
@@ -102,7 +106,7 @@ async def hash_submission_replay(
         raise ValueError("submission replay limits are invalid")
     remaining = (deadline_at - datetime.now(UTC)).total_seconds()
     if remaining <= 0:
-        raise ArtifactStoreUnavailableError("submission replay deadline expired")
+        raise SubmissionUploadTimeout("submission replay deadline expired")
     receipt = _IngressReceipt()
     try:
         async with asyncio.timeout(remaining):
@@ -112,7 +116,7 @@ async def hash_submission_replay(
                 pass
             _require_deadline(deadline_at)
     except TimeoutError:
-        raise ArtifactStoreUnavailableError("submission replay deadline expired") from None
+        raise SubmissionUploadTimeout("submission replay deadline expired") from None
     return receipt.identity()
 
 
@@ -130,12 +134,12 @@ async def receive_submission_source(
     upload = SubmissionSourceUpload.model_validate(upload)
     remaining = (upload.intent.upload_deadline_at - datetime.now(UTC)).total_seconds()
     if remaining <= 0:
-        raise ArtifactStoreUnavailableError("submission upload deadline expired")
+        raise SubmissionUploadTimeout("submission upload deadline expired")
     try:
         async with asyncio.timeout(remaining):
             return await _receive_parts(store, upload, chunks, operation_evidence)
     except TimeoutError:
-        raise ArtifactStoreUnavailableError("submission upload deadline expired") from None
+        raise SubmissionUploadTimeout("submission upload deadline expired") from None
 
 
 async def _receive_parts(
diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py
index 8df0a8a10..5246b2419 100644
--- a/backend/app/modules/checkers/api/selected_pre_submit.py
+++ b/backend/app/modules/checkers/api/selected_pre_submit.py
@@ -1089,6 +1089,10 @@ class SelectedPreSubmitCompletion:
 class SelectedPreSubmitCoordinationPort(Protocol):
     """CHECKERS-owned durable lease operations used by the ART workflow."""
 
+    async def read_source_terminal(self, *, source_operation_id: UUID) -> SelectedPreSubmitTerminalFacts | None:
+        """Read retained terminal evidence after ART authorizes the exact operation."""
+        ...
+
     async def read_current(
         self, facts: SelectedPreSubmitReservationFacts
     ) -> SelectedPreSubmitCurrentFacts | None:
diff --git a/backend/app/modules/checkers/selected_pre_submit_coordination.py b/backend/app/modules/checkers/selected_pre_submit_coordination.py
index 266d9a50f..35eb476fa 100644
--- a/backend/app/modules/checkers/selected_pre_submit_coordination.py
+++ b/backend/app/modules/checkers/selected_pre_submit_coordination.py
@@ -267,6 +267,32 @@ async def read_current(
             terminal=terminal,
         )
 
+    async def read_source_terminal(self, *, source_operation_id: UUID) -> SelectedPreSubmitTerminalFacts | None:
+        """Read immutable source evidence, including QC rejection, without rerunning PRE.
+
+        This internal port grants no actor authority. ART must hold its authorized
+        operation root and compare the returned original command before projection.
+        """
+        _require_root(self._session)
+        row = await self._session.scalar(select(SelectedPreSubmitRun).where(
+            SelectedPreSubmitRun.source_operation_id == str(source_operation_id)))
+        if row is None or row.terminal_json is None:
+            return None
+        if (row.finalize_evidence_id is None
+                or row.request_json.get("schema_version") != "workstream.selected_pre_submit_reservation.v2"
+                or row.terminal_json.get("schema_version") != "workstream.selected_pre_submit_terminal.v3"):
+            raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid")
+        try:
+            request = SelectedPreSubmitReservationFacts.from_canonical_body(row.request_json, source_contracts=self._source_contracts)
+            terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(row.terminal_json, source_contracts=self._source_contracts)
+            if not matches_source_request(row, request) or not matches_terminal(row, request, terminal):
+                raise ValueError("retained PRE differs")
+        except (TypeError, ValueError):
+            raise SelectedPreSubmitUnavailable("selected_pre_submit_stored_facts_invalid") from None
+        await self._session.execute(text("SELECT public.require_selected_pre_invocation(r) "
+            "FROM public.selected_pre_submit_runs r WHERE id=:id"), {"id": row.id})
+        return terminal
+
     async def read_accepted_terminal(self, *, run_id: UUID, source_operation_id: UUID,
                                      terminal_digest: str) -> SelectedPreSubmitTerminalFacts:
         """Read exact retained v3 evidence; ART independently owns accepted custody."""
diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py
index b407bbc07..bdd7665a9 100644
--- a/backend/scripts/behavior_ownership.py
+++ b/backend/scripts/behavior_ownership.py
@@ -936,6 +936,7 @@
     "backend/app/modules/authorization/project_catalogue.py",
 })
 SUBMISSION_INTAKE_TARGETS = frozenset({
+    "backend/app/modules/artifacts/intake/foreground_command.py",
     "backend/app/api/submission_intake.py",
     "backend/app/adapters/artifacts/source_cleanup.py",
     "backend/app/modules/artifacts/api/submission_cleanup.py",
diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py
index 04e85c9b0..06378c496 100644
--- a/backend/scripts/test_lane_catalogue.py
+++ b/backend/scripts/test_lane_catalogue.py
@@ -57,6 +57,7 @@ class TestLane:
     "tests/artifacts/test_submission_source_cleanup.py",
     "tests/artifacts/test_submission_pre_source.py",
     "tests/artifacts/test_submission_intake_admission.py",
+    "tests/artifacts/test_submission_foreground_command.py",
     "tests/authorization/post_submit/test_atomicity.py",
     "tests/authorization/post_submit/test_concurrency.py",
     "tests/authorization/post_submit/test_live_authority.py",
diff --git a/backend/tests/artifacts/intake_acceptance_support.py b/backend/tests/artifacts/intake_acceptance_support.py
index 8695f89c7..f9b208a75 100644
--- a/backend/tests/artifacts/intake_acceptance_support.py
+++ b/backend/tests/artifacts/intake_acceptance_support.py
@@ -1,4 +1,6 @@
 """Real T1/upload/PRE owners with the portable worker/runtime fixture for T4."""
+from contextlib import asynccontextmanager
+from datetime import timedelta
 from app.adapters.artifacts import submission_intake_pre_source_port
 from app.adapters.auth import selected_pre_submit_authority
 from app.adapters.checkers import selected_pre_submit_coordinator, SelectedPreSubmitCheckerExecutionAdapter
@@ -16,6 +18,51 @@
 from tests.test_trusted_intake import _archive
 
 
+@asynccontextmanager
+async def foreground_command(f, tmp_path, *, runtime_outcome="completed", idle_timeout_seconds=10):
+    from app.adapters.outbox import outbox_append
+    from app.adapters.tasks import task_submission_context_port
+    from app.modules.artifacts.intake.foreground_command import ForegroundSubmissionCommand, SubmissionForegroundLimits
+    from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease
+    from app.modules.tasks.intake_custody import IntakeTaskCustody
+
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    calls = []
+    payload = _archive("../escape") if runtime_outcome == "rejected" else _archive()
+    runtime, errors = _source_runtime(payload, tmp_path, runtime_outcome)
+    await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_PRE_SUBMIT)
+    await _seed_materializer(f.factory)
+
+    async def execute(reservation):
+        calls.append(reservation)
+        async with f.factory() as session:
+            service = SelectedPreSubmitExecutionService(
+                session=session, coordinator=selected_pre_submit_coordinator(session),
+                authority=selected_pre_submit_authority(session),
+                source_reads=SelectedPreSubmitSourceReads(
+                    session=session, sources=submission_intake_pre_source_port(session),
+                    authority=PreparedPreSubmitMaterializationAuthorization(
+                        session, request_id=new_record_id(), correlation_id=new_record_id()), store=store),
+                execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime),
+            )
+            return await service.execute(reservation=reservation)
+
+    try:
+        yield ForegroundSubmissionCommand(
+            admission=f.admission, upload=foreground_upload(f, store),
+            lease=ForegroundIntakeLease(f.factory,
+                lambda session: IntakeTaskCustody(session, task_submission_context_port(session)),
+                lease_duration=timedelta(seconds=60), heartbeat_interval=timedelta(seconds=10)),
+            limits=SubmissionForegroundLimits(part_bytes=5 * 1024**2,
+                idle_timeout_seconds=idle_timeout_seconds, pre_lease_seconds=60, replay_duration=timedelta(seconds=30)),
+            runtime_profile=_source_reservation().runtime_profile,
+            execute=execute, checkers=selected_pre_submit_coordinator, outbox=outbox_append,
+        ), calls
+        assert not errors, "\n".join(errors)
+    finally:
+        store.close()
+
+
 async def completed_source(f, tmp_path):
     """Return a real committed eligible PRE plus its exact original foreground owner."""
     metadata = SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment)
diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py
new file mode 100644
index 000000000..288e5bc32
--- /dev/null
+++ b/backend/tests/artifacts/test_submission_foreground_command.py
@@ -0,0 +1,166 @@
+"""Foreground command, exact replay and source-owner substitution proof."""
+import asyncio
+
+import pytest
+
+from app.core.identifiers import new_record_id
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+from tests.artifacts.test_submission_intake_admission import (
+    admission_intake as admission_intake,
+    admin_access as admin_access,
+    signed_access as signed_access,
+    rsa_signing_material as rsa_signing_material,
+    auth_database_env as auth_database_env,
+    clear_settings_cache as clear_settings_cache,
+)
+
+
+async def test_foreground_command_upload_timeout_retains_charge(admission_intake, tmp_path):
+    from sqlalchemy import text
+    from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
+    from tests.artifacts.intake_acceptance_support import foreground_command
+
+    f, key, drained = admission_intake, new_record_id(), asyncio.Event()
+    async def stalled_body():
+        try:
+            await asyncio.Event().wait()
+            yield b"unreachable"
+        finally:
+            drained.set()
+    async with foreground_command(f, tmp_path, idle_timeout_seconds=0.02) as (command, calls):
+        with pytest.raises(SubmissionIntakeFailure, match="submission_upload_timeout"):
+            await command.submit(
+                SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment), stalled_body(),
+                actor_id=f.actor.actor_profile_id, identity_link_id=f.actor.identity_link_id,
+                idempotency_key=key, declared_raw_bytes=None,
+            )
+        assert drained.is_set() and calls == []
+        async with f.factory() as session:
+            row = (await session.execute(text(
+                "SELECT id,state,failure_code FROM submission_intake_operations WHERE idempotency_key=:key"), {"key": key})).one()
+            assert (row.state, row.failure_code) == ("failed", "submission_upload_timeout")
+            assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": row.id}) == 1024
+
+
+@pytest.mark.parametrize("outcome", ["completed", "received_failure", "rejected"])
+async def test_foreground_command_accepts_or_fails_and_replays_without_new_pre(admission_intake, tmp_path, outcome):
+    from sqlalchemy import text
+    from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
+    from tests.artifacts.intake_acceptance_support import foreground_command
+    from tests.test_trusted_intake import _archive
+
+    f, key = admission_intake, new_record_id()
+    payload = _archive("../escape") if outcome == "rejected" else _archive()
+    async def body():
+        yield payload
+    arguments = dict(actor_id=f.actor.actor_profile_id, identity_link_id=f.actor.identity_link_id,
+                     idempotency_key=key, declared_raw_bytes=len(payload))
+    metadata = SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment)
+    async with foreground_command(f, tmp_path, runtime_outcome=outcome) as (command, calls):
+        if outcome == "completed":
+            receipt = await command.submit(metadata, body(), **arguments)
+            assert receipt["status"] == "accepted" and receipt["replayed"] is False
+            assert await command.submit(metadata, body(), **arguments) == dict(receipt, replayed=True)
+        else:
+            failures = []
+            code = "pre_submission_checker_failed" if outcome == "rejected" else "submission_infrastructure_unavailable"
+            for _ in range(2):
+                with pytest.raises(SubmissionIntakeFailure, match=code) as caught:
+                    await command.submit(metadata, body(), **arguments)
+                failures.append(caught.value.pre_submission_results)
+            assert failures[0] == failures[1]
+            if outcome == "rejected":
+                assert failures[0]
+        assert len(calls) == 1
+        async with f.factory() as session:
+            row = (await session.execute(text(
+                "SELECT state, failure_code, id FROM submission_intake_operations WHERE idempotency_key=:key"),
+                {"key": key})).one()
+            assert row.state == {"completed": "finalization_pending", "received_failure": "failed", "rejected": "rejected"}[outcome]
+            pointer = await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": f.task})
+            assert pointer == (row.id if outcome == "completed" else None)
+            assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": row.id}) == len(payload)
+            assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": f.task}) == 0
+
+
+async def test_foreground_command_cancellation_drains_and_releases_only_task_guard(admission_intake, tmp_path):
+    from sqlalchemy import text
+    from tests.artifacts.intake_acceptance_support import foreground_command
+
+    f, key, reading = admission_intake, new_record_id(), asyncio.Event()
+    async def body():
+        reading.set()
+        await asyncio.Event().wait()
+        yield b"unreachable"
+    async with foreground_command(f, tmp_path) as (command, calls):
+        pending = asyncio.create_task(command.submit(
+            SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment), body(),
+            actor_id=f.actor.actor_profile_id, identity_link_id=f.actor.identity_link_id,
+            idempotency_key=key, declared_raw_bytes=None,
+        ))
+        await asyncio.wait_for(reading.wait(), 20)
+        pending.cancel()
+        with pytest.raises(asyncio.CancelledError):
+            await asyncio.wait_for(pending, 20)
+        assert calls == []
+        async with f.factory() as session:
+            row = (await session.execute(text(
+                "SELECT id,state FROM submission_intake_operations WHERE idempotency_key=:key"), {"key": key})).one()
+            assert row.state == "cancelled"
+            assert await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": f.task}) is None
+            assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": row.id}) == 1024
+
+
+async def test_foreground_command_unknown_acceptance_never_terminalizes_committed_work(admission_intake, tmp_path, monkeypatch):
+    from app.modules.artifacts.intake.foreground_admission import IntakeCommitUnknown
+    from tests.artifacts.intake_acceptance_support import foreground_command
+    from tests.test_trusted_intake import _archive
+
+    f, key = admission_intake, new_record_id()
+    original = f.admission.accept
+    async def unknown(*args, **kwargs):
+        await original(*args, **kwargs)
+        raise IntakeCommitUnknown("response lost after commit")
+    monkeypatch.setattr(f.admission, "accept", unknown)
+    async def forbidden_finish(*args, **kwargs):
+        pytest.fail("Unknown acceptance must retain its durable outcome")
+    monkeypatch.setattr(f.admission, "finish", forbidden_finish)
+    async def body():
+        yield _archive()
+    metadata = SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment)
+    arguments = dict(actor_id=f.actor.actor_profile_id, identity_link_id=f.actor.identity_link_id,
+                     idempotency_key=key, declared_raw_bytes=None)
+    async with foreground_command(f, tmp_path) as (command, calls):
+        with pytest.raises(IntakeCommitUnknown):
+            await command.submit(metadata, body(), **arguments)
+        receipt = await command.submit(metadata, body(), **arguments)
+        assert receipt["status"] == "accepted" and receipt["replayed"] is True
+        assert len(calls) == 1
+
+
+@pytest.mark.parametrize("substitution", ["operation", "generation", "lease"])
+async def test_t3_reservation_rejects_substituted_source_or_owner(admission_intake, tmp_path, substitution):
+    from dataclasses import replace
+    from sqlalchemy import text
+    from app.adapters.checkers import selected_pre_submit_coordinator
+    from tests.artifacts.intake_acceptance_support import completed_source
+
+    f = admission_intake
+    owner, request, _ = await completed_source(f, tmp_path)
+    source = request.source
+    if substitution == "operation":
+        source = source.model_copy(update={"location": source.location.model_copy(
+            update={"operation_id": new_record_id()})})
+    elif substitution == "generation":
+        source = source.model_copy(update={"provider_generation": "another-generation"})
+    else:
+        owner = replace(owner, lease_id=new_record_id())
+    with pytest.raises(IntakeCustodyConflict):
+        await f.admission.reserve_pre(
+            owner, source, runtime_profile=request.runtime_profile,
+            checkers=selected_pre_submit_coordinator,
+        )
+    async with f.factory() as session:
+        assert await session.scalar(text(
+            "SELECT count(*) FROM selected_pre_submit_runs WHERE task_id=:id"), {"id": f.task}) == 1
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index d28572bd4..e6201ea6b 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -453,6 +453,12 @@ async def body():
         assert row.state == "receiving" and row.lease_generation == owner.generation
 
 
+
+
+
+
+
+
 async def test_t4_accepts_exact_source_and_replays_one_receipt(admission_intake, tmp_path):
     """T1/upload/PRE through the real atomic T4 owner; no formal Submission yet."""
     from sqlalchemy import text
@@ -502,31 +508,6 @@ async def repeated_body():
                                     {"id": owner.operation_id}) == 1
 
 
-@pytest.mark.parametrize("substitution", ["operation", "generation", "lease"])
-async def test_t3_reservation_rejects_substituted_source_or_owner(admission_intake, tmp_path, substitution):
-    from dataclasses import replace
-    from sqlalchemy import text
-    from app.adapters.checkers import selected_pre_submit_coordinator
-    from tests.artifacts.intake_acceptance_support import completed_source
-
-    f = admission_intake
-    owner, request, _ = await completed_source(f, tmp_path)
-    source = request.source
-    if substitution == "operation":
-        source = source.model_copy(update={"location": source.location.model_copy(
-            update={"operation_id": new_record_id()})})
-    elif substitution == "generation":
-        source = source.model_copy(update={"provider_generation": "another-generation"})
-    else:
-        owner = replace(owner, lease_id=new_record_id())
-    with pytest.raises(IntakeCustodyConflict):
-        await f.admission.reserve_pre(
-            owner, source, runtime_profile=request.runtime_profile,
-            checkers=selected_pre_submit_coordinator,
-        )
-    async with f.factory() as session:
-        assert await session.scalar(text(
-            "SELECT count(*) FROM selected_pre_submit_runs WHERE task_id=:id"), {"id": f.task}) == 1
 
 
 @pytest.mark.parametrize("boundary", ["outbox", "task"])
diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py
index 863aaac25..c49a0115a 100644
--- a/backend/tests/artifacts/test_submission_intake_contracts.py
+++ b/backend/tests/artifacts/test_submission_intake_contracts.py
@@ -23,7 +23,7 @@
 from app.interfaces.artifacts import (
     ArtifactInputMismatchError, ArtifactLimitExceededError, ArtifactStoreUnavailableError,
 )
-from app.modules.artifacts.intake.streaming import receive_submission_source
+from app.modules.artifacts.intake.streaming import receive_submission_source, SubmissionUploadTimeout
 
 
 OPERATION = UUID("019a0000-0000-7000-8000-000000000001")
@@ -447,7 +447,7 @@ async def chunks():
         finally:
             stopped.set()
 
-    with pytest.raises(ArtifactStoreUnavailableError):
+    with pytest.raises(SubmissionUploadTimeout):
         await hash_submission_replay(
             chunks(), maximum_raw_bytes=100, declared_raw_bytes=None,
             idle_timeout_seconds=10 if total_deadline else 0.01,
@@ -502,7 +502,7 @@ async def chunks():
 
     idle = 0.01 if deadline == "idle" else 10
     expires = datetime.now(UTC) + timedelta(seconds=0.01 if deadline == "total" else 10)
-    with pytest.raises(ArtifactStoreUnavailableError):
+    with pytest.raises(SubmissionUploadTimeout):
         if path == "replay":
             await hash_submission_replay(chunks(), maximum_raw_bytes=100, declared_raw_bytes=None,
                                          idle_timeout_seconds=idle, deadline_at=expires)
@@ -525,7 +525,7 @@ async def upload_source_part(self, upload, number, data, **kwargs):
     async def chunks():
         yield b"abc"
 
-    with pytest.raises(ArtifactStoreUnavailableError):
+    with pytest.raises(SubmissionUploadTimeout):
         await receive_submission_source(BufferedStore(), upload_value(
             upload_deadline_at=datetime.now(UTC) + timedelta(seconds=0.01),
         ), chunks())
diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py
index 77634a8a4..a4c12e605 100644
--- a/backend/tests/artifacts/test_submission_pre_source.py
+++ b/backend/tests/artifacts/test_submission_pre_source.py
@@ -441,7 +441,7 @@ async def execute_pre(self, lease, grant):
             try:
                 return await self.run(lease, grant)
             except Exception:
-                if runtime_outcome == "completed":
+                if runtime_outcome in {"completed", "rejected"}:
                     import traceback
                     runtime_errors.append(traceback.format_exc())
                 raise
@@ -453,7 +453,7 @@ async def run(self, lease, grant):
                 body = receipt_body(lease, outcome="infrastructure_failure", reason="capacity_exceeded")
                 body["cleanup"]["disposition"] = "pending"
                 return SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None}, source_contracts=selected_pre_submit_source_contracts())
-            if runtime_outcome == "completed":
+            if runtime_outcome in {"completed", "rejected"}:
                 worker, output, reply, actual_lease = _pre_worker(
                     tmp_path, payload, lease=lease,
                     isolation_override={"runtime": "smolvm", "isolation_mode": "smol-microvm"},
@@ -461,8 +461,12 @@ async def run(self, lease, grant):
                 assert actual_lease is lease
                 worker.run()
                 output.seek(0)
-                project_frame, completion = _read(output), _read(output)
-                assert project_frame["operation"] == "project" and reply.calls == 1
+                if runtime_outcome == "completed":
+                    project_frame, completion = _read(output), _read(output)
+                    assert project_frame["operation"] == "project" and reply.calls == 1
+                else:
+                    completion = _read(output)
+                    assert completion["payload"]["eligible"] is False and reply.calls == 0
                 assert completion["operation"] == "completed" and output.read() == b""
                 response = receipt_body(lease) | {"execution": completion["payload"]}
                 return SelectedPreSubmitInvocationResult.from_canonical_body(response, source_contracts=selected_pre_submit_source_contracts())
diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py
index 8d2ea726d..ea63b896e 100644
--- a/backend/tests/test_behavior_ownership.py
+++ b/backend/tests/test_behavior_ownership.py
@@ -2763,6 +2763,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ
     retained = "backend/app/core/config.py"
     target = "backend/app/modules/artifacts/api/submission_intake.py"
     additions = {
+        "backend/app/modules/artifacts/intake/foreground_command.py",
         "backend/app/api/submission_intake.py",
         target, "backend/app/modules/artifacts/intake/models.py",
         "backend/app/adapters/artifacts/source_cleanup.py",
diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py
index 68b980fb5..56fe1ad56 100644
--- a/backend/tests/test_ci_lane_catalogue.py
+++ b/backend/tests/test_ci_lane_catalogue.py
@@ -318,8 +318,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None:
     """A catalogue-internal move across semantic families must fail this contract."""
     expected = {
         "shared": (
-            275,
-            "d59b427b71f98d981bd188dbc4d1690498481d5a93c9cf74c382f748600dc609",
+            276,
+            "405c1f61d06426c34a9269e41530f36c0ce3dcaf9440edddf4def0945ce22ee6",
         ),
         "project": (
             256,

From 58cfcc8c6748fb587b8b455bcc1636cf9b5cae48 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 13:05:13 +0100
Subject: [PATCH 153/513] fix(submission): reject case-variant duplicate packet
 headers

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 34 +++++++++++
 backend/app/api/submission_intake.py          |  6 +-
 backend/tests/test_api_controls.py            | 56 +++++++++++++++++++
 3 files changed, 95 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 60a4c0533..7f56ab087 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4281,3 +4281,37 @@ members plus the new module before updating the276-member fingerprint. All59 CI
 lane catalogue tests passed in6.59s. Ownership validation/exact-addition proof,
 module boundaries, Ruff, Commitrail records, markdown links and diff checks passed.
 These are scoped worktree receipts, not full CI or public end-to-end readiness.
+
+### Frozen command proof and mixed-case header review repair
+
+Frozen implementation b2d7dd325ff41643dd0f898f53f80596b0da480f remained clean
+through the required review snapshots and final root suites. PostgreSQL command
+module:9passed186.81s, exit0, exacthead/Alembic0080/database cleanup complete
+(/tmp/submission-foreground-frozen-db.log/json). Combined intake contracts and
+API-controls:156passed71.30s, exit0 (/tmp/submission-foreground-frozen-pure.log).
+Both used backend/.venv Python with PYTHONFAULTHANDLER=1 and PYTHONMALLOC=debug.
+The earlier supplemental timeout case passed1 in39.07s with cleanup complete.
+Origin/main was fetched again and this branch has zero missing main commits.
+
+Documentation/CI integrity review passed the250d8af70..b2d7dd325 delta, including
+independent partition/lane preservation, AST relocation and adversarial mutations
+(/tmp/submission-foreground-docs-ci-adversarial.json). Architecture/security and
+QA/test_delta identified one shared Medium finding: Starlette getlist did not
+count differently cased raw ASGI header names. They found no second material
+command/retained-read defect; local duplication of retained decode validation
+was assessed as optional simplification, not a bypass. QA's lowercase-guard
+mutant failed the expected assertion; controlled retained-terminal substitutions
+were rejected. Those controlled probes are not PostgreSQL custody proof.
+
+Repair counts and selects from one raw-name-lowercased Headers collection,
+preserving exact value bytes. Twelve new regression cases first failed against
+b2d7dd325 (/tmp/submission-header-casefold-before.log): eleven valid-control
+mixed-case duplicates were accepted and a single uppercase-name packet was
+incorrectly rejected. Full API-controls after repair:55passed23.73s, exit0
+(/tmp/submission-header-casefold-after.log); Ruff/diff checks passed. This parser
+repair changes no command/runtime/DB owner. Affected review replay remains pending
+at this entry; the original blocked finding is not yet declared closed.
+
+The public route, explicit deployment composition/readiness, coordinated clients,
+remaining cleanup/deployment/provider qualification, full CI and complete goal
+remain unfinished. No merge readiness is requested.
diff --git a/backend/app/api/submission_intake.py b/backend/app/api/submission_intake.py
index cf16afbfc..637e6ceda 100644
--- a/backend/app/api/submission_intake.py
+++ b/backend/app/api/submission_intake.py
@@ -3,6 +3,7 @@
 from typing import NoReturn
 from uuid import UUID
 
+from starlette.datastructures import Headers
 from starlette.requests import Request
 
 from app.core.api_controls import StructuredHTTPException
@@ -32,7 +33,10 @@ def _reject(code: str, status_code: int, message: str) -> NoReturn:
 
 def submission_intake_headers(request: Request, task_id: UUID) -> SubmissionIntakeHeaders:
     """Parse once without reading, trimming or otherwise rewriting packet bytes."""
-    headers = request.headers
+    # Count and select from the same case-insensitive raw collection. ASGI
+    # servers normally lowercase names, but an intermediary must not be able
+    # to hide a second selector from the ambiguity check by preserving case.
+    headers = Headers(raw=[(name.lower(), value) for name, value in request.scope["headers"]])
     for name in _PACKET_HEADERS:
         if len(headers.getlist(name)) > 1:
             _reject("submission_packet_invalid", 422, "Submission headers are ambiguous")
diff --git a/backend/tests/test_api_controls.py b/backend/tests/test_api_controls.py
index 41aaa7c81..4c80705c1 100644
--- a/backend/tests/test_api_controls.py
+++ b/backend/tests/test_api_controls.py
@@ -1003,3 +1003,59 @@ def test_raw_submission_invalid_headers_refuse_before_body(extra, omit, status,
     with pytest.raises(StructuredHTTPException) as caught:
         submission_intake_headers(_raw_submission_request(extra, omit=omit), UUID(int=3))
     assert (caught.value.status_code, caught.value.error_code) == (status, code)
+
+
+def _casefold_packet_headers():
+    return [
+        (b'content-type', b'application/zip'),
+        (b'idempotency-key', b'019a0000-0000-7000-8000-000000000001'),
+        (b'x-task-assignment-id', b'019a0000-0000-7000-8000-000000000002'),
+        (b'x-submission-summary', b'Exact  text'),
+        (b'x-contributor-attestation', b'My work'),
+        (b'x-predecessor-submission-id', b'019a0000-0000-7000-8000-000000000003'),
+        (b'x-revision-preparation-id', b'019a0000-0000-7000-8000-000000000004'),
+        (b'x-revision-preparation-sha256', b'sha256:' + b'a' * 64),
+        (b'content-encoding', b'identity'),
+        (b'content-length', b'1'),
+    ]
+
+
+def _casefold_request(headers):
+    async def forbidden_read():
+        raise AssertionError('Header parsing consumed the body')
+    return Request({'type': 'http', 'headers': headers}, receive=forbidden_read)
+
+
+@pytest.mark.parametrize('header', [
+    b'content-type', b'idempotency-key', b'x-task-assignment-id',
+    b'x-submission-summary', b'x-contributor-attestation',
+    b'x-predecessor-submission-id', b'x-revision-preparation-id',
+    b'x-revision-preparation-sha256', b'content-encoding', b'content-length',
+    b'transfer-encoding',
+])
+def test_raw_submission_mixed_case_duplicates_reject_valid_packet(header):
+    from app.api.submission_intake import submission_intake_headers
+    from app.core.api_controls import StructuredHTTPException
+
+    headers = _casefold_packet_headers()
+    if header == b'transfer-encoding':
+        headers = [pair for pair in headers if pair[0] != b'content-length']
+        headers.append((header, b'chunked'))
+    task = UUID(int=3)
+    # Valid control prevents an unrelated packet/framing error from satisfying
+    # the duplicate refusal assertion.
+    assert submission_intake_headers(_casefold_request(headers), task).metadata.summary == 'Exact  text'
+    value = next(value for name, value in headers if name == header)
+    with pytest.raises(StructuredHTTPException) as caught:
+        submission_intake_headers(_casefold_request(headers + [(header.upper(), value)]), task)
+    assert caught.value.status_code == 422
+    assert caught.value.error_code == 'submission_packet_invalid'
+
+
+def test_raw_submission_single_mixed_case_names_preserve_exact_values():
+    from app.api.submission_intake import submission_intake_headers
+
+    lower = _casefold_packet_headers()
+    upper = [(name.upper(), value) for name, value in lower]
+    task = UUID(int=3)
+    assert submission_intake_headers(_casefold_request(upper), task) == submission_intake_headers(_casefold_request(lower), task)

From 53d369b4ceb9c19f621d95ece18e6bb91284b651 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 13:07:15 +0100
Subject: [PATCH 154/513] docs(submission): record foreground command proof and
 review closure

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md          | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 7f56ab087..d2161ee8b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4315,3 +4315,21 @@ at this entry; the original blocked finding is not yet declared closed.
 The public route, explicit deployment composition/readiness, coordinated clients,
 remaining cleanup/deployment/provider qualification, full CI and complete goal
 remain unfinished. No merge readiness is requested.
+
+### Foreground composition review closure
+
+All required bounded reviews closed on clean58cfcc8c6748fb587b8b455bcc1636cf9b5cae48,
+with implementation parentb2d7dd325ff41643dd0f898f53f80596b0da480f unchanged:
+architecture/security PASS, QA/test_delta PASS AFTER FIXES, documentation/CI
+integrity PASS. The shared mixed-case finding is closed. Architecture independently
+rejected same-value and conflicting mixed-case duplicates. QA independently ran
+all12 exact regression bodies on58cfcc8c6; all passed
+(/tmp/submission-header-casefold-qa-frozen-replay.log). No other material finding
+remains in this private-command/parser delta. The exactb2 PostgreSQL9 and pure156
+receipts remain applicable to unchanged command/runtime owners; parser55 proof
+and independent frozen regression replay cover the repair. Record/link/diff checks
+also passed after repair. This evidence closure changes no implementation.
+
+The full goal remains active: public HTTP/configuration/progress/client cutover,
+remaining cleanup/worker/provider qualification, downstream journeys and full CI
+are still required in PR708 before readiness. No merge request or new PR is made.

From 666be589370c15fe6be15b3ed96bcf97974912bb Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 13:59:25 +0100
Subject: [PATCH 155/513] feat(submission): expose raw ZIP acceptance and owner
 progress reads

---
 .ci/behavior-ownership/partition.v1.json      |   6 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 227 ++++++++
 backend/app/adapters/artifacts/__init__.py    | 151 ++++++
 backend/app/adapters/auth/__init__.py         |   7 +
 .../app/api/routes/artifact_submissions.py    | 213 +++-----
 backend/app/core/config.py                    |   3 +
 .../artifacts/api/submission_command.py       |  67 +++
 .../app/modules/artifacts/intake/progress.py  |  43 ++
 .../checkers/api/delivery_reconciliation.py   |  15 +
 backend/app/modules/checkers/api/execution.py |  19 +
 .../checkers/delivery_reconciliation.py       |  14 +-
 backend/app/modules/checkers/execution.py     |  38 +-
 .../checkers/execution_coordination.py        |  91 +++-
 .../app/modules/checkers/execution_results.py |  27 +
 .../modules/tasks/api/submission_history.py   |  26 +
 backend/app/modules/tasks/router.py           |  88 ---
 .../app/modules/tasks/submission_history.py   |  39 +-
 backend/scripts/behavior_ownership.py         |   1 +
 .../test_submission_foreground_command.py     |  60 +++
 .../test_submission_intake_admission.py       |  93 +++-
 .../test_submission_intake_contracts.py       |  79 +++
 .../tasks/test_public_submission_intake.py    |  30 +-
 backend/tests/test_api_controls.py            |  47 +-
 backend/tests/test_behavior_ownership.py      |   1 +
 cli/internal/api/submission.go                | 115 ++--
 cli/internal/api/submission_test.go           |   4 +-
 cli/internal/command/submission.go            |  47 +-
 cli/tests/integration/test_submission_http.py | 201 +++----
 mcp_server/README.md                          |  14 +-
 mcp_server/contracts/preparation_create.json  | 509 ------------------
 mcp_server/contracts/submission_create.json   | 321 +++++++----
 mcp_server/pyproject.toml                     |   1 -
 mcp_server/tests/test_task_execution.py       | 111 ++--
 .../test_task_execution_contract_drift.py     |   2 +-
 mcp_server/workstream_mcp/http_gateway.py     |  28 +-
 mcp_server/workstream_mcp/schemas.py          |  70 +--
 .../workstream_mcp/tools/task_execution.py    |   6 +-
 37 files changed, 1548 insertions(+), 1266 deletions(-)
 create mode 100644 backend/app/modules/artifacts/api/submission_command.py
 delete mode 100644 mcp_server/contracts/preparation_create.json

diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json
index 15a32df63..287d4ea30 100644
--- a/.ci/behavior-ownership/partition.v1.json
+++ b/.ci/behavior-ownership/partition.v1.json
@@ -568,6 +568,10 @@
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/api/submission_cleanup.py"
     },
+    {
+      "group": "artifacts",
+      "target": "backend/app/modules/artifacts/api/submission_command.py"
+    },
     {
       "group": "artifacts",
       "target": "backend/app/modules/artifacts/api/submission_finalization.py"
@@ -2769,7 +2773,7 @@
       "target": "backend/scripts/validate_test_lane_evidence.py"
     }
   ],
-  "authority_digest": "f559788ce2965bb7683b1c637c730130937fce9964084a3adc27974fb1976420",
+  "authority_digest": "d416a689c5079db878d9baa8a5008a63ef892cf8745cba615d4eab8066cf74db",
   "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6",
   "schema": "workstream.behavior-ownership-partition.v1"
 }
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index d2161ee8b..bd3e1c2bd 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4333,3 +4333,230 @@ also passed after repair. This evidence closure changes no implementation.
 The full goal remains active: public HTTP/configuration/progress/client cutover,
 remaining cleanup/worker/provider qualification, downstream journeys and full CI
 are still required in PR708 before readiness. No merge request or new PR is made.
+
+### Public raw-ZIP composition and CLI cutover worktree evidence
+
+The public POST now composes the foreground command through the canonical ART
+adapter root and returns the closed nine-field T4 acceptance snapshot. Removed
+the preparation POST and the old TASK JSON/admission mutation. An explicit
+submission execution profile supplies capacity, runtime and timing limits;
+missing/invalid configuration fails before provider work. No deployment values
+or provider qualification are inferred from test configuration. The new public
+command contract is registered without reassigning prior ownership targets.
+
+Real signed-HTTP tests exercise source upload and PRE with real owner/DB custody
+and a portable worker: rejected replay passed in the initial two-case run; accepted
+replay passed separately in `/tmp/submission-public-accepted-db.log/json` (1 pass,
+Alembic0080, isolated database cleanup complete). The initial accepted case failed
+in registry fixture setup: Docker logs establish a PostgreSQL backend signal11 at
+2026-11-16 12:16:28 UTC, before the submission request. Evidence is retained in
+`/tmp/submission-public-postgres-crash.log`. Recovery and a passing replay do not
+resolve that infrastructure defect or replace a clean combined run.
+
+CLI submit now streams the ZIP with the same caller key and exact packet/revision
+headers, validates the stable202 receipt and bounded PRE feedback, and distinguishes
+acceptance for evaluation from a final Submission. Removed the prepare command and
+admission-consuming mutation. Migrated the hostile-peer process tests to the new
+single mutation: preserve exact bytes/headers on explicit replay, revision pairing,
+local source bounds/change detection, unknown outcomes, no retry after HTTP2 GOAWAY,
+closed response identities, safe feedback and response size limits. The old JSON
+creation assertions are superseded by raw-ZIP acceptance assertions; immutable
+history/findings tests remain intact. Their shared fixtures remain consumed by
+TUI, contributor and management read tests.
+
+`go test ./internal/api ./internal/command` passed from cli/. The first attempted
+Go command from repository root did not run tests and is not validation. Initial
+migrated process suite:14 passed,1 failed in36.39s
+(`/tmp/submission-cli-http-cutover.log`): human rendering included a null feedback
+field before the readable findings. Fix omits that nil field during human
+serialization; raw API receipt validation still requires nonnull feedback. Final
+replay evidence follows when available. These local changes remain in progress;
+MCP, real public CLI journeys, progress exposure, full API controls and coordinated
+cutover review must close before treating this as a finished checkpoint.
+
+Corrected worktree replay: Go API/command packages passed and rebuilt executable
+passed all15 hostile-HTTP submission process tests in42.70s
+(`/tmp/submission-cli-http-cutover-fixed.log`). Full backend API-controls module
+passed57 in135.06s (`/tmp/submission-public-controls-rerun.log`), including the
+single raw-ZIP OpenAPI contract and ambiguous-header refusal before body/command
+execution. No files under either completed suite changed during that replay.
+A fresh origin/main fetch reported zero commits missing from this branch.
+These receipts close the local display and API-control test failures only;
+coordinated MCP/public journey migration and final scoped reviews remain open.
+
+### MCP single-mutation cutover worktree evidence
+
+Replaced the MCP admission JSON mutation with raw-ZIP submission acceptance.
+`submission_create` now accepts the caller assignment/key, bounded Base64 ZIP and
+exact packet/revision fields; the gateway sends one202 POST to submissions and
+binds response task/assignment identities. Removed preparation_create from input
+schemas, tool catalogue, fixed gateway operations, packaged contracts and wheel
+inclusions. Existing preparation reads remain until their retained-reader/public
+progress migration is complete. No second supported mutation or compatibility
+alias was added. The16 remaining execution tools preserve their prior read and
+management routes. Refreshed submission_create's snapshot from actual backend
+OpenAPI and updated MCP documentation.
+
+Retained upload/header, safe checker failure and fixed-route tests now exercise
+submission_create. Added acceptance substitutions/malformed-snapshot and revision
+pairing cases. Initial run42passed2skipped (backend comparison command absent),
+`/tmp/submission-mcp-cutover.log`; this does not establish OpenAPI drift closure.
+Ruff and diff checks passed. A configured backend comparison plus adversarial
+cases and package/catalogue checks are running; final receipts follow.
+
+Expanded configured MCP run:53passed1failed in54.22s
+(`/tmp/submission-mcp-cutover-verified.log`). Failure was the backend OpenAPI
+subprocess dying withSIGSEGV, not a reported contract difference. Exact failed
+test replay with PYTHONFAULTHANDLER=1/PYTHONMALLOC=debug passed1 in56.28s
+(`/tmp/submission-mcp-openapi-diagnostic.log`). The live backend OpenAPI matches
+all16 execution snapshots on replay; no root-cause fix is claimed. The retained
+first-run crash is additional native instability evidence.
+
+Catalogue/package command passed3 with1skip because no clean-wheel interpreter
+was configured. Built the wheel using the canonical isolated uv build (the earlier
+no-isolation attempt lacked hatchling and did not build), installed it into a
+fresh /tmp environment and started the configured independence proof. This removes
+the obsolete preparation contract from wheel inputs without requiring backend
+sources at runtime. Final package/type receipts follow when terminal.
+
+Configured clean-wheel independence proof passed1 in22.71s
+(`/tmp/submission-mcp-wheel-proof.log`), and mypy passed all25 source files
+(`/tmp/submission-mcp-types.log`). No MCP code changed during these final checks.
+This closes the bounded MCP upload/acceptance transport migration, not the full
+public journey: operation-progress API/client reads, bounded feedback parity,
+remaining real public CLI/backend fixtures, coordinated reviews, deployment
+qualification and the full acceptance audit remain required on the same PR.
+
+### Operation progress: exact finalized TASK association
+
+Within the coordinated public-read scope, extend TASK's existing immutable history
+port/repository to resolve the operation's exact finalized Submission and dispatch.
+Require project/task/assignment/contributor/admission identity together and equal
+stored Submission/dispatch versions. Return only the exact attempt status and
+original evaluation request identity; do not read the latest task Submission or
+infer evaluation activity from TASK status. Missing/mismatched association is an
+integrity-unavailable result, never fallback history. This is a read participant;
+its caller must establish AUTH in the read transaction before exposing facts.
+
+Allowed: existing TASK history API/repository and the existing real T5 integration
+proof. Preserve canonical adapter composition and all immutable rows. No new route
+or authorization grant is supplied by this participant. Verify real accepted T5
+association, each substituted selector and stored outcome after actual POST.
+Required coordinated ARCH/SEC, QA and DOCS review remains open for the complete
+public read; this participant alone cannot close progress or end-to-end delivery.
+
+Exact-association worktree verification: both real T5 cases (normal and expired
+finalizer claim) passed2,37deselected in64.69s, with migrations through0080 and
+isolated database cleanup complete (`/tmp/submission-progress-task-association.log/json`).
+Each case rejects substitution of project/task/assignment/contributor/Submission/
+admission and confirms that completed POST evidence without governed routing
+leaves this exact attempt's outcome unchanged. The added reader neither queries
+current task status nor selects a latest Submission. Ruff, diff and module-boundary
+validation passed (`/tmp/submission-progress-boundaries.log`, exit0).
+
+This is one required TASK read participant, not a publicly usable progress API.
+CHECKERS current-attempt/stall observation, contributor/management AUTH composition,
+current-task visibility and next-action eligibility, final closed response, route,
+CLI/MCP reads and their real public journeys remain open. Tests ran on the current
+worktree; metadata HEAD53d369b4c does not imply the uncommitted delta was frozen in
+that commit. Coordinated review and proper implementation commits remain pending.
+
+### Operation progress: current CHECKERS attempt evidence
+
+Extend the existing evaluation coordination port/owner with an exact current
+progress observation anchored to the original Submission dispatch request. Read
+that Submission's current fence and run; validate original and current scope,
+request/reservation, terminal result, and committed retry receipt for successors.
+Return the current request/reservation, owner status, database-clock live-lease
+fact, exact retry event (when applicable) and completion event. These are internal
+facts for progress composition; no new execution authority or public diagnostics.
+The caller owns the root transaction and TASK-first locking. Do not derive
+running/stalled status from TASK status or rewrite fences/leases. OUTBOX stall
+and reconciliation-child observation remains a separate required composition.
+
+Allowed: existing CHECKERS execution API/coordinator and existing real T5/retry
+integration tests. Retain exact historical Submission association and prior
+request validation. Verify queued/completed states through real source T5/POST,
+selector substitution and a real committed retry. Coordinated risk/reviewer
+requirements from the public cutover apply unchanged.
+
+Initial CHECKERS observation run passed the two source T5 cases but failed the
+existing retry test before the new observation: its shared material_fixture still
+calls retired bundle preparation and passes PreSubmitMaterializationPreparationFacts
+to the now guide-only resource mapper (AttributeError:guide_source_item_id).
+`/tmp/submission-progress-checker-observation.log/json`:2passed1failed,97.82s;
+isolated database cleanup complete. Do not restore the obsolete API or treat that
+fixture as proof of current intake. Its original assertions remain unchanged and
+its migration remains a full-suite requirement.
+
+Moved new retry-progress proof into the actual source T5 test: a controlled exact
+source-read outage produces retained infrastructure failure, then the real Operator
+retry owner commits a successor and the read follows its audited event. Successful
+POST cases additionally observe the actual running lease from an independent root
+session during the controlled worker call. No execution, authorization or retry
+owner is mocked. The controlled runtime/provider outage is not native qualification.
+Expanded source replay is running. Module-boundary validation passed before this
+test-only refinement; production CHECKERS files are unchanged since that check.
+
+Expanded source-first progress proof passed3,37deselected in98.68s
+(`/tmp/submission-progress-checker-source-retry.log/json`), Alembic0080 and database
+cleanup complete. It proves queued and completed exact-request observations,
+substituted-selector refusal, actual live-worker observation through an independent
+session, infrastructure failure, and current-fence transition to an authorized
+retry successor/event. The worker observation returned during execution; it did
+not wait for completion. No native-runtime or AWS qualification is inferred.
+
+One Pydantic serialization warning occurs on the real retry path: existing
+checker_retry builds request_fields with nested dicts, then
+make_selected_post_submit_request uses model_construct before serialized hashing
+and final model_validate. The final request and new read validate successfully;
+this warning does not originate from the progress read. It remains recorded and
+is not silenced. The earlier obsolete-fixture failure remains outstanding.
+
+CHECKERS runtime progress is now available internally through its existing port.
+Public progress still requires exact OUTBOX delivery/recovery-child observation,
+reader AUTH/current-task concealment and next-action eligibility, closed projection,
+HTTP/CLI/MCP reads, and end-to-end verification. These are uncommitted worktree
+receipts, not a reviewed/frozen implementation checkpoint or overall completion.
+
+### Operation progress: exact delivery observation
+
+Reuse publisher event construction for initial dispatch, completion and authorized
+reconciliation child. Extend the existing internal TASK/CHECKERS progress facts
+with their exact event expectations. ART's existing progress module will observe
+OUTBOX against those expectations and follow only a child bound to the same
+original event, claim generation/digest and current evaluation identity. Never
+expose event payloads/private coordinates in the public projection. A finalized
+UNKNOWN original with a pending authorized child is not itself proof of a current
+stall. Missing/mismatched custody fails closed.
+
+Allowed: existing TASK history API/repository, CHECKERS execution API/results/
+coordinator/publisher and reconciliation API/service, ART progress module and the
+existing source T5/contract tests. Preserve emitted event bytes, existing authority
+and original terminal evidence; no retries, publishes or claims from a read.
+Verify real stored initial/completion/retry event comparison and focused child
+association/refusal cases. Full public-route/read AUTH and final review remain
+required; this change only closes the durable delivery observation prerequisite.
+
+Delivery observation proof: real source T5 suite passed3 in92.12s with0080 and
+isolated database cleanup complete (`/tmp/submission-progress-delivery-db.log/json`).
+It compares stored initial, completion and retry events through OUTBOX's exact
+observation owner. Reconciliation contract module passed34 in5.39s; initial child
+association checks passed8 in1.94s. Module-boundary and all changed backend Python
+Ruff checks passed.
+
+An additional controlled retained-digest substitution reproduced a missing guard:
+parent read and child agreed with each other on a digest different from the
+owner's expected event. Before repair the new test failed DID NOT RAISE
+(`/tmp/submission-progress-delivery-digest-before.log`). Compare the retained claim
+to canonical_json_hash(event.payload) before following a child. All9 child identity
+cases now pass in2.39s (`/tmp/submission-progress-delivery-digest-after.log`). This
+repair adds no event publication or authority and changes only that read guard.
+
+Freeze the accumulated raw-ZIP API/CLI/MCP mutation cutover and internal progress
+participants as a proper implementation commit on the existing PR branch. The
+commit is an incomplete-goal checkpoint: public operation GET and client reads,
+MCP feedback parity, obsolete fixture/shared producer migration, complete downstream
+journeys, cleanup/runtime/provider/deployment qualification and full CI remain open.
+No PR readiness or merge request is made. Scoped internal reviews will assess this
+implemented delta with those omissions explicit, rather than certify goal completion.
diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py
index 997d6bc09..48f72ac06 100644
--- a/backend/app/adapters/artifacts/__init__.py
+++ b/backend/app/adapters/artifacts/__init__.py
@@ -2,6 +2,39 @@
 
 from __future__ import annotations
 
+from datetime import timedelta
+import logging
+
+from pydantic import ValidationError
+from sqlalchemy.exc import SQLAlchemyError
+
+from app.adapters.auth import selected_pre_submit_authority, submission_intake_authority
+from app.adapters.checkers import selected_pre_submit_checker_execution, selected_pre_submit_coordinator
+from app.adapters.outbox import outbox_append, finalized_unknown_deliveries
+from app.adapters.tasks import intake_task_custody_port
+from app.interfaces.artifacts import ArtifactInputMismatchError, ArtifactLimitExceededError, ArtifactStoreError
+from app.interfaces.external_services import ExternalServiceAdapterError
+from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
+from app.modules.artifacts.api.submission_command import SubmissionExecutionProfile, SubmissionIntakeCommand
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
+from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization
+from app.modules.artifacts.intake.capacity import SubmissionSourceCapacityConflict
+from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission, IntakeCommitUnknown
+from app.modules.artifacts.intake.foreground_command import ForegroundSubmissionCommand, SubmissionForegroundLimits
+from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease
+from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload
+from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService, SelectedPreSubmitSourceReads
+from app.modules.artifacts.service import artifact_storage_namespace_spec
+from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied
+from app.modules.checkers.api.source_contracts import source_contracts_context
+from app.modules.checkers.api.selected_pre_submit import (
+    SelectedPreSubmitAuthorityUnavailable, SelectedPreSubmitInfrastructureUnavailable,
+    SelectedPreSubmitRequestConflict, SelectedPreSubmitUnavailable,
+)
+from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable
+
+
 from contextlib import asynccontextmanager
 from collections.abc import Callable
 from typing import Annotated, cast
@@ -1051,3 +1084,121 @@ def construct(adapter):
     factory.register("local", lambda: construct(LocalSubmissionSourceCleanup))
     factory.register("s3_compatible", lambda: construct(S3SubmissionSourceCleanup))
     return factory.create(settings.artifact_store_backend)
+
+
+logger = logging.getLogger(__name__)
+
+
+def _submission_public_failure(exc: Exception) -> SubmissionIntakeFailure:
+    """Keep private custody/provider diagnostics out of the public error envelope."""
+    code = "submission_infrastructure_unavailable"
+    if isinstance(exc, IntakeCommitUnknown):
+        code = "submission_outcome_unknown"
+    elif isinstance(exc, IntakeAuthorityDenied):
+        code = "submission_unavailable"
+    elif isinstance(exc, ArtifactLimitExceededError):
+        code = "submission_archive_limit_exceeded"
+    elif isinstance(exc, ArtifactInputMismatchError):
+        code = "submission_packet_invalid"
+    elif isinstance(exc, SubmissionSourceCapacityConflict) and str(exc) == "source_capacity_exhausted":
+        code = "submission_capacity_exceeded"
+    elif isinstance(exc, IntakeCustodyConflict) and str(exc) in {
+        "submission_idempotency_conflict", "submission_operation_in_progress", "submission_operation_terminal",
+    }:
+        code = str(exc)
+    elif isinstance(exc, TaskSubmissionContextUnavailable):
+        if exc.code == "task_submission_operation_in_progress":
+            code = "submission_operation_in_progress"
+        elif exc.code in {
+            "task_submission_predecessor_changed", "revision_limit_reached", "revision_deadline_expired",
+            "revision_context_blocked", "revision_context_changed", "revision_acknowledgement_required",
+            "revision_acknowledgement_invalid",
+        }:
+            code = exc.code
+        else:
+            code = "submission_unavailable"
+    return SubmissionIntakeFailure(code)
+
+
+class ConfiguredSubmissionCommand:
+    def __init__(self, *, settings, sessions, context):
+        self._settings, self._sessions, self._context = settings, sessions, context
+
+    async def submit(self, metadata, chunks, *, actor_id, identity_link_id, idempotency_key, declared_raw_bytes):
+        if (actor_id, identity_link_id) != (self._context.actor_profile_id, self._context.identity_link_id):
+            raise SubmissionIntakeFailure("submission_unavailable")
+        try:
+            return await self._submit(metadata, chunks, actor_id=actor_id, identity_link_id=identity_link_id,
+                                      idempotency_key=idempotency_key, declared_raw_bytes=declared_raw_bytes)
+        except SubmissionIntakeFailure:
+            raise
+        except (IntakeCommitUnknown, IntakeAuthorityDenied, IntakeCustodyConflict,
+                SubmissionSourceCapacityConflict, TaskSubmissionContextUnavailable,
+                ArtifactStoreError, ExternalServiceAdapterError, SQLAlchemyError, ValidationError,
+                SelectedPreSubmitAuthorityUnavailable, SelectedPreSubmitInfrastructureUnavailable,
+                SelectedPreSubmitRequestConflict, SelectedPreSubmitUnavailable) as exc:
+            failure = _submission_public_failure(exc)
+            if failure.code in {"submission_infrastructure_unavailable", "submission_outcome_unknown"}:
+                logger.exception("Submission command unavailable")
+            raise failure from None
+
+    async def _submit(self, metadata, chunks, **arguments):
+        settings, sessions, context = self._settings, self._sessions, self._context
+        profile = SubmissionExecutionProfile.model_validate(
+            settings.submission_execution_profile,
+            context=source_contracts_context(selected_pre_submit_source_contracts()),
+        )
+        bootstrap = create_artifact_store_bootstrap(
+            settings, activation_guard=artifact_provider_activation_guard(settings, sessions=sessions))
+        try:
+            namespace = artifact_storage_namespace_spec(settings, bootstrap)
+            store = bootstrap.initialize_after_namespace_claim(ArtifactStoreNamespaceClaim(
+                adapter_identity=bootstrap.identity, namespace_identity=bootstrap.namespace_identity,
+                namespace_fingerprint=namespace.namespace_fingerprint,
+            ))
+            admission = ForegroundIntakeAdmission(
+                sessions, tasks=intake_task_custody_port, task_contexts=task_submission_context_port,
+                projects=project_locked_policy_context_port,
+                authorization=lambda session: submission_intake_authority(session, context),
+                events=outbox_append, deliveries=finalized_unknown_deliveries,
+                namespace=namespace, capacity_limits=profile.capacity,
+                maximum_raw_bytes=MAXIMUM_SUBMISSION_ZIP_BYTES,
+                upload_duration=timedelta(seconds=profile.upload_total_seconds),
+                lease_duration=timedelta(seconds=profile.foreground_lease_seconds),
+            )
+
+            async def execute(reservation):
+                async with sessions() as session:
+                    service = SelectedPreSubmitExecutionService(
+                        session=session, coordinator=selected_pre_submit_coordinator(session),
+                        authority=selected_pre_submit_authority(session),
+                        source_reads=SelectedPreSubmitSourceReads(
+                            session=session, sources=submission_intake_pre_source_port(session), store=store,
+                            authority=PreparedPreSubmitMaterializationAuthorization(
+                                session, request_id=context.request_id, correlation_id=context.correlation_id)),
+                        execution=selected_pre_submit_checker_execution(settings=settings),
+                    )
+                    return await service.execute(reservation=reservation)
+
+            command = ForegroundSubmissionCommand(
+                admission=admission, upload=ForegroundSourceUpload(sessions, intake_task_custody_port, store),
+                lease=ForegroundIntakeLease(sessions, intake_task_custody_port,
+                    lease_duration=timedelta(seconds=profile.foreground_lease_seconds),
+                    heartbeat_interval=timedelta(seconds=profile.heartbeat_seconds)),
+                limits=SubmissionForegroundLimits(part_bytes=profile.part_bytes,
+                    idle_timeout_seconds=profile.upload_idle_seconds,
+                    pre_lease_seconds=profile.foreground_lease_seconds,
+                    replay_duration=timedelta(seconds=profile.replay_total_seconds)),
+                runtime_profile=profile.runtime, execute=execute,
+                checkers=selected_pre_submit_coordinator, outbox=outbox_append,
+            )
+            return await command.submit(metadata, chunks, **arguments)
+        finally:
+            bootstrap.close()
+
+
+def get_submission_intake_command(
+    request: Request, context: Annotated[object, Depends(get_artifact_authorization_context)],
+) -> SubmissionIntakeCommand:
+    return ConfiguredSubmissionCommand(
+        settings=request.app.state.settings, sessions=get_session_factory(), context=context)
diff --git a/backend/app/adapters/auth/__init__.py b/backend/app/adapters/auth/__init__.py
index 8939f63cf..6ebbc00a9 100644
--- a/backend/app/adapters/auth/__init__.py
+++ b/backend/app/adapters/auth/__init__.py
@@ -484,6 +484,13 @@ def post_submit_execution_authority(session):
     return PostSubmitExecutionAuthorization(session)
 
 
+def submission_intake_authority(session, context):
+    """Compose current contributor reservation and operation-read authority."""
+    from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization
+
+    return SubmissionIntakeAuthorization(session, context)
+
+
 def selected_pre_submit_authority(session):
     """Compose fixed selected-PRE execute/finalize authority."""
     from app.modules.authorization.pre_submit_authorization import (
diff --git a/backend/app/api/routes/artifact_submissions.py b/backend/app/api/routes/artifact_submissions.py
index 5a1915515..75c588f70 100644
--- a/backend/app/api/routes/artifact_submissions.py
+++ b/backend/app/api/routes/artifact_submissions.py
@@ -1,170 +1,91 @@
-"""Contributor ZIP preparation through ART-owned selected intake and custody."""
-
-from typing import Annotated, Any
+"""One raw-ZIP contributor mutation through ART's foreground command."""
+from typing import Annotated
 from uuid import UUID
 
-from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
+from fastapi import APIRouter, Depends, Request
 from fastapi.responses import JSONResponse
-from pydantic import BaseModel, ConfigDict
-from sqlalchemy.ext.asyncio import AsyncSession
 
-from app.adapters.artifacts import (
-    get_submission_bundle_preparation_actor,
-    get_submission_bundle_preparation_command,
-)
-from app.core.api_controls import StructuredHTTPException, error_response, request_ids
-from app.db.session import get_db_session
-from app.modules.artifacts.api import (
-    SubmissionBundlePreparationCheckFailed,
-    SubmissionBundlePreparationCommand,
-    SubmissionBundlePreparationRejected,
-    SubmissionBundlePreparationInfrastructureUnavailable,
-    SubmissionBundlePreparationRequest,
-    SubmissionBundlePreparationStatus,
-    SubmissionBundlePreparationUnavailable,
-)
+from app.adapters.artifacts import get_submission_intake_command
+from app.api.deps.authorization import get_authorization_actor_identity
+from app.api.submission_intake import SubmissionIntakeHeaders, submission_intake_headers
+from app.core.api_controls import error_response
+from app.modules.artifacts.api.submission_command import SubmissionAcceptedResponse, SubmissionIntakeCommand
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
 from app.modules.authorization.api import ActorIdentityFacts
 
 router = APIRouter(tags=["tasks"])
 
-
-def require_single_preparation_headers(request: Request) -> None:
-    """Reject ambiguous custody selectors before resolving actor or product rows."""
-    for name in ("X-Task-Assignment-Id", "Idempotency-Key"):
-        if len(request.headers.getlist(name)) != 1:
-            raise StructuredHTTPException(
-                status_code=422,
-                detail="Submission preparation headers invalid",
-                error_code="submission_preparation_headers_invalid",
-                error_message="Submission preparation headers invalid",
-            )
-    for name in ("X-Revision-Preparation-Id", "X-Revision-Preparation-Sha256"):
-        if len(request.headers.getlist(name)) > 1:
-            raise StructuredHTTPException(
-                status_code=422,
-                detail="Submission preparation headers invalid",
-                error_code="submission_preparation_headers_invalid",
-                error_message="Submission preparation headers invalid",
-            )
+_HEADER_PARAMETERS = [
+    {"name": name, "in": "header", "required": required, "schema": schema}
+    for name, required, schema in (
+        ("Idempotency-Key", True, {"type": "string", "format": "uuid"}),
+        ("X-Task-Assignment-Id", True, {"type": "string", "format": "uuid"}),
+        ("X-Submission-Summary", False, {"type": "string", "maxLength": 65536}),
+        ("X-Contributor-Attestation", False, {"type": "string", "maxLength": 65536}),
+        ("X-Predecessor-Submission-Id", False, {"type": "string", "format": "uuid"}),
+        ("X-Revision-Preparation-Id", False, {"type": "string", "format": "uuid"}),
+        ("X-Revision-Preparation-Sha256", False, {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}),
+    )
+]
 
 
-class SubmissionBundlePreparationResponse(BaseModel):
-    """Bounded preparation state without provider or scratch coordinates."""
-
-    model_config = ConfigDict(extra="forbid", from_attributes=True)
-
-    put_attempt_id: UUID
-    admission_id: UUID | None
-    submission_bundle_preparation_status: SubmissionBundlePreparationStatus
-    replayed: bool
-    # Bounded intake feedback for the admitted attempt, including nonblocking
-    # findings; the same projection as a blocked preparation's error details.
-    pre_submission_results: list[dict[str, Any]]
+def _failure_status(code: str) -> int:
+    if code == "submission_unavailable":
+        return 404
+    if code == "submission_archive_limit_exceeded":
+        return 413
+    if code == "submission_upload_timeout":
+        return 408
+    if code == "submission_capacity_exceeded":
+        return 429
+    if code in {"submission_packet_invalid", "pre_submission_checker_failed", "revision_acknowledgement_invalid"}:
+        return 422
+    if code in {"submission_infrastructure_unavailable", "submission_outcome_unknown"}:
+        return 503
+    return 409
 
 
 @router.post(
-    "/tasks/{task_id}/submission-bundle-preparations",
-    response_model=SubmissionBundlePreparationResponse,
-    status_code=status.HTTP_202_ACCEPTED,
-    dependencies=[Depends(require_single_preparation_headers)],
+    "/tasks/{task_id}/submissions", response_model=SubmissionAcceptedResponse, status_code=202,
     openapi_extra={
-        "x-workstream-action-id": "artifact.submission_bundle.prepare",
-        "requestBody": {
-            "required": True,
-            "content": {"application/zip": {"schema": {"type": "string", "format": "binary"}}},
-        },
+        "x-workstream-action-id": "submission.create",
+        "parameters": _HEADER_PARAMETERS,
+        "requestBody": {"required": True, "content": {
+            "application/zip": {"schema": {"type": "string", "format": "binary"}},
+        }},
     },
     responses={
         404: {"description": "Task or contributor authority unavailable"},
-        409: {"description": "Preparation context or replay conflicts"},
-        422: {"description": "Invalid ZIP or bounded pre-submission checker feedback"},
-        503: {"description": "Preparation custody or infrastructure unavailable"},
+        408: {"description": "Upload idle or total deadline expired"},
+        409: {"description": "Operation, idempotency or governed revision conflict"},
+        413: {"description": "Raw ZIP exceeds the permitted limit"},
+        415: {"description": "Unsupported media type or content encoding"},
+        422: {"description": "Invalid packet or bounded pre-submission QC feedback"},
+        429: {"description": "Submission capacity exhausted"},
+        503: {"description": "Infrastructure unavailable or acceptance outcome unknown"},
     },
 )
-async def prepare_submission_bundle(
-    task_id: str,
+async def submit_source(
+    task_id: UUID,
     request: Request,
-    actor: Annotated[ActorIdentityFacts, Depends(get_submission_bundle_preparation_actor)],
-    command: Annotated[
-        SubmissionBundlePreparationCommand,
-        Depends(get_submission_bundle_preparation_command),
-    ],
-    session: Annotated[AsyncSession, Depends(get_db_session)],
-    assignment_id: Annotated[str, Header(alias="X-Task-Assignment-Id")],
-    idempotency_key: Annotated[str, Header(alias="Idempotency-Key")],
-    summary: Annotated[str | None, Header(alias="X-Submission-Summary")] = None,
-    contributor_attestation: Annotated[
-        str | None, Header(alias="X-Contributor-Attestation")
-    ] = None,
-    predecessor_submission_id: Annotated[
-        str | None, Header(alias="X-Predecessor-Submission-Id")
-    ] = None,
-    revision_preparation_id: Annotated[
-        str | None, Header(alias="X-Revision-Preparation-Id")
-    ] = None,
-    revision_preparation_sha256: Annotated[
-        str | None, Header(alias="X-Revision-Preparation-Sha256")
-    ] = None,
-) -> SubmissionBundlePreparationResponse | JSONResponse:
-    """Run continuous ZIP preparation under fresh contributor authority."""
-    try:
-        identifiers = (
-            UUID(task_id),
-            UUID(assignment_id),
-            UUID(idempotency_key),
-            UUID(predecessor_submission_id) if predecessor_submission_id else None,
-        )
-    except ValueError as exc:
-        raise HTTPException(status_code=404, detail="Task not found") from exc
+    headers: Annotated[SubmissionIntakeHeaders, Depends(submission_intake_headers)],
+    actor: Annotated[ActorIdentityFacts, Depends(get_authorization_actor_identity)],
+    command: Annotated[SubmissionIntakeCommand, Depends(get_submission_intake_command)],
+) -> SubmissionAcceptedResponse | JSONResponse:
+    """Acknowledge only committed acceptance, with no fabricated T5 identifiers."""
     try:
-        # Actor resolution may have opened a read root; ART owns its preparation roots.
-        await session.rollback()
-        request_id, correlation_id = (UUID(value) for value in request_ids(request))
-        result = await command.prepare(
-            SubmissionBundlePreparationRequest(
-                actor=actor,
-                request_id=request_id,
-                correlation_id=correlation_id,
-                task_id=identifiers[0],
-                assignment_id=identifiers[1],
-                predecessor_submission_id=identifiers[3],
-                idempotency_key=identifiers[2],
-                summary=summary or "",
-                contributor_attestation=contributor_attestation or "",
-                media_type=request.headers.get("content-type", ""),
-                byte_source=request.stream(),
-                revision_preparation_id=revision_preparation_id,
-                revision_preparation_sha256=revision_preparation_sha256,
-            )
+        receipt = await command.submit(
+            headers.metadata, request.stream(), actor_id=actor.actor_profile_id,
+            identity_link_id=actor.identity_link_id, idempotency_key=headers.idempotency_key,
+            declared_raw_bytes=headers.declared_raw_bytes,
         )
-    except SubmissionBundlePreparationCheckFailed as exc:
+    except SubmissionIntakeFailure as exc:
+        details = None
+        if exc.code == "pre_submission_checker_failed":
+            details = {"status": "failed", "eligible_to_submit": False, "results": exc.pre_submission_results or []}
         return error_response(
-            request,
-            status_code=422,
-            code="pre_submission_checker_failed",
-            message="Pre-submission checks failed",
-            details={
-                "status": "failed",
-                "eligible_to_submit": exc.facts.eligible,
-                "results": exc.public_results(),
-            },
+            request, status_code=_failure_status(exc.code), code=exc.code,
+            message="Submission unavailable" if exc.code == "submission_unavailable" else exc.code,
+            details=details, retryable=exc.code in {"submission_capacity_exceeded", "submission_infrastructure_unavailable", "submission_outcome_unknown"},
         )
-    except SubmissionBundlePreparationInfrastructureUnavailable as exc:
-        raise HTTPException(status_code=503, detail=str(exc)) from exc
-    except SubmissionBundlePreparationUnavailable as exc:
-        raise HTTPException(status_code=404, detail="Task not found") from exc
-    except SubmissionBundlePreparationRejected as exc:
-        code = str(exc)
-        if code in {"revision_limit_reached", "revision_deadline_expired", "revision_context_blocked", "revision_context_changed"}:
-            raise StructuredHTTPException(
-                status_code=409, detail=code, error_code=code, error_message=code,
-            ) from exc
-        if code in {"submission_bundle_preparation_context_changed",
-                    "submission_bundle_preparation_request_conflict"}:
-            raise HTTPException(status_code=409, detail=code) from exc
-        if code in {"revision_acknowledgement_required", "revision_acknowledgement_invalid"}:
-            raise StructuredHTTPException(
-                status_code=422, detail=code, error_code=code, error_message=code,
-            ) from exc
-        raise HTTPException(status_code=422, detail=code) from exc
-    return SubmissionBundlePreparationResponse.model_validate(result, from_attributes=True)
+    return SubmissionAcceptedResponse.model_validate(receipt)
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 10f5e4529..4a37bba10 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -282,6 +282,9 @@ class Settings(BaseSettings):
         le=86_400,
     )
     artifact_intake_service_socket: Path | None = None
+    # Required source-intake envelopes and runtime/capacity profile. No old
+    # preparation timers or unmeasured deployment defaults are inherited.
+    submission_execution_profile: dict[str, object] | None = None
     artifact_intake_image_digest: str | None = None
     artifact_intake_config_digest: str | None = None
     external_checker_service_socket: Path | None = None
diff --git a/backend/app/modules/artifacts/api/submission_command.py b/backend/app/modules/artifacts/api/submission_command.py
new file mode 100644
index 000000000..1b26c14a3
--- /dev/null
+++ b/backend/app/modules/artifacts/api/submission_command.py
@@ -0,0 +1,67 @@
+"""Public single-request submission command and explicit deployment contract."""
+from collections.abc import AsyncIterator
+from typing import Annotated, Literal, Protocol, Self
+from uuid import UUID
+
+from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator
+
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
+from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitRuntimeProfile
+
+Seconds = Annotated[float, Field(gt=0, allow_inf_nan=False)]
+
+
+class SubmissionExecutionProfile(BaseModel):
+    """Required finite values; validity does not establish measured qualification."""
+
+    model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
+    capacity: SubmissionSourceCapacityLimits
+    runtime: SelectedPreSubmitRuntimeProfile
+    upload_total_seconds: Seconds
+    upload_idle_seconds: Seconds
+    foreground_lease_seconds: Seconds
+    heartbeat_seconds: Seconds
+    replay_total_seconds: Seconds
+    part_bytes: int = Field(ge=5 * 1024**2, le=16 * 1024**2)
+
+    @model_validator(mode="after")
+    def bounded_envelopes(self) -> Self:
+        if not self.heartbeat_seconds < self.foreground_lease_seconds <= self.upload_total_seconds:
+            raise ValueError("submission foreground lease envelope is invalid")
+        if self.foreground_lease_seconds * 1000 > self.runtime.aggregate_deadline_ms:
+            raise ValueError("submission foreground lease exceeds PRE deadline")
+        if self.upload_idle_seconds > min(self.upload_total_seconds, self.replay_total_seconds):
+            raise ValueError("submission idle timeout exceeds request envelope")
+        # Validate representability before admission or any provider activity.
+        from datetime import UTC, datetime, timedelta
+        for value in (self.upload_total_seconds, self.replay_total_seconds):
+            try:
+                datetime.now(UTC) + timedelta(seconds=value)
+            except OverflowError:
+                raise ValueError("submission request envelope is not representable") from None
+        return self
+
+
+class SubmissionAcceptedResponse(BaseModel):
+    """Stable T4 snapshot; Submission/evaluation IDs do not exist until T5."""
+
+    model_config = ConfigDict(extra="forbid")
+    operation_id: UUID
+    task_id: UUID
+    assignment_id: UUID
+    status: Literal["accepted"]
+    accepted_at: AwareDatetime
+    task_status_at_acceptance: Literal["evaluation_pending"]
+    processing_stage_at_acceptance: Literal["finalization_pending"]
+    replayed: bool
+    pre_submission_results: list[dict[str, object]]
+
+
+class SubmissionIntakeCommand(Protocol):
+    async def submit(
+        self, metadata: SubmissionIntakeMetadata, chunks: AsyncIterator[bytes], *,
+        actor_id: UUID, identity_link_id: UUID, idempotency_key: UUID,
+        declared_raw_bytes: int | None,
+    ) -> dict:
+        """Return committed acceptance or a bounded SubmissionIntakeFailure."""
+        ...
diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py
index 35235b0a8..b62d409f3 100644
--- a/backend/app/modules/artifacts/intake/progress.py
+++ b/backend/app/modules/artifacts/intake/progress.py
@@ -2,6 +2,8 @@
 
 from uuid import UUID
 
+from app.core.hashing import canonical_json_hash
+
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
 from app.modules.artifacts.intake.acceptance import finalization_event
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict
@@ -10,6 +12,10 @@
     FINALIZATION_RECOVERY_EVENT, FINALIZATION_RECOVERY_SOURCES, SubmissionRecoveryPayload,
 )
 from app.modules.outbox.api import OutboxAppendPort, OutboxIdempotencyConflict, DeliveryUnavailable
+from app.modules.checkers.api.delivery_reconciliation import (
+    POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT, POST_SUBMIT_DELIVERY_SUPPORTED_EVENTS,
+    PostSubmitDeliveryChildPayload, post_submit_reconciliation_event,
+)
 
 
 async def finalization_progress(row, events: OutboxAppendPort, deliveries) -> SubmissionFinalizationProgress | None:
@@ -51,3 +57,40 @@ async def finalization_progress(row, events: OutboxAppendPort, deliveries) -> Su
         next_retry_at=delivery.next_attempt_at if not finalized else None,
         attempt_count=attempt_count, stalled_reason=delivery.error_code if stalled else None,
     )
+
+
+async def evaluation_delivery_progress(event_id, event, evaluation, events, deliveries):
+    """Observe one exact current evaluation delivery, including its recovery child."""
+    unavailable = "submission_evaluation_progress_unavailable"
+    try:
+        observation = await events.observe_delivery(event_id, event)
+        if observation.state != "dead_letter" or observation.error_code != "INVOKE_OUTCOME_UNKNOWN":
+            return observation
+        retained = await deliveries.read_finalized_unknown(
+            project_id=event.project_id, event_id=event_id,
+            event_types=POST_SUBMIT_DELIVERY_SUPPORTED_EVENTS,
+            child_event_type=POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT, lock=False,
+        )
+        if retained is None:
+            raise IntakeCustodyConflict(unavailable)
+        if retained.child is None:
+            return observation
+        payload = PostSubmitDeliveryChildPayload.model_validate_json(retained.child.payload_json)
+        claim = retained.envelope.claim
+        request, reservation = evaluation.current.request, evaluation.current.reservation
+        if (payload.original_event_id != event_id or claim.event_id != event_id
+                or claim.project_id != event.project_id
+                or payload.original_claim_generation != claim.claim_generation
+                or payload.original_payload_digest != claim.payload_digest
+                or claim.payload_digest != canonical_json_hash(event.payload)
+                or payload.original_event_type != event.event_type
+                or payload.original_event_version != event.event_version
+                or payload.evaluation_request_id != request.evaluation_request_id
+                or payload.checker_run_id != reservation.attempt_id
+                or payload.evaluation_generation != reservation.evaluation_generation):
+            raise IntakeCustodyConflict(unavailable)
+        return await events.observe_delivery(
+            retained.child.event_id, post_submit_reconciliation_event(event.project_id, payload),
+        )
+    except (OutboxIdempotencyConflict, DeliveryUnavailable, ValueError) as exc:
+        raise IntakeCustodyConflict(unavailable) from exc
diff --git a/backend/app/modules/checkers/api/delivery_reconciliation.py b/backend/app/modules/checkers/api/delivery_reconciliation.py
index 73198a538..cae8bf89b 100644
--- a/backend/app/modules/checkers/api/delivery_reconciliation.py
+++ b/backend/app/modules/checkers/api/delivery_reconciliation.py
@@ -9,6 +9,7 @@
 from pydantic import AwareDatetime, AfterValidator, BaseModel, ConfigDict, Field, model_validator
 
 from app.core.hashing import canonical_json_hash
+from app.modules.outbox.api import OutboxAppendInput
 from app.modules.checkers.api.evaluation_contract import PostSubmissionExecutionRequest
 
 
@@ -364,3 +365,17 @@ async def validate_replay(
     def close(self, handle: object) -> None: ...
 
     async def restage_denial(self, error: PostSubmitDeliveryAuthorityDenied) -> bool: ...
+
+
+def post_submit_reconciliation_event(
+    project_id: UUID, payload: PostSubmitDeliveryChildPayload,
+) -> OutboxAppendInput:
+    """Exact child envelope shared by publication and read-only observation."""
+    return OutboxAppendInput(
+        event_type=POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT, event_version=1,
+        aggregate_type="outbox_delivery", aggregate_id=payload.original_event_id,
+        project_id=project_id, correlation_id=str(payload.reconciliation_request_id),
+        causation_event_id=payload.original_event_id,
+        idempotency_key="post-submit-reconcile:" + str(payload.original_event_id),
+        payload=payload.model_dump(mode="json"),
+    )
diff --git a/backend/app/modules/checkers/api/execution.py b/backend/app/modules/checkers/api/execution.py
index ae01cc3b3..e79cb26ce 100644
--- a/backend/app/modules/checkers/api/execution.py
+++ b/backend/app/modules/checkers/api/execution.py
@@ -10,6 +10,7 @@
 from pydantic import AfterValidator, AwareDatetime, Field, model_validator
 
 from app.core.hashing import canonical_json_hash
+from app.modules.outbox.api import OutboxAppendInput
 
 from app.modules.checkers.api.evaluation_contract import (
     PostSubmissionExecutionRequest,
@@ -339,6 +340,17 @@ class ReservedEvaluation(CheckerValue):
     reservation: EvaluationReservation
 
 
+class EvaluationProgress(CheckerValue):
+    """Current owner evidence for one retained Submission, not a public outcome."""
+
+    current: ReservedEvaluation
+    status: Literal["queued", "running", "completed", "infrastructure_failed"]
+    live_worker_lease: bool
+    retry_event_id: ResourceId | None
+    completion_event_id: ResourceId | None
+    delivery_event: OutboxAppendInput | None
+
+
 class ExecutionLease(CheckerValue):
     """Database-timed generation granting temporary use of one reserved attempt."""
 
@@ -574,6 +586,13 @@ async def read_reserved_evaluation(
         """Read scoped retained custody without reserving or advancing a fence."""
         ...
 
+    async def read_current_progress(
+        self, *, project_id: ResourceId, task_id: ResourceId,
+        submission_id: ResourceId, original_request_id: ResourceId,
+    ) -> EvaluationProgress:
+        """Observe exact current attempt under caller-owned TASK-first custody."""
+        ...
+
     async def read_retry_delivery(
         self, *, project_id: ResourceId, submission_id: ResourceId,
         event_id: ResourceId,
diff --git a/backend/app/modules/checkers/delivery_reconciliation.py b/backend/app/modules/checkers/delivery_reconciliation.py
index 611b0863d..7a0752369 100644
--- a/backend/app/modules/checkers/delivery_reconciliation.py
+++ b/backend/app/modules/checkers/delivery_reconciliation.py
@@ -30,6 +30,7 @@
     POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT,
     POST_SUBMIT_DELIVERY_SUPPORTED_EVENTS,
     post_submit_delivery_request_digest,
+    post_submit_reconciliation_event,
 )
 from app.modules.checkers.api.execution import (
     COMPLETION_EVENT,
@@ -43,7 +44,6 @@
     DeliveryUnavailable,
     FinalizedUnknownDelivery,
     FinalizedUnknownDeliveryPort,
-    OutboxAppendInput,
     OutboxAppendPort,
     OutboxIdempotencyConflict,
     OutboxInputError,
@@ -322,17 +322,7 @@ async def reconcile(
             )
             try:
                 appended = await self._events.append(
-                    OutboxAppendInput(
-                        event_type=RECONCILIATION_EVENT,
-                        event_version=1,
-                        aggregate_type="outbox_delivery",
-                        aggregate_id=source.event_id,
-                        project_id=source.project_id,
-                        correlation_id=str(command.request_key),
-                        causation_event_id=source.event_id,
-                        idempotency_key="post-submit-reconcile:" + str(source.event_id),
-                        payload=payload.model_dump(mode="json"),
-                    )
+                    post_submit_reconciliation_event(source.project_id, payload)
                 )
             except OutboxIdempotencyConflict as exc:
                 raise PostSubmitDeliveryConflict(
diff --git a/backend/app/modules/checkers/execution.py b/backend/app/modules/checkers/execution.py
index bafd4b2de..92ff62ff0 100644
--- a/backend/app/modules/checkers/execution.py
+++ b/backend/app/modules/checkers/execution.py
@@ -11,11 +11,9 @@
 
 from app.core.identifiers import new_record_id
 from app.modules.checkers.api.execution import (
-    COMPLETION_EVENT,
     ExecutionAuthorityPort,
     FinalizationAuthorityPort,
     CheckerExecutionUnavailable,
-    EvaluationCompletion,
     ExecuteEvidence,
     ExecuteFacts,
     ExecutionLease,
@@ -39,7 +37,6 @@
     selected_post_submit_execution_budget_ms,
 )
 from app.modules.checkers.api.selected_post_submit import (
-    SelectedPostSubmitCurrentResultReference,
     SelectedPostSubmissionEvaluationRequest,
     SelectedPostSubmitInfrastructureUnavailable,
     make_selected_post_submit_result,
@@ -55,14 +52,13 @@
     reservation,
     stored_result,
 )
-from app.modules.checkers.execution_results import classify_result
+from app.modules.checkers.execution_results import classify_result, evaluation_completion_event
 from app.modules.checkers.api.materialization import (
     PostSubmissionMaterializationPort,
     PostSubmissionMaterializationFailure,
 )
 from app.modules.outbox.api import OutboxAppendPort
 from app.modules.checkers.api.execution import ReviewModePort
-from app.modules.outbox.api import OutboxAppendInput
 
 def _lease(run):
     """Recover the exact persisted lease, including its database expiry."""
@@ -361,35 +357,11 @@ async def finalize(self, facts: FinalizeFacts) -> PostSubmissionExecutionResult:
                 completed_at = await repo.now()
                 await repo.write_members(run, result)
                 if result.outcome == "completed":
-                    reference = SelectedPostSubmitCurrentResultReference(
-                        **result.model_dump(
-                            include=set(SelectedPostSubmitCurrentResultReference.model_fields)
-                            - {"schema_version"}
-                        )
-                    )
-                    reference.validate_result(result)
-                    event = EvaluationCompletion(
-                        project_id=request.project_id,
-                        task_id=request.task_id,
-                        submission_id=request.submission_id,
-                        reference=reference,
-                        routing_recommendation=classification.routing,
-                        output_binding_ids=(),
+                    appended = await self._outbox(session).append(evaluation_completion_event(
+                        request, result, attempt_id=UUID(run.id),
                         execute_evidence_id=UUID(run.execute_evidence_id),
-                        finalize_evidence_id=evidence_id,
-                    )
-                    appended = await self._outbox(session).append(
-                        OutboxAppendInput(
-                            event_type=COMPLETION_EVENT,
-                            event_version=1,
-                            aggregate_type="checker_run",
-                            aggregate_id=UUID(run.id),
-                            project_id=request.project_id,
-                            correlation_id=str(request.evaluation_request_id),
-                            idempotency_key="checker-completed:" + run.id,
-                            payload=event.model_dump(mode="json"),
-                        )
-                    )
+                        finalize_evidence_id=evidence_id, routing_recommendation=classification.routing,
+                    ))
                     run.completion_event_id = appended.event_id
                 run.result_json = canonical_checker_bytes(
                     result, exclude={"result_digest"}
diff --git a/backend/app/modules/checkers/execution_coordination.py b/backend/app/modules/checkers/execution_coordination.py
index 70355d108..e1d386a24 100644
--- a/backend/app/modules/checkers/execution_coordination.py
+++ b/backend/app/modules/checkers/execution_coordination.py
@@ -3,7 +3,7 @@
 import json
 from uuid import UUID
 
-from sqlalchemy import select, text
+from sqlalchemy import select, text, func
 from sqlalchemy.exc import DBAPIError, IntegrityError
 from sqlalchemy.ext.asyncio import AsyncSession
 
@@ -15,6 +15,7 @@
     CheckerRetrySourceUnavailable,
     CompletedEvaluation,
     EvaluationReservation,
+    EvaluationProgress,
     ReservedEvaluation,
     EvaluationCompletion,
     EvaluationTaskGuard,
@@ -39,7 +40,9 @@
     stored_result,
     stored_request,
 )
-from app.modules.checkers.models import CheckerRun, CheckerSubmissionFence
+from app.modules.outbox.api import OutboxAppendInput
+from app.modules.checkers.execution_results import evaluation_completion_event
+from app.modules.checkers.models import CheckerRun, CheckerSubmissionFence, CheckerRetryReceipt
 
 
 class EvaluationCoordinator:
@@ -181,6 +184,90 @@ async def read_reserved_evaluation(
             raise CheckerExecutionUnavailable("checker_reservation_unavailable")
         return ReservedEvaluation(request=request, reservation=reservation(run))
 
+    async def read_current_progress(
+        self, *, project_id: UUID, task_id: UUID, submission_id: UUID,
+        original_request_id: UUID,
+    ) -> EvaluationProgress:
+        """Read the exact Submission fence; never follow the task's newest attempt."""
+        original = await self.read_reserved_evaluation(
+            project_id=project_id, task_id=task_id, submission_id=submission_id,
+            request_id=original_request_id,
+        )
+        unavailable = "checker_progress_unavailable"
+        if original.reservation.evaluation_generation != 1:
+            raise CheckerExecutionUnavailable(unavailable)
+        run = await self._session.scalar(select(CheckerRun).join(
+            CheckerSubmissionFence, CheckerSubmissionFence.current_run_id == CheckerRun.id,
+        ).where(
+            CheckerSubmissionFence.submission_id == str(submission_id),
+            CheckerRun.submission_id == str(submission_id),
+            CheckerRun.project_id == str(project_id), CheckerRun.task_id == str(task_id),
+            CheckerRun.phase == "post_submission",
+        ).with_for_update(read=True, of=(CheckerSubmissionFence, CheckerRun))
+          .execution_options(populate_existing=True))
+        if run is None:
+            raise CheckerExecutionUnavailable(unavailable)
+        current = await self.read_reserved_evaluation(
+            project_id=project_id, task_id=task_id, submission_id=submission_id,
+            request_id=UUID(run.evaluation_request_id),
+        )
+        if (current.request.assignment_id != original.request.assignment_id
+                or current.request.submission_version != original.request.submission_version):
+            raise CheckerExecutionUnavailable(unavailable)
+        retry_event_id = None
+        delivery_event = None
+        if current.reservation.attempt_id == original.reservation.attempt_id:
+            if run.supersedes_checker_run_id is not None:
+                raise CheckerExecutionUnavailable(unavailable)
+        else:
+            receipt = await self._session.scalar(select(CheckerRetryReceipt).where(
+                CheckerRetryReceipt.successor_run_id == run.id,
+                CheckerRetryReceipt.project_id == str(project_id),
+                CheckerRetryReceipt.task_id == str(task_id),
+                CheckerRetryReceipt.submission_id == str(submission_id),
+                CheckerRetryReceipt.source_run_id == run.supersedes_checker_run_id,
+                CheckerRetryReceipt.successor_generation == run.evaluation_generation,
+            ))
+            if receipt is None or run.evaluation_generation <= 1:
+                raise CheckerExecutionUnavailable(unavailable)
+            retained = await self.read_retry_delivery(
+                project_id=project_id, submission_id=submission_id, event_id=receipt.event_id,
+            )
+            if retained is None or retained.request != current.request:
+                raise CheckerExecutionUnavailable(unavailable)
+            retry_event_id = receipt.event_id
+            expected = retained.expected_event
+            delivery_event = OutboxAppendInput(
+                **expected.model_dump(exclude={"payload_json", "payload_digest"}),
+                project_id=project_id, payload=json.loads(expected.payload_json),
+            )
+        terminal = run.status in {"completed", "infrastructure_failed"}
+        if terminal:
+            result = stored_result(run)
+            if (result.outcome != run.status or run.finalize_evidence_id is None
+                    or (run.status == "completed") != (run.completion_event_id is not None)):
+                raise CheckerExecutionUnavailable(unavailable)
+            if run.status == "completed":
+                if run.execute_evidence_id is None:
+                    raise CheckerExecutionUnavailable(unavailable)
+                delivery_event = evaluation_completion_event(
+                    current.request, result, attempt_id=UUID(run.id),
+                    execute_evidence_id=UUID(run.execute_evidence_id),
+                    finalize_evidence_id=UUID(run.finalize_evidence_id),
+                    routing_recommendation=run.routing_recommendation,
+                )
+        elif run.completion_event_id is not None:
+            raise CheckerExecutionUnavailable(unavailable)
+        now = await self._session.scalar(select(func.clock_timestamp()))
+        live = (run.status == "running" and run.worker_lease_id is not None
+                and run.worker_lease_generation > 0 and run.worker_lease_expires_at is not None
+                and run.worker_lease_expires_at > now)
+        return EvaluationProgress(
+            current=current, status=run.status, live_worker_lease=live,
+            retry_event_id=retry_event_id, completion_event_id=run.completion_event_id,
+            delivery_event=delivery_event,
+        )
+
     async def read_retry_delivery(
         self, *, project_id: UUID, submission_id: UUID, event_id: UUID,
     ) -> CheckerRetryDelivery | None:
diff --git a/backend/app/modules/checkers/execution_results.py b/backend/app/modules/checkers/execution_results.py
index 061ae105e..8552eef37 100644
--- a/backend/app/modules/checkers/execution_results.py
+++ b/backend/app/modules/checkers/execution_results.py
@@ -1,6 +1,11 @@
 """One complete member classification and closed history presentation."""
 
 from dataclasses import dataclass
+from uuid import UUID
+
+from app.modules.checkers.api.execution import COMPLETION_EVENT, EvaluationCompletion
+from app.modules.checkers.api.selected_post_submit import SelectedPostSubmitCurrentResultReference
+from app.modules.outbox.api import OutboxAppendInput
 
 from app.modules.checkers.api.evaluation_contract import (
     PostSubmissionExecutionRequest,
@@ -54,3 +59,25 @@ def classify_result(
         "Make the listed files readable by the project checks, then resubmit.",
     ),
 }
+
+
+def evaluation_completion_event(request, result, *, attempt_id: UUID,
+                                execute_evidence_id: UUID, finalize_evidence_id: UUID,
+                                routing_recommendation: str) -> OutboxAppendInput:
+    """One exact completion envelope shared by publication and observation."""
+    result.validate_request(request)
+    reference = SelectedPostSubmitCurrentResultReference(
+        **result.model_dump(include=set(SelectedPostSubmitCurrentResultReference.model_fields) - {"schema_version"})
+    )
+    reference.validate_result(result)
+    event = EvaluationCompletion(
+        project_id=request.project_id, task_id=request.task_id, submission_id=request.submission_id,
+        reference=reference, routing_recommendation=routing_recommendation, output_binding_ids=(),
+        execute_evidence_id=execute_evidence_id, finalize_evidence_id=finalize_evidence_id,
+    )
+    return OutboxAppendInput(
+        event_type=COMPLETION_EVENT, event_version=1, aggregate_type="checker_run",
+        aggregate_id=attempt_id, project_id=request.project_id,
+        correlation_id=str(request.evaluation_request_id),
+        idempotency_key="checker-completed:" + str(attempt_id), payload=event.model_dump(mode="json"),
+    )
diff --git a/backend/app/modules/tasks/api/submission_history.py b/backend/app/modules/tasks/api/submission_history.py
index 0668cc0d7..d858098a9 100644
--- a/backend/app/modules/tasks/api/submission_history.py
+++ b/backend/app/modules/tasks/api/submission_history.py
@@ -7,6 +7,8 @@
 from typing import Literal, Protocol
 from uuid import UUID
 
+from app.modules.outbox.api import OutboxAppendInput
+
 HistoryKind = Literal["task_submission_history", "submission_history", "checker_history"]
 
 
@@ -135,6 +137,22 @@ class ManagementSubmissionHistoryPage(BaseModel):
     next_cursor: str | None
 
 
+class SubmissionOperationAssociationUnavailable(RuntimeError):
+    """The operation's exact finalized TASK association cannot be proven."""
+
+
+@dataclass(frozen=True, slots=True)
+class SubmissionOperationOutcome:
+    """One retained attempt and original dispatch, never current-task status."""
+
+    submission_id: UUID
+    submission_version: int
+    status: SubmissionAttemptStatus
+    evaluation_request_id: UUID
+    evaluation_event_id: UUID
+    evaluation_event: OutboxAppendInput
+
+
 class SubmissionHistoryReadPort(Protocol):
     """TASK selects ownership before projection; the caller owns the transaction."""
 
@@ -153,3 +171,11 @@ async def read(
         submission_id: UUID | None = None, limit: int = 25,
         after: tuple[int, UUID] | None = None,
     ) -> tuple[list[ContributorSubmissionHistory | ManagementSubmissionHistory], bool]: ...
+
+
+    async def read_operation_outcome(
+        self, *, project_id: UUID, task_id: UUID, assignment_id: UUID,
+        contributor_id: UUID, submission_id: UUID, admission_id: UUID,
+    ) -> SubmissionOperationOutcome:
+        """Read exact finalized association after caller-owned authorization."""
+        ...
diff --git a/backend/app/modules/tasks/router.py b/backend/app/modules/tasks/router.py
index d497144ac..adb5480b7 100644
--- a/backend/app/modules/tasks/router.py
+++ b/backend/app/modules/tasks/router.py
@@ -9,7 +9,6 @@
 from app.api.deps.authorization import (
     get_task_commands, get_task_import_batch_commands,
     enforce_human_authorization_read,
-    get_authorization_actor_identity, get_submission_creation_command,
 )
 from app.modules.tasks.queue_router import router as queue_router
 from app.modules.tasks.task_batch_transition_router import router as batch_transition_router
@@ -19,13 +18,6 @@
 from fastapi import APIRouter, Depends, HTTPException, Query, Request
 from fastapi.responses import JSONResponse
 from fastapi.responses import StreamingResponse
-from sqlalchemy.exc import SQLAlchemyError
-from app.modules.authorization.api import ActorIdentityFacts
-from app.modules.tasks.api import (
-    SubmissionCreationCommand, SubmissionCreationRequest,
-    SubmissionCreationAdmissionError, SubmissionCreationUnavailable, TaskAuthorityDenied,
-    TaskSubmissionContextUnavailable,
-)
 from app.modules.tasks.api.guide_documents import TaskGuideUnavailable, VerifiedTaskGuideRead
 
 from app.core.api_controls import StructuredHTTPException, error_response, parse_idempotency_key
@@ -38,7 +30,6 @@
     TaskTransitionRequest,
     TaskRevisionRepairRequest,
     TaskClaimResponse,
-    AdmissionBackedSubmissionCreate, AdmissionBackedSubmissionResponse,
 )
 from app.modules.tasks.api.revision import ContributorRevisionContext
 from app.modules.tasks.service import TaskProjectNotReady, TaskServiceError, TaskNotFound
@@ -553,85 +544,6 @@ async def get_management_task_work_context(
         raise task_http_error(exc) from exc
 
 
-@router.post(
-    "/tasks/{task_id}/submissions",
-    response_model=AdmissionBackedSubmissionResponse,
-    status_code=201,
-    openapi_extra={"x-workstream-action-id": "submission.create"},
-    responses={
-        404: {"description": "Submission or contributor authority unavailable"},
-        409: {"description": "Admission, predecessor or packet conflicts"},
-        422: {"description": "Invalid submission packet"},
-        503: {"description": "Submission infrastructure unavailable"},
-    },
-)
-async def create_admission_backed_submission(
-    task_id: UUID,
-    payload: AdmissionBackedSubmissionCreate,
-    actor: Annotated[ActorIdentityFacts, Depends(get_authorization_actor_identity)],
-    command: Annotated[SubmissionCreationCommand, Depends(get_submission_creation_command)],
-) -> AdmissionBackedSubmissionResponse:
-    """Consume one verified admission through the existing atomic TASK writer."""
-    try:
-        created = await command.create(SubmissionCreationRequest(
-            task_id=task_id,
-            assignment_id=payload.assignment_id,
-            contributor_id=actor.actor_profile_id,
-            predecessor_submission_id=payload.predecessor_submission_id,
-            admission_id=payload.admission_id,
-            summary=payload.summary if payload.summary is not None else "",
-            contributor_attestation=(
-                payload.contributor_attestation
-                if payload.contributor_attestation is not None else ""
-            ),
-        ))
-    except TaskSubmissionContextUnavailable as exc:
-        if exc.code in {"task_submission_predecessor_changed", "revision_limit_reached", "revision_deadline_expired", "revision_context_blocked", "revision_context_changed"}:
-            raise StructuredHTTPException(
-                status_code=409, detail=exc.code,
-                error_code=exc.code, error_message=exc.code,
-            ) from exc
-        raise StructuredHTTPException(
-            status_code=404, detail="Submission unavailable",
-            error_code="submission_unavailable", error_message="Submission unavailable",
-        ) from exc
-    except SubmissionCreationAdmissionError as exc:
-        status_code = 404 if exc.code == "submission_bundle_admission_unavailable" else 409
-        raise StructuredHTTPException(
-            status_code=status_code, detail=exc.code,
-            error_code=exc.code, error_message=exc.code,
-        ) from exc
-    except SubmissionCreationUnavailable as exc:
-        raise StructuredHTTPException(
-            status_code=404, detail="Submission unavailable",
-            error_code="submission_unavailable", error_message="Submission unavailable",
-        ) from exc
-    except TaskAuthorityDenied as exc:
-        raise StructuredHTTPException(
-            status_code=404, detail="Submission unavailable",
-            error_code="submission_unavailable", error_message="Submission unavailable",
-        ) from exc
-    except ValueError as exc:
-        raise StructuredHTTPException(
-            status_code=422, detail="Submission packet invalid",
-            error_code="submission_packet_invalid", error_message="Submission packet invalid",
-        ) from exc
-    except TaskServiceError as exc:
-        raise task_http_error(exc) from exc
-    except SQLAlchemyError as exc:
-        raise StructuredHTTPException(
-            status_code=503, detail="Submission unavailable",
-            error_code="submission_infrastructure_unavailable",
-            error_message="Submission unavailable", retryable=True,
-        ) from exc
-    return AdmissionBackedSubmissionResponse(
-        submission_id=created.submission_id,
-        submission_version=created.submission_version,
-        admission_id=created.admission_id,
-        evaluation_request_id=created.evaluation_request_id,
-    )
-
-
 @router.get("/tasks/{task_id}/submissions", response_model=ContributorSubmissionHistoryPage,
     dependencies=[Depends(enforce_human_authorization_read)],
     openapi_extra={"x-workstream-action-id": "task.submission.list"},
diff --git a/backend/app/modules/tasks/submission_history.py b/backend/app/modules/tasks/submission_history.py
index 8d7f664eb..1ec3803fd 100644
--- a/backend/app/modules/tasks/submission_history.py
+++ b/backend/app/modules/tasks/submission_history.py
@@ -7,8 +7,10 @@
 
 from app.modules.tasks.api.submission_history import (
     SubmissionFindingCounts, SubmissionFindingCountsPort, SubmissionHistoryTarget,
+    SubmissionOperationAssociationUnavailable, SubmissionOperationOutcome,
 )
-from app.modules.tasks.models import EvidenceItem, Submission, WorkstreamTask
+from app.modules.tasks.submission_dispatch import evaluation_request_event
+from app.modules.tasks.models import EvidenceItem, Submission, SubmissionDispatch, WorkstreamTask
 from app.modules.tasks.api.submission_history import ContributorSubmissionHistory, ManagementSubmissionHistory
 
 
@@ -97,3 +99,38 @@ async def read(self, target, *, manager: bool, submission_id=None, limit=25, aft
             for row in page
         ]
         return values, len(rows) > limit
+
+
+    async def read_operation_outcome(
+        self, *, project_id: UUID, task_id: UUID, assignment_id: UUID,
+        contributor_id: UUID, submission_id: UUID, admission_id: UUID,
+    ) -> SubmissionOperationOutcome:
+        """Prove exact accepted association; never substitute a newer attempt."""
+        if not self._session.in_transaction() or self._session.in_nested_transaction():
+            raise SubmissionOperationAssociationUnavailable("submission_operation_association_unavailable")
+        row = (await self._session.execute(select(
+            Submission.id, Submission.version, Submission.attempt_status,
+            SubmissionDispatch,
+        ).join(SubmissionDispatch, SubmissionDispatch.submission_id == Submission.id).join(
+            WorkstreamTask, WorkstreamTask.id == Submission.task_id,
+        ).where(
+            Submission.id == str(submission_id),
+            Submission.task_id == str(task_id),
+            Submission.task_assignment_id == str(assignment_id),
+            Submission.contributor_id == str(contributor_id),
+            WorkstreamTask.project_id == str(project_id),
+            SubmissionDispatch.project_id == str(project_id),
+            SubmissionDispatch.task_id == str(task_id),
+            SubmissionDispatch.assignment_id == str(assignment_id),
+            SubmissionDispatch.contributor_id == str(contributor_id),
+            SubmissionDispatch.admission_id == str(admission_id),
+            SubmissionDispatch.submission_version == Submission.version,
+        ))).one_or_none()
+        if row is None:
+            raise SubmissionOperationAssociationUnavailable("submission_operation_association_unavailable")
+        return SubmissionOperationOutcome(
+            submission_id=UUID(row.id), submission_version=row.version,
+            status=row.attempt_status, evaluation_request_id=UUID(row.SubmissionDispatch.evaluation_request_id),
+            evaluation_event_id=UUID(str(row.SubmissionDispatch.evaluation_event_id)),
+            evaluation_event=evaluation_request_event(row.SubmissionDispatch),
+        )
diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py
index bdd7665a9..ada40e9be 100644
--- a/backend/scripts/behavior_ownership.py
+++ b/backend/scripts/behavior_ownership.py
@@ -936,6 +936,7 @@
     "backend/app/modules/authorization/project_catalogue.py",
 })
 SUBMISSION_INTAKE_TARGETS = frozenset({
+    "backend/app/modules/artifacts/api/submission_command.py",
     "backend/app/modules/artifacts/intake/foreground_command.py",
     "backend/app/api/submission_intake.py",
     "backend/app/adapters/artifacts/source_cleanup.py",
diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py
index 288e5bc32..0c5f65d53 100644
--- a/backend/tests/artifacts/test_submission_foreground_command.py
+++ b/backend/tests/artifacts/test_submission_foreground_command.py
@@ -16,6 +16,66 @@
 )
 
 
+@pytest.mark.parametrize("outcome", ["completed", "rejected"])
+async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admission_intake, tmp_path, monkeypatch, outcome):
+    from sqlalchemy import text
+    from app.adapters import artifacts as composition
+    from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter
+    from app.modules.actors.api import ServiceIdentity
+    from tests.artifacts.test_submission_pre_source import _source_runtime
+    from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer
+    from tests.checkers.execution.support import provision_post_submit_service
+    from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation
+    from tests.test_artifact_admission import _settings
+    from tests.test_trusted_intake import _archive
+
+    f, key = admission_intake, new_record_id()
+    payload = _archive("../escape") if outcome == "rejected" else _archive()
+    runtime, errors = _source_runtime(payload, tmp_path, outcome)
+    calls, original = [], runtime.execute_pre
+    async def execute(lease, grant):
+        calls.append(lease.reservation.attempt_id)
+        return await original(lease, grant)
+    runtime.execute_pre = execute
+    monkeypatch.setattr(composition, "selected_pre_submit_checker_execution",
+                        lambda **kwargs: SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime))
+    await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_PRE_SUBMIT)
+    await _seed_materializer(f.factory)
+    client = f.access.signed.client
+    app = client._transport.app
+    storage = {name: value for name, value in _settings(tmp_path).model_dump().items() if name.startswith("artifact_")}
+    settings = app.state.settings.model_copy(update=storage | {"submission_execution_profile": {
+        "capacity": {"maximum_total_bytes": 1_000_000},
+        "runtime": _source_reservation().runtime_profile.model_dump(mode="json"),
+        "upload_total_seconds": 300.0, "upload_idle_seconds": 10.0,
+        "foreground_lease_seconds": 60.0, "heartbeat_seconds": 10.0,
+        "replay_total_seconds": 30.0, "part_bytes": 5 * 1024**2,
+    }})
+    monkeypatch.setattr(app.state, "settings", settings)
+    headers = f.access.target.headers | {"Content-Type": "application/zip",
+        "X-Task-Assignment-Id": str(f.assignment), "Idempotency-Key": str(key)}
+    url = f"/api/v1/tasks/{f.task}/submissions"
+    first = await client.post(url, headers=headers, content=payload)
+    second = await client.post(url, headers=headers, content=payload)
+    assert not errors, "\n".join(errors)
+    assert len(calls) == 1
+    if outcome == "completed":
+        assert first.status_code == second.status_code == 202, (first.text, second.text)
+        receipt = first.json()
+        assert second.json() == dict(receipt, replayed=True)
+        assert receipt["status"] == "accepted" and receipt["replayed"] is False
+        assert set(receipt) == {"operation_id", "task_id", "assignment_id", "status", "accepted_at",
+                                "task_status_at_acceptance", "processing_stage_at_acceptance", "replayed", "pre_submission_results"}
+    else:
+        assert first.status_code == second.status_code == 422, (first.text, second.text)
+        assert first.json()["error"]["code"] == second.json()["error"]["code"] == "pre_submission_checker_failed"
+        assert first.json()["error"]["details"] == second.json()["error"]["details"]
+        assert first.json()["error"]["details"]["eligible_to_submit"] is False
+    async with f.factory() as session:
+        assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": f.task}) == 0
+        assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations WHERE task_id=:id"), {"id": f.task}) == 1
+
+
 async def test_foreground_command_upload_timeout_retains_charge(admission_intake, tmp_path):
     from sqlalchemy import text
     from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index e6201ea6b..016a2cffd 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -800,8 +800,8 @@ async def commit(self):
     assert receipt["status"] == "accepted" and receipt["replayed"] is True
 
 
-@pytest.mark.parametrize("expired_claim", [False, True])
-async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(admission_intake, tmp_path, expired_claim):
+@pytest.mark.parametrize("expired_claim,post_failure", [(False, False), (True, False), (False, True)])
+async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(admission_intake, tmp_path, monkeypatch, expired_claim, post_failure):
     from datetime import timedelta
     from sqlalchemy import text
     from app.adapters.artifacts import submission_admission_consumption_port
@@ -862,6 +862,41 @@ def submissions(session):
                 {"id": owner.operation_id}) == 1
         # Removing retained provenance must fail at commit even when all other
         # replica coordinates remain unchanged.
+        from app.adapters.tasks import submission_history_repository
+        from app.modules.tasks.api.submission_history import SubmissionOperationAssociationUnavailable
+        from app.adapters.checkers import evaluation_coordinator
+        from app.modules.checkers.api.execution import CheckerExecutionUnavailable
+        evaluation_selectors = dict(project_id=f.project, task_id=f.task,
+                                    submission_id=result.submission_id,
+                                    original_request_id=result.evaluation_request_id)
+        async with f.factory.begin() as session:
+            coordinator = evaluation_coordinator(session)
+            queued = await coordinator.read_current_progress(**evaluation_selectors)
+            assert queued.status == "queued" and not queued.live_worker_lease
+            assert queued.retry_event_id is queued.completion_event_id is None
+            for field in evaluation_selectors:
+                with pytest.raises(CheckerExecutionUnavailable):
+                    await coordinator.read_current_progress(**(evaluation_selectors | {field: new_record_id()}))
+        selectors = dict(project_id=f.project, task_id=f.task, assignment_id=request.assignment_id,
+                         contributor_id=request.actor_profile_id, submission_id=result.submission_id,
+                         admission_id=result.admission_id)
+        async with f.factory.begin() as session:
+            history = submission_history_repository(session)
+            outcome = await history.read_operation_outcome(**selectors)
+            assert outcome.submission_id == result.submission_id
+            assert outcome.submission_version == result.submission_version
+            assert outcome.evaluation_request_id == result.evaluation_request_id
+            assert outcome.status == "evaluation_pending"
+            from app.modules.artifacts.intake.progress import evaluation_delivery_progress
+            from app.adapters.outbox import finalized_unknown_deliveries
+            pending = await evaluation_delivery_progress(
+                outcome.evaluation_event_id, outcome.evaluation_event, queued,
+                outbox_append(session), finalized_unknown_deliveries(session),
+            )
+            assert pending.state == "pending"
+            for field in selectors:
+                with pytest.raises(SubmissionOperationAssociationUnavailable):
+                    await history.read_operation_outcome(**(selectors | {field: new_record_id()}))
         from sqlalchemy.exc import IntegrityError
         async with f.factory() as session:
             with pytest.raises(IntegrityError, match="retained source ownership is immutable"):
@@ -884,7 +919,59 @@ def submissions(session):
                     async with session.begin():
                         await session.execute(text(statement), {"id": identity})
         from tests.artifacts.intake_post_support import exercise_source_post
-        await exercise_source_post(f, result, store, request.source, tmp_path)
+        from tests.checkers.execution.support import ControlledSelectedExecution
+        running_observations = []
+        original_execute = ControlledSelectedExecution.execute
+        async def observe_running(runtime, execution_request, grant):
+            async with f.factory.begin() as session:
+                running = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
+                assert running.status == "running" and running.live_worker_lease
+                assert running.completion_event_id is None
+                running_observations.append(running)
+            return await original_execute(runtime, execution_request, grant)
+        with monkeypatch.context() as patch:
+            patch.setattr(ControlledSelectedExecution, "execute", observe_running)
+            if post_failure:
+                from app.interfaces.artifacts import ArtifactObjectMissingError
+                def missing_source(*_args, **_kwargs):
+                    raise ArtifactObjectMissingError("controlled source unavailable")
+                patch.setattr(type(store), "open_source", missing_source)
+            await exercise_source_post(f, result, store, request.source, tmp_path, missing=post_failure)
+        assert len(running_observations) == (0 if post_failure else 1)
+        async with f.factory.begin() as session:
+            # Completed checker evidence alone does not change the governed attempt.
+            after_post = await submission_history_repository(session).read_operation_outcome(**selectors)
+            assert after_post == outcome
+            completed = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
+            assert completed.status == ("infrastructure_failed" if post_failure else "completed")
+            assert not completed.live_worker_lease and completed.current == queued.current
+            assert (completed.completion_event_id is None) is post_failure
+            assert completed.retry_event_id is None
+            if not post_failure:
+                pending_completion = await evaluation_delivery_progress(
+                    completed.completion_event_id, completed.delivery_event, completed,
+                    outbox_append(session), finalized_unknown_deliveries(session),
+                )
+                assert pending_completion.state == "pending"
+        if post_failure:
+            from app.adapters.checkers import checker_retry_service
+            from tests.checkers.execution.test_checker_retry import _operator_for, _command
+            harness = SimpleNamespace(factory=f.factory, request=queued.current.request, created=result)
+            operator = await _operator_for(harness)
+            async with f.factory.begin() as session:
+                retry = await checker_retry_service(session, operator).retry(_command(harness, operator))
+            async with f.factory.begin() as session:
+                retrying = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
+                assert retrying.status == "queued" and not retrying.live_worker_lease
+                assert retrying.current.reservation.attempt_id == retry.successor.run_id
+                assert retrying.retry_event_id == retry.successor.event_id
+                assert retrying.completion_event_id is None
+                pending_retry = await evaluation_delivery_progress(
+                    retrying.retry_event_id, retrying.delivery_event, retrying,
+                    outbox_append(session), finalized_unknown_deliveries(session),
+                )
+                assert pending_retry.state == "pending"
+
     finally:
         store.close()
 
diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py
index c49a0115a..0e11e145f 100644
--- a/backend/tests/artifacts/test_submission_intake_contracts.py
+++ b/backend/tests/artifacts/test_submission_intake_contracts.py
@@ -41,6 +41,26 @@ def metadata(**updates):
     })
 
 
+@pytest.mark.parametrize("missing", ["capacity", "runtime", "upload_total_seconds", "upload_idle_seconds",
+    "foreground_lease_seconds", "heartbeat_seconds", "replay_total_seconds", "part_bytes"])
+def test_submission_execution_profile_requires_explicit_deployment_values(missing):
+    from app.modules.artifacts.api.submission_command import SubmissionExecutionProfile
+    from app.modules.checkers.api.source_contracts import source_contracts_context
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
+    from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation
+
+    values = dict(capacity={"maximum_total_bytes": 1_000_000},
+        runtime=_source_reservation().runtime_profile.model_dump(mode="json"),
+        upload_total_seconds=300.0, upload_idle_seconds=10.0, foreground_lease_seconds=60.0,
+        heartbeat_seconds=10.0, replay_total_seconds=30.0, part_bytes=5 * 1024**2)
+    context = source_contracts_context(selected_pre_submit_source_contracts())
+    assert SubmissionExecutionProfile.model_validate(values, context=context).upload_total_seconds == 300.0
+    del values[missing]
+    with pytest.raises(ValidationError) as caught:
+        SubmissionExecutionProfile.model_validate(values, context=context)
+    assert any(error["loc"] == (missing,) and error["type"] == "missing" for error in caught.value.errors())
+
+
 def location(**updates):
     return SubmissionSourceLocation.model_validate({
         "operation_id": OPERATION, "namespace_id": "primary",
@@ -577,3 +597,62 @@ def test_checker_source_contracts_preserve_closed_limits_and_source_wire(changed
     del source_body["media_type"]
     with pytest.raises(ValueError, match="not canonical"):
         contracts.parse_source(source_body)
+
+
+@pytest.mark.parametrize("changed", [None, "original_event_id", "original_claim_generation",
+    "original_payload_digest", "original_event_type", "evaluation_request_id", "checker_run_id",
+    "evaluation_generation", "retained_digest"])
+async def test_evaluation_progress_follows_only_exact_reconciliation_child(changed):
+    from types import SimpleNamespace
+    from unittest.mock import AsyncMock
+    from app.core.hashing import canonical_json_hash
+    from app.modules.artifacts.intake.progress import evaluation_delivery_progress
+    from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+    from app.modules.checkers.api.delivery_reconciliation import PostSubmitDeliveryChildPayload
+    from app.modules.outbox.api import OutboxAppendInput
+    event_id, child_id, project, run, request = (new_record_id() for _ in range(5))
+    event = OutboxAppendInput(event_type="PostSubmissionEvaluationRequested", event_version=1,
+        aggregate_type="submission", aggregate_id=new_record_id(), project_id=project,
+        correlation_id=str(request), idempotency_key="progress-fixture", payload={})
+    resource = {"resource_context": {}}
+    payload = PostSubmitDeliveryChildPayload(
+        original_event_id=event_id, original_claim_generation=2, original_payload_digest=canonical_json_hash(event.payload),
+        original_event_type=event.event_type, original_event_version=1,
+        evaluation_request_id=request, checker_run_id=run, evaluation_generation=1,
+        classification="retry_safe", reconciliation_request_id=new_record_id(), request_digest=SHA,
+        authorization_decision_id=new_record_id(),
+        authorization_resource_digest=canonical_json_hash(resource),
+        authorization_resource_json=json.dumps(resource, sort_keys=True, separators=(",", ":")),
+        operator_actor_profile_id=new_record_id(), operator_identity_link_id=new_record_id(),
+    )
+    body = payload.model_dump(mode="json")
+    if changed == "retained_digest":
+        body["original_payload_digest"] = SHA
+    elif changed is not None:
+        body[changed] = (3 if changed.endswith("generation") else
+                         "sha256:" + "b" * 64 if changed.endswith("digest") else
+                         "PostSubmissionEvaluationCompleted" if changed.endswith("type") else
+                         str(new_record_id()))
+    original = SimpleNamespace(state="dead_letter", error_code="INVOKE_OUTCOME_UNKNOWN")
+    child = SimpleNamespace(state="pending", error_code=None)
+    events = SimpleNamespace(observe_delivery=AsyncMock(side_effect=[original, child]))
+    retained = SimpleNamespace(
+        envelope=SimpleNamespace(claim=SimpleNamespace(event_id=event_id, project_id=project,
+            claim_generation=2, payload_digest=SHA if changed == "retained_digest" else canonical_json_hash(event.payload))),
+        child=SimpleNamespace(event_id=child_id, payload_json=json.dumps(body)),
+    )
+    deliveries = SimpleNamespace(read_finalized_unknown=AsyncMock(return_value=retained))
+    evaluation = SimpleNamespace(current=SimpleNamespace(
+        request=SimpleNamespace(evaluation_request_id=request),
+        reservation=SimpleNamespace(attempt_id=run, evaluation_generation=1),
+    ))
+    if changed:
+        with pytest.raises(IntakeCustodyConflict):
+            await evaluation_delivery_progress(event_id, event, evaluation, events, deliveries)
+        assert events.observe_delivery.await_count == 1
+    else:
+        assert await evaluation_delivery_progress(event_id, event, evaluation, events, deliveries) is child
+        observed_id, expected = events.observe_delivery.await_args.args
+        assert observed_id == child_id and expected.payload == payload.model_dump(mode="json")
+        assert expected.causation_event_id == event_id and expected.aggregate_id == event_id
+    assert deliveries.read_finalized_unknown.await_args.kwargs["lock"] is False
diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py
index a4ecf6dc0..f48deed48 100644
--- a/backend/tests/tasks/test_public_submission_intake.py
+++ b/backend/tests/tasks/test_public_submission_intake.py
@@ -15,7 +15,6 @@
 from sqlalchemy import func, select
 from sqlalchemy.exc import SQLAlchemyError
 
-from app.core.api_controls import StructuredHTTPException
 from app.core.config import Settings, get_settings
 from app.core.identifiers import new_record_id
 from app.api.deps.rate_controls import get_rate_control_service
@@ -28,7 +27,6 @@
 from app.modules.tasks.models import Submission
 from app.modules.tasks.models import TaskAssignment, WorkstreamTask
 from app.modules.tasks.api import SubmissionCreationRequest
-from app.modules.tasks.router import create_admission_backed_submission
 from app.modules.tasks.schemas import AdmissionBackedSubmissionCreate
 from app.modules.api_controls.service import AUTHORIZATION_READ_SCOPE, RateControlService
 from app.modules.actors.models import ActorProfile
@@ -408,22 +406,20 @@ async def no_new_checker(*_args, **_kwargs):
 
 
 async def test_public_submission_infrastructure_error_is_retryable_only_for_sql():
-    """A broken command composition must not be reported as transient storage."""
-    actor = SimpleNamespace(actor_profile_id=new_record_id())
-    payload = AdmissionBackedSubmissionCreate(
-        admission_id=new_record_id(), assignment_id=new_record_id(),
-        summary="test", contributor_attestation="test",
-    )
-    command = SimpleNamespace(create=AsyncMock(side_effect=SQLAlchemyError("database unavailable")))
-    with pytest.raises(StructuredHTTPException) as failure:
-        await create_admission_backed_submission(new_record_id(), payload, actor, command)
-    assert failure.value.status_code == 503
-    assert failure.value.error_code == "submission_infrastructure_unavailable"
-    assert failure.value.retryable is True
-
-    command.create.side_effect = RuntimeError("invalid composition")
+    """Known database failure is bounded; a programming defect is not relabeled."""
+    from app.adapters.artifacts import ConfiguredSubmissionCommand
+    from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
+    actor = SimpleNamespace(actor_profile_id=new_record_id(), identity_link_id=new_record_id())
+    command = ConfiguredSubmissionCommand(settings=None, sessions=None, context=actor)
+    command._submit = AsyncMock(side_effect=SQLAlchemyError("database unavailable"))
+    arguments = dict(actor_id=actor.actor_profile_id, identity_link_id=actor.identity_link_id,
+                     idempotency_key=new_record_id(), declared_raw_bytes=None)
+    with pytest.raises(SubmissionIntakeFailure) as failure:
+        await command.submit(None, None, **arguments)
+    assert failure.value.code == "submission_infrastructure_unavailable"
+    command._submit.side_effect = RuntimeError("invalid composition")
     with pytest.raises(RuntimeError, match="invalid composition"):
-        await create_admission_backed_submission(new_record_id(), payload, actor, command)
+        await command.submit(None, None, **arguments)
 
 
 async def test_public_initial_submission_replays_and_recovers_ready_upload(
diff --git a/backend/tests/test_api_controls.py b/backend/tests/test_api_controls.py
index 4c80705c1..f672bc036 100644
--- a/backend/tests/test_api_controls.py
+++ b/backend/tests/test_api_controls.py
@@ -625,7 +625,6 @@ def test_openapi_documents_request_error_and_response_context() -> None:
         "schema": {"type": "string", "format": "uuid"},
     }]
     public_entry_actions = {
-        "POST /api/v1/tasks/{task_id}/submission-bundle-preparations": "artifact.submission_bundle.prepare",
         "POST /api/v1/tasks/{task_id}/submissions": "submission.create",
     }
     assert public_entry_actions.keys() <= set(protected_inventory)
@@ -664,13 +663,13 @@ def test_openapi_documents_request_error_and_response_context() -> None:
         operation = schema["paths"][path][method.lower()]
         assert operation["x-workstream-action-id"] == action
         assert operation["security"]
-    assert len(route_inventory) == 134
+    assert len(route_inventory) == 133
     retained_routes = sorted(set(route_inventory) - proposal_routes - post_policy_routes - queue_routes - new_manager_reads - guide_read - contribution_reads.keys() - public_entry_actions.keys() - registry_actions.keys() - recovery_actions.keys() - model_actions.keys())
     retained_protected = sorted(set(protected_inventory) - proposal_routes - post_policy_routes - queue_routes - new_manager_reads - guide_read - contribution_reads.keys() - public_entry_actions.keys() - registry_actions.keys() - recovery_actions.keys() - model_actions.keys())
     assert sha256("\n".join(retained_routes).encode()).hexdigest() == (
         "9a495b21b504f27997a26c233e7dc4b814133038a063376b760147118bd44b7e"
     )
-    assert len(protected_inventory) == 132
+    assert len(protected_inventory) == 131
     assert sha256("\n".join(retained_protected).encode()).hexdigest() == (
         "8aa0828260680a7bccdb055ebb3f21fcd06d4e37a808b4a0a37dcbf77ffa0732"
     )
@@ -1020,6 +1019,48 @@ def _casefold_packet_headers():
     ]
 
 
+def test_submission_mutation_is_one_raw_zip_acceptance_contract():
+    from app.api.routes.artifact_submissions import router as intake_router
+    from app.modules.tasks.router import router as task_router
+
+    app = create_app()
+    path = "/api/v1/tasks/{task_id}/submissions"
+    # Inspect both route owners; the application lazily includes their router.
+    routes = [*intake_router.routes, *task_router.routes]
+    assert len([route for route in routes if getattr(route, "path", None) == "/tasks/{task_id}/submissions"
+                and "POST" in getattr(route, "methods", set())]) == 1
+    assert "post" not in app.openapi()["paths"].get("/api/v1/tasks/{task_id}/submission-bundle-preparations", {})
+    operation = app.openapi()["paths"][path]["post"]
+    assert operation["x-workstream-action-id"] == "submission.create"
+    assert set(operation["requestBody"]["content"]) == {"application/zip"}
+    assert "202" in operation["responses"] and "201" not in operation["responses"]
+    receipt = app.openapi()["components"]["schemas"]["SubmissionAcceptedResponse"]
+    assert set(receipt["required"]) == {"operation_id", "task_id", "assignment_id", "status", "accepted_at",
+        "task_status_at_acceptance", "processing_stage_at_acceptance", "replayed", "pre_submission_results"}
+    assert receipt["additionalProperties"] is False
+
+
+async def test_submission_route_refuses_ambiguous_packet_before_body_or_command():
+    from app.adapters.artifacts import get_submission_intake_command
+
+    app, consumed = create_app(), []
+    def forbidden_command():
+        pytest.fail("Ambiguous packet reached command construction")
+    app.dependency_overrides[get_submission_intake_command] = forbidden_command
+    async def body():
+        consumed.append(True)
+        yield b"not consumed"
+    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as client:
+        response = await client.post(f"/api/v1/tasks/{uuid4()}/submissions", content=body(), headers=[
+            ("Content-Type", "application/zip"), ("Idempotency-Key", str(uuid4())),
+            ("X-Task-Assignment-Id", str(uuid4())), ("X-Submission-Summary", "one"),
+            ("x-submission-summary", "two"),
+        ])
+    assert response.status_code == 422, response.text
+    assert response.json()["error"]["code"] == "submission_packet_invalid"
+    assert consumed == []
+
+
 def _casefold_request(headers):
     async def forbidden_read():
         raise AssertionError('Header parsing consumed the body')
diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py
index ea63b896e..a1c02dfda 100644
--- a/backend/tests/test_behavior_ownership.py
+++ b/backend/tests/test_behavior_ownership.py
@@ -2763,6 +2763,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ
     retained = "backend/app/core/config.py"
     target = "backend/app/modules/artifacts/api/submission_intake.py"
     additions = {
+        "backend/app/modules/artifacts/api/submission_command.py",
         "backend/app/modules/artifacts/intake/foreground_command.py",
         "backend/app/api/submission_intake.py",
         target, "backend/app/modules/artifacts/intake/models.py",
diff --git a/cli/internal/api/submission.go b/cli/internal/api/submission.go
index 141b5ba6f..217643c1f 100644
--- a/cli/internal/api/submission.go
+++ b/cli/internal/api/submission.go
@@ -5,20 +5,20 @@ import (
 	"encoding/json"
 	"errors"
 	"io"
-	"math/big"
 	"mime"
 	"net/http"
 	"net/url"
 	"os"
 	"regexp"
 	"strings"
+	"time"
 )
 
 // MaxSubmissionZipBytes bounds the compressed submission ZIP, independently of guide uploads.
 // Project limits may enforce a smaller allowance.
 const MaxSubmissionZipBytes = 500 * 1024 * 1024
 
-// SubmissionPacket is shared unchanged between explicit preparation and creation.
+// SubmissionPacket is the exact metadata for one source submission.
 // ART's current public header boundary requires ASCII; no client normalization.
 type SubmissionPacket struct {
 	Assignment  string  `json:"assignment_id"`
@@ -27,7 +27,7 @@ type SubmissionPacket struct {
 	Attestation *string `json:"contributor_attestation,omitempty"`
 }
 
-// RevisionAcknowledgement is preparation-only; it is not part of Submission JSON.
+// RevisionAcknowledgement binds the current governed revision context.
 type RevisionAcknowledgement struct {
 	PreparationID     string
 	PreparationSHA256 string
@@ -35,19 +35,16 @@ type RevisionAcknowledgement struct {
 
 var revisionPreparationDigest = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
 
-type PreparationReceipt struct {
-	PutAttemptID string            `json:"put_attempt_id"`
-	AdmissionID  *string           `json:"admission_id"`
-	Status       string            `json:"submission_bundle_preparation_status"`
-	Replayed     bool              `json:"replayed"`
-	Feedback     []json.RawMessage `json:"pre_submission_results,omitempty"`
-}
-
 type SubmissionReceipt struct {
-	SubmissionID        string   `json:"submission_id"`
-	Version             *big.Int `json:"submission_version"`
-	AdmissionID         string   `json:"admission_id"`
-	EvaluationRequestID string   `json:"evaluation_request_id"`
+	OperationID     string            `json:"operation_id"`
+	TaskID          string            `json:"task_id"`
+	AssignmentID    string            `json:"assignment_id"`
+	Status          string            `json:"status"`
+	AcceptedAt      string            `json:"accepted_at"`
+	TaskStatus      string            `json:"task_status_at_acceptance"`
+	ProcessingStage string            `json:"processing_stage_at_acceptance"`
+	Replayed        bool              `json:"replayed"`
+	Feedback        []json.RawMessage `json:"pre_submission_results,omitempty"`
 }
 
 func submissionSelector(value string) bool { return len(value) <= 100 && validUUID(value) }
@@ -66,36 +63,33 @@ func (p SubmissionPacket) validate(task string) error {
 		}
 		for _, value := range []byte(*text) {
 			if value < 32 || value > 126 {
-				return errors.New("packet text must be printable ASCII for the public preparation API")
+				return errors.New("packet text must be printable ASCII for the public submission API")
 			}
 		}
 	}
 	return nil
 }
 
-func submissionFailure(err error, preparation bool) error {
+func submissionFailure(err error) error {
 	var failure *Failure
 	if errors.As(err, &failure) && failure.OutcomeUnknown {
-		failure.RecoveryHint = "Submission outcome unknown; inspect task submissions; replay only the same task, assignment, admission and packet"
-		if preparation {
-			failure.RecoveryHint = "preparation outcome unknown; explicitly replay only the same task, assignment, ZIP bytes, packet, revision acknowledgement and idempotency key; no Submission was requested by this command"
-		}
+		failure.RecoveryHint = "Observe the submission operation using the same actor and idempotency key, or explicitly replay the same task, assignment, ZIP bytes, packet and revision acknowledgement; do not create a new key while the outcome is unknown"
 	}
 	return err
 }
 
-// PrepareSubmission streams one regular ZIP once. A receipt is not a Submission.
-func (c *Client) PrepareSubmission(ctx context.Context, task, key string, packet SubmissionPacket, acknowledgement *RevisionAcknowledgement, source *os.File) (Result[PreparationReceipt], error) {
-	var result Result[PreparationReceipt]
+// SubmitSubmission streams one regular ZIP once and returns its committed acceptance snapshot.
+func (c *Client) SubmitSubmission(ctx context.Context, task, key string, packet SubmissionPacket, acknowledgement *RevisionAcknowledgement, source *os.File) (Result[SubmissionReceipt], error) {
+	var result Result[SubmissionReceipt]
 	if err := packet.validate(task); err != nil {
 		return result, err
 	}
 	if !submissionSelector(key) || source == nil {
-		return result, errors.New("preparation requires a caller UUID key and a regular ZIP file")
+		return result, errors.New("submission requires a caller UUID key and a regular ZIP file")
 	}
 	if packet.Predecessor == nil {
 		if acknowledgement != nil {
-			return result, errors.New("initial preparation cannot acknowledge a revision")
+			return result, errors.New("initial submission cannot acknowledge a revision")
 		}
 	} else if acknowledgement == nil || !submissionSelector(acknowledgement.PreparationID) ||
 		!revisionPreparationDigest.MatchString(acknowledgement.PreparationSHA256) {
@@ -123,16 +117,16 @@ func (c *Client) PrepareSubmission(ctx context.Context, task, key string, packet
 		headers.Set("X-Revision-Preparation-Sha256", acknowledgement.PreparationSHA256)
 	}
 	response, err := c.openBodyRequest(ctx, c.guideHTTP, http.MethodPost,
-		"/api/v1/tasks/"+url.PathEscape(task)+"/submission-bundle-preparations", "",
+		"/api/v1/tasks/"+url.PathEscape(task)+"/submissions", "",
 		io.NewSectionReader(source, 0, initial.Size()), initial.Size(), key, "application/json", "application/zip", headers)
 	if err != nil {
-		return result, submissionFailure(err, true)
+		return result, submissionFailure(err)
 	}
 	defer response.Body.Close()
 	raw, err := io.ReadAll(io.LimitReader(response.Body, maxSubmissionReadBytes+1))
 	invalid := &Failure{Code: "invalid_api_response", Status: response.StatusCode, OutcomeUnknown: true}
 	if err != nil || len(raw) > maxSubmissionReadBytes {
-		return result, submissionFailure(invalid, true)
+		return result, submissionFailure(invalid)
 	}
 	if response.StatusCode != http.StatusAccepted {
 		failure := c.responseFailure(http.MethodPost, response, raw)
@@ -140,71 +134,32 @@ func (c *Client) PrepareSubmission(ctx context.Context, task, key string, packet
 			var typed *Failure
 			if errors.As(failure, &typed) && typed.Code == "pre_submission_checker_failed" {
 				if typed.OutcomeUnknown || !c.safeMutationResponse(raw) {
-					return result, submissionFailure(invalid, true)
+					return result, submissionFailure(invalid)
 				}
 				details, err := preparationFeedback(raw)
 				if err != nil {
-					return result, submissionFailure(invalid, true)
+					return result, submissionFailure(invalid)
 				}
 				typed.Details = details
 			}
 		}
-		return result, submissionFailure(failure, true)
+		return result, submissionFailure(failure)
 	}
 	kind, _, typeErr := mime.ParseMediaType(response.Header.Get("Content-Type"))
-	var value PreparationReceipt
-	fields, decodeErr := contextObject(raw, &value, []string{"put_attempt_id", "submission_bundle_preparation_status", "replayed", "pre_submission_results"}, nil)
-	if typeErr != nil || kind != "application/json" || decodeErr != nil || !requiredNullable(fields, "admission_id") ||
-		!validUUID(value.PutAttemptID) || !c.safeMutationResponse(raw) ||
-		value.Feedback == nil || !validPreSubmissionResults(value.Feedback, true) ||
+	var value SubmissionReceipt
+	_, decodeErr := contextObject(raw, &value, []string{"operation_id", "task_id", "assignment_id", "status", "accepted_at", "task_status_at_acceptance", "processing_stage_at_acceptance", "replayed", "pre_submission_results"}, nil)
+	_, acceptedErr := time.Parse(time.RFC3339Nano, value.AcceptedAt)
+	if typeErr != nil || kind != "application/json" || decodeErr != nil || acceptedErr != nil ||
+		!validUUID(value.OperationID) || !sameUUID(value.TaskID, task) || !sameUUID(value.AssignmentID, packet.Assignment) ||
+		value.Status != "accepted" || value.TaskStatus != "evaluation_pending" || value.ProcessingStage != "finalization_pending" ||
+		!c.safeMutationResponse(raw) || value.Feedback == nil || !validPreSubmissionResults(value.Feedback, true) ||
 		(response.Header.Get("Content-Encoding") != "" && response.Header.Get("Content-Encoding") != "identity") {
-		return result, submissionFailure(invalid, true)
-	}
-	switch value.Status {
-	case "ready":
-		if value.AdmissionID == nil || !validUUID(*value.AdmissionID) {
-			return result, submissionFailure(invalid, true)
-		}
-	case "prepared", "put_in_flight", "object_confirmed", "stored_pending_verification", "observed_confirmed",
-		"acknowledgement_unknown", "provider_unavailable", "conflict", "integrity_mismatch", "missing", "absent_replay_required", "stale":
-		if value.AdmissionID != nil {
-			return result, submissionFailure(invalid, true)
-		}
-	default:
-		return result, submissionFailure(invalid, true)
+		return result, submissionFailure(invalid)
 	}
 	finalHash, hashErr := uploadSourceHash(source, initial.Size())
 	final, statErr := source.Stat()
 	if hashErr != nil || statErr != nil || final.Size() != initial.Size() || !final.ModTime().Equal(initial.ModTime()) || finalHash != expected {
-		return result, submissionFailure(&Failure{Code: "submission_source_changed", OutcomeUnknown: true}, true)
-	}
-	return Result[PreparationReceipt]{Raw: raw, Value: value}, nil
-}
-
-func (c *Client) CreateSubmission(ctx context.Context, task, admission string, packet SubmissionPacket) (Result[SubmissionReceipt], error) {
-	var result Result[SubmissionReceipt]
-	if err := packet.validate(task); err != nil {
-		return result, err
-	}
-	if !submissionSelector(admission) {
-		return result, errors.New("admission must be a UUID")
-	}
-	body, err := json.Marshal(struct {
-		SubmissionPacket
-		Admission string `json:"admission_id"`
-	}{packet, admission})
-	if err != nil {
-		return result, err
-	}
-	raw, err := c.requestWithKey(ctx, http.MethodPost, "/api/v1/tasks/"+url.PathEscape(task)+"/submissions", "", body, "", http.StatusCreated)
-	if err != nil {
-		return result, submissionFailure(err, false)
-	}
-	var value SubmissionReceipt
-	_, err = contextObject(raw, &value, []string{"submission_id", "submission_version", "admission_id", "evaluation_request_id"}, nil)
-	if err != nil || !validUUID(value.SubmissionID) || value.Version == nil || value.Version.Sign() <= 0 ||
-		!sameUUID(value.AdmissionID, admission) || !validUUID(value.EvaluationRequestID) || !c.safeMutationResponse(raw) {
-		return result, submissionFailure(&Failure{Code: "invalid_api_response", OutcomeUnknown: true}, false)
+		return result, submissionFailure(&Failure{Code: "submission_source_changed", OutcomeUnknown: true})
 	}
 	return Result[SubmissionReceipt]{Raw: raw, Value: value}, nil
 }
diff --git a/cli/internal/api/submission_test.go b/cli/internal/api/submission_test.go
index 702f6aa45..dd40add9a 100644
--- a/cli/internal/api/submission_test.go
+++ b/cli/internal/api/submission_test.go
@@ -10,7 +10,7 @@ import (
 	"testing"
 )
 
-func TestPrepareSubmissionRejectsOversizedCompressedZipBeforeHTTP(t *testing.T) {
+func TestSubmitSubmissionRejectsOversizedCompressedZipBeforeHTTP(t *testing.T) {
 	var requests atomic.Int32
 	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		requests.Add(1)
@@ -30,7 +30,7 @@ func TestPrepareSubmissionRejectsOversizedCompressedZipBeforeHTTP(t *testing.T)
 	if err := file.Truncate(524288001); err != nil {
 		t.Fatal(err)
 	}
-	_, err = client.PrepareSubmission(context.Background(), testTask, testRun,
+	_, err = client.SubmitSubmission(context.Background(), testTask, testRun,
 		SubmissionPacket{Assignment: testSubmission}, nil, file)
 	if err == nil || err.Error() != "ZIP must be a nonempty regular file of at most 500MiB" {
 		t.Fatalf("expected local compressed ZIP limit rejection, got %v", err)
diff --git a/cli/internal/command/submission.go b/cli/internal/command/submission.go
index 7b6eb3fb0..7e3cdedd6 100644
--- a/cli/internal/command/submission.go
+++ b/cli/internal/command/submission.go
@@ -10,33 +10,26 @@ import (
 )
 
 func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client, error), output *string, stdout io.Writer) {
-	for _, prepare := range []bool{true, false} {
-		var assignment, predecessor, summary, attestation, path, key, admission string
+	{
+		var assignment, predecessor, summary, attestation, path, key string
 		var revisionPreparationID, revisionPreparationSHA256 string
-		name, description := "submit", "Create or explicitly replay a Submission from a ready admission"
-		if prepare {
-			name, description = "prepare", "Upload a ZIP for intake preparation; does not create a Submission"
-		}
+		name, description := "submit", "Upload one ZIP for initial checks and durable evaluation acceptance"
 		cmd := &cobra.Command{Use: name + " TASK_ID", Short: description, Args: cobra.ExactArgs(1)}
 		cmd.Flags().StringVar(&assignment, "assignment", "", "Required active task-assignment UUID")
 		cmd.Flags().StringVar(&predecessor, "predecessor", "", "Predecessor Submission UUID when required by the task")
-		cmd.Flags().StringVar(&summary, "summary", "", "Exact printable ASCII packet summary; use identically for preparation and submission")
+		cmd.Flags().StringVar(&summary, "summary", "", "Exact printable ASCII packet summary; preserve for same-key replay")
 		cmd.Flags().StringVar(&attestation, "attestation", "", "Exact printable ASCII contributor attestation")
-		if prepare {
-			cmd.Flags().StringVar(&path, "file", "", "Required regular ZIP; keep unchanged for explicit replay")
-			cmd.Flags().StringVar(&key, "idempotency-key", "", "Required caller-owned UUID; never retried automatically")
-			cmd.Flags().StringVar(&revisionPreparationID, "revision-preparation-id", "", "Exact preparation UUID from task context; required with --predecessor")
-			cmd.Flags().StringVar(&revisionPreparationSHA256, "revision-preparation-sha256", "", "Exact preparation digest from task context; required with --predecessor")
-		} else {
-			cmd.Flags().StringVar(&admission, "admission", "", "Required ready admission UUID; exact admission and packet identify replay")
-		}
+		cmd.Flags().StringVar(&path, "file", "", "Required regular ZIP; keep unchanged for explicit replay")
+		cmd.Flags().StringVar(&key, "idempotency-key", "", "Required caller-owned UUID; never retried automatically")
+		cmd.Flags().StringVar(&revisionPreparationID, "revision-preparation-id", "", "Exact preparation UUID from task context; required with --predecessor")
+		cmd.Flags().StringVar(&revisionPreparationSHA256, "revision-preparation-sha256", "", "Exact preparation digest from task context; required with --predecessor")
 		cmd.RunE = func(cmd *cobra.Command, args []string) error {
 			var acknowledgement *api.RevisionAcknowledgement
-			if prepare {
+			{
 				hasID := cmd.Flags().Changed("revision-preparation-id")
 				hasSHA := cmd.Flags().Changed("revision-preparation-sha256")
 				if cmd.Flags().Changed("predecessor") != (hasID && hasSHA) || hasID != hasSHA {
-					return commandError{"invalid_arguments", "revision preparation ID and sha256 are both required with --predecessor and forbidden for initial preparation"}
+					return commandError{"invalid_arguments", "revision preparation ID and sha256 are both required with --predecessor and forbidden for initial submission"}
 				}
 				if hasID {
 					acknowledgement = &api.RevisionAcknowledgement{
@@ -58,16 +51,6 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 			if err != nil {
 				return err
 			}
-			if !prepare {
-				result, err := c.CreateSubmission(cmd.Context(), args[0], admission, packet)
-				if err != nil {
-					return err
-				}
-				if *output == "json" {
-					return writeSafeJSON(stdout, result.Raw)
-				}
-				return writeTaskContextFields(stdout, []contextField{{"Submission receipt (not acceptance)", result.Value}})
-			}
 			bad := commandError{"invalid_arguments", "--file must be a readable, nonempty regular ZIP of at most 500MiB"}
 			info, err := os.Stat(path)
 			if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > api.MaxSubmissionZipBytes {
@@ -78,7 +61,7 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 				return bad
 			}
 			defer file.Close()
-			result, err := c.PrepareSubmission(cmd.Context(), args[0], key, packet, acknowledgement, file)
+			result, err := c.SubmitSubmission(cmd.Context(), args[0], key, packet, acknowledgement, file)
 			if err != nil {
 				return err
 			}
@@ -87,7 +70,7 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 			}
 			receipt := result.Value
 			receipt.Feedback = nil // Printed below as readable intake feedback lines.
-			if err := writeTaskContextFields(stdout, []contextField{{"Preparation receipt (no Submission created)", receipt}}); err != nil {
+			if err := writeTaskContextFields(stdout, []contextField{{"Submission accepted for evaluation", receipt}}); err != nil {
 				return err
 			}
 			// Nonblocking intake findings stay visible after admission; they are
@@ -97,11 +80,7 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 					return err
 				}
 			}
-			if result.Value.Status == "ready" {
-				_, err = fmt.Fprintln(stdout, "Ready admission: submit explicitly with the same assignment and packet.")
-			} else {
-				_, err = fmt.Fprintln(stdout, "Not ready: inspect the returned status. Any manual replay must use the same key, ZIP bytes, assignment, packet and revision acknowledgement; this command never polls.")
-			}
+			_, err = fmt.Fprintln(stdout, "Initial checks passed. Evaluation is pending; use the operation ID or the same idempotency key to observe progress.")
 			return err
 		}
 		task.AddCommand(cmd)
diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py
index 7b67627aa..936cfa3de 100644
--- a/cli/tests/integration/test_submission_http.py
+++ b/cli/tests/integration/test_submission_http.py
@@ -11,18 +11,11 @@
 TASK = "018f0ebc-7966-7e8d-bc4d-1cae1e000010"
 ASSIGNMENT = "018f0ebc-7966-7e8d-bc4d-1cae1e000011"
 KEY = "018f0ebc-7966-7e8d-bc4d-1cae1e000012"
-PUT = "018f0ebc-7966-7e8d-bc4d-1cae1e000013"
-ADMISSION = "018f0ebc-7966-7e8d-bc4d-1cae1e000014"
+OPERATION = "018f0ebc-7966-7e8d-bc4d-1cae1e000013"
 SUBMISSION = "018f0ebc-7966-7e8d-bc4d-1cae1e000015"
 RUN = "018f0ebc-7966-7e8d-bc4d-1cae1e000016"
 REVISION_PREPARATION = "018f0ebc-7966-7e8d-bc4d-1cae1e000017"
 REVISION_DIGEST = "sha256:" + "a" * 64
-RECEIPT = {
-    "submission_id": SUBMISSION,
-    "submission_version": 1,
-    "admission_id": ADMISSION,
-    "evaluation_request_id": RUN,
-}
 HISTORY = {
     "id": SUBMISSION,
     "task_id": TASK,
@@ -64,10 +57,10 @@
 }
 
 
-def prepare_args(path):
+def submit_args(path):
     return (
         "task",
-        "prepare",
+        "submit",
         TASK,
         "--assignment",
         ASSIGNMENT,
@@ -80,20 +73,6 @@ def prepare_args(path):
     )
 
 
-def submit_args():
-    return (
-        "task",
-        "submit",
-        TASK,
-        "--assignment",
-        ASSIGNMENT,
-        "--admission",
-        ADMISSION,
-        "-o",
-        "json",
-    )
-
-
 INTAKE_FEEDBACK = [
     {
         "source": "workstream_default",
@@ -127,12 +106,16 @@ def submit_args():
 ]
 
 
-def preparation(status="stored_pending_verification"):
+def acceptance(replayed=False):
     return {
-        "put_attempt_id": PUT,
-        "admission_id": ADMISSION if status == "ready" else None,
-        "submission_bundle_preparation_status": status,
-        "replayed": status == "ready",
+        "operation_id": OPERATION,
+        "task_id": TASK,
+        "assignment_id": ASSIGNMENT,
+        "status": "accepted",
+        "accepted_at": "2026-10-14T10:00:00Z",
+        "task_status_at_acceptance": "evaluation_pending",
+        "processing_stage_at_acceptance": "finalization_pending",
+        "replayed": replayed,
         "pre_submission_results": INTAKE_FEEDBACK,
     }
 
@@ -141,17 +124,17 @@ def respond(response, value, status=200):
     response.update(status=status, body=json.dumps(value, ensure_ascii=False).encode())
 
 
-def test_explicit_prepare_replay_then_create_preserves_packet_and_bytes(cli, tmp_path):
+def test_explicit_submit_replay_preserves_packet_and_bytes(cli, tmp_path):
     path = tmp_path / "submission.zip"
     path.write_bytes(b"PK\x03\x04exact-archive")
     packet = ("--summary", "Completed work", "--attestation", "")
     with http_fixture() as (origin, response, requests):
-        for status in ("stored_pending_verification", "ready"):
-            respond(response, preparation(status), 202)
-            result = cli(origin, TOKEN, *prepare_args(path), *packet)
+        for replayed in (False, True):
+            respond(response, acceptance(replayed), 202)
+            result = cli(origin, TOKEN, *submit_args(path), *packet)
             assert result.returncode == 0, result.stderr
-            assert json.loads(result.stdout) == preparation(status)
-        assert len(requests) == 2
+            assert json.loads(result.stdout) == acceptance(replayed)
+        assert len(requests) == 2  # Only caller-requested replay.
         assert response["raw_commands"] == [path.read_bytes()] * 2
         for headers in response["request_headers"]:
             assert headers["X-Task-Assignment-Id"] == ASSIGNMENT
@@ -159,45 +142,28 @@ def test_explicit_prepare_replay_then_create_preserves_packet_and_bytes(cli, tmp
             assert headers["X-Contributor-Attestation"] == ""
             assert headers["Idempotency-Key"] == KEY
             assert headers["Content-Type"] == "application/zip"
-        respond(response, RECEIPT, 201)
-        for _ in range(2):
-            result = cli(origin, TOKEN, *submit_args(), *packet)
-            assert result.returncode == 0 and json.loads(result.stdout) == RECEIPT
-        assert len(requests) == 4  # Caller explicitly replayed; CLI never did.
-        assert response["commands"][-1] == (
-            "application/json",
-            None,
-            {
-                "assignment_id": ASSIGNMENT,
-                "admission_id": ADMISSION,
-                "summary": "Completed work",
-                "contributor_attestation": "",
-            },
-        )
-        assert requests[-1] == (
-            "POST",
-            f"/api/v1/tasks/{TASK}/submissions",
-            "Bearer " + TOKEN,
-        )
+        assert requests == [
+            ("POST", f"/api/v1/tasks/{TASK}/submissions", "Bearer " + TOKEN)
+        ] * 2
 
 
-def test_admitted_preparation_shows_nonblocking_intake_feedback(cli, tmp_path):
+def test_accepted_submission_shows_nonblocking_intake_feedback(cli, tmp_path):
     path = tmp_path / "submission.zip"
     path.write_bytes(b"PK\x03\x04feedback")
-    human = prepare_args(path)[:-2]
+    human = submit_args(path)[:-2]
     with http_fixture() as (origin, response, requests):
-        respond(response, preparation("ready"), 202)
+        respond(response, acceptance(), 202)
         result = cli(origin, TOKEN, *human)
         assert result.returncode == 0, result.stderr
         receipt_line = result.stdout.splitlines()[0]
-        assert receipt_line.startswith("Preparation receipt")
+        assert receipt_line.startswith("Submission accepted for evaluation")
         assert "pre_submission_results" not in receipt_line
         assert "Intake feedback: warning submission_summary_missing" in result.stdout
         assert (
             "Intake feedback: coverage_incomplete coverage.files results/vendor.bin: "
             "One file was not evaluated." in result.stdout
         )
-        # An admitted receipt cannot carry blocking results or omit its feedback.
+        # An accepted receipt cannot carry blocking results or omit its feedback.
         blocked_check = copy.deepcopy(INTAKE_FEEDBACK)
         blocked_check[0] |= {
             "status": "failed",
@@ -208,23 +174,23 @@ def test_admitted_preparation_shows_nonblocking_intake_feedback(cli, tmp_path):
         error_finding[2]["findings"][0]["level"] = "error"
         failed_member = copy.deepcopy(INTAKE_FEEDBACK)
         failed_member[2]["status"] = "failed"
-        missing = preparation("ready")
+        missing = acceptance()
         missing.pop("pre_submission_results")
         for invalid in (
-            preparation("ready") | {"pre_submission_results": blocked_check},
-            preparation("ready") | {"pre_submission_results": error_finding},
-            preparation("ready") | {"pre_submission_results": failed_member},
-            preparation("ready") | {"pre_submission_results": None},
+            acceptance() | {"pre_submission_results": blocked_check},
+            acceptance() | {"pre_submission_results": error_finding},
+            acceptance() | {"pre_submission_results": failed_member},
+            acceptance() | {"pre_submission_results": None},
             missing,
         ):
             respond(response, invalid, 202)
             assert_failure(
-                cli(origin, TOKEN, *prepare_args(path)), "invalid_api_response"
+                cli(origin, TOKEN, *submit_args(path)), "invalid_api_response"
             )
         assert len(requests) == 6
 
 
-def test_revision_prepare_requires_and_replays_exact_acknowledgement_headers(
+def test_revision_submit_requires_and_replays_exact_acknowledgement_headers(
     cli, tmp_path
 ):
     path = tmp_path / "revision.zip"
@@ -254,13 +220,13 @@ def test_revision_prepare_requires_and_replays_exact_acknowledgement_headers(
             ("--predecessor", SUBMISSION, *pair[:-1], "sha256:" + "A" * 64),
         ):
             assert_failure(
-                cli(origin, TOKEN, *prepare_args(path), *args), "invalid_arguments", 2
+                cli(origin, TOKEN, *submit_args(path), *args), "invalid_arguments", 2
             )
         assert requests == []
-        respond(response, preparation("ready"), 202)
+        respond(response, acceptance(), 202)
         for _ in range(2):
             result = cli(
-                origin, TOKEN, *prepare_args(path), "--predecessor", SUBMISSION, *pair
+                origin, TOKEN, *submit_args(path), "--predecessor", SUBMISSION, *pair
             )
             assert result.returncode == 0, result.stderr
         assert len(requests) == 2
@@ -268,40 +234,32 @@ def test_revision_prepare_requires_and_replays_exact_acknowledgement_headers(
             assert headers["X-Predecessor-Submission-Id"] == SUBMISSION
             assert headers["X-Revision-Preparation-Id"] == REVISION_PREPARATION
             assert headers["X-Revision-Preparation-Sha256"] == REVISION_DIGEST
-        respond(response, RECEIPT | {"submission_version": 2}, 201)
-        result = cli(origin, TOKEN, *submit_args(), "--predecessor", SUBMISSION)
-        assert result.returncode == 0, result.stderr
-        assert response["commands"][-1][2] == {
-            "assignment_id": ASSIGNMENT,
-            "predecessor_submission_id": SUBMISSION,
-            "admission_id": ADMISSION,
-        }
 
 
-def test_prepare_rejects_untransportable_packet_before_request(cli, tmp_path):
+def test_submit_rejects_untransportable_packet_before_request(cli, tmp_path):
     path = tmp_path / "submission.zip"
     path.write_bytes(b"zip")
     with http_fixture() as (origin, _, requests):
         for summary in ("é", "line\nbreak", " leading", "trailing ", "x" * 65537):
-            result = cli(origin, TOKEN, *prepare_args(path), "--summary", summary)
+            result = cli(origin, TOKEN, *submit_args(path), "--summary", summary)
             assert_failure(result, "invalid_arguments", 2)
         assert requests == []
 
 
-def test_prepare_detects_file_change_and_never_confirms_success(cli, tmp_path):
+def test_submit_detects_file_change_and_never_confirms_success(cli, tmp_path):
     path = tmp_path / "submission.zip"
     for changed in (b"original-appended", b"modified"):
         path.write_bytes(b"original")
         with http_fixture() as (origin, response, requests):
-            respond(response, preparation(), 202)
+            respond(response, acceptance(), 202)
             response["after_body"] = lambda: path.write_bytes(changed)
-            result = cli(origin, TOKEN, *prepare_args(path))
+            result = cli(origin, TOKEN, *submit_args(path))
             assert_failure(result, "submission_source_changed")
             assert json.loads(result.stderr)["error"]["outcome_unknown"] is True
             assert len(requests) == 1
 
 
-def test_preparation_rejects_empty_nonregular_and_oversized_sources_without_request(
+def test_submission_rejects_empty_nonregular_and_oversized_sources_without_request(
     cli, tmp_path
 ):
     empty, oversized, pipe = (
@@ -314,7 +272,7 @@ def test_preparation_rejects_empty_nonregular_and_oversized_sources_without_requ
     with http_fixture() as (origin, _, requests):
         for path in (empty, tmp_path, pipe, oversized):
             assert_failure(
-                cli(origin, TOKEN, *prepare_args(path)), "invalid_arguments", 2
+                cli(origin, TOKEN, *submit_args(path)), "invalid_arguments", 2
             )
         assert requests == []
 
@@ -323,7 +281,7 @@ def test_submission_uncertain_responses_are_not_retried(cli, tmp_path):
     path = tmp_path / "submission.zip"
     path.write_bytes(b"zip")
     with http_fixture() as (origin, response, requests):
-        for args in (prepare_args(path), submit_args()):
+        for args in (submit_args(path),):
             for drop, status, body in (
                 (True, 200, {}),
                 (False, 503, {}),
@@ -351,54 +309,45 @@ def test_submission_uncertain_responses_are_not_retried(cli, tmp_path):
                 assert len(requests) == before + 1
 
 
-def test_submission_receipts_fail_closed_but_preserve_uuid_identity_and_large_versions(
-    cli,
-):
+def test_submission_receipts_fail_closed_and_preserve_uuid_identity(cli, tmp_path):
+    path = tmp_path / "submission.zip"
+    path.write_bytes(b"zip")
     with http_fixture() as (origin, response, requests):
-        valid = RECEIPT | {
-            "admission_id": ADMISSION.replace("-", ""),
-            "submission_version": 2**80,
-        }
-        respond(response, valid, 201)
-        result = cli(origin, TOKEN, *submit_args())
+        valid = acceptance() | {"assignment_id": ASSIGNMENT.replace("-", "")}
+        respond(response, valid, 202)
+        result = cli(origin, TOKEN, *submit_args(path))
         assert result.returncode == 0 and json.loads(result.stdout) == valid
-        for change in (
-            {"admission_id": KEY},
-            {"submission_version": None},
-            {"submission_version": 0},
-            {"submission_id": "bad"},
-            {"evaluation_request_id": None},
+        changes = (
+            {"assignment_id": KEY},
+            {"task_id": KEY},
+            {"operation_id": "bad"},
+            {"accepted_at": "bad"},
+            {"status": "completed"},
+            {"task_status_at_acceptance": "accepted"},
+            {"processing_stage_at_acceptance": "post_pending"},
+            {"replayed": None},
+            {"submission_id": SUBMISSION},
             {"internal_url": "private"},
-        ):
-            respond(response, RECEIPT | change, 201)
-            result = cli(origin, TOKEN, *submit_args())
+        )
+        for change in changes:
+            respond(response, acceptance() | change, 202)
+            result = cli(origin, TOKEN, *submit_args(path))
             assert_failure(result, "invalid_api_response")
             assert json.loads(result.stderr)["error"]["outcome_unknown"] is True
-        assert len(requests) == 7
+        assert len(requests) == 1 + len(changes)
 
 
 def test_submission_posts_are_not_replayed_after_http2_goaway(cli, tmp_path):
     path = tmp_path / "submission.zip"
     path.write_bytes(b"zip-bytes")
-    for args, expected in (
-        (prepare_args(path), path.read_bytes()),
-        (submit_args(), None),
-    ):
-        with goaway_fixture(tmp_path) as (origin, env, bodies, connections):
-            result = cli(origin, TOKEN, *args, extra_env=env)
-            assert_failure(result, "service_unavailable")
-            assert json.loads(result.stderr)["error"]["outcome_unknown"] is True
-            assert connections == ["h2"] and len(bodies) == 1
-            if expected is not None:
-                assert bodies == [expected]
-            else:
-                assert json.loads(bodies[0]) == {
-                    "assignment_id": ASSIGNMENT,
-                    "admission_id": ADMISSION,
-                }
+    with goaway_fixture(tmp_path) as (origin, env, bodies, connections):
+        result = cli(origin, TOKEN, *submit_args(path), extra_env=env)
+        assert_failure(result, "service_unavailable")
+        assert json.loads(result.stderr)["error"]["outcome_unknown"] is True
+        assert connections == ["h2"] and bodies == [path.read_bytes()]
 
 
-def test_preparation_feedback_is_closed_safe_and_not_a_submission(cli, tmp_path):
+def test_submission_feedback_is_closed_safe_and_not_a_submission(cli, tmp_path):
     path = tmp_path / "submission.zip"
     path.write_bytes(b"zip")
     details = {
@@ -435,7 +384,7 @@ def test_preparation_feedback_is_closed_safe_and_not_a_submission(cli, tmp_path)
     }
     with http_fixture() as (origin, response, requests):
         respond(response, envelope, 422)
-        result = cli(origin, TOKEN, *prepare_args(path))
+        result = cli(origin, TOKEN, *submit_args(path))
         assert_failure(result, "pre_submission_checker_failed")
         error = json.loads(result.stderr)["error"]
         assert error["details"] == details and not error.get("outcome_unknown", False)
@@ -447,12 +396,12 @@ def test_preparation_feedback_is_closed_safe_and_not_a_submission(cli, tmp_path)
         ):
             respond(response, {"error": envelope["error"] | {"details": invalid}}, 422)
             assert_failure(
-                cli(origin, TOKEN, *prepare_args(path)), "invalid_api_response"
+                cli(origin, TOKEN, *submit_args(path)), "invalid_api_response"
             )
         reflected = copy.deepcopy(envelope)
         reflected["error"]["details"]["results"][0]["findings"][0]["message"] = TOKEN
         respond(response, reflected, 422)
-        assert_failure(cli(origin, TOKEN, *prepare_args(path)), "invalid_api_response")
+        assert_failure(cli(origin, TOKEN, *submit_args(path)), "invalid_api_response")
         assert len(requests) == 5
 
 
@@ -739,7 +688,7 @@ def test_submission_response_caps_reject_otherwise_valid_oversized_json(cli, tmp
     path.write_bytes(b"zip")
     cap = 2 * 1024 * 1024
     cases = (
-        (prepare_args(path), preparation(), 202),
+        (submit_args(path), acceptance(), 202),
         (("submission", "show", SUBMISSION, "-o", "json"), HISTORY, 200),
         (
             ("task", "submissions", TASK, "-o", "json"),
diff --git a/mcp_server/README.md b/mcp_server/README.md
index 4bfa4f3a8..09b40d8f5 100644
--- a/mcp_server/README.md
+++ b/mcp_server/README.md
@@ -68,9 +68,9 @@ An independently installed adapter exposing 132 tools under the caller's authori
   projections plus deliberate operator retry, reconciliation and registration.
 - Nine operator-artifact tools cover readiness, bindings, replicas, receipts,
   verification/recovery, admission usage and audit events.
-- Seventeen task-execution tools cover bounded preparation ZIPs, contributor and
+- Sixteen task-execution tools cover bounded submission ZIPs, contributor and
   manager task context, screen/release/claim, guide-document reads and
-  admission-backed submission creation/history.
+  submission acceptance and immutable history.
 - Twenty-three project, task-management, import, audit, service-actor and model
   operations complete the current public product catalogue. Task-import source
   content uses an 8 MiB exact-byte boundary; health routes remain operational
@@ -220,12 +220,12 @@ Task execution uses separate contributor and manager read tools so the adapter
 never chooses an authority path on the caller's behalf. Screen, release and claim
 require typed UUID idempotency keys. Claim atomically assigns and starts a ready
 task through one request, returning `in_progress` and the started assignment.
-Submission creation consumes caller-supplied admission and assignment
-identifiers and stays unkeyed because that is the current backend contract.
-Preparation accepts a bounded Base64 ZIP, decodes it once and forwards the
+Submission creation accepts a bounded Base64 ZIP, decodes it once and forwards the
 caller's typed assignment/key and optional submission or revision fields as the
-fixed backend headers. Revision preparation ID and digest must be supplied
-together. Workstream owns ZIP validation, pre-submit checks, replay and all task
+fixed backend headers. The raw-ZIP POST returns a `202` acceptance snapshot with
+an operation ID; formal Submission creation and evaluation continue durably.
+Revision preparation ID and digest are both required with a predecessor and
+forbidden for initial submission. Workstream owns ZIP validation, pre-submit checks, replay and all task
 state changes. A checker rejection is a normal safe tool failure; an unverified
 mutation success remains uncertain and is never retried automatically.
 
diff --git a/mcp_server/contracts/preparation_create.json b/mcp_server/contracts/preparation_create.json
deleted file mode 100644
index 1fd978a69..000000000
--- a/mcp_server/contracts/preparation_create.json
+++ /dev/null
@@ -1,509 +0,0 @@
-{
-  "canonical_sha256": "dbd53852bf5dfb9396b3b14b98fbb201692847e87d97b2de2a42f810d375f085",
-  "components": {
-    "schemas": {
-      "ApiError": {
-        "additionalProperties": false,
-        "description": "Canonical machine-readable API error.",
-        "properties": {
-          "code": {
-            "title": "Code",
-            "type": "string"
-          },
-          "correlation_id": {
-            "title": "Correlation Id",
-            "type": "string"
-          },
-          "details": {
-            "additionalProperties": true,
-            "title": "Details",
-            "type": "object"
-          },
-          "message": {
-            "title": "Message",
-            "type": "string"
-          },
-          "retryable": {
-            "title": "Retryable",
-            "type": "boolean"
-          }
-        },
-        "required": [
-          "code",
-          "message",
-          "details",
-          "correlation_id",
-          "retryable"
-        ],
-        "title": "ApiError",
-        "type": "object"
-      },
-      "ApiErrorResponse": {
-        "additionalProperties": false,
-        "description": "Canonical error plus additive legacy compatibility fields.",
-        "properties": {
-          "detail": {
-            "anyOf": [
-              {},
-              {
-                "type": "null"
-              }
-            ],
-            "title": "Detail"
-          },
-          "error": {
-            "$ref": "#/components/schemas/ApiError"
-          }
-        },
-        "required": [
-          "error"
-        ],
-        "title": "ApiErrorResponse",
-        "type": "object"
-      },
-      "SubmissionBundlePreparationResponse": {
-        "additionalProperties": false,
-        "description": "Bounded preparation state without provider or scratch coordinates.",
-        "properties": {
-          "admission_id": {
-            "anyOf": [
-              {
-                "format": "uuid",
-                "type": "string"
-              },
-              {
-                "type": "null"
-              }
-            ],
-            "title": "Admission Id"
-          },
-          "pre_submission_results": {
-            "items": {
-              "additionalProperties": true,
-              "type": "object"
-            },
-            "title": "Pre Submission Results",
-            "type": "array"
-          },
-          "put_attempt_id": {
-            "format": "uuid",
-            "title": "Put Attempt Id",
-            "type": "string"
-          },
-          "replayed": {
-            "title": "Replayed",
-            "type": "boolean"
-          },
-          "submission_bundle_preparation_status": {
-            "$ref": "#/components/schemas/SubmissionBundlePreparationStatus"
-          }
-        },
-        "required": [
-          "put_attempt_id",
-          "admission_id",
-          "submission_bundle_preparation_status",
-          "replayed",
-          "pre_submission_results"
-        ],
-        "title": "SubmissionBundlePreparationResponse",
-        "type": "object"
-      },
-      "SubmissionBundlePreparationStatus": {
-        "description": "Closed public state vocabulary for one ART preparation operation.",
-        "enum": [
-          "prepared",
-          "put_in_flight",
-          "object_confirmed",
-          "stored_pending_verification",
-          "observed_confirmed",
-          "acknowledgement_unknown",
-          "provider_unavailable",
-          "conflict",
-          "integrity_mismatch",
-          "missing",
-          "absent_replay_required",
-          "stale",
-          "ready"
-        ],
-        "title": "SubmissionBundlePreparationStatus",
-        "type": "string"
-      }
-    }
-  },
-  "operation": {
-    "description": "Run continuous ZIP preparation under fresh contributor authority.",
-    "operationId": "prepare_submission_bundle_api_v1_tasks__task_id__submission_bundle_preparations_post",
-    "parameters": [
-      {
-        "in": "path",
-        "name": "task_id",
-        "required": true,
-        "schema": {
-          "title": "Task Id",
-          "type": "string"
-        }
-      },
-      {
-        "in": "header",
-        "name": "X-Task-Assignment-Id",
-        "required": true,
-        "schema": {
-          "title": "X-Task-Assignment-Id",
-          "type": "string"
-        }
-      },
-      {
-        "in": "header",
-        "name": "Idempotency-Key",
-        "required": true,
-        "schema": {
-          "title": "Idempotency-Key",
-          "type": "string"
-        }
-      },
-      {
-        "in": "header",
-        "name": "X-Submission-Summary",
-        "required": false,
-        "schema": {
-          "anyOf": [
-            {
-              "type": "string"
-            },
-            {
-              "type": "null"
-            }
-          ],
-          "title": "X-Submission-Summary"
-        }
-      },
-      {
-        "in": "header",
-        "name": "X-Contributor-Attestation",
-        "required": false,
-        "schema": {
-          "anyOf": [
-            {
-              "type": "string"
-            },
-            {
-              "type": "null"
-            }
-          ],
-          "title": "X-Contributor-Attestation"
-        }
-      },
-      {
-        "in": "header",
-        "name": "X-Predecessor-Submission-Id",
-        "required": false,
-        "schema": {
-          "anyOf": [
-            {
-              "type": "string"
-            },
-            {
-              "type": "null"
-            }
-          ],
-          "title": "X-Predecessor-Submission-Id"
-        }
-      },
-      {
-        "in": "header",
-        "name": "X-Revision-Preparation-Id",
-        "required": false,
-        "schema": {
-          "anyOf": [
-            {
-              "type": "string"
-            },
-            {
-              "type": "null"
-            }
-          ],
-          "title": "X-Revision-Preparation-Id"
-        }
-      },
-      {
-        "in": "header",
-        "name": "X-Revision-Preparation-Sha256",
-        "required": false,
-        "schema": {
-          "anyOf": [
-            {
-              "type": "string"
-            },
-            {
-              "type": "null"
-            }
-          ],
-          "title": "X-Revision-Preparation-Sha256"
-        }
-      },
-      {
-        "in": "header",
-        "name": "X-Request-ID",
-        "required": false,
-        "schema": {
-          "format": "uuid",
-          "maxLength": 36,
-          "minLength": 36,
-          "type": "string"
-        }
-      },
-      {
-        "in": "header",
-        "name": "X-Correlation-ID",
-        "required": false,
-        "schema": {
-          "format": "uuid",
-          "maxLength": 36,
-          "minLength": 36,
-          "type": "string"
-        }
-      }
-    ],
-    "requestBody": {
-      "content": {
-        "application/zip": {
-          "schema": {
-            "format": "binary",
-            "type": "string"
-          }
-        }
-      },
-      "required": true
-    },
-    "responses": {
-      "202": {
-        "content": {
-          "application/json": {
-            "schema": {
-              "$ref": "#/components/schemas/SubmissionBundlePreparationResponse"
-            }
-          }
-        },
-        "description": "Successful Response",
-        "headers": {
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      },
-      "400": {
-        "content": {
-          "application/json": {
-            "schema": {
-              "$ref": "#/components/schemas/ApiErrorResponse"
-            }
-          }
-        },
-        "description": "Invalid request.",
-        "headers": {
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      },
-      "401": {
-        "content": {
-          "application/json": {
-            "schema": {
-              "$ref": "#/components/schemas/ApiErrorResponse"
-            }
-          }
-        },
-        "description": "Authentication failed.",
-        "headers": {
-          "WWW-Authenticate": {
-            "schema": {
-              "type": "string"
-            }
-          },
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      },
-      "403": {
-        "content": {
-          "application/json": {
-            "schema": {
-              "$ref": "#/components/schemas/ApiErrorResponse"
-            }
-          }
-        },
-        "description": "Permission denied.",
-        "headers": {
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      },
-      "404": {
-        "description": "Task or contributor authority unavailable",
-        "headers": {
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      },
-      "409": {
-        "description": "Preparation context or replay conflicts",
-        "headers": {
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      },
-      "422": {
-        "description": "Invalid ZIP or bounded pre-submission checker feedback",
-        "headers": {
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      },
-      "500": {
-        "content": {
-          "application/json": {
-            "schema": {
-              "$ref": "#/components/schemas/ApiErrorResponse"
-            }
-          }
-        },
-        "description": "Internal server error.",
-        "headers": {
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      },
-      "503": {
-        "description": "Preparation custody or infrastructure unavailable",
-        "headers": {
-          "X-Correlation-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          },
-          "X-Request-ID": {
-            "required": true,
-            "schema": {
-              "format": "uuid",
-              "type": "string"
-            }
-          }
-        }
-      }
-    },
-    "security": [
-      {
-        "HTTPBearer": []
-      }
-    ],
-    "summary": "Prepare Submission Bundle",
-    "tags": [
-      "tasks"
-    ],
-    "x-workstream-action-id": "artifact.submission_bundle.prepare"
-  },
-  "schema_version": 1,
-  "source": {
-    "method": "POST",
-    "openapi_version": "3.1.0",
-    "path": "/api/v1/tasks/{task_id}/submission-bundle-preparations",
-    "repository_sha": "f0431385573eb53353c5ffc3c6cdb6a93d206b73"
-  }
-}
diff --git a/mcp_server/contracts/submission_create.json b/mcp_server/contracts/submission_create.json
index fde0c91ea..0b9b4da40 100644
--- a/mcp_server/contracts/submission_create.json
+++ b/mcp_server/contracts/submission_create.json
@@ -1,96 +1,7 @@
 {
-  "canonical_sha256": "1a81a3241210182829f40a72634eae30189abe5aaf983f8530bbd0adb46f4d0b",
+  "canonical_sha256": "024903204b1e82816bd0b9f9cdfcf3b5336e91d967840a6d411b4bc13aa91d75",
   "components": {
     "schemas": {
-      "AdmissionBackedSubmissionCreate": {
-        "additionalProperties": false,
-        "description": "Contributor packet and selectors for the canonical ready-admission POST.",
-        "properties": {
-          "admission_id": {
-            "format": "uuid",
-            "title": "Admission Id",
-            "type": "string"
-          },
-          "assignment_id": {
-            "format": "uuid",
-            "title": "Assignment Id",
-            "type": "string"
-          },
-          "contributor_attestation": {
-            "anyOf": [
-              {
-                "type": "string"
-              },
-              {
-                "type": "null"
-              }
-            ],
-            "title": "Contributor Attestation"
-          },
-          "predecessor_submission_id": {
-            "anyOf": [
-              {
-                "format": "uuid",
-                "type": "string"
-              },
-              {
-                "type": "null"
-              }
-            ],
-            "title": "Predecessor Submission Id"
-          },
-          "summary": {
-            "anyOf": [
-              {
-                "type": "string"
-              },
-              {
-                "type": "null"
-              }
-            ],
-            "title": "Summary"
-          }
-        },
-        "required": [
-          "admission_id",
-          "assignment_id"
-        ],
-        "title": "AdmissionBackedSubmissionCreate",
-        "type": "object"
-      },
-      "AdmissionBackedSubmissionResponse": {
-        "additionalProperties": false,
-        "description": "Stable Workstream result without provider or scratch coordinates.",
-        "properties": {
-          "admission_id": {
-            "format": "uuid",
-            "title": "Admission Id",
-            "type": "string"
-          },
-          "evaluation_request_id": {
-            "format": "uuid",
-            "title": "Evaluation Request Id",
-            "type": "string"
-          },
-          "submission_id": {
-            "format": "uuid",
-            "title": "Submission Id",
-            "type": "string"
-          },
-          "submission_version": {
-            "title": "Submission Version",
-            "type": "integer"
-          }
-        },
-        "required": [
-          "submission_id",
-          "submission_version",
-          "admission_id",
-          "evaluation_request_id"
-        ],
-        "title": "AdmissionBackedSubmissionResponse",
-        "type": "object"
-      },
       "ApiError": {
         "additionalProperties": false,
         "description": "Canonical machine-readable API error.",
@@ -149,12 +60,78 @@
         ],
         "title": "ApiErrorResponse",
         "type": "object"
+      },
+      "SubmissionAcceptedResponse": {
+        "additionalProperties": false,
+        "description": "Stable T4 snapshot; Submission/evaluation IDs do not exist until T5.",
+        "properties": {
+          "accepted_at": {
+            "format": "date-time",
+            "title": "Accepted At",
+            "type": "string"
+          },
+          "assignment_id": {
+            "format": "uuid",
+            "title": "Assignment Id",
+            "type": "string"
+          },
+          "operation_id": {
+            "format": "uuid",
+            "title": "Operation Id",
+            "type": "string"
+          },
+          "pre_submission_results": {
+            "items": {
+              "additionalProperties": true,
+              "type": "object"
+            },
+            "title": "Pre Submission Results",
+            "type": "array"
+          },
+          "processing_stage_at_acceptance": {
+            "const": "finalization_pending",
+            "title": "Processing Stage At Acceptance",
+            "type": "string"
+          },
+          "replayed": {
+            "title": "Replayed",
+            "type": "boolean"
+          },
+          "status": {
+            "const": "accepted",
+            "title": "Status",
+            "type": "string"
+          },
+          "task_id": {
+            "format": "uuid",
+            "title": "Task Id",
+            "type": "string"
+          },
+          "task_status_at_acceptance": {
+            "const": "evaluation_pending",
+            "title": "Task Status At Acceptance",
+            "type": "string"
+          }
+        },
+        "required": [
+          "operation_id",
+          "task_id",
+          "assignment_id",
+          "status",
+          "accepted_at",
+          "task_status_at_acceptance",
+          "processing_stage_at_acceptance",
+          "replayed",
+          "pre_submission_results"
+        ],
+        "title": "SubmissionAcceptedResponse",
+        "type": "object"
       }
     }
   },
   "operation": {
-    "description": "Consume one verified admission through the existing atomic TASK writer.",
-    "operationId": "create_admission_backed_submission_api_v1_tasks__task_id__submissions_post",
+    "description": "Acknowledge only committed acceptance, with no fabricated T5 identifiers.",
+    "operationId": "submit_source_api_v1_tasks__task_id__submissions_post",
     "parameters": [
       {
         "in": "path",
@@ -166,6 +143,69 @@
           "type": "string"
         }
       },
+      {
+        "in": "header",
+        "name": "Idempotency-Key",
+        "required": true,
+        "schema": {
+          "format": "uuid",
+          "type": "string"
+        }
+      },
+      {
+        "in": "header",
+        "name": "X-Task-Assignment-Id",
+        "required": true,
+        "schema": {
+          "format": "uuid",
+          "type": "string"
+        }
+      },
+      {
+        "in": "header",
+        "name": "X-Submission-Summary",
+        "required": false,
+        "schema": {
+          "maxLength": 65536,
+          "type": "string"
+        }
+      },
+      {
+        "in": "header",
+        "name": "X-Contributor-Attestation",
+        "required": false,
+        "schema": {
+          "maxLength": 65536,
+          "type": "string"
+        }
+      },
+      {
+        "in": "header",
+        "name": "X-Predecessor-Submission-Id",
+        "required": false,
+        "schema": {
+          "format": "uuid",
+          "type": "string"
+        }
+      },
+      {
+        "in": "header",
+        "name": "X-Revision-Preparation-Id",
+        "required": false,
+        "schema": {
+          "format": "uuid",
+          "type": "string"
+        }
+      },
+      {
+        "in": "header",
+        "name": "X-Revision-Preparation-Sha256",
+        "required": false,
+        "schema": {
+          "pattern": "^sha256:[0-9a-f]{64}$",
+          "type": "string"
+        }
+      },
       {
         "in": "header",
         "name": "X-Request-ID",
@@ -191,20 +231,21 @@
     ],
     "requestBody": {
       "content": {
-        "application/json": {
+        "application/zip": {
           "schema": {
-            "$ref": "#/components/schemas/AdmissionBackedSubmissionCreate"
+            "format": "binary",
+            "type": "string"
           }
         }
       },
       "required": true
     },
     "responses": {
-      "201": {
+      "202": {
         "content": {
           "application/json": {
             "schema": {
-              "$ref": "#/components/schemas/AdmissionBackedSubmissionResponse"
+              "$ref": "#/components/schemas/SubmissionAcceptedResponse"
             }
           }
         },
@@ -310,7 +351,26 @@
         }
       },
       "404": {
-        "description": "Submission or contributor authority unavailable",
+        "description": "Task or contributor authority unavailable",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "408": {
+        "description": "Upload idle or total deadline expired",
         "headers": {
           "X-Correlation-ID": {
             "required": true,
@@ -329,7 +389,45 @@
         }
       },
       "409": {
-        "description": "Admission, predecessor or packet conflicts",
+        "description": "Operation, idempotency or governed revision conflict",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "413": {
+        "description": "Raw ZIP exceeds the permitted limit",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "415": {
+        "description": "Unsupported media type or content encoding",
         "headers": {
           "X-Correlation-ID": {
             "required": true,
@@ -348,7 +446,26 @@
         }
       },
       "422": {
-        "description": "Invalid submission packet",
+        "description": "Invalid packet or bounded pre-submission QC feedback",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "429": {
+        "description": "Submission capacity exhausted",
         "headers": {
           "X-Correlation-ID": {
             "required": true,
@@ -393,7 +510,7 @@
         }
       },
       "503": {
-        "description": "Submission infrastructure unavailable",
+        "description": "Infrastructure unavailable or acceptance outcome unknown",
         "headers": {
           "X-Correlation-ID": {
             "required": true,
@@ -417,7 +534,7 @@
         "HTTPBearer": []
       }
     ],
-    "summary": "Create Admission Backed Submission",
+    "summary": "Submit Source",
     "tags": [
       "tasks"
     ],
@@ -428,6 +545,6 @@
     "method": "POST",
     "openapi_version": "3.1.0",
     "path": "/api/v1/tasks/{task_id}/submissions",
-    "repository_sha": "f0431385573eb53353c5ffc3c6cdb6a93d206b73"
+    "repository_sha": "53d369b4ceb9c19f621d95ece18e6bb91284b651"
   }
 }
diff --git a/mcp_server/pyproject.toml b/mcp_server/pyproject.toml
index 73c443c3a..60af89165 100644
--- a/mcp_server/pyproject.toml
+++ b/mcp_server/pyproject.toml
@@ -126,7 +126,6 @@ packages = ["workstream_mcp"]
 "contracts/artifact_recovery_attempt_get.json" = "workstream_mcp/contracts/artifact_recovery_attempt_get.json"
 "contracts/artifact_admission_usage_get.json" = "workstream_mcp/contracts/artifact_admission_usage_get.json"
 "contracts/artifact_audit_events_list.json" = "workstream_mcp/contracts/artifact_audit_events_list.json"
-"contracts/preparation_create.json" = "workstream_mcp/contracts/preparation_create.json"
 "contracts/preparations_list.json" = "workstream_mcp/contracts/preparations_list.json"
 "contracts/preparation_get.json" = "workstream_mcp/contracts/preparation_get.json"
 "contracts/task_get.json" = "workstream_mcp/contracts/task_get.json"
diff --git a/mcp_server/tests/test_task_execution.py b/mcp_server/tests/test_task_execution.py
index 02c16ae8f..f37265bbf 100644
--- a/mcp_server/tests/test_task_execution.py
+++ b/mcp_server/tests/test_task_execution.py
@@ -21,15 +21,14 @@
 PREPARATION_ID = "019a2a00-0000-7000-8000-000000000704"
 DOCUMENT_ID = "019a2a00-0000-7000-8000-000000000705"
 SUBMISSION_ID = "019a2a00-0000-7000-8000-000000000706"
-ADMISSION_ID = "019a2a00-0000-7000-8000-000000000707"
 KEY = "019a2a00-0000-7000-8000-000000000708"
-PUT_ATTEMPT_ID = "019a2a00-0000-7000-8000-000000000709"
+OPERATION_ID = "019a2a00-0000-7000-8000-000000000709"
 Adapter = tuple[TestClient, list[httpx.Request], dict[str, Any]]
 
 
 def _arguments(name: str) -> dict[str, Any]:
     values: dict[str, dict[str, Any]] = {
-        "preparation_create": {
+        "submission_create": {
             "task_id": TASK_ID,
             "assignment_id": ASSIGNMENT_ID,
             "zip_base64": base64.b64encode(b"PK\x03\x04fixture").decode(),
@@ -49,10 +48,6 @@ def _arguments(name: str) -> dict[str, Any]:
             "task_id": TASK_ID,
             "document_id": DOCUMENT_ID,
         },
-        "submission_create": {
-            "task_id": TASK_ID,
-            "body": {"admission_id": ADMISSION_ID, "assignment_id": ASSIGNMENT_ID},
-        },
         "task_submissions_list": {"task_id": TASK_ID, "limit": 25},
         "submission_get": {"submission_id": SUBMISSION_ID},
         "management_task_submissions_list": {
@@ -77,8 +72,6 @@ def _arguments(name: str) -> dict[str, Any]:
 
 
 def _bound_response(name: str) -> dict[str, Any]:
-    if name == "preparation_create":
-        return {"put_attempt_id": PUT_ATTEMPT_ID}
     if name in {"preparations_list", "task_submissions_list", "management_task_submissions_list"}:
         return {"items": [], "next_cursor": None}
     if name == "preparation_get":
@@ -102,7 +95,7 @@ def _bound_response(name: str) -> dict[str, Any]:
             "sha256": "sha256:" + "0" * 64,
         }
     if name == "submission_create":
-        return {"admission_id": ADMISSION_ID}
+        return {"task_id": TASK_ID, "assignment_id": ASSIGNMENT_ID}
     if name in {"submission_get", "management_submission_get"}:
         return {"id": SUBMISSION_ID}
     if name == "management_task_work_context_get":
@@ -115,6 +108,20 @@ def _bound_response(name: str) -> dict[str, Any]:
     raise AssertionError(name)
 
 
+def _acceptance() -> dict[str, Any]:
+    return {
+        "operation_id": OPERATION_ID,
+        "task_id": TASK_ID,
+        "assignment_id": ASSIGNMENT_ID,
+        "status": "accepted",
+        "accepted_at": "2026-11-16T12:00:00Z",
+        "task_status_at_acceptance": "evaluation_pending",
+        "processing_stage_at_acceptance": "finalization_pending",
+        "replayed": False,
+        "pre_submission_results": [],
+    }
+
+
 def _catalogue(client: TestClient) -> list[dict[str, Any]]:
     response = client.post(
         "/mcp",
@@ -141,6 +148,7 @@ def test_task_execution_catalogue_is_exact_closed_and_does_not_dispatch(
         ).validate(_arguments(name))
         assert tool["inputSchema"]["additionalProperties"] is False
         assert tool["annotations"]["readOnlyHint"] is False
+    assert "workstream_preparation_create" not in catalogue
     assert received == []
 
 
@@ -160,7 +168,7 @@ async def request(_: WorkstreamGateway, *args: Any, **kwargs: Any) -> GatewayRes
 
     monkeypatch.setattr(WorkstreamGateway, "_request", request)
     arguments = _arguments(name)
-    upload = b"PK\x03\x04fixture" if name == "preparation_create" else None
+    upload = b"PK\x03\x04fixture" if name == "submission_create" else None
     async with httpx.AsyncClient(base_url="http://workstream.test") as client:
         result = await WorkstreamGateway(
             Settings(api_url="http://127.0.0.1:8000"), client
@@ -254,19 +262,13 @@ async def request_binary(
     }
 
 
-def test_preparation_upload_decodes_once_and_forwards_only_reviewed_headers(
+def test_submission_upload_decodes_once_and_forwards_only_reviewed_headers(
     adapter: Adapter,
 ) -> None:
     client, received, upstream = adapter
     content = b"PK\x03\x04fixture"
     upstream["status"] = 202
-    upstream["json"] = {
-        "put_attempt_id": PUT_ATTEMPT_ID,
-        "admission_id": None,
-        "submission_bundle_preparation_status": "put_in_flight",
-        "replayed": False,
-        "pre_submission_results": [],
-    }
+    upstream["json"] = _acceptance()
     response = client.post(
         "/mcp",
         headers={
@@ -279,8 +281,8 @@ def test_preparation_upload_decodes_once_and_forwards_only_reviewed_headers(
             "id": 1,
             "method": "tools/call",
             "params": {
-                "name": "workstream_preparation_create",
-                "arguments": _arguments("preparation_create"),
+                "name": "workstream_submission_create",
+                "arguments": _arguments("submission_create"),
             },
         },
     )
@@ -295,8 +297,8 @@ def test_preparation_upload_decodes_once_and_forwards_only_reviewed_headers(
     assert request.headers["x-contributor-attestation"] == "reviewed"
 
 
-def test_preparation_bundle_contract_fits_inside_mcp_ingress() -> None:
-    schema = TASK_EXECUTION_INPUT_SCHEMAS["preparation_create"]
+def test_submission_bundle_contract_fits_inside_mcp_ingress() -> None:
+    schema = TASK_EXECUTION_INPUT_SCHEMAS["submission_create"]
     assert schema["properties"]["zip_base64"]["maxLength"] == (
         SUBMISSION_BUNDLE_MAX_BASE64_CHARS
     )
@@ -306,11 +308,11 @@ def test_preparation_bundle_contract_fits_inside_mcp_ingress() -> None:
 
 
 @pytest.mark.parametrize("field", ["summary", "contributor_attestation"])
-def test_preparation_header_text_rejects_trailing_newline_before_dispatch(
+def test_submission_header_text_rejects_trailing_newline_before_dispatch(
     adapter: Adapter, field: str
 ) -> None:
     client, received, _ = adapter
-    arguments = {**_arguments("preparation_create"), field: "ready\n"}
+    arguments = {**_arguments("submission_create"), field: "ready\n"}
     response = client.post(
         "/mcp",
         headers={
@@ -322,7 +324,7 @@ def test_preparation_header_text_rejects_trailing_newline_before_dispatch(
             "id": 1,
             "method": "tools/call",
             "params": {
-                "name": "workstream_preparation_create",
+                "name": "workstream_submission_create",
                 "arguments": arguments,
             },
         },
@@ -337,7 +339,7 @@ def test_preparation_header_text_rejects_trailing_newline_before_dispatch(
 def test_incomplete_revision_preparation_selector_never_dispatches(adapter: Adapter) -> None:
     client, received, _ = adapter
     arguments = {
-        **_arguments("preparation_create"),
+        **_arguments("submission_create"),
         "revision_preparation_id": PREPARATION_ID,
     }
     response = client.post(
@@ -351,7 +353,7 @@ def test_incomplete_revision_preparation_selector_never_dispatches(adapter: Adap
             "id": 1,
             "method": "tools/call",
             "params": {
-                "name": "workstream_preparation_create",
+                "name": "workstream_submission_create",
                 "arguments": arguments,
             },
         },
@@ -385,8 +387,8 @@ def test_pre_submit_checker_failure_is_a_safe_tool_outcome(adapter: Adapter) ->
             "id": 1,
             "method": "tools/call",
             "params": {
-                "name": "workstream_preparation_create",
-                "arguments": _arguments("preparation_create"),
+                "name": "workstream_submission_create",
+                "arguments": _arguments("submission_create"),
             },
         },
     )
@@ -414,3 +416,52 @@ async def request(_: WorkstreamGateway, *args: Any, **kwargs: Any) -> GatewayRes
 
     assert result.failure is not None
     assert result.failure.error == "workstream_execution_uncertain"
+
+
+@pytest.mark.parametrize("change", [
+    {"task_id": PROJECT_ID},
+    {"assignment_id": PROJECT_ID},
+    {"operation_id": "not-a-uuid"},
+    {"accepted_at": "not-a-timestamp"},
+    {"status": "completed"},
+    {"processing_stage_at_acceptance": "post_pending"},
+    {"replayed": None},
+    {"submission_id": SUBMISSION_ID},
+])
+def test_submission_acceptance_refuses_substitution_and_invalid_snapshots(
+    adapter: Adapter, change: dict[str, Any]
+) -> None:
+    client, received, upstream = adapter
+    upstream["status"] = 202
+    upstream["json"] = _acceptance() | change
+    response = client.post(
+        "/mcp",
+        headers={"authorization": "Bearer fixture-token",
+                 "accept": "application/json, text/event-stream"},
+        json={"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+              "params": {"name": "workstream_submission_create",
+                         "arguments": _arguments("submission_create")}},
+    )
+    result = response.json()["result"]
+    assert result["isError"] is True
+    assert result["structuredContent"]["error"] == "workstream_execution_uncertain"
+    assert len(received) == 1
+
+
+@pytest.mark.parametrize("fields", [
+    {"predecessor_submission_id": SUBMISSION_ID},
+    {"revision_preparation_id": PREPARATION_ID,
+     "revision_preparation_sha256": "sha256:" + "a" * 64},
+])
+def test_submission_revision_requires_predecessor_and_both_acknowledgements(
+    fields: dict[str, Any],
+) -> None:
+    validator = Draft202012Validator(
+        TASK_EXECUTION_INPUT_SCHEMAS["submission_create"], format_checker=FormatChecker()
+    )
+    assert not validator.is_valid(_arguments("submission_create") | fields)
+    assert validator.is_valid(_arguments("submission_create") | {
+        "predecessor_submission_id": SUBMISSION_ID,
+        "revision_preparation_id": PREPARATION_ID,
+        "revision_preparation_sha256": "sha256:" + "a" * 64,
+    })
diff --git a/mcp_server/tests/test_task_execution_contract_drift.py b/mcp_server/tests/test_task_execution_contract_drift.py
index 3dfeab72e..1480f10b0 100644
--- a/mcp_server/tests/test_task_execution_contract_drift.py
+++ b/mcp_server/tests/test_task_execution_contract_drift.py
@@ -69,7 +69,7 @@ def test_task_execution_contract_is_tamper_evident_and_matches_fixed_route(
 
 
 def test_exact_task_execution_contract_set_is_reviewed() -> None:
-    assert len(TASK_EXECUTION_CONTRACT_NAMES) == 17
+    assert len(TASK_EXECUTION_CONTRACT_NAMES) == 16
     assert set(TASK_EXECUTION_CONTRACT_NAMES) == set(TASK_EXECUTION_OPERATIONS)
 
 
diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py
index 31bd1b0cd..6c96a86be 100644
--- a/mcp_server/workstream_mcp/http_gateway.py
+++ b/mcp_server/workstream_mcp/http_gateway.py
@@ -363,11 +363,6 @@
 )
 
 TASK_EXECUTION_OPERATIONS = {
-    "preparation_create": (
-        "POST",
-        "/api/v1/tasks/{task_id}/submission-bundle-preparations",
-        202,
-    ),
     "preparations_list": (
         "GET",
         "/api/v1/tasks/{task_id}/submission-bundle-preparations",
@@ -393,7 +388,7 @@
         "/api/v1/tasks/{task_id}/guide/documents/{document_id}/content",
         200,
     ),
-    "submission_create": ("POST", "/api/v1/tasks/{task_id}/submissions", 201),
+    "submission_create": ("POST", "/api/v1/tasks/{task_id}/submissions", 202),
     "task_submissions_list": ("GET", "/api/v1/tasks/{task_id}/submissions", 200),
     "submission_get": ("GET", "/api/v1/submissions/{submission_id}", 200),
     "management_task_submissions_list": (
@@ -419,7 +414,6 @@
 }
 _TASK_EXECUTION_MUTATIONS = frozenset(
     {
-        "preparation_create",
         "task_screen",
         "task_release",
         "task_claim",
@@ -1511,7 +1505,7 @@ async def task_execution_operation(
             if value is not None and key not in excluded
         }
         extra_headers: dict[str, str] | None = None
-        if name == "preparation_create":
+        if name == "submission_create":
             if upload is None:
                 return GatewayResult(failure=SafeFailure("invalid_tool_input", status=400))
             extra_headers = {"X-Task-Assignment-Id": arguments["assignment_id"]}
@@ -1539,10 +1533,10 @@ async def task_execution_operation(
             expected_status=expected_status,
             mutation=mutation,
             raw_body=upload,
-            content_type="application/zip" if name == "preparation_create" else None,
+            content_type="application/zip" if name == "submission_create" else None,
             operation_timeout_seconds=(
                 self._settings.document_timeout_seconds
-                if name == "preparation_create"
+                if name == "submission_create"
                 else None
             ),
             extra_headers=extra_headers,
@@ -1565,15 +1559,6 @@ def _task_execution_response_matches(
     ) -> bool:
         task_id = arguments.get("task_id")
         project_id = arguments.get("project_id")
-        if name == "preparation_create":
-            put_attempt_id = data.get("put_attempt_id")
-            if not isinstance(put_attempt_id, str):
-                return False
-            try:
-                UUID(put_attempt_id)
-            except ValueError:
-                return False
-            return True
         if name in {"submission_get", "management_submission_get"}:
             return cls._same_uuid(data.get("id"), arguments["submission_id"])
         if not isinstance(task_id, str):
@@ -1616,8 +1601,9 @@ def _task_execution_response_matches(
                 )
             )
         if name == "submission_create":
-            body = arguments["body"]
-            return cls._same_uuid(data.get("admission_id"), body["admission_id"])
+            return cls._fields_match(
+                data, {"task_id": task_id, "assignment_id": arguments["assignment_id"]}
+            )
         if name in {"task_submissions_list", "management_task_submissions_list"}:
             return cls._items_match(data, {"task_id": task_id}, unique="id")
         if name == "management_task_submission_requirements_get":
diff --git a/mcp_server/workstream_mcp/schemas.py b/mcp_server/workstream_mcp/schemas.py
index 4fa144098..652fa0dfc 100644
--- a/mcp_server/workstream_mcp/schemas.py
+++ b/mcp_server/workstream_mcp/schemas.py
@@ -867,37 +867,6 @@ def _task_transition_input() -> dict[str, Any]:
 
 
 TASK_EXECUTION_INPUT_SCHEMAS: dict[str, dict[str, Any]] = {
-    "preparation_create": {
-        "type": "object",
-        "properties": {
-            "task_id": _UUID_INPUT,
-            "assignment_id": _UUID_INPUT,
-            "zip_base64": {
-                "type": "string",
-                "minLength": 4,
-                "maxLength": SUBMISSION_BUNDLE_MAX_BASE64_CHARS,
-                "pattern": r"^[A-Za-z0-9+/]*={0,2}$",
-            },
-            "idempotency_key": _IDEMPOTENCY_KEY_INPUT,
-            "summary": _ASCII_PACKET_TEXT,
-            "contributor_attestation": _ASCII_PACKET_TEXT,
-            "predecessor_submission_id": _UUID_INPUT,
-            "revision_preparation_id": _UUID_INPUT,
-            "revision_preparation_sha256": _SHA256_INPUT,
-        },
-        "required": ["task_id", "assignment_id", "zip_base64", "idempotency_key"],
-        "allOf": [
-            {
-                "if": {"required": ["revision_preparation_id"]},
-                "then": {"required": ["revision_preparation_sha256"]},
-            },
-            {
-                "if": {"required": ["revision_preparation_sha256"]},
-                "then": {"required": ["revision_preparation_id"]},
-            },
-        ],
-        "additionalProperties": False,
-    },
     "preparations_list": {
         "type": "object",
         "properties": {
@@ -944,20 +913,35 @@ def _task_transition_input() -> dict[str, Any]:
         "type": "object",
         "properties": {
             "task_id": _UUID_INPUT,
-            "body": {
-                "type": "object",
-                "properties": {
-                    "admission_id": _UUID_INPUT,
-                    "assignment_id": _UUID_INPUT,
-                    "predecessor_submission_id": {"anyOf": [_UUID_INPUT, {"type": "null"}]},
-                    "summary": {"type": ["string", "null"]},
-                    "contributor_attestation": {"type": ["string", "null"]},
-                },
-                "required": ["admission_id", "assignment_id"],
-                "additionalProperties": False,
+            "assignment_id": _UUID_INPUT,
+            "zip_base64": {
+                "type": "string",
+                "minLength": 4,
+                "maxLength": SUBMISSION_BUNDLE_MAX_BASE64_CHARS,
+                "pattern": r"^[A-Za-z0-9+/]*={0,2}$",
             },
+            "idempotency_key": _IDEMPOTENCY_KEY_INPUT,
+            "summary": _ASCII_PACKET_TEXT,
+            "contributor_attestation": _ASCII_PACKET_TEXT,
+            "predecessor_submission_id": _UUID_INPUT,
+            "revision_preparation_id": _UUID_INPUT,
+            "revision_preparation_sha256": _SHA256_INPUT,
         },
-        "required": ["task_id", "body"],
+        "required": ["task_id", "assignment_id", "zip_base64", "idempotency_key"],
+        "allOf": [
+            {
+                "if": {"required": ["predecessor_submission_id"]},
+                "then": {"required": ["revision_preparation_id", "revision_preparation_sha256"]},
+            },
+            {
+                "if": {"required": ["revision_preparation_id"]},
+                "then": {"required": ["revision_preparation_sha256", "predecessor_submission_id"]},
+            },
+            {
+                "if": {"required": ["revision_preparation_sha256"]},
+                "then": {"required": ["revision_preparation_id", "predecessor_submission_id"]},
+            },
+        ],
         "additionalProperties": False,
     },
     "task_submissions_list": {
diff --git a/mcp_server/workstream_mcp/tools/task_execution.py b/mcp_server/workstream_mcp/tools/task_execution.py
index cc677b52b..cfeb9cc47 100644
--- a/mcp_server/workstream_mcp/tools/task_execution.py
+++ b/mcp_server/workstream_mcp/tools/task_execution.py
@@ -23,7 +23,6 @@
 )
 
 _DESCRIPTIONS = {
-    "preparation_create": "Prepare and check one bounded submission ZIP.",
     "preparations_list": "List submission-bundle preparations for one task.",
     "preparation_get": "Read one submission-bundle preparation.",
     "task_get": "Read one task available to the current contributor.",
@@ -33,7 +32,7 @@
     "task_claim": "Claim and start one ready task atomically.",
     "task_work_context_get": "Read the current contributor work context for one task.",
     "task_guide_document_content_get": "Read one assigned guide document as bounded bytes.",
-    "submission_create": "Create one submission from a ready admission.",
+    "submission_create": "Upload one ZIP for initial checks and durable evaluation acceptance.",
     "task_submissions_list": "List the current contributor's submissions for one task.",
     "submission_get": "Read one submission visible to the current contributor.",
     "management_task_submissions_list": "List submissions for one managed project task.",
@@ -49,7 +48,6 @@
 TOOL_NAMES = tuple(f"workstream_{name}" for name in _DESCRIPTIONS)
 _MUTATIONS = frozenset(
     {
-        "preparation_create",
         "task_screen",
         "task_release",
         "task_claim",
@@ -113,7 +111,7 @@ async def invoke(
         return adapter_failure("invalid_tool_input", status=400)
 
     upload: bytes | None = None
-    if name == "preparation_create":
+    if name == "submission_create":
         upload = _decode_bundle(arguments)
         if upload is None:
             return adapter_failure("invalid_tool_input", status=400)

From 121f8dfbb71ea24b2ffb75ee1ac735fffe64ffff Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 14:18:07 +0100
Subject: [PATCH 156/513] fix(submission): normalize ASGI frames and reconcile
 MCP catalogue

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 76 +++++++++++++++++++
 .github/workflows/mcp.yml                     |  2 +-
 .../app/api/routes/artifact_submissions.py    |  4 +-
 backend/app/api/submission_intake.py          | 10 ++-
 .../artifacts/api/submission_intake.py        |  4 +
 .../app/modules/artifacts/intake/streaming.py |  2 +-
 .../test_submission_foreground_command.py     | 28 +++++--
 backend/tests/test_api_controls.py            | 25 ++++++
 deploy/hosted/compose.mcp.yml                 |  2 +-
 mcp_server/README.md                          |  4 +-
 .../contracts/service_actor_create.json       |  5 +-
 .../test_task_operation_contract_drift.py     |  2 +-
 scripts/test_hosted_mcp_container.py          |  4 +-
 13 files changed, 148 insertions(+), 20 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index bd3e1c2bd..3b8d73b51 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4560,3 +4560,79 @@ MCP feedback parity, obsolete fixture/shared producer migration, complete downst
 journeys, cleanup/runtime/provider/deployment qualification and full CI remain open.
 No PR readiness or merge request is made. Scoped internal reviews will assess this
 implemented delta with those omissions explicit, rather than certify goal completion.
+
+### Frozen public-cutover review and batched repairs
+
+Frozen666be589370c15fe6be15b3ed96bcf97974912bb stayed clean through shared
+verification and review snapshots. Combined pure/API/reconciliation suite221passed
+in127.34s (`/tmp/submission-cutover-frozen-pure.log`). Combined foreground/public
+HTTP/T5 suite14passed in376.40s with exact666 metadata,0080 and database cleanup
+complete (`/tmp/submission-cutover-frozen-db.log/json`). Commitrail record check
+passed. The existing retry-builder serialization warning remains disclosed.
+
+ARCH/SEC and QA identified the same Medium transport defect: request.stream()
+can yield a valid ZIP in a frame exceeding ART's1MiB internal chunk bound; the
+route forwarded that frame unchanged. Their independent split/one-frame probes
+confirmed identical legal bytes accepted when segmented and rejected whole. Add
+public initial/replay tests for both segmentations, expose the existing chunk
+bound through ART's public intake contract, and split only at the HTTP adapter.
+Keep internal size/EOF/deadline checks and bounded backpressure. This repair adds
+no whole-body spool or second ingress policy.
+
+DOCS/CI findingCI-CATALOGUE-001: actual MCP catalogue131 but six exact-count
+consumers still expected132. Allowed repair additionally includes the affected
+existing .github/workflows/mcp.yml, scripts/test_hosted_mcp_container.py and
+deploy/hosted/compose.mcp.yml assertions/summary, MCP drift test and README. Change
+only the intentional count removal; preserve exactness, tool-name/route assertions,
+health behavior, lane selection and deployment controls. This is catalogue repair,
+not deployment authorization. Reviewer independently preserved all692 prior
+ownership assignments/protected base with exactly693 total and full CI selection.
+
+QA's independent retained-digest test-of-test passed on666 and failed at the intended
+rejection assertion under its controlled guard-removal simulation
+(`/tmp/submission-progress-qa-digest-mutant.log`). No other concrete implementation
+finding was reported; the two shared repairs remain open until frozen replay.
+
+Both new real HTTP framing regressions reproduced the defect before repair:
+large-single initial failed413; large-split initial reached202 but same-key
+single-frame replay failed413 (`/tmp/submission-asgi-frame-before.log/json`,2failed,
+55.52s, database cleanup complete). The HTTP helper now yields bounded slices of
+each supplied frame without reading ahead; ART imports the same public1MiB bound
+and retains its guard. Four transport backpressure/boundary cases and the full
+API-controls module passed61 in95.25s (`/tmp/submission-asgi-controls-after.log`).
+Module-boundary validation and targeted Ruff/diff checks passed.
+
+First repaired four-case database run passed one case then the Python process
+segfaulted while garbage-collecting during FastAPI/Pydantic fixture schema creation
+(`/tmp/submission-asgi-frame-after.log/json`, exit245, cleanup complete). This is
+not an assertion failure or a root-cause fix for prior native instability. The
+unchanged four cases are being replayed; retain both outcomes.
+
+The exact131 catalogue repair passed its count assertion, then exposed one older
+snapshot drift: ServiceIdentity lacks workstream.artifact.source_cleanup added by
+this PR's sealed-cleanup owner. Independent comparison of all task-operation
+snapshots found exactly that one enum difference. Refresh only
+mcp_server/contracts/service_actor_create.json and its canonical digest/provenance;
+do not weaken comparison. Initial command27passed1failed,34.50s
+(`/tmp/submission-catalogue-count-repair.log`). Configured comparison rerun and a
+local hosted-compose smoke against the rebuilt MCP image are in progress. This
+smoke uses isolated fixture containers and is not deployment or AWS qualification.
+
+Unchanged repaired public HTTP replay passed all4 cases in123.46s
+(`/tmp/submission-asgi-frame-replay.log/json`),0080 and isolated database cleanup
+complete. Both large-ZIP initial/replay segmentations now return stable202 with
+one PRE; small acceptance and QC rejection remain covered. The earlier native
+SIGSEGV remains unexplained and is not erased by this pass.
+
+Configured MCP catalogue/task-operation OpenAPI checks passed28 in40.38s
+(`/tmp/submission-catalogue-count-contract-after.log`). Local hosted-compose smoke
+passed on image sha256:06bcaa810b65d2515db1ea44bcbefb8fe32d2402ffd4fc12385795bea16f423e,
+with131tools, restart, replacement and stale-namespace counterexample all passed
+(`/tmp/submission-mcp-hosted-smoke.log`, exit0). This exercised repaired health and
+smoke counts against the actual rebuilt package and removed fixture containers.
+It is local protocol/lifecycle proof, not deployment/provider qualification.
+
+Freeze the batched transport/catalogue repairs for affected reviewer replay.
+The unchanged666 owner/foreground14 and pure221 receipts remain bounded baseline
+evidence; the new transport cases require the repair's exact-head replay. The
+full goal and public progress wiring remain unfinished on PR708.
diff --git a/.github/workflows/mcp.yml b/.github/workflows/mcp.yml
index c344f5ab7..4a5f1427d 100644
--- a/.github/workflows/mcp.yml
+++ b/.github/workflows/mcp.yml
@@ -76,7 +76,7 @@ jobs:
               --header 'Content-Type: application/json' \
               --data '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \
               http://127.0.0.1:18080/mcp \
-              | python -c 'import json, sys; tools = [tool["name"] for tool in json.load(sys.stdin)["result"]["tools"]]; expected = ["workstream_projects_list", "workstream_service_actor_create", "workstream_task_import_batch_create", "workstream_management_tasks_list", "workstream_management_task_create", "workstream_operational_tasks_list", "workstream_task_import_batch_screen", "workstream_task_import_batch_release", "workstream_task_import_batch_get", "workstream_management_task_get", "workstream_management_task_locked_context_get", "workstream_operational_task_locked_context_get", "workstream_audit_task_locked_context_get", "workstream_task_revision_context_repair", "workstream_audit_task_evidence_get", "workstream_project_model_profile_provision", "workstream_project_model_budget_configure", "workstream_project_model_usage_effect_get", "workstream_project_model_recovery_child_create", "workstream_task_import_source_declare", "workstream_task_import_source_content_upload", "workstream_task_import_source_content_get", "workstream_task_import_source_get"]; assert len(tools) == len(set(tools)) == 132; assert tools[-23:] == expected'; then
+              | python -c 'import json, sys; tools = [tool["name"] for tool in json.load(sys.stdin)["result"]["tools"]]; expected = ["workstream_projects_list", "workstream_service_actor_create", "workstream_task_import_batch_create", "workstream_management_tasks_list", "workstream_management_task_create", "workstream_operational_tasks_list", "workstream_task_import_batch_screen", "workstream_task_import_batch_release", "workstream_task_import_batch_get", "workstream_management_task_get", "workstream_management_task_locked_context_get", "workstream_operational_task_locked_context_get", "workstream_audit_task_locked_context_get", "workstream_task_revision_context_repair", "workstream_audit_task_evidence_get", "workstream_project_model_profile_provision", "workstream_project_model_budget_configure", "workstream_project_model_usage_effect_get", "workstream_project_model_recovery_child_create", "workstream_task_import_source_declare", "workstream_task_import_source_content_upload", "workstream_task_import_source_content_get", "workstream_task_import_source_get"]; assert len(tools) == len(set(tools)) == 131; assert tools[-23:] == expected'; then
               exit 0
             fi
             sleep 1
diff --git a/backend/app/api/routes/artifact_submissions.py b/backend/app/api/routes/artifact_submissions.py
index 75c588f70..7ad0085c2 100644
--- a/backend/app/api/routes/artifact_submissions.py
+++ b/backend/app/api/routes/artifact_submissions.py
@@ -7,7 +7,7 @@
 
 from app.adapters.artifacts import get_submission_intake_command
 from app.api.deps.authorization import get_authorization_actor_identity
-from app.api.submission_intake import SubmissionIntakeHeaders, submission_intake_headers
+from app.api.submission_intake import SubmissionIntakeHeaders, submission_intake_headers, submission_intake_body
 from app.core.api_controls import error_response
 from app.modules.artifacts.api.submission_command import SubmissionAcceptedResponse, SubmissionIntakeCommand
 from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
@@ -75,7 +75,7 @@ async def submit_source(
     """Acknowledge only committed acceptance, with no fabricated T5 identifiers."""
     try:
         receipt = await command.submit(
-            headers.metadata, request.stream(), actor_id=actor.actor_profile_id,
+            headers.metadata, submission_intake_body(request), actor_id=actor.actor_profile_id,
             identity_link_id=actor.identity_link_id, idempotency_key=headers.idempotency_key,
             declared_raw_bytes=headers.declared_raw_bytes,
         )
diff --git a/backend/app/api/submission_intake.py b/backend/app/api/submission_intake.py
index 637e6ceda..2e2f919e4 100644
--- a/backend/app/api/submission_intake.py
+++ b/backend/app/api/submission_intake.py
@@ -1,4 +1,5 @@
 """Exact HTTP command metadata for the single raw-ZIP submission mutation."""
+from collections.abc import AsyncIterator
 from dataclasses import dataclass
 from typing import NoReturn
 from uuid import UUID
@@ -8,7 +9,7 @@
 
 from app.core.api_controls import StructuredHTTPException
 from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
-from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
+from app.modules.artifacts.api.submission_intake import MAXIMUM_INGRESS_CHUNK_BYTES, SubmissionIntakeMetadata
 
 
 @dataclass(frozen=True, slots=True)
@@ -72,3 +73,10 @@ def submission_intake_headers(request: Request, task_id: UUID) -> SubmissionInta
     except ValueError:
         _reject("submission_packet_invalid", 422, "Submission packet is invalid")
     return SubmissionIntakeHeaders(metadata, key, declared)
+
+
+async def submission_intake_body(request: Request) -> AsyncIterator[bytes]:
+    """Adapt arbitrary ASGI frames to bounded owner chunks without reading ahead."""
+    async for frame in request.stream():
+        for start in range(0, len(frame), MAXIMUM_INGRESS_CHUNK_BYTES):
+            yield frame[start:start + MAXIMUM_INGRESS_CHUNK_BYTES]
diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py
index 62ed581c5..7a96d5da7 100644
--- a/backend/app/modules/artifacts/api/submission_intake.py
+++ b/backend/app/modules/artifacts/api/submission_intake.py
@@ -17,6 +17,10 @@
 from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
 
 
+# Shared transport-to-owner bound; independent of the total compressed ZIP limit.
+MAXIMUM_INGRESS_CHUNK_BYTES = 1024 * 1024
+
+
 Sha256 = Annotated[str, Field(pattern=r"^sha256:[0-9a-f]{64}$")]
 
 
diff --git a/backend/app/modules/artifacts/intake/streaming.py b/backend/app/modules/artifacts/intake/streaming.py
index 927216583..45ecdc5c5 100644
--- a/backend/app/modules/artifacts/intake/streaming.py
+++ b/backend/app/modules/artifacts/intake/streaming.py
@@ -22,12 +22,12 @@
     ArtifactStoreUnavailableError,
 )
 from app.modules.artifacts.api.submission_intake import (
+    MAXIMUM_INGRESS_CHUNK_BYTES,
     SubmissionSourceCompletion,
     SubmissionSourceUpload,
 )
 
 
-MAXIMUM_INGRESS_CHUNK_BYTES = 1024 * 1024
 
 
 class SubmissionUploadTimeout(ArtifactStoreUnavailableError):
diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py
index 0c5f65d53..113230e28 100644
--- a/backend/tests/artifacts/test_submission_foreground_command.py
+++ b/backend/tests/artifacts/test_submission_foreground_command.py
@@ -16,8 +16,11 @@
 )
 
 
-@pytest.mark.parametrize("outcome", ["completed", "rejected"])
-async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admission_intake, tmp_path, monkeypatch, outcome):
+@pytest.mark.parametrize("outcome,framing", [
+    ("completed", "small"), ("rejected", "small"),
+    ("completed", "large-single"), ("completed", "large-split"),
+])
+async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admission_intake, tmp_path, monkeypatch, outcome, framing):
     from sqlalchemy import text
     from app.adapters import artifacts as composition
     from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter
@@ -31,6 +34,16 @@ async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admi
 
     f, key = admission_intake, new_record_id()
     payload = _archive("../escape") if outcome == "rejected" else _archive()
+    if framing.startswith("large"):
+        payload = _archive(content=b"finished work\n" * 90_000)
+        assert 1024 * 1024 < len(payload) < 2 * 1024 * 1024
+    def body(split):
+        if not split:
+            return payload
+        async def chunks():
+            for start in range(0, len(payload), 64 * 1024):
+                yield payload[start:start + 64 * 1024]
+        return chunks()
     runtime, errors = _source_runtime(payload, tmp_path, outcome)
     calls, original = [], runtime.execute_pre
     async def execute(lease, grant):
@@ -45,7 +58,7 @@ async def execute(lease, grant):
     app = client._transport.app
     storage = {name: value for name, value in _settings(tmp_path).model_dump().items() if name.startswith("artifact_")}
     settings = app.state.settings.model_copy(update=storage | {"submission_execution_profile": {
-        "capacity": {"maximum_total_bytes": 1_000_000},
+        "capacity": {"maximum_total_bytes": 4 * 1024 * 1024},
         "runtime": _source_reservation().runtime_profile.model_dump(mode="json"),
         "upload_total_seconds": 300.0, "upload_idle_seconds": 10.0,
         "foreground_lease_seconds": 60.0, "heartbeat_seconds": 10.0,
@@ -53,12 +66,13 @@ async def execute(lease, grant):
     }})
     monkeypatch.setattr(app.state, "settings", settings)
     headers = f.access.target.headers | {"Content-Type": "application/zip",
-        "X-Task-Assignment-Id": str(f.assignment), "Idempotency-Key": str(key)}
+        "X-Task-Assignment-Id": str(f.assignment), "Idempotency-Key": str(key),
+        "Content-Length": str(len(payload))}
     url = f"/api/v1/tasks/{f.task}/submissions"
-    first = await client.post(url, headers=headers, content=payload)
-    second = await client.post(url, headers=headers, content=payload)
+    first = await client.post(url, headers=headers, content=body(framing == "large-split"))
+    second = await client.post(url, headers=headers, content=body(framing != "large-split"))
     assert not errors, "\n".join(errors)
-    assert len(calls) == 1
+    assert len(calls) == 1, (first.status_code, first.text, second.status_code, second.text)
     if outcome == "completed":
         assert first.status_code == second.status_code == 202, (first.text, second.text)
         receipt = first.json()
diff --git a/backend/tests/test_api_controls.py b/backend/tests/test_api_controls.py
index f672bc036..66be0a95a 100644
--- a/backend/tests/test_api_controls.py
+++ b/backend/tests/test_api_controls.py
@@ -1100,3 +1100,28 @@ def test_raw_submission_single_mixed_case_names_preserve_exact_values():
     upper = [(name.upper(), value) for name, value in lower]
     task = UUID(int=3)
     assert submission_intake_headers(_casefold_request(upper), task) == submission_intake_headers(_casefold_request(lower), task)
+
+
+@pytest.mark.parametrize("size", [1024 * 1024 - 1, 1024 * 1024, 1024 * 1024 + 1, 2 * 1024 * 1024 + 3])
+async def test_submission_http_body_preserves_bytes_and_backpressure(size):
+    from app.api.submission_intake import submission_intake_body
+    from app.modules.artifacts.api.submission_intake import MAXIMUM_INGRESS_CHUNK_BYTES
+
+    payload, received = b"z" * size, []
+    async def receive():
+        received.append(True)
+        if len(received) == 1:
+            return {"type": "http.request", "body": payload, "more_body": True}
+        assert len(received) == 2
+        return {"type": "http.request", "body": b"tail", "more_body": False}
+    stream = submission_intake_body(Request({"type": "http"}, receive))
+    chunks = []
+    while sum(map(len, chunks)) < len(payload):
+        chunk = await anext(stream)
+        assert 0 < len(chunk) <= MAXIMUM_INGRESS_CHUNK_BYTES
+        assert len(received) == 1  # Do not pull the next ASGI frame early.
+        chunks.append(chunk)
+    assert b"".join(chunks) == payload
+    assert await anext(stream) == b"tail" and len(received) == 2
+    with pytest.raises(StopAsyncIteration):
+        await anext(stream)
diff --git a/deploy/hosted/compose.mcp.yml b/deploy/hosted/compose.mcp.yml
index ec7c3ab0c..a3ed75ec5 100644
--- a/deploy/hosted/compose.mcp.yml
+++ b/deploy/hosted/compose.mcp.yml
@@ -28,7 +28,7 @@ services:
       WORKSTREAM_MCP_MAX_IN_FLIGHT: "1"
       WORKSTREAM_MCP_ALLOWED_HOSTS: 127.0.0.1:8080,localhost:8080
     healthcheck:
-      test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/v1/health', timeout=2); r=urllib.request.Request('http://127.0.0.1:8080/mcp', data=b'{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{}}', headers={'Content-Type':'application/json','Accept':'application/json, text/event-stream'}); import json; assert len(json.load(urllib.request.urlopen(r,timeout=3))['result']['tools']) == 132"]
+      test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/v1/health', timeout=2); r=urllib.request.Request('http://127.0.0.1:8080/mcp', data=b'{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{}}', headers={'Content-Type':'application/json','Accept':'application/json, text/event-stream'}); import json; assert len(json.load(urllib.request.urlopen(r,timeout=3))['result']['tools']) == 131"]
       interval: 10s
       timeout: 6s
       retries: 3
diff --git a/mcp_server/README.md b/mcp_server/README.md
index 09b40d8f5..71dd23cda 100644
--- a/mcp_server/README.md
+++ b/mcp_server/README.md
@@ -1,6 +1,6 @@
 # Workstream MCP Adapter
 
-An independently installed adapter exposing 132 tools under the caller's authority:
+An independently installed adapter exposing 131 tools under the caller's authority:
 
 - `workstream_profile_get` calls `GET /api/v1/actors/me`.
 - `workstream_profile_update` calls the unkeyed `PATCH /api/v1/actors/me`.
@@ -251,7 +251,7 @@ retries. A mutation transport failure, upstream 5xx response, or unexpected
 success/redirect response is reported as non-retryable uncertain execution.
 Connections may be pooled, but
 caller credentials and results are not shared or cached. Response validation is
-pinned to the 132 selected public contracts in `contracts/`; upstream drift
+pinned to the 131 selected public contracts in `contracts/`; upstream drift
 must be reviewed, not silently accepted. There is no fallback service or
 backend-private import.
 
diff --git a/mcp_server/contracts/service_actor_create.json b/mcp_server/contracts/service_actor_create.json
index ce940f98a..cc9e67a47 100644
--- a/mcp_server/contracts/service_actor_create.json
+++ b/mcp_server/contracts/service_actor_create.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "3d848ecc58c83e5009511771fdbb2bae8880e8053aa243639ecbd36afc25d2bc",
+  "canonical_sha256": "1e0aca84e06cc1cda9d4e464fd375b59e4f57b8e0e7a2e2a86648995655d9899",
   "components": {
     "schemas": {
       "ApiError": {
@@ -163,6 +163,7 @@
           "workstream.artifact.verifier",
           "workstream.artifact.put_resolver",
           "workstream.artifact.scheduler",
+          "workstream.artifact.source_cleanup",
           "workstream.artifact.binding",
           "workstream.artifact.guide_reader",
           "workstream.artifact.materializer",
@@ -464,6 +465,6 @@
     "method": "POST",
     "openapi_version": "3.1.0",
     "path": "/api/v1/service-actors",
-    "repository_sha": "f0431385573eb53353c5ffc3c6cdb6a93d206b73"
+    "repository_sha": "666be589370c15fe6be15b3ed96bcf97974912bb"
   }
 }
diff --git a/mcp_server/tests/test_task_operation_contract_drift.py b/mcp_server/tests/test_task_operation_contract_drift.py
index e87182bb0..953b64b09 100644
--- a/mcp_server/tests/test_task_operation_contract_drift.py
+++ b/mcp_server/tests/test_task_operation_contract_drift.py
@@ -107,7 +107,7 @@ def test_task_operation_contracts_match_backend_openapi_when_configured() -> Non
         operation = openapi["paths"][path][method.lower()]
         assert operation["security"]
         assert operation["x-workstream-action-id"] == "project.guide_compilation.request"
-    assert len(all_operations - health_operations) == 132
+    assert len(all_operations - health_operations) == 131
     for name, (method, path, _) in TASK_OPERATIONS.items():
         snapshot = json.loads((CONTRACTS / f"{name}.json").read_text(encoding="utf-8"))
         assert snapshot["source"]["openapi_version"] == openapi["openapi"]
diff --git a/scripts/test_hosted_mcp_container.py b/scripts/test_hosted_mcp_container.py
index cc9eaba15..6d96268ad 100644
--- a/scripts/test_hosted_mcp_container.py
+++ b/scripts/test_hosted_mcp_container.py
@@ -140,7 +140,7 @@ def rpc(method: str, params: dict, bearer: str | None = None) -> dict:
 
         def prove_calls(generation: str) -> None:
             tools = rpc("tools/list", {})["tools"]
-            assert len(tools) == len({tool["name"] for tool in tools}) == 132
+            assert len(tools) == len({tool["name"] for tool in tools}) == 131
             params = {"name": "workstream_profile_get", "arguments": {}}
             for caller in ("alice", "bob"):
                 result = rpc("tools/call", params, "fixture-" + caller)
@@ -181,7 +181,7 @@ def prove_calls(generation: str) -> None:
             assert current_api != original_api and current_mcp != original_mcp
             prove_calls("replacement")
             print(json.dumps({"proof": "hosted MCP fixture transport", "image_id": image_id,
-                              "tools": 132, "restart": "passed", "replacement": "passed",
+                              "tools": 131, "restart": "passed", "replacement": "passed",
                               "stale_namespace_counterexample": "passed"}))
         finally:
             compose("down", "--volumes", "--remove-orphans", "--timeout", "10", timeout=45)

From c11ed9101a0ef2a28ade6107cb1373b0bcbb2f30 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 14:48:13 +0100
Subject: [PATCH 157/513] feat(submission): authorize project manager operation
 progress reads

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 135 ++++++++++++++++++
 backend/alembic/env.py                        |  12 +-
 .../versions/0081_operation_read_authority.py |  28 ++++
 .../artifacts/api/submission_command.py       |  47 ++++++
 .../authorization/action_definitions.py       |   3 +-
 .../authorization/api/submission_intake.py    |   4 +-
 .../app/modules/authorization/catalogue.py    |   6 +-
 .../authorization/domain/audit_targets.py     |   8 +-
 .../authorization/domain/contributor_reads.py |   2 -
 .../domain/submission_history.py              |  17 ++-
 backend/app/modules/authorization/runtime.py  |   2 +-
 .../authorization/submission_intake.py        |  17 ++-
 .../test_submission_intake_contracts.py       |  39 +++++
 .../tests/authorization/catalogue_fixtures.py |   2 +
 .../task_authority/test_intake_authority.py   |  44 ++++++
 backend/tests/authorization/test_catalogue.py |   4 +-
 backend/tests/conftest.py                     |   2 +-
 backend/tests/test_alembic.py                 |  20 +++
 18 files changed, 366 insertions(+), 26 deletions(-)
 create mode 100644 backend/alembic/versions/0081_operation_read_authority.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 3b8d73b51..287ada4a6 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4636,3 +4636,138 @@ Freeze the batched transport/catalogue repairs for affected reviewer replay.
 The unchanged666 owner/foreground14 and pure221 receipts remain bounded baseline
 evidence; the new transport cases require the repair's exact-head replay. The
 full goal and public progress wiring remain unfinished on PR708.
+
+
+## Public operation progress contract and authorization composition
+
+Repair121f8dfbb71ea24b2ffb75ee1ac735fffe64ffff exact-head large-ZIP
+replay passed2 in53.62s with migration0080 and isolated cleanup complete
+(`/tmp/submission-asgi-frame-frozen.log/json`). ARCH/SEC, QA and DOCS/CI
+closed the scoped framing/catalogue findings. Commitrail validation passed.
+Native crashes remain unexplained; these receipts do not establish full readiness.
+
+The next change closes specification5.5: an authorized read of one operation,
+never the latest submission. Existing TASK/CHECKERS/OUTBOX observations are reused.
+The first implementation step defines the closed public response and exactly-one
+selector in existing ART submission_command contract; it grants no read authority.
+Allowed files: that contract, existing intake contract tests, ART intake progress
+and repository/composition, canonical ART/AUTH adapters, existing AUTH intake
+contracts/evaluator, TASK read contracts/owners, public submission route and its
+existing tests, affected CLI/MCP contracts/consumers and this record. Broaden this
+list explicitly before unrelated changes. Prohibited: provider coordinates in
+responses, current-task status as historical outcome, ID possession as authority,
+new compatibility readers, data deletion, or weakened tests/CI.
+
+Acceptance: exactly one UUID selector; key lookup scoped to current actor;
+required nullable fields retained; existing TASK status reused; exact operation
+association; current contributor/management authorization; reassignment conceals
+current status; next action derives from current TASK eligibility and original
+assignment/revision; owner-backed stalls. Tests must cover closed shape, selectors,
+authorization substitution, historical revision independence and corruption.
+Risk: authorization/workflow. Required reviews: ARCH/SEC and QA, with DOCS/CI
+for generated contracts and client exposure. Human focus: management access,
+historical concealment and distinction between accepted handoff and governed result.
+The public route and full journey remain unfinished until composed and exercised.
+
+Initial public progress schema/selector checks passed7 (130 deselected) in3.57s;
+targeted Ruff and git diff --check passed. Nullable fields remain required and
+current_task_status reuses TASK TaskStatus. This is contract-only evidence, not
+authorization or public route proof. Response PRE feedback retains the existing
+projection shape pending bounded-feedback reconciliation. No endpoint is exposed
+by this step; contributor/management composition remains the next required work.
+
+
+Authorization extension reuses the existing historical-read evaluator, whose
+contributor branch requires current exact-project Submitter authority and whose
+management branch requires Project Manager authority. Allowed AUTH paths also
+include catalogue.py, action_definitions.py, domain/contributor_reads.py,
+domain/submission_history.py and existing task_authority/test_intake_authority.py.
+Move the existing operation read out of generic own-work dispatch, retain its
+original action/permission, and add its management action using the existing
+project.task.manage permission. A distinct closed operation resource is necessary:
+pre-handoff operations have no Submission ID, so a fabricated history target is
+forbidden. Both paths bind the real operation/task/project/contributor and current
+reader. An explicit internal management selection is an authorization request,
+not a grant; the kernel must independently validate it. Existing replay callers
+continue to request the contributor path. No public management route is added.
+
+The exact AUTH catalogue count increases194 to195 for the management operation
+read action; permissions remain95. Allowed tests include the existing
+authorization/test_catalogue.py exact inventory check. No count check is relaxed.
+
+Audit constraints require a forward migration0081_operation_read_authority;
+allowed paths include that migration, existing catalogue_fixtures.py and
+test_alembic.py. Preserve every existing action/permission pair and all retained
+rows; change only the exact management read pair. Initial catalogue run caught
+the missing independent expected row (6pass1fail), which must be added explicitly.
+The first DB run was deliberately interrupted before collecting proof when this
+missing constraint extension was identified; cleanup metadata confirms complete.
+
+First0081 authority run applied migration but refused reset against the old
+exact schema fingerprint:35 setup errors;20 pure checks passed and one catalogue
+active-count assertion correctly required170 to171. Update the existing
+tests/conftest.py exact fingerprint for the new audit constraint, keeping reset
+validation enabled; migration manifest comparison must prove no unrelated change.
+Separate migration process segfaulted during pytest assertion rewriting/GC before
+test execution (exit245, cleanup complete); unchanged collection-only diagnostic
+passed1 selected/68 deselected in0.93s. This is another retained native failure,
+not proof of migration behavior or a root-cause resolution.
+
+Progress authorization candidate is held unchanged for live v3 authority and
+migration replay processes. Logs/metadata: /tmp/submission-progress-authority-v3
+and /tmp/submission-progress-migration-replay (.log/.json). No pass is credited
+until terminal results are inspected. Latest shared checks: targeted Ruff, module
+boundaries, Commitrail and diff checks passed. All these changes remain uncommitted
+worktree work pending proof/review, not a delivered public progress endpoint.
+
+Migration replay completed1failed/68deselected in161.42s: existing
+alembic/env.py still hard-codes current head0071 and does not admit0080 as an
+upgrade starting revision. This is a forward-upgrade defect masked by fresh
+installs. Allowed repair includes alembic/env.py: enumerate the real intervening
+revisions and name0081 as current, preserving unknown-revision rejection. Apply
+after the frozen authority-v3 process finishes, then replay the manifest proof.
+Authority-v3 remains live (session19779); do not restart while running.
+
+Authority-v3 finished47passed9failed in240.34s, cleanup complete. Eight
+failures expose missing OperationReadResourceContext audit projection (resource_id
+was null); one new Operator negative-control fixture used an invalid project
+scope. Allowed repair includes domain/audit_targets.py and runtime.py closed
+resource union. Replace the obsolete generic operation-resource audit branch
+with the new exact type; preserve operation IDs in allow and denial evidence.
+Use a valid system Operator grant for the negative control, retaining denial.
+
+Repaired AUTH read matrix passed13 (22deselected) in101.52s on worktree
+parent121, migration0081, with complete isolated cleanup
+(`/tmp/submission-progress-authority-fixed.log/json`). Catalogue/audit contracts
+passed21 in1.53s (`/tmp/submission-progress-catalogue-fixed.log`). Lint and diff
+checks pass. Fetch confirms no missing origin/main commits.
+
+First preflight-repair migration run failed during unchanged0053 with a reported
+PostgresSyntaxError before reaching0081 (`/tmp/submission-progress-migration-fixed.log`).
+The exact46708-byte reported SQL has balanced parentheses and succeeded against
+a temporary table inside BEGIN/ROLLBACK on the same PostgreSQL server
+(`/tmp/submission-progress-migration-sql-probe.log`). Do not change0053 or claim
+the native/transport cause resolved from this diagnostic. The unchanged forward
+upgrade proof is replaying under /tmp/submission-progress-migration-fixed-replay.
+
+Preflight-repair replay successfully upgraded0080 to0081 and confirmed only
+the intended constraint changed; its final exact-string assertion failed because
+build_manifest uses PostgreSQL pretty constraint definitions without redundant
+parentheses. Correct the independent expected addition to that actual format;
+retain exact two occurrences and exact equality after removing only the new pair.
+Run ended1failed/68deselected in127.49s with cleanup complete. No production or
+preflight change is needed for this assertion-format repair.
+
+Final upgrade preservation replay passed1 (68deselected) in119.25s,0081
+with complete isolated cleanup (/tmp/submission-progress-migration-preservation.log/json).
+Exact comparison proves only the action-evidence constraint changes and removal
+of its two new manager-action/permission terms recovers the previous definition.
+Independent AST/script inventory confirms preflight recognizes all81 actual
+revisions and names the actual0081 head. Configured backend OpenAPI/MCP task
+contract drift passed25 in35.41s (/tmp/submission-progress-mcp-drift.log).
+Module-boundary validation, Commitrail validation and diff checks passed.
+
+Freeze this contract/authorization checkpoint for required ARCH/SEC and QA review.
+These are worktree receipts on parent121, not an exact committed-head full suite.
+Public route composition, TASK eligibility/concealment, client progress wiring,
+full journeys/CI and native instability remain open. Keep the one PR708 draft.
diff --git a/backend/alembic/env.py b/backend/alembic/env.py
index 397596ffb..2de71f052 100644
--- a/backend/alembic/env.py
+++ b/backend/alembic/env.py
@@ -21,7 +21,7 @@
 target_metadata = Base.metadata
 
 _BASELINE_REVISION = "0001_uuid7_v01"
-_CURRENT_HEAD_REVISION = "0071_source_first_pre"
+_CURRENT_HEAD_REVISION = "0081_operation_read_authority"
 _RECREATE_GUIDANCE = (
     "Workstream v0.1 requires a fresh database; recreate this database before "
     "running the 0001_uuid7_v01 migration"
@@ -125,6 +125,16 @@ def do_run_migrations(connection: Connection) -> None:
             ("0068_issuer_profile_email",),
             ("0069_submission_intake_custody",),
             ("0070_submission_intake_authority",),
+            ("0071_source_first_pre",),
+            ("0072_pre_invocation_receipts",),
+            ("0073_submission_acceptance",),
+            ("0074_submission_finalization",),
+            ("0075_source_post_custody",),
+            ("0076_submission_delivery_retry",),
+            ("0077_submission_recovery",),
+            ("0078_submission_cleanup",),
+            ("0079_cleanup_authority",),
+            ("0080_cleanup_decisions",),
             (_CURRENT_HEAD_REVISION,),
         ):
             raise RuntimeError(_RECREATE_GUIDANCE)
diff --git a/backend/alembic/versions/0081_operation_read_authority.py b/backend/alembic/versions/0081_operation_read_authority.py
new file mode 100644
index 000000000..3333353e9
--- /dev/null
+++ b/backend/alembic/versions/0081_operation_read_authority.py
@@ -0,0 +1,28 @@
+"""Admit exact management operation-read audit evidence without rewriting history."""
+from alembic import op
+from sqlalchemy import text
+
+revision = "0081_operation_read_authority"
+down_revision = "0080_cleanup_decisions"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.audit_events IN ACCESS EXCLUSIVE MODE")
+    name = "ck_audit_events_authorization_action_evidence"
+    definition = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_constraintdef(oid) FROM pg_catalog.pg_constraint "
+        "WHERE conrelid='public.audit_events'::regclass AND conname=:name"
+    ), {"name": name}).scalar_one()
+    anchor = "(((action_id)::text = 'task.submission_operation.read'::text) AND ((permission_id)::text = 'submission.read_own'::text))"
+    if definition.count(anchor) != 2 or "project.task.submission_operation.read" in definition:
+        raise RuntimeError("operation read audit action constraint shape changed")
+    addition = " OR (((action_id)::text = 'project.task.submission_operation.read'::text) AND ((permission_id)::text = 'project.task.manage'::text))"
+    op.execute("ALTER TABLE public.audit_events DROP CONSTRAINT " + name)
+    op.execute("ALTER TABLE public.audit_events ADD CONSTRAINT " + name + " " + definition.replace(anchor, anchor + addition))
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
diff --git a/backend/app/modules/artifacts/api/submission_command.py b/backend/app/modules/artifacts/api/submission_command.py
index 1b26c14a3..e7c893588 100644
--- a/backend/app/modules/artifacts/api/submission_command.py
+++ b/backend/app/modules/artifacts/api/submission_command.py
@@ -7,6 +7,7 @@
 
 from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
 from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitRuntimeProfile
+from app.modules.tasks.api.management_queue import TaskStatus
 
 Seconds = Annotated[float, Field(gt=0, allow_inf_nan=False)]
 
@@ -65,3 +66,49 @@ async def submit(
     ) -> dict:
         """Return committed acceptance or a bounded SubmissionIntakeFailure."""
         ...
+
+
+class SubmissionOperationSelector(BaseModel):
+    """Two selectors for one read; key scope is supplied by authenticated context."""
+
+    model_config = ConfigDict(extra="forbid", frozen=True)
+    operation_id: UUID | None = None
+    idempotency_key: UUID | None = None
+
+    @model_validator(mode="after")
+    def exactly_one(self) -> Self:
+        if (self.operation_id is None) == (self.idempotency_key is None):
+            raise ValueError("exactly one submission operation selector is required")
+        return self
+
+
+class SubmissionOperationResponse(BaseModel):
+    """Authorized operation projection; nullable fields are required on the wire."""
+
+    model_config = ConfigDict(extra="forbid", frozen=True)
+    operation_id: UUID
+    task_id: UUID
+    assignment_id: UUID
+    idempotency_key: UUID
+    operation_state: Literal[
+        "receiving", "pre_checking", "finalization_pending", "finalized",
+        "rejected", "failed", "abandoned", "cancelled",
+    ]
+    processing_stage: Literal[
+        "receiving", "pre_checking", "finalization_pending", "evaluation_pending",
+        "evaluation_running", "review_pending", "needs_revision", "accepted",
+        "rejected", "failed", "abandoned", "cancelled", "operationally_stalled",
+    ]
+    accepted_at: AwareDatetime | None
+    task_status_at_acceptance: Literal["evaluation_pending"] | None
+    current_task_status: TaskStatus | None
+    submission_id: UUID | None
+    submission_version: Annotated[int, Field(strict=True, gt=0)] | None
+    evaluation_request_id: UUID | None
+    pre_submission_results: list[dict[str, object]]
+    failure_code: str | None
+    operationally_stalled: bool
+    next_action: Literal[
+        "wait", "correct_and_submit_new_key", "retry_new_key_after_terminal",
+        "inspect_governed_outcome",
+    ]
diff --git a/backend/app/modules/authorization/action_definitions.py b/backend/app/modules/authorization/action_definitions.py
index f43b5f024..f2a7b8661 100644
--- a/backend/app/modules/authorization/action_definitions.py
+++ b/backend/app/modules/authorization/action_definitions.py
@@ -16,12 +16,13 @@
 ACTION_DEFINITIONS = (
     _active(ActionId.SUBMISSION_INTAKE_RESERVE, PermissionId.SUBMISSION_CREATE, ActionOwner.SUBMISSION_INTAKE),
     _active(ActionId.TASK_SUBMISSION_OPERATION_READ, PermissionId.SUBMISSION_READ_OWN, ActionOwner.SUBMISSION_INTAKE),
+    _active(ActionId.PROJECT_TASK_SUBMISSION_OPERATION_READ, PermissionId.PROJECT_TASK_MANAGE, ActionOwner.SUBMISSION_INTAKE),
     _active(
         ActionId.ACTOR_PROJECT_LIST, PermissionId.ACTOR_PROFILE_READ_SELF, ActionOwner.PILOT_READ_2
     ),
     *(
         _active(action, PermissionId.SUBMISSION_READ_OWN, ActionOwner.PILOT_READ_2)
-        for action in sorted(CONTRIBUTOR_WORK_READ_ACTIONS - {ActionId.TASK_SUBMISSION_OPERATION_READ})
+        for action in sorted(CONTRIBUTOR_WORK_READ_ACTIONS)
     ),
     *(
         _active(a, PermissionId.PROJECT_GUIDE_MANAGE, ActionOwner.PILOT_READ_3)
diff --git a/backend/app/modules/authorization/api/submission_intake.py b/backend/app/modules/authorization/api/submission_intake.py
index 3020e3c6f..cf11d284b 100644
--- a/backend/app/modules/authorization/api/submission_intake.py
+++ b/backend/app/modules/authorization/api/submission_intake.py
@@ -45,7 +45,7 @@ class IntakeAcceptanceAuthorityFacts(IntakeReservationAuthorityFacts):
 
 @dataclass(frozen=True, slots=True)
 class IntakeOperationReadFacts:
-    """An actor-owned stored operation, resolved before current-task eligibility."""
+    """Stored contributor ownership, resolved before current-task eligibility."""
     operation_id: UUID
     project_id: UUID
     task_id: UUID
@@ -65,6 +65,6 @@ async def consume(self, handle: object, facts: IntakeReservationAuthorityFacts)
     async def prepare_acceptance(self, facts: IntakeAcceptanceAuthorityFacts) -> object: ...
     async def consume_acceptance(self, handle: object, facts: IntakeAcceptanceAuthorityFacts) -> UUID: ...
     async def validate_acceptance_receipt(self, facts: IntakeAcceptanceAuthorityFacts, decision_id: UUID) -> None: ...
-    async def authorize_read(self, facts: IntakeOperationReadFacts) -> UUID: ...
+    async def authorize_read(self, facts: IntakeOperationReadFacts, *, manager: bool = False) -> UUID: ...
     async def restage_denial(self, error: IntakeAuthorityDenied) -> bool: ...
     def close(self) -> None: ...
diff --git a/backend/app/modules/authorization/catalogue.py b/backend/app/modules/authorization/catalogue.py
index bbca8495b..a64d1e3b3 100644
--- a/backend/app/modules/authorization/catalogue.py
+++ b/backend/app/modules/authorization/catalogue.py
@@ -116,6 +116,7 @@ class ActionId(StrEnum):
 
     SUBMISSION_INTAKE_RESERVE = "submission.intake.reserve"
     TASK_SUBMISSION_OPERATION_READ = "task.submission_operation.read"
+    PROJECT_TASK_SUBMISSION_OPERATION_READ = "project.task.submission_operation.read"
     TASK_SUBMISSION_LIST = "task.submission.list"
     SUBMISSION_READ = "submission.read"
     SUBMISSION_CHECKER_RUN_LIST = "submission.checker_run.list"
@@ -330,7 +331,6 @@ class ActionId(StrEnum):
         ActionId.ACTOR_WORK_SUMMARY_READ,
         ActionId.TASK_SUBMISSION_BUNDLE_PREPARATION_LIST,
         ActionId.TASK_SUBMISSION_BUNDLE_PREPARATION_READ,
-        ActionId.TASK_SUBMISSION_OPERATION_READ,
     }
 )
 CONTRIBUTOR_READ_ACTIONS = CONTRIBUTOR_WORK_READ_ACTIONS | {ActionId.ACTOR_PROJECT_LIST}
@@ -358,6 +358,8 @@ class ActionId(StrEnum):
 
 HISTORY_READ_ACTIONS = frozenset(
     {
+        ActionId.TASK_SUBMISSION_OPERATION_READ,
+        ActionId.PROJECT_TASK_SUBMISSION_OPERATION_READ,
         ActionId.TASK_SUBMISSION_LIST,
         ActionId.SUBMISSION_READ,
         ActionId.SUBMISSION_CHECKER_RUN_LIST,
@@ -571,7 +573,7 @@ def _active(
 
 def _require_catalogue_counts() -> None:
     """Keep the closed action inventory and permission boundary exact."""
-    if len(PERMISSION_IDS) != 95 or len(ACTION_IDS) != 194:
+    if len(PERMISSION_IDS) != 95 or len(ACTION_IDS) != 195:
         raise RuntimeError("authorization catalogue count mismatch")
     if len(HISTORICAL_PERMISSION_IDS) != 49 or len(NEW_PERMISSION_IDS) != 46:
         raise RuntimeError("authorization permission boundary mismatch")
diff --git a/backend/app/modules/authorization/domain/audit_targets.py b/backend/app/modules/authorization/domain/audit_targets.py
index dbc977244..b44ee4dd4 100644
--- a/backend/app/modules/authorization/domain/audit_targets.py
+++ b/backend/app/modules/authorization/domain/audit_targets.py
@@ -4,7 +4,6 @@
 from app.modules.authorization.api.submission_finalization import SubmissionFinalizationResourceContext
 from app.modules.authorization.api.submission_cleanup import SubmissionSourceCleanupResourceContext
 from app.modules.authorization.domain.submission_intake import IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext
-from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext
 
 from app.modules.authorization.catalogue import ActionId
 from app.modules.authorization.domain.lifecycle import ReviewLifecycleActivationContract
@@ -22,7 +21,7 @@
 from app.modules.authorization.domain.project_create import ProjectCreateResourceContext
 from app.modules.authorization.domain.task_authority import TaskAuthorityResourceContext, TaskImportBatchResourceContext
 from app.modules.authorization.domain.task_queues import QueueReadResourceContext
-from app.modules.authorization.domain.submission_history import HistoryReadResourceContext
+from app.modules.authorization.domain.submission_history import HistoryReadResourceContext, OperationReadResourceContext
 
 
 def _checker_retry_read_target(resource):
@@ -89,10 +88,7 @@ def _submission_operation_target(resource):
     if type(resource) in {IntakeAcceptanceResourceContext, SubmissionFinalizationResourceContext, SubmissionSourceCleanupResourceContext}:
         project_id = str(getattr(resource, "scope_project_id", None) or resource.project_id)
         return project_id, "submission_operation", str(resource.operation_id), "project", project_id
-    if type(resource) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext} or (
-        type(resource) is ContributorWorkReadResourceContext
-        and resource.resource_type == "submission_operation_read"
-    ):
+    if type(resource) in {IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, OperationReadResourceContext}:
         return (str(resource.scope_project_id), "submission_operation", str(resource.resource_id),
                 "submission_operation", str(resource.resource_id))
     return None
diff --git a/backend/app/modules/authorization/domain/contributor_reads.py b/backend/app/modules/authorization/domain/contributor_reads.py
index d8b43f0d5..00e4db32b 100644
--- a/backend/app/modules/authorization/domain/contributor_reads.py
+++ b/backend/app/modules/authorization/domain/contributor_reads.py
@@ -31,14 +31,12 @@ def exact_actor(self):
 
 ContributorWorkResourceType = Literal[
     "actor_assignment_collection", "actor_submission_collection", "actor_work_summary",
-    "submission_operation_read",
     "task_submission_bundle_preparation_collection", "submission_bundle_preparation_read",
 ]
 _ACTOR_WIDE = frozenset({
     "actor_assignment_collection", "actor_submission_collection", "actor_work_summary",
 })
 WORK_RESOURCE_BY_ACTION = {
-    ActionId.TASK_SUBMISSION_OPERATION_READ: "submission_operation_read",
     ActionId.ACTOR_ASSIGNMENT_LIST: "actor_assignment_collection",
     ActionId.ACTOR_SUBMISSION_LIST: "actor_submission_collection",
     ActionId.ACTOR_WORK_SUMMARY_READ: "actor_work_summary",
diff --git a/backend/app/modules/authorization/domain/submission_history.py b/backend/app/modules/authorization/domain/submission_history.py
index 89458ac61..47ad6f9e3 100644
--- a/backend/app/modules/authorization/domain/submission_history.py
+++ b/backend/app/modules/authorization/domain/submission_history.py
@@ -5,7 +5,7 @@
 
 from pydantic import BaseModel, ConfigDict, Field
 
-from app.modules.authorization.catalogue import ActionAvailability, HISTORY_READ_ACTIONS
+from app.modules.authorization.catalogue import ActionAvailability, ActionId, HISTORY_READ_ACTIONS
 from app.modules.authorization.domain.audit import AuthorizationDenialCode, MatchedAuthorityKind
 from app.modules.authorization.schemas import AdminRole
 
@@ -22,7 +22,22 @@ class HistoryReadResourceContext(BaseModel):
     request_digest: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
 
 
+class OperationReadResourceContext(BaseModel):
+    """Stored intake ownership, including operations without a Submission yet."""
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+    resource_type: Literal["submission_operation_read"] = "submission_operation_read"
+    resource_id: UUID
+    scope_project_id: UUID
+    task_id: UUID
+    contributor_id: UUID
+    actor_profile_id: UUID
+    request_digest: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
+
+
 def _valid_target(action, resource, context):
+    if action in {ActionId.TASK_SUBMISSION_OPERATION_READ, ActionId.PROJECT_TASK_SUBMISSION_OPERATION_READ}:
+        return type(resource) is OperationReadResourceContext and resource.actor_profile_id == context.actor_profile_id
+
     if type(resource) is not HistoryReadResourceContext or resource.actor_profile_id != context.actor_profile_id:
         return False
     name = action.value.removeprefix("project.")
diff --git a/backend/app/modules/authorization/runtime.py b/backend/app/modules/authorization/runtime.py
index 81ca18cfb..287a9276b 100644
--- a/backend/app/modules/authorization/runtime.py
+++ b/backend/app/modules/authorization/runtime.py
@@ -1058,7 +1058,7 @@ def bind_source_operation(self):
     | contributor_reads.ActorProjectListResourceContext | contributor_reads.ContributorWorkReadResourceContext
     | project_catalogue.ProjectCatalogueResourceContext
     | management_reads.ProjectManagementReadResourceContext |
-    submission_history.HistoryReadResourceContext | task_queues.QueueReadResourceContext
+    submission_history.HistoryReadResourceContext | submission_history.OperationReadResourceContext | task_queues.QueueReadResourceContext
     | checker_retry_reads.CheckerRetrySourceReadResourceContext
     | post_submit_deliveries.PostSubmitDeliveryReadResourceContext
     | post_submit_deliveries.PostSubmitDeliveryResourceContext
diff --git a/backend/app/modules/authorization/submission_intake.py b/backend/app/modules/authorization/submission_intake.py
index 391477264..9b4207188 100644
--- a/backend/app/modules/authorization/submission_intake.py
+++ b/backend/app/modules/authorization/submission_intake.py
@@ -11,7 +11,7 @@
     IntakeAcceptanceAuthorityFacts,
 )
 from app.modules.authorization.catalogue import ActionId
-from app.modules.authorization.domain.contributor_reads import ContributorWorkReadResourceContext
+from app.modules.authorization.domain.submission_history import OperationReadResourceContext
 from app.modules.authorization.domain.submission_intake import (
     IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext,
 )
@@ -183,18 +183,21 @@ async def validate_acceptance_receipt(self, facts: IntakeAcceptanceAuthorityFact
                 or event.matched_grant_id is None or event.request_id is None or event.correlation_id is None):
             raise IntakeAuthorityDenied("submission acceptance is unavailable")
 
-    async def authorize_read(self, facts: IntakeOperationReadFacts) -> UUID:
-        """Read own recorded context under current grant, regardless of task status."""
+    async def authorize_read(self, facts: IntakeOperationReadFacts, *, manager: bool = False) -> UUID:
+        """Read retained ownership under fresh contributor or management authority."""
         if (not self._session.in_transaction() or self._session.in_nested_transaction()
                 or type(facts) is not IntakeOperationReadFacts
-                or facts.actor_profile_id != self._context.actor_profile_id):
+                or not isinstance(self._context, HumanAuthorizationContext)):
             raise IntakeAuthorityDenied("submission intake is unavailable")
-        resource = ContributorWorkReadResourceContext(resource_type="submission_operation_read",
-            resource_id=facts.operation_id, actor_profile_id=facts.actor_profile_id,
+        resource = OperationReadResourceContext(
+            resource_id=facts.operation_id, contributor_id=facts.actor_profile_id,
+            actor_profile_id=self._context.actor_profile_id, task_id=facts.task_id,
             scope_project_id=facts.project_id,
             request_digest=canonical_json_hash({key: str(value) for key, value in asdict(facts).items()}))
+        action = (ActionId.PROJECT_TASK_SUBMISSION_OPERATION_READ if manager
+                  else ActionId.TASK_SUBMISSION_OPERATION_READ)
         try:
-            return (await self._kernel.require(ActionId.TASK_SUBMISSION_OPERATION_READ, resource)).decision_id
+            return (await self._kernel.require(action, resource)).decision_id
         except AuthorizationDenied as exc:
             raise IntakeAuthorityDenied("submission intake is unavailable") from exc
 
diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py
index 0e11e145f..23e929493 100644
--- a/backend/tests/artifacts/test_submission_intake_contracts.py
+++ b/backend/tests/artifacts/test_submission_intake_contracts.py
@@ -656,3 +656,42 @@ async def test_evaluation_progress_follows_only_exact_reconciliation_child(chang
         assert observed_id == child_id and expected.payload == payload.model_dump(mode="json")
         assert expected.causation_event_id == event_id and expected.aggregate_id == event_id
     assert deliveries.read_finalized_unknown.await_args.kwargs["lock"] is False
+
+
+@pytest.mark.parametrize("selectors,valid", [
+    ({}, False), ({"operation_id": OPERATION}, True),
+    ({"idempotency_key": OPERATION}, True),
+    ({"operation_id": OPERATION, "idempotency_key": OPERATION}, False),
+    ({"operation_id": "not-a-uuid"}, False),
+    ({"operation_id": OPERATION, "actor_id": TASK}, False),
+])
+def test_operation_progress_requires_one_selector_without_caller_actor_scope(selectors, valid):
+    from app.modules.artifacts.api.submission_command import SubmissionOperationSelector
+    if valid:
+        assert SubmissionOperationSelector.model_validate(selectors)
+    else:
+        with pytest.raises(ValidationError):
+            SubmissionOperationSelector.model_validate(selectors)
+
+
+def test_operation_progress_wire_contract_keeps_nulls_and_rejects_extra_fields():
+    from app.modules.artifacts.api.submission_command import SubmissionOperationResponse
+    values = dict(operation_id=OPERATION, task_id=TASK, assignment_id=ASSIGNMENT,
+        idempotency_key=REVISION, operation_state="receiving", processing_stage="receiving",
+        accepted_at=None, task_status_at_acceptance=None, current_task_status=None,
+        submission_id=None, submission_version=None, evaluation_request_id=None,
+        pre_submission_results=[], failure_code=None, operationally_stalled=False,
+        next_action="wait")
+    response = SubmissionOperationResponse.model_validate(values)
+    assert response.model_dump(mode="json").keys() == values.keys()
+    for key, value in values.items():
+        if value is None:
+            assert response.model_dump(mode="json")[key] is None
+            with pytest.raises(ValidationError):
+                SubmissionOperationResponse.model_validate({k: v for k, v in values.items() if k != key})
+    for updates in ({"provider_key": "secret"}, {"processing_stage": "submitted"},
+                    {"operation_state": "accepted"}, {"current_task_status": "invented"},
+                    {"submission_version": 0}, {"submission_version": True},
+                    {"next_action": "retry_same_key"}):
+        with pytest.raises(ValidationError):
+            SubmissionOperationResponse.model_validate({**values, **updates})
diff --git a/backend/tests/authorization/catalogue_fixtures.py b/backend/tests/authorization/catalogue_fixtures.py
index 1486a7681..d9d0bac74 100644
--- a/backend/tests/authorization/catalogue_fixtures.py
+++ b/backend/tests/authorization/catalogue_fixtures.py
@@ -300,6 +300,7 @@
 expected = {
     "submission.intake.reserve": ("submission.create", "WS-SUBMIT-001"),
     "task.submission_operation.read": ("submission.read_own", "WS-SUBMIT-001"),
+    "project.task.submission_operation.read": ("project.task.manage", "WS-SUBMIT-001"),
     "actor.project.list": ("actor.profile.read_self", "PILOT-READ-2"),
     "project.catalogue.list": ("project.read", "WS-CLI-001-46"),
     **dict.fromkeys(
@@ -582,6 +583,7 @@
 
 AUDIT_ALLOWED_ACTION_VALUES = {
     "submission.intake.reserve", "task.submission_operation.read",
+    "project.task.submission_operation.read",
     "project.catalogue.list",
     "checker.model_call.prepare",
     "checker.model_call.dispatch",
diff --git a/backend/tests/authorization/task_authority/test_intake_authority.py b/backend/tests/authorization/task_authority/test_intake_authority.py
index 3668f4965..e113566fb 100644
--- a/backend/tests/authorization/task_authority/test_intake_authority.py
+++ b/backend/tests/authorization/task_authority/test_intake_authority.py
@@ -271,3 +271,47 @@ async def test_acceptance_authority_rejects_changed_custody(intake_authority, fi
                 AuditEvent.request_id == str(ctx.request_id))))
         finally:
             authority.close()
+
+
+@pytest.mark.parametrize("scope", ["exact", "system", "foreign", "absent", "operator", "revoked"])
+async def test_operation_management_read_uses_current_manager_authority(admin_access, scope):
+    project = await create_project("Operation management read")
+    if scope != "absent":
+        grant_project = (None if scope in {"system", "operator"} else
+                         await create_project("Other operation project") if scope == "foreign" else project)
+        grant_id = await admin_access.signed.grant(
+            admin_access.admin, admin_access.target,
+            role="operator" if scope == "operator" else "project_manager", project_id=grant_project,
+        )
+        if scope == "revoked":
+            revoked = await admin_access.signed.revoke(admin_access.admin, grant_id)
+            assert revoked.status_code == 200, revoked.text
+    ctx = await context(admin_access)
+    read = IntakeOperationReadFacts(new_record_id(), project, new_record_id(), new_record_id())
+    async with db_session.get_session_factory()() as session:
+        authority = SubmissionIntakeAuthorization(session, ctx)
+        try:
+            if scope in {"exact", "system"}:
+                async with session.begin():
+                    decision = await authority.authorize_read(read, manager=True)
+                row = await session.get(AuditEvent, str(decision))
+                assert (row.action_id, row.permission_id, row.matched_grant_id) == (
+                    "project.task.submission_operation.read", "project.task.manage", grant_id)
+                assert row.resource_id == str(read.operation_id)
+                assert row.project_id == str(project)
+                await session.rollback()
+                # Management does not grant the contributor path, even for a known operation.
+                with pytest.raises(IntakeAuthorityDenied):
+                    async with session.begin():
+                        await authority.authorize_read(read)
+            else:
+                with pytest.raises(IntakeAuthorityDenied) as caught:
+                    async with session.begin():
+                        await authority.authorize_read(read, manager=True)
+                assert await authority.restage_denial(caught.value)
+                await session.commit()
+                rows = list(await session.scalars(select(AuditEvent).where(
+                    AuditEvent.request_id == str(ctx.request_id))))
+                assert rows and all(row.after_facts["allowed"] is False for row in rows)
+        finally:
+            authority.close()
diff --git a/backend/tests/authorization/test_catalogue.py b/backend/tests/authorization/test_catalogue.py
index 3dfdfcb74..434b47a29 100644
--- a/backend/tests/authorization/test_catalogue.py
+++ b/backend/tests/authorization/test_catalogue.py
@@ -39,7 +39,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
     assert {item.value for item in HISTORICAL_PERMISSION_IDS} == historical_permissions
     assert {item.value for item in NEW_PERMISSION_IDS} == new_permissions
     assert {item.value for item in PERMISSION_IDS} == historical_permissions | new_permissions
-    assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 194
+    assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 195
     assert set(ACTION_BY_ID) == ACTION_IDS
     assert {definition.owner for definition in ACTION_DEFINITIONS} == set(ActionOwner)
     assert {
@@ -118,7 +118,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() ->
     }
     assert all(not owner.value.startswith("WS-REV-") for owner in ActionOwner)
     assert Counter(definition.availability for definition in ACTION_DEFINITIONS) == {
-        ActionAvailability.ACTIVE: 170,
+        ActionAvailability.ACTIVE: 171,
         ActionAvailability.PLANNED: 24,
     }
     assert (
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 602f56424..b6fb51489 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "847165363b1b89c72011b450992ab83512f5984faa6def5e751eb019423b7370"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "646811e5e0dcd6f22e6a876e4cc71ba5d0075135822e77f45aa99c06974f9e3a"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py
index 3edc8c2ae..4af7b0602 100644
--- a/backend/tests/test_alembic.py
+++ b/backend/tests/test_alembic.py
@@ -2130,3 +2130,23 @@ def test_intake_authority_upgrade_changes_only_two_audit_constraints(isolated_da
     actions = new[("audit_events", "ck_audit_events_authorization_action_evidence")]["definition"]
     assert "submission.intake.reserve" in actions and "task.submission_operation.read" in actions
     assert "artifact.submission_bundle.prepare" in actions and "submission.create" in actions
+
+
+
+def test_operation_management_read_upgrade_preserves_other_schema(isolated_database_env, migration_lock):
+    config = _alembic_config()
+    with migration_lock():
+        asyncio.run(_execute(isolated_database_env, "drop schema public cascade; create schema public"))
+        command.upgrade(config, "0080_cleanup_decisions")
+        before = asyncio.run(build_manifest(isolated_database_env))
+        command.upgrade(config, "0081_operation_read_authority")
+        after = asyncio.run(build_manifest(isolated_database_env))
+    assert {key for key in before if before[key] != after[key]} == {"constraints"}
+    old = {(row["table_name"], row["name"]): row for row in before["constraints"]}
+    new = {(row["table_name"], row["name"]): row for row in after["constraints"]}
+    assert old.keys() == new.keys()
+    target = ("audit_events", "ck_audit_events_authorization_action_evidence")
+    assert {key for key in old if old[key] != new[key]} == {target}
+    addition = " OR action_id::text = 'project.task.submission_operation.read'::text AND permission_id::text = 'project.task.manage'::text"
+    assert new[target]["definition"].count(addition) == 2
+    assert new[target]["definition"].replace(addition, "") == old[target]["definition"]

From 0e45c371eb24f8909e7e88aaa05d8af6d6a54af7 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 15:41:56 +0100
Subject: [PATCH 158/513] feat(submission): expose authorized operation
 progress and governed outcomes

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 255 ++++++++++++++++++
 backend/app/adapters/artifacts/__init__.py    |  48 +++-
 .../app/api/routes/artifact_submissions.py    |  33 ++-
 .../artifacts/api/submission_command.py       |   6 +
 .../app/modules/artifacts/intake/progress.py  | 148 +++++++++-
 .../authorization/api/submission_intake.py    |   9 +
 .../authorization/submission_intake.py        |  28 +-
 .../checkers/api/delivery_reconciliation.py   |  23 +-
 backend/app/modules/checkers/api/execution.py |   3 +-
 .../checkers/delivery_reconciliation.py       |   5 +-
 .../checkers/execution_coordination.py        |   2 +-
 .../app/modules/tasks/api/intake_custody.py   |  18 +-
 .../modules/tasks/api/submission_history.py   |   3 +-
 backend/app/modules/tasks/intake_custody.py   |  29 +-
 .../app/modules/tasks/submission_history.py   |   2 +-
 .../test_submission_foreground_command.py     |  35 +++
 .../test_submission_intake_admission.py       |  58 +++-
 .../test_submission_intake_custody.py         |  44 +++
 .../task_authority/test_intake_authority.py   |  44 +++
 backend/tests/test_api_controls.py            |   5 +-
 .../tests/test_submission_bundle_admission.py |  10 +-
 ..._submission_bundle_preparation_recovery.py | 252 ++++++-----------
 cli/tests/integration/test_submission_http.py |   7 +-
 mcp_server/contracts/actor_get.json           |   3 +-
 mcp_server/contracts/admin_roles_list.json    |   3 +-
 .../contracts/authorization_context_get.json  |   5 +-
 .../test_task_operation_contract_drift.py     |   8 +-
 27 files changed, 871 insertions(+), 215 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 287ada4a6..0d71a8e41 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -4771,3 +4771,258 @@ Freeze this contract/authorization checkpoint for required ARCH/SEC and QA revie
 These are worktree receipts on parent121, not an exact committed-head full suite.
 Public route composition, TASK eligibility/concealment, client progress wiring,
 full journeys/CI and native instability remain open. Keep the one PR708 draft.
+
+
+### Public reader authority selection
+
+Continue in temporary worktree /tmp/workstream-submission-progress-read while the
+primary checkout remains frozen atc11 for its exact-head proof. This is a local
+implementation branch feeding the same PR708, not a second PR or replacement goal.
+The prior allowed public-reader scope and ARCH/SEC/QA review requirements apply.
+First close AUTH selection: the route cannot choose by actor ownership alone,
+because the stored contributor may now have only Project Manager authority.
+Extend the existing intake authority with a composition method selecting its
+existing read decision from current locked grants; never probe access by staging
+an intentional failed decision. Reuse authorize_read for the one actual decision.
+Return separate management visibility and same-owner Submitter-grant facts:
+a dual-role actor must not lose authorized management visibility or be treated as
+management-only for next-action eligibility. These facts do not grant submission;
+TASK must still validate original active assignment, predecessor/revision and
+operation guard. Prefer the manager read when its grant exists, and preserve the
+separately locked contributor fact for subsequent TASK eligibility. Replay callers
+retain the existing explicit contributor path. No client role selector is added.
+Allowed files for this step: AUTH api/submission_intake.py, submission_intake.py,
+existing task_authority/test_intake_authority.py, and this record. Tests exercise
+own Submitter, own Manager, dual-role, other-contributor Manager, wrong contributor,
+foreign Manager and absent grants using real decisions/audit rows. No provider,
+TASK mutation, route exposure or migration changes are part of this selection step.
+
+
+### TASK operation-read visibility and candidate context
+
+Extend the existing IntakeTaskCustodyPort and owner (api/intake_custody.py and
+intake_custody.py) with a read of the operation's exact original assignment.
+Allowed proof extends existing artifacts/test_submission_intake_custody.py.
+This does not change the frozen primary checkout or AUTH selection source under
+test. The reader receives authenticated projection facts from AUTH, checks exact
+TASK/project/assignment/contributor association under TASK-first locks, and exposes
+current status only to management or the active original contributor. A candidate
+new-intake context is returned only for an authorized same-owner Submitter with
+an active original assignment, matching current predecessor and no operation guard.
+Reuse the canonical Submission context service, not a second revision resolver.
+The candidate is not final eligibility: composition must apply the existing locked
+PROJECT revision-capacity and explicit acknowledgement checks before recommending
+a new submission. Missing original ownership is an integrity error. Current
+ineligibility yields no candidate without changing historical operation outcome.
+Acceptance/proof: initial active context, active-operation guard, cleared terminal
+guard, hidden status for non-active/unauthorized contributor projection, manager
+visibility, exact selector substitution refusal; existing AUTH tests supply the
+separate permission proof. No TASK writes or new submission transition are added.
+
+Frozen primary c11 replay passed14 in214.43s with exact c11 metadata,0081 and
+cleanup complete (/tmp/submission-progress-frozen-c11.log/json). ARCH/SEC, QA
+and DOCS/CI scoped reviews now closed with no required repairs.
+Isolated public automatic-authority selection passed7 in45.42s with0081 and
+cleanup complete (/tmp/submission-progress-auto-authority.log/json); these are
+worktree receipts on c11, not committed public-reader delivery. TASK-only additions
+were independent of that AUTH test scope. Closed/reassigned assignment public
+concealment and complete next-action policy checks still require composition proof.
+
+Reviewed commits666be5893,121f8dfbb,c11ed9101 were pushed together to existing
+PR708 branch after all three scoped reviews closed. The public-reader continuation
+remains uncommitted in the temporary worktree; primary checkout stays clean atc11.
+TASK context proof is live under /tmp/submission-progress-task-context-v2.log/json
+(session21862); inspect terminal result before rerunning or claiming proof.
+
+
+### Owner-backed progress read composition
+
+Compose the actual read in existing ART intake/progress.py, existing public
+submission_command.py, canonical adapters/artifacts/__init__.py and public
+api/routes/artifact_submissions.py. Extend existing public/intake tests rather
+than creating another reader subsystem. AUTH selects live read mode after exact
+TASK-first operation locking; key lookup is scoped to the current actor. Validate
+accepted custody with the existing database acceptance verifier, which checks
+retained PRE/receipt/AUTH/event evidence independently of the current reader.
+Read exact TASK finalized association and CHECKERS current attempt; follow the
+existing OUTBOX delivery/reconciliation observer. Governed attempt status outranks
+pending delivery, never current task status. Infrastructure-failed current CHECKERS
+attempt and dead-letter current delivery supply explicit operational stall facts;
+no expired clock alone is a stall. Live worker lease is required for running.
+TASK current status is contextual only; new-key advice requires its candidate plus
+shared locked PROJECT revision capacity and original acknowledgement validation.
+Errors are concealed/sanitized; no storage provider or execution profile is needed
+for a read. Commit the read audit before returning; restage canonical denials after
+rollback. Acceptance: public selectors, actor-scoped key, initial/PRE/accepted/
+finalized state progression, management/own authority, retained-attempt isolation,
+closed/reassigned concealment and bounded failures. Required ARCH/SEC and QA apply.
+
+Allowed API proof includes existing tests/test_api_controls.py exact route/action
+inventory addition and artifacts/test_submission_foreground_command.py public
+acceptance/QC read assertions. TASK context test hit PostgreSQL internal node61440
+during existing guide fixture setup (43.64s), before new assertions; cleanup
+complete. Saved server log /tmp/submission-progress-postgres-before-restart.log,
+confirmed no client backends, and restarted only the owned test PostgreSQL container.
+No native root cause is claimed. Replay the unchanged TASK proof on fresh server.
+
+
+Public accepted/QC progress reads and TASK context proof passed3 (67deselected)
+in203.47s with0081 and cleanup complete (/tmp/submission-progress-public-read.log/json).
+This is scoped portable/local proof after the owned server restart, not resolution
+of native failures. API controls found the intentional new GET needs count134,
+protected132; retain prior inventory hashes by explicitly classifying that new
+route in public_entry_actions, not refreshing unrelated hashes.
+
+CI on pushedc11 found two real public-contract boundary violations introduced in
+prior owner observations: TASK and CHECKERS API contracts import OUTBOX types.
+Do not relax architecture tests. Allowed repair extends tasks/api/submission_history.py,
+tasks/submission_history.py, checkers/api/execution.py, checkers/execution_coordination.py,
+checkers/api/delivery_reconciliation.py, checkers/delivery_reconciliation.py and
+existing intake-admission proof callers. Carry immutable serialized event facts
+across those public boundaries; reconstruct OutboxAppendInput only in private
+composers/observers. Preserve single shared event builders, exact envelopes,
+canonical payload digests and stored-event comparison. Rename the replaced fields
+and helper, update every consumer, and remove the prohibited imports entirely.
+No parallel old/new field or producer is retained. Run the actual architecture
+unit tests as well as module-boundary validation; generic validator alone missed
+these narrower dependency invariants. Other CI lane failures still need artifact
+inspection; /tmp/submission-c11-ci-task-lane.log alone has no terminal diagnosis.
+
+Extend the existing real T5/PRE/POST proof with actual public progress reads
+for finalized queued, worker-live running, completed awaiting governed routing,
+explicit infrastructure stall, and Operator successor retry. Retain all original
+owner association/substitution, retained-data and dispatch assertions. The revised
+API fields carry serialized event envelopes and observers revalidate via OUTBOX
+before exact comparison; public HTTP exposes neither those envelopes nor providers.
+
+### Removed-route test migration
+
+The raw CI task-lane log confirms collection errors in three modules rooted in
+recovery tests importing the removed preparation handler. Migrate the HTTP tests
+in tests/test_submission_bundle_preparation_recovery.py and the binary OpenAPI
+assertion in tests/test_submission_bundle_admission.py to the sole raw-ZIP submit
+contract. Preserve ordered bounded feedback, sanitized error categories, unexpected
+failure propagation and optional packet-text warning semantics. Keep the shared
+_feedback_facts and internal preparation tests until their remaining consumers are
+replaced; no compatibility route or production alias is permitted. This is test
+contract repair with QA review in the existing checkpoint, not a new product path.
+Verify collection of all three affected modules, targeted HTTP assertions and
+existing internal command assertions. Human review focus is preservation of error
+boundaries despite replacement error codes and response schema.
+
+Finalized public progress proof passed all3 cases in165.85s with0081 and isolated
+cleanup complete (/tmp/submission-progress-finalized-public.log/json). One Pydantic
+serializer warning in the existing forged-context case remains visible. This is
+uncommitted worktree proof, not full CI qualification.
+
+The three modules now collect: first execution reached61 cases,29passed/32failed.
+Failures expose the shared feedback fixture still constructing the removed
+zero-project-PRE facts shape (seven missing source evidence fields), plus the
+unexpected-error assertion now encountering mounted middleware's500 conversion.
+Use the existing structural source-completed fixture and required one-project
+member, retaining no-member default rejection; test unexpected propagation at the
+handler boundary as before. Do not relax production evidence validation.
+
+Additional CI repairs allowed: format cli/tests/integration/test_submission_http.py
+using the configured Ruff formatter; reconcile only the missing manager operation
+read ActionId in MCP contract snapshots containing that schema and recompute their
+canonical hashes. Verify full MCP OpenAPI comparison, not only task contracts.
+No unrelated schema refresh is authorized by this repair. Rust runtime log shows
+five unwrap failures in old PRE fixture helpers; investigation remains separate.
+
+Corrected route/fixture replay passed61 in36.52s across all three previously
+uncollectable modules (/tmp/submission-route-migration-v2.log/json), with0081 and
+isolated cleanup complete. The scoped CLI formatter check passes. MCP full drift
+probe still reports an ActionId schema mismatch; inspect exact normalized diff
+before refreshing anything else. The initial local MCP invocation incorrectly
+used PYTHONPATH=src although this package lives at its root; it collected78 tests
+rather than CI's144, so its scope is not accepted as complete MCP qualification.
+
+Exact normalized MCP diagnosis also finds the previously committed source-cleanup
+action, permission and service identity missing in authorization_context_get,
+admin_roles_list and actor_get snapshots. Extend snapshot repair only to these
+three existing enums from canonical authorization catalogue; prohibit removal or
+any other added enum member. This closes existing cleanup contract drift rather
+than changing authorization behavior.
+
+The fail-closed enum updater additionally identifies the already implemented
+artifact.submission.finalize action absent from the authorization-context snapshot
+(no removed actions). Include that exact canonical action in the repair scope.
+The intermediate MCP replay started before this last omission was repaired; its
+result cannot qualify the final snapshots.
+
+Scope correction: inspection of .github/workflows/mcp.yml shows CI's144 cases
+span four drift files; test_contract_drift.py alone has78 cases even with the
+correct package path. The count difference was not evidence of an import failure.
+Run the remaining three files too before claiming equivalence to that CI step.
+
+Final main MCP drift file passed78 in35.75s against configured current backend
+OpenAPI (/tmp/submission-mcp-full-drift-v3.log). Remaining three CI drift files
+are running under /tmp/submission-mcp-remaining-drift.log (session41274).
+Backend-wide collect-only verification is running under
+/tmp/submission-backend-collection.log (session77217). Preserve these live handles;
+do not restart based on observation timeout. All changed Python files passed Ruff
+and git diff --check. Current work remains uncommitted in the temporary worktree.
+
+Remaining MCP drift run passed64 and failed only the exact public route count:
+new operation progress GET makes132, not131. Extend allowed test scope to
+mcp_server/tests/test_task_operation_contract_drift.py: assert the exact GET path,
+security and contributor/management action metadata, then count132. This records
+backend exposure; CLI/MCP progress tool wiring remains required and is not implied
+by this inventory repair. Backend collect-only remains live (session77217).
+
+### Governed completion in public progress proof
+
+Extend only existing artifacts/test_submission_intake_admission.py T5 drill to
+actually deliver the retained POST completion through OUTBOX with fixed dispatcher
+and router authority. After acknowledgement assert public progress reflects the
+persisted governed submission outcome and inspect-governed-outcome next action,
+while preserving all pending/running/stall/retry checks. No direct outcome SQL
+mutation or fabricated acceptance is allowed. This closes the gap between completed
+checker evidence and governed progress. Existing ARCH/SEC and QA review applies.
+
+Backend collection reached12174 tests but8 modules require missing httpx2. This
+is a local environment mismatch: pyproject's agents extra pins httpx2==2.12.0.
+A separate /tmp/workstream-submission-agents-env is being provisioned using
+uv sync --frozen --extra agents, preserving the shared current environment.
+The MCP task-operation inventory replay passed25 in30.46s; combined with78 main
+and the other40 passing drift cases, all four CI drift files have scoped passing
+coverage after the intended inventory repair (not an entire MCP lifecycle suite).
+
+Correct locked agents+dev environment collects all12486 backend tests successfully
+in111.30s (/tmp/submission-backend-agents-collection.log). This closes collection
+only, not execution. Generic module-boundary validation also passed. The new
+real governed-completion drill remains live at /tmp/submission-progress-governed.log
+(session69102); do not claim its outcome yet. Rust investigation shows the failing
+fixture's prepared_generation_id belongs to the superseded PRE material-grant
+path; the corresponding production branch still exists. Its removal and transfer
+of output/cleanup/security proof to supported execution requires a focused owner
+cleanup, not insertion of old fields into the new source-bound request fixture.
+
+Governed drill ended2failed/1passed in171.48s, followed by a Python GC shutdown
+SIGSEGV; isolated cleanup completed. Both non-infrastructure cases dead-lettered.
+Inspection shows ART's seed_started_task_for_artifact_test deliberately arranges
+an ART-only active assignment without accepted_at, while TASK routing requires
+accepted work. Complete that prerequisite in this fixture's initial setup before
+any intake (not after routing), retaining production routing guards. This still
+is not public claim authority proof. Include full delivery outcome on assertion
+failure to distinguish any remaining cause. Replay one successful branch first.
+
+Focused governed replay uses the clean locked agents+dev environment and is live
+under /tmp/submission-progress-governed-v2.log/json (session84882). Fixture-local
+sqlalchemy.text import was corrected before test execution; Ruff/diff pass. Read
+its terminal result before further changes or qualification claims. Public progress
+and CI repairs remain local/uncommitted; required review and same-PR push remain
+outstanding, alongside full goal requirements.
+
+Focused governed replay passed1 in81.80s on the corrected initial assignment,
+with0081 and complete isolated cleanup (/tmp/submission-progress-governed-v2.log/json).
+Real OUTBOX completion delivery acknowledges, TASK persists review_pending and the
+public reader returns inspect_governed_outcome for that original submission.
+This proves the default human-review admission branch, not human terminal review
+or automatic final acceptance. No native crash occurred in this run; its cause
+is still unresolved. Freeze the current public reader plus scoped CI repairs for
+required ARCH/SEC, QA/test-delta and DOCS/CI review, with exact committed-head
+regression to cover all three T5 cases after the fixture correction. CLI/MCP
+progress commands, other governed outcomes, historical/new-revision concealment,
+old runtime removal and full acceptance/qualification remain open.
diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py
index 48f72ac06..9c06165b4 100644
--- a/backend/app/adapters/artifacts/__init__.py
+++ b/backend/app/adapters/artifacts/__init__.py
@@ -9,13 +9,13 @@
 from sqlalchemy.exc import SQLAlchemyError
 
 from app.adapters.auth import selected_pre_submit_authority, submission_intake_authority
-from app.adapters.checkers import selected_pre_submit_checker_execution, selected_pre_submit_coordinator
+from app.adapters.checkers import selected_pre_submit_checker_execution, selected_pre_submit_coordinator, evaluation_coordinator
 from app.adapters.outbox import outbox_append, finalized_unknown_deliveries
-from app.adapters.tasks import intake_task_custody_port
+from app.adapters.tasks import intake_task_custody_port, submission_history_repository
 from app.interfaces.artifacts import ArtifactInputMismatchError, ArtifactLimitExceededError, ArtifactStoreError
 from app.interfaces.external_services import ExternalServiceAdapterError
 from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
-from app.modules.artifacts.api.submission_command import SubmissionExecutionProfile, SubmissionIntakeCommand
+from app.modules.artifacts.api.submission_command import SubmissionExecutionProfile, SubmissionIntakeCommand, SubmissionOperationReader
 from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
 from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization
 from app.modules.artifacts.intake.capacity import SubmissionSourceCapacityConflict
@@ -24,6 +24,7 @@
 from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease
 from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+from app.modules.artifacts.intake.progress import SubmissionOperationReadService
 from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService, SelectedPreSubmitSourceReads
 from app.modules.artifacts.service import artifact_storage_namespace_spec
 from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied
@@ -1202,3 +1203,44 @@ def get_submission_intake_command(
 ) -> SubmissionIntakeCommand:
     return ConfiguredSubmissionCommand(
         settings=request.app.state.settings, sessions=get_session_factory(), context=context)
+
+
+class ConfiguredSubmissionOperationReader:
+    """Read stored progress without provider credentials or an execution profile."""
+
+    def __init__(self, *, sessions, context):
+        self._sessions, self._context = sessions, context
+
+    async def read(self, task_id, selector):
+        from app.modules.checkers.api.execution import CheckerExecutionUnavailable
+        from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextUnavailable
+        from app.modules.tasks.api.submission_history import SubmissionOperationAssociationUnavailable
+
+        async with self._sessions() as session:
+            authority = submission_intake_authority(session, self._context)
+            try:
+                async with session.begin():
+                    service = SubmissionOperationReadService(
+                        session, tasks=intake_task_custody_port(session), authority=authority,
+                        history=submission_history_repository(session), evaluations=evaluation_coordinator(session),
+                        prechecks=selected_pre_submit_coordinator(session), projects=project_locked_policy_context_port(session),
+                        events=outbox_append(session), deliveries=finalized_unknown_deliveries(session),
+                    )
+                    return await service.read(task_id, selector, actor_id=self._context.actor_profile_id)
+            except IntakeAuthorityDenied as exc:
+                if await authority.restage_denial(exc):
+                    await session.commit()
+                raise SubmissionIntakeFailure("submission_unavailable") from None
+            except (IntakeCustodyConflict, TaskSubmissionContextUnavailable, SubmissionOperationAssociationUnavailable,
+                    CheckerExecutionUnavailable, SelectedPreSubmitUnavailable, ProjectLockedPolicyContextUnavailable,
+                    SQLAlchemyError, ValidationError) as exc:
+                logger.exception("Submission operation progress unavailable")
+                raise SubmissionIntakeFailure("submission_infrastructure_unavailable") from exc
+            finally:
+                authority.close()
+
+
+def get_submission_operation_reader(
+    context: Annotated[object, Depends(get_artifact_authorization_context)],
+) -> SubmissionOperationReader:
+    return ConfiguredSubmissionOperationReader(sessions=get_session_factory(), context=context)
diff --git a/backend/app/api/routes/artifact_submissions.py b/backend/app/api/routes/artifact_submissions.py
index 7ad0085c2..4637008a4 100644
--- a/backend/app/api/routes/artifact_submissions.py
+++ b/backend/app/api/routes/artifact_submissions.py
@@ -2,14 +2,17 @@
 from typing import Annotated
 from uuid import UUID
 
-from fastapi import APIRouter, Depends, Request
+from fastapi import APIRouter, Depends, Request, Query
 from fastapi.responses import JSONResponse
 
-from app.adapters.artifacts import get_submission_intake_command
+from app.adapters.artifacts import get_submission_intake_command, get_submission_operation_reader
 from app.api.deps.authorization import get_authorization_actor_identity
 from app.api.submission_intake import SubmissionIntakeHeaders, submission_intake_headers, submission_intake_body
 from app.core.api_controls import error_response
-from app.modules.artifacts.api.submission_command import SubmissionAcceptedResponse, SubmissionIntakeCommand
+from app.modules.artifacts.api.submission_command import (
+    SubmissionAcceptedResponse, SubmissionIntakeCommand, SubmissionOperationReader,
+    SubmissionOperationResponse, SubmissionOperationSelector,
+)
 from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
 from app.modules.authorization.api import ActorIdentityFacts
 
@@ -89,3 +92,27 @@ async def submit_source(
             details=details, retryable=exc.code in {"submission_capacity_exceeded", "submission_infrastructure_unavailable", "submission_outcome_unknown"},
         )
     return SubmissionAcceptedResponse.model_validate(receipt)
+
+
+@router.get(
+    "/tasks/{task_id}/submission-operations", response_model=SubmissionOperationResponse,
+    openapi_extra={
+        "x-workstream-action-id": "task.submission_operation.read",
+        "x-workstream-management-action-id": "project.task.submission_operation.read",
+    },
+    responses={404: {"description": "Operation or current read authority unavailable"},
+               422: {"description": "Exactly one operation UUID or actor-scoped idempotency key is required"},
+               503: {"description": "Stored operation progress cannot be verified"}},
+)
+async def read_submission_operation(
+    task_id: UUID, request: Request,
+    selector: Annotated[SubmissionOperationSelector, Query()],
+    reader: Annotated[SubmissionOperationReader, Depends(get_submission_operation_reader)],
+) -> SubmissionOperationResponse | JSONResponse:
+    """Read this operation's own evidence under current contributor or management authority."""
+    try:
+        return await reader.read(task_id, selector)
+    except SubmissionIntakeFailure as exc:
+        return error_response(request, status_code=_failure_status(exc.code), code=exc.code,
+            message="Submission unavailable" if exc.code == "submission_unavailable" else exc.code,
+            retryable=exc.code == "submission_infrastructure_unavailable")
diff --git a/backend/app/modules/artifacts/api/submission_command.py b/backend/app/modules/artifacts/api/submission_command.py
index e7c893588..e156fab68 100644
--- a/backend/app/modules/artifacts/api/submission_command.py
+++ b/backend/app/modules/artifacts/api/submission_command.py
@@ -112,3 +112,9 @@ class SubmissionOperationResponse(BaseModel):
         "wait", "correct_and_submit_new_key", "retry_new_key_after_terminal",
         "inspect_governed_outcome",
     ]
+
+
+class SubmissionOperationReader(Protocol):
+    async def read(self, task_id: UUID, selector: SubmissionOperationSelector) -> SubmissionOperationResponse:
+        """Read one authorized operation without changing submission state."""
+        ...
diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py
index b62d409f3..c51071304 100644
--- a/backend/app/modules/artifacts/intake/progress.py
+++ b/backend/app/modules/artifacts/intake/progress.py
@@ -11,10 +11,10 @@
 from app.modules.artifacts.api.submission_recovery import (
     FINALIZATION_RECOVERY_EVENT, FINALIZATION_RECOVERY_SOURCES, SubmissionRecoveryPayload,
 )
-from app.modules.outbox.api import OutboxAppendPort, OutboxIdempotencyConflict, DeliveryUnavailable
+from app.modules.outbox.api import OutboxAppendInput, OutboxAppendPort, OutboxIdempotencyConflict, DeliveryUnavailable
 from app.modules.checkers.api.delivery_reconciliation import (
     POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT, POST_SUBMIT_DELIVERY_SUPPORTED_EVENTS,
-    PostSubmitDeliveryChildPayload, post_submit_reconciliation_event,
+    PostSubmitDeliveryChildPayload, post_submit_reconciliation_event_json,
 )
 
 
@@ -90,7 +90,149 @@ async def evaluation_delivery_progress(event_id, event, evaluation, events, deli
                 or payload.evaluation_generation != reservation.evaluation_generation):
             raise IntakeCustodyConflict(unavailable)
         return await events.observe_delivery(
-            retained.child.event_id, post_submit_reconciliation_event(event.project_id, payload),
+            retained.child.event_id, OutboxAppendInput.model_validate_json(post_submit_reconciliation_event_json(event.project_id, payload)),
         )
     except (OutboxIdempotencyConflict, DeliveryUnavailable, ValueError) as exc:
         raise IntakeCustodyConflict(unavailable) from exc
+
+
+class SubmissionOperationReadService:
+    """One root-transaction read across the existing durable evidence owners."""
+
+    def __init__(self, session, *, tasks, authority, history, evaluations, prechecks, projects, events, deliveries):
+        self._session, self._tasks, self._authority = session, tasks, authority
+        self._history, self._evaluations, self._prechecks = history, evaluations, prechecks
+        self._projects, self._events, self._deliveries = projects, events, deliveries
+
+    async def read(self, task_id, selector, *, actor_id):
+        import json
+        from sqlalchemy import text
+        from app.modules.artifacts.api.submission_command import SubmissionOperationResponse
+        from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
+        from app.modules.artifacts.intake.repository import SubmissionIntakeRepository
+        from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied, IntakeOperationReadFacts
+        from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest
+
+        repository = SubmissionIntakeRepository(self._session, self._tasks)
+        operation_id = selector.operation_id
+        if operation_id is None:
+            found = await repository.find_actor_key(actor_id, selector.idempotency_key)
+            if found is None:
+                raise IntakeAuthorityDenied("submission intake is unavailable")
+            operation_id = UUID(found.id)
+        try:
+            row = await repository._lock(operation_id)
+        except IntakeCustodyConflict as exc:
+            if str(exc) == "intake_unavailable":
+                raise IntakeAuthorityDenied("submission intake is unavailable") from None
+            raise
+        if row.task_id != str(task_id):
+            raise IntakeAuthorityDenied("submission intake is unavailable")
+        access = await self._authority.authorize_operation_read(IntakeOperationReadFacts(
+            UUID(row.id), UUID(row.project_id), task_id, UUID(row.actor_profile_id)))
+        metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata))
+        if (metadata.task_id != task_id or metadata.assignment_id != UUID(row.assignment_id)
+                or metadata.metadata_sha256() != row.metadata_sha256):
+            raise IntakeCustodyConflict("submission_operation_metadata_inconsistent")
+        current = await self._tasks.read_operation_context(
+            TaskSubmissionContextRequest(task_id, UUID(row.assignment_id), UUID(row.actor_profile_id),
+                                         metadata.predecessor_submission_id),
+            project_id=UUID(row.project_id), reader_id=actor_id,
+            management=access.management, own_submitter=access.own_submitter,
+        )
+        accepted = row.state in {"finalization_pending", "finalized"}
+        if accepted:
+            await self._session.execute(text("SELECT public.require_submission_acceptance(o) "
+                "FROM public.submission_intake_operations o WHERE id=:id"), {"id": UUID(row.id)})
+            results = row.acceptance_receipt["pre_submission_results"]
+        else:
+            results = await self._feedback(row, repository)
+        stage, action, stalled = row.state, "wait", False
+        submission_id = version = request_id = None
+        if row.state == "finalization_pending":
+            progress = await finalization_progress(row, self._events, self._deliveries)
+            stalled = progress.operationally_stalled
+            stage = "operationally_stalled" if stalled else "finalization_pending"
+        elif row.state == "finalized":
+            if row.finalized_submission_id is None or row.finalized_admission_id is None:
+                raise IntakeCustodyConflict("submission_operation_association_unavailable")
+            outcome = await self._history.read_operation_outcome(
+                project_id=UUID(row.project_id), task_id=task_id, assignment_id=UUID(row.assignment_id),
+                contributor_id=UUID(row.actor_profile_id), submission_id=UUID(row.finalized_submission_id),
+                admission_id=UUID(row.finalized_admission_id),
+            )
+            evaluation = await self._evaluations.read_current_progress(
+                project_id=UUID(row.project_id), task_id=task_id, submission_id=outcome.submission_id,
+                original_request_id=outcome.evaluation_request_id,
+            )
+            submission_id, version = outcome.submission_id, outcome.submission_version
+            request_id = evaluation.current.request.evaluation_request_id
+            if outcome.status != "evaluation_pending":
+                stage, action = outcome.status, "inspect_governed_outcome"
+            else:
+                event_id = evaluation.completion_event_id or evaluation.retry_event_id or outcome.evaluation_event_id
+                event = OutboxAppendInput.model_validate_json(evaluation.delivery_event_json or outcome.evaluation_event_json)
+                delivery = await evaluation_delivery_progress(event_id, event, evaluation, self._events, self._deliveries)
+                stalled = evaluation.status == "infrastructure_failed" or delivery.state == "dead_letter"
+                stage = ("operationally_stalled" if stalled else
+                         "evaluation_running" if evaluation.live_worker_lease else "evaluation_pending")
+        elif row.state in {"rejected", "failed", "abandoned", "cancelled"}:
+            action = "inspect_governed_outcome"
+            if row.state != "cancelled" and await self._permits_new_intake(current.candidate, metadata):
+                action = "correct_and_submit_new_key" if row.state == "rejected" else "retry_new_key_after_terminal"
+        code = row.failure_code
+        if code is not None and code not in {
+            "submission_packet_invalid", "submission_archive_limit_exceeded", "submission_upload_timeout",
+            "submission_infrastructure_unavailable", "pre_submission_checker_failed",
+            "submission_foreground_expired", "submission_operation_cancelled",
+        }:
+            code = "submission_operation_terminal"
+        return SubmissionOperationResponse(
+            operation_id=UUID(row.id), task_id=task_id, assignment_id=UUID(row.assignment_id),
+            idempotency_key=UUID(row.idempotency_key), operation_state=row.state,
+            processing_stage=stage, accepted_at=row.accepted_at,
+            task_status_at_acceptance="evaluation_pending" if accepted else None,
+            current_task_status=current.current_task_status, submission_id=submission_id,
+            submission_version=version, evaluation_request_id=request_id,
+            pre_submission_results=results, failure_code=code, operationally_stalled=stalled, next_action=action,
+        )
+
+    async def _feedback(self, row, repository):
+        from app.modules.artifacts.api.submission_preparation import public_pre_submission_results
+        terminal = await self._prechecks.read_source_terminal(source_operation_id=UUID(row.id))
+        if terminal is None or terminal.execution is None:
+            return []
+        reservation = terminal.lease.reservation
+        if (reservation.metadata_sha256 != row.metadata_sha256
+                or reservation.actor_profile_id != UUID(row.actor_profile_id)
+                or reservation.idempotency_key != UUID(row.idempotency_key)
+                or reservation.task_id != UUID(row.task_id)
+                or reservation.assignment_id != UUID(row.assignment_id)
+                or reservation.source != repository._sealed_source(row)):
+            raise IntakeCustodyConflict("submission_operation_pre_inconsistent")
+        return public_pre_submission_results(terminal.execution)
+
+    async def _permits_new_intake(self, candidate, metadata):
+        from dataclasses import asdict
+        from app.modules.projects.api.locked_policy import (
+            ProjectLockedPolicyContextRequest, ProjectLockedPolicyContextUnavailable,
+        )
+        from app.modules.projects.api.policy_lineage import RevisionPolicySemantics
+        from app.modules.tasks.api.submission_context import (
+            TaskSubmissionContextUnavailable, require_revision_acknowledgement, require_revision_capacity,
+        )
+        if candidate is None:
+            return False
+        references = asdict(candidate.locked_project_context)
+        references.pop("locked_contribution_policy_version_id")
+        try:
+            project = await self._projects.lock_locked_policy_context(ProjectLockedPolicyContextRequest(**references))
+            if candidate.predecessor is not None:
+                revision = project.activation_receipt.command.revision
+                require_revision_capacity(candidate, project_id=project.project_id,
+                    policy_id=revision.policy_id, policy_generation=revision.generation, policy_hash=revision.policy_hash,
+                    max_revision_rounds=RevisionPolicySemantics.model_validate_json(project.revision_policy.value).max_revision_rounds)
+            require_revision_acknowledgement(candidate, metadata.revision_preparation_id, metadata.revision_preparation_sha256)
+        except (ProjectLockedPolicyContextUnavailable, TaskSubmissionContextUnavailable):
+            return False
+        return True
diff --git a/backend/app/modules/authorization/api/submission_intake.py b/backend/app/modules/authorization/api/submission_intake.py
index cf11d284b..7a86217d5 100644
--- a/backend/app/modules/authorization/api/submission_intake.py
+++ b/backend/app/modules/authorization/api/submission_intake.py
@@ -52,6 +52,14 @@ class IntakeOperationReadFacts:
     actor_profile_id: UUID
 
 
+@dataclass(frozen=True, slots=True)
+class IntakeOperationReadAccess:
+    """Current read projection facts; TASK still owns all submission eligibility."""
+    decision_id: UUID
+    management: bool
+    own_submitter: bool
+
+
 class IntakeAuthorityDenied(RuntimeError):
     """Concealed intake authorization failure."""
 
@@ -66,5 +74,6 @@ async def prepare_acceptance(self, facts: IntakeAcceptanceAuthorityFacts) -> obj
     async def consume_acceptance(self, handle: object, facts: IntakeAcceptanceAuthorityFacts) -> UUID: ...
     async def validate_acceptance_receipt(self, facts: IntakeAcceptanceAuthorityFacts, decision_id: UUID) -> None: ...
     async def authorize_read(self, facts: IntakeOperationReadFacts, *, manager: bool = False) -> UUID: ...
+    async def authorize_operation_read(self, facts: IntakeOperationReadFacts) -> IntakeOperationReadAccess: ...
     async def restage_denial(self, error: IntakeAuthorityDenied) -> bool: ...
     def close(self) -> None: ...
diff --git a/backend/app/modules/authorization/submission_intake.py b/backend/app/modules/authorization/submission_intake.py
index 9b4207188..01780baab 100644
--- a/backend/app/modules/authorization/submission_intake.py
+++ b/backend/app/modules/authorization/submission_intake.py
@@ -8,9 +8,10 @@
 from app.core.hashing import canonical_json_hash
 from app.modules.authorization.api.submission_intake import (
     IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts,
-    IntakeAcceptanceAuthorityFacts,
+    IntakeAcceptanceAuthorityFacts, IntakeOperationReadAccess,
 )
-from app.modules.authorization.catalogue import ActionId
+from app.modules.authorization.catalogue import ActionId, PermissionId
+from app.modules.authorization.schemas import AdminRole
 from app.modules.authorization.domain.submission_history import OperationReadResourceContext
 from app.modules.authorization.domain.submission_intake import (
     IntakeReservationResourceContext, IntakeReservationPreflightResourceContext, IntakeAcceptanceResourceContext,
@@ -201,6 +202,29 @@ async def authorize_read(self, facts: IntakeOperationReadFacts, *, manager: bool
         except AuthorizationDenied as exc:
             raise IntakeAuthorityDenied("submission intake is unavailable") from exc
 
+    async def authorize_operation_read(self, facts: IntakeOperationReadFacts) -> IntakeOperationReadAccess:
+        """Select public read authority from live grants, not a client role flag."""
+        context = self._context
+        if type(facts) is not IntakeOperationReadFacts or not isinstance(context, HumanAuthorizationContext):
+            raise IntakeAuthorityDenied("submission intake is unavailable")
+        await self.lock_actor(context.actor_profile_id, context.identity_link_id)
+        manager = await self._repository.find_effective_grant(
+            context.actor_profile_id, PermissionId.PROJECT_TASK_MANAGE,
+            scope_project_id=facts.project_id, for_update=True,
+            allowed_roles=frozenset({AdminRole.PROJECT_MANAGER}),
+        )
+        submitter = None
+        if facts.actor_profile_id == context.actor_profile_id:
+            submitter = await self._repository.find_active_project_role(
+                project_id=facts.project_id, actor_profile_id=context.actor_profile_id,
+                role="submitter", for_update=True,
+            )
+        # A foreign contributor needs management authority even when no such
+        # grant exists; the kernel records that exact denied request once.
+        management = manager is not None or facts.actor_profile_id != context.actor_profile_id
+        decision_id = await self.authorize_read(facts, manager=management)
+        return IntakeOperationReadAccess(decision_id, management, submitter is not None)
+
     async def restage_denial(self, error: IntakeAuthorityDenied) -> bool:
         """Restage only this request kernel's retained denial after root rollback."""
         if isinstance(error.__cause__, AuthorizationDenied):
diff --git a/backend/app/modules/checkers/api/delivery_reconciliation.py b/backend/app/modules/checkers/api/delivery_reconciliation.py
index cae8bf89b..96c1d72f7 100644
--- a/backend/app/modules/checkers/api/delivery_reconciliation.py
+++ b/backend/app/modules/checkers/api/delivery_reconciliation.py
@@ -9,7 +9,6 @@
 from pydantic import AwareDatetime, AfterValidator, BaseModel, ConfigDict, Field, model_validator
 
 from app.core.hashing import canonical_json_hash
-from app.modules.outbox.api import OutboxAppendInput
 from app.modules.checkers.api.evaluation_contract import PostSubmissionExecutionRequest
 
 
@@ -367,15 +366,15 @@ def close(self, handle: object) -> None: ...
     async def restage_denial(self, error: PostSubmitDeliveryAuthorityDenied) -> bool: ...
 
 
-def post_submit_reconciliation_event(
+def post_submit_reconciliation_event_json(
     project_id: UUID, payload: PostSubmitDeliveryChildPayload,
-) -> OutboxAppendInput:
-    """Exact child envelope shared by publication and read-only observation."""
-    return OutboxAppendInput(
-        event_type=POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT, event_version=1,
-        aggregate_type="outbox_delivery", aggregate_id=payload.original_event_id,
-        project_id=project_id, correlation_id=str(payload.reconciliation_request_id),
-        causation_event_id=payload.original_event_id,
-        idempotency_key="post-submit-reconcile:" + str(payload.original_event_id),
-        payload=payload.model_dump(mode="json"),
-    )
+) -> str:
+    """Immutable child envelope shared by publication and read-only observation."""
+    return json.dumps({
+        "event_type": POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT, "event_version": 1,
+        "aggregate_type": "outbox_delivery", "aggregate_id": str(payload.original_event_id),
+        "project_id": str(project_id), "correlation_id": str(payload.reconciliation_request_id),
+        "causation_event_id": str(payload.original_event_id),
+        "idempotency_key": "post-submit-reconcile:" + str(payload.original_event_id),
+        "payload": payload.model_dump(mode="json"),
+    }, sort_keys=True, separators=(",", ":"))
diff --git a/backend/app/modules/checkers/api/execution.py b/backend/app/modules/checkers/api/execution.py
index e79cb26ce..c521bc8ea 100644
--- a/backend/app/modules/checkers/api/execution.py
+++ b/backend/app/modules/checkers/api/execution.py
@@ -10,7 +10,6 @@
 from pydantic import AfterValidator, AwareDatetime, Field, model_validator
 
 from app.core.hashing import canonical_json_hash
-from app.modules.outbox.api import OutboxAppendInput
 
 from app.modules.checkers.api.evaluation_contract import (
     PostSubmissionExecutionRequest,
@@ -348,7 +347,7 @@ class EvaluationProgress(CheckerValue):
     live_worker_lease: bool
     retry_event_id: ResourceId | None
     completion_event_id: ResourceId | None
-    delivery_event: OutboxAppendInput | None
+    delivery_event_json: str | None
 
 
 class ExecutionLease(CheckerValue):
diff --git a/backend/app/modules/checkers/delivery_reconciliation.py b/backend/app/modules/checkers/delivery_reconciliation.py
index 7a0752369..e12e22afa 100644
--- a/backend/app/modules/checkers/delivery_reconciliation.py
+++ b/backend/app/modules/checkers/delivery_reconciliation.py
@@ -30,7 +30,7 @@
     POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT,
     POST_SUBMIT_DELIVERY_SUPPORTED_EVENTS,
     post_submit_delivery_request_digest,
-    post_submit_reconciliation_event,
+    post_submit_reconciliation_event_json,
 )
 from app.modules.checkers.api.execution import (
     COMPLETION_EVENT,
@@ -41,6 +41,7 @@
 )
 from app.modules.checkers.api.evaluation_contract import PostSubmissionExecutionRequest
 from app.modules.outbox.api import (
+    OutboxAppendInput,
     DeliveryUnavailable,
     FinalizedUnknownDelivery,
     FinalizedUnknownDeliveryPort,
@@ -322,7 +323,7 @@ async def reconcile(
             )
             try:
                 appended = await self._events.append(
-                    post_submit_reconciliation_event(source.project_id, payload)
+                    OutboxAppendInput.model_validate_json(post_submit_reconciliation_event_json(source.project_id, payload))
                 )
             except OutboxIdempotencyConflict as exc:
                 raise PostSubmitDeliveryConflict(
diff --git a/backend/app/modules/checkers/execution_coordination.py b/backend/app/modules/checkers/execution_coordination.py
index e1d386a24..34b779e62 100644
--- a/backend/app/modules/checkers/execution_coordination.py
+++ b/backend/app/modules/checkers/execution_coordination.py
@@ -265,7 +265,7 @@ async def read_current_progress(
         return EvaluationProgress(
             current=current, status=run.status, live_worker_lease=live,
             retry_event_id=retry_event_id, completion_event_id=run.completion_event_id,
-            delivery_event=delivery_event,
+            delivery_event_json=delivery_event.model_dump_json() if delivery_event is not None else None,
         )
 
     async def read_retry_delivery(
diff --git a/backend/app/modules/tasks/api/intake_custody.py b/backend/app/modules/tasks/api/intake_custody.py
index 8fa56bfc2..db88bce11 100644
--- a/backend/app/modules/tasks/api/intake_custody.py
+++ b/backend/app/modules/tasks/api/intake_custody.py
@@ -4,7 +4,8 @@
 from typing import Protocol
 from uuid import UUID
 
-from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest
+from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest, TaskSubmissionContextFacts
+from app.modules.tasks.api.management_queue import TaskStatus
 
 
 @dataclass(frozen=True, slots=True)
@@ -16,6 +17,13 @@ class IntakeTaskSnapshot:
     context_json: str
 
 
+@dataclass(frozen=True, slots=True)
+class IntakeTaskReadContext:
+    """Current visibility and candidate facts, never a historical attempt outcome."""
+    current_task_status: TaskStatus | None
+    candidate: TaskSubmissionContextFacts | None
+
+
 class IntakeTaskCustodyPort(Protocol):
     """Maintain the pointer and T4 pending state inside authorized owner work."""
 
@@ -38,3 +46,11 @@ async def release(self, task_id: UUID, operation_id: UUID) -> None:
     async def accept(self, task_id: UUID, operation_id: UUID, expected_status: str) -> None:
         """T4-only direct transition; deferred custody requires exact accepted AUTH/event."""
         ...
+
+
+    async def read_operation_context(
+        self, request: TaskSubmissionContextRequest, *, project_id: UUID,
+        reader_id: UUID, management: bool, own_submitter: bool,
+    ) -> IntakeTaskReadContext:
+        """After AUTH, read visibility and a candidate needing locked policy/ack checks."""
+        ...
diff --git a/backend/app/modules/tasks/api/submission_history.py b/backend/app/modules/tasks/api/submission_history.py
index d858098a9..00a0b5b22 100644
--- a/backend/app/modules/tasks/api/submission_history.py
+++ b/backend/app/modules/tasks/api/submission_history.py
@@ -7,7 +7,6 @@
 from typing import Literal, Protocol
 from uuid import UUID
 
-from app.modules.outbox.api import OutboxAppendInput
 
 HistoryKind = Literal["task_submission_history", "submission_history", "checker_history"]
 
@@ -150,7 +149,7 @@ class SubmissionOperationOutcome:
     status: SubmissionAttemptStatus
     evaluation_request_id: UUID
     evaluation_event_id: UUID
-    evaluation_event: OutboxAppendInput
+    evaluation_event_json: str
 
 
 class SubmissionHistoryReadPort(Protocol):
diff --git a/backend/app/modules/tasks/intake_custody.py b/backend/app/modules/tasks/intake_custody.py
index e47d6e6f3..991b3d350 100644
--- a/backend/app/modules/tasks/intake_custody.py
+++ b/backend/app/modules/tasks/intake_custody.py
@@ -6,7 +6,7 @@
 from sqlalchemy import text
 from sqlalchemy.ext.asyncio import AsyncSession
 
-from app.modules.tasks.api.intake_custody import IntakeTaskSnapshot
+from app.modules.tasks.api.intake_custody import IntakeTaskSnapshot, IntakeTaskReadContext
 from app.modules.tasks.api.submission_context import (
     TaskSubmissionContextPort, TaskSubmissionContextRequest, TaskSubmissionContextUnavailable,
 )
@@ -77,3 +77,30 @@ async def accept(self, task_id: UUID, operation_id: UUID, expected_status: str)
             raise TaskSubmissionContextUnavailable("task_submission_context_invalid")
         task.status = "evaluation_pending"
         await self._session.flush()
+
+
+    async def read_operation_context(
+        self, request: TaskSubmissionContextRequest, *, project_id: UUID,
+        reader_id: UUID, management: bool, own_submitter: bool,
+    ) -> IntakeTaskReadContext:
+        """Keep current visibility separate from the operation's retained outcome."""
+        if await self.lock(request.task_id) != project_id:
+            raise TaskSubmissionContextUnavailable("task_submission_context_invalid")
+        task = await self._tasks.get_task(str(request.task_id), for_update=True)
+        assignment = await self._tasks.lock_accepted_assignment(
+            project_id=project_id, task_id=request.task_id, assignment_id=request.assignment_id,
+        )
+        if assignment is None or assignment.contributor_id != str(request.contributor_id):
+            raise TaskSubmissionContextUnavailable("task_submission_context_invalid")
+        own_active = (reader_id == request.contributor_id and assignment.status == "active"
+                      and task.assigned_to == str(request.contributor_id))
+        visible = management or (own_submitter and own_active)
+        status = task.status if visible else None
+        if (not own_submitter or not own_active or task.active_submission_operation_id is not None
+                or task.status not in {"in_progress", "needs_revision"}):
+            return IntakeTaskReadContext(status, None)
+        try:
+            candidate = await self._contexts.lock_submission_context(request)
+        except TaskSubmissionContextUnavailable:
+            return IntakeTaskReadContext(status, None)
+        return IntakeTaskReadContext(status, candidate)
diff --git a/backend/app/modules/tasks/submission_history.py b/backend/app/modules/tasks/submission_history.py
index 1ec3803fd..b831360cd 100644
--- a/backend/app/modules/tasks/submission_history.py
+++ b/backend/app/modules/tasks/submission_history.py
@@ -132,5 +132,5 @@ async def read_operation_outcome(
             submission_id=UUID(row.id), submission_version=row.version,
             status=row.attempt_status, evaluation_request_id=UUID(row.SubmissionDispatch.evaluation_request_id),
             evaluation_event_id=UUID(str(row.SubmissionDispatch.evaluation_event_id)),
-            evaluation_event=evaluation_request_event(row.SubmissionDispatch),
+            evaluation_event_json=evaluation_request_event(row.SubmissionDispatch).model_dump_json(),
         )
diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py
index 113230e28..39e84d2c2 100644
--- a/backend/tests/artifacts/test_submission_foreground_command.py
+++ b/backend/tests/artifacts/test_submission_foreground_command.py
@@ -85,6 +85,41 @@ async def execute(lease, grant):
         assert first.json()["error"]["code"] == second.json()["error"]["code"] == "pre_submission_checker_failed"
         assert first.json()["error"]["details"] == second.json()["error"]["details"]
         assert first.json()["error"]["details"]["eligible_to_submit"] is False
+    if framing == "small":
+        # Reads need no writer/runtime deployment configuration or provider bootstrap.
+        monkeypatch.setattr(app.state, "settings", settings.model_copy(update={"submission_execution_profile": None}))
+        progress_url = f"/api/v1/tasks/{f.task}/submission-operations"
+        progress = await client.get(progress_url, headers=f.access.target.headers,
+                                    params={"idempotency_key": str(key)})
+        assert progress.status_code == 200, progress.text
+        observed = progress.json()
+        expected = "finalization_pending" if outcome == "completed" else "rejected"
+        assert observed["operation_state"] == observed["processing_stage"] == expected
+        assert observed["next_action"] == ("wait" if outcome == "completed" else "correct_and_submit_new_key")
+        assert observed["operationally_stalled"] is False
+        assert observed["current_task_status"] == ("evaluation_pending" if outcome == "completed" else "in_progress")
+        assert observed["submission_id"] is observed["submission_version"] is observed["evaluation_request_id"] is None
+        assert observed["pre_submission_results"] == (receipt["pre_submission_results"] if outcome == "completed"
+                                                       else first.json()["error"]["details"]["results"])
+        by_id = await client.get(progress_url, headers=f.access.target.headers,
+                                 params={"operation_id": observed["operation_id"]})
+        assert by_id.status_code == 200 and by_id.json() == observed, by_id.text
+        managed = await client.get(progress_url, headers=f.manager.headers,
+                                   params={"operation_id": observed["operation_id"]})
+        assert managed.status_code == 200, managed.text
+        assert managed.json()["processing_stage"] == expected
+        assert managed.json()["next_action"] == ("wait" if outcome == "completed" else "inspect_governed_outcome")
+        manager_key = await client.get(progress_url, headers=f.manager.headers,
+                                       params={"idempotency_key": str(key)})
+        assert manager_key.status_code == 404, manager_key.text
+        stranger = await f.access.signed.actor("progress-stranger")
+        concealed = await client.get(progress_url, headers=stranger.headers,
+                                     params={"operation_id": observed["operation_id"]})
+        assert concealed.status_code == 404, concealed.text
+        for params in ({}, {"operation_id": observed["operation_id"], "idempotency_key": str(key)},
+                       {"operation_id": "invalid"}, {"operation_id": observed["operation_id"], "actor_id": str(f.actor.actor_profile_id)}):
+            invalid = await client.get(progress_url, headers=f.access.target.headers, params=params)
+            assert invalid.status_code == 422, invalid.text
     async with f.factory() as session:
         assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": f.task}) == 0
         assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations WHERE task_id=:id"), {"id": f.task}) == 1
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 016a2cffd..459bf04ec 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -52,6 +52,7 @@ async def test_stalled_accepted_source_is_protected_from_cleanup(recovery_intake
 
 @pytest.fixture
 async def admission_intake(tmp_path, isolated_database_env, admin_access, request):
+    from sqlalchemy import text
     from app.adapters.outbox import outbox_append, finalized_unknown_deliveries
     from app.adapters.projects import project_locked_policy_context_port
     from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission
@@ -94,6 +95,10 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
             await seed_started_task_for_artifact_test(connection, dict(
                 task=str(task), assignment=str(assignment), project=str(project), actor=str(actor.actor_profile_id),
             ))
+            # ART's shared seed omits work acceptance; this fixture also proves TASK routing.
+            await connection.execute(text(
+                "UPDATE task_assignments SET accepted_at=clock_timestamp() WHERE id=:id"
+            ), {"id": assignment})
         admission = ForegroundIntakeAdmission(
             factory, tasks=lambda session: IntakeTaskCustody(session, task_submission_context_port(session)),
             task_contexts=task_submission_context_port, projects=project_locked_policy_context_port,
@@ -808,6 +813,7 @@ async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(ad
     from app.adapters.checkers import selected_pre_submit_coordinator
     from app.adapters.outbox import outbox_append
     from app.adapters.tasks import accepted_submission_creation_service
+    from app.modules.outbox.api import OutboxAppendInput
     from app.modules.actors.api import ServiceIdentity
     from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
     from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
@@ -839,6 +845,23 @@ def submissions(session):
         assert await finalizer.run(owner.operation_id) == result
         assert await f.admission.accept(owner, request, terminal.terminal_digest,
             checkers=selected_pre_submit_coordinator, outbox=outbox_append) == dict(accepted, replayed=True)
+        async def public_progress(stage, evaluation_request_id, *, stalled=False, governed=False):
+            response = await f.access.signed.client.get(
+                f"/api/v1/tasks/{f.task}/submission-operations", headers=f.access.target.headers,
+                params={"operation_id": str(owner.operation_id)},
+            )
+            assert response.status_code == 200, response.text
+            observed = response.json()
+            assert observed["operation_state"] == "finalized"
+            assert observed["submission_id"] == str(result.submission_id)
+            assert observed["submission_version"] == result.submission_version
+            assert observed["evaluation_request_id"] == str(evaluation_request_id)
+            assert observed["processing_stage"] == stage
+            assert observed["operationally_stalled"] is stalled
+            assert observed["next_action"] == ("inspect_governed_outcome" if governed else "wait")
+            return observed
+
+        await public_progress("evaluation_pending", result.evaluation_request_id)
         async with f.factory() as session:
             row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
             assert row.state == "finalized" and row.finalized_submission_id == str(result.submission_id)
@@ -890,7 +913,7 @@ def submissions(session):
             from app.modules.artifacts.intake.progress import evaluation_delivery_progress
             from app.adapters.outbox import finalized_unknown_deliveries
             pending = await evaluation_delivery_progress(
-                outcome.evaluation_event_id, outcome.evaluation_event, queued,
+                outcome.evaluation_event_id, OutboxAppendInput.model_validate_json(outcome.evaluation_event_json), queued,
                 outbox_append(session), finalized_unknown_deliveries(session),
             )
             assert pending.state == "pending"
@@ -928,6 +951,7 @@ async def observe_running(runtime, execution_request, grant):
                 assert running.status == "running" and running.live_worker_lease
                 assert running.completion_event_id is None
                 running_observations.append(running)
+            await public_progress("evaluation_running", result.evaluation_request_id)
             return await original_execute(runtime, execution_request, grant)
         with monkeypatch.context() as patch:
             patch.setattr(ControlledSelectedExecution, "execute", observe_running)
@@ -949,10 +973,12 @@ def missing_source(*_args, **_kwargs):
             assert completed.retry_event_id is None
             if not post_failure:
                 pending_completion = await evaluation_delivery_progress(
-                    completed.completion_event_id, completed.delivery_event, completed,
+                    completed.completion_event_id, OutboxAppendInput.model_validate_json(completed.delivery_event_json), completed,
                     outbox_append(session), finalized_unknown_deliveries(session),
                 )
                 assert pending_completion.state == "pending"
+        await public_progress("operationally_stalled" if post_failure else "evaluation_pending",
+                              result.evaluation_request_id, stalled=post_failure)
         if post_failure:
             from app.adapters.checkers import checker_retry_service
             from tests.checkers.execution.test_checker_retry import _operator_for, _command
@@ -967,10 +993,36 @@ def missing_source(*_args, **_kwargs):
                 assert retrying.retry_event_id == retry.successor.event_id
                 assert retrying.completion_event_id is None
                 pending_retry = await evaluation_delivery_progress(
-                    retrying.retry_event_id, retrying.delivery_event, retrying,
+                    retrying.retry_event_id, OutboxAppendInput.model_validate_json(retrying.delivery_event_json), retrying,
                     outbox_append(session), finalized_unknown_deliveries(session),
                 )
                 assert pending_retry.state == "pending"
+            await public_progress("evaluation_pending", retrying.current.request.evaluation_request_id)
+        else:
+            from app.adapters.auth import outbox_dispatch_authorization
+            from app.adapters.outbox import outbox_delivery
+            from app.adapters.tasks import evaluation_completion_handler
+            from app.modules.checkers.api.execution import COMPLETION_EVENT
+            from app.modules.outbox.api import DeliveryOptions
+            from app.modules.outbox.registry import HandlerRegistry
+            from tests.authorization.post_submit_routing.support import provision_router
+            from tests.tasks.evaluation_delivery.support import outcome as delivery_outcome
+
+            await provision_post_submit_service(f.factory, ServiceIdentity.OUTBOX_DISPATCHER)
+            await provision_router(f.factory)
+            dispatcher = outbox_delivery(
+                f.factory, authorization_factory=outbox_dispatch_authorization,
+                registry=HandlerRegistry([(COMPLETION_EVENT, 1,
+                    evaluation_completion_handler(sessions=f.factory))]),
+                options=DeliveryOptions(),
+            )
+            delivered = await dispatcher.deliver(
+                completed.completion_event_id, f.project, "source-progress-governed-outcome")
+            assert delivery_outcome(delivered)["delivery_state"] == "acknowledged", delivery_outcome(delivered)
+            async with f.factory.begin() as session:
+                governed = await submission_history_repository(session).read_operation_outcome(**selectors)
+                assert governed.status == "review_pending"
+            await public_progress("review_pending", result.evaluation_request_id, governed=True)
 
     finally:
         store.close()
diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py
index 9fd10054e..870def557 100644
--- a/backend/tests/artifacts/test_submission_intake_custody.py
+++ b/backend/tests/artifacts/test_submission_intake_custody.py
@@ -967,3 +967,47 @@ def command(*owner):
     with pytest.raises(IntakeCustodyConflict, match="renewal_expired"):
         await runner.run(operation, lease, 1, command)
     assert not called
+
+
+async def test_operation_read_context_keeps_visibility_and_guard_separate(intake):
+    from dataclasses import replace
+    from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest
+
+    request = TaskSubmissionContextRequest(intake.task, intake.assignment,
+        intake.actor.actor_profile_id, None)
+    async with intake.factory.begin() as session:
+        owner = IntakeTaskCustody(session, task_submission_context_port(session))
+        project_id = await owner.lock(intake.task)
+
+        async def read(selected=request, **updates):
+            return await owner.read_operation_context(selected, **{
+                "project_id": project_id, "reader_id": request.contributor_id,
+                "management": False, "own_submitter": True, **updates,
+            })
+
+        initial = await read()
+        assert initial.current_task_status == "in_progress"
+        assert initial.candidate is not None and initial.candidate.assignment_id == intake.assignment
+        changed_predecessor = await read(replace(request, predecessor_submission_id=new_record_id()))
+        assert changed_predecessor.current_task_status == "in_progress"
+        assert changed_predecessor.candidate is None
+        # These booleans are already authorized by AUTH; this proves only TASK projection.
+        management = await read(reader_id=new_record_id(), management=True, own_submitter=False)
+        assert management.current_task_status == "in_progress" and management.candidate is None
+        hidden = await read(reader_id=new_record_id())
+        assert hidden.current_task_status is None and hidden.candidate is None
+        read_only = await read(own_submitter=False)
+        assert read_only.current_task_status is None and read_only.candidate is None
+        for field in ("task_id", "assignment_id", "contributor_id"):
+            with pytest.raises(TaskSubmissionContextUnavailable):
+                await read(replace(request, **{field: new_record_id()}))
+        with pytest.raises(TaskSubmissionContextUnavailable):
+            await read(project_id=new_record_id())
+
+        row = await reserve(intake, session, with_upload=False)
+        guarded = await read()
+        assert guarded.current_task_status == "in_progress" and guarded.candidate is None
+        await repository(session).terminalize(UUID(row.id), UUID(row.lease_id), row.lease_generation,
+            state="failed", failure_code="submission_infrastructure_unavailable")
+        released = await read()
+        assert released.current_task_status == "in_progress" and released.candidate is not None
diff --git a/backend/tests/authorization/task_authority/test_intake_authority.py b/backend/tests/authorization/task_authority/test_intake_authority.py
index e113566fb..e8a364666 100644
--- a/backend/tests/authorization/task_authority/test_intake_authority.py
+++ b/backend/tests/authorization/task_authority/test_intake_authority.py
@@ -315,3 +315,47 @@ async def test_operation_management_read_uses_current_manager_authority(admin_ac
                 assert rows and all(row.after_facts["allowed"] is False for row in rows)
         finally:
             authority.close()
+
+
+@pytest.mark.parametrize("case,management,own_submitter", [
+    ("own_submitter", False, True), ("own_manager", True, False),
+    ("own_both", True, True), ("other_manager", True, False),
+    ("other_submitter", None, False), ("foreign_manager", None, False),
+    ("absent", None, False),
+])
+async def test_public_operation_read_selects_live_authority(admin_access, case, management, own_submitter):
+    project = await create_project("Public operation reader selection")
+    if case in {"own_submitter", "own_both", "other_submitter"}:
+        manager = await project_manager(admin_access, project)
+        await grant(admin_access, manager, project)
+    if case in {"own_manager", "own_both", "other_manager", "foreign_manager"}:
+        scope = await create_project("Foreign management scope") if case == "foreign_manager" else project
+        await admin_access.signed.grant(admin_access.admin, admin_access.target,
+            role="project_manager", project_id=scope)
+    ctx = await context(admin_access)
+    owner = new_record_id() if case.startswith("other_") else ctx.actor_profile_id
+    read = IntakeOperationReadFacts(new_record_id(), project, new_record_id(), owner)
+    async with db_session.get_session_factory()() as session:
+        authority = SubmissionIntakeAuthorization(session, ctx)
+        try:
+            if management is None:
+                with pytest.raises(IntakeAuthorityDenied) as caught:
+                    async with session.begin():
+                        await authority.authorize_operation_read(read)
+                assert await authority.restage_denial(caught.value)
+                await session.commit()
+            else:
+                async with session.begin():
+                    access = await authority.authorize_operation_read(read)
+                assert access.management is management
+                assert access.own_submitter is own_submitter
+                row = await session.get(AuditEvent, str(access.decision_id))
+                assert row.action_id == ("project.task.submission_operation.read" if management
+                                         else "task.submission_operation.read")
+            rows = list(await session.scalars(select(AuditEvent).where(
+                AuditEvent.request_id == str(ctx.request_id))))
+            assert len(rows) == 1  # No denied contributor read used as a role probe.
+            assert rows[0].after_facts["allowed"] is (management is not None)
+            assert rows[0].resource_id == str(read.operation_id)
+        finally:
+            authority.close()
diff --git a/backend/tests/test_api_controls.py b/backend/tests/test_api_controls.py
index 66be0a95a..58b1e2829 100644
--- a/backend/tests/test_api_controls.py
+++ b/backend/tests/test_api_controls.py
@@ -625,6 +625,7 @@ def test_openapi_documents_request_error_and_response_context() -> None:
         "schema": {"type": "string", "format": "uuid"},
     }]
     public_entry_actions = {
+        "GET /api/v1/tasks/{task_id}/submission-operations": "task.submission_operation.read",
         "POST /api/v1/tasks/{task_id}/submissions": "submission.create",
     }
     assert public_entry_actions.keys() <= set(protected_inventory)
@@ -663,13 +664,13 @@ def test_openapi_documents_request_error_and_response_context() -> None:
         operation = schema["paths"][path][method.lower()]
         assert operation["x-workstream-action-id"] == action
         assert operation["security"]
-    assert len(route_inventory) == 133
+    assert len(route_inventory) == 134
     retained_routes = sorted(set(route_inventory) - proposal_routes - post_policy_routes - queue_routes - new_manager_reads - guide_read - contribution_reads.keys() - public_entry_actions.keys() - registry_actions.keys() - recovery_actions.keys() - model_actions.keys())
     retained_protected = sorted(set(protected_inventory) - proposal_routes - post_policy_routes - queue_routes - new_manager_reads - guide_read - contribution_reads.keys() - public_entry_actions.keys() - registry_actions.keys() - recovery_actions.keys() - model_actions.keys())
     assert sha256("\n".join(retained_routes).encode()).hexdigest() == (
         "9a495b21b504f27997a26c233e7dc4b814133038a063376b760147118bd44b7e"
     )
-    assert len(protected_inventory) == 131
+    assert len(protected_inventory) == 132
     assert sha256("\n".join(retained_protected).encode()).hexdigest() == (
         "8aa0828260680a7bccdb055ebb3f21fcd06d4e37a808b4a0a37dcbf77ffa0732"
     )
diff --git a/backend/tests/test_submission_bundle_admission.py b/backend/tests/test_submission_bundle_admission.py
index 5e6d00d7b..085d26486 100644
--- a/backend/tests/test_submission_bundle_admission.py
+++ b/backend/tests/test_submission_bundle_admission.py
@@ -255,23 +255,23 @@ def test_artifact_adapter_composes_submission_command_from_owner_ports(
     artifact_adapters.project_locked_policy_context_port.assert_called_once_with(session)
 
 
-def test_submission_bundle_preparation_is_public_binary_contract() -> None:
+def test_submission_is_public_binary_contract() -> None:
     from fastapi import FastAPI
 
     app = create_app()
     route = next(
         route
         for route in submission_router.routes
-        if getattr(route, "name", None) == "prepare_submission_bundle"
+        if getattr(route, "name", None) == "submit_source"
     )
     assert route.include_in_schema is True
-    mounted = app.url_path_for("prepare_submission_bundle", task_id=str(new_record_id()))
+    mounted = app.url_path_for("submit_source", task_id=str(new_record_id()))
     assert str(mounted).startswith("/api/v1/tasks/")
-    assert str(mounted).endswith("/submission-bundle-preparations")
+    assert str(mounted).endswith("/submissions")
     assert route.methods == {"POST"}
     schema_app = FastAPI()
     schema_app.include_router(submission_router, prefix="/api/v1")
-    operation = schema_app.openapi()["paths"]["/api/v1/tasks/{task_id}/submission-bundle-preparations"]["post"]
+    operation = schema_app.openapi()["paths"]["/api/v1/tasks/{task_id}/submissions"]["post"]
     assert operation["requestBody"]["content"]["application/zip"]["schema"] == {
         "type": "string", "format": "binary",
     }
diff --git a/backend/tests/test_submission_bundle_preparation_recovery.py b/backend/tests/test_submission_bundle_preparation_recovery.py
index 9d3a51e7d..c7ed2076d 100644
--- a/backend/tests/test_submission_bundle_preparation_recovery.py
+++ b/backend/tests/test_submission_bundle_preparation_recovery.py
@@ -13,23 +13,17 @@
 import pytest
 from httpx import ASGITransport, AsyncClient
 
-from fastapi import HTTPException
-from starlette.requests import Request
 
 import app.modules.artifacts.submission_admission as submission_admission
-from app.api.routes.artifact_submissions import prepare_submission_bundle
-from app.adapters.artifacts import (
-    get_submission_bundle_preparation_actor,
-    get_submission_bundle_preparation_command,
-)
+from app.api.deps.authorization import get_authorization_actor_identity
+from app.adapters.artifacts import get_submission_intake_command
+from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
+from app.modules.artifacts.api.submission_preparation import public_pre_submission_results
 from app.main import create_app
-from app.db.session import get_db_session
 from app.modules.artifacts.api import (
     SubmissionBundlePreparationRequest,
     SubmissionBundlePreparationCheckFailed,
-    SubmissionBundlePreparationRejected, SubmissionBundlePreparationUnavailable,
-    SubmissionBundlePreparationInfrastructureUnavailable, SubmissionBundlePreparationResult,
-    SubmissionBundlePreparationStatus,
+    SubmissionBundlePreparationRejected,
 )
 from app.modules.artifacts.submission_admission import (
     PreparedSubmissionBundlePreparationCommand,
@@ -63,51 +57,56 @@ def _feedback_facts(*, eligible: bool = False) -> SelectedPreSubmitExecutionFact
         eligible=eligible, checks=checks,
         warnings=({"code": "submission_summary_missing"}, {"code": "submission_attestation_missing"}),
     )
-    return SelectedPreSubmitExecutionFacts(
-        policy_sha256="sha256:" + "1" * 64, workstream_default=default,
-        required_external_count=0, external_members=(), eligible=eligible,
-     source_contracts=selected_pre_submit_source_contracts())
+    from dataclasses import replace
+    from tests.checkers.external.test_selected_pre_submit_coordination import (
+        _source_completed_execution, _source_reservation,
+    )
+    execution = _source_completed_execution(_source_reservation())
+    return replace(
+        execution, workstream_default=default, eligible=eligible,
+        external_members=execution.external_members if eligible else (),
+        source_contracts=selected_pre_submit_source_contracts(),
+    )
 
 
-async def _mounted_preparation_response(error: RuntimeError):
+
+async def _mounted_submission_response(error=None, *, command=None, packet_text=True):
     app = create_app()
-    app.dependency_overrides[get_submission_bundle_preparation_actor] = _actor
-    app.dependency_overrides[get_submission_bundle_preparation_command] = lambda: SimpleNamespace(
-        prepare=AsyncMock(side_effect=error)
-    )
-    app.dependency_overrides[get_db_session] = lambda: SimpleNamespace(
-        rollback=AsyncMock()
-    )
+    app.dependency_overrides[get_authorization_actor_identity] = _actor
+    command = command or SimpleNamespace(submit=AsyncMock(side_effect=error))
+    app.dependency_overrides[get_submission_intake_command] = lambda: command
     task_id, assignment_id, key = (new_record_id() for _ in range(3))
+    headers = {
+        "Content-Type": "application/zip",
+        "X-Task-Assignment-Id": str(assignment_id),
+        "Idempotency-Key": str(key),
+    }
+    if packet_text:
+        headers.update({"X-Submission-Summary": "summary",
+                        "X-Contributor-Attestation": "attestation"})
     async with AsyncClient(
         transport=ASGITransport(app=app), base_url="http://testserver"
     ) as client:
         return await client.post(
-            f"/api/v1/tasks/{task_id}/submission-bundle-preparations",
-            headers={
-                "Content-Type": "application/zip",
-                "X-Task-Assignment-Id": str(assignment_id),
-                "Idempotency-Key": str(key),
-                "X-Submission-Summary": "summary",
-                "X-Contributor-Attestation": "attestation",
-            },
-            content=b"PK\x03\x04blocked",
+            f"/api/v1/tasks/{task_id}/submissions",
+            headers=headers, content=b"PK\x03\x04blocked",
         )
 
 
 @pytest.mark.asyncio
-async def test_mounted_preparation_returns_exact_ordered_bounded_feedback() -> None:
+async def test_mounted_submission_returns_exact_ordered_bounded_feedback() -> None:
     facts = _feedback_facts()
 
-    response = await _mounted_preparation_response(
-        SubmissionBundlePreparationCheckFailed(facts)
+    response = await _mounted_submission_response(
+        SubmissionIntakeFailure("pre_submission_checker_failed",
+                                pre_submission_results=public_pre_submission_results(facts))
     )
 
     assert response.status_code == 422
     payload = response.json()
     assert set(payload) == {"error"}
     assert payload["error"]["code"] == "pre_submission_checker_failed"
-    assert payload["error"]["message"] == "Pre-submission checks failed"
+    assert payload["error"]["message"] == "pre_submission_checker_failed"
     assert payload["error"]["retryable"] is False
     assert payload["error"]["details"] == {
         "status": "failed",
@@ -126,15 +125,15 @@ async def test_mounted_preparation_returns_exact_ordered_bounded_feedback() -> N
 
 
 @pytest.mark.asyncio
-async def test_mounted_preparation_returns_sanitized_archive_rejection() -> None:
-    response = await _mounted_preparation_response(
-        SubmissionBundlePreparationRejected("submission_archive_malformed")
+async def test_mounted_submission_returns_sanitized_archive_rejection() -> None:
+    response = await _mounted_submission_response(
+        SubmissionIntakeFailure("submission_packet_invalid")
     )
 
     assert response.status_code == 422
     payload = response.json()
-    assert payload["detail"] == "submission_archive_malformed"
-    assert payload["error"]["code"] == "invalid_request"
+    assert set(payload) == {"error"}
+    assert payload["error"]["code"] == "submission_packet_invalid"
     assert payload["error"]["retryable"] is False
     assert payload["error"]["details"] == {}
     assert all(
@@ -144,30 +143,19 @@ async def test_mounted_preparation_returns_sanitized_archive_rejection() -> None
 
 
 @pytest.mark.asyncio
-async def test_mounted_preparation_does_not_reclassify_unexpected_failure() -> None:
-    command = SimpleNamespace(
-        prepare=AsyncMock(side_effect=RuntimeError("unexpected inspector failure"))
-    )
-    request = Request(
-        {
-            "type": "http",
-            "method": "POST",
-            "path": "/",
-            "headers": [(b"content-type", b"application/zip")],
-        }
-    )
-
+async def test_mounted_submission_does_not_reclassify_unexpected_failure() -> None:
+    from starlette.requests import Request
+    from app.api.routes.artifact_submissions import submit_source
+    from app.api.submission_intake import SubmissionIntakeHeaders
+    from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
+
+    metadata = SubmissionIntakeMetadata(task_id=new_record_id(), assignment_id=new_record_id())
+    command = SimpleNamespace(submit=AsyncMock(side_effect=RuntimeError("unexpected inspector failure")))
     with pytest.raises(RuntimeError, match="unexpected inspector failure"):
-        await prepare_submission_bundle(
-            task_id=str(new_record_id()),
-            request=request,
-            actor=_actor(),
-            command=command,
-            session=SimpleNamespace(rollback=AsyncMock()),
-            assignment_id=str(new_record_id()),
-            idempotency_key=str(new_record_id()),
-            summary="summary",
-            contributor_attestation="attestation",
+        await submit_source(
+            task_id=metadata.task_id, request=Request({"type": "http", "headers": []}),
+            headers=SubmissionIntakeHeaders(metadata, new_record_id(), None),
+            actor=_actor(), command=command,
         )
 
 
@@ -370,45 +358,24 @@ async def test_post_reservation_archive_failure_remains_recoverable(
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize(
-    "error,status_code,detail",
-    (
-        (
-            SubmissionBundlePreparationRejected(
-                "submission_bundle_preparation_context_changed"
-            ),
-            409,
-            "submission_bundle_preparation_context_changed",
-        ),
-        (
-            SubmissionBundlePreparationUnavailable(
-                "submission bundle preparation is unavailable"
-            ),
-            404,
-            "Task not found",
-        ),
-        (
-            SubmissionBundlePreparationInfrastructureUnavailable(
-                "pre_submission_attempt_outcome_unresolved"
-            ),
-            503,
-            "pre_submission_attempt_outcome_unresolved",
-        ),
-        (
-            SubmissionBundlePreparationInfrastructureUnavailable("deadline_exceeded"),
-            503,
-            "deadline_exceeded",
-        ),
-    ),
-)
-async def test_mounted_preparation_preserves_non_feedback_error_boundaries(
-    error, status_code, detail,
+@pytest.mark.parametrize("code,status_code,retryable", (
+    ("submission_operation_in_progress", 409, False),
+    ("submission_unavailable", 404, False),
+    ("submission_outcome_unknown", 503, True),
+    ("submission_upload_timeout", 408, False),
+    ("submission_infrastructure_unavailable", 503, True),
+    ("submission_capacity_exceeded", 429, True),
+    ("submission_archive_limit_exceeded", 413, False),
+))
+async def test_mounted_submission_preserves_non_feedback_error_boundaries(
+    code, status_code, retryable,
 ) -> None:
-    response = await _mounted_preparation_response(error)
-
+    response = await _mounted_submission_response(SubmissionIntakeFailure(code))
     assert response.status_code == status_code
     payload = response.json()
-    assert payload["detail"] == detail
+    assert set(payload) == {"error"}
+    assert payload["error"]["code"] == code
+    assert payload["error"]["retryable"] is retryable
     assert payload["error"]["details"] == {}
     assert "results" not in payload["error"]["details"]
 
@@ -429,70 +396,25 @@ def test_blocked_feedback_rejects_noncanonical_or_non_false_facts(eligible) -> N
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize("error,status_code,detail", (
-    (SubmissionBundlePreparationRejected("submission_bundle_preparation_context_changed"),
-     409,"submission_bundle_preparation_context_changed"),
-    (SubmissionBundlePreparationInfrastructureUnavailable("pre_submission_checked_custody_unavailable"),
-     503,"pre_submission_checked_custody_unavailable"),
-    (SubmissionBundlePreparationInfrastructureUnavailable("pre_submission_attempt_outcome_unresolved"),
-     503,"pre_submission_attempt_outcome_unresolved"),
-    (SubmissionBundlePreparationUnavailable("submission bundle preparation is unavailable"),
-     404,"Task not found"),
-))
-async def test_hidden_preparation_maps_context_custody_and_authority_distinctly(
-    error, status_code, detail,
-) -> None:
-    command = SimpleNamespace(
-        prepare=AsyncMock(
-            side_effect=error
-        )
-    )
-    request = Request(
-        {
-            "type": "http",
-            "method": "POST",
-            "path": "/",
-            "headers": [(b"content-type", b"application/zip")],
-        }
-    )
-
-    with pytest.raises(HTTPException) as failure:
-        await prepare_submission_bundle(
-            task_id=str(new_record_id()),
-            request=request,
-            actor=_actor(),
-            command=command,
-            session=SimpleNamespace(rollback=AsyncMock()),
-            assignment_id=str(new_record_id()),
-            idempotency_key=str(new_record_id()),
-            summary="summary",
-            contributor_attestation="attestation",
-        )
-
-    assert failure.value.status_code == status_code
-    assert failure.value.detail == detail
-
-
-@pytest.mark.asyncio
-async def test_hidden_preparation_treats_missing_optional_packet_text_as_warnings() -> None:
+async def test_mounted_submission_keeps_missing_optional_packet_text_warning_only() -> None:
     """Missing summary and attestation reach PRE as empty warning-only values."""
-    command = SimpleNamespace(prepare=AsyncMock(return_value=SubmissionBundlePreparationResult(
-        put_attempt_id=new_record_id(), admission_id=None,
-        submission_bundle_preparation_status=SubmissionBundlePreparationStatus.PREPARED,
-        replayed=False, pre_submission_results=(),
-    )))
-    request = Request({
-        "type": "http", "method": "POST", "path": "/",
-        "headers": [(b"content-type", b"application/zip")],
-    })
-
-    await prepare_submission_bundle(
-        task_id=str(new_record_id()), request=request, actor=_actor(), command=command,
-        session=SimpleNamespace(rollback=AsyncMock()),
-        assignment_id=str(new_record_id()), idempotency_key=str(new_record_id()),
-        summary=None, contributor_attestation=None,
-    )
+    from datetime import UTC, datetime
+
+    async def accept(metadata, chunks, **kwargs):
+        return {
+            "operation_id": new_record_id(), "task_id": metadata.task_id,
+            "assignment_id": metadata.assignment_id, "status": "accepted",
+            "accepted_at": datetime.now(UTC), "task_status_at_acceptance": "evaluation_pending",
+            "processing_stage_at_acceptance": "finalization_pending", "replayed": False,
+            "pre_submission_results": public_pre_submission_results(_feedback_facts(eligible=True)),
+        }
 
-    prepared = command.prepare.await_args.args[0]
-    assert prepared.summary == ""
-    assert prepared.contributor_attestation == ""
+    command = SimpleNamespace(submit=AsyncMock(side_effect=accept))
+    response = await _mounted_submission_response(command=command, packet_text=False)
+    assert response.status_code == 202
+    submitted = command.submit.await_args.args[0]
+    assert submitted.summary == ""
+    assert submitted.contributor_attestation == ""
+    warnings = [item["warning_code"] for item in response.json()["pre_submission_results"]
+                if item["status"] == "warning"]
+    assert warnings == ["submission_summary_missing", "submission_attestation_missing"]
diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py
index 936cfa3de..c056d175e 100644
--- a/cli/tests/integration/test_submission_http.py
+++ b/cli/tests/integration/test_submission_http.py
@@ -142,9 +142,10 @@ def test_explicit_submit_replay_preserves_packet_and_bytes(cli, tmp_path):
             assert headers["X-Contributor-Attestation"] == ""
             assert headers["Idempotency-Key"] == KEY
             assert headers["Content-Type"] == "application/zip"
-        assert requests == [
-            ("POST", f"/api/v1/tasks/{TASK}/submissions", "Bearer " + TOKEN)
-        ] * 2
+        assert (
+            requests
+            == [("POST", f"/api/v1/tasks/{TASK}/submissions", "Bearer " + TOKEN)] * 2
+        )
 
 
 def test_accepted_submission_shows_nonblocking_intake_feedback(cli, tmp_path):
diff --git a/mcp_server/contracts/actor_get.json b/mcp_server/contracts/actor_get.json
index 43c5a7de1..e59d19271 100644
--- a/mcp_server/contracts/actor_get.json
+++ b/mcp_server/contracts/actor_get.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "848b53dfc7e18cee10df67bac79612aefe2e4dd0c217b110e50980dd12b804c9",
+  "canonical_sha256": "cc365a001eaee9329e36ac6beb4d632abc4c809543a05fa3c4349e1c14024e50",
   "components": {
     "schemas": {
       "ActorProfileAdminResponse": {
@@ -217,6 +217,7 @@
           "workstream.artifact.verifier",
           "workstream.artifact.put_resolver",
           "workstream.artifact.scheduler",
+          "workstream.artifact.source_cleanup",
           "workstream.artifact.binding",
           "workstream.artifact.guide_reader",
           "workstream.artifact.materializer",
diff --git a/mcp_server/contracts/admin_roles_list.json b/mcp_server/contracts/admin_roles_list.json
index b6279cd72..cd7f3499f 100644
--- a/mcp_server/contracts/admin_roles_list.json
+++ b/mcp_server/contracts/admin_roles_list.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "c08ddf466d13a8ac0a3241e2b9beede0cda9eaf798fda8a446036685e25bdc0f",
+  "canonical_sha256": "b09af3f83afbfbe787e85834dfd4b21efe6a6dbc5c3bb3c7f16bef9b4ce2a87c",
   "components": {
     "schemas": {
       "AdminRole": {
@@ -223,6 +223,7 @@
           "artifact.recovery_attempt.read",
           "artifact.audit.read",
           "artifact.guide_source.ingest",
+          "artifact.submission_source.cleanup",
           "artifact.binding.create",
           "artifact.verification.execute",
           "artifact.pending_work.scan",
diff --git a/mcp_server/contracts/authorization_context_get.json b/mcp_server/contracts/authorization_context_get.json
index 9576b0916..8e5925c00 100644
--- a/mcp_server/contracts/authorization_context_get.json
+++ b/mcp_server/contracts/authorization_context_get.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "9e60e21c075c212a67255a1bef3bbff256541e40d773e087b3a3bbfdcc6eda1c",
+  "canonical_sha256": "e8809457e0535252680c1da3d7a95876261005706b1c597228d8436fc93ef210",
   "components": {
     "schemas": {
       "ActionId": {
@@ -7,6 +7,7 @@
         "enum": [
           "submission.intake.reserve",
           "task.submission_operation.read",
+          "project.task.submission_operation.read",
           "task.submission.list",
           "submission.read",
           "submission.checker_run.list",
@@ -157,6 +158,8 @@
           "artifact.task_import_source.read",
           "artifact.guide_source.read",
           "artifact.submission_bundle.prepare",
+          "artifact.submission_source.cleanup",
+          "artifact.submission.finalize",
           "artifact.submission.binding.create",
           "artifact.checker_output.binding.create",
           "artifact.verification.execute",
diff --git a/mcp_server/tests/test_task_operation_contract_drift.py b/mcp_server/tests/test_task_operation_contract_drift.py
index 953b64b09..569cd7fa1 100644
--- a/mcp_server/tests/test_task_operation_contract_drift.py
+++ b/mcp_server/tests/test_task_operation_contract_drift.py
@@ -107,7 +107,13 @@ def test_task_operation_contracts_match_backend_openapi_when_configured() -> Non
         operation = openapi["paths"][path][method.lower()]
         assert operation["security"]
         assert operation["x-workstream-action-id"] == "project.guide_compilation.request"
-    assert len(all_operations - health_operations) == 131
+    progress_path = "/api/v1/tasks/{task_id}/submission-operations"
+    assert ("GET", progress_path) in all_operations - health_operations
+    progress = openapi["paths"][progress_path]["get"]
+    assert progress["security"]
+    assert progress["x-workstream-action-id"] == "task.submission_operation.read"
+    assert progress["x-workstream-management-action-id"] == "project.task.submission_operation.read"
+    assert len(all_operations - health_operations) == 132
     for name, (method, path, _) in TASK_OPERATIONS.items():
         snapshot = json.loads((CONTRACTS / f"{name}.json").read_text(encoding="utf-8"))
         assert snapshot["source"]["openapi_version"] == openapi["openapi"]

From 686d7f7d7da90db6eb0b8fd546ecc0ea7252e8f8 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 15:52:19 +0100
Subject: [PATCH 159/513] docs(submission): record public progress proof and
 review closure

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 24 +++++++++++++++++++
 1 file changed, 24 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 0d71a8e41..6f8802e56 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5026,3 +5026,27 @@ required ARCH/SEC, QA/test-delta and DOCS/CI review, with exact committed-head
 regression to cover all three T5 cases after the fixture correction. CLI/MCP
 progress commands, other governed outcomes, historical/new-revision concealment,
 old runtime removal and full acceptance/qualification remain open.
+
+### Frozen public-reader review closure
+
+Code checkpoint0e45c371eb24f8909e7e88aaa05d8af6d6a54af7 has exact-head proof:
+- /tmp/submission-progress-frozen-0e45.log/json:11passed231.52s (threeT5,
+  sevenlive-authority selections, oneTASK visibility/context),0081,cleanuptrue.
+- /tmp/submission-public-frozen-0e45.log/json:2passed61.32s (small accepted and
+  QC-rejected public ZIP/progress flows),0081,cleanuptrue.
+- /tmp/submission-progress-architecture-full.log:92passed245.83s.
+Ruff, diff, module-boundary and Commitrail checks passed. Remote fetch confirms
+no missing origin/main commits. PR708 remains the only draft PR.
+
+ARCH/SEC code review, QA/test-delta and DOCS/CI reviews closed with no required
+repairs on clean0e45. QA independently proved the mounted error test detects a
+503-to409 mutation and that PRE feedback rejects metadata/actor/key/task/assignment/
+source substitutions (/tmp/submission-progress-read-qa-error-mutant.log and
+/tmp/submission-progress-read-qa-feedback-probe.log). DOCS/CI inventory mutants
+reject absent GET/security, wrong manager action and an extra public route
+(/tmp/submission-progress-read-docs-ci-adversarial.json). These are scoped review
+verdicts; earlier native failures and remaining full-goal requirements persist.
+This evidence-only follow-up does not change the reviewed production/test code.
+Next work: client progress commands and pending task/work-context projection,
+real historical/reassignment/new-revision and remaining governed outcome proof,
+obsolete runtime/consumer cleanup, full CI and A01-A35/C01-C07 qualification.

From ddf6234fd0be8b9e902361baa24c361fcc306feb Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 16:10:41 +0100
Subject: [PATCH 160/513] feat(clients): inspect submission operation progress
 without resubmitting

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  76 +++
 backend/scripts/test_lane_catalogue.py        |   1 +
 .../test_submission_intake_admission.py       | 221 -------
 .../test_submission_intake_progress.py        | 250 ++++++++
 backend/tests/test_ci_lane_catalogue.py       |   4 +-
 cli/README.md                                 |  14 +-
 cli/internal/api/submission_progress.go       |  76 +++
 cli/internal/api/submission_progress_test.go  |  87 +++
 cli/internal/command/submission.go            |  25 +
 cli/tests/integration/test_submission_http.py | 106 ++++
 mcp_server/README.md                          |   9 +-
 .../contracts/submission_operation_get.json   | 544 ++++++++++++++++++
 mcp_server/pyproject.toml                     |   1 +
 mcp_server/tests/test_task_execution.py       | 114 ++++
 .../test_task_execution_contract_drift.py     |   2 +-
 mcp_server/workstream_mcp/http_gateway.py     |   8 +-
 mcp_server/workstream_mcp/schemas.py          |  11 +
 .../workstream_mcp/tools/task_execution.py    |   4 +
 18 files changed, 1323 insertions(+), 230 deletions(-)
 create mode 100644 backend/tests/artifacts/test_submission_intake_progress.py
 create mode 100644 cli/internal/api/submission_progress.go
 create mode 100644 cli/internal/api/submission_progress_test.go
 create mode 100644 mcp_server/contracts/submission_operation_get.json

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 6f8802e56..9d68a6352 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5050,3 +5050,79 @@ This evidence-only follow-up does not change the reviewed production/test code.
 Next work: client progress commands and pending task/work-context projection,
 real historical/reassignment/new-revision and remaining governed outcome proof,
 obsolete runtime/consumer cleanup, full CI and A01-A35/C01-C07 qualification.
+
+### Client operation inspection
+
+Extend existing CLI submission API/command and MCP task-execution adapter with
+one read-only operation lookup using exactly one operation UUID or actor-scoped
+idempotency UUID. No resubmit, poll loop, provider field or client-owned lifecycle
+inference. Preserve required nullable fields, original task/selector binding,
+closed stage/action enums and bounded feedback through existing safe output paths.
+Allowed: cli/internal/api/submission_progress.go and focused tests, existing
+cli/internal/command/submission.go and command/HTTP tests; MCP existing schemas,
+http_gateway, task_execution tools, catalogue tests/packaging and a snapshot for
+the new read; CLI/MCP README and this record. Keep governed revision preparation.
+MCP key lookup must remain a query parameter, never the mutation-only header or
+filtered out by common submit-field exclusion. Response binding must validate
+task and the supplied selector, including manager ID lookup versus own key lookup.
+Risk: public adapter/security contracts; require ARCH/SEC and QA/test-delta review,
+DOCS/CI for snapshot/catalogue changes. Acceptance: each selector emits one GET,
+invalid/ambiguous selectors make no request, foreign/malformed/extra-field output
+is refused, and accepted/rejected/stalled/governed responses preserve server advice.
+Verify focused Go/CLI HTTP tests, MCP input/output/gateway and actual OpenAPI drift.
+The task/work-context pending projection remains a separate required owner change.
+
+Client worktree evidence: Go API/command packages pass; existing CLI HTTP15cases
+pass, and corrected explicit-json progress cases pass2 in1.79s (initial test
+invocations accidentally requested default text). MCP focused run60passed/2backend
+probes skipped; configured backend drift replay20passed48.81s closes those probes.
+Additional response-negative tests initially omitted authentication and therefore
+failed their one-upstream-request assertion; corrected authentication is required
+also for invalid-selector tests so absence of dispatch cannot pass vacuously.
+
+CI on pushed686 independently confirms92 architecture tests pass, then rejects
+new structural debt: intake_admission.py1330lines and its T5 function220lines.
+Do not refresh the debt ledger to bless growth. Extract cohesive existing proof
+into focused tests/helpers with unchanged assertions and collect/lane membership.
+CLI real-API failures still use removed PRE materialization constructor/fields;
+these require shared consumer migration, alongside the known Rust obsolete grant
+path. Logs /tmp/submission-686-ci-133380152032.log and
+/tmp/submission-686-ci-133382036484.log. Neither is fixed by client progress work.
+
+Client progress negative replay passed10 in56.98s with authenticated calls:
+/tmp/submission-progress-mcp-negative-v2.log. Both selector GETs, no mutation header,
+wrong selector/task refusal, extra/private field, missing nullable, unknown stage
+and invalid input/no-dispatch cases exercised. Built CLI inspection replay passed2
+in2.27s including JSON and safe text paths (/tmp/submission-progress-cli-http-v3.log).
+MCP wheel built successfully and contains the exact new contract bytes
+(/tmp/submission-progress-mcp-dist/workstream_mcp_server-0.1.0-py3-none-any.whl).
+These are local worktree receipts on parent686, not reviewed/pushed client delivery.
+Current client implementation is ready for scoped review after the required test
+structure repair; same PR708 and all remaining goal requirements still apply.
+
+### Preserve T5 proof without structural debt
+
+Move the existing three-parameter T5 proof from test_submission_intake_admission.py
+to focused tests/artifacts/test_submission_intake_progress.py. Extract its existing
+contiguous retained-custody/association assertions into one local helper, return
+only the owner observations needed by the remaining progression assertions, and
+move imports to module scope. Preserve every assertion, parameter, real HTTP call,
+source substitution and real OUTBOX outcome. No skips, new abstractions, debt ledger
+refresh or limit increase. Add the new module beside admission in the existing
+shared-foundation lane catalogue; verify collection and actual lane membership.
+Allowed files are those two tests, scripts/test_lane_catalogue.py and any exact
+catalogue expectation proven stale by this move, plus this record. QA/test-delta
+and CI integrity review must inspect preservation and selection on the frozen
+client/proof checkpoint. Run the three moved cases and structure validation.
+
+Extraction replay passed3 in152.57s,0081,cleanupcomplete
+(/tmp/submission-progress-extracted.log/json), retaining the existing intentional
+forged-context serializer warning. Mechanical AST comparison preserved all42
+assertions and original3-case parametrization. Main test117lines and custody
+helper75lines are below the120line function limit; source admission file shrank
+below1200. Structure validator passes with unchanged debt ledger. Lane/catalogue
+replay passed76 in19.89s; removing only the new progress-module path reproduces the
+prior shared-family fingerprint exactly. Behavior-ownership validation passes.
+Freeze client progress plus proof extraction for ARCH/SEC, QA/test-delta and
+DOCS/CI review. All receipts above are worktree receipts on parent686; no full CI
+or historical/terminal branch qualification is implied.
diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py
index 06378c496..a64bbc586 100644
--- a/backend/scripts/test_lane_catalogue.py
+++ b/backend/scripts/test_lane_catalogue.py
@@ -57,6 +57,7 @@ class TestLane:
     "tests/artifacts/test_submission_source_cleanup.py",
     "tests/artifacts/test_submission_pre_source.py",
     "tests/artifacts/test_submission_intake_admission.py",
+    "tests/artifacts/test_submission_intake_progress.py",
     "tests/artifacts/test_submission_foreground_command.py",
     "tests/authorization/post_submit/test_atomicity.py",
     "tests/authorization/post_submit/test_concurrency.py",
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 459bf04ec..64e7544b6 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -805,227 +805,6 @@ async def commit(self):
     assert receipt["status"] == "accepted" and receipt["replayed"] is True
 
 
-@pytest.mark.parametrize("expired_claim,post_failure", [(False, False), (True, False), (False, True)])
-async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(admission_intake, tmp_path, monkeypatch, expired_claim, post_failure):
-    from datetime import timedelta
-    from sqlalchemy import text
-    from app.adapters.artifacts import submission_admission_consumption_port
-    from app.adapters.checkers import selected_pre_submit_coordinator
-    from app.adapters.outbox import outbox_append
-    from app.adapters.tasks import accepted_submission_creation_service
-    from app.modules.outbox.api import OutboxAppendInput
-    from app.modules.actors.api import ServiceIdentity
-    from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
-    from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
-    from tests.artifact_store_helpers import initialize_local_store
-    from tests.artifacts.intake_acceptance_support import completed_source
-    from tests.checkers.execution.support import provision_post_submit_service
-
-    f = admission_intake
-    owner, request, terminal = await completed_source(f, tmp_path)
-    accepted = await f.admission.accept(owner, request, terminal.terminal_digest,
-        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
-    await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_BINDING)
-    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
-    def submissions(session):
-        return accepted_submission_creation_service(session, settings=_settings(tmp_path),
-            admissions=submission_admission_consumption_port(session,
-                request_id=new_record_id(), correlation_id=owner.operation_id))
-    finalizer = AcceptedSubmissionFinalization(
-        f.factory, tasks=f.admission._tasks, submissions=submissions,
-        checkers=selected_pre_submit_coordinator, store=store, lease_duration=timedelta(seconds=60),
-        authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
-            session, request_id=new_record_id(), correlation_id=owner.operation_id),
-    )
-    try:
-        if expired_claim:
-            from tests.artifacts.intake_post_support import leave_expired_finalizer_claim
-            await leave_expired_finalizer_claim(f, finalizer, owner.operation_id)
-        result = await finalizer.run(owner.operation_id)
-        assert await finalizer.run(owner.operation_id) == result
-        assert await f.admission.accept(owner, request, terminal.terminal_digest,
-            checkers=selected_pre_submit_coordinator, outbox=outbox_append) == dict(accepted, replayed=True)
-        async def public_progress(stage, evaluation_request_id, *, stalled=False, governed=False):
-            response = await f.access.signed.client.get(
-                f"/api/v1/tasks/{f.task}/submission-operations", headers=f.access.target.headers,
-                params={"operation_id": str(owner.operation_id)},
-            )
-            assert response.status_code == 200, response.text
-            observed = response.json()
-            assert observed["operation_state"] == "finalized"
-            assert observed["submission_id"] == str(result.submission_id)
-            assert observed["submission_version"] == result.submission_version
-            assert observed["evaluation_request_id"] == str(evaluation_request_id)
-            assert observed["processing_stage"] == stage
-            assert observed["operationally_stalled"] is stalled
-            assert observed["next_action"] == ("inspect_governed_outcome" if governed else "wait")
-            return observed
-
-        await public_progress("evaluation_pending", result.evaluation_request_id)
-        async with f.factory() as session:
-            row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
-            assert row.state == "finalized" and row.finalized_submission_id == str(result.submission_id)
-            assert row.continuation_generation == (2 if expired_claim else 1)
-            task = (await session.execute(text("SELECT status, active_submission_operation_id "
-                "FROM workstream_tasks WHERE id=:id"), {"id": f.task})).one()
-            assert task.status == "evaluation_pending" and task.active_submission_operation_id is None
-            admission = (await session.execute(text("SELECT source_operation_id, durable_intent_id, put_attempt_id, "
-                "verification_receipt_id FROM submission_bundle_admissions WHERE id=:id"),
-                {"id": result.admission_id})).one()
-            assert admission.source_operation_id == owner.operation_id
-            assert admission.durable_intent_id is admission.put_attempt_id is admission.verification_receipt_id is None
-            replica = (await session.execute(text("SELECT provider_object_ref FROM artifact_replicas "
-                "WHERE source_operation_id=:id"), {"id": owner.operation_id})).one()
-            assert replica.provider_object_ref == request.source.location.object_ref
-            for table in ("submissions", "submission_dispatches", "checker_runs"):
-                assert await session.scalar(text(f"SELECT count(*) FROM {table} WHERE task_id=:id"), {"id": f.task}) == 1
-            assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE project_id=:id "
-                "AND event_type='PostSubmissionEvaluationRequested'"), {"id": f.project}) == 1
-            assert await session.scalar(text("SELECT count(*) FROM submission_source_charges WHERE operation_id=:id"),
-                {"id": owner.operation_id}) == 1
-        # Removing retained provenance must fail at commit even when all other
-        # replica coordinates remain unchanged.
-        from app.adapters.tasks import submission_history_repository
-        from app.modules.tasks.api.submission_history import SubmissionOperationAssociationUnavailable
-        from app.adapters.checkers import evaluation_coordinator
-        from app.modules.checkers.api.execution import CheckerExecutionUnavailable
-        evaluation_selectors = dict(project_id=f.project, task_id=f.task,
-                                    submission_id=result.submission_id,
-                                    original_request_id=result.evaluation_request_id)
-        async with f.factory.begin() as session:
-            coordinator = evaluation_coordinator(session)
-            queued = await coordinator.read_current_progress(**evaluation_selectors)
-            assert queued.status == "queued" and not queued.live_worker_lease
-            assert queued.retry_event_id is queued.completion_event_id is None
-            for field in evaluation_selectors:
-                with pytest.raises(CheckerExecutionUnavailable):
-                    await coordinator.read_current_progress(**(evaluation_selectors | {field: new_record_id()}))
-        selectors = dict(project_id=f.project, task_id=f.task, assignment_id=request.assignment_id,
-                         contributor_id=request.actor_profile_id, submission_id=result.submission_id,
-                         admission_id=result.admission_id)
-        async with f.factory.begin() as session:
-            history = submission_history_repository(session)
-            outcome = await history.read_operation_outcome(**selectors)
-            assert outcome.submission_id == result.submission_id
-            assert outcome.submission_version == result.submission_version
-            assert outcome.evaluation_request_id == result.evaluation_request_id
-            assert outcome.status == "evaluation_pending"
-            from app.modules.artifacts.intake.progress import evaluation_delivery_progress
-            from app.adapters.outbox import finalized_unknown_deliveries
-            pending = await evaluation_delivery_progress(
-                outcome.evaluation_event_id, OutboxAppendInput.model_validate_json(outcome.evaluation_event_json), queued,
-                outbox_append(session), finalized_unknown_deliveries(session),
-            )
-            assert pending.state == "pending"
-            for field in selectors:
-                with pytest.raises(SubmissionOperationAssociationUnavailable):
-                    await history.read_operation_outcome(**(selectors | {field: new_record_id()}))
-        from sqlalchemy.exc import IntegrityError
-        async with f.factory() as session:
-            with pytest.raises(IntegrityError, match="retained source ownership is immutable"):
-                async with session.begin():
-                    await session.execute(text("UPDATE artifact_replicas SET source_operation_id=NULL "
-                        "WHERE source_operation_id=:id"), {"id": owner.operation_id})
-        substitutions = (
-            ("UPDATE artifact_contents SET sha256='sha256:' || repeat('f',64) WHERE id=:id",
-             result.artifact_content_id, "accepted source content is immutable"),
-            ("UPDATE artifact_contents SET byte_count=byte_count+1 WHERE id=:id",
-             result.artifact_content_id, "accepted source content is immutable"),
-            ("UPDATE artifact_contents SET media_type='application/octet-stream' WHERE id=:id",
-             result.artifact_content_id, "accepted source content is immutable"),
-            ("UPDATE artifact_replicas SET adapter='substituted' WHERE source_operation_id=:id",
-             owner.operation_id, "source admission provenance mismatch"),
-        )
-        for statement, identity, message in substitutions:
-            async with f.factory() as session:
-                with pytest.raises(IntegrityError, match=message):
-                    async with session.begin():
-                        await session.execute(text(statement), {"id": identity})
-        from tests.artifacts.intake_post_support import exercise_source_post
-        from tests.checkers.execution.support import ControlledSelectedExecution
-        running_observations = []
-        original_execute = ControlledSelectedExecution.execute
-        async def observe_running(runtime, execution_request, grant):
-            async with f.factory.begin() as session:
-                running = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
-                assert running.status == "running" and running.live_worker_lease
-                assert running.completion_event_id is None
-                running_observations.append(running)
-            await public_progress("evaluation_running", result.evaluation_request_id)
-            return await original_execute(runtime, execution_request, grant)
-        with monkeypatch.context() as patch:
-            patch.setattr(ControlledSelectedExecution, "execute", observe_running)
-            if post_failure:
-                from app.interfaces.artifacts import ArtifactObjectMissingError
-                def missing_source(*_args, **_kwargs):
-                    raise ArtifactObjectMissingError("controlled source unavailable")
-                patch.setattr(type(store), "open_source", missing_source)
-            await exercise_source_post(f, result, store, request.source, tmp_path, missing=post_failure)
-        assert len(running_observations) == (0 if post_failure else 1)
-        async with f.factory.begin() as session:
-            # Completed checker evidence alone does not change the governed attempt.
-            after_post = await submission_history_repository(session).read_operation_outcome(**selectors)
-            assert after_post == outcome
-            completed = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
-            assert completed.status == ("infrastructure_failed" if post_failure else "completed")
-            assert not completed.live_worker_lease and completed.current == queued.current
-            assert (completed.completion_event_id is None) is post_failure
-            assert completed.retry_event_id is None
-            if not post_failure:
-                pending_completion = await evaluation_delivery_progress(
-                    completed.completion_event_id, OutboxAppendInput.model_validate_json(completed.delivery_event_json), completed,
-                    outbox_append(session), finalized_unknown_deliveries(session),
-                )
-                assert pending_completion.state == "pending"
-        await public_progress("operationally_stalled" if post_failure else "evaluation_pending",
-                              result.evaluation_request_id, stalled=post_failure)
-        if post_failure:
-            from app.adapters.checkers import checker_retry_service
-            from tests.checkers.execution.test_checker_retry import _operator_for, _command
-            harness = SimpleNamespace(factory=f.factory, request=queued.current.request, created=result)
-            operator = await _operator_for(harness)
-            async with f.factory.begin() as session:
-                retry = await checker_retry_service(session, operator).retry(_command(harness, operator))
-            async with f.factory.begin() as session:
-                retrying = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
-                assert retrying.status == "queued" and not retrying.live_worker_lease
-                assert retrying.current.reservation.attempt_id == retry.successor.run_id
-                assert retrying.retry_event_id == retry.successor.event_id
-                assert retrying.completion_event_id is None
-                pending_retry = await evaluation_delivery_progress(
-                    retrying.retry_event_id, OutboxAppendInput.model_validate_json(retrying.delivery_event_json), retrying,
-                    outbox_append(session), finalized_unknown_deliveries(session),
-                )
-                assert pending_retry.state == "pending"
-            await public_progress("evaluation_pending", retrying.current.request.evaluation_request_id)
-        else:
-            from app.adapters.auth import outbox_dispatch_authorization
-            from app.adapters.outbox import outbox_delivery
-            from app.adapters.tasks import evaluation_completion_handler
-            from app.modules.checkers.api.execution import COMPLETION_EVENT
-            from app.modules.outbox.api import DeliveryOptions
-            from app.modules.outbox.registry import HandlerRegistry
-            from tests.authorization.post_submit_routing.support import provision_router
-            from tests.tasks.evaluation_delivery.support import outcome as delivery_outcome
-
-            await provision_post_submit_service(f.factory, ServiceIdentity.OUTBOX_DISPATCHER)
-            await provision_router(f.factory)
-            dispatcher = outbox_delivery(
-                f.factory, authorization_factory=outbox_dispatch_authorization,
-                registry=HandlerRegistry([(COMPLETION_EVENT, 1,
-                    evaluation_completion_handler(sessions=f.factory))]),
-                options=DeliveryOptions(),
-            )
-            delivered = await dispatcher.deliver(
-                completed.completion_event_id, f.project, "source-progress-governed-outcome")
-            assert delivery_outcome(delivered)["delivery_state"] == "acknowledged", delivery_outcome(delivered)
-            async with f.factory.begin() as session:
-                governed = await submission_history_repository(session).read_operation_outcome(**selectors)
-                assert governed.status == "review_pending"
-            await public_progress("review_pending", result.evaluation_request_id, governed=True)
-
-    finally:
-        store.close()
 
 
 async def test_operator_recovers_same_accepted_finalization_once(recovery_intake, tmp_path):
diff --git a/backend/tests/artifacts/test_submission_intake_progress.py b/backend/tests/artifacts/test_submission_intake_progress.py
new file mode 100644
index 000000000..3b2b03ad8
--- /dev/null
+++ b/backend/tests/artifacts/test_submission_intake_progress.py
@@ -0,0 +1,250 @@
+"""Exact finalized source custody and public progress through governed routing."""
+from types import SimpleNamespace
+
+import pytest
+
+from app.core.identifiers import new_record_id
+from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+from tests.test_artifact_admission import _settings
+from tests.artifacts.test_submission_intake_admission import admission_intake as admission_intake
+from tests.authentication.fixtures import (
+    auth_database_env as auth_database_env,
+    clear_settings_cache as clear_settings_cache,
+    rsa_signing_material as rsa_signing_material,
+)
+from tests.authorization.admin_access.fixtures import (
+    signed_access as signed_access,
+    admin_access as admin_access,
+)
+from datetime import timedelta
+from sqlalchemy import text
+from app.adapters.artifacts import submission_admission_consumption_port
+from app.adapters.checkers import selected_pre_submit_coordinator
+from app.adapters.outbox import outbox_append
+from app.adapters.tasks import accepted_submission_creation_service
+from app.modules.outbox.api import OutboxAppendInput
+from app.modules.actors.api import ServiceIdentity
+from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization
+from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
+from tests.artifact_store_helpers import initialize_local_store
+from tests.artifacts.intake_acceptance_support import completed_source
+from tests.checkers.execution.support import provision_post_submit_service
+from app.adapters.tasks import submission_history_repository
+from app.modules.tasks.api.submission_history import SubmissionOperationAssociationUnavailable
+from app.adapters.checkers import evaluation_coordinator
+from app.modules.checkers.api.execution import CheckerExecutionUnavailable
+from sqlalchemy.exc import IntegrityError
+from tests.artifacts.intake_post_support import exercise_source_post
+from tests.checkers.execution.support import ControlledSelectedExecution
+from tests.artifacts.intake_post_support import leave_expired_finalizer_claim
+from app.modules.artifacts.intake.progress import evaluation_delivery_progress
+from app.adapters.outbox import finalized_unknown_deliveries
+from app.adapters.checkers import checker_retry_service
+from tests.checkers.execution.test_checker_retry import _operator_for, _command
+from app.adapters.auth import outbox_dispatch_authorization
+from app.adapters.outbox import outbox_delivery
+from app.adapters.tasks import evaluation_completion_handler
+from app.modules.checkers.api.execution import COMPLETION_EVENT
+from app.modules.outbox.api import DeliveryOptions
+from app.modules.outbox.registry import HandlerRegistry
+from tests.authorization.post_submit_routing.support import provision_router
+from tests.tasks.evaluation_delivery.support import outcome as delivery_outcome
+from app.interfaces.artifacts import ArtifactObjectMissingError
+
+
+async def _assert_retained_custody(f, owner, request, result, expired_claim):
+    async with f.factory() as session:
+        row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+        assert row.state == "finalized" and row.finalized_submission_id == str(result.submission_id)
+        assert row.continuation_generation == (2 if expired_claim else 1)
+        task = (await session.execute(text("SELECT status, active_submission_operation_id "
+            "FROM workstream_tasks WHERE id=:id"), {"id": f.task})).one()
+        assert task.status == "evaluation_pending" and task.active_submission_operation_id is None
+        admission = (await session.execute(text("SELECT source_operation_id, durable_intent_id, put_attempt_id, "
+            "verification_receipt_id FROM submission_bundle_admissions WHERE id=:id"),
+            {"id": result.admission_id})).one()
+        assert admission.source_operation_id == owner.operation_id
+        assert admission.durable_intent_id is admission.put_attempt_id is admission.verification_receipt_id is None
+        replica = (await session.execute(text("SELECT provider_object_ref FROM artifact_replicas "
+            "WHERE source_operation_id=:id"), {"id": owner.operation_id})).one()
+        assert replica.provider_object_ref == request.source.location.object_ref
+        for table in ("submissions", "submission_dispatches", "checker_runs"):
+            assert await session.scalar(text(f"SELECT count(*) FROM {table} WHERE task_id=:id"), {"id": f.task}) == 1
+        assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE project_id=:id "
+            "AND event_type='PostSubmissionEvaluationRequested'"), {"id": f.project}) == 1
+        assert await session.scalar(text("SELECT count(*) FROM submission_source_charges WHERE operation_id=:id"),
+            {"id": owner.operation_id}) == 1
+    # Removing retained provenance must fail at commit even when all other
+    # replica coordinates remain unchanged.
+    evaluation_selectors = dict(project_id=f.project, task_id=f.task,
+                                submission_id=result.submission_id,
+                                original_request_id=result.evaluation_request_id)
+    async with f.factory.begin() as session:
+        coordinator = evaluation_coordinator(session)
+        queued = await coordinator.read_current_progress(**evaluation_selectors)
+        assert queued.status == "queued" and not queued.live_worker_lease
+        assert queued.retry_event_id is queued.completion_event_id is None
+        for field in evaluation_selectors:
+            with pytest.raises(CheckerExecutionUnavailable):
+                await coordinator.read_current_progress(**(evaluation_selectors | {field: new_record_id()}))
+    selectors = dict(project_id=f.project, task_id=f.task, assignment_id=request.assignment_id,
+                     contributor_id=request.actor_profile_id, submission_id=result.submission_id,
+                     admission_id=result.admission_id)
+    async with f.factory.begin() as session:
+        history = submission_history_repository(session)
+        outcome = await history.read_operation_outcome(**selectors)
+        assert outcome.submission_id == result.submission_id
+        assert outcome.submission_version == result.submission_version
+        assert outcome.evaluation_request_id == result.evaluation_request_id
+        assert outcome.status == "evaluation_pending"
+        pending = await evaluation_delivery_progress(
+            outcome.evaluation_event_id, OutboxAppendInput.model_validate_json(outcome.evaluation_event_json), queued,
+            outbox_append(session), finalized_unknown_deliveries(session),
+        )
+        assert pending.state == "pending"
+        for field in selectors:
+            with pytest.raises(SubmissionOperationAssociationUnavailable):
+                await history.read_operation_outcome(**(selectors | {field: new_record_id()}))
+    async with f.factory() as session:
+        with pytest.raises(IntegrityError, match="retained source ownership is immutable"):
+            async with session.begin():
+                await session.execute(text("UPDATE artifact_replicas SET source_operation_id=NULL "
+                    "WHERE source_operation_id=:id"), {"id": owner.operation_id})
+    substitutions = (
+        ("UPDATE artifact_contents SET sha256='sha256:' || repeat('f',64) WHERE id=:id",
+         result.artifact_content_id, "accepted source content is immutable"),
+        ("UPDATE artifact_contents SET byte_count=byte_count+1 WHERE id=:id",
+         result.artifact_content_id, "accepted source content is immutable"),
+        ("UPDATE artifact_contents SET media_type='application/octet-stream' WHERE id=:id",
+         result.artifact_content_id, "accepted source content is immutable"),
+        ("UPDATE artifact_replicas SET adapter='substituted' WHERE source_operation_id=:id",
+         owner.operation_id, "source admission provenance mismatch"),
+    )
+    for statement, identity, message in substitutions:
+        async with f.factory() as session:
+            with pytest.raises(IntegrityError, match=message):
+                async with session.begin():
+                    await session.execute(text(statement), {"id": identity})
+    return SimpleNamespace(queued=queued, outcome=outcome,
+                           selectors=selectors, evaluation_selectors=evaluation_selectors)
+
+
+@pytest.mark.parametrize("expired_claim,post_failure", [(False, False), (True, False), (False, True)])
+async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(admission_intake, tmp_path, monkeypatch, expired_claim, post_failure):
+
+    f = admission_intake
+    owner, request, terminal = await completed_source(f, tmp_path)
+    accepted = await f.admission.accept(owner, request, terminal.terminal_digest,
+        checkers=selected_pre_submit_coordinator, outbox=outbox_append)
+    await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_BINDING)
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    def submissions(session):
+        return accepted_submission_creation_service(session, settings=_settings(tmp_path),
+            admissions=submission_admission_consumption_port(session,
+                request_id=new_record_id(), correlation_id=owner.operation_id))
+    finalizer = AcceptedSubmissionFinalization(
+        f.factory, tasks=f.admission._tasks, submissions=submissions,
+        checkers=selected_pre_submit_coordinator, store=store, lease_duration=timedelta(seconds=60),
+        authorization=lambda session: PreparedSubmissionFinalizationAuthorization(
+            session, request_id=new_record_id(), correlation_id=owner.operation_id),
+    )
+    try:
+        if expired_claim:
+            await leave_expired_finalizer_claim(f, finalizer, owner.operation_id)
+        result = await finalizer.run(owner.operation_id)
+        assert await finalizer.run(owner.operation_id) == result
+        assert await f.admission.accept(owner, request, terminal.terminal_digest,
+            checkers=selected_pre_submit_coordinator, outbox=outbox_append) == dict(accepted, replayed=True)
+        async def public_progress(stage, evaluation_request_id, *, stalled=False, governed=False):
+            response = await f.access.signed.client.get(
+                f"/api/v1/tasks/{f.task}/submission-operations", headers=f.access.target.headers,
+                params={"operation_id": str(owner.operation_id)},
+            )
+            assert response.status_code == 200, response.text
+            observed = response.json()
+            assert observed["operation_state"] == "finalized"
+            assert observed["submission_id"] == str(result.submission_id)
+            assert observed["submission_version"] == result.submission_version
+            assert observed["evaluation_request_id"] == str(evaluation_request_id)
+            assert observed["processing_stage"] == stage
+            assert observed["operationally_stalled"] is stalled
+            assert observed["next_action"] == ("inspect_governed_outcome" if governed else "wait")
+            return observed
+
+        await public_progress("evaluation_pending", result.evaluation_request_id)
+        observed = await _assert_retained_custody(f, owner, request, result, expired_claim)
+        queued, outcome = observed.queued, observed.outcome
+        selectors, evaluation_selectors = observed.selectors, observed.evaluation_selectors
+        running_observations = []
+        original_execute = ControlledSelectedExecution.execute
+        async def observe_running(runtime, execution_request, grant):
+            async with f.factory.begin() as session:
+                running = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
+                assert running.status == "running" and running.live_worker_lease
+                assert running.completion_event_id is None
+                running_observations.append(running)
+            await public_progress("evaluation_running", result.evaluation_request_id)
+            return await original_execute(runtime, execution_request, grant)
+        with monkeypatch.context() as patch:
+            patch.setattr(ControlledSelectedExecution, "execute", observe_running)
+            if post_failure:
+                def missing_source(*_args, **_kwargs):
+                    raise ArtifactObjectMissingError("controlled source unavailable")
+                patch.setattr(type(store), "open_source", missing_source)
+            await exercise_source_post(f, result, store, request.source, tmp_path, missing=post_failure)
+        assert len(running_observations) == (0 if post_failure else 1)
+        async with f.factory.begin() as session:
+            # Completed checker evidence alone does not change the governed attempt.
+            after_post = await submission_history_repository(session).read_operation_outcome(**selectors)
+            assert after_post == outcome
+            completed = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
+            assert completed.status == ("infrastructure_failed" if post_failure else "completed")
+            assert not completed.live_worker_lease and completed.current == queued.current
+            assert (completed.completion_event_id is None) is post_failure
+            assert completed.retry_event_id is None
+            if not post_failure:
+                pending_completion = await evaluation_delivery_progress(
+                    completed.completion_event_id, OutboxAppendInput.model_validate_json(completed.delivery_event_json), completed,
+                    outbox_append(session), finalized_unknown_deliveries(session),
+                )
+                assert pending_completion.state == "pending"
+        await public_progress("operationally_stalled" if post_failure else "evaluation_pending",
+                              result.evaluation_request_id, stalled=post_failure)
+        if post_failure:
+            harness = SimpleNamespace(factory=f.factory, request=queued.current.request, created=result)
+            operator = await _operator_for(harness)
+            async with f.factory.begin() as session:
+                retry = await checker_retry_service(session, operator).retry(_command(harness, operator))
+            async with f.factory.begin() as session:
+                retrying = await evaluation_coordinator(session).read_current_progress(**evaluation_selectors)
+                assert retrying.status == "queued" and not retrying.live_worker_lease
+                assert retrying.current.reservation.attempt_id == retry.successor.run_id
+                assert retrying.retry_event_id == retry.successor.event_id
+                assert retrying.completion_event_id is None
+                pending_retry = await evaluation_delivery_progress(
+                    retrying.retry_event_id, OutboxAppendInput.model_validate_json(retrying.delivery_event_json), retrying,
+                    outbox_append(session), finalized_unknown_deliveries(session),
+                )
+                assert pending_retry.state == "pending"
+            await public_progress("evaluation_pending", retrying.current.request.evaluation_request_id)
+        else:
+
+            await provision_post_submit_service(f.factory, ServiceIdentity.OUTBOX_DISPATCHER)
+            await provision_router(f.factory)
+            dispatcher = outbox_delivery(
+                f.factory, authorization_factory=outbox_dispatch_authorization,
+                registry=HandlerRegistry([(COMPLETION_EVENT, 1,
+                    evaluation_completion_handler(sessions=f.factory))]),
+                options=DeliveryOptions(),
+            )
+            delivered = await dispatcher.deliver(
+                completed.completion_event_id, f.project, "source-progress-governed-outcome")
+            assert delivery_outcome(delivered)["delivery_state"] == "acknowledged", delivery_outcome(delivered)
+            async with f.factory.begin() as session:
+                governed = await submission_history_repository(session).read_operation_outcome(**selectors)
+                assert governed.status == "review_pending"
+            await public_progress("review_pending", result.evaluation_request_id, governed=True)
+
+    finally:
+        store.close()
+
diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py
index 56fe1ad56..872fb2500 100644
--- a/backend/tests/test_ci_lane_catalogue.py
+++ b/backend/tests/test_ci_lane_catalogue.py
@@ -318,8 +318,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None:
     """A catalogue-internal move across semantic families must fail this contract."""
     expected = {
         "shared": (
-            276,
-            "405c1f61d06426c34a9269e41530f36c0ce3dcaf9440edddf4def0945ce22ee6",
+            277,
+            "e9280bafac00f22e4bd54acd1c6dcd3699411a927269f5132f3cc39ca31224a1",
         ),
         "project": (
             256,
diff --git a/cli/README.md b/cli/README.md
index 2af387690..cc763b9ec 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -7,7 +7,7 @@ administrative actor, identity-link and grant inspection and explicit writes,
 active-guide/intake-policy inspection,
 contributor work discovery, claim, locked guide documents and governing
 context/intake requirements, explicit batch import/screen/release, Finance
-policy management, explicit ZIP preparation/submission, checker findings,
+policy management, single-request ZIP submission and operation progress, checker findings,
 system-Operator checker registration, terminal recovery and uncertain-delivery reconciliation, and
 contribution-evidence exports and exact Audit Authority task reads:
 
@@ -200,8 +200,8 @@ the [terminal presentation contract](../docs/design/cli-terminal-experience.md).
 | `workstream operations delivery list PROJECT_ID [--limit N] [--cursor TOKEN]` | `GET /api/v1/operations/projects/PROJECT_ID/post-submit-deliveries` |
 | `workstream operations delivery reconcile PROJECT_ID EVENT_ID --reason TEXT --idempotency-key UUID` | `POST /api/v1/operations/projects/PROJECT_ID/post-submit-deliveries/EVENT_ID/reconcile` |
 | `workstream task ready PROJECT_ID` | `GET /api/v1/projects/PROJECT_ID/tasks/ready` |
-| `workstream task prepare TASK_ID --assignment UUID --file ZIP --idempotency-key UUID` (revision: add predecessor and exact preparation ID/SHA-256) | `POST /api/v1/tasks/TASK_ID/submission-bundle-preparations` |
-| `workstream task submit TASK_ID --assignment UUID --admission UUID` | `POST /api/v1/tasks/TASK_ID/submissions` |
+| `workstream task submit TASK_ID --assignment UUID --file ZIP --idempotency-key UUID` | `POST /api/v1/tasks/TASK_ID/submissions` |
+| `workstream task submission-operation TASK_ID --operation-id UUID` (or `--idempotency-key UUID`) | `GET /api/v1/tasks/TASK_ID/submission-operations` |
 | `workstream task submissions TASK_ID [--limit N] [--cursor TOKEN]` | `GET /api/v1/tasks/TASK_ID/submissions` |
 | `workstream submission show SUBMISSION_ID` | `GET /api/v1/submissions/SUBMISSION_ID` |
 | `workstream submission findings SUBMISSION_ID [--limit N] [--cursor TOKEN]` | `GET /api/v1/submissions/SUBMISSION_ID/checker-runs` |
@@ -2242,3 +2242,11 @@ artifact binding, replica and verification evidence through the Operator CLI,
 and checks non-Operator concealment. The separate signed API test exercises
 retry only on a genuinely exhausted verification job. A successful upload is
 never used as an eligible retry fixture.
+
+Submission acceptance returns an operation ID before a formal Submission exists.
+Use `task submission-operation` to inspect it once, using exactly one selector.
+Key lookup uses the current actor; managers may use an authorized operation ID.
+The response preserves nullable IDs, current task context, the operation’s own
+processing stage, bounded PRE findings and the server’s next-action advice.
+Inspection never uploads again or polls automatically. Revisions still require
+the predecessor and exact revision preparation ID and digest.
diff --git a/cli/internal/api/submission_progress.go b/cli/internal/api/submission_progress.go
new file mode 100644
index 000000000..3ce6d644c
--- /dev/null
+++ b/cli/internal/api/submission_progress.go
@@ -0,0 +1,76 @@
+package api
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"math/big"
+	"net/http"
+	"net/url"
+)
+
+// SubmissionProgress preserves the operation's outcome separately from current task context.
+type SubmissionProgress struct {
+	OperationID            string            `json:"operation_id"`
+	TaskID                 string            `json:"task_id"`
+	AssignmentID           string            `json:"assignment_id"`
+	IdempotencyKey         string            `json:"idempotency_key"`
+	State                  string            `json:"operation_state"`
+	Stage                  string            `json:"processing_stage"`
+	AcceptedAt             *string           `json:"accepted_at"`
+	TaskStatusAtAcceptance *string           `json:"task_status_at_acceptance"`
+	CurrentTaskStatus      *string           `json:"current_task_status"`
+	SubmissionID           *string           `json:"submission_id"`
+	SubmissionVersion      *big.Int          `json:"submission_version"`
+	EvaluationRequestID    *string           `json:"evaluation_request_id"`
+	Feedback               []json.RawMessage `json:"pre_submission_results"`
+	FailureCode            *string           `json:"failure_code"`
+	Stalled                bool              `json:"operationally_stalled"`
+	NextAction             string            `json:"next_action"`
+}
+
+func decodeSubmissionProgress(raw json.RawMessage, task, operation, key string) (SubmissionProgress, error) {
+	var value SubmissionProgress
+	bad := &Failure{Code: "invalid_api_response"}
+	fields, err := contextObject(raw, &value, []string{"operation_id", "task_id", "assignment_id", "idempotency_key", "operation_state", "processing_stage", "pre_submission_results", "operationally_stalled", "next_action"}, nil)
+	if err != nil || !requiredNullable(fields, "accepted_at", "task_status_at_acceptance", "current_task_status", "submission_id", "submission_version", "evaluation_request_id", "failure_code") ||
+		!validUUID(value.OperationID) || !sameUUID(value.TaskID, task) || !validUUID(value.AssignmentID) || !validUUID(value.IdempotencyKey) ||
+		(operation != "" && !sameUUID(value.OperationID, operation)) || (key != "" && !sameUUID(value.IdempotencyKey, key)) ||
+		!oneOf(value.State, "receiving", "pre_checking", "finalization_pending", "finalized", "rejected", "failed", "abandoned", "cancelled") ||
+		!oneOf(value.Stage, "receiving", "pre_checking", "finalization_pending", "evaluation_pending", "evaluation_running", "review_pending", "needs_revision", "accepted", "rejected", "failed", "abandoned", "cancelled", "operationally_stalled") ||
+		!oneOf(value.NextAction, "wait", "correct_and_submit_new_key", "retry_new_key_after_terminal", "inspect_governed_outcome") ||
+		(value.AcceptedAt != nil && !validTime(*value.AcceptedAt)) ||
+		(value.TaskStatusAtAcceptance != nil && *value.TaskStatusAtAcceptance != "evaluation_pending") ||
+		(value.CurrentTaskStatus != nil && !oneOf(*value.CurrentTaskStatus, "draft", "screening", "ready", "in_progress", "submitted", "evaluation_pending", "review_pending", "needs_revision", "accepted")) ||
+		(value.SubmissionID != nil && !validUUID(*value.SubmissionID)) ||
+		(value.EvaluationRequestID != nil && !validUUID(*value.EvaluationRequestID)) ||
+		(value.SubmissionVersion != nil && value.SubmissionVersion.Sign() <= 0) ||
+		value.Feedback == nil || !validPreSubmissionResults(value.Feedback, value.AcceptedAt != nil) {
+		return value, bad
+	}
+	return value, nil
+}
+
+// SubmissionOperation makes one bounded read; it never retries the submission mutation.
+func (c *Client) SubmissionOperation(ctx context.Context, task, operation, key string) (Result[SubmissionProgress], error) {
+	var result Result[SubmissionProgress]
+	if !submissionSelector(task) || (operation == "") == (key == "") ||
+		(operation != "" && !submissionSelector(operation)) || (key != "" && !submissionSelector(key)) {
+		return result, errors.New("task and exactly one operation ID or idempotency key must be UUIDs")
+	}
+	query := url.Values{}
+	if operation != "" {
+		query.Set("operation_id", operation)
+	} else {
+		query.Set("idempotency_key", key)
+	}
+	raw, err := c.requestWithResponseLimit(ctx, http.MethodGet, "/api/v1/tasks/"+url.PathEscape(task)+"/submission-operations", query.Encode(), nil, "", http.StatusOK, maxSubmissionReadBytes)
+	if err != nil {
+		return result, err
+	}
+	value, err := decodeSubmissionProgress(raw, task, operation, key)
+	if err != nil || !c.safeMutationResponse(raw) {
+		return result, &Failure{Code: "invalid_api_response"}
+	}
+	return Result[SubmissionProgress]{Raw: raw, Value: value}, nil
+}
diff --git a/cli/internal/api/submission_progress_test.go b/cli/internal/api/submission_progress_test.go
new file mode 100644
index 000000000..95a8b9b6d
--- /dev/null
+++ b/cli/internal/api/submission_progress_test.go
@@ -0,0 +1,87 @@
+package api
+
+import (
+	"context"
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+)
+
+func progressJSON() map[string]any {
+	return map[string]any{"operation_id": testRun, "task_id": testTask, "assignment_id": testFinding,
+		"idempotency_key": testSubmission, "operation_state": "finalization_pending", "processing_stage": "finalization_pending",
+		"accepted_at": "2026-11-16T12:00:00Z", "task_status_at_acceptance": "evaluation_pending", "current_task_status": nil,
+		"submission_id": nil, "submission_version": nil, "evaluation_request_id": nil, "pre_submission_results": []any{},
+		"failure_code": nil, "operationally_stalled": false, "next_action": "wait"}
+}
+
+func TestSubmissionProgressSelectorsAndNoMutation(t *testing.T) {
+	requests := 0
+	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		requests++
+		if r.Method != "GET" || r.URL.Path != "/api/v1/tasks/"+testTask+"/submission-operations" || r.Header.Get("Idempotency-Key") != "" {
+			t.Error("unexpected mutation or route", r)
+		}
+		if len(r.URL.Query()) != 1 || (r.URL.Query().Get("operation_id") != testRun && r.URL.Query().Get("idempotency_key") != testSubmission) {
+			t.Error("selector lost", r.URL)
+		}
+		w.Header().Set("Content-Type", "application/json")
+		_ = json.NewEncoder(w).Encode(progressJSON())
+	}))
+	defer server.Close()
+	client, err := New(server.URL, "fixture-token")
+	if err != nil {
+		t.Fatal(err)
+	}
+	for _, selectors := range [][2]string{{testRun, ""}, {"", testSubmission}} {
+		got, err := client.SubmissionOperation(context.Background(), testTask, selectors[0], selectors[1])
+		if err != nil || got.Value.Stage != "finalization_pending" || got.Value.SubmissionID != nil {
+			t.Fatal(got, err)
+		}
+	}
+	for _, selectors := range [][2]string{{"", ""}, {testRun, testSubmission}, {"invalid", ""}} {
+		if _, err := client.SubmissionOperation(context.Background(), testTask, selectors[0], selectors[1]); err == nil {
+			t.Fatal("invalid selectors accepted")
+		}
+	}
+	if requests != 2 {
+		t.Fatal("unexpected HTTP requests", requests)
+	}
+}
+
+func TestSubmissionProgressRefusesUnboundOrMalformedEvidence(t *testing.T) {
+	for _, field := range []string{"task_id", "operation_id", "idempotency_key", "assignment_id", "processing_stage", "next_action", "provider_key", "submission_version", "pre_submission_results", "current_task_status"} {
+		t.Run(field, func(t *testing.T) {
+			value := progressJSON()
+			value[field] = "invalid"
+			raw, _ := json.Marshal(value)
+			if _, err := decodeSubmissionProgress(raw, testTask, testRun, testSubmission); err == nil {
+				t.Fatal("accepted invalid field", field)
+			}
+		})
+	}
+	for _, field := range []string{"accepted_at", "submission_id", "submission_version", "evaluation_request_id", "current_task_status", "failure_code", "task_status_at_acceptance"} {
+		value := progressJSON()
+		delete(value, field)
+		raw, _ := json.Marshal(value)
+		if _, err := decodeSubmissionProgress(raw, testTask, testRun, ""); err == nil {
+			t.Fatal("missing nullable accepted", field)
+		}
+	}
+	for _, stage := range []string{"evaluation_pending", "evaluation_running", "review_pending", "needs_revision", "accepted", "rejected", "operationally_stalled"} {
+		value := progressJSON()
+		value["operation_state"] = "finalized"
+		value["processing_stage"] = stage
+		value["submission_id"] = testFinding
+		value["submission_version"] = 2
+		value["evaluation_request_id"] = testSubmission
+		value["operationally_stalled"] = stage == "operationally_stalled"
+		value["next_action"] = "inspect_governed_outcome"
+		raw, _ := json.Marshal(value)
+		got, err := decodeSubmissionProgress(raw, testTask, testRun, "")
+		if err != nil || got.Stage != stage || got.NextAction != "inspect_governed_outcome" {
+			t.Fatal(stage, err)
+		}
+	}
+}
diff --git a/cli/internal/command/submission.go b/cli/internal/command/submission.go
index 7e3cdedd6..47c400c67 100644
--- a/cli/internal/command/submission.go
+++ b/cli/internal/command/submission.go
@@ -86,6 +86,31 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 		task.AddCommand(cmd)
 	}
 
+	{
+		var operation, key string
+		progress := &cobra.Command{Use: "submission-operation TASK_ID", Short: "Inspect one submission operation without resubmitting", Args: cobra.ExactArgs(1)}
+		progress.Flags().StringVar(&operation, "operation-id", "", "Operation UUID; choose this or --idempotency-key")
+		progress.Flags().StringVar(&key, "idempotency-key", "", "Your original caller UUID key; choose this or --operation-id")
+		progress.RunE = func(cmd *cobra.Command, args []string) error {
+			if cmd.Flags().Changed("operation-id") == cmd.Flags().Changed("idempotency-key") || (operation == "" && key == "") {
+				return commandError{"invalid_arguments", "provide exactly one nonempty --operation-id or --idempotency-key"}
+			}
+			c, err := client()
+			if err != nil {
+				return err
+			}
+			result, err := c.SubmissionOperation(cmd.Context(), args[0], operation, key)
+			if err != nil {
+				return err
+			}
+			if *output == "json" {
+				return writeSafeJSON(stdout, result.Raw)
+			}
+			return writeTaskContextFields(stdout, []contextField{{"Submission operation", result.Value}})
+		}
+		task.AddCommand(progress)
+	}
+
 	var historyLimit int
 	var historyCursor string
 	history := &cobra.Command{Use: "submissions TASK_ID", Short: "Read one page of authorized immutable submission history", Args: cobra.ExactArgs(1)}
diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py
index c056d175e..0cb52b8ed 100644
--- a/cli/tests/integration/test_submission_http.py
+++ b/cli/tests/integration/test_submission_http.py
@@ -721,3 +721,109 @@ def test_submission_response_caps_reject_otherwise_valid_oversized_json(cli, tmp
                 status == 202
             )
         assert len(requests) == len(cases) * 2
+
+
+def operation_progress():
+    return {
+        "operation_id": OPERATION,
+        "task_id": TASK,
+        "assignment_id": ASSIGNMENT,
+        "idempotency_key": KEY,
+        "operation_state": "finalization_pending",
+        "processing_stage": "finalization_pending",
+        "accepted_at": "2026-11-16T12:00:00Z",
+        "task_status_at_acceptance": "evaluation_pending",
+        "current_task_status": None,
+        "submission_id": None,
+        "submission_version": None,
+        "evaluation_request_id": None,
+        "pre_submission_results": [],
+        "failure_code": None,
+        "operationally_stalled": False,
+        "next_action": "wait",
+    }
+
+
+def test_operation_inspection_is_one_read_with_exact_selector(cli):
+    with http_fixture() as (origin, response, requests):
+        respond(response, operation_progress())
+        for flag, value, query in (
+            ("--operation-id", OPERATION, "operation_id"),
+            ("--idempotency-key", KEY, "idempotency_key"),
+        ):
+            result = cli(
+                origin,
+                TOKEN,
+                "--output",
+                "json",
+                "task",
+                "submission-operation",
+                TASK,
+                flag,
+                value,
+            )
+            assert result.returncode == 0, result.stderr
+            assert json.loads(result.stdout) == operation_progress()
+            method, path, authorization = requests[-1]
+            assert method == "GET" and authorization == "Bearer " + TOKEN
+            assert urlsplit(path).path == f"/api/v1/tasks/{TASK}/submission-operations"
+            assert parse_qs(urlsplit(path).query) == {query: [value]}
+        assert len(requests) == 2
+        for flags in (
+            (),
+            ("--operation-id", OPERATION, "--idempotency-key", KEY),
+            ("--operation-id", ""),
+            ("--operation-id", "invalid"),
+        ):
+            result = cli(
+                origin,
+                TOKEN,
+                "--output",
+                "json",
+                "task",
+                "submission-operation",
+                TASK,
+                *flags,
+            )
+            assert result.returncode != 0
+        assert len(requests) == 2
+        text_result = cli(
+            origin,
+            TOKEN,
+            "task",
+            "submission-operation",
+            TASK,
+            "--operation-id",
+            OPERATION,
+        )
+        assert text_result.returncode == 0, text_result.stderr
+        assert (
+            "finalization_pending" in text_result.stdout
+            and "wait" in text_result.stdout
+        )
+        assert len(requests) == 3
+
+
+def test_operation_inspection_refuses_foreign_or_private_response(cli):
+    with http_fixture() as (origin, response, requests):
+        for changed in (
+            {"operation_id": RUN},
+            {"task_id": RUN},
+            {"provider_key": "private"},
+            {"processing_stage": "invented"},
+            {"next_action": "submit_now"},
+        ):
+            respond(response, operation_progress() | changed)
+            result = cli(
+                origin,
+                TOKEN,
+                "--output",
+                "json",
+                "task",
+                "submission-operation",
+                TASK,
+                "--operation-id",
+                OPERATION,
+            )
+            assert_failure(result, "invalid_api_response")
+        assert len(requests) == 5
diff --git a/mcp_server/README.md b/mcp_server/README.md
index 71dd23cda..e16f7722b 100644
--- a/mcp_server/README.md
+++ b/mcp_server/README.md
@@ -1,6 +1,6 @@
 # Workstream MCP Adapter
 
-An independently installed adapter exposing 131 tools under the caller's authority:
+An independently installed adapter exposing 132 tools under the caller's authority:
 
 - `workstream_profile_get` calls `GET /api/v1/actors/me`.
 - `workstream_profile_update` calls the unkeyed `PATCH /api/v1/actors/me`.
@@ -224,6 +224,11 @@ Submission creation accepts a bounded Base64 ZIP, decodes it once and forwards t
 caller's typed assignment/key and optional submission or revision fields as the
 fixed backend headers. The raw-ZIP POST returns a `202` acceptance snapshot with
 an operation ID; formal Submission creation and evaluation continue durably.
+Use `workstream_submission_operation_get` with `task_id` and exactly one of
+`operation_id` or `idempotency_key` for one authorized progress read. Keys are
+actor-scoped; management reads can select an operation ID. The tool preserves
+nullable fields, PRE feedback and server next-action advice without resubmitting
+or polling. Current task status is context, not the historical operation outcome.
 Revision preparation ID and digest are both required with a predecessor and
 forbidden for initial submission. Workstream owns ZIP validation, pre-submit checks, replay and all task
 state changes. A checker rejection is a normal safe tool failure; an unverified
@@ -251,7 +256,7 @@ retries. A mutation transport failure, upstream 5xx response, or unexpected
 success/redirect response is reported as non-retryable uncertain execution.
 Connections may be pooled, but
 caller credentials and results are not shared or cached. Response validation is
-pinned to the 131 selected public contracts in `contracts/`; upstream drift
+pinned to the 132 selected public contracts in `contracts/`; upstream drift
 must be reviewed, not silently accepted. There is no fallback service or
 backend-private import.
 
diff --git a/mcp_server/contracts/submission_operation_get.json b/mcp_server/contracts/submission_operation_get.json
new file mode 100644
index 000000000..3d91e9d72
--- /dev/null
+++ b/mcp_server/contracts/submission_operation_get.json
@@ -0,0 +1,544 @@
+{
+  "canonical_sha256": "d952c167bfdd1a6e434c2549bbe7fd86b27dce9e4653afa72cdd5f66e740aeef",
+  "components": {
+    "schemas": {
+      "ApiError": {
+        "additionalProperties": false,
+        "description": "Canonical machine-readable API error.",
+        "properties": {
+          "code": {
+            "title": "Code",
+            "type": "string"
+          },
+          "correlation_id": {
+            "title": "Correlation Id",
+            "type": "string"
+          },
+          "details": {
+            "additionalProperties": true,
+            "title": "Details",
+            "type": "object"
+          },
+          "message": {
+            "title": "Message",
+            "type": "string"
+          },
+          "retryable": {
+            "title": "Retryable",
+            "type": "boolean"
+          }
+        },
+        "required": [
+          "code",
+          "message",
+          "details",
+          "correlation_id",
+          "retryable"
+        ],
+        "title": "ApiError",
+        "type": "object"
+      },
+      "ApiErrorResponse": {
+        "additionalProperties": false,
+        "description": "Canonical error plus additive legacy compatibility fields.",
+        "properties": {
+          "detail": {
+            "anyOf": [
+              {},
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Detail"
+          },
+          "error": {
+            "$ref": "#/components/schemas/ApiError"
+          }
+        },
+        "required": [
+          "error"
+        ],
+        "title": "ApiErrorResponse",
+        "type": "object"
+      },
+      "SubmissionOperationResponse": {
+        "additionalProperties": false,
+        "description": "Authorized operation projection; nullable fields are required on the wire.",
+        "properties": {
+          "accepted_at": {
+            "anyOf": [
+              {
+                "format": "date-time",
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Accepted At"
+          },
+          "assignment_id": {
+            "format": "uuid",
+            "title": "Assignment Id",
+            "type": "string"
+          },
+          "current_task_status": {
+            "anyOf": [
+              {
+                "enum": [
+                  "draft",
+                  "screening",
+                  "ready",
+                  "in_progress",
+                  "submitted",
+                  "evaluation_pending",
+                  "review_pending",
+                  "needs_revision",
+                  "accepted"
+                ],
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Current Task Status"
+          },
+          "evaluation_request_id": {
+            "anyOf": [
+              {
+                "format": "uuid",
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Evaluation Request Id"
+          },
+          "failure_code": {
+            "anyOf": [
+              {
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Failure Code"
+          },
+          "idempotency_key": {
+            "format": "uuid",
+            "title": "Idempotency Key",
+            "type": "string"
+          },
+          "next_action": {
+            "enum": [
+              "wait",
+              "correct_and_submit_new_key",
+              "retry_new_key_after_terminal",
+              "inspect_governed_outcome"
+            ],
+            "title": "Next Action",
+            "type": "string"
+          },
+          "operation_id": {
+            "format": "uuid",
+            "title": "Operation Id",
+            "type": "string"
+          },
+          "operation_state": {
+            "enum": [
+              "receiving",
+              "pre_checking",
+              "finalization_pending",
+              "finalized",
+              "rejected",
+              "failed",
+              "abandoned",
+              "cancelled"
+            ],
+            "title": "Operation State",
+            "type": "string"
+          },
+          "operationally_stalled": {
+            "title": "Operationally Stalled",
+            "type": "boolean"
+          },
+          "pre_submission_results": {
+            "items": {
+              "additionalProperties": true,
+              "type": "object"
+            },
+            "title": "Pre Submission Results",
+            "type": "array"
+          },
+          "processing_stage": {
+            "enum": [
+              "receiving",
+              "pre_checking",
+              "finalization_pending",
+              "evaluation_pending",
+              "evaluation_running",
+              "review_pending",
+              "needs_revision",
+              "accepted",
+              "rejected",
+              "failed",
+              "abandoned",
+              "cancelled",
+              "operationally_stalled"
+            ],
+            "title": "Processing Stage",
+            "type": "string"
+          },
+          "submission_id": {
+            "anyOf": [
+              {
+                "format": "uuid",
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Submission Id"
+          },
+          "submission_version": {
+            "anyOf": [
+              {
+                "exclusiveMinimum": 0.0,
+                "type": "integer"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Submission Version"
+          },
+          "task_id": {
+            "format": "uuid",
+            "title": "Task Id",
+            "type": "string"
+          },
+          "task_status_at_acceptance": {
+            "anyOf": [
+              {
+                "const": "evaluation_pending",
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Task Status At Acceptance"
+          }
+        },
+        "required": [
+          "operation_id",
+          "task_id",
+          "assignment_id",
+          "idempotency_key",
+          "operation_state",
+          "processing_stage",
+          "accepted_at",
+          "task_status_at_acceptance",
+          "current_task_status",
+          "submission_id",
+          "submission_version",
+          "evaluation_request_id",
+          "pre_submission_results",
+          "failure_code",
+          "operationally_stalled",
+          "next_action"
+        ],
+        "title": "SubmissionOperationResponse",
+        "type": "object"
+      }
+    }
+  },
+  "operation": {
+    "description": "Read this operation's own evidence under current contributor or management authority.",
+    "operationId": "read_submission_operation_api_v1_tasks__task_id__submission_operations_get",
+    "parameters": [
+      {
+        "in": "path",
+        "name": "task_id",
+        "required": true,
+        "schema": {
+          "format": "uuid",
+          "title": "Task Id",
+          "type": "string"
+        }
+      },
+      {
+        "in": "query",
+        "name": "operation_id",
+        "required": false,
+        "schema": {
+          "anyOf": [
+            {
+              "format": "uuid",
+              "type": "string"
+            },
+            {
+              "type": "null"
+            }
+          ],
+          "title": "Operation Id"
+        }
+      },
+      {
+        "in": "query",
+        "name": "idempotency_key",
+        "required": false,
+        "schema": {
+          "anyOf": [
+            {
+              "format": "uuid",
+              "type": "string"
+            },
+            {
+              "type": "null"
+            }
+          ],
+          "title": "Idempotency Key"
+        }
+      },
+      {
+        "in": "header",
+        "name": "X-Request-ID",
+        "required": false,
+        "schema": {
+          "format": "uuid",
+          "maxLength": 36,
+          "minLength": 36,
+          "type": "string"
+        }
+      },
+      {
+        "in": "header",
+        "name": "X-Correlation-ID",
+        "required": false,
+        "schema": {
+          "format": "uuid",
+          "maxLength": 36,
+          "minLength": 36,
+          "type": "string"
+        }
+      }
+    ],
+    "responses": {
+      "200": {
+        "content": {
+          "application/json": {
+            "schema": {
+              "$ref": "#/components/schemas/SubmissionOperationResponse"
+            }
+          }
+        },
+        "description": "Successful Response",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "400": {
+        "content": {
+          "application/json": {
+            "schema": {
+              "$ref": "#/components/schemas/ApiErrorResponse"
+            }
+          }
+        },
+        "description": "Invalid request.",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "401": {
+        "content": {
+          "application/json": {
+            "schema": {
+              "$ref": "#/components/schemas/ApiErrorResponse"
+            }
+          }
+        },
+        "description": "Authentication failed.",
+        "headers": {
+          "WWW-Authenticate": {
+            "schema": {
+              "type": "string"
+            }
+          },
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "403": {
+        "content": {
+          "application/json": {
+            "schema": {
+              "$ref": "#/components/schemas/ApiErrorResponse"
+            }
+          }
+        },
+        "description": "Permission denied.",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "404": {
+        "description": "Operation or current read authority unavailable",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "422": {
+        "description": "Exactly one operation UUID or actor-scoped idempotency key is required",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "500": {
+        "content": {
+          "application/json": {
+            "schema": {
+              "$ref": "#/components/schemas/ApiErrorResponse"
+            }
+          }
+        },
+        "description": "Internal server error.",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      },
+      "503": {
+        "description": "Stored operation progress cannot be verified",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
+      }
+    },
+    "security": [
+      {
+        "HTTPBearer": []
+      }
+    ],
+    "summary": "Read Submission Operation",
+    "tags": [
+      "tasks"
+    ],
+    "x-workstream-action-id": "task.submission_operation.read",
+    "x-workstream-management-action-id": "project.task.submission_operation.read"
+  },
+  "schema_version": 1,
+  "source": {
+    "method": "GET",
+    "openapi_version": "3.1.0",
+    "path": "/api/v1/tasks/{task_id}/submission-operations",
+    "repository_sha": "686d7f7d7da90db6eb0b8fd546ecc0ea7252e8f8"
+  }
+}
diff --git a/mcp_server/pyproject.toml b/mcp_server/pyproject.toml
index 60af89165..914fb96d5 100644
--- a/mcp_server/pyproject.toml
+++ b/mcp_server/pyproject.toml
@@ -135,6 +135,7 @@ packages = ["workstream_mcp"]
 "contracts/task_claim.json" = "workstream_mcp/contracts/task_claim.json"
 "contracts/task_work_context_get.json" = "workstream_mcp/contracts/task_work_context_get.json"
 "contracts/task_guide_document_content_get.json" = "workstream_mcp/contracts/task_guide_document_content_get.json"
+"contracts/submission_operation_get.json" = "workstream_mcp/contracts/submission_operation_get.json"
 "contracts/submission_create.json" = "workstream_mcp/contracts/submission_create.json"
 "contracts/task_submissions_list.json" = "workstream_mcp/contracts/task_submissions_list.json"
 "contracts/submission_get.json" = "workstream_mcp/contracts/submission_get.json"
diff --git a/mcp_server/tests/test_task_execution.py b/mcp_server/tests/test_task_execution.py
index f37265bbf..a890094f7 100644
--- a/mcp_server/tests/test_task_execution.py
+++ b/mcp_server/tests/test_task_execution.py
@@ -28,6 +28,7 @@
 
 def _arguments(name: str) -> dict[str, Any]:
     values: dict[str, dict[str, Any]] = {
+        "submission_operation_get": {"task_id": TASK_ID, "operation_id": OPERATION_ID},
         "submission_create": {
             "task_id": TASK_ID,
             "assignment_id": ASSIGNMENT_ID,
@@ -94,6 +95,8 @@ def _bound_response(name: str) -> dict[str, Any]:
             "byte_count": 1,
             "sha256": "sha256:" + "0" * 64,
         }
+    if name == "submission_operation_get":
+        return {"task_id": TASK_ID, "operation_id": OPERATION_ID, "idempotency_key": KEY}
     if name == "submission_create":
         return {"task_id": TASK_ID, "assignment_id": ASSIGNMENT_ID}
     if name in {"submission_get", "management_submission_get"}:
@@ -465,3 +468,114 @@ def test_submission_revision_requires_predecessor_and_both_acknowledgements(
         "revision_preparation_id": PREPARATION_ID,
         "revision_preparation_sha256": "sha256:" + "a" * 64,
     })
+
+
+def _operation_progress() -> dict[str, Any]:
+    return {
+        "operation_id": OPERATION_ID,
+        "task_id": TASK_ID,
+        "assignment_id": ASSIGNMENT_ID,
+        "idempotency_key": KEY,
+        "operation_state": "finalization_pending",
+        "processing_stage": "finalization_pending",
+        "accepted_at": "2026-11-16T12:00:00Z",
+        "task_status_at_acceptance": "evaluation_pending",
+        "current_task_status": None,
+        "submission_id": None,
+        "submission_version": None,
+        "evaluation_request_id": None,
+        "pre_submission_results": [],
+        "failure_code": None,
+        "operationally_stalled": False,
+        "next_action": "wait",
+    }
+
+
+@pytest.mark.parametrize(
+    "selector,value", [("operation_id", OPERATION_ID), ("idempotency_key", KEY)]
+)
+def test_operation_progress_uses_one_get_and_binds_selector(
+    adapter: Adapter, selector, value
+) -> None:
+    client, received, upstream = adapter
+    upstream["json"] = _operation_progress()
+    arguments = {"task_id": TASK_ID, selector: value}
+
+    def read():
+        return client.post(
+            "/mcp",
+            headers={
+                "authorization": "Bearer fixture-token",
+                "accept": "application/json, text/event-stream",
+            },
+            json={
+                "jsonrpc": "2.0",
+                "id": 1,
+                "method": "tools/call",
+                "params": {"name": "workstream_submission_operation_get", "arguments": arguments},
+            },
+        ).json()["result"]
+
+    assert read()["isError"] is False
+    assert len(received) == 1
+    assert received[0].method == "GET"
+    assert received[0].url.path == f"/api/v1/tasks/{TASK_ID}/submission-operations"
+    assert dict(received[0].url.params) == {selector: value}
+    assert "idempotency-key" not in received[0].headers
+    upstream["json"][selector] = ASSIGNMENT_ID
+    assert read()["isError"] is True
+
+
+@pytest.mark.parametrize(
+    "selectors",
+    [
+        {},
+        {"operation_id": OPERATION_ID, "idempotency_key": KEY},
+        {"operation_id": "bad"},
+        {"idempotency_key": KEY, "actor_id": ASSIGNMENT_ID},
+    ],
+)
+def test_operation_progress_invalid_selectors_never_dispatch(adapter: Adapter, selectors) -> None:
+    client, received, _ = adapter
+    response = client.post(
+        "/mcp",
+        headers={"authorization": "Bearer fixture-token",
+                 "accept": "application/json, text/event-stream"},
+        json={
+            "jsonrpc": "2.0",
+            "id": 1,
+            "method": "tools/call",
+            "params": {
+                "name": "workstream_submission_operation_get",
+                "arguments": {"task_id": TASK_ID, **selectors},
+            },
+        },
+    )
+    assert response.json()["result"]["isError"] is True
+    assert received == []
+
+
+@pytest.mark.parametrize(
+    "change", ["foreign_task", "private_field", "missing_nullable", "unknown_stage"]
+)
+def test_operation_progress_rejects_unbound_or_noncontract_response(
+    adapter: Adapter, change
+) -> None:
+    client, received, upstream = adapter
+    progress = _operation_progress()
+    if change == "foreign_task":
+        progress["task_id"] = ASSIGNMENT_ID
+    elif change == "private_field":
+        progress["provider_key"] = "private"
+    elif change == "missing_nullable":
+        del progress["evaluation_request_id"]
+    else:
+        progress["processing_stage"] = "invented"
+    upstream["json"] = progress
+    response = client.post("/mcp", headers={"authorization": "Bearer fixture-token",
+                 "accept": "application/json, text/event-stream"},
+        json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {
+            "name": "workstream_submission_operation_get",
+            "arguments": {"task_id": TASK_ID, "operation_id": OPERATION_ID}}})
+    assert response.json()["result"]["isError"] is True
+    assert len(received) == 1
diff --git a/mcp_server/tests/test_task_execution_contract_drift.py b/mcp_server/tests/test_task_execution_contract_drift.py
index 1480f10b0..3dfeab72e 100644
--- a/mcp_server/tests/test_task_execution_contract_drift.py
+++ b/mcp_server/tests/test_task_execution_contract_drift.py
@@ -69,7 +69,7 @@ def test_task_execution_contract_is_tamper_evident_and_matches_fixed_route(
 
 
 def test_exact_task_execution_contract_set_is_reviewed() -> None:
-    assert len(TASK_EXECUTION_CONTRACT_NAMES) == 16
+    assert len(TASK_EXECUTION_CONTRACT_NAMES) == 17
     assert set(TASK_EXECUTION_CONTRACT_NAMES) == set(TASK_EXECUTION_OPERATIONS)
 
 
diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py
index 6c96a86be..2e398d8fc 100644
--- a/mcp_server/workstream_mcp/http_gateway.py
+++ b/mcp_server/workstream_mcp/http_gateway.py
@@ -388,6 +388,7 @@
         "/api/v1/tasks/{task_id}/guide/documents/{document_id}/content",
         200,
     ),
+    "submission_operation_get": ("GET", "/api/v1/tasks/{task_id}/submission-operations", 200),
     "submission_create": ("POST", "/api/v1/tasks/{task_id}/submissions", 202),
     "task_submissions_list": ("GET", "/api/v1/tasks/{task_id}/submissions", 200),
     "submission_get": ("GET", "/api/v1/submissions/{submission_id}", 200),
@@ -1499,6 +1500,8 @@ async def task_execution_operation(
             "revision_preparation_id",
             "revision_preparation_sha256",
         }
+        if name == "submission_operation_get":
+            excluded.remove("idempotency_key")
         params = {
             key: str(value)
             for key, value in arguments.items()
@@ -1529,7 +1532,7 @@ async def task_execution_operation(
             correlation_id,
             json_body=arguments.get("body"),
             params=params or None,
-            idempotency_key=arguments.get("idempotency_key"),
+            idempotency_key=arguments.get("idempotency_key") if mutation else None,
             expected_status=expected_status,
             mutation=mutation,
             raw_body=upload,
@@ -1565,6 +1568,9 @@ def _task_execution_response_matches(
             return False
         if project_id is not None and not isinstance(project_id, str):
             return False
+        if name == "submission_operation_get":
+            selector = "operation_id" if "operation_id" in arguments else "idempotency_key"
+            return cls._fields_match(data, {"task_id": task_id, selector: arguments[selector]})
         if name == "preparations_list":
             return cls._items_match(data, {"task_id": task_id}, unique="preparation_id")
         if name == "preparation_get":
diff --git a/mcp_server/workstream_mcp/schemas.py b/mcp_server/workstream_mcp/schemas.py
index 652fa0dfc..15d8200bd 100644
--- a/mcp_server/workstream_mcp/schemas.py
+++ b/mcp_server/workstream_mcp/schemas.py
@@ -909,6 +909,17 @@ def _task_transition_input() -> dict[str, Any]:
         "required": ["task_id", "document_id"],
         "additionalProperties": False,
     },
+    "submission_operation_get": {
+        "type": "object",
+        "properties": {
+            "task_id": _UUID_INPUT,
+            "operation_id": _UUID_INPUT,
+            "idempotency_key": _IDEMPOTENCY_KEY_INPUT,
+        },
+        "required": ["task_id"],
+        "oneOf": [{"required": ["operation_id"]}, {"required": ["idempotency_key"]}],
+        "additionalProperties": False,
+    },
     "submission_create": {
         "type": "object",
         "properties": {
diff --git a/mcp_server/workstream_mcp/tools/task_execution.py b/mcp_server/workstream_mcp/tools/task_execution.py
index cfeb9cc47..e405faf51 100644
--- a/mcp_server/workstream_mcp/tools/task_execution.py
+++ b/mcp_server/workstream_mcp/tools/task_execution.py
@@ -32,6 +32,10 @@
     "task_claim": "Claim and start one ready task atomically.",
     "task_work_context_get": "Read the current contributor work context for one task.",
     "task_guide_document_content_get": "Read one assigned guide document as bounded bytes.",
+    "submission_operation_get": (
+        "Read one authorized submission operation by operation ID or your idempotency key; "
+        "never resubmits."
+    ),
     "submission_create": "Upload one ZIP for initial checks and durable evaluation acceptance.",
     "task_submissions_list": "List the current contributor's submissions for one task.",
     "submission_get": "Read one submission visible to the current contributor.",

From 4346f80e9c2e23cac110dc5a57411c94d8f31a0b Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 16:21:54 +0100
Subject: [PATCH 161/513] fix(clients): reconcile progress catalogue checks and
 submission docs

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 24 +++++
 .github/workflows/mcp.yml                     |  2 +-
 .../test_submission_intake_progress.py        |  1 -
 cli/README.md                                 | 99 +++++++++----------
 deploy/hosted/compose.mcp.yml                 |  2 +-
 mcp_server/README.md                          |  2 +-
 scripts/test_hosted_mcp_container.py          |  5 +-
 7 files changed, 77 insertions(+), 58 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 9d68a6352..7111b91af 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5126,3 +5126,27 @@ prior shared-family fingerprint exactly. Behavior-ownership validation passes.
 Freeze client progress plus proof extraction for ARCH/SEC, QA/test-delta and
 DOCS/CI review. All receipts above are worktree receipts on parent686; no full CI
 or historical/terminal branch qualification is implied.
+
+### Client review repairs
+
+Frozen ddf proof passed3DB153.91s (0081/cleanuptrue),66configuredMCP238.40s,
+17CLIHTTP37.68s and GoAPI/command packages. QA/test-delta passes, with independent
+binding mutant detection and exact42assertion/four-raises preservation. ARCH/SEC
+found no runtime defect, but the newly tracked test has an extra empty EOF line;
+precommit diff --check had not inspected untracked files. DOCS/CI requires132-tool
+counts in .github/workflows/mcp.yml, scripts/test_hosted_mcp_container.py and
+deploy/hosted/compose.mcp.yml, plus CLI's stale prepare/admission walkthrough and
+MCP's Seventeen family summary. Extend repair scope to these three exact hosted
+consumers; retain uniqueness and fixed-name checks and explicitly require the new
+progress tool where names are already inspected. Remove only the EOF blank line,
+reconcile the current submission walkthrough/unknown-outcome/revision advice,
+and remove duplicate appended progress prose. No client/runtime behavior change.
+Verify committed diff whitespace, document scans and actual assertion probes;
+replay affected reviews against the repair commit before pushing samePR708.
+
+Repair verification: actual application tools/list returns132 tools and passes the
+exact workflow Python assertion, hosted smoke count/name assertions and Compose
+healthcheck Python with substituted HTTP responses. Workflow counterprobes reject
+missing, extra, duplicate and missing-progress-tool catalogues. Artifact:
+/tmp/submission-catalogue-repair-probe.log. This proves catalogue assertions, not
+hosted deployment. Commitrail validation and worktree whitespace checks pass.
diff --git a/.github/workflows/mcp.yml b/.github/workflows/mcp.yml
index 4a5f1427d..0815707a7 100644
--- a/.github/workflows/mcp.yml
+++ b/.github/workflows/mcp.yml
@@ -76,7 +76,7 @@ jobs:
               --header 'Content-Type: application/json' \
               --data '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \
               http://127.0.0.1:18080/mcp \
-              | python -c 'import json, sys; tools = [tool["name"] for tool in json.load(sys.stdin)["result"]["tools"]]; expected = ["workstream_projects_list", "workstream_service_actor_create", "workstream_task_import_batch_create", "workstream_management_tasks_list", "workstream_management_task_create", "workstream_operational_tasks_list", "workstream_task_import_batch_screen", "workstream_task_import_batch_release", "workstream_task_import_batch_get", "workstream_management_task_get", "workstream_management_task_locked_context_get", "workstream_operational_task_locked_context_get", "workstream_audit_task_locked_context_get", "workstream_task_revision_context_repair", "workstream_audit_task_evidence_get", "workstream_project_model_profile_provision", "workstream_project_model_budget_configure", "workstream_project_model_usage_effect_get", "workstream_project_model_recovery_child_create", "workstream_task_import_source_declare", "workstream_task_import_source_content_upload", "workstream_task_import_source_content_get", "workstream_task_import_source_get"]; assert len(tools) == len(set(tools)) == 131; assert tools[-23:] == expected'; then
+              | python -c 'import json, sys; tools = [tool["name"] for tool in json.load(sys.stdin)["result"]["tools"]]; expected = ["workstream_projects_list", "workstream_service_actor_create", "workstream_task_import_batch_create", "workstream_management_tasks_list", "workstream_management_task_create", "workstream_operational_tasks_list", "workstream_task_import_batch_screen", "workstream_task_import_batch_release", "workstream_task_import_batch_get", "workstream_management_task_get", "workstream_management_task_locked_context_get", "workstream_operational_task_locked_context_get", "workstream_audit_task_locked_context_get", "workstream_task_revision_context_repair", "workstream_audit_task_evidence_get", "workstream_project_model_profile_provision", "workstream_project_model_budget_configure", "workstream_project_model_usage_effect_get", "workstream_project_model_recovery_child_create", "workstream_task_import_source_declare", "workstream_task_import_source_content_upload", "workstream_task_import_source_content_get", "workstream_task_import_source_get"]; assert len(tools) == len(set(tools)) == 132; assert "workstream_submission_operation_get" in tools; assert tools[-23:] == expected'; then
               exit 0
             fi
             sleep 1
diff --git a/backend/tests/artifacts/test_submission_intake_progress.py b/backend/tests/artifacts/test_submission_intake_progress.py
index 3b2b03ad8..574cbf26d 100644
--- a/backend/tests/artifacts/test_submission_intake_progress.py
+++ b/backend/tests/artifacts/test_submission_intake_progress.py
@@ -247,4 +247,3 @@ def missing_source(*_args, **_kwargs):
 
     finally:
         store.close()
-
diff --git a/cli/README.md b/cli/README.md
index cc763b9ec..2d67d3f57 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -1090,58 +1090,60 @@ including stored foreign-project concealment. Canonical retained prerequisites
 and Celery publication to an in-memory test broker do not prove distributed
 delivery, worker completion, live setup inference or deployed Flow behavior.
 
-## Prepare, submit and inspect contributor work
+## Submit and inspect contributor work
 
 ```sh
-workstream task prepare TASK_ID --assignment ASSIGNMENT_ID --file work.zip \
+workstream task submit TASK_ID --assignment ASSIGNMENT_ID --file work.zip \
   --idempotency-key CALLER_UUID --summary 'Completed work' --attestation 'My attestation'
-# If still pending, wait for server verification and explicitly repeat the same
-# preparation command, key, file bytes and packet. There is no polling GET.
-workstream task submit TASK_ID --assignment ASSIGNMENT_ID --admission READY_ADMISSION_ID \
-  --summary 'Completed work' --attestation 'My attestation'
+# Inspect once using the returned operation ID, or your original caller key.
+workstream task submission-operation TASK_ID --operation-id OPERATION_ID
+workstream task submission-operation TASK_ID --idempotency-key CALLER_UUID
 # For a checker-requested revision, inspect the current task context first.
 workstream task context TASK_ID --output json
-workstream task prepare TASK_ID --assignment ASSIGNMENT_ID --file revision.zip \
+workstream task submit TASK_ID --assignment ASSIGNMENT_ID --file revision.zip \
   --predecessor SOURCE_SUBMISSION_ID --revision-preparation-id PREPARATION_ID \
   --revision-preparation-sha256 "$PREPARATION_SHA256" \
   --idempotency-key REVISION_KEY --summary 'Revised work'
-workstream task submit TASK_ID --assignment ASSIGNMENT_ID --admission READY_REVISION_ADMISSION_ID \
-  --predecessor SOURCE_SUBMISSION_ID --summary 'Revised work'
 workstream task submissions TASK_ID --limit 25
 workstream submission show SUBMISSION_ID
 workstream submission findings SUBMISSION_ID --limit 25
 workstream submission findings SUBMISSION_ID --run CHECKER_RUN_ID
 ```
 
-Preparation streams one nonempty regular ZIP (at most 500MiB compressed,
-524,288,000 bytes) to the public authenticated API. Server project limits can be
-smaller. It never creates a
-Submission, automatically retries or polls. A `ready` receipt supplies the
-admission for the separate submit command. Other statuses must not be interpreted
-as readiness. Before confirming a successful upload, the CLI checks file size,
-modification time and SHA-256 again; a changed source reports an uncertain outcome.
-
-Both commands accept optional `--summary`, `--attestation` and `--predecessor`.
-Revision preparation additionally requires the exact `revision_context.preparation_id`
-and `revision_context.preparation_sha256` from the authorized task context as
+Submit streams one nonempty regular ZIP, at most 500MiB compressed
+(524,288,000 bytes), through one authenticated request. Server project limits can
+be smaller. Inline PRE returns actionable findings or durable acceptance with an
+operation ID. Formal Submission creation and POST evaluation continue durably;
+acceptance of intake is not a governed acceptance of the work. The CLI ends after
+printing the response and never automatically resubmits or polls.
+
+`task submission-operation` performs one read using exactly one selector. A key
+lookup is scoped to the current actor; managers can use an authorized operation
+ID. Nullable Submission/evaluation IDs remain null before finalization. The
+operation's processing stage, PRE feedback and next-action advice come from the
+server; current task status is contextual and may differ from a historical outcome.
+
+Submit accepts optional `--summary`, `--attestation` and `--predecessor`.
+Revisions require the exact `revision_context.preparation_id` and
+`revision_context.preparation_sha256` from authorized task context as
 `--revision-preparation-id` and `--revision-preparation-sha256`. Both flags are
-forbidden for initial preparation and are sent as preparation headers only; they
-are not part of the Submission JSON. Keep the pair unchanged for explicit
-preparation replay. A fresh server check rejects a stale pair after a rebase,
-deadline or source change; the CLI never selects a replacement automatically.
-Use the same packet for preparation, creation and explicit replay. The current
-preparation API transports text in headers: printable ASCII only, at most 64KiB
-per text field, with no leading/trailing whitespace. Unsupported text is rejected
-before dispatch, not rewritten. Omitted or explicitly empty text is supported;
-the server supplies warning-only defaults where applicable. The API owns all
-policy checks, predecessor/currentness rules and authorization.
-
-Submission creation is keyed by the exact admission and packet; there is no
-additional client-generated creation key. A lost or malformed write response
-exits 1 with `outcome_unknown: true`, empty stdout and a text-mode recovery hint.
-Inspect task history and explicitly replay only unchanged inputs. Do not generate
-a new preparation key simply because a response was lost. Each replay requires
-fresh server authority, including after a CLI restart.
+forbidden for initial submission. These acknowledge the governed revision context;
+they do not request a separate bundle preparation. A fresh server check rejects a
+stale pair after a rebase, deadline or source change. The CLI never chooses a
+replacement automatically.
+
+Packet text uses headers: printable ASCII only, at most 64KiB per field, without
+leading/trailing whitespace. Unsupported text is rejected before dispatch, not
+rewritten. Omitted or empty text is supported, with warning-only defaults where
+applicable. The API owns policy, predecessor/currentness and authorization checks.
+Before confirming upload success, the CLI rechecks file size, modification time
+and SHA-256; a changed source reports an uncertain outcome.
+
+A lost or malformed write response exits 1 with `outcome_unknown: true`, empty
+stdout and a text-mode recovery hint. Inspect progress with the original actor
+and key. Any explicit replay must preserve task, assignment, key, ZIP bytes,
+packet and revision acknowledgement. Do not create a new key while the outcome
+is unknown. Every read or replay requires fresh server authority.
 
 Blocked pre-submission intake prints the validated contributor findings in error
 `details`; it creates no Submission. Infrastructure failures are not quality
@@ -1174,10 +1176,11 @@ eligible may claim a new assignment at round 0, including a previous claimant;
 there is no contributor-count limit. Human decision integration remains #554.
 
 
-The native process test uses real HTTP, PostgreSQL and local ART custody, with
-approved-policy/assignment prerequisites arranged by fixtures. It drives the real
-independent verifier directly; it does not certify distributed scheduling, S3 or
-the complete public guide-setup journey owned by PILOT #552.
+Built-process HTTP tests cover submission and progress response handling. Backend
+source-custody tests separately exercise PostgreSQL, PRE, finalization and POST
+routing. The older CLI real-API fixtures still require migration to the source-bound
+PRE path; these checks do not yet prove the complete CLI-to-worker journey,
+distributed scheduling, hosted S3 or public guide setup.
 
 ## Inspect an exact derived post-submission policy
 
@@ -1795,7 +1798,7 @@ browsing receives an empty document list. Task examples are never included.
 For a task awaiting revision, the optional `revision_context` gives the current
 preparation ID and digest, source Submission, deadline, eligibility disposition
 and bounded change summary. It may be absent or null on other tasks. Use its
-exact preparation pair for a revision ZIP preparation; the read does not reserve
+exact preparation pair for a revision ZIP submission; the read does not reserve
 or authorize later intake.
 Hints are observations, not authority
 or a claimability guarantee. The CLI never recomputes them or automatically
@@ -1805,7 +1808,7 @@ Requirements expose the task's locked guide and intake rules: packet fields,
 artifact/evidence requirements, forbidden patterns, attestation, hash/manifest
 requirements, storage-reference restrictions, size/entry limits and packaging.
 They are not a current-guide lookup, a checker verdict or permission to upload.
-These reads do not invoke the separate `task prepare`/`task submit` commands. Described
+These reads do not invoke `task submit`. Described
 paths and storage references are displayed only, never read, downloaded or executed.
 
 ### Read the assigned guide
@@ -1823,7 +1826,7 @@ latest guide or drafts. A successor activation alone never changes its documents
 Checker-requested revision preparation can atomically rebase the complete task
 and assignment context for the next attempt. Inspect `task context` for its
 frozen change summary and acknowledge the exact preparation pair when running
-`task prepare`; this guide download does not initiate a rebase. Covered-manager
+`task submit`; this guide download does not initiate a rebase. Covered-manager
 repair is a separate backend operation with no CLI command. Genuine human
 Review revision integration remains #554 work.
 
@@ -2242,11 +2245,3 @@ artifact binding, replica and verification evidence through the Operator CLI,
 and checks non-Operator concealment. The separate signed API test exercises
 retry only on a genuinely exhausted verification job. A successful upload is
 never used as an eligible retry fixture.
-
-Submission acceptance returns an operation ID before a formal Submission exists.
-Use `task submission-operation` to inspect it once, using exactly one selector.
-Key lookup uses the current actor; managers may use an authorized operation ID.
-The response preserves nullable IDs, current task context, the operation’s own
-processing stage, bounded PRE findings and the server’s next-action advice.
-Inspection never uploads again or polls automatically. Revisions still require
-the predecessor and exact revision preparation ID and digest.
diff --git a/deploy/hosted/compose.mcp.yml b/deploy/hosted/compose.mcp.yml
index a3ed75ec5..ec7c3ab0c 100644
--- a/deploy/hosted/compose.mcp.yml
+++ b/deploy/hosted/compose.mcp.yml
@@ -28,7 +28,7 @@ services:
       WORKSTREAM_MCP_MAX_IN_FLIGHT: "1"
       WORKSTREAM_MCP_ALLOWED_HOSTS: 127.0.0.1:8080,localhost:8080
     healthcheck:
-      test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/v1/health', timeout=2); r=urllib.request.Request('http://127.0.0.1:8080/mcp', data=b'{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{}}', headers={'Content-Type':'application/json','Accept':'application/json, text/event-stream'}); import json; assert len(json.load(urllib.request.urlopen(r,timeout=3))['result']['tools']) == 131"]
+      test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/v1/health', timeout=2); r=urllib.request.Request('http://127.0.0.1:8080/mcp', data=b'{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{}}', headers={'Content-Type':'application/json','Accept':'application/json, text/event-stream'}); import json; assert len(json.load(urllib.request.urlopen(r,timeout=3))['result']['tools']) == 132"]
       interval: 10s
       timeout: 6s
       retries: 3
diff --git a/mcp_server/README.md b/mcp_server/README.md
index e16f7722b..b911763a2 100644
--- a/mcp_server/README.md
+++ b/mcp_server/README.md
@@ -68,7 +68,7 @@ An independently installed adapter exposing 132 tools under the caller's authori
   projections plus deliberate operator retry, reconciliation and registration.
 - Nine operator-artifact tools cover readiness, bindings, replicas, receipts,
   verification/recovery, admission usage and audit events.
-- Sixteen task-execution tools cover bounded submission ZIPs, contributor and
+- Seventeen task-execution tools cover bounded submission ZIPs, contributor and
   manager task context, screen/release/claim, guide-document reads and
   submission acceptance and immutable history.
 - Twenty-three project, task-management, import, audit, service-actor and model
diff --git a/scripts/test_hosted_mcp_container.py b/scripts/test_hosted_mcp_container.py
index 6d96268ad..3cd7e0bd2 100644
--- a/scripts/test_hosted_mcp_container.py
+++ b/scripts/test_hosted_mcp_container.py
@@ -140,7 +140,8 @@ def rpc(method: str, params: dict, bearer: str | None = None) -> dict:
 
         def prove_calls(generation: str) -> None:
             tools = rpc("tools/list", {})["tools"]
-            assert len(tools) == len({tool["name"] for tool in tools}) == 131
+            assert len(tools) == len({tool["name"] for tool in tools}) == 132
+            assert "workstream_submission_operation_get" in {tool["name"] for tool in tools}
             params = {"name": "workstream_profile_get", "arguments": {}}
             for caller in ("alice", "bob"):
                 result = rpc("tools/call", params, "fixture-" + caller)
@@ -181,7 +182,7 @@ def prove_calls(generation: str) -> None:
             assert current_api != original_api and current_mcp != original_mcp
             prove_calls("replacement")
             print(json.dumps({"proof": "hosted MCP fixture transport", "image_id": image_id,
-                              "tools": 131, "restart": "passed", "replacement": "passed",
+                              "tools": 132, "restart": "passed", "replacement": "passed",
                               "stale_namespace_counterexample": "passed"}))
         finally:
             compose("down", "--volumes", "--remove-orphans", "--timeout", "10", timeout=45)

From fae1d4dce8924f32dd97984d48f0112b476c173a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 16:55:32 +0100
Subject: [PATCH 162/513] test(cli): exercise signed raw ZIP submission and
 durable finalization

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  58 ++
 .../integration/test_submission_public_api.py | 529 ++++++++----------
 2 files changed, 283 insertions(+), 304 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 7111b91af..b146169cd 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5150,3 +5150,61 @@ healthcheck Python with substituted HTTP responses. Workflow counterprobes rejec
 missing, extra, duplicate and missing-progress-tool catalogues. Artifact:
 /tmp/submission-catalogue-repair-probe.log. This proves catalogue assertions, not
 hosted deployment. Commitrail validation and worktree whitespace checks pass.
+
+### Real CLI raw-ZIP journey migration
+
+The pushed client repair is closed by affected ARCH/SEC and DOCS/CI reviewers at
+4346f80e9. Current main is contained. The real CLI submission drill still calls
+removed preparation routes and fails inside old materialization authorization
+before exercising the CLI. Replace that drill with the signed admission fixture,
+real socket/raw-ZIP command, portable source-bound PRE and actual T5 finalizer.
+Allowed: cli/tests/integration/test_submission_public_api.py and its narrowly
+scoped support, additive ownership registration if needed, and this record.
+Preserve exact replay, changed-packet refusal, immutable bytes/one Submission and
+POST dispatch, history/detail/findings/own-work reads, same-project/foreign-project
+concealment, suspension and grant-revocation checks. Replace obsolete preparation
+reads with operation-ID/key progress and unknown-operation refusal. Do not restore
+legacy constructors, mutate production authorization, narrow CI or claim native
+runtime/distributed scheduling. Approved-policy/task fixture setup is not public
+setup proof. Risk is integration/proof fidelity. Verify built CLI against signed
+HTTP/PostgreSQL and real Local storage; review QA/test-delta and ARCH/SEC with
+explicit before/after behavior mapping. Human review focus is retained authority
+and exact source custody. Shared legacy materialization fixtures remain a separate
+consumer migration, not fixed by this drill.
+
+Worktree drill evidence: initial collection needed explicit pytest-asyncio wrappers
+for imported backend fixtures, matching adjacent CLI proofs. The historical GET
+preparation routes remain intentional; only the obsolete POST is asserted absent.
+The v3/v4 runs now reach accepted raw-ZIP replay, pending progress, production
+OUTBOX finalization, finalized history/own-work reads, one-PRE custody, foreign
+concealment and suspended-actor denials. They fail when the reactivated actor's
+submitter grant is revoked: progress still succeeds while submit/history/findings
+fail. v4 reports stored actor active/grant revoked. Retain this regression;
+no authority relaxation or production change has been made. Investigate the exact
+read audit/selected grant before repairing. Logs: /tmp/submission-cli-source-journey-v3.log
+and /tmp/submission-cli-source-journey-v4.log. Structural validation, Ruff,
+Commitrail and whitespace pass; these are not a passing journey result.
+
+Diagnosis supersedes the suspected authorization defect: v5 audit shows the
+revoked submitter decision denied, followed by a valid management decision.
+seed_started_task_for_artifact_test grants the task actor a project manager role
+for screen/release and retains it. This is not a submitter-only fixture. Revoke
+that setup-only management grant through signed admin API before the CLI journey,
+assert no active management grants remain, then keep the original contributor
+revocation refusal. No production AUTH repair is justified. v6 is the explicit
+counterprobe asserting that the unadjusted fixture is submitter-only.
+
+The v6 counterprobe fails before upload with exactly one active project_manager
+grant on the task actor. The repaired drill revokes that grant via the signed
+admin API, retains its row/audit history, and asserts zero active management grants
+before and after the journey. Temporary verbose audit diagnostics are removed.
+The v7 run is the first execution of that repaired contributor-only setup.
+
+Repaired contributor-only journey passes1 in71.96s, exit0, migrations0081 and
+isolated database/role cleanup complete (/tmp/submission-cli-source-journey-v7.log/json).
+This is worktree evidence based on4346f80e9; only this record changes after that
+execution. The full assertion path includes accepted replay before/after T5,
+changed-packet409, both progress selectors, zero-before/one-after Submission,
+retained raw digest/size, history/findings/own-work, same/foreign project404 and
+suspension/revocation404. Production OUTBOX handler performs T5; actual broker,
+POST execution and native/provider qualification are not claimed by this drill.
diff --git a/cli/tests/integration/test_submission_public_api.py b/cli/tests/integration/test_submission_public_api.py
index 0e9a30c29..f7197197a 100644
--- a/cli/tests/integration/test_submission_public_api.py
+++ b/cli/tests/integration/test_submission_public_api.py
@@ -1,9 +1,7 @@
-"""Built CLI -> real socket/API -> PostgreSQL and local ART custody.
+"""Built CLI -> signed HTTP -> raw source custody and OUTBOX finalization.
 
-Fixtures arrange approved policy, a started assignment and development identity.
-The CLI creates the tested preparation and Submission. The actual independent ART
-verifier is invoked directly; distributed worker scheduling and full public setup
-are #552's separate proof, not claims of this test.
+Policy/task setup is arranged; portable PRE does not qualify native Smol, and
+direct delivery invocation does not qualify broker scheduling or public setup.
 """
 
 import asyncio
@@ -17,6 +15,7 @@
 from uuid import uuid4
 
 import pytest
+import pytest_asyncio
 from sqlalchemy import func, select
 import uvicorn
 
@@ -26,19 +25,35 @@
     clean_postgres_database as clean_postgres_database,
     postgres_database_url as postgres_database_url,
     isolated_database_env as isolated_database_env,
+    pagination_cursor_hmac_secret as pagination_cursor_hmac_secret,
 )
-from tests.tasks.test_submission_lineage import _prepared_packet  # noqa: E402
-from tests.tasks.test_public_submission_intake import _client  # noqa: E402
-from tests.tasks.submission_lineage_support import _verify_put_attempt  # noqa: E402
+from tests.artifacts.test_submission_intake_admission import (  # noqa: E402
+    admission_intake as _admission_intake, admin_access as _admin_access,
+    signed_access as _signed_access, rsa_signing_material as rsa_signing_material,
+    auth_database_env as auth_database_env, clear_settings_cache as clear_settings_cache,
+)
+from tests.artifacts.test_submission_pre_source import _source_runtime  # noqa: E402
+from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation  # noqa: E402
+from tests.checkers.execution.support import provision_post_submit_service  # noqa: E402
+from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer  # noqa: E402
+from tests.test_trusted_intake import _archive  # noqa: E402
+from tests.test_artifact_admission import _settings  # noqa: E402
+from app.adapters import artifacts as composition  # noqa: E402
+from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter  # noqa: E402
+from app.modules.actors.api import ServiceIdentity  # noqa: E402
+from app.modules.artifacts.intake.models import SubmissionIntakeOperation  # noqa: E402
+from tests.authorization.admin_access.support import AdminAccess, create_project  # noqa: E402
+from tests.authorization.task_authority.test_postgresql import grant, project_manager  # noqa: E402
 from app.modules.actors.models import ActorProfile  # noqa: E402
 from app.modules.tasks.models import Submission  # noqa: E402
 from app.modules.checkers.models import CheckerRun  # noqa: E402
 from app.modules.artifacts.models import SubmissionBundleAdmission  # noqa: E402
-from app.modules.authorization.models import ProjectRoleGrant  # noqa: E402
-from tests.test_artifact_admission import _context, _seed_human_actor  # noqa: E402
-from tests.submission_preparation_auth_helpers import install_submitter_grant  # noqa: E402
-from tests.project_create_fixtures import seed_historical_project  # noqa: E402
-from app.core.identifiers import new_record_id  # noqa: E402
+from app.modules.authorization.models import AdminRoleGrant, ProjectRoleGrant  # noqa: E402
+
+
+admission_intake = pytest_asyncio.fixture(_admission_intake.__wrapped__)
+admin_access = pytest_asyncio.fixture(_admin_access.__wrapped__)
+signed_access = pytest_asyncio.fixture(_signed_access.__wrapped__)
 
 
 @asynccontextmanager
@@ -64,296 +79,202 @@ async def socket_api(app):
             listener.close()
 
 
-@pytest.mark.asyncio
-async def test_cli_public_preparation_creation_replay_history_and_suspension(
-    isolated_database_env,
-    tmp_path,
-    monkeypatch,
-    cli,
-):
-    async with _prepared_packet(isolated_database_env, tmp_path) as h:
-        archive = tmp_path / "work.zip"
-        archive.write_bytes(h.archive_bytes)
-        key = str(uuid4())
-        packet = (
-            "--assignment",
-            str(h.assignment_id),
-            "--summary",
-            h.preparation_request.summary,
-            "--attestation",
-            h.preparation_request.contributor_attestation,
-        )
-        prepare = (
-            "task",
-            "prepare",
-            str(h.task_id),
-            *packet,
-            "--file",
-            str(archive),
-            "--idempotency-key",
-            key,
-        )
-        async with _client(h, monkeypatch, isolated_database_env) as direct:
-            async with socket_api(direct._transport.app) as origin:
+async def _remove_setup_management(f):
+    # ART's task seed needs management to screen/release, but this drill must
+    # exercise only contributor authority. Retain and revoke the setup grant.
+    async with f.factory() as session:
+        [role] = list(await session.scalars(select(AdminRoleGrant).where(
+            AdminRoleGrant.target_actor_profile_id == str(f.actor.actor_profile_id),
+            AdminRoleGrant.status == "active")))
+        assert role.role == "project_manager" and role.scope_project_id == str(f.project)
+        role_id = str(role.id)
+    response = await f.access.signed.revoke(f.access.admin, role_id)
+    assert response.status_code == 200, response.text
+    await _assert_submitter_only(f)
+
 
-                async def call(*args, denied=None):
-                    # PRE runs real bounded intake work before responding; the
-                    # default 20s fake-peer budget is not its processing contract.
-                    result = await asyncio.to_thread(
-                        cli,
-                        origin,
-                        "public-intake-token",
-                        "-o",
-                        "json",
-                        *args,
-                        process_timeout=90 if args[:2] == ("task", "prepare") else 20,
-                    )
-                    if denied is not None:
-                        assert result.returncode == 1 and result.stdout == "", (
-                            result.stderr
-                        )
-                        assert json.loads(result.stderr)["error"]["status"] == denied
-                        return None
-                    assert result.returncode == 0 and result.stderr == "", result.stderr
-                    return json.loads(result.stdout)
+async def _assert_submitter_only(f):
+    async with f.factory() as session:
+        assert await session.scalar(select(func.count()).select_from(AdminRoleGrant).where(
+            AdminRoleGrant.target_actor_profile_id == str(f.actor.actor_profile_id),
+            AdminRoleGrant.status == "active")) == 0
 
-                paths = (await direct.get("/openapi.json")).json()["paths"]
-                assert (
-                    "post"
-                    in paths["/api/v1/tasks/{task_id}/submission-bundle-preparations"]
-                )
-                assert "post" in paths["/api/v1/tasks/{task_id}/submissions"]
-                prepared = await call(*prepare)
-                assert (
-                    prepared["submission_bundle_preparation_status"]
-                    == "stored_pending_verification"
-                )
-                assert prepared["admission_id"] is None
-                # The admitted attempt's intake feedback is returned, not dropped.
-                assert prepared["pre_submission_results"]
-                assert all(
-                    item["status"] in {"passed", "warning"}
-                    for item in prepared["pre_submission_results"]
-                )
-                async with h.factory() as session:
-                    assert (
-                        await session.scalar(
-                            select(func.count()).select_from(Submission)
-                        )
-                        == 0
-                    )
-                admission_id = await _verify_put_attempt(
-                    h.factory,
-                    h.store,
-                    h.namespace,
-                    h.settings,
-                    prepared["put_attempt_id"],
-                )
-                ready = await call(*prepare)
-                assert ready == prepared | {
-                    "submission_bundle_preparation_status": "ready",
-                    "admission_id": str(admission_id),
-                    "replayed": True,
-                }
-                submit = (
-                    "task",
-                    "submit",
-                    str(h.task_id),
-                    *packet,
-                    "--admission",
-                    str(admission_id),
-                )
-                receipt = await call(*submit)
-                assert receipt["admission_id"] == str(admission_id)
-                assert receipt["submission_version"] == 1
-                assert await call(*submit) == receipt
-                changed = list(submit)
-                changed[changed.index("--summary") + 1] += " changed"
-                await call(*changed, denied=404)
-                submission_id = receipt["submission_id"]
-                history = await call(
-                    "task", "submissions", str(h.task_id), "--limit", "1"
-                )
-                assert [v["id"] for v in history["items"]] == [submission_id]
-                detail = await call("submission", "show", submission_id)
-                assert detail == history["items"][0]
-                assert detail["summary"] == h.preparation_request.summary
-                findings = await call("submission", "findings", submission_id)
-                assert len(findings["items"]) == 1
-                run = findings["items"][0]
-                assert (
-                    run["submission_id"] == submission_id and run["status"] == "queued"
-                )
-                assert (
-                    await call(
-                        "submission", "findings", submission_id, "--run", run["id"]
-                    )
-                    == run
-                )
-                # The caller's own-work reads decode the same real records.
-                [assignment] = (await call("me", "assignments"))["items"]
-                assert assignment["task_id"] == str(h.task_id)
-                assert assignment["latest_submission"]["submission_id"] == submission_id
-                assert assignment["next_action"] == "awaiting_evaluation"
-                [attempt] = (await call("me", "submissions", "--task", str(h.task_id)))[
-                    "items"
-                ]
-                assert attempt["submission_id"] == submission_id
-                assert attempt["status"] == detail["status"]
-                summary = await call("me", "summary")
-                assert summary["assignments"] == {"active": 1, "closed": 0}
-                [project] = (await call("me", "projects"))["items"]
-                assert project["project_id"] == assignment["project_id"]
-                assert project["project_roles"] == ["submitter"]
-                preparations = (await call("task", "preparations", str(h.task_id)))[
-                    "items"
-                ]
-                [preparation] = [
-                    item for item in preparations if item["state"] == "submitted"
-                ]
-                assert preparation["submission_id"] == submission_id
-                one = await call(
-                    "task", "preparation", str(h.task_id), preparation["preparation_id"]
-                )
-                assert {k: v for k, v in one.items() if k != "findings"} == preparation
-                assert one["findings"] == prepared["pre_submission_results"]
-                await call(
-                    "task", "preparation", str(h.task_id), str(uuid4()), denied=404
-                )
-                await call("submission", "show", str(uuid4()), denied=404)
-                async with h.factory() as session:
-                    assert (
-                        await session.scalar(
-                            select(func.count()).select_from(Submission)
-                        )
-                        == 1
-                    )
-                    assert (
-                        await session.scalar(
-                            select(func.count()).select_from(CheckerRun)
-                        )
-                        == 1
-                    )
-                    admission = await session.get(
-                        SubmissionBundleAdmission, str(admission_id)
-                    )
-                    assert admission.status == "consumed"
-                    assert (
-                        admission.archive_sha256
-                        == "sha256:" + hashlib.sha256(h.archive_bytes).hexdigest()
-                    )
-                    assert admission.archive_byte_count == len(h.archive_bytes)
-                    assert admission.consumed_by_submission_id == submission_id
-                    stored_run = await session.get(CheckerRun, run["id"])
-                    assert (
-                        stored_run.evaluation_request_id
-                        == receipt["evaluation_request_id"]
-                    )
-                foreign_context = _context()
-                other_project_context = _context()
-                other_project = new_record_id()
-                async with h.factory.begin() as session:
-                    await _seed_human_actor(session, foreign_context)
-                    await _seed_human_actor(session, other_project_context)
-                    await seed_historical_project(
-                        session,
-                        project_id=str(other_project),
-                        name="Other CLI project",
-                        slug=f"cli-other-{other_project}",
-                    )
-                    await install_submitter_grant(
-                        await session.connection(),
-                        {
-                            "project": str(h.project_id),
-                            "actor": str(foreign_context.actor_profile_id),
-                        },
-                    )
-                    await install_submitter_grant(
-                        await session.connection(),
-                        {
-                            "project": str(other_project),
-                            "actor": str(other_project_context.actor_profile_id),
-                        },
-                    )
-                # A different authenticated actor with a real same-project
-                # Submitter grant still cannot reuse this assignment/history.
-                for actor in (foreign_context, other_project_context):
-                    with monkeypatch.context() as foreign_patch:
-                        async with _client(
-                            h,
-                            foreign_patch,
-                            isolated_database_env,
-                            subject=f"human-{actor.actor_profile_id}",
-                        ) as foreign:
-                            async with socket_api(
-                                foreign._transport.app
-                            ) as foreign_origin:
-                                for args in (
-                                    submit,
-                                    ("submission", "show", submission_id),
-                                    ("submission", "findings", submission_id),
-                                    ("task", "submissions", str(h.task_id)),
-                                ):
-                                    result = await asyncio.to_thread(
-                                        cli,
-                                        foreign_origin,
-                                        "public-intake-token",
-                                        "-o",
-                                        "json",
-                                        *args,
-                                    )
-                                    assert (
-                                        result.returncode == 1 and result.stdout == ""
-                                    ), result.stderr
-                                    assert (
-                                        json.loads(result.stderr)["error"]["status"]
-                                        == 404
-                                    )
-                async with h.factory.begin() as session:
-                    profile = await session.get(
-                        ActorProfile, str(h.context.actor_profile_id)
-                    )
-                    profile.status = "suspended"
-                    profile.suspended_by = "cli-test"
-                    profile.suspended_at = datetime.now(UTC)
-                    profile.suspension_reason = "fresh authority regression"
-                await call(*submit, denied=404)
-                await call("submission", "show", submission_id, denied=404)
-                await call("submission", "findings", submission_id, denied=404)
-                await call("task", "submissions", str(h.task_id), denied=404)
-                # Arrange a different invalidation independently: restore the
-                # actor and revoke its exact project grant, preserving provenance.
-                async with h.factory.begin() as session:
-                    profile = await session.get(
-                        ActorProfile, str(h.context.actor_profile_id)
-                    )
-                    profile.status = "active"
-                    profile.suspended_by = profile.suspended_at = (
-                        profile.suspension_reason
-                    ) = None
-                    profile.reactivated_by = "cli-test"
-                    profile.reactivated_at = datetime.now(UTC)
-                    profile.reactivation_reason = "Isolate revoked-grant proof"
-                    grant = (
-                        await session.scalars(
-                            select(ProjectRoleGrant).where(
-                                ProjectRoleGrant.actor_profile_id
-                                == str(h.context.actor_profile_id),
-                                ProjectRoleGrant.project_id == str(h.project_id),
-                                ProjectRoleGrant.role == "submitter",
-                            )
-                        )
-                    ).one()
-                    grant.status, grant.version = "revoked", 2
-                    grant.revoked_by_actor_profile_id = (
-                        grant.granted_by_actor_profile_id
-                    )
-                    grant.revoked_by_admin_role_grant_id = (
-                        grant.granted_by_admin_role_grant_id
-                    )
-                    grant.revoked_reason = "CLI fresh replay authority regression"
-                    grant.revoked_at = datetime.now(UTC)
-                await call(*submit, denied=404)
-                await call("submission", "show", submission_id, denied=404)
-                await call("submission", "findings", submission_id, denied=404)
-                await call("task", "submissions", str(h.task_id), denied=404)
+
+async def _configure(f, tmp_path, monkeypatch, payload):
+    runtime, errors = _source_runtime(payload, tmp_path, "completed")
+    calls, original = [], runtime.execute_pre
+    async def execute(lease, request):
+        calls.append(lease.reservation.attempt_id)
+        return await original(lease, request)
+    runtime.execute_pre = execute
+    monkeypatch.setattr(composition, "selected_pre_submit_checker_execution",
+                        lambda **kwargs: SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime))
+    await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_PRE_SUBMIT)
+    await _seed_materializer(f.factory)
+    app = f.access.signed.client._transport.app
+    storage = {k: v for k, v in _settings(tmp_path).model_dump().items() if k.startswith("artifact_")}
+    settings = app.state.settings.model_copy(update=storage | {"submission_execution_profile": {
+        "capacity": {"maximum_total_bytes": 4 * 1024 * 1024},
+        "runtime": _source_reservation().runtime_profile.model_dump(mode="json"),
+        "upload_total_seconds": 300.0, "upload_idle_seconds": 10.0,
+        "foreground_lease_seconds": 60.0, "heartbeat_seconds": 10.0,
+        "replay_total_seconds": 30.0, "part_bytes": 5 * 1024**2,
+    }})
+    monkeypatch.setattr(app.state, "settings", settings)
+    return app, settings, calls, errors
+
+
+async def _finalize(f, tmp_path, settings, operation_id):
+    from datetime import timedelta
+    from uuid import UUID
+    from app.adapters.auth import outbox_dispatch_authorization
+    from app.adapters.outbox import outbox_delivery
+    from app.modules.outbox.api import DeliveryOptions
+    from app.modules.outbox.registry import HandlerRegistry
+    from tests.artifact_store_helpers import initialize_local_store
+    for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER):
+        await provision_post_submit_service(f.factory, identity)
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    try:
+        handler = composition.submission_finalization_handler(
+            sessions=f.factory, settings=settings, store=store, lease_duration=timedelta(seconds=30))
+        event_type = "SubmissionFinalizationRequested"
+        delivery = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
+            registry=HandlerRegistry([(event_type, 1, handler)], replay_safe=frozenset({(event_type, 1)})),
+            options=DeliveryOptions(lease_seconds=30, handler_timeout_seconds=25))
+        async with f.factory() as session:
+            row = await session.get(SubmissionIntakeOperation, operation_id)
+            event_id = UUID(row.finalization_event_id)
+        assert await delivery.deliver(event_id, f.project, "cli-finalizer") is not None
+    finally:
+        store.close()
+
+
+async def _inspect(call, f, receipt, payload):
+    progress = await call("task", "submission-operation", str(f.task), "--operation-id", receipt["operation_id"])
+    submission_id = progress["submission_id"]
+    assert progress["operation_state"] == "finalized"
+    assert progress["processing_stage"] == "evaluation_pending"
+    assert progress["submission_version"] == 1
+    history = await call("task", "submissions", str(f.task), "--limit", "1")
+    assert [v["id"] for v in history["items"]] == [submission_id]
+    detail = await call("submission", "show", submission_id)
+    assert detail == history["items"][0]
+    assert detail["summary"] == "Completed the required project work and included evidence."
+    [run] = (await call("submission", "findings", submission_id))["items"]
+    assert run["submission_id"] == submission_id and run["status"] == "queued"
+    assert await call("submission", "findings", submission_id, "--run", run["id"]) == run
+    [assignment] = (await call("me", "assignments"))["items"]
+    assert assignment["task_id"] == str(f.task)
+    assert assignment["latest_submission"]["submission_id"] == submission_id
+    assert assignment["next_action"] == "awaiting_evaluation"
+    [attempt] = (await call("me", "submissions", "--task", str(f.task)))["items"]
+    assert attempt["submission_id"] == submission_id and attempt["status"] == detail["status"]
+    assert (await call("me", "summary"))["assignments"] == {"active": 1, "closed": 0}
+    [project] = (await call("me", "projects"))["items"]
+    assert project["project_id"] == assignment["project_id"]
+    assert project["project_roles"] == ["submitter"]
+    await call("submission", "show", str(uuid4()), denied=404)
+    await call("task", "submission-operation", str(f.task), "--operation-id", str(uuid4()), denied=404)
+    async with f.factory() as session:
+        for model in (Submission, CheckerRun):
+            assert await session.scalar(select(func.count()).select_from(model).where(model.task_id == str(f.task))) == 1
+        row = await session.get(SubmissionIntakeOperation, receipt["operation_id"])
+        admission = await session.scalar(select(SubmissionBundleAdmission).where(
+            SubmissionBundleAdmission.source_operation_id == row.id))
+        assert admission.status == "consumed"
+        assert admission.archive_sha256 == "sha256:" + hashlib.sha256(payload).hexdigest()
+        assert admission.archive_byte_count == len(payload)
+        assert admission.consumed_by_submission_id == submission_id
+        assert (await session.get(CheckerRun, run["id"])).evaluation_request_id == progress["evaluation_request_id"]
+    return submission_id
+
+
+async def _conceal_foreign(call, f, commands):
+    same = await f.access.signed.actor("cli-same-project")
+    other = await f.access.signed.actor("cli-other-project")
+    same_access = AdminAccess(f.access.signed, f.access.admin, same, f.access.bootstrap_grant_id)
+    await grant(same_access, f.manager, f.project)
+    other_project = await create_project("cli-other-project")
+    other_access = AdminAccess(f.access.signed, f.access.admin, other, f.access.bootstrap_grant_id)
+    other_manager = await project_manager(other_access, other_project)
+    await grant(other_access, other_manager, other_project)
+    for actor in (same, other):
+        for args in commands:
+            await call(*args, token=actor.token, denied=404)
+
+
+async def _invalidate(call, f, commands):
+    async with f.factory.begin() as session:
+        profile = await session.get(ActorProfile, str(f.actor.actor_profile_id))
+        profile.status, profile.suspended_by = "suspended", "cli-test"
+        profile.suspended_at, profile.suspension_reason = datetime.now(UTC), "fresh authority regression"
+    for state in ("suspended", "revoked"):
+        if state == "revoked":
+            async with f.factory.begin() as session:
+                profile = await session.get(ActorProfile, str(f.actor.actor_profile_id))
+                profile.status = "active"
+                profile.suspended_by = profile.suspended_at = profile.suspension_reason = None
+                profile.reactivated_by, profile.reactivated_at = "cli-test", datetime.now(UTC)
+                profile.reactivation_reason = "Isolate revoked-grant proof"
+                role = await session.get(ProjectRoleGrant, f.grant_id)
+                role.status, role.version = "revoked", 2
+                role.revoked_by_actor_profile_id = role.granted_by_actor_profile_id
+                role.revoked_by_admin_role_grant_id = role.granted_by_admin_role_grant_id
+                role.revoked_reason, role.revoked_at = "CLI fresh replay authority regression", datetime.now(UTC)
+        for args in commands:
+            await call(*args, denied=404)
+
+
+@pytest.mark.asyncio
+async def test_cli_public_submission_progress_replay_history_and_suspension(
+    admission_intake, tmp_path, monkeypatch, cli,
+):
+    f, key, payload = admission_intake, str(uuid4()), _archive()
+    await _remove_setup_management(f)
+    app, settings, calls, errors = await _configure(f, tmp_path, monkeypatch, payload)
+    await _assert_submitter_only(f)
+    archive = tmp_path / "work.zip"
+    archive.write_bytes(payload)
+    submit = ("task", "submit", str(f.task), "--assignment", str(f.assignment),
+              "--file", str(archive), "--idempotency-key", key,
+              "--summary", "Completed the required project work and included evidence.")
+    async with socket_api(app) as origin:
+        async def call(*args, denied=None, token=None):
+            result = await asyncio.to_thread(cli, origin, token or f.access.target.token,
+                "-o", "json", *args, process_timeout=90 if args[:2] == ("task", "submit") else 20)
+            if denied is not None:
+                assert result.returncode == 1 and result.stdout == "", result.stderr
+                assert json.loads(result.stderr)["error"]["status"] == denied, result.stderr
+                return None
+            assert result.returncode == 0 and result.stderr == "", result.stderr
+            return json.loads(result.stdout)
+        paths = (await f.access.signed.client.get("/openapi.json")).json()["paths"]
+        assert "post" not in paths.get("/api/v1/tasks/{task_id}/submission-bundle-preparations", {})
+        assert "post" in paths["/api/v1/tasks/{task_id}/submissions"]
+        receipt = await call(*submit)
+        assert receipt["status"] == "accepted" and receipt["replayed"] is False
+        assert receipt["pre_submission_results"]
+        assert all(item["status"] in {"passed", "warning"} for item in receipt["pre_submission_results"])
+        assert await call(*submit) == dict(receipt, replayed=True)
+        changed = list(submit)
+        changed[changed.index("--summary") + 1] += " changed"
+        await call(*changed, denied=409)
+        by_key = await call("task", "submission-operation", str(f.task), "--idempotency-key", key)
+        by_id = await call("task", "submission-operation", str(f.task), "--operation-id", receipt["operation_id"])
+        assert by_key == by_id
+        assert by_id["processing_stage"] == "finalization_pending"
+        assert by_id["submission_id"] is by_id["evaluation_request_id"] is None
+        assert by_id["pre_submission_results"] == receipt["pre_submission_results"]
+        async with f.factory() as session:
+            assert await session.scalar(select(func.count()).select_from(Submission).where(Submission.task_id == str(f.task))) == 0
+        await _finalize(f, tmp_path, settings, receipt["operation_id"])
+        submission_id = await _inspect(call, f, receipt, payload)
+        assert await call(*submit) == dict(receipt, replayed=True)
+        assert len(calls) == 1 and not errors, errors
+        commands = (submit, ("submission", "show", submission_id),
+                    ("submission", "findings", submission_id), ("task", "submissions", str(f.task)),
+                    ("task", "submission-operation", str(f.task), "--operation-id", receipt["operation_id"]))
+        await _conceal_foreign(call, f, commands)
+        await _assert_submitter_only(f)
+        await _invalidate(call, f, commands)

From 8989e3b5c905c0ed86dd08b1f8c451dbd8558b93 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 17:00:05 +0100
Subject: [PATCH 163/513] fix(tests): remove unused import after submission
 route migration

---
 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++++
 backend/tests/test_authorization.py                       | 2 +-
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index b146169cd..8ace195d7 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5208,3 +5208,11 @@ changed-packet409, both progress selectors, zero-before/one-after Submission,
 retained raw digest/size, history/findings/own-work, same/foreign project404 and
 suspension/revocation404. Production OUTBOX handler performs T5; actual broker,
 POST execution and native/provider qualification are not claimed by this drill.
+
+ARCH/SEC and QA/test-delta close the fae1d4dce drill with no required repairs;
+QA independently confirms the zero/one manager guard and unchanged socket helper.
+Both preserve the worktree evidence provenance and broader goal limits.
+CI4346 preflight now passes structure but finds one unused dataclasses.asdict
+import in backend/tests/test_authorization.py, left by removed-route migration.
+Extend the repair scope to removing only that unused import; no test behavior or
+production code changes. Verify the full backend Ruff gate before the same-PR push.
diff --git a/backend/tests/test_authorization.py b/backend/tests/test_authorization.py
index 0731008a5..af22c8c80 100644
--- a/backend/tests/test_authorization.py
+++ b/backend/tests/test_authorization.py
@@ -38,7 +38,7 @@
 import copy
 from collections import UserDict
 from collections.abc import Iterator, Mapping
-from dataclasses import asdict, replace
+from dataclasses import replace
 from datetime import UTC, datetime
 import inspect
 import hashlib

From b67d02a1226ba807d46e8891fbae47aea1809a4d Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 17:14:13 +0100
Subject: [PATCH 164/513] refactor(checkers): remove obsolete prepared PRE
 material grants

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  54 +++
 external_checkers/README.md                   |   9 +-
 .../workstream-checker-service/src/main.rs    | 333 +++++-------------
 .../src/smol/pre/transport/tests.rs           |   3 +-
 4 files changed, 143 insertions(+), 256 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 8ace195d7..a373d945d 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5216,3 +5216,57 @@ CI4346 preflight now passes structure but finds one unused dataclasses.asdict
 import in backend/tests/test_authorization.py, left by removed-route migration.
 Extend the repair scope to removing only that unused import; no test behavior or
 production code changes. Verify the full backend Ruff gate before the same-PR push.
+
+### Remove superseded runtime prepared-PRE grants
+
+The source-bound execute_pre path is separate from execute/POST grant handling.
+The service still parses the removed prepared_generation PRE material grant, and
+five runtime tests panic when their helper looks for prepared_generation_id in
+the current source request. This is an affected obsolete implementation, not a
+reason to add legacy fields back to the source contract. Next bounded scope is
+external_checkers/workstream-checker-service/src/main.rs and this record only.
+Remove PRE_GRANT_PROTOCOL/GrantManifest/GrantIdentity, old matching and its unused
+semantic wrapper. Keep shared POST semantic hashing and all POST retained/source
+custody validation. General wire/output/uncertain-cleanup tests use a valid parsed
+POST request and exact published POST grant. Keep explicit current PRE model-grant
+refusal without manufacturing prepared material. Replace old positive prepared-PRE
+lineage test with binding-valid old protocol refusal at verify_grant. Prohibited:
+new compatibility path, relaxed request/grant/custody checks, test skips or reduced
+execution/cleanup assertions. Risk: runtime architecture/security and proof fidelity.
+Verify pinned Rust1.84 service tests and workspace tests; ARCH/SEC and QA/test-delta
+review before samePR push. This closes obsolete runtime acceptance and its failing
+consumer proofs; shared backend fixtures, native deployment and full goal remain.
+
+Extend scope to external_checkers/README.md's affected grant paragraph: POST owns
+verified aggregate workspace grants; PRE owns the sealed-source single session.
+Remove the stale statement that PRE retains a distinct prepared material grant.
+Initial service run:132passed/3failed. Two fixture repairs preserve assertions:
+match the POST fixture's image digest in test cache and release the POST materials
+directory for teardown. An unchanged Smol launch-bound test also hit its500ms
+execution deadline; its unchanged second-run case passes, not a root-cause fix.
+No deadline or production execution bound has been relaxed.
+
+Service v2 passes135 unit cases and11/26/16 integration cases. Full workspace
+then passes guest/SDK suites but fails one unchanged PRE transport permitted-log
+case (134servicepass/1fail). Its is_ok assertion hides the actual error. Extend
+scope solely to a diagnostic assertion in smol/pre/transport/tests.rs; retain the
+same is_ok predicate and every deadline/bound. Run that exact case to expose the
+cause before claiming workspace success. Log:/tmp/submission-runtime-workspace.log.
+
+The diagnostic log-limit case passes once under cargo and three direct repeats
+with the same bounds; no hidden error reproduced. Artifacts:
+/tmp/submission-runtime-log-diagnostic.log and /tmp/submission-runtime-log-repeats.log.
+Do not infer that the earlier transient transport failures are fixed. Keep the
+improved error assertion and replay the workspace with it; no production timing,
+log limit, cleanup assertion or test selection has changed.
+
+Workspace replay with diagnostic assertion passes the permitted-log case but
+fails the unchanged launch-bound positive with deadline_exceeded (134service
+pass/1fail); /tmp/submission-runtime-workspace-v2.log. Guest/SDK suites12/40/9pass.
+Do not call the workspace green. No further repeat-until-pass attempts: keep
+these timing failures open for dedicated transport diagnosis/native qualification.
+The grant-cutover service v2 proof passed135unit+11/26/16integration before the
+error-only diagnostic edit, with no grant implementation changes afterward.
+Rustfmt, Commitrail, Markdown link and whitespace checks pass. Freeze this
+bounded removal for ARCH/SEC, QA/test-delta and affected documentation review;
+full goal still requires the failed gate and all other lifecycle work to close.
diff --git a/external_checkers/README.md b/external_checkers/README.md
index 15285ffa2..c8062d620 100644
--- a/external_checkers/README.md
+++ b/external_checkers/README.md
@@ -37,8 +37,8 @@ for separate runner provisioning and Operator registration; it changes no policy
 
 - Workstream owns guide compilation, authorization, policy approvals, registry
   identity, immutable submission custody and lifecycle decisions.
-- ART provides request-bound verified material. The service independently checks
-  its grant and manifest before mounting the material read-only.
+- For POST, ART provides request-bound verified material. The service independently
+  checks its grant and manifest before mounting the material read-only.
 - The service executes the selected cached digest-pinned image under the
   configured sandbox, limits, deadline and output budget, then validates its
   normalized result and settles owned resources.
@@ -54,8 +54,9 @@ may additionally expose the exact prior attempt at `/work/context/predecessor`
 and bounded prior findings in `input.evaluation_context`. Neither a global
 Submission version nor a project image request authorizes historical access.
 Initial attempts carry explicit null prior context, including after another
-contributor releases a task. PRE keeps its distinct pre-admission grant; there
-is no POST fallback to the PRE protocol. See the
+contributor releases a task. PRE streams the sealed raw source into one session
+for default intake and the selected PRE checker; prepared-PRE workspace grants
+are rejected. See the
 [POST contract](../docs/architecture_checker_framework.md#post-submit-contract)
 for selection, evidence, quota and replay rules.
 
diff --git a/external_checkers/workstream-checker-service/src/main.rs b/external_checkers/workstream-checker-service/src/main.rs
index 8030a0f23..dd83905d1 100644
--- a/external_checkers/workstream-checker-service/src/main.rs
+++ b/external_checkers/workstream-checker-service/src/main.rs
@@ -44,7 +44,6 @@ use workstream_checker_sdk::{
 };
 
 const PROTOCOL: &str = "external_checker_service.v1";
-const PRE_GRANT_PROTOCOL: &str = "workstream.external_checker_material_grant.v1";
 const POST_GRANT_PROTOCOL: &str = "workstream.external_checker_material_grant.v2";
 const CURRENT_ARCHIVE_ROLE: &str = "submission_archive";
 const PREDECESSOR_ARCHIVE_ROLE: &str = "predecessor_submission_archive";
@@ -168,18 +167,6 @@ struct GrantReference {
     binding_digest: String,
 }
 
-#[derive(Debug, Clone, Deserialize, Serialize)]
-struct GrantManifest {
-    protocol_version: String,
-    grant_id: String,
-    request_digest: String,
-    #[serde(flatten)]
-    identity: GrantIdentity,
-    directories: Vec,
-    files: Vec,
-    binding_digest: String,
-}
-
 struct VerifiedGrant {
     binding_digest: String,
     input: PathBuf,
@@ -193,20 +180,6 @@ struct ExecutedChecker {
     value: Value,
 }
 
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(tag = "phase", deny_unknown_fields)]
-enum GrantIdentity {
-    #[serde(rename = "pre_submit")]
-    PreSubmit {
-        prepared_generation_id: String,
-        attempt_id: String,
-        attempt_request_digest: String,
-        archive_sha256: String,
-        archive_byte_count: u64,
-        semantic_manifest_sha256: String,
-    },
-}
-
 #[derive(Debug, Clone, Deserialize, Serialize)]
 #[serde(deny_unknown_fields)]
 struct PostGrantManifest {
@@ -1492,29 +1465,6 @@ fn verify_grant(
         return Err("grant binding differs".into());
     }
     match value.get("protocol_version").and_then(Value::as_str) {
-        Some(PRE_GRANT_PROTOCOL) => {
-            let manifest: GrantManifest =
-                serde_json::from_value(value).map_err(|_| "grant manifest invalid")?;
-            if manifest.grant_id != reference.grant_id
-                || manifest.request_digest != request.request_digest
-                || manifest.binding_digest != reference.binding_digest
-                || !grant_matches_request(&manifest, request)
-            {
-                return Err("grant binding differs".into());
-            }
-            let input = grant_root.join("workspace");
-            let observed = inspect_workspace(&input, config.sandbox_uid, config.sandbox_gid)?;
-            if observed.files != manifest.files || observed.directories != manifest.directories {
-                return Err("grant material differs".into());
-            }
-            Ok(VerifiedGrant {
-                binding_digest: reference.binding_digest.clone(),
-                input,
-                input_inventory: observed,
-                predecessor: None,
-                predecessor_inventory: None,
-            })
-        }
         Some(POST_GRANT_PROTOCOL) => {
             let manifest: PostGrantManifest =
                 serde_json::from_value(value).map_err(|_| "grant manifest invalid")?;
@@ -1524,62 +1474,6 @@ fn verify_grant(
     }
 }
 
-fn grant_matches_request(manifest: &GrantManifest, request: &ValidatedRequest) -> bool {
-    let Some(identity) = request.value.get("identity").and_then(Value::as_object) else {
-        return false;
-    };
-    let Some(materials) = request.value.get("materials").and_then(Value::as_array) else {
-        return false;
-    };
-    let Some(archive) = materials.iter().find_map(|item| {
-        let object = item.as_object()?;
-        (object.get("phase")?.as_str()? == request.phase
-            && object.get("role")?.as_str()? == "submission_archive")
-            .then_some(object)
-    }) else {
-        return false;
-    };
-    let semantic_manifest_sha256 = semantic_manifest_hash(manifest).ok();
-    match &manifest.identity {
-        GrantIdentity::PreSubmit {
-            prepared_generation_id,
-            attempt_id,
-            attempt_request_digest,
-            archive_sha256,
-            archive_byte_count,
-            semantic_manifest_sha256: expected_manifest,
-        } => {
-            request.phase == "pre_submit"
-                && identity
-                    .get("prepared_generation_id")
-                    .and_then(Value::as_str)
-                    == Some(prepared_generation_id)
-                && identity.get("attempt_id").and_then(Value::as_str) == Some(attempt_id)
-                && identity
-                    .get("attempt_request_digest")
-                    .and_then(Value::as_str)
-                    == Some(attempt_request_digest)
-                && archive
-                    .get("prepared_generation_id")
-                    .and_then(Value::as_str)
-                    == Some(prepared_generation_id)
-                && archive.get("attempt_id").and_then(Value::as_str) == Some(attempt_id)
-                && archive
-                    .get("attempt_request_digest")
-                    .and_then(Value::as_str)
-                    == Some(attempt_request_digest)
-                && archive.get("archive_sha256").and_then(Value::as_str) == Some(archive_sha256)
-                && archive.get("archive_byte_count").and_then(Value::as_u64)
-                    == Some(*archive_byte_count)
-                && archive
-                    .get("semantic_manifest_sha256")
-                    .and_then(Value::as_str)
-                    == Some(expected_manifest)
-                && semantic_manifest_sha256.as_deref() == Some(expected_manifest)
-        }
-    }
-}
-
 fn verify_post_grant(
     config: &ServiceConfig,
     request: &ValidatedRequest,
@@ -1828,10 +1722,6 @@ fn verify_materials_root<'a>(
     Ok(())
 }
 
-fn semantic_manifest_hash(manifest: &GrantManifest) -> Result {
-    semantic_manifest_hash_parts(&manifest.directories, &manifest.files)
-}
-
 fn semantic_manifest_hash_parts(
     directories: &[String],
     files: &[GrantFile],
@@ -3336,76 +3226,48 @@ mod tests {
         fs::remove_dir_all(root).unwrap();
     }
 
-    fn pre_submit_envelope_with_grant(config: &ServiceConfig) -> Value {
-        let grant_id = "extract_0123456789abcdef0123456789abcdef";
+    fn post_config() -> (PathBuf, ServiceConfig) {
+        let (root, mut config) = test_config();
+        let request = parse_request(include_bytes!("../../fixtures/post_request.json")).unwrap();
+        config.cache[0].platform_manifest_digest = request.image_digest;
+        (root, config)
+    }
+
+    fn post_submit_envelope_with_grant(config: &ServiceConfig) -> Value {
         let mut request: Value =
-            serde_json::from_slice(include_bytes!("../../fixtures/request.json")).unwrap();
-        let mut manifest = GrantManifest {
-            protocol_version: PRE_GRANT_PROTOCOL.into(),
-            grant_id: grant_id.into(),
-            request_digest: String::new(),
-            identity: GrantIdentity::PreSubmit {
-                prepared_generation_id: request["identity"]["prepared_generation_id"]
-                    .as_str()
-                    .unwrap()
-                    .into(),
-                attempt_id: request["identity"]["attempt_id"].as_str().unwrap().into(),
-                attempt_request_digest: request["identity"]["attempt_request_digest"]
-                    .as_str()
-                    .unwrap()
-                    .into(),
-                archive_sha256: request["materials"][0]["archive_sha256"]
-                    .as_str()
-                    .unwrap()
-                    .into(),
-                archive_byte_count: request["materials"][0]["archive_byte_count"]
-                    .as_u64()
-                    .unwrap(),
-                semantic_manifest_sha256: String::new(),
-            },
-            directories: Vec::new(),
-            files: Vec::new(),
-            binding_digest: format!("sha256:{}", "0".repeat(64)),
+            serde_json::from_slice(include_bytes!("../../fixtures/post_request.json")).unwrap();
+        request["materials"][0]["semantic_manifest_sha256"] =
+            Value::String(semantic_manifest_hash_parts(&[], &[]).unwrap());
+        let mut body = request.as_object().unwrap().clone();
+        body.remove("request_digest");
+        request["request_digest"] = Value::String(canonical_hash(&Value::Object(body)).unwrap());
+        let validated = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap();
+        let mut manifest = PostGrantManifest {
+            protocol_version: POST_GRANT_PROTOCOL.into(),
+            grant_id: "extract_0123456789abcdef0123456789abcdef".into(),
+            request_digest: validated.request_digest,
+            phase: "post_submit".into(),
+            identity: request["identity"].clone(),
+            evaluation_context_sha256: None,
+            materials: vec![PostGrantMaterial {
+                material: request["materials"][0].clone(),
+                directories: Vec::new(),
+                files: Vec::new(),
+            }],
+            visible_roles: vec![CURRENT_ARCHIVE_ROLE.into()],
+            binding_digest: String::new(),
         };
-        let semantic = semantic_manifest_hash(&manifest).unwrap();
-        let GrantIdentity::PreSubmit {
-            semantic_manifest_sha256,
-            ..
-        } = &mut manifest.identity;
-        *semantic_manifest_sha256 = semantic.clone();
-        request["materials"][0]["semantic_manifest_sha256"] = Value::String(semantic);
-        let mut request_body = request.as_object().unwrap().clone();
-        request_body.remove("request_digest");
-        let request_digest = canonical_hash(&Value::Object(request_body)).unwrap();
-        request["request_digest"] = Value::String(request_digest.clone());
-        manifest.request_digest = request_digest;
-
-        let mut manifest_value = serde_json::to_value(&manifest).unwrap();
-        manifest_value
-            .as_object_mut()
-            .unwrap()
-            .remove("binding_digest");
-        manifest.binding_digest = canonical_hash(&manifest_value).unwrap();
-
-        let grants = config.material_root.join("workspaces");
-        let grant_root = grants.join(grant_id);
-        let workspace = grant_root.join("workspace");
-        fs::create_dir(&grants).unwrap();
-        fs::create_dir(&grant_root).unwrap();
-        fs::create_dir(&workspace).unwrap();
-        fs::set_permissions(&grant_root, fs::Permissions::from_mode(0o700)).unwrap();
-        fs::set_permissions(&workspace, fs::Permissions::from_mode(0o500)).unwrap();
-        let manifest_path = grant_root.join(".external-checker-grant.json");
-        fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();
-        fs::set_permissions(&manifest_path, fs::Permissions::from_mode(0o400)).unwrap();
-
+        let mut body = serde_json::to_value(&manifest).unwrap();
+        body.as_object_mut().unwrap().remove("binding_digest");
+        manifest.binding_digest = canonical_hash(&body).unwrap();
+        let reference = publish_post_grant(config, &manifest);
         serde_json::json!({
             "protocol_version": PROTOCOL,
             "operation": "execute",
             "request": request,
             "grant": {
-                "grant_id": grant_id,
-                "binding_digest": manifest.binding_digest,
+                "grant_id": reference.grant_id,
+                "binding_digest": reference.binding_digest,
             },
             "model_grant": null,
         })
@@ -3976,8 +3838,8 @@ exit 2
 
     #[test]
     fn execute_wire_requires_an_exact_model_grant_member() {
-        let (root, config) = test_config();
-        let envelope = pre_submit_envelope_with_grant(&config);
+        let (root, config) = post_config();
+        let envelope = post_submit_envelope_with_grant(&config);
         assert!(serde_json::from_value::(envelope.clone()).is_ok());
 
         let mut missing = envelope.clone();
@@ -3993,17 +3855,19 @@ exit 2
         assert!(serde_json::from_value::(extended).is_err());
         let workspace = config
             .material_root
-            .join("workspaces/extract_0123456789abcdef0123456789abcdef/workspace");
+            .join("workspaces/extract_0123456789abcdef0123456789abcdef/materials");
         fs::set_permissions(workspace, fs::Permissions::from_mode(0o700)).unwrap();
         fs::remove_dir_all(root).unwrap();
     }
 
     #[test]
     fn model_grants_are_rejected_outside_the_bound_post_request() {
-        let (root, mut config) = test_config();
+        let (root, mut config) = post_config();
         config.model_proxy_socket = Some(PathBuf::from("/unused/private/proxy.sock"));
         config.model_relay_root = Some(PathBuf::from("/unused/private/relay"));
-        let mut envelope = pre_submit_envelope_with_grant(&config);
+        let mut envelope = post_submit_envelope_with_grant(&config);
+        envelope["request"] =
+            serde_json::from_slice(include_bytes!("../../fixtures/request.json")).unwrap();
         envelope["model_grant"] = serde_json::json!({
             "grant_id": format!("model_{}", "1".repeat(32)),
             "binding_digest": envelope["request"]["request_digest"],
@@ -4016,7 +3880,7 @@ exit 2
 
         let workspace = config
             .material_root
-            .join("workspaces/extract_0123456789abcdef0123456789abcdef/workspace");
+            .join("workspaces/extract_0123456789abcdef0123456789abcdef/materials");
         fs::set_permissions(workspace, fs::Permissions::from_mode(0o700)).unwrap();
         fs::remove_dir_all(root).unwrap();
     }
@@ -4085,8 +3949,8 @@ exit 2
 
     #[test]
     fn checker_output_cannot_request_another_execution() {
-        let (root, config) = test_config();
-        let envelope = pre_submit_envelope_with_grant(&config);
+        let (root, config) = post_config();
+        let envelope = post_submit_envelope_with_grant(&config);
         let request = parse_request(&serde_json::to_vec(&envelope["request"]).unwrap()).unwrap();
         let cache = &config.cache[0];
         fs::write(
@@ -4136,7 +4000,7 @@ exit 2
                 .material_root
                 .join("workspaces")
                 .join(envelope["grant"]["grant_id"].as_str().unwrap())
-                .join("workspace"),
+                .join("materials"),
             fs::Permissions::from_mode(0o700),
         )
         .unwrap();
@@ -4178,7 +4042,7 @@ exit 2
 
     #[test]
     fn unresolved_cleanup_closes_the_listener_loop_without_admitting_the_next_connection() {
-        let (root, config) = test_config();
+        let (root, config) = post_config();
         let retained = root.join("retained-container");
         let second_admitted = root.join("second-admitted");
         let cache = &config.cache[0];
@@ -4207,7 +4071,7 @@ exit 2
         )
         .unwrap();
         fs::set_permissions(&config.docker_binary, fs::Permissions::from_mode(0o700)).unwrap();
-        let execute = serde_json::to_vec(&pre_submit_envelope_with_grant(&config)).unwrap();
+        let execute = serde_json::to_vec(&post_submit_envelope_with_grant(&config)).unwrap();
         let health = serde_json::to_vec(
             &serde_json::json!({"protocol_version": PROTOCOL, "operation": "health"}),
         )
@@ -4242,7 +4106,7 @@ exit 2
         fs::remove_file(listener_path).unwrap();
         let workspace = config
             .material_root
-            .join("workspaces/extract_0123456789abcdef0123456789abcdef/workspace");
+            .join("workspaces/extract_0123456789abcdef0123456789abcdef/materials");
         fs::set_permissions(workspace, fs::Permissions::from_mode(0o700)).unwrap();
         fs::remove_dir_all(root).unwrap();
 
@@ -4669,70 +4533,40 @@ exit 2
     }
 
     #[test]
-    fn grant_lineage_matches_the_normalized_pre_submit_request() {
-        let mut request = parse_request(include_bytes!("../../fixtures/request.json")).unwrap();
-        let mut manifest = GrantManifest {
-            protocol_version: PRE_GRANT_PROTOCOL.into(),
-            grant_id: "extract_0123456789abcdef0123456789abcdef".into(),
-            request_digest: request.request_digest.clone(),
-            identity: GrantIdentity::PreSubmit {
-                prepared_generation_id: request.value["identity"]["prepared_generation_id"]
-                    .as_str()
-                    .unwrap()
-                    .into(),
-                attempt_id: request.value["identity"]["attempt_id"]
-                    .as_str()
-                    .unwrap()
-                    .into(),
-                attempt_request_digest: request.value["identity"]["attempt_request_digest"]
-                    .as_str()
-                    .unwrap()
-                    .into(),
-                archive_sha256: request.value["materials"][0]["archive_sha256"]
-                    .as_str()
-                    .unwrap()
-                    .into(),
-                archive_byte_count: request.value["materials"][0]["archive_byte_count"]
-                    .as_u64()
-                    .unwrap(),
-                semantic_manifest_sha256: String::new(),
-            },
-            directories: Vec::new(),
-            files: Vec::new(),
-            binding_digest: format!("sha256:{}", "9".repeat(64)),
+    fn prepared_pre_grants_are_refused_even_with_a_valid_binding() {
+        let (root, config) = test_config();
+        let request = parse_request(include_bytes!("../../fixtures/request.json")).unwrap();
+        let mut value = serde_json::json!({
+            "protocol_version": "workstream.external_checker_material_grant.v1",
+            "grant_id": "extract_0123456789abcdef0123456789abcdef",
+            "request_digest": request.request_digest,
+            "phase": "pre_submit",
+            "prepared_generation_id": "00000000-0000-4000-8000-000000000001",
+            "attempt_id": request.value["identity"]["attempt_id"],
+            "attempt_request_digest": request.value["identity"]["attempt_request_digest"],
+            "archive_sha256": format!("sha256:{}", "a".repeat(64)),
+            "archive_byte_count": 0,
+            "semantic_manifest_sha256": semantic_manifest_hash_parts(&[], &[]).unwrap(),
+            "directories": [], "files": []
+        });
+        let binding = canonical_hash(&value).unwrap();
+        value["binding_digest"] = Value::String(binding.clone());
+        let grant_id = value["grant_id"].as_str().unwrap().to_owned();
+        let grant_root = config.material_root.join("workspaces").join(&grant_id);
+        fs::create_dir_all(&grant_root).unwrap();
+        fs::set_permissions(&grant_root, fs::Permissions::from_mode(0o700)).unwrap();
+        let path = grant_root.join(".external-checker-grant.json");
+        fs::write(&path, serde_json::to_vec(&value).unwrap()).unwrap();
+        fs::set_permissions(path, fs::Permissions::from_mode(0o400)).unwrap();
+        let reference = GrantReference {
+            grant_id,
+            binding_digest: binding,
         };
-        let semantic = semantic_manifest_hash(&manifest).unwrap();
-        let GrantIdentity::PreSubmit {
-            semantic_manifest_sha256,
-            ..
-        } = &mut manifest.identity;
-        *semantic_manifest_sha256 = semantic;
-        request.value["materials"][0]["semantic_manifest_sha256"] =
-            Value::String(semantic_manifest_sha256.clone());
-        assert!(grant_matches_request(&manifest, &request));
-        for field in 0..6 {
-            let original = manifest.identity.clone();
-            let GrantIdentity::PreSubmit {
-                prepared_generation_id,
-                attempt_id,
-                attempt_request_digest,
-                archive_sha256,
-                archive_byte_count,
-                semantic_manifest_sha256,
-            } = &mut manifest.identity;
-            match field {
-                0 => *prepared_generation_id = "00000000-0000-4000-8000-000000000000".into(),
-                1 => *attempt_id = "00000000-0000-4000-8000-000000000000".into(),
-                2 => *attempt_request_digest = format!("sha256:{}", "8".repeat(64)),
-                3 => *archive_sha256 = format!("sha256:{}", "8".repeat(64)),
-                4 => *archive_byte_count += 1,
-                _ => *semantic_manifest_sha256 = format!("sha256:{}", "8".repeat(64)),
-            }
-            assert!(!grant_matches_request(&manifest, &request));
-            manifest.identity = original;
-        }
-        request.phase = "post_submit".into();
-        assert!(!grant_matches_request(&manifest, &request));
+        assert_eq!(
+            verify_grant(&config, &request, &reference).err(),
+            Some("grant protocol invalid".into())
+        );
+        fs::remove_dir_all(root).unwrap();
     }
 
     fn post_grant_fixture(
@@ -4982,9 +4816,6 @@ exit 2
         let mut extra = serde_json::to_value(&visible_manifest).unwrap();
         extra["unexpected"] = Value::Bool(true);
         assert!(serde_json::from_value::(extra).is_err());
-        let mut legacy_shape = serde_json::to_value(&visible_manifest).unwrap();
-        legacy_shape["protocol_version"] = Value::String(PRE_GRANT_PROTOCOL.into());
-        assert!(serde_json::from_value::(legacy_shape).is_err());
         let mut unknown_role = visible_manifest.materials[1].clone();
         unknown_role.material["role"] = Value::String("foreign_archive".into());
         assert!(validate_post_grant_material(&unknown_role).is_err());
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs
index 05215d29c..6daf612e8 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/transport/tests.rs
@@ -211,7 +211,8 @@ fn host_launch_passes_identical_clamped_limits_to_argv_and_job() {
 #[test]
 fn large_log_allowances_do_not_prevent_deadline_or_successful_completion() {
     assert_eq!(run_case("log_stall").unwrap_err(), "deadline_exceeded");
-    assert!(run_case("permitted_logs").is_ok());
+    let result = run_case("permitted_logs");
+    assert!(result.is_ok(), "permitted log exchange failed: {result:?}");
 }
 
 #[test]

From e0ed3892b50aa7e297147fcb3d2c27c1c643ee74 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 17:23:25 +0100
Subject: [PATCH 165/513] fix(ci): reconcile authorization test digest after
 import cleanup

---
 .ci/auth-boundaries/TEST_STRUCTURE_DEBT.json  |  2 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 23 +++++++++++++++++++
 2 files changed, 24 insertions(+), 1 deletion(-)

diff --git a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
index 117d503e8..47dac53f7 100644
--- a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
+++ b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json
@@ -86,7 +86,7 @@
     },
     {
       "capability": "oversized_authorization_structure",
-      "content_sha256": "83e22112a91dc19952da68aa220dd6a55d7834d2824cd3fd1fa8af20480c89be",
+      "content_sha256": "989df8969082c9f2005df3ee0d3e24c364f88566204d88fdc05574df00eee422",
       "end_line": 10709,
       "hard_limit": 1200,
       "kind": "test_file",
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index a373d945d..6b75a0e7b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5270,3 +5270,26 @@ error-only diagnostic edit, with no grant implementation changes afterward.
 Rustfmt, Commitrail, Markdown link and whitespace checks pass. Freeze this
 bounded removal for ARCH/SEC, QA/test-delta and affected documentation review;
 full goal still requires the failed gate and all other lifecycle work to close.
+
+All three bounded runtime reviews close on b67d02a12 without required repairs.
+QA independently runs the retired-protocol refusal test in an isolated copy and
+confirms a permissive-v1 mutant fails its precise protocol assertion. The initial
+compiler SIGSEGV remains unexplained; single-job/larger compiler stack diagnostic
+completes. This does not close the recorded full-workspace transport failures.
+
+### Structural ledger reconciliation after import repair
+
+CI8989 preflight fails exact structural-debt parity. Inventory isolates one change:
+backend/tests/test_authorization.py has the same10709 lines but its hash changed
+when8989 removed unused asdict from the existing import. Protected main has10754
+lines; the earlier route-test migration already shrank this item. Allowed scope:
+this record and that single content_sha256 in TEST_STRUCTURE_DEBT.json. No source,
+assertions, policy, exceptions, limits or other ledger entries change. Acceptance:
+exact current inventory parity and full trusted-transition/assertion-map validation.
+Risk is CI evidence consistency; focused CI reviewer inspects the one-entry delta.
+Human review focus is confirming the digest corresponds to the already-reviewed
+import-only edit, without accepting new or growing structural debt.
+
+Full structural validator passes exit0 with the reconciled digest, including
+trusted-main transition and assertion-map checks; log:
+/tmp/submission-structure-reconciliation.log. No test or policy edit was needed.

From fac8ea5110dfe3ac1d8fa90a5f0ff132c3811034 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 17:26:12 +0100
Subject: [PATCH 166/513] style(cli): format raw ZIP public journey with pinned
 Ruff

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  13 +
 .../integration/test_submission_public_api.py | 278 ++++++++++++++----
 2 files changed, 233 insertions(+), 58 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 6b75a0e7b..cee141af7 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5293,3 +5293,16 @@ import-only edit, without accepting new or growing structural debt.
 Full structural validator passes exit0 with the reconciled digest, including
 trusted-main transition and assertion-map checks; log:
 /tmp/submission-structure-reconciliation.log. No test or policy edit was needed.
+
+Focused CI review closes the digest repair without findings. Latest CLI HTTP job
+133428292508 stops before HTTP tests: Ruff check passes, formatter rejects only
+cli/tests/integration/test_submission_public_api.py. Extend repair scope to pinned
+Ruff formatting of that already-reviewed drill. Require identical Python AST,
+full CLI lint/format gates, and unchanged structural inventory; no behavior edits.
+
+Formatting repair preserves the complete Python AST. Move the existing E402
+annotation to the formatter-expanded import's opening line so Ruff still applies
+it. All98 CLI test files pass lint and format checks; full structural validation
+again passes exit0 (/tmp/submission-format-structure.log). Both latest CLI jobs
+stop at this same formatting gate before integration execution. No new journey
+execution evidence is claimed. Latest fetched main is already contained in HEAD.
diff --git a/cli/tests/integration/test_submission_public_api.py b/cli/tests/integration/test_submission_public_api.py
index f7197197a..e3276f597 100644
--- a/cli/tests/integration/test_submission_public_api.py
+++ b/cli/tests/integration/test_submission_public_api.py
@@ -28,12 +28,17 @@
     pagination_cursor_hmac_secret as pagination_cursor_hmac_secret,
 )
 from tests.artifacts.test_submission_intake_admission import (  # noqa: E402
-    admission_intake as _admission_intake, admin_access as _admin_access,
-    signed_access as _signed_access, rsa_signing_material as rsa_signing_material,
-    auth_database_env as auth_database_env, clear_settings_cache as clear_settings_cache,
+    admission_intake as _admission_intake,
+    admin_access as _admin_access,
+    signed_access as _signed_access,
+    rsa_signing_material as rsa_signing_material,
+    auth_database_env as auth_database_env,
+    clear_settings_cache as clear_settings_cache,
 )
 from tests.artifacts.test_submission_pre_source import _source_runtime  # noqa: E402
-from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation  # noqa: E402
+from tests.checkers.external.test_selected_pre_submit_coordination import (  # noqa: E402
+    _source_reservation,
+)
 from tests.checkers.execution.support import provision_post_submit_service  # noqa: E402
 from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer  # noqa: E402
 from tests.test_trusted_intake import _archive  # noqa: E402
@@ -83,10 +88,18 @@ async def _remove_setup_management(f):
     # ART's task seed needs management to screen/release, but this drill must
     # exercise only contributor authority. Retain and revoke the setup grant.
     async with f.factory() as session:
-        [role] = list(await session.scalars(select(AdminRoleGrant).where(
-            AdminRoleGrant.target_actor_profile_id == str(f.actor.actor_profile_id),
-            AdminRoleGrant.status == "active")))
-        assert role.role == "project_manager" and role.scope_project_id == str(f.project)
+        [role] = list(
+            await session.scalars(
+                select(AdminRoleGrant).where(
+                    AdminRoleGrant.target_actor_profile_id
+                    == str(f.actor.actor_profile_id),
+                    AdminRoleGrant.status == "active",
+                )
+            )
+        )
+        assert role.role == "project_manager" and role.scope_project_id == str(
+            f.project
+        )
         role_id = str(role.id)
     response = await f.access.signed.revoke(f.access.admin, role_id)
     assert response.status_code == 200, response.text
@@ -95,31 +108,61 @@ async def _remove_setup_management(f):
 
 async def _assert_submitter_only(f):
     async with f.factory() as session:
-        assert await session.scalar(select(func.count()).select_from(AdminRoleGrant).where(
-            AdminRoleGrant.target_actor_profile_id == str(f.actor.actor_profile_id),
-            AdminRoleGrant.status == "active")) == 0
+        assert (
+            await session.scalar(
+                select(func.count())
+                .select_from(AdminRoleGrant)
+                .where(
+                    AdminRoleGrant.target_actor_profile_id
+                    == str(f.actor.actor_profile_id),
+                    AdminRoleGrant.status == "active",
+                )
+            )
+            == 0
+        )
 
 
 async def _configure(f, tmp_path, monkeypatch, payload):
     runtime, errors = _source_runtime(payload, tmp_path, "completed")
     calls, original = [], runtime.execute_pre
+
     async def execute(lease, request):
         calls.append(lease.reservation.attempt_id)
         return await original(lease, request)
+
     runtime.execute_pre = execute
-    monkeypatch.setattr(composition, "selected_pre_submit_checker_execution",
-                        lambda **kwargs: SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime))
+    monkeypatch.setattr(
+        composition,
+        "selected_pre_submit_checker_execution",
+        lambda **kwargs: SelectedPreSubmitCheckerExecutionAdapter(
+            external_execution=runtime
+        ),
+    )
     await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_PRE_SUBMIT)
     await _seed_materializer(f.factory)
     app = f.access.signed.client._transport.app
-    storage = {k: v for k, v in _settings(tmp_path).model_dump().items() if k.startswith("artifact_")}
-    settings = app.state.settings.model_copy(update=storage | {"submission_execution_profile": {
-        "capacity": {"maximum_total_bytes": 4 * 1024 * 1024},
-        "runtime": _source_reservation().runtime_profile.model_dump(mode="json"),
-        "upload_total_seconds": 300.0, "upload_idle_seconds": 10.0,
-        "foreground_lease_seconds": 60.0, "heartbeat_seconds": 10.0,
-        "replay_total_seconds": 30.0, "part_bytes": 5 * 1024**2,
-    }})
+    storage = {
+        k: v
+        for k, v in _settings(tmp_path).model_dump().items()
+        if k.startswith("artifact_")
+    }
+    settings = app.state.settings.model_copy(
+        update=storage
+        | {
+            "submission_execution_profile": {
+                "capacity": {"maximum_total_bytes": 4 * 1024 * 1024},
+                "runtime": _source_reservation().runtime_profile.model_dump(
+                    mode="json"
+                ),
+                "upload_total_seconds": 300.0,
+                "upload_idle_seconds": 10.0,
+                "foreground_lease_seconds": 60.0,
+                "heartbeat_seconds": 10.0,
+                "replay_total_seconds": 30.0,
+                "part_bytes": 5 * 1024**2,
+            }
+        }
+    )
     monkeypatch.setattr(app.state, "settings", settings)
     return app, settings, calls, errors
 
@@ -132,16 +175,29 @@ async def _finalize(f, tmp_path, settings, operation_id):
     from app.modules.outbox.api import DeliveryOptions
     from app.modules.outbox.registry import HandlerRegistry
     from tests.artifact_store_helpers import initialize_local_store
-    for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER):
+
+    for identity in (
+        ServiceIdentity.ARTIFACT_BINDING,
+        ServiceIdentity.OUTBOX_DISPATCHER,
+    ):
         await provision_post_submit_service(f.factory, identity)
     store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
     try:
         handler = composition.submission_finalization_handler(
-            sessions=f.factory, settings=settings, store=store, lease_duration=timedelta(seconds=30))
+            sessions=f.factory,
+            settings=settings,
+            store=store,
+            lease_duration=timedelta(seconds=30),
+        )
         event_type = "SubmissionFinalizationRequested"
-        delivery = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization,
-            registry=HandlerRegistry([(event_type, 1, handler)], replay_safe=frozenset({(event_type, 1)})),
-            options=DeliveryOptions(lease_seconds=30, handler_timeout_seconds=25))
+        delivery = outbox_delivery(
+            f.factory,
+            authorization_factory=outbox_dispatch_authorization,
+            registry=HandlerRegistry(
+                [(event_type, 1, handler)], replay_safe=frozenset({(event_type, 1)})
+            ),
+            options=DeliveryOptions(lease_seconds=30, handler_timeout_seconds=25),
+        )
         async with f.factory() as session:
             row = await session.get(SubmissionIntakeOperation, operation_id)
             event_id = UUID(row.finalization_event_id)
@@ -151,7 +207,13 @@ async def _finalize(f, tmp_path, settings, operation_id):
 
 
 async def _inspect(call, f, receipt, payload):
-    progress = await call("task", "submission-operation", str(f.task), "--operation-id", receipt["operation_id"])
+    progress = await call(
+        "task",
+        "submission-operation",
+        str(f.task),
+        "--operation-id",
+        receipt["operation_id"],
+    )
     submission_id = progress["submission_id"]
     assert progress["operation_state"] == "finalized"
     assert progress["processing_stage"] == "evaluation_pending"
@@ -160,43 +222,76 @@ async def _inspect(call, f, receipt, payload):
     assert [v["id"] for v in history["items"]] == [submission_id]
     detail = await call("submission", "show", submission_id)
     assert detail == history["items"][0]
-    assert detail["summary"] == "Completed the required project work and included evidence."
+    assert (
+        detail["summary"]
+        == "Completed the required project work and included evidence."
+    )
     [run] = (await call("submission", "findings", submission_id))["items"]
     assert run["submission_id"] == submission_id and run["status"] == "queued"
-    assert await call("submission", "findings", submission_id, "--run", run["id"]) == run
+    assert (
+        await call("submission", "findings", submission_id, "--run", run["id"]) == run
+    )
     [assignment] = (await call("me", "assignments"))["items"]
     assert assignment["task_id"] == str(f.task)
     assert assignment["latest_submission"]["submission_id"] == submission_id
     assert assignment["next_action"] == "awaiting_evaluation"
     [attempt] = (await call("me", "submissions", "--task", str(f.task)))["items"]
-    assert attempt["submission_id"] == submission_id and attempt["status"] == detail["status"]
+    assert (
+        attempt["submission_id"] == submission_id
+        and attempt["status"] == detail["status"]
+    )
     assert (await call("me", "summary"))["assignments"] == {"active": 1, "closed": 0}
     [project] = (await call("me", "projects"))["items"]
     assert project["project_id"] == assignment["project_id"]
     assert project["project_roles"] == ["submitter"]
     await call("submission", "show", str(uuid4()), denied=404)
-    await call("task", "submission-operation", str(f.task), "--operation-id", str(uuid4()), denied=404)
+    await call(
+        "task",
+        "submission-operation",
+        str(f.task),
+        "--operation-id",
+        str(uuid4()),
+        denied=404,
+    )
     async with f.factory() as session:
         for model in (Submission, CheckerRun):
-            assert await session.scalar(select(func.count()).select_from(model).where(model.task_id == str(f.task))) == 1
+            assert (
+                await session.scalar(
+                    select(func.count())
+                    .select_from(model)
+                    .where(model.task_id == str(f.task))
+                )
+                == 1
+            )
         row = await session.get(SubmissionIntakeOperation, receipt["operation_id"])
-        admission = await session.scalar(select(SubmissionBundleAdmission).where(
-            SubmissionBundleAdmission.source_operation_id == row.id))
+        admission = await session.scalar(
+            select(SubmissionBundleAdmission).where(
+                SubmissionBundleAdmission.source_operation_id == row.id
+            )
+        )
         assert admission.status == "consumed"
-        assert admission.archive_sha256 == "sha256:" + hashlib.sha256(payload).hexdigest()
+        assert (
+            admission.archive_sha256 == "sha256:" + hashlib.sha256(payload).hexdigest()
+        )
         assert admission.archive_byte_count == len(payload)
         assert admission.consumed_by_submission_id == submission_id
-        assert (await session.get(CheckerRun, run["id"])).evaluation_request_id == progress["evaluation_request_id"]
+        assert (
+            await session.get(CheckerRun, run["id"])
+        ).evaluation_request_id == progress["evaluation_request_id"]
     return submission_id
 
 
 async def _conceal_foreign(call, f, commands):
     same = await f.access.signed.actor("cli-same-project")
     other = await f.access.signed.actor("cli-other-project")
-    same_access = AdminAccess(f.access.signed, f.access.admin, same, f.access.bootstrap_grant_id)
+    same_access = AdminAccess(
+        f.access.signed, f.access.admin, same, f.access.bootstrap_grant_id
+    )
     await grant(same_access, f.manager, f.project)
     other_project = await create_project("cli-other-project")
-    other_access = AdminAccess(f.access.signed, f.access.admin, other, f.access.bootstrap_grant_id)
+    other_access = AdminAccess(
+        f.access.signed, f.access.admin, other, f.access.bootstrap_grant_id
+    )
     other_manager = await project_manager(other_access, other_project)
     await grant(other_access, other_manager, other_project)
     for actor in (same, other):
@@ -208,27 +303,43 @@ async def _invalidate(call, f, commands):
     async with f.factory.begin() as session:
         profile = await session.get(ActorProfile, str(f.actor.actor_profile_id))
         profile.status, profile.suspended_by = "suspended", "cli-test"
-        profile.suspended_at, profile.suspension_reason = datetime.now(UTC), "fresh authority regression"
+        profile.suspended_at, profile.suspension_reason = (
+            datetime.now(UTC),
+            "fresh authority regression",
+        )
     for state in ("suspended", "revoked"):
         if state == "revoked":
             async with f.factory.begin() as session:
                 profile = await session.get(ActorProfile, str(f.actor.actor_profile_id))
                 profile.status = "active"
-                profile.suspended_by = profile.suspended_at = profile.suspension_reason = None
-                profile.reactivated_by, profile.reactivated_at = "cli-test", datetime.now(UTC)
+                profile.suspended_by = profile.suspended_at = (
+                    profile.suspension_reason
+                ) = None
+                profile.reactivated_by, profile.reactivated_at = (
+                    "cli-test",
+                    datetime.now(UTC),
+                )
                 profile.reactivation_reason = "Isolate revoked-grant proof"
                 role = await session.get(ProjectRoleGrant, f.grant_id)
                 role.status, role.version = "revoked", 2
                 role.revoked_by_actor_profile_id = role.granted_by_actor_profile_id
-                role.revoked_by_admin_role_grant_id = role.granted_by_admin_role_grant_id
-                role.revoked_reason, role.revoked_at = "CLI fresh replay authority regression", datetime.now(UTC)
+                role.revoked_by_admin_role_grant_id = (
+                    role.granted_by_admin_role_grant_id
+                )
+                role.revoked_reason, role.revoked_at = (
+                    "CLI fresh replay authority regression",
+                    datetime.now(UTC),
+                )
         for args in commands:
             await call(*args, denied=404)
 
 
 @pytest.mark.asyncio
 async def test_cli_public_submission_progress_replay_history_and_suspension(
-    admission_intake, tmp_path, monkeypatch, cli,
+    admission_intake,
+    tmp_path,
+    monkeypatch,
+    cli,
 ):
     f, key, payload = admission_intake, str(uuid4()), _archive()
     await _remove_setup_management(f)
@@ -236,45 +347,96 @@ async def test_cli_public_submission_progress_replay_history_and_suspension(
     await _assert_submitter_only(f)
     archive = tmp_path / "work.zip"
     archive.write_bytes(payload)
-    submit = ("task", "submit", str(f.task), "--assignment", str(f.assignment),
-              "--file", str(archive), "--idempotency-key", key,
-              "--summary", "Completed the required project work and included evidence.")
+    submit = (
+        "task",
+        "submit",
+        str(f.task),
+        "--assignment",
+        str(f.assignment),
+        "--file",
+        str(archive),
+        "--idempotency-key",
+        key,
+        "--summary",
+        "Completed the required project work and included evidence.",
+    )
     async with socket_api(app) as origin:
+
         async def call(*args, denied=None, token=None):
-            result = await asyncio.to_thread(cli, origin, token or f.access.target.token,
-                "-o", "json", *args, process_timeout=90 if args[:2] == ("task", "submit") else 20)
+            result = await asyncio.to_thread(
+                cli,
+                origin,
+                token or f.access.target.token,
+                "-o",
+                "json",
+                *args,
+                process_timeout=90 if args[:2] == ("task", "submit") else 20,
+            )
             if denied is not None:
                 assert result.returncode == 1 and result.stdout == "", result.stderr
-                assert json.loads(result.stderr)["error"]["status"] == denied, result.stderr
+                assert json.loads(result.stderr)["error"]["status"] == denied, (
+                    result.stderr
+                )
                 return None
             assert result.returncode == 0 and result.stderr == "", result.stderr
             return json.loads(result.stdout)
+
         paths = (await f.access.signed.client.get("/openapi.json")).json()["paths"]
-        assert "post" not in paths.get("/api/v1/tasks/{task_id}/submission-bundle-preparations", {})
+        assert "post" not in paths.get(
+            "/api/v1/tasks/{task_id}/submission-bundle-preparations", {}
+        )
         assert "post" in paths["/api/v1/tasks/{task_id}/submissions"]
         receipt = await call(*submit)
         assert receipt["status"] == "accepted" and receipt["replayed"] is False
         assert receipt["pre_submission_results"]
-        assert all(item["status"] in {"passed", "warning"} for item in receipt["pre_submission_results"])
+        assert all(
+            item["status"] in {"passed", "warning"}
+            for item in receipt["pre_submission_results"]
+        )
         assert await call(*submit) == dict(receipt, replayed=True)
         changed = list(submit)
         changed[changed.index("--summary") + 1] += " changed"
         await call(*changed, denied=409)
-        by_key = await call("task", "submission-operation", str(f.task), "--idempotency-key", key)
-        by_id = await call("task", "submission-operation", str(f.task), "--operation-id", receipt["operation_id"])
+        by_key = await call(
+            "task", "submission-operation", str(f.task), "--idempotency-key", key
+        )
+        by_id = await call(
+            "task",
+            "submission-operation",
+            str(f.task),
+            "--operation-id",
+            receipt["operation_id"],
+        )
         assert by_key == by_id
         assert by_id["processing_stage"] == "finalization_pending"
         assert by_id["submission_id"] is by_id["evaluation_request_id"] is None
         assert by_id["pre_submission_results"] == receipt["pre_submission_results"]
         async with f.factory() as session:
-            assert await session.scalar(select(func.count()).select_from(Submission).where(Submission.task_id == str(f.task))) == 0
+            assert (
+                await session.scalar(
+                    select(func.count())
+                    .select_from(Submission)
+                    .where(Submission.task_id == str(f.task))
+                )
+                == 0
+            )
         await _finalize(f, tmp_path, settings, receipt["operation_id"])
         submission_id = await _inspect(call, f, receipt, payload)
         assert await call(*submit) == dict(receipt, replayed=True)
         assert len(calls) == 1 and not errors, errors
-        commands = (submit, ("submission", "show", submission_id),
-                    ("submission", "findings", submission_id), ("task", "submissions", str(f.task)),
-                    ("task", "submission-operation", str(f.task), "--operation-id", receipt["operation_id"]))
+        commands = (
+            submit,
+            ("submission", "show", submission_id),
+            ("submission", "findings", submission_id),
+            ("task", "submissions", str(f.task)),
+            (
+                "task",
+                "submission-operation",
+                str(f.task),
+                "--operation-id",
+                receipt["operation_id"],
+            ),
+        )
         await _conceal_foreign(call, f, commands)
         await _assert_submitter_only(f)
         await _invalidate(call, f, commands)

From 1fb303ace30e750ce2a46ba9a0858a2448969a3e Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Mon, 16 Nov 2026 20:45:48 +0100
Subject: [PATCH 167/513] fix(submissions): preserve accepted revision custody
 and phase cardinality

Require one PRE and one POST image for new approvals while retaining historical policy and revision evidence. Validate revision eligibility at acceptance and immutable custody during durable finalization, including continuation after the original deadline.

Close source streams before failed or cancelled materialization returns. Move affected producers onto raw ZIP intake and production OUTBOX finalization, with historical archives, rollback probes, replay checks, and source cleanup regressions.

Verified focused materialization and revision/reclaim suites plus a real one-hour deadline drill. Full specification qualification and remaining end-to-end gates remain in progress on the existing draft PR.
---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 646 ++++++++++++++++++
 .../versions/0082_policy_phase_cardinality.py |  45 ++
 .../0083_accepted_revision_continuation.py    |  94 +++
 .../artifacts/post_submit_materialization.py  |  25 +-
 .../modules/checkers/api/external_policy.py   |   4 +-
 .../modules/projects/api/guide_proposals.py   |   4 +-
 .../artifacts/revision_deadline_drill.py      |  84 +++
 .../artifacts/test_post_source_cleanup.py     | 120 ++++
 .../artifacts/test_post_source_manifest.py    |  44 ++
 .../test_submission_intake_admission.py       |  42 +-
 .../test_submission_intake_custody.py         |   2 +-
 .../guide_proposals/test_postgresql.py        |   8 +-
 .../checkers/execution/completion_fixture.py  |   2 +-
 .../checkers/execution/storage_fixture.py     |   6 +
 .../checkers/execution/test_execution.py      |  12 +-
 .../tests/checkers/external/test_policy.py    | 138 ++--
 .../external/test_revision_materialization.py | 256 +++----
 .../checkers/external/test_trial_policy.py    |   5 +-
 backend/tests/committed_guide_fixtures.py     |  18 +-
 backend/tests/conftest.py                     |   2 +-
 .../tests/fixtures/multi_post_capture.py.txt  |  73 ++
 .../tests/fixtures/multi_post_history.json.gz | Bin 0 -> 146399 bytes
 backend/tests/fixtures/multi_post_history.md  |  46 ++
 .../policy_cardinality_capture.py.txt         |  33 +
 .../policy_cardinality_history.json.gz        | Bin 0 -> 55164 bytes
 .../fixtures/policy_cardinality_history.md    |  35 +
 backend/tests/historical_policy_fixtures.py   |  72 ++
 .../historical_revision_material_fixtures.py  | 137 ++++
 .../post_submit_materialization_helpers.py    | 102 +--
 .../projects/guide_activation/pg_support.py   |   3 +-
 .../guide_activation/source_fixtures.py       |   6 +-
 .../guide_activation/test_postgresql.py       |   3 +-
 .../guide_activation/test_successor.py        |   7 +-
 .../guide_compilation/proposals/pg_support.py |  11 +-
 .../proposals/test_approved_tip.py            |   6 +-
 .../proposals/test_attachment_input.py        |  44 +-
 .../proposals/test_attachment_postgresql.py   |  80 ++-
 .../proposals/test_audit_schema.py            |   4 +-
 .../proposals/test_authority_contract.py      |   5 +-
 .../proposals/test_contracts.py               |   5 +-
 .../proposals/test_postgresql.py              |  78 ++-
 .../proposals/test_public_api.py              |  14 +-
 .../test_evaluation_context_specifications.py |  14 +-
 .../tests/projects/policy_bundle_fixtures.py  |  30 +-
 .../projects/post_policy/test_compiler.py     |  11 +-
 .../projects/submission_policy_fixtures.py    |  20 +-
 .../projects/test_locked_policy_custody.py    |  10 +-
 .../tests/projects/unified_policy_fixtures.py |   8 +-
 backend/tests/retained_material_fixtures.py   | 464 ++++++-------
 backend/tests/selected_policy_fixtures.py     |   6 +-
 backend/tests/submission_fixtures.py          |  82 +--
 .../tasks/post_submit_routing/support.py      |  58 +-
 .../accepted_revision_probes.py               | 102 +++
 .../submission_dispatch/test_concurrency.py   | 184 ++---
 .../test_evaluation_revision.py               |  20 +-
 .../test_revision_exhaustion.py               |  43 +-
 .../submission_dispatch/test_rollback.py      | 105 +--
 .../tests/tasks/test_submission_lineage.py    |   3 +-
 .../tests/test_post_submit_materialization.py |  85 +--
 backend/tests/test_tasks.py                   |  68 +-
 cli/README.md                                 |   7 +-
 cli/internal/api/guide_approval.go            |   2 +-
 .../test_guide_activation_public_api.py       |  12 +-
 .../integration/test_guide_approval_http.py   |  11 +-
 .../test_guide_approval_public_api.py         |  12 +-
 .../test_guide_post_approval_public_api.py    |  12 +-
 .../test_guide_post_correction_public_api.py  |  12 +-
 mcp_server/README.md                          |   5 +
 .../guide_pre_submission_approve.json         |   8 +-
 mcp_server/tests/test_guide_lifecycle.py      |  67 +-
 70 files changed, 2768 insertions(+), 1014 deletions(-)
 create mode 100644 backend/alembic/versions/0082_policy_phase_cardinality.py
 create mode 100644 backend/alembic/versions/0083_accepted_revision_continuation.py
 create mode 100644 backend/tests/artifacts/revision_deadline_drill.py
 create mode 100644 backend/tests/artifacts/test_post_source_cleanup.py
 create mode 100644 backend/tests/artifacts/test_post_source_manifest.py
 create mode 100644 backend/tests/fixtures/multi_post_capture.py.txt
 create mode 100644 backend/tests/fixtures/multi_post_history.json.gz
 create mode 100644 backend/tests/fixtures/multi_post_history.md
 create mode 100644 backend/tests/fixtures/policy_cardinality_capture.py.txt
 create mode 100644 backend/tests/fixtures/policy_cardinality_history.json.gz
 create mode 100644 backend/tests/fixtures/policy_cardinality_history.md
 create mode 100644 backend/tests/historical_policy_fixtures.py
 create mode 100644 backend/tests/historical_revision_material_fixtures.py
 create mode 100644 backend/tests/tasks/submission_dispatch/accepted_revision_probes.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index cee141af7..b89aa052a 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -5306,3 +5306,649 @@ it. All98 CLI test files pass lint and format checks; full structural validation
 again passes exit0 (/tmp/submission-format-structure.log). Both latest CLI jobs
 stop at this same formatting gate before integration execution. No new journey
 execution evidence is claimed. Latest fetched main is already contained in HEAD.
+
+### Shared retained-history producer cutover: caller audit
+
+CI8989 task_lifecycle_a artifact14244099338 supplies the failing test log at
+/tmp/submission-8989-task-a-tests.log. It exposes two superseded producer paths:
+retained_material_fixtures._runtime_factory passes removed materialization to
+SelectedPreSubmitExecutionService; tasks.submission_lineage_support prepares old
+material facts for the current guide-source authority. Neither warrants restoring
+old constructors or weakening AUTH. Current retained_admission has two callers:
+submission_fixtures.seed_retained_submission and dispatch/test_concurrency's
+second-ready-admission race. The latter assumes two independent ready admissions
+before TASK creation; current T1 task exclusion and T4/T5 handoff require a new
+race trigger, preserving single committed Submission/dispatch/checker/event proof.
+MemoryStore also serves checksum-bound migration rows and POST storage proofs;
+its retained-object read/write semantics must survive. Migration snapshots remain
+immutable and are not a substitute for a current submission producer.
+
+Next bounded implementation scope: retained_material_fixtures.py,
+submission_fixtures.py, checkers/execution/storage_fixture.py and directly affected
+submission_dispatch fixture/race consumers, plus a focused current-source fixture
+helper if required for cohesion. Replace preparation/verification/hidden-current
+creation with real source T1/upload/PRE/T4 and production OUTBOX T5. Keep portable
+external PRE as explicit controlled runtime evidence for the one selected image.
+New producers must explicitly approve exactly one PRE and one POST before task
+release; empty-policy historical reads remain valid, not new execution inputs. Preserve private retained packet fields only at the existing
+fixture injection boundary around the canonical T5 writer. Retain exact source
+bytes for subsequent POST and separate historical archive reads. Prohibited:
+compatibility constructors, fabricated eligible PRE, SQL bypass of custody,
+disabled triggers, weakened race assertions, changing snapshot data, or calling
+this provider/native/broker qualification. Acceptance is the affected retained
+history/read/storage suite plus concrete initial/revision and duplicate-finalizer
+proof, followed by the original failing lane. Risks: lineage/authorization,
+fixture proof fidelity and test structure. ARCH/SEC and QA must review the caller
+mapping and frozen implementation; CI review applies if assertion maps/lane
+selection need reconciliation. Human focus is preserved original proof and exact
+T4/T5 source lineage. Shared post_submit_materialization_helpers and other old
+lineage callers remain tracked follow-on consumers, not silently accepted green.
+
+ARCH/SEC plan review confirms the existing ready-admission race cannot be carried
+forward literally: T1 already owns exclusion, and duplicate T5 must prove exactly
+one durable continuation. It also confirms private packet injection belongs only
+around production T5's existing build_submission boundary. Source provider fixture
+must bind operation/fence/generation and bytes while preserving historical reads.
+
+Concrete prerequisite found during caller audit: ExternalCheckerPolicyCompileRequest
+and GuideProposalApprovalInput still allow0..200 images per phase, whereas spec
+D08/A34 and T1 require exactly1 each. Do not manufacture a selected image when
+migrating retained policies. Tighten NEW approval/compiler input and CLI/MCP input
+contracts together, leaving LockedExternal* retained decoders unchanged (spec20.2).
+This requirement precedes creating valid current retained-history producers.
+Allowed prerequisite paths: checkers/api/external_policy.py (compile input only),
+projects/api/guide_proposals.py (approval input), cli/internal/api/guide_approval.go,
+MCP generated approval contract and affected schema generation/tests, focused
+policy/approval/client tests, and current selection docs. Prohibited: rewriting
+locked policy bodies, changing historical decoder cardinality, silently picking a
+first image or supplying defaults, relaxing admission, or removing retained replay
+proof. Verification must cover missing/zero/two selections in either phase, exact
+one-per-phase success with real registry resolution, rejection before registry or
+HTTP side effects, schema parity, and historical empty/multiple-policy decoding.
+ARCH/SEC and QA review apply; client contract/docs review applies on frozen target.
+Broader caller migration remains required after this boundary is enforced.
+
+Cardinality worktree regression: four zero/two-per-phase cases fail before input
+bounds change; exact-one registry resolution passes. Tightened compiler and public
+approval request fields to1..1, without changing retained decoders. Updated phase
+configuration/model/forge tests to supply an explicit valid counterpart selection,
+so their original failure boundaries remain reachable. Old duplicate/unsorted
+multi-selection input proof now checks categorical cardinality refusal. Retained
+multi-PRE aggregate runtime-budget guard is tested at stored decoding; historical
+zero/two phase bodies retain exact JSON/hash. Full policy module passes35 in4.21s
+(/tmp/submission-cardinality-policy-v2.log). Two saved-POST compiler tests now use
+explicit one-per-phase inputs; their exact projection/hash assertions remain.
+
+CLI input validator and MCP snapshot enforce the same cardinality. Their boundary
+fixtures now explicitly select both images; zero/two selections must fail without
+HTTP. Initial CLI replay launched before its new binary existed and failed fixture
+setup; this is no product evidence. Replay begins only after binary existence is
+observed. Client tests, backend schema parity, remaining approval fixture migration,
+full shared checks and frozen review are still outstanding. These edits are not yet
+committed/pushed; latest PR head remainsfac8ea511.
+
+Current client evidence: Go API/command packages pass; rebuilt CLI approval HTTP
+module passes6 in55.39s (/tmp/submission-cardinality-cli-v2.log), including the
+new zero/two no-request cases. MCP lifecycle and configured full backend OpenAPI
+snapshot checks remain live at this checkpoint; no result is inferred from partial
+progress output. The latest full policy run remains35pass; saved-POST fixture
+updates made afterward still need their focused execution.
+
+Extend affected fixture scope to projects/guide_activation/source_fixtures.py,
+projects/unified_policy_fixtures.py, selected_policy_fixtures.py and proposal
+pg_support/test_postgresql/test_public_api. Ordinary fixture defaults deliberately
+select the existing controlled PRE/POST specs before approval. Explicit None
+continues to mean no registration for tests proving later image registration;
+it cannot be approved by the new contract. proposal_case must register its exact
+selected images through the existing real Operator owner, returning those values
+for typed/public approvals. Tests must forward those exact values rather than
+manufacture new identity/configuration. Preserve all authority/rollback/replay
+assertions. Intentional historical multi-policy and T1-incompatible-policy tests
+require retained fixture treatment, not silently changing their expected facts.
+
+QA plan review independently confirms model-scope and PRE-budget tests detect
+specific simulated defects. Add matching-hash retained duplicate/order negatives
+for both phases because new-input cardinality now rejects earlier. Pure public
+input/saved-POST projection tests pass10 in4.33s; configured MCP snapshot/backend
+OpenAPI comparison passes78 in237.76s. MCP lifecycle remains running.
+
+Caller trace extends the same fixture migration to guide_activation/pg_support,
+post_submit_materialization_helpers, tasks/test_submission_lineage and the
+projects policy_bundle/submission_policy fixtures; they explicitly forward their
+own absent defaults. Authorization guide_proposals approval tests also consume the
+same proposal_case choices. Preserve explicit absence for historical/late-register
+scenarios. Focused database run initially refused the admin URL's plain postgres
+scheme before provisioning; corrected to required postgresql+asyncpg for owned
+loopback test database. No production database or guard changed.
+
+Expanded pure replay passes85 in22.91s (/tmp/submission-cardinality-pure-v3.log):
+policy cardinality/historical identity/order/budget, trial and evaluation-context
+selection, approval replacement/attachment inputs and saved POST projection.
+Evaluation-context no-write negative now additionally proves both actual registry
+reads occurred, preventing an early cardinality denial from falsely satisfying it.
+Proposal-case normal setup registers exact real images; explicit None remains an
+unregistered setup opt-out for the later-publication test, which now rejects empty
+approval and registers both images before its existing replay/conflict assertions.
+The selected5 PostgreSQL/public approval cases are running against isolated0081;
+MCP lifecycle process is live and progressing, neither yet counted as passed.
+
+Still required in this cardinality change: complete shared policy_bundle and
+submission_policy fixture migration, successor and remaining CLI/API/auth approval
+callers, historical incompatible T1/multi-POST proof preservation, actual database
+results, structural inventory/affected gates/docs and frozen ARCH/SEC/QA/client
+review. No push or readiness claim at this checkpoint.
+
+Focused5 real PostgreSQL/public approval cases pass in124.70s at0081;
+/tmp/submission-cardinality-approval-db-v2.log/json records exit0 and complete
+isolated database/role cleanup. Worktree evidence is based onfac8ea511; subsequent
+fixture edits are not covered by that result. Shared policy-bundle approval now
+registers explicit controlled fixture selections through the real Operator owner;
+explicit empty inputs remain rejected. Extend directly affected scope to activation
+successor/late-registration and locked_policy_custody tests. Successor selects real
+registered images; locked-context refusal reuses exact original stored approval
+choices; late-registration explicitly opts out of fixture registration until its
+own publication step. Original lifecycle/hash/replay/denial assertions remain.
+Broader affected approval/activation database replay is now running as v3.
+
+Additional SQL boundary audit:0066's guide_approval_attachments_valid accepts
+coherent zero/multiple selection arrays and protects retained evidence; tightening
+it globally would invalidate historical approvals, including non-null request_json
+rows from0066 through0081. ARCH/SEC confirms the correct extension is a new0082
+migration replacing only require_current_guide_proposal_approval, already attached
+BEFORE INSERT. Preserve its current request/schema checks; require safe JSON array
+types and exact length1 in both request phases and locked plan phases. Do not alter
+the deferred validator or old rows. Scope includes the new migration and focused
+SQL insertion/preservation tests. Verify coherent zero/two new inserts fail at the
+specific new guard, current1/1 owner approval succeeds, and retained null/non-null
+old-cardinality rows remain readable under unchanged custody. Wait for running v3
+schema proof to terminate before editing migration head.
+
+Historical T1 review rejects a project-only fake as equivalent old-row proof: TASK's
+frozen PRE hash would not match the zero-PRE projection. Preserve a genuinely
+coherent retained TASK/PROJECT fixture for no_pre/no_post; fault-injection tests
+may supplement but cannot replace that claim. The historical multi-POST visibility
+proof likewise remains pending retained-custody migration.
+
+MCP lifecycle replay finishes60pass in1244.70s; the prior process was slow but live,
+not stalled or restarted. Structural validator exits0 with no ledger adjustment
+(/tmp/submission-cardinality-structure-v1.log). Full backend Ruff, all98 CLI test
+format checks, Markdown links and whitespace pass at this worktree checkpoint.
+Broad database v3 remains live; do not infer its result from heartbeat output.
+New schema guard and coherent historical fixtures are still incomplete, so no
+frozen implementation review, commit or push is claimed for cardinality yet.
+
+Historical fixture capture plan: use detachedfac8ea511 (before cardinality edits)
+in an isolated0081 database to run the existing real no_pre/no_post approved TASK
+fixtures. Capture exact nonempty public table rows plus actor/task/assignment and
+namespace selectors, with fixed source commit and checksum. These are synthetic
+test data only. Restore via the existing owned-database snapshot loader before
+upgrading to0082; validate retained TASK/PROJECT context and original T1 zero-write
+refusal after upgrade. This preserves the former integration assertion instead
+of forging a mismatched port response. Allowed additions are a checksum-bound
+historical policy fixture archive, concise loader/provenance and affected tests;
+no executable old approval path in production, no locked row rewriting, no data
+from user/provider environments. Capture scripts run only in detached temporary
+worktree and isolated runner; main branch production changes remain separate.
+
+Historical capture v2 passes2 in148.32s with0081 and full database/role cleanup.
+Only the capture test was appended in the detachedfac8ea511 checkout; all original
+source bytes match the commit. Archive policy_cardinality_history.json.gz binds
+52nonempty tables/308rows per scenario, including actual non-null approval requests
+with0/1 and1/0 phases. SHA256:
+0b7cb10abc1c23864fac6c3be2b898caf297760192cc423e2f6f2c1e1862911c.
+The checked-in capture text/provenance makes source and expected proof explicit.
+Original T1 zero-operation/task-link/audit assertions now consume restored exact
+TASK/PROJECT data through the same extracted intake_admission composition. Live
+fixture setup always approves valid1/1; no fake historical context is introduced.
+The existing snapshot loader checks ownership, exact rows/FKs and reinstated guards.
+Restoration baseline and direct SQL negative are running before the0082draft is
+installed; SQL negative is expected to fail until its new guard exists. Do not
+count baseline as passing until terminal evidence is inspected. All new helper
+lint/link/whitespace checks pass. Broader approval v3 remains live at0081.
+
+Approval database v3 finished84pass in1174.75s at0081 with complete owned
+database/role cleanup. Historical baseline finished2pass; SQL insertion regression
+failed at the old uniqueness guard instead of the required cardinality guard,
+confirming the new boundary was absent. Installed0082 only after both runs ended;
+separate owned runs now verify upgraded historical refusal and current insertion.
+Extend fixture scope to test_tasks and tasks/post_submit_routing/support: ordinary
+new approvals must register a POST image by default instead of forwarding None.
+Explicit None remains explicit; no production compatibility path is added.
+
+0082 SQL replay initially stops at fixture schema fingerprint before test bodies.
+The migration replaces only the existing BEFORE INSERT function; reset fingerprints
+include function definitions. Extend allowed scope to tests/conftest.py pinned
+EXPECTED_PUBLIC_SCHEMA_SHA256, updating0081 646811e5… to observed0082 35cf33c4…;
+retain exact equality guard. Failed setup run cleaned its database/role completely.
+Approval authority input replay passes19 in3.83s.
+
+Historical upgraded0082 T1 cases pass2 in151.79s (37 unrelated tests deselected);
+original zero-operation/task-pointer/audit assertions remain intact. Backend Ruff
+passes for app/tests/new migration. MCP README now states the same exact1/1
+approval input requirement as its checked contract and CLI instructions.
+
+0082 SQL replay v2 passes2 in35.42s: real current approval/replay succeeds and
+rehashed zero/two phase inserts fail at the named cardinality guard, leaving the
+original approval unchanged. Reset/task replay passes6 in37.26s, including exact
+schema preservation, schema-drift rejection and draft task creation with current
+approval defaults. Structural validator v2 exits0 without ledger edits; Markdown
+links pass15 changed files. Expanded SQL replay v3 independently varies request,
+locked plan and both, with zero/two entries and null/object array-type violations.
+This final expansion is running, not yet claimed passed. No cardinality commit
+or full-goal completion is claimed; historical multi-POST and downstream current
+producer migration remain required.
+
+Expanded SQL replay v3 finishes2pass in25.07s at0082, complete database/role
+cleanup. It checks24 invalid request/plan combinations plus current approval and
+replay, and exact unchanged original approval row. Fresh origin/main fetch remains
+94334ccf4085c26c7bfaa054465fc05cfbdad1fc; current branch is0commits behind.
+All processes started for this migration checkpoint are terminal. Full goal remains
+active, with no readiness or full-suite success claim.
+
+Historical multi-POST preservation: capture the unchanged per-binding revision
+journey at pinned main94334ccf4085c26c7bfaa054465fc05cfbdad1fc (schema0068),
+where its original prepared-admission producer is still authoritative. A temporary
+detached checkout adds only an observer test: snapshot accepted successor custody
+and synthetic MinIO objects immediately before POST, then allow the original
+test to complete all grant/visibility/replay/immutability assertions. Capture all
+three role combinations. Only successful original journeys qualify as fixtures.
+Allowed scope: captured synthetic archive/provenance/loader and existing revision
+materialization test, with no production compatibility path or locked-row edits.
+Current-head replay must drain retained accepted POST and preserve every distinct
+visibility assertion. Native/AWS qualification remains separate.
+
+QA provisional multi-POST plan review confirms endpoint-bound namespace cannot
+be rewritten for CI. Use captured bytes only for current owner/grant isolation;
+retain separate current real-MinIO single-image revision coverage as a required
+proof. Capture observer preserves original test bytes and writes only after all
+original assertions pass. First available archive is predecessor_submission_archive:
+71tables/388rows,2objects, SHA256 cf6d55f9ed34334b86697961af192233a94097368ca777fc20e33527f0746fc2.
+Both objects match exact retained replica/content hashes and sizes. Other role
+cases are still running under owned runner handle38676, metadata/log
+/tmp/submission-multipost-capture-v1.{json,log}; no whole-run success claim.
+Portable restoration fixture drafted at /tmp/submission-multipost-fixture.py,
+not installed: checksum/provenance/role validation, bounded read-only exact-ref
+store, coordinator reread after upgrade, real current materialization. QA requires
+original grant/context/SQL/replay/foreign-request/cleanup assertions unchanged.
+
+Capture v1 is terminal:2pass/1fail in391.68s, all database/role/MinIO cleanup
+complete. Archive-only and findings+archive original journeys passed; findings-only
+was cancelled at ArtifactScratchManager.reserve_bytes/run_blocking_cancellation_resistant.
+No timeout/guard changes made. Replay only that unchanged failed role in isolated
+/tmp/submission-multipost-capture-findings-v2.log/json to distinguish a repeated
+behavior from the first run cancellation. Do not count findings-only as captured.
+
+Installed an explicitly incomplete two-variant multi_post_history archive to
+exercise current upgrade while the missing-role recapture runs; not committed or
+published. Current restore v1 selects only captured roles1/roles2. Replaced original
+test setup with historical_revision_material; AST comparison confirms every
+statement from successor materialization through visibility/SQL/cleanup/replay/
+foreign-assignment assertions is identical. Actual original producer/helper source
+is preserved by pinned capture provenance, not retained as an executable current
+approval path. Full3-case replay and capture provenance remain pending.
+
+Findings-only unchanged recapture v2 passes1 in202.15s, complete owned DB/role/
+MinIO cleanup. All3original role journeys now have successful captures; first-run
+cancellation remains recorded, with no timing/budget changes. Each snapshot has
+71nonempty tables/388rows and2objects. Do not replace the partial archive while
+restore v1 handle92448 is still live; its imported checksum must stay consistent.
+After that run terminates, consolidate all3snapshots and replay the missing role.
+
+Historical multi-POST current replay completes: roles1/roles2 pass2 in184.14s;
+roles0 passes1 in55.85s. Both runs finish at0082 and clean owned database/role.
+All original successor assertions retain identical AST; the fixture additionally
+rereads the exact request through current coordinator after upgrade. Final3-role
+archive SHA256 acde3375a3e96603868480fff9ffbb4492fe62ef3a89f9348e2ac9caddaae552,
+146399bytes; existing two snapshots are byte-semantically unchanged after adding
+the third. Ruff app/tests/new migration passes; structural validator v3 exits0
+without ledger changes; Markdown links pass16 changed files. All processes started
+for this checkpoint are terminal; QA plan review completed, implementation review
+is still pending. Current real-MinIO single-image revision and shared producer
+cutover remain required; no cardinality commit, full CI or full-goal claim.
+
+Current producer cutover prerequisite: retained_material_fixtures still constructs
+SelectedPreSubmitExecutionService(materialization=), and submission_fixtures then
+uses the retired hidden prepared-admission creation operation. Replace this shared
+producer with raw ZIP T1/upload/source PRE/T4 and production outbox T5. Preserve
+fixture-private packet fields only around build_submission during T5; do not fake
+source/PRE/acceptance rows or skip AUTH. Allowed files: retained_material_fixtures,
+submission_fixtures, checkers/execution/storage_fixture and directly affected
+tasks/submission_dispatch/test_concurrency (its competing ready-admission premise
+is replaced by competing T1/finalizer proof). Keep actual old object bytes for
+historical migration consumers, and share complete source state by factory and
+namespace. Tests use existing current-task, revision/history/acceptance consumers;
+architecture/security/QA review remains required. No production compatibility path.
+
+Retained source replay v1 reaches real T1 and rejects the old symbolic provider
+profile "test" created by committed_guide_fixtures. Extend allowed fixture scope
+to that default namespace constructor: use canonical local-v2 descriptor/hash
+through ArtifactStoreNamespaceIdentity/artifact_store_namespace_material from
+the start of new guide setup. This remains an explicitly scripted byte provider,
+not a filesystem/deployment proof. Existing retained rows and real provider
+namespace overrides are unchanged. No production qualification guard is relaxed.
+
+Retained source v2: initial owner/SQL lineage test passes; revision-history test
+reaches accepted T4 then leaves T5 unfinalized (1pass/1fail,94.85s). Added an
+observing wrapper around the unchanged production finalization handler so the
+next exact-case replay exposes the underlying exception that OUTBOX classifies
+as uncertain; no retry/guard bypass. /tmp/submission-retained-revision-v3.log/json
+is running. Current concurrency replacement passes2 in60.09s: pause exact source
+observation during a real OUTBOX T5 claim, refuse duplicate delivery or a new-key
+T1, then assert one operation/Submission/dispatch/checker and one event per phase.
+All completed runs cleaned owned database/role. ARCH/SEC in-progress review finds
+no blocking fixture composition issue; scoped proof excludes provider/VM and
+private-packet/source equality. Remaining role-race/rollback/material producers
+still need current acceptance-path migration; no compatibility alias retained.
+
+Verified production revision defect: retained revision replay v3 fails125.19s
+at T5 admission INSERT with SQL CheckViolation "revision admission context
+unavailable" from0043 guard_revision_admission_context. The trigger still reads
+a prepared durable intent and requires needs_revision/current deadline, despite
+source T4 having accepted custody and moved TASK to evaluation_pending.0074
+updated the verified-lineage guard but omitted this revision guard. Scope extends
+to new0083 migration and pinned test schema fingerprint, plus focused accepted
+revision SQL substitution tests. Proposed change delegates source rows to existing
+require_source_submission_admission (complete acceptance/PRE/actor/task/assignment/
+revision-id/hash/predecessor/remediation validation); preserve old trigger body
+exactly for non-source rows. A11 requires accepted work to survive delayed workers
+without renewed contributor/deadline eligibility. No old row rewriting or guard
+disabling. ARCH/SEC plan review requested before installing migration.
+
+Revision continuation plan correction after ARCH/SEC inspection: 0043 also guards
+Submission insertion and deferred revision deadline. 0083 must adapt all three
+source paths, binding the exact accepted operation, source admission, immutable
+revision preparation/lineage and continuation authority. Preserve non-source
+branches. At T4 add preparation target/current TASK lineage and current routing
+fence checks to require_submission_acceptance_current; these are eligibility
+checks and must not recur after acceptance. Risk: high authorization/atomicity.
+Acceptance: actual failing revision journey succeeds; invalid source/revision
+bindings fail; acceptance refuses stale target/fence; delayed accepted work does
+not recheck contributor deadline. Allowed files remain 0083, schema fingerprint,
+focused existing intake/revision tests and this record. No retained row rewriting,
+new public API, provider qualification claims or compatibility producers. Human
+review focus is exact T4/T5 authority boundary; ARCH/SEC and QA review required.
+
+0083 candidate installed: T4 adds exact revision project/target lineage/current
+routing fence checks. All three old revision guards delegate accepted source
+custody to the existing admission validator and a new exact Submission bridge;
+the BEFORE bridge uses TASK active operation and the deferred bridge uses finalized
+Submission identity plus consumed admission and commit authority. Non-source
+branches remain unchanged. ARCH/SEC code-scope provisional PASS; no full proof
+claim. Schema upgrades successfully; first run stops at expected fingerprint
+mismatch 4f2fa4c887c1fe29c555b4af534227535c7b28b2ddccc53013c1e62eba8625a5,
+now pinned. v2 /tmp/submission-revision-0083-v2.log/json runs actual revision
+history with five finalized-record substitution probes plus reset tests. Ruff
+and structural validator pass (structure log /tmp/submission-revision-0083-structure.log).
+QA identifies outstanding direct preinsert and T4 stale target/fence cases and
+expired-after-T4 replay. Existing expiry fixtures disable immutable triggers or
+rewrite pre-preparation history; they are not no-bypass current-source evidence.
+Use retained_intake/finalize_retained_intake split for new current boundary tests.
+No commit/push or full-goal completion claim at this checkpoint.
+
+0083 v2 terminal result: 32passed in236.32s; migration head0083; owned database
+and role cleanup complete. This includes the previously failing real source
+revision T4→OUTBOX T5/history journey, five finalized-record forged lineage
+refusals, and database reset suite. Current blocker is repaired for this concrete
+journey; acceptance/preinsert/deadline proof gaps above remain open. All local
+processes started for this checkpoint are terminal. No full CI/provider claim.
+
+0083 next proof increment: extend allowed test scope with
+backend/tests/tasks/submission_dispatch/accepted_revision_probes.py and the existing
+retained revision history case. Observe real T5 immediately before repository
+Submission insertion; require a valid committed=false control and reject forged
+revision lineage and source admission/preparation/predecessor/remediation records
+inside savepoints, then invoke the unchanged repository insertion. No provider,
+authority, SQL trigger, clock, or durable owner mutation bypass. Keep these
+preinsert probes distinct from committed=true history probes. QA review will
+assess actual boundary coverage; expiry and T4 stale-current evidence stay open.
+
+T4 stale-fence proof design: stage real acceptance with unchanged owner, reserve
+a legitimate generation2 predecessor checker evaluation inside the same root
+transaction, then let deferred SQL validate commit. Expect named revision
+acceptance refusal and complete rollback of receipt/event/Submission/admission.
+This tests the new database fence check after Python context preflight; no raw
+fence update, trigger disabling, or mocked eligibility. Add one existing task
+client test and a scoped observing helper in accepted_revision_probes.py.
+
+Expiry proof scope: add explicit long-running
+backend/tests/artifacts/revision_deadline_drill.py (run by direct pytest path;
+not ordinary test_ collection) and expose revision_deadline_hours on existing
+create_active_project/create_policy_bundle_for_guide fixtures, default unchanged48.
+Drill approves actual one-hour policy, creates genuine revision T4, observes
+PostgreSQL time until its original deadline, then runs production OUTBOX T5.
+No clock override, immutable-row edits or trigger bypass. This is scripted-store
+owner/SQL timing proof, not provider/native qualification. Run with isolated
+runner timeout4500; retain exact terminal result before claiming A11 evidence.
+
+0083 v3 preinsert probes exposed test savepoint lifetime: SQLAlchemy ROLLBACK TO
+left a PostgreSQL subtransaction active; later checker root pg_export_snapshot
+correctly refused. No production relaxation. Probe helper now explicitly issues
+SAVEPOINT, ROLLBACK TO, RELEASE for each rejected composite. v3 failed61.84s,
+owned DB/role cleanup complete. v4 terminal: 2passed163.23s, cleanup complete;
+real preinsert false-branch controls/source substitutions + original finalized
+history probes + exact T4 stale-fence commit refusal all pass. One existing
+storage_request generation2 Pydantic serializer warning remains visible.
+
+Deadline drill v1 intentionally interrupted after QA found wrong POST event-name
+oracle; cleanup complete. Corrected to canonical REQUEST_EVENT. v2 intentionally
+interrupted before waiting an hour to batch final QA request: invoke production
+finalizer twice within the same still-live OUTBOX invocation after deadline and
+require identical full creation results. Cleanup complete. v3 now runs exact
+final drill at /tmp/submission-revision-deadline-drill-v3.log/json, timeout4500;
+do not restart merely for silence or elapsed observation. No expiry pass claim
+until terminal evidence. QA code review confirms meaningful preinsert and
+same-transaction T4 fence coverage; stale-target case remains open. No reviewer
+is running, no full-goal claim, and only original PR708 remains authorized.
+
+Shared material producer cutover scope: post_submit_materialization_helpers.py,
+retained_material_fixtures.py, tasks/submission_dispatch/test_concurrency.py and
+test_rollback.py, plus directly affected source-read assertions. Replace retired
+_verified_admission/hidden create with actual raw ZIP source intake and OUTBOX T5
+using real existing local/MinIO provider. Preserve exact archive mode bytes and
+POST request reads. Custom producer hooks move to foreground submission so role
+races test T4 authority; rollback cases move to accepted T5 and retain acceptance
+receipt/event while refusing partial finalization. Do not add compatibility
+aliases or a second producer. Retain creation_request projection only for existing
+current downstream consumers, explicitly trace remaining old revision callers.
+Risk high owner/AUTH/atomicity; focused real PG/local+MinIO execution, race/rollback
+checks and required ARCH/SEC/QA review before commit. No provider qualification
+claim from controlled portable project runtime. One-hour deadline v3 remains live.
+
+Material source cutover implemented: exact archive bytes now traverse _foreground
+and production OUTBOX T5; current dispatch result read from persisted owner row.
+Removed prepared admission/hidden creation from this shared producer. Role race
+hooks now pause T4 prepare_acceptance and prove already accepted work survives
+later contributor revocation. T5 rollback tests preserve evaluation_pending,
+acceptance receipt and finalization event, while requiring no source admission,
+Submission, binding, CheckerRun or POST event after a failed participant. Current
+selected POST fixture asserts one entry. CountedStore implements exact open_source;
+real MinIO fixture enables bucket versioning. Remaining downstream old revision
+helpers and composition/replay callers are traced, not treated as passed.
+
+Material v1 terminal2fail81.32s: portable PRE lacked its directory and role race
+never reached T4. Added mkdir with per-task unique source-runtime directory.
+Material v2 terminated at collection because test imported ArtifactAuthorityDeniedError
+from wrong module; corrected to artifacts.schemas. Both owned DB/role cleanups
+complete. Structural validator v1 exited0, no debt ledger change. v3 now runs
+local+MinIO execution/replay, T4 revocation race and seven T5 rollback cases,
+/tmp/submission-material-source-v3.log/json. Deadline drill v3 remains active;
+confirmed real accepted revision in workstream_test_906ae3a89dbc and original
+PostgreSQL deadline2026-11-16T19:25:25.361833Z. No deadline result yet.
+
+Shared producer ARCH/SEC code review complete: no further concrete bypass found;
+portable-runtime versus real-provider proof scope retained. v3 remains live with
+runner-owned MinIO bucket workstream-ci-isolated-4b500b25f9c9 and database
+workstream_test_4b500b25f9c9. Seven rollback cases collect successfully. Latest
+Ruff/diff checks pass. Fresh origin/main fetch remains94334ccf4; HEAD167ahead/0behind.
+No merge/rebase needed at this checkpoint. No results inferred from live run.
+
+Material v3 terminal: 8passed/2failed289.58s; owned DB/role/MinIO cleanup complete.
+Passed local source POST/replay, T4 role revocation race, five staged participant
+rollbacks and unmanaged-savepoint refusal. MinIO POST returned infrastructure_failed;
+add materialization exception diagnostics before rerunning that exact case. Revoked
+binding denies via PreparedAuthorizationUnsupported at fixed-service resolution,
+not ArtifactAuthorityDeniedError; corrected exact assertion, no runtime change.
+v4 /tmp/submission-material-source-v4.log/json runs only the two failed cases.
+
+Next traced shared consumer within cutover: tasks/post_submit_routing/support.py
+_create_submission still prepares/verifies and calls hidden create for sibling and
+revision successors. Extend allowed scope to that producer. Extract the already
+implemented current archive->source->T5 composition as create_source_submission
+in post_submit_materialization_helpers.py and reuse it from both initial and
+routing producers. Keep exact metadata revision acknowledgment from locked TASK,
+whole real underlying store and persisted dispatch.result; no compatibility
+producer. Use unique runtime directory per invocation so revision of the same
+TASK cannot collide. Verify existing sibling, successor/routing and previous
+version denial cases; current live-MinIO revision qualification still separate.
+
+Material v4 terminal1passed/1failed80.50s, owned DB/role/MinIO cleanup complete.
+Revoked binding test now passes exact fixed-service denial. MinIO diagnostic shows
+ArtifactPreparationDeadlineError, followed by async-generator aclose-already-running
+teardown errors. Fixture inherited 2-byte provider buffers from adapter vectors;
+normal material execution will use bounded64KiB, matching existing source POST
+fixture, without increasing any deadline. The cleanup symptom exposes a production
+gap: PostSubmissionMaterializationService passes open_source directly to prepare
+without closing that closable generator if preparation fails while suspended at a
+yield. Extend bounded scope to post_submit_materialization.py and existing
+materialization tests. Register exact-source generator closure in AsyncExitStack
+with cancellation-resistant await; retained non-source iterator contract unchanged.
+Regression must open real local/MinIO source, fail scratch write after first chunk,
+and prove provider generator closed before failure returns, no consumer entry,
+no active scratch. ARCH/SEC/QA review required before commit; no workaround by
+relaxing timeouts or silently discarding the observed cleanup defect.
+
+Routing source v1 terminal3passed103.52s: sibling mixed-lineage denial, old-version
+routing refusal after real successor, and superseded-checker reserve/replay denial.
+All use current archive source/T4/T5 composition; owned DB/role cleanup complete.
+New cleanup regression added to test_post_submit_materialization.py: wrap real
+provider open_source; fail scratch write after first chunk; require generator
+finally completed before error return and zero scratch/consumer entry. Running
+local baseline against unchanged production owner at
+/tmp/submission-source-close-before-v1.log/json before installing closure fix.
+
+Source close baseline fails exactly: first553-byte chunk written, closed count0,
+30.64s, cleanup complete. Source close after-v1 passes4 in90.82s: real local/MinIO
+first-write failure cleanup plus both normal execution/replay journeys; owned
+DB/role/bucket cleanup complete. Production source generators now register on the
+existing AsyncExitStack before scratch preparation. Final callback creates one
+close task, shields/drains it despite repeated cancellation, preserves caller
+cancellation only after successful closure, and maps ordinary or self-cancelled
+close failures to ArtifactScratchIntegrityError (not a normal terminal material
+failure). This follows ARCH/SEC review; generic preserving-cancellation helper
+would suppress close errors during cancellation, so the callback explicitly lets
+cleanup uncertainty win.
+
+Keep the new cohesive regressions in backend/tests/artifacts/test_post_source_cleanup.py
+instead of enlarging the existing materialization suite. Added real local/MinIO
+repeated-cancellation draining and pure ordinary/self-cancelled close-failure
+controls. after-v2 /tmp/submission-source-close-after-v2.log/json now verifies all
+six cleanup cases plus local/MinIO normal execution against final callback. Ruff
+and diff checks pass; no final result yet. Deadline v3 remains the same live run.
+
+Final source-close structural check exits0, no debt-ledger edits. QA scoped code
+review finds no additional defect; independently verified compound cancellation
+then late-close-error probe exits0 and preserves original cause/integrity failure
+(/tmp/submission-post-source-close-qa-compound.log). Final eight-case v2 still live
+handle43563; deadline v3 same handle59321. No reviewers remain running. No final
+execution/goal/signoff claim before terminal receipts; no commit/push yet.
+
+Final cleanup v2 terminal7passed/1setup error150.91s, owned DB/role/MinIO cleanup
+complete. Asyncpg raised UnicodeDecodeError while decoding canonical schema
+inventory before the local first-write case executed; no owner assertion failed.
+Keep this environment failure open, do not mask/skip it. Exact unchanged local
+case replay runs /tmp/submission-source-close-after-v3-local.log/json. The seven
+completed cases include MinIO ordinary cleanup, both repeated-cancellation paths,
+both unconfirmed-close errors and both normal provider execution/replays.
+
+Continue existing test_post_submit_materialization.py consumer cutover: use
+actual selected POST processor with controlled registered-image adapter and exact
+execution lease instead of synthesizing empty-policy results. Adapt existing
+provider fault/lock hooks to open_source (closable generator), and protect source
+reads as well as object reads in binding-consumption proof. Preserve foreign-result
+refusal by rehashing a completed actual result with mismatched generation. Existing
+manifest-corruption behavior will be checked, not weakened speculatively. Scope
+is directly affected tests, no new runtime compatibility path or policy relaxation.
+
+Unchanged local source-close replay v3 passes1 in27.04s; owned DB/role cleanup
+complete. All eight targeted final-callback cases now have passing evidence
+across v2+local replay, but prior asyncpg schema-decoding setup error is retained
+as unresolved environment evidence, not claimed repaired. Existing whole POST
+materialization owner suite now uses actual selected processor/lease and source
+read hooks; running /tmp/submission-materialization-owner-v1.log/json and scoped
+structure validation. No current-owner suite pass claim yet. Source cleanup
+production/code review is complete; broader acceptance and native qualification
+requirements remain active.
+
+Next bounded proof cutover: test_evaluation_revision.py must create its consumed
+revision using create_source_submission, actual raw ZIP PRE/T4 and OUTBOX T5.
+Allowed files are that test and this record; preserve every revision-read,
+rebase, substitution, replay and no-mutation assertion. No production changes,
+historical-data rewriting, guard relaxation or compatibility helper. Risk is
+test fidelity; verification is the entire four-case owner file on isolated
+PostgreSQL plus Ruff and structural validation. QA/test-delta review should
+compare the old assertions and current producer custody. Human focus is whether
+the revision selector is exercised against the same actual source-backed
+submission the public intake now creates.
+
+Structural diagnosis: frozen Python diagnostic run exits0, system Python exits139
+in garbage collection during ast.parse in coverage_policy.py. This is unresolved
+interpreter/environment evidence, not proof of a validator defect or its repair.
+Both materialization-owner and real deadline integration runs remain live.
+
+QA-EVAL-001 found an affected shared producer in test_revision_exhaustion.py:
+_submit_initial_after_reclaim still invokes the removed preparation endpoint.
+Expand allowed test scope to this helper and its direct callers. Preserve HTTP
+claim and submission boundaries, inject the real foreground owner with controlled
+runtime through the configured command, then run production finalization. Keep
+all caller assertions. Verify reclaimed-contributor isolation and existing
+exhaustion/reclaim callers; do not claim an unrun caller passes.
+
+Environment evidence at 2026-11-16 19:07 UTC: owned PostgreSQL log records backend
+PID2068 killed by signal9 while updating project_setup_runs.documents_ready_at;
+server terminated other connections and recovered. Before death host process
+235582 used35.4 percent of16GB RAM. This is not a diagnosed application or
+hardware root cause. Preserve affected run receipts. Evaluation v1 had loaded
+the superseded reclaim helper; deliberately SIGINT that test process only after
+repair, terminal exit2 with1passed404.65s and runner cleanup_complete=true.
+New six-case current candidate run is /tmp/submission-evaluation-revision-source-v2.log/json,
+including full evaluation-revision file and both zero-cap reclaim modes, failfast.
+Ruff/diff checks pass. Structural /tmp/submission-evaluation-revision-structure-v1.log
+is pending. Main materialization and deadline runs were not restarted.
+
+Materialization owner v1 terminal3failed/14passed948.09s, cleanup_complete=true.
+Quota case failed during setup at the exact PostgreSQL UPDATE killed19:07UTC;
+consumer-deadline case hit outer10s while revalidating audit custody, not during
+consumer waiting. Replay those two unchanged before any timeout/production change.
+Stored-manifest corruption now fails earlier in require_source_submission_admission
+with23514 before provider I/O; the old expected late manifest error is obsolete
+for this source-backed fixture. Bound test repair to test_post_submit_materialization.py
+and new cohesive artifacts/test_post_source_manifest.py: retain corrupt-database
+rejection with exact SQLSTATE/provenance and zero provider/consumer calls; separately
+inject changed executable semantics from the controlled inspector over exact source
+bytes and require independent manifest mismatch before consumer/export. Preserve
+cleanup assertions. No production guard changes. QA/test-delta review must verify
+both distinct boundaries and a discriminating mismatch-check removal probe.
+
+QA/test-delta confirms reclaim helper preserves HTTP/authenticated identity and
+returns stored dispatch fields required by all traced callers. Its extracted
+helper control and actor/metadata substitution probes pass
+(/tmp/submission-reclaim-qa-auth-probe-bounded.log); these are not database proof.
+QA independently ran exact new semantic-manifest test against exact materialize
+method with controlled DB selection and real scratch/inspection: baseline passes,
+removing only the semantic digest comparison fails at forbidden export
+(/tmp/submission-source-manifest-qa-probe.log). Both boundary assertions remain.
+Removed obsolete pre_submit_evidence_sets mutation from stored-corruption test
+(source admissions do not link that table); replay final exact case after v2.
+Frozen current test candidate; Ruff/diff pass. Revision structural run exits0;
+new manifest structural run /tmp/submission-post-manifest-structure-v1.log pending.
+Fresh origin/main fetch has167ahead/0behind; sole draft PR708 still points fac8ea511.
+No native/provider/full-goal completion or new commit claimed.
+
+
+Checkpoint verification: materialization owner focused replay passes4 in345.70s;
+revision/reclaim passes6 in710.46s; real one-hour revision deadline drill passes1
+in3680.50s. All three isolated runner receipts confirm cleanup complete. Source
+cleanup, historical replay and policy-cardinality evidence remain as recorded
+above. Python lint, Markdown links and structural validation pass. Native/provider
+qualification, broader full-suite proof and full-spec acceptance remain unfinished.
+This checkpoint does not mark PR708 ready or the active goal complete.
diff --git a/backend/alembic/versions/0082_policy_phase_cardinality.py b/backend/alembic/versions/0082_policy_phase_cardinality.py
new file mode 100644
index 000000000..7f1fd7b46
--- /dev/null
+++ b/backend/alembic/versions/0082_policy_phase_cardinality.py
@@ -0,0 +1,45 @@
+"""Require one image per phase for new approvals; preserve retained policy custody."""
+from alembic import op
+
+revision = "0082_policy_phase_cardinality"
+down_revision = "0081_operation_read_authority"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.project_guide_proposal_approvals IN SHARE ROW EXCLUSIVE MODE")
+    # This existing trigger runs only BEFORE INSERT. Historical approvals, including
+    # non-null zero/multiple requests, keep their original deferred custody checks.
+    op.execute("""
+CREATE OR REPLACE FUNCTION public.require_current_guide_proposal_approval()
+RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+BEGIN
+    IF NEW.request_json IS NULL OR NEW.target_json->>'result_schema_version'
+        IS DISTINCT FROM 'project_guide_check_specification.v1' THEN
+        RAISE EXCEPTION 'current guide approval request required' USING ERRCODE='23514';
+    END IF;
+    IF jsonb_typeof(NEW.request_json->'pre_submit_attachments') IS DISTINCT FROM 'array'
+       OR jsonb_typeof(NEW.request_json->'post_submit_attachments') IS DISTINCT FROM 'array'
+       OR jsonb_typeof(NEW.effective_pre_submit_plan::jsonb #> '{pre_submit,entries}') IS DISTINCT FROM 'array'
+       OR jsonb_typeof(NEW.effective_pre_submit_plan::jsonb #> '{post_submit,entries}') IS DISTINCT FROM 'array'
+    THEN
+        RAISE EXCEPTION 'guide approval requires one PRE and one POST image'
+            USING ERRCODE='23514', CONSTRAINT='ck_guide_approval_phase_cardinality';
+    END IF;
+    IF jsonb_array_length(NEW.request_json->'pre_submit_attachments') <> 1
+       OR jsonb_array_length(NEW.request_json->'post_submit_attachments') <> 1
+       OR jsonb_array_length(NEW.effective_pre_submit_plan::jsonb #> '{pre_submit,entries}') <> 1
+       OR jsonb_array_length(NEW.effective_pre_submit_plan::jsonb #> '{post_submit,entries}') <> 1
+    THEN
+        RAISE EXCEPTION 'guide approval requires one PRE and one POST image'
+            USING ERRCODE='23514', CONSTRAINT='ck_guide_approval_phase_cardinality';
+    END IF;
+    RETURN NEW;
+END $$
+""")
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
diff --git a/backend/alembic/versions/0083_accepted_revision_continuation.py b/backend/alembic/versions/0083_accepted_revision_continuation.py
new file mode 100644
index 000000000..142d06952
--- /dev/null
+++ b/backend/alembic/versions/0083_accepted_revision_continuation.py
@@ -0,0 +1,94 @@
+"""Check revision eligibility at acceptance and immutable custody at finalization."""
+from alembic import op
+from sqlalchemy import text
+
+revision = "0083_accepted_revision"
+down_revision = "0082_policy_phase_cardinality"
+branch_labels = None
+depends_on = None
+
+
+def _replace(signature, old, new):
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))"
+    ), {"signature": signature}).scalar_one()
+    if body.count(old) != 1:
+        raise RuntimeError("revision continuation predecessor changed: " + signature)
+    op.execute(body.replace(old, new))
+
+
+def upgrade():
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.workstream_tasks, public.submission_intake_operations, "
+               "public.submission_bundle_admissions, public.submissions "
+               "IN ACCESS EXCLUSIVE MODE")
+    _replace("public.require_submission_acceptance_current(public.submission_intake_operations)",
+        "      OR p.blocked_reason IS NOT NULL OR p.outcome NOT IN ('kept','rebased')",
+        """      OR p.project_id IS DISTINCT FROM o.project_id
+      OR p.packet#>'{candidate,target,lineage}' IS DISTINCT FROM
+         (SELECT public.revision_task_lineage(to_jsonb(t)) FROM public.workstream_tasks t WHERE t.id=o.task_id)
+      OR NOT EXISTS (SELECT 1 FROM public.task_post_submit_routing_manifests m
+         JOIN public.checker_submission_fences f ON f.submission_id=m.submission_id
+         WHERE m.id=p.routing_manifest_id AND f.current_run_id=m.checker_run_id)
+      OR p.blocked_reason IS NOT NULL OR p.outcome NOT IN ('kept','rebased')""")
+    _replace("public.guard_revision_admission_context()", "BEGIN\n SELECT selected_request_json",
+        """BEGIN
+ IF NEW.source_operation_id IS NOT NULL THEN
+   PERFORM public.require_source_submission_admission(NEW);
+   RETURN NEW;
+ END IF;
+ SELECT selected_request_json""")
+    op.execute(_SOURCE_REVISION)
+    for name, result in (("guard_new_revision_submission", "NEW"),
+                         ("guard_revision_submission_deadline", "NULL")):
+        anchor = f" IF NEW.supersedes_submission_id IS NULL THEN RETURN {result}; END IF;"
+        _replace(f"public.{name}()", anchor, anchor + f"""
+ IF public.accepted_revision_submission_valid(NEW,{'true' if result == 'NULL' else 'false'}) THEN
+   RETURN {result};
+ END IF;""")
+
+
+_SOURCE_REVISION = """
+CREATE FUNCTION public.accepted_revision_submission_valid(s public.submissions, committed boolean)
+RETURNS boolean LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE o public.submission_intake_operations%ROWTYPE;
+ a public.submission_bundle_admissions%ROWTYPE; p public.task_revision_preparations%ROWTYPE;
+BEGIN
+ -- At INSERT the binding is not consumed yet. At deferred commit, use the
+ -- finalized submission identity, since TASK may already have cleared its pointer.
+ SELECT * INTO o FROM public.submission_intake_operations candidate
+ WHERE candidate.task_id=s.task_id AND
+   ((NOT committed AND candidate.id=(SELECT active_submission_operation_id
+       FROM public.workstream_tasks WHERE id=s.task_id))
+    OR (committed AND candidate.finalized_submission_id=s.id));
+ IF o.id IS NULL THEN RETURN false; END IF;
+ SELECT * INTO a FROM public.submission_bundle_admissions WHERE source_operation_id=o.id;
+ SELECT * INTO p FROM public.task_revision_preparations
+ WHERE id=(o.command_metadata->>'revision_preparation_id')::uuid;
+ IF o.state NOT IN ('finalization_pending','finalized') OR a.id IS NULL OR p.id IS NULL
+    OR NOT public.submission_finalization_authority_valid(o,'claim')
+    OR s.task_assignment_id IS DISTINCT FROM o.assignment_id
+    OR s.contributor_id IS DISTINCT FROM o.actor_profile_id
+    OR s.supersedes_submission_id IS DISTINCT FROM a.predecessor_submission_id
+    OR s.version IS DISTINCT FROM a.predecessor_submission_version+1
+    OR p.id IS DISTINCT FROM a.revision_preparation_id
+    OR p.preparation_sha256 IS DISTINCT FROM a.revision_preparation_sha256
+    OR p.packet#>'{candidate,target,lineage}' IS DISTINCT FROM public.revision_submission_lineage(s)
+ THEN RAISE EXCEPTION 'accepted revision submission custody mismatch' USING ERRCODE='23514'; END IF;
+ PERFORM public.require_source_submission_admission(a);
+ IF committed AND (o.state IS DISTINCT FROM 'finalized'
+    OR o.finalized_admission_id IS DISTINCT FROM a.id
+    OR a.status IS DISTINCT FROM 'consumed'
+    OR a.consumed_by_submission_id IS DISTINCT FROM s.id
+    OR NOT EXISTS (SELECT 1 FROM public.submissions retained WHERE retained.id=s.id
+       AND retained.submission_bundle_admission_id=a.id)
+    OR NOT public.submission_finalization_authority_valid(o,'commit')) THEN
+   RAISE EXCEPTION 'accepted revision submission closure mismatch' USING ERRCODE='23514';
+ END IF;
+ RETURN true;
+END $$;
+"""
+
+
+def downgrade():
+    raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database")
diff --git a/backend/app/modules/artifacts/post_submit_materialization.py b/backend/app/modules/artifacts/post_submit_materialization.py
index a2ba6e26b..4381bd874 100644
--- a/backend/app/modules/artifacts/post_submit_materialization.py
+++ b/backend/app/modules/artifacts/post_submit_materialization.py
@@ -1,7 +1,7 @@
 """Verified post-submit input through the sole bounded artifact scratch owner."""
 
 import asyncio
-from collections.abc import Callable
+from collections.abc import AsyncGenerator, Callable
 from contextlib import AsyncExitStack, contextmanager
 from dataclasses import dataclass
 
@@ -107,6 +107,21 @@
 from app.modules.checkers.api.selected_post_submit import SelectedPostSubmitCurrentResultReference
 
 
+async def _close_source_stream(stream: AsyncGenerator[bytes, None]) -> None:
+    """Drain provider cleanup before a failed or cancelled materialization returns."""
+    closing = asyncio.ensure_future(stream.aclose())
+    try:
+        await asyncio.shield(closing)
+    except asyncio.CancelledError:
+        try:
+            await await_cancellation_resistant(closing)
+        except BaseException as error:
+            raise ArtifactScratchIntegrityError("source stream cleanup is unconfirmed") from error
+        raise
+    except Exception as error:
+        raise ArtifactScratchIntegrityError("source stream cleanup is unconfirmed") from error
+
+
 def _external_material(facts, media_type, role):
     """Project verified custody without provider coordinates or file paths."""
     material = facts.material
@@ -702,12 +717,16 @@ async def materialize(
                 inspections, intakes, media_types = {}, {}, {}
                 expanded_bytes, entries = 0, 0
                 for role, selection in selections.items():
+                    if selection.sealed_source:
+                        stream = self._store.open_source(selection.sealed_source)
+                        intake_cleanup.push_async_callback(_close_source_stream, stream)
+                    else:
+                        stream = self._store.open(selection.provider_object_ref)
                     prepared, intake = await intake_cleanup.enter_async_context(
                         prepared_trusted_intake(
                             self._intake,
                             self._preparation.prepare(
-                                (self._store.open_source(selection.sealed_source) if selection.sealed_source
-                                 else self._store.open(selection.provider_object_ref)),
+                                stream,
                                 media_type=selection.media_type,
                                 expected_sha256=selection.sha256,
                                 expected_size=selection.byte_count,
diff --git a/backend/app/modules/checkers/api/external_policy.py b/backend/app/modules/checkers/api/external_policy.py
index 9bff735f0..eef9783b2 100644
--- a/backend/app/modules/checkers/api/external_policy.py
+++ b/backend/app/modules/checkers/api/external_policy.py
@@ -214,8 +214,8 @@ def validate_attachment(self) -> Self:
 class ExternalCheckerPolicyCompileRequest(_PolicyValue):
     """Phase-separated project images, independent of setup suggestions."""
 
-    pre_submit_attachments: tuple[ExternalCheckerImageAttachment, ...] = Field(max_length=200)
-    post_submit_attachments: tuple[ExternalCheckerImageAttachment, ...] = Field(max_length=200)
+    pre_submit_attachments: tuple[ExternalCheckerImageAttachment, ...] = Field(min_length=1, max_length=1)
+    post_submit_attachments: tuple[ExternalCheckerImageAttachment, ...] = Field(min_length=1, max_length=1)
 
     @model_validator(mode="after")
     def validate_order(self) -> Self:
diff --git a/backend/app/modules/projects/api/guide_proposals.py b/backend/app/modules/projects/api/guide_proposals.py
index 49c6b7d4d..3f7839c44 100644
--- a/backend/app/modules/projects/api/guide_proposals.py
+++ b/backend/app/modules/projects/api/guide_proposals.py
@@ -75,8 +75,8 @@ class GuideProposalApprovalInput(BaseModel):
 
     model_config = ConfigDict(extra="forbid", frozen=True)
     target: GuideProposalTarget
-    pre_submit_attachments: tuple[ExternalCheckerImageAttachment, ...] = Field(max_length=200)
-    post_submit_attachments: tuple[ExternalCheckerImageAttachment, ...] = Field(max_length=200)
+    pre_submit_attachments: tuple[ExternalCheckerImageAttachment, ...] = Field(min_length=1, max_length=1)
+    post_submit_attachments: tuple[ExternalCheckerImageAttachment, ...] = Field(min_length=1, max_length=1)
     acknowledged_warning_hashes: tuple[Digest, ...] = Field(default=(), max_length=200)
     expected_previous_approval_operation_id: UUID | None = None
     expected_previous_approval_output_digest: Digest | None = None
diff --git a/backend/tests/artifacts/revision_deadline_drill.py b/backend/tests/artifacts/revision_deadline_drill.py
new file mode 100644
index 000000000..0c4b82834
--- /dev/null
+++ b/backend/tests/artifacts/revision_deadline_drill.py
@@ -0,0 +1,84 @@
+"""Explicit one-hour real-clock proof: pytest -q tests/artifacts/revision_deadline_drill.py.
+
+Kept outside default test_ collection because policy windows cannot be shorter
+than one hour. Use the isolated runner with --timeout-seconds 4500. Scripted
+source/PRE transport; real acceptance, PostgreSQL clock, authority and OUTBOX T5.
+"""
+import asyncio
+from unittest.mock import patch
+
+from sqlalchemy import text
+
+from app.db import session as db_session
+from app.modules.checkers.api.execution import REQUEST_EVENT
+from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization
+from tests.submission_fixtures import seed_retained_submission, route_retained_checker_remediation
+from tests.retained_material_fixtures import finalize_retained_intake
+from tests.test_tasks import (
+    task_client, task_database_env,  # noqa: F401 -- pytest fixtures
+    create_active_project, create_started_task, complete_submission_payload, set_dev_actor,
+)
+
+
+async def test_accepted_revision_finishes_after_original_deadline(task_client, monkeypatch):  # noqa: F811
+    project = await create_active_project(task_client, revision_deadline_hours=1)
+    task = await create_started_task(task_client, project["id"], monkeypatch)
+    first = await seed_retained_submission(task["id"], complete_submission_payload())
+    await route_retained_checker_remediation(first)
+    set_dev_actor(monkeypatch, roles="worker", subject="worker-one")
+    observed = []
+
+    async def delayed(factory, intake):
+        async with factory() as session:
+            row = (await session.execute(text("""
+                SELECT o.accepted_at,p.deadline_at,o.acceptance_receipt,o.state
+                FROM submission_intake_operations o JOIN task_revision_preparations p
+                  ON p.id=(o.command_metadata->>'revision_preparation_id')::uuid WHERE o.id=:id
+            """), {"id": intake.operation_id})).one()
+        assert row.state == "finalization_pending" and row.accepted_at < row.deadline_at
+        while True:
+            async with factory() as session:
+                remaining = await session.scalar(text(
+                    "SELECT extract(epoch FROM (CAST(:deadline AS timestamptz)-clock_timestamp()))"
+                ), {"deadline": row.deadline_at})
+            if remaining <= 0:
+                break
+            await asyncio.sleep(min(30, float(remaining) + 0.01))
+        run = AcceptedSubmissionFinalization.run
+        replays = []
+
+        async def run_and_replay(finalizer, operation_id):
+            first_result = await run(finalizer, operation_id)
+            replay = await run(finalizer, operation_id)
+            assert replay == first_result
+            replays.append(operation_id)
+            return first_result
+
+        with patch.object(AcceptedSubmissionFinalization, "run", run_and_replay):
+            result = await finalize_retained_intake(factory, intake)
+        assert replays == [intake.operation_id]
+        async with factory() as session:
+            final = (await session.execute(text("""
+                SELECT o.state,o.acceptance_receipt,o.finalized_at,o.finalized_submission_id,
+                       a.status,a.consumed_by_submission_id,t.active_submission_operation_id
+                FROM submission_intake_operations o JOIN submission_bundle_admissions a
+                  ON a.id=o.finalized_admission_id JOIN workstream_tasks t ON t.id=o.task_id
+                WHERE o.id=:id
+            """), {"id": intake.operation_id})).one()
+        assert final.state == "finalized" and final.acceptance_receipt == row.acceptance_receipt
+        assert final.finalized_at >= row.deadline_at
+        assert str(final.finalized_submission_id) == result == str(final.consumed_by_submission_id)
+        assert final.status == "consumed" and final.active_submission_operation_id is None
+        observed.append(result)
+        return result
+
+    with patch("tests.submission_fixtures.finalize_retained_intake", delayed):
+        second = await seed_retained_submission(task["id"], complete_submission_payload(), predecessor_id=first)
+    assert observed == [second]
+    async with db_session.get_session_factory()() as session:
+        assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": task["id"]}) == 2
+        assert await session.scalar(text("SELECT count(*) FROM submission_dispatches WHERE submission_id=:id"), {"id": second}) == 1
+        assert await session.scalar(text("""
+            SELECT count(*) FROM outbox_events WHERE event_type=:event_type
+              AND payload->>'submission_id'=:id
+        """), {"id": second, "event_type": REQUEST_EVENT}) == 1
diff --git a/backend/tests/artifacts/test_post_source_cleanup.py b/backend/tests/artifacts/test_post_source_cleanup.py
new file mode 100644
index 000000000..dd2bdd421
--- /dev/null
+++ b/backend/tests/artifacts/test_post_source_cleanup.py
@@ -0,0 +1,120 @@
+"""Exact source readers close before failed or cancelled POST materialization returns."""
+
+import asyncio
+
+import pytest
+
+from app.modules.artifacts.preparation import ArtifactScratchIntegrityError
+from app.modules.checkers.api.materialization import PostSubmissionMaterializationFailure
+from tests.checkers.execution.support import material_execution
+from tests.post_submit_materialization_helpers import material_fixture
+
+
+class _ForbiddenConsumer:
+    def __init__(self):
+        self.calls = 0
+
+    async def evaluate(self, *_args):
+        self.calls += 1
+        pytest.fail("failed source preparation reached the consumer")
+
+
+@pytest.mark.parametrize("provider", ["local", "minio"])
+async def test_source_stream_closes_before_scratch_failure_returns(tmp_path, isolated_database_env, monkeypatch, provider):
+    from app.modules.artifacts.preparation import ArtifactScratchCapacityError
+    if provider == "minio":
+        from tests.test_s3_artifact_store import provision_minio_bucket
+        await provision_minio_bucket.__wrapped__()
+    async with material_fixture(tmp_path, isolated_database_env, provider=provider) as h:
+        execution = await material_execution(h)
+        consumer = _ForbiddenConsumer()
+        closed, written = [], []
+        original_open, original_write = h.store.open_source, h.preparation._write_chunk
+
+        async def observed_source(source, **kwargs):
+            stream = original_open(source, **kwargs)
+            try:
+                async for chunk in stream:
+                    yield chunk
+            finally:
+                await stream.aclose()
+                closed.append(source.location.operation_id)
+
+        async def failed_write(descriptor, chunk):
+            await original_write(descriptor, chunk)
+            written.append(len(chunk))
+            raise ArtifactScratchCapacityError("injected scratch exhaustion after first source chunk")
+
+        monkeypatch.setattr(h.store, "open_source", observed_source)
+        monkeypatch.setattr(h.preparation, "_write_chunk", failed_write)
+        with pytest.raises(PostSubmissionMaterializationFailure, match="material_unavailable"):
+            await h.service.materialize(execution, consumer)
+        assert len(written) == len(closed) == 1
+        assert consumer.calls == 0 and not h.preparation._active
+        assert (await h.manager.usage()).reserved_bytes == 0
+
+
+@pytest.mark.parametrize("provider", ["local", "minio"])
+async def test_source_close_drains_repeated_cancellation(tmp_path, isolated_database_env, monkeypatch, provider):
+    if provider == "minio":
+        from tests.test_s3_artifact_store import provision_minio_bucket
+        await provision_minio_bucket.__wrapped__()
+    async with material_fixture(tmp_path, isolated_database_env, provider=provider) as h:
+        execution = await material_execution(h)
+        consumer = _ForbiddenConsumer()
+        written, closing, release = asyncio.Event(), asyncio.Event(), asyncio.Event()
+        closed = []
+        original_open, original_write = h.store.open_source, h.preparation._write_chunk
+
+        async def observed_source(source, **kwargs):
+            stream = original_open(source, **kwargs)
+            try:
+                async for chunk in stream:
+                    yield chunk
+            finally:
+                closing.set()
+                await release.wait()
+                await stream.aclose()
+                closed.append(source.location.operation_id)
+
+        async def paused_write(descriptor, chunk):
+            await original_write(descriptor, chunk)
+            written.set()
+            await asyncio.Event().wait()
+
+        monkeypatch.setattr(h.store, "open_source", observed_source)
+        monkeypatch.setattr(h.preparation, "_write_chunk", paused_write)
+        operation = asyncio.create_task(h.service.materialize(execution, consumer))
+        try:
+            await asyncio.wait_for(written.wait(), 10)
+            operation.cancel()
+            await asyncio.wait_for(closing.wait(), 10)
+            operation.cancel()
+            await asyncio.sleep(0)
+            assert not operation.done()
+            release.set()
+            with pytest.raises(asyncio.CancelledError):
+                await asyncio.wait_for(operation, 10)
+            assert len(closed) == 1 and consumer.calls == 0
+            assert not h.preparation._active and (await h.manager.usage()).reserved_bytes == 0
+        finally:
+            release.set()
+            if not operation.done():
+                operation.cancel()
+            await asyncio.gather(operation, return_exceptions=True)
+
+
+@pytest.mark.parametrize("failure", [RuntimeError, asyncio.CancelledError])
+async def test_unconfirmed_source_close_is_integrity_failure(failure):
+    from app.modules.artifacts.post_submit_materialization import _close_source_stream
+
+    async def source():
+        try:
+            yield b"source"
+        finally:
+            raise failure("injected source close failure")
+
+    stream = source()
+    assert await anext(stream) == b"source"
+    with pytest.raises(ArtifactScratchIntegrityError, match="source stream cleanup is unconfirmed"):
+        await _close_source_stream(stream)
diff --git a/backend/tests/artifacts/test_post_source_manifest.py b/backend/tests/artifacts/test_post_source_manifest.py
new file mode 100644
index 000000000..224be128c
--- /dev/null
+++ b/backend/tests/artifacts/test_post_source_manifest.py
@@ -0,0 +1,44 @@
+"""POST inspection must agree with accepted source semantics before export."""
+
+from dataclasses import replace
+
+import pytest
+
+from app.modules.checkers.api.materialization import PostSubmissionMaterializationFailure
+from tests.checkers.execution.support import material_execution
+from tests.post_submit_materialization_helpers import material_fixture
+
+
+async def test_inspected_source_semantics_must_match_accepted_manifest(
+    tmp_path, isolated_database_env, monkeypatch,
+):
+    async with material_fixture(tmp_path, isolated_database_env) as h:
+        execution = await material_execution(h)
+        inspect = h.inspector.inspect
+        observed = []
+
+        def changed_inspection(reader):
+            actual = inspect(reader)
+            changed = tuple(
+                replace(entry, executable=False) if entry.normalized_path == "run.sh" else entry
+                for entry in actual.entries
+            )
+            assert changed != actual.entries
+            observed.append(actual)
+            return replace(actual, entries=changed)
+
+        def forbidden_export(*args, **kwargs):
+            pytest.fail("manifest disagreement reached material export")
+
+        class Consumer:
+            async def evaluate(self, *args):
+                pytest.fail("manifest disagreement reached the consumer")
+
+        monkeypatch.setattr(h.inspector, "inspect", changed_inspection)
+        monkeypatch.setattr(h.inspector, "_projected_tree", forbidden_export)
+        with pytest.raises(PostSubmissionMaterializationFailure, match="manifest_mismatch"):
+            await h.service.materialize(execution, Consumer())
+        assert len(observed) == len(h.store.opens) == 1
+        assert not h.preparation._active
+        assert (await h.manager.usage()).reserved_bytes == 0
+        assert list((h.scratch / "workspaces").iterdir()) == []
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index 64e7544b6..babe625c0 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -24,6 +24,7 @@
     rsa_signing_material as rsa_signing_material,
 )
 from tests.artifacts.intake_recovery_support import recovery_intake as recovery_intake
+from tests.historical_policy_fixtures import historical_policy_intake as historical_policy_intake
 from tests.authorization.admin_access.fixtures import (
     signed_access as signed_access,
     admin_access as admin_access,
@@ -53,10 +54,6 @@ async def test_stalled_accepted_source_is_protected_from_cleanup(recovery_intake
 @pytest.fixture
 async def admission_intake(tmp_path, isolated_database_env, admin_access, request):
     from sqlalchemy import text
-    from app.adapters.outbox import outbox_append, finalized_unknown_deliveries
-    from app.adapters.projects import project_locked_policy_context_port
-    from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission
-    from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization
     from tests.authorization.task_authority.test_postgresql import context, grant, project_manager
 
     engine = create_async_engine(isolated_database_env)
@@ -83,8 +80,8 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
         from tests.checkers.external.support import pre_registry_spec, post_registry_spec
         plan, _ = await approved_selected_policy_fixture(
             factory, namespace, guide_version="v1",
-            pre_submit_registry_spec=None if getattr(request, "param", None) == "no_pre" else pre_registry_spec(),
-            post_submit_registry_spec=None if getattr(request, "param", None) == "no_post" else post_registry_spec(),
+            pre_submit_registry_spec=pre_registry_spec(),
+            post_submit_registry_spec=post_registry_spec(),
         )
         project = plan.lineage.project_id
         manager = await project_manager(admin_access, project)
@@ -99,14 +96,7 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
             await connection.execute(text(
                 "UPDATE task_assignments SET accepted_at=clock_timestamp() WHERE id=:id"
             ), {"id": assignment})
-        admission = ForegroundIntakeAdmission(
-            factory, tasks=lambda session: IntakeTaskCustody(session, task_submission_context_port(session)),
-            task_contexts=task_submission_context_port, projects=project_locked_policy_context_port,
-            authorization=lambda session: SubmissionIntakeAuthorization(session, actor), namespace=namespace,
-            events=outbox_append, deliveries=finalized_unknown_deliveries,
-            capacity_limits=SubmissionSourceCapacityLimits(maximum_total_bytes=1_000_000), maximum_raw_bytes=1024,
-            upload_duration=timedelta(seconds=300), lease_duration=timedelta(seconds=60),
-        )
+        admission = intake_admission(factory, actor, namespace)
         yield SimpleNamespace(factory=factory, actor=actor, task=task, assignment=assignment,
                               admission=admission, project=project, namespace=namespace,
                               access=admin_access, manager=manager, grant_id=grant_id,
@@ -115,6 +105,22 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
         await engine.dispose()
 
 
+def intake_admission(factory, actor, namespace):
+    """Compose the same T1 owner for current and faithfully restored contexts."""
+    from app.adapters.outbox import outbox_append, finalized_unknown_deliveries
+    from app.adapters.projects import project_locked_policy_context_port
+    from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission
+    from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization
+    return ForegroundIntakeAdmission(
+        factory, tasks=lambda session: IntakeTaskCustody(session, task_submission_context_port(session)),
+        task_contexts=task_submission_context_port, projects=project_locked_policy_context_port,
+        authorization=lambda session: SubmissionIntakeAuthorization(session, actor), namespace=namespace,
+        events=outbox_append, deliveries=finalized_unknown_deliveries,
+        capacity_limits=SubmissionSourceCapacityLimits(maximum_total_bytes=1_000_000), maximum_raw_bytes=1024,
+        upload_duration=timedelta(seconds=300), lease_duration=timedelta(seconds=60),
+    )
+
+
 async def admit_new(fixture, *, key=None, metadata=None):
     return await fixture.admission.admit(
         metadata or SubmissionIntakeMetadata(task_id=fixture.task, assignment_id=fixture.assignment),
@@ -341,11 +347,13 @@ async def record_intake_eof(f, owner, payload):
                          raw_sha256="sha256:" + hashlib.sha256(payload).hexdigest(), raw_byte_count=len(payload))
 
 
-@pytest.mark.parametrize("admission_intake", ["no_pre", "no_post"], indirect=True)
-async def test_t1_requires_one_selected_checker_in_each_phase(admission_intake):
+@pytest.mark.postgres_schema_contract
+@pytest.mark.parametrize("historical_policy_intake", ["no_pre", "no_post"], indirect=True)
+async def test_t1_requires_one_selected_checker_in_each_phase(historical_policy_intake):
     from sqlalchemy import func, select
     from app.modules.tasks.models import WorkstreamTask, AuditEvent
-    f = admission_intake
+    f = historical_policy_intake
+    f.admission = intake_admission(f.factory, f.actor, f.namespace)
     with pytest.raises(IntakeCustodyConflict, match="intake_requires_one_pre_and_post_checker"):
         await admit_new(f)
     async with f.factory() as session:
diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py
index 870def557..48c50daa5 100644
--- a/backend/tests/artifacts/test_submission_intake_custody.py
+++ b/backend/tests/artifacts/test_submission_intake_custody.py
@@ -48,7 +48,7 @@ async def intake(tmp_path, isolated_database_env, capacity_limits, request):
         from tests.checkers.external.support import pre_registry_spec
         plan, _ = await approved_selected_policy_fixture(
             factory, _namespace(_settings(tmp_path)), guide_version="v1",
-            pre_submit_registry_spec=pre_registry_spec() if getattr(request, "param", False) else None,
+            pre_submit_registry_spec=pre_registry_spec(),
         )
         actor = _context()
         async with factory.begin() as session:
diff --git a/backend/tests/authorization/guide_proposals/test_postgresql.py b/backend/tests/authorization/guide_proposals/test_postgresql.py
index a9e55f83e..5bf5f4677 100644
--- a/backend/tests/authorization/guide_proposals/test_postgresql.py
+++ b/backend/tests/authorization/guide_proposals/test_postgresql.py
@@ -115,7 +115,7 @@ async def evidence_state(factory):
 
 @pytest.mark.parametrize("action", ["approve", "correct"])
 async def test_real_proposal_transaction_replay_and_revocation(clean_postgres_database, action):
-    async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant):
+    async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant):
         review = await package(factory, command, actor)
         before_events, before_finalizations = await evidence_state(factory)
         assert len(before_events) == 1
@@ -123,7 +123,7 @@ async def test_real_proposal_transaction_replay_and_revocation(clean_postgres_da
         assert before_events[0]["resource_id"] == str(command.compilation_id)
         payload = (
             GuideProposalApproval(
-                pre_submit_attachments=(), post_submit_attachments=(),
+                pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"],
                 target=review.target,
                 idempotency_key=uuid4(),
                 acknowledged_warning_hashes=review.warning_hashes,
@@ -166,7 +166,7 @@ async def test_real_proposal_transaction_replay_and_revocation(clean_postgres_da
 async def test_real_authority_denial_has_no_product_or_allowed_writes(
     clean_postgres_database, action, authority
 ):
-    async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant):
+    async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant):
         review = await package(factory, command, actor)
         before = await evidence_state(factory)
         if authority == "revoked":
@@ -197,7 +197,7 @@ async def test_real_authority_denial_has_no_product_or_allowed_writes(
                     factory,
                     actor,
                     GuideProposalApproval(
-                pre_submit_attachments=(), post_submit_attachments=(),
+                pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"],
                         target=review.target,
                         idempotency_key=uuid4(),
                         acknowledged_warning_hashes=review.warning_hashes,
diff --git a/backend/tests/checkers/execution/completion_fixture.py b/backend/tests/checkers/execution/completion_fixture.py
index 8f3aeafbe..33e1a05ff 100644
--- a/backend/tests/checkers/execution/completion_fixture.py
+++ b/backend/tests/checkers/execution/completion_fixture.py
@@ -33,7 +33,7 @@ async def completed_evidence(
     async with material_fixture(
         tmp_path,
         database_url,
-        post_submit_registry_spec=post_registry_spec() if failed or findings else None,
+        post_submit_registry_spec=post_registry_spec(),
         **options,
     ) as h:
         await reserve(h)
diff --git a/backend/tests/checkers/execution/storage_fixture.py b/backend/tests/checkers/execution/storage_fixture.py
index 64e861eb9..dc8adace3 100644
--- a/backend/tests/checkers/execution/storage_fixture.py
+++ b/backend/tests/checkers/execution/storage_fixture.py
@@ -34,6 +34,12 @@ class _UnavailableArchiveStore:
     def __init__(self, store):
         self.identity = store.identity
 
+    async def open_source(self, _source, **_kwargs):
+        from app.interfaces.artifacts import ArtifactStoreUnavailableError
+
+        raise ArtifactStoreUnavailableError()
+        yield  # Preserve the async source stream port for infrastructure failures.
+
     async def open(self, _ref, byte_range=None, **_kwargs):
         from app.interfaces.artifacts import ArtifactStoreUnavailableError
 
diff --git a/backend/tests/checkers/execution/test_execution.py b/backend/tests/checkers/execution/test_execution.py
index 6ccd60c8b..f066ce3fc 100644
--- a/backend/tests/checkers/execution/test_execution.py
+++ b/backend/tests/checkers/execution/test_execution.py
@@ -49,17 +49,23 @@ async def test_verified_material_execution_and_replay(
     async with material_fixture(tmp_path, isolated_database_env, provider=provider) as h:
         reservation = await reserve(h)
         receipts = []
+        material_errors = []
         materialize = h.service.materialize
 
         async def observe_receipt(*args, **kwargs):
-            value = await materialize(*args, **kwargs)
+            try:
+                value = await materialize(*args, **kwargs)
+            except Exception:
+                import traceback
+                material_errors.append(traceback.format_exc())
+                raise
             receipts.append(value.input_materialization_evidence_id)
             return value
 
         monkeypatch.setattr(h.service, "materialize", observe_receipt)
         executor = live_executor(h)
         result = await executor.evaluate_post_submission(h.request)
-        assert result.outcome == "completed"
+        assert result.outcome == "completed", "\n".join(material_errors) or result
         assert (
             result.attempt_id == reservation.attempt_id
             and result.result_id == reservation.result_id
@@ -107,7 +113,7 @@ async def observe_receipt(*args, **kwargs):
             assert tuple(row.checker_name for row in rows) == tuple(
                 m.requirement_id for m in result.execution.external_members
             )
-            assert len(rows) == len(h.request.policy.entries) == 0
+            assert len(rows) == len(h.request.policy.entries) == 1
             event = await session.scalar(
                 select(OutboxEvent).where(OutboxEvent.event_type == COMPLETION_EVENT)
             )
diff --git a/backend/tests/checkers/external/test_policy.py b/backend/tests/checkers/external/test_policy.py
index d4ef72882..47ed62b41 100644
--- a/backend/tests/checkers/external/test_policy.py
+++ b/backend/tests/checkers/external/test_policy.py
@@ -186,32 +186,36 @@ def _model_profile(project_id, entry) -> ProjectModelProfile:
     )
 
 
-@pytest.mark.asyncio
-async def test_explicit_empty_attachments_compile_only_the_default_pre():
-    registry = _Registry(())
-    pre, post = await compile_external_checker_policies(_request(), registry)
-    assert pre.workstream_default.checker_id == "workstream.default"
-    assert pre.entries == () and post.entries == ()
-    assert registry.calls == []
+@pytest.mark.parametrize("phase", ["pre", "post"])
+@pytest.mark.parametrize("count", [0, 2])
+def test_new_policy_requires_exactly_one_image_per_phase(phase, count):
+    pre_entry = _entry("acme.safe_archive", "pre_submit")
+    post_entry = _entry("acme.quality_review", "post_submit")
+    members = {
+        "pre": (_attachment(pre_entry, "archive"),),
+        "post": (_attachment(post_entry, "quality"),),
+    }
+    entry = pre_entry if phase == "pre" else post_entry
+    members[phase] = tuple(_attachment(entry, f"member_{i}") for i in range(count))
+    with pytest.raises(ValueError):
+        _request(**members)
 
 
 @pytest.mark.asyncio
-async def test_human_phase_attachments_use_exact_registry_rows_and_allow_reused_image():
+async def test_human_phase_attachments_resolve_exactly_one_registry_row_each():
     pre_entry = _entry("acme.safe_archive", "pre_submit")
     post_entry = _entry("acme.quality_review", "post_submit")
     registry = _Registry((pre_entry, post_entry))
     request = _request(
-        pre=(_attachment(pre_entry, "archive_a"), _attachment(pre_entry, "archive_b")),
+        pre=(_attachment(pre_entry, "archive"),),
         post=(_attachment(post_entry, "quality"),),
     )
     pre, post = await compile_external_checker_policies(request, registry)
-    assert [item.requirement_id for item in pre.entries] == ["archive_a", "archive_b"]
-    assert [item.registry.registry_entry_id for item in pre.entries] == [
-        pre_entry.registry_entry_id, pre_entry.registry_entry_id,
-    ]
+    assert pre.workstream_default.checker_id == "workstream.default"
+    assert [item.requirement_id for item in pre.entries] == ["archive"]
+    assert [item.registry.registry_entry_id for item in pre.entries] == [pre_entry.registry_entry_id]
     assert [item.requirement_id for item in post.entries] == ["quality"]
     assert registry.calls == [
-        (pre_entry.registry_entry_id, pre_entry.entry_digest),
         (pre_entry.registry_entry_id, pre_entry.entry_digest),
         (post_entry.registry_entry_id, post_entry.entry_digest),
     ]
@@ -220,8 +224,9 @@ async def test_human_phase_attachments_use_exact_registry_rows_and_allow_reused_
 @pytest.mark.parametrize("keys", [("same", "same"), ("z", "a")])
 def test_duplicate_or_unsorted_human_member_keys_are_rejected(keys):
     entry = _entry("acme.safe_archive", "pre_submit")
-    with pytest.raises(ValueError, match="unique canonical"):
-        _request(pre=tuple(_attachment(entry, key) for key in keys))
+    with pytest.raises(ValueError, match="at most 1 item"):
+        _request(pre=tuple(_attachment(entry, key) for key in keys),
+                 post=(_attachment(_entry("acme.post", "post_submit"), "quality"),))
 
 
 def test_platform_default_member_key_is_reserved():
@@ -237,18 +242,18 @@ async def test_missing_digest_and_wrong_phase_fail_before_policy_creation():
     missing = _Registry(())
     with pytest.raises(ValueError, match="unavailable"):
         await compile_external_checker_policies(
-            _request(pre=(_attachment(pre_entry, "archive"),)), missing,
+            _request(pre=(_attachment(pre_entry, "archive"),), post=(_attachment(post_entry, "quality"),)), missing,
         )
     with pytest.raises(ValueError, match="phase mismatch"):
         await compile_external_checker_policies(
-            _request(pre=(_attachment(post_entry, "archive"),)), _Registry((post_entry,)),
+            _request(pre=(_attachment(post_entry, "archive"),), post=(_attachment(post_entry, "quality"),)), _Registry((post_entry,)),
         )
     wrong_digest = _attachment(pre_entry, "archive").model_copy(
         update={"registry_entry_digest": "sha256:" + "0" * 64}
     )
     with pytest.raises(ValueError, match="unavailable"):
         await compile_external_checker_policies(
-            _request(pre=(wrong_digest,)), _Registry((pre_entry,)),
+            _request(pre=(wrong_digest,), post=(_attachment(post_entry, "quality"),)), _Registry((pre_entry,)),
         )
 
 
@@ -262,20 +267,22 @@ async def test_configuration_is_schema_checked_and_exact_json_is_locked():
         schema_sha256=external_checker_json_hash(document),
     )
     entry = _entry("acme.safe_archive", "pre_submit", schema)
+    post = _entry("acme.post", "post_submit")
     pre, _ = await compile_external_checker_policies(
-        _request(pre=(_attachment(entry, "archive", {"groups": ["a", "b"]}),)),
-        _Registry((entry,)),
+        _request(pre=(_attachment(entry, "archive", {"groups": ["a", "b"]}),), post=(_attachment(post, "quality"),)),
+        _Registry((entry, post)),
     )
     assert pre.entries[0].configuration == {"groups": ["a", "b"]}
     with pytest.raises(ValueError, match="value is invalid"):
         await compile_external_checker_policies(
-            _request(pre=(_attachment(entry, "archive", {"groups": [1]}),)),
-            _Registry((entry,)),
+            _request(pre=(_attachment(entry, "archive", {"groups": [1]}),), post=(_attachment(post, "quality"),)),
+            _Registry((entry, post)),
         )
 
 
 @pytest.mark.asyncio
 async def test_model_profile_configuration_requires_exact_project_scope():
+    pre = _entry("acme.pre", "pre_submit")
     project_id = new_record_id()
     entry = _entry("acme.quality_review", "post_submit", _model_configuration_schema())
     profile = _model_profile(project_id, entry)
@@ -286,39 +293,86 @@ async def test_model_profile_configuration_requires_exact_project_scope():
     }
     profiles = _Profiles(profile)
     _, post = await compile_external_checker_policies(
-        _request(post=(_attachment(entry, "quality", config),)),
-        _Registry((entry,)), project_id=project_id, profiles=profiles,
+        _request(pre=(_attachment(pre, "archive"),), post=(_attachment(entry, "quality", config),)),
+        _Registry((pre, entry)), project_id=project_id, profiles=profiles,
     )
     assert post.entries[0].configuration == config
     assert profiles.calls[0][1] == {"project_id": project_id}
     with pytest.raises(ValueError):
         await compile_external_checker_policies(
-            _request(post=(_attachment(entry, "quality", config),)),
-            _Registry((entry,)), project_id=new_record_id(), profiles=profiles,
+            _request(pre=(_attachment(pre, "archive"),), post=(_attachment(entry, "quality", config),)),
+            _Registry((pre, entry)), project_id=new_record_id(), profiles=profiles,
         )
     with pytest.raises(ValueError):
         await compile_external_checker_policies(
-            _request(post=(_attachment(entry, "quality", {"model_profile_id": config["model_profile_id"]}),)),
-            _Registry((entry,)), project_id=project_id, profiles=profiles,
+            _request(pre=(_attachment(pre, "archive"),), post=(_attachment(entry, "quality", {"model_profile_id": config["model_profile_id"]}),)),
+            _Registry((pre, entry)), project_id=project_id, profiles=profiles,
         )
 
 
 @pytest.mark.asyncio
-async def test_aggregate_pre_and_post_budgets_reject_unrunnable_images():
-    pre_a = _entry("acme.a", "pre_submit", deadline_ms=3_600_000)
-    pre_b = _entry("acme.b", "pre_submit", deadline_ms=3_600_000)
+async def test_retained_pre_and_new_post_budgets_reject_unrunnable_images():
+    from app.modules.checkers.api.external_policy import validate_stored_external_pre_policy
+
+    pre_entry = _entry("acme.pre", "pre_submit", deadline_ms=3_600_000)
+    post_entry = _entry("acme.post", "post_submit")
+    pre, _ = await compile_external_checker_policies(
+        _request(pre=(_attachment(pre_entry, "a"),), post=(_attachment(post_entry, "p"),)),
+        _Registry((pre_entry, post_entry)),
+    )
+    # Retained multi-image evidence keeps its original aggregate budget guard.
+    body = pre.model_dump(mode="json", exclude={"policy_sha256"})
+    body["entries"].append(body["entries"][0] | {"requirement_id": "b"})
     with pytest.raises(ValueError, match="ART custody deadline"):
-        await compile_external_checker_policies(
-            _request(pre=(_attachment(pre_a, "a"), _attachment(pre_b, "b"))),
-            _Registry((pre_a, pre_b)),
-        )
+        validate_stored_external_pre_policy(body | {"policy_sha256": canonical_json_hash(body)})
     post = _entry("acme.post", "post_submit", deadline_ms=3_600_000)
     with pytest.raises(ValueError, match="durable worker deadline"):
         await compile_external_checker_policies(
-            _request(post=(_attachment(post, "p"),)), _Registry((post,)),
+            _request(pre=(_attachment(pre_entry, "a"),), post=(_attachment(post, "p"),)),
+            _Registry((pre_entry, post)),
         )
 
 
+@pytest.mark.asyncio
+@pytest.mark.parametrize("count", [0, 2])
+async def test_historical_phase_cardinality_preserves_exact_locked_evidence(count):
+    from app.modules.checkers.api.external_policy import validate_stored_external_pre_policy
+
+    pre_entry = _entry("acme.pre", "pre_submit")
+    post_entry = _entry("acme.post", "post_submit")
+    pre, post = await compile_external_checker_policies(
+        _request(pre=(_attachment(pre_entry, "a"),), post=(_attachment(post_entry, "p"),)),
+        _Registry((pre_entry, post_entry)),
+    )
+    for policy, decode in ((pre, validate_stored_external_pre_policy),
+                           (post, validate_stored_external_post_policy)):
+        body = policy.model_dump(mode="json", exclude={"policy_sha256"})
+        member = body["entries"][0]
+        body["entries"] = [member | {"requirement_id": f"member_{i}"} for i in range(count)]
+        retained = body | {"policy_sha256": canonical_json_hash(body)}
+        assert decode(retained).model_dump(mode="json") == retained
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("phase", ["pre", "post"])
+@pytest.mark.parametrize("keys,reason", [(("a", "a"), "duplicated"), (("b", "a"), "not canonical")])
+async def test_retained_policy_rejects_duplicate_or_reordered_members_even_with_matching_hash(phase, keys, reason):
+    from app.modules.checkers.api.external_policy import validate_stored_external_pre_policy
+
+    pre_entry = _entry("acme.pre", "pre_submit")
+    post_entry = _entry("acme.post", "post_submit")
+    pre, post = await compile_external_checker_policies(
+        _request(pre=(_attachment(pre_entry, "a"),), post=(_attachment(post_entry, "p"),)),
+        _Registry((pre_entry, post_entry)),
+    )
+    policy, decode = ((pre, validate_stored_external_pre_policy) if phase == "pre"
+                      else (post, validate_stored_external_post_policy))
+    body = policy.model_dump(mode="json", exclude={"policy_sha256"})
+    body["entries"] = [body["entries"][0] | {"requirement_id": key} for key in keys]
+    with pytest.raises(ValueError, match=reason):
+        decode(body | {"policy_sha256": canonical_json_hash(body)})
+
+
 def test_locked_default_refuses_substituted_behavior_digest():
     with pytest.raises(ValueError, match="behavior"):
         LockedWorkstreamDefault(behavior_sha256="sha256:" + "0" * 64)
@@ -466,21 +520,23 @@ def test_retained_forge_policy_without_locator_declaration_preserves_locked_json
     compile_external_checker_policy_bundle,
 ])
 async def test_new_forge_binding_without_locator_declaration_cannot_compile(compiler):
+    pre = _entry("acme.pre", "pre_submit")
     binding = _forge_binding(_FORGE_SELECTION, locator_declared=False)
     entry = binding.registry
-    request = _request(post=(_attachment(entry, binding.requirement_id, _FORGE_SELECTION),))
+    request = _request(pre=(_attachment(pre, "archive"),), post=(_attachment(entry, binding.requirement_id, _FORGE_SELECTION),))
 
     with pytest.raises(ExternalCheckerPolicyError, match="does not declare forge locator"):
-        await compiler(request, _Registry((entry,)))
+        await compiler(request, _Registry((pre, entry)))
 
 
 @pytest.mark.asyncio
 async def test_new_forge_binding_with_locator_declaration_compiles_in_approval_bundle():
+    pre = _entry("acme.pre", "pre_submit")
     binding = _forge_binding(_FORGE_SELECTION)
     entry = binding.registry
-    request = _request(post=(_attachment(entry, binding.requirement_id, _FORGE_SELECTION),))
+    request = _request(pre=(_attachment(pre, "archive"),), post=(_attachment(entry, binding.requirement_id, _FORGE_SELECTION),))
 
-    policies = await compile_external_checker_policy_bundle(request, _Registry((entry,)))
+    policies = await compile_external_checker_policy_bundle(request, _Registry((pre, entry)))
 
     assert policies.post_submit.entries == (binding,)
     assert policies.post_submit.entries[0].registry.entry_digest == entry.entry_digest
diff --git a/backend/tests/checkers/external/test_revision_materialization.py b/backend/tests/checkers/external/test_revision_materialization.py
index 5c09a99b3..94714f425 100644
--- a/backend/tests/checkers/external/test_revision_materialization.py
+++ b/backend/tests/checkers/external/test_revision_materialization.py
@@ -1,67 +1,13 @@
 """Approved revision inputs through real TASK/CHECKERS/ART and bounded scratch."""
 
 import json
-from contextlib import asynccontextmanager
 
 import pytest
 
-from app.adapters.checkers import evaluation_coordinator
 from app.core.identifiers import new_record_id
 from app.modules.artifacts.preparation import HARD_MAXIMUM_ARTIFACT_BYTES
-from app.modules.checkers.api.external import ExternalCheckerSchema, external_checker_json_hash
-from app.modules.checkers.api.external_policy import (
-    EVALUATION_CONTEXT_ROLES_KEY as ROLES,
-    EVALUATION_CONTEXT_VERSION_KEY as VERSION,
-)
 from tests.checkers.execution.support import ControlledSelectedExecution, live_executor
-from tests.checkers.external.support import post_registry_spec
-from tests.tasks.post_submit_routing.remediation_support import remediation_source
-from tests.tasks.post_submit_routing.support import revision_archive
-from tests.tasks.submission_dispatch.test_replacement_creation import (
-    _create, _creation_request, _ready_replacement,
-)
-from tests.test_submission_predecessor_custody import _fixture_revision_context
-from tests.test_checker_materialization import _limits
-
-
-def _approved_context_proposal(monkeypatch, roles):
-    """Select exact human-approved revision inputs; proposal output is unchanged."""
-    from tests.projects.guide_activation import source_fixtures
-    from tests.checkers.execution import completion_fixture
-
-    original = completion_fixture.material_fixture
-    document = {
-        "type": "object",
-        "properties": {VERSION: {"const": "v1"}, ROLES: {"type": "array", "items": {"type": "string"}}},
-        "additionalProperties": False,
-    }
-    spec = post_registry_spec()
-    spec = type(spec).model_validate(spec.model_copy(update={
-        "configuration_schema": ExternalCheckerSchema(
-            schema_id="revision_context_config", schema_version="v1", document=document,
-            schema_sha256=external_checker_json_hash(document),
-        ),
-    }).model_dump())
-
-    async def configurations(_factory, _project, _registry):
-        return (
-            source_fixtures.PostSubmitAttachmentCase(
-                requirement_id="project.post_submit",
-                configuration={VERSION: "v1", ROLES: list(roles)},
-            ),
-            source_fixtures.PostSubmitAttachmentCase(
-                requirement_id="project.z_current_only", configuration={},
-            ),
-        )
-
-    @asynccontextmanager
-    async def selected_material(*args, **kwargs):
-        kwargs["post_submit_configurations_setup"] = configurations
-        async with original(*args, **kwargs) as fixture:
-            yield fixture
-
-    monkeypatch.setattr(completion_fixture, "material_fixture", selected_material)
-    monkeypatch.setattr(completion_fixture, "post_registry_spec", lambda: spec)
+from tests.historical_revision_material_fixtures import historical_revision_material as historical_revision_material
 
 
 class InspectingExecution(ControlledSelectedExecution):
@@ -101,128 +47,104 @@ async def materialize(self, facts, consumer):
             raise AssertionError("expected successful revision materialization") from cause
 
 
+@pytest.mark.postgres_schema_contract
 @pytest.mark.parametrize("roles", [
     ("predecessor_findings",),
     ("predecessor_submission_archive",),
     ("predecessor_findings", "predecessor_submission_archive"),
 ])
 async def test_revision_reads_exact_previous_material_with_per_binding_visibility(
-    tmp_path, isolated_database_env, monkeypatch, roles,
+    historical_revision_material, roles,
 ):
-    """Initial and revised evidence remain exact across two grants and replay."""
-    _approved_context_proposal(monkeypatch, roles)
-    from tests.test_s3_artifact_store import provision_minio_bucket
-
-    await provision_minio_bucket.__wrapped__()
-    # This composed journey includes two stored archives and two image grants.
-    # Match the production aggregate allowance: two archive reservations plus
-    # their bounded extraction workspace must coexist. The smaller one-archive
-    # unit fixture has no room left for extraction after reserving a predecessor.
-    # Dedicated capacity and deadline tests retain the rejection/cleanup proof.
-    async with remediation_source(
-        tmp_path, isolated_database_env, provider="minio",
-        scratch_limits=_limits(
-            aggregate_reserved_bytes=4 * HARD_MAXIMUM_ARTIFACT_BYTES,
-            maximum_files=8, maximum_concurrency=4,
-            total_deadline_seconds=60.0, reservation_ttl_seconds=120.0,
-        ),
-    ) as h:
-        first_result, first_submission = h.result, h.created
-        assert first_result.execution.external_members[0].input_receipt is not None
-        assert first_result.execution.external_members[1].input_receipt is None
-        await _fixture_revision_context(h)
-        prepared, admission_id = await _ready_replacement(h, revision_archive(h.data))
-        created = await _create(h, _creation_request(h, prepared, admission_id))
-        async with h.factory() as session, session.begin():
-            envelope = await evaluation_coordinator(session).read_reserved_evaluation(
-                project_id=h.request.project_id, task_id=h.request.task_id,
-                submission_id=created.submission_id, request_id=created.evaluation_request_id,
-            )
-        h.request = envelope.request
-        h.service = DiagnosticMaterialization(h.service)
-        adapter = InspectingExecution(h.scratch)
-        executor = live_executor(h, selected_execution=adapter)
-        h.store.opens.clear()
-        completed = await executor.evaluate_post_submission(h.request)
-        assert completed.outcome == "completed", completed.model_dump_json()
-        assert len(h.store.opens) == 1 + int("predecessor_submission_archive" in roles)
-        assert len(adapter.requests) == 2
-        scoped, current_only = adapter.requests
-        context = scoped.input["evaluation_context"]
-        assert context["kind"] == "checker_remediation"
-        assert context["predecessor"]["submission_id"] == str(first_submission.submission_id)
-        assert context["source"]["preparation_id"] == str(h.revision_preparation_id)
-        assert context["source"]["evaluation"]["result_digest"] == first_result.result_digest
-        if "predecessor_findings" in roles:
-            feedback = context["feedback"]
-            assert feedback["source"]["result"]["result_digest"] == first_result.result_digest
-            assert feedback["members"][0]["findings"][0]["code"] == "post_evidence_failed"
-        else:
-            assert context["feedback"] is None
-        expected_roles = ["submission_archive"]
-        if "predecessor_submission_archive" in roles:
-            expected_roles.append("predecessor_submission_archive")
-            assert scoped.materials[1].submission_id == first_submission.submission_id
-        assert [item.role for item in scoped.materials] == expected_roles
-        assert "evaluation_context" not in current_only.input
-        assert len(current_only.materials) == 1
-        assert adapter.manifests[1]["visible_roles"] == ["submission_archive"]
-        assert adapter.manifests[1]["evaluation_context_sha256"] is None
-        from sqlalchemy import text
-        from sqlalchemy.exc import IntegrityError
-
+    """Drain retained two-binding POST without changing exact visibility or replay."""
+    h = historical_revision_material
+    first_result, first_submission = h.first_result, h.first_submission
+    assert first_result.execution.external_members[0].input_receipt is not None
+    assert first_result.execution.external_members[1].input_receipt is None
+    h.service = DiagnosticMaterialization(h.service)
+    adapter = InspectingExecution(h.scratch)
+    executor = live_executor(h, selected_execution=adapter)
+    h.store.opens.clear()
+    completed = await executor.evaluate_post_submission(h.request)
+    assert completed.outcome == "completed", completed.model_dump_json()
+    assert len(h.store.opens) == 1 + int("predecessor_submission_archive" in roles)
+    assert len(adapter.requests) == 2
+    scoped, current_only = adapter.requests
+    context = scoped.input["evaluation_context"]
+    assert context["kind"] == "checker_remediation"
+    assert context["predecessor"]["submission_id"] == str(first_submission.submission_id)
+    assert context["source"]["preparation_id"] == str(h.revision_preparation_id)
+    assert context["source"]["evaluation"]["result_digest"] == first_result.result_digest
+    if "predecessor_findings" in roles:
+        feedback = context["feedback"]
+        assert feedback["source"]["result"]["result_digest"] == first_result.result_digest
+        assert feedback["members"][0]["findings"][0]["code"] == "post_evidence_failed"
+    else:
+        assert context["feedback"] is None
+    expected_roles = ["submission_archive"]
+    if "predecessor_submission_archive" in roles:
+        expected_roles.append("predecessor_submission_archive")
+        assert scoped.materials[1].submission_id == first_submission.submission_id
+    assert [item.role for item in scoped.materials] == expected_roles
+    assert "evaluation_context" not in current_only.input
+    assert len(current_only.materials) == 1
+    assert adapter.manifests[1]["visible_roles"] == ["submission_archive"]
+    assert adapter.manifests[1]["evaluation_context_sha256"] is None
+    from sqlalchemy import text
+    from sqlalchemy.exc import IntegrityError
+
+    async with h.factory() as session:
+        retained = (await session.execute(text(
+            "SELECT input_context_custody,public.checker_input_receipt_valid(r) AS valid "
+            "FROM public.checker_runs r WHERE id=:id"
+        ), {"id": completed.attempt_id})).one()
+        assert retained.valid is True
+        assert retained.input_context_custody["evaluation_context"] == context
+        assert (retained.input_context_custody["predecessor"] is not None) == (
+            "predecessor_submission_archive" in roles
+        )
+    if "predecessor_findings" in roles:
+        # Validate the SQL predicate directly on detached candidate values:
+        # immutable-row guards alone must not hide an incomplete witness.
         async with h.factory() as session:
-            retained = (await session.execute(text(
-                "SELECT input_context_custody,public.checker_input_receipt_valid(r) AS valid "
-                "FROM public.checker_runs r WHERE id=:id"
-            ), {"id": completed.attempt_id})).one()
-            assert retained.valid is True
-            assert retained.input_context_custody["evaluation_context"] == context
-            assert (retained.input_context_custody["predecessor"] is not None) == (
-                "predecessor_submission_archive" in roles
-            )
-        if "predecessor_findings" in roles:
-            # Validate the SQL predicate directly on detached candidate values:
-            # immutable-row guards alone must not hide an incomplete witness.
-            async with h.factory() as session:
-                for replacement in ("'null'::jsonb", "to_jsonb(CAST('wrong' AS text))"):
-                    valid = await session.scalar(text(
-                        "SELECT public.checker_input_context_valid(jsonb_populate_record("
-                        "NULL::public.checker_runs,jsonb_set(to_jsonb(r),"
-                        "'{input_context_custody,evaluation_context,feedback,source,result,schema_version}',"
-                        + replacement + "))) FROM public.checker_runs r WHERE id=:id"
-                    ), {"id": completed.attempt_id})
-                    assert valid is False
-                missing = await session.scalar(text(
+            for replacement in ("'null'::jsonb", "to_jsonb(CAST('wrong' AS text))"):
+                valid = await session.scalar(text(
                     "SELECT public.checker_input_context_valid(jsonb_populate_record("
-                    "NULL::public.checker_runs,to_jsonb(r) #- "
-                    "'{input_context_custody,evaluation_context,feedback,source,result,schema_version}')) "
-                    "FROM public.checker_runs r WHERE id=:id"
+                    "NULL::public.checker_runs,jsonb_set(to_jsonb(r),"
+                    "'{input_context_custody,evaluation_context,feedback,source,result,schema_version}',"
+                    + replacement + "))) FROM public.checker_runs r WHERE id=:id"
                 ), {"id": completed.attempt_id})
-                assert missing is False
-        for expression in (
-            "NULL",
-            "jsonb_set(input_context_custody,'{evaluation_context,source,preparation_sha256}',to_jsonb(CAST(:wrong AS text)))",
-        ):
-            with pytest.raises(IntegrityError):
-                async with h.factory() as session, session.begin():
-                    await session.execute(text(
-                        "UPDATE public.checker_runs SET input_context_custody=" + expression + " WHERE id=:id"
-                    ), {"id": completed.attempt_id, "wrong": "sha256:" + "f" * 64})
-        assert list((h.scratch / "workspaces").iterdir()) == []
-        assert not h.preparation._active
-        prior_calls, prior_opens = len(adapter.requests), len(h.store.opens)
-        replay = await executor.evaluate_post_submission(h.request)
-        assert replay == completed
-        assert (len(adapter.requests), len(h.store.opens)) == (prior_calls, prior_opens)
-
-        # A foreign request never acquires provider material or an image grant.
-        from tests.checkers.post_submit.support import change_request
-        from app.modules.checkers.api.execution import CheckerExecutionUnavailable
-
-        with pytest.raises(CheckerExecutionUnavailable):
-            await executor.evaluate_post_submission(change_request(h.request, assignment_id=new_record_id()))
-        assert (len(adapter.requests), len(h.store.opens)) == (prior_calls, prior_opens)
+                assert valid is False
+            missing = await session.scalar(text(
+                "SELECT public.checker_input_context_valid(jsonb_populate_record("
+                "NULL::public.checker_runs,to_jsonb(r) #- "
+                "'{input_context_custody,evaluation_context,feedback,source,result,schema_version}')) "
+                "FROM public.checker_runs r WHERE id=:id"
+            ), {"id": completed.attempt_id})
+            assert missing is False
+    for expression in (
+        "NULL",
+        "jsonb_set(input_context_custody,'{evaluation_context,source,preparation_sha256}',to_jsonb(CAST(:wrong AS text)))",
+    ):
+        with pytest.raises(IntegrityError):
+            async with h.factory() as session, session.begin():
+                await session.execute(text(
+                    "UPDATE public.checker_runs SET input_context_custody=" + expression + " WHERE id=:id"
+                ), {"id": completed.attempt_id, "wrong": "sha256:" + "f" * 64})
+    assert list((h.scratch / "workspaces").iterdir()) == []
+    assert not h.preparation._active
+    prior_calls, prior_opens = len(adapter.requests), len(h.store.opens)
+    replay = await executor.evaluate_post_submission(h.request)
+    assert replay == completed
+    assert (len(adapter.requests), len(h.store.opens)) == (prior_calls, prior_opens)
+
+    # A foreign request never acquires provider material or an image grant.
+    from tests.checkers.post_submit.support import change_request
+    from app.modules.checkers.api.execution import CheckerExecutionUnavailable
+
+    with pytest.raises(CheckerExecutionUnavailable):
+        await executor.evaluate_post_submission(change_request(h.request, assignment_id=new_record_id()))
+    assert (len(adapter.requests), len(h.store.opens)) == (prior_calls, prior_opens)
 
 
 async def test_cancellation_during_second_projection_drains_and_closes_every_role(
diff --git a/backend/tests/checkers/external/test_trial_policy.py b/backend/tests/checkers/external/test_trial_policy.py
index 39fcc16bc..2611e7a83 100644
--- a/backend/tests/checkers/external/test_trial_policy.py
+++ b/backend/tests/checkers/external/test_trial_policy.py
@@ -65,12 +65,13 @@ def test_ordinary_images_do_not_acquire_or_require_trial_privileges():
 
 @pytest.mark.asyncio
 async def test_human_post_attachment_locks_declared_trial_configuration():
+    pre = _entry("acme.intake", "pre_submit")
     values = _configuration()
     entry = _entry(
         "project.runtime_evidence", "post_submit", _binding({}).registry.configuration_schema,
     )
     _, post = await compile_external_checker_policies(
-        _request(post=(_attachment(entry, "runtime_evidence", values),)),
-        _Registry((entry,)),
+        _request(pre=(_attachment(pre, "intake"),), post=(_attachment(entry, "runtime_evidence", values),)),
+        _Registry((pre, entry)),
     )
     assert post.entries[0].configuration == values
diff --git a/backend/tests/committed_guide_fixtures.py b/backend/tests/committed_guide_fixtures.py
index b8caa0eb8..edeb779ce 100644
--- a/backend/tests/committed_guide_fixtures.py
+++ b/backend/tests/committed_guide_fixtures.py
@@ -84,13 +84,19 @@ async def create_committed_document_fixture(
         assert items
         namespace = await session.get(ArtifactStorageNamespace, "primary")
         if namespace is None:
+            from app.interfaces.artifacts import ArtifactStoreNamespaceIdentity, artifact_store_namespace_material
+            from app.interfaces.external_services import ExternalServiceAdapterIdentity
+            identity = ArtifactStoreNamespaceIdentity("local-v2", (
+                ("private_prefix", "workstream/artifacts"),
+                ("private_root_identity", sha256_hash("committed-guide-fixture")),
+            ))
+            descriptor, fingerprint = artifact_store_namespace_material(
+                backend="local", adapter_identity=ExternalServiceAdapterIdentity("artifact_store", "local"),
+                namespace_identity=identity,
+            )
             namespace = ArtifactStorageNamespace(
-                id="primary",
-                backend="local",
-                adapter="local",
-                provider_profile="test",
-                namespace_descriptor={"root": "committed-guide-fixture"},
-                namespace_fingerprint=sha256_hash("committed-guide-fixture"),
+                id="primary", backend="local", adapter="local", provider_profile=identity.provider_profile,
+                namespace_descriptor=descriptor, namespace_fingerprint=fingerprint,
             )
             session.add(namespace)
             await session.flush()
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index b6fb51489..199c2d077 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "646811e5e0dcd6f22e6a876e4cc71ba5d0075135822e77f45aa99c06974f9e3a"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "4f2fa4c887c1fe29c555b4af534227535c7b28b2ddccc53013c1e62eba8625a5"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/backend/tests/fixtures/multi_post_capture.py.txt b/backend/tests/fixtures/multi_post_capture.py.txt
new file mode 100644
index 000000000..5aac1381f
--- /dev/null
+++ b/backend/tests/fixtures/multi_post_capture.py.txt
@@ -0,0 +1,73 @@
+
+
+@pytest.mark.parametrize("roles", [
+    ("predecessor_findings",),
+    ("predecessor_submission_archive",),
+    ("predecessor_findings", "predecessor_submission_archive"),
+])
+async def test_capture_retained_multi_post(tmp_path, isolated_database_env, monkeypatch, roles):
+    """Observe accepted old custody, then require the unchanged journey to pass."""
+    import asyncpg
+    import base64
+    from dataclasses import asdict
+    from pathlib import Path
+    from scripts.run_isolated_tests import _minio_client
+
+    real_executor = live_executor
+    captured = {}
+
+    def observe(h, **options):
+        executor = real_executor(h, **options)
+
+        class ObservedExecutor:
+            async def evaluate_post_submission(self, request):
+                if not captured:
+                    connection = await asyncpg.connect(isolated_database_env.replace("+asyncpg", ""))
+                    try:
+                        tables = {}
+                        for table in await connection.fetch("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename"):
+                            name = table["tablename"]
+                            quoted = '"' + name.replace('"', '""') + '"'
+                            rows = await connection.fetch(f"SELECT to_jsonb(r)::text AS value FROM public.{quoted} r ORDER BY to_jsonb(r)::text")
+                            if rows:
+                                tables[name] = [json.loads(row["value"]) for row in rows]
+                    finally:
+                        await connection.close()
+                    objects = []
+                    async with _minio_client(h.settings.artifact_s3_endpoint_url) as client:
+                        listed = await client.list_objects_v2(
+                            Bucket=h.settings.artifact_s3_bucket, Prefix=h.settings.artifact_s3_private_prefix + "/")
+                        assert not listed.get("IsTruncated")
+                        for entry in listed.get("Contents", []):
+                            obj = await client.get_object(Bucket=h.settings.artifact_s3_bucket, Key=entry["Key"])
+                            async with obj["Body"] as body:
+                                data = await body.read()
+                            objects.append({"key": entry["Key"], "body": base64.b64encode(data).decode(),
+                                            "metadata": obj["Metadata"], "content_type": obj["ContentType"],
+                                            "etag": obj["ETag"]})
+                    assert len(objects) >= 2
+                    captured.update({
+                        "revision": "0068_issuer_profile_email",
+                        "source_commit": "94334ccf4085c26c7bfaa054465fc05cfbdad1fc",
+                        "tables": tables,
+                        "seed": {
+                            "roles": roles, "request": request.model_dump(mode="json"),
+                            "first_result": h.result.model_dump(mode="json"),
+                            "first_submission_id": str(h.created.submission_id),
+                            "revision_preparation_id": str(h.revision_preparation_id),
+                            "namespace": asdict(h.namespace),
+                            "bucket": h.settings.artifact_s3_bucket,
+                            "private_prefix": h.settings.artifact_s3_private_prefix,
+                            "objects": objects,
+                        },
+                    })
+                return await executor.evaluate_post_submission(request)
+        return ObservedExecutor()
+
+    monkeypatch.setitem(globals(), "live_executor", observe)
+    await test_revision_reads_exact_previous_material_with_per_binding_visibility(
+        tmp_path, isolated_database_env, monkeypatch, roles,
+    )
+    assert captured
+    label = "-".join(roles)
+    Path(f"/tmp/submission-multipost-{label}.json").write_text(json.dumps(captured, sort_keys=True, separators=(",", ":")))
diff --git a/backend/tests/fixtures/multi_post_history.json.gz b/backend/tests/fixtures/multi_post_history.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..4b7a01a7bae48a772c3298731f3816fec0f9467e
GIT binary patch
literal 146399
zcmV))K#IQ~iwFP!000021MGcib6m%<!@0_FN~NEl)OB9Y|XQuWZ9Z=AZi8s
z5kO;lp-4IO-{<7*ZuEl2Z8Qjg*l3vq?p8}?o?I#`>)%I{{H~tG;}3N_8II16-W>fr
z8o!@R$2Fb}&St06;qk?2GCh7boJ>dKPlFHQ=&Pg2dAyjs8%-xiZ~lFBF|MWNI+={d
z$8C6ChUX{U^>O_$Tzryq>yL+%$*hi#FUF%bJgvuQba+bNsgY%E*|FYp#HXMp>0gsS-o*86Q52
zn8jf{oljqybH*0Ad}@_B%`HnUYNn0w!PV%jtoTCuG_4r=>>TrLjQZ-Rn}+jknp;x}
zb0P+olq-zOSY>I}OGVvSzOy|-+oUhbR+XA;vIJeUkIm=?hS4q-Tdg;shZN1U<{eF!
z(#4p7N#Tii1R9olp6gbBBxucC^cbFSf_Y_%a+$}f8cjYrSBV)5EqY0|M^JTGbV@%V(uWC3n+b!~Qe4Rjxk3qJ9Ne|6c^G0+TuZ_g6fR+=Uvw>AYC
zedAtx7lUtAL<>F9e1V35LeQc@6iRZ%NhLyvQpO^WuC%bmp%#oCy=4wBG3cqr1h7y*
z1ym7A_v-(f?V??C+=hUUR1EXDZT>?KWi2nxf54HhpX&J1H5a^wb2#fdV`6Xs|;!^7N<>Lmcq|%5^>xX)Z+jTtd
z*c?2Kr_X1nr-b2?3Ah7y{}V6&X8H1O<}VM3;o|h&{OMo+MLM>PBW8BiNo>~!{X6f#
z{F9^EG>2B=1$u0WzfFSP03h?L+8aj`M6hrpu%A
z(@(D;{W6$gCrIm7Qc0%T=#3QIaGqR*cU-j9vZ~-<*W=q6zcgu8304ZYPiQ)sTywq)
zkOq-2Mu3q|S9}rYl(jiGxV1IH|K{4K+7gHU2uVT}g^;T87SP-H
z(oT5nOAqqWOYd}ji5F8+0Y?*cOvHnlN~c`_BZ4i@%Z@uMH^0XC7e)WDU
zmV*9IIxRl^)H&WAe)YAoFQ$gKE=I!+wSghS>8JHTLr~dhQB*Wp!aD_A`PM?@EsN@d
zr0`ZKu;wg`sT@qI9K6*cOgWhyP1419_#wiWxER+q{D@C4BSK$aqLi;8!}kq>MQtk+
z2Jh<{eBq+|z=%NmGG<7h7@iMDtP^m8zmDv)39Aq;){*rA;wL@5B6A>->RSZ8Mun#I
zhu=+p`^`6heY^bg$G?8_?fKWgoc*4DnP2}C{Z;<(`(NTG7_L%GepG*Zm*up4duHCH
zAAbmcQr~<65}p0&=ZnAo*Ux|X-S02I_V(S||MkmwBL3NZ<6HXNH=6!BEoZ0ifBMn<
z_fP*7KK=BM-;4NFthh|L(gFe|qny^vj>S
zuKtt0{i*z@XIZ}cIiH39_tTHx@jw3d?ZfnKYjmp`rR+(3~iWy
z{&Mo^&)TjnR^HTrg
zZ=ccL=zsli_IDZo@!ds|+Wzqm-+jpEe>(jqzWvj;-|+Z{A5P+r;^*{-zfUnY{Gb2$
z8$CDs_Vk-Szy0eUe|Y{_fk~zx~S(tH*x#
zcKp9*zx@5={pC0Q<7D$oCvSh}=-;3I@zcdmfB5_CpYn$f`Rwl>%a5m@e){pR)3xi<
zzhF+lYu~(m_t)Rou;$zPXDa_bejM1_Y27L`#=AC;dD+0D(joG$%gvytCUPdd@Oq|fd#OMmwLr|$jft}$Qy@jw1X|E9CRfBMH?X5~NL
zag6!*bC943`RiLpKY#nfH}g0C=l?uNmQ8_;z(sCJ!9LZY7#oX70zaD={pZVa`}(sN
zcQ$1CUw2^5EbQ&h%7Yzua(=e8l!Y&p;tK&RiA1V2KWeqLp-D_y*a49hR!QIRU(_l}*>w`-tjFo+BXyUUWvu8c{fW_Krx3Jq_zE6iAK*hNq2+#f9YB(an?}X3i
zib*1qQRrIm*&9cGuQY}NmC}{!JWOCrQH{2Ss-lA_SvnG3X!NiuQe_)gt?le5JYU6}&y5901=DCtnv~!#mBpKr9g=W)eY3BgCzE-Jt^zAs
z0Kt>xR>~}l=Cy$>rF8|ayQo@vPEMMXAyzPS(p9+i7I)98w3t*kTF(SbAuC^a&a8u)_7Fa!IWEl
zcPpF)pC9hHbqpS7W+Hf5c*B33lhZZtekbDR)A6t_!iwt|8gz5z1|RQ8uAt>?dU1C~
z3sgY=>lsR-mAF_=9bsA+heK#5pf0;Li-p|QeKU~!@Atn!5Dfp>r%Ya>?gdY2yC4m9v5fMJRNg$yQHFFop8n^U
zRwt$%$yz*})Xu@aymUjF{rhM*t!Ld23+n@~fNVsEr8zPl$4~V84XN0%PZ#7Oa<0BJ
z_wVULi}+JFO_zeS{LXw9R#B=e*$)t=Qk<(sLc$spzfK}V=v)VYmHVg
z7THQWnW~pSS7OEMfx+&p*V8J>>;h?lsB(pw6KXTLl;B}rD%faAtC&>Qcmntc7!EuX
zC@*d_FfH@zX*HTn?`k}YrIjx*h`#lYN)hq&={V-;XqEf71xQfwFq<=HF_)jIr|Z-K${@21m>
z$(yggUN9+Z!;h30GMJLO`s(O3PC7$i*oN2ZQ8#d2IUoK9=Wn`fcp7c*<5qihqkMhaeDYVY|7*RRskTUX}++DNH)m$yEQ-fw+ker5gj`IXH#fh^P6q_g^_i+u#M
zx%Rn)qvc$&8`5v_f#dhXE=A(q>@1#l7IQC4SRh863v-vZ
zNHKlSl1QT2oT3%w1}wqSXf!4Db8#SZ_+Y&-FO@kiXN}#Ernh4g;2lWI!E_YPcZJIc
zNNUZP!`Z}TjqVkPjt0k+%3LKy*(q(EP1Z7bhUaq~xRWR5P4rXU4`69|?{-q15{W2p
zj&-XN%ZYvLe6Xffm*&f)PG=WaDNIxu=DMH8UKLn&_zCKUGai$WkYm@1IGn~_Rpwd}
z@O(Mo3N+@{8_7%C1qDkzHfX1#pJ51A@_+#Y`Q1%nzz-B`Zm(|$19;p*U+rcH@`^{3
zc=}XW;f55vo#6L+3QvcVemb{A7DEnl|qyKZGW_yO1s4d0kA
ztb%Q;o~(MfGHG)^ZZu{$Bv62k}gIc%n0}v
z7@=bRlY|))g=p|T;Y~YxFN|Q+K*GXtH^d4&F1+JfJ}({8Pr=(U1t}w^bfT<)NI5K-
z{Mp*FKb$EFXyAma~M0I#0ceY$PIX07{|qvg@ulm
z?1n_UEgu+4y)rC1AiK^^r|KyPUvI+)6idtrUa+O;P%5pt$bE9_d_Y*huBG}7TnEsV
z^WcNu?K)g=&z=gq0u$GS`;Hhj3T}gwx6&)G`KZk9Sk0B$>2%w-K45DmynDP
zw;-%@%o!e7)LOD;oh{KvSF*Zu!UC;!2iunciYG?eJ}TUXv<~wnG~_IR62Z30ns-r3
zBb&1AFw)MyMZxu;n9sz8%^0D4%#GhA7>74P54@$!@SU_J*PCnd8=ekz_Y&gP)a@#Z
zdC7cjg;5~OIw`W@16PEOD7$jgEX+fchY&)(3^R|
zl{c5mQBP?7WHg(m(Z@j_a^rUDV5*ixq(d<+5xQk6V=X=)S%|9cV)#zUTgp@Nc*Rz^bqk!tLY>@zt{Ht6Txv
z>y_f99xrxTE%IAV#&yCzh&NF00&cXXtwuR&1zXc8I2Wnv5K0IcSBeNW1R%RDa2$;V
zyo5y6G=iF!#M^4}nz3Jb?wVQH@!ZA5#^hdkVv%Gq9{qegscU&Ix*0_~et?cCMxMDc
zIwiOvQPrHPsYS?`bn#V)L>qasY_xevVD3}UX0>hO?mvBnxz;l}HX<$ajcT~DC@#8~
zr#<e6Os)6rR^0*v!Q7co=P&E3JzHf!~P%jBY-myPCD*H(?quT8EtHM=MW&~K%9
zo*!@YW-z?+#^JoNRA9H`jw|^S8{Bbi0>#7eOK*D0&G`lLGmEFkOR}y%be~Mqo6Pax
zth7b!JB67mc^4auv}4ii;aI3Qcj6Ut_R{i>`D7~(dVvQpyg`XD+4_Y1NEfXJShfRua3=e>2W^exo~t>xOrvgPwTi#N?jv;N3dH+MfZPscl^
zLqYQJBA)I|*4s|NAk|m{*;kpABn+%#J(Vju>d(l#b_nZ_Tt9@}iF}LmSLgA}`Rnsa
zRoz)wlT4{)>t&D@ywP1>R;imG2)B#Zrg3~yr^mN1ld?*;Bapfw$1LgyPCwm
z-i%{z+UtEhbyIHW<+|P3J=rs7EoVLl&6335$~T>j{DRE2%z^65IZ?eZ!Y1>`S?Z=0+cubP@qt@&
zU2m?-y>gwi+#CN~xGqFm`%jK}k6){B&BtPN67~yn-Lm4x10h&%Zp{7hk`@E6==_9d
z!b{O)I+w&{7Ie~#WHF1VjP3GBUJ>k&tegAeI->@PLsiRX!gWP@O~>#=7B$bzRzt@c
zhGf&1G{xHRJksg6>n8H!;Jf}To_pjwJCGs>^;}$lQW{)<;AsI!Hag`bSsQsQPQ9Yt
zfdzEdxQ?P2r}Zoi^J)v&|M~awiR1Gborq4A_~si8SMALsXWjdY^{j3Z=M{DHJL=-%
zpwIPFwv3_*^^=Y5W|wFB?&M_uMsYZ^X4hVV-Oo!okkZ<)l?qHzt@RSs+o!rpkpq=7
zE+(iHO7hYLWutb^Lu=#+hEs)(>r%lbA(ZD%sh~i>(5h*CGa}+RW!w}xp%?yYc8Xcf
zYc5WUkme`Aj>;@|wZYrXDR=qSvT*)74|H;H3O3ymgvCzLYi3IiXb9Y|?Fb}3T$H&U
zp2hK}ZRRZX;&k+>D~0~m(UpVG+Gn3Hx7ZiCaoTfVbgttOkj=^U(C-UoyZ{4R^Txb0
zl{KqcaIk-baZiQuHa`F6rX{Af0JQ7yD~CQx4vhx30gQ34eP)@d!0EYG3RU%lb)XdC$u}<
zdpR9a66Ep|T!RVh9g2Sc9Bhk2clzm<9p&NN^i+m;r&h*O8T3tT`UA(ZE~jaE?A@x2
z*&z!XaXK9j)2u`NMb9YHx4YJ*H*_b!ZZ1{9_qV1L@F;8v`22-&8LKSKda3f>_=WNV
z(bZ(ToWsp;`vd`pPiz?!j%L~j4?Po|mEAVn(aA8!)8oZ*(%PYfX?9*t>+xtjJQ>cb
zG2UiPiMBdoQtH{o=91Q;BHdP3C8iZ~8(82qGpm~9xrNedUOR2`G703eub0fQQABVC
z{R{0>CrhHPbzr`CE-zDoa~-brZN1RypY0J*-v`S-$*{N
zM0>ZB^pXj9P9VKVaNz~vpC~otlze_u@*pgH+z6Y^XK$;~I(8?jp4BppmsZ!s#p$BEUte_A-1%sH)@?yA$D3*RM_o0u
z!ThOho5;A7Id>&A9}*oPjh{j>iYFUl1m#LLR!MCvaH7Fh@=@m2TJcG8O0(M?o$be_
zt$^A#HudA)wbSs+@S<-T771f_9Z}rvU-Wth+a}?*)!r}scRc>jwTU-mW98f|L};Ng
z7xI2SJ4;m8mprcJ5!AEuH7Q(Pol-T0a0|pSq9x6$
za)H6wfk453V$sFsvM2tHM~4e*sna+-r6FO=olq^Sv(icO+bEbKn7C3jAXs!F!DEYA
z({a03cU0=>F|MBO0P0H$lhM^3fIgZ{;SF`x
z*5V-Y;|Ww-=Nfg}ata7KKahOkXfASvCSTtW__kHX`ovK(PtX=xEOJ(ZO%m^N>v*Rh
zi2c!#H!Yq{>ihzRd*vf=032k1C2J^!ry0|PHc9KX1E#kRruP6pV1whjIS1x}m+d^K
zs*Nc+SFFgUX6us*(Iu-KymxNEPoa8Ov?}v$U=J)9TzK@2XWAkf89+_IrfQiWRvYwR
zC>adfhCO8AmObHF%ZU`z-F#b*^S-kX>$_dKX)AQ+lX7n1-!u%BmIc$mvIa9;9#
z3r3JU$|$&LmP4P46r%7VHWlzcnT%GjF(9%j6`N)8+G|PAM<5yJS$z?~xVz=sLrtF>
z$j;S$l(3N;l~F4Ad=SO~{sI)+QZgUP*S3BA
z*^9x~2vE1~o+WHBpp=gVj)+$^g$fv1}qvj4s@+gfbL*`k4AvR*Pk5^zfOQ?>7jV=zBSNXAv1hfbD6U*PTW+0
zh)7f&rBKRXYta9y$Xc7TP#ir1)L>-?Nj{S(O8H`awJ-w!blh3*b&;|L5xtBq!;Xon
z!r8Lb2Z(nrzHa(7>qA^mAifQ5%-=sgBq8^(Q0cnp-$BRv5;nhR$NKX0zG%n#vbFA}
zWBWvFN5}T1?Hsn4dB+{=OY8We9qU`o|Dql1Thl$TW7h!PHNnkzK05DI*LbNpHCwu1)3`a*o-WjFF!xOx>!h96uh|8Xi{HLq+6Unt{*Rka5UEs&)Q{`#E-+X+1cV$uWnf246`>B
z-D}NIG;(qgG0p~yrH*NX)td5Fkq41$axPo=@mz@rqZh^reuD+frISXL2ptq*+gmGD
zw8~;qFm#?IX{Ph~aoUl5HM+GCtR1%0my2-+!L^iM-
z7eV7I8E%hLtL)07+pSf^XKR&RD-`|Vll#>f^HhlEpfm1Z!KPPdbbI%VGuDZ{I^%|U
z;afW6N(R}(>5skZWRGgu=H9kDKDhq4X`1!zHO#IJz1L`%nBSj|eg+hu+}&Q!Yt_pg
zEU7#Z^|EV|%fqRceUZ~w^>Q=yatF(qz3Qdg+~c5(yncr2W#20DqgvFwxBXDhP`&Kh
z@%Q=aWzS}?1-C3#mrJ~$di5ZdI;P!bkl@rYZ~PF4r!fsrA;`ze{b;ju>P2^m;LX&<
z)m;aBv&}v;x4qXX2RPP~@$M0IMd2ZSqw`FMbFbmu{e$cs<>@WIvV@>FM^yNG#6F0d
z$jMtMbXcxot{ttrf%H&;
zt7@5FiuLX?`R)F=vYRm>F;3slm5bBL%9mry&)92qldT-Ry8g4+a=z0`c3S$;u;pE(
zl-(O!V#Y)m1X#G*+>|ZX74((1_o?ax%0|Of
zjV8w5D
zE-*e*Emz2ywv`Ek_jL`vaIu$>#`R>LQ8}AHF8$y)9H9t
z*Gd_5F3QKN;XmGr^zfB!b0sTNV-6w(@>4*a1>n9VW+D7BL?Biky;4}`;jwk2wV)AZ;{`~vbo%^kmsYxZ~lNLPAMd1y6*vojvEYFp<}n3_3gWN=g3$SrS1)mXu}6g_N>@?y>dg
z@|9&Mcs|}==Dja94;S?!I$k+0qq8_XUp?2&%ly_w{B$~sWj+P-ON(#*7oFQjMeyIQ
zfBfx&!pn!(OHqKrbxfE%uU@}e5LsNF%sS_4dA*HCXU9uru=^mgz8P5G%mkLLV_N39
z{Lp#lb1oJQ;*3=3hq`gpz{VqsD*tn~zy5yb7A|g2FwY-4PP?=n&bkv5%QYu7^qs0U
z%6T>(_npiHC;%v|mK#X_t)k3VrT^-wLYGHfY;sG*FlWoHRm(Vi_e~8;P#Ucmx7;!9
zngv3oz)TReS*wj&9Hex$%E_F13ImofEmBgfIv+A^iLj#WsB*IG?!5o2k_+1>FsxBv
z`}zj;Rs=g}J!I{*1q80DflWsn+`6cob4h{a8NcL$!L9tX_@OH}wG)baPiA^>DE8p5
z?6YWzR?c93$f%MwDN37+F9|jwd_;JP@NZLAE&D_n&?T7=4Q(H}PbglSv>c%!VN@n)
z2i9^jroiMfN$iJWKd>rTr4EPUm>|1`?2D#p7lIRLS#agjOM&9v8F*??+HZZe;43PHM`tj?
zN*A#CA;PMPPas+hCk58I73U(CNh@PT@HX)rVpL7lEJWeC@K_B`PRbx1j4Q1g
z94(`BP*F$zoWVMB4N{c|C!aW9SK|^1x9yH>d#x^bfXFm8Kc%h35;B%YSi_x
z9j&8I(d>!bBTWDpHam3==GRp`=w+Se+jxsvVuq%*Dnr
zeW}u>3mFug78TomKvx4}jWdTwwc#2G=B&`*?UtF1MhK;S(;aWW2te@F
zEg~6Zsx_J7cQzGgf-_k)3k-(=W~sW5Y9hx1Uh(&e)KaHFF(lS#g~G@J6A;!ClT|l(
zD>(M!J?*KD^=+t~+@Mc}`60&aOUUXiAwByB{CzTws
zq}tj(&{c)X(diIKUFsMT_B6oSX`E%
z@JrD#8CQ$BSFkoA)hu{m4h91=29uWHqqD+m^og`et2Y5_?~GX6ta4+pR#f|y(m7KU
zf$=JqA`%`@`aP<26WO9V?j1gryB6
z0CMR<$|m*TwoosV#Yzqlx#5*V)3DPc1Q#bz>%%0#l(H
zR*N#S0KJ@rJXN1@~&3*i@@vN8F)r`ZDCx)2(^#W
zxHbjfqn%h(ZiN}xQt&ZhC)XN)xWbiIOAknUE*L~M(yl$tL
zMK|vVm#<8V)mGvQjTe(T?qLJ3vB&Dbnz%tQWnXAeor6@r%
z?F>~{lSR0gQp*8|r-6C*y1B)guF4K(sTHQZZ{RjA;gv}lT4~vJp7kEkrOho08suQm
z&BDT;Z(g&&18fSb6x0k?D!-J7M*j@FsH_h^2#R)A?S;deFK4W!r!$PONVp2EUQ#WW!`wH
zRd8iO#Q#DN;(i0r(NYLSGwBj|&PmOp1AvIyf{#2H^m9L4hk<~R?+>?;vuuJ2!f|-?
z*)pIOC)=b%;a&<{_s+nJg6l9)90r4W)NtJ*B!bJ#lJl17+9dN$7mUO?B?U~b)LuMX
z_e7)P1(kGpD$t!vsAR~3tX^wCwedyRVu9Q|W&96+ORgQ2C60|}%T?8dtEQCDt=ubg
zSDBPc$+GNnVW!)AA6sN97ph~ai;;dWbQ?b47O-y)hi;EnF)f8fku%eQ>u&qHX)ngo
z?wx^`1l`~w&$Tq+u?MW9Y|U1lAu}d2EsCWhGZG8Xw`7PH!&`5_nu>B3O074Bad@;4
zvu0FRs_GU2>$BN3KFx6T#b~k^+4ORgENr>ZJU937Y=Bz
zUKz`aP*k?873ru@NT^ZR``w&wt27P0WY#&!OtWNaVEUSOC0J);OZ#neBL>oVc^iPI
zog>ad!FUhz6uK=7SyQd@#Q=Qo3_PFswUJZ>1YrNz;ahUg6M6~}$Qs7CfTHROTT>mS
zSd(_CXR8dz30KSU2y#}%iZcp#k`k)N_&&ZK>7FNiKPdyMtU}>cG(S|DNSg25J
zAft((y!I|C9$bpze)rWFQLQPB&ZrKY84)#$v`v5u=}pPO%NF+I
zw;Tv#LpVHNqzK*Z)s`$(*ezaE?I1R3UTps*;CKHFyeI=*4uTUvkjIYj-5Cw0CJ;+i
zrVIWG#wFHhOS5)WY^7YkBK&r>C?Mr{n7ZPIg9Ql}wXez;XnPH=7bz-p(P8FPa;zy;
zN)1VuZm;lzS}l7
z<%_`e-WhmexL#ye+O$O$HP6geLsh*)vgro(`@lucdugu^ywLU&5G=0a!NWqj&bo9P
zB~=!R>EIoUwA)x~Sw*A5L9z$Zi{>ym8<#A`0#nM71K@4cA?<+lb@W?c_|t~&`9kMY
zf^KMBr!1A1O(A1mj5o&CkVR}YsrZ1>JfexZ^!0`73lkY3RO~rPJZ$-4ijmIUrfI
z5NK07c-2?%W(I*_P4nVy6IJ=_gwV-y9gI#@zyZ~@l^g-yPXM*`KuS_ThoiO)0iJi`
zXw^Dq6o<;<1sdzc7~H)x@WN1ADH-G|Xg__>-b~7;J0G4-<-h8j5|&O?kp%=&B5LiL
zqij(tt2HuZ!o`qylveUk0peBW;!M`u-EaL7mo-~CB=vo5)E9w6uj=8ffp6{HUn#e3i?rQ&GB9WMq*{wgvemm
zG%8mIog}<=HM%UD>`5j}flh!HnuQuYqixbQ+H7U!d$;B+(C$etUeZCug9*^1URQ#o
z|7`3B2WzWC;{Ze{T+Nss!A+ne@x1XWKvtuQs_>e!@=ZvcV#7bm73Gr0W&JS4qDtin
z9*K&e8y&QyX&a|7L8luS*LEPhlD8;9QYtOk*bGvMqFIzV8Tdl5$zIGVW$z3;HRHN8
z4>QRN;IyQ3t9`OI@>ra@0a)9CqV2+RFIaaF@UU3DE+>(>S};UcX`HmDIe}~~ztqI<
zd9$C7#OvR=4t^KU?1015VXOI5o*%|~OE_FSd0${xd}c6TV9IdX5N%^>S~w-UQ_?oU
zj#&IEw4K(I2qah^>Ndh{ar7l`-MLo!ist=2rfG*4xJ1mW-X)dg)l_aNd*;0lfmc

x*7;_wRb}=4oyF(3MiZg~9|v^MIVn@fR2A0b=7Lrh zlyHHp$5>^}%?EgV#c_5HlyKO*J5K%PPbqk zrV6fnZ;RLQAdtpjsL;ca!5=hKD5tq-S0CHhN40$t=FVp}hgFNRMZ1)|(9$&l_l&B6 zNKp#ORaRUzV`@w>Km|DNxf6oQ2t*@Qw(+{2Y-Qb7sel=oOj41VMw8McsrTNLAy(5q&qJ0 zd*e{ywFlNu8eW;B@9U>cyGTT;&SY5v05h%NMOaK&4vV6vbM|MG4Rkm8d3Q?l_rD;4uPIIOe736rjww z6>{AYeEYZWf76B^r?YYW&F~yfK|KA<+|3-GpB&B4B#xhsch1Y=ULKu+er4mv+=jdo zz?0U}x_8VfHYKel$Zj!_Vd0X?z;Z<%8Q3lgEox9D$;gW=fIt;{wuJW^8QZ2NnHd|7 zF90QL@~g#r(Ab{9M zFgP)EuKUx7hpC)=tTq{#>yBjdPHY)SWwf2 z(cvL1airTY#YnFacpOw`kyY_yP-};4h9}q<4}` zC1pLpUMMHx{T_Wn273`+GizWE>!LVIQUqpPtgz$_RLs7hn13VmASeYp`Y=Dyai*wX zl!NYqLiCXi%Yr9UX(!=}$mrcW1J9)t5qQK6q%^@_pRao<`hD{LAQ7+|3dJrH1r(JQ zYTaoC+Y}Bl-h_jywQW-FJ^}WMpVN)|32l*^cY7VN`%ip@1t>8=Fx~?lKM<==FjHw4 z(ihnw=NbpjdLtBvHCj!Pu%ev@{3e)6Dmh%0(Hi{iQ!-vgtuyRc1y{(Yd#(k#;;Kd^ z3Zv)D3n!RYrYM(rtg7wDXE!j$%C+M>Z;a2fp;aIg^Q2U36&lWmRzla8g3rA(@T~AT zxZrHhuH`;Cf54TAy~1!EF5m2>1?NrR3+3r%AZmUz>eGeg#epqP1ecYG+W83IE(zL` zEUNe5P?>znHhYDc)A0K!nKi~#A(1AOYORNDouto?AD5*VcqgQl2jj9TW6aurVt4);`lKn`#ek{ zP7y?SE?IJ_GCHX{H$g`)@cq~+;ZM>I(8IAa*$OpR5;PoFaPOi@4KkL(OR;JDXW)q? z;xwKenB0N9ZkFI(kwGch^?N>s&sJ8gf_Mtj7opqH)sTAak!PMRvct-Z99zYC*yFnaxx1{&1W*rQT zV0Ox~N|AXAo|__brW1PRSyr#m_zI181&xXiOn^Gq2ScMZoule40RtGddXyPnx4a|@bCwQe=#DEER$IlbO~!r+Y)mm% zC_(jo{~n%-5Ldwtz_ zKG>(T_`Pd6?FkgNXew~7s%_r$j2{Ho0&}53BZ~Os=2TUcN5KUh{SZ{+QqaaaXA1Ws zA3gf@^v^)yYUsd=mRRtmvc{8A#=yPk4l#ZaDBL>(FKInpi-B@f+2VPur>~J%0*Zh~ zP_(>eW));Aw@~H>l=L8UH^`@T(Bv|oY_&;zZ&1Nm=D1DF$JAJqs@7aWGCq6}ur4WO zBZ`(j!%H`k`=H^y*c>ID2?7|8hG&`JP&R^Vt5Zs$X^~+2XZ}DYbM>H~v6j&p4=n3K zbz762uZr}8wbp}Rg4Bm6jz&6d$H7S;mpU`w;5z71Qmro~akPI1o{`CH20mE9&HlvE zor3h6f28~yNm1DCC6&o!ng zM_vT1dMJ-vjPS11$Xga6=GJKbtP{3M5jFm9)l>P9CxFj(paX67Jsh7aoJQARefg?k z!n-?i!&lStJ+1J4Mb!@$ZAWOxD_VqanU7B=(V-BypvXy#6GxOqax6k%Fcr+~*T zds8)66#mfK0IU*hQbovYm1>d^!bs4a(E-;z;hwZp($K~@k&uvPIb;~u`K71 z;rQ{yQ+yGiyl)1c3n&MwWI^@G^g%ZB7u#+1ipIOqcr=@)(Z@j|Y1~_s_sH0$?)`h6{UrD#TUcejv~-vdg4J1GM|N8Wu{4%r+0lw8Roaybg3R zK5k&_8434BWw_x~0yL|Do`oHtJ0IelO0TGUzsIA)(ac$fqCr4zKulePicSgGzFtV+ zuAz!BI^jlfA~>TB;1@zj#_|28R}`H}S3Wc50G^8hsGBq#h9+aRDhjtZ0j-lLsjXMx z7N}dnw9rdnT67{q(L@QhZ~qKDBk&CaczmwM;eAoy)p7=>22ZQiaI4R`TIQL*D zg>04R-Yjyy(HSZ&4ZpU6n%lc%#Cs-L9;ZTw9Q~?laouW+N3K-k7Jci3V}zm zYSCHfc73llwJ6zEG{cIck}1w}7Lp?XWPM|hCPCBfcy`COcWm3XZQHhO8#}gb+qQPh zXKZ})zW0l`H{$;3uE?&c=%~o3&dzgAIxjim_$nr=VM%I%)1u(>Xfb1;0r zuq;Otg5kAnw)<~Zm!D+eMFfi*Y%r+ ze)V%U3Dh5V&7ImHg#boR==XTVPvA$)An`$}2bk{i$w`}l&~L|r+$lWJ{3Wqhd{ft_vb5A!C7d{1KCJ$6r;Os%EJ@WAwNUPLJ;^RzUzqM3orRz_ z(2980ML+#}Q|TD{7!d8p38KhUfE5Rw(fU`!H@G z0b!66F*p87CrySDT$9$QET`994xRW)R|FVzNBixFJ&1{9;HbLUz!j|aUB7B=b{cjz*sq#nJYQtnS}{Guv>8@;cq+<*8dY^{E88UKlZSL6f&Yth^4CP z3tqrkB%Qll+dGtUSpEsOUil02gD|q;k5RGopwDYkzdeAY+#yTgWip7YBUslhh3;7{ zMsyNHfi;2~2(e5W|4|Nvj1ROs&xXa&t%)$^PXCi%Htz_LGe-t0O7)oag_x$$L9(6c zSCD3ga_P%{2KR??9@7v*6&_2uM+c61H{HwNKgbqwo*Q@*lb35Xa%B+%;R^GsYi46>5(TO!z866NVW3;zPntKZIH~Nn^+9!JxBr}k91s+({ z-_itAFGnIoQcs9uTB6W6on#`cXC$gX^^NHVitRcrGQO;2r=iiZ=_Bc0|HKLLI7w)I zOTd4pEp5kd5!AcX_ni0w!Fazn2!_Tr^2!`Yz6x};cLd96cHN!;|zim0W92G zLycbr!y^KS0%RNQ;*iED~<;DPJzc{5X^1+AvLCudq z>T4Ayg{v&nbeKkDz zezPR8!vz6h3&{NDl`NchX2czZ*5>JCuU^XG_*kxPhs)-L zrg@WxM_vl1S53FjO4!^OweXyY4Q3Ur)!mZlj5tXcSLJUME2h7g z6HciNR*!1d)D!9uuoDP*;&B4wT&uT9@&~dXyGE^@B#o{}&dE{F7DcyHK-0>DM?j{l zG^ZpS!U65~%MIs_2iI`&kWmUbll}3sH>3!tXOl7hPri z=9>8xAhBU^NHwKvOM@hw^^+m(!pyKG9!{LW|74=T9>|#ZuUN@S_+7ysh`h<-Rs$R6 zO{tiAy$=!KPTww=kuM&z$ggQh1vRoL0l$kpn*a;p2{CtdpbAH#ayxnGd zQ*j>mVMni0TRV1;FDJXgt)R>4LQjm$08L`GQ)IKT=L?J(v&d=w%8ATG=j6sL;M%UM zT`%lbbh28C92eSx^0mZj12(Gok7Uvq^28l+@#bLxB;vISj%)&&uy+ZmHC`szKZgB||m{R4hQ4uN1 zyRjf3oX|u8(!!iO++VsvmGjn~Y6k%x%v_&DL2dq_=d2nvrVmIt=k79ybUvdt{DCB( zLZnU*T%vWhixG~f4g0F(Y-tM@(%}e{!;G^5@-PZj%P_X_1 zn3s)o`HuKajp32{INYYgsP)_Rn+NCcU6_-@?qNqx?%Gi>9w@Awr1ftHcUCSg-FQ}? z%!SFwAuP6w^|{Ls(ChPq4mv6)>T8KX(-t96-0Qj4ci*l5RbH~>RAZo0 zLx6+h=c`#$53s6rFXuySC)#R6iYDLCqcOF1X#leoHxJWps)0ZJU-{*%I`F6CR!E_} zhqLe787J;Tt(2N|*3Arsm6PrA2G)L;{gsl9aye22V~Xlv_){sFLz{;PhA&RU#GV zA{mC6`KC=V)X5DPwmM=CGvk%*IcFS?Q2v0EY&>l$BdRQami~bj#1|Ui!GYV`)$z>+ z1auT6wieDQ1=;QGG%;hM;UGt^TPj7b8$whQ>@Ah>wK@ZKKES+Ao*-Yb#6Oqa!qG{9 zYRm?>Jvh34A~OpfNte}Gl_5qnTojeTAg?Bk`1C`CH%VTxn&Et zUzsk3E}ZWL%}<~al%vqG_m;BS56B##ElgBJr`Eq_Bb>em$7W4x|XP*cTE*q$5==`XJhHF8B^Fz*gysg!;G zk=WF?9=u=u^Z#aHp)ZjSNg?~Zd=){)zARPHkv0!`+N7ANDj^sVOeVw~4V-i)XsWPa zA+&;trvxn95)@9>^Xs-o{3w(8--ZWwO># zT48C}*}uR{8yuJkY3;nv^rfaAoY<>{xPqIY+(Md0gxF-Zk4M+uaa0Yx>S`}dBerP? zmy>5c`tofPLTXc8Y15*g2rqlq#CYh~pH@LU$7{~*u`3BLr!mBabg9g>d~Q%JEoqg- zm&4dxMq*x4oA{nf@0u@1MY*dcH`3Ny?bDdbQAP8p@A!^rfb3MOM)&anD-EK_e}6i& z*8CjTr-wc8Zrfm}rb!o%6gN}$P<3oDgd<-+8w#URZe=YyhnJd{o27C(u6C*gjV~%} z#M-QB4<>{2JQ$aj(R_7c4ONcqGsf$(c)QIUkg}9?M{8WBhr1tT?b>bKuH&!m?*0z1 zbn9*M7)J7~L-wgsMc9X2{M(8pn&pEIn3rD z^qAwu6lK?6cs6i6DHj{UJ#j&68kfu$F;keNO&&vX0&R1pKbEqF9e6Ni3^G(tZ=&&! z8Mmh}LKl`7F>plN4Sfc}gw@(<)EShiY_wN101`~xRN&;4oWlSt znZk-zO7nknty)!u#>4;xtg!mnc2NO{5XE?Mkh}N*x{>wD6hHkbQaBv2M#1l9 zc^#9nma}h*ppCCb&rHPc$MMlxKnn8DU946Nhrts-FV_Ts)xPa8iCX>Blg{em&y-nG z(ly`ZMSN|Zxf>Cyn*`(Cjg4<3J>(m_#QJ^jl4V$>bmWdr)xh*&!QE5}!QZ^Q0~e54 z^A$i)RuT|#XQ%s_z{ZA^yT15XO8H(5Z~f@mYq{&`rnZ~rW%gOVb2tb^86?C_;ZG(XT7zQb9>ar z&h^Z{_w#Z5J=E5MJjdT0^g}mk{MEB#b(hyZ?$gur^>K#2ca?0{@8Qjt>jCtn>-+R^ zMm_5Gfrn+QR%^o*yB_xh7ZDv>sf+KpK!xO>Eb4fD2-+ip&Uq2~a;V0RZUTf6ckYN)Q%g5S~QB&`>TenuA)^=5z?}A~c z!VW8kbqbr?ldxHnG{X)p{^FFT$A5F!Ok|oAz<52kvpJK7FGXIf(eR z@9}Y~N$GK`i+|%*u@&&IgzfAon=6G4@HeGyzY29cUw9>N%L&696|+A3lCQEaa~rarsw9le?!6AuBPCCe(G zg%#uJib&S{GvYmbmeg)^eZHl5>hStoJLIapkmgvEf4Q?t=%_jHTvW?xw^r^`YRDJK8L}t}#ZP^ky`K^ZOw^o&Vrr#3^lGj9}T~Zf#q2tTQ5%#}r9ji^d-QWs&4ll@_zM=3lw7e|Nx$dNl2_ zo8B38`d&4&pWgC~nv+}YT>A5;k!7@9ql_s=>OW!kzFg3$L_Lj~&w<&NHT{;^?kjAL zn@E)X?w=mxy+WFNHQop}?yYeYTWvd{lFc*m1knLYh)h?~eGgztBH~{A&86pE5lUZ{ zBaHMRLETggj-W$@1r;*DU99C0l4|^mIGn()vTchK>ya;4F5;R)Eo3}4-F6?zjjHL* z13pb4-;YkNf0v3#Ceot=n#Uu@1^egh(OLp%QwL1+i7YT+$HA>kqTz7L^aUOI8``C) zE^mUTBKKPhF=B;zy-hzJBr$;C%kyi zF^sw^58r&mcI>lXcKGF#*%r+pTiAaS@v@jZE_?`qen5z=rNUd~QC;5Zju<3h@8Xq2 zDw9=>Rzio@EP>nQX&+~+3JJR)&vX_xa}=&+&zZ=cGLkuGAa_jt);W$gbP}!C0G@_2 zSLJU6$wZy&brY=@8u{n+a5F;pOvWVtmYjG{`Pe^Bh(5#__u&wiD2t?OLkf9@e8xu} z1E#A^yVE7WG`POx?$R9Wu@(LV{lri z35|o4Kim%2{pImZX_dpY22}nK)Xykf#)9BHgj8wOHEoNsC1uvX!QeV6v%bMQij`4l zCixiAoHFb(sX=@X?=1a(16p3T*bp7PRIj(!UqON&Xmd}{P+Flq#A&wcxw&|6pQu&}63U7GZqB`1w6nA76|=0kbA&uYgvRe;~~~ zMMl6FEktHut)N(D_>MDx4Xnx_=G%DYmIFhilcPY0t5d^Jnsn2;9+Ds?e%Bu9XiZdi-od%X?3wB1Lx@*hSmk) zk~0ofxkd3H?Yl&zl(!eg`e9BO3}D`|o`DM>b#uXnx6lfi;SQfZn<-=uc#Z1lMN?=*>3^&FZ20Khmut!6i5;1Q5+?o9TwioTd$K%d3s6GClLY zi^1J1ha#Oq5;rOio$O(~{x_hli|Uj(Y#LP`XYLv=zr?UFQ-!}nc!&K4rBnP>r(8vm zjYx@;`+B?%stovT0Z1H?rjm8F&Kd`GjY%x{Qi#l+nx8rNAR27{fTM*By=zhQlcZ#%YnrUtqW6@+EHCQ3f*oCyE$)G z+)LNEPc%4Nh0%xXRn0OfVZU`KAP0X9D4i9I*i;b}0oIL%Hbs$n*v+*#U(GLuOd2gb ze0?90Zy8q-TUxPd-LV^-eNjI-Ua?5PDPapsl`PD@KBku)9qylg6lP>uaSvyVa=bkn zJI8UEj^xA-SR)gYQODTRv4)L~Umq}%eR)TD2d_3{N<`o?EYGTDUr0GqFGr?#W1E}M za#XACG4HTjARR;cbs)}d?jpp3a0Vdslf&4O7IS(BcURLD+iTjoe;Y90;`TumL#tUYoty+CRK$Ha&!e|$KuNsGbq=D> zv#@wQAWGy}fS|C|l#a+%lqiimvaIG_|zx^$x6@9Q~ zhgjgWXSJ&(m(fHAWAQ1dj~i{}Fj{P@u)_BN-#R~Du+0oX?&a3KOb=iAYfPY)^kvrqx6omcAtRyes|n%hnm@N%^@oTH`vxZCE0KMB{6 zbEO#t)y@QHBDM(i@hC$XnE!hfo-g4$8+>cLKC1FGs7X&d;o?ekI&EvYa=5xS8rU@w zxJx^g<|=_K@pS0PHhQaw1#DL878Tx<;mw;dv{a&7bl|Vc+=6rqH$LC8?fH1Kib*^c z=+MpXIePxy$u?V`;9gldU+kXfjb=0Q^h%>DjQWTD%J7u2Ha-`ZM=5jK3G~ZAPU&zUcnB)>t~=;$fr!}t`2lsa7T_YpQ*a0_OC;=ZlLpE z^#BWX61rI1WX%k@=H1wT2~SU<#l1aW(5v0i-L{^(R${^fy!0J&17y6oc}!XbaI-`p z+m_;si6GCSSt-WIVVzbsH#W_ zOfXebkp>@7qSA=?Fmm>DaIkjpuC)KTczd%yjJ;ni6dLhKUx${Pw13K)9Itaqb~83# zd!1oAv|4-3fgNvh8T!aw#|h;h))8CCqnjQCm0j?QPew3J$cf$KEIT;OzYb=cK>^Cxc!s3WBye)@T70I`)7IMtLhZ3)e5P5nFYutEZ}oU= zN+Ax0l_+;H=&JS&9KkRH!{M3xJ3pNj2W!&P(U*9IZW@`RS=g4WrLgK1f}c|%Z|Uw^ z$VOsRZ#bW#R-@dPiwB}$l`nXI=?SvQLl{ma-9D2d>Fhk1B5wdxMVX3irKH?^t?O<4 z@Q_)-TETKf(mI#T2a7kCS}GYq5aL<`C)3|xlnZVcl4Z>A&6xg6CoC7*BxPJ*VLW5- z0*RkT(xTYD0cFh7pi64bbL%&YWC|ns+O(a&n&7QA@UzBXm&{1JA{gYfR*rXIk3s_K zH1~+XocRI+P&*b7e~t;B-vJ>hkZuQr^%ySZx0Up6XKc&UjjuBZNzY@N@wm&=@+esz zqEz==0zUikidqks_u9W1B6lOf@9P9IL{Hc`n`KwE%@;fwV*uqvbfxkfy%zt2Lc{!s zIh9lmwr9_n#eP^J?ds~Mz{Iz;oe=4KKaOb2=a*fe9uPyHMO|-GAWwn~IYRKk^x9^f z_7J2`vfOM))$OOyuM-7P&7Ssd+djY{$t)~2q7~A+G;&G%m?9|)l?$SBHrn}uWUE4v}W0}^R zcR%wDMB$dZN;-Q8n$^;c!WuRu3{vP>U7oIh2uH4%w6-kbn41L3rKN7Lg$b^2A)_3s zb%eFU>y2eQ0GfqamMO6--pfP_zfqBsbj|-_`{~|d@cBjgU}8g)yqNG%Y^L9@IUw)K zB4js)28s2PExFVS>v=##3vbwKHLe6p1q1fnXX0z9n}Hfdfn_44AfLg_26QOvgGnJ4XcnBsl3c|SAac@8%_ug5tWt8Xu{a7o zBz|Q{A_XT~d0M2Fi@T5(rp=-C#<-PSj+unBU$sYTW=!DY!Ntb!|lec+-FOMrkvCU2%0B zX>Y+C96%`7JY*l{PK^D;a_Pypq9U_)*bBBYif(cD0?7|kLxRv>;duC(CnvfSIr#~l z`~4`k`^}^7)1~nhQYWK%n3mo630r?4-_w=Ou*t9b*IshjubYI7+z49VTW`c4o{APX z;Mds10~(&`_sC~M22s#tXUuR@+>u^DhBAv}vSkr}g(t@EKn?@pi`zDVFp!4WIo8&- zHNz`nCd5E6Bh(wCr=yF~rzNpy0MVY3+8HPLJ~)ha?E*rMzbyxJ>znZX5%AyyV*}E& zTF=Xzb3$q&=^7R^?xFsTDx-M-hRCBc@} z9(c=e397YLHnOHHXmrXR05?Hw;nG#n%)r85m7wi5h=6%2Z{rRPBxHgEhsJ<1SN~5<>630c928Z(^99sNN_|;^o0y*;>C}*Sc&e z+IAwl@7nS<&)oLd;*r~IT_(I8Wo_N8&gkM2THIahUeQf#hex{D`O|piOKAVLEEJS~2 zb;0(_ShqiZg%W%8&-1WkYEfmo{uBoS-Z4FjJw@33WK^8*BUio;a5S?|r zs31;0S)JUwFqFLSPdOUe0FXDKXa4fluq<}kus>~phdG_5Lly%I2_#-q%M1A!DiAhE z9~UUUbt4^-6U16J_Znj}Cmq0cQ|RvQ(z-ezD`-{Kq#s5hgC$nv&dfgciMnlqGY3eK z{1-n}7GYB~`?~m%uS9xGi$!T3BG5r3ML1`;JT`&33)EKfUKNOC9Mpi&BoIF}16Kvc zpipY+DG%z7G5D5OXr+qq^!3#`)P$A78%)^Mc{8DS<)$Jz;lk0%hQN!Ey8&L&BQIF& ztSRh1$O6%7YAR!+p-8AbvdaL{2#`v#z^Q0J>(~+>h4WG=WF5`JMv+-q{`m$|igI7{ zfO);3{uK?X=xw^Z8HaEWOnGQHRmBn^2+?3mfcwAclB+{1Y-=;jUs$SUB3PiIX+j6h zkuFJsr{cN!qwOeJNY;xKa=Pq;0q!tvD1K;QC%N;n9bkq0`br{<3kLH-gZ!|hgwU62 zB+XF%tQW5MvZ%Nm%q#1myxv9QPmZ9=JBz$R*cMAftN66FzMQjXusO&V4d>59*WbS1 z%p|uT`|(_Vmaeha*m(`v#|AE({MzSd_oP8cDh6PNSV5KhBQBIpe0 zxaeIdn^z7I)M-FS9`-iXF)E1}C&h)%|<;OsY-z=49hq~6a3;9 z;ygP311O8_XycORjC$u)xKuNPjL))Hva;RvJl%hw^LbgYCQEv``UE2sDFWg94uD`) z0v;8-fC#fzG={?d3@!Q`J_GWc+>p9!b4;FLkLS;ol`iAf8aXlqfyqd(C~Ko@{<1sQ zQ>W;^jw4537}?22j@B;SvXaSw{Kis4--9fnnD2OmfMAXT35?>P=t|+&GlvcA7uqia zS|%z}ts0v?mI0b5uh3g=n`)%|wNwT&M%)b+~ptvLo#cy-tMX{hs zex)ecAW*j=^8;nzq2YL{opr%;7DDOyZ%FLf=1|!g46lz7p?@4rpYH4}(@^RjgoTMl z1GuhV?C@E8{0w~?>kqgj&imWR#$YObVfyC;gegO0$x~NYNIHKmjPk8;{fgrNy#uI* zoW%}W4|ZaYtU#8PKR{=XWW=dXiBb8!i&3q3>L03T9bZ%)0mVYf2_2w!b#;snzAlk! z+<_MjCL%G!)nluL+VIpxloj*)Y2S}&<3}fXamXGHDdb^?q7 z?#j^d|TQG`yuUY`YE35-tXJR^YtiL`Rn8Cu+#6$+VgdEJnZXZ z*!b5^aSXu%zb{MA*XMD!Z|sh`GnEm^+K;N$u2{ztu%Y~&AJ-L$4`?Ii~ z^t(NDzjW@8VKZclr(tJ--WS7#O1dw`vwL(U%kO`cztemeNcQNySi3*on~wZGOguRd z<@G+C-maA+zf3s$dc9e@-%ERCX}>vNul0Jen?BMg2EQJo#<%JCGVD*&@??1*j?9u$ zdp{109ec8C_R{j?c0W&omA+=llEQl5E)Mr=OYUAP?Z~>{&H>0spPm~_t4gT%kAPCQ zZ~C*5)jV0zhexwTw^GoLxBG~-kGEQ6-ZxLldObfLAGZp_p07<|Ucb-Tv%y`NUoTmF zvZ3G8esVqU)9A>NpQaUPy%|V1Y4t&5Wp%CA3lMtWrurglpfF6|a?zpgfaYkhuRj30g&O^AKJ9QKx^<;l>I z<$R0+cz@jI$HCsujvj=1ciXak%_~U1ZdWa8d$N1pfBfkTs5kfNHEUe^^I-D~;fq0| z-_MuxY{X5et_`vy>mY+VoD(-sPJdBk|6i6TBul7j)!}JCG}`XA>d*T z&!0%OKVhPdy@4Aabdor~{&n0_v%DU{v1?hvh?A==R|P|n>XqvUV&)Z&GiWj{W9E$!k-Wtqs@AF3NPbV`j=OU4);p0) zW2^53s_2U9ctE+wEc6$-UbxqF?Y?Mff4TppmaIA$UrP$g$vxx$IX9!v{Hx(U(_*KG zqEM+`DeNO2s*G~kIcmZGtUcg%S^dI&jcxr0pPWR?QCvk)KT`3V5cVY0O3N}&ka8WY z5aX56@Ni1v*lL0U(WPa+eYAsEzksbK)wYl9kEFF}wUc#^N8^-T8QQFPSr|{=JlW!A-AuR2eIO zk(aZr^(E74fmq_?*de5Z$QYl?Z)0X}^cm-(z4RV(Td;<2;Uhb3vhqlSs&g}s?yPC@ z<%}h3J$HJm+#wK~r*8ddc^b25bD44XJ*9H(h5V_$LBCYdiq-HaRv=5geA)8$*inpE zWzJ`SGevnla9C2?{D#CSAi{wdCA8}mZ&+Pigi-TlLJJw0jv-A{6rSS5Q7SSQZDo^O(ft^$gf~3a zX7~bEdx23DcsLijDng8wUtpMo-L*_2gqs3cuL&sAMz6-`jS=`Q&2_w^5__Z`PzyGA zL!fTd8{^`)|K!_C5LYjL)le)%mk!P;B9w0|p@EJm<|r-= zxyQO{`P*ur6a4W15#N=jxib#@>(a>$HRd0B9{B;(Ov`b?*~5z}cPjcVFc zdzl5sOnK<#8?oI7A@>Td%R1C@>=Z*Bq?W(G6S~nS%uL#4`i3RIb&?%KmJ%a4-JL~+ z1q8P1|9;QJXzpaP=q>A_MHacyBm9R~F_&Ah!RyGt*}h~OwB?M-J+mV9;9I>^<~amj zCwzX4?VPuGZp~iCUf%jJSypqfMu5-nf}0ypv)r7!R;rHw&b;chjs~yF5oQfdWEaN) zy(Q3NA)Rf%CzEOEVwd6s18vlewycTZ<2{?glNm8j3G-f$R4TaIyl!T&C3JCVZfq^c zEy(|DX?UY&EiXc#f=vFqT(%_1184ODo)FhB?QhKv+YRa&6O^yIE>3gWm(olWw&%x{h&A|dh(Hf^RQn%!kc465>=KVzJ|77i=r~3f*fzkiyl|1Tv8!QzM;~@ z0AE^F%&z+%qb99l6_b&wB^e2H^Ie^4_2U9#8NAsKgnW{zapdA4A`woU^)z0QerTev;Vy0u ziA`dh%b})0S}JqQ%Y_c3dw4cDcCNRO<+p}?7tsAGOdulEKM6JgT(>v?mAd?=>lKoX zqNVFKh`RR`iu539`(?So;wZ=qFg>P26WsXk_nM~~l~F)97mAM)Do)O5nGq^bJ(YsB zDvMHPBVjw(a{cToTaVjC6OWgd*FN3shP9a1@O0jB#aA(`k48hRhVTgSU-m-^Gi!Hd2-5;3Q7H;bxDc@9nO6sqg=eAE072E{~N!{p(~* zrX8k^19BlBP3-Y=7FfO#)qY~;ZuvD9HDyE8eHzi=o(TnmNHIp(l)- zzM@b^U=Dp?Ge@Lk(s9PXYTV3}0?a18bs+ zZC264TB>-?D}&p8VAgj)Sm(3JR~F0DHf2_dZy7fq7GKk(>U^50W(Ek87K`$&em-{) za6pYV{k7a?dSc1sw*3x?%7Jyh<|p4xL@^)JQLF1vilezcQFxX@PEC?N)de+oucDj` zT{Tlzw{^XctU6iLRq5yq>rd8CpW-U#zaZ(FL$;JCA z>Kb4ApZsVr9cX`eQ)o0Uh!0qB{a=ME3j8e)ReA;#W-~>uc;EfWcS4>a)Stj`Y@sTJ z2COKP&(EfzfNQr7zzs+O5e6|(o$sH9A;{7yu>^_A;<-VEuUW!_tyn{bSs~~HmIOE$=>KDG?zcc!&0yvF>>-`+Fv&B(F~a()6S%| zlDG=jk4o1nxtE8s@+HN@DO;LxVOqwe8c13fVw%gJS3ub>Ao)r3?zO)E6x(f_8zLf- zik9Po)i01r_;U#SUgIy_y6K}}DT!O}vvs1LAnuMI7XVQgza8mZn>G;Q;X1ba9BP`m zf3No7@s(}42A$MFX3tNweYzI6oY9Xj*F5c z;L2cSqjbd4-j1t8jkt~Gawp)J+jYYnJ?qH(X}>e@m=GR8pw|?JgojG`RS=i?oM~~1 zfm>P0qj|c02qVfzL-Wit2F*fi^gZTn>$VQLkSoYbZvfB=&y}_|Dc(%0t0c86WB{5k zc~T)gkzUdrZNk113JvP>sEJH~C~-3QnV zN;|vk;E-L6$fHe=^?OxpkYz1u>%x3Y$tG}v{nYmyLuY*e{oU3Q`t@1JI1`PN{D;Xj z)2XvOeBsMGsTP~*ST5~hXu2}1^>w*9j&HBB_Kl`U?dXS^cgmAqYi?g^d=lOAMt3*8 zNreSyD_3n4;Iw9u{G{`B@P+o?^~>T-^vm4D2d=A8$7ts7V?e|3_E zCn2L$2J@KGD=Zb$MFp5U zJXbM;W>soydoXa2wLCjMugaR`&W#u*@zpM(#k`NDV81aLtDUUOQVTd9FSR8mrhG4Q zBWA&-#Kq#c!0Hd{c(A>|Upb5J&7IkqUal1Byu4zgwGhgsKbwyK>sDsG=vDGQMeUXP z_O5V?9q*wjyg(<+2rGYiX!rcEUKBF|Gn3}q-c~R~HQ1!BGj|C1dnmg7idr0TQPOg@ zCi@1WZ}q#1;oz+6(mcH|E@5(ljy!1k30;rHBh37Bm(2hOV^E$Xe;E0zt8`J6sq3y1 zUlkX>0A2?BD)zCmx!IZ1DpteEIkS+Dx098Q^Y5yi&J{ucdTTsJ)TFyFbl_$`iE(S! znUgFlZnmS26V#XPhH2QGb)bQ2Oj)pta5;2@lc!@z9CFtk!OP{rrkW4uz*DyxAC2t} zYog0Zrx(gH*-%g=u8%utkB&=6-LM-C`c849EnVlVk!WTMYw#mk);4cgRo^pG2_oAQ ztamTodxuZ{*_k=f3f*pbJFB>V37_lz*7S&I)bqT$P|et;)c2p`C`LG(C9UaJ{KCr9 z;laprz-QeXVSJ5c5#SuL!qO`QP+H=uFd{5+MI3#`c`YxWr#QEI+({pJO;FC0X?1G2 zI>(c;RQfs8(kPh>AtRDSF0YJ^!Vz?ox4cwU0#{!Cn9&T&^Ee#bCZLdp9a)%wOT6?H zF>6!2e0lCRpS2y-xroeH=7~tMeAVJs(o8$!+34GAuA?BRNeUKuUegu1Qjy}^j)Dw;8zeGt9vto1(Rsff@f1hKOx(V!^2dq zsV5lYXbdd!3tkuD+Y~<;6x8sho*==DEWo%+@ zzfO^QTzQ+{(^kLK%*y%h{&3a*c=7Ujm|h$gCNd|DY3173`Sbre6sNHtfI={CAxf5) z7-<6AR;aIWfNqV?lDd<<)U!2BR=M!8a`dG3+mgfoSh6&W#_YX8f`+BFqq9RpZ-+i_ z(|Mb|Gur;b(EM1vSn=uQ)GEe*qwD5i^W(5611x!Tsz$tkVO3w0Ob zHd{OOr8BhMF$A)^rN)bI%i||>fBonRv5~o#w*q92c+qrB#RU4wB=FW+%$_aKwQ!Qi znQXgM>>hwRFt>KFtrYfaKft$uDFE?;tmF999bE8kI6TZfzS1;3YNQEXS8XN~*s=gu z*M{*>X6{#RX3cB+BV@g^&CxvMR4UHU*2P9$+>7YCf?C$cyI>PRs=7hi3I_?Qor6Wp?=$nWk~umrr~- z4^a{2K;b)^KIz!Zz0+1>R<9d{)IY5_7cg9TZwxnQL9dTJScN%JNS3QVOryi6{hK5* z9R+dxuSsbkb1uue&V0GA7a~S%O#y+G`_H+vCF74J&nuoLZ||Xk7`CicE5WJAv$4dg zQt?_<(xY}Im!ihszHvpH@uLb{M=-dB3A$i^V`L%wAeNsus6L5n9&p4$-J(gB>z6;@FfHQVevEmfG#&ydC=fBRD(eG1ANcc?-rc?pfvIa&8pL`*+ z8d^2Y$%xkO5@3TDNlX7+#F)JKr&6;2v^p@YfH7pb4&r8(Th?S7 z5eL|C&eCRk-$rTJAMeHHOz!(JB5$wuE;&WdCjYb((>t)1YSIXK#&;&1JB7~dPbwy1Dsu^&fb%k zT#g>ISU|>s*YQiP$AR+-j+6K7&!f@jsau|(W>v|L{r~CGdEj-umJ?sPajH3q8}<;V zl>Hf!s)NswE7ysILe{&|R~nQc8U~Vgjcnzd=l^%~@~~^{SB75}?Diw(hYogJ=d+7u z_u~Js^^Z}a1k1WM+O}=mwr$(CZQHhO+qUhVZQI?md){9A+vlEj$Nm1)ct?)-Q&m}! zS&

eDiI}Z21H9`+Acc$aPDJ#-q{7Z-91rw(oUpPF2_hvxSis^E41XkqJgh=ElY; zWbA;Pa|%cSog`^n4^}O$H3>wMDQkZ<^p*v{tFW^7I6?V)PVwI`&TZI?j`_%a*sN!Y z);hOMIuK!~rCMF6pvfqjieg?2AhznB*l~7BG_L*c4?F zU-sf|hJ-@JH4UkZYAahNGMy%TLDi;YF{w?HU9I6>D&;a66J~?Cc6w8Hne|Ax%ni#Z zbiU$=A*E~V4Fz@=R6;3(r5q1lA+15IgBcqb*bMe6iO`G=?LG$FjLRsH z2-DhB0dZ!lMCuLs3AK??3S^arAzD30r+{?RZ=yWb7!Etx$t3x^ms1GNWEHrE&VQN? zA#P=wguF)@TM8)&Vk|@AiBGx8-n%!o9#~URPB)KuCHP9K>8G1w)m`L)mov^#|!N zT2XU+w?jmmfaECp6+|E?id0m}3%ABx@wAAcP6_0`&HyH&%59PRBsCRlMB{JtC~3EV zr23QreqI8SO>HHd$Zu{yLTmzCYt<7WPhh2kP_+#XxCf0|6N#=Y;m#c7^e;KB0YDkm znGy}|4`A_7Q$nzU?L*bBhmcf^hLWpgnd@kXgHCCYDe=nNLFDYUJ9pt|FMkuT&knlp zO$fR8h=Df7*`CC8x|pD^(>mtS48|D-hWRuj^L4!<71vfV&f`+8+Lc8>_Q_2ZtiM)W zR)EO>8vcG8eO|u)sBG{NV}sfGl=l8F;4u&cr3cLkA;f(S)UJH_se5Kb}lp7HJ9Wu0aTVO_x>*x6YY#< zhi=YYC6JZL8j!1$Sel3v6!Snx*Cnhd#EPH(j)J;BegF)+p?>HG*9As~q0+Vnv-R~FD~g|B3E6s5-6i>={&m$913;G6k7 zJ{C6)>i1-&K=;WG<^GF4@V{pE4J3&4nCC9JO12;?%ChE789_JZL9?v)bwi@I1<0Xb zm51b*oi>*)Hg;11$#_v2YR@G^-1N<#LE)5R}-=6#V%H}jG9kYoUbkOwe# z>4+F;<=>cUJOrG!ud%#qKQ0U|A1fupc?IIQ`pI2oe0 zujdgFS=k&3kD3F8IZog3cOO1m%m&1l>+NHCxWI5yBe<+n4g4gOW_lV7P}vh{AR>$x zRE=uRQE<^!Ecpb~s}oGT-*0Atc0Jt-?)T}8fNRLBVO6f8m`Xf38tBP7;g*xnXRZ14 zj+ar7?eW`~ea(2zl^v<%+s1Y^I95jWVA~|&w+w{+e@>EAMrE5#bTf;u7Ukb`n*DPV zBCLNF*JZ&lb@~cj&;9PFOZ~;y-*iU9e6SpsQUlJnI-z94zTbq;ClS6{vD%mChPVVw zqaT6Ou-{>|>dE4bny4JkD5J(S#yKXvkxAZ&1e`tqOwXB0Fk#97P@9?$#l+pil?%F+ z&0x=DRWXdx+_&X`O+)A!EMft_Y#9zY77{S79DM@fS;5ZfAqZ#S>ynstqNa5;nU4;0h^hO`~mYFnbDzeAimHke=M zRJsuxrY5!C%9{NX>qUFwhFgfsj>t=*2}sul@F&4siyVL#_gz9Eul2c)5{@>6Kmvn8 zI5kQdgBNlF!NWlXq6(4r;q&#{$kDIQA{e&vudO=$d6A?aL!`oWT3fVi%E%gup}(M_ zgRe@l3J`{(1`>U;M`vTXBXx)?bwevBeq-U)t%`t@V+N?66)p)1=Y0c{fK}PbCKjjz z6t_NV!HE#HA*p#HrW#DVz|rXEf0s7d>jHk?X(}h+@aya5^>3F4zoMsCTU*M6NSe#M zGU#PA5u#IB((5A31=1b|%>#adRo?*o}x@eOla&H{LiS_7I~E zZu57|a)s?;UAscra1G?&f>}(hz1ddqlt%|u^iyK1hy51*{cpKWN|u@cmv6nczF$u8SI*yd3H;LZ$N zZ5_D-x*XcrLbdOBM<|%9v?yGD9Dn~zStP#mTSCA#l%PmnTnnW%l=m=29fVcYD#%%5 zwp1IpX$^lmjWQMJ42lP4zMTd->M>iyZLb>k@jSoR39RF0&N__|SSyPnN|(mOrXsgi z2MtwGY4#|49ldXPDc_QI{30bcnKuaJg?!%}z^)m;{Bwb~0Wz^&lgdk;eCOBP^9NdR zF6qSt#lc|jkzimfGnx~m_rwUkb6EH2$gDHkFn#m}vO^yXQcq)r4<)??hP%1tZh0su z?98R-(J0=IDds;Su6;ya{V4CpJAB>$)C?=Q-egLtn5ifj00Hzwru|LFL%yVGuSo;E zgph`~q7a#Om8+}6w6}SOx4^xQ>Bx<@{Fw@Z)DEA(jU*G5fg>sXL?z2HRd$~F!9dyJ?<`Jj z&caw6`E^pd#RGvI8%vg=U}#fXWcxwYP(xkQ6Q)>TI`t;8P$>Tp>d04Z4ooG^4dLw{ z@$@d-?41hfQC9^Ujj)4OBfG@E+VHf6%=;!|@&KLN#4}VlWqCPYTM|Z(x*-bldCj=I z*S86}>H>@NL__`uOhphoV-eyzmL%~ha6TOOJxA(bJa;ay<=)1;WnACW0V{(RqJQj) z9}mt;iqPm>0P&9##DEe}t~?ADft`;Oc~AGh&Vu(feI>2=?PzHEz*1e`C^&pY1o;kI zYJ(e~4@t%rT>`aU`6i|WJnD5VfUdrfGI38s_2ZgdyC~_))d5Z-ND6sRu`1zBV@6=nahs`J9Ax?!I8A`+>^MGBls0V=Uj--p4i+AC)~FjmeQm*K32nUl1l^U&MdeE4%#6|A@=E8qX0h@ED#yLlgOYap02@2yZn9* z-aBFSxuCh2D28-uDCaowV3>tO;DY(kAz>{mE>#XR2e-l(R)jb*_*DKfJ$)*~vk~b7 zWHHjfLXrynBNBjI7vL4`a6A|Yqk7_aGQqL}^;;nkE2j zO!B2FNH=`dgr=}GDCCq3w&E4{mglTeuI)%MN=RPjNJzZ3rrDDHH&5?9_X3ENMGXr* z0S&kyevUzk9JtN^DWnn#s$O~SWV$#QC24lvQ{uYB zPYKaneX%f@4E(BjxRl%+|C`Kf!TX1VY;Z-|h%t|Iw-XX;jHd9RSdNuLS8En)F*ItoUM%LO=eg^j=B}=( zbKUjMa@Rf2UM9HfLwvOH4}2ty_(&d%;3c0$yk2$6GxqQ~A_c#uK%LD9z@5hoP|z@L zxXLX31Pei@Q6UT$B7f0+ARlW&WLTDl+;T=dTLzhm_c1}{C_Ke~FhS=jJj4c>q4NGS z6dxOO$59V-Fl-udy(FXwuRud#Sut#Z0ZeGBj03-bmN2#jNrO*7oC}*evwFP1yZI1{ zhu-gS>rrI3xqy5I?Q){aV=pY9CEJD;#afz~?K7-CtwvyLj~ef|Kw>}Ez1&*<{lG03 zKN`|+fCodsQ>>hbO2A*u@>T^j5)5!Uq;x4w;QK~#^Y;hXX1ND~xsH;ov)p0Iaq(pu zWmld}HGebs9&jf7Y^d-b-6-*^g@1L1N*XqmFk~zSFquANDzhl6$1v?0L`+d-LPCg| zga)03Y70$a0X8Qm#Xnw3&RggLx0WXz3nO(ED}1^~o#hrs1J~E2S-qxBX*TakGy2VI z((GQ7=5(9?86^I*brkSWw|8SKUv&osbql4;TVMfW)>0+QFi?}Ix~MQ&f#ZZWufY`#lVW+$iYR7%XNW;`jEAq0$Sh%8Gh#co!~eg_?J&sSB65M$LO2{`NR&i^3{#{@ zh^YgWV0hsvycIaBi9s^6f`T5xRuDw8FZIr47xN9MqlKD= zTTsvZ*+!aXY!|oSIlF~TSgvkCbN2IVu-x5(X6)yEhBVU@V0+wTC-=i{k??qeU7%9+ z=hSvGGB_R$qSAUhU~Rhp9AkK04e9Rzp}qDOufwwNS+3PhI(-C^UgGT` z#~AUO{Y|l?QtgKmyU6ROhOAsHs&ZZwL8)xgf<6m8>6E~Z-AU}7Uje(}fG5Oypii@v z7(4eAn%u(UO zTT*v}R=v2z?}fo==(v}4-k!b-e^x79aZD;eD{J<4u?TFv=;#^hKVEH$wR%Vzv@K}F zPct{K9`5CE{&jPO&rW11ub-t-Zft~Wpe~-3T+!G25j@XkuxN=L^VT3!05VR!q>y@) z@J4mTr68tQys9P~FE8Cwom<;7@+~Yc3*Eao$EZ}r$4UBJTs`g+aD3oPs(U~DA~K$5 zTXbM{R@REf$0e!$&_>y~od&a^eiE#l3O|rs8130v!gcSv96h}ubJelq@+8tD<@q_C zaN7HgIQ9o<;``@CG_Mq9!f?4F*!jzSSZw$`PzIW&lQa-f&V4>enyXVv*&R%|_ovH>y?;p2FPRGH#f&CY56qNv!nd+^@vK ztuj4$3$TnpB8J-{oJN+E5s@$`w|3GUy8N?+ZAz+Lm;*QMmPC{|8-oQgw<>60e+dosg~RDvuCor>3mMn;txSQ@3HlPrG*a09)$&3RA6{OT zW&aYFGv*=|Acpl61w{mVPFV8{~C^9 z185Zb6^i3H)dwNc8MHG~6nAwaqbO9Hw0JU<;ICG{lrIGlob07|V+7z7FH5k7y1EX* zcKO6+?#RAb&x4WVk3*(ajG`2tCo#^!AbOF0v9)9a#{WsB_&-Fy_?9$pjtM%3g ztKiUo&YIJ%zt-jg*Pbq6$duloV}O-NH6}+#Z$>rupPDAldQTd=kw%QLc*Zqzt zwK}Qo1Zour=08wpgoA3YeBm<07)t2Au&~JS(f#|TfUnq}+|um0=as%_PQ$gw)*cOQ z*}g+Odp<3{b6B2tsPfbONVz^3eJoNN&)K6pxTw{qqr=MmZK}v&`{jYs=ALFtaz?F? zy4FRUBx5I8ngGa^@r^a}q-z`8*k1jQ6_jK62i+*ded7PeG zhr?2&2_k)7(Izm5)n6@Pcu)p0Ki=2zQpLHy{xbEEmLlx!DsY_BT9VeDe2R7BU4=4+ zwsp&<6-E#xDN6zlTB)K`tKK9}7C4}#{1Htzvd$|?q_WI-Xf+D-@MLk#)@}Wxr>JDw zc&T~_1U1BD(BZe7S7w!OtQ4UPM>=#(z@kK#_lh9wcjZr_zjtcjgSf~5Dl8#V+9JsW zL1=LY{yYNB!GZu$M!Ij&u!22e5Pw81PD1(Yln zS*0@Rit1=vX-�RsJ(Ql5g0yXf_WT0RaW6vc&Gm(|#HXx7f+4N9fGh)Q3ih+*lA^ z`6IwwlyDo@T3u6aPqi|+hWJS{ZTNT3Nv*<78l+&1l1jOVO-QJJsB5k#cy^9QE+4K? z6UA_XLQ{kUePi3I#r@A`m*QO)fFqbnYp7dc}H>M9=cWM@Dsgts20L*rijuH|^US0;i}g+W-n zTj8sSNi|JrT%kd$60$UxB{&<0s$0b?t{Q$=uU3J3m}=qr?!T7WK( zK}8XR`%uw3UjC*U57`EY>@}^Z7b${gCF(tjKuxu0h#lJ~^^vq%$|57-g!+Z9vs{Q&c-_@e>S*@1p1_YaiV>9T;XHS|89yLMC-#vM%siL2vnbiv z!Fu`2C0~}GuQghcF{#2TAaI%#l62K2md$*S>W&DMP?hMb3^`b4a?ueHhLLndVnT_n z$xJqA*D}l(VV)@d#7)k9eGv?b6RaV!0KaUF+4K6Yo%UB&Jo<-A=qksR!TNLNLxKFL zCH4mgraLl;sP45pZPsmBi^VRqK3#oQtwPqv+(ZxFx63^1*ZSlknLf+Eb6p>T;A!?2 zxLtU^&gZ-H&%El51o>iA3(oZ$ozO8fPks?lwq=%ptG-+}w6(@y?IkcbNhwwav=~XK z*XI8O$p#h`DnLk>5YmtJKwzg+sye!GjA}G-t=4cfHlz5j&Ts2tsehwnkK9Oc2ESpl z#d@fsB8T}HNI4H^1&PVf-!Pf56Qr6A6au@Nl1Yp-YPW5zdgNs#;C8$<^{K^6FgrL*A}^o3a} zncs``ra6T}>u`f>=n3bk4uUBQ<^h&L&H-SH1wGc3zR5a5c*F6C)}j0{hKo)pCt!BB zbir%TSI<9L#}-P2RS_+s(Uk$f8W2!`0}v`Al=>ibz3Ag@X%~5rAz)@Yn-^)_=o#GI)_Y z21k!|gWncgGLt}o%{wEjY!L^1$Nrf2uj;<^tHiJxN@Ux`Wy#q{161MArq=ygsEgwM zn~W1FahOH==_r*@a>C-g>NKX6~p&cA~0YxukfCW-M1~iv~%GL}n z)KFS5jx+8-YQr6qe(^GCTpR0Rajfo-<(&lHj_4ma-Ltp$zbR1ILIq8roF6_uzbZ4> zLVD8rgwP8PlM&*YYXZOq(?^j}*jfNJfeo^L6pY9aDI%WcV!SCSSf{H)@G~CJA^0qIXs{>g#Y2gg(v~+Cnvd`eFEDU!?o@2_dPOpYy9Ng z9=L{MXus>wi}oTb7IKJw);`U{NwpMi8b@XeQ5Ie{Q|YQww{5ee^Dn{^``G$tv%Rr$ z+~VivaCUnQc5N)C#!2Tido>fD+Q|Xuf|{5CZU0l6YftYSM%J8(-E8@&|K-~)WtLFt zdi83Bd^yp;`@HXfsOfDz>v5-@D^aENFpA~GRMV@)6Z_)N(PrJ;zam3w^>+3IR!?CL zwgdd-#g)INqMg4y1$DFNvUC^11_Tu4byMx1Vwu?jAID*7mV=aX(gjr)Ar)X*$N+0UqNi$YL@FAqTICFQ(ygEY z-t;OAK>B`AHtiV01*da&9}_Xq$^N8-p(BH9{K^=$KdDOzd93>~r@Yh#sK+w&eKJfmW$YY;e(i~)!@ zD`4xRC1}KGM2F{`-^b~(e+*}tL;Y8dRcc#@-CaS(B#vc_pr%Au7CBYZYl6{b7~{ob z6`l)Lq8f8><-Oqky{CrwS431EGO0_FDqDi*-f+yLKGPn%*b)LA+f)BNGQEwyh5FZF z4Srj94_|z_wHEq1D(Jc}-0;_@me2x~u9*;*LgQ3HYtYgG`iMv4RJe#&=FX2fyFMP` zpU0T)%>J6#AvnapfD55iOB9JIhOLlFU=g%+I&wT2NdQ{bg%Fy_2Q3c?7QBI8NC9EU zntkRI5Kf_XIMK)sTxp&jO*P~QxI41E^L z37mgS`u~gkfj!jE zqy3(AGnoDo>#8T^*wY2T--W@pf!%pn*T}~YTy`|q*xYN___oPH4Ir~A7}$QdFh9Fz)>tCvxe6BC0e-LoP#tY86l{&qN&eDrWU{VL7b zOZCe%Q*SpI2c_$R>#=%O&{uRAJnT8yPwvK1k;>iDa&ClkJI{wtmQjW)lTj5WP)~bp zyBY~OLr53B`UO;_pYO$9YZbBu89$>$R*EL`m*xJcgur;G+uzZP&+2!Uyo89&QT_%^ zp(T?q0eBQQ=i`Z8eR_0uJ6bR}&xUUayQX(mR3eE>Bv~w~=3~t1;q;e24q2){J3Y+9~ozqyE9v4KC<%z{x z@)f?7-4e@?wfPe(G^WFxlKhJsT^9J_UOwo-2Nj7U|D#{frK&?$XD>Es=sxEX%?KVY zxG!&Ceei^9AWJAmH*l0@hc)*qA0g z>k;}?K#+zE6tmQD4hY^GJGI7n&7uk;Bkh+P=mF@WdAgJ!O^jHzxBTy60c(#G95;m!ftM8BR5MjTt^dd0Yq|_>VcgZJ z!3x+G@j#!>ax%z~!MzvcnpJ6_0%{Z;qi_w{qB+S1p=K1p4LgTuv(u!%rvHcjl&d`^p7i3cz(pW&przhA;HG zFk0L8(7m3!upv%j=N^F>`mlmF1t!K`<3rFfgRYXI=(Mjg)*VQ*I4TqBs*oyy?^-0| zNvs8`RrxKOo^(MF0d6JNhBWga(h<6uf~~K97Z(MiBRPeNUM+4?$<)+|f|XasepXjS^&_w9rX03=ER29#=zQK^<~A^;OJ z)8Po;7mVXvSyb+joQ5o??lWYLzC!1tVPgVp`}w#~*fn&_lnj7n3O!a;*>?418E(D+=l35)49uuAw-K|uWZcJ&G1qQ}9DCVv?1jsJTG*bqTg1g=C%&M3jBD$I=hf}s{Z zkfKKFy`)tSjVik}r)r_6~6$366|iwt#mhuL-?@^b427!)J+MpgJRucO+P) zOW)9Bku~5DV9|D9FY&F$OV< zQHc4UN$`K}1eZ_GEj-?LYBNT$_#tJ>L+VB}N9oIl%b3UIVfe^(Yy+)#V+}JH5=?Zk zgHAFEkNE=Q8sR$0 zhz4X@j2d}uf9r_JPw`g7G-k`{% zESHf$!2{Z8pb9d^TNY^iCs9ClZgcr2#xVrA0o-LQBi48A@o?^SsJ__{!08m0tr-=~ z3XEEbgDk>{A6K}OBjzF@#MRyT9t7Zt(q&udrMY;aI(_?rb@%oLL~hOX*rwzQ{E zvV6IHIZr9q**M`lpwwzQlRt-quF8F0b_mVy;s=S@zfn!kt1bzS^Aeh$L}0dNQ_RmR zIG5M&Av(1{_sJ36y~_W(N1gfPNcseAR9@b`zRFL^Q>>;NLfL=G>;fWPfq}F2r+1V$ zdnag%#u!feBiMc`2Iu7UuFQVFb+1?xgkSF@`wAJqu3G<(g#3kLMw_*G73tMknwhaJ z&JWGR*JT|>(nzM7mYb;y(Ruw`HUNQ}B5N`_)agolRf!eGq=_oS*~!#VUi(8CoY(Fj z`R4vPjRxuKj4Rk#myAq~+QNUQU%kCnfzPv@L$AZ8Gw20OBOrx=`%MS|C>Q|=OjljX z^mg_EteuiB7X;w>K?*ykC+&Y$*HposvM^KB9H6>Gnb2rn2tDf!h z?nBmBqIl=;h7%v{VY!n?Bou4I-{BJm9wX!L z;V+AgwInjyn#f>d7P}d**u`wcDt0qkv6schSQ7v5>heF1<^QqyFZ2H&sVA^C5u8ft z;BGX~&vxD?aL>{kCN~J6mDdbmQ->gHB?$EE(QQlt&;YYwO$sNdU@!(yNT9vjp)2ck zaH?FSt0XD(kSZ~b;qD7OZ}oRN1m@JI%Pmp^Okp}ue!)9V1EyBxu%>ikcH2aosMkewK5sIUe z-OAyX=iJ4Y=}Ffnj5&r_l^{wO8ES!m09YzifQ7ctMp2C}u1kudFjk;cat-}*LLtp0OckXneLx-Gxq?o>kk^K5 zxT+Hnd%zkt8aOSvaWVa{dKbiGjg+JrbLt*V%TQzk0wh`|ke9)dcAnq|yCCKc-gNr8 zn)uwj;hh_*w*j%vsi#82T{odC>I8=ZDaO{`ZiU+tz&j8T2Ma#QXwTnw^RUv6UCBBie>cH z3w?ijJi4-fsvNqz?8qgUk!c2EZTnu-@8u`cwAy&4$5^m{qCjD?fdr(@!mD?#z=d}Rc>AYib6-g}@Wi%MhmXU%Gr63w~YY>$x0y$C1wpvkzb*4-}%GKSF89I3O z8n&hKjghOo2mzYeCEt~Y%xvV7OVY6Dw*ee^WfL%PQh}C|bX8R{BFh*hsa2lNj2flJ z3hGbIL(a<~=M%@xC9_A39IQUAh-v9c0$DbO0eDDsSj4~LR5{6wdCCu=;xeM&dU_%P zDAHQ*v7VmI$J;%7eiz09G{nCbQWQ1FSKRzo!3xdkIcL)9^v7K%@M%G^@5h1vl!8h* z<{D`-JT}Sbyb2W3oxUI)uARKP>{jrkK$z2k&$(+*U`>^t!a+@r2YS6rY*RUHb`ct4 zWm$7V#z6Z#h>WJ%>go<(3wWC#aOXFzgrHB7 zD=E8`Fp-Ogh{&t6bbkW2@3?;dx9d)8+wtpAsA{ICs4PK5)>2R-C6O8SN-66$5!ipK zK2L6sF(|Nt0J@)3(3DjZWw)4ZRQ31svyMBR0l%uklAxMrydmR?OInQ_%j!!!HP#RO05AY8VDNP3n@~jX;Qes3-e^9Umh!G zbV|16n89xiy=?dNo3M=J_M+~_e|IEYJ;wGFa3s7<7`y@goi-m-a~*xs&M740bZ_}} zJyeQa%fGiIzo5yL!;E)|;cPjsv&ES1HdBiGD~EB84CDTLNsi{7Y1}o@VGE6Cn7WDA zVLVDUAHlecY}HIKNf}@t&_Q(X+6E)`Jb2Ik{wef{$Tm6;0O=#Z6Ok9TgE2Riyg*lN&fIOUoLwI+3WZBXYwYYck54*GVuY zW}`nzl;}aCPPmdW`3U=&_&Q6!{BQN~N&`!!WHMW)h7QgNg9TJbtc+w<)ML0+QV>0j zw7o^7oWq?@yjqC%rqz>$+IpCEZH!8q#y!%Z0l2_{F|@mmPF%I(W}_=ke%HKReL2+J zEscRoZ5!j`VIp4KkLU3y5kDR-Yf+H-zxPkLEKkW>*|DSH7zZ@`Wxh(aO3P*_yW7>g;!q)tU#P>bp_>Ralp){POi>XAjS8 z2icmEVUo_+HbK@I6YJHh+*{~2O671o#4Tru!Ss6jdS!uaD>Je*#S83DoagwfRrQd6 zswm~w*>N4czQfgHPkXq$UHu-c)Q&pyuzgVF%iou&dFK5esMPQUpFUpD>*?z5r>7}T zD|c(^=NQVWy=I@i7{iyHXV~~OWVZf&U0QvUt#4YPVYuAbDx36vY+p)jC0pj-#%%I& zTJmDKW@ZQSHTJZ)8DBe-m^+_tZY`S`pKfM&vT?DAcRRIE|DTJCOwh;T@SMb;4c)U2+?Em|F{JVkSvKX6b&ZU-zH_NM)mG``#Y1W12;!WLY;ga?- zDsl0WwZp=9UT!-s`<~A&%|S(u`*0$_SCF%@Jv%&g-rF;9-qq$cRC6f1(?j69Rpj|Q zfYanV^3>4OR4x!vO48~#ANxU0JMd0cT@4PPPChQx#O=0cu4@kM#c2)8l$@>=R4;X= z8t3Wd+1v@_x*T?iMU*q&o??NkH;7teY0k3JMnb-DeYU<__vpc#Q;LSIEv2#z89|Qz zjkG$=)TXR?#(miPXqO2nLs=nd5Slb%43jg7NxZx8Qr?SDBZ4U_6a_XyHno*g?S+gU zx1BlIaE(#c!lu&Hx?^048*QVg;VGL;S><3BjK0~ZWOeq-o_@k8`JICyVO_AP)+buq z7QOL9=!2~_lYXFLgk=Cc6k{eLQz$hH-e6&OB2cZsSmCb?L(}WgLKU{KD^P4dJ!`Ce zS!@+i=HIwpwsm7>TUV>B41c?PY+Ce^AvrFLCuc|Vu3m)ei3j-vSjugqZ(wbs7WLhz z%*yh!1KH{q{qPG>-6KIXPn9;=JI^jT&r&@1`WAZerh*+I}unG*W z?`F!(9s6*}pQrcUl9F!I*EMx|iafU+WaPBX(!R9;0{dqPFWjP_?c3B{#@tI8+p+KG zMn-g1-^Nf4_D&&a805Q<(e*BkjjslHi41HFafMuBkS1bk#BmZYBgiz_3SFc$GIl7@ zrV?UfDleTwX3)X#<~a@7Q3e`gD9YFxIw0*c1Vv_8LlRR!t~nVB2BrephlY|NOQ6M| ze%(7QMHm)xVc;@0vz&*FssoF1Lt;=2icP5@F(?-0np1&+BI5Z$_3MjejT|%@U^au6LlHc3ZtxSF?DwI8VKL7gVFi-20FE`Es#f7MYD7p zH>TISzS|cJ)z$;n@{#B*--a;PfdhhE+e<@gefO?zu7jjxq%UeL0+2JIb>qKNK$%Js zq*qz->fJ1Y>5AkP>}0~g6cAm`CkwZdtf%^t*d~pV=6@YF#Tu~=F!-!^H%gkWUYdNe zQ|XBM=OB%nTbjRi^6pmM+1o}eeVeCjrx`~+vxI<>80&W7r)i1RM=ms3?s#E%v)3}J z>6MF8QaWLP2Nm*q&z8(B3kL`?CBaln+(NMh(jf8fhKTFE*wA|VoZTGHd_Te0ZL`+F zN48(p4J5y-_w*2PP*{&lCF)Le(X|-cb zG8w}VH9h9V!m6?*6Fm2uMViy|dv$izR*!C~3ATR=rAHHJl;*@`8QT;(l77a}$i&Xu zSUlSh{p5$Rf(jp%QmlURoYj*z?-u)8q&WXv!mmibUxQ1&y-jU541Y${<+WOvrc63! zy}k*_wg3eK2D?T#2rR5pF$n~&GO%D0(PoU?eBj37)TH7z+fpY(*KL0tW8hXTsNCgK1 z2yq5`XR5I-VZmcsz?xtON}>=@+KV^nBiQ4JFYm!XWFa9E4hfk`<;wYhk9G|o$Sc1( zRoL)!zV*I{7Hi{T3IYEMGPIW3Iw?!zI-K(L#8T@C_KVWUbMs{F?XXI|wkx{}S2|n~ zp*D^AESz1g;nx$j>wBIp8?K=g2~K??h^LVPx^^3DE&y=raJ^#Cerf6KT9Zk_LI6(_ z#P^0RUB%h1rC!Ow!2PZ+_IG`*kNa6&?DrD+XO#@Lpv$`+e%Ihw$X}9c`V)g?vO-V{ zhRHfnAt(mhBo^#)QJ5W*aC;@D(f#$Wo6$t?-(7rjQZ~QZ@8RporS>}v{*8iQwcg*O zt)XoGzMp)0znxk$G`mOQ*Qxk=|L?=`*46nee4I*vv-tXl1Wm*ISKjs&0qeXzY1Ed} zHEGv{Ea^KHA?@$oN0t>UiyQj26=7>|9_rT>SbtgB7JPHjMZarR(QR|phv70Nt*`Mc z#|=6mW!zfb%8zi_(3aO`-SuwNj;rj^CHmb)THVz>C%vAk4>RH37PFx=D2*4>(>~Va zPj`LlX6JH=rw4(XmQ%U!OUrM=y>>q>=O;hV)}PrsZQF2x-~!1i@zY`y8P zG~(^HH0jjUxRbj24Q1Qfj}rDHUX~pdM_bSzwsoB=;wxQd;}*A^e&So#sS_-@40yFCRY;OeHO;quO#BrZgf`B<%dah!Frhlj0?qrxc5r z1P5n_q=S1H{ZC8&RQHdg?iY@dUMD1>aW$> zc-5P03`pmz%k@~%#jzp_Vtt+z`nVgAaXUF<_VUK;<&9a(>r<9CWSnitxc@pd(X-$l zWE^1#!x%#tp038}Yg>9`oQhcAOEwxpX%CzII{NNH8qMg8o(O}|WQK!g$j8qdk5RIf zzmMMTQBY((T5vX_I^&B=?Phvy~(V;%FaZpgLwlBd3N%gBntd%ZiHbv zVp;_eyF_}c%Qgd>9&a&q=+ff?*SA1MsNXu*mWJVaW5D&wW#AWKQ?j`9Si~~Er#Qw$ zp7KNhFld=d_>yvlLwpNSW&j)>1KdC{yH&rolasi|O@eO1=()p3jwgsoyix0{3Dkld zECur?Va+7nVue(L0YU4&ls+{8pOD?fuK4MA=L50m=SFQ z(g1?y497=}&MckwXFYAHM6czAVf#W`S-g!d{VWb+4(LITp{VdMbV`Y|e0?pkS9=MS zU9zwPOX&XtvOrD0sHKItAvu73>BNPe*8^BrREk3F3F$QuEoNVQ#wffEG$v&tKo+l# z*OOdWVKe~M^5jCP3MDy_N-IuxOC4c6QPlD_5-(M&iV#6PrkzSxV%1_z4fNUe_Lofo zp}NLj{xZG9*XRB$UtfCM6kF|WzPf~!)i3)Yi&r^l=aK-NXdl&C(+pLTToYbvFlNp6-=(w; zwgm80L4{H1FPLEw`&O9>vQ%TcXb2ThUM7fh5qL+-m9OQ$JXKUDwy_jPl`F#(sV#(v zhZRU1gacv~Gc2ynr8w~CY3WvD6(5$q`}ak-Gfy#fB1oOBK^halrGj3w+|S=k^9{7m?NuX1XGzPsW8kE<4V(KP(Jq`l z|K#i<)rYmz0aEvxN}!w=|<%uKUdcShaT_ zvT+-}KTng3IGr@JIGOz(r2GGA4wyAN<>Gn@YwKgds?liy8rsUNs!2=jF;{W^bDv+dQNGw;e!x%SGa0oV7xKJ#6{EL`hg* z3QLAe6SJ-)P!U}?*EU5Ailr|K_01jiRrYo(o$nJEtyP`nOV z3m9L@X9q*3DGYjVklyUVg{k3^^&-IrEG5F8!dsc34NcT|lM}U+^AeMRt)8@~MR8$x zWrM-`9K&K0q?5&{S`e)majhVl^B+1E#z3SQB^w7L=!uwSCh2& z`n%s=|K{tj|MF(`&maEs^*85V{&M!a`j__eKi2KmGk*zx<2;_U6z0 zhj)Me8=HRnoA1=0zW?pVKmYrOvp=7GE5AMaj(@w;vwo`2x((v5rxEj#|KqRseBN)r z`Q4juzneeto8P|q%jK6=y=xx!-F*If|Ga(k+c&FggZ2FS&AY$+X8RiS{`te3um9_3 z{P*|&;Qsr+o`$nOpZ-bw@ihMPAD8j$A3y!+``+h&fAjOV|M>b(Z~pR!@7{dq%gt}z z{Noqqo4NUh){lO_{E*+=y#3dk{`#za=bwKU-S^Yx`kQs{eEEm}_-p-dICJ!ee|~$L z{^K3RJOA$Mx6Rj>kiWb!_0QjY_jP;4|M@>XPwPhCX1?)n@x_m?m4#KNm`JeLxMW-< zCu<)rC=gxU;Xl5v-6Na6<$Gbqm+db9l8P_y?c6=XXp_IGNdt{}H}2*A_VVxD-{^(= zzW(JOZ;!o~FaGnpGwhdt{`oR+ssHf%KfjOXe?0vc?)}3zUsM14@80_F+0Wtk|G2^2 z(0~2&ul0Ag-<+=7Q|s4n@y|C^-0PRP&!4aUbpF@(;rkD3_tn*Z-Tv~Aw?EDA@gHyR zV2P>!{o$WKT>kL;f873yfA=1H|3muz^y3fT|K+Cl`OUYOleIXrb`5*~{13{r@ zg{k_*|8DI&zyI#$KmWT~m*4$s-8=vEHvM*Wz3|T8b$IiaH($T`&29bD-`}?QxYzy< z$}0*Ek+ZXc%ILwrg-|hbkzrK$`|kggzAUDc1j3%6(~Wj18x>s%lIa9RFN4RwIa3y} zS@*iofC&uQH;qoZM#a4@(Y+%n4|MkB&J&i`7nIV$pox?OSZ0J~8ekhS zlbh2{YmbKXOWdtwg52L|?caQ5q(N2FOJriDP=pECfJ!vY3|6jN9q-kK**!u&PVe4# z=G7C!y@pWK8HPp=jOGMe_;p*2HvhaTU)`ri&#u{=R)cYhy3Ha)*4Dk|1uTu=YKH~! zx>q%K%}ATikDfX+lrvLPnFRi)gxY4Mz$CUh!hrX+DDJ$Q?aG*Vb^#L?4TpW@VMJmw zJ#0lGYtAiGR^^Dv%z{!CFxMPPz!(=plCbL4qD$@_cUB2lWoPP%Hvy#LAqa@Hv!%(9 zocGIou=7zHo5Iav-bX$_b%X?xgYws7*T2X!M*^=Mle{vS77Ow$#{BiqJbzt&Mcsr- z0aiBVuaEibPa%Ij)}Gyf{6Y}L%BB@pN z_>ZX(9)N|^szj<{3CY)5L(Tb_&}r#ek*i+w*;$dL0epby)>9|72BqW#`%EV9qI9%5 z$5BtZEJ|rM=U`H=qS5NTu*VHko;b}@bruR9ES0LcS9^#Czkhdgb9w#MmtS^LOv>~_ zO)Z(+RDJfv>r;Q-FokKEZdSB*B9y}ppOy>YfX6UFzvHtK7Bt zG<>}CY3t%$t^@Y|;-{5cw4d}ZZ$DYSa(+&#xp!`5yirecyqe7w*>U~48=U+!ZIUdS zUeyhy9ux^#J^6rNQr&Q*W}kX%tyY5XFA|b>y2FO3NOZ}`z`29`?jRB*TwL5#{dBpf za7Zqhe5tZApER=Lk{%`{N&*uTjRZ(YiB3M7VrtPUzrU0y3Apej*0VZ=0O&H{&IE`` zUrKtZK-2S9N3Io#u0Gk8RX4B$dgXunt6npaYT_Mf!Wy%Qed==1)4DTybDeK)FYm5! zU6pCfJFKy(k(4NjE6~Lpgw?@RU?R~2*0{EpmWmVSYJ0k(Q}GULr8y3D2MK0sY*J1y zeg;v@Rb2uF;=A2Zz!;<5?kWOgkvhFrAga}TaqUl^izw{4f(LH=A&X*Pp-9;HPHEz# z4g?00)wBj(i(DrZGiFRWyX-*fU^NpvONABMa`tSM!<{K>t-OmXvg3jtCL^wZm1HG} z)qxW!Y)&o~rkkTAd&-C_ycVZ4#A{E9Dw1U`xV6+h3~;!KV^9uyM-jo#sWHktTM^lD z)eaH_lbIt%Ly5v1l?29%i-}5CgP;2f0`3L-7B?e~7f|2;OCwpG+9vSF7X+qiIV5X# z#ESZJ?X>yKG|2D@9wZc2I>;FhFsC6}xVckNIT|zD-{!=$p&MM`^&%4P(kZTUcn;lI*x>hsuE>22)Bv_E~LoOcS+|@thBl z1C2qkOk8FVQ%$ARHt5(Cu$jw2#R9T%)psx)u&ze%^;W|rwd7d={_p}EXf)ua28N*q zU>He>&?4bqV?sJ;RV^{GRwOEdl4uiSR$!2njjKAassjsf_^Lt;WFv{k0uV4B%B0J} z2zSV;LXk5Th)o*69ZV6?GL@_!S9M@j2NvM)RSm?@h?Sti5|y;Ue}#8m9FKzt1FJf)00*yXO~9o|5ind$qKFbkyH~CpvRA96SL-|l7Z?#wM~STP@An3LtIdX2pVFRp8Kv?*B)!z+$+w)z%&t?gB3iaVpBTm z+A2MfLO~0yUE6AGQ(60>Jfqd!wh#xeZjI4JY&j1O1~fH^N2zlO{D9Sk;L&;Wv$PqZ)fRvcv^1L_fP9Nsb-eD15C6gguTzF7ngaSg0Wa%R#RJ6ip_PUK$^QR zEe^CHV}GaiD`vlF||Mql&Uw5bU$A%lV@=OR8y%xUMOb~;&Caj{Sr3c%2bwuIiwBR9PJo!@Pkg*Css zyj+^xJHMEfC%yRj<6X%Dv5E<|lH(r%u%q$l19buTrx>VP_}-Lz@#rcIkS zZQV?#{^LolYOpC?WGHo^!K&+=&wGPt>K9bGZaSmon|BvY7VYiL#hI@K8{5JdwWrwi z_3_|mRkVh{<+>KOU3%Q&v&F;O&#v!2YM{pLn)O@gozG7;1``%W+1Ot;W(w?3=~zjZ zSdxy7`4W#OFN4`AyUR;kwEASWtoi+Y7-eJY`W@HYSqVlh+d92y)MLuWK%&O8GH+%@JSVdvRMTHt zf9od@p~WJ9{_-=B67oFdr|oHUeR2AJl%GeCpMm6)=P5s39Bh=GhnJm!6qn~IJF~#q zC^`=+^^rG?cFMJVj`=Xwu`$P=BG1D@J#- zik8IaPFm3;3DUOApl2mWwMNEdsUFA0?aiklLaWPtd|_HjU0RZ*9rLpuQNo6X@vJ0l zZ9>(jkgeY8H_0{WYcsrvHKH%E38k|>pHTw9?SOfwlr1K9qT&QR0WFFNg6t0>4bnEm;ay6LdHYiu=;^*^rJ1<1()gpAYRirFaRGZI5q?E_)oMpsm zFnL}g^TLTBJfJMOiBlF^{&SHf-?Tf?g*a&f$x?D^e5f5uMg-flhRnlB9a9sg zxwGOkkvfx2-MzUG>y#pl7n?;cKA2CbH_PZa7cp0p(6loUv4XE_}@@ zt4XbM3kJe8@tO-?yU>_8^0j?y;`F4hdNEG(S(wJfA+P`Me`miqIlrwv(ka!pJxRED zUh6k&uJ6KF%_O$PXydy&#IE&czwee3wIu!Z(t)yhm){MNEZl@T2Kl?=ciZrLF|pjy z)zDLQYV~VUul9N6N{A$d5?1G;lgJcOUw9D8dl{$=*?6j=b(%hB7K+vKq*zT65-B3&7-dkQsg(3I4RKuWmTbn~b;Rz=Ca9QGF+yS|YHmmlSwx+<&^!1p zB&%g9C|xM5<$Gt(ac`K;#CyT8=_wT|OO;$z45t@wr_rCDbfKhPFTZemo=)@0#ntrf zv@NxGNIa>YXvC!Cv&-dhR#$IsWvD<;VyMMXjY-5|LNL;psn)&Ln)3vZ`B>+|uv8-O z7U~zuDPPYPwKstFpj@0~0mnS;jc<{#{oqRvy`Ae}j+CIcMarZmPS6l2OrE%vd+_S3 zaL($rOP`3BO>#!?#8QVzWsJp~!90w5T1&sJG3MhfeIEs>+$#! z{%VyIDH9^4Cb?o=sNJIRCzq6TlSn{Eqr8nfH) z=eK8}7VWJD*R0?4?Rjq(&OW`VfO$_~~hVCA@R9sb;lTYuorc4WUZ{%1S}Jt4%?jq&i1! ze3PrPngB*aZ4MU+ww{Km7A!WO$yzi;$`dB<0+UC zh8nijbsayshH7g}qvk|T!h*Kl$2&W-%M-f(a!24>RT+K2%$Q`I1qlY`ZD6I=0JqAs z(&&dO{uszt#h+g1_5-}`otq@s$bxfXSsj7RxC^#+R;<@e`c4=6YKAMU7t_?2%oXL4 z#;CR7fHq~52ct6FyUe+C3C0B;#+i$ZCuW&y4}d-L#&Ff4V15i_)AW2kzj)$7_W6^k4)qaG|E$T+kyu*nR7EbC}2 zrwZ?BlGF_1-F%O}|w#|z!= zOMQ0OJL_@|Q}jSSo(!=e#j0LhN|u$F%h1j^!V4aCXS5sQq#lHHSdyKf+HXDm|kzQUI#1q?vbEMd#Ifei%Uq9G}s z3f?AV9)Zmiz?^wdfooXk+!`SYGvMUO1en937Gck(aBv;*DL2p&9N7DE=Yuv7NH%O4 zSg8p{W^hm~%El-JM(N$q20FqEK9voW(wF!4hi}?IHS!P)R5wibIw_F-=oKu>;JMp% z1Jy;UjZmooiN@qr!r*IX$`Fhl+CaiW%_l`c7J@P8jnh#FLt)vb>Azw>dH4|AXsSMoSXjq;=EB^?JYT6Q(B1<6obUD1PV zrg|fq{d(EAxE3?F@_5(^sZ|6K({W9Ozn`b zaYz)WA0gS*kNKp$Zx0X&>79q`=r&BJGQB!$JU*4Edw}^u{8t0li%47VZ2RKFIX1T6 z)U1Tw58J=OX1TgK>4nm|FZ0z|4cToLL`-JClEM4}V8rcdeUY@@kF~Y_{gQ;Q#!5z| z@~M@|9-i1ChvKMIc2g=xa7@2Ir7{!)cv7D0QK>8mq7k&;yXKLUN_RADlU6x~+xSk7 z+f&slcQfhMYZZ2Ht+FmgG3-EjSe?-(LwpW8;|L*}EjmM}304LFw^e8Cm>9mIGw$S& zJ*xf~j+8yAz|Dglc6@aGv1_9BeKgG7r;2h~e+y2nbzh5QWF%eFZ3lL~7-*ommmP`#`>@^^prvgJ5f zCoNrkIr+<4s~(FbPU?9x?BLJ{uYd2Sr#?(iv5`+^C(>@u>nNHgfxD@TwMR~d^Udy? z-9BWL103_)tMzZxRD{R&yEu=v`F0QQ9v)rIwEomAfMu+`SH9D}OTli+4l>;0o13L>8)P;awbw4Ly1bY+`{|BZ;hl&|vLw8UJX@=|vZXjr zOJvzPPD_X`d2A9XOLQt^ssp&UVS-1~Mmm}{Ef9kYb=$OiY5S=5lrHx$6R4^B7QBL~ zVjS~YMya<7(p7%jrc~Zu6WEG3q@HDa%>A=wR7=vfB$)q(Ww(@e*jab%V0Xcu%65xo zzhuL&D(09vr4KuVBuQ(UL|{e@<)h4O@CETW@&qgFaHDjr6a!Ea8<|;bWNSI$h9`^Z zli(PyXYQ}A+Qd>oaQ@8$c-R-&_`OM8D+;@TVpB$A+Y$d27PHgzCE_wI#Bg7rFky`| z<6(-cAhKs0r>{D^H%{LXJV^Ub-!LLH0(zUKHz)c1{GfiVP(C}W(mDSo?HpHbw5F`X zaC$_01&GP4d*7;qvHQWrY3@#@_=1gi(lVz?)J{(?ey(78b9I}0r3@Mi<-=X)UxZ1L zGgHZm7_>@8Y7UZ-q;olXp^Z@zj8U1)xy4cxSE7I}kva;jbgbN_R_gEEV7T$=MRkMs zyAp(4F0S%yj9mcW)KAY&uFw7D^}7p<=YM})bNB}vFc+;0!LAWRD&dKBkZ)FVTd=Wm zac&pRD+F^=^iKAi*RVwF2MijTd8eGegHUS=HLRi}JOrhv^@fM?dVa~w5!}A-FYV}4 zj?=DQL?bIF>Eg^!&lkUI=B54W(tkX?@Tr}G_M`5ef2%F~Y61K={hPn(R(ST~ekls9 zaK5UT+*Yn%ghRTIuWuXMYW8`#x;Q(TDT577$OdMhf0zj(o3Cn+XMUse#^mfm2L86H z()W3(&A`%6x(ffT*l+&6u?oAduQAW>8%djUhqIw<78tC`kKG@df>Uduc(5zeqeHRMf@*1_4irSdLg~?Bay@*M zSY;11!}wJ}W0|7YFsUpvd>1ITLR-%E zhhl9U0jY2#@JR6|D5M&afnIniP&_yT&kc$Pd%|slVmG0jTFW*<@f^FZCv#Wl1jgBM zK-sIn8N&-$2GdH)TJ}OQP3jS|ti2JD(E(7_8t5k?Cl*_rSelYE1tx-yYe0D}E{iOT z7TZp+evQZO$k;qMy1UrC!}x|Vd!{wpT2jNzd9Welqr)`}k{lvN=LJuKX=wuB80L27 zO2`7B%Sl786gxr8M7nsqMVbq8Rg=-mgmON7uCG@PMNs{1rAeNWNrQ%WtyG!7e zT3A4Of4DZPp1y42=vfgeY?PuXZKQuGa6LE!&knAK8pm#jYc8#Id@FNqF`(@$c5p7u zo?yNXl0u56!Qa1qRTL!b1VLu;2y|gg1M3))zJS(t|{t9~7yXDmEDki&aQW6>yt4TO#o_Z#gpU zvlP1^HFhT!e}AM7)?#bdM#NkhA{fucLZ8vBUJ6nV&cJg+>cMX2TacR3iC_jwYB!|b z00@r)+onVnxi)y$LhG&(xTVj8`oN8J1_tqv7u(n5eV-_CwP3f4jz{GUm#GYRvG2U} z$>OD-J)pNi+0E2jf&e5Mi4&F*oqRUMcoVY!6o4)&NCVWt{e=o9N>!o-KjEq-LZ&1X zpx%O;2NAsE&Z@vcxh)G($dcnDxwV6I#IT}?P27^q3bP?<@8kAjX^c&%b6gzY*3PL$ zXqYG7Qj42v1|q|XvGkKOP}rs-E)*q9hWjH_2dYrO0-HYN3Roa&M?M)Ix4d&|v(aGF~xb ze0Bnc(hGs=;Tia>pjy)^`A^aZVqyk+ih+n^BvDylCA_nQ=IFiRGDHo>h9tY}I<_Ko>PCFHWaG>Xfgr!=49N`(TubHR#AA zGcr-5InyTFz^Do;Q5q$SMLLK_NC0mdR86N8w$=yo{6WE5>5@U`1*z^5qP&$PsO&-a zLM=w@l#gx~u&xF!<@^jDc~^jrCR!pf;<=ky2nanC6H8J=0Y3;Pnt{Z^pUj z4d40Z_Oc$en6&2$o(EdT0@D`6GYb)2JqD^JST^7=rfO9cX}OX~rL3sK$^xfDtOQrjphtoyTLb2C0>?#%${>@;gR$>P}DCkG{ zTFFG&1+D=w)T#a9T3J;YA}5Yl6EMd}y;do_m`LI947@P7wy+Jje$sGVJDOPI>(E86 z&5{$b^=N%boWZ`WN2*7-9`Hr`%UaRpnLxKql+)_PNIC$kRXyeBGcB-*T+xin!d3R5 zwS`5cc+||&n5B%&2FdNi9){tp)NTl#2p$>j!XdkwZ&HT?KnxT4=)9}2WQ|#LARJd(){KXmppy%cUP0~FdRR_q z=Xhq)nPG=DbTv#^;(Vke;?pKRX@}5z$YFhUd*h#{yZZ9tx_h&m`60KwrXBz*8Y{1MV4cv2YnFsJYQ}zABMjM&+)(J_1EslUE))TqL z5|{{)acXs2IBP4wTVXBR{{W2%)r+ICO3-lFBAPl(kfG2mF9qNSXW%pPU(1QGkT&vwos{cPBq@=)n5cBlmQNDlj8O-xZFCTC&24`CAI9tC5cU7M6I&rYaz@R1KdM1@WOywDP@!!f&23W?#tV7I=z1PJTRN{ zl8RG4748c!FfxO8(MqW$r&&ZESk9WK%$a17$>LZM2B^)229oM$f!SJ8zP}U2(%Q#> zCqX>yZBhgL%Hye0zLW%&;Td>gplyURijScE{6Tv;Bfoz0{@G*{a#egbLGa9d!Vrt6 z&M_u56;jq{Dh0LnLI>wfrp(wH&t#TmZItl#VNc!UQVQh85`{q!B}MJ>nha5tx+FY} z%=umL+Hz{u{t4h#;DN@oD#EoJ1!uZuzI(@C3}6q=z>D&F>xrmGz@BK?KPPQvS0qFu ziOh-Bu11k~o3L(1J3m6}G)uKmr+zV5Jval;46CiG z^=7G~kRhgPt101g6x76Bu-Z(Z@SWJ6{oNqI<3e?Ro7BTq8TZAe2I>k9W)*yp;iV>h zw~xI)5clu134OcYtU<%mY02?pZ2Pbth=$!S9|-Fd%b0#)h>JlHTAQ3C8K@9(A#zw$P`7AN2)R>unm<8?_I&uJ0TI?9-` zDo4&z7L>xy5}G@nO)a35VDkqRw>@o@OqPJLJ5$fHh}!uz1ffN4{gF#Inrp+?OHYs zEKVC^@KqRm;wBmNwP|HN;a{auHMNs+ib5`KwseGQwF&0h->j@7WDX)3f@KiX!lFye z;YDg)4eTpueNmLk9?NZnto6AJV>Zc}axY?2;AQPoR*MhRR`W5{s*A}JFQSY9Dl3}q zP`w-U&V~-WO#fHQuVX3p3{4QgVs&xOv7o8uJTfI|E}|Z!H!0}CvgDT54&0nO2qXxB z%*<>a&FX1CQNv(C5F25-WvgqAcW(r%YtxdNs|B_1Ssi^VWj{R&+T5K;PxMYRr_3dBF|62Vznk z6I8A%g;C9Tp9sGB>)&6M>4%%!tNdzu4x7NAzG{uk>G|8&Z98KB@nr41bl=5`Gpt`) z`l6+fcbk)Dowf2*`6Nt$Eu%5q%&}xTQARlpG-#&_QGZgzjoKrh;S!qU`Uc$(Fy<$ebo+X2< zyppS4KS@miHR zyj~1>&>03BrnYo{9^Nn}isQ0SkwFt!ikvf0GnI5vQTnLB)4eFR7QSULO$4}u!?<$+ z70wXm&)FO1>(MyP@u%oH;h9+&F3@fErJT1Ko`DzT4YLzi20H{UMrYXQ3>%$c_i~2a zTP2Oou+bSdI>Sb1*ys!!oneh79zwOmBMGMdsrK(n)Ep2-U_1xF9aF{zsY5D}3#TN6 zOF^;fm^m;Jf*wPKcNw9Vy<(mkYk`PKiYM;?>s#&zIl%@Ep-<%m`)liHcoI&qzB^~- zwPFHH0-s38nqgXuu38Q>B)w=y*kUI?3+Gom+*QZdjBrjC`hPOh|I_o!+Z))z5Uy!0 zI6dGI1LGFT5KgHr{bkPSDOyL@%1|Nh00tSJ9 zK^Lv$8F~^wH6}lB5AT>ofL_i-7nmv18mLvMZK7bRSi=B0WqSz=!6sJlLy~zT>;=#S z4z{B}c?`573>o1Je<>v_hG*dODM2Lo1p5-|ext{0zV(Op`=dC(cH9&jC`u@>g<-*A z9L7tcV234;_>x#$>j1lB=QQvAj84b3!|o&YaHChq0Yu*T048lEf$fILvOz2TNlL`Q zIyI@#sC8yA=V1Q?fLRIDHO9GSVD`XgWkpUZ8yQ&)(!v0=*??u6$B9_Lo~_|O7C`0% zC1CoZ9@27UhwgzwOsJMznf>t@<~n3qQR1q%8M3OUJWdvlba;&rY&{`a zU|uE5b?_;=vI}-v?x@(m$!g5J)c#2jw~(qURtOhuDM7s$pTpn`JhwEQB(W=urUdp_ zAzmvHLn($ewO6;HtC}c7joaKoYOzVXGK-I&g(ID){_YwyVl|$|jGzik$KN?U{6u`a zgQ$0Ti>KY(K*nmHm+Onu_XBumAf`GKZzS}B7772Fno#{I_-H9kxMExoS^JV|YYyd= zGDTM}fkR(1UA+9zrc0~&gR;eGy7z1RxxhJR6U_o zYr8+DCTb`#iX{T3B8j3&sc03=M!XPA9iD;Dh>z+CQ^H!a-H*F|rw>H4_J_u#GBMr) za+%?T@uW2qR$HA$XdI#On9yh^&MBb|fW{DVZHOX4whaCUoV|7&kviL#0*!++@EJj) zn@}mJ9Fg(p$O!SAmT7G3u5FDjxmpHJ5^n`1)ELU7%fblvDWEYpksXuTN1?JyJX0#8 zw2=zWGZ!g%=Svn@6v=JWflH@_WB6NeI&ibjCTRUQ%$np7HD)6 z>6kd6U~Wn^5w~^&u#9;^Gu~e%$ZAtS>_tH1;0%0L(5RWwd^J|Ap^ zj7Vv?7{T!Yz_I7P4Y+)I{&wNU-GGp_50WTnl{7+_O!F=X zXaIt(37m5>LHPH2oeZ94r)O zriMU80gb2^#zMuFVCR-d4-|AGT$ChbQ#3`pq6j7R{ZDaW)l$i=<16IdLmFj_56DehsrIG`a zsdh?G46Iq3V2$Ulo<2AAw6lp2h~ytBZ8Qg0Vq+=5Y9@3bS$JntjI~_R3&H2%8TgFw zSx&U!%(-W99Cn21132^6vsO=wG@GKOP=UH2vjXBOVPO*mYeSJzi-buEHr2CNpv_9F zB8|odbkSlpd3pMvtkgtmW_y|5yMb~dEJsa@tcmiba6+ANI%>&Td>Kt_w#~rj1IkKI zICXBQ|KspZAK~~Z!12ZHO}O|lNz?1gDhF#37(!hVEWub9@gZSKlu10w|DU}#ZI0tO z)`kBH10VgWacW=mO}1s(M~ii}c+sT-Q7bt|00wskki_HQe}A9s?wRSH4cmZ%$WhQV zrBx1THd{T@MYx=^j*bV)>fv=Lly}QX?X5F5 z^J<~YGcBd9k!s&^inNd>s^p*6SnPRthVtHTt%{&iV7m+`kQ$FhUgtwm`O}!fqmtJ z$rhWe8pjfZtqq1{A(Z6O>KK^|4w51V9jVfSeJ5TOU;bdOVx!`@#>6@JgEFcxvVCxC zxmQ+68N?IYGgJ}P3DI!HN~4n1Bm+Z}lQ1!fQiCiskDzF=zoF=wC=wa1?Ee0(eJxF>eNYc0vd(RM~y*0kABO9J4K z{FrL|8K$%qrbJVtOgSYL6f@ZbtelL@D0*%)v!k{DP}uX{8F-J_ zGd~rEaburMH&7~qtg?hq%!k64_s+n3#FxdX zP}1|?L8kE|Up{6Ue>btw?Y59odn517I*nwUPM}%isotYk-WBF#V(CNiTiZVaA5LsE zsEC3#t$SZ$qmSuypVBLhOYci^%GT1>Ko2}iX_Qtj$;7eV8nh>kD}bsz3oBBA#u!17 z6su9*k!M8ofv80^&XR1ch0Dsas!`p}Q{}1mTsVGzo~o#1J4J~_K=6h#3{%LUsUJwi z$lGS%J%Xd^lo(j?wk1_cqfk|} zR`Nuq4hL=CJ8TBUGE^{Kt6}uV#ef&z5pVQ~PB|Quj8Lm+R0>H&Z>lV}AN~t>s+1fS zDZMLi^r-+eK~ZXAg=)id;yxA|i~3Mt}rFIVHC*3S1+#4%k_$5u5N9kA)_QF)(QngQhWpb7fjG& zZ``4#D>J8>X|7j($kaA=?afu*_nO0N;I*riDytn&BV5E*Tusj>Y0`=Xh=D823Ml4m z3NqcsQ7w39V|}9V>c|>pl;tWGCuOS)w6E{%64$4Ub2lj8uzVrD>6UvLCp@@8QfqNN zLQMQbfu{39n%{NTam*n8nc4`<*OOPTPky{@Qn@?@Fn4^#-51ZtH=~8qiU!S6;|a%` z9KZu?uuwjTlhz6f0;la}@y*%mFn>Kb1&lI#mXpmo@&pNJZ1pZVZ6$E2&^iim5u1y3 zyttrL38wfWDWcbBCboTHZ8T!xgX+K8_NM8?6GZFu8iDT%LjV~ErI zhCm0{`fNdY*k*O|>ZT()y15FQ9q_Ov9$6q6iWY*@Eb}>7MeV@fyyc*)%LC>UX6ZF1 zljviA`=cpnF~*>KXWjY^Dz6l)tWnT5v=Ismiv{&k`;giifEs*#V~{7ov+a0x$2N9$ zY}>YN@7T6&+qP{Rzp-uGxbu&D=qjW?)@>{ybOf=j$lpp9Q zFLRuid?*x|jS2Url-W!jIRaa3hgcfnmTpbP(sgM)jogkq-II;DeZpc)t6l?(EnI5DkheIK zyK$a^5nX-^ftaNlv7aG4TaSm73K=!R!HQxP*MhmLjc38tH^+L~CxKs!Kd?zYwE|Py zzJvi=>@3K>Z93KwBDE4Gz1x2pem6FJu3lqGMXP$fsDlo|O_6`GX?Bh13rfJv7v{1R z6;#A+3Gn__0f8Y$0$}rf9HyTPtNLy4WNK-uF4^AB-jSM_BYPvsC~~GfdYmv}FH$MW zAhJx;Uy~4#5z*jnwx40)u0Gd1JY`QW4F49PMbQU*i&KXVvX-E(ZhU>xcXaBiK|rWm zCCh^OYbj{A3Pg;YMjCduv49EaDsz1CpLIDkTz;GD-D#QljmBD`Una50u?Sa?Tm`f! zupTgG z^n@T)z$fQB8J>h!9tVE89V&j5{5=vo%3{83@?au5t_|w7Rlesv)~~V_FdEAz3r5QD z7>N}l;bc7$HF;yuKoE9m#_6Vc@LFQ@3rO6CK_X~Aj2r_M22tq_^H0!o&Ul3w^_Zy> zvcCk1ESLzOU~(DmFpLbeZi#;8wsxB|%-zh5Qq=(oq&iF)`b}f8PHkEmH>;t$Rao6nj?T4ec`ostR|TTfc*GaKk_`xr2wQDQ;>0Cx zw&(ZsuMM_Y_(x_>j3R?o5~MxiU7m;bd&c&xF2?(;2b(5r<(yfS6vZjV? zXeHY9!yfy~J@zEKp|g5%wcgg?N;M_HdVfBoz7c#IUcIEiK(bdNEc#w>@4VbxQWfCP zTqLEfdaXiIpJ%#mKy&`|(oa}=pSS^R|VlS;}v+*&lDa4`c5)*F+%3FcV-tVFWo&x%fraTVi8U9_3#f0;V~b45~ypg<7whmRNBiUo)sy} zoX7z>dYKqw#I1Q;t#(@G*IWsdC&q0UHne2XJJK=iQ)g7~f~^`#rajOHLRRAcaNArF zB%tp(Z#vUDD3$Gj!gX|^L0|>YB}@;d78>-M(N=&1w<>_Xv?v9?nhH)+tQrmGo_?Qp zZhhU`XVQNkj*ZY>Co=wAMQI^94L-KAxdB}*8>qA$R=4)Gw8PSutC&`b`(1!;kK9cF zOAjh;7ZKizJtvPwM(F0RGK;U}3Yy>QwBxrdDn=DP3$~^)kFjUnU8jW1S08w^WzBwZ zH#WMTX)Ua4+zkciF{n@2_$w!m)`0HYtLE+*=jk`Ys@3yLo3v|fl8dKBol=`weIGBw zV*D_Y;O&jY{Y^Q8*C)^OE%hz+>qkTWftQYsw=Qh@#_Q+e+sAJ1r4t@Yk1k1%i%VMB zt!76_!Bb43pTeo}O4BL(4PRG&oSDn>6SOUFz%(b0F{C>a3HZG3ZY_czhez)3fQhOr zi~&sVN>RO@w@q!loQSWYeWr~DC?qRbj_5gtF<5Dv4XMJNApurYG;#E z?SzT>ho@;c$Y|?r7}iwMf4D2uIRZN`xCC_Iv;}l%JOy;DouJ&> zZlK)Q?V;V+pP=2^jxgq=ACB4-TO)TLlc-KhEum7UppBK5Jgp20=pXQ}HaPQ@h zSB=((UD<{;L0mv;M04z@_x4z}XL9gXQ_+gm+2&(gpZZq$Rc|edwF&P}wvQa){&Tvp zUCXP-=b|#?=-yn8wGD==OO}lx9LKWeU8Dx9PynSzagaU1k)?!ykJL`C)KtU2UJ4pX zW0)Cn#_3r-5YJJ(zj-7KN0k~|Y(d2PS&P!PVXW#wmJX;4qCcuJdhJ&Vy4EstR|6aC zRqdB`j|%^2e-}9jtF35p)X`CvNmW;;%zd6(VQc;wM%#t&O9SPRug}#u|E;k7?r(gP zW@sWhs%R21LzRYw+e%f@ifN99DETkg-=^U9z-YYbEVcsVJvnoEyZ~v-LA_0mK>570 zdHi5hvJZl0tz<7^V7q#$`F1F8!+?V~Fd*=d{Jm9IoFWuGh~SM#olw2kp6<}%%(YK= zEWx%}AY1j)4_Cg|=kxlY+$%6M^+?r^E0QkE*cp6~LqI^;PczB1b4Fn_@Vl3gJ=N?6 z!5XGe6$7AOo{E)Gn^#rz_!FXOx&T|?F>7ZN(#p8o90}d@;M>w>ZNb0@OSxn-#euu5 z6OED`wh6&pVriQ^x%!scPi~WJBUL@ZWg}Qjdy3QCyv&sc<;GvT=v0Y2+ew5lP-N;4 zzvx|0lF0_6{oOX^>CQuk(=zX)t>ID|y+uUN6Wws?*SSraDvsn3<&9?fuH|EJI9y8-? zD2ZV81^?oWcZ|Sg$&&R|*nXhU4?&fksPWSp`mzY3{i=Z6*|fm;Jjj3l+gAEWim=Nt za#~|jvnC8S5^rGp_|K_H8E*9PiWoP{hHrsX;TR7#FvR4zAZc-2FxK6S3-75?qYp+> z11JE}kp>Gb6~tBv)pl4p%Sw4rLP=(ky~FY=Iyg57O6c9(sd)}}^?~P<(z!hr{!?Yb z_+I6jcZ~s8^<5Z?|AXc?*kJgb5L7A?J z{wabx%R{>+^CqWaqcm+7woMYE=o+TqX`N?uknxr0l&_T1`9SL)3_S7hAIUxNKh*r` z?4Bu#w>BfL3%y#^Kn|grO_{JIJ3%mG2@8)#{F*kJoQLuhI7R*1g&^Ob*Or#WL=r4< z3-}+PV)7>YQQ>8#e1k|%iHmVE=gh21Y)YIdkpqOnZr&M6D+a&Wp@N@9>2N|loqs`? z;#Z;-;G#53VMVAG+hH0odW?B1Hy*H$nrT*;Dx6b0-%CRSQn@X|EYeS zt2<3N;fV)ypx@ScClwrBpM$nC1zN4tI;ZvHSsQE7*jua*D8-!wKCyKHosW0YokvNTrcSL;U4DNlt#qvVJoufj<{`00=Wx z0By=Ek;>Q^Ja#mPgnLuAo>5%Yw@w+^O~2*c8EU%va7*#2BgAK$@pFLz#Kec{gq&); zyX#{oSUJ}1IjWddw^Q>+@+wwWCmJzNdrS7GpS&A3C3a1?4Vw_2Z`98p2aT!f7@&9V z#`M-svd&=q&~l|-e9-4cS85%C3Tp~r+MvdFpg*2IhC@f#wW0Pm1Zj<|dj zWZ1zz-mzb;59TL>9taOrxt`XqBm1(mFb}=zGu#XL!M4R-NVm|6JB9DWsqw3{B9Nt_ zD5oM2AO1o$-{e7lg)%=Kb%CmS1Q4HyvaDnri;{Akw*MF=(U4kVU+P~kPgZiEQ1sth zYUrSP2_d!znI#Hf%}rZ-ZO4l;Gu-9xGLDi&=f*TUb$T%L3^_vWLk_gZ<`z>sf6`73 zqGp25um!x1NI*5pF>WC1Lq$`%?xg%}oygn%Ro!0gD*|1h!i}H+{l73BF>KtYU%SP) zbd7Z8Dh6Wv0n|`|9M}IehETpgaEjQw!rJQ)R2a%r0CE(0s6thwyG>0putfIUl?I@s zLLcbei9C33kITRxoH791Tt3_#`FJ?~;D7c+f9Z;T*A#p&1HR8sd_DhfD-eY|*iHbo z*FCq`HP~Pex_qMDs<^nmp+)P#{@&~Ub4>$p&^#2-IwM+3)ybObE0JB^^|pLo+_J0zMbTw1M_@F;=kKDyw3et#c7({PY)IDjxL_SiR=pd^-G-<>Sk9Ri02OL zf#!e&_1eKW$i=B~8q}GB?efsGK5Erpn8PONbYmegyu7d47*>^kb>nE3AZ50D?O2zu zCGk3c{SN-&I5X*-MVTLCWw4#{c50XhzA9xiI?2PqnWv1nOZ>P9bZArH3R$v+Y9?8B z!=%2Y>pK?w3c(v5^^Qu3Zzg)Jw13~yz0Roplj{-g+R@~;>$a+?M)mGTtcDe!vWOs{ z7l~c7KDRKx5P#a8rI+-R_nBeAR8;W<)IEseW{N`Ox?jm01pMSu3&gQ>Opy+)*wqO4Pgm9vtZ2+5O*$(vKPaSxGG>&Z9M~xSbw+p->&CJk z=sWJbXCcgBH1=NnGMMzL_`v6fK}v z|Fnx+u^e^3G*5gMJPn%0Rp(mhdWkQ=uH)o0x^?$;?p<57)ZA9*k)o$Woqxv>#=RbwO51PUEAKTCF zkX1GTD0#jZpx!Wl@+IlyIn~*qXUwpac9x6(z)HJ|f} z2TH}QD7l?ixtTcDbb-SFoX?nB0j~xXE?Y@Esx})XHqUdnS0l^+SdS%jgCZ*I*>#E8 zg*91IRQ2QGNB@ajQpw;dP^dO)6|4+9p;88XK$mfAB$I%vQ^PZ;^x-u+Z@MkmFzqOV zxuMTDS~X^xZ;_tFZ!j^F{yriki$B*d7%GQ1xOjUO#UolyfFf|FMULh|m00cDTAx;q zY(@c3sU4|6i2_1@Bmkqif63Ck*mkiZ(v_lFC#-2u-QmS*hkcZ+dE7VHhRL95wc&B!y&e6X z9dG)#KlIxgT-$(74LDpb8#ydiI2Gt8>n!~4FO~QH@%g!%OFerBp9#G}CoU-_zD~7k zOINii7$XP8%Ya$iN1GFEfj!i6qZe8j>B(9D5;t4YR1pNn_+OsprRh_AxVbsm!zuo? zHVSk|(_=nlp(z{#cNtx$Y`7S!qq{SMWH`X=Vn)Rnzs6sEt{m17^-pC(A2u}$laPzG z)x36RX7+_dCu-bMMH9&Lg}i^}L;mpVYac*W(s%0FApy(}Ap?y{bA23(EKa4?^7bKD zjdyxcxTO{if>X;EbPZ0wH~mo}RTkYn9aI~}W_-&a4cG#fzHD2Mrs3Aw1nG0&u5qi2 zUimfBKe@zb-#JI!UeLa6TS;c%w#FJjo$uV=6x+CzIN>j5V-7YJ(3RCy)zEZgyAn=T z8RQBXcPh8D6|0-Jpv^yoD)8ZL9EOLZl~oBo7tD17LLTn&7zV0}hM8^E*Kh#p?>A-{ zMwJ$cB>K6>)ZIdlMgkQpnIG2&;S1SAS+`7`+N-qLQFE>?MVHUDogo^<#)y%1OX(9_ zQzWWc7D~&vRgBUgJNw3jQ~7bhby4cBZg6W7RINfroB>@(DxQLHBhoJ}&O=;-=S|B@yh zYSm?%sYke_(rq}ykN?C0oYD zc&{{?pYhJ@_;d69KZ1}VNNgPZorbw%rfl8dir4eg$F&O{7OT5t_{y34>5Z{{x(?l&F>pat>n6*8N2ed2*l5xsBn^Z4FKJ=(0wU z(P2m`n|@^#g6duUDNu2Lz1?HZ`}Dy3JOEm1Tl`N3g z#4lQSM?$BIGe4I?+rbs+nT2= z*PwiD%-E2K_$d$-$rJ?v0|84q7RkwOONDUbwBYBE0s=%pXE;uUj-M|Xi-gLxt-wqa zgo}*9R}dB#KC4pZvRELE(wAr(azj~DC ziH26+eSb%o4oGaY_i|YD-)7cPB4DfRlTlfci-lJyNj(t6SsH-p2^7z$c4{)Pfows) z?a*XSVcC^>WtIb)rg*4MdMDj(>|>+tk8s2zL8rAodKr#5Up^G(9Yo)(r#b3u;q{%! zN=X`LeCuturVXO3qXPzS0IMqdtAL6}rr?2ASRH>K&n+%Z0`?3cQQ|;CK9F@6KREYg z+6ur^ljUEOdDHmH(vJejTx31~@2(&2uckk}zsIKZa}vXm(1Jp?mbKqX+zqp-7N8C@ zj`^_O)ho=V|B`OpU;*KX^7H&XRt7pTp^-HY5-v}$NTx3643O97O)3#oVe1rI;A5Ti%FDBkjfg>U5Zk6p^YFEZQr?Cc+uJP@! z(5()Q(6+N%+e~5u0qy>jF%NA>3u}?BlNV!0!HOoA2Y%Z#(NX_r!ty$oH7q?2>=lnc zMkcn>9791QJApprk{b_f+xOe5z||H7rN`QfnZ5Y7Zh6=Q_PWv6fK{NC)*0cE5xiXM zedbNT)Yz{CE(3*NNYseW=HW{fBByt@YhiI&DXPXD_>ZA?-W%2u^h z3K}rTUbR7X=U_=&kO~-5I0ef6y z{h^~%1eXZoSQlYDYJj1#!^dmSFdg)@=IHdA=oAV${iKpflH zTrKQ>m6>Rqatyt!GvXIoA}gS3tOdEsWm!L|yg27XwPaHPbyN5;h+8B#hRjNDxU;A+ za(C>cfF**$a0GoMtUrYD$BiRS6R>NA_!$`g&gE|mEl6{y*0nPtHo+4($1i0-uGgkU z&?L83r#2ts)*0vMJe1cyo4oGua+uvbYMfP{bSUQ=^v^F|N4r5$8sR)4nU>im6_E=_ z7%JA94g^ak=iS(B(#91%5V?k(^d7HpgC{{=Niyb+9c@Bd(2CM;5Wi-o_>9SQ-FXO{^@gq8+OHH?vqz%kmYZsYLFlZ8m*I4 zxC4OKJ;4s4W>x z>S55z!M~8bl|4n!N#Yc@TdUbM4Q}SGNJ%WzzM;m6Ye-!Sxx#LfsxQknJ?1IN;3k1tKG$lQmDIei`gKv#*&}h#-KAxGeuI?_QRe0tuPL?>q z7&LCXi*Bu2=OsVv=95_FNI&9w4VaN%1lVN!#UVrnCk16#T_cP<^;mU9eSA(!vnI06 z>*xIZ{JKW=Oh(+J)9hmWbi-JEfBeBjDa7ka>-7{srQB;_ zPB_brkQD~SxLlKms@T2;t1$;<(0(GH0IjpVzb3>bXv!|Xte~SsbaOv3vHjyl8DIsmTykMldYsp1Y{`0}Zw zH7SjgTuIzgTW*Wm_>vpHVl=^$p6AHngh^dN1?pw|=n+Mt!+;U!fLzFa_tuI0)`JhL zk}TntE5bl%-OA2%zjSq%L=$kJh=L4$*PlW2_Ye84ND}Lml8`?`_*CZTo+RvvDZs@e z>izyiE=vmVFm5@L+enjJ_$|iPz3(_Do|Ly>29s#+EF@!178^WED1(=$jsNDTz~xy6 z=fWY*g;8Ue13HBiD&4z)R9|L01f&B>YQv>RBPF!6W9rMMum%P`UON8CS$~eZk#TJ5 z#i5ZCy;M^0c>4eEn*8%>?^yq0c&j?@lx$vcL*LSwm=~kq=pW;zAOrZeRN#0jWCK_V zU&ey2afM~K&I-%fU3X+?-Tx4Ua})pxLhPdS0R_g(Azp2iNK!G=^<%NhJ`-?TH(D98nE=e`f)osjhJ~XenT|0_!cl)lRrkhXH z6+~cEvrO~!U~Zmvwet^Ae%R`!+-l!H^u0%2XQw_dxp`8GZ}PqdIt6EnNg^Bi-|f1w zpgiNRQ9o&p_*BXu;30wCVSI;lgHHm}Ch_Tv6a408+JY-On z2+=U2k$bgjlDB})l2=Nz+9T%Eo>&V+qjlD8g+Ujx)OFdnA-wo*tjF-_YLuhZRojPt zj&(_9pDd1ofGVhyp50iJ8{P2?i7)t2GB<-{cX19npya?XEc5#s#!3K{7Obrcd>1R~ zV5yg;h)RIoDHHY{3_8I)Bo% ztG-v0<2UUt=^QLv>ZwCHT$B0hpof#`yfO|G3%a#r*s@S_jNr zkHCN5HvnevMeyJDNp+*Wzw92a@V`GcPmXm*T)v-D05f)^-!F?V$J^g*U#~HM85@!P z&;6Etmmcir*Bsp#?=KI}=MX@L&zsT5{Y(MR_i0T|v`_Ws=kdug`hJIQWczJN%@_CE z>+|hqj}PzL>r{>iZx252M~q#K_lxJt{meJ_*>Dao{x+`9^UVJ0%R>WTQ?>_Fdb4CZ zYUyPDx(D;?W5OpU{cYm7pqS@<|K+%(0Q~c!h7jrV!e&2YB=LS#wE)=rY4iJMNzW&{ zJ>EQDuZt%gKA+Y?A3mSn3wPUJTv$8X-55@HHo8&QUpat~ucxV(tCj-gm+RZmulMWy zpLK{G-ph(^e||LF&h$j{JiMk95O{t)h6?e1|NFSlDY*9L$!?$V!MMDl<-vsAjkxvq zzI`pl*7amGKZ~#to&Oqo5!8)--bwMnd7Uy% z@nR?0q5Y=+dY!SG_6g5;jBb5r|nyqcY5-N^0FXVa3899a=~pZjOPz;@*8J?nOi z`{NX^DAC(xYnjc+-=lTjpJlr(MA`7-MxCtB3|~h>zFeXcHosnOi@u+%(+_#SU%qVC zg}y%F6MlVM_Walc-QS(-FAl6Pmv8R3D;M2pvZszZwGV5l-fb_&J(z7TR&UqNte$uM zhrDav*YlHOlW(j~9NN|A?dak6&z^6Vuh-9)7`b4SRZ0AI`-wwEHe%>6KMtT2PfFye3o&Wvkn!@9yGBbtl z`lHOx-iGrU@yc*Ywkf&4qbN_m)S#|T}C?yInur^XweKQA$W)gLswh$ylx&KQ#Lob+st7^SL-pkh$U}>$57H5%n*o2*Ai`ky04_t3!}@6wSH`~IsrNqftZ^vdPXDQ!v>xnr=m zVIVA1vYB>g{d{@DYnYYbuChK^um_CrqR80^cQLzDNJkg1+G^E@G>uR8my&e`jr2&C z28)i{yir<142|%%v7&|M3M142u}eiRw3I-)P9+kp%cq(aE=hR@l+CDf=c$j}m|h7K zV{vRi#VpGxnX!F%QD!EJmMyXXodjAo(Y&8qS%6$_@A#x3GP#aRak6(WDX4^{NfoPQ zw>vXsO)17qx}pCOxRvDk3yRYKS%SMtocJooEY0>=m4H!z)u#Ts)|p^Y8|hP!a3X_! zNQRq<+FHANG*v`u@i6vn zplrEmr!j#UuD?}GY;s4M6u~9EwAqwC=P%vB(APv3)@k1>)VWWn@9E#Cyg$qAxoEf}|e_c)T9sT#Sh){$&9e#vUw|8%^fpREHf3l9# zz@>uXpg8B*;l?UKT>YDqv>XkV1R%5giI%NY6c;nK{;b6d7sR$!}PK|IMIyke7(x@{tH{@r|1@SkxmNt?vruG(w zC;i5+ANK=?TeU)V%WU8g_`6-G(q0`6iN{pX=Nw3$F)L1%MuFc}zaAllH{QpoUBCCJH=vYS$V1m&&mHb)u0*`4}MC#K1 z&0LOW2TT?B{tB^~!o{mOOdfqk{mGJlPDe4?fuQX{Y9#1bMe;;HK0-70s8l}GB|Ocu z=s${WS?+WVySf-`0e;9zRI*Oj$r+X@NQP0-WU3N*vd>w4(Z>`S)GK$FNOxupyDwv4 z(vXygbPI&mg@7UnI=nXFN8gz#mKR&sS6!5qRc_>c5?gnE8M@jOv`Qit<*XLFL}8UQ z>rpg7z)1ShjC82u`K>SIcC%(1gA=XFX&e~RU6#jjOOdI_EC7niJiga@tb7!Hl`Fd> z7Vxf8jMO+jG)`vjE!xS!>L&?M8z)9`REbIyCan~swwk>4=&zucG6qizf_+c`@BdX? zU+Q+rHF{+R0aflx)Wia-CU4HvsD-M$&{tdPN?qY(zym+tqtr`Kt-Se-q#qZV@&OD-2PTB@t@$Zq+H*@WD?MF5-^>@TWf&o zcC&Hw&6zVfoxebLp`N!i06~8VXz_r%^NmGfbGTxNz|Bd2Ot6!2B#JOY_Fy$7Rso4h zvq&v;XC>AKAsq9Yk_LMiG+M21kvhBQ{ax|~`I5Z&LAF{TBU(tHrLac%jmy|oaNbo0 zE&Zcq1OOxM^7M>1gi{m+j{k<#vl&PaQzcs3ga!JWI(?3h=XE7?>Q&c5NpS~=lDn-3 zGm}`LZbvw6!tqt;|5EP1{b@r=lJ7o)D!ztVUzsSoZrDQKT^8Qz>26v|Gxc^}Og1T| zjA-o|GuEVY2i$XzA4^tzbr7FJ0!-f}mW!Th&BIZzceQx^?i<)Ku8ny#3*XNr7vM>c zsAwlDTV@p8EJcfE(Yf5re)GPABQt**KV~vLY;M7Tdnt4ME+5!{+ zGgfKohmZP55lg zL}knY~wfbTr_r z@$;Vt<2G?mx3%`*drZWJS{WuaSQfRw;1QDo`zY+f`<{p#no+bK57( zD){?~S38rBBl1sGLD1swS4N05OS)i}i@$@yzCz+v9?{8F+K5B=Uo2^uH!@ui3ZgWN zW1Cr=L_Ef2yH$;;!j`p@;9?am_t`MkizmfWHbz;NjJGslcP#0FC|)&mLUPDG=0(se z#C+`+-QyDdCCCd9PEy5}psd*z)JP=7hU6AqMf}S6#ZH_Q+KAS6CWdgD7aEMeRAeL1 zxq3EJmj_CW&Uxw9S^NkoPED?pyJ%&D*3v;gQ+thEq+Wb4tBLuzF5|^gsvyp)?7mo< zj-uy$!83+Ix`z)?9jrF)IK|xVCL8E@q+Q>(8iOiALlFsc9O-|<-=X*{#T`M9F)>BJ z4K2cvKm0@SuS-p~e%_pbVx}_u?sc?oLCbe35s@!1?)XpV=UcOtR3nKhNq%UI%z%a$ zp`43*KWMQM{sarEMWjji$H+?Qwmyu{KgzcEqd1=A(pvC6o@b01b5OV#mQa`|!GII^ znO3Ogq)`{`f*{UG5tgVxb}=Xj`?622Id2}T>d(FXk4tN#UC(uPL5|8f#-9$#$76b- zWfEId9;9$YStE7I_1k&3K>lcp|LRH}NY2D=HH8}7cKtl5#W=sE0bvSXpH!kzM644lX(G-S~#DP8J*d-DwLU_w)dhnF5VAxq*oEx z7m>m2s)2EcpOfDD!S8CJW)c1>w(=-JRhy--s;is(cC>dxsbd5UGufGlW;4gJUhAl# zf+fA!gx3o%YiQ;;-m#u|X!S9-#t5v<>cpc#kf$N0=^e&V_n zf8y1hQ=9o>YLE6D@-l6;ZVLKOWHqp+TMdVxt8`x7!%)A^lRtoynA^m5)t7SLl?8Zi*gJ&gQ*vJSuN2d=LzhR`^vs?U zr#@#W(i8%jX>lrT*_pRjs)4jrt-U>>=eE=qslII503U6c8eO6ElGyh+gbJ;LPQvO{ zh12@DhHga9(wVE~_S*4(AD6CA)g`nfoAoZ+t%dup{e{aDADt5dEYK4Vf9WTpi@xmS z-XV;#Ny84Hy;#f(lmjM=Q>BX&U5weO=b_U-s1rBBJLpQN>^>Koan~hu zfh=+Tn#{R^Cg6hEUog@t`vZ|yEWK}qGn_-0zOBx|eCeqoh#X!2X40NCCc)75f0VfO zzym^>qpo`2h9opOxFw>{)}VDn_!}yYBWnELg$OtO;R(J6%#^9sD(A!J3>sxfyBg z^)IWlnWxb^Ma6UdSai9?$LnDX@XKL{7pGgMfAG~v&KgHNk@zzXkh{5Sj z0ZAq_oZ-Ed18CO0tR_ZTD@_|03z*cC9&GdGiD4*@jttt5b)M2l)>& zxU3DeI$o8$_<|ANZmVh6$0qk5^LvuCvOL~y{W3uu#y>rGw|J5UM?n*p`BS&-ulfhp zL5E=2D_XV5M+=x8=IkL*q-RDlFxs3Pm)a^TJcCQ=^%sHgX$i_)-T0CjNe+j0n1m>q zF-5a?8S3d5KAg*{uc$>+I`jxgPXAIM{5Z$xpoaa4pqBleyo!5lvGWF=fDLt@zrvg5 zxEi`NGo_|K)Y0XDw%Ev~=Nbad6V7>!8JgPYgo=Cdv`5f$>lUZkUS0=wcpC`mn?vMp z!Co7d4=QcqnbJoWBCn(yCCtcUcQgfT^ktL&b8PqZ#T50@=FQ&W}N@Q!ggtEn`lkIfz*C00;&aABknP z{|HDhGPU|dO@VE>c}II#f4b+?6LrCcA;JpN%H>gZlH*jabob|qgpo@n#j0RvCy6{n}K6f z5sk&xOzXE9UXL36x`dNy8ID0t@?+|!Bm}L^a|%{BBhHhZRHg!wu4|PF#Z@hoJ>WX+ z`r`tTl=!L#)e;RqmSSu2+usy5H^PZtb2-BsJHzAzTBq&dPpcrRpe#M5aK$iYFFCkl zmREVF!{l1_v_9|OPT8Q^lUm1axx(7!sDo5((c5vW(+AD-hN`@PqA^P~fETV94@#)b z9-#`q+s1M6%OEyaF&6w#5ir6d!)av@Yzuqn3k6-=5R06HT0tK}L@dbU+_fDftKZ#O z&?J^De>Yy2G=~~MKW*g2&yv=BN~v;7C5}Cp^+6@h0tg(`oW7)$>4Z<8>K>u8W>&92 z3WgKW5(vHV?wkO?WiY?4mSLc5iW2jap{r+>_X1q3j9-q^37UF$raaM&CJ0&q?|4X# zF;um%p3&Q0l0x9Q--N||-;3qR>GJwl^t2C0C)+*2kWu0EZWhcJ=t6%WPr~6BL^EKv zs{2(>mLx3|Bt-#~gG@W20q!p0!1xG>7$VGw59q|#z7(fKin6J&z-I>V;q`FM z{`QRX=@I?KE&83k-*+l+|G%UE%;-5LEB^0i|2;a{cIfb#se0Tvm6E)p=6?$*oBEQf zsD_7`De;00PuQ;5pVyHs@QRjoxn*vT5S$g1vCl3FnS^x6?FjGNcD`x-)GA5f{CouH z&s_n1TwMZ(a9&cPa;G+N?V+5!O`Yxh`|KsLuQCebutiOcSV@oU&{LxrZc|7r$E>gO z^=_z&o3lv!+w`PR*KeG$bB1Rkoh%Qffi1m{TO_@d`yppK6R*inahy2ioTQ$Jp7)nc z2-$xjio~QP)zqAi1anWbyjfwHOzIO4l0DJLvKKaeFst#(yl_}DQdljT3riZqSziAzy{3}qim3|2!w__2g?Eo2qH z%o;nkDG^e|F^p}L5{@OTLcVV+Mq-LNTw2yao`56y{I4~d^APd@h?XVhTF_seS!0J7 zhYRHX`XQpTybsJLwulAr6&f<<=W=O^APqS{KHPlTV}DV{X+?hfLmB^y$3fO{o$KGp z4j$|?Kd`J!tcTIqI)O=oIRK`p1xVBT*>l(FwNrH-z%q^!aTx@cWU2PD32zF-D$JEx zi9UR0-TrCW!0Nu$WLuqvA}@PRuY}dj^>B;h(!{aDpMCGkjsDWE_q8nEXZml+mLhJ9cT>S-!3?n8W^27K?(WW%cwUv007KG2HH)}?mLLq?9EBe=aSVI8%V5-=3b2%SIKYOi-@4@(o9cWGJvFTq3N$(6a>jnGzaGtPF?ds7FV4Q!Dh zL1vy+uBj?WNpmzPm^;Q@>?T0BYDMAzT_wJ$fShR-jZnIDt7s z@#;rqe*+j(At+P`7!I&q1Qz9(yDK}vSP&QhAxu zgTq~r(j5^9cKk2N*9)R|mp>2GbK^JoDp`m^1=OKf98REgKZ-S_*sZfK;gHd4R0T=X zWcET>^AZI@BHGDHO&D%t8%i=ir^#w+p(&L&DaYx@B0HTz0DY!LFS@<=zSq8TIPL|I zAd9}*zt1fCU6>?S7$j8SgCmE)7(o3%A9J_}W5T8RmxsI+Le(=MI5W2i{#n{6+=v>3 zTsznu52d}sT~K1!qN@e7Og1eL`|;-bh4DRT=e4i**Hf;F&j@;86q&vKa2_y@AS#NTa{L*u^Ey}C6)XQBaDNsz%8#GK<%-#pqucOa4=e}X!=7#u{2v^ z^-Xu?u?F7Qr^%8cOJPmei;WxyLZbfIup&0)~0YY7r)=Yt zZQHiZQ?{+Ip4>U{%(Yg;j)*w}{AmY*esdio5YqaDQ)-y@S?(`K z;P7s3p)pM)1;f1OJpvYjfM?d_h@FfBGn08D;$UI|i01~O;>iTwIK+i8ahJIVjE?_9 z8K7JN5KV$?l&u|izZ|;v82_F9;M>Lh+wvO7hO)WNvC~p(t4lSm1EHuN0IV2@Vh>uS zY+`#1LSaBuIk>#eA)3H@rT|>gpK8e8)gOBGs_9I0gK&6Z1oI0ls1-Vfs4g*s;uie@8{S2a+jhubA;;yR`>P!A zAO-Sn33Y=bl(UW%RsJnkUU@=ueralL=-|V9o|9P7VY54DRx}gG;Gl1n-sZZ4!a^$% z{0r1$jJ6Z62nokBnD~k5t^`|?h+SKo9Y=5DC7jj3y#hcHrCH~6mq!YCDbC46=%{#I z2qAs`Ra_-;7d65Vu+}sjQxz5*sC+4;0DucB_rHzj4(RN6PSfMKgNLWbmuV`@x{i1C ze-Z*HER&ZL8wJt+ix6OTMSAK#2mxq^j=?(2RroJ2XP-aSNv;J%?_6VTyQU3#z__cx ztd^UAS0UHypP*mrbOF;dhlN__AU$mWEREUL$S%);sYmfTTPti}2RK=)#klH|RO`k| z1vYZ-9dWa02mr*$l&}eLiW=ILAsq)*1G5H?s^>wxNjol_AK1qFdHhpOV(nLc-(B#5 zuCyoahm6^W*=-4Lt|+Bz>(q=F7yr8ph;1N>Xg?K^t1%njXvpixw4oV4v;sM=yCB4T%ub-tvQBcR<@I|+$PEgDEbTceSNsn+JfcDL2zn3rMF z3vA4Rd8dc|nYVii(RD!w_`RRQfEFU~T&ztobGN`kA{IcDbGTd&+D;31{gdvZ#VYp_ zGAT*Cub*2T+I1Dw_Ybg^aGq62%1GnmzTwUeUjJ$9V5nTa$Z4G&GYbMF*lBNTpmYRC z+3>~^3hY*ky}0BAh=)VqbX#;Ruc&5s2kFDHuC9xgmM7D%4)Km~JR|E^#%8yPJbsX; z4PHAFwD4_!{D6m)abb1xf7-V+(Oi_Z1K6mzfN7NggUqAHfNWF5PSbX(-fEXjo-vMJ zx$ng;XvkWO%bn!`)2g8|ncmbXf3fJ3dX7fdgaRu-=?KkLJJJ9vdtG5T|8t)8BYY@kuN+Jh0lu@8=k;D zhr$^t+KHHUKvjaT0Yeu38cnIV7K;EkU@MRLXxeBo90&K7frB2r?Cw2OP71CZya71K zzAm8D(R^44;l?dt;JqtyiYGsuIHOg|u;Nid6EY+)QW-lcj5RlOK8_yZMM9G2ScvI} z?ngL^a$<`%z7ZUN3Our~i+j++eeqJxfT+!ehPga^5QMrxzgBY3#5Gn1qemg_2r!>% zq)nK;o`_FPKb7I6Axy^W+4S0Ff!%&oU%nUici^;BfytYd23ag(!E+=AuG3yvh+C|t zdp*JRp4wHmxG8Xd&CT1)dslu|lDP_|rOGWB^(3(oLSU8A64Nw!cbk{7f+sE=CH=|N zkSM{-LU*rdZ0zU+`L;7@V{_n#;wY~$Ku$+orgGQN zNg(zK03gM0T1~47lC2?hyPZ;YO;4GuwbHtcM8hkm3k}vLcIG3C9<%XbYIt<4jrBDI z!ijg`HUd1$UwL;ZHa^=ERz#rIgMUgzPN@EF>t(Wed=F}z}A;?CIiZOYo3Pa-}*zbK&l@XP;E&?FU6sXtW3BE zs8{M~y637FyBu0X`W0AcuH7$3KV4Xed8%xw?onGb&LpFgo;n1^Z`nZcCs_|z1z4TS zR@*Jzx7*_QLG%Q95Z92jxb}v|%0o6ZE*kDT>6CWav;m&xFD4>024R#+QF8C$L&OT#BAM%5*^>}7!lgrP;o-CfVvP8^CZ<61`{AOjKWqC6a)|-wO>(jq zoeMO2Dl8hp8L80udBn;pYD`c?vhQ zw^YGXBsWDy2orH9y{U_Ik=^Ep$`7kI`enmoQVUm9YLbEY;S!t_>+M6>JL z1|a@U47k~eZ`iK}u$1Qh6++hRQAD>Xnq!%<45S*XT3?WSVNS}eITrK(hXAcl4Emk) zY45WVk2Z3BJ|-1jtsi0oweWM^6q@XK%A=Y$Hjhdv*$(rt(xSNihtDxu`+JCKUBu`0 zrndwBZ*b*>Sjzf9lM?w(z)4hsIl9cyNpNU1jR1}XaR3woG8ScpiENlB43g<+@citt zJK}PSb4z=rgSg491xRkne`BOJ6~eix9K=blN(Z~J!}P?`D+=V>RmaK>YL$midj+{e zC`(E^tr*1^Vn+mGSw%EzZ8(>-7i}{K?9d}SXx1L8;a2dSS3f&=EZUcBKply10Wb@o z891D^r(oS%?4v%^NET43@Jo@kIL)jH5J7TDQTv`!>=);34#T%pQ_lVl$P&#ASsmhe zWU+)z9~D{VS9Ay5sLA@5&l*d3)1@(Uy#sqy;Y=^uKWKXV=~9Iw0gKh87OzR(=~x-> z*0vPaODVv7FbCt!5R5gQ{ofGy!36W5SL?NKGv{TRa{QJi-y(}~w_{lNLogUc4tjyJ zSv%=`MalD=NP8Oqjjp<2g_ea+L&ecMpr{i{=UPvDLHiN@+EvVgpL|qax^8)tcI_SIP_Ge49fPNiao1PI-9Imh4XM7pl7kl53Wq@- z`KAuV3N)w`9!2;Y9=RO|j9Z&I$;kEkJ-MicgSs>Lr(f$;FedpXgb zwhQ{K)TeAsQ-CIx^v@D-_)7JWLzHj11r0oubJD;KAwz!I>6znq&)Vzvt#kYq8Vhl~ zb>$LaL!JKW92Rk1AMShbKUIDC3)7g_zUczdE}@RB=qE>z1grPfr76_Gmtw;3zoa{> zvZEUZBg61A(LAfNg$tE^oTW~{)nYxs#|F@oo$K(c#h9L~aba7?*|VE(<|K29Gn)r( z)tL0%&;gfQZzt$d)}o+>=reM(i(NIt9!odK=UGy3lT9+7uZWWRAme^MS|pDoX544F z0{pS-pHSG)E&dL(uj_(n8Z9r8>hC&P)26p`>f4jSy~K&`54OSg3r|=>YcDwIdZdeQ z=I9`c&FWRY^L7;MAl>||sv=I?F@q^N)J250UVLD|2HDPwRJd_9M=Wrnxm~;yR%dE( zXQXTSwcc#0v91KIv<2TQI%bLlr9=N*kswJm&X+=-NUP}0&_JFi@v_w=ICly|*1Ty$ z!vwrWCu+Uap?r2O0Raf9jO@bSF_c|rQ*@MFNh1>_VhMI%U^vf#92V&%YX_Dm8a{ur z7gvzqjWq&-B+fpLmViiFR@E{R_!ZfZVaFd zmL+Jyuncr4p82+Ux=C$83th>Sy(5nDN#UvptE;GK7i@&pzFrpg0Qn&NO^>no{MNU8`Jaswp23eR-@TeiyYm7C1NY1w$?C z0Xp;-fmC&LbZ~NLKJmy-x(_+3>p~h-LTy-e_Ug88- zCZz;5;^pK64aF})LMfmN+DwbIf7!JtI+{u+Cr zkT9F2n)_AIQ={^Rfbcl7)y+>^T$VH}ig47Sth;n~=Ta=B3dw+SlP*b7;}{c^;L=t? z$e6kNLB<%8B4fL1C8n_j!Xg8FyDL(a1GAU-N{ZVhD1tAOLOQ2+a-MMjL@-mXPBImE zcv&wjavy2w6(5A~wlr9+Fm# z4oU7iDg=LC4P&U8BbO8c6Tp+!alj#@$xNuc%VXB4 z7_jleDg7_Y>zagol378|(u01P_GUs2M##fb+Cj7FBv9ILWZnRvOfnya5oBtP&7X#D z$BT}8<~T<}f8;289`|Op{N`4weMNMARX4buGIoz@{iOL@fAF3eN7i*$PYkjXdvM6p zA%hZkP7F)EFe&g>9<9hA0x&mizc1|{4HP*(kP$zr1pY&ImI&ZJ5mE3494=bf9Oc01 z+jG(oghpKkA#(}=^Eh?~<8ex{q+br`11T8k#LIGJ-J)%^P?7y1_kXW6$0XB*}5rJgCB!0gzN)q2>MP@3F; z*V{9$TU}9&s`acZ-Edn}Rn^@Dk5#QsaoZg)c8OMqsO{d_*NC~z^fDT4E~mf^2j~R^ zoV(d5E8Hj;og|*fVw{xn!aTYq=nM_bgzNXp-GXQPk1B_vBGV&q9(n8OC)lfbZxj!M zQGQsUgim}n?DkTBkR;Gx!l^beD6{k!iZ>*A#sstAyPkSbU@l(QwguMDS`zhQEEWU29Qq$p@=L@4;!oL3kPsGshJ z)YYf1jF5zw8(y9HzauZdseh+buf2MU9-k;*C1m9>vpkK{EFL2fiW_WGQqZV2fR10< z`rE)b&DPPtfP{a8z5heEX>irHCb{lWexGvh zt3$H)cxI@CSg2yqss=zgL@H7joI)Dy5+M8um7ZxCNvyL{fu$lFxB`^qm>@jDP>F?+ zkf(|+2FL=Hs{jxUWR4>6rybz!)j4Iv*~8(SBWR4#5Pffo5#BKHuTl-c`sz60ah1P{gvlklh+smy`IE~V>NW{^oYi~ zavcke(6n|uIY_gDqK*u*>~G+mHG-D5dn+5}JMQtr?<8_%I{082NjQ{J9xG(Xnts?e z4pX@UReCHj^bhoj0R)su-UXZaQyJh@zLV4jd3WZHd4}bjH;u<2b#KZ=G9_pa-mbrK z)lh7{kE|B7EU6lqy{DturF3YABq`AwFtfc*Rt;)zfD1jXAOn9kJ3H1GloX^5R5dLM zOFB<5vcX(P5olaxD3U2D1P##ftl6**NL3J!#sMn)PrarZBPl9>IeU6JIDQ@pPb$`e zSCS81{<5W;nPHn`5eFZS#pyWjL>eR4kbUfR;>sxT2?5g9a5&g=ms!U@POp=T^*N_m%1@vK%9lGF{#}R-OAC#~p(Kk`EO64U-05rHzct=q z)!`oOEx^D>>2?X#l+j#h=PR~1Xb-HlXZe`E6;QFpyb*{+wT4w-KqcG?u_ZQyDnOn< z&rbCl>_@24e<|Y@M;P!(O@P&{Xz;4`vIMbV6VdboqOa!{H9!k;5}OGmN;zwqpI1`zyo())A2%j2@l1|H>W9-QJ&2@bQPNz;i42JRd5yS%tBF zLUaP*HVOpjWl?a6LNck<7e$SOI^$aG)VQu-5{5R>%tbDIFNNWkS(b3lmgci<&33_> z{Q>iEllCl#7YH2Ig$p_KVjFU?)x9MC@7kCvaJoNufTuzD$mV9M9?~>HW7E1ltwy9= zYr0p!)|Zga)6ne5`FRO3$^!=%u9_)w36u3~;E`-IO<}n-I(1J!jL4`LE$S_tohfd4 z(mK4uH+Ez-JI=bbbVUd4g%)jXe6Y6}AK2oa69VYccKx8)zBSH+#Vu)C6{lauGQR@1(mzrnM>q8##v5kCMG}%SwC)_1EPCTw!ec~pY%|^oC222KHE2^? z*!?r=1EXzRN9RW%6mS11&W~zi#c&cEO^>EAGaW@m{lHOMn6+ra4n|}4(2L=$`2Sv; z1pru}v;X$_5BL9pzo^X)dapA~q#y8IN{r()4jxi{Y^JXjECwnr8B(2!TFDw$C!PDu z+tjnYqa&~px|A6y0)Z`o5_pxFAk&uo!=&PCEb%MmLyPZtfPfTE$dxUEu*VeTi%mgs zX}#?FQnb~OEA%%-Ae=KhR|rHArA5mH@&P>$vjLlBKX)S0w&=sraMfxI(${_5PI{OV&wda}@5Q zlCPkH{rZbVPzoTytfmS0nwHE~$_t`CA$0^ND`l>h4R}p0^93|Mr2%>!1oGAv8?l~- zsh%&cZ=g|-CRa;9rL5=sp@^Mvrtc{y*Yl}?teI4ZOM_CJs~9vQlMHxsVNEeRkvCp+ zlIQHM&IZMj0kSBIssi}tV45RP77e(jId6#hKx6mMYzd&4hW}x&UQ9Tuk>OC9IwP5C zltUF`HS2KGaO*P03KlZ;@Lj8xsa?>pF|$+D!vlT_5B?(EM3H^aZ>5xeIebo zJCN`msTxx;T{-*2`J<<+k{W7Y5tRy8vH47_jjvBjS5Z39=A2`O)<`WzMcn2jub2Qu z#bi^lEHqRZ0>=d^=~Jj7tK#HH+J%EG!si+In>jX#;4khyTQ~wTTcxsr_Cvcs*JG|d zY4GA=7tV!N@Gnxy8m3WjKMoQ3Mi&_b4?0Mq1d|*S%W~8Dxuud}$l(l#ImowtR+4)Q z(%(E&qo>6n@ji_0K9EGB5U4!CS^K2tD1FmSy&huIj$;CL1On5McggYDx%u)h z;4E3c$a%c}fW(hPI{9km4a3I~Al0*jO;&5rw$EzV2$mNT4`e8b&LvC(2Y58ZIX?Qi-oCA4M*w`ny$E9>HS>G^0}yA+h&I)pt_7 zii)XtB%pp{jj zsH;TRDEe0zI0hr+TH1I!SLk>hD=?kpKAL2A=Y+b%X2Yo)Uc2wZ-het!65i`0VKy-# zz}Bgw8^Zr?J-sPzNwjZ=4vTV)T2J~t+)@U*bb!UvOzOr-pVS8U#>)?X;O_m(zm+NF zt5A}9OmEv4gZxqOr#F&q^er#}p3DsQyLVdv^Iwh zR2xygqYb}PtBf5{^QGn-AV2A(r^~?Ew~62Z>>M3QNQ{qdi=3A{^1}tdTReJj0~eb* zvSo<1mpJuA`{ZPhzHPcmOcHI+KLQ^2l_i+$^ejQ?RoK(hbbkGnsZASfSH7<4LRMxH zP{lK20Z7Pl18e6Krw2zuxgSH9MQyZqwJNoVLT6 zXNN3uOebD)fj)tMwcTsrc%Aa5l&{(VcNjO%W>%Cx%G}CmcjkUZWX+~m>r-RuDb`)E zHVe(zUHBC-3~K8e$f+=$E=xK;JRC*wx!z4)oqRD5q~Xwa`E%RPS+cdaV9F1*k(1Pl7?wv}*O6+rAE|H&WSF3Y<+bZ$kHmcZ*sjb- znL78XXv;=~rUL8~a7j;DPmqp;n3`PpUNU4+^9QX?fX0zRQFgg2lJwSo^D{L8w2_Hg zyQsL27ZQ2NoYAZ|&(%yKa0>h+*H<3GvP_-^ji;JaLN~x|A@V-o=*kDOMqr@B{D>As zXZ+1JjdywZt=V#s%Kn7m`YF5#*P@mimf&?*XcYcBbez@Xi^&ejq`RrRW(s*Sn!b>u7y>z0=(=ipFv%!9H;5J) zB#E+5@RpG!#$z(UDMt!XzW1RSa$XpRzQ2W)kzBq4z@!gqzx<^M^=eb|p7L4Rd$T+- zR!7?nEYilxUUU_SljT9|i2F+ji$v+|4&8kxz&@p$E?N04uaE=GfV(K1T zLakem#&`l@Kz-Eq9jGB;6|HU5c)CT&aUn;Jt;#N6J$%R(5Ut3vm5xh1K7GtY1`sW_ z2=Q9113YQL`>CxhD3RIj_?Xo;Wdp;TtP10*AThqfU3$yG8{!nW=vL@JY#k=S0ZE(i z?U-(V6P7b^ZGdwD_x>Sx?;5yP4lt#2be4~x1M4_>26Nnks!1hN*w@c&aUJXS@?H5N z;`k|IYLk?c%sUox$EbTN&5r$OBl^|VsQ)?bhWFpu!Own)+0Od9ffH-j@;hG zQJTK$9mPoLVSUEI=JG+4!R7mV+UghIJ*T|9HR7)Icl1(^?u#n8Xj8lUgpZ}AK@ho1 zf~$u}q-wllk~DBXdUUTDCr_1gX5bpE0Dw+4fkb}>chjXR1`w%OdNGqVD>c>0W*F5U zHLo_E0KQq5GUZe9u;GcQLn2B{;(N(LahQj#Cba2k`P?t5R^(XzppOaeU?ApZl?X7; z0K3|f^7sU*st{#qS2qaIh^=A;ZfYZ*g*&=Dfs3E9vL%f;nY$v&i1UklaFR1dloyG- zULOxoBZ`|uSWvuM=L1IKkYM0BLoNZ*>-^wVNkO$<0faA!c%jY$snr%%VBmsOSO9KP zN}bBS>nIdkpe8dXHfI=#7{IYPe4e);ale}rc)ZU(BLT;MpEWt zPIr5jmt`Byj8+``v#kv7B{RxjSvN9tXGS=V`j>EmL0&m=oVG&K%|}E~Oqj;Ts4rUP zyRva)D#CRuI3$c=5u}Bq-h(|X5=wh;>J1sB5^J*8X{;u1vo>Pwhj;^_M#%AX;iDM+ zn7rl%;5HAr(Rht>L2RM+!wAz9{{NFKS`#s`A#!RCWieK=siT$6S7hAEjEp&!`CDE|g>M&; z&v^rzQ{-Yw;ng{l4J<~js}e`4K=Q!IGT0C3BNkF<#OT{XzYK1ls&_3s+ja-QPFy*4bpSv7@Fj-EJzKg zC=`c#+Z_QZO=sPhpV6;xSfRgC4?k;4eeXs2Yqy7E0;OOLo^_TS(H0B{C z0B(U5Y)l!|&(@-O`G*w_)Kl*;LMMqMQEH+(DhFiXAwL=+FmhBz7b5K^F+oaT_(@D) z|CN}Wh8}fVT$zz-qhG9`VjOu+Q1VC?^)x+NPhV{*LFd}Rlewa+IYZE*xabFLE0|aq z&h;_Hqc$F-RyBajE3J#9;W^l&z75)FykQ8IJ9v436EWr$?FIz}#-_M1#t|7+52aZ# z9%)9kq5VLNGb~{pqf#pvm*~7|#udZ=ToC`y=Re&411^j=aolv6t|5JjZv~%Di-Z@A zp3+yfn4005(a9AqZjVNb|9wWa?f#B`@hQ@e)j~4WvR92vXbd76L?L1C9aP2?0G$p6 zx`hvq&j)Yzppb{k$_6RS2s{iGJ(}bxBEEI2V&emI91*y}7{vu{E5P@8D2Vlan2Y6m zoBOYuptJw;zYo}CjC;@Xl;+L6k}?wTtfb^!PWqy;l=9;OJRP}e^X&A0=oXmn_IE}U z0);0$b|2#st#zWUl`{%qOD0X!W}3x@h`Z1CHZdkIr9k-tgbm{j_h$hQDgL2ZM<^ij zvLkG0t0q(JYYo>Y&*agU6kd`a(&(dsUvlcC0&%(aXEC;Z0DA))r2ff}N~zW5rnN1Q z;d6`xus}klu7V~QV6cXq18D-=>0TFLCGhjKKaFs{+!SsGL0!|#tY8i}+%WCj#!t+F z2I>`@46Hb2v);?qReDh|%>7j;bl^EYcECzOpA=7SZ@%4M{CGaTQQ*J5+$smY;{rcG zo-&NDW(U6gy|2qAyqaWbX1N_h<#vNWxY~f>zNPov@V>x_>W~2lUL*PRL9a(m`szSexSS^%vrQx7h@^=zpno~{{GjV!dPKENrl-UHC&nSe?xH^r`#38 z!JfvGZh;$~wosWq5H4Ob#8+(vmS~XGjI0a*;+`>1hu?`J!M{!zy3zr<`Z|0DeGc~s z1Rw*2rC}3{5-}lQim{eGU+m9;GzRK%sPRG#H$;Ge=n=(A$AmK2GQ595WKB6;-DqYr z3?>|guSyRWn@VdXQ$(^U8mcW{BKZX?$OAWw*sj@7e(WERh+jVOJ+VW>7_u)P3Brg@brhDS}3|iWo?P z86pE%ni&S8js!2vhS(U#*`Yd836&W0t;aP;v8B`6Y3OL`QA7eYmKE7)A4LttG4&ce z-kz&oR93@Fpg_3;lkCZ=5*pD+R8m|+#%V<&aB5JD%arF)#ql*d%D5Xi5S*bvPbz6;M!?F+lN(hz;xn13 zKLcf*7@F$`??Q7Nm!TL0ExpH4vKK3l=Zyj4XG`yo-6Q<#)D|MkU>M;BER~%s6Y{Ih zZL4ghauX` zQLG2RX`p&#=!OIfOapK$1o$9A(5fy8?DBHbQhmoGs8E%E5rA*Po3Kbi^CFewNdVR_ zgDGi%6b&Oi32Aij`4<@y82!VwtxN@lVR%=UH`&n-WYW$si-S5wjQGP~e?u$ei? z)YzntDm{zDwA)LmDsZ~nN_6f@F`#B2&iWfHaZZC(QL)(8e>r0djRHALc&+|ziTdQY z_Qea;(|}k;x;^VimtGng*6V0jXWaEPzWli;lzMYo= zV{@&QXSQvL?QmIPTD@z$uaEoL+8Ius!^ST4MLz=eW&&&j!dgzxrm=kgI;))e1_psx zLGHRgVZag!*&?PZ+lG}qmh7Ff#b_{_cw>e(BcMGKcjqkuAbZ z`iRBK-4`=3mD*u_-j}atf?ZWDRom^7eI8ZiyL@9s)@IF^Jve|8l>_*|*4R(rk}9rs zbT#mj7Ypd}8(~^i$beU)W@`~N&lI2YR|y&Y!SLmX84zb1c}8_~IRlJr^DK;I>KcZ> zkdNGzcyC?B*xK-kUWlO}pBBUsMeaI94QM6M_TNt*_h$)fQunFxn^_6K0fA#{Y;@ zmK0M^+6MPRyij8%M5bv$+Z z9Fq9CfjmS-33|>6;~)C7Fn_Om%?7ZK+wJ^r3F9-<9oW=%Rh18Q;lJE-hJUJzq)rv> zX8YUbo3;kiuxA1DJ6ebpEDHJpYZ6x^UyqE;Q7D-7iCTy`qjP26>24yJ5q zKT`Mmr|@)}OL}WNe1l4StPE#B(JA@nIdM-Yr-*>>E)(5YbS-d`qZ zxed;qW;~aSIZqggHY3IxjBBnk&A7k3qDpxGCj>3W_J7=AQynuVQaF%}Mr| zoHsTxa@K~_^0-S!KD)^pQ%fXCR5?eg-BP8B)G0cMtW=&AB13MTGG?U`h2)~l99Bqy zBZ!t7B_Y?sHD%~!Ka__K-Syy*i?+5t(q&)km(KO}ThmNZBc8Yg z;AYCX;-H@YG7q~^cv=7X(D9_NtpeOEmGu>aIm=|#+3pN#!4Fk+% zgTrqw8(F*BZe|8J{5*AMy8O7i)k8^lQi{Fv#O(uAvJ`!fs3%Rkuwf%g&r}pwZrz|4 zWQ8H6M(y0s8Gn^bZ|gp3E+7o8+ug$}*$o2wQZB2&@#vlv1Mew+2E<+=VewJ6hNJ7_ zGg8%2ZbnaAyE_dvzBnt7DS-rmd!gVxva zn)WLuQc$sEpea(=uUcu;yaW^0@!C>#u={S}O1!e(7~w8*l~COfh;FC46#1iWsx^WU zhI6(S-_d;9xt`X+c2pgmGc$LC1N(2o`={X8>3>C~)zNKMMpyss{qvm%;Gv%UKf}xM zpRvna5c5$rE~A@`-sAaJn^h)~HXg6rWwmHgj*M$2*g}>B{NCPj!^U9RRx^3WrJj`* zC$;&H`dv(vkW+rJzORB*3%0)3rH<3zwq(c8ua__Xx5H-{A?{$VYqhl}7=XH@LpJMo z#-8~-Y4e4Cun&G-Ue%QCI%M$;o2UCD5@yRhB7c$0g@o~gGgB|vi)O@SR)|*Z3reI8 zFJQH}Vy#(;XazaKpAmL)pUZn!E@@f5CzLT)as+6(QNj2N6Qm9$gHx5ix?2Ikxc)_p zBGc*vxkQX$$*l~Jj^Z16PlA^9eR&B7@>r!K)uHO5w7~R_lbY%d*jlJYl^VkQ`hZ?j znmxo#H`00T1%WKBSdJ*QM52$$4l*)p7fovQ7p3T#j*LSmz0RZaVi*y{wTd8Y6UI?Q z>c(^K#2!aEsB+PNc}luvw4o2Vdd$?qo2dJxB#`M!Yww)rg{Zb4*&&+RU^2t2(N_R& z&fmIGJ#2{f#tEJi$o(6JB`w1CXR@TraVHG0Q^d9d_$g(!VoBzyx;t>)WvVV3v zJL-Ci=PYtb%J&{0^3`1=-n+WK_?iDsjNDK?J@?C|l&3b~gE#nwl(2(>Z8$6(LI9rU z0;7tyXq(}tb%UXZ0UR;{N4YLCnIoyQII>}P(t z`M5s*Y}MB&3wXY?P*NTMn2h124Ld2GpkO@Q|6;3dC^$wEbalN|9qkF7OJHbj8fn)wvZ- z>ER4oV-!$oC;`M38h`omgVJjPcTM{~S%^M?g}(p@xM`_e0;tIOOinvjvMAT&MX-&l zM_k<4i|i-T@8|^J65J1X~}eCJ(H-zu2yFIm5+MsThHt+5evlzXqux@W(3s5S!WqWsNiA7D#;Gh}-w+)L!YB=s;R{*lz{AoW_C+Zw6XtnavG zg#_0RqMhuQnI(WgD{O+&BYnuLzsyZ}yp|$5$!;@J#ixr`(j;@~2Jz|j4PgS#i>Kk; zdXDVe(UvQ)G)l|XKK zTCCMw>L^qqPXd5)p{ifjk%iPE1@}t=(FZ{>N;h%N>dukpjr}cLjDIfvL!`%=SEc1f z#jedjF2AAU%7{_NpxZ!&T9OMG4rnInLrf<+WJv`Dy$8Z81$4w z(Gm|lom$r1CyzvWEysOy>%=?K{EdZ6=R)p%v9l|03G79%MYbBZ_VMINrUEV2UK>l! zj+~c{7q(<}Zf1jk9nrJ=&Keoc_f+KGsShn4u zRqxH?MwrbF)Ucr)dOzMps(Fn&c6+|o(Ccnh<)dxiLtQ+a9n$M{uB&5Lb?r$Ua&DB( zjDI;x*OdrqzCU#=N?3*ImM1LpwX2fbJa!+N{}umw%c_ zvo^W*rHpIAS{&t}E`=7@6|S}I6n1qM)N69j*EX-)XTVogFT?Rw*0AAx*vEuIpAQTb!eLcFCK!NGliH_)z=48YY%@N6LGfkIgDj#0WW{L=?#5g#4vI;ZKs+ zrqgX#qDvrcQzmehAcA)xvLTM&3Xx%~c+x*1ywzZfb;rXYno2!35Gwu@O3AW@4fxYo zT?UV>g8KrL!t{Gbj?S*81Gu`N$Nd5Qhpu5xkLN8C|5yNgkj7Xf^Mh4#Vd5Ofed<16 z%x8KH@N@-Uic~8}diP$40K1{bca4z86v&2_ScT%R^eN8_jk#KsvY6ws{tg+cvhn)Q zB11hy;yOVgNy#!gtT+nZf0h&8?CMuDV3K*#>F(66Gdg{4vNVzIp*yCSqNgiC$5aehq<>JWq$$6`V@%eB^ce6 zJ8T+k#N7X%(fH5nPR#v`AdH~|!w7@NYF^$(RYwIVM0VV2mJ@}$_g|hpAN4B^Ae%XV zYDWGt?#nrh*l0))L-954$d}Sg`sogDT#?)hC|R504V*X2Pd&VulG#b7cLiK|G<9<4 z^{M_I&KSjJ@U#rRWpj|DE9NDo-@xMPg5ny{fQV5q&fc$D2zXm&?8??7BQUWp6JrWXUZ)fVu^MRCjQBt$i?+P2U41d00jBI>O~` zD*vzQn|o0X`V}?6AXOT*bltvOEQ))mg(>+tk_uJ(+GGhL2#dfYc}fG^!pi!*t+DOW zV0x-3@lkc~0ROU{&1#P772f`NvBQ%%6U)xs^19i~+yYV!8MWk+kVM!Ezf>+BQu|#_ zm>cuph`4CfQRKSOU3fd%5jY5MYI8w=xLejq`FDcsgj6x<<}O=tb1B5AlW{|6OKYe} z-{i7U(WH%Y*WK&H_3L3OKAO*`>xtH8IaMXT1WO@@?s%zo>%7&BLcMAp9&0|CyX&CDf{(MLdukX`W zlj78Fuy#GUGCnmkT>qAuoq-3A5xd#xAFZvjy?9SfUOj}qxFSwu%LU$8{od*xV`}W~ zu2J$-3&;8Dzhf7^CoA7ec;Z%^hj*Sp17|+x0Vh#eiFb7J%6AhX4{!Bq(5Hyr*M+hS zKLVU%{cUjQoVwlIKC&Ce0Jeq>m#)6i)=L(}p{UkVIi4WjeQ=SqEc1-!HCa(j=6Te8 z#{Q@J>S6U8mH-;SIuRPvx%`C92H6csl7HFt>59^zHNcF;v#VdSGYgHifD{0hY_A_kns6^h0&p;$z+kak_uW0@*SnYe^HVkOR*_g zT^rcbu!(~e$8(5iGB1o=qIPOSb;+7y z{355v2h%Ki zj>8`{T9m%`-K?EjAM1}PK76b^E-suF3LO=b+ya5SCi4+yn9e|m`oN7rnyBisIBawP zREDfTXwsC9y~F)7jjZZ)qV+njhs`J`9^>Z+I_E7v>b!c>YU#jNSkUJ^w+adS(;dB- zz}=6MQy}Y3e+Xe2+tRez>^$K8E}M6B*+D0l8aLhmKghXFMb8AVIWDqwZGOnZdcNP@ z)ONh@Q)|rpe7{rey1QQPj_-G7`PbQ>sM9^LM0>=IhXc5=?yZ##P4 z`A6-xfsJRrZx)vHzGi;;y*=6;75ID}oqvDcKVr~{q@m;zx{D*=g0BA;I^~#q45#!^PN-1 z|M@h7to{D%_x?e}*7%gtjY_Mv)%;@dN&mhRBa&u91D_w&-O`)gt6 z*zV(LMeqCYOuA&Jk^cSN`xDGh*YESZM(r8w{dH=^?(44N(~IHd{=KH>_4?1vch6@S z#Lnjf^K zW~%4)$mN|G?SNiS>+QY8@4MLRuis})K#5C*UBhPZ%FEu8G+zC}SU*T37)&YiOehN; za5jKYdAFxz71;*aF}T5SDsHOZ*jg&Q>s5|XGv}tfuYlEdbf-54{df51$}7BGcY)u> z{^S1#*gz-0v3dFOfB*d){PNE~UqzwJ?|=K}x9Q>!XWwJ&AHMyDh2Q@Db@-0|6o31V z8>|ic{-1xP`)`Wp)=Fr0?Rl6c`kI@>Wn>B%7TS(|n__5@ zf@butO!eutX@q5pG4D-MVl{^5)#eylYyuZ;Qle|T^|7HdW~#s_Q{3%{p(*y@WxjV; z6#8(gK+cM8V3^eg=Cn54!%&ND^mNwMc+gUMa6ILa&cUp`VR?TIr#>QH1?t5D(_C=Q zU^_8a^}J~5N`lLkj26gCB|R-Rj(?{v%R9wGH+ zF!tKI(mAY{8YuFx7NwWWxe7Z(zwBz)mY-JXtG{~mM4IgxG@;SdTGb}b8t=enB_(H= z2alNYa!_M;!%W-jN6(Vkl^%oHQalo)7f@>gvT#zSuq~B`dF$JiIi(2G(3c8ou^#9S z2&mAug3`R076SPq18{Y5$^;guYg38w1F((~ESY{f?WZOUz@dkVnjB`-WoO@`< zWIPmg+(S{L02&3*D1b%*Gzy^SB7h!xDC!6vi+dc3+H{U1G@`bx^HgdaOR*8j5fQ>9 zWdmp3x~!}wFbfNwvh7QfHbicPvQ=}Rr4W#fic@YqNlwOM%J^I%3v--v*@pD*5w>pU z(xo+Q30TJ_TQb(GQjJrUH8EgOvB<94ZLJE$hGImm3$iqprO?pkG)zY4c+yHp`*PR^ zXjsr{c_yk<*;prX{N>Elg964W&bjF1yK9O34ym)QmT}yVooP=Bv4Ce zpn@{GCZY!)b&jz`0Vev|owr+{s$0FiE!Wh)7j(JQ(`iXNJ6p#k_bjM&}m$wnUE@0F1hx1Ac-bkUfz%(x;ltB z)QOPVEC0C?$9&bAJMQWI$V5vG%HxH)jHxEYShCX=dTuzJOtdtVjAh%i)lJ4ou5xme zyCInjvU?^MoiyA?6Mgxyox84~lQVDZ#$Bi6BFd#}+DOH0VV^o34CL!fk-086w^!>s zOuI5k*u8WIePXmW&fJ+Uv~xnsXDc4o7Ok`BE~m{MxAb0A zqS|wmf{xF77>c4WrECZ$*TbO$W6`NYO(hdeYND>5YN2M=rpG=4bhr~kG0(fIm$+RT z=G3z#kvs0%y$Hd;umx>N*jd7tCJV})E>ISHJeUwL7Nw08-Z)WgBLkP(up(icJ_;dF z(OqUF<98zj+-@v6H$E*HvU>;bMHJQ;NohE;iK6m`F)lrm)w8Uyc3+urMsDWvbj4irtT2D~ z9^BJ%pggL^>I|fgf;Z9Ylqt`Nx6aLjH#X2%sd1jiCgmhVV3jML#*N**u{-wQ{u>(` zD+9PprPz=sr*dPMarZ)QsvA|I{nzXo_~wo6JrvJuZ+C6Oz4kUXN|WpsH3H(H)`kr9R8{%hRZKfz zZ`-lj8l)cfn@vr{#IU(h*J_Wtw_2aT++lXJ3zckdriuv9X?OQ+#JzVHQW1&|Yn-qg zaNx3z7F5IKJ$BctuI^@Jnm1B=NQ`7kS$3fgf&&kWopk%GnUi|sJ}+MMRab@Ot9d-? z83j--Z*St|yOTV*zM`%+ZS9n8oBgjZRyO;5@_Lqvhqsk3NB@itL$%A?pHgC!4EDC1 zU0#)W`o&^{Ii|zXxo+O_uR`FQxu}9OE(I#^Z7kK&jYWB%y-&E3saYm?#GC9qRS>Pr z$C>~;va6G~^2#mWzINZ1RoHOf)z#ACuH7*!H+uQg>2(>Tyr`-rEF3m7Au4FH08TpHlSJj58;-S)Ug^bIj^hu#MqI;`jwM%1cY2N54s{hr`*qrr znz$DHUg~7kBX!=$w0R@b=Iu;N%ybsspHk_9tr;XcvKd;ix-R8nFp0KE0nv5a39a0` zxok6NZ*MNo165`0s$WnKvFq#O!Otpb?E;r;Dpb4ly2Z7{%ergV>#y2Xvvz&|7J}!K zqmA7u3?pqEP8%};c0cM^OQ2Yyj;$FKAC6vj=BM19Ub-UGr?YJx-t?G6voo9HgOk$A zW*-%1))Ft42x&vq>;sa}uH=aka`x`!k?CY55#!^Eqn#-eBW>*6zoXK|S_Z~PrH$QL z6eDfy-M?ef#(Gl5laVjG6DvkK*}Ip=qmxbP8Xpxyb|+hmw6S;pj%n^}3P>%RJA;VS zha{05i5t(#!kHE8Jed`nn*7|kTt5O8E$#DXK}9>VM4l%VbsdbZFVEhNRP@29Xh%xQ z^Q59aE;drohoYbzxi8O?f@aaQk$^r70qw}Kc~%6}=fRvTdT)M`B(#zVv`j+FsX!l) zigso5JWncGEvNM14YT1!AD4{Qla7|iXf5mL0};}`#Gz+JNK`%JWT{fet|L z_NMEt#JsqmLe#o#{puQ(fN3eo7;IO!X?srI)=wDTvi%b_r}Fh}Sv!wr_jp&fs%?>V zohZ3%SQDwIjrRJiWL?)MZWFEDgz4*Yb9(G$cw(ADlVxSe#BFMqn| z*m*%pFBYM#JtU=1v{KG|G9+b~h6=`O6GWo3pa4S#+fRn-DinWDg(`5VNzT~nQV><9RH)Ydvd18NuBrLU-0G3`ZpAiY1qs=NU?gsnL#TcVG>j z0o9Qg77D^WOgerQubuaGb`?)(2%yG8js3Wh|uwM0Qv)2-n;!J_gm9VM` z=eZ1A8R<&V)CkK7lVK&ekVW-2#mrQpwq{isCz)RJh!CSUwiez{oo}c;$-*S(72MQy zP|dfgEfikwzH{@ZW>xfuG|=+F8OU^n5&E;DTUM8yFzbgt@{SJsn%9%_FnzyDoVi?` zUA}MYqJQynwK_D`@S$xd`;(DNO`vys=RhM`GvUR+_4^qUURzA4Wz((qs1waU~AfVLAJDfCHFD7Dj5TtLT=u5n)2oQqLe>E}YB4;1PnNj^D}j8J>I zF^%V5H$1UaWbyQ$XGfB|+83;lB!zFE4L!E4TMwc~N%W=slHYn4J>q_K0&UkSdl)?` z5rXHb1TO{ke!!|J#+*^q!XqbHnWNTH9y^nTw>-p@m`_Ga!(^)JdDX}R!g5?@L{us2WpQ;=%#xp;k7g(jd5I#ghzxI9og-WXISF~D=P~O zK+pT`v(JF=9#wlBDfHu0XsT4ymo<<*s=C}464ti0LNzW> zR-e<}Yvr)?{@Ib_!?nk!L64hVlkNQb*4RVh6hxf2y-&Jp2gj8?+2iwali6#YI-i8cvLOpxqS3pbov9oWyq)fp_pMIvqJ(K;pS#KiMK84 z_cNnR-}YLY-q5y#T?FP1wC#FP)9kD3o{AxL* z)z_q39;y_)Jv=RUOCKQv1Mna_1j3`=DMZy|pnoyzrWQwJ01PS2%T zDsU>3!Tc6!+mF8Wu?d{MIcV2->tmx+kg8xI6?c1;4{SYS%2=~;>m%*8z^pSBMAoK( z!U`qBLwi-?X>I+!#+e^(>xWp-Z`gViQMkP|U+jrjOiI3mDHX$)+9XTkk}C~Jyjq<^ zjGT7nyyQukYh71YXZ>`)yvh^;zqp*9w};U4>2ezW%eJ1`Nq5((PNZ#2jA5Cp^O3qq z<8MA|$)bT?RA9R#YWAwI8#Pp@q%Me5Yt1eSRx{t?o!yB|s}8l*W!Q~-TbJSI$%>dEu`q6W7V0Ht&+iwv=aDM=lEpRaM}2!S z;KJF}8>**pTHcb0l!mzxEq2nImQ{=?jE+IO+gx+h)~#pIU&6UV59= z%fp#9mzyv-qff#&w@fvw&q{6OSMy9LlhCqUAz-C$yfnfG;4IH_1K$^_XHamPqaIOM za|=7L7S`57&RD!lU`~2}`ePZGi^7RQEteM2)0{gB{FmHdTdIJ`nk1B45>Tc3rv)_}sNY zT%g2H2pJ6`DbYHCWwnggLAUAEF7+ugo}3qn+aPKPu*_?cx`vW$)Uw(F6CR2{#P%nl zQnHCf&2$VpmCS5+4D16lhVh^U9YN*XxklAkVE)w76q$-uiD#ec2Ve|Rnz(CRwxUTo zBv5*aI;wTX;F7k+gNdS6jaDWFFR?XU8Tf6CL0e!-P%5a3O#qf#9RZ`t%Pb4`q2}zW zmlfb2GuJ6n=6DggR-XWTp8#WUks4bV7CB1Z7@q|`Q!&BwV>1R7MKD-!?WAUrC7GOz z)j@YF-a+U?p>Vuf2oRofm7)l5OO=MPzyMzEqcFzt!ncR2K6l`qO?ihoQX!>OYU6aV+ zQbY>}Y$OQryE9Ox2C){P)%Z5en_KKy05_YwgMq3Dz(`?vtWiZEmjh_Ig0H~;LNZK9 z&SOe46rgZsK01hc=<0?PG*vz(10BJGeW>nyF9sqdo4^e!brW=9jZ&;_`J`N1LuxAn z9pM9?3Ii$j<%9j<+ZZUqbb;`(f{tc!UYi&-&yWT&r#mwcZ4#Ae!YnB7fOblHOej?y z)D8v$r&~<1a8@*j)#SO2Dk)u{R4bt(ba4x~49-}a0e|?KY%-^dehn{s1uI_KZFxZ}wyDsgb`z;j6KdQK)=up>lvHc9%nO6e@QU zDo1cke||z`XAIy;d9FvHvLsZbH`4V~9__&6 z2bUjrO|-thgxPeYcZ-Ax>Bo!9p8&j=Q|z6%iYAw z5dxY!#Y=m<$3qFR_7fB@`{Kw?Dy;cvC!#(<@v`a6-^0brp5tIWwe<1j9ImKhJvK|8 z(s?s*aBPV;ybY7H5GQ9~MgY1zq^=6~YAn2=?RQmg}dCTv@Cx=)GdsbkWGeh^xQY z-tZ9eddP{Uy{86t>g?;}^){SM@)qLSc%F(I$^1fyeJs*DX8POXQ6*N4oj^oMv4<-A zj%E4dk>$fqTkSv0u}juJj4UO%|HNr-jDIR*d6cBG$0N&j#jF;_-IXeb@_Fsm`y_RQ zZcw@&FDt+75vB4(XrWe4@GU-Z@$I=>rzy13OT2z3|KtpDbxk>f*EjFGBB9~t&CWT- zTl{jf)NrGjtp&B?#Zy<8la`xStqKWqf_5HyD1=~f&Is*l^?}vIivupz2oV{;B1+Zd zbu7$8TZ08+B-<4PY+JQ}2nwWa+w!IBv$~ME+*K%lDyqiE_DrL9fisHB+r4BoEw8(b z%G>J(rs7RQN7+6k_iUKe60t4O<-cLrEoB|{#vQ-6x8OioyT`C!GT~R{vel5r)FhG8 z_N0<7TUV@Ud3~FiJ~PP|2}ydh!P}iiZA)w1H=CP`*NgQ9Upk(8xR-El7|pR{uSaWL z$=G6Y42C>R2oE#S9+QMN$;JDU5XsO0?snBTF^SYbxd~QPDWThZAQIZ=ZMq)`?b8kp zCZSCV!NW*sO<-=vsHG#Hd#V$x>4sa0W2F{A66DO!pacb-t)?7BPD*%BHe~1h>WfV* z#RKQRJc5ILk&HiB(~XpHH&AS=XzV`WzpBIBY4u{0wW^JcH8s%zuq3ZG=fp!&eCz6w zyL;>E9l?Ke`0DM(gO)yT^W^5VyqzD@ryAw6lPbOI@1$E|QjIngb=aL8(LDjZWY)oN z)xFr?aCuhxb19*M4Np78iS)Fyv&)|dN^hpOWl+eVHBa8HyZ%6+LNgnsb;~l$zzFI^}E2sJL zJWMVY_qFTN{d5)HpIwIBEkSpwAM^iE*FGwN|MhV2ulpUI-8?KrfgLVWLgcP?{UR9B zU%tL=4XfGpI=wtUor!|YZOC@5!0;#&NVZHV#4{i0qO~{sfI+w=LHf2VH5ypDrLXbd zk^T1HTa&Q=`5No|wxzVW=5XHjOU#@5GwkfCcA3)cbh@j-ocF-eK_r``-@?PZ&i(5> zh31VemZ_!SGjC@Ht7bm>cFY>BEHc`r%BUNaLtAM;H;@`Un-rpNJIZeV#uf!e z3>^fLMn%Jn^;&GIaWb23H~&S!h1LEGgB@7CzO;Lb4Lc|nGI*?qz(p;vo699??d#^u zcVO1ymkcl%mGAq%wB@EYLGkXsOdlMIGlPa8V8yzOiDi(bNJhpCLCTo33No(%hCM(S z=0OUiqTt`E7;S_w{!yWLv1pb7fH}92^q#6;qyX_?eRgg?6zdc1oY3-cD0Y%)2LJIU zKv6CN%7HZ&Yw@{2@y-=^Zcx0lE8IRPHYeON$@o?%o@3Yb$=uI*0@Lg`pbX=_J>b^l zY^Vl|gg^#0c{ydGi>?n zp<2Tz@!kfZ@ENcuxzR4b+J9WlSqfOP1vILP6OBq(KCi28O3_s6%oSh#ez-O#$|~>g zp*cf{QSYkM;JZ@;p53cPA=S*n7S99(#pzADl?@XEl z!QAVtxT&m3721qqS~pPu`DA6|ClzEIHUWnj?AvQLK0 zOXWWsu->%-pBY#SMHL)IuzucPP2u)Q2Qnx98g4=A-F<>Tyca|#R!cC6`KmK>vDTcd zvQ?VkwKkar?Hv{{Ms5p;J9+^_I2ssbq-;MbQahb^s<8SnyG%7eS>q^VBzU1y{MvTv z-5#WNCsc+<>VuJ5$&9TEc%hdPTO~_mf_tyD`Am>{_X<2Sq~6`nd>>N#6GnZu@2FO9 z0fY|%+d9}{lH&~>O>IPd> zhwDC9>e)I=Zfl*S2~lnzd3Xj;opoWJ2@ezoWIJJlaT!W@;7Y*I5;=+_OQ__`EEM$P zDa+_1XAWwM&W{S!A!}W2#O7s9ne>`9p~7zWKAHl9kU69GLp48yuAF9OeB%4jc>rmr{V&fdJ!H0PgHxc33YC{<6CiaiQ*hYx0Bg%~ z)T{6&3cM^r|YeAFSnxl$x2t(?zraKv^wV<5M(^;G$$1YJ|c3xq$V~75Id}TAoH28WWj7px@__^Tq&K3BC@LEBpTbOE3Gr$q$1rD@U9 zCC%|?2S_`uU?4HyLWG?SZq zK=(=IeFPV{Dmql*3pO`$5ru$mEKN|hQn5Ri@V6{I^h~Z9<6a6Q9K>;gw5X39P2?q4 zud!%6H%c&2n+Ub3iZPQo1ij(=L06qvE(AY3??Xqt%feiMJrAo;h*&c-j1C-pE}*+} z1wN;|53NrGbdW)2{x(=%#)1zE&pF8I7=z|4tZC@rL*tEPjZ92eI;~cm{p|BUXoK2q zdxmgrIR{b$mU;Bv0+B_{CL5!8DOKuJ6!$UnQblEg+#Et>M;R+nn`O3-oBSa{mZApO zVFkMf$x)k#OHELr5(PqWyF;u{pD68wH;2P@R*?>Xh{gvPkC6&slxUc(^>cyioh$H} z!8LfptEY|DnKK!+Zg|z4dL_%o+hUtqz`@zFWJLb#(Rzn7I$TjjmuG_9C79@}E3luO z*U70MosB$3=dFfToukCs0W=E-P#T9@d~rF6l%c(v$MtT20HcplHG)S87!jU&g0Y4r zZ;iq%v)96Kg}>9(n)m9smGIuEJ&{--Jt0-jpIfF`XQ!D zVop3Nz7z2&A89<{_ZeS5sSEE&m+q(cfj1DX9;Q+6wg%Pu%36a}|N#sOGy@;1hCRTdF;{N4=GW zE{%%@j1ohnhMZP>HrXP(SKzbK&)tcZ${GID5gt!7z<7ZXD+u8w^h6t|j$t%L3L72I zBf{^h76qi7PGVc!@TA|uzV=m~0&Tb8y75?Z8(yH zufj8b`Zanh2mL48vh1}aYZV;yqt2X)WUnTj=^05}AAR@txd6Hw=s2NC4mnNlQbYqN zRJirrP&YKOD9~tS_!rlZ5pD7*RztbW_T##nP^lL20J}?Dp9>h)L=k{$HZ!WCtVLGO z1=n}Zzz2rwCNM$*>oJ%JgjXdg!6N6aD7z2W{X}r6q}wHT3O>Ptg&`iiTS!;J)=a+K zqENa^=+0<2QpFDo*%4dF1+@dxBL|RU=Qr4OoU&^P$~0u$*dM&7%^~{r82({HcX!PB zAwhS@5KCA|V7yv`kcD!JX`z{uK2f@QP6_{*jEu5wYHV9+s|+!#02c4e2LRoEBE56! z{?RrjQT~0(^@=?UwY8?mvI)l6XCspDoPlQs-9|FCBOd1n-5)e`U){#D>Fo7~f!e|Z zyeptUvBbG&6fwz2x@K8fs8B9?DU;`sM+c3$5h2p!Uugcs{5tKsXbwjJ5oT+8;h@kA3p#&d(o=PoWXAM$LhL zCEE-%EJ--4TwvIz5;vvJ##B~|ib8l9AbfiTx?oCbQ|nuflLWU=oHaGD&}eTeWkk-6 zSD~29bIe}ttzU?(rZ{)@{uUCes&1|9jkf{3A~I8rb6B_MVj9JeEUQu+db7J{60y~dl?V$FpzG3<@Z>Cx_k zJiVkU#giG(qioASvb!+$yEkVSqdm_`c|*nRMB)julL>_q133|@=32$7oCS=K|I{XW#<^Yao!M4B?vMz+DqE=pHa;Kt*=|YcWyG?UJrX5b$oXdbm$WE>2K{ zSd@(cHzG;fu0*XrC&%yZvyVsOVLRL4w|`~>9G*>UNpDhDi}itU*gyHUz|NG?Se615 zX)2Q@qjNlICFFVq0V45rXge#f0+3)h)K!FAq38u|9h@uup62~0Ow$G}aE_Sk+9hUz zL(Xx*w8!+-1XF}-JsJDv20jS;U1(p2+3P{!w$brhBh zn}JQdKo3?0U-v}@>#fgBJg^gMe&HDap#roXW*a9sXPPmF&9-cRWA^!#(IhZp;Y&5% zSRYc-(NUO5fKG1}$LNYM$r>fA4hFlpKq;k4e3>y{tmON?wjxdjXUR6t8y`JoQBqly z5||z?b=S~>9iIF=_{a`Nit)H?%~b*gcw|YDD;DjBD5H_do06$UUuE8vlChH7NRh!u z&=;n)h*g(6eeyo8A^Tg~GUDs9`h2{-$Y*6`z?fMXf`d5kt%l-WWegauElIJ6X=YLj zBfPd6bfQW&Aw}qLSaxf1EAIT_HX5XZ7OK>tAyhc&C3CJOn+7yEilbUBg}L#W@vusk zCMz4MI;OCdC!e{;KzPoyuM*a{YF$F4Vgt%DN2#nG5GQCMlL^~;vf_0gB=~LOtntpr zrldrvRGIHGv<(^<#E0$}%eGKhXIHjxHIg)M9D<=BqBolP%( zTJJk0YqzF})rW>z<~2|c0{#k6*Z%#MPOMfq2 zo@4#;=td_)u5w=n_R54}pgA%vDy=|XBnm`D)^+Z!Qj&quRw!d88|HMPBo3gK3JzAb zi<-NIj8##S#Eg+5IZKyUOQv@}`4LSmYA|;`3%}79d#z=*E}YDDxO*vu5ANID=jpdq zHSs&V|7}YPo3z3e4REd)p8Rro{nP9Q1a|((^rE|YvPn}MKDZF=nky1B()0>i*2#(< zc{2A1Ss4;|DJIWByrMJ$j)To42|`Nt0}fc|ep*ol`yaO#zT3Z>m&)Dz)xmyR`Kcp= z&AQjyOki`e?D9@?7?c<)>;7Tb!#tG?bJ_swQpk{YVuaX}oQ347jP#I}z)l0RqDT)} zfv`Kt%&2g+=hb}F_OM82tqSddt>Lm-DzHZ<-|o5C!*oe2(pm_`RX3_sh)_zhM)L^aLqUy+X|GX?n~AfI z$@^#0kAg&T8}U^ZN)x2PN^$5gK|d3t*zOtlSW*#zM(jj!2a4Ki@>*>DUHko=SitVM zDYl3xk&%E(0R>RBahYTa(8yyHW}^jcP0wk^{QEA&F z3P>xd6@K1*7H7b&wF$CwkWy#m3?%2Oq2}czoGGj|9BHU@o+?oZ23cQeD1iY=hfng| z99l#{IVm;%f_z*WsA8T<8;UIUM_gd1$XM@i> zXW*m4XTyZoJ2Fn}+UM`~WMcPb*oMn@d#R_q8FZm^Gd4tZl~F%jSnlh!d?2{2m1kV= zq_j{%kaRS3~;Cwtu(m4W9fLrt{%vC~ZibDZ7(Y&s@N{+k#;L)zHLk|{Y zs&jJaS&iVzqEt)O0)pfr0FA5kCKhzmGdj+4HpMKNmcpp|j+`6G8_hbIn`o_Ql#JE~ zE_1y@W(L6~RznB8Kcv2m3c|Ypv7MFY0;xM^;NuZTK_X-d-BG}L&qm*I zn00?-EY>!bRVqu(U1Mt0+Gyo6Pe)`tBI6;E(N45x!rwp1SPqeB)H2ApST7^V35v7C z%5%}wchA5_1dVoLxwGnsj0Zw&%nn6j#5mxbjFDzI36Ax2gcio*QXb+mPXty2-yZSsU}!V1O}fJbJ;U%-%AxV z78B2f^WbbPDex+kzy?4s1uMRWYNL?8FqUJYq_xuM%5tp`_L)xU9U)}46x5Jx6IC{i z(K%JjoU!dm>>h*^6U~%=zzKL2lu1HL)qqemMoRcUm}GvIFAboxCwGwufa z;T(K#I!gNhl3Fk)Og2WBVuFp3mV?zn`C1s3PI8xv%(D6bq&Be%3otH~Gv_>Ju3CNa zL{fx;@3#%3=YZ$P}N4q&Y(#%r(ce@b5?6lu!-070F*CduG~03XZp*@(_;^4WG-9;%(%(yHes7^xM>yUL$CtM^@$%P6p3bg_4mKh%h+4bSSX)`+ zgyl^RF6(Fk!d$)|u~<`(U#L7qYn8GPdUP~7D&b_zSgR5kc!jf0$jXEMig7Xr&54WrbLMirMYXWP&`$mjS%}2CuqS(41Lk%^>{jUrx^GwP&8h%xxv4@rh`KRa7gLfodZ!)F9&5%Z ziK0*tiYbSxizQYQ5*5;l;q8jOOynFX#=T|_(8XWDOWo)!id0rb7R8-F*I8p9fVu_% zZ|Ot}qi2nlMOA5qGci6F)ZIA)9~J5fFmUtaP#1zu3PrVrfw2RkuT3ZxlCCr{IY_N` zd!o?ifx2yRfT1#SeYx$Rj=+~<#zckirVJG^fJ#aN z)2h|Z3t3%=ju(NojzKx8IWvI7NO`0&mG8z7j7iH>cZZX64y6jmnx&|rGI@U|@D-YQ zWA6{Xg&ELp6iuWA!^OI!gc4FclY_c_Gw>0CuLbxz%eEVWx9;(GX>HiI5w>A)Cde_; zQV|3yAYxpp-nn4ewq(u2%=9$U>BXzl^Kdb(1RfuHm5}>_@P|<)^9GVW1N&IVU<8Rwt z{0+g?lgKE(M7h(eGIyO_T|glrZqfqsq$pH5YgJN(did;8i!Ua%ok0k4ufxTwb|pWM z1mhQ_vAhn)Aw)bbO~CK#5n`rb0Nvn0SU;ALdi5&Jce zyNVZWEt2OTQ}3REk42^ijqr)*UTXaTI9J?pQ*4p1ohZN{Jkn52ou;x9H47I1X2(q9 zPcWk`7Z#F~=9w!eg=4aW;2>ad!L#C}=oBD@h3b{g_%CKqhT>#0ju);&c{er>XE+Ia zE;LR>)_8KylTHR3)P8&x6RChI{{HwJrJ+Nv(m3*q(FK32STk?U+|L4^ch0~^gwJAv z0dn;LWE$VM8Mfi_-CjCo8h;|VEHsx?^e#ex=At_3Q&8D4r?{bV>Q?w)~<2$$6a)Gvho z05Xjqf%%we{M|%Hcl!dGvbz5{o;Q*;kaQfShqX}?Q z6{YfHkO@SUL8@m0jk{;yBZ5XZQA&F0j?j3_r@O#L2{k<>;GE^oYbTR0C3D7#h){I1 zQo>=WQmv&FV-}FR@xH_hO^u6XiTt_YY^t zisP%UkY*!P<3kK37H>lJ&jcHH&%nonji3D<{1D#VFP!E5!bn84bo-e-Z0J7?gd!bT^RbLxnV$6Vtp z09mz20sEl%l2YQiaEUmnQlT< z<3gpK?J>y^Zgq^@q@0z{G?4D~tzFV?qP4MZDYPtJh;O>(Uc?CxZV=a+{~p06exg9r zSs~5urt3In5dTbV1m^4MtJfz#?weF?Cf-{+@N$_yAK#1?4*V4ez_ITWg_FlvveOoV zR~wC0AzBjBcC+~A^mUlM9)wXu2{j2zopt2URlrTEcM0!HQM1rG3d@DfKt^6%P^tt{ zYhY66vYPtVD1nXdf@mVRX?yN!3gsNqbapik#%#kI=SxYr){P-v<~JmC0M@VP zl!t9rr>|~1qNAJ3u-O5IE##58BtyYM;F@JN15^x9CS0f2m^C7V-3^V#+6ohcew=m- zIdH%>SSafpm8jJ!m@2Z8Ip>gVGyr;A0#=t(254*w230xc009QtU)C~rDF|Lo(Vcbz zwghW08Qx&soFsI^Ut|hz9HyLWi_O&5ZBOAU#Oc{W776LROlF~$#YBvr84h|PCaukG zJZ_-Fd7v)l%XCXY=xuj%p3?1b_VqOZM7R5T7J4=K>5i-SpOfiLIdA_l=Mx|ZNbgvO zxqNhe9p2FO9apg>q*hR+RVo;yPa^Q%mge%X#YbeL0-RE zul}PTX;&VYG0}_QDs#%&;9V^|m?T(rIWn1@RJ>H5bF|qC$-NIkgqAd?=iyb^5Ul&S zKh!XV?`6oc1S&b8Y~Xryaeo!XZQu3+1zM z(Wa(kj66HTAdU>g&lXzJ)$Qr|^z3YkEAU3r<3c{0UX)XU9_X(0+j;nPdVYI;+AnQ< zb3-pn+Sa&P&M(n}{zopA0M`_b;DsdW>2+DA>FA}($#`193}3BIHdz8zx!zs|L{>yo zgM{oL0setQs0f)Gst;q7FJ4jUkR*5||0CCyuQv?(N(!M?7mf_*$bgOv=*WPM4CrHL zK>v5z8m92`<;B^XZ9M45g;KV<@V4eEnY2_xT&W0jsj)^G4aJg{?77I5c}JG{WVMk3 zN{|<&Fs((bt=H|^!Y`j1D;si3bOB~7p9;>(5TM{WAgRP>WDNL_ zEtJnuWx=EdrF(5PR#KI0$j4Y!Z=gowR^0rlZMu8u{Sh_yjgww7=W4R)p-H&J-%E0z{-xq+F?EeMn#$ba>a6$5|~cD z%`t`b(8$)O!%c`k5vm`>1KB?iWw-@)S z*U%lAjC*og128>5pdv~?(9_H7OlK8rEjgN^?AKu#*fH6fxXvKlo)H#Z zUt_h&Vs)`tTHtKN@Rki<1v(^{uh2WmQuq5uEgsN8P-Z|%(UGM$nJWnY?McOlvUnbo znFQs1(xPFJ=?Z-YBBi?5;_>&gcx$_Iup9B)MK~{8b;P%{K9{$Yov=Uky?^l`tXHdY zZQ|nNp-x(3F@5+J95CTKuP#Z;9L_z&soQjO+s1R>2Y9A*+Cnl;Sn12*bdR;Y-=8qN z8Iaq;roEWncMJ;aG_)q>J$o|R0fFzFjQGs`A7bHCJ7nx@v z+5Cz9CCu)=ojZ%i!mM;VyO|%ltr@TA*9zq+hV;|Cqx~6qyKCEH)xkO2f~T&kcS{r5 zkhN_vmvwu5?)uZYMXi6~xA`cR`3~nk4V%|zXHiZfbMo-mbi&!+8+Lj{bvw91y8n~+ zI(FUL+U60H{jvNqe`aMjZG2`t5ukmOm5tGHC2ZvYCQim8o->_gCrnb+x`Y_05SL|+ zS>8r51TADTVOvkeW7k1)EGK7;cOD>^k~7RR&rKOO&;sb*!3>`o567{n6U)Jt>P+?C z^Jth6B5|!)sg!!l*c?seh2k)3@>&QVN^&}?!tM6ntPCiT^GvCQ(l?t%@Zt<+Bh@y; z>73k$yEf!4{2`T0lpdM@9BZo5jwR2~Ju*e~-jJ*NL{y3*P^Jk0)+PrDd0VsKHCesL z$TUYWF!9zff3toZkVA#GtqmFx(KO6t4fVZ>&i*xjXVs|0!C^T_CDCz3!j4c-)3sHS z1@K)c+dP9Uu&jfRpb@ZcDzh9#6eeH~bym46%xGBcPNe!P%Fy2Diaf7vDj~^YTJ{Q@ zy11F9WqR_}j+MZ%$XuCdgo+9pe7$pwCqdgTJob)l+qP}n+_7!%*tU0U+qS)9{>J8+ z=XvvfU(P=#soY&v-RX2!CEb;~E|9z+E_=ix;#D1;W>8`k2B4#V>`p5e$y8jQH zJW7^PSX@a@cFXeD?U0mG$}laqx(WLFUofo-MJYgfa^Rm~D@UvJ;dg(Y=a%m-+_DjW z&%5zS9hrwpC-|5`X9C@XuhDeZ9A_thQe9u70>GB*(iwZ!Grq zP2T1*s|1smtNe8<7l0~Xz_y%k?+*7xT(fy?ORrH+YewCshIeU?c=+da<+g7XE7Qku zD*iR%&w6+E2VOFqv#c+m{u|TZU8lEI1`hDvZRyi&AIH{#u&EDNfcJi%Oxo4%C@FXV zns0yWCQZ3Nda3I5{s({Z_;5GL2k+0I;P>%4*_pG<@HA)N>)$?qVa%Bj=lXGh(axiI zDc&{uY;4xh>TTd6Yj)~C-_zkH+W5BRfjtImGLyUV!Po&mi;(etWq&j5!R0>U!F4mz zHv6{Uzd};=0el_QvW!0>eqSUt+Mf?Y>^Tw&k|qWaJMh-<`thOP{w13e}Dg z@bkOlrT*k-htQ?YWP-$K!N?kx>h5))c6ITm8RG#c>(=pEJ&6CNFJIVL#}%M{Vam-v z4oQ%KmtS4TqjFZ_+w1yqUSxXU`oQeu<<{x+_15X??bfO2dUUe=esnV7d33V=eRLA- zJI=0fH7>0~jTkcivE&8toW*&km%eY3gA^xwJBIrIhg~!k+`P2w!zclIm$hG{PKcFr z5XkEQ;`OB2fm|N_NIdjy+dLfHb-GF@IGIg1^8qP)YwY#5QG#8gBYj`jbztVIhwwFP zw=LVzwe;Yb!BpIQb-*+{DOpn#6S{s5X#E;tN>v4>h3vx2SYfgJ&g8zdX%J);BCEH$ zn&~{9jy{h~3MvTzC!BBh1#ZOHb&tFBhz1naHErB!yQAZC%B}adg)c|{<`TTX1s~FR zQF;`;MuvK^G7H?@|Gg#V7x4(hF~UejFmiGgMW8Q8LqH=q%QegBOzgk18T33YW;X78 zn@-vSb0klB^Rbr|YzC!Nkd|MT1;SQ>BD_|B^gCi$nUx2tNVE(rMe`e^XSsM}l9p(- zb->u``lb(e-k@jyKBMneEfg@+=YT=KF$;N_FZ7S{1W)6G=lG&SM>22ihBH@T!1r74 znc6$lEA?~@2p6&u^5i2L=}H1=@tmvlC9zg>5X*rmvXCSSD`ah`M@qv)m^!_85wf@j zW*jqVTKgy?H|Qh09k&3DZpIy;EOgsDzN^#Dj*$^L)s{;EH{pOp0d*I92cD(0x@hY3 z>RW&0m$L<%+JvGUB_bbC&3{1IXSQEO5MH?2*FMPko(+}~p+-x|MPu=0UA03V5#w?e zX%?XG4m_V6C690CrvP3YHpLlv9?Q<}1tBtkr-J+}gY)yP#+(m*?Ph1Up%@kPj-V5d z{k2GT`)4zWe3v#u?QB{xa}dN#$i~Z(&I0y|K$8j1w@<>4C>FP+g&VU!XhYw(M7CYe zAiaf(WVyXpN?j5f#nGxDzR`DcGQ(FTMqlSDICWh~r$Ckxa*Lfu~x3qgF}$C%K^VD_FZ59#dnY1EwzTM+FO$_kjq33c`s9 zu^aW*Nc^iloyGLC`;5pPt1Dl|;);EB&fOSVtnMDYZlM1QkB)YpO-**giV%NdznK&QrPvIZ3r>;kc>NkRHset{i9GE z4W`L8rt!)DtNip#t|b8DVa@$-XpD9ht(UR&!QtzIUgbf?J&iEI-q;~dcS;~I&M^C` z+bby|Rj-5=IktSdPSFNo&{Z(#7G{a^Sa$LB%qhd5+ls3|q`lLk6V`~h*jsKy{<}3; zt3lYjKC<3`V{ZL$C%yE1x)Uj(K==$n!dxoXP>_@s~%}^NqnDeBet0>-YfLN+073xW>eX){-Ii|$hSAA)7r55ZFR0d*1=+a^8?=ctZa`!>KAfsbo! z%+)18f}Y49?XU6=n3Q(O7SWtdoBZ=7{wrr{4|BmE?o1%;fk5Ofj_7kV{>$WHpULYM zv)dzDpI4j#|G(W5r5>h{{~O@W{Bwyud8~cx5tz`zVa~2?j&NXe0wNSwOk^d&)HpJv z6?H5Mm96Jrd}(y}A{j7V$2(P4ibQVb3tmoVT^~-k-< z3P^?T_n@zCnYB6JZCo*QsZ{RnGtly5`tS7^Ua`j+w)B&|xbX3>!ffx*6I&8SL(e0m@$W=q&3|yIzNy8u}-55Mq^Fas035TL3Fh|!i?Qxm& z8?K{76m2`zKi~h@wcXMgE+p`_@|~|xQ$zFc8w7Hn$tja~$u{FMPZ6Wt) z{U+jF_UT7(xS=m6WH$=tm0R^sE?%<|_{hcNJ^1O<{Sr^zV$SRHNUM79Rb4C05j&+} z^2kd?zh*($9Ib9?s;v7ZSUE1i5}#fHl|(C-%Hc334)_tIj^+h~qERq0hxW1dMuu_5 zF^@5)oL(BoZf{!&YyPAKz9N6_lYU-X?X%{NW`$3d38M-Z{EtohO?Mg(z5=7VR`2rI% z6>U)Gprx->q$EW2ln2hs_z$!&#o0q$&|9f}ecQp4LKG!x=>1t0q43ZQI22O}$L{kV z!q}XY-5N1F7(N@02bn|6E(};*uEqr2u<x%P~%*Z15#Sa z4O>CAfXC`Bwmgd_ogNh+}6j15{QL)qS8qW z+~${F?Lc6{6PK~lITK3*kg%+95uuCVbi3r;@?m1=bl=y2_4*v}`*x2&Q8-vk16Kmg~+t#TcV$Xv+y1`9)gdrnEil>eTI`HYXuy zcV6+H^ZoL`LfRRow8gFtt4mNr33iub9~L7h3~73)n>SvDWODv|CqYQevIIxzOoJYk z1v^+s=c^-bW?0L z|66ZpkX>34#hBB2f1fOm*r$8?a%JOnyXa+4iNwcB$dGKGUWY1HCTdw!zp1{VCHF(r z(Wz*af6J0;8xYyv+v^I=2~Q4Fp%0?w5>-AG{{asdB4uQ8+L)vQ^_C$7wx*CD4+yO; zj9;$~Fm9?${t%=LelwWRo%vLqdw zpOf6%WK!g9>F%cPwk|6}J#56N)y!_%H%UYSCPEuk7y})&{p2iK`ASLe@~p0>U<=65zdA$x(Sa0?ZY`4kDWtxspMCIh!4jWex31f)ZLGCNuz9 zKlk`lKWcmUg&8$20YM(fOhT(;#6=d*WlwJ2mW-&%`wN#pVKqCtatI5^Ob6>#TvO)^ zIPcs2+B|%wtMUlT&6Q^brB&8vf;rrLnq}~8Dl$;~Hr9=xP3+TUp6Ku^bJy^T%2JRQ zs+&s%9b)6yZ34edAkQ}*3yv?|7#m%Iw}Vil)t9||oHbS#^N33Ep&THpKd&67bMTv- z!$I=ocX)JV8iSi$KJQT{OcSI&wC~vV}{pIX_JjCTwcQ1Hu4)P)I zef;9i`nqCzKrM(;8=v^wLuT0h{HIIoYmaQM*4?u^ho2*QCVu_t$UaKF8o_bt$*Ax-Zl>tg@m~2!i7HH?-apt_Kr+MQ zskib~?f6RGJ}VNxs<4*gEr2ZYa_P(v*{X%N0@xH56g?E9PIZ)8vM9_^ml^B&!{w=cP5mM3u4s??A81PR-$hKa;4EbQTB$TYo*HeN-pl_ zc`|IymE>L$pU%PT?W4>$o7Wr`WBPA6{OkhkUb|$i`nQ_5p&aT^>tIK&2kp((7`YKf zwFo*8dMuM(^iISi z?=wy8-p`9gkQ0AJlt0>a;rWA%Vva@{gr77}izp-bkVUIVNv_!kRMGVh!bLB+h2Z zEljX_$~@1(ytYMzAsOiT7giV;(mH6rB>~yeEg)TMBjzhTP9$!3wP(rFzPeq79!+p5R?Sz7&l*_0#LhhAShRqNY zFb9`CG(WE{pCFG8jx;&fqHM7XsQ*)R3 z1G&^zf8{9hlf8{EZg=}{dlR(9L~S65Lu!FL-LAlE>8}w_B>mz>Mm~Q>o@?R9F6!?oVJ!clA{2*;CNUj&9VNp#f3)2C(Y#0VOni<>Dt=Nxk|`s(l&ZJftA+ z(}I5)F5zK5C&gMT_((7+%5#gir&B6T&^L#3^DkH0Y^N<3f~=z7J+m{A^`RbJ;{4a=C@VlMc^cYI}u1AoPwpb87IqO^N|NnQm8`%0?5MJBu1ufN1PZ55}DJW1NQ+wTP~ zY!($ZUpv|vsxANc$wF{9S{s{|Vu!aUohuDsh*l}>4Besz22jGD;T2;-{Y6`dSEx75 zY9~htYMcP4e3RcVU0P3{uu@WjVhC2~ugnBhQO?@1JA@4L{BBWW{Z_bmiY)Pk3~}%$ zIz&WvephGKmmbyvMPg#z$by09I~<`Ii_JJm@Af*i>!B}~t+i9Xq!L*n<3=M#{P;RK zGX>4WaPKKZDVW?`w@i~hYtkv(1L6j^n}wB$aUK@#oETnxpqPzj+Bhc1nQAH=*uodx z;LO7f)tB0Ax-sE!y8zvUM!gXY_tQe@s{$XzByh29Z-Y& zZpRR?rDW%h?6GRc-|}+1@-yk~Te%5g7aAqo1~}fX0afE!?t4$t+jOe5lMhwv+}^nB zt^q+S5$i@eURQ)DV1t%V+J(HL4$rHw51bxWz>8mfQt$??IG|NfZ;66sROxV^Nl0DKic z@GdsWb*t)AK^cVzp$Bm!HSm42>D7~XUEc+TAZUkOx%fYWpaFZaYD46JN=k~$?Nb)x z|I6_naO8KTbGT;bL7g3r>VR;(2CKl3s89aBA>)UtqPZAF@z zg9bG3{STc{lICGLm4Pemj3>aj zT1Zs;5z0$dG1_A-J_c&QOXOrYy0BHpJLfj{2XnkZBYXFjBiq^jxL#-&x%NfM~6n7lc!gTmQp6 zF*{|d!V1ia0U9YnYQ1wwb4W=fPG0?=>|iTGYLL-p8?=FW4fU3sMZ({dopPpz6}o>l zsXHRh__EDTjmU>vus0{%q;$#ZXhD6M&<^VCiF4>M{@N^?#}l&%Q3PH2rHeH>LCYM@fAlr86pY<<7q zI?C0B=W@{626n%xE7SIJ>Rt;C9(bw5Rz)Dh)-`G)7z>}E7I(bs~GN;Y0 zI8KZ3J}fh#m>{OtBco~U5SEzrS>6qAg5W;$ip5#p%?(z?V^uI7GP4mc*ft3E?Ktz2 zN(!U{*Vxp}x$?gJC`}D$Pl^ODZ&_Zlpa;hwDkq_C2|19ZCGL(;tDOL^WuD3(JP&VLhZSzT0O0_N~h7okpetRqAqu_(-bi zGL>nTN-!!(%7^V-SFcRTTR6AhE+VVaRyTeI123ag_{B$s)j zkpAOT2Y#4C53xf(GsPepI&ePR_4D>FOR~MLR-bv}$&qh?7DH>|v2Mwh7j6Yl2Up8q z(u$WT@!1E-EX1IQo2xAi5hS(%EdPq?Zr5JLo zb^RTvd8mYvP}U+?O)9gOq;sdg+cS2htmyIVw=cJL-v7JmWxP_>*$H4M-1R!t>oY#l zYwJy=0Olkr`7K;9&t^&{RY+O^IB{p)#2ZR)SS^ydZd` zXJ7Tz8D2-N+YV2T($0B^D&eS!doZvdLoF7ne(p}R-J`x<(SFH?gF)J@?Jdsij=j(O zkWbUh0glx9*EoeT(3zmCePIYCRzVZRV53yU_RKZcmx*W4O*~=ziF%l&0_*1fHk#Q5 z9;%ub!XD@7TBM21@F;;!{UIo5<%Vl}N0&a-D6EW#HAYuk7gZF{GP}+l*W6wvGZTUt zM-7~gx1m}gH4^1`it3hVM)R1mmIa}S}}M4hVi_o&z=wKpu~}>>2O>#9UKmem|w+9-&Y* zJ^I)?3QDEGbCtk@xt3zexM3@n4f?h%=;5pnrHqV&-z@P8>}Nkl-zCeThkk5eKD{&2 zK(AyZf=_}rPMi{#Cc+V3#ZFmCwV?bBwr?CV5CF}2OudA=SA6YKT%hn^QbF!!7dLf4 z_trOOiS)`S^G~1ApSsYKAF+ff!+3P6qeGawW6l3tuNC}g=+73YJO-9UWLy`XNp;Nq zHb`586Vs}|t+QQNXp=sz-EWhyQKWO;&gO>33CY^^-v8^S@jcX4xOeg%Pc1GtJ16#X zViF7~>v|UW)J`GB&}tWUlgRRd=i%WhoIQA+S7O-3%~RU4?hSdvFu18v!uw-!_G@W% z3_$<=v3zAa zG1}|H-lN<8K0AMeanNZH-Eliw`^DGs@&0nP+e@J5cRxCR^n4Kh&2+Vl;E$vKb=E7f z{j#__;y$|jx#+>p|L)`R+-NVZ^1SX|#P)XiZXcHB|8=dT;{Ubzw|w@SvFF34DL?Pq zOtdiX+x6on-HHF(inVXH_dV}NT1Num`^f%avQ~WebJCq;|9kSeDE0fTY#!+QZTN4J z|EHDDv%fgO+Xcr#=WeX}UhgQ$+jVaoLoa^9#4bOM@3Vbg9K$#B+uUvs?yo(2gE+|t z``w?n=6bu@9Z`91B@pj?k5Z5jc`@$FH~6q!iec!%VtX8JEwcPJ{wQD=^}hKT0{pML zd!$TXF8w)%Ufjp?pNH}Na*_oY__1u58N@=rO#1)lj&`pG1~Cj0K#xbgqt~%Y50$q- zy>C7~&$a#pdSAW|+qFIT%^%AigI}MM^V_uoc!0TD0UY1ci&+Ue|If7fLmxi<{@Py5 z-uLTy`PV!J2?YQ9=lQ|i=-bz|@(NeDM3KS7P_`Y7%MK zkHb7_HwOBp(_Vb+X50NBe01}*li+74zZQF==>@)5Po26X{?-(p!*Car;|Iw!hDKhmeQ_uPDP^?uwvA#WV|Vwh5of$*9LX zC#rat0f5E2O*c z{3#hP@wHwK+5Yl)ofNZ%=@##08i2r_G|TC2VEZuqM8OF!BtF*EI_+NxC4Ut(N4OJs zlJT$mu?Wf1|L}QLS!dA`uNc9mHA0MJtGV@+5+mM_JV&E12Y2f56tQSzlhWLfUx5)@KbCEwsc&n> z^i+@`T~OFsn(Eg_0V-`{QO#k~xMe+YwT%nik4RqzII3@(OY|ND_E)QHTp=&u_cBW+WlGQW-Te<*}pa=FS{e`VzSp^ zxDax29vSq6XSe^UMCF=_z%MN%vP9WLGuNnI>(=Sz-uQ7OQ5Ex*QdM)=;OuDxzPi8< z8nbbbFA>K)HFPw26y;4`Gp6l6$Y15nOYZtChL$(wFY+&i5er^$x6g$!*lIalhUd1 zF|R$6JcXE}yUR`}A~0#R^wPF1239 zZ~Z<|j3~w1wz<8)NvqkIm!kwqJT|cfx@DyFf8<6fPewJ}AzOD_Ks`;HwekMwaY52o z`LJ%Ni`B5Q^O(?@QEDKe5S1vzI^vM1v!U1KEcNJY`DAH7b?|a{7(x^P{^`jfW11c! zVwwi^{j=T2<%9A<@nBe3YNddDXUeu8xgkOp5OOrdnKS8N6{Q&?LhVZlm@aJFCr#tp zkQ3bXe-T2SfjaH&$=>$qBs`x*cjft7%ZuQJxO!)^JwBm%P2y1=#a`Jpv%8*ve#;xx z+?7%Fp3{}fzLSlR`>pRscZUAJ%W&V+(W7L9^E#FJx6L{cjvvZE#;)Fz$i>bF2bP)! zeF1x4qxcF#Utd;7E>!#{(amA(W?_27lXS?7o@+O)NK!bnyW@G@$P*cZVF@A z7uxcdCQWg+*%!8F=+EX{oi4Df=H*PlcTc(J4Q<7Q6-Mx4Jv5VCAz}5pQRdL1d0UQV z2&KkTSYfIt_IznhS&@zuEsZ-9iV+?_qO(}T13~q74P%Dv%F0)+=9#LrQCK?5PJ9nz zYfmjOK;f4}-tn)&-jgwfeN*hw7Ci2pzt2OSCzP&2-w{BM`mG1~oCMiO4gi@q6n{mT z1QrC#4aGzd)KZRyWS`beFbR_l^9!kisb~wW)Y{^&p(;(1=*0Roz>URvGohC0$VzmZ zj}Q8-;8+CHThsl={7Tq`HEi2vQ^Xwoc@*KB`o}G1%HXt6rQ4PB{S(fU`p7j^-B?RX^js~8&oOUD#%i1 zIQ%Kp7dJF#TG}x}v!` zfmg%E6SCSwu;5+yGX(x9>erjhICUL*k+L`V1?IqYEF}W<@MC3ehL8Nx+ab&Q`A%$P z-18eOdkxeRoYHp0)GmIdX!^6E7IqDcnRk%w6QSTVd*n=!ZFJW&qz_-0uRH*v>$TiC zyiq!%O!)LkFYlH2*PkK+#8qnyoa$QD=N0{K@7=+%pA zIAHHambY_iMJ_2c@SCho2p(E0;7oOyN%)io1`Q4)yR|c~r?)3w-E6nl*p>4vff>!u z9yMQS{sOpFePAL=*Z2WaYj7=PPW>u2-k0;_d6 zRnJC)f*x5fjlIi5+ZC|I%!X5=t1C?u*~*Bcf61T(!H~%`m}R}pVO1&Maca!mk+i&K zAitx!st*EbGR(N0L2BV+q|vhqikD8u*jR`H=^{l|L@|%gh{ZUv$Q9`{=6>?1xCma8 z%sk5~a-?qm&hwNE!-0Jn5l>CIMIrjBEz-czv9gJ{W~#zHGT1C=G0;4P$~61JE=ha3 zUqOOlb12}8Er5*!+J(eI`ye9H`U-M{o>*2{3tmD z?^+P&Jp)Q&^j(hj)Y}joBDn6N^3x29pq;)5{*YFcdabC;=%I5mp-|qn=$;*{yGQJj~<57eLP^uE*&vUo)j0Hm>*Tmlyy)v4Tqb9 zS9-C?HLCo9JE24Sq?HfrMYz{&qR<>{$Z1@@bnV@)oS837{^U8LNyRd{n$qYCZ$jC@ zjjb)NApFW)5{)j5&^m?dCJXCm=PscSLY7z)uP4T)w%7_GCF6uUV9TT|sO!P&Nn{Qo zs8vH@erj;0Hr{ulvJJiWw&{CLc)hLj0SC#H;l9CSM8Dt~E>{zpkIImNH@p`Yly*p% z&-7NWmcSL)WT}??N=1-6f-NW8)GFz$M^mkitZv@2bu%s9oO-YGjk;B-e4MJy1{oy5j^? zb`Pw$yn4s|Aq${ zxDYAy@Xs3NMZ3>jusXm>D1(2;D20SIQi5VS9h2vFB~?)<@FE@PL@4g&v^!v-GJ)J# zVx-;>THI3L+3=spiVU8{>)GxJ+lwn<-dmoz?RHlw4oW{EOr5s0qIc&CX1NCsR`OAG z9)htBKddC{MLI2$_9^~ubcx&tJ6e8HvP*snP2m?_BJBnu?hVTP2YW9UNH|XO%v{$c zu`voJDyX+F#|VrXW_wnM(a~|2ulra=tVJl0*yPK!Zb z%^hxNoXX#u>n$>B$bSf=om8NSR#svGj1WShkR1z@O5UL`S8+`$IbrkM|YX%^4>(V@NypYinI{r<+;6+ zuES_B_m8~z1TOY%c5?bc2K&0MJhl-SZw0&LYn73&6a0I#iRgIuoV+0ga`RrcVL{GY zWBFSBT@(d%AI_xgc$SebIjoA0j2CO>*uAJG0Y=#ViNF&{9dhFsy}+_e3n0F!4g7n* zr$2R@WeH;sgs#~`V>f?%JxU+Lrp&<$Y5yU5ZDIPzQXtQa6J-(hgLB%K`}mhi-N9sE zZPa8IM#3@Gp&uz&%6*f2NG4qhJvJ8rr$77+%zly}6*{IDZ+2(;D9W<+a+`zxR4~_c zAxkWBM~p73-OMXD%WP8lo0HNXlzDbh^dnTV6b;q;1CYm$*F0a*e?+XSz(DmlVXRF* zYk9|^=rnmX5RE+isIuv1L*grBcmY+Vc0gt9#yHhKI%bMinmlO!8O5+MCDQcO+iVAf zIanw!Ora3c$d%KQy(gCb$$Ifj^fuQrpQG8UX(f|Ha>D5po9jFU`aA7hjNx=Tu7+Lk z-zy!WiC4mmosa{L8}u1n?XeccCVZ^B9uA~Gg;R546BxKv0!7pQ{%Pzt7pi>8PxvUA&0_W`p=G|@Oen7tG!flT~*VTL8AD?BR zr5R);ug2{iPBZY@OqRsX2Is|%|H<}QcyqB|l-6KpvRz#=pj6=Tert9_I?8=dGs-5R z6=Tn03gZZOZM=2EULZtcKB^OIS>R+a6Cuz;EvlyxvaaG0tp_J-Lllbyy*Yt#N6dP786hjX&q9seMkkx^jTNJp6n_?D=_B%liZ+(fLy*XN2 zXHUf-_74uKYyAMH_9da>CPdzaY$f0FbvMU5BnJg$kH#mlbmb<&b#$d(_RR7dAPlhA zesFnwhuyefhInOY@x=8a#wYgyY2QsTrkQukG8w5?{Pob zTU`+=c8}-N%a(nNkk_!ArR+&Y2Ce0r$434E99VzT=A9yWKE&q=ENzo&eJ3S-XX(@N z@!tI%)q4uhn!ImJB7lseRj*kl9OGmGRsM9N#dQBE*FlcmvK%g?ey8JO!cSU6^`j@_ zJ%i&>iSium84F-ArA;s9>gv!d=-?y;Pj4+e#F}*E5^0TikQp|G-SOrbPhPJhBCtFy zIuO=)GxP@A@Sj;4cC@@1omks1Q`DZeKEEI7t6xfI9JNdVs~+eGl3TNch+RHzD^j+$_y4Ty zH%3lmA3B;oUdg!Lx{684q8RlqlCvc@-L3qFAUA&7Kibnu1h=OPtj&vrULr{yrN49c zWb^RA<9Bd(f;aL5oX2vWAeEP@SMnZ@_WwkhzuY~UGh!sxKYjhug!MgXSXp$gI(Rs@ z(XM$9bZy;~{v9x@J2Q|agyM5M^qsin&i6t4DIKd+c`f-y9id{zn45JGztPvmkD#+TPLmk9mKMk>RKO+I73?MV*i3C5hA<@g&zavh(z_@Aw zIgV=IT`(=_X1m6N|I&5YCtD-VZf>wL6HznFVM4_(R+(XPdO!}khpIuCH^A9ynHSBH zPc7UQwmuu?HsK16&tJ(q1sgoNhLy~L4bhDb8Nsn37d%0tVbT0Gq)|0#WLkBv;&9w{B9%N8aq3Nu`nYHQK%L`y%K7(UDat@ zMNlwX@3bda*Be`aob5y86yPu_E23Yu*4cl!Azo!abyBB8*d;NI3QqR7p6GockD^2#Ej$r*ZR5QIhQ1h z`+v^;w^igl>-U_?$Mj}1(1x^P|7Tu6*7b=(+uhgDBlkg!Ql4M6w=5@Cyz?XXYTwEQ z!#_Vf`;b=(A;ZEszZ0&1*X5?|Rk!Sb=kvN~uo!UryuAq;lJ!s$i4R8?#|hry*~r_b z#aB1pQTLQA3c6N;g3g-aY92^~6pF?L1A|=)!wa<4=at(Kjn4|@2D#(a+em)HZUc`F zw(J`(cg*jh6liGM)2TW`nFC<1rzEvA&??rt?U~PIMstu=t}t9fuLw#pOXw+)=<&uq ztmz z2vaDY)BFJM-10$C9ymu8DS;y=L?Rh48xqui`UkbZXkRp*xH^y$7+>(qe93cW z!zv9@M*dEbyyKrG=>|Q_AF4r!R&};IP{yw6_M_jeiejrH)-nMj5$%dKkoC03O{wI1 zfm}lqs@U(&oRQm%vB+S(r)nrQ0)fk+Q-6R3R$bLPJZp<2QA!U`d65@nIHO z2^T-up$|Bmbq7mCgh&{2o^^qYV4WXFCp*d8au;4-M?<#nt=z;s@0ob(NlJCEnpVGp zY)?iVj!z&xBYEY;EY0`IpvON}Pb8`)KdcmBNL%60!&Ai&VmtUZ5!^CF3=hG8sKn5t zxllx|=tCd0mcnf(D8e@Jf41|AIfCH|2v7fNNTw92kw36dPi#&eMS?xVVj3x~0?$$< zHVezqZHFK;oi}goh~qRS4AK0LB5-k4RG}&KmJ1%uC+2Vh-f;!MX&l&w%Gyba8LJo& zFrEJ(o~DT%H@(UUd?&w9S@Fb!WyO`C%tG=!MyB{!LQ}PN85GfRlZ||ebAXKKY}>NM z2?UH;B25qBARL7?O~iSe#Bww~L6#Mg*pt}L?kP+`jdReS(!`wZF{=l%;mXzBI*y{{ zQ65E%gUHZed_--)rxlfT7T}fa7|T3EWSY%3 zIJNH+!#qEabwo_JZPW4q(bnFR<9emA+PFf5Wh^6E+letdL%&!taEn-PKA*B$AoK36 zEEo}Q6wqi0|7&GY#AiT#xCgQkk&Uw`jDi2q!{tbemYWpoDoc?6N|QR(hH^t|xgmDP z=hf|DB}&f|i0-ge2)_>;wJF@KVESvFe#WvZC%1YvOi3L5L8g^RCID8gd@ZB8LzCMd zx>*&Y86!g|6=j5T&lXHw3kMZLnr<^Mc>V`Rs}!#iuuQ#BUp^i*iVSxMhQMy8#%AhY zP^h^M20wBPdQ8ntYogr4L!Q~XTZT&D4}@DJebpZ#+6VRZ{nS&%k!YfIT?==rftK@5 zEPxee^a2>TSsaEEtzq#Uo|aQy*b08V{whqpI!`feEdNPjaK)QIvu#dM%_Vl z$8j?Lab-y=2gm(DF>|@USnnV_G@6(EWnP7Tec}aehP&cVFX+L!aKaFh)Ec_lN}T9) zXgNTo`6!h)@i1z#D;e3a=iW(7ue>9_VXmKV!V6R{wLA81C~}xCCJn}GUGb7_BLo>eaSs`Szydod>Vx3mT=`D?^K@=1lF1=v2k7RWnumn z=sQW=+w06WQ5{B;k|PKth9fkIXM_-|uxW<%^*`nsv?y8!u7_xy*_h>qpYq6Bnmz^=u#GjbfDhRl);fs}1E}?@0@tNF!{6Y;-Gb(a1t^r8 zn9oF_r5M8_N>`#L3*l=A`)L_+?#8+RZBe)Zbsk3T8Q{Ow217#OS;l}&p#|*dH_aQqdm`&v-xg!2fb&{v+}l9O#Bw^KC07eo$}FRlhs`d0B)}v(rm2 zx&G+?*W67 zP}M#(gS_$WJ^NIo48ikj;~(Q046LQ>1996#wiCK^13EmU{KH1r_+^Cl8bU2t@s->lsZl^h6ZtIQgHd^FC-QzqD|cbt2eBgmAXQcitjuyi(MCPeRsFzt#dRrX+%&tZ+?M{0ek#!|KCdMn5;y z0~#TrWu4OuOm#|Z9QucinHw-!2|EqM2D${N$Raom^tt_O&R_pAXZ-ed8}QgF!hY(I z#-$U{NKY3>ONCaTXH}&%U?jJb{3AMWGoVMs^~~1>o=u2w5@$(gjJF>j-Z?exHs7JN z@ys>Z?K;S#!qGKo-?}~Lpc@>#7YGpdvPXb=_`INasYk1GTw01SN)wx~b|@g;S*{$| zkEk}D-5y?kuq`7+4PRX9k$RbMh7vP#<7B~aNQ@094J^z)n1H|`%$+e(QOgpZ^@mFB zD8NB*MYcf=+c(~VPPki^|GvmyD?)Az3O}8=jp!>!7aybG3Zr`o?(x&Fk1Ja?8bqR+ZSCMn}HeJ7me13 zKrL5h+%it_BG3W`u9I6h%KC~6ZEUVZMw>`{wb_qu$!tXoB6whxhkSIM?@j4vpS>~> ze#tyntsaJQLVVHp&&-HFvY@|?OYDBw+faWGF7@DS@1=+L>E1VaRnJ)bw#Rs|0^Xj6 z2OMZ;Somgib%?CB=B1hwu*}W(To2N$b9#x_mB6vrixC124+iv=$QlO z2;u*wT6&P!pjRl0DN9JvhV4SwCnN%%_IKN4zO5run6_vDuXZJ3f|BlUdyM@wY<11H zbLNSfXnVK27suUJRz@CR&4!2ly`kd88LT%?R>v&hQvAwM!bXucuWDJ1n`DG$a;<$q zc~PaH?KZ$B&{;C3pM0by)ptEWU|wNua==!ComZV)d#dTNkxbo z$1@tty8vcvqphNjyUPIRV+ey8p2``x_7X4f{CtLnc74i}C23lgo#nq33)Uo_hyFdh zlSG#`t9~nf`n)S=51#|*{zlCF1hW_M1Lx#Q4~W5g`7$DrDKf7j)VMk_G3TS=iYe~O z=!FfgY1Mi~GBykKm>}RgMQUj*pQ}*cBTLCLK7chG$LYeJpEza;Z|$uD)#PU@kKOv5 zs0a!}rCPHur@B@8?=e^~{JUDQkZQFm;UXvu%q1P!SF&&uCd;~_S=?AYP(`lIy|pxv z>_vnHd{%OKkyT10p4!H9&f^&!_|Cp1nn<0G{G>Ds&fo1?@GfO@dlKMo&x&33@6ioPDUIpjd??VJ7R znSweR_e7y52I&xmI=6L&ZIdrq=<;~Z3*g8ibYay&ri4Gw&JILLb~G1_grAsO!3Vp; z7$65T_}2yfet`=a>mp{3Uh_bf&*AgS#H$TqC$?;%-B2`qy@EU)#Mz8Nzt08i_-O}F z{_t|=si^|=#3%MK^+JYsY)PKatXqPN{sq?-42DuM>)B!-er ziWw7L?;o`XP0Ej)1AMJse?Dx6Y#ZlGHr*ozshh}t)&0z9O|ht6emcPfkloh4Q7LY0 z_riy}PQ6Q8e8dqD0lwF$x8M(Gfbpi)82taVb(TSKZOh-rU4lD<1PLy|-GggzcMtBa z3GN!)-Q6L$3_iHKyUWWt_uPM-dh32zPxV^0Kg^!Jr)G8c>R)ew5RBlBz@_0~n}V|| zQ7IHf#-^=O0_B%HDnzNvW~as6)G{{u@y4V|dB@V>@02w5=BTereK+L24R*?|B(fpi zX+s9K725aTZycY#L^P~q5f_So<{?6^6rlqt+xlF(@zDZ1F8yo@v0lQ_5iweZ(CaBR ziUYULh z+1}B45@iI5WVLe{&OHskqZY@L&q=%^0kOS^mq- zxf9BO2>^4U_}RBGRnyV=?r4B~zzm1C) z#S6#%??L97$fDYajE zTn7p0N0Ty|b@i#&r*8%M4&$vMF$vItDuEBST-5oiDwl+?HY$@3E-g{@S(*0SSQu~J zVYmoJ2$Y)Yngf2tBB#9iIzUdQ-+~vvWMMkr;VsfoHwSK!DN(;Fb1}BQrIbF8S03?5 ze0qbr-|VnE5Gcs`1AYvIOf_=b#&;=kBP}*1o7D&&=2$o(E*%il&CV~6uU4UCjxNG$ z9+bRquS>iXQ24!F0A>mFUPF{UF)EOAioH)Otbi<|mzvKt{$DWbZrBIkHbPxdmM=Xg zhmIaE)fIaDP9_A>;-2WU8FYX-v6I=;UayOd82o`i-&mefxwH?s~e2h|#uB@&DqAXptVqM4pnCOi-x@XqXyszNEIRRCvB2gL! z=y&tpA2zB=F8lFcR&v^oTWJ{g`=5NI{fXupRpZgi(?IIeK#(rU7JSK?K!1W zW(D0C`ozKAriFAGLN9oJ_v_r6KGnq?Q&F_N$E6mUSO z#ze+oil09ICNK$292Cf0n`U8#02XFmpXgdxQNGeYBSHoUZnz5Lmdmu$mBmjls+L=h z=*U+Z2%+f?m;{9_v(~9j;8>cMCw8$~?aG)|*QnxK?N&`_a;ZvJ*lTFw)&~n|{r|WD z44I_Pb!#~)WioofD#m6YYr0I5v>Qc8qjDZM}9$?NjhcIIZP#bc*!JtOI@_&!1o#H!K7wG<(;atG9MHmxY*_uX^R;J^7|gvN3UH zOI@n_530^Q=4((P)fYo8xL9;^b*;X(Dk3{P8J{Daz3ni?T0G6wPj45ws^B@O-wqDe zu4olHm^?m2nV_4iw`vEQ|qpgj~@HBJ!(BphqRbm3KARW)e?{OE{ zaMawA>0&KmC>pn%R(Zd0OPzS~BP9FPq1@37MyVakRiX07edMXvaa;SU59>eO{ z^yH5EN8GncWwStYzS@ztQG;8M{T_r8Gg4Z|vb`2BN~TzI&C00#GZVe0iS2RBzfWEA zv==u?~@k?dUA|5xPc-bGmX8uzQ|fHc9Ng zv#kvs+5RZL?ZS)y&_=tHYHzW7*mAM%LcZ?wS_!~?_6eoXAh>&P4zIIVIbZNO=)~k< z>=5Si)N&*&Gl(SGXUy>gdy#0#!b|hs+iiA^fgyu=&kY|-M^P8;L;I^0Ub{nF@`AL? zxw4!@1J5|!Fxyu$%2p%z&Zs^C-lvLm-n=CWUV~%In1rZOqp4nBbm+4UuM6Oza|GoU z!-8cG)HmkeZa5v2a}_t&q_iEigJpU)>YbrKCYw3(B}YXx8P4{{jzA~*HCYS3dd?dp zv8_H&EdD!hbrZCVE$EsBN(l)89;2nyY-~H!bjckHPtJ4GlGA(6w>Zi_Vvdj7*6oue zXFXDaY*f#NPu7#-0ICJYp5v2{0eZS1A_gT{3#*zwuTL2tp%PQvdPlFflz`TH?Q++# zaEe>JwkHQkJ_KQ1ni3#Mj8RCzdxzu$u-ADd?{+>rnl+Sgxz@em^_f z;gl zBB%K{gx1UAO_BGhiw~XX=2v;#yu)jMHF4cnROJwn0xD@~xmQ#FyT3H1blgLay zjyK4i-1lhyl;-{H4I*S=hBZ@e;!`=wHr*%^Z%)zKVqpp1-{>)#&MZ9oq`iF>$5ph; z&6FyQoFEdhYxNLm=)TN|QTi>UBn*wJpnjMIfixwE!?*-RHK>Uekx(Mf>XuHDnpt>A zgC0$?Dy|E7y6=65L-5v8jAfl2dm-+-W0!Zsxx)P z<60a#9%{4ISIlom0Tg@&HL5=i9Z~WUQbbI=Ed^K!AA3wkHA89VNPTw~eIsR5$bPn&{Hs_`Hj>BDN;55b&YbhDSNRgLOf zzfD74VO>At4#`iD+Gl1OlnGB@sjxFd&xJ;P^w7}OEe3NagDKN_Yd%MQ;RlZsaP%zc zFp;W+GHAfO5+96N93-tqhwra-IIvMmm!oGfbip zz3z7%ub=}(pc6gofH+S8Gon=w5n7l@f}}`P=vidn>!4(ooTfE%d_Bq>B4a?p$k5N= zP?BmX_`A3Z1uKY~GK45tSU!{{fEMEUFx1@Av4#nF^rDel?r1P~A$k^*Q6ueM;OT@6q_7I1k}sd6zXWJOI)HcRcj}&aJS^H+kMeu=Yv)OT^%p?G|ZhYQ%q&` zI6FS^uSM`5g+)9#j&6-;7-#mdTm*wZ>K9wiipK3v#zL85bi#Ft6K7~r5Txl?>7*N{ z?8vP@g7i3bm5wmIDk%vH262fa9wf*Nqsh=AGxFV5h7nOn4!vFa44cWACzLjk&gDoN zK<0CHZS22-Vco6el!n_J*U6oj$ybK^9iFY2$o3<8H+|#o%ux7mHtrxQF$-jI*K41< zDMYn%J)H1ChnaT+ggc@C5e++qq~CwycdfaX>a2S3fBjmaf9I5CfIUywdwM%KU(2N> z^`Kc~6>|7%#YhjFiE~Rtv$TcgL!%So6PZm2x^gX&Dp8veK)^nsZC^=!(p31_mx}F| z&9zO_Ln+IGGcS`7*;oIvu`gzUu8DSr=zR8x!zcM$1s>Fr(l7XO{(@*8Q`#%t#;0+X zYY(WaZh{S-!AA!Wr!{a^Hq-037n(i0jhTjGLWN`>;+z{2cXGXMrVQCckY6i$88;OB zSZ~JmMRyEL3ZzdiG-W08SlfYu@-JwN_NW9b^=x|M2U0wV$&*YGa)QDr!~vV&x=FtHg?@B3F1$0*FDywiF(kW3*c9r9gVgo@A7;guCiQCh00BODH#)0JBkm8Z;P;DA; zeUcR?Qx`Eye!JQqLwH_`nbtI}^)|PeY=Tnu@ac%*0Ez@(KY6&&lyoVd`l}#DGKJWU z20>|Xx#~YiWg(C^^GCve1;YM`i21rg-ejp^7#*J7JuQG{APvgl=pVGZZJ-KA` zjw({Sbo9I8E@;W)CYy!0WyY-Vce(hK+nuAT#`964XI9<^$mK=w4m+*-nf&2Ayc(HYon09FGo%?Oy1Rk4`u7UwC9Lp3QHHG`C zGR%1&c|S{`oqcrpo;%e0%%06Rta8Iiz78j0u+Se*dPVuJ9Nxk?JRXs!exX~~R7#$QKzK>8* zh6s+LR~d(x%ytph((sxb$lr2@M)@|}vK7>~Gqf^iqFCT2n|kAE1$vp{rkb$EBR zd7Q;8)w9Nwm5|fr)!x>!#yU-yQO)d7UU@C`(e~4-6xN|e$z7I|S4+d5MqdlEYNNus zvi(5?qfY9!)k$J|97PJqe&}Xrw#1$H(cDJ~61LH@yV;m~DEFw|r5v)@o=88@;0sKq zw>xcv?eWrS3m5D)DnVAaj(`Z?bYa6QEd@#+xmWP>sZ~@_aiJB838PF1cPz1ZxKJMg z2^xk$OMAfXG&iJ-!acG1_CZBi0OYtd)7o_rUNagO=Nhe%9lf1A&DbFV*NH4 zBZJPcn!j8MfLD}In3y!3K_lq=hy-5&M$c>NW}VtoZ#pb0i8P^^y6&k{^Ux6SbI#@T zat)b&-`u4V@q#N2p8CRl`sT@A67v;A8DSG3vj6nns~tUB3NqypXsI z(XLzNibXKq(ku<$?`tM!De(1`^;yc*jM0OH@NE@m_;5#hbi1tK08#GS;mW5t% zf(@oj^{+debGb!&nYUXaVQ~5o&hHVXZI4I79j!USt08}#T^usRsbD2yRe6Df$q2o# z%*^rG+nUy(=k=w3&dzc^vhjy^^$)x0UBVWpW+?!aHZZd&GI22R6V0(7fnkz^RrO~r zK9-q%OA{GR#X8dP2trwr)Nx~0vV{CZTM&GLnB_-WZl*$ubs*=ClPXQIgo!l%4N3;- zcMGZlpAp~a1za&}e7(9a?;v$?*HKLYeVaK_*g*Dw0AHTeZTS!WUNiMe1Gj`J#>+PK z!w<}5rgqtF!t9|oHfr;ma)I6uG?5XBy4rG&g3bbs>fIZxL}@0{@EnU4s@tE@v6T&! z7b)%Z`xBh_C8<=as{T=kgX0IURDdHLg+Mg@tDFNjh=!721KSS=Skh)%pw0t8;bNm4 ziZ%)0yq1&sBv&!jV$>^DfZPDHUulLki}|5K=%AWktS%RU8W;)jAP!|^rNjUON+Iz@ zqx^Q~9W(DjhdE=hX|o?rPZScsbu%nJ_@*lp6P-%7Itb;?fOk)bk^htuzaNpFVpSj- zLB~J?j4xaG(e@@Z z@i+Ad?&N~&JzTG z*?mZXX_<;376rl(h8&SZ42Qn7_j?#)3irkWLmir?iZr8vwAM5B_Rfg$UWrzv%AbR` za2DoQ$oK>nSumjTqdW@u)770??$+M>D`jEBptV#I?JmT7QAyueJYsSRaOH zig=L4|AsFn+TN;E?g@)_=lzm*CY8Ikikn86iWaJCFW>w=$A*(vo#x_j4X4{})95BQ zi%}U5VdNKZGoy~Oos4Z7r{7|n@#2Dve;)aW(FvQ<oRCvGYoZ&g-Av^k+rVr4e}w zK=dxEI5HE5A@5*s*v*Ps9{7yelDEenXIKKNwmZ}c*r|Asow3y=4;%&| zgFvobMziS$jq=rc>jjg~cyV!uwDu%0z2BSP9GbLweL6HWCc{s&WKfQG9MR(P!Kd|;sSY0(Hve$sAtcprZWVi!6~gcPuDKCJ>2XU^a% zEx(9$ZSU(j4zTAri6$THTilWJy_!G7O~citW>kK()V{59xXcRo^q4wK9|t}18;MU) zZRo|chSqDZ2uvUhoMjw>8&yKU%*YP-^$^QDSb=qowWKO5Y$HQ1gsE$Xs#iXre*t@~ zzJKHyGN1k=fjNsQakA?fPqp1Vd-1d}kCxHDLycjb@7mq>9}%IZ(n9m%@&9DN+?=Ew z2|&-Le7W{ruFI7s_rX~Rj<8hNN)WdY2eot!ILW%?PRjZ3`*W+9i0~eN2v(2<+uY7J z;3z2LUKy2ddI$b&_&*+Puxk-rP-Qh3Pjzq73GIpcD{+3W3DKljA^0d4Uli-H+>7U5 zx_4sW&4%Xn_{hSJ`Mc&6>we$0mVY+^)vaqUI6mC|fal>|6(N=)?isG8PzCUh8IAS1 z%HKcYCNL)l*jtPREpm{062h1B#oqgHIm!6FneZB+pSt24yhJ}}aIhQ)0w2Y0G) z>O>@-KK^3;gYCB%HVP8c^iQZy4)Z#*_}RTI!NE5$7uSL_8W7)Z*!G#Pff>GxVgp} zezE8MbQeAo3r{4Oj!jI{&IA}ZKHH)};#xd;OgY4%_2_+hPOTl_HLzCbn4seH5T>m~ zj-B%dVqG=iSXBh#t=HWCsqs34vsNV?9yqZbI}~-X104Rnv^+xy$GdFfTN#kx@=s;~28qUOC%JO@!_VMA3`dWaahzpj;8jcYkBrvo+?t`{^Tg2}hqe2OlKe5Voq}$9@Ja zxR44d=Z_vEV!WK-OwE?#hz>qm%~nB*m(pdy_KcE`Vlq6y7G!zBIg zz1)|s{RhYoqe=EL;}Ua+i!~r0HievD^^|as$Z(doFZvf(1}*uwku@Q|oTZwt!OjRI zBA>dJZ##jT5gWuAcgb83OIK0!=L@}^^e4-I)XUV4QN6L~Ok(pm`siRA!M=i%nzo z4?d|4aw+|)vC2M&HUiawP0)rJDk7UWxHE!yto&{j~oR$jZ-7U{S@=BL(9V?qXlDz zcnz31f?oJa8b$*q!Ty;b__jeM^hd!Z%aU@NseVsb0mOc)b5!sGbl_YFD4z4Z%w^n9 zka>hj@zOU7?=8(ZSNt;?#EXBMY5VK96L=lg!W#KgCKtZJd)wA6`g^K}ZyF>d0ah@A%p>=c`7{{i%+< z3_4X=J>Cee7!%!(%X%N2*z|UGCXfLWg|R`xJ|;owsGk;pfdu|_XN_L+g+jIN{Q?te z=+nu9^eMga@f~^JcPp{=tgnRpD@u<_!ay-xaxvcXp;kks&OBPE) zF9hC86?WYaR#qP`1@cAdUH^rhlY{lPDOyw2{8$?NlH7lwDOa{z|6jz?{CoSAA0}RE z{=WebEp^-Vl&$}HSwP%(b*cVlPcHV<5j{^x-#s=*!8$?Hb|3TXNRccru=A#k2D-*} z=gJ;(+K@Zy4UbhKSdjW+Q!MllbYGu&I7Afj^NN8b89}>H-@Hv!J+C|U`CI6Uo+f3x ziM7^1Om%<3 z_U@bEOWRWhm6YJPe9e{^Z$8bqc@5I}PAE7_`^_%!z- z!~*1nf$__RIKO@tKDJZ|V@8YXMx;2*mh7lrH~@!{Wue3F`}$=sb+^bg(@26kyDqk$ zLDP)eO#un`r)je)%{@f$SHNbE(YbJGd*H|~g$!(8Qvm1n%bnEqxx?>u$hjniue{8~ zd=Y4soPN>uljkYcu!3VqbuqnQMp7=!7Q8xmB%5T%1X0(hspdn8bEllXJQM3t*S>$Y zU#iRYxq(%G`&-?tZ%fxNlaGqM_(Jf`3{dm^J5B~cQOX|u?mlkd62NO|{M?-}gxeGM zH&!M|p9}Z50f5Cz?0<3CmegtWH~wDxkBjv8^S_k9_s##`cvF0dbuH5-agFO)_dM;K z-*CSKOAi1?;xxp5*7#Ygf5R-J7^29&5<+(wa^ixnK;@Gm z=g$)L@;bx(Dl?=gGn(d^V>+D6UxW)FVSU1%N49(Y(JUa6Kc zxO7AmXZjmMg+q^XU4~M2i(4+2&2XUWAF4M$p>tl^7#CFkRHQ)n+<|&aDB;_!c8F$W zkAiw80>CFbtL&KDy!7g8P{ioyetXJKbU-E{Kxak`rQ-l8pdKeo?AnGmVw((OQ5$IZjE4U93S6b=df#6*&9#TQ}UvaRLu{SYAxom`F=`$CL1Q6Tt=v9!TS`;prkZ7KK-*4NfN#$*My|CD@3)%mw{Q0{m zSy~Q7J$pvA4EUjYe1e-CYd?dX$91;Oenlv>pvfO4*s&P@s5PrW+fA@ke!&4|V zyUVa0#wi)b-Q4!jv$*^=FscYP##x=4Ru}@LjdsMe%SxufjRMX6)b+f!yY@F-J{Lqh z_vSP*9AFs>zC@6aU*M!zQq2MLFDN$@g|jSW6DMX34E@K6qLb_qQB{Oen9d!65_YET?}eb# z(6dS#zNPVf9*EilX`X+O4Xg$CfR2fD1G1K}s72&|)7?lFgQVzb*bv-^9UZZ}b0g~v zk|wCmQI4D};_U%~?Nop@eQ1LBX?08WHmNW@m)0^E8hv)duheuDO#B5ZtCf9VgSa7Z zdm#_feTEy2J4P& zaxNpL%l*QO$Qu|8EzbR;W`t63!38$(f@EOx;F3cWD!Jxikc3kCU=}^diNxyiMq1L~ zTE9i8Y3dpXp3lP5_kPH-I#n-51ey;2Qj&< zv#MeN*A=SLwztK;!* zC=gOdfNPq6UVj7QbLnbcY25OT1Qm0GQ?Gq! z;bm$Y5NX?5Vdm4^t9AH9mn#qQaNU*XZ<9)*Djzo2_P~&X!SQX-h>1eAx9GFAQ$u#q zzz~o&NQUuKXKp{+c7F z%Wdmb(uLRX+me2nty%-hY(EwkdDvazF}zT??@}MOSVd&U?#Asi{fE7C6*W<)d<#&>>KfURJw5ZhlwhkupBiBBkR zKe8u?mfJQ!b=*||3ceqRS&xeD_-l^~N3|Rnx?H@;phYcnaPIBs?FR~p*)T%qhdp*Q zSZ0M^Mo?ku;#U#+@`F$V@pvL2C#sg@@cvlUukV$_RCw1svYQP_5_>OMxoi$Z-T|Ca zF`U?=4(pAGBEK)IH~be-&L1oPmxdSzYcL{Wv?J!o*kX;idX%u`x{=b~)j2R?_!H?T zf?|{+46yQjvxQyRb%wKhdi4||Koz(Q+SqnuWij5pKZIGvGQN8?y>5_7qNF9r+m>1w zi3k3!M**e=u)tesH!zUG{3xg$W46{xPDIcgGVaZZwT2!E-05ce?Y#E5keE1aPZfSph?`MN z7D`1wo0@{mlv5aW02GTzoyNR28i-mHPO5l``DUD2)~QC>!IUIl~%;@sE# zl^6$+5#%pT3bG%w{~k>K2>J@M@#K7nUp&pa2Zbf-)sJp6Yn^C**l5 znms1NztEz}b8z^N-S)qyAgud%ylC>v_T%zL(!PCUc8l!N1?X*OZj}c(lv6`S-`E$R zQ0nL=-Oxl{gPGRJ;r?H(wO1v)^Afi{xFUU#@)oE%5J-iU^P_Btdk< z^UBT5{l?pYx4&PTN0o{0Sz3`=}kgM-gl#W&#gSP8ha1 zM^Ayz7{a*$(+gF9!UvQA=Cx0^(3;QFIQr-BjeK#N)l1PlE_e88OGsj?$v)YDh*I{G zaM15*E@AOySFnoMDSW&NG0ybBMZ&Q?eRkM7t`z#-MY7-jdac-4G|BV+i+_Fj9QiB4 zZ2!8hK|z*0kBB0VPc8e26VC=V1cgZy4Cj{$sr6 z$yk9Y$IN3Kv-|2u`%jyrve2{hox_}vaU4$Rti*H+T?yS802Qb7tnE9WV9@9(Yoc~^ z)kab!p6OSm`#4(lyXDY+_3U=Qgg8}HdR~woC1Zhs@Q4P*u`Hfv=hHR+<(daaJ7Iza zwa&(fYkQcc6P<3^Ys2q-9Lt{>26naDCuCx}-pGY}8n+$81`9}N5*rr%qLbZEYXeFN z4XwBv^(t{OiAN%qqqOazhM0sRFS5@uiDqfT#!)KHCf^+?F^v?JUv&z;R|kmF&@3Rp z0!4(l6pE#MmTH~^GaNZu=w>u@ z)b$hJRqnhP1dJZm?w@)_+o!3`F0fzW%SFWZk?V4}mSwp6R+!xoxlK?*Cr#5&*sN3B zp}LmZ%U$fCMhaA|tBaN4zIZ!qooU!%)eu7{wXWW>5aJgWRS+@9AMXbjZ=5Uf5Qi5_ zjiY%gqk5?By^`~QhC4XV7Z$?UgYTyoqnA4qTd_~hx-Y6dK>wlj352fpgx==so~kcj*@3Eb=h=-vy2>ZEqU>uiJY5A$Rvh$_ zg^Fo#rEs7tYL6nuG|J*ioxJbENNe67Y=pmflO1u>*{b?B)A+71`oZ2!B)w`JOGBWF z-!!&%=}RAkqMrKa1L>HJ+Fb3XZ;m57Tu49lfA0HXfWm;J!?l_ zHDKhUPwU@bAygQAmhSd^2>%7%G|mt1e5h$sK_~cZ5dD{$SPEN8onbjo!!Y{p3w*s0 zwx{7X;9dl~3@2)PuqyhlmQbtLdd;+Kap)dP|0LO^6)2aUzkTXH1NIx`ww||>a8NO; zF4n|nYMIPjHfEjU((q7>Sag$gWT3Buo;0RF)*aq?LuMrhFcx#I-chCK_gt?vMN7< z5&bmA#EKwxS)_xPF!30{h3uG)Whg8lPS|3?)wscAN-x13=N?Om8)y1w#jjz)*yU5Z zGWK`{nwu_LFW1X-tE|&T%}yuk^+#jHYHpciQ8C=4qxYS_;q*#Ny(SF3H#cEiUy(0z zQ+`MBesrqx09O`2P+Kl~BQ;bjI!W53hiwE&b{zT&hCV2#DWj!smjd^7yYWY|d}8+a zb6Dq{#@PXZtR|c>9=Y9;0Y!Nmm*!=k5nHd21ZcNg{yN@7;_-333E`a?0mEVF404u? zYb^_(HV1;;o#1T)0G8=omsV9k?m5dGB8pkA(YZhu=ZDno^9qxp|7~;N@)M8SqnIm_I^K{ zL`yo=$3yGDf*z&Lf~`wW=%$~I*&+PlPvjW+OKKhc>%P~1lm!qqc;UVB;2BHSN`Pst zGmSzGgnu0inn9ToNyciH2l6Y_=Wi1u^BlbM(k(Qt&iWaov;wJTd!n zr3?SONxwfu>3L!KxjJ!djIg68l8s=x$x5iUl@SkC;%1^r(D^k0}MWB+D5*G^6Z>Zi%BZ3rHxf+vJ9)rw`; z<0OHB;-H3WhlQyNqmHXV{iPrLgpo(zxwKXG4?G4QEaf3_t8^Fpsur570VA?wS*Aj1 z&=%PF8Zmzvi$+4?9tWgU#xJcn^OtY$Q#>pn}2A7yIK!S`SEoj_d$zotMW{ z^xs*GK97gjqorn>E?G5J{CZyRhu3S|=C7y|Dq+{x(8Mf>4|r=2sg~xiGkQv>6wS9Jr8LG(_A2IP_FUI# z>&h;^y0=(VJ(LITBAqc zE=Nx^Ue*aa7dWjOVq^~cL65o=VaOUbPR*XT@R#A6q_{$-;xWq*N7bT;F5VF*qjv$>A#Dv#PHG>?sK zYq0qbe6j)wnChz0_=c@wlUz}ukJzfha3WV~)h5f=Me($f#Wu(RK;!`Y{e zeczyIy2E}-V)jtEwYG3(n)s6&{a+@$x&6YE56HZ1SsO7)Of`cX4ZQGHACv4z2b`W&^G@JxAFKbT&(uO{ePiRFFh^6DzMWuLQHQGB%S+YN5OkE+<}wJc;RgQ6}PYa{bG8PeP@& zW|hy$SI#G$OyW|;xb^0Ck7nuryG`>&(`E`$<`7erj4_pP+*RlStq4_-S*oZH@!~Cp zH=j>lUSFZ*ZbzabuF@jf${0r~K{KX@QRR)shpydKn%}sP>gkT|W|1)S7njrEE^*tt z@Jp&^fBDPmg>g*tFq_;gm+FXjZ)TI%ZjrEdDNlaGjj8{?6c+Q}&tEwvRp*J>bXo@A zOcEY!9{9v3FS)Ru1!p{E($Y*K_aQkhA_W)&5mGA=bmpo4!t^y7 zUJ=l;d(~@J=5Rf{Jh^_EX6R5oooxrQFai_mlOoC)p0W|zYk}2>ET^o{0WO1#Nm0-W z=2>WG1Hq-uAciA4fM3g;^hhZNUTLgX<(Z*{61@phWX;P8F5LW=jrF!*0TL?{6R$kU zMtK#Im9(@!pWek%bHiLJ-|o8u=0 z=vdGI+|YdH`u6g&|7&S&U#0C0q)%e!Y+9Z-4incR=(bsK#tj%`h^bi)ugy zb|ekA#vVyEW@L!c;sDVM&c~xBnuVLaObgIQL6x8@3Ce(Q6{+$<>nbvzv(<_u>+Vb~ zF+kWQ2B-vRRgUL^*p}+72C1d#{AODjGi`&ce9#8MS9mL2B#wq%bkYKM1$b`Y*Rw>i9>6xsZqx4Tx&@28;m$sFK;1? zm(%&!SHEjiG=wmkr^W5f_6nC(nLsx^yvEUhRVC0oCJAzio=WTWUDzINL4OJksuK$V z`crgJ_(&v??i3HL5;V$}(_d$4p4=?F0`rGg$1*=15yrKkM>0PiC&DPclOQlXu)Cm4 zJ`qwlas}_k_)J7JX;|fwvQ_fJL=}aBDRnwgFja^mkP6aPR*+v74SUb*PE9lY)^L3V zdm2X2>`p>~j<|v4VveQ@^igjs8&5_kY)x9@DS&=?>RKnP`VM@A{iL#))UNDh|X-a9a#LuB&VX7LULTwfl9C zpEv!`SCf~mTf6ij)!wjhSzNO98ina?@gout&GqYa3DGugot_;4p})I8%GMz2J80&F`rQL3E?B6xLxz}rX!#JZmCPJy>`(poOkmy_88gZ`em7->3s1L093uE zpFo6BV!Uv$K7tdR6Qy~i-X~a2(b|AtBDKm|p=@#UB&k9s)@K;^w)VAdeR9v(x1QTG z3p<{>x#>;r))TF}b2j~T3>#zB-i64Lhv=vY%sWRy@lkm%vvoWLpJa-ZIWHo_H}!xN z9$2Q70%HmDRuo^$y*0f>TwUMl#%4&EUN3NCTtg9lZ}6gOU;KYJa3g?Q7ALqZm(QQ# zw~RY6AnwF~xE}-JWPWq$-i(Vw9v}ar9@mR+Tc7#1CwQn!HC)b9x*l-va>)c+4ZL>J z7uEq^jIYw-)wF!h-7cnA=xiA0$qY@p5Yl{pKHS@+-XT<*-=yo<``r4s^~aju=G&jT zy@`7%VL2g0s&+!wV)8!8Z`1#|hx!H`pznwJ2D>y&eYKld38tBProQfkP$f^KzNYPA zBHQ+z_Nc5S)O(?#-9F|ae`lX^n)g3)+SpvbE!tSR4DU)E8{XC)b?kMwJ{Y|WJF}0c z7x2%myBsfDxR(F?u014j6bNok0rcsJeyvo@ynUJUNjEK`p;F{7hhaY z787^*;?sI&UVPdO34GzF(?$8aX!iAcL)O00nyd}-<>UU%czbK68BzCmbHLp5tHNP+3+?02lA@4N1nlQcb-9vfTyAB1)HmIiU*Nb)+ z=0z)^UUbg^3=<6OHg2G)n&T+u*j^u^sbi^Okm`2&fRch@#j~vp5v-VILTeG23;8_~ z*OGqPb$TGW8gz#Z(p8-Pdfl+|nv`Cw)t>_-MMqRBWBCU{Qi7InC2B(Dr4ATs%u*2* zgd~rgq>erH&?CC#nTb16-LOaGUa1a>h~o4^p*pThBZ&aWGCD|N3P#45)ccf@%P6vk zL9k&D%01GO8F9vl`A}#{MvZy&kyT)N1tni`pHq}Px@QDCF^KWLsIL5PM6@I2Jc-C@;y>ro?N?Yn2NolvX6r9hJ8JQbobeBHrMLbGEk2_K}P*)S(% z*}U=*KPl-*3F6d>1HYlVdm?yNUR!HnJ!UUcH!(pQa!HSfB$GsHwvH+Mb#e_39H-xI zCbKl(`I_1P8kTK#{MQQiZ_d(&J9l%Aq=~To@SiRxeUgt#7i7`Ga~qtqQ8E)X$9#F0 zXmr-|Hr1!rzG)LQC+cifADajj>fEr#4!4eq4Ga3>T zu%UfsHh7w-lhm@`xHeRbyeYTk7vXNIND=l|d{F@r*>p?JcFgQStIFZ2SRd+TlLQGesBe75u z6s>%;$??pMuARzPDNfu{Cc2xViPxO|`Pe0^hUt`2+~HBYSq-rL+L z650(RAm?nXw^};<1-RtILqBo&e1s*>nUKn7m(dsFSSS>4JR>>M{@irsVn~ylc9z@% zO3lrpNKju6%3!(M%R4ELdVh)JJBexHx^WVp_P#Wf>C2Tu!|D;y1 z@&i|K$GWTH3E(bNhFRDXIgrc(7T@zG?a-&(^;H`+hPQcOMTpoI#+9T*FJPw$FcmB;n&by`FR?P8RbE zQ&1V@NyW9!)>8q3ZA5zEf|8voyUTfMe!y_I8gZC?OLAqBFqMH4ni$P0c-BFx6#%xA zuc@(klok;wVaPyW7)LZQv7~t-+A77c;zHRRxuBLAUDm;i0G&fh)jEt4JLByRis{FQ3$9GwhXk*6cc2P$DiC} z4$B4RHV=J?(i!3&iR-SX*Y#30rr@e0znA*=?+>~7ku@J;ZA;I>EmkzbY)>#8 z*VDP;;f*Qk^YW=2ej-z*-%_}(S^s6aUePA$-Y5jUY`*!mP7t;V#W<&k8${~MRE{)u zb-6an$}TQ+zfG=gui6v5^{_x0@}Pb+$i4TULGC*Jwy2kUJ-W^aI;SDmI@ES5y)#Js z8}PcDoj^x`s(2e}YR<>|#yW2`JkYL7O;g?b%k}Cya4uFE^-gjcwL0hc6y@qssRZ|+ zo_Bm^t*C*f0Q>H$7DGiIxtD3YCjWXKK>b&4_NF;UeKncSmkPu(W^MK33LBd{C9PrS z!R8V&dbU`>$ogiQU6q`q`v_5uIB1uz1BO;F03&WM%Ru68;d&s#cZ0%<9`-C$9+6Nv zMLitSa-N0CaYE$`+VaOIR0a)`N2N|b3zeQw(cO%V_a#!g7EDVFttV_N;j()T)7kk+ zotwMOLUM6?{mb?A*ZTOtak8QDNsdo(C%&Vra*&uy0>ziJ-6N`F{lQh!>rjs6cA)D4 z(>TAI**%a9dX-_Mi@57!0tYzbG%~9}~ZYKagc>0=h z*72}!4Cy)b_DRD zi#aZ&R_7W&@p#VO3{abize*FYTG(GsL@&h3rwqtmcBEBuFWuy7yexHq?!DdN8a0GV zERLw8@xBsPippr`DwP?GYs!V8`3}i=K$1oE4qc_VNpf^jp7rLHJ!(z8_Tz}Dom@Aw zyqb>Y){T2}Id!oadGk}-)TgDX_RQ9|%QdSdUh`Nt7u7P=<9M0xY^me7Kd+K@HNWTC z^lDWkVdoJF=;@U<0uybWs5Dr?xtNIMWW%`&LQJz_xvUzxe(f$NvDI?jZPD{zr(UQ^ z?~yi2q#>sL_iJ&`-kt-mUe~0xlCmIOh~u~w6*CRtb~YO#3d2}8C+JO4J2n-d?Fi>p z@YBGtwob)~BPkeyZml&PpVz*9X%7kZ!f;N~={MiphdApcI;rEG*Y-6$?NMoakn_DG z=rbe^7mC;giM`quX8^`8+V;MxlPW$CC)is1FYmtu~V185BE< zol|%dF4H)?a?rufjf+E6xEmKY>F~Xx<52haq2ty71~IaEY1H;+REI>)(`CMRFTm+8 zFQ>m2+jud%O-}(Ht)Yz4)8SFZvZIz{IkXfiSPU^S8v|o%8y=hS{=4aYOra_6^-c)+ zeL1#XMAN6;#y@Rm|3R>Fa0WggtTZEPG&JRXSUJFe!&+sBC=y03K?zhS}j#Rv)BcZcDav4`%mN_=-kq z35i$%Cq67(wJ=R2^V^ZUb~p zUGkeSpQ`ARanTW(wf^8R(I`XA{oCd542uI)cm})t-obI8`|rmtzhB&ZFuVLb=x9ew zF|fkv@aRlvDo|P?QpLR!<>aAAI({s6`QQwEP*};Wq*A>fyZl+Ld;n)wM2DG zf1Iq3HjCEU=Ho8+_TV&NTD|aq(?nP$GA&ys!B)})r-`zHk|8)fkZg1VPPfVOeR?_v z`@REFcl3T(5nYyzXdq#q{yCUO^1S+IXG!YV$=|jEZy`^?Ia)}UjrTD3EdDAPJ|S#M z_Rs8tR4FN}4f9^-psb-V3Z)Z6IDJMmm7MZ4@~yke5YcdDH$;Cu!OR#ls0P9~_Fcgj#6> zlU(5cqTtk^Et!SVDJJidHd5(qW5$x|D4eoB1w%>_q?A&)S19geQZ3uj+J(w1ODZl2 zp_XNWZeE;TQs!7F7RqGMOos6%oTyaxBDlyvH1;Eb;^7&1Vo*Gsj`t80vyqUTv%Nu8 z>vLf9(dr1sXm)#j9#E!)B+ZDgl$0^*~;^KdTg2Zw9Iqf3$) zAv6``xS%pTFq(C8f}3)_!s%FYLn)dm;1L?A&deE_sHHK``-N+(b+oFa-;Jzz&2;4g zrjH9@c%(3+DLo9=Y@~!_rw45bPoQa0nIYjVhuTPkW6=^5KN_?ioPno?)`Kbg51}<5 zDG-~W2NmZA0-C&$DIQ^Dju9AmL#e(U|HD|1N7LamCVLOUh;`VWrEfuaw(`dJ>)_OFtp~5RE{%O!C-b$C6TSj9|=+q z&%hHy>ftgn2asBl5iKd8#c@cz2M`_vwpH|CZI&yhQ&De}D^12KFs?L<(k4Ct+cM!% z%}eqPXJe&QOjbj=%u)>au(t+1UJv@o1A3EgYQN?USkkaFDO6ZIKS_~c3&ZKfZ_sjZj;uoy=xpN*)r zz?VhQFdR7u=#rIM$`B2w19}K$sUSg|syAsA+QEFV$Uhc9ADn>?C%ywT!Z=q{-T|)H z?EWBdeJb*v!br!%b(?1H$@)rebDo4rq1<-g;R!%Bm&#EWRkGPhlZ*R9bLt&o*}y2E zG}XaFG6v}1LfFW3WKcpP4KT>u{W`R%55Z80SxV)MX2jxImUsoBVgVVvSi8qSwNcb| z!v2qiYE3=<(SnrycU5I=ykrTprTs?&)x$IJ0YNn%Ng|kfoc`*pWu`Kg(qf^+@MU0! z*1lqqB*P?yQOx$Ev!>RST?tlM=Trret6<6cq=P$%&K*cw*1CF9!6D04>ttYDr(d65 zPJq-g&6=ZbPeHHFC431+qnA>8m2eH^NgK{m*%4H8ZAu#A5 zozgLUEMPr210N7ri;*;hvBO}!I)1QZ_J_r7$`}9yYB9h!RuVc$WhHTy%}kVNFJ{?* z6GThPDxK=uJ|R`YFea_mnmRLp+xwC3X#;p#+}@OQ(4!`g=+nS!lY$F5D2D!V9~1XH zYeh1X68+_pDDGmg-Z*BV&5B5r_Ld~=lgCf)z8%}D-b#T=Pb>5V`bD6s3JQd$EhS1E zt|SFs)W$#wIUTRPsA*hPCOJ?Lb0swxtcvil#90r|zz2laa%81sf;~#*I)(t7#`-E5 zok|`cQ5mKLmP1RIjE}+%xIVP!kh$nm1zDScKZZ!*lO;|bR<3JIE5)=g+iso-m$!cG zJ$oGB&eH2i`gJKc4}k8Y3j2`E1NC{*0?VLD^n^eIPAUcptc_7b%VF0ltr)S=kz8Vv zMNTy2hGND~higm?zzSb=CZ#HKZDRn% zD?>jPxE`E=j|#5Mh*+VSeAIBAcuHDAg|=S#!Z5tDtmJy;5eo?Bg`xA&!}WkO+TD~K zmQMw`LoRVx(5OJlMlcyXg>EgA*388SfOIxdNp+A^MdLIRa68TJV+q?E zo`H`Cy750cf-++ty}R0TWjPqO^1&AHrlEqw@f9$eT5vfuv@qzdF8>HydCq;s46!N5 zWDS#db5~#8F5J^}R^LqL?Z_6ZBa%;Ww=oqhx8OLGUq)5d!3r9cOM%;5$~eXBmGKbw zk$NHmh@@0mWF=hM3JCi9#CKbY|1!){j!9I~m)%A~AQUw-Nixu_F^BQJgoaphhYa;L zG5~_1_)E!9C8COpl<6n~)vl z5HXZ-W^6KyLU9)?OOw5$S#htu3rRxU3mfJA?mjy3N;yDZL7N2Q;ukye7RM;}fi6SuNt zg9;7+UlJsGrZD6{l%~u{CiOGG52cC%P|ha4uH`;zm#|HI6=wk3J+SU%^kvUTSH@9Y zGK%r+EsMeD_o9|#sl7A2BpD%&S&qfG!FVU7;*!VgN?~i2zyQ(bB#9Lw1e*k&%%GC{ z&7YbC^;xM(Mwcofy#%soRVk-=NL;gM>|t2fBZ@~gI~~@oDn!m=ar-1tIx`A3sbcA4 ziP#>VfhPv*P8lEp@w_rwr7C2RY4G0VAdi4`4Oj;e?LRG9&YobwTo(@>7Sh3-l)zrD zm=mNDT9LAV4D1pGC^D21vil+3!E}WQhS#n3Xd{#}93nX4c4d|7qF;;QPaC?MZO*3z z-4XKJ#A1j^4K>?DfSl9HC~gdXA%WgvB^{lS zl~Nu^9qWkwM619ZCDJ-;{J@#_!q1f!-joD)5M(0ikO<+C@q@>5TCjUcp6&ewV}sNL zHf1Wg1AxyWc%djyhSjw^KEjIIl0%4>N<$<_2|A&svdYAY*WqXdSjlq-XOG$S(Uq&}!X5h_PS5KZp8{q>-H354Yxakg1dk2pQVHij~trIQ-8v z2Z}x{P?Xx*`!Biu&agN@gzsK*`~Jakp!@HoSDJBeh^LCN^syN1gER0!K_wMhar%BrZa=G)_n=m8)sr37OtG&@>|ib2rvsTT z1<4f?70p1zZO!I3L1PH8Ps={VvWme~y;*o*%@$c_fQGqwRT&_eDzFofkU7Q1@weQf_ z=cTPL3OGLyfTt3xPi;9{R}N5TfEY2sQ$COxuJgK2qGbGal__~k7!iti;VhT+(T)!c z;`Io&0MY!RF&SE+9EocKOS@>}@6P4w>*;s^V_1LAk|{z;(x$%xx)p=OJ> z4+_9~#4IEB^g7&tBUWikY~_qfB@0((OeL!J=fN*+bU@-Aad`Rc7o8@*YuN4K5P4t< z?h}!ZmI`|@dyCNb!uPQtaZayCp-O5gdk^qk7JTVWj*nYIe=kWukM&!8D6U>mOUcij zDp~>qMUJU*%&{u5V2Gv}KO6*S+wG~_X0@skvJ}fXW)rB zE`}AML$GK@!U%Rm?WhiqK5T^6k=)V)$fa+(2Y{c2qA1aaRsj8Sa*|LHdWecSpUmuv7KXeUf5 z@Q|QWVqPkzTsAa0;(R_vr;Mb;Rl!KEY=p@pW64!+InP92e291m?OO}_@Oap#!}PlB znwRMFHL1KaEFQ}sn|kA378$btxn;hP9YMb^%P^3Avan2vm*=qmhexn&|L-5eQLnI_|5uL}MAra|xa=w%wA(T@YASQXq-&4*IdzYm%j+#s) z;}25~JF28$d`Adw(0|3H_sVB$QaYSSliCrdgcET(?CTitRU-@k`N|q=Mbw`2kEU$j z@C-aLr$}hz;`<;wOEe8_Zk8o_&{2RPh_QyQk7RqS4nFH z_NLBh_pzq7AJ~#R35mPy?1SI-nH_MriV%MXIBcK1FR)X@Vm3&u40M4C;BS;yAz8Uy z(4&y}Hnd%)moB{N4RsUYHYj>UTW6O_zbo_p3#MtuN%tjUZl9nBJa7#e57qZ-Yo~FYQIj~ep>>rS(+tHZj6TMKxr^mX~<#A zFz<|KMu|{~OC7z^JVfRbjZiyn(ilK?EU|=TgHBBkeQo2+tl_cL8?B2=LrHg}qz}QD z65DKOB@QoMcRn(ZE3!YXoCE9>gQiIq5ztu<+I-&MUPq|3{Q+YrArqc?fKnA`NRo0+RG{9MB#wqkl|q(= zM)07`)F`Tqpy;zQOyxNE#eFoGv4j+MAulOHxls`$WAL?gW4%f-8dgEM26QDMn)~e1$dRSxUf(vznK51+apsi9$HQN2uK~JHN6~SOD;Z ze@Zn1BT@xs@Sbq%!Lj`YIwi0M2Gf12KO6(06i5UB0+zvWmU=}LV}VLRQU*vcRk$wG zB$xq5TgjMp3Gm`YqI!RCHi{atlHMpO4*?u=6{ScD6z%}B7e%|OV+GgBeaG(T+9{_A z+S+JE&lb~_1YOy&Yy57-_tpa)b+V(5{*vDG_1J>#vQ+%`z&-}O0>CO#45HCv*Jq8k z`wk6QYgYN3z@a|rRM0`j*cURzxazN&rY?AIsRq*06e(9=YXuYp=-X6Qjq02<^U@OM zq>sAx|^t&Hkq^L^GqoilNIEsqEZ^D$;LsfMyO}XYhshojKcCr1s@If84$>+|DgS0p%eut zr0fSkotkz>mDS)db1f>-17^b*FN7yG%7-ex@k9K!x z-@6@qE_hu6mj^<6IkZEw&g^(F(Sx)wn?!GNjy?;!El`PN%tceVCKELNF#@W&!Jp6* zp(yHNM*y*x3eNtlOZy}dRUD$(!&c%tX$AZvRs=#^U?qp1#rL#yCAW4ou^dB4LKr3> zOLJBx_(rJQOs@eIuNI4&75y?oJGbt7+<)Wk{pbF-pY3|;)<=z&OTKg}pPD7$-HFPM z2nF5BV~I+Sj8>NOJw$aN4tk5IbaFa4LaM+ybhC1@+B?T80^{3hlAy=O4Wb%26uXbC zLZm_pNfV1%fldKASxL(wn@F&MOXsbRP_LN)m4mDdg)IoR2NrAe^c~6SU_|k5vf3G% zdpcnO&w3WwB()G$mr#b(U(M}yX&%V#zK2rtQ6E>dxwZnS<1?TxV1(-L~sPX-nQ<#BW!fIlCw50evv%alYKe zjA`E~;IR)zKt!ZaApj+Di#`D9iOHS^(<1hyDAjGpTMD^%|Kq#39Ot(fD(tSFDbV?G z6X5!{x)8UzGw&`~?_OhFbhYx{jsC3fcwlLJG`D_rv${k?ceZN@vE?aWiiv||Cbcz+ z*#p=*TuH9BtIA$MQ;iO9-^ELRN{y&X2Q+|5Qtz>D6K^D(G}cHdbt0^HpneuBNi|Q! zw+P%uE7$I-2-4xxmx!g5bc01_~ zEYFTloHE(x+J@;lKBQ#W@lyg_G1ah=T zRXH}C+s>JZ4Vsd$T2x56BA(_-r~o?P8M4_$9sw{Idb4Ld!7?p5qB~7X@4~M8*SA-G zz2$!=Brm+z9{vrt^9AJgPH@?$Vxu8Q$|z+>NhTsVq$3Qp91|r;Yi@kP%#sW{E_sqj zaGDE4eTMO2bCk_q?#2SH!mDs=a|KuTHs^q@ZK)58+FP&29%^4r$WDUa6RGCBV#UQB zE1yKETd56!NiCx|t~{(%(ipmz=A%zmSyctbK=Z7)Mo0vcamAS?q{#6nO!GWS27(qc zCK#7OLrqLj4Gl0uu;fY^31@>%jIjg)1GG>W!YXGLp!)~)O!GrDztRTIN$;K}=ySPj zM`bP{&@(JFS3(WUQI$1~A+&R-{%(51W0kee$&v=qh(jn$- z^wK)WNJt2-DD|WW1TS+8*@d8qkGnZyRgz~HOLWO(n=STeNFCL$orn)nN9s<^1{)9! z6!wBu2E8R9WVuQP=(f34{`zWdHc55uXD-|3vwhWbq@OLt{P6~WFiV-y>?c)Gef#5%e9V2+om?BU8N-#mCevL1KI|o$sjVl)7llS=e-Shwa?i`3GEtf zz-Yl0#wrJ+GIB$-bHcK_jrQlBllV~h-;o|1GE&xbtA+3Ljt|wAUcWOQlA*^pvazLh zQn}q_JFh2hJQUu8-jwnj4&smnG)1CQ1pksqm#x&Zy5p?J{+P>A>jUq$u!<_#l}*^v zSi+M^B4JtzEODB_5~?_xyKUS(6lSA|tx)dGeTU9T5@=b|nR}VWwO_s2f2m`dix-ra zt(Vp4i-&gXE?<^?^H*0Z!F#d!$kO4v3=VLMMJk|IGgg{iHG4eM>)foIyBtFZxN-U| zT;8^rf&sPn=Hn9JG*9?t(R-vW)>!IxPH(Rl&QC7ucs0-^27?tSVN)e#^|-{j6#Zp3 zc{wS&1no60UoGb2x*M}AbQUAU+kO)9;nj*a>~&K{Fe`fv|20b2uglCd`&ET~mU~z$ zk8>}!285B_?d77zv5j^{|8h|P{dHsib+*>V=j__}TwS}FoNLOOmd@0v@!2|cu9;dx@OfLCpP{u$ z9LKpkTSNbKo|aNLTc_%#&eg3Fn@|@gJzryI>e}pF^EErqY+b{)C1b-w1tXYJg%z^Bpo&eziXEG^AmPeQ6%mGk^9{@3}M9G|_D<1==0G5w{^ zCwZ23?%1K9>*FqyTs(=J2FsQEZE|&c1uG!DDn`>PvZ-<4Y~G$v{+(daF1DYj?c?rk zO6vdCPu#fhOKp919+Inv(hRp&7FQ?cX?sND`r%O>;?*=-CZS{JEx!aK=gQTF&Bebb zH^uB(-sw-n+qM7V(HM=#8*NWvdC#>>s{pIM)f&@0%qBOB&T)~QGu=e#E`P0-jZ~zG zadYL|M17cLw3uF9b^^NE4*cBd!7^q0yL4dLM%#f)=hJ0zvu$YL z^W3ezU+60>K-B57J_519pi6eDqvNiw+^nb#1&7Lk!8Nm9>{^afPBb?Vwgcc!MIj80 z-5(Tf`jZ~kpLLY8>XEr(9-r^*OwOV6+P3GlyU(fqo=YWvjLx)kdSI$Y=gT>#uj>51 zz3Ndq3eV~hy%%Guc=K9hQnp*v`QuFcH7mgtf8=MHP~fM?+CLmUUapA((KDZmC# zbl%zFc!!vkM}GeA$gFRMatSPD$#biuik=6qh&9e=XM*55C5gAQLdSwm<5iWy>4kjWY*4<1>Zk9VFut`jQ$+{q8KJX|_UFDF>TnDwVwmE;1~BQ3Zm#S$a5{0^s2)jpi<=B~107>C*d%jrh{t z^73}J411~>K2F1JT`jEmh+?b*THWQhvl7$VoGowjzua_w>Oxk7NNxDkw8@n7cF)Il zcYM@)c3(#~k3~lvEJO9Z=RP zYyd^LxgB3kE-xpI7y3}@6~RWrmQ)a(WRoslPOc%%&;oC~*o8peYz1R8rIfK0y)RS` z5--T1yL8WXl|vTv+J@_bw&Ptk#wpu<>>{JKz<#$c?Ey0WO*tG7p4>oC>i_ zu8L^dO8owg|J7yvZf+O5=xd8edQaAU-(srHA@2I=&Gt9R!m*%j$!h0#NIX!RvJ5fW zk_eMW%DmtXfFtk()5KD5NlD3}i4>TrKsMXoAcv)7pWZIYL#<5bOe<4F!POM&y4={{ zf>Es*ZnRGyGbQ~;ch5=Vn!eb4_#URB|ACFUxOr7ldVkV6XJ0$Z3kas!5mB#9#F9my zRW2!8B`-`=QJ5U!s-2cK_Z^}yd2dQul~8$QNyWjS)Iw5Zp$4<*Kq3~&Q&JHbq9kS` za$548Fd9_~E|I_(7m5?3eDsvMzzyV{XIYiBV?QsoimThjvR`{MB5g&<)~}8l9BGo( z6zjj1WvdKJ|JOO4-g%%_4L5JzHLiFt2M(Z2j;J!6@}qL#)X=AdWOPpo9N~kiprPc- zNt-GHEx-e#m1k~e3LLbRlE|bS3yFX-=w&8T3+=9?N{cKS#SSDY9FAmO6V*oc$-UI3 zjfXDbWaX&}(1wC3Y1<^F@#4J4a-fVQo-CNvL+ycBuskbWGISE~M+V$*9|7ewQVHcP z8^H)Qcv>aVra(HJ<(@~EBr!s0iiv`-F+4B`(FDIG*fUCky2;opqNuj zW1#!98xE`Et5iJ=75}G8-n&kjcJkn?@;$$D*Tt%8ZJkdpJ}(^gqLJ5o&Kk9E9ys`L zIG^;I&dE=AJQc9S|90E7z1r5bp$u~T<83ZYK)K--igF~KP09vJZep$tkvMUyV<$H^ z%QKC?Z*BvU${`t2?CibY6ks>TLy5kp6_j-D2sCe3lh?BA;{mskcS4q*T+k#dr(rgw9)3PT$zZg8@nX_-Mw}73DLXH$&i|G^qkPM%}Gxqd51~qZW%23 zZ3FGrBz1V4CsEQp6H8g}(|bI)&iB2PJA)K=D+hgL3$NY9f8AH8n*GQ!vU^pu-gZdt zj)T3+`S1-L?PSgPNG)#E>S71TzKru)X*EC22jfrcXwDsT%i#dRZmXQY$ zOr4A4t_QB)?p4hHQwN~di6QTu5KdP@&Y>~aZw1Q&Pl@3%!z$>Xv;tP>QZI!GCoG_d z+?AVWP-G`Jiw$o|S9Gz)fN|G#$*D(^mglz{jJ2tg^LjG9osXNGMs3}q?f{mx8wOuk z+nXEi*-a_FWj|R2i{f7iHD zRX1DBb7m>TWNd+CZLOBYbw^TwMxRrR#uWj>f-VJyHMQ2X?(aJN#0~4Aj_c+bivFBjD*n`pmN{) z`R}rczkc`dkkJw=8eoz1A%V{^mlnDpb!J~nyZKW&4fMxC3yvk0Cg-F>07WY2F{F@P z^emMtQTzsiz`iovq0dqJ9GmUN{P-2i5(CHw^UD-?UC7mVXfQ#Umi97<>L+N))SUSK6W?4qfK+=?{z?PuZ?!#^* z>c)$LDIa5o#_OZZ34}m`b=*J|hSU?8$fQ`oDh`^9%;c1%_bghcSU*vBzwH2aV$Lby zSX7R1gZ`tdB}1lD8FG|3fjLbgNt#^gJ)RO}G$}gK7Wk~g6dG^$b@o)zzqjv4U%U8WjF$FnbcAide2OUi-FTrjUcLbZpU*7uSs5} z8f;dt2?mDl_2gErt^mGCVt0b>!WqVtv-Wkkp!P=-IFH{L>dVOiAa z)*~g5P=ybBU)f+g&tX+Si2(zL486$^DSU!uAU}?4)l@xpXOmda?4lgkS_O zfEb3BvQ|d$QfyO0x6BlFUl1fK>8ulAeFJ(7!lZS(r&C2s4z+c*ArJ3pvOV6AvA1QH zp$U*{G}m9Qr@vmN__CbXYBRDgA?|;Fem5cU$m>*e5BsgK@aEE8Z}ihj!vKFV24?|M z#ql6xVyaYx0d9%9OrH19GN2FMpi}plbpd4 zPN@&k4^Xb*4rLnJT3wsCW&(@Q#u9*=YCxwq3>ve9dhLl<&~2fy#3(@N1ri|0p-y}B zT^R}(HLgpf`*Z<3nV_J9q#;%*3k)*PXJBX~(Enme%0SFQVPMP&VxgCUW$|IiK@d@l zb>wW9Ra7%cMKFpA!xP~ zs<4Er>M(-__BwQ1*hCg+RvWR3LV?vx(%?BgE|ljCZoRXI@;p1Ao}Ew6&ZlSR)3fvG z+4=PBe0p|1Jv*PColnosr)THWv-9cM`Sk33dSuS0<74($C*NA+UBO}#TzI&qCg%zQ z!fMgojh!>%wa>bkaGr018ZYPTAdgi zdZ>oogU+ZnATnKWnk7?#x(dQTzYgKi&FKE%)h#Ms>klVJjPEYHV)VBRw&IqVN*g@-6eOehO8kwQ_U$%m|cv?RlBhq>*oqS1SFDfAJ#P_8^MsbrxCen$L7HT;Gg4T4ic~tbkzG=$pH=`*EwdCZMNcnV*l1NwuRgtgim)Q!KJG*1 z1oKsj%!r(bWHKKqtkz^Zf-QKTh4$JRXk53&$*?>mA6FLo2rtHx%C0^i(%Fc;O7nR+ z@v=<(FqywtR-GL6lLbz$^R&a3XBK&yS`VVorn0b_Drq=WE5;eQa}>eKK);*2b*Ja{ zQRj?X)pd3Ad7VygmDHnI>ZL1o6F56GJpAAe_!)j-o6wJWzM<;glk;)Usk}}NvHSiK zfR1~r2UCY$*bhm2-ziTIKeQW+mf0yL^Xa&xziR7PLkt$q?(z7ipZ%$=RNGws`J3M5 zS6}rmzwST$*H3$w-+kY^{IUP=-#_nN{?z->A3puMcln3jyMOr8553F3^zVN0=iX(% zlYjW8fBDxx^e_L`yZo*<-amZbfA@!epa1@C@A9AhyFc~b{o|+o%Rlw{{Kvn1*1z1i z`}f}ESN*$R^}6xLZ~oc4{A>U2Uw`afe)q@T<&XV`|JLu-PhWN~|McIzZv5%X{@wm} z|J0w2&pz+n{p`Em)P43tZ;d|t@w@KjpZ~kp)StiXHTC%)`j?;e7W8a=V{m3c*X@Lp ziEZ1qjVHEk+ty@aJDJ#=*tTukPM$bl-aq%gx4v7oYgbqGsngvDb(wTGbY6enxW*d!pF|E4yn?^? zyYrbm?}mN$`?`JZmTZOjy+1H?j!%EhwqG!;#%=?L-u4B$PxL=mx-as^Vn41wt7=By zt76Uk&trl10#7Sv*V{nyV*+3P*WnWX?>n^Bec^gX;Q!p<{}T3jNbr{Wf$-tDU-y;Q zmG(TW|JM21^mWyY^Pd@aZ66bOIX}h{yoo$Z*h751Xx88eJg%OV)OcGzD9^s;hJS9m zfF`?V_j{+%CuVZ=F3dO~*gf6I7h)m-D0NGo&N4I#?a>m(U{+kU(sa_}Ov#XCD0(4a z+1I5quqm968E_JRjijH!#0{@9C=5Qruh7YZoNIL0w zlAy*?=kY<<-67A9+otpt#=*Uc{6S+fW@V+`PrrFh>qk!TOoWx!B9&$h|BGm(L0!T? zY(^Vl(ORr$IVi{xV^R@~#&y_Z3Qv8_3!Fh;*5<~^PzoR_%-oCUmZO>)t}wX2^Xo*q zzyHUpc)Vk^X;J||+?R8(93}LfH?iA3ZnXj&HZs;~BJ3wUb~$y^P4hKWEqZVhY%ipj zjWdi_MUJ{^lNOx5lmiB*5#*NK^Jn$&mLnaw1|w2sgIo=+J5b58^oDQmT0}Bwx_OxP zTL6su0@}>MnF-*2zeZVVUn})y^_djs^_Qm|RsUv|jCW+6rOc=iWKdL|86h9pUe4F8 zHR{_wdUO0Kd5Y6}pvJXXV&kM5o=+$wP^wIeCk%4*t<;z;aJuOos~<({cM6Y{_eddE zD@&7|N(v->lxyvCQUOpXnhG0{3DzewjjERqNTl>bm#seWwCjMBNI-2I{Ae=rY$vsc z5@rL{MjMfaAAbgxAGe*qu}5G8p$1WpjhD6vy0^nv8%jE>67(hmnUTKUa?Cq2Xq$^? z%}`_c)-7~J?CmdSH;0c_4Bw7&Z^bQL^mxtB6;#?XgiTr|56yydcmuj*O#r9;o5$)% z)vu!Z=9bFX$96mj6FaR)D904Ivf?g^1ga_=Hz0EZ)mhEe z>EfCtQU|FU1kFXKw7nlxhu4=r-{}!F0xq3G5R#MOMJ`>{m-=@nk)pG1B zL$lDSMq?j0pUGdAQ@EyW&4b7W@pFtU`M3r-F8I;!Q;NHE26rLE)tkI zPVWNJ-)PhPMkfv%SU23~AjO+M$3F`cm<%RS`oWd^Xoj7+DD6(;(R4;60g(TEY<^)d zQ!|T<@s;SF*-Xz^8JR`{2uGA=BKvIF>=P6szam$fbe)~WD^(3F)> z?K~+QHGxA=&OE=!IjLQyky;ZoiWHVSz&(nxxT>$?ITB>O&Hb!15ty$c*wv;fW`<$^ z;kWz?Pt&wThak#YIEM$M<1(!LRYdhzMD@dBaX|bUIt~8H%Zu+<++=j#zj&m8lf56m zFqsV&mBG3&sD=n_m|_JPXVSu9$Rgu{22sJ7W<>K!pe!1gpZI5}F9zB9h?m~xQzs3B zvOD>4o7Y#%M{owG+z4Lr_-oUvrF+j)X(%Q;;6(KG_*1|#*{G(_v%8+GsxPr#cSgsC z*&g!tX}&`YFLJkQc;kippywqOrIQ6m$6{?|c)I#JsTAn4OpV3QuaSpbaTuQ57521v zbPQuV;)CbOdhO%ukf_!Fkxz(fURNPm4S?53Ky130|PZD_P(vVAf)_;t^G;_^x(>Kd_r!Sf{ zH2!Rr*>E>l1rzbzt)5kic7K7($m+J>3w}hEt4{5z8+6&2GC!LdIKUQ=GqNtYN(%~P z0PC(UiNxrdNQ}IcgjS)CjY3$PEBz#cr`m?>LKX5-05 zH($a0!b91L?rx_Cui2=q?QTQiD`aR5Rmr|D-5_P2mK~dX3D420r$%|vtSoVv`pCe3 zX?j~!gAB{|8q%&aXGw>p*Yd(}pMo$O)&`g3uvzVAOBel@Y`Ffwf@~PRTe;wbt{>k` z@Ec1Y8av_9+Y34Hv=pw;F{DzkpTj@3R>u(W0M;&kOt$48cl-uuNF46y?`Dy4rN&}B zjs@-{!qn)|BHTA73;Ji%>Mf46-EZ;*oz3?J-{bju{OZbPaKk{yOVDgyzC30kan;5# z_&7CdW(Y)k)*E2m8|n(YPBq@FIr` zXWRwo*vj1~@Ak#eRMo>pSMk?}x8@2VuCRK@-WF1^t+{bDvcfQZ5M7Y#JE_@+2YJNm zdN#Y)#T5D}X%%~*<@(R|M3U%n)yXJRlP(ETN|k+wsI(d|LzeQTDZ>|8M#R)8r_xGP z(shNzL3!pS;;^uyC}>OIV+T{kOTosy|H z-dV1iCG0KfvH#?Acipf7elDQMgWTRsMfBm@h#v2aFnTERO>{r^ce=eEo#f_beDcyc z=E0;ZR!_wcaL3oI(y0+sy^JNEZ+Tt4? zK;mJDXjMoy$Qv^!nNgi;Kpdc0E}YI_Fl(Mf?=?eTa^fP8!ODYJ#EboSjczv+t=5FJ zzN9Z;&cFTU3taY&y?F7sPOr*z2RJGa+OuzM z{g}mXNe(J&*=rleUXI2BeK1oAL z4T4_u-DNsD$==jsAXm5Sz=~}i+gQDd%^UoBuW;O+9=?AbzmxuIdp^*|Fc}#5^M1bP z{?!JRsM$j2?LL2Mn)TThp*rjw;c~@5WOfS;<`HUs`(yY63c7bZH8pxojRWD|Q?Z>7 zm6&-M`pg%#V*VGkx7@N_-69qLUfbn@Q!K)O;nB1T6aPgfYPG!FH@|?w`fa_PR?9X z^=<}}m)v2LH!Q`{z~XsuUA|j?vD-{n0c}4z#m3C*o4dt)`JyQgbQX*V#b#c~CH99V zf|eD=r7gZ%IL^zf7JMHMl)mNWBRrrdiUCZc8}wl{>8V{7iEPlxkQcYCg6$2XGA#75O*h>Pn zx|wvvGL>u~7QjYe*5dd1wt8CI0uy5cDR!|}q7ym4~|JbhZdo8iT#m15m$ zxYOIZb?(bogs{?XsZxzVnwocAsPZ>qvqtN|uk(6sqPJ%6I6GzkBn3Lu;L@F#m&$13 zI5r(>Ax3q?wW&7~quG^Pn1}8-w7@Z~J}lAF{zv|p!s8FwyX3ZdrJynDB&B^a85^u4 zrjD?#fiYF^-d)%p<`oq=^VfX8HEJOb@G49A!5F$RiNKn~s z)xZ~tD3&3_eTI^tcS!!Bp(40dSpYVJo;W&0ziU`<3``x(jk3pd`TU~?6`HK1NkH#}T=V90;@79jP z(|d@H4UWVxg^o%kqvZ1yGBHjz(Yn_SrS81oxA<&F^_tiVpqFQ`f6cIwjztAiE%n8EXfY8UzUbVIXgNch0`|-~Toaxg4@#XP@c+w)!-$m}}4fGA_hz z=UQCojDnOa&O-mcbL6oN7E;5vynyZ^2W6VTY&;ai2c5y!GTW2t z>7DB}kB!cn`H}2QRk9Mi^=1ims5YL4j(+-?y-BZqGw1%_(ubvy)X8K0WLG4NlV$E{ z?un9Axac={l0%4%sG#{W62D!8F{6ds?$v4msf@m7m3foisLYbi$>kQk040Ey=AY$= zUA!}}PwDe_I=Z{;+W7j9ts}*I9&xVfQZrqCTiIV2nQIeRhkBM??9!X`sh-R#L4Om_ zlcUl`?gFW`?YP*)7@*xt@teG9v?$U6;S|WQ&Jn+JRm-GO$F-PG~`@qq?Cdg0ih|mE_GFyKIe^Jjs8Sk_A#ySObuHmzydd&U|zRyu)Qe?51$o|C{(I-KOGzdY`pVvMcH;no>B8 zE~6V%SdPp#DDsOod{;#EJB+IO_L#u(tkm>?EGa-+{(zRZpo-jwGN&;xCV^gCDp-^T ze@^BDE@|+aU`ARcU}&rZ5)lVl41-TK#3_#~Ss@Snw_wM?D)V(|QK1P6=>&GokD{3n zf-1c_X(~(bT|Hl6Ew$WolUJBuBZFz+3l?V+e!id$q>_bl&{q(2ZlDhcw27*wi+KwH zR3K_C$Q>a7WZI-%dPAh5X~%AUqVH6NAI5^rXeW4nLgNEF)7(?_G0yOK=HpEDYx*>0Cu8`B)C`+GT``av6L!b4 z&+|5VKS@Pw9d}jl_YUinoWhK*^Oq{y?#9?OcNkVnWld{F6) z_SzY?OubzS!qhSV<~^BUCn`u^&$L)uGZ>qDS3sj?Jp?k)gN=l*oK6ng1YEAEkS~CC z_qK&7^OZ4wXTJ!kSVaEsg|U?OhC0r6=aT9wV@?sxFQ6~(2-pair;3`Zs=HFsLh=vL zK&aSZ0^p6qbvBibpisLd#@a*9<$=z?@TsXD3ZAJ6h{D;^NJ0+}%{~8GIgG{czBS54 zvC@VK*yj)?cxE(hA(#l5qLj<&UJEiTYe=IY&XkdVP%YB=*wyu5XpcTk9Das@UI%}qB2 zDR}0ljK|#1T`_d0R9#Iic%Vtc8VjZbSVDv6GST_E43L9qSVC$~R>6DDvA>@olf+cz zx#g9^VOm4U)I$fr<#>l8NcFD@ zNIq_^VYDtny~L*L{+u|K*63N=e|RNgysz1tlLYOP62&vkvDqA_AD{c01j!~n6|@Ll zX_huBMMf7L!rkBYn+Z;thD(SIz9k|dv283Z@djPmIm(aK^^Z;y?aM z!q;20iRC_dz7e6Ez+!4(9p4p zey^BOYa~#6)c12o57y_#()xMbwG}QJ$}-m}u%yDF-7hKyBs9ZV!@M0KrJ^k4)y6nF zIF5ktNS#dx){hK?w(fx{-sPsL_gSVyav*{!`%LxUEZ9c56mCf$xBSJS)oyx<4gV`` z>h)Gz`JCR>-SskTI!bV|BH2<9>>2sPa1U4hACaCXS`LPe;P9wfjrO!^%ekfSE8-P@ z(&Hc)>%@*lQQuk*^evJJtvOy+WbG$Q6^d-=bOF)7gEdo3){}Ne4Y!HL-r;rV=07{F zF{>05d+6^l3SwCHPzwL*(NebxN+vh@LEv6e$yCYpZaZ#Y+2{#xItv>-}?FJ z#%y*`!JGRwO9mck!K#u3GDq))>Vz+`20a;(5{@*zrTZG&p0Z?V$Bw7t>8)G*t5Qfb zC)|@K7VuU?HX_Itz2aZrAtWOrt5iE3)kH62X1}NB#L-cjo1+K?XIu{FU+txIB6Q;A zF7m{&ej&Xc+gpWW`uEe8!`|j}wJA3TSHO|q$BEykPTy&j|8N60Vb8dFl)F+-`G&qs zm7JgjZdPQGE16m{v`4_%W!8HVLe)I@bv#QEvOATm3CCD->L=mW3cIg4(Y55RiKP7x zp~3@R9x|5*UTrtGoZ} zLadx@QM%rSx=3vW-kLFENB3>Fbbq@`WPM1X&e+s^hL4%M41a+~9H&pAwt#L_{n`Pq zjlv2bt6-~yhI3d_Vj&p?L(xTSh%R7WQh%si(IEDN{`r@x2RQpDV<?Udb z&+f6j-OC`J7H54pOXdp0e*YO#;zVb79<A%?j7MjNd5DdNgB;sV`FIQlgT3SC);O(|A6f)W;K=J(*B}q zZf&>b(J_`lzQw@v%3{ij=v}aR7GfhSeo_NcxRR^jTfIUPZ#UNp-etg%G^{%8Oi+^n zdCQNZkWDRx@bJI}TR>{V7b9(RB}dqx6W1+ZpD(f*HyU+lFBCG zaS#Ojt#sX#w)ObWi$oNwi;86}FTnF-?!V2^{2^kw6xnFAsEmme8BOm4kL-VC*=%ri zEnDg^dm8T0MYeY5OS%Galm>Wy@s1 zO3>b|P=I_km~VxjzBJV?=&nKUKUi}md0`cH+CU1Ot2D}(HA;yn$uw#JoN9)B&}mZ! zOx)#j_`>V2#mTwI@gQe|q7#NgbqnQ~2+opC^g&|CLu%C00!7MtsJkzonYuUm@0gU* zSHxC3c|0Irx;(|#eY8Yp`yafSKrOAEam4XMT0#)(i@MZ(r<C$&KVWjdZk4)X>T!)XEc@NCmQSe9%W*{J5u0V94*$*Wed z+v3N)Cqmps?2M4IPdqCcvYcfk?@#|4`hE-Ft^zEpJzl-~1)-8sF>ucja7o!8@is}f zan7`_;_7q;d2^a!4}~|qnsoef8l}wUGf#7EQ?<2QgJGhu4E@*#L zD=4XgtB`7%wzTP-e{jeU4m2LX&O;^8CD5fyGqMIGuDUUAn}e7o(hfxJpZBbjUSTjY z#sV`DNWisodI&wQ!o{ty%IlFBkLDvI>^Qpsd5VJtEnF%W8j61WXX_M9RP4ZTigz2@jX z|37Di-m%{j!HA2fo12)pCuY==mx#%tBPm1#5hM+N7{FA`bYo@GfaIm{b2NDvqkH=% zhKs@Puwp+v!&FROM{YJbXU-JEbIz{LRi!c-!4~CZbHg>Dp-Xk+SSUCOK|nU;@6*0} zR?J~Y4pT6g26BUe8eG~>2!f>*PV=5R*&$G%xKT1eQMN#55Bp>V~|OJuRCb~I|q`K731_(gm( zV-&QY7M2hAPYC|o%AeW^QWw&>><#xiHb%+{XS_NGt-mb~JI+?6-JTM%J59_PR{vKs zVEOOwsA=d?JZ}YGWrdr{y?&6@mHHo^AQU!?4P{hoMsUKr!B)KbBMfL9kCo~|yQoCn z-t^J?2nJK2ni!4mF(hZ&h0K64V;eYHgmlhD!QCCkZ&G=H6eIk3|G`=Bbp7s(>qNu| z^x{wW-*T#5eSfwo;1{?Sc5Mc-qg(2c+}Zc0#5Y#|@ZdO_lU&&hbjtM9sNs%Kv?9R1 zBTF+Thxi4CnrnK7&e7=z=TKt=NGPmBa1$*GOT?fln~L<c5xf;$Rw(=B;o!R zs7)!-*z;ML(k8EQr5s*B^0f<1+s)MDJp4b+4`^deFRq&uCaQLnZ7BxIHv>ai#6DIC zRFFAcnhPo6b@tlBa$cW~yprm^M-q$OclU?3qM_^V&h8w)7Qg0^2`^`0^`8HDtj9gi z81A#3Vq-u8{MLde$~wzu>#r)SrEvg9yT62$QuzSXmX6DQP)syv2o60ADP1Ki^WS*} z(;wxsGHgOl^OW!CP(T$GYfG)(eG*64b?`VH-rPzIK)ms(@HU5s7R_Q3qZj>3k&-|M~bG%q=ys7ryNOY82gGVinX@W9b?*R8-|gQUZ(at&Y)3l@we|GzZ_9l83J>c`;dzXEh2Wcq=s*-@hnp5 z^CK(=FR)c!(NQGrw1Vn1752EwK{xW66$wyfPiw0X=gjJr2ss9LWV8vO)+-fpnmd+T zW9(#|3d51@kP+9P6ogl3M3$}c?(^$@m5)R;mTCqU>ta&y$YtZh2+lzppG!A!b>-Xx zBQ0|seUxxRKOMNp+3cMuEAP+x?@AI2A6YKtj|YY68SFm;)sFJTyZ7+QHWHS)>B+Vk z5>}f>X6^#J2}F%?6EX9DFve~ji9=ks&dRiyxTO{|qeyK{ia@xAX>DpN3{#DC1+@kH zNBug>jrk-adj-41Tb0K}+`G3)N3CzK6J&(h=5)1C0vD>-zMd*Mj^ z?NNP(j^lRT=FTfdHC>LUV2ujm;t4h$CwcC)52l7hn|AK07!BNBaPZVer|HIPj(q2I zW^)A^`Lr0@{6diSJ|(~$&h)3fPW*k<&XDTLkHYe-(Q(pcFh@{)`kBAAq1!0^8m1Oa z??)iYsGAZddc+o1Wl9&VxY7L?TZSf~Z1EmRE#A`KbvQ=#^kN#Jq+5nWVH#{rht zPzLl(Un(&Oa&5q zUN2%4)r_fAF0>gNQEhL>-9M`(0}nYE|0FX1>dqSbQplgrS?F$7QR+X009VT|VqP2A z2TG^a@0oY#whnT%{6C^PHbsuWs#Kt}PyXPD)hEh2GHe42en@@<+WO_<4aTa&n7;Wv zrl^VppH*#7KhffkZK}S-w4a8>A^;B>%jer^HljEJYlf(xK9#`De}m2Z%5nRuU1BX2 zwzdsve~6Dt6xPmrK-vt_?(`A(Fz-F{*61$Kz5N)^YW&jNa>SVfUUEL#&E03VMb^5% zlJNNF7wlfDe>r;}8tM)hdk{v59*rIB z9-TQ^)=%)<0QC@#$d8q|8SRai0-I)Zy|aT{uQ|5r)OZCOZn^kb7WC$892OMMBKF5^pBw%BpFo3I?!;DaFAKQj{NLWIn$#hgDW3 z4ZT;@CB!@6pHru`>MVSqAXIoPNkZqygS=Evbr8#zGIUWZo2Y%x*QhW;7wvs?iwv&XWSmq^tyd@EYBadlLE#7FtNWr zRBP|u0g&a`_H#p7Ok)a|Vyw{vb-|Mg)SjWTB$TyEX1^h{<i<-sSf!?^otc8{;rb>OR z&VUnC&!-+#Yq4D8j9(gqc^7X-?-CM_ z@anf&x#h4=7Fr8-vehB0HZUEUA%e8|!VKsHOZ6IN;`dgg*3;k~0ioh>xD$;FP^NuR zaAzMj%*$QqR{v@@T6A)8G+oI-OFNHv3K-iw-8$^G8fyrVpfCAtGgs}~Ar`r1u7u9U zAK@dI_=7w7at^Kj>=OBQc(lMQ1LvO>??r?8wi^2fkQphnz_x%gm3dK@#wnGNz%g76 z$X8S%;i*8xUhx1eb=M|yj)XL11n4>WRuIAR-*S*5{-p_tXBykU`V%(ddJzXU5CaTo zTSLtAh(ArtWOyx?(VW$sb5JO=s zgwb&Gxp|8de4CB<;~8O?0vLJg zpF^pN%opPtFX+_d*z+Kf_!qOrFTQA6GI?KIBD1 zK2Pe1O$x8MegA9_9XP$)SN*G%n?yKrs$ba2#9E2U?UI8YqLA}&s68$+2tS2{{TY|1 zX$uV|0rDah+KPu7HPs5jZn#%BfS{qRX4hezc zVWcOa#V2flrQI-8(07BX=zBAjMYWP1l>L8PCj>ORK#m*r>mWsnHO0Z{2}YL(R_IE3 za2L%ZRe7Vx7{0LGngK55PUlD2Po?tuzx?N?^?&h~=htJ6rwb%70#iDjb?Y5wl*ui1 zA|Z7u1N{ho8V0m??;ezqx_95j(I&QQ^VCF)xbtF0ooDwvLZ zA4l)OT%n*8B9nE(_+a8WPD2Gz#C38?KBX--8BI30dYj`!2>CEF=TcCkT=Z|MMn0lJ zOivVC71G*7o@{^{StVcVRza&ksVz$e=x9ut;#$49As!nMDcBaM#?V)B4_@!3MK3Y2ZDkJyXq;0seDB&ByG72PHf~p$IiEfb$^+yjuxm z14K*Lph}w|QoToU2rJmghVxWC4&rnPhnttIK)?V1EkfxX#PMAV+uh+0R z6@w!l)GC0DFejE}WEUN!g0S6gWPcr<>SBg#hvr~iQ|dvKYLx1t);0+IZoj|(@`I!M zSq#`;_>MV(oIVqt`7|*2(NBvtv1IHbEK`{>UO)HHt8KTG#24Bx=w$c!)Wy|k%^47_ zyBD1-!#=LRFK^vFCD@qrYDc=f7ZqkOrX3VG_@arwO8pdB+68V>lP3Wk zR%NI8H`s9|2+WsxlLiDdgVrd{OK{UEIPd_B%h|m>0~^*fFG#_eG{f3k1Gr_WNJU3Y zcVq=^P|h*cA|rIm6wNelg*nn4o=VY1V{cVi*yv$>mLY!J(40 zAHi@VBG!@iNg?U_mM+zYA-yUnZu>gZ6*O#{Obx3JT~Dh7TmzlV{rC4{?Z+(!G3kr4 zlGuBsHjqdS+|3ckGhFmZ%*(ap*kw47Jk_ZEyb~?auZBZ`y1`s0nxuQ&Zuj(w)o642pcR(Nie=hFp>9 zL?&81pZO)F&G;{B<5#9}%3xXEC8%BR4RSC%-|Q&8p>QX?o@rZUy23~JhBRKsOcdSR7SMdHVu zN|}78DY)SkiJAvymZ8&3J(TJ$b5~QEkRT)r>n<_kwH?dd{B*wOubQ4A4a^bp=EGvf zI9_+pO#i(^LerCtvsoS=hkikyenHiKpV*7mHqgml~MAG{dlTt_vSZ} z6)bt9C-k-5M?&0~^3$8vI;It)KF8MJ=$T%0ZS zf276XIleBe`*&3RQCY`y<-|8WH1)!hZDVt{(}n%Pd=<(!K04Lv17htR-0oigkMHXG zgLdf2Bh~HI>seIWzKS1b{R89_!v5?1!^-V*>Z?Ub;{~`pA7%ScVI?>+!;)m4R@B3}qQ=LIq(ogjwg$BF54@~dUNK_;m#=#@e&RD+pz3BsF zkZj#f@oT_|{**ScVX4hhkps;lIVJ8+2FMXuG*5FK4#i!4oqq;021Jw}SVeaDqEEt5 z>}P_W;+o7Tnk+pl%=~2rO`VQ&H!wK57y7G!Qig|dCmr9Wwf3C6FkqyS z2tChcO~9vYUdD67Y9)U*66vN{y~j!y%=oqJKYiWO;@7d34wq-U@8%^Gn4>%Qo$N-x z@NdHvzx5^d5~C@?Xs7JG>%BpS;-&iw7%RMJlFh~(91A%VBooyosOIyddZD~DH`sMb zE4bT;dPiHqKX1XrrJHt!b}!+21Jn@3GWxpcJuCT)USO-qw5J)BZu3b)VD z8abwTvYjTDKq@KCQ{$2}gQ)8@{Gu?!!*7H+eRDBwy=}rUt9ac)FpEZf#u%eD&BVC? zYw^y26m`pV=su=jwh|?So^Z6<7GwyT6+%34J8;8MNSU0r8uGr^9OCQv>rCP_vA$=^ zR94Erra9D0)z02YLe{aca>?ZstpcOD;_?t#tevG4H~%7I;{};!v={QdDAoY}{%#e9 zZ64^?rurPTwL|GsAX^$g6}Wv$j&7x=(sy6B!mp>msK&J{;v71fax4cclGR9zR}ME--o zo#+4|g2IjqBod2U=}9u=;^>xWv%!hIrg$wy_v*X4hw_oj zOHf;q`n7r1$0vq2G(Vd4Ij~T`fjMCLcBSP+B+#7lm{hz4c^D$n8? zOw8C$0Izkt>0r^>Txu<&6=^J{49%g-eq`{WplOn{&sC_Q>t5~_wh>7vyowvQ)K5Q4 zSG0deeN~G{6-332I#OkbhdSxl^0h7BV*o$*Y$Z@Wn7?v z<7k5^=MHMZ%zQ@TEH+P|6^>k4k!&5zqWz6NC(r^8iYWxrX9=56%B*#t5XdK{pn9*a z3NyP6)ON6C>w6er^c?b=?S^PmR!i=~?(5U}R*yU{vnOZ1pBIkHDtD!#-;&i>x_M9z*vj*UkZmIx%tz*g` zm$Z)dxBBrhzOeYiK__>y!=z@3UFIQM1|_%KAB=mq3H+q?YSlcv$TY}uycd-!dWlM_ zIruSkS@lY*@?}{8bpE~o(*;IPRhQRF6-Yp+H=UPje2#S4gKb(m=Y)@;^=V2!0^?ti zEWM_1hBjK#Yl50GJ1=i91A)sKPcjC0M@s%hO)m1OB!S!h%_9aYwnFgQIm|K z1q)&NB6~csKb`KGb@a?6Pat^hb-1fufl#!VaMA8!3j`PU^~;gt|@nryEAU}ey({>o=}qCbZ*QK@1g%K{rA}|J>|`jT;<{2%9#TApsefuAIO>55L}yu_ zqh+lq2j!in3|M{*JoQtPRSh7Ms^M>ib4>ZJ3p?x`Yis>%Mp#6X>?ME`^q0u7 zLvDav5;v)d6NK^8Z)uBQy)uFUJOX=QO(<75rgb+xlNbd;tAzm`wew~TA1!$T~1ICRj)GEAn~x?#gt-e0Sa{HY6zPhQBvpG6I- zhyIk?PdHz0?5_;L$;Ko%Vuoa}-yc`@N?gr={mMEDR0#chPJ}4l`?2W}8X)CwpsMB( z+cC9gAGJIgM_SOvfQjvX{vW-W*`JxQk}7Q+Q!yCzuf%lsM$*P$Xq;^H95NQyg)&Pc z3{fF>;c?}uNqe5K_k0i@I00ARWsksr;Mu;M{%DiGw?`11{==ykbuG;{5!oC)nbG?@ z$WYH%MSK7`;aDG+9NU)5->?6Dw1ty6l!9?02MmG`WfCL|AaqqJK5Hb5B|-MWq(`{N51a5h!~5PV ziK2T%Jl7n7j?XMXc{3J|iJ@I-5^1cBB~7R-ro`8BLu8Pd7U1nOd*v84T_e;~)N_E- z{OC4CL*Cc4=}_Mx?j1p1QSWmcme`Tqx$Zi(aVKH@d*{Rhqo@5rLD=16W!5Wh2c73fgqaaO2Xp&6C*LoMSdDoAS9jW*hwjo-mD-p-GW%H&J~J7x0ht#6hB{(arrw zOTkrX^=NQ+O>8U_W(CMQU`UGO@7<@g|4l26eTN2Y=;C;KKSdw77|n z>D|3_?ym93B!{6LD-VqY%p!V(2Ho#k2cCbg%Gu#NhUt%?LqiQhKPk7jAtacpaeq=! z`O}CiY%(+7Bzl&L18}-vKs8JbP?i0Ccpiz#>EZR*?&O z59*vHm}IOnmQqQKfi0L8iLs-)3OQUi*$Y7~IFNTJGEzsawx1fkh&JRP<56K!jD#hf zIf$#`&3Jv@bM_DEd8{^rXP8tV_;DTbyc*wyCn9kb(@yB@78;HrW&t;fOY$$wZZ(zI zQAQROz14W45fg+Qer$#>s@g~?wcU)G<0XqUF)xjhvzaOJawjV>E5I6apDLZ)dPoO) z$hvdb5Q@5-Qe!%?g+a+%WVkq@R-xwLmkW6dvUCKKKba&SKd3!y*)YxMg|HP*Jiw!w zqG}5iiUD+;tA1kia_Y}oDJt|4lFP8PeL~EJ3P0$2i!}QZnbN#Ct1u)?76aEE(n^=c z+ezf1M7O8lwUeA}$yQ*;+7|1~S0mGy7d`0?)yOo+$uD7Q&xXZcAXW)vNsS6IVAV`- zOBH*K#3A3C>m-r&y()JOkp@|8yQUp$h;&;T$c-9RHigT{_qcEv-U{{t|CV}IxG-nH zs-VZA?ejTiI#sbTbYOczYQSf{UpnbuH;jmpzc?VrZ=hQA=z$o4=OXdIxX=axooT1Z zPEGSs?ylXSXMmEY-;bNIS|%UYD?b4Xjo-t$1kDU<=6pgAa7^bxO$g*8%lA_8cX$_`Z} zJ6vCdLO!{u6|CmSNAzsm4l5@`?)wEGu&GkyzY7$qHDgvV%v5zY8V3t+^CHX25^Ln@ zMiiOpY)^sGm-Qn>y}ZGCh>DI-53%~*TsnlzIj4Vofq0;+K(26WQTuD;DwNY)Th{xz zu_~eL0Hm?Sa^hssj+*~$DY>4JY<^#y$$^JWnpLNUIHU)D9y!9~O&`|qoL3dkv1ZdT1kBijC*@@HU&GV^Q zU8>P~@|usfMA9!t&N!TL%AB|~!_a^gx!IYyy8t?Nd`%k3k5<4x6XPYYPg@plp+LjJ z30IRbhHw(|ePXX=CLP(wHmSaOPE$ErX0})}pWSh{!oU%%)hEv$o1QswjZKP$(%Ka$ zk1ue2J^soD)ZN3qt2k*kksM9au1bDU@odt2_Zm1H5 z&oIf1GF3_NQ^#MkVJqT7=)TYro@$(I!vQffwvb6HO1b{D>gfu)G z)avDEOl%mq@AK{t=^fAiM!QWNwT9g6OU?0o00j}fEI;iqI%SPhIH(sYMN?848-K_( zY6MSt2y}41e2#O;F>Ituvi;&{nZ8Jg{c=K!QvqzkN)X{{6VdK^9C6_;wjHn$&|XV( zHVCd^PDuEDo3Ym=EK=yOffAvcxSdwS%6U@rfxWE4`z>C zw=l3A2@f^nPbE7IFOyk2uG7*lo$bhK0IpLrP$88w4G|U06P>IMHvPLL$is-l&N=j( zKhkOVtO#~9YI2z3O~Xl5mp^%??w~Gxw6e%N_YIthMVWLenn#qdA9+6^oA6~*w{Q~% z$vsZU0s091S7q^Js28@mgl-Xy$TSwc9cr2bO9fAtw3WnT?QNCs))-=!5@ZT)M5Ki( zje!OFxAaLlBh#+xRuJ)dxCP<^9>Pi!x2epsTrmE&xqkg*q-=^GJDP_xSPxAb2kPnS z>TT)@&jRsX&Gn;V4s=XecB8Agxsy@GN>`TEQ{b8Lq?e0>QX$g2@o(hjf ztZzhy4>jHTn2CwlEHrin4I)u%9K>+j-*`vF^0P};-a_=qiXrg;EzT1H(*~3TN-cOz z18TnOVB2Ym1niGzgA;kJq7n5eT#ZC?F835F0Q%{J2FT_<=?%Lu=dr)7MYZqc)mc?A z=2Ab$yc&CiN|X_L#cmG<1TId{j>P6t$aHq&$n8*uk;UA(br8?Ip3mb8(pE|1+tZQn zlL=xZX@cF4*HO^9W5t~|7VBgtQ6t3pbOFHJ2&lnR$l3&iHq*Szgj|a_FDn6!XkrHD zre7Ofg)X|aiSjp5l`s!vI6U2QLWsHC8$J*tg|zf2qM%^nt@gOXi9v++3e{MQ^00g5 zga*jXPlpfNYTGl+sr$P1dA(PVq8PQ<1>U6pUGSR##mm8f@FxNt@_=j$;Y$NfZ{t*2 zsONbpu@YU_r2p{F`=sA|mOynVW|d1*=Qsi@Lf+Y9lD1P1dz2_QQDs`&=e7A4D?B*iBjO)0w_e z;Pi%!$S2}VO!VeZn69f~xLH7*`0n!Dm-jsI8M(QX*sD^B{+Y@512j``oGOA4;w_Yh zZFMm<8Y_ zWsUfA7iE?GI;g_Q1vCZS!|hIpD41LY%0&A=63}_pMxsj*p;Wcez-dhm(zxHjfq(^W zVY__!^JUhL3bo0BUJo^2Fo8Byv2%^kjEv?Nt!%`_8gF-lgMc1Prp zmOs+8cSV&*A%{ZB{f))ub1R6Ot^)=SCxg@;`I|nORFnbA$PjdxvbROXFWR~^KfP5G zZp}7m=c=8a{WKAIzBKO2+Vb?8Os#1A;-oHE2X3kmEK$*!F@& zF-QBaXj%=o``&yS?s6-^&dX~~6N=~1eyly8L@4@38|(wx6svc-VqFtLcp;uqTquuC z_A(D;%->AaipDB=QyvH-Nfm5p*Zu=PJBG30#5Gw!Nj~3S%)$c{q@;Z;+2Y*HoXIQ;}sp0i5NA7ZV!FpZMsef6w8}&)MLElYsgXamD0nD zV*8E%;D>v-$>|VZt)!fpe-><0qukm<9++hj;q~L|m*xDaw9YKGuOBQrO7HXutXnxF zQGTY@dPAX%uI2VtGmRUs)8#amJ{|4+7Z+a7LxBEgwV8g*=o2Z$H^cR|IIVqAU;U%P$$ia?)Dca%riZ~=F)0XPS}@bFX*%pq^8df#G#sm=2@zp8ths{U}=1A8JA!ytW zRhN`(?-LW=A^um~8boD3TXBTBobrH2GlawUGje6UyvoY^up2-0-q!{_T*K*i;r55V zY4x|I03>6eYx?L22JRTp$RAboG}WYGs*7Rj!m?F|yrE1A~Pkq@)0k1d~k7$J3+l z6U?g2@AckYmw`tPeY;f3{oPAX55Z2;u{_^_(vi{uoSGnJ67UH*?FG2=qksRJ1|q#Y zS;I6XZES&4L9aI%oW&G^-l5`&P(Ww)k35>R*?@nyBuO)Un}y=+Qkz|lUG8vL zixi(23i*d&eD6YbxyJr85srahiw{#XG~ulL!8=SZ3(YJMy){r{k=H=Cb)ej}>?HiM z(P)~Xk}GKo2m6$H46T~JtfuS)8%W)dP@dPj-ectf3*_LtU>Y()HG{BwSweR|AxwQZcnk>!$0dh~|v zxwV>s@+;mf%`(8^x5(@qedf7|_C_}KhjH6?+Xn@K$rBxArpp1f15MAVo+Ch7sc|+# znFcyD(xs~{uWwSeKNaG)-tAcr@EAGI!XYsPX`bk}NlET+?plq&Mar2*wc1Bz9d%T>jdU3(s{JE_Z}o=TL+q zD4FAVEBT6F`SX^dur4oOkUd=-2@H-edhu%DhU3JLhHAw@Z}P`j%JFc1D@0lH36Xe~ z6G=4+*&&R}U9+y^YwgUxP95h(~b#Uk!Lu&DgdT$Vb5vAUASSw`uO`w-Ea;{FBO z@M}?nk--QItIB3Klu&Ou7P|z>*AGH?y3~mal=!WTI~prdrUcP1?YdyKnWrI>I8?;N^LfBW5;FG1<${P2Fa;E(A*ZYanU2V3oEoTR?-p5~N& zxk;~pTm77kVK(I7rdY?t4he)-R?MWz@<$i`c+!y$JrAG!W{2F#g0BgOSkkd)w#tEu zag_xix@K8Qjc=(wr*dR9D3%ND`@X5ay>uFTu;jzp9jb)Hu=g1k5d@1Lrn}T51xuT~z;2NK-bWprFD{-kBQJ|(3S?iEqt%}LLtpnR_S z)KKrFrQvd$l;R?{P^OAe+%*}09dRS~!Ur6^BM4vrRFvNBY z8Vv0WPORUAF+-y@g17kI!f3O(+tISBnOyfJG@*5z(EZs-p{%=8#V?bEAI9htzSD0K zltq0|J7Q8JW~Uk2tB9=!yfnWIic9QN-i4ipgHLRdLY!P6^1csFf7O+~4(3!P|0Eg( zFa9_0$Igg-1oQ{z`6FL0j*n5VEG=O=e*ZeCJiiQX>`smB$u7hS+zOnWMkR~PrduGF zgOd#A`ep=vM4!O0A2(*u`Z`FpIi^th6rhF9-m_vxhb<{*(qoEk#mw@{Dm$7*Y1lkh zr9s>Ys3Wq0;#?0+DeU3Q$G~U*lS**4jQXMd!(iK`Csbn>^4!Z=eFWhJCT+1IJp6|( zNoM90JqxDa%xK-7upRted45&e``v{ZxUzRYMIM#^?MrB9OF+cDn__?b)WApgsW>4M zmdj1p=>EVtE*Hi5Ipn&?@nETuY`$)+ExS6KqyMH9s?UY?<7D*O^9h*B_fg<|ly#R2 zm>`8@>kjO$iyB|^nAG%utRsM%-jXm}L8F;bn$3|k&WFT7FE;1XBw1Bxu0WeeCtHX8 z%TLL*e$QaD@JqD~M?42jF>M&K;zIcJ%P0EHuh+wDukZq#|nIDmyGf2l|DOM&vJ!HFi&`6}C74Qsd zWMI)bghE$~Rs=8hP9_zI&X}Xt0If~IL!X6CcRiJqpLA6Dvjw|Yfh)K7z)<=?= zf*ss!l9d1Wz_RZ^7 z$Q7K#vlm&Q9Q4$6{zJfs-Y9YIid2A^S0FRGYZMy=7+mg3cwN* zfQ9}G{inPtC7ZuH$m|k6%-xRXdz5(XnbT7i!BL)0xt~E{bh0Et(%~8Y7NROZ{ydJH zGm&pLl;`t?OMf=Iv+;RBjI*R$nFIzeA0k{S3BnY8^d@vtI4Y7ACPJh?rb6mQo6a{O zi`-O`9nVR_idVqxa1agepcHw$mwF+{DGT{6uNNK8m+ZlN^Yw^GH_YO&cOt=hA^hTIR;e@hkHl%rvSllh>7U1z z=LJ8%GbDTI(p_!HM>r{49_{aNI2zBvlr8yC)W$Y17oG;SP$J+X=cx{$W7>9Mk>UtU znua)=5G|c@=il;etdNC~3~{+<&Y6tP%XdO=0+&W!+VWNLB4xcU@~54-%l-ltMfIy$ z$xBkhsEtg`uXVrjKOU9J!C|{{GCMThnr_lzlwYO%V9xI^ zbtW+ql$M6M^bX#qh}Jrr0vf`7vXt8zaphw}KIJ@z7x))m(9>w>*52u8S4b%y1pGni zg!Bt}88!4=%_cRr1cdUB{Ie#pskw)wwu1Af{LYt-zc3Ayt~|#rBi&#(!kt5B<%n#` zMfWmpslbe7W=}DmIoQu-{|Z@@X_XdO5XHnx#DSiQA+|E`c<6g99!b*Va|na(m@J|U zL7>#WZzV5J#oH1x)|8~Cs(ch<7gp!TF_x|z?!oj*j-0es-t0e|-JTh7G~bp&dTPR0 z;W4CC;yxHWk)}%9!=j!opg3dLmJPd_^H$v_c5E__BUTQ|fti%hsULrWeZ4e$=tJrI zAx~B0P5s$RZ-MwdOYMha_rdI2y~b(`f~X#Ut9<9=VV0qc0)6BA z*e|%VB}UN>cPo{UyRP}zp!11e z*0%^Lcjn4c&>1dejs9qUako$HvZ-9Fu_s5@UR=MxlKf|%#MX%E@5v&YtNNVE4B;IW zFO#pHIiA9S&XGGX6@M5=jFjNu4vu!8_nP@E(>>q~SFIfvu@a~s+2TS2?s0L887ki- zP7tPOC06iI6Ixys*#&R0hcJsP|1Iaww_6&9!hx6pS8cDx52VxEFW{0*aqG3Ckbqri zUlj5aFa>E?{q%&oNLZ%b!1?^UupBp{fn>Sp#1 zHZE{KZYfV8Qty+u-C_Vt&<3R)P6$>NF=u$O6^yZRW|1R$3NftT>1&mE)kaazACa^y zhyo^kMUqE`CbYw2PEczy%V#^>jRhl|boW`jHp%j0+#@Ciy2Efs@z!$~;?6M{Ub!Am zOAspLwR6z+e<$aF;m18vUYXPN>jDzTJ58F1i@jUBk=qnYi~w!nUjI7H0Nm|zTh9mZ zwHjN`pMf^C1!;TmQ3sPWD-5fuM6asN_^xs^+!fLhM3jTcl8PxKS{muF>`t)As|_R= zF6$ih;XP?pjFI$k51}`Jz47<_6aAGd|?L zuS3K>ykld$aI04YjF`Mk8m)(KJ(;DI96TSN`;RthN2q&~dD&vVhpM&~9Vx;S=XVqq zoop%foX?0pKdB(Pp!Hl`s&*j&fW6~SL!fI>Bmmf^< zn8wU`C-CZ4ENM8T>{Us@{hU!3OCGeBWwu;MZTw7rEbCO4txO$==?!_H#TlG66m#|_ zN&i8c&b`t5`{WuKn!MMI9o(C|woo}PP7+?G)wSL0MRtfiak#1prLMP+2L;_wsf1K* zXZuSck3IU`Chd`HVsRm1VIp}e3{{S9OW+{0wkEtzyLTYcM7l|Y3y1q~DmTK7R?nDd z;9mMS6N5V`EhUV}Zap4dzG-&z>SN>r5UfJ=&8o{gfq}%~{Tp(EvKGe%Pn=&LFZOVWi*3o?2os%dIKJG};_`SCB%UsG8|?i7Ro{(eeMCm%1DRQb8tONG{j#HK}b4m)|) z_lXf-*M?;V`L*Uq6_-m_&kEvmZ62jk2KnW3mFPv3K!tU{C$x6vQKUDa{POIK{DQI+ z<+8B(tWQ|tJ5zs`pr)!Ii^?MagR3)Ki3WlM)|FOk*KbByGQRFr#Dgn?gmjmyP03| zw67={@F^Z-OLV%2M#x_PZhLjcZG~^GqjcEo?qK<-3*G?@PK#a3A$@+>7Ik@Mskbx?F~j{u`WHI(+v{a$FDS zefF&Ti{UK-d1N!mV~=grZe6RAcKSK;TssVXHC@95i^&(ex%Ww?e+Vq1$KZt7%Bh)m zf4CSrs;3viTL2#{>RjR7uDNZO5hFVP+Zm|^cn3j@*gL~rfJ*z3vb##qiqUL|)@is) zV0$e*OSH7vM#0K0H{mNMBB58@3_#7#G*x+jm^H8A;<^3%o(4aJ^6{@gWc_BB^up(m zZG^@NIgb}%FVOXVBe!&h#t-fQk-A`YbHq2HepKF~o_nSC#kUo;dni{ErG=$G6I(x3 zv}JS>1IU$Ob*d!qDE(~j&)C?-etAIQ2F*EK{f^;_FC6`fb>$*JZoC^u1iDJcS#&55 zC@%PQdRiuvB!wehE^lKmC8ZNFvTzbF{}1EJ{YNo!q)??}BB0w1Vs-~~WC3iMD@RkM zN^ScO};eO*xT%zH= zm%6{vCDv;WHm)aj_)2WHpgv6)sQg5)Bp@tu4i7qr_j%@n$^8ObnGz15A0KAS0#Q{I zgGHFQTg^K!0cYnMnvd0EU_!Sg#1Kv|wZa6ZY@r8Bw9K6B#5^f^f?EbF6w1+)@^_+2 z+5#p8b0#Ew2P^37VUu`2MnjihVDi10-C;{R%liGKNHl?=6npKvnnQxwvfvCl2S&P=7aSIkN3-)Whk_du7q2t_ULUI})zrZEo) z1q70^lRTFE%D~tLuA6EUtpHQzpC9>7Ce%2_7R{Ou8@q#RlJOx*;yse5%i*_v&xc+M zN(;Yxn#A<{V|O#)D%0EVr{1^c6FgVSFX$m-Ock!U-s?KAgcN4KT@U*G+ab~}v!=ha zOV?ZKE1)#Vu}S|mKNADZ+W6%*3?{7W>gbRu4DKELyS)4`*k|mR=p*By92{HR`jTJK z^u{iky$h{352&F_=UK(|iE>+To|SpMNgGM9B_!dJSd%^6y-f+WJ|r%~^QJPeOPv-@q;#5c!8RT~FuPCPn&jXgG#ncL1PQvSf$ptI) zbXL~*=kZVTe3_Y;3+{J%Hmel&RZ?nEifd8QWo^I`oyujN{sun+N}cr-aEF#)4Th9E z>Kh6ueL7ci51a^+AdTYht-xMPBWLC%)$NF$hYbS@$F(6eYZY2m8HOd#LiuV&!^MD? z`mwx!mh2p*KpV;;cVm%vn(ItC6_C&fBTSVy`ROalV)8IgPXces;OJ?XJG0Q+NQKHR zf6&`!`AT%V{4aCpHH})h+xmVT)`?p|X{ire;?1QN<|MQGv@=I8LvILDZzz{seJ*Z& zY>7T>HM(DqK-#@2*0|=r=)AUxqA|zeD$fThjifbM9245DqX=!TGah-mmDXha8=-5w z9gx-4T`jtgbz5s5{gul^LHf(^nt7KJHxZc9V<7M08UEu|10&;x z)RT{6W`;i*mlU0IA&7W$z<89aJ}jwXJ*kM%OTFT;oYGOk_kuZWNJA6Qzu~Sxz?oiO zk3VVijS=(5PJxHd#~-&>1PMn+%#uWHn>z0g&JeMTaqh347Bz#5P;;d~2hK=p@|6Rv zf}|WV9?VEt=K2H2*>PxRKzI>2W(cf$0f@((>LFl6H=9AtN@IBfwYJSXyBVV2^%!eutC6;eLGpTq!p3&E2-xUB^w&GW_>TX zmV$RCw)JJXrT~DrkU9Du$L_CjQf{!SZv6xdeb6~UsqhtSv6%6 z^>?y~I&~2eHwBD}88CPoxsJK$Xui`BUX!U;J?-%KO)?HrD*9?Lhd8>dGmAX$jBJyL zg}ThaWT6FR1Sf@iytxdq2(%{ac7n7RP`2?4 z(G?TtuyQz+Msv_+JQf+my_#i2y*Cdbj)p ztOG}$nOO%0F@T)D*u8EsJPHdgTU(*L`Yn$1w73fMFY%?QyxYDNZ@ClH&>;;|IvjOY zJ3!UuV6hPeLbXdv0b(rM+Hbp!RZ4)_Nx=cn(c9)M|1b)oclJ=@v~aUZs=+iX|#ibARjbo zK4QQ0%(*j>$)gI~4{ZK*hel=xnU4Z%1-*pgfgTd!NK$%YO_gerl?kiv7gyKAW5|am zW$Y2RSMKyyY2)+hg%8jFolN$~eL`H<&+^SAz6QbQJQ>(*X157e)r{u8(+rJv9yXwZ zoe8|jnpT)LzCL+4h#^vAcYry{17L{dk}HOYh6EJ|rw364Mh*a>7(SmSFOen#MuyU+ zdUyx}Sb@Jm7E<8&$ieC^qD<)ex#X(yL9`90i?pp=HQ(8v5pD^w@H;9~HYZ}thdX~A zL?iOC!?ZF%Hymie+bAA4E8kJ0zqczFtVH3}N#j9A=lC+a(|FVPtu zl_hPE${NNqfSY&xnmiUv;e{H-19=5hkX&+2wYa+uuX+aHNaXHvO}|#7$ITVk9urDk{k6 zKmcfcKoF=Avg4&?mC~}D zMMeV6{t(ayJtlcWHWwQZI%A;f{bh_uE5l=Pc4O3YJ||w8NAPiuJ@^-^3iwG5bHP(( zs5_+MCOgv1qg&k6cJiZK3gW$Hgs?p{@%=lsatze8tp}P0cV=iCLKoYp(^de_h)7@>goEf4(yM;e5P~3L<=cwC+xQe_ig( zTz|2=+zW$T;|{3b_oy(X-*@Tm(l=Ju$@70t zX~G2i&GS*<_xZe=>qqc+oY0rm{hH91_v79z2=jAy8zT26Oc3$c1LF42Fx2*YeKX;8 z2!7bqb$q{E?x22gWz7nH8O}xv`f{3|#rk2xy%UBpzO{a@Y_)Q)QjR#HIGNCU>~lPtmixb|w$KN+zyWx|SR$P}LVC0KDDpX||a zrh4R#(DODkH(1+)XVIv!5A5@3samPwhqLs$qzTaX;m&}WjtpTE7QduClj>z-791-{avD^V{p=e&TjU ziM;nSmT^Sz+xX`t?&t0!e%c-%zla*M-d^U8HosYZTxsySjlz5L*W70+>HEA-wLx#k zh~L=t5~}TY-Zs5mEtyC4kS;=!y$Mcm6J2wpJk!u8=x{n)=50W>dXd>gGEZ}Dqnv~> zVBmU%RNagZNT_gNa{SRNLt|G_=1!~>zF6ea=j}DuCGfX;sZrHLE%60S>dA@4!?Tp? zH1<_LmC)>xCYfH9Y@F=*{ zkL65H*|Z44$7!i8dO#_rNaqrdZY$qN7Q2z&p&i<kJSfR1mQ>6eMO&MRA;4<3TM)tk#P$QDxp zPmJYe2na*HEZbEmriQ9lTT4yRkSe^Q(24xIW4X@?N+5p|>+B0e%HmNx3Zf(gka=wy zi6){j1wZ7d?_DcLoM-0P%3rU%GYRs!$}djFx~5mnKsm7Hr79DhKFfhU8`EmYjd!WT zUmOj)kGpSo^t%02GH>bA(c_^HSyn>3IX(PQBbPF_*fpbmJ4lIn-uTBkY37lKE(Oa0 zK)R~zwUU%&?}2I80g7ld`C&M^F(feS{YeK7)rtn!qw=pZX`zB(E_Y68BDZzM@Bq8| zjNWl&sXFhGP@6L9%#>i+20<0a#(}>}py+mywrHhL7P9jdJ_qfn9Q9PeLVY})S>5tg zv$4RexNiCPYz>y&(WV%c2L>#GvX5_(0=adz$ca#e{s~1iUNiT=};20qk=$5 zT4eo^8Z2pA;Ell6F8ZkGAyzakc1kV+L14e|AjZ^YT3L}^NIhZBI-m&})CmR%^|QY4 z{#tVFL$;vm736(ed@vRZ^??V2Ap#dTg}-Bsm2#xpj5z!6 zv80pf@oVSNFqZc8e8y{#N;?(2MNpfhb~=nTecd1ayj(fFs1kw$-is`))eiDKS*u-RHUvv-S782d!+<#6~m_}8y%%C9~zyUlgDt9zA< z!2-438PlS*1tY8^FL&zr5<2DhXAw%#WAENuCOm_)UUWO*$B#Z1Hrvk+Aq_aFkloIE3N3 zERzl4^1M^tcZ)(4sh;1)`N~A%{5oP4g3FGiG+@hXN0l>E>gU4>>O4dZv5K^p|07_P zhzcje_0Jhfsc&im2$2I)Y1RTLzDaKW>|8bfz18f^s(2ppk+a8 zCPpjY;jOVoCu8loNUY3|=zG6I6xc405KBAg-<~vW7IiyHzwAFT}6@G zRmRwM)e00v{XM_nOOg3SQAtpn?V&|9t99op#qAzwed7-@?u>W3m@I~<*8C}vJCSw~ zSpoQ6ZNsFvsYwM`l2!QWU->{SAR4IlI}YOuaYFM(|9HO}sE#d6J6wU2er>_YZX7z! z!|W>duvpt{0oTMUDv#530`poO3d84nCvI1j$URHevU4hr>H3n~|L_|2PcTrA+Ec-- z;dWd)MTCvC+x&eVGFc~&#H|(ENy6)saJfYEQmG=ZB_)sAJ4dzc6LqHAG6&W>r+Eci zhi$5m^(K$jq9=q%OFG=9!Qc6+-xo)bUaP&Ls0A|}I&OcWAc6C{mX!gR^M^_!VcNd$PXkYU$L9{$HYpnSrmLBD8^x_PBSo2C!A6ARr8?e)g<4%F!*I03jomNyVhv`YWsdM#0pQMWu9dk*fT0R=yhtnv?9zcGP~c zBPa>L{Mc^Sbf)*&(Ur66@Zx=xIKVkqKH%#0gE8!vIGx8bS|dK=uVfxZBn+=KTP(^y zvrXx0duz3J;ORN73!S{KyJfmGsx^0n9Q6kYh4~W9b$l7yTy|8Q*`ja7!<@L40D^w= zwyxa!6){Y_y@Y!bJGf^yzRf&^tCPkO%x{WL$ql^qc7Kh2e5ULoOR(3(R!#rR^WjIt zAc?p5N`5HqEGlZ&Qs91c4^6REUq+V~G_+Kc9!O_}JK-wN8&^YPEUy%FNGC#BeDaZW%FE z04C10A{ZkYDp%u%Sh6%X-7bNplUO9`=<>y7Rnx}FWd?t>N0l#6&zSx+7rY(2_pTFM zQ(H&x`lOx8#A%y;`{s?+=5LilAtrKL&^j3=*R*A3dbJ2n3$JZDI92 z7TgbX{qK|OI%OV6B4^bgr4)10kXqp$D7eAR$Z_SSPDd&OL4 z`i(GQyvT7VUn+9)){qTcWzw#NQKgu;ZTK;R&VGHXDBlSyYvh`0*_(3qw7NJZtOn zr(ARY-6zjl6<(pSVJJ3Rrt~~sOxTUa&Xx7FsNL*AE)j&k1S7QM={N#y#L$59ycF_~ zxLtK9{)td6hWPa|w%>C$<77%6qH?+a?3sQZmS&GF56|h()_F-in$Vs*X!(*- zc-1I`nlYMST^9F-AydVC2=Z@&c&kyb1OAOuVWemf@+k5Y&Cxrq?vSn1@f@KWd#uq2 zaL|X-3J}{cYUzwlHJC28rts~nf7^WENCL!vWYsJsUL|A=T_{X7PpMRqgj~GSuIj@O zLM`y$;+{H%?sV~d{RvS>jq@Wyj7cz)A_{M4enq@PNX!iQln;P@AUO+wCzM{)|JM4D zNy$QPRD4IZzKQsusS3@jMTkh6>4HODaQjifAK0s2qs&qd5)L@qFPnqo$Mny>7}&?5 zo+_ccTW<7)Bvwg3d^?Lop5_t1THXY7D3c_7Q>YUEGJ#P`$=Ex|B(Z!60&Z264RQlg z+3KlY(pYJtP`W!4LmLj7U$60JS9pee88K$}Jenj5mN4_+EoB^a^VpTTY6}cC3`hBu zG|Pmo-lxU&)U`o-B5di4gr0?D_t#t>27*x6B%iL9gf=L&K|WdiL{;asfySg^Bsu-> z-9W$m3gur4&zYt-{yDFo^RMgl6MocgGXQ5c-RS>b6g7t{G&3!^jJgfe&bJ(eCL46{druKT8LgCp+g*&0ki9gYBDO&@Av z8{HHF4%zx~6WL`V50c71Vv=b1Pz$(zs@Xofj@**-ATF`YFmtHHLtQ zYJ))Hp2yK)Jh^TTD*Ij+?tAgJ!dvPmCuwR>!JzNC8<4tTGe#%%8j@BBXtqEQfdf2F z8sNGOcPf%%bkv7sMku&fLUSZx9uiLdV~!daqe+U1n3t4{O)X4mBEvNyi+HmtTTuAa z)E<;n6zM~xqOh-6sw826zlZ$5N>r)GE~C(%mGe-8onZ*;2-JqXYl@yHPR3(%3q|T@2jk$vVSf03r$(vHCY!5A(sU!{&8Mvkc|y%t11t}PYN$_$mpp?x9*oX67Syr_LY zevpy&1Vp#X`WC2$xPu}U5bF&l>xg2mu0`mPaPuuTJc}{OIaWmz&|cK=kLHx62+^NQ z%783KKu6aRDv2%hhAO8FPYI`)OkQ6rZ$w=v(ZF_e-(AE~j7T_Twk3J7JtB@yPrHl` z+zuE>Uie5h0Zj(YXOfBrJtPc`!d(SYLokYRb`XszQrH%h)?Y=GBMz^051OwY_x*~f z$^AhB!9RAipf>2{AP~zMalgx6plc#OkD=*2*nuL-2|B8=m0`iIR*8rQP;gN=U%jHk z(r4<@YrCpY=`tk&VePQ1cfVIK;ldra>SQ3NpX^o>{^nK9regmlOB|IT)&!wFYLdnS zJQqT0Z4eX6nA6DHp(2W91O${0JL9M(`J)DVkwlcCGcF4 zx7AqL$iW%pw10gZ*+$93#3%)dvPhZot4h_hEaV>#uqoBC<9LclmN>)|opfOIh_N}` zA}^-2&BS%moI7BM#j6Zov^1B72p2L-O0ZjO5XT@%YZC(O>INi#}tF@nP-h? zzwU#h;ANU4vVM+IMGG{G7j*v^Lm1RKjEY#KfK;a<=-iBH zX{Q6bKqPfaavabH+!+5t1xAIodJB!TIKG|;O`!WE8gDafuZn1%9sn}z%PC=21>30@ zIMez=tW=YIklc96jCVKz0_h=64Y~?HeNc?84UVE{KFl0Hm1mX8JKbblO*utl|*0dpdyVXw{T?#hR+zupuf-qGe%sl zX2p*@tUp|I8VG97-3yNfiYUWbb9naVXQ}@iWfd?V677d>>U%iwUM~8y*UcT#>i57B z+0<3sO^#9E954kcfoA03yaO?N2E1DiEQ78xlh+nkVPiD2C&VKWC><6Lw@M%*`;kPH z6F!oKz4u~Ii9Os*(UrPH|1-pIG4ifp9w$6fVTm{k>>( zAkE8kp9g8Wvq3{SyD~>*fP_`FT^0MZp!p|B6^5!M1EUqfR%+YrGfl0ihGV2zeN9iU zW`<;cUpIHU@|Hzp+gO4ivw;bMr z5LR3{2-3bzH+TPvCnqcU^C4(+_0O6}tAu#Ki{t0t*bFG`h?<+He? zBi4&jWex^)!9fpE?PB?9EbN>_eb?CD(wGBlv9stvubEJEvM8z3aB-BChd~5{l7C() zS#fQdgzie!K^7#qT%5ns-=;n#Ewg^>wk|G{8hbnDArxhw$U$Ht<|#+Fmbr3S$y z1ZYr$A`OpA=aQE+YRr2G!SfNHP<7SjB?WQ9LFfbeVq(=QHyP)0p2{{EXa6$5AEd>s zQbjg-g6)^GH6bw=$dT$AE2eQYvQc9Tq5AmKleKsV>nya!E7Yfh(tnreSy4gv4sZ*%YEvhB7rsMH?Ng7#3HT zfvPxYZc9g@5Q+u@Mn-^oVAdF+Jlz zDsayxkZTW;O_>>F*{yn1a}0etQoU6Ix>Xtc97f^JRb3WLTw2#qLP!2*VXxM78Bz;e z&Vs7nwQ3&7T0S^n}cfetrer`@`DS_ax;k9k1h^T?(KH<>SJCX3b$cVLu*>M>C zM#zPjZ}-OkSJqX2MFDtOqL38orTf>?7 zBRT18Iet3nOh~>IPun4p2fbZsfxIx-03*WLkX^`ABfXTD)1d+TZ(i5}-B!Z@QAUPp z)CeBJKyWj~N-e|~9GEyEKo@qCb~Gzm`+z2!LpGY^=+NB{43kO4mobsWdAHd*hVPC} z1xO>XAy4gZ-02NuFAVU=ZF?$B)U)sa1hWW=XO4`hY1nxPq@-lR3Nn|MqTLq7QcE_= zpYNVBR=S|j;l98urx0SaSyzNK{3d7lqAPU6zt9?kB1^PPg|8|S3Q80Yu=mvene>HF zrJ*2dj5%6&qbtszz7(W}W43qEADRVXr%K*s(0T8yWZ=~;rD2fvz_h{ryfwkC=3pg9 z3XQ+55B&8`$wFc*`;B!cStuUgdHNsfKHmE8YE$)l8#*jj`qXR{ScI9TDCMSyi6fiD z6Sr8}kOh)Y05|0~dU8H^KP`xivA_FV;Y7a+DI~?G6szZhR5nra?s^V*zewm5FJH1Li(MsevT5lRg=-Z|;F$RgB{I^r8J#L4$PbJXpP&kdmo-WpM?z9xF0sD1Xz zs!5@a{&|kiXUd{)L*<)kEA(rR0c|eCPijX5=IKkufADlQM=aYw@VMN|Sd@Qr&(hk@ z@FhR=-SpTlj_P7>-!KXn_DRRvvnR_o$zMIG!wiXM@d^|W$BXQUw2okO{>gOh^aq*l zlA-H9pV7Pe3i1yut>jDRIhqYoQ|;N=tm_wJ=s9^@avPlX@%^PU8se{c;A#3h06#U* zH=Tr4&OLGTLoG{yV!VWc*aC&OfX!@mu7Kl7+PTYMp~n@MQb>pcMSp7*J6TJshN*80 zgI2fHLz0KDi#!)kmimcEGFUR{ifg8)+y|DZ1mQ-)wp234(D)?zX~jPR)&*qj3Lz=y zwF27Ic9|Q?atabR1%(q~?tdjEWmKnj(_1;J1w!r9HdGFX-gTf#b65eV2+FgBKDiDt z2>@VpxytTjC~(eWOV3E`9M~;B6O+mfjM=@FgpA?ajJuH;ZmK@VX^QZoW4a}^93E^R z+!cpXN@#&VPdemd*5poeq=K_w8Tke4L{q|)Lww0tT3E?GWC4|sB} z%}v)a>JddtnfY!M5wE`%0}e?dN(zL;zd&x8%13mrscYlFS!^#QR3~(*VN55w$Vy$3 zvR3@czxsMjiZj);bU+!fz4mlPzPTo3&kqf5aQ~ydO1kTiIC;oZ zccvdWkT4?{t6UAq9fy*?uIDG$rSdXNVv35fnt~qP-tCa0A25e$T`c2W&Zbv*f-KBK z5ufy-E`rW4TngUx=NKA zRjnR{KAPXxYo@>kXcFWXx&9&AR<4H>HxGo23}+>iDqP3G&}8%b?^dS}Zt!{|u9qs^ zMZtG||KV4BWopbpVm&h)UaV>y>$clmGC$-D^r%1MlW13hZvBGRY3X>L#_Wd#xkn+n zhGSZ30Ly7U&3*M|%(&mmfCEtQs9tg6RZCp7m;)JdqwhoeOz;x~-kO1=#9vR$NaMq3 zb{~vKC4tgdJ>a4G&jtLXV9B%1l@1Pf$(rmNTp!3G z;W^2W1d0K|`sL3q^f4xNaazH=GTR4IrBP)A=U8Y|5vfU5|GyB!{m8c4FI(k!*>gWy zsmEm^niUkxX&q|RG4MsSS;oy%?JJ2@k~!pz(+(GH{8oXz3z|c-^Q!wpY;}-G*Lmn2 zafPmVIs;0&aUsVq#((Ny@M~~9w@}O935CHQ1{nq{OWo`FeCdKHDAC4o`3#%anRLQh zbS$i{9)JE{IffGjGnT01;rj})s2TzZ++-40eN(X|6}C}`g0OJ}NmwQ$ai4pF*owR9 zq-AbgCjLxF_CHjJASM?NpY)D}fJ!E@3siC@d@T4%tzH67xaJJsUvPQg{u)A48>$|sUWVapg2p^lfBJ zvdT)3<*Mx!wYSXVDIERl(|V1~%V6~4WayxQjNdmS3J;yv5;c@SYy zjW}=dH3+hq+uG;Y4B0!mIU`pfgzcwLfTntEkK@Etw1_>*YHBfwpWAj`VXJ2;fKpf9 zQcNi7$s9-aX{up&=?w2>1h?Yu=70&Q}Ddhs?SWX!7s22`}LyV{>2D^iV#+|{$BYOw3sSsB`pH@^LhAVfX=n9 z=+n_}=7D&a>-H&24IyUT;Ss|c>3p9{a4kC4b+Bib1iO7`m7HtegAcEi>eTyEDaDz) z>Y3D1GJW^lsiRimc+I3}7TJ%8&A*xeTnT_o#|heEbA;Z~S^i5?T4@U*$o->PpyhOE zagKf}6`6&TG|&%R1v*Z@@inad^SX%(XZZ#3{l`wjYKulpdF7)dL(Z>^MQhWEy`qvz zj&sQKJc^fOU~Uvj#B{ZhQH&wx#3wJL&K0hNwD#%0&GUxb7XTF1zR(c=8uR_`kZsz& zJmnUBqrdObNg+IJ1lgI5rS2MQ7HaCYEkxMwR=X*%j1c$DWBZu3!x4xLNn4Bb((EK}+R;uAL4Q0^y34=?$K!-Bv5S|VZJcMH?f0-&{N{f@R+H)-3b!eW zVR?Gz#5pD4*xM1wasJXj#`4)t^cHt{NoMO*XtUBB?pnEiHgKqt`7+Q@G}Z`bNH-R( zZLiV80AH|DJMlop6Z;zmI>$f8?~v>))Xson%N+x~pWs6dMI1F5ix++Bd4aJ(_-75p zF}GpQS(Vf|4wuq>6>+l zCBoMT1TLupPt^NI<}9*|uc{DlAY0L&h z}^KV&#=ynBkU_!ruq>OEVfr0+mcWvy?n)%~AruPXP%&ZY!Zdbd9?< zXgrS9-5;^6wy3I)|JZ%yO1)GWUDI_Tc=z%4{7T$t#`Bg_w8+o!~y>ZswRsCgDqSX+ytxJGM7>gGJOpl zi~k0FuQhi-*XU#7mRx&G=~zFA5X%0ZDa$l7E{S3=Ki{lE2?Q8W@j=J;~gKJ-R(5ZDQ z!Jd=MbOx|``}WH&i9YaWn`bic-VlzQmxI);1M&iB7WPjmHp#HAO9sUF2Lj_fEV@Ui zk4;~Dn z4YT)NyUMW~(Mae%+r9u}hTYmefa(w}>n;SDzCt>&64NN6RzFfS8`2T-6eyX}1>-G^ z#W%;zqRohQ=%EBns%y~7vC)T_{pP1Zr>CnGJM}7k|IW67z8ex`Wj@-vn?k+!%Yxjg z#!I_82brkFCHE>MBq!yaN#SgaUGLGV`Q&pF-@VAa=IlSw&;KxD*E|n~*YI_Q72xc0 zWS8LK!f^uTXGG0EZVV{g*e>WgF|-;TQ%rcXQ%If|0bGeh->s!EW5BQ$wit53ev{NL zu*Bs?Y4VSX=>|m5c=7Cba!jR7>lbKv8LY8>pSWAUh6?y;uzkyST76d4VjddNXgTkg zH>2QQ%^Qt#GEih-2JwdS98p*n6UVtSZnP}T6jkH)70P`gFI3aj)w_C0|NY*=rLXBU zjGwCd1E&S`5wecMX=MH1yv+F``&FCG?C#JbeNJLGIj8tCd}~-T$P0O}P{f@YuyhJy zQ>ht^JRiG{4|JVRQY$rMYwhNf30=U zd&c$f`CSubR#Pa5xb6Fm>FazUM!TOpeiplVxiTFDh5wm9;d3p&c1Sz9^F3O%GMjFr z9uLa@ljc^rR>R}AM7+~q4zu`>fYBBdY=R(s&Uba)@x6|?MC3ViSu^Dop=`GZyZy*i zS$cz6jaQr+3cPi7oGLXnu&exESm_3icf1(hryAsq z+JS_e;`<>eM2ZTI;E8k(`g8}n24|24++z*a zuXAIas9gZBIe|Lw!A~Iu_qg}N4lJYn}X6(g; zCupq`zJ|>KtEf=jsiH9&%(uZD2T=$fHKGsUU{dt#*YoH-EZA4hq2QI%M%A7=k3n@k z93SzUC<-^_m?m+m+LE_JjUrhd1q^^AUI;$27@?DoUBMy=T-Y1Y$Zv)ZX#9r?rz&J&MP`e05^n8h_BV0LMpds=r6+e-7MX+3 zqdbAiX~ZL5W;@}%Q#Z3DKC3Hl6V&T(HcG7k(2A-f`JASh$CheF;)0(n60AU5BDP$% zu(&mQsyH->FX_f&ceFiGzapHLR5|}~cYl9S%uVAcsL6P)N8#J6r5`3ISYMxRKMq5g zJZH1gOY5KlpAJWoqn#yb0cy_|$L{Zn*`8!RyJax)5Bjq_tP9Z5g7R7&1Yqr4KfAy5 zr%b0w?4{bI)$p7bf+4A(YCf(Usyug9;MA@0F5O z@8Bui`+%VdFP@9jvz?p574g)1A^)2O8q*xuUOf3AkFoaq6pavaIuf>jdE?{ivSVVl zf7;;jCUKlMD#eQmV!-a~x0x2T$;C+N-beRf7sVQB8EQiw@r;j+G0fxw9vZ5Qk9H5c z61rHmC?Y;to5r1Xi?*Z=uuY;THXBa=Oz4koCi7}fPBPSJu!HD}OBzIy8abQph2AGg z@No41Uf8HSqSNR(&7Fznqup$tZS-fI`^e&rN8oyo6~CL(E?SJ-VSu<@ZHxSp$6P62 z>A<*`>PK dict: + """Restore synthetic captured rows with all guards reinstated before returning.""" + assert name in {"no_pre", "no_post"} + encoded = ARCHIVE.read_bytes() + assert hashlib.sha256(encoded).hexdigest() == ARCHIVE_SHA256 + body = json.loads(gzip.decompress(encoded)) + assert body["schema_version"] == "workstream.policy_cardinality_history.v1" + snapshot = body["snapshots"][name] + assert snapshot["source_commit"] == SOURCE_COMMIT + assert snapshot["revision"] == PREDECESSOR + [approval] = snapshot["tables"]["project_guide_proposal_approvals"] + assert approval["request_json"] is not None + plan = approval["effective_pre_submit_plan"] + assert tuple(len(plan[phase]["entries"]) for phase in ("pre_submit", "post_submit")) == ( + (0, 1) if name == "no_pre" else (1, 0) + ) + return await _restore_validated_snapshot_rows( + database_url, snapshot, expected_revision=PREDECESSOR, + ) + + +@pytest.fixture +async def historical_policy_intake(postgres_database_url, migration_lock, monkeypatch, request): + """Upgrade coherent captured custody before testing current intake refusal.""" + import asyncio + from types import SimpleNamespace + from uuid import UUID + from alembic import command + from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + from app.core.config import get_settings + from app.modules.artifacts.service import ArtifactStorageNamespaceSpec + from app.modules.authorization.runtime import HumanAuthorizationContext + from tests.conftest import _drop_test_database_schema + from tests.migration_fixtures import _config + + monkeypatch.setenv("WORKSTREAM_DATABASE_URL", postgres_database_url) + get_settings.cache_clear() + with migration_lock(): + await _drop_test_database_schema(postgres_database_url) + await asyncio.to_thread(command.upgrade, _config(), PREDECESSOR) + seed = await restore_historical_policy(postgres_database_url, request.param) + await asyncio.to_thread(command.upgrade, _config(), "head") + engine = create_async_engine(postgres_database_url) + factory = async_sessionmaker(engine, expire_on_commit=False) + try: + yield SimpleNamespace( + factory=factory, + actor=HumanAuthorizationContext.model_validate_json(json.dumps(seed["actor"])), + task=UUID(seed["task"]), assignment=UUID(seed["assignment"]), project=UUID(seed["project"]), + namespace=ArtifactStorageNamespaceSpec(**seed["namespace"]), + ) + finally: + await engine.dispose() + get_settings.cache_clear() diff --git a/backend/tests/historical_revision_material_fixtures.py b/backend/tests/historical_revision_material_fixtures.py new file mode 100644 index 000000000..934db0ea6 --- /dev/null +++ b/backend/tests/historical_revision_material_fixtures.py @@ -0,0 +1,137 @@ +"""Drain captured multi-image POST custody; byte transport is a bounded test port.""" +import asyncio +import base64 +import gzip +import hashlib +import json +from pathlib import Path +from types import MappingProxyType, SimpleNamespace +from uuid import UUID + +import pytest +from alembic import command +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.adapters.artifacts import post_submission_materialization +from app.adapters.checkers import evaluation_coordinator +from app.core.config import get_settings +from app.interfaces.artifacts import ArtifactObjectMissingError +from app.interfaces.external_services import ExternalServiceAdapterIdentity +from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits +from app.modules.artifacts.preparation import ArtifactPreparationService, ArtifactScratchManager, HARD_MAXIMUM_ARTIFACT_BYTES +from app.modules.artifacts.service import ArtifactStorageNamespaceSpec +from app.modules.checkers.api.evaluation_contract import PostSubmissionExecutionRequest, PostSubmissionExecutionResult +from tests.conftest import _drop_test_database_schema +from tests.historical_submission_fixtures import _restore_validated_snapshot_rows +from tests.migration_fixtures import _config +from tests.test_checker_materialization import _limits +from tests.trusted_intake_fixtures import LocalIntakeAdapter + +ARCHIVE = Path(__file__).with_name("fixtures") / "multi_post_history.json.gz" +ARCHIVE_SHA256 = "acde3375a3e96603868480fff9ffbb4492fe62ef3a89f9348e2ac9caddaae552" +PREDECESSOR = "0068_issuer_profile_email" +SOURCE_COMMIT = "94334ccf4085c26c7bfaa054465fc05cfbdad1fc" + + +class CapturedArchiveStore: + """Only exact captured references can be read; no provider qualification claim.""" + def __init__(self, namespace, seed): + self.identity = ExternalServiceAdapterIdentity("artifact_store", namespace.adapter) + prefix = seed["private_prefix"] + "/" + objects = {} + for item in seed["objects"]: + assert item["key"].startswith(prefix) + ref = item["key"][len(prefix):] + assert ref and ref not in objects + data = base64.b64decode(item["body"], validate=True) + assert len(data) <= 1024 * 1024 + objects[ref] = data + assert len(objects) == 2 + self.objects, self.opens = MappingProxyType(objects), [] + + async def put(self, *_args, **_kwargs): + raise AssertionError("captured historical store is read-only") + + def open_source(self, *_args, **_kwargs): + raise AssertionError("historical material must use its exact retained replica reference") + + async def open(self, reference, byte_range=None, *, operation_evidence=None): + assert byte_range is None and operation_evidence is None + self.opens.append(reference) + if reference not in self.objects: + raise ArtifactObjectMissingError() + data = self.objects[reference] + for offset in range(0, len(data), 65536): + yield data[offset:offset + 65536] + + +def snapshot_for(roles): + encoded = ARCHIVE.read_bytes() + assert hashlib.sha256(encoded).hexdigest() == ARCHIVE_SHA256 + body = json.loads(gzip.decompress(encoded)) + assert body["schema_version"] == "workstream.multi_post_history.v1" + snapshot = body["snapshots"]["-".join(roles)] + assert snapshot["revision"] == PREDECESSOR and snapshot["source_commit"] == SOURCE_COMMIT + assert tuple(snapshot["seed"]["roles"]) == roles + entries = snapshot["seed"]["request"]["policy"]["entries"] + assert len(entries) == 2 + assert tuple(entries[0]["configuration"]["workstream_evaluation_context_roles"]) == roles + assert entries[1]["configuration"] == {} + contents = {row["id"]: row for row in snapshot["tables"]["artifact_contents"]} + replicas = snapshot["tables"]["artifact_replicas"] + for item in snapshot["seed"]["objects"]: + prefix = snapshot["seed"]["private_prefix"] + "/" + assert item["key"].startswith(prefix) + ref = item["key"][len(prefix):] + data = base64.b64decode(item["body"], validate=True) + expected = [(contents[row["content_id"]]["sha256"], contents[row["content_id"]]["byte_count"]) + for row in replicas if row["provider_object_ref"] == ref] + assert expected and set(expected) == {("sha256:" + hashlib.sha256(data).hexdigest(), len(data))} + return snapshot + + +@pytest.fixture +async def historical_revision_material(tmp_path, postgres_database_url, migration_lock, monkeypatch, request): + snapshot = snapshot_for(request.node.callspec.params["roles"]) + monkeypatch.setenv("WORKSTREAM_DATABASE_URL", postgres_database_url) + get_settings.cache_clear() + with migration_lock(): + await _drop_test_database_schema(postgres_database_url) + await asyncio.to_thread(command.upgrade, _config(), PREDECESSOR) + seed = await _restore_validated_snapshot_rows(postgres_database_url, snapshot, expected_revision=PREDECESSOR) + await asyncio.to_thread(command.upgrade, _config(), "head") + engine = create_async_engine(postgres_database_url) + factory = async_sessionmaker(engine, expire_on_commit=False) + namespace = ArtifactStorageNamespaceSpec(**seed["namespace"]) + store = CapturedArchiveStore(namespace, seed) + scratch = tmp_path / "historical-post-scratch" + manager = ArtifactScratchManager(root=scratch, limits=_limits( + aggregate_reserved_bytes=4 * HARD_MAXIMUM_ARTIFACT_BYTES, + maximum_files=8, maximum_concurrency=4, + total_deadline_seconds=60.0, reservation_ttl_seconds=120.0, + )) + preparation = ArtifactPreparationService(manager) + captured_request = PostSubmissionExecutionRequest.model_validate_json(json.dumps(seed["request"])) + try: + service = post_submission_materialization( + sessions=factory, store=store, namespace=namespace, preparation=preparation, + intake=LocalIntakeAdapter(), archive_limits=SubmissionArchiveLimits(), artifact_deadline_ms=120_000, + ) + async with factory() as session, session.begin(): + envelope = await evaluation_coordinator(session).read_reserved_evaluation( + project_id=captured_request.project_id, task_id=captured_request.task_id, + submission_id=captured_request.submission_id, request_id=captured_request.evaluation_request_id, + ) + assert envelope.request == captured_request + yield SimpleNamespace( + factory=factory, namespace=namespace, store=store, scratch=scratch, + preparation=preparation, service=service, + request=envelope.request, + first_result=PostSubmissionExecutionResult.model_validate_json(json.dumps(seed["first_result"])), + first_submission=SimpleNamespace(submission_id=UUID(seed["first_submission_id"])), + revision_preparation_id=UUID(seed["revision_preparation_id"]), + ) + finally: + manager.close() + await engine.dispose() + get_settings.cache_clear() diff --git a/backend/tests/post_submit_materialization_helpers.py b/backend/tests/post_submit_materialization_helpers.py index efc6f13c6..f9048e722 100644 --- a/backend/tests/post_submit_materialization_helpers.py +++ b/backend/tests/post_submit_materialization_helpers.py @@ -1,5 +1,6 @@ -"""Real verified admission/Submission fixtures and controlled post-submit authority.""" +"""Real source intake/OUTBOX finalization fixtures and controlled POST authority.""" +from tests.checkers.external.support import pre_registry_spec, post_registry_spec from tests.trusted_intake_fixtures import LocalIntakeAdapter from contextlib import asynccontextmanager @@ -12,14 +13,12 @@ from app.adapters.artifacts import create_artifact_store_bootstrap, post_submission_materialization from app.adapters.tasks import submitted_bundle_port -from app.api.deps.authorization import compose_hidden_submission_creation_command from app.core.identifiers import new_record_id from app.interfaces.artifacts import ( ArtifactByteRange, ArtifactProviderOperationEvidence, ArtifactStoreNamespaceClaim, ) -from app.modules.artifacts.api import SubmissionBundlePreparationRequest from app.modules.artifacts.models import SubmissionBundleAdmission from app.modules.artifacts.preparation import ArtifactPreparationService, ArtifactScratchManager from app.modules.artifacts.service import artifact_storage_namespace_spec @@ -32,14 +31,17 @@ from app.modules.artifacts.api.submission_manifest import ( build_submission_manifest, ) -from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.tasks.api import SubmissionCreationRequest +from app.modules.tasks.models import SubmissionDispatch +from app.modules.actors.api import ServiceIdentity +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata +from tests.retained_material_fixtures import _foreground, finalize_retained_intake +from tests.artifacts.test_submission_pre_source import _source_runtime from app.modules.tasks.api.submitted_bundle import SubmittedBundleRequest from tests.artifact_store_helpers import artifact_admission_limit_settings from tests.selected_policy_fixtures import approved_selected_policy_fixture from tests.submission_preparation_auth_helpers import install_submitter_grant from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test -from tests.tasks.submission_lineage_support import _seed_services, _verified_admission from tests.test_artifact_admission import _settings, _context, _seed_human_actor from tests.test_checker_materialization import _limits from tests.archive_fixtures import byte_source as _bytes, submission_archive as _archive @@ -65,6 +67,11 @@ def open( ) + def open_source(self, source, **kwargs): + self.opens.append(source.location.object_ref) + return self.wrapped.open_source(source, **kwargs) + + def archive_with_modes(evidence_path, project_id): """Build a valid packet with independently known executable/plain members.""" data = _archive(evidence_path=evidence_path) @@ -86,7 +93,9 @@ async def provision_material_services(factory, *, artifacts, checker): from tests.checkers.execution.support import provision_post_submit_service if artifacts: - await _seed_services(factory) + for identity in (ServiceIdentity.ARTIFACT_MATERIALIZER, ServiceIdentity.ARTIFACT_BINDING, + ServiceIdentity.CHECKER_PRE_SUBMIT, ServiceIdentity.OUTBOX_DISPATCHER): + await provision_post_submit_service(factory, identity) if checker: await provision_post_submit_service(factory) @@ -103,14 +112,12 @@ def _archive_facts(data): return inspector, manifest, files, digest -async def _write_current_submission(factory, context, request): - async with factory() as session: - return await compose_hidden_submission_creation_command( - session, - context, - request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(request) +async def _submit_current_source(factory, context, command, metadata, data): + return await command.submit( + metadata, _bytes(data), actor_id=context.actor_profile_id, + identity_link_id=context.identity_link_id, idempotency_key=new_record_id(), + declared_raw_bytes=len(data), + ) async def _read_current_request(session, facts, created, data): @@ -131,7 +138,7 @@ async def material_fixture(tmp_path, database_url, **options): async with _material_fixture( tmp_path, database_url, - write_submission=_write_current_submission, + submit_source=_submit_current_source, read_request=_read_current_request, **options, ) as material: @@ -144,7 +151,7 @@ def _material_storage(tmp_path, provider, storage_settings, scratch_limits, post elif provider == "minio": from tests.test_s3_artifact_store import minio_settings - settings = minio_settings(private_prefix=f"material/{new_record_id()}").model_copy( + settings = minio_settings(private_prefix=f"material/{new_record_id()}", buffer_bytes=65536).model_copy( update={ **artifact_admission_limit_settings(1024 * 1024), "artifact_scratch_root": tmp_path / "intake-scratch", @@ -175,6 +182,23 @@ def _material_storage(tmp_path, provider, storage_settings, scratch_limits, post return settings, bootstrap, namespace, store, scratch, manager +async def create_source_submission(factory, context, store, namespace, settings, metadata, data, + *, submit_source=_submit_current_source): + """Commit exact archive bytes through foreground acceptance and durable T5.""" + runtime_root = settings.artifact_scratch_root.parent / f"source-pre-{new_record_id()}" + runtime_root.mkdir(parents=True) + runtime, errors = _source_runtime(data, runtime_root, "completed") + command = _foreground(factory, context, namespace, store, runtime) + receipt = await submit_source(factory, context, command, metadata, data) + assert not errors, "\n".join(errors) + intake = SimpleNamespace(operation_id=UUID(receipt["operation_id"]), store=store, + namespace=namespace, settings=settings) + submission_id = await finalize_retained_intake(factory, intake) + async with factory() as session: + dispatch = await session.get(SubmissionDispatch, submission_id) + return dispatch.result() + + async def _create_material_submission( factory, engine, @@ -183,7 +207,7 @@ async def _create_material_submission( store, namespace, settings, - write_submission, + submit_source, *, provision_services, provision_checker, @@ -205,35 +229,20 @@ async def _create_material_submission( await seed_started_task_for_artifact_test(connection, params) await install_submitter_grant(connection, params) data = archive_with_modes(policy["evidence_path"], plan.lineage.project_id) - preparation_request = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - context.actor_profile_id, context.identity_link_id, ActorKind.HUMAN - ), - request_id=context.request_id, - correlation_id=context.correlation_id, - task_id=task_id, - assignment_id=assignment_id, - predecessor_submission_id=None, - idempotency_key=new_record_id(), + metadata = SubmissionIntakeMetadata( + task_id=task_id, assignment_id=assignment_id, summary="Completed the required project work and included evidence.", contributor_attestation="I confirm no confidential client data, credentials, or copied source material is included in this submission; rights_confirmed. " + " ".join(policy["attestation_terms"]), - media_type="application/zip", - byte_source=_bytes(data), - ) - admission_id = await _verified_admission( - factory, store, namespace, settings, context, preparation_request ) + created = await create_source_submission(factory, context, store, namespace, settings, metadata, data, + submit_source=submit_source) + admission_id = created.admission_id creation_request = SubmissionCreationRequest( - task_id=task_id, - assignment_id=assignment_id, - contributor_id=context.actor_profile_id, - predecessor_submission_id=None, - admission_id=admission_id, - summary=preparation_request.summary, - contributor_attestation=preparation_request.contributor_attestation, + task_id=task_id, assignment_id=assignment_id, contributor_id=context.actor_profile_id, + predecessor_submission_id=None, admission_id=admission_id, + summary=metadata.summary, contributor_attestation=metadata.contributor_attestation, ) - created = await write_submission(factory, context, creation_request) return context, task_id, data, admission_id, creation_request, created @@ -242,7 +251,7 @@ async def _material_fixture( tmp_path, database_url, *, - write_submission, + submit_source, read_request, provider="local", scratch_limits=None, @@ -252,8 +261,8 @@ async def _material_fixture( contribution_awards=(), human_review_required=True, max_revision_rounds=2, - pre_submit_registry_spec=None, - post_submit_registry_spec=None, + pre_submit_registry_spec=pre_registry_spec(), + post_submit_registry_spec=post_registry_spec(), post_submit_configuration_setup=None, post_submit_configurations_setup=None, post_submit_specification=None, @@ -265,6 +274,11 @@ async def _material_fixture( settings, bootstrap, namespace, store, scratch, manager = _material_storage( tmp_path, provider, storage_settings, scratch_limits, post_scratch_root) try: + if namespace.provider_profile == "minio-v1": + async with store._client() as client: + await client.put_bucket_versioning( + Bucket=settings.artifact_s3_bucket, VersioningConfiguration={"Status": "Enabled"}, + ) plan, policy = await approved_selected_policy_fixture( factory, namespace, @@ -286,7 +300,7 @@ async def _material_fixture( store, namespace, settings, - write_submission, + submit_source, provision_services=provision_services, provision_checker=provision_checker, ) diff --git a/backend/tests/projects/guide_activation/pg_support.py b/backend/tests/projects/guide_activation/pg_support.py index 2c777bb6f..0ea0bac77 100644 --- a/backend/tests/projects/guide_activation/pg_support.py +++ b/backend/tests/projects/guide_activation/pg_support.py @@ -1,5 +1,6 @@ """Complete approved guide and real CON publication, with controlled hidden authority.""" +from tests.checkers.external.support import post_registry_spec from app.modules.projects.api.guide_activation_context import GuidePolicySelection from contextlib import asynccontextmanager @@ -167,7 +168,7 @@ async def readiness_read(factory, project_id, guide_id): @asynccontextmanager async def activation_case( url, *, human_review_required=True, compensated=False, contribution_awards=(), - post_submit_registry_spec=None, compilation_outcome=None, configuration=None, + post_submit_registry_spec=post_registry_spec(), compilation_outcome=None, configuration=None, ): from .source_fixtures import source_case diff --git a/backend/tests/projects/guide_activation/source_fixtures.py b/backend/tests/projects/guide_activation/source_fixtures.py index 8dc3fd3ab..d3377a1f0 100644 --- a/backend/tests/projects/guide_activation/source_fixtures.py +++ b/backend/tests/projects/guide_activation/source_fixtures.py @@ -6,6 +6,8 @@ from uuid import UUID, uuid4 from sqlalchemy import select + +from tests.checkers.external.support import pre_registry_spec, post_registry_spec from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from app.modules.actors.models import ActorIdentityLink, ActorProfile @@ -206,8 +208,8 @@ async def source_case( namespace=None, guide_version="v1", artifact_proposal=None, - pre_submit_registry_spec=None, - post_submit_registry_spec=None, + pre_submit_registry_spec=pre_registry_spec(), + post_submit_registry_spec=post_registry_spec(), post_submit_configuration_setup: PostSubmitConfigurationSetup | None = None, post_submit_configurations_setup: PostSubmitConfigurationsSetup | None = None, post_submit_specification=None, diff --git a/backend/tests/projects/guide_activation/test_postgresql.py b/backend/tests/projects/guide_activation/test_postgresql.py index fe9146260..2e0951724 100644 --- a/backend/tests/projects/guide_activation/test_postgresql.py +++ b/backend/tests/projects/guide_activation/test_postgresql.py @@ -265,7 +265,8 @@ async def test_later_checker_registration_attaches_to_unchanged_proposal_before_ from .pg_support import publish_policy from .source_fixtures import _register_external_checker_fixture, source_case - async with source_case(clean_postgres_database) as ( + async with source_case(clean_postgres_database, pre_submit_registry_spec=None, + post_submit_registry_spec=None) as ( values, factory, finalization, actor, grant, ): before = await read_package(factory, finalization, actor, grant) diff --git a/backend/tests/projects/guide_activation/test_successor.py b/backend/tests/projects/guide_activation/test_successor.py index 810f1c47b..d92b6c702 100644 --- a/backend/tests/projects/guide_activation/test_successor.py +++ b/backend/tests/projects/guide_activation/test_successor.py @@ -24,9 +24,12 @@ async def successor_command(factory, command, actor, grant, policy): values = { **ids(), "project": command.target.proposal.project_id, - "pre_submit_attachments": (), - "post_submit_attachments": (), } + from tests.checkers.external.support import pre_registry_spec, post_registry_spec + from .source_fixtures import _prepare_human_attachments + values.update(await _prepare_human_attachments( + factory, values["project"], pre_registry_spec(), post_registry_spec(), None, None, + )) async with factory() as session: actor_id, link_id = ( await session.execute( diff --git a/backend/tests/projects/guide_compilation/proposals/pg_support.py b/backend/tests/projects/guide_compilation/proposals/pg_support.py index c95b31889..62a8f53d7 100644 --- a/backend/tests/projects/guide_compilation/proposals/pg_support.py +++ b/backend/tests/projects/guide_compilation/proposals/pg_support.py @@ -1,5 +1,6 @@ """Strict test-only request authority over actual PostgreSQL proposal custody.""" +from tests.checkers.external.support import pre_registry_spec, post_registry_spec from contextlib import asynccontextmanager from uuid import UUID, uuid4 @@ -173,6 +174,8 @@ async def prepare_proposal_operation(self, locator): raise AuthorizationDenied("test close rejected") + + @asynccontextmanager async def proposal_case( url, @@ -180,6 +183,8 @@ async def proposal_case( classification="draft_ready", guide_version="v1", outcome=None, + pre_submit_registry_spec=pre_registry_spec(), + post_submit_registry_spec=post_registry_spec(), ): async with database_case( url, @@ -187,8 +192,10 @@ async def proposal_case( guide_version=guide_version, outcome=outcome, ) as (values, factory, command): - values["pre_submit_attachments"] = () - values["post_submit_attachments"] = () + from tests.projects.guide_activation.source_fixtures import _prepare_human_attachments + values.update(await _prepare_human_attachments( + factory, values["project"], pre_submit_registry_spec, post_submit_registry_spec, None, None, + )) await finalize(factory, values, command) async with factory() as session: row = ( diff --git a/backend/tests/projects/guide_compilation/proposals/test_approved_tip.py b/backend/tests/projects/guide_compilation/proposals/test_approved_tip.py index 9b856dacb..76fa9c0a9 100644 --- a/backend/tests/projects/guide_compilation/proposals/test_approved_tip.py +++ b/backend/tests/projects/guide_compilation/proposals/test_approved_tip.py @@ -21,7 +21,7 @@ async def test_database_rejects_duplicate_approved_tip_and_allows_linked_success ): async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) - first = await approve(factory, command, actor, grant, GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + first = await approve(factory, command, actor, grant, GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4())) correction = await correct(factory, command, actor, grant, GuideProposalCorrection( target=package.target, idempotency_key=uuid4(), reason="Reconsider the required inputs.")) @@ -58,7 +58,7 @@ async def omit_prior_supersession(self, objects=None): expected_previous_approval_output_digest=next_package.current_approval_output_digest) expected_error = GuideProposalError if omitted_guard == "lookup" else DBAPIError with pytest.raises(expected_error) as error: - await approve(factory, successor, actor, grant, GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + await approve(factory, successor, actor, grant, GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=next_package.target, idempotency_key=uuid4(), **prior)) if omitted_guard == "lookup": assert error.value.code == "storage_unavailable" @@ -74,7 +74,7 @@ async def omit_prior_supersession(self, objects=None): assert await session.scalar(text("SELECT lifecycle_status FROM submission_artifact_policies WHERE id=:id"), {"id": str(next_package.target.artifact_policy_id)}) == "draft" - second = await approve(factory, successor, actor, grant, GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + second = await approve(factory, successor, actor, grant, GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=next_package.target, idempotency_key=uuid4(), expected_previous_approval_operation_id=first.operation_id, expected_previous_approval_output_digest=next_package.current_approval_output_digest)) diff --git a/backend/tests/projects/guide_compilation/proposals/test_attachment_input.py b/backend/tests/projects/guide_compilation/proposals/test_attachment_input.py index 9b86b8a18..e2ea2df1d 100644 --- a/backend/tests/projects/guide_compilation/proposals/test_attachment_input.py +++ b/backend/tests/projects/guide_compilation/proposals/test_attachment_input.py @@ -31,28 +31,32 @@ def _target(): ) -def test_omitted_attachments_are_invalid_but_explicit_empty_is_valid(): - target = _target() - with pytest.raises(ValidationError): - GuideProposalApprovalInput(target=target) +@pytest.mark.parametrize("phase", ["pre_submit_attachments", "post_submit_attachments"]) +@pytest.mark.parametrize("count", [None, 0, 2]) +def test_approval_requires_exactly_one_explicit_image_per_phase(phase, count): + pre = _attachment(_entry("project.pre", "pre_submit"), "intake") + post = _attachment(_entry("project.post", "post_submit"), "quality") + body = {"target": _target(), "pre_submit_attachments": (pre,), + "post_submit_attachments": (post,)} + if count is None: + del body[phase] + else: + member = body[phase][0] + body[phase] = tuple(member.model_copy(update={"requirement_id": f"member_{i}"}) + for i in range(count)) + with pytest.raises(ValidationError) as error: + GuideProposalApprovalInput(**body) + assert error.value.errors()[0]["loc"] == (phase,) + + +def test_approval_preserves_exact_single_phase_selections(): + pre = _attachment(_entry("project.pre", "pre_submit"), "intake") + post = _attachment(_entry("project.post", "post_submit"), "quality") approved = GuideProposalApprovalInput( - target=target, pre_submit_attachments=(), post_submit_attachments=(), + target=_target(), pre_submit_attachments=(pre,), post_submit_attachments=(post,), ) - assert approved.pre_submit_attachments == () - assert approved.post_submit_attachments == () - - -def test_duplicate_human_execution_key_is_invalid_even_for_distinct_images(): - first = _entry("project.first", "pre_submit") - second = _entry("project.second", "pre_submit") - with pytest.raises(ValidationError, match="unique canonical"): - GuideProposalApprovalInput( - target=_target(), - pre_submit_attachments=( - _attachment(first, "same_key"), _attachment(second, "same_key"), - ), - post_submit_attachments=(), - ) + assert approved.pre_submit_attachments == (pre,) + assert approved.post_submit_attachments == (post,) def test_current_target_rejects_old_catalogue_identity(): diff --git a/backend/tests/projects/guide_compilation/proposals/test_attachment_postgresql.py b/backend/tests/projects/guide_compilation/proposals/test_attachment_postgresql.py index 1818cf3a6..2089a3245 100644 --- a/backend/tests/projects/guide_compilation/proposals/test_attachment_postgresql.py +++ b/backend/tests/projects/guide_compilation/proposals/test_attachment_postgresql.py @@ -28,7 +28,8 @@ async def test_later_publication_and_one_human_image_cover_independent_suggestio suggestion.model_copy(update={"suggestion_id": "another_suggestion"}), ), }) - async with proposal_case(clean_postgres_database, outcome=outcome) as ( + async with proposal_case(clean_postgres_database, outcome=outcome, + pre_submit_registry_spec=None, post_submit_registry_spec=None) as ( _, factory, command, actor, grant, ): package = await read_package(factory, command, actor, grant) @@ -37,12 +38,13 @@ async def test_later_publication_and_one_human_image_cover_independent_suggestio assert package.target.result_schema_version == "project_guide_check_specification.v1" with pytest.raises(ValidationError): GuideProposalApproval(target=package.target, idempotency_key=uuid4()) - empty = GuideProposalApproval( - target=package.target, pre_submit_attachments=(), post_submit_attachments=(), - idempotency_key=uuid4(), - ) - assert empty.pre_submit_attachments == () + with pytest.raises(ValidationError): + GuideProposalApproval( + target=package.target, pre_submit_attachments=(), post_submit_attachments=(), + idempotency_key=uuid4(), + ) entry = await _register_external_checker_fixture(factory, registry_spec("pre_submit")) + post_entry = await _register_external_checker_fixture(factory, registry_spec("post_submit")) after_publication = await read_package(factory, command, actor, grant) assert after_publication.target.digest == original_digest attachment = ExternalCheckerImageAttachment( @@ -51,10 +53,15 @@ async def test_later_publication_and_one_human_image_cover_independent_suggestio registry_entry_digest=entry.entry_digest, configuration={}, ) + post_attachment = ExternalCheckerImageAttachment( + requirement_id="human_project_post_image", + registry_entry_id=post_entry.registry_entry_id, + registry_entry_digest=post_entry.entry_digest, configuration={}, + ) command_key = uuid4() approval = GuideProposalApproval( target=after_publication.target, - pre_submit_attachments=(attachment,), post_submit_attachments=(), + pre_submit_attachments=(attachment,), post_submit_attachments=(post_attachment,), idempotency_key=command_key, ) receipt = await approve(factory, command, actor, grant, approval) @@ -73,3 +80,62 @@ async def test_later_publication_and_one_human_image_cover_independent_suggestio attachment.model_copy(update={"requirement_id": "another_human_image"}), )}), ) + + +async def test_sql_new_approval_cannot_bypass_exact_phase_cardinality(clean_postgres_database): + """Rehashed request/plan edits cannot insert a new zero/multiple-image approval.""" + import copy + import json + from sqlalchemy import text + from sqlalchemy.exc import DBAPIError + from app.core.identifiers import new_record_id + + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): + package = await read_package(factory, command, actor, grant) + approval = GuideProposalApproval( + target=package.target, idempotency_key=uuid4(), + pre_submit_attachments=values["pre_submit_attachments"], + post_submit_attachments=values["post_submit_attachments"], + acknowledged_warning_hashes=package.warning_hashes, + ) + receipt = await approve(factory, command, actor, grant, approval) + async with factory() as session: + original = json.loads(await session.scalar(text( + "SELECT to_jsonb(a)::text FROM project_guide_proposal_approvals a WHERE operation_id=:id" + ), {"id": receipt.operation_id})) + for phase in ("pre_submit", "post_submit"): + for surface in ("request", "plan", "both"): + for count in (0, 2, None, "object"): + candidate = copy.deepcopy(original) + candidate["operation_id"] = str(new_record_id()) + request, plan = candidate["request_json"], candidate["effective_pre_submit_plan"] + attachment = request[phase + "_attachments"][0] + member = plan[phase]["entries"][0] + if surface in ("request", "both"): + request[phase + "_attachments"] = ( + None if count is None else {} if count == "object" else + [attachment | {"requirement_id": f"member_{i}"} for i in range(count)] + ) + if surface in ("plan", "both"): + plan[phase]["entries"] = ( + None if count is None else {} if count == "object" else + [member | {"requirement_id": f"member_{i}"} for i in range(count)] + ) + plan[phase]["policy_sha256"] = canonical_json_hash( + {key: value for key, value in plan[phase].items() if key != "policy_sha256"}) + plan["policies_sha256"] = canonical_json_hash( + {key: value for key, value in plan.items() if key != "policies_sha256"}) + candidate["request_digest"] = canonical_json_hash(request) + candidate["effective_pre_submit_plan_hash"] = plan["policies_sha256"] + with pytest.raises(DBAPIError, match="guide approval requires one PRE and one POST image"): + async with factory() as session, session.begin(): + await session.execute(text( + "INSERT INTO project_guide_proposal_approvals " + "SELECT (jsonb_populate_record(NULL::project_guide_proposal_approvals,CAST(:body AS jsonb))).*" + ), {"body": json.dumps(candidate)}) + async with factory() as session: + assert await session.scalar(text("SELECT count(*) FROM project_guide_proposal_approvals")) == 1 + stored = json.loads(await session.scalar(text( + "SELECT to_jsonb(a)::text FROM project_guide_proposal_approvals a WHERE operation_id=:id" + ), {"id": receipt.operation_id})) + assert stored == original diff --git a/backend/tests/projects/guide_compilation/proposals/test_audit_schema.py b/backend/tests/projects/guide_compilation/proposals/test_audit_schema.py index d992fbe4b..33ec0ed71 100644 --- a/backend/tests/projects/guide_compilation/proposals/test_audit_schema.py +++ b/backend/tests/projects/guide_compilation/proposals/test_audit_schema.py @@ -20,7 +20,7 @@ async def test_review_package_audit_requires_catalogue_manager_permission( action = ActionId.PROJECT_GUIDE_COMPILATION_REVIEW_PACKAGE_READ permission = ACTION_BY_ID[action].permission_id.value assert permission == "project.guide.manage" - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) receipt = await approve( factory, @@ -29,7 +29,7 @@ async def test_review_package_audit_requires_catalogue_manager_permission( grant, GuideProposalApproval( target=package.target, - pre_submit_attachments=(), post_submit_attachments=(), + pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], idempotency_key=uuid4(), ), ) diff --git a/backend/tests/projects/guide_compilation/proposals/test_authority_contract.py b/backend/tests/projects/guide_compilation/proposals/test_authority_contract.py index 370313fa0..a44ff2dcd 100644 --- a/backend/tests/projects/guide_compilation/proposals/test_authority_contract.py +++ b/backend/tests/projects/guide_compilation/proposals/test_authority_contract.py @@ -122,10 +122,13 @@ async def test_proposal_owner_requires_clean_caller_root_transaction(patch): def test_manager_commands_reject_unknown_server_owned_fields(model, extra): from pydantic import ValidationError + from tests.checkers.external.test_policy import _entry, _attachment + pre = _attachment(_entry("project.pre", "pre_submit"), "intake") + post = _attachment(_entry("project.post", "post_submit"), "quality") with pytest.raises(ValidationError, match="Extra inputs"): model( target=GuideProposalTarget(**target_values()), idempotency_key=uuid4(), - **({"pre_submit_attachments": (), "post_submit_attachments": ()} + **({"pre_submit_attachments": (pre,), "post_submit_attachments": (post,)} if model is GuideProposalApproval else {}), **extra, ) diff --git a/backend/tests/projects/guide_compilation/proposals/test_contracts.py b/backend/tests/projects/guide_compilation/proposals/test_contracts.py index 086506e3b..d863e420a 100644 --- a/backend/tests/projects/guide_compilation/proposals/test_contracts.py +++ b/backend/tests/projects/guide_compilation/proposals/test_contracts.py @@ -48,10 +48,13 @@ def test_blocked_target_rejects_each_independently_populated_policy_field(field) ], ) def test_replacement_requires_both_prior_identity_fields(field, value): + from tests.checkers.external.test_policy import _entry, _attachment + pre = _attachment(_entry("project.pre", "pre_submit"), "intake") + post = _attachment(_entry("project.post", "post_submit"), "quality") with pytest.raises(ValidationError, match="complete or absent"): GuideProposalApproval( target=GuideProposalTarget(**target_values()), - pre_submit_attachments=(), post_submit_attachments=(), + pre_submit_attachments=(pre,), post_submit_attachments=(post,), idempotency_key=uuid4(), **{field: value} ) diff --git a/backend/tests/projects/guide_compilation/proposals/test_postgresql.py b/backend/tests/projects/guide_compilation/proposals/test_postgresql.py index 4a514c4ad..e92f95cd5 100644 --- a/backend/tests/projects/guide_compilation/proposals/test_postgresql.py +++ b/backend/tests/projects/guide_compilation/proposals/test_postgresql.py @@ -143,7 +143,7 @@ async def test_unified_approval_postgresql_commits_exact_chain_and_provenance( async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): before = await stored_state(factory, command) package = await read_package(factory, command, actor, grant) - payload = GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), target=package.target, idempotency_key=uuid4()) + payload = GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4()) receipt = await approve(factory, command, actor, grant, payload) replay = await approve(factory, command, actor, grant, payload) assert replay == receipt @@ -165,8 +165,9 @@ async def test_unified_approval_postgresql_commits_exact_chain_and_provenance( assert (await stored_state(factory, command))[:2] == before[:2] + async def test_correction_postgresql_replay_creates_one_successor(clean_postgres_database): - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): before = await stored_state(factory, command) package = await read_package(factory, command, actor, grant) payload = GuideProposalCorrection( @@ -206,13 +207,14 @@ async def test_correction_postgresql_replay_creates_one_successor(clean_postgres command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), ), ) + async def test_correction_uses_canonical_human_request_and_binds_feedback(clean_postgres_database): async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) @@ -341,7 +343,7 @@ async def test_correction_rejects_authority_for_a_substituted_locator_operation( async def test_approval_rejects_every_substituted_target_identity(clean_postgres_database): - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) with pytest.raises(ValidationError) as invalid_result_version: type(package.target).model_validate({ @@ -383,7 +385,7 @@ async def test_approval_rejects_every_substituted_target_identity(clean_postgres command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target.model_copy(update=patch), idempotency_key=uuid4(), ), @@ -398,7 +400,7 @@ async def test_approval_rejects_every_substituted_target_identity(clean_postgres command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), ), @@ -406,11 +408,12 @@ async def test_approval_rejects_every_substituted_target_identity(clean_postgres assert receipt.artifact_policy_id == package.target.artifact_policy_id + async def test_warning_acknowledgment_is_exact_and_required(clean_postgres_database): async with proposal_case( clean_postgres_database, classification="draft_ready_with_warnings" ) as ( - _, + values, factory, command, actor, @@ -425,7 +428,7 @@ async def test_warning_acknowledgment_is_exact_and_required(clean_postgres_datab command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), acknowledged_warning_hashes=warnings, @@ -436,7 +439,7 @@ async def test_warning_acknowledgment_is_exact_and_required(clean_postgres_datab command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), acknowledged_warning_hashes=package.warning_hashes, @@ -445,9 +448,10 @@ async def test_warning_acknowledgment_is_exact_and_required(clean_postgres_datab assert receipt.artifact_policy_id == package.target.artifact_policy_id + async def test_blocked_result_allows_correction_but_never_approval(clean_postgres_database): async with proposal_case(clean_postgres_database, classification="guide_blocked") as ( - _, + values, factory, command, actor, @@ -461,7 +465,7 @@ async def test_blocked_result_allows_correction_but_never_approval(clean_postgre command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), ), @@ -480,11 +484,12 @@ async def test_blocked_result_allows_correction_but_never_approval(clean_postgre assert receipt.successor_setup_generation == command.setup_generation + 1 + async def test_capability_close_failure_rolls_back_every_decision_effect(clean_postgres_database): from sqlalchemy import func from app.modules.tasks.models import AuditEvent - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) before = await stored_state(factory, command) for action in ("approve", "correct"): @@ -507,7 +512,7 @@ async def test_capability_close_failure_rolls_back_every_decision_effect(clean_p ) if action == "approve": await service.approve( - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), ), @@ -547,7 +552,7 @@ async def test_capability_close_failure_rolls_back_every_decision_effect(clean_p command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), ), @@ -555,18 +560,19 @@ async def test_capability_close_failure_rolls_back_every_decision_effect(clean_p assert receipt.artifact_policy_id == package.target.artifact_policy_id + async def test_database_preserves_approved_content_lifecycle_and_operation(clean_postgres_database): from sqlalchemy import text from sqlalchemy.exc import DBAPIError - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) receipt = await approve( factory, command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), ), @@ -625,6 +631,7 @@ async def test_database_preserves_approved_content_lifecycle_and_operation(clean assert after.artifact_policy_status == "approved" + @pytest.mark.parametrize("omitted", [None, "reservation", "operation"]) async def test_unified_approval_postgresql_requires_reservation_and_operation( clean_postgres_database, @@ -638,7 +645,7 @@ async def test_unified_approval_postgresql_requires_reservation_and_operation( SubmissionPolicyMutationReplayRepository, ) - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) if omitted == "reservation": @@ -685,7 +692,7 @@ def add_without_operation(row, **kwargs): ), external_checker_registry_reader(session), ).approve( - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), ), @@ -706,6 +713,7 @@ def add_without_operation(row, **kwargs): assert policy.lifecycle_status == ("draft" if omitted else "approved") + async def test_corrected_generation_replaces_exact_approved_chain_and_preserves_history( clean_postgres_database, ): @@ -718,7 +726,7 @@ async def test_corrected_generation_replaces_exact_approved_chain_and_preserves_ async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): first_package = await read_package(factory, command, actor, grant) - first_payload = GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), target=first_package.target, idempotency_key=uuid4()) + first_payload = GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=first_package.target, idempotency_key=uuid4()) first = await approve( factory, command, @@ -748,7 +756,7 @@ async def test_corrected_generation_replaces_exact_approved_chain_and_preserves_ next_command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=next_package.target, idempotency_key=uuid4(), ), @@ -758,7 +766,7 @@ async def test_corrected_generation_replaces_exact_approved_chain_and_preserves_ next_command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=next_package.target, idempotency_key=uuid4(), expected_previous_approval_operation_id=first.operation_id, @@ -801,14 +809,15 @@ async def test_corrected_generation_replaces_exact_approved_chain_and_preserves_ assert retained.artifact_policy_status == "superseded" + async def test_concurrent_approvals_have_one_winner_and_one_exact_replay(clean_postgres_database): import asyncio from sqlalchemy import func - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) payloads = [ - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), target=package.target, idempotency_key=uuid4()) for _ in range(2) + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4()) for _ in range(2) ] outcomes = await asyncio.gather( *(approve(factory, command, actor, grant, payload) for payload in payloads), @@ -832,11 +841,12 @@ async def test_concurrent_approvals_have_one_winner_and_one_exact_replay(clean_p ) + async def test_approval_requires_current_manager_authority_even_on_replay(clean_postgres_database): - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) - payload = GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), target=package.target, idempotency_key=uuid4()) + payload = GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4()) receipt = await approve(factory, command, actor, grant, payload) # A different (nonexistent) grant cannot confer manager authority even # when all persisted result and replay identities are otherwise valid. @@ -860,11 +870,12 @@ async def test_approval_requires_current_manager_authority_even_on_replay(clean_ assert await approve(factory, command, actor, grant, payload) == receipt + async def test_projected_draft_content_cannot_be_changed_before_approval(clean_postgres_database): from sqlalchemy import text from sqlalchemy.exc import DBAPIError - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) with pytest.raises(DBAPIError, match="unified proposal content is immutable"): async with factory() as session, session.begin(): @@ -882,7 +893,7 @@ async def test_projected_draft_content_cannot_be_changed_before_approval(clean_p command, actor, grant, - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4(), ), @@ -890,6 +901,7 @@ async def test_projected_draft_content_cannot_be_changed_before_approval(clean_p ).artifact_policy_id == package.target.artifact_policy_id + @pytest.mark.parametrize("guide_version", ["v0.1", "example-proof"]) async def test_approval_preserves_opaque_guide_version(clean_postgres_database, guide_version): async with proposal_case(clean_postgres_database, guide_version=guide_version) as ( @@ -900,7 +912,7 @@ async def test_approval_preserves_opaque_guide_version(clean_postgres_database, grant, ): package = await read_package(factory, command, actor, grant) - payload = GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), target=package.target, idempotency_key=uuid4()) + payload = GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4()) receipt = await approve(factory, command, actor, grant, payload) assert await approve(factory, command, actor, grant, payload) == receipt async with factory() as session: @@ -912,6 +924,7 @@ async def test_approval_preserves_opaque_guide_version(clean_postgres_database, await finalize(factory, values, command) + @pytest.mark.parametrize( "authority_change", [ @@ -931,9 +944,9 @@ async def test_stored_authority_variants_deny_review_replay_and_correction( from .pg_support import seed_review_actor, revoke_review_grant from project_create_fixtures import seed_historical_project - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): package = await read_package(factory, command, actor, grant) - payload = GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), target=package.target, idempotency_key=uuid4()) + payload = GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4()) receipt = await approve(factory, command, actor, grant, payload) assert await approve(factory, command, actor, grant, payload) == receipt denied_grant = grant @@ -1009,6 +1022,7 @@ async def test_stored_authority_variants_deny_review_replay_and_correction( ).scalar_one() == 0 + async def test_another_current_manager_can_admit_correction_after_creator_revocation( clean_postgres_database, ): @@ -1086,7 +1100,7 @@ async def test_database_approval_requires_guide_to_remain_draft( from .pg_support import seed_selected_review_revision_inputs - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, grant): await seed_selected_review_revision_inputs(factory, command, actor) package = await read_package(factory, command, actor, grant) before = await stored_state(factory, command) @@ -1115,7 +1129,7 @@ async def test_database_approval_requires_guide_to_remain_draft( ProposalAuthority(session, actor, command.project_id, grant), external_checker_registry_reader(session), ).approve( - GuideProposalApproval(pre_submit_attachments=(), post_submit_attachments=(), target=package.target, idempotency_key=uuid4()), + GuideProposalApproval(pre_submit_attachments=values["pre_submit_attachments"], post_submit_attachments=values["post_submit_attachments"], target=package.target, idempotency_key=uuid4()), actor=actor, request_id=uuid4(), ) diff --git a/backend/tests/projects/guide_compilation/proposals/test_public_api.py b/backend/tests/projects/guide_compilation/proposals/test_public_api.py index b4eb98536..c821d0345 100644 --- a/backend/tests/projects/guide_compilation/proposals/test_public_api.py +++ b/backend/tests/projects/guide_compilation/proposals/test_public_api.py @@ -68,7 +68,7 @@ async def test_public_approval_read_replay_and_current_authority(clean_postgres_ } ), }) - async with proposal_case(clean_postgres_database, outcome=outcome) as (_, factory, command, actor, grant): + async with proposal_case(clean_postgres_database, outcome=outcome) as (values, factory, command, actor, grant): path = proposal_path(command) async with proposal_client(factory, actor) as client: package = await client.get(path + "/proposal") @@ -86,7 +86,7 @@ async def test_public_approval_read_replay_and_current_authority(clean_postgres_ outcome.submission_artifact_policy, field ) key = {"Idempotency-Key": str(uuid4())} - payload = {"pre_submit_attachments": [], "post_submit_attachments": [], "target": body["target"], "acknowledged_warning_hashes": body["warning_hashes"]} + payload = {"pre_submit_attachments": [item.model_dump(mode="json") for item in values["pre_submit_attachments"]], "post_submit_attachments": [item.model_dump(mode="json") for item in values["post_submit_attachments"]], "target": body["target"], "acknowledged_warning_hashes": body["warning_hashes"]} approved = await client.post(path+"/pre-submission-approval", headers=key, json=payload) assert approved.status_code == 200, approved.text replay = await client.post(path+"/pre-submission-approval", headers=key, json=payload) @@ -113,15 +113,16 @@ async def test_public_approval_read_replay_and_current_authority(clean_postgres_ assert denied.status_code == 404, denied.text + @pytest.mark.parametrize("failure", ["missing_key", "invalid_key", "wrong_path", "warning", "changed_target", "omitted_attachments"]) async def test_public_approval_rejects_without_writes(clean_postgres_database, failure): - async with proposal_case(clean_postgres_database) as (_, factory, command, actor, _): + async with proposal_case(clean_postgres_database) as (values, factory, command, actor, _): path = proposal_path(command) async with proposal_client(factory, actor) as client: package = await client.get(path+"/proposal") assert package.status_code == 200, package.text body = package.json() - payload = {"pre_submit_attachments": [], "post_submit_attachments": [], "target":body["target"], "acknowledged_warning_hashes":body["warning_hashes"]} + payload = {"pre_submit_attachments": [item.model_dump(mode="json") for item in values["pre_submit_attachments"]], "post_submit_attachments": [item.model_dump(mode="json") for item in values["post_submit_attachments"]], "target":body["target"], "acknowledged_warning_hashes":body["warning_hashes"]} headers = {"Idempotency-Key":str(uuid4())} expected = 409 if failure == "missing_key": @@ -147,6 +148,7 @@ async def test_public_approval_rejects_without_writes(clean_postgres_database, f assert await session.scalar(text("SELECT count(*) FROM audit_events WHERE action_id='project.submission_artifact_policy.approve'")) == 0 + @pytest.mark.parametrize("subject_kind,expected", [("service",404),("human",422)]) @pytest.mark.parametrize("suffix", ["corrections", "pre-submission-approval"]) @pytest.mark.parametrize("keys", ["missing", "duplicate_equal", "duplicate_conflicting"]) @@ -196,7 +198,7 @@ async def test_public_package_denies_other_roles_and_scopes(clean_postgres_datab @pytest.mark.parametrize("classification", ["draft_ready", "guide_blocked"]) async def test_setup_pointer_opens_exact_complete_proposal(clean_postgres_database, classification): - async with proposal_case(clean_postgres_database,classification=classification) as (_,factory,command,actor,_): + async with proposal_case(clean_postgres_database,classification=classification) as (values,factory,command,actor,_): path = proposal_path(command) async with proposal_client(factory,actor) as client: status = await client.get(f"/api/v1/projects/{command.project_id}/guides/{command.guide_id}/setup-runs/latest") @@ -208,6 +210,6 @@ async def test_setup_pointer_opens_exact_complete_proposal(clean_postgres_databa assert package.status_code == 200, package.text assert package.json()["result"]["status"] == classification if classification == "guide_blocked": - denied = await client.post(path+"/pre-submission-approval",headers={"Idempotency-Key":str(uuid4())},json={"target":package.json()["target"], "pre_submit_attachments": [], "post_submit_attachments": []}) + denied = await client.post(path+"/pre-submission-approval",headers={"Idempotency-Key":str(uuid4())},json={"target":package.json()["target"], "pre_submit_attachments": [item.model_dump(mode="json") for item in values["pre_submit_attachments"]], "post_submit_attachments": [item.model_dump(mode="json") for item in values["post_submit_attachments"]]}) assert denied.status_code == 409, denied.text assert denied.json()["error"]["code"] == "approval_blocked" diff --git a/backend/tests/projects/guide_compilation/test_evaluation_context_specifications.py b/backend/tests/projects/guide_compilation/test_evaluation_context_specifications.py index 6d7b476c6..c0dd94ea0 100644 --- a/backend/tests/projects/guide_compilation/test_evaluation_context_specifications.py +++ b/backend/tests/projects/guide_compilation/test_evaluation_context_specifications.py @@ -55,9 +55,10 @@ def policy_case(method="model", *, registry_declared=True, selected=SELECTED): @pytest.mark.asyncio @pytest.mark.parametrize("method", ["model", "trial"]) async def test_human_attachment_accepts_exact_declared_revision_context(method): + pre = _entry("acme.intake", "pre_submit") entry, attachment, project_id, profiles = policy_case(method) _, post = await compile_external_checker_policies( - _request(post=(attachment,)), _Registry((entry,)), + _request(pre=(_attachment(pre, "intake"),), post=(attachment,)), _Registry((pre, entry)), project_id=project_id, profiles=profiles, ) assert post.entries[0].configuration[ROLES] == SELECTED @@ -66,6 +67,7 @@ async def test_human_attachment_accepts_exact_declared_revision_context(method): @pytest.mark.asyncio @pytest.mark.parametrize("fault", ["incomplete", "unsupported_registry", "invalid_roles"]) async def test_approval_denies_false_context_selection(fault): + pre = _entry("acme.intake", "pre_submit") entry, attachment, project_id, profiles = policy_case( registry_declared=fault != "unsupported_registry", selected=None if fault == "incomplete" else ["unknown"] if fault == "invalid_roles" else SELECTED, @@ -76,13 +78,14 @@ async def test_approval_denies_false_context_selection(fault): }) with pytest.raises(ValueError, match="evaluation context"): await compile_external_checker_policies( - _request(post=(attachment,)), _Registry((entry,)), + _request(pre=(_attachment(pre, "intake"),), post=(attachment,)), _Registry((pre, entry)), project_id=project_id, profiles=profiles, ) @pytest.mark.asyncio async def test_approval_checks_actual_registry_before_any_policy_write(monkeypatch): + pre = _entry("acme.intake", "pre_submit") entry, attachment, project_id, profiles = policy_case(registry_declared=False) class NoWrites: @@ -101,10 +104,13 @@ def _merge_effective_submission_artifact_policy(self, body): locked = SimpleNamespace(view=SimpleNamespace(policy=SimpleNamespace(policy_body={}))) command = SimpleNamespace( target=SimpleNamespace(project_id=project_id), - pre_submit_attachments=(), post_submit_attachments=(attachment,), + pre_submit_attachments=(_attachment(pre, "intake"),), post_submit_attachments=(attachment,), ) + registry = _Registry((pre, entry)) with pytest.raises(GuideProposalError) as exc: await _compile_approval( - NoWrites(), locked, command, new_record_id(), _Registry((entry,)), profiles, + NoWrites(), locked, command, new_record_id(), registry, profiles, ) assert exc.value.code == "approval_blocked" + assert registry.calls == [(pre.registry_entry_id, pre.entry_digest), + (entry.registry_entry_id, entry.entry_digest)] diff --git a/backend/tests/projects/policy_bundle_fixtures.py b/backend/tests/projects/policy_bundle_fixtures.py index 3460d7494..1adf8fbc1 100644 --- a/backend/tests/projects/policy_bundle_fixtures.py +++ b/backend/tests/projects/policy_bundle_fixtures.py @@ -3,6 +3,7 @@ from __future__ import annotations from httpx import AsyncClient +from tests.checkers.external.support import pre_registry_spec, post_registry_spec from projects.guide_fixtures import read_guide_source_snapshot from projects.post_submit_fixtures import ( @@ -24,7 +25,7 @@ async def create_approved_policy_bundle( sufficiency_status: str = "passed", artifact_proposal=None, request_headers=None, - post_submit_registry_spec=None, + post_submit_registry_spec=post_registry_spec(), document_access_factory=None, ) -> dict: snapshot = await read_guide_source_snapshot(project_id, guide_id) @@ -51,31 +52,18 @@ async def create_approved_policy_bundle( ProjectSetupRun.guide_id == guide_id, ))).one() report = {**report, "id": setup.output_sufficiency_report_id} - post_submit_attachments = () - if post_submit_registry_spec is not None: - from app.adapters.checkers import external_checker_registry_reader - from app.modules.checkers.api.external_policy import ExternalCheckerImageAttachment - - async with db_session.get_session_factory()() as session, session.begin(): - entry = await external_checker_registry_reader(session).read_identity( - capability_id=post_submit_registry_spec.capability_id, - capability_version=post_submit_registry_spec.capability_version, - phase="post_submit", - ) - assert entry.entry_digest == post_submit_registry_spec.spec_digest - post_submit_attachments = (ExternalCheckerImageAttachment( - requirement_id="project.post_evidence", - registry_entry_id=entry.registry_entry_id, - registry_entry_digest=entry.entry_digest, - configuration={}, - ),) + from tests.projects.guide_activation.source_fixtures import _prepare_human_attachments + choices = await _prepare_human_attachments( + db_session.get_session_factory(), project_id, + pre_registry_spec(), post_submit_registry_spec, None, None, + ) effective = await approve_submission_artifact_policy( client, project_id, guide_id, policy["id"], - pre_submit_attachments=(), - post_submit_attachments=post_submit_attachments, + pre_submit_attachments=choices["pre_submit_attachments"], + post_submit_attachments=choices["post_submit_attachments"], ) compiled_pre_submit_checker = await load_pre_submit_checker_policy(effective) assert compiled_pre_submit_checker["lifecycle_status"] == "compiled" diff --git a/backend/tests/projects/post_policy/test_compiler.py b/backend/tests/projects/post_policy/test_compiler.py index bcb3e6509..28b259911 100644 --- a/backend/tests/projects/post_policy/test_compiler.py +++ b/backend/tests/projects/post_policy/test_compiler.py @@ -12,9 +12,11 @@ @pytest.mark.asyncio async def test_saved_post_policy_is_exact_approved_post_body(): + pre = _entry("acme.intake", "pre_submit") entry = _entry("acme.quality_review", "post_submit") locked = await compile_external_checker_policy_bundle( - _request(post=(_attachment(entry, "project_quality"),)), _Registry((entry,)), + _request(pre=(_attachment(pre, "intake"),), post=(_attachment(entry, "project_quality"),)), + _Registry((pre, entry)), ) assert compile_saved_post_policy(policies=locked) == locked.post_submit assert compile_saved_post_policy( @@ -24,7 +26,12 @@ async def test_saved_post_policy_is_exact_approved_post_body(): @pytest.mark.asyncio async def test_saved_post_policy_rejects_changed_locked_bundle_digest(): - locked = await compile_external_checker_policy_bundle(_request(), _Registry(())) + pre = _entry("acme.intake", "pre_submit") + post = _entry("acme.quality_review", "post_submit") + locked = await compile_external_checker_policy_bundle( + _request(pre=(_attachment(pre, "intake"),), post=(_attachment(post, "quality"),)), + _Registry((pre, post)), + ) changed = locked.model_dump(mode="json") changed["post_submit"]["policy_sha256"] = "sha256:" + "0" * 64 with pytest.raises(ValueError): diff --git a/backend/tests/projects/submission_policy_fixtures.py b/backend/tests/projects/submission_policy_fixtures.py index d24e6f733..985f9ec21 100644 --- a/backend/tests/projects/submission_policy_fixtures.py +++ b/backend/tests/projects/submission_policy_fixtures.py @@ -140,15 +140,29 @@ async def approve_submission_artifact_policy( guide_id: str, policy_id: str | None, *, - pre_submit_attachments=(), - post_submit_attachments=(), + pre_submit_attachments=None, + post_submit_attachments=None, ) -> dict: - """Approve a policy with the caller's explicit phase image choices (empty by default).""" + """Approve explicit choices, or register the controlled fixture images when omitted.""" from projects.guide_fixtures import read_guide_source_snapshot from projects.unified_policy_fixtures import ( approve_unified_submission_policy, create_unified_submission_policy, ) + if pre_submit_attachments is None or post_submit_attachments is None: + from tests.checkers.external.support import pre_registry_spec, post_registry_spec + from tests.projects.guide_activation.source_fixtures import _prepare_human_attachments + choices = await _prepare_human_attachments( + db_session.get_session_factory(), project_id, + pre_registry_spec() if pre_submit_attachments is None else None, + post_registry_spec() if post_submit_attachments is None else None, + None, None, + ) + if pre_submit_attachments is None: + pre_submit_attachments = choices["pre_submit_attachments"] + if post_submit_attachments is None: + post_submit_attachments = choices["post_submit_attachments"] + if policy_id is None: snapshot = await read_guide_source_snapshot(project_id, guide_id) report = await create_sufficiency_report(client, project_id, guide_id, snapshot["id"]) diff --git a/backend/tests/projects/test_locked_policy_custody.py b/backend/tests/projects/test_locked_policy_custody.py index 7297097bc..f48ddd853 100644 --- a/backend/tests/projects/test_locked_policy_custody.py +++ b/backend/tests/projects/test_locked_policy_custody.py @@ -143,6 +143,12 @@ async def test_context_read_does_not_allow_activated_proposal_mutations(clean_po guide_id=target.guide_id, compilation_id=target.compilation_id, ) + from app.modules.projects.guide_compilation.models import ProjectGuideProposalApproval + async with factory() as session: + original = await session.get( + ProjectGuideProposalApproval, receipt.command.target.upstream.operation_id, + ) + choices = GuideProposalApproval.model_validate_json(json.dumps(original.request_json)) for status in ("active", "superseded"): async with factory() as session, session.begin(): assert ( @@ -161,8 +167,8 @@ async def test_context_read_does_not_allow_activated_proposal_mutations(clean_po grant, GuideProposalApproval( target=target, - pre_submit_attachments=(), - post_submit_attachments=(), + pre_submit_attachments=choices.pre_submit_attachments, + post_submit_attachments=choices.post_submit_attachments, idempotency_key=uuid4(), acknowledged_warning_hashes=receipt.command.target.upstream.acknowledged_warning_hashes, ), diff --git a/backend/tests/projects/unified_policy_fixtures.py b/backend/tests/projects/unified_policy_fixtures.py index 3b3b2cc5b..b2c801006 100644 --- a/backend/tests/projects/unified_policy_fixtures.py +++ b/backend/tests/projects/unified_policy_fixtures.py @@ -4,6 +4,8 @@ from sqlalchemy import select +from tests.checkers.external.support import pre_registry_spec, post_registry_spec + from app.adapters.artifacts import guide_document_manifest_port from app.adapters.auth import ( artifact_policy_projection_authorization, @@ -51,7 +53,7 @@ async def create_unified_submission_policy( snapshot_id, *, proposal=None, - post_submit_registry_spec=None, + post_submit_registry_spec=post_registry_spec(), document_access_factory=None, ): """Project the actual scripted result, with no manual policy row replacement.""" @@ -173,8 +175,8 @@ async def create_standalone_unified_policy( contribution_awards=(), human_review_required=True, max_revision_rounds=2, - pre_submit_registry_spec=None, - post_submit_registry_spec=None, + pre_submit_registry_spec=pre_registry_spec(), + post_submit_registry_spec=post_registry_spec(), post_submit_configuration_setup=None, post_submit_configurations_setup=None, post_submit_specification=None, diff --git a/backend/tests/retained_material_fixtures.py b/backend/tests/retained_material_fixtures.py index ac4293344..868801741 100644 --- a/backend/tests/retained_material_fixtures.py +++ b/backend/tests/retained_material_fixtures.py @@ -1,89 +1,65 @@ -"""Real ART admission owners with an in-memory byte provider for retained history. +"""Current intake and finalization owners with a retained in-memory byte provider. -These prerequisites exercise canonical storage guards, not deployment/provider -conformance. Local/MinIO execution has its own focused integration proof. +These prerequisites exercise custody and authorization, not provider qualification. +Old object reads remain available for checksum-bound historical migration fixtures. """ - -from tests.trusted_intake_fixtures import LocalIntakeAdapter - -from contextlib import asynccontextmanager +from datetime import timedelta +import hashlib from io import BytesIO from pathlib import Path from tempfile import TemporaryDirectory +from types import SimpleNamespace from uuid import UUID from weakref import WeakKeyDictionary from zipfile import ZipFile -from sqlalchemy import select - -from app.adapters.auth import selected_pre_submit_authority -from app.adapters.checkers import ( - SelectedPreSubmitCheckerExecutionAdapter, - selected_pre_submit_coordinator, -) -from app.adapters.tasks import task_submission_context_port +from app.adapters.artifacts import submission_intake_pre_source_port, submission_finalization_handler +from app.adapters.auth import selected_pre_submit_authority, outbox_dispatch_authorization +from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter, selected_pre_submit_coordinator +from app.adapters.outbox import outbox_append, finalized_unknown_deliveries, outbox_delivery +from app.adapters.projects import project_locked_policy_context_port +from app.adapters.tasks import task_submission_context_port, intake_task_custody_port from app.core.identifiers import new_record_id from app.interfaces.artifacts import ( - ArtifactObjectHead, - ArtifactPutObservation, - ArtifactPutResult, - artifact_provider_object_ref, + ArtifactObjectHead, ArtifactObjectMissingError, ArtifactIntegrityError, + ArtifactPutObservation, ArtifactPutResult, SealedSourceObservation, artifact_provider_object_ref, ) from app.interfaces.external_services import ExternalServiceAdapterIdentity -from app.modules.artifacts.api import SubmissionBundlePreparationRequest -from app.modules.artifacts.authorization import ( - PreparedPreSubmitMaterializationAuthorization, - PreparedSubmissionBundlePreparationAuthorization, -) -from app.modules.artifacts.models import ( - ArtifactStorageNamespace, - ArtifactVerificationJob, - SubmissionBundleAdmission, -) -from app.modules.artifacts.preparation import ArtifactPreparationService, ArtifactScratchManager -from app.modules.artifacts.service import ( - ArtifactAdmissionService, - ArtifactStorageNamespaceSpec, - ArtifactStorageOrchestrator, -) -from app.modules.artifacts.submission_admission import ( - PreparedSubmissionBundlePreparationCommand, - SubmissionBundleDurablePutService, - SubmissionBundlePreparationRuntime, -) -from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService -from app.modules.artifacts.api.submission_archive import ( - SubmissionArchiveLimits, -) -from app.modules.artifacts.submission_archive import ( - SubmissionArchiveInspector, -) -from app.modules.artifacts.submission_materialization import PreparedBundleMaterializationService -from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.actors.api import ServiceIdentity -from app.modules.projects.locked_policy_repository import ProjectLockedPolicyRepository +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, SubmissionIntakeMetadata, SubmissionSourceCapacityLimits, + SubmissionSourceUpload, SubmissionSourcePart, +) +from app.modules.artifacts.authorization import PreparedPreSubmitMaterializationAuthorization +from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission +from app.modules.artifacts.intake.foreground_command import ForegroundSubmissionCommand, SubmissionForegroundLimits +from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease +from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload +from app.modules.artifacts.intake.models import SubmissionIntakeOperation +from app.modules.artifacts.models import ArtifactStorageNamespace +from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService, SelectedPreSubmitSourceReads +from app.modules.artifacts.service import ArtifactStorageNamespaceSpec +from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization +from app.modules.outbox.api import DeliveryOptions +from app.modules.outbox.registry import HandlerRegistry from app.modules.projects.models import EffectiveProjectSubmissionArtifactPolicy from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest -from tests.test_artifact_admission import _AllowArtifactAuthority, _context, _settings -from tests.test_checker_materialization import _limits +from tests.artifacts.test_submission_pre_source import _source_runtime from tests.checkers.execution.support import provision_post_submit_service +from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation +from tests.test_artifact_admission import _context, _settings -async def _bytes(value: bytes): +async def _bytes(value): yield value -class _ForbiddenExternalExecution: - async def execute(self, *_args, **_kwargs): - raise AssertionError("empty selected policy invoked an external image") - - class MemoryStore: - """Implement the existing byte port; all database work stays in ART owners.""" - - def __init__(self, namespace, *, objects=None): + """Keep exact fixture object/source versions across owner transactions.""" + def __init__(self, namespace): + self.namespace = namespace self.identity = ExternalServiceAdapterIdentity("artifact_store", namespace.adapter) - self.objects = {} if objects is None else objects + self.objects, self.uploads, self.sources = {}, {}, {} async def put(self, source, **_kwargs): ref = artifact_provider_object_ref(source.commitment) @@ -99,225 +75,205 @@ async def observe_put_result(self, commitment, **_kwargs): return ArtifactPutObservation(ref, ref in self.objects) async def open(self, ref, byte_range=None, **_kwargs): + if ref not in self.objects: + raise ArtifactObjectMissingError() data = self.objects[ref] if byte_range is not None: end = None if byte_range.length is None else byte_range.offset + byte_range.length - data = data[byte_range.offset : end] - yield data + data = data[byte_range.offset:end] + for offset in range(0, len(data), 65536): + yield data[offset:offset + 65536] async def head(self, ref, **_kwargs): data = self.objects.get(ref) return ArtifactObjectHead(ref, data is not None, len(data) if data is not None else None) + def _namespace(self, location): + assert location.namespace_id == "primary" + assert location.namespace_fingerprint == self.namespace.namespace_fingerprint + assert location.provider_profile == self.namespace.provider_profile + + def _upload(self, upload): + self._namespace(upload.intent.location) + stored = self.uploads[upload.provider_upload_id] + assert stored.upload == upload + return stored + + async def begin_source_upload(self, intent, **_kwargs): + self._namespace(intent.location) + assert intent.maximum_raw_bytes <= 1024 * 1024 + assert not any(item.upload.intent.location == intent.location for item in self.uploads.values()) + upload = SubmissionSourceUpload(intent=intent, provider_upload_id=str(new_record_id())) + self.uploads[upload.provider_upload_id] = SimpleNamespace(upload=upload, parts=[], receipts=[], completion=None) + return upload + + async def upload_source_part(self, upload, number, data, **_kwargs): + stored = self._upload(upload) + assert stored.completion is None and number == len(stored.parts) + 1 + assert 0 < len(data) <= upload.intent.part_bytes + assert sum(map(len, stored.parts)) + len(data) <= upload.intent.maximum_raw_bytes + receipt = SubmissionSourcePart(number=number, byte_count=len(data), provider_etag=hashlib.sha256(data).hexdigest()) + stored.parts.append(bytes(data)) + stored.receipts.append(receipt) + return receipt + + async def complete_source_upload(self, completion, **_kwargs): + stored = self._upload(completion.upload) + if stored.completion is not None: + assert stored.completion == completion + return self.sources[completion.upload.intent.location.operation_id][0] + data = b"".join(stored.parts) + assert tuple(stored.receipts) == completion.parts + assert len(data) == completion.raw_byte_count + assert "sha256:" + hashlib.sha256(data).hexdigest() == completion.raw_sha256 + source = SealedSubmissionSource( + location=completion.upload.intent.location, provider_generation=str(new_record_id()), + raw_sha256=completion.raw_sha256, raw_byte_count=completion.raw_byte_count, + sealed_upload_fence=completion.upload.intent.upload_fence, + ) + assert source.location.operation_id not in self.sources + self.sources[source.location.operation_id] = source, data + stored.completion = completion + return source + + def _source(self, source): + self._namespace(source.location) + if source.location.operation_id not in self.sources: + raise ArtifactObjectMissingError() + retained, data = self.sources[source.location.operation_id] + if source != retained: + raise ArtifactIntegrityError("fixture source identity differs") + return data + + async def open_source(self, source, *, maximum_chunk_bytes=65536, **_kwargs): + assert 1 <= maximum_chunk_bytes <= 65536 + data = self._source(source) + for offset in range(0, len(data), maximum_chunk_bytes): + yield data[offset:offset + maximum_chunk_bytes] + + async def observe_sealed_source(self, source, **_kwargs): + self._source(source) + return SealedSourceObservation(source.location, source.provider_generation, source.raw_byte_count, source.sealed_upload_fence) -_RETAINED_OBJECTS = WeakKeyDictionary() + async def observe_source_upload(self, completion, **_kwargs): + stored = self._upload(completion.upload) + if stored.completion is None: + return None + assert stored.completion == completion + return self.sources[completion.upload.intent.location.operation_id][0] + + +_RETAINED_STORES = WeakKeyDictionary() def retained_archive_store(factory, namespace): - """Keep immutable fixture bytes until their owning test factory is disposed.""" - namespaces = _RETAINED_OBJECTS.setdefault(factory, {}) - objects = namespaces.setdefault(namespace.namespace_fingerprint, {}) - return MemoryStore(namespace, objects=objects) + """Keep all provider state until its owning test session factory is disposed.""" + namespaces = _RETAINED_STORES.setdefault(factory, {}) + store = namespaces.setdefault(namespace.namespace_fingerprint, MemoryStore(namespace)) + assert store.namespace == namespace + return store -def _submission_request(task, assignment, link, packet, predecessor_id, policy, revision_context): +def _submission_source(task, assignment, link, packet, predecessor_id, policy, revision_context): content = BytesIO() paths = {entry["path"] for entry in policy["required_artifacts"] if entry.get("required", True)} - paths.update( - entry.get("path") or "evidence/" + entry["key"] - for entry in policy["required_evidence"] - if entry.get("required", True) - ) + paths.update(entry.get("path") or "evidence/" + entry["key"] + for entry in policy["required_evidence"] if entry.get("required", True)) with ZipFile(content, "w") as archive: for path in sorted(paths): archive.writestr(path, f"{task.id}:{predecessor_id}:{packet.summary}\n") context = _context(actor_profile_id=UUID(task.assigned_to), identity_link_id=UUID(link.id)) - request = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - context.actor_profile_id, context.identity_link_id, ActorKind.HUMAN - ), - request_id=context.request_id, - correlation_id=context.correlation_id, - task_id=UUID(task.id), - assignment_id=UUID(assignment.id), + metadata = SubmissionIntakeMetadata( + task_id=UUID(task.id), assignment_id=UUID(assignment.id), predecessor_submission_id=UUID(predecessor_id) if predecessor_id else None, - idempotency_key=new_record_id(), - summary=packet.summary, - contributor_attestation=packet.worker_attestation, - media_type="application/zip", - byte_source=_bytes(content.getvalue()), - revision_preparation_id=(str(revision_context.preparation_id) if revision_context else None), - revision_preparation_sha256=(revision_context.preparation_sha256 if revision_context else None), + summary=packet.summary, contributor_attestation=packet.worker_attestation, + revision_preparation_id=revision_context.preparation_id if revision_context else None, + revision_preparation_sha256=revision_context.preparation_sha256 if revision_context else None, ) - return context, request - - -def _runtime_factory( - *, - session, - settings, - namespace, - authority, - materialization_authority, - preparation, - inspector, - materialization, - storage, - tasks, - projects, - coordinator, -): - @asynccontextmanager - async def runtime(): - try: - yield SubmissionBundlePreparationRuntime( - preparation=preparation, - intake=LocalIntakeAdapter(inspector), archive_limits=SubmissionArchiveLimits(), - materialization=materialization, - durable_put=SubmissionBundleDurablePutService( - session=session, - admission=ArtifactAdmissionService(session, settings, namespace), - storage=storage, - authorization=authority, - task_contexts=tasks, - project_contexts=projects, - ), - selected_coordinator=coordinator, - selected_execution=SelectedPreSubmitExecutionService( - session=session, - coordinator=coordinator, - authority=selected_pre_submit_authority(session), - materialization=materialization, - ), - storage_scheme="s3", - artifact_deadline_ms=180_000, - ) - finally: - materialization_authority.close() + return context, metadata, content.getvalue() - return runtime - -async def _verify_admission(factory, store, namespace, settings, result): - async with factory() as session: - job_id = await session.scalar( - select(ArtifactVerificationJob.id).where( - ArtifactVerificationJob.originating_put_attempt_id == str(result.put_attempt_id), - ) - ) - assert job_id is not None, result - await session.rollback() - orchestrator = ArtifactStorageOrchestrator( - session, store, namespace, settings, _AllowArtifactAuthority() - ) - assert await orchestrator.verify_object( - UUID(job_id), - submission_task_contexts=task_submission_context_port(session), - ) == "verified" - admission = await session.scalar( - select(SubmissionBundleAdmission).where( - SubmissionBundleAdmission.put_attempt_id == str(result.put_attempt_id), - ) - ) - assert admission.status == "ready" - return admission.id +def _foreground(factory, context, namespace, store, runtime): + admission = ForegroundIntakeAdmission( + factory, tasks=intake_task_custody_port, task_contexts=task_submission_context_port, + projects=project_locked_policy_context_port, + authorization=lambda session: SubmissionIntakeAuthorization(session, context), namespace=namespace, + events=outbox_append, deliveries=finalized_unknown_deliveries, + capacity_limits=SubmissionSourceCapacityLimits(maximum_total_bytes=16 * 1024**2), + maximum_raw_bytes=1024**2, upload_duration=timedelta(seconds=300), lease_duration=timedelta(seconds=60), + ) + async def execute(reservation): + async with factory() as session: + return await SelectedPreSubmitExecutionService( + session=session, coordinator=selected_pre_submit_coordinator(session), + authority=selected_pre_submit_authority(session), + source_reads=SelectedPreSubmitSourceReads( + session=session, sources=submission_intake_pre_source_port(session), + authority=PreparedPreSubmitMaterializationAuthorization( + session, request_id=new_record_id(), correlation_id=new_record_id()), store=store), + execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime), + ).execute(reservation=reservation) + return ForegroundSubmissionCommand( + admission=admission, upload=ForegroundSourceUpload(factory, intake_task_custody_port, store), + lease=ForegroundIntakeLease(factory, intake_task_custody_port, + lease_duration=timedelta(seconds=60), heartbeat_interval=timedelta(seconds=10)), + limits=SubmissionForegroundLimits(part_bytes=5 * 1024**2, idle_timeout_seconds=20, + pre_lease_seconds=60, replay_duration=timedelta(seconds=30)), + runtime_profile=_source_reservation().runtime_profile, + execute=execute, checkers=selected_pre_submit_coordinator, outbox=outbox_append, + ) -async def retained_admission( - factory, - task, - assignment, - link, - packet, - predecessor_id, - *, - external_execution=None, -): - """Prepare/check/publish/verify actual ZIP bytes for this existing assignment.""" - await provision_post_submit_service(factory, ServiceIdentity.ARTIFACT_MATERIALIZER) - await provision_post_submit_service(factory, ServiceIdentity.CHECKER_PRE_SUBMIT) +async def retained_intake(factory, task, assignment, link, packet, predecessor_id): + """Accept exact raw ZIP bytes through current T1, source PRE and atomic T4.""" + for identity in (ServiceIdentity.ARTIFACT_MATERIALIZER, ServiceIdentity.CHECKER_PRE_SUBMIT): + await provision_post_submit_service(factory, identity) async with factory() as session, session.begin(): - current = await task_submission_context_port(session).lock_submission_context( - TaskSubmissionContextRequest( - task_id=UUID(task.id), assignment_id=UUID(assignment.id), - contributor_id=UUID(task.assigned_to), - predecessor_submission_id=UUID(predecessor_id) if predecessor_id else None, - ) - ) + current = await task_submission_context_port(session).lock_submission_context(TaskSubmissionContextRequest( + task_id=UUID(task.id), assignment_id=UUID(assignment.id), contributor_id=UUID(task.assigned_to), + predecessor_submission_id=UUID(predecessor_id) if predecessor_id else None, + )) persisted = await session.get(ArtifactStorageNamespace, "primary") - namespace = ArtifactStorageNamespaceSpec( - persisted.backend, - persisted.adapter, - persisted.provider_profile, - persisted.namespace_descriptor, - persisted.namespace_fingerprint, - ) - policy = ( - await session.get( - EffectiveProjectSubmissionArtifactPolicy, - str(current.locked_project_context.effective_policy_id), - ) - ).effective_policy - # A retained successor is still a new governed attempt: explicitly acknowledge - # its canonical current preparation, then let ART revalidate the binding. - context, request = _submission_request( - task, assignment, link, packet, predecessor_id, policy, current.revision_context, - ) + namespace = ArtifactStorageNamespaceSpec(persisted.backend, persisted.adapter, persisted.provider_profile, + persisted.namespace_descriptor, persisted.namespace_fingerprint) + policy = (await session.get(EffectiveProjectSubmissionArtifactPolicy, + str(current.locked_project_context.effective_policy_id))).effective_policy + context, metadata, payload = _submission_source(task, assignment, link, packet, predecessor_id, policy, current.revision_context) store = retained_archive_store(factory, namespace) - with TemporaryDirectory(prefix="retained-material-") as directory: - settings = _settings(Path(directory), maximum_bytes=1024 * 1024) - # This fixture traverses multiple real database transactions. Its scratch - # lifetime is not the ten-second unit-test timeout from materialization. - manager = ArtifactScratchManager( - root=Path(directory) / "bounded", - limits=_limits(reservation_ttl_seconds=300, total_deadline_seconds=180), - ) - try: - async with factory() as session: - authority = PreparedSubmissionBundlePreparationAuthorization(session, context) - materialization_authority = PreparedPreSubmitMaterializationAuthorization( - session, - request_id=request.request_id, - correlation_id=request.correlation_id, - ) - tasks = task_submission_context_port(session) - projects = ProjectLockedPolicyRepository(session) - preparation = ArtifactPreparationService(manager) - inspector = SubmissionArchiveInspector(SubmissionArchiveLimits()) - materialization = PreparedBundleMaterializationService( - session=session, - authorization=materialization_authority, - preparation=preparation, - checker_execution=SelectedPreSubmitCheckerExecutionAdapter( - external_execution=external_execution or _ForbiddenExternalExecution(), - ), - storage_scheme="s3", archive_limits=SubmissionArchiveLimits(), - ) - storage = ArtifactStorageOrchestrator( - session, store, namespace, settings, _AllowArtifactAuthority() - ) - coordinator = selected_pre_submit_coordinator(session) + with TemporaryDirectory(prefix="retained-source-pre-") as directory: + runtime, errors = _source_runtime(payload, Path(directory), "completed") + command = _foreground(factory, context, namespace, store, runtime) + receipt = await command.submit(metadata, _bytes(payload), actor_id=context.actor_profile_id, + identity_link_id=context.identity_link_id, idempotency_key=new_record_id(), declared_raw_bytes=len(payload)) + assert not errors, "\n".join(errors) + return SimpleNamespace(operation_id=UUID(receipt["operation_id"]), store=store, namespace=namespace, + settings=_settings(Path(directory), maximum_bytes=1024**2)) + - result = await PreparedSubmissionBundlePreparationCommand( - session=session, - authority=authority, - task_contexts=tasks, - project_contexts=projects, - runtime_factory=_runtime_factory( - session=session, - settings=settings, - namespace=namespace, - authority=authority, - materialization_authority=materialization_authority, - preparation=preparation, - inspector=inspector, - materialization=materialization, - storage=storage, - tasks=tasks, - projects=projects, - coordinator=coordinator, - ), - ).prepare(request) - return await _verify_admission(factory, store, namespace, settings, result) - finally: - manager.close() +async def finalize_retained_intake(factory, intake): + """Deliver the exact durable event through production OUTBOX and T5 owners.""" + for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER): + await provision_post_submit_service(factory, identity) + handler = submission_finalization_handler(sessions=factory, settings=intake.settings, + store=intake.store, lease_duration=timedelta(seconds=120)) + failures = [] + async def observed_handler(envelope): + try: + return await handler(envelope) + except Exception as error: + failures.append(error) + raise + event_type = "SubmissionFinalizationRequested" + delivery = outbox_delivery(factory, authorization_factory=outbox_dispatch_authorization, + registry=HandlerRegistry([(event_type, 1, observed_handler)], replay_safe=frozenset({(event_type, 1)})), + options=DeliveryOptions(lease_seconds=180, handler_timeout_seconds=150)) + async with factory() as session: + row = await session.get(SubmissionIntakeOperation, intake.operation_id) + event_id, project_id = UUID(row.finalization_event_id), UUID(row.project_id) + assert await delivery.deliver(event_id, project_id, "retained-finalizer") is not None + if failures: + raise AssertionError("expected successful retained source finalization") from failures[0] + async with factory() as session: + row = await session.get(SubmissionIntakeOperation, intake.operation_id) + assert row.state == "finalized" + return row.finalized_submission_id diff --git a/backend/tests/selected_policy_fixtures.py b/backend/tests/selected_policy_fixtures.py index edb11c177..fa61a3859 100644 --- a/backend/tests/selected_policy_fixtures.py +++ b/backend/tests/selected_policy_fixtures.py @@ -5,6 +5,8 @@ from sqlalchemy import select +from tests.checkers.external.support import pre_registry_spec, post_registry_spec + async def approved_selected_policy_fixture( factory, @@ -14,8 +16,8 @@ async def approved_selected_policy_fixture( contribution_awards=(), human_review_required=True, max_revision_rounds=2, - pre_submit_registry_spec=None, - post_submit_registry_spec=None, + pre_submit_registry_spec=pre_registry_spec(), + post_submit_registry_spec=post_registry_spec(), post_submit_configuration_setup=None, post_submit_configurations_setup=None, post_submit_specification=None, diff --git a/backend/tests/submission_fixtures.py b/backend/tests/submission_fixtures.py index 75493b20a..b6b2bf47f 100644 --- a/backend/tests/submission_fixtures.py +++ b/backend/tests/submission_fixtures.py @@ -1,14 +1,13 @@ """Stored upstream prerequisites for checker/review-owner tests. -These fixtures use ART preparation, verification and consumption owners with -a scripted provider, then seed retained Submission projections with locked +These fixtures use current raw-ZIP intake and durable OUTBOX finalization with +a scripted provider, preserving private retained packet projections with locked lineage. CHECKERS reads these bytes with real phase authority and controlled external-image outcomes; this is not a deployment/provider conformance proof. """ -from uuid import UUID from types import SimpleNamespace -from tests.retained_material_fixtures import retained_admission +from tests.retained_material_fixtures import retained_intake, finalize_retained_intake from sqlalchemy import select @@ -23,7 +22,7 @@ async def seed_retained_submission( task_id: str, payload: dict, *, predecessor_id: str | None = None, ) -> str: - """Seed a retained locked packet with guards enabled; not an intake proof.""" + """Create retained packet history through source intake and durable finalization.""" # Historical private evidence is fixture input, not a public intake DTO. packet = SimpleNamespace(**payload) async with db_session.get_session_factory()() as session: @@ -44,62 +43,27 @@ async def seed_retained_submission( assert link is not None and link.status == "active" session.expunge_all() await session.rollback() - # Detached selectors remain fixture inputs; real preparation rechecks them. - admission_id = await retained_admission( - db_session.get_session_factory(), task, assignment, link, packet, predecessor_id, - ) - # Retained history includes private packet fields absent from public - # intake. Seed those fixture-only values before the real atomic writer - # seals the row; all ownership, authority and dispatch guards stay enabled. - from unittest.mock import patch - from app.api.deps.authorization import compose_hidden_submission_creation_command - from app.modules.tasks.api import SubmissionCreationRequest - from app.modules.actors.api.service_identities import ServiceIdentity - from app.modules.actors.models import ActorProfile - from tests.test_artifact_admission import _context - service = await session.scalar(select(ActorProfile).where( - ActorProfile.service_identity == ServiceIdentity.ARTIFACT_BINDING.value, - )) - if service is None: - service_id = str(new_record_id()) - session.add(ActorProfile( - id=service_id, actor_kind="service", status="active", - provisioning_method="manual_service_provisioning", - service_identity=ServiceIdentity.ARTIFACT_BINDING.value, - created_by="retained-history-fixture", - )) - session.add(ActorIdentityLink( - id=str(new_record_id()), actor_profile_id=service_id, - issuer="flow-test", subject=service_id, subject_kind="service", - status="active", linked_by="retained-history-fixture", - )) - await session.commit() + intake = await retained_intake( + db_session.get_session_factory(), task, assignment, link, packet, predecessor_id, + ) + # Only historical packet fields are fixture input; T5 owns all custody writes. + from unittest.mock import patch - def retained_packet(**values): - identifier = values["submission_id"] - return build_submission( - **values, package_uri=packet.package_uri, package_hash=packet.package_hash, - artifact_hash_manifest=packet.artifact_hash_manifest, - evidence_items=[EvidenceItem( - id=str(new_record_id()), submission_id=identifier, type=item["type"], - label=item["label"], uri=item.get("uri"), hash=item.get("hash"), - size_bytes=item.get("size_bytes"), metadata_json=item.get("metadata", {}), - locked_at=datetime.now(UTC), - ) for item in packet.evidence_items], - ) + def retained_packet(**values): + identifier = values["submission_id"] + return build_submission( + **values, package_uri=packet.package_uri, package_hash=packet.package_hash, + artifact_hash_manifest=packet.artifact_hash_manifest, + evidence_items=[EvidenceItem( + id=str(new_record_id()), submission_id=identifier, type=item["type"], + label=item["label"], uri=item.get("uri"), hash=item.get("hash"), + size_bytes=item.get("size_bytes"), metadata_json=item.get("metadata", {}), + locked_at=datetime.now(UTC), + ) for item in packet.evidence_items], + ) - with patch("app.modules.tasks.submission_composition.build_submission", retained_packet): - created = await compose_hidden_submission_creation_command( - session, _context(actor_profile_id=UUID(task.assigned_to), identity_link_id=UUID(link.id)), - request_id=new_record_id(), correlation_id=new_record_id(), - ).create(SubmissionCreationRequest( - admission_id=UUID(admission_id), task_id=UUID(task_id), - assignment_id=UUID(assignment.id), contributor_id=UUID(task.assigned_to), - predecessor_submission_id=UUID(predecessor_id) if predecessor_id else None, - summary=packet.summary, contributor_attestation=packet.worker_attestation, - )) - submission_id = str(created.submission_id) - return submission_id + with patch("app.modules.tasks.submission_composition.build_submission", retained_packet): + return await finalize_retained_intake(db_session.get_session_factory(), intake) async def seed_retained_checker_run(submission_id: str, *, verdict="passed", state="completed", generation=1) -> str: diff --git a/backend/tests/tasks/post_submit_routing/support.py b/backend/tests/tasks/post_submit_routing/support.py index a782703fe..d113c18e8 100644 --- a/backend/tests/tasks/post_submit_routing/support.py +++ b/backend/tests/tasks/post_submit_routing/support.py @@ -8,26 +8,23 @@ from app.adapters.checkers import evaluation_coordinator from app.adapters.tasks import task_submission_context_port -from app.api.deps.authorization import compose_hidden_submission_creation_command from app.core.identifiers import new_record_id from app.modules.actors.models import ActorIdentityLink -from app.modules.artifacts.api import SubmissionBundlePreparationRequest -from app.modules.authorization.api import ActorIdentityFacts, ActorKind +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata from app.modules.checkers.models import CheckerRun from app.modules.projects.models import ( ReviewPolicy, ) -from app.modules.tasks.api import SubmissionCreationRequest, TaskSubmissionContextRequest +from app.modules.tasks.api import TaskSubmissionContextRequest from app.modules.tasks.api.post_submit_routing import TaskPostSubmitManifestFacts from app.modules.tasks.api.transition_audit import TaskPolicyLineage from app.modules.tasks.models import Submission, SubmissionDispatch, TaskAssignment, WorkstreamTask from tests.checkers.execution.support import live_executor, reserve +from tests.checkers.external.support import post_registry_spec from tests.checkers.post_submit.support import change_request -from tests.post_submit_materialization_helpers import material_fixture +from tests.post_submit_materialization_helpers import material_fixture, create_source_submission from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test -from tests.tasks.submission_lineage_support import _verified_admission from tests.test_artifact_admission import _context -from tests.archive_fixtures import byte_source as _bytes SOURCE_COLUMNS = ( @@ -216,7 +213,7 @@ async def completed_source( contribution_awards=(), human_review_required=True, max_revision_rounds=2, - post_submit_registry_spec=None, + post_submit_registry_spec=post_registry_spec(), ): """Yield one real authorized allow-review run and its valid source scalars.""" async with material_fixture( @@ -253,51 +250,16 @@ async def _create_submission(h, context, task_id, assignment_id, predecessor_id= ) ) revision = current.revision_context - preparation = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - context.actor_profile_id, - context.identity_link_id, - ActorKind.HUMAN, - ), - request_id=context.request_id, - correlation_id=context.correlation_id, - task_id=task_id, - assignment_id=assignment_id, - predecessor_submission_id=predecessor_id, - revision_preparation_id=str(revision.preparation_id) if revision else None, + metadata = SubmissionIntakeMetadata( + task_id=task_id, assignment_id=assignment_id, predecessor_submission_id=predecessor_id, + revision_preparation_id=revision.preparation_id if revision else None, revision_preparation_sha256=revision.preparation_sha256 if revision else None, - idempotency_key=new_record_id(), summary=h.creation_request.summary, contributor_attestation=h.creation_request.contributor_attestation, - media_type="application/zip", - byte_source=_bytes(h.data), ) - admission_id = await _verified_admission( - h.factory, - h.store, - h.namespace, - h.settings, - context, - preparation, + return await create_source_submission( + h.factory, context, h.store.wrapped, h.namespace, h.settings, metadata, h.data, ) - async with h.factory() as session: - created = await compose_hidden_submission_creation_command( - session, - context, - request_id=new_record_id(), - correlation_id=new_record_id(), - ).create( - SubmissionCreationRequest( - task_id=task_id, - assignment_id=assignment_id, - contributor_id=context.actor_profile_id, - predecessor_submission_id=predecessor_id, - admission_id=admission_id, - summary=preparation.summary, - contributor_attestation=preparation.contributor_attestation, - ) - ) - return created async def completed_sibling_source(h): diff --git a/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py b/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py new file mode 100644 index 000000000..49ae98812 --- /dev/null +++ b/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py @@ -0,0 +1,102 @@ +"""Probe revision custody during real T5, before its Submission INSERT.""" + +import json +from contextlib import asynccontextmanager, contextmanager +from unittest.mock import patch + +import pytest +from sqlalchemy import text +from sqlalchemy.exc import IntegrityError + +from app.core.identifiers import new_record_id +from app.modules.tasks.repository import TaskRepository + + +@asynccontextmanager +async def _probe_savepoint(session): + # ROLLBACK TO alone leaves PostgreSQL inside the savepoint. Explicit release + # restores the root transaction required by the subsequent checker owner. + await session.execute(text("SAVEPOINT revision_probe")) + try: + yield + finally: + await session.execute(text("ROLLBACK TO SAVEPOINT revision_probe")) + await session.execute(text("RELEASE SAVEPOINT revision_probe")) + + +@contextmanager +def probe_revision_insert(): + """Keep the real transaction and insertion; reject forged composite inputs.""" + original = TaskRepository.add_submission + observed = [] + + async def add(repository, submission): + if submission.supersedes_submission_id is None: + return await original(repository, submission) + session = repository._session + record = {column.name: getattr(submission, column.key) + for column in submission.__table__.columns} + query = text(""" + SELECT public.accepted_revision_submission_valid( + jsonb_populate_record(NULL::public.submissions, CAST(:record AS jsonb)), false) + """) + assert await session.scalar(query, {"record": json.dumps(record, default=str)}) is True + for field, value in ( + ("task_assignment_id", str(new_record_id())), + ("supersedes_submission_id", str(new_record_id())), + ("locked_review_policy_hash", "sha256:" + "0" * 64), + ): + with pytest.raises(IntegrityError, match="accepted revision submission custody mismatch"): + async with _probe_savepoint(session): + await session.execute(query, {"record": json.dumps(record | {field: value}, default=str)}) + admission = await session.scalar(text(""" + SELECT to_jsonb(a) FROM public.submission_bundle_admissions a + JOIN public.workstream_tasks t ON t.active_submission_operation_id=a.source_operation_id + WHERE t.id=:task + """), {"task": submission.task_id}) + assert admission is not None + source_query = text(""" + SELECT public.require_source_submission_admission(jsonb_populate_record( + NULL::public.submission_bundle_admissions, CAST(:record AS jsonb))) + """) + await session.execute(source_query, {"record": json.dumps(admission)}) + for field in ("source_operation_id", "revision_preparation_id", "predecessor_submission_id", + "checker_remediation_manifest_id"): + with pytest.raises(IntegrityError, match="source admission"): + async with _probe_savepoint(session): + await session.execute(source_query, { + "record": json.dumps(admission | {field: str(new_record_id())}), + }) + observed.append(submission.id) + return await original(repository, submission) + + with patch.object(TaskRepository, "add_submission", add): + yield observed + assert len(observed) == 1 + + +@contextmanager +def stale_fence_before_acceptance_commit(): + """Reserve a legitimate successor after T4 staging, before deferred SQL checks.""" + from app.adapters.checkers import evaluation_coordinator + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from tests.checkers.execution.storage_fixture import storage_request + + original = ForegroundIntakeAdmission._accept_new + observed = [] + + async def accept(admission, session, authority, repository, row, owner, + request, terminal_digest, checkers, outbox): + receipt = await original(admission, session, authority, repository, row, owner, + request, terminal_digest, checkers, outbox) + predecessor = row.accepted_context["predecessor_submission_id"] + assert predecessor is not None and row.state == "finalization_pending" + successor = await storage_request(session, predecessor, generation=2) + reserved = await evaluation_coordinator(session).reserve_current_evaluation(successor) + assert reserved.request_id == successor.evaluation_request_id + observed.append(row.id) + return receipt + + with patch.object(ForegroundIntakeAdmission, "_accept_new", accept): + yield observed + assert len(observed) == 1 diff --git a/backend/tests/tasks/submission_dispatch/test_concurrency.py b/backend/tests/tasks/submission_dispatch/test_concurrency.py index 7f113dfa5..ed27bf129 100644 --- a/backend/tests/tasks/submission_dispatch/test_concurrency.py +++ b/backend/tests/tasks/submission_dispatch/test_concurrency.py @@ -4,93 +4,98 @@ import pytest -from sqlalchemy import select, func, text +from sqlalchemy import select, func -from app.api.deps.authorization import compose_hidden_submission_creation_command from app.core.identifiers import new_record_id from app.modules.checkers.models import CheckerRun from app.modules.outbox.models import OutboxEvent from app.modules.tasks.models import Submission, SubmissionDispatch -from app.modules.tasks.repository import TaskRepository -from tests.post_submit_materialization_helpers import _material_fixture, _read_current_request - - -@pytest.mark.parametrize("different_admissions", [False, True]) -async def test_concurrent_initial_creation_has_one_committed_dispatch(tmp_path, isolated_database_env, monkeypatch, different_admissions): - held, release, contender_entered = asyncio.Event(), asyncio.Event(), asyncio.Event() - contender_pid = [] - original = TaskRepository.get_task - - async def pause_at_task(repository, *args, **kwargs): - label = repository._session.info.pop("dispatch_contender", None) - if label == "second": - contender_pid.append(await repository._session.scalar(text("SELECT pg_catalog.pg_backend_pid()"))) - contender_entered.set() - result = await original(repository, *args, **kwargs) - if label == "first": - held.set() - await asyncio.wait_for(release.wait(), 15) - return result - - async def competing_writer(factory, context, request): - second_request = request - if different_admissions: - from dataclasses import replace - from types import SimpleNamespace - from uuid import UUID - from app.modules.tasks.models import WorkstreamTask, TaskAssignment - from app.modules.actors.models import ActorIdentityLink - from tests.retained_material_fixtures import retained_admission - async with factory() as session: - task = await session.get(WorkstreamTask, str(request.task_id)) - assignment = await session.get(TaskAssignment, str(request.assignment_id)) - link = await session.get(ActorIdentityLink, str(context.identity_link_id)) - session.expunge_all() - other = await retained_admission(factory, task, assignment, link, - SimpleNamespace(summary=request.summary, worker_attestation=request.contributor_attestation), None) - assert UUID(other) != request.admission_id - second_request = replace(request, admission_id=UUID(other)) - async def create(label): - async with factory() as session: - session.info["dispatch_contender"] = label - return await compose_hidden_submission_creation_command( - session, context, request_id=new_record_id(), correlation_id=new_record_id(), - ).create(second_request if label == "second" else request) - - with monkeypatch.context() as patch: - patch.setattr(TaskRepository, "get_task", pause_at_task) - first = asyncio.create_task(create("first")) - second = None - try: - await asyncio.wait_for(held.wait(), 15) - second = asyncio.create_task(create("second")) - await asyncio.wait_for(contender_entered.wait(), 15) - async with factory() as observer: - async with asyncio.timeout(10): - while not await observer.scalar(text("SELECT cardinality(pg_catalog.pg_blocking_pids(:pid))>0"), {"pid": contender_pid[0]}): - await asyncio.sleep(.02) - assert not second.done() - release.set() - results = await asyncio.wait_for(asyncio.gather(first, second, return_exceptions=True), 30) - if different_admissions: - from app.modules.tasks.api import TaskSubmissionContextUnavailable - assert isinstance(results[1], TaskSubmissionContextUnavailable), results[1] - else: - assert results[0] == results[1] - assert not isinstance(results[0], BaseException), results[0] - return results[0] - finally: - release.set() - for task in (first, second): - if task is not None and not task.done(): - task.cancel() - await asyncio.gather(*(task for task in (first, second) if task is not None), return_exceptions=True) - - async with _material_fixture(tmp_path, isolated_database_env, - write_submission=competing_writer, read_request=_read_current_request) as h: - async with h.factory() as session: - for owner in (Submission, SubmissionDispatch, CheckerRun, OutboxEvent): - assert await session.scalar(select(func.count()).select_from(owner)) == 1 +from tests.post_submit_materialization_helpers import _material_fixture, _read_current_request, _submit_current_source +from tests.artifacts.test_submission_intake_admission import ( + admission_intake as admission_intake, + admin_access as admin_access, + auth_database_env as auth_database_env, + clear_settings_cache as clear_settings_cache, + rsa_signing_material as rsa_signing_material, + signed_access as signed_access, +) + + +@pytest.mark.parametrize("contender", ["duplicate_delivery", "new_intake_key"]) +async def test_concurrent_initial_creation_has_one_committed_dispatch(admission_intake, tmp_path, monkeypatch, contender): + """A live T5 owner excludes duplicate delivery and a competing task intake.""" + from datetime import timedelta + from uuid import UUID + from app.adapters.artifacts import submission_finalization_handler + from app.adapters.auth import outbox_dispatch_authorization + from app.adapters.checkers import selected_pre_submit_coordinator + from app.adapters.outbox import outbox_append, outbox_delivery + from app.modules.actors.api import ServiceIdentity + from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from app.modules.outbox.api import DeliveryOptions + from app.modules.outbox.registry import HandlerRegistry + from app.modules.tasks.api import TaskSubmissionContextUnavailable + from tests.artifact_store_helpers import initialize_local_store + from tests.artifacts.intake_acceptance_support import completed_source + from tests.checkers.execution.support import provision_post_submit_service + from tests.test_artifact_admission import _settings + + f = admission_intake + owner, request, terminal = await completed_source(f, tmp_path) + await f.admission.accept(owner, request, terminal.terminal_digest, + checkers=selected_pre_submit_coordinator, outbox=outbox_append) + for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER): + await provision_post_submit_service(f.factory, identity) + store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=65536) + held, release, observations = asyncio.Event(), asyncio.Event(), [] + observe = store.observe_sealed_source + + async def pause_observation(source): + observations.append(source) + held.set() + await release.wait() + return await observe(source) + + monkeypatch.setattr(store, "observe_sealed_source", pause_observation) + handler = submission_finalization_handler(sessions=f.factory, settings=_settings(tmp_path), + store=store, lease_duration=timedelta(seconds=120)) + kind = "SubmissionFinalizationRequested" + delivery = outbox_delivery(f.factory, authorization_factory=outbox_dispatch_authorization, + registry=HandlerRegistry([(kind, 1, handler)], replay_safe=frozenset({(kind, 1)})), + options=DeliveryOptions(lease_seconds=180, handler_timeout_seconds=150)) + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, owner.operation_id) + event_id = UUID(row.finalization_event_id) + first = asyncio.create_task(delivery.deliver(event_id, f.project, "first-finalizer")) + try: + await asyncio.wait_for(held.wait(), 30) + assert not first.done() + if contender == "duplicate_delivery": + assert await delivery.deliver(event_id, f.project, "second-finalizer") is None + else: + with pytest.raises(TaskSubmissionContextUnavailable): + await f.admission.admit(SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment), + actor_id=f.actor.actor_profile_id, identity_link_id=f.actor.identity_link_id, + idempotency_key=new_record_id(), declared_raw_bytes=None) + release.set() + assert await asyncio.wait_for(first, 45) is not None + await delivery.deliver(event_id, f.project, "replay-finalizer") + assert observations == [request.source] + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, owner.operation_id) + assert row.state == "finalized" + for model in (SubmissionIntakeOperation, Submission, SubmissionDispatch, CheckerRun): + assert await session.scalar(select(func.count()).select_from(model).where(model.task_id == str(f.task))) == 1 + for event_type in (kind, "PostSubmissionEvaluationRequested"): + assert await session.scalar(select(func.count()).select_from(OutboxEvent).where( + OutboxEvent.project_id == str(f.project), OutboxEvent.event_type == event_type)) == 1 + finally: + release.set() + if not first.done(): + first.cancel() + await asyncio.gather(first, return_exceptions=True) + store.close() async def _role_race(tmp_path, database_url, monkeypatch, operation): @@ -101,12 +106,12 @@ async def _role_race(tmp_path, database_url, monkeypatch, operation): from app.modules.authorization import router from app.modules.authorization.models import ProjectRoleGrant from app.modules.authorization.project_role_schemas import ProjectRoleGrantRevokeBody - from app.modules.authorization.submission_creation_authorization import PreparedSubmissionCreationAuthorization + from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization from app.modules.tasks.models import WorkstreamTask from tests.test_artifact_admission import _context, _seed_human_actor from tests.project_role_issue_fixtures import issue_body, issue_runtime - async def writer(factory, context, request): + async def writer(factory, context, command, request, data): manager = _context() async with factory.begin() as session: project_id = UUID((await session.get(WorkstreamTask, str(request.task_id))).project_id) @@ -119,7 +124,7 @@ async def writer(factory, context, request): await grant_fixture_admin_role(session, manager.actor_profile_id, role="project_manager", scope="project", project_id=project_id) held, release = asyncio.Event(), asyncio.Event() - original = PreparedSubmissionCreationAuthorization.prepare + original = SubmissionIntakeAuthorization.prepare_acceptance async def pause_after_authority(self, facts): handle = await original(self, facts) held.set() @@ -129,10 +134,7 @@ async def pause_after_authority(self, facts): engine = create_async_engine(database_url, connect_args={"server_settings": {"application_name": name}}) role_factory = async_sessionmaker(engine, expire_on_commit=False) async def create(): - async with factory() as session: - return await compose_hidden_submission_creation_command( - session, context, request_id=new_record_id(), correlation_id=new_record_id(), - ).create(request) + return await _submit_current_source(factory, context, command, request, data) async def mutate(): async with role_factory() as session: prepared, resolved = await issue_runtime( @@ -151,7 +153,7 @@ async def mutate(): pending = [] try: with monkeypatch.context() as patch: - patch.setattr(PreparedSubmissionCreationAuthorization, "prepare", pause_after_authority) + patch.setattr(SubmissionIntakeAuthorization, "prepare_acceptance", pause_after_authority) pending.append(asyncio.create_task(create())) await asyncio.wait_for(held.wait(), 30) pending.append(asyncio.create_task(mutate())) @@ -168,7 +170,7 @@ async def mutate(): await asyncio.gather(*pending, return_exceptions=True) await engine.dispose() - async with _material_fixture(tmp_path, database_url, write_submission=writer, + async with _material_fixture(tmp_path, database_url, submit_source=writer, read_request=_read_current_request) as h: async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(SubmissionDispatch)) == 1 diff --git a/backend/tests/tasks/submission_dispatch/test_evaluation_revision.py b/backend/tests/tasks/submission_dispatch/test_evaluation_revision.py index 1ad3ab633..5f76adc0d 100644 --- a/backend/tests/tasks/submission_dispatch/test_evaluation_revision.py +++ b/backend/tests/tasks/submission_dispatch/test_evaluation_revision.py @@ -5,6 +5,7 @@ import pytest from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_command import SubmissionIntakeMetadata from app.modules.artifacts.models import SubmissionBundleAdmission from app.modules.tasks.api.evaluation_revision import TaskEvaluationRevisionRequest from app.modules.tasks.api.submitted_bundle import SubmittedBundleUnavailable @@ -12,11 +13,9 @@ from app.modules.tasks.models import Submission from tests.tasks.post_submit_routing.remediation_support import remediation_source from tests.tasks.post_submit_routing.support import activate_successor_guide, revision_archive +from tests.post_submit_materialization_helpers import create_source_submission from tests.tasks.submission_dispatch.test_replacement_creation import ( - _create, - _creation_request, _creation_snapshot, - _ready_replacement, ) from tests.tasks.submission_dispatch.test_revision_exhaustion import ( _apply, @@ -63,8 +62,19 @@ async def test_exact_consumed_preparation_and_source_are_read_without_mutation( if rebase: await activate_successor_guide(h) source_id = await _fixture_revision_context(h) - prepared, admission_id = await _ready_replacement(h, revision_archive(h.data)) - created = await _create(h, _creation_request(h, prepared, admission_id)) + created = await create_source_submission( + h.factory, h.actor_context, h.store.wrapped, h.namespace, h.settings, + SubmissionIntakeMetadata( + task_id=h.request.task_id, + assignment_id=h.request.assignment_id, + predecessor_submission_id=h.created.submission_id, + revision_preparation_id=h.revision_preparation_id, + revision_preparation_sha256=h.revision_preparation_sha256, + summary=h.creation_request.summary, + contributor_attestation=h.creation_request.contributor_attestation, + ), + revision_archive(h.data), + ) selector = await revision_selector(h, created.submission_id) before = await _creation_snapshot(h) context = await _read(h, selector) diff --git a/backend/tests/tasks/submission_dispatch/test_revision_exhaustion.py b/backend/tests/tasks/submission_dispatch/test_revision_exhaustion.py index a96d6ad1b..f500e55b6 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_exhaustion.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_exhaustion.py @@ -1,6 +1,7 @@ """Terminal checker failures release one assignment without inventing a revision.""" from uuid import UUID +from unittest.mock import patch import pytest from pydantic import ValidationError @@ -8,6 +9,8 @@ from sqlalchemy.exc import DBAPIError from app.adapters.tasks import task_post_submit_outcome +from app.adapters.artifacts import ConfiguredSubmissionCommand +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata from app.core.identifiers import new_record_id from app.modules.actors.api import ServiceIdentity from app.modules.authorization.runtime import AuthorizationDenied, PreparedAuthorizationUnsupported @@ -15,14 +18,13 @@ from app.modules.projects.api.policy_lineage import RevisionPolicySemantics from app.modules.projects.schemas import RevisionPolicyInput from app.modules.tasks.revision.models import TaskRevisionExhaustion -from app.modules.tasks.schemas import AdmissionBackedSubmissionResponse from tests.checkers.execution.support import service_link_state from tests.checkers.execution.completion_fixture import completed_evidence from tests.tasks.post_submit_routing.outcome_support import outcome_snapshot from tests.tasks.post_submit_routing.remediation_support import no_economic_effects, remediation_source from tests.tasks.post_submit_routing.support import revision_archive from tests.tasks.submission_dispatch.test_revision_capacity import _fail_current_submission -from tests.tasks.submission_lineage_support import _verify_put_attempt +from tests.post_submit_materialization_helpers import create_source_submission from tests.tasks.test_public_submission_intake import _client @@ -163,20 +165,29 @@ async def _submit_initial_after_reclaim(h, client): "Idempotency-Key": str(new_record_id()), "X-Submission-Summary": h.creation_request.summary, "X-Contributor-Attestation": h.creation_request.contributor_attestation} - route = f"/api/v1/tasks/{h.request.task_id}/submission-bundle-preparations" - prepared = await client.post(route, headers=headers, content=h.data) - assert prepared.status_code == 202, prepared.text - admission = await _verify_put_attempt(h.factory, h.store, h.namespace, h.settings, - prepared.json()["put_attempt_id"]) - ready = await client.post(route, headers=headers, content=h.data) - assert ready.status_code == 202 and ready.json()["admission_id"] == str(admission), ready.text - created = await client.post(f"/api/v1/tasks/{h.request.task_id}/submissions", json={ - "assignment_id": str(assignment), "admission_id": str(admission), - "summary": h.creation_request.summary, - "contributor_attestation": h.creation_request.contributor_attestation, - }) - assert created.status_code == 201, created.text - return AdmissionBackedSubmissionResponse.model_validate(created.json()) + + async def submit_http(factory, context, command, metadata, data): + async def submit(configured, received_metadata, chunks, **arguments): + assert received_metadata == metadata + assert arguments["actor_id"] == context.actor_profile_id + return await command.submit(received_metadata, chunks, **arguments) + + with patch.object(ConfiguredSubmissionCommand, "submit", submit): + accepted = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", headers=headers, content=data, + ) + assert accepted.status_code == 202, accepted.text + return accepted.json() + + return await create_source_submission( + h.factory, h.actor_context, h.store.wrapped, h.namespace, h.settings, + SubmissionIntakeMetadata( + task_id=h.request.task_id, assignment_id=assignment, + summary=h.creation_request.summary, + contributor_attestation=h.creation_request.contributor_attestation, + ), + h.data, submit_source=submit_http, + ) async def _other_eligible_actor(h): diff --git a/backend/tests/tasks/submission_dispatch/test_rollback.py b/backend/tests/tasks/submission_dispatch/test_rollback.py index 1326e3f96..aa87ab9c0 100644 --- a/backend/tests/tasks/submission_dispatch/test_rollback.py +++ b/backend/tests/tasks/submission_dispatch/test_rollback.py @@ -1,12 +1,15 @@ -"""Every real participant is staged inside the same rollback boundary.""" +"""T5 failures preserve accepted custody and roll back every finalization owner.""" import pytest -from sqlalchemy import select, func +from sqlalchemy import select, func, text from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine +from app.modules.authorization.prepared import PreparedAuthorizationUnsupported from app.modules.artifacts.models import SubmissionBundleAdmission, SubmissionBindingReceipt, ArtifactBinding +from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization +from app.modules.artifacts.intake.models import SubmissionIntakeOperation from app.modules.artifacts.submission_bindings import SubmissionAdmissionConsumptionService -from app.modules.authorization.submission_creation_authorization import PreparedSubmissionCreationAuthorization +from app.modules.checkers.api.execution import CheckerExecutionUnavailable, REQUEST_EVENT from app.modules.checkers.execution_coordination import EvaluationCoordinator from app.modules.checkers.models import CheckerRun from app.modules.outbox.models import OutboxEvent @@ -20,12 +23,33 @@ class ParticipantFailure(RuntimeError): pass +async def assert_accepted_without_finalization(database_url): + engine = create_async_engine(database_url) + try: + async with async_sessionmaker(engine)() as session: + for model in (Submission, SubmissionDispatch, SubmissionBundleAdmission, + SubmissionBindingReceipt, ArtifactBinding, CheckerRun): + assert await session.scalar(select(func.count()).select_from(model)) == 0 + assert await session.scalar(select(WorkstreamTask.status)) == "evaluation_pending" + operation = (await session.scalars(select(SubmissionIntakeOperation))).one() + assert operation.state == "finalization_pending" and operation.acceptance_receipt is not None + assert operation.finalized_submission_id is None + assert await session.scalar(select(func.count()).select_from(OutboxEvent).where( + OutboxEvent.event_type == "SubmissionFinalizationRequested")) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent).where( + OutboxEvent.event_type == REQUEST_EVENT)) == 0 + assert await session.scalar(select(func.count()).select_from(AuditEvent).where( + AuditEvent.action_id == "submission.create")) == 1 + finally: + await engine.dispose() + + @pytest.mark.parametrize("owner,method,stored", [ (SubmissionAdmissionConsumptionService, "consume", SubmissionBindingReceipt), - (PreparedSubmissionCreationAuthorization, "consume", AuditEvent), + (PreparedSubmissionFinalizationAuthorization, "consume", AuditEvent), (EvaluationCoordinator, "reserve_current_evaluation", CheckerRun), (OutboxService, "append", OutboxEvent), - (TaskSubmissionCreationService, "create", SubmissionDispatch), + (TaskSubmissionCreationService, "create_accepted", SubmissionDispatch), ]) async def test_participant_failure_rolls_back_actual_staged_rows( tmp_path, isolated_database_env, monkeypatch, owner, method, stored, @@ -35,77 +59,64 @@ async def test_participant_failure_rolls_back_actual_staged_rows( async def fail_after_write(self, *args, **kwargs): result = await original(self, *args, **kwargs) + if owner is OutboxService and args[0].event_type != REQUEST_EVENT: + return result + if owner is PreparedSubmissionFinalizationAuthorization and kwargs["facts"].phase != "commit": + return result session = self._repository._session if owner is OutboxService else self._session query = select(func.count()).select_from(stored) if stored is AuditEvent: - query = query.where(AuditEvent.action_id == "submission.create") - assert await session.scalar(query) == 1 + query = query.where(AuditEvent.action_id == "artifact.submission.finalize") + elif stored is OutboxEvent: + query = query.where(OutboxEvent.event_type == REQUEST_EVENT) + assert await session.scalar(query) == (2 if stored is AuditEvent else 1) observed.append(result) raise ParticipantFailure("after real participant write") monkeypatch.setattr(owner, method, fail_after_write) - with pytest.raises(ParticipantFailure, match="after real participant write"): + with pytest.raises(AssertionError, match="expected successful retained source finalization") as error: async with material_fixture(tmp_path, isolated_database_env): - pytest.fail("partial creation committed") + pytest.fail("partial finalization committed") + assert isinstance(error.value.__cause__, ParticipantFailure) assert len(observed) == 1 - engine = create_async_engine(isolated_database_env) - try: - async with async_sessionmaker(engine)() as session: - for model in (Submission, SubmissionDispatch, SubmissionBindingReceipt, ArtifactBinding, CheckerRun, OutboxEvent): - assert await session.scalar(select(func.count()).select_from(model)) == 0 - assert await session.scalar(select(SubmissionBundleAdmission.status)) == "ready" - assert await session.scalar(select(WorkstreamTask.status)) == "in_progress" - assert await session.scalar(select(func.count()).select_from(AuditEvent).where( - AuditEvent.action_id.in_(["submission.create", "artifact.submission.binding.create"]), - )) == 0 - finally: - await engine.dispose() + await assert_accepted_without_finalization(isolated_database_env) async def test_raw_savepoint_cannot_release_creation_custody(tmp_path, isolated_database_env, monkeypatch): - from sqlalchemy import text - original = TaskSubmissionCreationService.create + original = TaskSubmissionCreationService.create_accepted observed = [] - async def inside_raw_savepoint(self, request): + async def inside_raw_savepoint(self, request, **kwargs): await self._session.execute(text("SAVEPOINT caller_savepoint")) assert self._session.in_nested_transaction() is False observed.append(True) - return await original(self, request) + return await original(self, request, **kwargs) - monkeypatch.setattr(TaskSubmissionCreationService, "create", inside_raw_savepoint) - with pytest.raises(RuntimeError, match="requires one root transaction"): + monkeypatch.setattr(TaskSubmissionCreationService, "create_accepted", inside_raw_savepoint) + with pytest.raises(AssertionError, match="expected successful retained source finalization") as error: async with material_fixture(tmp_path, isolated_database_env): pytest.fail("creation accepted an unmanaged savepoint") + assert isinstance(error.value.__cause__, CheckerExecutionUnavailable) + assert "checker_caller_transaction_required" in str(error.value.__cause__) assert observed == [True] + await assert_accepted_without_finalization(isolated_database_env) -async def test_revoked_binding_identity_rolls_back_initial_creation(tmp_path, isolated_database_env): - from sqlalchemy import text - from app.modules.tasks.api import SubmissionCreationAdmissionError - from tests.post_submit_materialization_helpers import _material_fixture, _write_current_submission, _read_current_request +async def test_revoked_binding_identity_preserves_accepted_custody(tmp_path, isolated_database_env): + from tests.post_submit_materialization_helpers import _material_fixture, _submit_current_source, _read_current_request - async def revoke_before_create(factory, context, request): + async def revoke_after_acceptance(factory, context, command, metadata, data): + receipt = await _submit_current_source(factory, context, command, metadata, data) async with factory.begin() as session: await session.execute(text("""UPDATE public.actor_identity_links SET status='revoked', revoked_by='dispatch-test', revoked_at=clock_timestamp(), revoked_reason='Withdraw binding authority' WHERE actor_profile_id IN (SELECT id FROM public.actor_profiles WHERE service_identity='workstream.artifact.binding')""")) - return await _write_current_submission(factory, context, request) + return receipt - with pytest.raises(SubmissionCreationAdmissionError, match="submission_bundle_admission_unavailable"): + with pytest.raises(AssertionError, match="expected successful retained source finalization") as error: async with _material_fixture(tmp_path, isolated_database_env, - write_submission=revoke_before_create, read_request=_read_current_request): + submit_source=revoke_after_acceptance, read_request=_read_current_request): pytest.fail("revoked binding service created a Submission") - engine = create_async_engine(isolated_database_env) - try: - async with async_sessionmaker(engine)() as session: - for model in (Submission, SubmissionDispatch, SubmissionBindingReceipt, ArtifactBinding, CheckerRun, OutboxEvent): - assert await session.scalar(select(func.count()).select_from(model)) == 0 - assert await session.scalar(select(SubmissionBundleAdmission.status)) == "ready" - assert await session.scalar(select(WorkstreamTask.status)) == "in_progress" - assert await session.scalar(select(func.count()).select_from(AuditEvent).where( - AuditEvent.action_id.in_(["submission.create", "artifact.submission.binding.create"]), - )) == 0 - finally: - await engine.dispose() + assert isinstance(error.value.__cause__, PreparedAuthorizationUnsupported) + await assert_accepted_without_finalization(isolated_database_env) diff --git a/backend/tests/tasks/test_submission_lineage.py b/backend/tests/tasks/test_submission_lineage.py index 00e8d2cf4..02ca18994 100644 --- a/backend/tests/tasks/test_submission_lineage.py +++ b/backend/tests/tasks/test_submission_lineage.py @@ -1,6 +1,7 @@ """Real ZIP, ART custody and hidden TASK creation with exact contribution lineage.""" import asyncio +from tests.checkers.external.support import pre_registry_spec from dataclasses import replace from contextlib import asynccontextmanager from types import SimpleNamespace @@ -58,7 +59,7 @@ @asynccontextmanager async def _prepared_packet( - isolated_database_env, tmp_path, *, verify=True, pre_submit_registry_spec=None, + isolated_database_env, tmp_path, *, verify=True, pre_submit_registry_spec=pre_registry_spec(), ): engine = create_async_engine(isolated_database_env) factory = async_sessionmaker(engine, expire_on_commit=False) diff --git a/backend/tests/test_post_submit_materialization.py b/backend/tests/test_post_submit_materialization.py index 1462843d7..6f1cc814e 100644 --- a/backend/tests/test_post_submit_materialization.py +++ b/backend/tests/test_post_submit_materialization.py @@ -8,13 +8,14 @@ import pytest from sqlalchemy import text +from sqlalchemy.exc import IntegrityError from app.core.identifiers import new_record_id from app.modules.checkers.api.materialization import ( PostSubmissionMaterializationUnavailable, PostSubmissionMaterializationFailure, ) from tests.checkers.post_submit.support import change_request -from tests.checkers.execution.support import selected_result as result +from tests.checkers.execution.support import ControlledSelectedExecution from tests.post_submit_materialization_helpers import material_fixture from tests.checkers.execution.support import material_execution, service_link_state from app.modules.actors.api import ServiceIdentity @@ -28,14 +29,16 @@ class Consumer: - def __init__(self, files): + def __init__(self, files, execution): + self.execution = execution self.files, self.view, self.calls = files, None, 0 self.entered, self.release = asyncio.Event(), None self.failure = None async def evaluate(self, request, view): await self.inspect(view) - return result(request) + from app.modules.checkers.execution import _SelectedExternalConsumer + return await _SelectedExternalConsumer(ControlledSelectedExecution(), self.execution.lease).evaluate(request, view) async def inspect(self, view): """Assert current bytes and lifetime independently of the selected result.""" @@ -59,7 +62,7 @@ class ExternalGrantConsumer(Consumer): """Exercise the real POST lineage through ART's callback-scoped grant.""" def __init__(self, files, execution, scratch): - super().__init__(files) + super().__init__(files, execution) self.execution = execution self.scratch = scratch self.grant_path = None @@ -146,7 +149,7 @@ async def test_exact_materialization_reads_verified_original_and_revokes_view(tm await provision_minio_bucket.__wrapped__() async with material_fixture(tmp_path, isolated_database_env, provider=provider) as h: execution = await material_execution(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, execution) material = await h.service.materialize(execution, consumer) assert material.submission_id == h.created.submission_id assert material.submission_version == h.created.submission_version @@ -198,7 +201,7 @@ async def test_revoked_materializer_denies_before_provider_or_scratch(tmp_path, async with material_fixture(tmp_path, isolated_database_env) as h: execution = await material_execution(h) await service_link_state(h.factory, ServiceIdentity.ARTIFACT_MATERIALIZER, active=False) - consumer = Consumer(h.files) + consumer = Consumer(h.files, execution) with pytest.raises(PostSubmissionMaterializationUnavailable, match="authority_unavailable"): await h.service.materialize(execution, consumer) assert h.store.opens == [] and consumer.calls == 0 and not h.preparation._active @@ -207,7 +210,7 @@ async def test_revoked_materializer_denies_before_provider_or_scratch(tmp_path, async def test_foreign_or_changed_request_denies_before_provider(tmp_path, isolated_database_env): async with material_fixture(tmp_path, isolated_database_env) as h: execution = await material_execution(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, execution) for field in ("task_id", "assignment_id", "submission_id", "binding_id", "content_id", "submission_version", "byte_count", "content_sha256"): value = (2 if field == "submission_version" else h.request.byte_count + 1 if field == "byte_count" else "sha256:" + "0" * 64 if field == "content_sha256" else new_record_id()) @@ -224,7 +227,7 @@ async def test_foreign_or_changed_request_denies_before_provider(tmp_path, isola async def test_async_exit_and_concurrent_drift_never_return_stale_material(tmp_path, isolated_database_env, outcome): async with material_fixture(tmp_path, isolated_database_env) as h: execution = await material_execution(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, execution) consumer.release = asyncio.Event() operation = asyncio.create_task(h.service.materialize(execution, consumer)) await asyncio.wait_for(consumer.entered.wait(), 10) @@ -256,12 +259,12 @@ async def test_wrong_provider_bytes_never_reach_consumer(tmp_path, isolated_data from tests.archive_fixtures import byte_source as _bytes async with material_fixture(tmp_path, isolated_database_env) as h: execution = await material_execution(h) - consumer = Consumer(h.files) - original = h.store.open - h.store.open = lambda _: _bytes(h.data[:-1] + bytes([h.data[-1] ^ 1])) + consumer = Consumer(h.files, execution) + original = h.store.open_source + h.store.open_source = lambda _: _bytes(h.data[:-1] + bytes([h.data[-1] ^ 1])) with pytest.raises(PostSubmissionMaterializationFailure, match="material_unavailable"): await h.service.materialize(execution, consumer) - h.store.open = original + h.store.open_source = original assert consumer.calls == 0 and not h.preparation._active @@ -279,7 +282,7 @@ def paused_projection(*args, **kwargs): assert release.wait(10) yield tree monkeypatch.setattr(h.inspector, "_projected_tree", paused_projection) - consumer = Consumer(h.files) + consumer = Consumer(h.files, execution) operation = asyncio.create_task(h.service.materialize(execution, consumer)) assert await asyncio.to_thread(entered.wait, 10) operation.cancel() @@ -296,7 +299,7 @@ async def test_consumer_deadline_revokes_material_and_releases_scratch(tmp_path, from tests.test_checker_materialization import _limits async with material_fixture(tmp_path, isolated_database_env, scratch_limits=_limits(total_deadline_seconds=2)) as h: execution = await material_execution(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, execution) consumer.release = asyncio.Event() with pytest.raises(PostSubmissionMaterializationFailure, match="material_unavailable"): await asyncio.wait_for(h.service.materialize(execution, consumer), 10) @@ -311,7 +314,7 @@ async def test_post_submit_expansion_cannot_bypass_aggregate_quota(tmp_path, iso aggregate_reserved_bytes=HARD_MAXIMUM_ARTIFACT_BYTES, )) as h: execution = await material_execution(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, execution) baseline = (await h.manager.usage()).reserved_bytes reservation, descriptor = await h.manager.allocate() try: @@ -337,24 +340,20 @@ async def test_post_submit_expansion_cannot_bypass_aggregate_quota(tmp_path, iso async def test_stored_manifest_mismatch_never_reaches_consumer(tmp_path, isolated_database_env): async with material_fixture(tmp_path, isolated_database_env) as h: execution = await material_execution(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, execution) # Deliberately corrupt retained custody in this isolated database. Normal - # database guards forbid these writes; exercise ART's independent byte check. + # database guards forbid these writes; source custody must reject them + # before provider I/O, even when mutation guards were bypassed. async with h.factory() as session, session.begin(): - for table in ("submission_bundle_admissions", "pre_submit_evidence_sets"): - await session.execute(text(f"alter table {table} disable trigger user")) - await session.execute(text( - "update pre_submit_evidence_sets set semantic_manifest_sha256=:bad where id=" - "(select pre_submit_evidence_set_id from submission_bundle_admissions where id=:id)" - ), {"id": str(h.created.admission_id), "bad": "sha256:" + "0" * 64}) + await session.execute(text("alter table submission_bundle_admissions disable trigger user")) await session.execute(text( "update submission_bundle_admissions set semantic_manifest_sha256=:bad where id=:id" ), {"id": str(h.created.admission_id), "bad": "sha256:" + "0" * 64}) - for table in ("submission_bundle_admissions", "pre_submit_evidence_sets"): - await session.execute(text(f"alter table {table} enable trigger user")) - with pytest.raises(PostSubmissionMaterializationFailure, match="manifest_mismatch"): + await session.execute(text("alter table submission_bundle_admissions enable trigger user")) + with pytest.raises(IntegrityError, match="source admission provenance mismatch") as refused: await h.service.materialize(execution, consumer) - assert len(h.store.opens) == 1 and consumer.calls == 0 + assert refused.value.orig.sqlstate == "23514" + assert h.store.opens == [] and consumer.calls == 0 assert not h.preparation._active assert list((h.scratch / "workspaces").iterdir()) == [] @@ -364,9 +363,13 @@ async def test_foreign_consumer_result_is_rejected_and_cleaned(tmp_path, isolate execution = await material_execution(h) class WrongResult(Consumer): async def evaluate(self, request, view): - await super().evaluate(request, view) - return result(request, evaluation_generation=request.evaluation_generation + 1) - consumer = WrongResult(h.files) + from app.modules.checkers.api.selected_post_submit import make_selected_post_submit_result + completed = await super().evaluate(request, view) + fields = {name: getattr(completed, name) for name in type(completed).model_fields + if name != "result_digest"} + fields["evaluation_generation"] += 1 + return make_selected_post_submit_result(**fields) + consumer = WrongResult(h.files, execution) with pytest.raises(ValueError, match="request mismatch"): await h.service.materialize(execution, consumer) assert consumer.calls == 1 @@ -385,14 +388,18 @@ async def test_provider_stream_has_no_selection_transaction_and_rejects_drift(tm }) h.service._sessions = async_sessionmaker(selection_engine) entered, release = asyncio.Event(), asyncio.Event() - original = h.store.open - async def paused_stream(reference): - async for chunk in original(reference): - entered.set() - await release.wait() - yield chunk - h.store.open = paused_stream - consumer = Consumer(h.files) + original = h.store.open_source + async def paused_stream(source): + stream = original(source) + try: + async for chunk in stream: + entered.set() + await release.wait() + yield chunk + finally: + await stream.aclose() + h.store.open_source = paused_stream + consumer = Consumer(h.files, execution) operation = asyncio.create_task(h.service.materialize(execution, consumer)) try: await asyncio.wait_for(entered.wait(), 10) @@ -439,6 +446,7 @@ def forbidden_read(*args, **kwargs): async def capture(service, request): with monkeypatch.context() as patch: patch.setattr(LocalStorageAdapter, "open", forbidden_read) + patch.setattr(LocalStorageAdapter, "open_source", forbidden_read) first = await consume(service, request) assert not first.replayed observed.append((request, first)) @@ -454,6 +462,7 @@ async def capture(service, request): async with h.factory() as session, session.begin(): with monkeypatch.context() as patch: patch.setattr(LocalStorageAdapter, "open", forbidden_read) + patch.setattr(LocalStorageAdapter, "open_source", forbidden_read) replay = await SubmissionAdmissionConsumptionService(session, PreparedSubmissionBindingAuthorization( session, request_id=new_record_id(), correlation_id=new_record_id(), )).read_consumed(_replay_request(request)) diff --git a/backend/tests/test_tasks.py b/backend/tests/test_tasks.py index 521ab1e56..20eba2e7f 100644 --- a/backend/tests/test_tasks.py +++ b/backend/tests/test_tasks.py @@ -32,6 +32,7 @@ from projects.guide_fixtures import complete_guide_payload from tests.projects.policy_read_faults import corrupt_locked_policy_reads +from tests.checkers.external.support import post_registry_spec from auth_concurrency_support import wait_for_named_database_lock from tests.submission_fixtures import seed_retained_submission, route_retained_checker_remediation @@ -618,8 +619,9 @@ async def create_policy_bundle_for_guide( guide_id: str, artifact_proposal=None, *, - post_submit_registry_spec=None, + post_submit_registry_spec=post_registry_spec(), document_access_factory=None, + revision_deadline_hours=48, ) -> dict: for kind, body in ( ( @@ -640,7 +642,7 @@ async def create_policy_bundle_for_guide( "revision", { "max_revision_rounds": 7, - "revision_deadline_hours": 48, + "revision_deadline_hours": revision_deadline_hours, "allowed_resubmission_states": ["needs_revision"], "reviewer_reassignment_rule": "same reviewer preferred", }, @@ -721,7 +723,8 @@ def complete_submission_payload(package_hash: str = "sha256:package-v1") -> dict async def create_active_project( - client: AsyncClient, *, slug: str = "task-queue-project", post_submit_registry_spec=None, + client: AsyncClient, *, slug: str = "task-queue-project", post_submit_registry_spec=post_registry_spec(), + revision_deadline_hours=48, ) -> dict: project_response = await client.post( "/api/v1/projects", @@ -744,6 +747,7 @@ async def create_active_project( guide = guide_response.json() await create_policy_bundle_for_guide( client, project["id"], guide["id"], post_submit_registry_spec=post_submit_registry_spec, + revision_deadline_hours=revision_deadline_hours, ) await seed_active_guide_for_downstream_test( @@ -2464,9 +2468,11 @@ async def test_retained_submission_versions_are_readable_without_exposing_packet v2_payload = complete_submission_payload("sha256:package-v2") v2_payload["artifact_hash_manifest"][0]["hash"] = "sha256:answer-v2" - v2_id = await seed_retained_submission( - started_task["id"], v2_payload, predecessor_id=v1_id, - ) + from tests.tasks.submission_dispatch.accepted_revision_probes import probe_revision_insert + with probe_revision_insert(): + v2_id = await seed_retained_submission( + started_task["id"], v2_payload, predecessor_id=v1_id, + ) v2 = await task_client.get( f"/api/v1/submissions/{v2_id}", headers=auth_headers(), ) @@ -2488,6 +2494,29 @@ async def test_retained_submission_versions_are_readable_without_exposing_packet assert dispatch is not None assert str(dispatch.checker_remediation_manifest_id) == remediation_id + # Finalized revisions retain exact accepted custody, independent of the + # contributor's later eligibility. Probe the SQL owner with forged records. + async with db_session.get_session_factory()() as session: + assert await session.scalar(text(""" + SELECT public.accepted_revision_submission_valid(s, true) + FROM public.submissions s WHERE s.id=:id + """), {"id": v2_id}) is True + for field, value in ( + ("task_assignment_id", str(new_record_id())), + ("contributor_id", str(new_record_id())), + ("supersedes_submission_id", str(new_record_id())), + ("version", 99), + ("locked_review_policy_hash", "sha256:" + "0" * 64), + ): + with pytest.raises(IntegrityError, match="accepted revision submission custody mismatch"): + async with session.begin_nested(): + await session.execute(text(""" + SELECT public.accepted_revision_submission_valid( + jsonb_populate_record(NULL::public.submissions, + to_jsonb(s) || CAST(:replacement AS jsonb)), true) + FROM public.submissions s WHERE s.id=:id + """), {"id": v2_id, "replacement": json.dumps({field: value})}) + listed = await task_client.get( f"/api/v1/tasks/{started_task['id']}/submissions", headers=auth_headers(), @@ -2506,6 +2535,33 @@ async def test_retained_submission_versions_are_readable_without_exposing_packet assert denied.status_code == 404 +async def test_revision_acceptance_rejects_checker_fence_changed_before_commit(task_client, monkeypatch): + from app.modules.artifacts.intake.repository import IntakeCustodyConflict + from tests.tasks.submission_dispatch.accepted_revision_probes import stale_fence_before_acceptance_commit + + project = await create_active_project(task_client, post_submit_registry_spec=post_registry_spec()) + task = await create_started_task(task_client, project["id"], monkeypatch) + first = await seed_retained_submission(task["id"], complete_submission_payload()) + await route_retained_checker_remediation(first) + set_dev_actor(monkeypatch, roles="worker", subject="worker-one") + with stale_fence_before_acceptance_commit(): + with pytest.raises(IntakeCustodyConflict) as error: + await seed_retained_submission(task["id"], complete_submission_payload(), predecessor_id=first) + assert "revision acceptance is no longer eligible" in str(error.value.__cause__) + async with db_session.get_session_factory()() as session: + assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": task["id"]}) == 1 + assert await session.scalar(text("SELECT count(*) FROM submission_bundle_admissions WHERE task_id=:id"), {"id": task["id"]}) == 1 + row = (await session.execute(text(""" + SELECT state, acceptance_receipt, finalization_event_id FROM submission_intake_operations + WHERE task_id=:id AND command_metadata->>'predecessor_submission_id' IS NOT NULL + """), {"id": task["id"]})).one() + assert row.state == "failed" and row.acceptance_receipt is None and row.finalization_event_id is None + assert await session.scalar(text(""" + SELECT count(*) FROM outbox_events + WHERE event_type='SubmissionFinalizationRequested' AND payload->>'task_id'=:id + """), {"id": task["id"]}) == 1 + + async def test_retained_submission_history_preserves_locked_guide_after_activation( task_client: AsyncClient, monkeypatch: pytest.MonkeyPatch, diff --git a/cli/README.md b/cli/README.md index 2d67d3f57..d31c0121b 100644 --- a/cli/README.md +++ b/cli/README.md @@ -946,15 +946,16 @@ workstream project guide proposal PROJECT_ID GUIDE_ID COMPILATION_ID -o json > p jq '{target: .target, pre_submit_attachments: [], post_submit_attachments: [], acknowledged_warning_hashes: []}' proposal.json > approval.json # Read the findings. Edit approval.json to acknowledge only the exact displayed # warning_hashes you deliberately accept; the backend requires the complete order. -# Add each selected registered image to the appropriate attachments array. +# Add exactly one selected registered PRE image and one POST image. # Each attachment needs requirement_id, registry_entry_id, -# registry_entry_digest and configuration. Empty arrays select no images. +# registry_entry_digest and configuration. Empty or multiple selections are rejected. workstream project guide approve-pre PROJECT_ID GUIDE_ID COMPILATION_ID --input approval.json --idempotency-key APPROVAL_UUID -o json ``` `--input` is a regular UTF-8 JSON file of at most 1 MiB containing the public `GuideProposalApprovalInput`, not the entire display package. It requires -`target`, `pre_submit_attachments` and `post_submit_attachments`. Each attachment +`target`, `pre_submit_attachments` and `post_submit_attachments`. Each phase must +contain exactly one image attachment. Each attachment uses a human-authored requirement ID, the exact registry entry ID and digest, and a configuration object. Omitted `acknowledged_warning_hashes` means an empty list, never automatic acknowledgment. When replacing an earlier approval, supply both diff --git a/cli/internal/api/guide_approval.go b/cli/internal/api/guide_approval.go index 9b07978da..d80c2ca45 100644 --- a/cli/internal/api/guide_approval.go +++ b/cli/internal/api/guide_approval.go @@ -89,7 +89,7 @@ func decodeGuideApprovalInput(raw json.RawMessage) (guideApprovalInput, error) { func validGuideImageAttachments(raw json.RawMessage) bool { var members []json.RawMessage - if jsonv2.Unmarshal(raw, &members) != nil || members == nil || len(members) > 200 { + if jsonv2.Unmarshal(raw, &members) != nil || members == nil || len(members) != 1 { return false } previous := "" diff --git a/cli/tests/integration/test_guide_activation_public_api.py b/cli/tests/integration/test_guide_activation_public_api.py index 368c7c3cd..2e0822585 100644 --- a/cli/tests/integration/test_guide_activation_public_api.py +++ b/cli/tests/integration/test_guide_activation_public_api.py @@ -59,7 +59,7 @@ def token(actor): # Canonical source/compilation prerequisites, not live inference certification. async with source_case(clean_postgres_database) as ( - _, + values, factory, command, actor, @@ -249,8 +249,14 @@ async def stored(expected, saved=None): headers=headers | {"Idempotency-Key": str(uuid4())}, json={ "target": proposal["target"], - "pre_submit_attachments": [], - "post_submit_attachments": [], + "pre_submit_attachments": [ + item.model_dump(mode="json") + for item in values["pre_submit_attachments"] + ], + "post_submit_attachments": [ + item.model_dump(mode="json") + for item in values["post_submit_attachments"] + ], "acknowledged_warning_hashes": proposal["warning_hashes"], }, ) diff --git a/cli/tests/integration/test_guide_approval_http.py b/cli/tests/integration/test_guide_approval_http.py index 47fb8d308..8d9a4eebc 100644 --- a/cli/tests/integration/test_guide_approval_http.py +++ b/cli/tests/integration/test_guide_approval_http.py @@ -21,7 +21,14 @@ def approval(): "configuration": {"required": True, "labels": ["research", 2]}, } ], - "post_submit_attachments": [], + "post_submit_attachments": [ + { + "requirement_id": "project.quality", + "registry_entry_id": OTHER, + "registry_entry_digest": HASH, + "configuration": {}, + } + ], "acknowledged_warning_hashes": [HASH], } @@ -166,6 +173,8 @@ def test_approval_invalid_input_never_dispatches(cli, tmp_path): variants.append(approval() | {"acknowledged_warning_hashes": value}) for phase in ("pre_submit_attachments", "post_submit_attachments"): for attachments in ( + [], + [approval()[phase][0] | {"requirement_id": key} for key in ("a", "b")], None, {}, [None], diff --git a/cli/tests/integration/test_guide_approval_public_api.py b/cli/tests/integration/test_guide_approval_public_api.py index 6b6411aed..b850c18ab 100644 --- a/cli/tests/integration/test_guide_approval_public_api.py +++ b/cli/tests/integration/test_guide_approval_public_api.py @@ -69,7 +69,7 @@ def token(actor): clean_postgres_database, classification="draft_ready_with_warnings", outcome=validated, - ) as (_, factory, command, actor, grant): + ) as (values, factory, command, actor, grant): outsider, _ = await seed_review_actor( factory, None, role="audit_authority", scope="system" ) @@ -188,8 +188,14 @@ async def stored(expected): assert len(package["warning_hashes"]) == 1 body = { "target": package["target"], - "pre_submit_attachments": [], - "post_submit_attachments": [], + "pre_submit_attachments": [ + item.model_dump(mode="json") + for item in values["pre_submit_attachments"] + ], + "post_submit_attachments": [ + item.model_dump(mode="json") + for item in values["post_submit_attachments"] + ], "acknowledged_warning_hashes": package["warning_hashes"], } for warnings in ([], ["sha256:" + "f" * 64]): diff --git a/cli/tests/integration/test_guide_post_approval_public_api.py b/cli/tests/integration/test_guide_post_approval_public_api.py index f7eaaf032..1a746ef5d 100644 --- a/cli/tests/integration/test_guide_post_approval_public_api.py +++ b/cli/tests/integration/test_guide_post_approval_public_api.py @@ -59,7 +59,7 @@ def token(actor): # Retained prerequisites use canonical owner fixtures, not live setup inference. async with source_case(clean_postgres_database) as ( - _, + values, factory, command, actor, @@ -203,8 +203,14 @@ async def stored(expected, policy_id, original): headers=headers | {"Idempotency-Key": str(uuid4())}, json={ "target": proposal["target"], - "pre_submit_attachments": [], - "post_submit_attachments": [], + "pre_submit_attachments": [ + item.model_dump(mode="json") + for item in values["pre_submit_attachments"] + ], + "post_submit_attachments": [ + item.model_dump(mode="json") + for item in values["post_submit_attachments"] + ], "acknowledged_warning_hashes": proposal["warning_hashes"], }, ) diff --git a/cli/tests/integration/test_guide_post_correction_public_api.py b/cli/tests/integration/test_guide_post_correction_public_api.py index eea754d8a..642833842 100644 --- a/cli/tests/integration/test_guide_post_correction_public_api.py +++ b/cli/tests/integration/test_guide_post_correction_public_api.py @@ -52,7 +52,7 @@ def token(actor): # Canonical retained prerequisite, not live inference or broker-delivery proof. async with source_case(clean_postgres_database) as ( - _, + values, factory, command, actor, @@ -250,8 +250,14 @@ async def stored(expected, policy_id, original, saved=None): headers=headers | {"Idempotency-Key": str(uuid4())}, json={ "target": source["target"], - "pre_submit_attachments": [], - "post_submit_attachments": [], + "pre_submit_attachments": [ + item.model_dump(mode="json") + for item in values["pre_submit_attachments"] + ], + "post_submit_attachments": [ + item.model_dump(mode="json") + for item in values["post_submit_attachments"] + ], "acknowledged_warning_hashes": source["warning_hashes"], }, ) diff --git a/mcp_server/README.md b/mcp_server/README.md index b911763a2..d03704d4f 100644 --- a/mcp_server/README.md +++ b/mcp_server/README.md @@ -204,6 +204,11 @@ review-mode inheritance, immutable lineage, stale/malformed preconditions, authorization and replay. Selector recovery, approval and activation remain outside these two guide-policy tools. +Guide proposal approval requires exactly one registered PRE image and exactly +one registered POST image, with explicit configuration for each. Missing, empty +or multiple selections are rejected before the adapter sends an HTTP request. +Workstream validates the selected immutable identities and approval authority. + Workspace reads accept only their documented UUID selectors, filters, bounded page size and opaque cursor. Contribution export is JSON-only in MCP; the adapter sets `format=json` and does not expose CSV bytes as structured tool diff --git a/mcp_server/contracts/guide_pre_submission_approve.json b/mcp_server/contracts/guide_pre_submission_approve.json index ca352ffc1..4c22726a4 100644 --- a/mcp_server/contracts/guide_pre_submission_approve.json +++ b/mcp_server/contracts/guide_pre_submission_approve.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "690119502ed43be6bef23eaf8d4312a376ed6e8d98b5c225d9a477aaba1155a2", + "canonical_sha256": "34cb5add8ef872ab59ae097b3350b0d7b3953900172b0947ea6f7a3e80b0eb89", "components": { "schemas": { "ApiError": { @@ -162,14 +162,16 @@ "items": { "$ref": "#/components/schemas/ExternalCheckerImageAttachment" }, - "maxItems": 200, + "maxItems": 1, + "minItems": 1, "type": "array" }, "pre_submit_attachments": { "items": { "$ref": "#/components/schemas/ExternalCheckerImageAttachment" }, - "maxItems": 200, + "maxItems": 1, + "minItems": 1, "type": "array" }, "target": { diff --git a/mcp_server/tests/test_guide_lifecycle.py b/mcp_server/tests/test_guide_lifecycle.py index 31555389c..4935180c1 100644 --- a/mcp_server/tests/test_guide_lifecycle.py +++ b/mcp_server/tests/test_guide_lifecycle.py @@ -73,7 +73,14 @@ def _approval_arguments() -> dict[str, Any]: "idempotency_key": IDEMPOTENCY_KEY, "body": { "target": target, - "pre_submit_attachments": [], + "pre_submit_attachments": [ + { + "requirement_id": "project.intake", + "registry_entry_id": POLICY_ID, + "registry_entry_digest": digest, + "configuration": {}, + } + ], "post_submit_attachments": [ { "requirement_id": "project.quality", @@ -112,14 +119,22 @@ def test_approval_forwards_human_image_attachments_unchanged( @pytest.mark.parametrize("field", ["pre_submit_attachments", "post_submit_attachments"]) +@pytest.mark.parametrize("count", [None, 0, 2]) def test_approval_requires_explicit_phase_image_choice( adapter: Adapter, call: Call, field: str, + count: int | None, ) -> None: client, received, _ = adapter arguments = _approval_arguments() - del arguments["body"][field] + if count is None: + del arguments["body"][field] + else: + member = arguments["body"][field][0] + arguments["body"][field] = [ + member | {"requirement_id": f"member_{i}"} for i in range(count) + ] result = call( client, name="workstream_guide_pre_submission_approve", arguments=arguments ).json()["result"] @@ -584,7 +599,9 @@ def test_initial_dispatch_forwards_exact_key_and_caller_without_body( upstream["status"] = 202 upstream["json"] = _initial_dispatch_receipt() result = call( - client, name=f"workstream_{name}", arguments=_initial_dispatch_arguments(), + client, + name=f"workstream_{name}", + arguments=_initial_dispatch_arguments(), token="explicit-guide-caller", ).json()["result"] assert result["isError"] is False @@ -603,11 +620,17 @@ def test_initial_dispatch_forwards_exact_key_and_caller_without_body( @pytest.mark.parametrize(("name", "_suffix"), _INITIAL_DISPATCH_ROUTES) -@pytest.mark.parametrize("change", ( - {"idempotency_key": None}, {"idempotency_key": "not-a-uuid"}, - {"project_id": "foreign/path"}, {"guide_id": "not-a-uuid"}, - {"body": {"inference_required": True}}, {"token": "caller-override"}, -)) +@pytest.mark.parametrize( + "change", + ( + {"idempotency_key": None}, + {"idempotency_key": "not-a-uuid"}, + {"project_id": "foreign/path"}, + {"guide_id": "not-a-uuid"}, + {"body": {"inference_required": True}}, + {"token": "caller-override"}, + ), +) def test_initial_dispatch_rejects_invalid_selectors_keys_and_behavior_overrides( adapter: Adapter, call: Call, name: str, _suffix: str, change: dict[str, Any] ) -> None: @@ -621,12 +644,15 @@ def test_initial_dispatch_rejects_invalid_selectors_keys_and_behavior_overrides( @pytest.mark.parametrize(("name", "_suffix"), _INITIAL_DISPATCH_ROUTES) -@pytest.mark.parametrize(("status", "response"), ( - (200, _initial_dispatch_receipt()), - (202, {**_initial_dispatch_receipt(), "setup_run_id": "invalid"}), - (202, {**_initial_dispatch_receipt(), "setup_generation": 0}), - (202, {**_initial_dispatch_receipt(), "project_id": PROJECT_ID}), -)) +@pytest.mark.parametrize( + ("status", "response"), + ( + (200, _initial_dispatch_receipt()), + (202, {**_initial_dispatch_receipt(), "setup_run_id": "invalid"}), + (202, {**_initial_dispatch_receipt(), "setup_generation": 0}), + (202, {**_initial_dispatch_receipt(), "project_id": PROJECT_ID}), + ), +) def test_initial_dispatch_rejects_uncertain_success_without_retry( adapter: Adapter, call: Call, name: str, _suffix: str, status: int, response: dict[str, Any] ) -> None: @@ -643,10 +669,15 @@ def test_initial_dispatch_rejects_uncertain_success_without_retry( @pytest.mark.parametrize(("name", "_suffix"), _INITIAL_DISPATCH_ROUTES) -@pytest.mark.parametrize(("status", "code"), ( - (404, "proposal_unavailable"), (409, "operation_conflict"), - (503, "storage_unavailable"), (503, "authorization_service_unavailable"), -)) +@pytest.mark.parametrize( + ("status", "code"), + ( + (404, "proposal_unavailable"), + (409, "operation_conflict"), + (503, "storage_unavailable"), + (503, "authorization_service_unavailable"), + ), +) def test_initial_dispatch_preserves_safe_public_failures( adapter: Adapter, call: Call, name: str, _suffix: str, status: int, code: str ) -> None: From 3c57b1232501876e342e86f42ccf842be3dff817 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 20:50:32 +0100 Subject: [PATCH 168/513] feat(tasks): expose authorized pending submission progress --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 80 +++++++++ backend/app/adapters/artifacts/__init__.py | 58 ++++++- backend/app/adapters/tasks/__init__.py | 2 + backend/app/api/deps/authorization.py | 5 +- .../authorization/api/submission_intake.py | 4 + .../authorization/submission_intake.py | 4 +- .../modules/tasks/api/pending_submission.py | 29 ++++ backend/app/modules/tasks/api/task_detail.py | 7 + .../app/modules/tasks/authorized_commands.py | 22 ++- .../test_pending_submission_authority.py | 160 ++++++++++++++++++ .../tasks/test_pending_submission_progress.py | 76 +++++++++ backend/tests/tasks/test_work_context.py | 7 +- cli/internal/api/contributor_tasks.go | 13 +- cli/internal/api/manager_task_context.go | 2 +- cli/internal/api/pending_submission.go | 12 ++ cli/internal/api/task_context.go | 2 +- cli/internal/api/tasks.go | 27 +-- cli/internal/command/contributor_tasks.go | 3 + cli/internal/command/pending_submission.go | 14 ++ cli/internal/command/tasks.go | 3 + .../integration/test_task_http_boundary.py | 1 + .../integration/test_task_pending_http.py | 41 +++++ docs/operations_project_operating_manual.md | 8 + mcp_server/contracts/management_task_get.json | 37 +++- .../management_task_work_context_get.json | 37 +++- mcp_server/contracts/task_get.json | 37 +++- .../contracts/task_work_context_get.json | 37 +++- 27 files changed, 691 insertions(+), 37 deletions(-) create mode 100644 backend/app/modules/tasks/api/pending_submission.py create mode 100644 backend/tests/tasks/test_pending_submission_authority.py create mode 100644 backend/tests/tasks/test_pending_submission_progress.py create mode 100644 cli/internal/api/pending_submission.go create mode 100644 cli/internal/command/pending_submission.go create mode 100644 cli/tests/integration/test_task_pending_http.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b89aa052a..8e9841998 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -5952,3 +5952,83 @@ cleanup, historical replay and policy-cardinality evidence remain as recorded above. Python lint, Markdown links and structural validation pass. Native/provider qualification, broader full-suite proof and full-spec acceptance remain unfinished. This checkpoint does not mark PR708 ready or the active goal complete. + +Bounded implementation: spec5.5 pending operation in TASK detail/work-context. +ARCH/SEC design review recommends TASK-owned typed port, ART bridge on exact +request session/context, reuse existing authorized operation reader and stage +derivation. Allowed files: TASK pending-operation API, detail DTOs, authorized +commands, TASK/ART composition, request dependency, focused task/operation tests, +affected wire contracts/docs and this record. No schema migration, provider +bootstrap, second root transaction, alternate stage logic or relaxed authority. +Expose operation ID/stage only to assigned contributors with operation-read +authority and authorized managers. Other visible TASK reads retain null. Only +genuine AUTH-denied reads may suppress the projection with staged denial retained; +missing/corrupt pointer or unavailable composition must fail closed. Embed field +in detail so work-context shares it. Preserve predecessor as historical evidence. +Risk: authorization and cross-owner transaction visibility. Required ARCH/SEC +implementation review plus QA proof: own/manager/non-owner/revoked authority, +active stages, revision pending, T5 clear, corrupt pointers, no provider I/O and +OpenAPI/JSON nullability; existing detail/work-context regression checks. Human +focus: no pending-operation identity leakage through broader task visibility. + +Terminal evidence: materialization owner v2 passes4 in345.70s, cleanup complete; +revision/reclaim v2 passes6 in710.46s, cleanup complete. Real one-hour deadline +v3 passes1 in3680.50s, cleanup complete: original deadline remained unchanged, +accepted revision finalized after it and exact replay produced one Submission +and POST dispatch. Manifest structural check exits0. Environment root cause +from prior killed PostgreSQL/native Python failures remains unresolved. + +Pending-progress implementation scoped ARCH/SEC code review finds no defect; +execution proof remains separate. Initial v1 fails after successful owner/manager +pending reads because test incorrectly expected non-owner assigned-task visibility. +Actual current TASK authority conceals it with404. Preserve existing visibility, +repair that expectation without broadening product access. V1 cleanup complete. +V2 tests initial/revision, receiving/PRE, revocation, missing/cross-task selector, +missing reader, OpenAPI and final stored-manifest corruption; pending. +Extend affected client scope to the four CLI task/detail-context decoders and +their HTTP tests, plus four transitive MCP contract snapshots. Go API package +tests pass; build /tmp/workstream-pending-progress-cli succeeds. Native CLI and +MCP OpenAPI drift checks running. Operator manual documents the nullable field; +roadmap reconciliation remains required before full PR readiness. + +Boundary validation found new ART adapter importing private AUTH runtime to +classify denied operation reads. Do not expand the frozen import ledger. Extend +allowed AUTH API/service scope with a typed IntakeOperationReadDenied subtype, +raised only around AUTH's operation-read kernel denial; ART consumes that public +type and never inspects private AuthorizationDenied. Existing base-error callers +retain identical denial behavior. Replay ARCH/SEC and module-boundary validation. + +Module inventory also exposed one new private ART repository edge from the new +adapter file. Move PendingSubmissionReader beside the existing configured reader +in adapters/artifacts/__init__.py; remove the new file and update imports. Exact +private-edge sets now match: module-boundaries v3 exits0, no ledger changes. +ARCH/SEC narrow replay passes code scope, including typed denial staging behavior. +CLI HTTP v1 had18pass/1failure: prior fixture lacked the new nullable field in +complete text projection. Update shared detail fixture and add visible pending +identity/stage to contributor/manager text detail. Rebuilt CLI v2 passes19 in108.40s. +MCP live OpenAPI/transitive-snapshot checks pass78 in45.16s. + +Pending PG v2 completes5pass/3fail403.57s, cleanup complete. Failures are test +oracles: initial Submission history is concealed until a Submission exists; +revoked sole Submitter loses task detail/work-context before ART read. Preserve +these404 boundaries, assert initial stored Submission count0, and check TASK +denial audits. QA additionally identified seeded manager fallback and weak +cross-task negative: remove fixture manager grants through real API before own +authority tests; add two real tasks/operations with valid controls then swap +selectors. Add actual stalled-OUTBOX fixture and manager post-T5 null checks. +PG v3 running. Reviewer-retained owner detail is a distinct legitimate200/null +case: issue Reviewer, revoke Submitter, require committed ART denial audit while +work-context remains404. Its dedicated run is +/tmp/submission-task-reviewer-progress-v1.log/json. Full existing work-context +regression and final structural checks now running. No full-readiness claim. + +Pending-progress checkpoint verification: PostgreSQL v3 passes 8 in 451.05s; +Reviewer-retained visibility passes 1 in 76.46s; complete existing work-context +regression passes 24 in 370.81s. All three isolated runner receipts confirm +cleanup_complete=true. CLI HTTP passes 19; MCP contract checks pass 78; Go API, +module boundaries, test structure, changed Python Ruff, and Markdown links pass. +Receipts record the pre-commit HEAD because these tests ran against the working +changes; they are not clean-commit CI attestations. ARCH/SEC and QA code reviews +found no remaining scoped defect; final clean-candidate review is still required. +Downstream completion tests remain running, and full specification qualification, +roadmap reconciliation, provider qualification and complete CI remain unfinished. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 9c06165b4..dd901f8d8 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -1205,6 +1205,57 @@ def get_submission_intake_command( settings=request.app.state.settings, sessions=get_session_factory(), context=context) +def submission_operation_read_service(session, authority): + """Compose operation progress inside its caller's existing transaction.""" + return SubmissionOperationReadService( + session, tasks=intake_task_custody_port(session), authority=authority, + history=submission_history_repository(session), evaluations=evaluation_coordinator(session), + prechecks=selected_pre_submit_coordinator(session), projects=project_locked_policy_context_port(session), + events=outbox_append(session), deliveries=finalized_unknown_deliveries(session), + ) + + +class PendingSubmissionReader: + """TASK progress through the existing ART read in the caller transaction.""" + + def __init__(self, session, context): + self._session, self._context = session, context + + async def read(self, task_id, operation_id): + from app.modules.artifacts.api.submission_command import SubmissionOperationSelector + from app.modules.authorization.api.submission_intake import IntakeOperationReadDenied + from app.modules.tasks.api.pending_submission import PendingSubmissionOperation, PendingSubmissionOperationUnavailable + from app.modules.checkers.api.execution import CheckerExecutionUnavailable + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitUnavailable + from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextUnavailable + from app.modules.tasks.api import TaskSubmissionContextUnavailable + from app.modules.tasks.api.submission_history import SubmissionOperationAssociationUnavailable + + if not self._session.in_transaction(): + raise PendingSubmissionOperationUnavailable("pending submission requires the caller transaction") + authority = submission_intake_authority(self._session, self._context) + try: + response = await submission_operation_read_service(self._session, authority).read( + task_id, SubmissionOperationSelector(operation_id=operation_id), + actor_id=self._context.actor_profile_id, + ) + if (response.task_id != task_id or response.operation_id != operation_id + or response.operation_state not in {"receiving", "pre_checking", "finalization_pending"}): + raise PendingSubmissionOperationUnavailable("pending submission association is inconsistent") + return PendingSubmissionOperation(response.operation_id, response.processing_stage) + except IntakeOperationReadDenied: + # AUTH has staged this denial in the same still-owned transaction. + return None + except IntakeAuthorityDenied as exc: + raise PendingSubmissionOperationUnavailable("pending submission association is unavailable") from exc + except (IntakeCustodyConflict, TaskSubmissionContextUnavailable, SubmissionOperationAssociationUnavailable, + CheckerExecutionUnavailable, SelectedPreSubmitUnavailable, ProjectLockedPolicyContextUnavailable, + SQLAlchemyError, ValidationError, ValueError) as exc: + raise PendingSubmissionOperationUnavailable("pending submission progress is unavailable") from exc + finally: + authority.close() + + class ConfiguredSubmissionOperationReader: """Read stored progress without provider credentials or an execution profile.""" @@ -1220,12 +1271,7 @@ async def read(self, task_id, selector): authority = submission_intake_authority(session, self._context) try: async with session.begin(): - service = SubmissionOperationReadService( - session, tasks=intake_task_custody_port(session), authority=authority, - history=submission_history_repository(session), evaluations=evaluation_coordinator(session), - prechecks=selected_pre_submit_coordinator(session), projects=project_locked_policy_context_port(session), - events=outbox_append(session), deliveries=finalized_unknown_deliveries(session), - ) + service = submission_operation_read_service(session, authority) return await service.read(task_id, selector, actor_id=self._context.actor_profile_id) except IntakeAuthorityDenied as exc: if await authority.restage_denial(exc): diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py index 158019fbf..c3e6592ff 100644 --- a/backend/app/adapters/tasks/__init__.py +++ b/backend/app/adapters/tasks/__init__.py @@ -263,6 +263,7 @@ def task_commands( audit: TaskTransitionAuditPort, actor_profile_id: UUID, settings: Settings, + pending_submissions=None, ) -> AuthorizedTaskCommands: """Compose TASK commands without exposing private product imports to delivery.""" from app.adapters.artifacts import task_guide_documents_port @@ -278,6 +279,7 @@ def task_commands( guide_documents=task_guide_documents_port(session, settings), compensation_terms=locked_compensation_terms_port(session), outbox=outbox_append(session), + pending_submissions=pending_submissions, ) diff --git a/backend/app/api/deps/authorization.py b/backend/app/api/deps/authorization.py index 7d873243b..0c753a7f3 100644 --- a/backend/app/api/deps/authorization.py +++ b/backend/app/api/deps/authorization.py @@ -188,6 +188,8 @@ async def get_task_commands( from app.adapters.auth import task_authorization from app.adapters.tasks import task_commands from app.modules.tasks.api import TaskAuthorityDenied + from app.adapters.artifacts import PendingSubmissionReader + from app.modules.tasks.api.pending_submission import PendingSubmissionOperationUnavailable request_id, correlation_id = (UUID(value) for value in request_ids(request)) context = _authorization_context(resolved, request_id, correlation_id) @@ -202,6 +204,7 @@ async def get_task_commands( authorization=authority, audit=task_transition_audit(session), actor_profile_id=context.actor_profile_id, + pending_submissions=PendingSubmissionReader(session, context), ) except TaskAuthorityDenied as exc: await session.rollback() @@ -225,7 +228,7 @@ async def get_task_commands( error_code="permission_not_granted", error_message="Task authority denied", ) from exc - except (AuthorizationEvidenceUnavailable, SQLAlchemyError) as exc: + except (AuthorizationEvidenceUnavailable, SQLAlchemyError, PendingSubmissionOperationUnavailable) as exc: await session.rollback() raise StructuredHTTPException( status_code=503, diff --git a/backend/app/modules/authorization/api/submission_intake.py b/backend/app/modules/authorization/api/submission_intake.py index 7a86217d5..2f51e8ad4 100644 --- a/backend/app/modules/authorization/api/submission_intake.py +++ b/backend/app/modules/authorization/api/submission_intake.py @@ -64,6 +64,10 @@ class IntakeAuthorityDenied(RuntimeError): """Concealed intake authorization failure.""" +class IntakeOperationReadDenied(IntakeAuthorityDenied): + """A current operation-read AUTH decision denied and staged its audit evidence.""" + + class IntakeAuthorizationPort(Protocol): """The caller owns root transactions, product locks and original provenance.""" async def lock_actor(self, actor_id: UUID, identity_link_id: UUID) -> None: ... diff --git a/backend/app/modules/authorization/submission_intake.py b/backend/app/modules/authorization/submission_intake.py index 01780baab..fff8d4f6b 100644 --- a/backend/app/modules/authorization/submission_intake.py +++ b/backend/app/modules/authorization/submission_intake.py @@ -7,7 +7,7 @@ from app.core.hashing import canonical_json_hash from app.modules.authorization.api.submission_intake import ( - IntakeAuthorityDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts, + IntakeAuthorityDenied, IntakeOperationReadDenied, IntakeOperationReadFacts, IntakeReservationAuthorityFacts, IntakeReservationPreflightFacts, IntakeAcceptanceAuthorityFacts, IntakeOperationReadAccess, ) from app.modules.authorization.catalogue import ActionId, PermissionId @@ -200,7 +200,7 @@ async def authorize_read(self, facts: IntakeOperationReadFacts, *, manager: bool try: return (await self._kernel.require(action, resource)).decision_id except AuthorizationDenied as exc: - raise IntakeAuthorityDenied("submission intake is unavailable") from exc + raise IntakeOperationReadDenied("submission intake is unavailable") from exc async def authorize_operation_read(self, facts: IntakeOperationReadFacts) -> IntakeOperationReadAccess: """Select public read authority from live grants, not a client role flag.""" diff --git a/backend/app/modules/tasks/api/pending_submission.py b/backend/app/modules/tasks/api/pending_submission.py new file mode 100644 index 000000000..1f3b8d5f9 --- /dev/null +++ b/backend/app/modules/tasks/api/pending_submission.py @@ -0,0 +1,29 @@ +"""Authorized current intake progress attached to TASK display facts.""" + +from dataclasses import dataclass +from typing import Literal, Protocol +from uuid import UUID + + +class PendingSubmissionOperationUnavailable(RuntimeError): + """The active pointer cannot be safely projected.""" + + +@dataclass(frozen=True, slots=True) +class PendingSubmissionOperation: + operation_id: UUID + processing_stage: Literal[ + "receiving", "pre_checking", "finalization_pending", "operationally_stalled", + ] + + def __post_init__(self) -> None: + if not isinstance(self.operation_id, UUID) or self.processing_stage not in { + "receiving", "pre_checking", "finalization_pending", "operationally_stalled", + }: + raise ValueError("pending submission operation is invalid") + + +class PendingSubmissionOperationReadPort(Protocol): + async def read(self, task_id: UUID, operation_id: UUID) -> PendingSubmissionOperation | None: + """Use the caller transaction; return None only for denied read authority.""" + ... diff --git a/backend/app/modules/tasks/api/task_detail.py b/backend/app/modules/tasks/api/task_detail.py index 0b7c2b68a..e4423d754 100644 --- a/backend/app/modules/tasks/api/task_detail.py +++ b/backend/app/modules/tasks/api/task_detail.py @@ -8,6 +8,7 @@ from app.modules.tasks.api.ready_queue import TaskCompensationTerms, _aware from app.modules.tasks.api.assignment_outcome import TaskAssignmentOutcome from app.modules.tasks.api.revision import ContributorRevisionContext +from app.modules.tasks.api.pending_submission import PendingSubmissionOperation @dataclass(frozen=True, slots=True) @@ -75,9 +76,12 @@ class ContributorTaskDetail(_TaskDetailFields): compensation: TaskCompensationTerms last_assignment_outcome: TaskAssignmentOutcome | None = None + pending_submission_operation: PendingSubmissionOperation | None = None def __post_init__(self) -> None: _TaskDetailFields.__post_init__(self) + if self.pending_submission_operation is not None and not isinstance(self.pending_submission_operation, PendingSubmissionOperation): + raise ValueError("pending submission operation is invalid") if (not isinstance(self.compensation, TaskCompensationTerms) or (self.last_assignment_outcome is not None and not isinstance(self.last_assignment_outcome, TaskAssignmentOutcome))): @@ -97,9 +101,12 @@ class ManagementTaskDetail(_TaskDetailFields): assigned_to: str | None last_assignment_outcome: TaskAssignmentOutcome | None = None revision_context: ContributorRevisionContext | None = None + pending_submission_operation: PendingSubmissionOperation | None = None def __post_init__(self) -> None: _TaskDetailFields.__post_init__(self) + if self.pending_submission_operation is not None and not isinstance(self.pending_submission_operation, PendingSubmissionOperation): + raise ValueError("pending submission operation is invalid") if ( not isinstance(self.source_type, str) or not isinstance(self.created_by, str) or any(value is not None and not isinstance(value, str) for value in ( diff --git a/backend/app/modules/tasks/authorized_commands.py b/backend/app/modules/tasks/authorized_commands.py index 54bec43d4..5969c4bdd 100644 --- a/backend/app/modules/tasks/authorized_commands.py +++ b/backend/app/modules/tasks/authorized_commands.py @@ -42,6 +42,9 @@ from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable from app.modules.tasks.command_replay import TaskCommandReplay, TaskReplayConflict from app.modules.tasks.repository import TaskRepository +from app.modules.tasks.api.pending_submission import ( + PendingSubmissionOperationReadPort, PendingSubmissionOperationUnavailable, +) from app.modules.tasks.revision.models import TaskRevisionPreparation from app.modules.tasks.revision.expiry_event import revision_preparation_event from app.modules.outbox.api import OutboxAppendPort @@ -141,6 +144,7 @@ def __init__( guide_documents: TaskGuideDocumentsPort, compensation_terms: LockedCompensationTermsPort | None = None, outbox: OutboxAppendPort | None = None, + pending_submissions: PendingSubmissionOperationReadPort | None = None, ) -> None: self._session = session self._authorization = authorization @@ -150,6 +154,7 @@ def __init__( self._contexts = contexts self._guide_documents = guide_documents self._outbox = outbox + self._pending_submissions = pending_submissions self._replay = TaskCommandReplay(session) self._transition_context_owner = object() @@ -871,6 +876,14 @@ async def audit_evidence(self, request: AuditTaskEvidenceRequest) -> AuditTaskEv raise TaskValidationError("task audit evidence is invalid") from None return response + async def _with_pending_submission(self, task, detail, *, visible): + if not visible or task.active_submission_operation_id is None: + return detail + if self._pending_submissions is None: + raise PendingSubmissionOperationUnavailable("pending submission reader is unavailable") + pending = await self._pending_submissions.read(UUID(task.id), UUID(task.active_submission_operation_id)) + return replace(detail, pending_submission_operation=pending) + async def _read_task_projection(self, task_id: UUID, operation: TaskAuthorityOperation, project_id: UUID | None = None): """Consume exact authority and serialize detached facts before committing evidence.""" if not isinstance(task_id, UUID) or ( @@ -888,7 +901,7 @@ async def _read_task_projection(self, task_id: UUID, operation: TaskAuthorityOpe TaskAuthorityOperation.AUDIT_LOCKED_CONTEXT: AuditTaskLockedContext, }[operation] async with self._session.begin(): - task, _, _ = await self._locked_task(task_id, operation, project_id=project_id) + task, assignment, _ = await self._locked_task(task_id, operation, project_id=project_id) exact_project = UUID(task.project_id) if operation is TaskAuthorityOperation.READ: response = await self._repo.read_contributor_task_detail( @@ -908,6 +921,11 @@ async def _read_task_projection(self, task_id: UUID, operation: TaskAuthorityOpe response = response_type(**self._contexts._locked_context_reference_values(task)) if response is None: raise TaskNotFound("task not found") + if operation in {TaskAuthorityOperation.READ, TaskAuthorityOperation.MANAGEMENT_READ}: + own = assignment is not None and assignment.contributor_id == str(self._actor_id) and task.assigned_to == str(self._actor_id) + response = await self._with_pending_submission( + task, response, visible=operation is TaskAuthorityOperation.MANAGEMENT_READ or own, + ) adapter = TypeAdapter(response_type) response = adapter.validate_json(adapter.dump_json(response, warnings="error")) return response @@ -930,6 +948,7 @@ async def contributor_work_context(self, task_id: UUID) -> ContributorTaskWorkCo and task.assigned_to == str(self._actor_id) ) actions = () + detail = await self._with_pending_submission(task, detail, visible=own_assignment) if task.status == "ready" and assignment is None and task.assigned_to is None: actions = ("claim",) selection = context.facts.activation_receipt.command @@ -985,6 +1004,7 @@ async def management_work_context( detail = await self._repo.read_management_task_detail(ManagementTaskDetailRequest(project_id, task_id)) if detail is None: raise TaskNotFound("task not found") + detail = await self._with_pending_submission(task, detail, visible=True) selection = context.facts.activation_receipt.command response = ManagementTaskWorkContext( task=detail, project=context.facts.project, guide=context.facts.guide, diff --git a/backend/tests/tasks/test_pending_submission_authority.py b/backend/tests/tasks/test_pending_submission_authority.py new file mode 100644 index 000000000..293438bb5 --- /dev/null +++ b/backend/tests/tasks/test_pending_submission_authority.py @@ -0,0 +1,160 @@ +"""Pending TASK projection uses fresh operation authority and exact associations.""" + +import pytest +from types import SimpleNamespace +from sqlalchemy import text + +from app.adapters.artifacts import PendingSubmissionReader +from app.core.identifiers import new_record_id +from app.modules.tasks.api.pending_submission import PendingSubmissionOperationUnavailable +from tests.artifacts.test_submission_intake_admission import ( + admission_intake as admission_intake, admit_new, +) +from tests.authentication.fixtures import ( + auth_database_env as auth_database_env, + clear_settings_cache as clear_settings_cache, + rsa_signing_material as rsa_signing_material, +) +from tests.authorization.admin_access.fixtures import ( + signed_access as signed_access, admin_access as admin_access, +) +from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test +from tests.artifacts.intake_recovery_support import recovery_intake as recovery_intake + + +async def remove_fixture_management(f): + async with f.factory() as session: + grants = list(await session.scalars(text(""" + SELECT id FROM admin_role_grants WHERE target_actor_profile_id=:actor + AND role='project_manager' AND status='active' + """), {"actor": f.actor.actor_profile_id})) + assert grants + for grant_id in grants: + revoked = await f.access.signed.revoke(f.access.admin, str(grant_id)) + assert revoked.status_code == 200, revoked.text + + +@pytest.mark.parametrize("stage", ["receiving", "pre_checking"]) +async def test_task_pending_stage_and_revoked_read_authority(admission_intake, tmp_path, stage): + f = admission_intake + await remove_fixture_management(f) + if stage == "receiving": + owner = await admit_new(f) + else: + from tests.artifacts.intake_acceptance_support import completed_source + owner, _, _ = await completed_source(f, tmp_path) + client = f.access.signed.client + path = f"/api/v1/tasks/{f.task}" + for suffix in ("", "/work-context"): + response = await client.get(path + suffix, headers=f.access.target.headers) + assert response.status_code == 200, response.text + detail = response.json()["task"] if suffix else response.json() + assert detail["pending_submission_operation"] == { + "operation_id": str(owner.operation_id), "processing_stage": stage, + } + revoked = await client.post( + f"/api/v1/projects/{f.project}/role-grants/{f.grant_id}/revoke", + headers=f.manager.headers | {"Idempotency-Key": str(new_record_id())}, + json={"reason": "Withdraw submission operation read access"}, + ) + assert revoked.status_code == 200, revoked.text + for suffix in ("", "/work-context"): + response = await client.get(path + suffix, headers=f.access.target.headers) + assert response.status_code == 404, response.text + assert str(owner.operation_id) not in response.text + async with f.factory() as session: + assert await session.scalar(text(""" + SELECT count(*) FROM audit_events + WHERE action_id IN ('task.read','task.work_context.read') AND project_id=:id + AND after_facts->>'allowed'='false' + """), {"id": str(f.project)}) == 2 + manager = await client.get( + f"/api/v1/projects/{f.project}/tasks/{f.task}", headers=f.manager.headers, + ) + assert manager.status_code == 200, manager.text + assert manager.json()["pending_submission_operation"]["operation_id"] == str(owner.operation_id) + + +async def test_pending_reader_rejects_missing_and_cross_task_associations(admission_intake): + f = admission_intake + owner = await admit_new(f) + other_task, other_assignment = new_record_id(), new_record_id() + async with f.factory.kw["bind"].begin() as connection: + await seed_started_task_for_artifact_test(connection, { + "task": str(other_task), "assignment": str(other_assignment), + "project": str(f.project), "actor": str(f.actor.actor_profile_id), + }) + other = SimpleNamespace(**(vars(f) | {"task": other_task, "assignment": other_assignment})) + other_owner = await admit_new(other) + for task_id, operation_id in ((f.task, owner.operation_id), (other_task, other_owner.operation_id)): + async with f.factory() as session, session.begin(): + valid = await PendingSubmissionReader(session, f.actor).read(task_id, operation_id) + assert valid.operation_id == operation_id and valid.processing_stage == "receiving" + for task_id, operation_id in ((other_task, owner.operation_id), (f.task, other_owner.operation_id), (f.task, new_record_id())): + async with f.factory() as session, session.begin(): + with pytest.raises(PendingSubmissionOperationUnavailable): + await PendingSubmissionReader(session, f.actor).read(task_id, operation_id) + async with f.factory() as session: + with pytest.raises(PendingSubmissionOperationUnavailable, match="caller transaction"): + await PendingSubmissionReader(session, f.actor).read(f.task, owner.operation_id) + + +async def test_active_task_pointer_requires_composed_reader(admission_intake, monkeypatch): + import app.adapters.tasks as composition + f = admission_intake + await admit_new(f) + original = composition.task_commands + + def without_reader(*args, **kwargs): + kwargs["pending_submissions"] = None + return original(*args, **kwargs) + + monkeypatch.setattr(composition, "task_commands", without_reader) + response = await f.access.signed.client.get( + f"/api/v1/tasks/{f.task}", headers=f.access.target.headers, + ) + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "task_authority_unavailable" + + +async def test_pending_task_stage_uses_actual_stalled_finalization(recovery_intake): + f, owner = recovery_intake.f, recovery_intake.owner + for prefix, headers in (("/api/v1", f.access.target.headers), + (f"/api/v1/projects/{f.project}", f.manager.headers)): + for suffix in ("", "/work-context"): + response = await f.access.signed.client.get(f"{prefix}/tasks/{f.task}{suffix}", headers=headers) + assert response.status_code == 200, response.text + detail = response.json()["task"] if suffix else response.json() + assert detail["pending_submission_operation"] == { + "operation_id": str(owner.operation_id), "processing_stage": "operationally_stalled", + } + + +async def test_reviewer_task_visibility_does_not_disclose_pending_submitter_operation(admission_intake): + from tests.authorization.task_authority.test_postgresql import grant + f = admission_intake + await remove_fixture_management(f) + await grant(f.access, f.manager, f.project, role="reviewer") + owner = await admit_new(f) + client = f.access.signed.client + path = f"/api/v1/tasks/{f.task}" + before = await client.get(path, headers=f.access.target.headers) + assert before.status_code == 200, before.text + assert before.json()["pending_submission_operation"]["operation_id"] == str(owner.operation_id) + revoked = await client.post( + f"/api/v1/projects/{f.project}/role-grants/{f.grant_id}/revoke", + headers=f.manager.headers | {"Idempotency-Key": str(new_record_id())}, + json={"reason": "Keep reviewer visibility only"}, + ) + assert revoked.status_code == 200, revoked.text + detail = await client.get(path, headers=f.access.target.headers) + assert detail.status_code == 200, detail.text + assert detail.json()["pending_submission_operation"] is None + assert str(owner.operation_id) not in detail.text + context = await client.get(path + "/work-context", headers=f.access.target.headers) + assert context.status_code == 404, context.text + async with f.factory() as session: + assert await session.scalar(text(""" + SELECT count(*) FROM audit_events WHERE action_id='task.submission_operation.read' + AND resource_id=:id AND after_facts->>'allowed'='false' + """), {"id": str(owner.operation_id)}) == 1 diff --git a/backend/tests/tasks/test_pending_submission_progress.py b/backend/tests/tasks/test_pending_submission_progress.py new file mode 100644 index 000000000..6bcb28ce2 --- /dev/null +++ b/backend/tests/tasks/test_pending_submission_progress.py @@ -0,0 +1,76 @@ +"""Task display separates accepted pending work from retained submission history.""" + +from unittest.mock import patch + +import pytest +from sqlalchemy import text + +from tests.retained_material_fixtures import finalize_retained_intake +from tests.submission_fixtures import seed_retained_submission, route_retained_checker_remediation +from tests.test_tasks import ( + task_client, task_database_env, # noqa: F401 -- pytest fixtures + create_active_project, create_started_task, complete_submission_payload, + set_dev_actor, auth_headers, admit_and_grant_project_submitter, +) + + +@pytest.mark.parametrize("revision", [False, True]) +async def test_pending_task_progress_is_authorized_and_clears_after_finalization( + task_client, monkeypatch, revision, # noqa: F811 +): + project = await create_active_project(task_client) + task = await create_started_task(task_client, project["id"], monkeypatch) + predecessor = None + if revision: + predecessor = await seed_retained_submission(task["id"], complete_submission_payload()) + await route_retained_checker_remediation(predecessor) + await admit_and_grant_project_submitter(task_client, monkeypatch, project["id"], "other-reader") + set_dev_actor(monkeypatch, roles="worker", subject="worker-one") + observed = [] + + async def read_details(management=False): + prefix = f"/api/v1/projects/{project['id']}" if management else "/api/v1" + values = [] + for suffix in ("", "/work-context"): + response = await task_client.get(f"{prefix}/tasks/{task['id']}{suffix}", headers=auth_headers()) + assert response.status_code == 200, response.text + body = response.json() + values.append(body["task"] if suffix else body) + return values + + async def inspect_pending(factory, intake): + expected = {"operation_id": str(intake.operation_id), "processing_stage": "finalization_pending"} + with patch("app.adapters.artifacts.create_artifact_store_bootstrap", side_effect=AssertionError("progress opened provider")): + for manager in (False, True): + set_dev_actor(monkeypatch, roles="project_manager" if manager else "worker", + subject="project-manager-subject" if manager else "worker-one") + for detail in await read_details(manager): + assert detail["pending_submission_operation"] == expected + assert detail["status"] == "evaluation_pending" + set_dev_actor(monkeypatch, roles="viewer", subject="other-reader") + for suffix in ("", "/work-context"): + concealed = await task_client.get(f"/api/v1/tasks/{task['id']}{suffix}", headers=auth_headers()) + assert concealed.status_code == 404, concealed.text + assert str(intake.operation_id) not in concealed.text + set_dev_actor(monkeypatch, roles="worker", subject="worker-one") + history = await task_client.get(f"/api/v1/tasks/{task['id']}/submissions", headers=auth_headers()) + if revision: + assert history.status_code == 200, history.text + assert [item["id"] for item in history.json()["items"]] == [predecessor] + else: + assert history.status_code == 404, history.text + async with factory() as session: + assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": task["id"]}) == 0 + observed.append(intake.operation_id) + return await finalize_retained_intake(factory, intake) + + with patch("tests.submission_fixtures.finalize_retained_intake", inspect_pending): + result = await seed_retained_submission( + task["id"], complete_submission_payload(), predecessor_id=predecessor, + ) + assert result != predecessor and len(observed) == 1 + for manager in (False, True): + set_dev_actor(monkeypatch, roles="project_manager" if manager else "worker", + subject="project-manager-subject" if manager else "worker-one") + for detail in await read_details(manager): + assert detail["pending_submission_operation"] is None diff --git a/backend/tests/tasks/test_work_context.py b/backend/tests/tasks/test_work_context.py index 8f1bac951..324d5190e 100644 --- a/backend/tests/tasks/test_work_context.py +++ b/backend/tests/tasks/test_work_context.py @@ -46,7 +46,7 @@ COMMON = {"task_id", "project_id", "title", "description", "task_type", "difficulty", "skill_tags", "estimated_time_minutes", "status", "acceptance_criteria", "rejection_criteria", - "deadline_at", "created_at", "updated_at"} + "deadline_at", "created_at", "updated_at", "pending_submission_operation"} MANAGEMENT = {"source_type", "source_ref", "source_payload_hash", "import_batch_id", "external_task_id", "created_by", "assigned_to"} CONTRIBUTOR = COMMON | {"compensation"} @@ -183,6 +183,8 @@ def test_work_context_openapi(): ("ContributorTaskDetail", "last_assignment_outcome", "TaskAssignmentOutcome"), ("ManagementTaskDetail", "last_assignment_outcome", "TaskAssignmentOutcome"), ("ManagementTaskDetail", "revision_context", "ContributorRevisionContext"), + ("ContributorTaskDetail", "pending_submission_operation", "PendingSubmissionOperation"), + ("ManagementTaskDetail", "pending_submission_operation", "PendingSubmissionOperation"), ): nullable = definitions[name]["properties"][field] assert nullable["anyOf"] == [{"$ref": f"#/components/schemas/{target}"}, {"type": "null"}] @@ -264,9 +266,10 @@ async def test_work_context_public_projections(task_client, monkeypatch): # Nullable audience fields remain explicit; prepared revision contexts # are covered by their journey. assert body["task"]["last_assignment_outcome"] is None + assert body["task"]["pending_submission_operation"] is None assert (body["task"] if management else body)["revision_context"] is None assert set(body["task"]) == fields - for name in fields - {"created_at", "updated_at", "deadline_at", "compensation", "last_assignment_outcome", "revision_context"}: + for name in fields - {"created_at", "updated_at", "deadline_at", "compensation", "last_assignment_outcome", "revision_context", "pending_submission_operation"}: assert body["task"][name] == stored["id" if name == "task_id" else name], name for name in ("created_at", "updated_at", "deadline_at"): assert datetime.fromisoformat(body["task"][name]) == stored[name] diff --git a/cli/internal/api/contributor_tasks.go b/cli/internal/api/contributor_tasks.go index 3f34cf150..3d41abffa 100644 --- a/cli/internal/api/contributor_tasks.go +++ b/cli/internal/api/contributor_tasks.go @@ -45,11 +45,12 @@ type ReadyTaskPage struct { // ContributorTaskDetail excludes management-only source and actor metadata. type ContributorTaskDetail struct { TaskSummary - Description string `json:"description"` - AcceptanceCriteria *string `json:"acceptance_criteria"` - RejectionCriteria *string `json:"rejection_criteria"` - Compensation CompensationTerms `json:"compensation"` - LastAssignmentOutcome *AssignmentOutcome `json:"last_assignment_outcome,omitempty"` + Description string `json:"description"` + AcceptanceCriteria *string `json:"acceptance_criteria"` + RejectionCriteria *string `json:"rejection_criteria"` + Compensation CompensationTerms `json:"compensation"` + LastAssignmentOutcome *AssignmentOutcome `json:"last_assignment_outcome,omitempty"` + PendingSubmissionOperation *PendingSubmissionOperation `json:"pending_submission_operation"` } var exactQuantity = regexp.MustCompile(`^(0|[1-9][0-9]*)(\.[0-9]+)?$`) @@ -143,7 +144,7 @@ func (c *Client) ContributorTask(ctx context.Context, selector string) (Result[C []string{"task_id", "project_id", "title", "description", "status", "created_at", "updated_at"}, []string{"skill_tags", "compensation"}) returned, valid := uuidIdentity(value.TaskID) - if err != nil || !valid || returned != selected || !validTask(value.TaskSummary, value.ProjectID) || !ValidCompensation(value.Compensation) { + if err != nil || !valid || returned != selected || !validTask(value.TaskSummary, value.ProjectID) || !ValidCompensation(value.Compensation) || !validPendingSubmission(value.PendingSubmissionOperation) { return result, &Failure{Code: "invalid_api_response"} } return Result[ContributorTaskDetail]{Raw: raw, Value: value}, nil diff --git a/cli/internal/api/manager_task_context.go b/cli/internal/api/manager_task_context.go index d9e8ca49f..3ff54a456 100644 --- a/cli/internal/api/manager_task_context.go +++ b/cli/internal/api/manager_task_context.go @@ -135,7 +135,7 @@ func (c *Client) ManagementWorkContext(ctx context.Context, project, task string return result, &Failure{Code: "invalid_api_response"} } if err := decodeTask(fields["task"], &value.Task, true); err != nil || !sameUUID(value.Task.TaskID, task) || !validTask(value.Task.TaskSummary, project) || !oneOf(value.Task.Status, taskStatuses...) || !validUUID(value.Task.CreatedBy) || - (value.Task.AssignedTo != nil && !validUUID(*value.Task.AssignedTo)) { + (value.Task.AssignedTo != nil && !validUUID(*value.Task.AssignedTo)) || !validPendingSubmission(value.Task.PendingSubmissionOperation) { return result, &Failure{Code: "invalid_api_response"} } if _, err := contextObject(fields["project"], &value.Project, []string{"id", "name", "slug"}, nil); err != nil || !sameUUID(value.Project.ID, project) { diff --git a/cli/internal/api/pending_submission.go b/cli/internal/api/pending_submission.go new file mode 100644 index 000000000..dd55ad1f9 --- /dev/null +++ b/cli/internal/api/pending_submission.go @@ -0,0 +1,12 @@ +package api + +// PendingSubmissionOperation identifies accepted or in-flight work separately from retained submissions. +type PendingSubmissionOperation struct { + OperationID string `json:"operation_id"` + ProcessingStage string `json:"processing_stage"` +} + +func validPendingSubmission(value *PendingSubmissionOperation) bool { + return value == nil || (validUUID(value.OperationID) && oneOf(value.ProcessingStage, + "receiving", "pre_checking", "finalization_pending", "operationally_stalled")) +} diff --git a/cli/internal/api/task_context.go b/cli/internal/api/task_context.go index fe4fce55e..5e28b6cb9 100644 --- a/cli/internal/api/task_context.go +++ b/cli/internal/api/task_context.go @@ -145,7 +145,7 @@ func (c *Client) WorkContext(ctx context.Context, selector string) (Result[WorkC if err := decodeTaskFields(fields["task"], &value.Task, []string{"task_id", "project_id", "title", "description", "status", "created_at", "updated_at"}, []string{"skill_tags", "compensation"}); err != nil || !sameUUID(value.Task.TaskID, selector) || - !validTask(value.Task.TaskSummary, value.Project.ID) || !ValidCompensation(value.Task.Compensation) { + !validTask(value.Task.TaskSummary, value.Project.ID) || !ValidCompensation(value.Task.Compensation) || !validPendingSubmission(value.Task.PendingSubmissionOperation) { return result, &Failure{Code: "invalid_api_response"} } if _, err := contextObject(fields["project"], &value.Project, []string{"id", "name", "slug"}, nil); err != nil { diff --git a/cli/internal/api/tasks.go b/cli/internal/api/tasks.go index 0b3979464..b2ff86cd4 100644 --- a/cli/internal/api/tasks.go +++ b/cli/internal/api/tasks.go @@ -28,18 +28,19 @@ type TaskSummary struct { type TaskDetail struct { TaskSummary - Description string `json:"description"` - AcceptanceCriteria *string `json:"acceptance_criteria"` - RejectionCriteria *string `json:"rejection_criteria"` - SourceType string `json:"source_type"` - SourceRef *string `json:"source_ref"` - SourcePayloadHash *string `json:"source_payload_hash"` - ImportBatchID *string `json:"import_batch_id"` - ExternalTaskID *string `json:"external_task_id"` - CreatedBy string `json:"created_by"` - AssignedTo *string `json:"assigned_to"` - LastAssignmentOutcome *AssignmentOutcome `json:"last_assignment_outcome,omitempty"` - RevisionContext *RevisionContext `json:"revision_context,omitempty"` + Description string `json:"description"` + AcceptanceCriteria *string `json:"acceptance_criteria"` + RejectionCriteria *string `json:"rejection_criteria"` + SourceType string `json:"source_type"` + SourceRef *string `json:"source_ref"` + SourcePayloadHash *string `json:"source_payload_hash"` + ImportBatchID *string `json:"import_batch_id"` + ExternalTaskID *string `json:"external_task_id"` + CreatedBy string `json:"created_by"` + AssignedTo *string `json:"assigned_to"` + LastAssignmentOutcome *AssignmentOutcome `json:"last_assignment_outcome,omitempty"` + RevisionContext *RevisionContext `json:"revision_context,omitempty"` + PendingSubmissionOperation *PendingSubmissionOperation `json:"pending_submission_operation"` } type TaskPage struct { @@ -178,7 +179,7 @@ func (c *Client) Task(ctx context.Context, project, selector string) (Result[Tas if value.AssignedTo != nil { _, validAssignment = uuidIdentity(*value.AssignedTo) } - if err != nil || !validTask(value.TaskSummary, project) || !valid || selected != returned || !validCreator || !validAssignment { + if err != nil || !validTask(value.TaskSummary, project) || !valid || selected != returned || !validCreator || !validAssignment || !validPendingSubmission(value.PendingSubmissionOperation) { return result, &Failure{Code: "invalid_api_response"} } return Result[TaskDetail]{Raw: raw, Value: value}, nil diff --git a/cli/internal/command/contributor_tasks.go b/cli/internal/command/contributor_tasks.go index c67368f34..55762d20a 100644 --- a/cli/internal/command/contributor_tasks.go +++ b/cli/internal/command/contributor_tasks.go @@ -79,6 +79,9 @@ func addContributorTasks(root *cobra.Command, client func() (*api.Client, error) if err := writeAssignmentOutcome(stdout, t.LastAssignmentOutcome); err != nil { return err } + if err := writePendingSubmission(stdout, t.PendingSubmissionOperation); err != nil { + return err + } _, err = fmt.Fprintf(stdout, "Description: %s\nAcceptance criteria: %s\nRejection criteria: %s\n", safeText(t.Description), optional(t.AcceptanceCriteria), optional(t.RejectionCriteria)) return err diff --git a/cli/internal/command/pending_submission.go b/cli/internal/command/pending_submission.go new file mode 100644 index 000000000..36d4a2b13 --- /dev/null +++ b/cli/internal/command/pending_submission.go @@ -0,0 +1,14 @@ +package command + +import ( + "io" + + "github.com/Flow-Research/workstream/cli/internal/api" +) + +func writePendingSubmission(w io.Writer, pending *api.PendingSubmissionOperation) error { + if pending == nil { + return nil + } + return writeTaskContextFields(w, []contextField{{"Pending submission operation", pending}}) +} diff --git a/cli/internal/command/tasks.go b/cli/internal/command/tasks.go index 4fc020990..73d57ca2e 100644 --- a/cli/internal/command/tasks.go +++ b/cli/internal/command/tasks.go @@ -79,6 +79,9 @@ func addTaskReads(project *cobra.Command, client func() (*api.Client, error), ou if err := writeAssignmentOutcome(stdout, t.LastAssignmentOutcome); err != nil { return err } + if err := writePendingSubmission(stdout, t.PendingSubmissionOperation); err != nil { + return err + } if t.RevisionContext != nil { if err := writeTaskContextFields(stdout, []contextField{{"Revision context", t.RevisionContext}}); err != nil { return err diff --git a/cli/tests/integration/test_task_http_boundary.py b/cli/tests/integration/test_task_http_boundary.py index 7841b391c..6a7e8b626 100644 --- a/cli/tests/integration/test_task_http_boundary.py +++ b/cli/tests/integration/test_task_http_boundary.py @@ -28,6 +28,7 @@ "updated_at": "2026-10-02T00:00:00Z", } DETAIL = SUMMARY | { + "pending_submission_operation": None, "description": "Instructions\n\x1b[32m", "acceptance_criteria": "Accurate", "rejection_criteria": "Missing", diff --git a/cli/tests/integration/test_task_pending_http.py b/cli/tests/integration/test_task_pending_http.py new file mode 100644 index 000000000..36f275783 --- /dev/null +++ b/cli/tests/integration/test_task_pending_http.py @@ -0,0 +1,41 @@ +"""Current task readers preserve pending identity and reject invented stages.""" + +from copy import deepcopy +import json + +import pytest + +from test_contributor_task_http import CONTRIBUTOR +from test_http_boundary import ACTOR, PROJECT, TOKEN, assert_failure, http_fixture +from test_manager_task_evidence_http import MANAGER_CONTEXT +from test_task_context_http import CONTEXT +from test_task_http_boundary import DETAIL, TASK + + +@pytest.mark.parametrize("command,original,nested", [ + (("task", "show", TASK), CONTRIBUTOR, False), + (("task", "context", TASK), CONTEXT, True), + (("project", "task", PROJECT, TASK), DETAIL, False), + (("project", "task-context", PROJECT, TASK), MANAGER_CONTEXT, True), +]) +def test_pending_task_projection_uses_exact_server_identity(cli, command, original, nested): + with http_fixture() as (origin, response, _requests): + for stage in ("receiving", "pre_checking", "finalization_pending", "operationally_stalled"): + body = deepcopy(original) + task = body["task"] if nested else body + task["pending_submission_operation"] = {"operation_id": ACTOR, "processing_stage": stage} + response["body"] = json.dumps(body).encode() + result = cli(origin, TOKEN, *command, "-o", "json") + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout) == body + displayed = cli(origin, TOKEN, *command) + assert displayed.returncode == 0, displayed.stderr + assert ACTOR in displayed.stdout and stage in displayed.stdout + for invalid in ( + {"operation_id": "not-a-uuid", "processing_stage": "receiving"}, + {"operation_id": ACTOR, "processing_stage": "accepted"}, + {"operation_id": ACTOR, "processing_stage": "evaluation_running"}, + ): + task["pending_submission_operation"] = invalid + response["body"] = json.dumps(body).encode() + assert_failure(cli(origin, TOKEN, *command, "-o", "json"), "invalid_api_response") diff --git a/docs/operations_project_operating_manual.md b/docs/operations_project_operating_manual.md index ea8ba929c..23929a6f8 100644 --- a/docs/operations_project_operating_manual.md +++ b/docs/operations_project_operating_manual.md @@ -590,6 +590,14 @@ and manager task facts, the exact historical guide, review/revision references `contribution_policy_version_id`. It omits obsolete payment amounts and submission/precheck flags. Contributor `lifecycle.next_actions` contains only currently applicable claim hints; management has no contributor lifecycle. + +Task detail and the embedded work-context task include +`pending_submission_operation`: either null or the authorized operation's +`operation_id` and `processing_stage`. This identifies work still receiving, +running PRE, awaiting finalization, or explicitly stalled during finalization. +While a revision awaits finalization, its predecessor remains in submission +history; it is not the pending revision. Finalization clears the pending field. +Task visibility and operation-read authority continue to govern these reads. Executing a hint always rechecks authority. Locked policy provenance uses three separate reads (all prefixed by `/api/v1`): diff --git a/mcp_server/contracts/management_task_get.json b/mcp_server/contracts/management_task_get.json index e29e7e0a1..ec317ef6f 100644 --- a/mcp_server/contracts/management_task_get.json +++ b/mcp_server/contracts/management_task_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "f8c0684b499f49b53428332dbfb28038bb2dd3c0a4f2495ecb6868307ec760e3", + "canonical_sha256": "f82719a1566923d782b112b980104e5c471483fdd5951e9686fd73556a7b7d2e", "components": { "schemas": { "ApiError": { @@ -352,6 +352,16 @@ } ] }, + "pending_submission_operation": { + "anyOf": [ + { + "$ref": "#/components/schemas/PendingSubmissionOperation" + }, + { + "type": "null" + } + ] + }, "project_id": { "format": "uuid", "title": "Project Id", @@ -467,6 +477,31 @@ "title": "ManagementTaskDetail", "type": "object" }, + "PendingSubmissionOperation": { + "properties": { + "operation_id": { + "format": "uuid", + "title": "Operation Id", + "type": "string" + }, + "processing_stage": { + "enum": [ + "receiving", + "pre_checking", + "finalization_pending", + "operationally_stalled" + ], + "title": "Processing Stage", + "type": "string" + } + }, + "required": [ + "operation_id", + "processing_stage" + ], + "title": "PendingSubmissionOperation", + "type": "object" + }, "RevisionContextChange": { "additionalProperties": false, "description": "One bounded policy identity change, without provider or finance internals.", diff --git a/mcp_server/contracts/management_task_work_context_get.json b/mcp_server/contracts/management_task_work_context_get.json index 28c112cf4..f188893b5 100644 --- a/mcp_server/contracts/management_task_work_context_get.json +++ b/mcp_server/contracts/management_task_work_context_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "5f285419117ad3839e187997e3109795b0eee334f03e0cd32ca83e4b27c4415b", + "canonical_sha256": "655e95deedfcaf6fa49a2791c4023a4236c2c2067bb0ea73054f89c3d6dd5b9e", "components": { "schemas": { "ApiError": { @@ -424,6 +424,16 @@ } ] }, + "pending_submission_operation": { + "anyOf": [ + { + "$ref": "#/components/schemas/PendingSubmissionOperation" + }, + { + "type": "null" + } + ] + }, "project_id": { "format": "uuid", "title": "Project Id", @@ -575,6 +585,31 @@ "title": "ManagementTaskWorkContext", "type": "object" }, + "PendingSubmissionOperation": { + "properties": { + "operation_id": { + "format": "uuid", + "title": "Operation Id", + "type": "string" + }, + "processing_stage": { + "enum": [ + "receiving", + "pre_checking", + "finalization_pending", + "operationally_stalled" + ], + "title": "Processing Stage", + "type": "string" + } + }, + "required": [ + "operation_id", + "processing_stage" + ], + "title": "PendingSubmissionOperation", + "type": "object" + }, "ProjectDisplayFacts": { "description": "Detached current project description; not a policy or authority input.", "properties": { diff --git a/mcp_server/contracts/task_get.json b/mcp_server/contracts/task_get.json index 27cdcf8f8..73b03f6a0 100644 --- a/mcp_server/contracts/task_get.json +++ b/mcp_server/contracts/task_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "308b9007c563ee66799b9066daf1697b72d078a4d33e70a37e682d7da853205d", + "canonical_sha256": "2974bc5e8d6c4c78b634000fcf5d39971b61c544d4aa7096d695db4552ab23ee", "components": { "schemas": { "ApiError": { @@ -131,6 +131,16 @@ } ] }, + "pending_submission_operation": { + "anyOf": [ + { + "$ref": "#/components/schemas/PendingSubmissionOperation" + }, + { + "type": "null" + } + ] + }, "project_id": { "format": "uuid", "title": "Project Id", @@ -223,6 +233,31 @@ ], "type": "object" }, + "PendingSubmissionOperation": { + "properties": { + "operation_id": { + "format": "uuid", + "title": "Operation Id", + "type": "string" + }, + "processing_stage": { + "enum": [ + "receiving", + "pre_checking", + "finalization_pending", + "operationally_stalled" + ], + "title": "Processing Stage", + "type": "string" + } + }, + "required": [ + "operation_id", + "processing_stage" + ], + "title": "PendingSubmissionOperation", + "type": "object" + }, "TaskAssignmentOutcome": { "additionalProperties": false, "description": "An immutable rejected attempt with no remaining action on its assignment.", diff --git a/mcp_server/contracts/task_work_context_get.json b/mcp_server/contracts/task_work_context_get.json index e661d1aaa..ff2c25d24 100644 --- a/mcp_server/contracts/task_work_context_get.json +++ b/mcp_server/contracts/task_work_context_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "71a41267cce48ef486d90bae34850659edcde9455a75ffd971fcdcb928f43f95", + "canonical_sha256": "9f69f02d8981989465c20891d3c9676c1e09d437ea99c6fbe7860cd071e1c941", "components": { "schemas": { "ApiError": { @@ -354,6 +354,16 @@ } ] }, + "pending_submission_operation": { + "anyOf": [ + { + "$ref": "#/components/schemas/PendingSubmissionOperation" + }, + { + "type": "null" + } + ] + }, "project_id": { "format": "uuid", "title": "Project Id", @@ -601,6 +611,31 @@ ], "type": "object" }, + "PendingSubmissionOperation": { + "properties": { + "operation_id": { + "format": "uuid", + "title": "Operation Id", + "type": "string" + }, + "processing_stage": { + "enum": [ + "receiving", + "pre_checking", + "finalization_pending", + "operationally_stalled" + ], + "title": "Processing Stage", + "type": "string" + } + }, + "required": [ + "operation_id", + "processing_stage" + ], + "title": "PendingSubmissionOperation", + "type": "object" + }, "ProjectDisplayFacts": { "description": "Detached current project description; not a policy or authority input.", "properties": { From 1c1689d6178504a501ce65be23e4c0828660102c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 20:58:56 +0100 Subject: [PATCH 169/513] fix(submissions): enforce pending read contract and exercise selected POST delivery --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 30 +++++++++++++++++++ .../evaluation_delivery/test_completion.py | 21 +++++++------ cli/internal/api/contributor_tasks.go | 2 +- cli/internal/api/task_context.go | 2 +- cli/internal/api/tasks.go | 2 +- .../integration/test_task_http_boundary.py | 1 + .../integration/test_task_pending_http.py | 8 +++++ 7 files changed, 54 insertions(+), 12 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8e9841998..1dfee6aaa 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6032,3 +6032,33 @@ changes; they are not clean-commit CI attestations. ARCH/SEC and QA code reviews found no remaining scoped defect; final clean-candidate review is still required. Downstream completion tests remain running, and full specification qualification, roadmap reconciliation, provider qualification and complete CI remain unfinished. + +Downstream current-source run completes 3 passed/2 failed in 263.13s, cleanup +complete. Both production-registry cases still assume an empty POST policy and +remove execution configuration; current selected policy correctly produces an +infrastructure failure. Bounded repair scope: test_completion.py and this record. +Use the existing ControlledSelectedExecution at the configured external port, +assert one selected execution/member, retain actual production OUTBOX registration, +AUTH, materialization, completion, atomic acceptance/awards and replay assertions. +No production owner, policy bypass, new fake acceptance, or provider qualification +claim. Risk: test validity; QA review and both production-registry cases required. + +Frozen pending review found CLI omission accepted as null although the field is +required by the wire schema. Repair scope: contributor_tasks.go, task_context.go, +tasks.go shared management detail decoder, and test_task_pending_http.py. Require +key presence while retaining explicit null; prove omission rejection and null +success in all four readers. No backend authority or schema change. Replay Go +API and four HTTP readers; ARCH/SEC closure required on the final clean commit. + +Corrected production-registry cases pass 2 in 185.64s with cleanup complete +(/tmp/submission-current-source-outcome-v2.log/json). CLI omission regression +fails against prior v2 binary as intended; corrected Go API passes. Expanded CLI +run passes 24 and fails 1 because the existing manager minimal-response fixture +omits the newly required nullable field. Extend repair scope to that fixture in +test_task_http_boundary.py: retain explicit null in its required-key projection. +Focused unchanged-behavior replay follows; no decoder weakening. + +Final manager minimal-response replay passes 1 in 5.20s. The expanded CLI run's +other 24 cases remain passing, including all four omitted-key/explicit-null +regressions. Changed Python Ruff and diff whitespace checks pass. Final clean +review replay remains required; no full-spec readiness claim. diff --git a/backend/tests/tasks/evaluation_delivery/test_completion.py b/backend/tests/tasks/evaluation_delivery/test_completion.py index 4993150b8..656999f89 100644 --- a/backend/tests/tasks/evaluation_delivery/test_completion.py +++ b/backend/tests/tasks/evaluation_delivery/test_completion.py @@ -287,6 +287,7 @@ async def test_production_registry_delivers_request_then_completion_exactly_once ): """Production registration must consume its own emitted completion event.""" from app.adapters import artifacts as artifact_adapters + from tests.checkers.execution.support import ControlledSelectedExecution awards = () if human else ("money", "project_points") async with material_fixture( @@ -305,14 +306,14 @@ async def test_production_registry_delivers_request_then_completion_exactly_once assert accepted.rowcount == 1 await provision_router(h.factory) await delivery_fixture(h) - # An empty locked POST policy completes without constructing or - # contacting the external service. Actual image execution is covered - # by the production Rust/MinIO probe. - settings = h.settings.model_copy(update={ - "external_checker_service_socket": None, - "external_checker_material_root": None, - }) - monkeypatch.setattr("app.core.config.get_settings", lambda: settings) + # Keep the selected POST image and real execution owner; control only + # the external port. This proves delivery/acceptance, not native isolation. + selected = ControlledSelectedExecution() + monkeypatch.setattr("app.core.config.get_settings", lambda: h.settings) + monkeypatch.setattr( + "app.adapters.checkers.configured_post_submit_external_execution", + lambda settings, *, sessions: selected, + ) monkeypatch.setattr( artifact_adapters, "worker_post_submission_materialization", @@ -333,7 +334,9 @@ async def test_production_registry_delivers_request_then_completion_exactly_once assert outcome(request_receipt)["delivery_state"] == "acknowledged", outcome(request_receipt) completed = await state(h) assert completed["run"]["status"] == "completed" - assert completed["members"] == 0 + assert completed["members"] == 1 + assert len(selected.requests) == 1 + assert selected.requests[0].identity.phase == "post_submit" completion_event_id = completed["run"]["completion_event_id"] assert completion_event_id is not None diff --git a/cli/internal/api/contributor_tasks.go b/cli/internal/api/contributor_tasks.go index 3d41abffa..3d2ff8429 100644 --- a/cli/internal/api/contributor_tasks.go +++ b/cli/internal/api/contributor_tasks.go @@ -142,7 +142,7 @@ func (c *Client) ContributorTask(ctx context.Context, selector string) (Result[C var value ContributorTaskDetail err = decodeTaskFields(raw, &value, []string{"task_id", "project_id", "title", "description", "status", "created_at", "updated_at"}, - []string{"skill_tags", "compensation"}) + []string{"skill_tags", "compensation", "pending_submission_operation"}) returned, valid := uuidIdentity(value.TaskID) if err != nil || !valid || returned != selected || !validTask(value.TaskSummary, value.ProjectID) || !ValidCompensation(value.Compensation) || !validPendingSubmission(value.PendingSubmissionOperation) { return result, &Failure{Code: "invalid_api_response"} diff --git a/cli/internal/api/task_context.go b/cli/internal/api/task_context.go index 5e28b6cb9..c23665199 100644 --- a/cli/internal/api/task_context.go +++ b/cli/internal/api/task_context.go @@ -144,7 +144,7 @@ func (c *Client) WorkContext(ctx context.Context, selector string) (Result[WorkC } if err := decodeTaskFields(fields["task"], &value.Task, []string{"task_id", "project_id", "title", "description", "status", "created_at", "updated_at"}, - []string{"skill_tags", "compensation"}); err != nil || !sameUUID(value.Task.TaskID, selector) || + []string{"skill_tags", "compensation", "pending_submission_operation"}); err != nil || !sameUUID(value.Task.TaskID, selector) || !validTask(value.Task.TaskSummary, value.Project.ID) || !ValidCompensation(value.Task.Compensation) || !validPendingSubmission(value.Task.PendingSubmissionOperation) { return result, &Failure{Code: "invalid_api_response"} } diff --git a/cli/internal/api/tasks.go b/cli/internal/api/tasks.go index b2ff86cd4..d71c0b49b 100644 --- a/cli/internal/api/tasks.go +++ b/cli/internal/api/tasks.go @@ -204,7 +204,7 @@ func decodeTask(raw json.RawMessage, value any, detail bool) error { required = append(required, "skill_tags") if detail { strings = append(strings, "description", "source_type", "created_by") - required = append(required, "description", "source_type", "created_by") + required = append(required, "description", "source_type", "created_by", "pending_submission_operation") } else { required = append(required, "task_type", "difficulty", "estimated_time_minutes", "deadline_at") } diff --git a/cli/tests/integration/test_task_http_boundary.py b/cli/tests/integration/test_task_http_boundary.py index 6a7e8b626..594d8ce16 100644 --- a/cli/tests/integration/test_task_http_boundary.py +++ b/cli/tests/integration/test_task_http_boundary.py @@ -130,6 +130,7 @@ def test_manager_task_reads_preserve_fields_and_wire(cli): "description", "source_type", "created_by", + "pending_submission_operation", } } for value in ( diff --git a/cli/tests/integration/test_task_pending_http.py b/cli/tests/integration/test_task_pending_http.py index 36f275783..074527dfc 100644 --- a/cli/tests/integration/test_task_pending_http.py +++ b/cli/tests/integration/test_task_pending_http.py @@ -39,3 +39,11 @@ def test_pending_task_projection_uses_exact_server_identity(cli, command, origin task["pending_submission_operation"] = invalid response["body"] = json.dumps(body).encode() assert_failure(cli(origin, TOKEN, *command, "-o", "json"), "invalid_api_response") + task["pending_submission_operation"] = None + response["body"] = json.dumps(body).encode() + explicit_null = cli(origin, TOKEN, *command, "-o", "json") + assert explicit_null.returncode == 0, explicit_null.stderr + assert json.loads(explicit_null.stdout) == body + del task["pending_submission_operation"] + response["body"] = json.dumps(body).encode() + assert_failure(cli(origin, TOKEN, *command, "-o", "json"), "invalid_api_response") From 62c138605387da4793a060ec5e03c8fc68257f2a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 21:00:25 +0100 Subject: [PATCH 170/513] docs(submissions): clarify pending projection validation evidence --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 1dfee6aaa..59697579d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6044,7 +6044,8 @@ No production owner, policy bypass, new fake acceptance, or provider qualificati claim. Risk: test validity; QA review and both production-registry cases required. Frozen pending review found CLI omission accepted as null although the field is -required by the wire schema. Repair scope: contributor_tasks.go, task_context.go, +required by the intended CLI projection contract. The generated OpenAPI DTO +schema permits omission because the backend field defaults to None. Repair scope: contributor_tasks.go, task_context.go, tasks.go shared management detail decoder, and test_task_pending_http.py. Require key presence while retaining explicit null; prove omission rejection and null success in all four readers. No backend authority or schema change. Replay Go From 4708bb358de88448b8264644d1df4441289381dd Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 21:06:25 +0100 Subject: [PATCH 171/513] fix(ci): register pending submission API in behavior inventory --- .ci/behavior-ownership/partition.v1.json | 6 +++++- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 17 +++++++++++++++++ backend/scripts/behavior_ownership.py | 1 + backend/tests/test_behavior_ownership.py | 1 + 4 files changed, 24 insertions(+), 1 deletion(-) diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 287d4ea30..1e40950e7 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -2292,6 +2292,10 @@ "group": "lifecycle", "target": "backend/app/modules/tasks/api/management_queue.py" }, + { + "group": "lifecycle", + "target": "backend/app/modules/tasks/api/pending_submission.py" + }, { "group": "lifecycle", "target": "backend/app/modules/tasks/api/post_submit_routing.py" @@ -2773,7 +2777,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "d416a689c5079db878d9baa8a5008a63ef892cf8745cba615d4eab8066cf74db", + "authority_digest": "69033945f9e74f3e3391cde0ac8e8f7c80a29ec88242a46d32f0482c651a92bf", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 59697579d..65f6da830 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6063,3 +6063,20 @@ Final manager minimal-response replay passes 1 in 5.20s. The expanded CLI run's other 24 cases remain passing, including all four omitted-key/explicit-null regressions. Changed Python Ruff and diff whitespace checks pass. Final clean review replay remains required; no full-spec readiness claim. + +Head62c138605 hosted preflight fails behavior_ownership partition_target_mismatch +(job133573919169); prior module/AUTH/structure checks and 92 architecture tests +pass. Exact inventory diff shows only missing +backend/app/modules/tasks/api/pending_submission.py, no stale targets. Bounded +repair scope: behavior_ownership.py existing SUBMISSION_INTAKE_TARGETS exact set, +partition.v1.json, existing exact-addition test, and this record. Preserve original +protected base, all retained assignments, group rules and unrelated-path rejection. +No new wildcard, bypass, reviewed behavior claim, or catalogue population. CI +integrity/QA review required; verify partition/catalogue plus validator tests. + +Partition repair verification: complete behavior-ownership validator suite passes +170 in 8.77s (one unknown asyncio config warning with plugin autoload disabled). +Catalogue validation exits0 with existing unresolved population listed, not +claimed reviewed. Exact diff adds only the pending TASK API lifecycle assignment +and its digest; protected base and retained assignments remain unchanged. Ruff +and whitespace checks pass. Hosted rerun and scoped CI review remain pending. diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index ada40e9be..23c9ab1b9 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -977,6 +977,7 @@ "backend/app/adapters/artifacts/local_submission_source.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", + "backend/app/modules/tasks/api/pending_submission.py", "backend/app/modules/tasks/intake_custody.py", }) FORGE_PROOF_FACTS_TARGETS = frozenset({ diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index a1c02dfda..2ff537334 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2803,6 +2803,7 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ "backend/app/adapters/artifacts/local_submission_source.py", "backend/app/modules/artifacts/intake/repository.py", "backend/app/modules/tasks/api/intake_custody.py", + "backend/app/modules/tasks/api/pending_submission.py", "backend/app/modules/tasks/intake_custody.py", } assert ownership.SUBMISSION_INTAKE_TARGETS == additions From 86a1bfb807a71a747e044388a018eeb810bb335a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 21:10:43 +0100 Subject: [PATCH 172/513] fix(ci): include submission proofs in test lanes and format CLI test --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 26 +++++++++++++ backend/scripts/test_lane_catalogue.py | 4 ++ backend/tests/test_ci_lane_catalogue.py | 14 ++++--- .../integration/test_task_pending_http.py | 39 +++++++++++++------ 4 files changed, 66 insertions(+), 17 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 65f6da830..e62ef3da6 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6080,3 +6080,29 @@ Catalogue validation exits0 with existing unresolved population listed, not claimed reviewed. Exact diff adds only the pending TASK API lifecycle assignment and its digest; protected base and retained assignments remain unchanged. Ruff and whitespace checks pass. Hosted rerun and scoped CI review remain pending. + +Further hosted diagnostics before pushing the repair: every sampled backend lane +stops at missing_lane_modules for the four new cleanup/manifest/pending tests; +CLI API and HTTP jobs stop at Ruff format for test_task_pending_http.py. Extend +bounded CI repair scope to test_lane_catalogue.py and that CLI formatting only. +Assign both artifact tests alongside existing POST materialization and both TASK +progress tests alongside work-context; preserve completeness/error propagation, +SDK selection, infrastructure requirements and timeouts. No excluded/skipped test +or workflow weakening. Run lane validator tests and full CLI lint/format gates; +CI integrity review required on clean combined candidate. +Separately, current economic facts proof passes all three unpaid/one-award/two-award +cases in136.19s, cleanup complete (/tmp/submission-current-economic-facts-v1). +It verifies exact FinalAcceptance, ContributionRecord and award facts/replay with +no fabricated human Review; this remains controlled execution owner proof. + +Lane validator first run:201pass/3fail20.11s. Failures are independent exact +membership assertions for the intended four additions, not runtime failures. +Extend scope to test_ci_lane_catalogue.py: add the two POST modules to expected +delivery membership, update project256→258/task94→96 canonical family hashes, +and project ownership hash. Preserve exact comparisons and negative controls. + +Final lane catalogue/evidence/runner tests pass204; repository discovery now +covers all collected modules with exact ownership and unchanged rejection gates. +Full CLI Ruff check and format check pass99files; AST comparison confirms the +pending HTTP formatting changes no behavior. Scoped combined CI review and hosted +rerun remain required. No full-suite or provider qualification claim. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index a64bbc586..9c24b84a2 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -585,6 +585,8 @@ class TestLane: "tests/checkers/execution/test_delivery_reconciliation_custody.py", "tests/checkers/execution/test_delivery_reconciliation_public.py", "tests/test_post_submit_materialization.py", + "tests/artifacts/test_post_source_cleanup.py", + "tests/artifacts/test_post_source_manifest.py", "tests/test_post_submit_selection.py", "tests/test_checker_output_custody.py", "tests/test_checker_output_storage.py", @@ -664,6 +666,8 @@ class TestLane: "tests/project_reads/test_consistency.py", "tests/tasks/test_task_detail.py", "tests/tasks/test_work_context.py", + "tests/tasks/test_pending_submission_authority.py", + "tests/tasks/test_pending_submission_progress.py", "tests/tasks/test_guide_documents.py", "tests/project_reads/test_guide_document_content.py", "tests/tasks/test_locked_context.py", diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 872fb2500..3aef12bb9 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -129,6 +129,8 @@ def test_checker_delivery_and_routing_preparation_partition_every_node_once() -> "tests/checkers/execution/test_delivery_reconciliation_custody.py", "tests/checkers/execution/test_delivery_reconciliation_public.py", "tests/test_post_submit_materialization.py", + "tests/artifacts/test_post_source_cleanup.py", + "tests/artifacts/test_post_source_manifest.py", "tests/test_post_submit_selection.py", "tests/test_checker_output_custody.py", "tests/test_checker_output_storage.py", @@ -322,12 +324,12 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: "e9280bafac00f22e4bd54acd1c6dcd3699411a927269f5132f3cc39ca31224a1", ), "project": ( - 256, - "65376b7218792edcf026d5f851fb85d909a59ad7df363f6904e04e501ba5118d", + 258, + "d1c3c2852afa36476206c00129dcd8b63a10b187b0ad8634e6f894a20cd4deed", ), "task": ( - 94, - "49ae5e1b0b26ee4b71fd117e0502802a1e1439850628f1ed0d65130c38c0c4d9", + 96, + "dfd8a2c63b43d85422eaf9f98fe30ef9a044a492a7e8270261de9c2b491a0eb3", ), } actual = { @@ -395,9 +397,9 @@ def test_project_lane_ownership_has_an_independent_fingerprint() -> None: ) + "\n" ) - assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 256 + assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 258 assert hashlib.sha256(canonical.encode()).hexdigest() == ( - "ed9527add277491e0b20f495767bdf844cecdffa518ce8854109e3b3bcfbe56b" + "f2581105d16fe388d824b0e50b017aa10f97ba7cbf5df27a8121d5591d2be96d" ) diff --git a/cli/tests/integration/test_task_pending_http.py b/cli/tests/integration/test_task_pending_http.py index 074527dfc..8dd62b68a 100644 --- a/cli/tests/integration/test_task_pending_http.py +++ b/cli/tests/integration/test_task_pending_http.py @@ -12,18 +12,31 @@ from test_task_http_boundary import DETAIL, TASK -@pytest.mark.parametrize("command,original,nested", [ - (("task", "show", TASK), CONTRIBUTOR, False), - (("task", "context", TASK), CONTEXT, True), - (("project", "task", PROJECT, TASK), DETAIL, False), - (("project", "task-context", PROJECT, TASK), MANAGER_CONTEXT, True), -]) -def test_pending_task_projection_uses_exact_server_identity(cli, command, original, nested): +@pytest.mark.parametrize( + "command,original,nested", + [ + (("task", "show", TASK), CONTRIBUTOR, False), + (("task", "context", TASK), CONTEXT, True), + (("project", "task", PROJECT, TASK), DETAIL, False), + (("project", "task-context", PROJECT, TASK), MANAGER_CONTEXT, True), + ], +) +def test_pending_task_projection_uses_exact_server_identity( + cli, command, original, nested +): with http_fixture() as (origin, response, _requests): - for stage in ("receiving", "pre_checking", "finalization_pending", "operationally_stalled"): + for stage in ( + "receiving", + "pre_checking", + "finalization_pending", + "operationally_stalled", + ): body = deepcopy(original) task = body["task"] if nested else body - task["pending_submission_operation"] = {"operation_id": ACTOR, "processing_stage": stage} + task["pending_submission_operation"] = { + "operation_id": ACTOR, + "processing_stage": stage, + } response["body"] = json.dumps(body).encode() result = cli(origin, TOKEN, *command, "-o", "json") assert result.returncode == 0, result.stderr @@ -38,7 +51,9 @@ def test_pending_task_projection_uses_exact_server_identity(cli, command, origin ): task["pending_submission_operation"] = invalid response["body"] = json.dumps(body).encode() - assert_failure(cli(origin, TOKEN, *command, "-o", "json"), "invalid_api_response") + assert_failure( + cli(origin, TOKEN, *command, "-o", "json"), "invalid_api_response" + ) task["pending_submission_operation"] = None response["body"] = json.dumps(body).encode() explicit_null = cli(origin, TOKEN, *command, "-o", "json") @@ -46,4 +61,6 @@ def test_pending_task_projection_uses_exact_server_identity(cli, command, origin assert json.loads(explicit_null.stdout) == body del task["pending_submission_operation"] response["body"] = json.dumps(body).encode() - assert_failure(cli(origin, TOKEN, *command, "-o", "json"), "invalid_api_response") + assert_failure( + cli(origin, TOKEN, *command, "-o", "json"), "invalid_api_response" + ) From fc70c536201ba8110788a9a6843a9158c91cd09d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 21:33:30 +0100 Subject: [PATCH 173/513] docs(submissions): explain source custody and continuation contracts --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 75 ++++++++++++ .../artifacts/local_submission_source.py | 18 +++ .../app/adapters/artifacts/source_cleanup.py | 9 ++ .../artifacts/api/submission_cleanup.py | 9 +- .../artifacts/api/submission_command.py | 4 + .../artifacts/api/submission_finalization.py | 1 + .../artifacts/api/submission_recovery.py | 17 ++- .../modules/artifacts/intake/acceptance.py | 3 + .../modules/artifacts/intake/finalization.py | 10 ++ .../artifacts/intake/finalization_delivery.py | 5 + .../authorization/api/submission_intake.py | 44 +++++-- .../modules/checkers/api/source_contracts.py | 114 +++++++++++++----- .../modules/tasks/api/pending_submission.py | 3 + 13 files changed, 270 insertions(+), 42 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e62ef3da6..e8400faa7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6106,3 +6106,78 @@ covers all collected modules with exact ownership and unchanged rejection gates. Full CLI Ruff check and format check pass99files; AST comparison confirms the pending HTTP formatting changes no behavior. Scoped combined CI review and hosted rerun remain required. No full-suite or provider qualification claim. + +A12 target-change proof scope: test_tasks.py and accepted_revision_probes.py. +ARCH/SEC review establishes legitimate PM repair cannot commit a changed target +while active intake protects its locked snapshot (0069 deferred custody guard); +after T4, evaluation_pending also makes repair ineligible. Test completed real +revision PRE before opening T4, activate a genuine successor guide, call authorized +PM repair, require named custody rejection and rollback of TASK/preparation/audit/ +outbox effects, then complete original T4/T5 under unchanged lineage. No trigger +bypass, fabricated acceptance, clock mutation or independent SQL target-check +claim. Keep existing stale-fence proof separate. QA/ARCH review and focused real +PostgreSQL execution required. This closes legitimate target-change interleaving +proof, not all A12 scenarios or provider/native qualification. + +Current request-delivery local/MinIO baseline fails2 in96.58s, cleanup complete +including owned MinIO bucket. Real selected POST is unconfigured in the shared +old empty-policy fixture, yielding infrastructure_failed. Bounded fixture repair: +evaluation_delivery/support.py and test_delivery.py. Bind existing controlled +selected execution only while composing the test handler (captured constructor +port), preserve production registry/authority/materialization, and assert exact +one selected result/request. No product fallback, provider qualification claim or +runtime bypass. QA proof: full delivery file including lostack, revocation and +eligibility, real local/MinIO storage, then affected delivery consumers as needed. + +Affected delivery-consumer trace finds old open(reference) hooks in custody and +worker materialization tests; current POST reads open_source(exact source). +Extend scope to those two tests: move pauses/missing-object injection to the +current port with kwargs forwarded, retain cancellation/unknown/cleanup guards. +Do not add a production alias. ARCH/SEC A12 code review requests explicit changed +v2-versus-locked-guide assertion; added. Final execution must include it. + +Hosted86a preflight now reaches existing docstr gate and fails78.8% against80. +Scope documentation-only repair to new submission code: checker API source_contracts; +local_submission_source/source_cleanup adapters; ART intake acceptance/finalization/ +finalization_delivery; ART API submission_recovery/submission_command/submission_cleanup/ +submission_finalization; AUTH API submission_intake; TASK API pending_submission. +Document source identity, bounds, custody, cleanup and authority contracts after +reading implementations. Do not alter logic, annotations, interfaces, coverage +configuration or unrelated old files. Verify normalized AST equality excluding +docstrings, Ruff and unchanged docstr gate; docs review for accuracy required. + +Final A12 target/fence replay passes2 in121.84s (existing serializer warning), +cleanup complete. Local/MinIO delivery passes5 in141.14s, database and bucket +cleanup complete. Two cancellation custody tests pass; three worker cases first +error because the runner omitted MinIO endpoint (no product failure), then fail +on obsolete Consumer(files) signature and one-event count. Pass the actual +material execution to Consumer and assert the two real T4/T5 request events; +retain all source cancellation and missing-object assertions. Replay entire +worker materialization file. Documentation review corrects removal wording: +provider deletes bytes, not custody; all MCP selected fragments remain unchanged. +Hosted CLI API collection exposes ambiguous historical fixture import from +conftest resolving CLI conftest. Extend scope to historical_submission_fixtures.py: +use existing tests.conftest qualified owner import, preserve database ownership +assertion unchanged. Verify collection of all four affected public modules. + +Shared Consumer trace also finds obsolete one-argument consumers in authorization +post_submit test_principals/test_atomicity/test_live_authority/test_receipt_custody +and test_post_submit_selection. Extend scope to supply each existing real execution +lease, constructing consumers only for materialize phases. Preserve denial, +rollback and positive-control assertions; no optional/compatibility constructor. +QA also requires paused source wrappers to close their inner iterator in finally; +add explicit aclose forwarding in custody/worker tests, preserving cancellation. + +Checkpoint evidence: final A12 pair2pass121.84s; local/MinIO delivery5pass141.14s; +signed CLI raw-ZIP progress/replay/history/suspension1pass129.46s. All receipts +confirm owned database cleanup and delivery MinIO bucket cleanup. Structural +validator v2 exits0. CLI four-module collection5nodes succeeds (existing custom +marker warnings). Source cleanup wording corrected per DOC-CLEANUP-001; QA-HOOK-001 +addressed with deterministic inner iterator closure. All12 documented production +files retain identical executable AST excluding docstrings. Existing docstr gate +passes6957/8692=80.0%; all selected MCP fragments match actual generated OpenAPI, +so no snapshot regeneration is needed. Ruff and whitespace checks pass. +Full worker-materialization run and affected authorization/material consumer run +are still active; the final close-forwarding hooks require their focused replay. +Do not treat this checkpoint as full CI/provider/spec readiness. Hosted preflight +and CLI collection fixes still require rerun on the final pushed head. diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py index 53a871307..5f1c14d7e 100644 --- a/backend/app/adapters/artifacts/local_submission_source.py +++ b/backend/app/adapters/artifacts/local_submission_source.py @@ -33,9 +33,11 @@ class LocalSubmissionSource: """Private synchronous primitives, called off-loop with cancellation drained.""" def __init__(self, store: Any) -> None: + """Bind filesystem primitives to the initialized local store owner.""" self.store = store def location(self, value: SubmissionSourceLocation) -> SubmissionSourceLocation: + """Validate the location against the pinned local provider namespace.""" self.store._require_initialized() value = SubmissionSourceLocation.model_validate(value) if (value.provider_profile != "local-v2" @@ -45,6 +47,7 @@ def location(self, value: SubmissionSourceLocation) -> SubmissionSourceLocation: @staticmethod def deadline(intent: SubmissionSourceUploadIntent) -> float: + """Return remaining upload time or reject an expired deadline.""" remaining = (intent.upload_deadline_at - datetime.now(UTC)).total_seconds() if remaining <= 0: raise ArtifactStoreUnavailableError("submission upload deadline expired") @@ -52,6 +55,7 @@ def deadline(intent: SubmissionSourceUploadIntent) -> float: @contextmanager def locked(self, location: SubmissionSourceLocation, intent: SubmissionSourceUploadIntent | None = None, *, create: bool = False) -> Iterator[int]: + """Hold the operation lock and yield its safely opened source directory.""" location = self.location(location) key = hashlib.sha256(location.object_ref.encode()).hexdigest() lock_fd = os.open(key + ".lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, @@ -82,6 +86,7 @@ def locked(self, location: SubmissionSourceLocation, intent: SubmissionSourceUpl os.close(lock_fd) def read(self, directory: int, name: str) -> bytes: + """Read bounded private metadata without following symbolic links.""" descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) try: info = self.store._assert_private_regular(descriptor) @@ -99,6 +104,7 @@ def read(self, directory: int, name: str) -> bytes: def publish(self, directory: int, name: str, value: dict[str, Any]) -> None: # Every caller holds the same operation lock. Only metadata is renamed; # the raw ZIP remains at its original key and inode from begin onward. + """Persist new metadata atomically while the caller holds the operation lock.""" try: os.stat(name, dir_fd=directory, follow_symlinks=False) except FileNotFoundError: @@ -120,6 +126,7 @@ def publish(self, directory: int, name: str, value: dict[str, Any]) -> None: os.fsync(directory) def upload(self, directory: int, supplied: SubmissionSourceUpload) -> SubmissionSourceUpload: + """Require the supplied upload identity to match stored metadata.""" stored = SubmissionSourceUpload.model_validate_json(self.read(directory, "upload.json")) if stored != supplied: raise ArtifactOperationConflictError("submission upload identity mismatch") @@ -127,6 +134,7 @@ def upload(self, directory: int, supplied: SubmissionSourceUpload) -> Submission @staticmethod def exists(directory: int, name: str) -> bool: + """Check directory-relative presence without following symbolic links.""" try: os.stat(name, dir_fd=directory, follow_symlinks=False) return True @@ -134,6 +142,7 @@ def exists(directory: int, name: str) -> bool: return False def begin(self, intent: SubmissionSourceUploadIntent) -> SubmissionSourceUpload: + """Create one upload receipt and its original private ZIP inode.""" intent = SubmissionSourceUploadIntent.model_validate(intent) with self.locked(intent.location, intent, create=True) as directory: if self.exists(directory, "upload.json") or self.exists(directory, "aborted.json"): @@ -151,6 +160,7 @@ def begin(self, intent: SubmissionSourceUploadIntent) -> SubmissionSourceUpload: return upload def part(self, upload: SubmissionSourceUpload, number: int, data: bytes) -> SubmissionSourcePart: + """Append the next bounded part under the upload lock and deadline.""" upload = SubmissionSourceUpload.model_validate(upload) if type(number) is not int or not 1 <= number <= 100 or type(data) is not bytes or not data: raise ArtifactInputMismatchError("submission source part is invalid") @@ -178,6 +188,7 @@ def part(self, upload: SubmissionSourceUpload, number: int, data: bytes) -> Subm provider_etag=hashlib.sha256(data).hexdigest()) def verify(self, descriptor: int, completion: SubmissionSourceCompletion) -> os.stat_result: + """Stream-check part receipts, total length and raw digest on the opened inode.""" info = self.store._assert_private_regular(descriptor) if info.st_size != completion.raw_byte_count: raise ArtifactIntegrityError("submission source size mismatch") @@ -202,6 +213,7 @@ def verify(self, descriptor: int, completion: SubmissionSourceCompletion) -> os. @staticmethod def source(completion: SubmissionSourceCompletion, info: os.stat_result) -> SealedSubmissionSource: + """Bind the completion facts to the upload token and physical inode.""" return SealedSubmissionSource( location=completion.upload.intent.location, provider_generation=f"{completion.upload.provider_upload_id}:{info.st_dev}:{info.st_ino}", @@ -210,6 +222,7 @@ def source(completion: SubmissionSourceCompletion, info: os.stat_result) -> Seal ) def complete(self, completion: SubmissionSourceCompletion) -> SealedSubmissionSource: + """Verify the ZIP, persist its seal and make the same inode read-only.""" completion = SubmissionSourceCompletion.model_validate(completion) upload = completion.upload with self.locked(upload.intent.location, upload.intent) as directory: @@ -258,6 +271,7 @@ def observe_sealed(self, source: SealedSubmissionSource) -> SealedSourceObservat return None def observe(self, completion: SubmissionSourceCompletion) -> SealedSubmissionSource | None: + """Resolve uncertain completion only from matching sealed metadata and bytes.""" completion = SubmissionSourceCompletion.model_validate(completion) try: with self.locked(completion.upload.intent.location) as directory: @@ -281,6 +295,7 @@ def observe(self, completion: SubmissionSourceCompletion) -> SealedSubmissionSou return None def discover(self, intent: SubmissionSourceUploadIntent) -> tuple[SubmissionSourceUpload, ...]: + """Find handles for this exact intent without adopting foreign upload state.""" intent = SubmissionSourceUploadIntent.model_validate(intent) try: with self.locked(intent.location) as directory: @@ -305,6 +320,7 @@ def discover(self, intent: SubmissionSourceUploadIntent) -> tuple[SubmissionSour return () def abort(self, upload: SubmissionSourceUpload) -> None: + """Fence unfinished writes while preserving a successfully sealed source.""" upload = SubmissionSourceUpload.model_validate(upload) try: with self.locked(upload.intent.location) as directory: @@ -379,6 +395,7 @@ def delete_sealed(self, source: SealedSubmissionSource, upload: SubmissionSource os.close(descriptor) def seal(self, directory: int) -> tuple[SubmissionSourceCompletion, SealedSubmissionSource]: + """Decode the exact completion and source pair from bounded seal metadata.""" value = json.loads(self.read(directory, "seal.json")) if not isinstance(value, dict) or set(value) != {"completion", "source"}: raise ArtifactIntegrityError("submission source seal is invalid") @@ -388,6 +405,7 @@ def seal(self, directory: int) -> tuple[SubmissionSourceCompletion, SealedSubmis ) def chunk(self, source: SealedSubmissionSource, position: int, maximum_chunk_bytes: int) -> bytes: + """Read bounded bytes after rechecking the sealed generation and inode state.""" source = SealedSubmissionSource.model_validate(source) with self.locked(source.location) as directory: completion, sealed = self.seal(directory) diff --git a/backend/app/adapters/artifacts/source_cleanup.py b/backend/app/adapters/artifacts/source_cleanup.py index 2d06b31db..a5030d8da 100644 --- a/backend/app/adapters/artifacts/source_cleanup.py +++ b/backend/app/adapters/artifacts/source_cleanup.py @@ -8,17 +8,21 @@ class LocalSubmissionSourceCleanup: """Separate composition-owned capability over the pinned Local namespace.""" def __init__(self, store): + """Bind cleanup to the local namespace and its source primitives.""" self._store = store self._source = LocalSubmissionSource(store) @property def identity(self): + """Advertise the separate source-cleanup capability and adapter name.""" return ExternalServiceAdapterIdentity(SUBMISSION_SOURCE_CLEANUP_CAPABILITY, "local") def close(self): + """Release the cleanup store resources.""" self._store.close() async def remove(self, source, upload): + """Delete exact sealed bytes and observe object and part absence.""" await self._store._source_io(self._source.delete_sealed, source, upload) # The shared operation lock drains Local writers. Retained seal/upload # metadata prevent subsequent begin/part/complete from reopening the key. @@ -35,16 +39,20 @@ class S3SubmissionSourceCleanup: """ def __init__(self, cleanup_store): + """Bind the separately credentialed cleanup store supplied by composition.""" self._store = cleanup_store @property def identity(self): + """Advertise the separate source-cleanup capability and adapter name.""" return ExternalServiceAdapterIdentity(SUBMISSION_SOURCE_CLEANUP_CAPABILITY, "s3_compatible") def close(self): + """Release the cleanup store resources.""" self._store.close() async def _absent(self, source): + """Prove exact-version absence without treating bucket loss or denial as cleanup.""" from botocore.exceptions import ClientError from app.interfaces.artifacts import ArtifactProviderOperationEvidence @@ -71,6 +79,7 @@ async def _absent(self, source): return False async def remove(self, source, upload): + """Delete only the sealed version and retain unresolved handle or version obligations.""" from app.interfaces.artifacts import ArtifactOperationConflictError, ArtifactProviderOperationEvidence from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceUpload diff --git a/backend/app/modules/artifacts/api/submission_cleanup.py b/backend/app/modules/artifacts/api/submission_cleanup.py index 0a393c447..414b7d910 100644 --- a/backend/app/modules/artifacts/api/submission_cleanup.py +++ b/backend/app/modules/artifacts/api/submission_cleanup.py @@ -11,6 +11,7 @@ @dataclass(frozen=True, slots=True) class SubmissionSourceCleanupAuthorityFacts: + """Bind cleanup claim or confirmation to an exact operation and source digest.""" operation_id: UUID project_id: UUID task_id: UUID @@ -33,6 +34,10 @@ class SubmissionSourceRemoval: class SubmissionSourceCleanupProvider(ExternalServiceAdapter, Protocol): """Separate deletion capability supplied only to the audited coordinator.""" - async def remove(self, source: SealedSubmissionSource, upload: SubmissionSourceUpload) -> SubmissionSourceRemoval: ... + async def remove(self, source: SealedSubmissionSource, upload: SubmissionSourceUpload) -> SubmissionSourceRemoval: + """Remove exact sealed-source bytes and return independent settlement observations.""" + ... - def close(self) -> None: ... + def close(self) -> None: + """Release the separately composed cleanup capability resources.""" + ... diff --git a/backend/app/modules/artifacts/api/submission_command.py b/backend/app/modules/artifacts/api/submission_command.py index e156fab68..f60d71829 100644 --- a/backend/app/modules/artifacts/api/submission_command.py +++ b/backend/app/modules/artifacts/api/submission_command.py @@ -27,6 +27,7 @@ class SubmissionExecutionProfile(BaseModel): @model_validator(mode="after") def bounded_envelopes(self) -> Self: + """Require consistent, finite and representable upload and lease envelopes.""" if not self.heartbeat_seconds < self.foreground_lease_seconds <= self.upload_total_seconds: raise ValueError("submission foreground lease envelope is invalid") if self.foreground_lease_seconds * 1000 > self.runtime.aggregate_deadline_ms: @@ -59,6 +60,7 @@ class SubmissionAcceptedResponse(BaseModel): class SubmissionIntakeCommand(Protocol): + """Single raw-ZIP mutation whose success is durable T4 acceptance.""" async def submit( self, metadata: SubmissionIntakeMetadata, chunks: AsyncIterator[bytes], *, actor_id: UUID, identity_link_id: UUID, idempotency_key: UUID, @@ -77,6 +79,7 @@ class SubmissionOperationSelector(BaseModel): @model_validator(mode="after") def exactly_one(self) -> Self: + """Reject missing selectors and ambiguous operation/key combinations.""" if (self.operation_id is None) == (self.idempotency_key is None): raise ValueError("exactly one submission operation selector is required") return self @@ -115,6 +118,7 @@ class SubmissionOperationResponse(BaseModel): class SubmissionOperationReader(Protocol): + """Read stored progress for an authenticated operation selector.""" async def read(self, task_id: UUID, selector: SubmissionOperationSelector) -> SubmissionOperationResponse: """Read one authorized operation without changing submission state.""" ... diff --git a/backend/app/modules/artifacts/api/submission_finalization.py b/backend/app/modules/artifacts/api/submission_finalization.py index 907708d27..ef3caf060 100644 --- a/backend/app/modules/artifacts/api/submission_finalization.py +++ b/backend/app/modules/artifacts/api/submission_finalization.py @@ -24,6 +24,7 @@ class SubmissionFinalizationProgress: @dataclass(frozen=True, slots=True) class SubmissionFinalizationAuthorityFacts: + """Bind claim or commit authority to accepted source custody and continuation fencing.""" operation_id: UUID project_id: UUID task_id: UUID diff --git a/backend/app/modules/artifacts/api/submission_recovery.py b/backend/app/modules/artifacts/api/submission_recovery.py index fdc2d1edc..ead454b90 100644 --- a/backend/app/modules/artifacts/api/submission_recovery.py +++ b/backend/app/modules/artifacts/api/submission_recovery.py @@ -11,11 +11,13 @@ class RecoveryValue(BaseModel): + """Strict immutable recovery data with unknown fields rejected.""" model_config = ConfigDict(extra="forbid", frozen=True, strict=True, revalidate_instances="always", hide_input_in_errors=True) class SubmissionRecoveryCommand(RecoveryValue): + """An operator request scoped to one accepted operation and reason.""" operation_id: UUID project_id: UUID actor_profile_id: UUID @@ -25,12 +27,14 @@ class SubmissionRecoveryCommand(RecoveryValue): @field_validator("reason") @classmethod def bounded_reason(cls, value): + """Reject surrounding whitespace and control characters in recovery reasons.""" if value != value.strip() or any(ord(c) < 32 or ord(c) == 127 for c in value): raise ValueError("invalid finalization recovery reason") return value class SubmissionRecoverySource(RecoveryValue): + """The exact original event, claim generation and accepted receipt to recover.""" operation_id: UUID project_id: UUID task_id: UUID @@ -41,18 +45,21 @@ class SubmissionRecoverySource(RecoveryValue): class SubmissionRecoveryAuthority(RecoveryValue): + """Recorded authorization provenance bound to the recovery resource.""" decision_id: UUID identity_link_id: UUID resource_digest: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") class SubmissionRecoveryPayload(RecoveryValue): + """Bind the operator command, accepted source and authorization evidence.""" command: SubmissionRecoveryCommand source: SubmissionRecoverySource authority: SubmissionRecoveryAuthority @model_validator(mode="after") def exact_source(self): + """Reject commands whose operation or project differs from the source.""" if (self.command.operation_id != self.source.operation_id or self.command.project_id != self.source.project_id): raise ValueError("finalization recovery source differs") @@ -60,6 +67,7 @@ def exact_source(self): class SubmissionRecoveryResult(RecoveryValue): + """Expose the durable recovery event identity and delivery state.""" operation_id: UUID recovery_event_id: UUID state: Literal["pending", "active", "acknowledged", "unknown", "held"] @@ -70,6 +78,11 @@ class SubmissionRecoveryUnavailable(RuntimeError): class SubmissionRecoveryAuthorizationPort(Protocol): + """Authorize recovery and revalidate its stored originating decision.""" async def authorize(self, command: SubmissionRecoveryCommand, - source: SubmissionRecoverySource) -> SubmissionRecoveryAuthority: ... - async def validate_cause(self, payload: SubmissionRecoveryPayload) -> None: ... + source: SubmissionRecoverySource) -> SubmissionRecoveryAuthority: + """Authorize this command against the exact accepted recovery source.""" + ... + async def validate_cause(self, payload: SubmissionRecoveryPayload) -> None: + """Revalidate the authority that originated the stored recovery payload.""" + ... diff --git a/backend/app/modules/artifacts/intake/acceptance.py b/backend/app/modules/artifacts/intake/acceptance.py index 2607fc093..47e718d61 100644 --- a/backend/app/modules/artifacts/intake/acceptance.py +++ b/backend/app/modules/artifacts/intake/acceptance.py @@ -10,6 +10,7 @@ def acceptance_context(terminal: SelectedPreSubmitTerminalFacts) -> dict: + """Freeze PRE, source and revision lineage into the accepted context.""" request = terminal.lease.reservation lineage = request.admission_lineage return { @@ -28,6 +29,7 @@ def acceptance_context(terminal: SelectedPreSubmitTerminalFacts) -> dict: def acceptance_receipt(terminal: SelectedPreSubmitTerminalFacts, accepted_at: datetime) -> dict: + """Build the stable T4 response before a formal Submission exists.""" request = terminal.lease.reservation return { "operation_id": str(request.source.location.operation_id), "task_id": str(request.task_id), @@ -62,6 +64,7 @@ def authority_facts(row) -> IntakeAcceptanceAuthorityFacts: def finalization_event(row) -> OutboxAppendInput: + """Construct the identifier-only event bound to this acceptance decision.""" return OutboxAppendInput( event_type="SubmissionFinalizationRequested", event_version=1, aggregate_type="submission_operation", aggregate_id=UUID(row.id), project_id=UUID(row.project_id), diff --git a/backend/app/modules/artifacts/intake/finalization.py b/backend/app/modules/artifacts/intake/finalization.py index e5be2d663..ab55ee20d 100644 --- a/backend/app/modules/artifacts/intake/finalization.py +++ b/backend/app/modules/artifacts/intake/finalization.py @@ -20,12 +20,14 @@ @dataclass(frozen=True, slots=True) class AcceptedContinuation: + """The exact sealed source and lease generation claimed for T5.""" source: SealedSubmissionSource lease_id: UUID generation: int def continuation_facts(row, lease_id, generation): + """Reconstruct claim authority facts from immutable acceptance custody.""" return SubmissionFinalizationAuthorityFacts( operation_id=UUID(row.id), project_id=UUID(row.project_id), task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), contributor_id=UUID(row.actor_profile_id), @@ -42,6 +44,7 @@ class AcceptedSubmissionFinalization: def __init__(self, sessions, *, tasks, authorization, submissions, checkers, store, lease_duration, delivery=None): # Match the durable outbox's one-hour structural lease ceiling. This is # not a deployment default; composition must still supply its profile. + """Bind continuation owners and require an explicit bounded lease duration.""" if not isinstance(lease_duration, timedelta) or not timedelta(0) < lease_duration <= timedelta(hours=1): raise ValueError("finalization lease duration must be explicit, positive and at most one hour") self._sessions, self._tasks, self._authorization = sessions, tasks, authorization @@ -51,6 +54,7 @@ def __init__(self, sessions, *, tasks, authorization, submissions, checkers, sto @asynccontextmanager async def _root(self): + """Own the transaction and authority lifetime while preserving uncertain commits.""" session = self._sessions() authority = self._authorization(session) try: @@ -69,6 +73,7 @@ async def _root(self): await await_completion_preserving_cancellation(session.close()) async def run(self, operation_id: UUID) -> SubmissionCreationResult: + """Claim accepted work, observe its sealed source, and finalize or replay T5.""" lease_id = new_record_id() try: claim = await self._claim(operation_id, lease_id) @@ -87,6 +92,7 @@ async def run(self, operation_id: UUID) -> SubmissionCreationResult: return await self._finalized(session, row) async def _lock(self, session, authority, operation_id): + """Lock operation custody, authorize the service, and recheck delivery fencing.""" row = await SubmissionIntakeRepository(session, self._tasks(session))._lock(operation_id) await authority.authorize() if self._delivery is not None: @@ -94,6 +100,7 @@ async def _lock(self, session, authority, operation_id): return row async def _claim(self, operation_id, lease_id): + """Replay finalized work or acquire one authorized continuation generation.""" async with self._root() as (session, authority): row = await self._lock(session, authority, operation_id) if row.state == "finalized": @@ -120,6 +127,7 @@ async def _claim(self, operation_id, lease_id): return AcceptedContinuation(SubmissionIntakeRepository._sealed_source(row), lease_id, generation) async def _recover_claim(self, operation_id, lease_id): + """Resolve an uncertain claim acknowledgement using its original lease ID.""" async with self._root() as (session, authority): row = await self._lock(session, authority, operation_id) if row.state == "finalized": @@ -137,6 +145,7 @@ async def _recover_claim(self, operation_id, lease_id): return AcceptedContinuation(SubmissionIntakeRepository._sealed_source(row), lease_id, row.continuation_generation) async def _finalize(self, operation_id: UUID, claim: AcceptedContinuation, observation: SealedSourceObservation): + """Revalidate live custody and atomically register the source and Submission.""" async with self._root() as (session, authority): tasks = self._tasks(session) row = await self._lock(session, authority, operation_id) @@ -174,6 +183,7 @@ async def _finalize(self, operation_id: UUID, claim: AcceptedContinuation, obser return result async def _finalized(self, session, row): + """Validate committed acceptance and source custody before reading exact results.""" if row.state != "finalized": raise IntakeCommitUnknown("finalization result unavailable") await session.execute(text("SELECT public.require_submission_acceptance(o) " diff --git a/backend/app/modules/artifacts/intake/finalization_delivery.py b/backend/app/modules/artifacts/intake/finalization_delivery.py index 213a13dc6..105cdca95 100644 --- a/backend/app/modules/artifacts/intake/finalization_delivery.py +++ b/backend/app/modules/artifacts/intake/finalization_delivery.py @@ -13,6 +13,7 @@ def require_finalization_event(row, envelope): + """Require every envelope and payload identity to match accepted finalization.""" expected = finalization_event(row) if ( str(envelope.claim.event_id) != row.finalization_event_id @@ -36,9 +37,11 @@ class FinalizationInvocation: @property def lease_expires_at(self): + """Expose the delivery deadline that bounds the continuation lease.""" return self.envelope.claim.claim_expires_at async def fence(self, session, row): + """Require the exact committed invocation to remain live in this transaction.""" require_finalization_event(row, self.envelope) envelope = self.envelope observed = await self.fence_factory(session).fence_invocation(envelope) @@ -50,9 +53,11 @@ class SubmissionFinalizationHandler: """Acknowledge only after T5 or its exact committed replay succeeds.""" def __init__(self, *, observer, finalizer): + """Bind the durable invocation observer and finalizer factory.""" self._observer, self._finalizer = observer, finalizer async def __call__(self, envelope): + """Reject unqualified invocations and acknowledge only successful finalization.""" try: envelope = OutboxEventEnvelope.model_validate(envelope.model_dump()) except (AttributeError, TypeError, ValueError): diff --git a/backend/app/modules/authorization/api/submission_intake.py b/backend/app/modules/authorization/api/submission_intake.py index 2f51e8ad4..0c0b12229 100644 --- a/backend/app/modules/authorization/api/submission_intake.py +++ b/backend/app/modules/authorization/api/submission_intake.py @@ -70,14 +70,36 @@ class IntakeOperationReadDenied(IntakeAuthorityDenied): class IntakeAuthorizationPort(Protocol): """The caller owns root transactions, product locks and original provenance.""" - async def lock_actor(self, actor_id: UUID, identity_link_id: UUID) -> None: ... - async def preflight(self, facts: IntakeReservationPreflightFacts) -> None: ... - async def prepare(self, facts: IntakeReservationAuthorityFacts) -> object: ... - async def consume(self, handle: object, facts: IntakeReservationAuthorityFacts) -> UUID: ... - async def prepare_acceptance(self, facts: IntakeAcceptanceAuthorityFacts) -> object: ... - async def consume_acceptance(self, handle: object, facts: IntakeAcceptanceAuthorityFacts) -> UUID: ... - async def validate_acceptance_receipt(self, facts: IntakeAcceptanceAuthorityFacts, decision_id: UUID) -> None: ... - async def authorize_read(self, facts: IntakeOperationReadFacts, *, manager: bool = False) -> UUID: ... - async def authorize_operation_read(self, facts: IntakeOperationReadFacts) -> IntakeOperationReadAccess: ... - async def restage_denial(self, error: IntakeAuthorityDenied) -> bool: ... - def close(self) -> None: ... + async def lock_actor(self, actor_id: UUID, identity_link_id: UUID) -> None: + """Lock the exact actor and identity link before consuming authority.""" + ... + async def preflight(self, facts: IntakeReservationPreflightFacts) -> None: + """Check current reservation authority before resolving task eligibility.""" + ... + async def prepare(self, facts: IntakeReservationAuthorityFacts) -> object: + """Prepare reservation authority for the exact locked operation facts.""" + ... + async def consume(self, handle: object, facts: IntakeReservationAuthorityFacts) -> UUID: + """Consume a prepared reservation decision against unchanged facts.""" + ... + async def prepare_acceptance(self, facts: IntakeAcceptanceAuthorityFacts) -> object: + """Prepare operation-scoped T4 authority over the exact PRE result.""" + ... + async def consume_acceptance(self, handle: object, facts: IntakeAcceptanceAuthorityFacts) -> UUID: + """Consume T4 authority and return its recorded decision identity.""" + ... + async def validate_acceptance_receipt(self, facts: IntakeAcceptanceAuthorityFacts, decision_id: UUID) -> None: + """Validate the stored decision against immutable accepted facts.""" + ... + async def authorize_read(self, facts: IntakeOperationReadFacts, *, manager: bool = False) -> UUID: + """Authorize the requested contributor or management operation view.""" + ... + async def authorize_operation_read(self, facts: IntakeOperationReadFacts) -> IntakeOperationReadAccess: + """Resolve current operation-read authority and projection visibility.""" + ... + async def restage_denial(self, error: IntakeAuthorityDenied) -> bool: + """Restore matching denial evidence after the caller rolls back its root.""" + ... + def close(self) -> None: + """Invalidate authority handles when the owning transaction scope ends.""" + ... diff --git a/backend/app/modules/checkers/api/source_contracts.py b/backend/app/modules/checkers/api/source_contracts.py index 02020d90b..a7ec7fccd 100644 --- a/backend/app/modules/checkers/api/source_contracts.py +++ b/backend/app/modules/checkers/api/source_contracts.py @@ -13,20 +13,31 @@ class SubmissionSourceLocationView(Protocol): + """Provider-neutral location facts; reading them does not authorize access.""" @property - def operation_id(self) -> UUID: ... + def operation_id(self) -> UUID: + """Identify the intake operation that owns this physical source.""" + ... @property - def namespace_id(self) -> str: ... + def namespace_id(self) -> str: + """Identify the configured artifact namespace.""" + ... @property - def namespace_fingerprint(self) -> str: ... + def namespace_fingerprint(self) -> str: + """Bind the location to the exact namespace configuration.""" + ... @property - def provider_profile(self) -> str: ... + def provider_profile(self) -> str: + """Name the storage profile that interprets the object reference.""" + ... @property - def object_ref(self) -> str: ... + def object_ref(self) -> str: + """Return the opaque provider reference for the operation-owned object.""" + ... @runtime_checkable @@ -35,32 +46,50 @@ class SealedSubmissionSourceView(Protocol): @classmethod def __get_pydantic_core_schema__(cls, source_type, handler): + """Provide Pydantic validation for this owner-bound protocol.""" def validate(value, info): + """Parse serialized source facts or require the concrete owner value.""" contracts = source_contracts_from_context(info.context) return contracts.parse_source(value) if type(value) is dict else contracts.require_source(value) return core_schema.with_info_plain_validator_function(validate) @property - def location(self) -> SubmissionSourceLocationView: ... + def location(self) -> SubmissionSourceLocationView: + """Return the immutable operation and namespace location.""" + ... @property - def provider_generation(self) -> str: ... + def provider_generation(self) -> str: + """Identify the exact sealed provider generation, not merely its key.""" + ... @property - def raw_sha256(self) -> str: ... + def raw_sha256(self) -> str: + """Return the digest of the uploaded ZIP bytes.""" + ... @property - def raw_byte_count(self) -> int: ... + def raw_byte_count(self) -> int: + """Return the verified length of the uploaded ZIP.""" + ... @property - def sealed_upload_fence(self) -> int: ... + def sealed_upload_fence(self) -> int: + """Bind the sealed source to the upload ownership generation.""" + ... @property - def media_type(self) -> str: ... + def media_type(self) -> str: + """Return the source archive media type.""" + ... - def model_dump(self, *, mode: Literal["json"]) -> dict[str, object]: ... + def model_dump(self, *, mode: Literal["json"]) -> dict[str, object]: + """Serialize the complete sealed-source identity for persisted evidence.""" + ... - def source_sha256(self) -> str: ... + def source_sha256(self) -> str: + """Digest the canonical source identity, including provider custody.""" + ... @runtime_checkable @@ -69,36 +98,56 @@ class SubmissionArchiveLimitsView(Protocol): @classmethod def __get_pydantic_core_schema__(cls, source_type, handler): + """Provide Pydantic validation for this owner-bound protocol.""" def validate(value, info): + """Parse serialized bounds or require the concrete owner limits.""" contracts = source_contracts_from_context(info.context) return contracts.parse_limits(value) if type(value) is dict else contracts.require_limits(value) return core_schema.with_info_plain_validator_function(validate) @property - def maximum_entries(self) -> int: ... + def maximum_entries(self) -> int: + """Bound the number of archive entries inspected.""" + ... @property - def maximum_path_bytes(self) -> int: ... + def maximum_path_bytes(self) -> int: + """Bound each archive path in encoded bytes.""" + ... @property - def maximum_path_depth(self) -> int: ... + def maximum_path_depth(self) -> int: + """Bound the number of path components in an archive entry.""" + ... @property - def maximum_central_directory_bytes(self) -> int: ... + def maximum_central_directory_bytes(self) -> int: + """Bound ZIP directory metadata before entry processing.""" + ... @property - def maximum_entry_bytes(self) -> int: ... + def maximum_entry_bytes(self) -> int: + """Bound the expanded size of an individual entry.""" + ... @property - def maximum_expanded_bytes(self) -> int: ... + def maximum_expanded_bytes(self) -> int: + """Bound the aggregate expanded archive size.""" + ... @property - def maximum_compression_ratio(self) -> int: ... + def maximum_compression_ratio(self) -> int: + """Bound expansion relative to compressed archive content.""" + ... @property - def maximum_inspection_seconds(self) -> float: ... + def maximum_inspection_seconds(self) -> float: + """Bound the archive inspection duration.""" + ... - def canonical_body(self) -> dict[str, int | float]: ... + def canonical_body(self) -> dict[str, int | float]: + """Serialize exact configured limits for request hashing.""" + ... @runtime_checkable @@ -107,19 +156,30 @@ class SelectedPreSubmitSourceContracts(Protocol): @classmethod def __get_pydantic_core_schema__(cls, source_type, handler): + """Provide Pydantic validation for this owner-bound protocol.""" return core_schema.is_instance_schema(cls) - def parse_source(self, body: object) -> SealedSubmissionSourceView: ... + def parse_source(self, body: object) -> SealedSubmissionSourceView: + """Decode source facts using the concrete ART schema.""" + ... - def require_source(self, source: object) -> SealedSubmissionSourceView: ... + def require_source(self, source: object) -> SealedSubmissionSourceView: + """Reject values that are not the concrete ART source type.""" + ... - def parse_limits(self, body: object) -> SubmissionArchiveLimitsView: ... + def parse_limits(self, body: object) -> SubmissionArchiveLimitsView: + """Decode inspection limits using the concrete ART schema.""" + ... - def require_limits(self, limits: object) -> SubmissionArchiveLimitsView: ... + def require_limits(self, limits: object) -> SubmissionArchiveLimitsView: + """Reject values that are not the concrete ART limits type.""" + ... def validate_manifest( self, body: object, *, sha256: str, limits: SubmissionArchiveLimitsView, - ) -> tuple[SubmissionMaterialEntry, ...]: ... + ) -> tuple[SubmissionMaterialEntry, ...]: + """Validate manifest digest and bounds, then expose material entries.""" + ... def source_contracts_context(contracts: SelectedPreSubmitSourceContracts) -> dict[str, object]: diff --git a/backend/app/modules/tasks/api/pending_submission.py b/backend/app/modules/tasks/api/pending_submission.py index 1f3b8d5f9..f23c3a7b4 100644 --- a/backend/app/modules/tasks/api/pending_submission.py +++ b/backend/app/modules/tasks/api/pending_submission.py @@ -11,12 +11,14 @@ class PendingSubmissionOperationUnavailable(RuntimeError): @dataclass(frozen=True, slots=True) class PendingSubmissionOperation: + """Narrow current intake identity and stage, separate from Submission history.""" operation_id: UUID processing_stage: Literal[ "receiving", "pre_checking", "finalization_pending", "operationally_stalled", ] def __post_init__(self) -> None: + """Reject invalid identities and stages outside the active intake vocabulary.""" if not isinstance(self.operation_id, UUID) or self.processing_stage not in { "receiving", "pre_checking", "finalization_pending", "operationally_stalled", }: @@ -24,6 +26,7 @@ def __post_init__(self) -> None: class PendingSubmissionOperationReadPort(Protocol): + """Resolve pending progress under the caller transaction and current authority.""" async def read(self, task_id: UUID, operation_id: UUID) -> PendingSubmissionOperation | None: """Use the caller transaction; return None only for denied read authority.""" ... From 99d4fa40634179522eb7be541ee10111c091fd41 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 21:33:30 +0100 Subject: [PATCH 174/513] test(submissions): preserve revision targets and use current POST source custody --- .../post_submit/test_atomicity.py | 5 +- .../post_submit/test_live_authority.py | 6 +- .../post_submit/test_principals.py | 5 +- .../post_submit/test_receipt_custody.py | 3 +- .../tests/historical_submission_fixtures.py | 2 +- .../tasks/evaluation_delivery/support.py | 17 +++-- .../tasks/evaluation_delivery/test_custody.py | 46 +++++++----- .../evaluation_delivery/test_delivery.py | 4 +- .../test_worker_materialization.py | 36 +++++---- .../accepted_revision_probes.py | 13 ++++ backend/tests/test_post_submit_selection.py | 3 +- backend/tests/test_tasks.py | 73 +++++++++++++++++++ 12 files changed, 163 insertions(+), 50 deletions(-) diff --git a/backend/tests/authorization/post_submit/test_atomicity.py b/backend/tests/authorization/post_submit/test_atomicity.py index dc0093b2d..9f615fc4c 100644 --- a/backend/tests/authorization/post_submit/test_atomicity.py +++ b/backend/tests/authorization/post_submit/test_atomicity.py @@ -25,7 +25,8 @@ async def test_real_audit_insert_failure_rolls_back(tmp_path, isolated_database_ else "checker.post_submit." + phase) before = await snapshot(h) opened = len(h.store.opens) - consumer = Consumer(h.files) + consumer = (Consumer(h.files, ExecuteFacts(request=h.request, lease=lease)) + if phase == "materialize" else None) async with h.factory() as session, session.begin(): await session.execute(text("CREATE SEQUENCE test_post_submit_audit_attempt")) await session.execute(text("""CREATE FUNCTION test_post_submit_audit_failure() RETURNS trigger @@ -51,7 +52,7 @@ async def invoke(): await invoke() assert await snapshot(h) == before assert len(h.store.opens) == opened - assert consumer.calls == 0 and not h.preparation._active + assert (consumer is None or consumer.calls == 0) and not h.preparation._active assert list((h.scratch / "workspaces").iterdir()) == [] async with h.factory() as session: # Sequence effects survive rollback: the real INSERT trigger ran. diff --git a/backend/tests/authorization/post_submit/test_live_authority.py b/backend/tests/authorization/post_submit/test_live_authority.py index 3bc4e1448..0e82dbb9e 100644 --- a/backend/tests/authorization/post_submit/test_live_authority.py +++ b/backend/tests/authorization/post_submit/test_live_authority.py @@ -61,7 +61,7 @@ async def test_materialization_rejects_substituted_live_lease_before_io( "expires_at": facts.lease.expires_at + timedelta(microseconds=1)}[field] substituted = facts.model_copy(update={"lease": facts.lease.model_copy(update={field: changed})}) before = await snapshot(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, facts) with pytest.raises(PostSubmissionMaterializationUnavailable): await h.service.materialize(substituted, consumer) assert await snapshot(h) == before @@ -88,7 +88,7 @@ async def test_materialization_rejects_mixed_valid_stored_lineage_before_io( # Well-typed internally consistent selectors mix two genuine stored # lineages; they do not match either committed current execution. before = await snapshot(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, facts) with pytest.raises(PostSubmissionMaterializationUnavailable): await h.service.materialize(mixed, consumer) assert await snapshot(h) == before @@ -157,7 +157,7 @@ async def test_execution_identity_substitution_denies_before_material_access(tmp }) mixed = ExecuteFacts(request=request, lease=facts.lease.model_copy(update={"reservation": reservation})) before = await snapshot(h) - consumer = Consumer(h.files) + consumer = Consumer(h.files, facts) with pytest.raises(PostSubmissionMaterializationUnavailable): await h.service.materialize(mixed, consumer) assert await snapshot(h) == before diff --git a/backend/tests/authorization/post_submit/test_principals.py b/backend/tests/authorization/post_submit/test_principals.py index 11b9857b1..7be4d3ce7 100644 --- a/backend/tests/authorization/post_submit/test_principals.py +++ b/backend/tests/authorization/post_submit/test_principals.py @@ -34,7 +34,8 @@ async def test_inactive_fixed_actor_denies_phase(tmp_path, isolated_database_env suspended_by='test',suspended_at=clock_timestamp(),suspension_reason='test' WHERE service_identity=:identity"""), {"identity": identity.value}) before = await snapshot(h) - consumer = Consumer(h.files) + consumer = (Consumer(h.files, ExecuteFacts(request=h.request, lease=lease)) + if phase == "materialize" else None) async def invoke(): if phase == "execute": @@ -47,7 +48,7 @@ async def invoke(): with pytest.raises(expected): await invoke() assert await snapshot(h) == before - assert not h.store.opens and not h.preparation._active and consumer.calls == 0 + assert not h.store.opens and not h.preparation._active and (consumer is None or consumer.calls == 0) # Restore the fixture to prove that the same complete operation is valid. async with h.factory() as session, session.begin(): await session.execute(text("""UPDATE actor_profiles SET status='active', suspended_by=NULL, diff --git a/backend/tests/authorization/post_submit/test_receipt_custody.py b/backend/tests/authorization/post_submit/test_receipt_custody.py index 458aaa3c3..288747c22 100644 --- a/backend/tests/authorization/post_submit/test_receipt_custody.py +++ b/backend/tests/authorization/post_submit/test_receipt_custody.py @@ -103,7 +103,8 @@ async def test_execute_receipt_substitution_rejected(tmp_path, isolated_database async with h.factory() as session: borrowed = UUID((await session.get(CheckerRun, str(foreign.reservation.attempt_id))).execute_evidence_id) elif substitution == "material_read": - await h.service.materialize(ExecuteFacts(request=h.request, lease=lease), Consumer(h.files)) + execution = ExecuteFacts(request=h.request, lease=lease) + await h.service.materialize(execution, Consumer(h.files, execution)) async with h.factory() as session: borrowed = UUID(await session.scalar(select(AuditEvent.id).where( AuditEvent.action_id == "artifact.post_submit.checker_input.materialize", diff --git a/backend/tests/historical_submission_fixtures.py b/backend/tests/historical_submission_fixtures.py index 6786c1b04..6a1e0fbf5 100644 --- a/backend/tests/historical_submission_fixtures.py +++ b/backend/tests/historical_submission_fixtures.py @@ -24,7 +24,7 @@ from app.core.hashing import canonical_json_hash from app.db import session as db_session -from conftest import _assert_owned_test_database +from tests.conftest import _assert_owned_test_database _ARCHIVE = Path(__file__).with_name("fixtures") / "pilot04_predecessor_rows.json.gz" diff --git a/backend/tests/tasks/evaluation_delivery/support.py b/backend/tests/tasks/evaluation_delivery/support.py index 76f3e1632..6063f0fa4 100644 --- a/backend/tests/tasks/evaluation_delivery/support.py +++ b/backend/tests/tasks/evaluation_delivery/support.py @@ -2,6 +2,7 @@ import json from types import SimpleNamespace +from unittest.mock import patch from sqlalchemy import select, func @@ -18,6 +19,7 @@ from app.modules.outbox.registry import HandlerRegistry from app.modules.tasks.models import AuditEvent from tests.outbox.conftest import Harness +from tests.checkers.execution.support import ControlledSelectedExecution async def delivery_fixture(h, *, options=None, materialization=None): @@ -38,16 +40,21 @@ async def delivery_fixture(h, *, options=None, materialization=None): subject=ServiceIdentity.OUTBOX_DISPATCHER.value, subject_kind="service", status="active", linked_by="workstream:system:bootstrap", )) - handler = evaluation_request_handler( - sessions=h.factory, - materialization=h.service if materialization is None else materialization, - ) + selected = ControlledSelectedExecution() + # The constructor captures this port; the patch never spans delivery or + # changes the independent production registry's external configuration. + with patch("app.adapters.checkers.configured_post_submit_external_execution", + lambda settings, *, sessions: selected): + handler = evaluation_request_handler( + sessions=h.factory, + materialization=h.service if materialization is None else materialization, + ) delivery = outbox_delivery( h.factory, authorization_factory=outbox_dispatch_authorization, registry=HandlerRegistry([(REQUEST_EVENT, 1, handler)]), options=options or DeliveryOptions(), ) - return SimpleNamespace(handler=handler, delivery=delivery) + return SimpleNamespace(handler=handler, delivery=delivery, selected=selected) async def invoked(h, d): diff --git a/backend/tests/tasks/evaluation_delivery/test_custody.py b/backend/tests/tasks/evaluation_delivery/test_custody.py index b65e4ef22..a7a0bd00e 100644 --- a/backend/tests/tasks/evaluation_delivery/test_custody.py +++ b/backend/tests/tasks/evaluation_delivery/test_custody.py @@ -60,16 +60,19 @@ async def test_delivery_closed_during_io_cannot_publish_terminal(tmp_path, isola d = await delivery_fixture(h) envelope = await invoked(h, d) entered, release = asyncio.Event(), asyncio.Event() - original = h.store.open - - async def paused(reference): - source = original(reference) - entered.set() - await release.wait() - async for chunk in source: - yield chunk - - monkeypatch.setattr(h.store, "open", paused) + original = h.store.open_source + + async def paused(reference, **kwargs): + source = original(reference, **kwargs) + try: + entered.set() + await release.wait() + async for chunk in source: + yield chunk + finally: + await source.aclose() + + monkeypatch.setattr(h.store, "open_source", paused) operation = asyncio.create_task(d.handler(envelope)) try: await asyncio.wait_for(entered.wait(), 20) @@ -104,16 +107,19 @@ async def test_cancellation_after_execute_preserves_unknown(tmp_path, isolated_d d = await delivery_fixture(h) envelope = await invoked(h, d) entered = asyncio.Event() - original = h.store.open - - async def paused(reference): - source = original(reference) - entered.set() - await asyncio.Event().wait() - async for chunk in source: - yield chunk - - monkeypatch.setattr(h.store, "open", paused) + original = h.store.open_source + + async def paused(reference, **kwargs): + source = original(reference, **kwargs) + try: + entered.set() + await asyncio.Event().wait() + async for chunk in source: + yield chunk + finally: + await source.aclose() + + monkeypatch.setattr(h.store, "open_source", paused) operation = asyncio.create_task(d.handler(envelope)) try: await asyncio.wait_for(entered.wait(), 20) diff --git a/backend/tests/tasks/evaluation_delivery/test_delivery.py b/backend/tests/tasks/evaluation_delivery/test_delivery.py index bf1b464fe..1f39b149f 100644 --- a/backend/tests/tasks/evaluation_delivery/test_delivery.py +++ b/backend/tests/tasks/evaluation_delivery/test_delivery.py @@ -33,7 +33,9 @@ async def test_shared_delivery_runs_exact_request_once(tmp_path, isolated_databa assert saved["run"]["worker_lease_generation"] == 1 assert set(saved["allows"]) == {saved["run"]["execute_evidence_id"], saved["run"]["finalize_evidence_id"]} assert len(saved["allows"]) == 2 and saved["events"] == 1 - assert saved["members"] == len(h.request.policy.entries) + assert saved["members"] == 1 + assert len(d.selected.requests) == 1 + assert d.selected.requests[0].identity.phase == "post_submit" assert saved["run"]["material_custody"] == { "submission_id": str(h.created.submission_id), "submission_version": h.created.submission_version, "admission_id": str(h.created.admission_id), "binding_id": str(h.created.artifact_binding_id), diff --git a/backend/tests/tasks/evaluation_delivery/test_worker_materialization.py b/backend/tests/tasks/evaluation_delivery/test_worker_materialization.py index e2727e141..7c7383d44 100644 --- a/backend/tests/tasks/evaluation_delivery/test_worker_materialization.py +++ b/backend/tests/tasks/evaluation_delivery/test_worker_materialization.py @@ -91,21 +91,26 @@ async def test_worker_art_lease_cancellation_revokes_view_and_scratch( async with material_fixture(tmp_path, isolated_database_env) as h: port = _worker_port(h, monkeypatch) try: - consumer = Consumer(h.files) + execution = await material_execution(h) + consumer = Consumer(h.files, execution) consumer.release = asyncio.Event() stream_entered, stream_release = asyncio.Event(), asyncio.Event() - original_open = LocalStorageAdapter.open + original_open = LocalStorageAdapter.open_source - async def paused_stream(store, reference): - async for chunk in original_open(store, reference): - stream_entered.set() - await stream_release.wait() - yield chunk + async def paused_stream(store, reference, **kwargs): + source = original_open(store, reference, **kwargs) + try: + async for chunk in source: + stream_entered.set() + await stream_release.wait() + yield chunk + finally: + await source.aclose() with monkeypatch.context() as patch: if stage == "stream": - patch.setattr(LocalStorageAdapter, "open", paused_stream) - operation = asyncio.create_task(port.materialize(await material_execution(h), consumer)) + patch.setattr(LocalStorageAdapter, "open_source", paused_stream) + operation = asyncio.create_task(port.materialize(execution, consumer)) try: entered = stream_entered if stage == "stream" else consumer.entered await asyncio.wait_for(entered.wait(), 20) @@ -169,7 +174,7 @@ def unavailable(_settings): with monkeypatch.context() as patch: patch.setattr(artifact_adapter, "create_artifact_scratch_manager", unavailable) with pytest.raises(RuntimeError, match="scratch construction outage"): - await port.materialize(execution, Consumer(h.files)) + await port.materialize(execution, Consumer(h.files, execution)) assert internal_workers._runtime is not None assert internal_workers._runtime_active_operations == 0 finally: @@ -192,7 +197,7 @@ def unavailable(**_kwargs): with monkeypatch.context() as patch: patch.setattr(artifact_adapter, "post_submission_materialization", unavailable) with pytest.raises(RuntimeError, match="materializer construction outage"): - await port.materialize(execution, Consumer(h.files)) + await port.materialize(execution, Consumer(h.files, execution)) await _scratch_is_closed(h) finally: internal_workers.shutdown_artifact_internal_runtime() @@ -206,13 +211,13 @@ async def test_worker_known_missing_object_records_infrastructure_result( async with material_fixture(tmp_path, isolated_database_env) as h: port = _worker_port(h, monkeypatch) - def missing(_store, _reference): + def missing(_store, _reference, **_kwargs): raise ArtifactObjectMissingError("controlled verified object loss") try: d = await delivery_fixture(h, materialization=port) with monkeypatch.context() as patch: - patch.setattr(LocalStorageAdapter, "open", missing) + patch.setattr(LocalStorageAdapter, "open_source", missing) receipt = await d.delivery.deliver( h.created.evaluation_event_id, h.request.project_id, "missing-object", ) @@ -222,7 +227,10 @@ def missing(_store, _reference): assert json.loads(saved["run"]["result_json"])["infrastructure_failure_code"] == "material_unavailable" assert saved["events"] == 0 async with h.factory() as session: - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 + assert set(await session.scalars(select(OutboxEvent.event_type))) == { + "SubmissionFinalizationRequested", REQUEST_EVENT, + } await _scratch_is_closed(h) finally: internal_workers.shutdown_artifact_internal_runtime() diff --git a/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py b/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py index 49ae98812..fb816f18e 100644 --- a/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py +++ b/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py @@ -100,3 +100,16 @@ async def accept(admission, session, authority, repository, row, owner, with patch.object(ForegroundIntakeAdmission, "_accept_new", accept): yield observed assert len(observed) == 1 + + +async def revision_target_snapshot(factory, task_id): + """Observe all repair-owned writes, excluding foreground lease heartbeats.""" + async with factory() as session: + return (await session.execute(text(""" + SELECT + (SELECT to_jsonb(t) FROM workstream_tasks t WHERE t.id=:task), + (SELECT jsonb_agg(to_jsonb(p) ORDER BY p.id) + FROM task_revision_preparations p WHERE p.task_id=:task), + (SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) FROM audit_events a), + (SELECT jsonb_agg(to_jsonb(e) ORDER BY e.event_id) FROM outbox_events e) + """), {"task": task_id})).one() diff --git a/backend/tests/test_post_submit_selection.py b/backend/tests/test_post_submit_selection.py index 55fff9acf..b2bf6a2ea 100644 --- a/backend/tests/test_post_submit_selection.py +++ b/backend/tests/test_post_submit_selection.py @@ -96,7 +96,8 @@ async def test_valid_foreign_lineage_mixes_deny_before_material_access(tmp_path, assert first.created.admission_id != second.created.admission_id # Each untouched stored lineage must pass through real materialization. for own in (first, second): - value = await own.service.materialize(await material_execution(own), Consumer(own.files)) + execution = await material_execution(own) + value = await own.service.materialize(execution, Consumer(own.files, execution)) assert value.submission_id == own.created.submission_id own.store.opens.clear() def forbidden(*args, **kwargs): diff --git a/backend/tests/test_tasks.py b/backend/tests/test_tasks.py index 20eba2e7f..367398941 100644 --- a/backend/tests/test_tasks.py +++ b/backend/tests/test_tasks.py @@ -2964,3 +2964,76 @@ async def test_task_metadata_round_trips(task_client: AsyncClient) -> None: assert task is not None assert task.skill_tags == ["stem", "proofs"] assert task.source_payload_hash == "hash-123" + + +async def test_active_revision_prevents_manager_target_change_before_acceptance(task_client, monkeypatch): + """A genuine PM rebase cannot invalidate an in-flight successful PRE.""" + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.tasks.authorized_commands import AuthorizedTaskCommands + from tests.tasks.submission_dispatch.accepted_revision_probes import revision_target_snapshot + + project = await create_active_project(task_client) + task = await create_started_task(task_client, project["id"], monkeypatch) + first = await seed_retained_submission(task["id"], complete_submission_payload()) + await route_retained_checker_remediation(first) + factory = db_session.get_session_factory() + original_accept = ForegroundIntakeAdmission.accept + original_repair = AuthorizedTaskCommands.repair_revision_context + failures, observed = [], [] + + async def observe_repair(commands, *args, **kwargs): + try: + return await original_repair(commands, *args, **kwargs) + except IntegrityError as exc: + failures.append(str(exc.orig)) + raise + + async def before_accept(admission, owner, request, terminal_digest, **kwargs): + # PRE has committed; T4 has not acquired its transaction or TASK lock. + assert request.admission_lineage.predecessor_submission_id == UUID(first) + async with factory() as session: + pending = (await session.execute(text(""" + SELECT state,command_metadata FROM submission_intake_operations WHERE id=:id + """), {"id": owner.operation_id})).one() + assert pending.state == "pre_checking" + set_dev_actor(monkeypatch, roles="project_manager", subject="project-manager-subject") + guide = await task_client.post( + f"/api/v1/projects/{project['id']}/guides", headers=auth_headers(), + json=complete_guide_payload("v2"), + ) + assert guide.status_code == 201, guide.text + await create_policy_bundle_for_guide(task_client, project["id"], guide.json()["id"]) + await seed_active_guide_for_downstream_test( + factory, project_id=project["id"], guide_id=guide.json()["id"], + ) + before = await revision_target_snapshot(factory, task["id"]) + assert guide.json()["version"] == "v2" != before[0]["locked_guide_version"] + response = await task_client.post( + f"/api/v1/projects/{project['id']}/tasks/{task['id']}/revision-context/repair", + headers=auth_headers() | {"Idempotency-Key": str(new_record_id())}, + json={"parent_preparation_id": pending.command_metadata["revision_preparation_id"], + "parent_preparation_sha256": pending.command_metadata["revision_preparation_sha256"], + "reason": "Adopt the corrected active guide after successful PRE"}, + ) + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "task_authority_unavailable" + assert len(failures) == 1 and "intake task custody mismatch" in failures[0] + assert await revision_target_snapshot(factory, task["id"]) == before + set_dev_actor(monkeypatch, roles="worker", subject="worker-one") + receipt = await original_accept(admission, owner, request, terminal_digest, **kwargs) + assert receipt["status"] == "accepted" + observed.append(owner.operation_id) + return receipt + + set_dev_actor(monkeypatch, roles="worker", subject="worker-one") + with monkeypatch.context() as patch: + patch.setattr(ForegroundIntakeAdmission, "accept", before_accept) + patch.setattr(AuthorizedTaskCommands, "repair_revision_context", observe_repair) + second = await seed_retained_submission(task["id"], complete_submission_payload(), predecessor_id=first) + assert len(observed) == 1 + async with factory() as session: + prior, current = await session.get(Submission, first), await session.get(Submission, second) + assert current.version == 2 and current.supersedes_submission_id == first + assert current.locked_guide_version == prior.locked_guide_version + stored_task = await session.get(WorkstreamTask, task["id"]) + assert stored_task.active_submission_operation_id is None From 1084c224b63dd33cbd97d018bd63435ba19aaa16 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 21:42:12 +0100 Subject: [PATCH 175/513] test(checkers): pass source contracts through PRE transport probes --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 22 +++++++++++++++++++ .../tests/checkers/external/test_runtime.py | 6 ++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e8400faa7..3c83aad75 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6181,3 +6181,25 @@ Full worker-materialization run and affected authorization/material consumer run are still active; the final close-forwarding hooks require their focused replay. Do not treat this checkpoint as full CI/provider/spec readiness. Hosted preflight and CLI collection fixes still require rerun on the final pushed head. + +Hosted transport replay repair scope: tests/checkers/external/test_runtime.py. +The single PRE transport matrix fails before exercising transport because +dataclasses.replace requires the reservation's explicit source_contracts InitVar. +Supply the existing ART composition dependency while replacing source facts; +preserve every tampering, deadline, transport and runtime assertion. No production +contract default or compatibility path. Low-risk fixture repair; verify the full +existing transport matrix and Ruff. Broader hosted failures in retired PRE and +replacement producers remain separate required migration work. + +Transport replay first reaches11passing cases and exposes the slow-decode hook's +old signature. Forward the real source_contracts keyword through that hook; +preserve its300ms delay and deadline_exceeded assertion. Final transport matrix +passes12 in3.38s; Ruff and Commitrail checks pass. Final worker/custody hook replay +passes4 in111.54s on99d, with database and MinIO cleanup complete. This replays the +previous consumer timeout without extending its20s bound; it does not establish +the original timeout's root cause. Documentation review passes; QA code review +closes inner-stream cleanup finding, while full AUTH execution remains pending. +Hosted86a artifacts contain146 failing cases across completed lanes, including +42 obsolete preparation-fact callers and multiple retired PRE constructors. +Artifacts: /tmp/submission-ci-43947584976; failure index: +/tmp/submission-hosted-failures-86a.txt. Full CI remains incomplete and failing. diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py index 58ca6ee1b..37c6a5c3a 100644 --- a/backend/tests/checkers/external/test_runtime.py +++ b/backend/tests/checkers/external/test_runtime.py @@ -1164,7 +1164,7 @@ async def test_single_pre_transport_streams_source_and_validates_combined_result payload = b"controlled transport bytes" * 4000 reservation = _source_reservation() - reservation = replace(reservation, source=reservation.source.model_copy(update={ + reservation = replace(reservation, source_contracts=selected_pre_submit_source_contracts(), source=reservation.source.model_copy(update={ "raw_sha256": "sha256:" + hashlib.sha256(payload).hexdigest(), "raw_byte_count": len(payload), })) @@ -1231,10 +1231,10 @@ async def open_source(self, *, lease): import time from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts decode = SelectedPreSubmitExecutionFacts.from_canonical_body - def delayed_decode(cls, value): + def delayed_decode(cls, value, *, source_contracts): decode_called.append(True) time.sleep(0.3) - return decode(value) + return decode(value, source_contracts=source_contracts) monkeypatch.setattr(SelectedPreSubmitExecutionFacts, "from_canonical_body", classmethod(delayed_decode)) expected_lease = lease grant = Grant() From 27531b23fc1258c6aaa738fac9db33682ab9bc04 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 21:50:43 +0100 Subject: [PATCH 176/513] test(submissions): migrate review successors and retry source fixtures --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 37 ++++++++++++++++++ .../checkers/execution/test_checker_retry.py | 34 +++++++++-------- backend/tests/reviews/decision/support.py | 38 +++---------------- 3 files changed, 62 insertions(+), 47 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3c83aad75..906bec5c9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6203,3 +6203,40 @@ Hosted86a artifacts contain146 failing cases across completed lanes, including 42 obsolete preparation-fact callers and multiple retired PRE constructors. Artifacts: /tmp/submission-ci-43947584976; failure index: /tmp/submission-hosted-failures-86a.txt. Full CI remains incomplete and failing. + +Review-history successor producer migration scope: reviews/decision/support.py. +Replace obsolete prepare/verify/hidden-create setup in _admit_successor with +existing create_source_submission, using the same actor, locked revision context, +exact predecessor, summary and corrected ZIP. Preserve all storage review, +finding carry-forward and predecessor assertions; no compatibility alias, direct +Submission insert or authority bypass. Medium risk shared lifecycle fixture; +verify its three consuming storage tests on isolated PostgreSQL, Ruff and test +structure checks. QA review must confirm the current producer does not weaken +the history guards. Existing review fixtures remain storage proofs, not public +human-decision authority claims. + +Adjacent retry-fixture scope: checkers/execution/test_checker_retry.py. +Its missing-object injection still patches open, while current selected POST +reads open_source. Move the exact controlled provider failure to open_source and +accept its keyword arguments. Preserve material_unavailable, Operator receipt, +rollback and retry assertions. Verify local/MinIO recovery first, then affected +retry/authority consumers; QA review of this shared injection is required. No +production changes or weakening of expected infrastructure failure classification. + +Local/MinIO retry pair now reaches actual Operator successor creation; both fail +on obsolete total-event count2 versus3 (T4 finalization plus two POST requests). +Update this file's exact total counts for the one retained finalization event, +explicitly assert that finalization event in the shared source fixture, and move +the independent concurrency fixture's identical old open hook to open_source. +Preserve all rollback/replay and exact retry receipt checks; no event filtering +that could hide duplicates. Replay provider pair and full affected retry file. + +Successor verification: all3 existing predecessor-chain, finding carry-forward +and first-review-after-correction cases pass273.83s; owned database and MinIO +cleanup complete (/tmp/submission-review-successor-v1). Existing serializer +warnings remain. QA finds no code defect: same actor/revision custody, unchanged +history/finding assertions; all11 retry event totals increase exactly1 for retained +T4 and the new source assertion requires exactly1 finalization event. Ruff, +whitespace, Commitrail and initial structure validation pass. Full retry replay +(/tmp/submission-current-retry-v2) and prior AUTH replay remain live; this checkpoint +does not claim their success or whole-spec readiness. diff --git a/backend/tests/checkers/execution/test_checker_retry.py b/backend/tests/checkers/execution/test_checker_retry.py index 9e495dc08..91efde603 100644 --- a/backend/tests/checkers/execution/test_checker_retry.py +++ b/backend/tests/checkers/execution/test_checker_retry.py @@ -113,7 +113,7 @@ async def _failed_source( ) as h: port = _worker_port(h, monkeypatch) - def missing(_store, _reference): + def missing(_store, _reference, **kwargs): raise ArtifactObjectMissingError("controlled verified object loss") try: @@ -121,7 +121,7 @@ def missing(_store, _reference): with monkeypatch.context() as patch: patch.setattr( LocalStorageAdapter if provider == "local" else S3CompatibleArtifactStore, - "open", missing, + "open_source", missing, ) initial = await delivery.delivery.deliver( h.created.evaluation_event_id, h.request.project_id, "retry-source", @@ -130,6 +130,10 @@ def missing(_store, _reference): saved = await state(h) assert saved["run"]["status"] == "infrastructure_failed" assert json.loads(saved["run"]["result_json"])["infrastructure_failure_code"] == "material_unavailable" + async with h.factory() as session: + assert await session.scalar(select(func.count()).select_from(OutboxEvent).where( + OutboxEvent.event_type == "SubmissionFinalizationRequested", + )) == 1 yield h, delivery finally: internal_workers.shutdown_artifact_internal_runtime() @@ -413,7 +417,7 @@ async def test_retry_sql_rejects_unreceipted_terminal_supersession( async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 async def test_retry_sql_rejects_crossed_receipt_with_real_authority_participants( @@ -463,7 +467,7 @@ def omit_only_receipt(session, value): assert fence.current_run_id == str(command.source_run_id) assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 async with h.factory.begin() as session: valid = await checker_retry_service(session, operator).retry(command) assert valid.successor.generation == 2 @@ -589,7 +593,7 @@ async def false_digest_append(service, event): async with h.factory.begin() as session: await checker_retry_service(session, operator).retry(command) async with h.factory() as session: - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0 async with h.factory.begin() as session: @@ -608,7 +612,7 @@ async def test_retry_without_operator_grant_denies_without_effects( async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 assert await session.scalar(select(func.count()).select_from( AuditEvent ).where(AuditEvent.action_id == ActionId.OPERATIONS_CHECKER_RETRY.value)) == 0 @@ -627,7 +631,7 @@ async def test_retry_caller_rollback_removes_whole_successor( async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 assert await session.get(CheckerRun, str(staged.successor.run_id)) is None assert await session.get(AuditEvent, str(staged.authorization_decision_id)) is None @@ -668,7 +672,7 @@ async def test_retry_audit_failure_removes_whole_successor( ))).one() == (1, True) assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 fence = await session.get(CheckerSubmissionFence, str(h.request.submission_id)) assert fence.current_run_id == str(h.created.evaluation_attempt_id) assert await session.scalar(select(func.count()).select_from( @@ -714,7 +718,7 @@ async def test_retry_real_outbox_conflict_rolls_back_successor( assert fence.current_run_id == str(command.source_run_id) assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 3 assert await session.scalar(select(func.count()).select_from( AuditEvent ).where(AuditEvent.action_id == ActionId.OPERATIONS_CHECKER_RETRY.value)) == 0 @@ -741,7 +745,7 @@ async def test_retry_known_missing_object_dispatches_new_generation( assert receipt.source_result_digest == source.result_digest assert receipt.successor_request_digest == successor.request_digest assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 1 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 3 authorization = await session.get(AuditEvent, str(created.authorization_decision_id)) assert authorization.action_id == ActionId.OPERATIONS_CHECKER_RETRY.value assert authorization.project_id == str(h.request.project_id) @@ -821,7 +825,7 @@ async def retained_effects(): assert set(before[1]) == { str(command.source_run_id), str(created.successor.run_id), str(later.attempt_id), } - assert tuple(map(len, before[2:])) == (1, 3, 1, 1) + assert tuple(map(len, before[2:])) == (1, 4, 1, 1) async with h.factory.begin() as session: historical_replay = await checker_retry_service(session, operator).retry(command) assert historical_replay == created @@ -833,7 +837,7 @@ async def retained_effects(): assert successor.status == "completed" assert await session.get(CheckerRun, str(later.attempt_id)) is not None assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 1 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 3 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 4 async def test_retry_replays_after_real_auto_acceptance_but_new_key_denies( @@ -984,13 +988,13 @@ async def test_independent_sessions_wait_for_task_and_commit_one_retry( async with material_fixture(tmp_path, isolated_database_env) as h: port = _worker_port(h, monkeypatch) - def missing(_store, _reference): + def missing(_store, _reference, **kwargs): raise ArtifactObjectMissingError("controlled verified object loss") try: delivery = await delivery_fixture(h, materialization=port) with monkeypatch.context() as patch: - patch.setattr(LocalStorageAdapter, "open", missing) + patch.setattr(LocalStorageAdapter, "open_source", missing) initial = await delivery.delivery.deliver( h.created.evaluation_event_id, h.request.project_id, "concurrent-source", ) @@ -1072,7 +1076,7 @@ async def invoke(context, request): assert sum(isinstance(result, CheckerExecutionUnavailable) for result in outcomes) == 1 async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 1 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 3 assert await session.scalar(select(func.count()).select_from(AuditEvent).where( AuditEvent.action_id == ActionId.OPERATIONS_CHECKER_RETRY.value, )) == 1 diff --git a/backend/tests/reviews/decision/support.py b/backend/tests/reviews/decision/support.py index 176fa7aa8..468122a3c 100644 --- a/backend/tests/reviews/decision/support.py +++ b/backend/tests/reviews/decision/support.py @@ -9,14 +9,12 @@ from sqlalchemy import insert, select, text from app.adapters.tasks import submitted_bundle_port, task_submission_context_port -from app.api.deps.authorization import compose_hidden_submission_creation_command from app.core.identifiers import new_record_id from app.modules.actors.models import ActorIdentityLink -from app.modules.artifacts.api import SubmissionBundlePreparationRequest +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata from app.modules.artifacts.api.submission_manifest import ( build_submission_manifest, ) -from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.checkers.models import CheckerRun from app.modules.reviews.decision.models import ( FindingResolution, @@ -26,16 +24,14 @@ ) from app.modules.reviews.decision.schemas import ReviewFindingInput, ReviewSourceInput from app.modules.reviews.packet.repository import ReviewPacketRepository -from app.modules.tasks.api import SubmissionCreationRequest from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest from app.modules.tasks.api.submitted_bundle import SubmittedBundleRequest from app.modules.tasks.models import Submission from tests.checkers.execution.support import live_executor, reserve from tests.reviews.packet.support import packet_source, prepare_packet +from tests.post_submit_materialization_helpers import create_source_submission from tests.tasks.post_submit_routing.support import next_request, source_values -from tests.tasks.submission_lineage_support import _verified_admission from tests.test_artifact_admission import _context -from tests.archive_fixtures import byte_source as _bytes @asynccontextmanager @@ -282,40 +278,18 @@ async def _admit_successor(h): f"revision-{h.request.submission_version + 1}.txt", "The requested result is corrected." ) revised_data = revised_bytes.getvalue() - preparation = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - context.actor_profile_id, context.identity_link_id, ActorKind.HUMAN - ), - request_id=context.request_id, - correlation_id=context.correlation_id, + metadata = SubmissionIntakeMetadata( task_id=h.request.task_id, assignment_id=h.request.assignment_id, predecessor_submission_id=h.request.submission_id, - idempotency_key=new_record_id(), summary=h.creation_request.summary, contributor_attestation=h.creation_request.contributor_attestation, - media_type="application/zip", - byte_source=_bytes(revised_data), - revision_preparation_id=str(revision.preparation_id), + revision_preparation_id=revision.preparation_id, revision_preparation_sha256=revision.preparation_sha256, ) - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, context, preparation + created = await create_source_submission( + h.factory, context, h.store.wrapped, h.namespace, h.settings, metadata, revised_data, ) - async with h.factory() as session: - created = await compose_hidden_submission_creation_command( - session, context, request_id=new_record_id(), correlation_id=new_record_id() - ).create( - SubmissionCreationRequest( - task_id=h.request.task_id, - assignment_id=h.request.assignment_id, - contributor_id=context.actor_profile_id, - predecessor_submission_id=h.request.submission_id, - admission_id=admission_id, - summary=preparation.summary, - contributor_attestation=preparation.contributor_attestation, - ) - ) async with h.factory() as session: facts = await submitted_bundle_port(session).read( SubmittedBundleRequest(h.request.project_id, h.request.task_id, created.submission_id) From a950351619ee37aac71c75768b79c7652dd38307 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 21:59:20 +0100 Subject: [PATCH 177/513] test(submissions): separate parent custody and migrate PRE authority fixtures --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 39 ++++++++++++++++ .../post_submit/test_principals.py | 4 +- .../test_selected_pre_submit_coordination.py | 45 ++++++++++++++----- .../tests/tasks/test_submission_lineage.py | 44 +++++++++++------- 4 files changed, 104 insertions(+), 28 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 906bec5c9..849308b1f 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6240,3 +6240,42 @@ T4 and the new source assertion requires exactly1 finalization event. Ruff, whitespace, Commitrail and initial structure validation pass. Full retry replay (/tmp/submission-current-retry-v2) and prior AUTH replay remain live; this checkpoint does not claim their success or whole-spec readiness. + +PRE coordination fixture migration scope: test_selected_pre_submit_coordination.py +read-current replay, expired-lease read, execution capability and authority digest +proofs, plus their shared queued-row fixture. Use the existing _source_reservation +and real SelectedPreSubmitSourceCustody adapter; retain exact task/source locking, +changed-source replay rejection, lease identity and one-use/digest assertions. +Populate current source row fields without invented manifest/default inputs. +No production compatibility, retired admission capability repair or new alias. +Medium authority-test risk: run the four affected proofs and entire module to +separate remaining retired-contract failures; focused QA review required. + +ARCH/SEC separates retained historical jobs from obsolete new preparation flow: +do not revive PRE facts via guide-source AUTH fallback. Bounded parent-lock scope: +test_submission_lineage.py, extract existing current task/assignment setup from +_prepared_packet, use it directly for owner-substitution and NOWAIT parent locks. +Replace verifier positive control in substitution test with exact canonical +parent-lock success. Preserve all four substituted owners, both held locks and +both released-lock assertions. Leave historical migration replay unchanged and +explicitly defer obsolete verifier/new-creation tests to subsequent conversion. +No extra product writer, authority bypass or duplicated lifecycle implementation. +Run the five parent cases on real PostgreSQL; QA review required. + +Full affected AUTH/material replay terminates39pass1fail1342.16s. The sole +principals.finalize failure counts real setup materialization from final_facts as +denied-operation I/O. Extend scope to test_principals.py: snapshot source opens +after valid setup and require unchanged opens across denied operation, retaining +database snapshot, scratch/consumer and restored-authority positive control. +Do not clear observations or skip phases. Replay all three phase cases; QA check +must distinguish setup I/O from unauthorized I/O. No product authority change. + +Coordination final targeted replay passes4 in1.58s. Initial full module85pass4fail +included three untouched retired-contract cases and the missing explicit invocation +receipt now repaired; those three old cases remain required work. QA finds no +scoped defect in TASK fixture split, current source coordination or principal I/O +baseline. Independent exact-test probes detect reusable capabilities and +outcome-insensitive finalization digests (/tmp/submission-coordination-qa-mutation.log). +Unrelated verifier/history test ASTs remain unchanged. Ruff, whitespace and record +checks pass; parent5/principal3/fullretry and structure validation remain pending +at this checkpoint. Do not infer full readiness from these focused proofs. diff --git a/backend/tests/authorization/post_submit/test_principals.py b/backend/tests/authorization/post_submit/test_principals.py index 7be4d3ce7..5eae4e85d 100644 --- a/backend/tests/authorization/post_submit/test_principals.py +++ b/backend/tests/authorization/post_submit/test_principals.py @@ -34,6 +34,7 @@ async def test_inactive_fixed_actor_denies_phase(tmp_path, isolated_database_env suspended_by='test',suspended_at=clock_timestamp(),suspension_reason='test' WHERE service_identity=:identity"""), {"identity": identity.value}) before = await snapshot(h) + opened_before = tuple(h.store.opens) consumer = (Consumer(h.files, ExecuteFacts(request=h.request, lease=lease)) if phase == "materialize" else None) @@ -48,7 +49,8 @@ async def invoke(): with pytest.raises(expected): await invoke() assert await snapshot(h) == before - assert not h.store.opens and not h.preparation._active and (consumer is None or consumer.calls == 0) + assert tuple(h.store.opens) == opened_before + assert not h.preparation._active and (consumer is None or consumer.calls == 0) # Restore the fixture to prove that the same complete operation is valid. async with h.factory() as session, session.begin(): await session.execute(text("""UPDATE actor_profiles SET status='active', suspended_by=NULL, diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index 6b1cf5497..dda3f8a29 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -86,26 +86,31 @@ def _queued_row(reservation: SelectedPreSubmitReservationFacts) -> SimpleNamespa task_id=str(reservation.task_id), assignment_id=str(reservation.assignment_id), idempotency_key=str(reservation.idempotency_key), - prepared_generation_id=str(reservation.prepared_generation_id), + prepared_generation_id=None, + source_operation_id=str(reservation.source.location.operation_id), request_json=reservation.canonical_body(), request_digest=reservation.request_digest, policy_sha256=reservation.policy_sha256, default_behavior_sha256=reservation.default_behavior_sha256, - default_input_sha256=reservation.default_input_sha256, + default_input_sha256=None, archive_sha256=reservation.archive_sha256, archive_byte_count=reservation.archive_byte_count, - semantic_manifest_sha256=reservation.semantic_manifest_sha256, + semantic_manifest_sha256=None, execution_budget_ms=reservation.execution_budget_ms, status="queued", terminal_json=None, terminal_digest=None, eligible=None, + queued_at=datetime.now(UTC) - timedelta(seconds=3), + started_at=None, completed_at=None, + lease_id=None, lease_generation=0, lease_expires_at=None, + execute_evidence_id=None, finalize_evidence_id=None, ) @pytest.mark.asyncio async def test_selected_pre_current_replays_only_stable_actor_key_facts() -> None: - stored = _reservation() + stored = _source_reservation() row = _queued_row(stored) transaction = SimpleNamespace(is_active=True) session = SimpleNamespace( @@ -114,11 +119,15 @@ async def test_selected_pre_current_replays_only_stable_actor_key_facts() -> Non scalar=AsyncMock(return_value=row), ) tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock()) - coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, source_contracts=selected_pre_submit_source_contracts()) + sources = _source_guard(stored) + coordinator = SelectedPreSubmitCoordinator( + session, tasks=tasks, sources=SelectedPreSubmitSourceCustody(sources), + source_contracts=selected_pre_submit_source_contracts(), + ) fresh = replace( stored, attempt_id=new_record_id(), - prepared_generation_id=new_record_id(), + source_contracts=selected_pre_submit_source_contracts(), ) current = await coordinator.read_current(fresh) @@ -129,21 +138,28 @@ async def test_selected_pre_current_replays_only_stable_actor_key_facts() -> Non assert current.status == "queued" tasks.lock_selected_pre_submit_scope.assert_awaited_once_with(fresh) + changed = replace( + fresh, source=fresh.source.model_copy(update={"raw_sha256": "sha256:" + "f" * 64}), + source_contracts=selected_pre_submit_source_contracts(), + ) + sources.lock_pre_source.return_value = _source_guard(changed).lock_pre_source.return_value with pytest.raises( SelectedPreSubmitRequestConflict, match="selected_pre_submit_request_conflict", ): - await coordinator.read_current(replace(fresh, archive_sha256="sha256:" + "f" * 64)) + await coordinator.read_current(changed) @pytest.mark.asyncio async def test_selected_pre_expired_lease_read_keeps_task_first_custody() -> None: - reservation = _reservation() + reservation = _source_reservation() row = _queued_row(reservation) row.status = "running" row.lease_id = str(new_record_id()) row.lease_generation = 3 row.lease_expires_at = datetime.now(UTC) - timedelta(seconds=1) + row.started_at = row.queued_at + row.execute_evidence_id = str(new_record_id()) now = datetime.now(UTC) transaction = SimpleNamespace(is_active=True) session = SimpleNamespace( @@ -152,7 +168,11 @@ async def test_selected_pre_expired_lease_read_keeps_task_first_custody() -> Non scalar=AsyncMock(side_effect=[row, now]), ) tasks = SimpleNamespace(lock_selected_pre_submit_scope=AsyncMock()) - coordinator = SelectedPreSubmitCoordinator(session, tasks=tasks, source_contracts=selected_pre_submit_source_contracts()) + sources = _source_guard(reservation) + coordinator = SelectedPreSubmitCoordinator( + session, tasks=tasks, sources=SelectedPreSubmitSourceCustody(sources), + source_contracts=selected_pre_submit_source_contracts(), + ) lease = await coordinator.read_expired_lease( run_id=reservation.attempt_id, @@ -302,7 +322,7 @@ def test_selected_pre_admission_capability_is_exact_and_single_use() -> None: def test_selected_pre_execution_capability_is_exact_and_single_use() -> None: from datetime import UTC, datetime - reservation = _reservation() + reservation = _source_reservation() lease = SelectedPreSubmitLeaseFacts( reservation=reservation, lease_id=new_record_id(), @@ -334,7 +354,7 @@ def test_selected_pre_execution_capability_is_exact_and_single_use() -> None: def test_selected_pre_authority_digests_bind_lease_and_infrastructure_outcome() -> None: from datetime import UTC, datetime, timedelta - reservation = _reservation() + reservation = _source_reservation() lease = SelectedPreSubmitLeaseFacts( reservation=reservation, lease_id=new_record_id(), @@ -353,6 +373,7 @@ def test_selected_pre_authority_digests_bind_lease_and_infrastructure_outcome() terminal = SelectedPreSubmitFinalizeFacts( lease=lease, execution=None, + invocation_receipt=None, infrastructure_failure_code="deadline_exceeded", source_contracts=selected_pre_submit_source_contracts()) @@ -362,6 +383,7 @@ def test_selected_pre_authority_digests_bind_lease_and_infrastructure_outcome() != SelectedPreSubmitFinalizeFacts( lease=lease, execution=None, + invocation_receipt=None, infrastructure_failure_code="material_unavailable", source_contracts=selected_pre_submit_source_contracts()).facts_digest ) @@ -369,6 +391,7 @@ def test_selected_pre_authority_digests_bind_lease_and_infrastructure_outcome() SelectedPreSubmitFinalizeFacts( lease=lease, execution=None, + invocation_receipt=None, infrastructure_failure_code=None, source_contracts=selected_pre_submit_source_contracts()) diff --git a/backend/tests/tasks/test_submission_lineage.py b/backend/tests/tasks/test_submission_lineage.py index 02ca18994..65ac1e211 100644 --- a/backend/tests/tasks/test_submission_lineage.py +++ b/backend/tests/tasks/test_submission_lineage.py @@ -58,8 +58,8 @@ @asynccontextmanager -async def _prepared_packet( - isolated_database_env, tmp_path, *, verify=True, pre_submit_registry_spec=pre_registry_spec(), +async def _submission_task( + isolated_database_env, tmp_path, *, pre_submit_registry_spec=pre_registry_spec(), ): engine = create_async_engine(isolated_database_env) factory = async_sessionmaker(engine, expire_on_commit=False) @@ -89,6 +89,27 @@ async def _prepared_packet( await seed_started_task_for_artifact_test(connection, params) await install_submitter_grant(connection, params) archive_bytes = _archive(evidence_path=policy["evidence_path"]) + yield SimpleNamespace( + factory=factory, context=context, task_id=task_id, assignment_id=assignment_id, + project_id=plan.lineage.project_id, settings=settings, store=store, + namespace=namespace, archive_bytes=archive_bytes, policy=policy, + ) + finally: + bootstrap.close() + await engine.dispose() + + +@asynccontextmanager +async def _prepared_packet( + isolated_database_env, tmp_path, *, verify=True, pre_submit_registry_spec=pre_registry_spec(), +): + async with _submission_task( + isolated_database_env, tmp_path, pre_submit_registry_spec=pre_submit_registry_spec, + ) as task: + factory, context = task.factory, task.context + task_id, assignment_id = task.task_id, task.assignment_id + store, namespace, settings = task.store, task.namespace, task.settings + archive_bytes, policy = task.archive_bytes, task.policy request = SubmissionBundlePreparationRequest( actor=ActorIdentityFacts( context.actor_profile_id, context.identity_link_id, ActorKind.HUMAN @@ -127,15 +148,12 @@ async def _prepared_packet( creation = None yield SimpleNamespace( factory=factory, context=context, task_id=task_id, assignment_id=assignment_id, - project_id=plan.lineage.project_id, + project_id=task.project_id, admission_id=admission_id, creation=creation, preparation_request=request, archive_bytes=archive_bytes, settings=settings, store=store, namespace=namespace, put_attempt_id=put_attempt_id, ) - finally: - bootstrap.close() - await engine.dispose() @pytest.mark.parametrize("changed_owner", ("project", "task", "assignment", "contributor")) @@ -144,7 +162,7 @@ async def test_retained_submission_parent_lock_rejects_identity_substitution( tmp_path, changed_owner, ): - async with _prepared_packet(isolated_database_env, tmp_path, verify=False) as h: + async with _submission_task(isolated_database_env, tmp_path) as h: exact = TaskRetainedSubmissionParentsRequest( project_id=h.project_id, task_id=h.task_id, @@ -165,14 +183,8 @@ async def test_retained_submission_parent_lock_rejects_identity_substitution( replace(exact, **{field: new_record_id()}) ) - admission_id = await _verify_put_attempt( - h.factory, - h.store, - h.namespace, - h.settings, - h.put_attempt_id, - ) - assert admission_id is not None + async with h.factory.begin() as session: + await task_submission_context_port(session).lock_retained_submission_parents(exact) @pytest.mark.parametrize("lifecycle_owner", ("profile", "identity_link")) @@ -267,7 +279,7 @@ async def test_retained_submission_parent_port_holds_task_and_assignment_locks( isolated_database_env, tmp_path, ): - async with _prepared_packet(isolated_database_env, tmp_path, verify=False) as h: + async with _submission_task(isolated_database_env, tmp_path) as h: exact = TaskRetainedSubmissionParentsRequest( project_id=h.project_id, task_id=h.task_id, From 4fa3912042b9e90cdfab551c0be319d4114148c7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 22:10:23 +0100 Subject: [PATCH 178/513] test(submissions): prove malformed ZIP rejection through source intake --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 31 ++++ .../test_submission_foreground_command.py | 49 +++--- .../tasks/test_public_submission_intake.py | 165 +++++++----------- 3 files changed, 127 insertions(+), 118 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 849308b1f..9fc2e6123 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6279,3 +6279,34 @@ outcome-insensitive finalization digests (/tmp/submission-coordination-qa-mutati Unrelated verifier/history test ASTs remain unchanged. Ruff, whitespace and record checks pass; parent5/principal3/fullretry and structure validation remain pending at this checkpoint. Do not infer full readiness from these focused proofs. + +Public malformed-ZIP migration scope: artifacts/test_submission_foreground_command.py +and tasks/test_public_submission_intake.py. Extract the existing signed raw-ZIP +HTTP setup for reuse; preserve its four framing/replay tests. Replace obsolete +prepare-route malformed test with current submissions route: sealed upload precedes +real guest default inspection, bounded QC rejection preserves task/assignment and +creates no Submission/POST/finalization event, failed source remains cleanup-owned, +and corrected bytes with a new key accept. Keep response privacy assertions. +Do not restore removed preparation endpoints, suppress provider I/O, fabricate +PRE results or bypass task authority. Medium public-contract risk; run migrated +case plus existing four framing cases and QA review of changed outcome oracle. + +Public first replay4pass1fail131.98s: rejection checks pass, corrected-key control +hits500. QA identifies reused simulated-worker pre-tree directory; corrected +invocation must use a fresh child root, without clearing retained source/charge. +Restore exact malformed default failure/no project result and zero admission +assertions per QA-MALFORMED-001/002. Check simulated-runtime errors before the +positive HTTP assertion to retain diagnostic cause; no response/production change. +Earlier pending receipts now terminal: parent locks5pass145.79s, structure pass; +full retry26pass813.55s with cleanup complete. Principal three-phase replay2pass +and one10s scratch deadline in restored materializer positive control; unchanged +limit single-case replay passes1 in29.81s, cleanup complete. Do not claim the +transient deadline root cause resolved or all-provider qualification. + +Final malformed rejection/corrected-key proof passes1 in34.08s with owned database +and MinIO cleanup complete (/tmp/submission-public-malformed-v3). The unchanged +four framing/replay cases passed in v1. QA closes all three findings by inspection; +fresh worker root resolves the positive-control fixture failure. Ruff, whitespace, +record and structure checks pass. Current27531 hosted CLI API failure is now +concrete: three old _prepared_packet consumers and one registry409 fixture conflict; +they remain required migration work. Same draft PR708; no full-suite readiness claim. diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py index 39e84d2c2..6b965e86b 100644 --- a/backend/tests/artifacts/test_submission_foreground_command.py +++ b/backend/tests/artifacts/test_submission_foreground_command.py @@ -16,12 +16,8 @@ ) -@pytest.mark.parametrize("outcome,framing", [ - ("completed", "small"), ("rejected", "small"), - ("completed", "large-single"), ("completed", "large-split"), -]) -async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admission_intake, tmp_path, monkeypatch, outcome, framing): - from sqlalchemy import text +async def configure_source_http(f, tmp_path, monkeypatch, payload, outcome): + """Bind signed HTTP to real intake owners and the controlled guest transport.""" from app.adapters import artifacts as composition from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter from app.modules.actors.api import ServiceIdentity @@ -30,20 +26,6 @@ async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admi from tests.checkers.execution.support import provision_post_submit_service from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation from tests.test_artifact_admission import _settings - from tests.test_trusted_intake import _archive - - f, key = admission_intake, new_record_id() - payload = _archive("../escape") if outcome == "rejected" else _archive() - if framing.startswith("large"): - payload = _archive(content=b"finished work\n" * 90_000) - assert 1024 * 1024 < len(payload) < 2 * 1024 * 1024 - def body(split): - if not split: - return payload - async def chunks(): - for start in range(0, len(payload), 64 * 1024): - yield payload[start:start + 64 * 1024] - return chunks() runtime, errors = _source_runtime(payload, tmp_path, outcome) calls, original = [], runtime.execute_pre async def execute(lease, grant): @@ -65,6 +47,33 @@ async def execute(lease, grant): "replay_total_seconds": 30.0, "part_bytes": 5 * 1024**2, }}) monkeypatch.setattr(app.state, "settings", settings) + return client, settings, errors, calls + + +@pytest.mark.parametrize("outcome,framing", [ + ("completed", "small"), ("rejected", "small"), + ("completed", "large-single"), ("completed", "large-split"), +]) +async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admission_intake, tmp_path, monkeypatch, outcome, framing): + from sqlalchemy import text + from tests.test_trusted_intake import _archive + + f, key = admission_intake, new_record_id() + payload = _archive("../escape") if outcome == "rejected" else _archive() + if framing.startswith("large"): + payload = _archive(content=b"finished work\n" * 90_000) + assert 1024 * 1024 < len(payload) < 2 * 1024 * 1024 + def body(split): + if not split: + return payload + async def chunks(): + for start in range(0, len(payload), 64 * 1024): + yield payload[start:start + 64 * 1024] + return chunks() + client, settings, errors, calls = await configure_source_http( + f, tmp_path, monkeypatch, payload, outcome, + ) + app = client._transport.app headers = f.access.target.headers | {"Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), "Idempotency-Key": str(key), "Content-Length": str(len(payload))} diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index f48deed48..19bcb1b26 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -25,12 +25,20 @@ from app.modules.checkers.api.pre_submit_material import SubmissionPacketView from app.modules.outbox.models import OutboxEvent from app.modules.tasks.models import Submission -from app.modules.tasks.models import TaskAssignment, WorkstreamTask +from app.modules.tasks.models import WorkstreamTask from app.modules.tasks.api import SubmissionCreationRequest from app.modules.tasks.schemas import AdmissionBackedSubmissionCreate from app.modules.api_controls.service import AUTHORIZATION_READ_SCOPE, RateControlService from app.modules.actors.models import ActorProfile from tests.tasks.test_submission_lineage import _prepared_packet +from tests.artifacts.test_submission_intake_admission import ( + admission_intake as admission_intake, + admin_access as admin_access, + signed_access as signed_access, + rsa_signing_material as rsa_signing_material, + auth_database_env as auth_database_env, + clear_settings_cache as clear_settings_cache, +) from tests.test_artifact_admission import _context, _seed_human_actor from tests.submission_preparation_auth_helpers import install_submitter_grant from tests.tasks.post_submit_routing.backfill_support import assert_upgrade_refuses_stale_findings @@ -123,104 +131,65 @@ def _payload(request, admission_id): } -async def test_public_malformed_zip_returns_bounded_422_without_effects( - isolated_database_env, tmp_path, monkeypatch, +async def test_public_malformed_zip_preserves_task_and_retains_cleanup_custody( + admission_intake, tmp_path, monkeypatch, ): - """Reject unreadable contributor bytes before PRE, provider, or lifecycle effects.""" - async with _prepared_packet(isolated_database_env, tmp_path, verify=False) as h: - route = f"/api/v1/tasks/{h.task_id}/submission-bundle-preparations" - headers = { - "Content-Type": "application/zip", - "X-Task-Assignment-Id": str(h.assignment_id), - "Idempotency-Key": str(new_record_id()), - "X-Submission-Summary": h.preparation_request.summary, - "X-Contributor-Attestation": h.preparation_request.contributor_attestation, - } - counted_models = ( - Submission, - SubmissionBundleAdmission, - SelectedPreSubmitRun, - CheckerRun, - ArtifactPutAttempt, - OutboxEvent, - ) - - async with _client( - h, - monkeypatch, - isolated_database_env, - raise_app_exceptions=False, - ) as client: - async with h.factory() as session: - before_count_values = [] - for model in counted_models: - before_count_values.append( - await session.scalar(select(func.count()).select_from(model)) - ) - before_counts = tuple(before_count_values) - task = await session.get(WorkstreamTask, str(h.task_id)) - assignment = await session.get(TaskAssignment, str(h.assignment_id)) - before_state = (task.status, assignment.status) - - from app.adapters.artifacts.local import LocalStorageAdapter - from app.modules.artifacts.selected_pre_submit_execution import ( - SelectedPreSubmitExecutionService, - ) - - async def unexpected_effect(*_args, **_kwargs): - raise AssertionError("archive rejection reached checker or provider effects") - - with monkeypatch.context() as patch: - patch.setattr(LocalStorageAdapter, "put", unexpected_effect) - patch.setattr( - SelectedPreSubmitExecutionService, "execute", unexpected_effect, - ) - response = await client.post( - route, - headers=headers, - content=b"PK\x03\x04not-a-readable-zip", - ) - - async with h.factory() as session: - after_count_values = [] - for model in counted_models: - after_count_values.append( - await session.scalar(select(func.count()).select_from(model)) - ) - after_counts = tuple(after_count_values) - task = await session.get(WorkstreamTask, str(h.task_id)) - assignment = await session.get(TaskAssignment, str(h.assignment_id)) - after_state = (task.status, assignment.status) - - assert after_counts == before_counts - assert after_state == before_state == ("in_progress", "active") - assert not tuple((h.settings.artifact_scratch_root / "files").iterdir()) - assert not tuple((h.settings.artifact_scratch_root / "workspaces").iterdir()) - assert response.status_code == 422, response.text - payload = response.json() - assert payload["detail"] == "submission_archive_malformed" - assert payload["error"] == { - "code": "invalid_request", - "message": "Invalid request", - "details": {}, - "correlation_id": response.headers["X-Correlation-ID"], - "retryable": False, - } - rendered = response.text - assert all( - value not in rendered - for value in ("/tmp/", "s3://", "not-a-readable-zip", "BadZipFile") - ) - - valid = await client.post( - route, - headers=headers | {"Idempotency-Key": str(new_record_id())}, - content=h.archive_bytes, - ) - assert valid.status_code == 202, valid.text - assert valid.json()["submission_bundle_preparation_status"] == ( - "stored_pending_verification" - ) + """Malformed sealed input rejects before acceptance and remains cleanup-owned.""" + from sqlalchemy import text + from app.adapters import artifacts as composition + from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.artifacts.test_submission_pre_source import _source_runtime + from tests.test_trusted_intake import _archive + + f = admission_intake + malformed = b"PK\x03\x04not-a-readable-zip" + client, settings, errors, calls = await configure_source_http( + f, tmp_path, monkeypatch, malformed, "rejected", + ) + headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + "Idempotency-Key": str(new_record_id()), + } + route = f"/api/v1/tasks/{f.task}/submissions" + response = await client.post(route, headers=headers, content=malformed) + assert response.status_code == 422, response.text + assert response.json()["error"]["code"] == "pre_submission_checker_failed" + assert response.json()["error"]["details"]["eligible_to_submit"] is False + results = response.json()["error"]["details"]["results"] + assert any(item["source"] == "workstream_default" + and item.get("failure_code") == "submission_archive_malformed" for item in results) + assert not any(item["source"] == "project_external_checker" for item in results) + assert len(calls) == 1 and not errors, errors + assert all(value not in response.text for value in ( + "/tmp/", "s3://", "not-a-readable-zip", "BadZipFile", + )) + async with f.factory() as session: + assert await session.scalar(text("SELECT status FROM workstream_tasks WHERE id=:id"), + {"id": f.task}) == "in_progress" + assert await session.scalar(text("SELECT status FROM task_assignments WHERE id=:id"), + {"id": f.assignment}) == "active" + assert await session.scalar(select(func.count()).select_from(Submission)) == 0 + assert await session.scalar(select(func.count()).select_from(SubmissionBundleAdmission)) == 0 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 0 + assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 0 + assert await session.scalar(text("SELECT state FROM submission_intake_operations WHERE task_id=:id"), + {"id": f.task}) == "rejected" + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges")) == len(malformed) + assert not tuple(settings.artifact_scratch_root.glob("files/*")) + assert not tuple(settings.artifact_scratch_root.glob("workspaces/*")) + + valid_bytes = _archive() + retry_root = tmp_path / "corrected-worker" + retry_root.mkdir() + runtime, valid_errors = _source_runtime(valid_bytes, retry_root, "completed") + monkeypatch.setattr(composition, "selected_pre_submit_checker_execution", + lambda **kwargs: SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime)) + valid = await client.post(route, headers=headers | {"Idempotency-Key": str(new_record_id())}, + content=valid_bytes) + assert not valid_errors, "\n".join(valid_errors) + assert valid.status_code == 202, valid.text + assert valid.json()["status"] == "accepted" and valid.json()["replayed"] is False def test_optional_public_text_keeps_packet_utf8_byte_limit(): From 8bfd9f171f86e82ce073f887a104192495936812 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 22:17:34 +0100 Subject: [PATCH 179/513] test(cli): exercise current source submissions and registry custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 27 ++++++++++ .../test_submission_foreground_command.py | 10 ++-- .../tasks/test_public_submission_intake.py | 2 +- .../test_checker_operations_public_api.py | 5 +- .../test_manager_task_evidence_public_api.py | 49 +++++++++++++++---- cli/tests/integration/test_tui_public_api.py | 31 +++++++----- 6 files changed, 94 insertions(+), 30 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 9fc2e6123..2cf6005ee 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6310,3 +6310,30 @@ fresh worker root resolves the positive-control fixture failure. Ruff, whitespac record and structure checks pass. Current27531 hosted CLI API failure is now concrete: three old _prepared_packet consumers and one registry409 fixture conflict; they remain required migration work. Same draft PR708; no full-suite readiness claim. + +CLI current producer scope: integration/test_manager_task_evidence_public_api.py, +test_tui_public_api.py, test_checker_operations_public_api.py; shared signed HTTP +setup in artifacts/test_submission_foreground_command.py and its malformed caller. +Manager retains actual CLI submission using file/key, accepts202 then drives exact +OUTBOX T5 before history checks. TUI setup uses current TASK fixture and real source +submission where needed; claim-only case needs no admission. Shared HTTP setup +takes explicit factory/client, provisions fixed principals idempotently without +resetting lifecycle. Preserve all fresh-revocation, concealment, history and CLI +wire assertions. Registry probes use distinct versions from two locked fixture +images and assert exact total4 after two CLI registrations. No compatibility flags, +authority bypass, skipped test or changed production API. Medium risk client/owner +integration: run all four affected CLI cases with built binary, existing HTTP +helper consumers, CLI Ruff/format, structural checks and focused QA review. +Use the existing signed raw-ZIP journey's90s subprocess allowance only for task +submit; keep20s for reads. This accommodates the foreground upload/PRE command +instead of the removed short admission call; no product deadline changes. + +CLI current-producer replay passes4 in185.90s (existing marker/serializer warnings), +including actual manager CLI ZIP submission, signed TUI read/claim and revocation, +Operator registry/retry. Shared HTTP helper consumers pass5 in169.90s. Both isolated +receipts confirm database and MinIO cleanup complete. QA finds no scoped defect; +all prior manager/TUI assertions and registry replay/concealment/revocation guards +remain. Full CLI Ruff/format99files, structural validator, record and whitespace +checks pass. Fresh origin/main fetch has no commits absent from this branch. +These focused proofs close the four observed27531 CLI API failures locally; +hosted rerun and remaining full-spec/current producer migrations remain required. diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py index 6b965e86b..ee7eac04c 100644 --- a/backend/tests/artifacts/test_submission_foreground_command.py +++ b/backend/tests/artifacts/test_submission_foreground_command.py @@ -16,13 +16,12 @@ ) -async def configure_source_http(f, tmp_path, monkeypatch, payload, outcome): +async def configure_source_http(factory, client, tmp_path, monkeypatch, payload, outcome): """Bind signed HTTP to real intake owners and the controlled guest transport.""" from app.adapters import artifacts as composition from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter from app.modules.actors.api import ServiceIdentity from tests.artifacts.test_submission_pre_source import _source_runtime - from tests.authorization.test_pre_submit_attempt_authority import _seed_materializer from tests.checkers.execution.support import provision_post_submit_service from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation from tests.test_artifact_admission import _settings @@ -34,9 +33,8 @@ async def execute(lease, grant): runtime.execute_pre = execute monkeypatch.setattr(composition, "selected_pre_submit_checker_execution", lambda **kwargs: SelectedPreSubmitCheckerExecutionAdapter(external_execution=runtime)) - await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_PRE_SUBMIT) - await _seed_materializer(f.factory) - client = f.access.signed.client + await provision_post_submit_service(factory, ServiceIdentity.CHECKER_PRE_SUBMIT) + await provision_post_submit_service(factory, ServiceIdentity.ARTIFACT_MATERIALIZER) app = client._transport.app storage = {name: value for name, value in _settings(tmp_path).model_dump().items() if name.startswith("artifact_")} settings = app.state.settings.model_copy(update=storage | {"submission_execution_profile": { @@ -71,7 +69,7 @@ async def chunks(): yield payload[start:start + 64 * 1024] return chunks() client, settings, errors, calls = await configure_source_http( - f, tmp_path, monkeypatch, payload, outcome, + f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, outcome, ) app = client._transport.app headers = f.access.target.headers | {"Content-Type": "application/zip", diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index 19bcb1b26..451baa0a1 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -145,7 +145,7 @@ async def test_public_malformed_zip_preserves_task_and_retains_cleanup_custody( f = admission_intake malformed = b"PK\x03\x04not-a-readable-zip" client, settings, errors, calls = await configure_source_http( - f, tmp_path, monkeypatch, malformed, "rejected", + f.factory, f.access.signed.client, tmp_path, monkeypatch, malformed, "rejected", ) headers = f.access.target.headers | { "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), diff --git a/cli/tests/integration/test_checker_operations_public_api.py b/cli/tests/integration/test_checker_operations_public_api.py index fdd705f7e..6fb85a085 100644 --- a/cli/tests/integration/test_checker_operations_public_api.py +++ b/cli/tests/integration/test_checker_operations_public_api.py @@ -56,6 +56,7 @@ async def test_operator_registry_and_exact_terminal_retry_through_real_api( operator_grant = await signed.grant(admin_access.admin, admin_access.target) outsider = await signed.actor("cli-checker-outsider") payload = registry_spec().model_dump(mode="json") + payload["capability_version"] = "v1.2.4" input_file = tmp_path / "checker.json" input_file.write_text(json.dumps(payload, ensure_ascii=False)) key = str(uuid4()) @@ -152,7 +153,7 @@ async def call(actor, *args, status=None): ) numeric_payload = registry_spec().model_dump(mode="json") - numeric_payload["capability_version"] = "v1.2.4" + numeric_payload["capability_version"] = "v1.2.5" document = numeric_payload["configuration_schema"]["document"] document["examples"] = [9007199254740993, -0.0, 1e20] numeric_payload["configuration_schema"]["schema_sha256"] = ( @@ -285,7 +286,7 @@ async def call(actor, *args, status=None): ExternalCheckerRegistryEntryRecord ) ) - == 2 + == 4 # Two locked fixture images and two CLI registrations. ) revoked = await signed.revoke(admin_access.admin, operator_grant) diff --git a/cli/tests/integration/test_manager_task_evidence_public_api.py b/cli/tests/integration/test_manager_task_evidence_public_api.py index 599243dfe..31ce57c25 100644 --- a/cli/tests/integration/test_manager_task_evidence_public_api.py +++ b/cli/tests/integration/test_manager_task_evidence_public_api.py @@ -1,6 +1,6 @@ """Manager CLI reads through real HTTP/API/PostgreSQL authority and retained rows. -The existing fixture arranges approved policy, a started task, admission and +The existing fixture arranges approved policy, a started task and manager/Submitter grants. The tested Submission is created by the public CLI; this test makes no backend authority or checker decision on the CLI's behalf. """ @@ -10,7 +10,8 @@ import json import sys from pathlib import Path -from uuid import uuid4 +from uuid import UUID, uuid4 +from types import SimpleNamespace import pytest from sqlalchemy import select @@ -24,7 +25,7 @@ postgres_database_url as postgres_database_url, isolated_database_env as isolated_database_env, ) -from tests.tasks.test_submission_lineage import _prepared_packet # noqa: E402 +from tests.tasks.test_submission_lineage import _submission_task # noqa: E402 from tests.tasks.test_public_submission_intake import _client # noqa: E402 from tests.project_create_fixtures import ( # noqa: E402 grant_fixture_admin_role, @@ -41,8 +42,23 @@ async def test_manager_context_history_and_checker_authority( monkeypatch, cli, ): - async with _prepared_packet(isolated_database_env, tmp_path) as h: + async with _submission_task(isolated_database_env, tmp_path) as h: async with _client(h, monkeypatch, isolated_database_env) as direct: + from tests.artifacts.test_submission_foreground_command import ( + configure_source_http, + ) + from tests.retained_material_fixtures import finalize_retained_intake + + _, settings, runtime_errors, runtime_calls = await configure_source_http( + h.factory, + direct, + tmp_path, + monkeypatch, + h.archive_bytes, + "completed", + ) + archive = tmp_path / "manager-submission.zip" + archive.write_bytes(h.archive_bytes) async with socket_api(direct._transport.app) as origin: project, task = str(h.project_id), str(h.task_id) @@ -54,6 +70,7 @@ async def call(*args, status=200): "-o", "json", *args, + process_timeout=90 if args[:2] == ("task", "submit") else 20, ) if status != 200: assert result.returncode == 1 and result.stdout == "", ( @@ -103,14 +120,28 @@ async def call(*args, status=200): task, "--assignment", str(h.assignment_id), - "--admission", - str(h.admission_id), + "--file", + str(archive), + "--idempotency-key", + str(uuid4()), "--summary", - h.preparation_request.summary, + "Completed the required project work and included evidence.", "--attestation", - h.preparation_request.contributor_attestation, + " ".join(h.policy["attestation_terms"]), + ) + assert receipt["status"] == "accepted" and receipt["replayed"] is False + assert len(runtime_calls) == 1 and not runtime_errors, runtime_errors + submission = str( + await finalize_retained_intake( + h.factory, + SimpleNamespace( + operation_id=UUID(receipt["operation_id"]), + settings=settings, + store=h.store, + namespace=h.namespace, + ), + ) ) - submission = receipt["submission_id"] [item] = ( await call( "project", "task-submissions", project, task, "--limit", "1" diff --git a/cli/tests/integration/test_tui_public_api.py b/cli/tests/integration/test_tui_public_api.py index aa3a61524..a561240c6 100644 --- a/cli/tests/integration/test_tui_public_api.py +++ b/cli/tests/integration/test_tui_public_api.py @@ -21,8 +21,8 @@ ) from test_submission_public_api import socket_api from tui_terminal_support import Terminal -from app.api.deps.authorization import compose_hidden_submission_creation_command -from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata +from tests.post_submit_materialization_helpers import create_source_submission from app.modules.authorization.models import ProjectRoleGrant from app.modules.checkers.models import CheckerRun from app.modules.contributions.records.models import ContributionRecord @@ -43,7 +43,7 @@ from tests.conftest import ( pagination_cursor_hmac_secret as pagination_cursor_hmac_secret, ) -from tests.tasks.test_submission_lineage import _prepared_packet +from tests.tasks.test_submission_lineage import _submission_task signed_access = pytest_asyncio.fixture(_signed_access.__wrapped__) admin_access = pytest_asyncio.fixture(_admin_access.__wrapped__) @@ -55,7 +55,7 @@ async def test_tui_real_signed_owner_positive_reads_then_fresh_grant_revocation( tmp_path, auth_database_env, admin_access ): signed = admin_access.signed - async with _prepared_packet(auth_database_env, tmp_path) as h: + async with _submission_task(auth_database_env, tmp_path) as h: # Bind the actual stored identity link, not intake_client's actor override. subject = f"human-{h.context.actor_profile_id}" owner = SignedActor( @@ -70,13 +70,20 @@ async def test_tui_real_signed_owner_positive_reads_then_fresh_grant_revocation( profile = await client.get("/api/v1/actors/me", headers=owner.headers) assert profile.status_code == 200, profile.text assert profile.json()["actor_profile_id"] == str(owner.id) - async with h.factory() as session: - receipt = await compose_hidden_submission_creation_command( - session, - h.context, - request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(h.creation) + receipt = await create_source_submission( + h.factory, + h.context, + h.store, + h.namespace, + h.settings, + SubmissionIntakeMetadata( + task_id=h.task_id, + assignment_id=h.assignment_id, + summary="Completed the required project work.", + contributor_attestation=" ".join(h.policy["attestation_terms"]), + ), + h.archive_bytes, + ) submission_id = str(receipt.submission_id) access = SimpleNamespace(signed=signed) ready_id = await create_task(access, h.project_id, owner) @@ -227,7 +234,7 @@ async def test_tui_real_signed_claim_starts_work_replay_then_fresh_revocation( tmp_path, auth_database_env, admin_access ): signed = admin_access.signed - async with _prepared_packet(auth_database_env, tmp_path) as h: + async with _submission_task(auth_database_env, tmp_path) as h: subject = f"human-{h.context.actor_profile_id}" owner = SignedActor( h.context.actor_profile_id, From 953c0a97aa578a947893e42080b8bfabbc734bbd Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 22:26:41 +0100 Subject: [PATCH 180/513] test(submissions): preserve packet text and feedback through source replay --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 33 ++ .../test_submission_foreground_command.py | 4 +- .../artifacts/test_submission_pre_source.py | 16 +- .../tasks/test_public_submission_intake.py | 284 ++++++++---------- 4 files changed, 169 insertions(+), 168 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2cf6005ee..6ea5b240a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6337,3 +6337,36 @@ remain. Full CLI Ruff/format99files, structural validator, record and whitespace checks pass. Fresh origin/main fetch has no commits absent from this branch. These focused proofs close the four observed27531 CLI API failures locally; hosted rerun and remaining full-spec/current producer migrations remain required. + +Optional public packet migration scope: tasks/test_public_submission_intake.py. +Replace removed nullable admission-JSON contract with raw header metadata: +omitted/empty ASCII text hashes equally, bounds remain enforced, retained packet +UTF-8 byte bound remains independently protected. Real signed ZIP accepts with +warning-only empty text, explicit empty replay keeps one PRE/source, changed +metadata conflicts before extra work. Drive production OUTBOX T5 then repeat +replay and inspect exact empty stored packet/consumed admission and one Submission. +No nullable-header compatibility, fabricated ready admission, skipped guard or +changed product API. Medium contract/replay risk: targeted pure+PostgreSQL tests, +Ruff/structure/record checks and focused QA review required. + +Public nonblocking-feedback migration extends scope to the existing source runtime +fixture in artifacts/test_submission_pre_source.py and configure_source_http helper. +Permit explicit controlled project findings through the worker's existing project +reply hook, deriving the result digest with the canonical constructor. Guest still +derives source inspection/defaults and binds request/lease. Convert removed prepare +endpoint test to signed raw ZIP accepted receipt, exact coverage-incomplete finding, +no PRE replay, T5 evaluation_pending and existing0049 incompatible-finding refusal. +No caller-supplied manifest/default or product/runtime changes. Verify converted +case and unchanged-default optional packet consumer; QA shared-helper review. + +Optional packet/bounds first replay passes2 in32.86s with cleanup complete. +Feedback first pair1pass1fail62.17s: strict constructor correctly rejects JSON UUID +strings in simulated project reply. QA-FEEDBACK-001 repairs fixture normalization: +decode original ExternalCheckerExecutionResult, use typed fields, replace findings +and derive fresh digest. Exact-hook probe preserves request/registry/lease and +detects lost coverage findings. Final feedback+optional pair passes2 in62.18s, +including T5 and retained0049 check; database/MinIO cleanup complete. QA finds no +remaining scoped code issue. Ruff, whitespace, record and structure checks pass. +Hosted8bfd gates/images pass but Backend was pending behind superseded27531 run; +requested cancellation of that old same-PR run, retaining its artifacts. No full +CI/spec/provider readiness claim; remaining old public producers still need migration. diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py index ee7eac04c..9644776e4 100644 --- a/backend/tests/artifacts/test_submission_foreground_command.py +++ b/backend/tests/artifacts/test_submission_foreground_command.py @@ -16,7 +16,7 @@ ) -async def configure_source_http(factory, client, tmp_path, monkeypatch, payload, outcome): +async def configure_source_http(factory, client, tmp_path, monkeypatch, payload, outcome, *, project_findings=()): """Bind signed HTTP to real intake owners and the controlled guest transport.""" from app.adapters import artifacts as composition from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter @@ -25,7 +25,7 @@ async def configure_source_http(factory, client, tmp_path, monkeypatch, payload, from tests.checkers.execution.support import provision_post_submit_service from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation from tests.test_artifact_admission import _settings - runtime, errors = _source_runtime(payload, tmp_path, outcome) + runtime, errors = _source_runtime(payload, tmp_path, outcome, project_findings=project_findings) calls, original = [], runtime.execute_pre async def execute(lease, grant): calls.append(lease.reservation.attempt_id) diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py index a4c12e605..18049d02e 100644 --- a/backend/tests/artifacts/test_submission_pre_source.py +++ b/backend/tests/artifacts/test_submission_pre_source.py @@ -420,7 +420,7 @@ async def _assert_stored_receipt(factory, run_id, terminal): assert stored.finalize_evidence_id is not None -def _source_runtime(payload, tmp_path, runtime_outcome): +def _source_runtime(payload, tmp_path, runtime_outcome, *, project_findings=()): """Real intake worker with an explicit simulated project reply or capacity failure.""" from contextlib import aclosing from app.interfaces.external_services import ExternalServiceAdapterIdentity @@ -430,6 +430,19 @@ def _source_runtime(payload, tmp_path, runtime_outcome): from tests.checkers.external.test_pre_invocation import receipt_body from tests.test_trusted_intake import _pre_worker, _read + def project_result(body): + import json + from app.modules.checkers.api.external import ( + ExternalCheckerExecutionResult, make_external_checker_execution_result, + ) + + fields = ExternalCheckerExecutionResult.model_validate_json( + json.dumps(body["result"]), + ).model_dump(mode="python", exclude={"result_digest"}) + body["result"] = make_external_checker_execution_result( + **(fields | {"findings": project_findings}), + ).model_dump(mode="json") + runtime_errors = [] class SourceRuntime: @property @@ -456,6 +469,7 @@ async def run(self, lease, grant): if runtime_outcome in {"completed", "rejected"}: worker, output, reply, actual_lease = _pre_worker( tmp_path, payload, lease=lease, + result_change=project_result if project_findings else None, isolation_override={"runtime": "smolvm", "isolation_mode": "smol-microvm"}, ) assert actual_lease is lease diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index 451baa0a1..50610f4f1 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -26,8 +26,6 @@ from app.modules.outbox.models import OutboxEvent from app.modules.tasks.models import Submission from app.modules.tasks.models import WorkstreamTask -from app.modules.tasks.api import SubmissionCreationRequest -from app.modules.tasks.schemas import AdmissionBackedSubmissionCreate from app.modules.api_controls.service import AUTHORIZATION_READ_SCOPE, RateControlService from app.modules.actors.models import ActorProfile from tests.tasks.test_submission_lineage import _prepared_packet @@ -44,7 +42,7 @@ from tests.tasks.post_submit_routing.backfill_support import assert_upgrade_refuses_stale_findings from tests.tasks.post_submit_routing.remediation_support import remediation_source from tests.tasks.post_submit_routing.support import revision_archive -from tests.tasks.submission_lineage_support import _verified_admission, _verify_put_attempt +from tests.tasks.submission_lineage_support import _verified_admission from tests.test_submission_predecessor_custody import ( _fixture_revision_context, _replacement_request, ) @@ -192,186 +190,142 @@ async def test_public_malformed_zip_preserves_task_and_retains_cleanup_custody( assert valid.json()["status"] == "accepted" and valid.json()["replayed"] is False -def test_optional_public_text_keeps_packet_utf8_byte_limit(): - """The new nullable body still uses the existing exact packet byte bound.""" - base = {"admission_id": str(new_record_id()), "assignment_id": str(new_record_id())} - assert set(AdmissionBackedSubmissionCreate.model_json_schema()["required"]) == { - "admission_id", "assignment_id", - } - for value in (None, ""): - packet = AdmissionBackedSubmissionCreate.model_validate( - base | {"summary": value, "contributor_attestation": value} - ) - assert packet.summary == value - assert packet.contributor_attestation == value - omitted = AdmissionBackedSubmissionCreate.model_validate(base) - assert omitted.summary is None and omitted.contributor_attestation is None - canonical = SubmissionCreationRequest( - admission_id=new_record_id(), task_id=new_record_id(), - assignment_id=new_record_id(), contributor_id=new_record_id(), - predecessor_submission_id=None, summary="", contributor_attestation="", - ) - assert SubmissionPacketView( - canonical.summary, canonical.contributor_attestation, - ).sha256 == SubmissionPacketView("", "").sha256 +def test_optional_public_text_keeps_metadata_and_retained_packet_bounds(): + """Empty ASCII headers normalize; retained packets keep their UTF-8 bound.""" + from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata + + base = {"task_id": new_record_id(), "assignment_id": new_record_id()} + omitted = SubmissionIntakeMetadata(**base) + empty = SubmissionIntakeMetadata(**base, summary="", contributor_attestation="") + assert omitted.summary == omitted.contributor_attestation == "" + assert omitted.metadata_sha256() == empty.metadata_sha256() + assert SubmissionIntakeMetadata(**base, summary="x" * 65536).summary == "x" * 65536 + with pytest.raises(ValueError): + SubmissionIntakeMetadata(**base, summary="x" * 65537) + with pytest.raises(ValueError, match="printable ASCII"): + SubmissionIntakeMetadata(**base, summary="é") assert SubmissionPacketView("é" * 32768, "").sha256 with pytest.raises(ValueError, match="submission packet text is invalid"): SubmissionPacketView("é" * 32769, "") -async def test_public_optional_packet_text_round_trips_through_ready_admission( - isolated_database_env, tmp_path, monkeypatch, +async def test_public_optional_packet_text_survives_acceptance_finalization_and_replay( + admission_intake, tmp_path, monkeypatch, ): - """Omitted, null and empty POST text match PRE's warning-only empty packet.""" - async with _prepared_packet(isolated_database_env, tmp_path) as h: - preparation_route = f"/api/v1/tasks/{h.task_id}/submission-bundle-preparations" - creation_route = f"/api/v1/tasks/{h.task_id}/submissions" - key = new_record_id() - headers = { - "Content-Type": "application/zip", - "X-Task-Assignment-Id": str(h.assignment_id), - "Idempotency-Key": str(key), - } - async with _client(h, monkeypatch, isolated_database_env) as client: - prepared = await client.post( - preparation_route, headers=headers, content=h.archive_bytes, - ) - assert prepared.status_code == 202, prepared.text - assert prepared.json()["submission_bundle_preparation_status"] == "stored_pending_verification" - assert prepared.json()["admission_id"] is None - admission_id = await _verify_put_attempt( - h.factory, h.store, h.namespace, h.settings, - prepared.json()["put_attempt_id"], - ) - ready = await client.post( - preparation_route, - headers=headers | { - "X-Submission-Summary": "", - "X-Contributor-Attestation": "", - }, - content=h.archive_bytes, - ) - assert ready.status_code == 202, ready.text - assert ready.json()["submission_bundle_preparation_status"] == "ready" - assert ready.json()["admission_id"] == str(admission_id) - assert ready.json()["replayed"] is True + """Omitted and empty headers retain warning-only packet facts through T5.""" + from uuid import UUID + from sqlalchemy import text + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.retained_material_fixtures import finalize_retained_intake + from tests.test_artifact_admission import _local_store + from tests.test_trusted_intake import _archive - async with h.factory() as session: - selected = await session.scalar( - select(SelectedPreSubmitRun).where( - SelectedPreSubmitRun.idempotency_key == str(key) - ) - ) - assert selected is not None - default = selected.terminal_json["execution"]["workstream_default"] - assert default["eligible"] is True - assert [warning["code"] for warning in default["warnings"]] == [ - "submission_summary_missing", "submission_attestation_missing", - ] - - empty = _payload(h.creation, admission_id) - empty.pop("summary") - empty.pop("contributor_attestation") - created = await client.post(creation_route, json=empty) - assert created.status_code == 201, created.text - result = created.json() - for value in (None, ""): - replay_packet = empty | { - "summary": value, - "contributor_attestation": value, - } - replay = await client.post(creation_route, json=replay_packet) - assert replay.status_code == 201, replay.text - assert replay.json() == result - - changed = empty | {"summary": "now supplied"} - denied = await client.post(creation_route, json=changed) - assert denied.status_code == 404, denied.text - assert denied.json()["error"]["code"] == "submission_unavailable" + f, payload, key = admission_intake, _archive(), new_record_id() + client, settings, errors, calls = await configure_source_http( + f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "completed", + ) + route = f"/api/v1/tasks/{f.task}/submissions" + headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + "Idempotency-Key": str(key), + } + first = await client.post(route, headers=headers, content=payload) + assert not errors, "\n".join(errors) + assert first.status_code == 202, first.text + receipt = first.json() + assert receipt["status"] == "accepted" and receipt["replayed"] is False + warnings = [item["warning_code"] for item in receipt["pre_submission_results"] + if item["source"] == "workstream_default" and item["status"] == "warning"] + assert warnings == ["submission_summary_missing", "submission_attestation_missing"] + empty_headers = headers | {"X-Submission-Summary": "", "X-Contributor-Attestation": ""} + replay = await client.post(route, headers=empty_headers, content=payload) + assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text + changed = await client.post(route, headers=headers | {"X-Submission-Summary": "now supplied"}, + content=payload) + assert changed.status_code == 409, changed.text + assert changed.json()["error"]["code"] == "submission_idempotency_conflict" + assert len(calls) == 1 and not errors, errors + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(Submission)) == 0 - async with h.factory() as session: - stored = await session.get(Submission, result["submission_id"]) - assert stored.summary == "" - assert stored.worker_attestation == "" - assert await session.scalar(select(func.count()).select_from(Submission)) == 1 - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert admission.status == "consumed" - assert admission.packet_sha256 == SubmissionPacketView("", "").sha256 + bootstrap, store = _local_store(settings, f.namespace) + try: + submission_id = await finalize_retained_intake(f.factory, SimpleNamespace( + operation_id=UUID(receipt["operation_id"]), settings=settings, + store=store, namespace=f.namespace, + )) + finally: + bootstrap.close() + replay = await client.post(route, headers=empty_headers, content=payload) + assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text + assert len(calls) == 1 and not errors, errors + async with f.factory() as session: + stored = await session.get(Submission, submission_id) + assert stored.summary == stored.worker_attestation == "" + assert await session.scalar(select(func.count()).select_from(Submission)) == 1 + admission = (await session.scalars(select(SubmissionBundleAdmission))).one() + assert admission.status == "consumed" + assert admission.packet_sha256 == SubmissionPacketView("", "").sha256 + assert await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun)) == 1 + assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 1 -async def test_public_preparation_returns_nonblocking_feedback_on_success_and_replay( - isolated_database_env, tmp_path, monkeypatch, +async def test_public_source_submission_retains_nonblocking_feedback_on_replay( + admission_intake, tmp_path, monkeypatch, ): - """An admitted attempt keeps its coverage gap visible; replay returns it unchanged.""" - from app.adapters.checkers import _ConfiguredExternalCheckerExecution - from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService - from tests.checkers.execution.support import ControlledSelectedExecution - from tests.checkers.external.support import pre_registry_spec + """A passed PRE keeps coverage gaps visible through acceptance and T5.""" + from uuid import UUID + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.retained_material_fixtures import finalize_retained_intake + from tests.test_artifact_admission import _local_store + from tests.test_trusted_intake import _archive coverage = { "check_id": "coverage.files", "code": "coverage.unreadable", "level": "coverage_incomplete", "message": "One file was not evaluated.", "path": "results/vendor.bin", "line": None, } - project_checker = ControlledSelectedExecution(verdict="passed", findings=(coverage,)) - - async def locked_image(_adapter, request, grant): - return await project_checker.execute(request, grant) - - monkeypatch.setattr(_ConfiguredExternalCheckerExecution, "execute", locked_image) - async with _prepared_packet( - isolated_database_env, tmp_path, pre_submit_registry_spec=pre_registry_spec(), - ) as h: - route = f"/api/v1/tasks/{h.task_id}/submission-bundle-preparations" - headers = { - "Content-Type": "application/zip", - "X-Task-Assignment-Id": str(h.assignment_id), - "Idempotency-Key": str(new_record_id()), - "X-Submission-Summary": h.preparation_request.summary, - "X-Contributor-Attestation": h.preparation_request.contributor_attestation, - } - async with _client(h, monkeypatch, isolated_database_env) as client: - prepared = await client.post(route, headers=headers, content=h.archive_bytes) - assert prepared.status_code == 202, prepared.text - feedback = prepared.json()["pre_submission_results"] - external = [item for item in feedback if item["source"] == "project_external_checker"] - assert [(item["status"], item["findings"]) for item in external] == [("passed", [coverage])] - assert all( - item["status"] == "passed" for item in feedback - if item["source"] == "workstream_default" and "check_id" in item - ) - admission_id = await _verify_put_attempt( - h.factory, h.store, h.namespace, h.settings, prepared.json()["put_attempt_id"], - ) - checked = len(project_checker.requests) - - async def no_new_checker(*_args, **_kwargs): - raise AssertionError("exact replay invoked selected PRE again") + f, payload = admission_intake, _archive() + client, settings, errors, calls = await configure_source_http( + f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "completed", + project_findings=(coverage,), + ) + route = f"/api/v1/tasks/{f.task}/submissions" + headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + "Idempotency-Key": str(new_record_id()), + } + first = await client.post(route, headers=headers, content=payload) + assert not errors, "\n".join(errors) + assert first.status_code == 202, first.text + receipt = first.json() + feedback = receipt["pre_submission_results"] + external = [item for item in feedback if item["source"] == "project_external_checker"] + assert [(item["status"], item["findings"]) for item in external] == [("passed", [coverage])] + assert all(item["status"] == "passed" for item in feedback + if item["source"] == "workstream_default" and "check_id" in item) + replay = await client.post(route, headers=headers, content=payload) + assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text + assert len(calls) == 1 and not errors, errors - with monkeypatch.context() as patch: - patch.setattr(SelectedPreSubmitExecutionService, "execute", no_new_checker) - ready = await client.post(route, headers=headers, content=h.archive_bytes) - assert ready.status_code == 202, ready.text - assert ready.json()["submission_bundle_preparation_status"] == "ready" - assert ready.json()["replayed"] is True - assert ready.json()["pre_submission_results"] == feedback - - # Intake feedback never decides the outcome: the attempt awaits evaluation. - created = await client.post( - f"/api/v1/tasks/{h.task_id}/submissions", - json=_payload(h.preparation_request, admission_id), - ) - assert created.status_code == 201, created.text - async with h.factory() as session: - stored = await session.get(Submission, created.json()["submission_id"]) - assert (stored.attempt_status, stored.decided_at) == ("evaluation_pending", None) - pre_run = await session.scalar(select(SelectedPreSubmitRun.id).where( - SelectedPreSubmitRun.task_id == str(h.task_id), - )) - assert len(project_checker.requests) == checked - await assert_upgrade_refuses_stale_findings( - h.factory, store="selected_pre_submit_runs", row_id=pre_run, - ) + bootstrap, store = _local_store(settings, f.namespace) + try: + submission_id = await finalize_retained_intake(f.factory, SimpleNamespace( + operation_id=UUID(receipt["operation_id"]), settings=settings, + store=store, namespace=f.namespace, + )) + finally: + bootstrap.close() + async with f.factory() as session: + stored = await session.get(Submission, submission_id) + assert (stored.attempt_status, stored.decided_at) == ("evaluation_pending", None) + pre_run = (await session.scalars(select(SelectedPreSubmitRun.id).where( + SelectedPreSubmitRun.task_id == str(f.task), + ))).one() + assert len(calls) == 1 and not errors, errors + await assert_upgrade_refuses_stale_findings( + f.factory, store="selected_pre_submit_runs", row_id=pre_run, + ) async def test_public_submission_infrastructure_error_is_retryable_only_for_sql(): From bb87eb94f215fccde4fa99928dd86a611ddf2050 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 22:35:08 +0100 Subject: [PATCH 181/513] test(submissions): prove current initial replay and authority guards --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 20 ++ .../tasks/test_public_submission_intake.py | 229 +++++++++--------- 2 files changed, 129 insertions(+), 120 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6ea5b240a..29ac0d94c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6370,3 +6370,23 @@ remaining scoped code issue. Ruff, whitespace, record and structure checks pass. Hosted8bfd gates/images pass but Backend was pending behind superseded27531 run; requested cancellation of that old same-PR run, retaining its artifacts. No full CI/spec/provider readiness claim; remaining old public producers still need migration. + +Initial public replay migration scope: tasks/test_public_submission_intake.py only. +Replace obsolete prepare/admission JSON test with signed raw ZIP T1/PRE/T4 and +real OUTBOX T5. Preserve duplicate-header refusal, authorized foreign contributor +concealment, uncaused predecessor refusal, rejection of caller-owned JSON URI, +exact replay without a second provider upload/PRE, immutable metadata, history, +fresh suspension and exact one-source/admission/Submission/PRE/POST counts. +No production changes, compatibility route or weakened authority oracle. Medium +contract risk; isolated PostgreSQL test, Ruff/structure and focused QA review. +Human review focus: obsolete response semantics replaced by accepted receipt plus +finalized history without dropping replay ownership or packet integrity checks. + +Initial replay first run reached all HTTP/T5/suspension checks then failed on test +model attribute submission_version (stored model uses version); corrected assertion. +Final isolated replay passes1 in34.43s (/tmp/submission-initial-replay-v2), database +and MinIO cleanup complete. QA finds no scoped findings; unrelated function ASTs +unchanged, independent assertion probes detect second PRE and lost replay feedback. +Ruff, structural boundary, record and whitespace checks pass. This closes current +initial replay proof only; remediation/deadline and other remaining spec work stay +open. Hosted953 backend lanes now running; no final full-CI qualification claim. diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index 50610f4f1..5397d97c8 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -20,12 +20,11 @@ from app.api.deps.rate_controls import get_rate_control_service from app.db.session import get_db_session from app.main import create_app -from app.modules.artifacts.models import ArtifactPutAttempt, SubmissionBundleAdmission +from app.modules.artifacts.models import SubmissionBundleAdmission from app.modules.checkers.models import CheckerRun, SelectedPreSubmitRun from app.modules.checkers.api.pre_submit_material import SubmissionPacketView from app.modules.outbox.models import OutboxEvent from app.modules.tasks.models import Submission -from app.modules.tasks.models import WorkstreamTask from app.modules.api_controls.service import AUTHORIZATION_READ_SCOPE, RateControlService from app.modules.actors.models import ActorProfile from tests.tasks.test_submission_lineage import _prepared_packet @@ -37,8 +36,6 @@ auth_database_env as auth_database_env, clear_settings_cache as clear_settings_cache, ) -from tests.test_artifact_admission import _context, _seed_human_actor -from tests.submission_preparation_auth_helpers import install_submitter_grant from tests.tasks.post_submit_routing.backfill_support import assert_upgrade_refuses_stale_findings from tests.tasks.post_submit_routing.remediation_support import remediation_source from tests.tasks.post_submit_routing.support import revision_archive @@ -345,124 +342,116 @@ async def test_public_submission_infrastructure_error_is_retryable_only_for_sql( await command.submit(None, None, **arguments) -async def test_public_initial_submission_replays_and_recovers_ready_upload( - isolated_database_env, tmp_path, monkeypatch, +async def test_public_initial_submission_replays_and_recovers_accepted_upload( + admission_intake, tmp_path, monkeypatch, ): - async with _prepared_packet(isolated_database_env, tmp_path) as h: - route = f"/api/v1/tasks/{h.task_id}/submissions" - async with _client(h, monkeypatch, isolated_database_env) as client: - duplicate = await client.post( - f"/api/v1/tasks/{h.task_id}/submission-bundle-preparations", - headers=[ - ("Authorization", "Bearer public-intake-token"), - ("Content-Type", "application/zip"), - ("X-Task-Assignment-Id", str(h.assignment_id)), - ("Idempotency-Key", str(h.preparation_request.idempotency_key)), - ("Idempotency-Key", str(h.preparation_request.idempotency_key)), - ], - content=h.archive_bytes, - ) - assert duplicate.status_code == 422, duplicate.text - assert duplicate.json()["error"]["code"] == "submission_preparation_headers_invalid" - - # Losing a ready response can be recovered with the exact ZIP and key. - from app.adapters.artifacts.local import LocalStorageAdapter - from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService - - async def no_new_put(*_args, **_kwargs): - raise AssertionError("ready replay invoked a second provider PUT") - - async def no_new_checker(*_args, **_kwargs): - raise AssertionError("ready replay invoked selected PRE again") - - with monkeypatch.context() as patch: - patch.setattr(LocalStorageAdapter, "put", no_new_put) - patch.setattr(SelectedPreSubmitExecutionService, "execute", no_new_checker) - prepared = await client.post( - f"/api/v1/tasks/{h.task_id}/submission-bundle-preparations", - headers={ - "Content-Type": "application/zip", - "X-Task-Assignment-Id": str(h.assignment_id), - "Idempotency-Key": str(h.preparation_request.idempotency_key), - "X-Submission-Summary": h.preparation_request.summary, - "X-Contributor-Attestation": h.preparation_request.contributor_attestation, - }, - content=h.archive_bytes, - ) - assert prepared.status_code == 202, prepared.text - assert prepared.json()["submission_bundle_preparation_status"] == "ready" - assert prepared.json()["admission_id"] == str(h.admission_id) - assert prepared.json()["replayed"] is True - - foreign_context = _context() - async with h.factory.begin() as session: - await _seed_human_actor(session, foreign_context) - task = await session.get(WorkstreamTask, str(h.task_id)) - await install_submitter_grant(await session.connection(), { - "project": task.project_id, - "actor": str(foreign_context.actor_profile_id), - }) - with monkeypatch.context() as foreign_patch: - async with _client( - h, foreign_patch, isolated_database_env, - subject=f"human-{foreign_context.actor_profile_id}" - ) as foreign: - denied_actor = await foreign.post(route, json=_payload(h.creation, h.admission_id)) - assert denied_actor.status_code == 404, denied_actor.text - assert denied_actor.json()["error"]["code"] == "submission_unavailable" - - uncaused = _payload(h.creation, h.admission_id) - uncaused["predecessor_submission_id"] = str(new_record_id()) - denied_predecessor = await client.post(route, json=uncaused) - assert denied_predecessor.status_code == 409, denied_predecessor.text - assert denied_predecessor.json()["error"]["code"] == "task_submission_predecessor_changed" - - client_owned = _payload(h.creation, h.admission_id) - client_owned["package_uri"] = "s3://caller-controlled/bundle.zip" - denied_uri = await client.post(route, json=client_owned) - assert denied_uri.status_code == 422, denied_uri.text - - created = await client.post(route, json=_payload(h.creation, h.admission_id)) - assert created.status_code == 201, created.text - result = created.json() - assert result["admission_id"] == str(h.admission_id) - assert result["submission_version"] == 1 - assert result["submission_id"] - - replay = await client.post(route, json=_payload(h.creation, h.admission_id)) - assert replay.status_code == 201, replay.text - assert replay.json() == result - - changed = _payload(h.creation, h.admission_id) - changed["summary"] += " changed" - denied = await client.post(route, json=changed) - assert denied.status_code == 404, denied.text - assert denied.json()["error"]["code"] == "submission_unavailable" - - history = await client.get(f"/api/v1/tasks/{h.task_id}/submissions") - assert history.status_code == 200, history.text - assert [item["id"] for item in history.json()["items"]] == [result["submission_id"]] - - async with h.factory.begin() as session: - profile = await session.get(ActorProfile, str(h.context.actor_profile_id)) - profile.status = "suspended" - profile.suspended_by = "intake-test" - profile.suspended_at = datetime.now(UTC) - profile.suspension_reason = "test suspension" - revoked = await client.post(route, json=_payload(h.creation, h.admission_id)) - assert revoked.status_code == 404, revoked.text - assert revoked.json()["error"]["code"] == "submission_unavailable" + """Lost acceptance recovers without upload/PRE and retains current authority.""" + from uuid import UUID + from sqlalchemy import text + from app.adapters.artifacts.local import LocalStorageAdapter + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.authorization.task_authority.test_postgresql import grant + from tests.retained_material_fixtures import finalize_retained_intake + from tests.test_artifact_admission import _local_store + from tests.test_trusted_intake import _archive - async with h.factory() as session: - assert await session.scalar(select(func.count()).select_from(Submission)) == 1 - assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) >= 1 - assert await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun)) == 1 - assert await session.scalar(select(func.count()).select_from(ArtifactPutAttempt).where( - ArtifactPutAttempt.producer_request_type == "submission_bundle" - )) == 1 - admission = await session.get(SubmissionBundleAdmission, str(h.admission_id)) - assert admission.status == "consumed" + f, payload = admission_intake, _archive() + client, settings, errors, calls = await configure_source_http( + f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "completed", + ) + route = f"/api/v1/tasks/{f.task}/submissions" + headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + "Idempotency-Key": str(new_record_id()), "X-Submission-Summary": "Completed work", + "X-Contributor-Attestation": "I completed this work", + } + duplicate = await client.post(route, headers=list(headers.items()) + [ + ("Idempotency-Key", headers["Idempotency-Key"]), + ], content=payload) + assert duplicate.status_code == 422, duplicate.text + assert duplicate.json()["error"]["code"] == "submission_packet_invalid" + + foreign = await f.access.signed.actor("foreign-submission-contributor") + await grant(SimpleNamespace(signed=f.access.signed, target=foreign), f.manager, f.project) + denied_actor = await client.post(route, headers=headers | foreign.headers, content=payload) + assert denied_actor.status_code == 404, denied_actor.text + assert denied_actor.json()["error"]["code"] == "submission_unavailable" + denied_predecessor = await client.post(route, headers=headers | { + "X-Predecessor-Submission-Id": str(new_record_id()), + }, content=payload) + assert denied_predecessor.status_code == 409, denied_predecessor.text + assert denied_predecessor.json()["error"]["code"] == "task_submission_predecessor_changed" + denied_uri = await client.post(route, headers=headers | {"Content-Type": "application/json"}, + json={"package_uri": "s3://caller-controlled/bundle.zip"}) + assert denied_uri.status_code == 415, denied_uri.text + assert denied_uri.json()["error"]["code"] == "submission_media_type_unsupported" + assert calls == [] + async with f.factory() as session: + assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 0 + assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 0 + + first = await client.post(route, headers=headers, content=payload) + assert not errors, "\n".join(errors) + assert first.status_code == 202, first.text + receipt = first.json() + assert receipt["status"] == "accepted" and receipt["replayed"] is False + + async def no_new_upload(*args, **kwargs): + raise AssertionError("accepted replay invoked another provider upload") + + with monkeypatch.context() as replay_patch: + replay_patch.setattr(LocalStorageAdapter, "begin_source_upload", no_new_upload) + replay_patch.setattr(LocalStorageAdapter, "upload_source_part", no_new_upload) + replay_patch.setattr(LocalStorageAdapter, "complete_source_upload", no_new_upload) + replay = await client.post(route, headers=headers, content=payload) + assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text + changed = await client.post(route, headers=headers | {"X-Submission-Summary": "changed"}, + content=payload) + assert changed.status_code == 409, changed.text + assert changed.json()["error"]["code"] == "submission_idempotency_conflict" + foreign_replay = await client.post(route, headers=headers | foreign.headers, content=payload) + assert foreign_replay.status_code == 404, foreign_replay.text + assert foreign_replay.json()["error"]["code"] == "submission_unavailable" + assert len(calls) == 1 and not errors, errors + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(Submission)) == 0 + + bootstrap, store = _local_store(settings, f.namespace) + try: + submission_id = await finalize_retained_intake(f.factory, SimpleNamespace( + operation_id=UUID(receipt["operation_id"]), settings=settings, + store=store, namespace=f.namespace, + )) + finally: + bootstrap.close() + replay = await client.post(route, headers=headers, content=payload) + assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text + history = await client.get(route, headers=f.access.target.headers) + assert history.status_code == 200, history.text + assert [item["id"] for item in history.json()["items"]] == [str(submission_id)] + async with f.factory.begin() as session: + profile = await session.get(ActorProfile, str(f.actor.actor_profile_id)) + profile.status = "suspended" + profile.suspended_by = "intake-test" + profile.suspended_at = datetime.now(UTC) + profile.suspension_reason = "test suspension" + revoked = await client.post(route, headers=headers, content=payload) + assert revoked.status_code == 404, revoked.text + assert revoked.json()["error"]["code"] == "submission_unavailable" + assert len(calls) == 1 and not errors, errors + async with f.factory() as session: + assert await session.scalar(select(func.count()).select_from(Submission)) == 1 + stored = await session.get(Submission, submission_id) + assert stored.version == 1 + assert stored.summary == headers["X-Submission-Summary"] + assert stored.worker_attestation == headers["X-Contributor-Attestation"] + assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 + assert await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun)) == 1 + assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 1 + assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 1 + admission = (await session.scalars(select(SubmissionBundleAdmission))).one() + assert admission.status == "consumed" + assert stored.submission_bundle_admission_id == admission.id async def test_public_checker_remediation_uses_exact_predecessor( From 35eeff32a159f4eb1b31a5043b12f8358c4cb1c4 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 22:40:10 +0100 Subject: [PATCH 182/513] test(submissions): retain deadline receipts through public replay --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 21 ++++ .../artifacts/test_submission_pre_source.py | 6 +- .../tasks/test_public_submission_intake.py | 105 ++++++++---------- 3 files changed, 73 insertions(+), 59 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 29ac0d94c..2658220b7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6390,3 +6390,24 @@ unchanged, independent assertion probes detect second PRE and lost replay feedba Ruff, structural boundary, record and whitespace checks pass. This closes current initial replay proof only; remediation/deadline and other remaining spec work stay open. Hosted953 backend lanes now running; no final full-CI qualification claim. + +Public deadline migration scope: tasks/test_public_submission_intake.py and shared +artifacts/test_submission_pre_source.py runtime fixture. Replace retired processor +TimeoutError/prepare route with current signed ZIP and a simulated provider deadline +receipt after exact source read/drain. This proves current receipt persistence, +public infrastructure classification, stable replay, retained source cleanup charge, +unchanged task/assignment and no admission/Submission/POST. It does not qualify +real elapsed runtime enforcement; that remains separate A25 provider evidence. +Keep existing capacity-failure fixture behavior unchanged. Medium lifecycle/contract +risk: isolated target and existing receipt-source consumer, Ruff/structure, focused +QA review. No production timers, compatibility interfaces or fabricated defaults. + +Deadline v1 selected an invalid parameterized node and ran no tests. Collected +actual IDs and corrected selection; v2 public deadline + existing received-capacity +source consumer pass2 in45.17s, database/MinIO cleanup complete. QA reports no +scoped code findings; actual shared-branch probe proves exact source drain/close +and typed pending receipt, and named public assertion detects capacity-for-deadline +substitution (/tmp/submission-deadline-qa-probe.log). Ruff, structural boundaries, +record and whitespace checks pass. Removed now-unused _prepared_packet import; +remaining remediation consumer still uses old preparation and requires migration. +Real timer/provider qualification remains open; no full-spec readiness claim. diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py index 18049d02e..a181281cd 100644 --- a/backend/tests/artifacts/test_submission_pre_source.py +++ b/backend/tests/artifacts/test_submission_pre_source.py @@ -462,8 +462,10 @@ async def execute_pre(self, lease, grant): async def run(self, lease, grant): async with aclosing(grant.open_source(lease=lease)) as reader: assert b"".join([chunk async for chunk in reader]) == payload - if runtime_outcome == "received_failure": - body = receipt_body(lease, outcome="infrastructure_failure", reason="capacity_exceeded") + if runtime_outcome in {"received_failure", "deadline_exceeded"}: + deadline = runtime_outcome == "deadline_exceeded" + body = receipt_body(lease, outcome="deadline_exceeded" if deadline else "infrastructure_failure", + reason="deadline_exceeded" if deadline else "capacity_exceeded") body["cleanup"]["disposition"] = "pending" return SelectedPreSubmitInvocationResult.from_canonical_body(body | {"execution": None}, source_contracts=selected_pre_submit_source_contracts()) if runtime_outcome in {"completed", "rejected"}: diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index 5397d97c8..59eccdd38 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -27,7 +27,6 @@ from app.modules.tasks.models import Submission from app.modules.api_controls.service import AUTHORIZATION_READ_SCOPE, RateControlService from app.modules.actors.models import ActorProfile -from tests.tasks.test_submission_lineage import _prepared_packet from tests.artifacts.test_submission_intake_admission import ( admission_intake as admission_intake, admin_access as admin_access, @@ -490,61 +489,53 @@ async def test_public_checker_remediation_uses_exact_predecessor( async def test_confirmed_intake_deadline_persists_terminal_failure_and_replays( - isolated_database_env, tmp_path, monkeypatch, + admission_intake, tmp_path, monkeypatch, ): - """A drained PRE timeout commits failure once without admission or Submission.""" + """A simulated provider deadline retains exact failure/cleanup custody on replay.""" + from sqlalchemy import text from app.modules.artifacts.models import SubmissionBundleDurableIntent - from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor - - async with _prepared_packet(isolated_database_env, tmp_path, verify=False) as h: - calls = 0 - - async def deadline_after_intake(self, material, default): - nonlocal calls - calls += 1 - assert default.eligible - assert material.entries - # ART has exported, evaluated default and awaited intake.close() - # before invoking this project processor. Exercise its TimeoutError - # conversion without changing the production deadline or finalizer. - raise TimeoutError("project operation deadline") - - monkeypatch.setattr(SelectedPreSubmitProcessor, "process", deadline_after_intake) - key = new_record_id() - headers = { - "Content-Type": "application/zip", - "X-Task-Assignment-Id": str(h.assignment_id), - "Idempotency-Key": str(key), - "X-Submission-Summary": h.preparation_request.summary, - "X-Contributor-Attestation": h.preparation_request.contributor_attestation, - } - route = f"/api/v1/tasks/{h.task_id}/submission-bundle-preparations" - async with _client(h, monkeypatch, isolated_database_env) as client: - first = await client.post(route, headers=headers, content=h.archive_bytes) - assert first.status_code == 503, first.text - assert first.json()["detail"] == "deadline_exceeded" - async with h.factory() as session: - run = (await session.scalars(select(SelectedPreSubmitRun).where( - SelectedPreSubmitRun.idempotency_key == str(key) - ))).one() - assert run.status == "infrastructure_failed" - assert run.terminal_json["outcome"] == "infrastructure_failed" - assert run.terminal_json["infrastructure_failure_code"] == "deadline_exceeded" - assert run.terminal_json["execution"] is None and run.eligible is None - assert run.execute_evidence_id and run.finalize_evidence_id - retained = (run.id, run.terminal_digest, run.finalize_evidence_id) - for model in (SubmissionBundleDurableIntent, SubmissionBundleAdmission): - assert await session.scalar(select(func.count()).select_from(model).where( - model.selected_pre_submit_run_id == run.id - )) == 0 - assert await session.scalar(select(func.count()).select_from(Submission).where( - Submission.task_id == str(h.task_id) - )) == 0 - replay = await client.post(route, headers=headers, content=h.archive_bytes) - assert replay.status_code == 503 and replay.json()["detail"] == "deadline_exceeded" - assert calls == 1 - async with h.factory() as session: - run = (await session.scalars(select(SelectedPreSubmitRun).where( - SelectedPreSubmitRun.idempotency_key == str(key) - ))).one() - assert (run.id, run.terminal_digest, run.finalize_evidence_id) == retained + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.test_trusted_intake import _archive + + f, payload = admission_intake, _archive() + client, _, errors, calls = await configure_source_http( + f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "deadline_exceeded", + ) + route = f"/api/v1/tasks/{f.task}/submissions" + headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + "Idempotency-Key": str(new_record_id()), + "X-Submission-Summary": "Completed work", "X-Contributor-Attestation": "I completed this work", + } + first = await client.post(route, headers=headers, content=payload) + assert first.status_code == 503, first.text + assert first.json()["error"]["code"] == "submission_infrastructure_unavailable" + async with f.factory() as session: + run = (await session.scalars(select(SelectedPreSubmitRun))).one() + assert run.status == "infrastructure_failed" + assert run.terminal_json["outcome"] == "infrastructure_failed" + assert run.terminal_json["infrastructure_failure_code"] == "deadline_exceeded" + assert run.terminal_json["execution"] is None and run.eligible is None + invocation = run.terminal_json["invocation_receipt"] + assert invocation["outcome"] == invocation["reason"] == "deadline_exceeded" + assert invocation["cleanup"]["disposition"] == "pending" + assert run.execute_evidence_id and run.finalize_evidence_id + retained = (run.id, run.terminal_digest, run.finalize_evidence_id, run.terminal_json) + for model in (SubmissionBundleDurableIntent, SubmissionBundleAdmission, Submission, CheckerRun, OutboxEvent): + assert await session.scalar(select(func.count()).select_from(model)) == 0 + row = (await session.execute(text( + "SELECT state, failure_code FROM submission_intake_operations WHERE task_id=:id" + ), {"id": f.task})).one() + assert tuple(row) == ("failed", "submission_infrastructure_unavailable") + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges")) == len(payload) + assert await session.scalar(text("SELECT status FROM workstream_tasks WHERE id=:id"), {"id": f.task}) == "in_progress" + assert await session.scalar(text("SELECT status FROM task_assignments WHERE id=:id"), {"id": f.assignment}) == "active" + replay = await client.post(route, headers=headers, content=payload) + assert replay.status_code == 503, replay.text + assert replay.json()["error"]["code"] == "submission_infrastructure_unavailable" + assert len(calls) == 1 and not errors, errors + async with f.factory() as session: + run = (await session.scalars(select(SelectedPreSubmitRun))).one() + assert (run.id, run.terminal_digest, run.finalize_evidence_id, run.terminal_json) == retained + assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 1 + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges")) == len(payload) From 69dac1c39479e1d28d3c1ebeea62a1e2e086f6a5 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 22:53:17 +0100 Subject: [PATCH 183/513] test(submissions): prove public revision source lineage and replay --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 26 ++++++ .../tasks/test_public_submission_intake.py | 93 ++++++++++++++----- 2 files changed, 94 insertions(+), 25 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2658220b7..cdfb36b8e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6411,3 +6411,29 @@ substitution (/tmp/submission-deadline-qa-probe.log). Ruff, structural boundarie record and whitespace checks pass. Removed now-unused _prepared_packet import; remaining remediation consumer still uses old preparation and requires migration. Real timer/provider qualification remains open; no full-spec readiness claim. + +Public remediation migration scope: tasks/test_public_submission_intake.py only. +Use existing real source-backed predecessor and routed failed POST; submit revised +raw ZIP over HTTP with exact predecessor and revision preparation acknowledgement, +reject wrong predecessor before PRE, accept/replay immutable receipt, then real +OUTBOX T5 produces version2 bound to consumed admission and predecessor. Assert +exact two Submission/PRE/POST runs across initial+revision, one successor and history. +No production changes or fabricated predecessor/default manifest. Retain shared +_client/_payload because revision-expiry and CLI consumers still import them. +Medium lifecycle risk: isolated target, whole public module, lint/structure and QA +review; human review focus is preserved lineage plus current asynchronous receipt. + +Remediation QA001 repaired: CountedStore lacks observe_sealed_source, so T5 uses +its initialized underlying provider. QA002 repaired: consumed admission now binds +independently to receipt.operation_id and observed PRE run, not merely successor's +own admission selector. Independent mutation probes reject either substitution. +Full module first run7pass1fail284.17s; remediation failed T1 because predecessor +fixture locks16MiB namespace capacity while HTTP helper supplies4MiB. Preserve +production mismatch guard; explicitly use predecessor's16MiB test profile for +this revision only. QA verifies rest of profile unchanged and no shared change. +Diagnostic v3 loaded repaired code and passes1 in181.35s; explicit final v4 passes1 +in152.66s. Both database/MinIO cleanup complete. Together with unchanged seven +cases from full run, every public module case has passing evidence. Ruff, structure, +record and whitespace pass. Shared _payload remains for revision_expiry consumer; +no removed preparation call remains in this module's tests. This is local proof, +not full CI/native/provider or full-spec completion. diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index 59eccdd38..6922ffec3 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -1,4 +1,4 @@ -"""Public admission-backed intake against real TASK/ART owners and PostgreSQL.""" +"""Public source intake against real TASK/ART owners and PostgreSQL.""" from __future__ import annotations @@ -38,9 +38,8 @@ from tests.tasks.post_submit_routing.backfill_support import assert_upgrade_refuses_stale_findings from tests.tasks.post_submit_routing.remediation_support import remediation_source from tests.tasks.post_submit_routing.support import revision_archive -from tests.tasks.submission_lineage_support import _verified_admission from tests.test_submission_predecessor_custody import ( - _fixture_revision_context, _replacement_request, + _fixture_revision_context, ) @@ -456,36 +455,80 @@ async def no_new_upload(*args, **kwargs): async def test_public_checker_remediation_uses_exact_predecessor( isolated_database_env, tmp_path, monkeypatch, ): + """A revision ZIP retains its exact failed predecessor through T4/T5 replay.""" + from uuid import UUID + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.retained_material_fixtures import finalize_retained_intake + async with remediation_source(tmp_path, isolated_database_env) as h: await _fixture_revision_context(h) - request = _replacement_request( - h, revision_archive(h.data), - predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ) - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, h.actor_context, request, - ) - route = f"/api/v1/tasks/{request.task_id}/submissions" + payload = revision_archive(h.data) + route = f"/api/v1/tasks/{h.request.task_id}/submissions" + headers = { + "Content-Type": "application/zip", + "X-Task-Assignment-Id": str(h.request.assignment_id), + "Idempotency-Key": str(new_record_id()), + "X-Predecessor-Submission-Id": str(h.created.submission_id), + "X-Revision-Preparation-Id": str(h.revision_preparation_id), + "X-Revision-Preparation-Sha256": h.revision_preparation_sha256, + "X-Submission-Summary": h.creation_request.summary, + "X-Contributor-Attestation": h.creation_request.contributor_attestation, + } async with _client(h, monkeypatch, isolated_database_env) as client: - wrong = _payload(request, admission_id) - wrong["predecessor_submission_id"] = str(new_record_id()) - denied = await client.post(route, json=wrong) + client, settings, errors, calls = await configure_source_http( + h.factory, client, tmp_path, monkeypatch, payload, "completed", + ) + # The predecessor's source fixture already locked this namespace + # to a 16 MiB test capacity; the revision must use the same profile. + settings = settings.model_copy(update={"submission_execution_profile": { + **settings.submission_execution_profile, + "capacity": {"maximum_total_bytes": 16 * 1024**2}, + }}) + monkeypatch.setattr(client._transport.app.state, "settings", settings) + denied = await client.post(route, headers=headers | { + "X-Predecessor-Submission-Id": str(new_record_id()), + }, content=payload) assert denied.status_code == 409, denied.text assert denied.json()["error"]["code"] == "task_submission_predecessor_changed" - - created = await client.post(route, json=_payload(request, admission_id)) - assert created.status_code == 201, created.text - result = created.json() - assert result["submission_version"] == 2 - - replay = await client.post(route, json=_payload(request, admission_id)) - assert replay.status_code == 201 and replay.json() == result + assert calls == [] + + created = await client.post(route, headers=headers, content=payload) + assert not errors, "\n".join(errors) + async with h.factory() as session: + runs = (await session.scalars(select(SelectedPreSubmitRun))).all() + diagnostics = [(run.status, run.terminal_json) for run in runs] + assert created.status_code == 202, (created.text, calls, diagnostics) + receipt = created.json() + assert receipt["status"] == "accepted" and receipt["replayed"] is False + replay = await client.post(route, headers=headers, content=payload) + assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text + assert len(calls) == 1 and not errors, errors + async with h.factory() as session: + assert await session.scalar(select(func.count()).select_from(Submission)) == 1 + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(receipt["operation_id"]), settings=settings, + store=h.store.wrapped, namespace=h.namespace, + )) + replay = await client.post(route, headers=headers, content=payload) + assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text + assert len(calls) == 1 and not errors, errors + history = await client.get(route) + assert history.status_code == 200, history.text + assert {item["id"] for item in history.json()["items"]} == { + str(h.created.submission_id), str(submission_id), + } async with h.factory() as session: - successor = await session.get(Submission, result["submission_id"]) + successor = await session.get(Submission, submission_id) + assert successor.version == 2 assert successor.supersedes_submission_id == str(h.created.submission_id) - assert successor.submission_bundle_admission_id == str(admission_id) + admission = await session.get(SubmissionBundleAdmission, successor.submission_bundle_admission_id) + assert admission.status == "consumed" + assert admission.source_operation_id == receipt["operation_id"] + assert admission.selected_pre_submit_run_id == str(calls[0]) + assert await session.scalar(select(func.count()).select_from(Submission)) == 2 + assert await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun)) == 2 + assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 2 async def test_confirmed_intake_deadline_persists_terminal_failure_and_replays( From 0f250567c42e1ae31834b31d07a9b7d4ead8a003 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 22:58:18 +0100 Subject: [PATCH 184/513] refactor(checkers): remove unused prepared admission capability --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 29 +++ .../selected_pre_submit_coordination.py | 84 ------- .../test_selected_pre_submit_coordination.py | 233 ++++++++---------- 3 files changed, 130 insertions(+), 216 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index cdfb36b8e..0745e5cd3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6437,3 +6437,32 @@ cases from full run, every public module case has passing evidence. Ruff, struct record and whitespace pass. Shared _payload remains for revision_expiry consumer; no removed preparation call remains in this module's tests. This is local proof, not full CI/native/provider or full-spec completion. + +PRE coordination cleanup scope: modules/checkers/selected_pre_submit_coordination.py +and tests/checkers/external/test_selected_pre_submit_coordination.py. Repo-wide +consumer trace finds no caller/issuer of SelectedPreSubmitAdmissionCapability +outside its obsolete unit test; current finalize always returns capability=None. +Remove dead class/member/export, retaining execution capability and all historical +readers/data. Replace obsolete capability test with exact current acceptance lock +refusal/positive controls; migrate TASK guard and packet/lineage tests to source +reservation without caller-derived manifests. Remove unused old reservation helper. +Medium authority risk: full coordination/receipt tests, Ruff/structure and QA+ARCH +review. No compatibility alias, relaxed authority, schema or retained-data changes. +Human focus: dead issuance removal must not weaken exact T4 evidence consumption. + +Coordination initial full run136pass15.09s. QA-COORD001 identified coupled predecessor +ID/version negative could survive removal of either guard. Added typed current +revision positive control and separate ID-only/version-only substitutions alongside +initial case. Final full coordination+receipt run137pass9.98s; no retiredconstructor +failures remain in this module. Ruff, structure and whitespace pass. ARCH confirms +no live issuer or historical reader depends on deleted class; current T4 checks +persisted evidence independently. New mocked acceptance matrix proves immediate +conditions only; real database/source acceptance proofs remain separate. Old ART +admission-authority protocol/consumer cleanup remains traced residual work, not +removed blindly in this scope. QA mutation closure pending at this checkpoint. + +QA-COORD001 closed: exact revision test detects independent removal of predecessor +ID and version guards, and acceptance test detects receipt-guard removal. In-memory +probes leave source unchanged (/tmp/submission-coordination-qa-repair.log). No +remaining scoped QA/ARCH findings;137pass final suite evidence inspected. Same +single draft PR708, with remaining full-spec/provider/CI work still open. diff --git a/backend/app/modules/checkers/selected_pre_submit_coordination.py b/backend/app/modules/checkers/selected_pre_submit_coordination.py index 35eb476fa..269afe176 100644 --- a/backend/app/modules/checkers/selected_pre_submit_coordination.py +++ b/backend/app/modules/checkers/selected_pre_submit_coordination.py @@ -47,88 +47,6 @@ async def lock_selected_pre_submit_scope( _CAPABILITY_SEAL = object() -class SelectedPreSubmitAdmissionCapability: - """One-use completed-pass authority minted inside the finalization root.""" - - __slots__ = ( - "_consumed", - "_owner", - "_seal", - "_lock", - "run_id", - "terminal_digest", - "attempt_id", - "prepared_generation_id", - "archive_sha256", - "semantic_manifest_sha256", - ) - - def __init__(self, *_: object, **__: object) -> None: - raise TypeError("selected PRE admission capabilities are coordinator-issued") - - @classmethod - def _issued( - cls, - *, - owner: SelectedPreSubmitCoordinator, - run_id: UUID, - terminal: SelectedPreSubmitTerminalFacts, - ) -> SelectedPreSubmitAdmissionCapability: - reservation = terminal.lease.reservation - value = object.__new__(cls) - value._owner = owner - value._seal = _CAPABILITY_SEAL - value._lock = threading.Lock() - value._consumed = False - value.run_id = run_id - value.terminal_digest = terminal.terminal_digest - value.attempt_id = reservation.attempt_id - value.prepared_generation_id = reservation.prepared_generation_id - value.archive_sha256 = reservation.archive_sha256 - value.semantic_manifest_sha256 = reservation.semantic_manifest_sha256 - return value - - def consume( - self, - *, - run_id: UUID, - terminal_digest: str, - attempt_id: UUID, - prepared_generation_id: UUID, - archive_sha256: str, - semantic_manifest_sha256: str, - ) -> UUID: - """Consume only for the exact finalized run and still-live prepared bytes.""" - with self._lock: - if ( - self._seal is not _CAPABILITY_SEAL - or self._consumed - or self._owner._capability is not self - or ( - run_id, - terminal_digest, - attempt_id, - prepared_generation_id, - archive_sha256, - semantic_manifest_sha256, - ) - != ( - self.run_id, - self.terminal_digest, - self.attempt_id, - self.prepared_generation_id, - self.archive_sha256, - self.semantic_manifest_sha256, - ) - ): - raise SelectedPreSubmitUnavailable( - "selected_pre_submit_admission_unavailable" - ) - self._consumed = True - self._owner._capability = None - return self.run_id - - class SelectedPreSubmitExecutionCapability: """One-use authority for the committed lease's process-local ART callback.""" @@ -204,7 +122,6 @@ def __init__( self._tasks = tasks self._source_contracts = source_contracts self._sources = sources - self._capability: SelectedPreSubmitAdmissionCapability | None = None self._execution_capability: SelectedPreSubmitExecutionCapability | None = None async def read_current( @@ -573,7 +490,6 @@ async def _lock( __all__ = ( - "SelectedPreSubmitAdmissionCapability", "SelectedPreSubmitCompletion", "SelectedPreSubmitCoordinator", "SelectedPreSubmitExecutionCapability", diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index dda3f8a29..a8fccc14c 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -27,7 +27,6 @@ SubmissionBundleAdmission, SubmissionBundleDurableIntent, ) -from app.modules.checkers.api.default_checker import WORKSTREAM_DEFAULT_BEHAVIOR_SHA256 from app.modules.checkers.api.selected_pre_submit import ( SelectedPreSubmitExecuteFacts, SelectedPreSubmitAdmissionLineage, @@ -41,7 +40,6 @@ from app.modules.tasks.submission_context import TaskSubmissionContextService from app.modules.checkers.models import SelectedPreSubmitRun from app.modules.checkers.selected_pre_submit_coordination import ( - SelectedPreSubmitAdmissionCapability, SelectedPreSubmitExecutionCapability, SelectedPreSubmitCoordinator, ) @@ -56,27 +54,6 @@ _POST_POLICY = _POST_POLICY_WITHOUT_DIGEST | {"policy_sha256": _POST_POLICY_SHA256} -def _reservation() -> SelectedPreSubmitReservationFacts: - return SelectedPreSubmitReservationFacts( - actor_profile_id=new_record_id(), - identity_link_id=new_record_id(), - project_id=new_record_id(), - task_id=new_record_id(), - assignment_id=new_record_id(), - attempt_id=new_record_id(), - idempotency_key=new_record_id(), - attempt_request_digest=SHA, - prepared_generation_id=new_record_id(), - policy_sha256="sha256:" + "1" * 64, - default_behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - default_input_sha256="sha256:" + "2" * 64, - archive_sha256="sha256:" + "3" * 64, - archive_byte_count=1024, - semantic_manifest_sha256="sha256:" + "4" * 64, - execution_budget_ms=120_000, - source_contracts=selected_pre_submit_source_contracts()) - - def _queued_row(reservation: SelectedPreSubmitReservationFacts) -> SimpleNamespace: return SimpleNamespace( id=str(reservation.attempt_id), @@ -187,37 +164,21 @@ async def test_selected_pre_expired_lease_read_keeps_task_first_custody() -> Non @pytest.mark.asyncio -async def test_selected_pre_task_guard_rechecks_exact_locked_lineage(monkeypatch) -> None: - lineage = SelectedPreSubmitAdmissionLineage( - predecessor_submission_id=new_record_id(), - predecessor_submission_version=2, - checker_remediation_manifest_id=new_record_id(), - guide_id=new_record_id(), - guide_version="guide-v2", - source_snapshot_id=new_record_id(), - source_snapshot_sha256="sha256:" + "5" * 64, - locked_guide_sha256="sha256:" + "6" * 64, - effective_policy_id=new_record_id(), - effective_policy_sha256="sha256:" + "7" * 64, - pre_submit_policy_id=new_record_id(), - pre_submit_policy_sha256="sha256:" + "8" * 64, - effective_plan_sha256="sha256:" + "9" * 64, - rules_sha256="sha256:" + "d" * 64, - external_checker_policies_sha256=SHA, - post_submit_policy_sha256=_POST_POLICY_SHA256, - post_submit_policy_body=_POST_POLICY, - locked_policy_context_hash="sha256:" + "a" * 64, - semantic_manifest_id=new_record_id(), - semantic_manifest_body={"schema_version": "test"}, - packet_sha256="sha256:" + "b" * 64, - storage_scheme="s3", - ) - reservation = replace( - _reservation(), - policy_sha256=lineage.effective_plan_sha256, - semantic_manifest_sha256=canonical_json_hash(lineage.semantic_manifest_body), - admission_lineage=lineage, - ) +@pytest.mark.parametrize("revision", [False, True]) +async def test_selected_pre_task_guard_rechecks_exact_locked_lineage(monkeypatch, revision) -> None: + reservation = _source_reservation() + if revision: + from app.modules.checkers.api.default_checker import WorkstreamDefaultPredecessor + predecessor = WorkstreamDefaultPredecessor(new_record_id(), 2, SHA, SHA) + reservation = replace(reservation, + default_context=replace(reservation.default_context, + predecessor=predecessor, current_predecessor=predecessor, + predecessor_exists=True, predecessor_rules_sha256=reservation.default_context.current_rules_sha256), + admission_lineage=replace(reservation.admission_lineage, + predecessor_submission_id=predecessor.submission_id, predecessor_submission_version=2, + checker_remediation_manifest_id=new_record_id()), + source_contracts=selected_pre_submit_source_contracts()) + lineage = reservation.admission_lineage locked = SimpleNamespace( project_id=reservation.project_id, guide_version=lineage.guide_version, @@ -233,10 +194,8 @@ async def test_selected_pre_task_guard_rechecks_exact_locked_lineage(monkeypatch assignment_id=reservation.assignment_id, contributor_id=reservation.actor_profile_id, checker_remediation_manifest_id=(lineage.checker_remediation_manifest_id), - predecessor=SimpleNamespace( - submission_id=lineage.predecessor_submission_id, - version=lineage.predecessor_submission_version, - ), + predecessor=(SimpleNamespace(submission_id=lineage.predecessor_submission_id, + version=lineage.predecessor_submission_version) if revision else None), locked_project_context=locked, ) @@ -248,6 +207,18 @@ async def lock(_repository, request): guard = selected_pre_submit_task_guard(SimpleNamespace()) await guard.lock_selected_pre_submit_scope(reservation) + exact_predecessor = context.predecessor + context.predecessor = SimpleNamespace(submission_id=new_record_id(), + version=lineage.predecessor_submission_version if revision else 1) + with pytest.raises(RuntimeError, match="selected PRE TASK custody changed"): + await guard.lock_selected_pre_submit_scope(reservation) + context.predecessor = exact_predecessor + if revision: + context.predecessor.version += 1 + with pytest.raises(RuntimeError, match="selected PRE TASK custody changed"): + await guard.lock_selected_pre_submit_scope(reservation) + context.predecessor.version = lineage.predecessor_submission_version + context.checker_remediation_manifest_id = new_record_id() with pytest.raises(RuntimeError, match="selected PRE TASK custody changed"): await guard.lock_selected_pre_submit_scope(reservation) @@ -288,35 +259,58 @@ def test_selected_pre_model_compiles_complete_owner_and_authority_custody() -> N assert value in admission_sql -def test_selected_pre_admission_capability_is_exact_and_single_use() -> None: - reservation = _reservation() - owner = SimpleNamespace(_capability=None) - run_id = new_record_id() - terminal = SimpleNamespace( - lease=SimpleNamespace(reservation=reservation), - terminal_digest="sha256:" + "5" * 64, - ) - capability = SelectedPreSubmitAdmissionCapability._issued( - owner=owner, - run_id=run_id, - terminal=terminal, - ) - owner._capability = capability - values = { - "run_id": run_id, - "terminal_digest": terminal.terminal_digest, - "attempt_id": reservation.attempt_id, - "prepared_generation_id": reservation.prepared_generation_id, - "archive_sha256": reservation.archive_sha256, - "semantic_manifest_sha256": reservation.semantic_manifest_sha256, - } - with pytest.raises( - SelectedPreSubmitUnavailable, match="selected_pre_submit_admission_unavailable" - ): - capability.consume(**(values | {"semantic_manifest_sha256": "sha256:" + "6" * 64})) - assert capability.consume(**values) == run_id - with pytest.raises(SelectedPreSubmitUnavailable): - capability.consume(**values) +@pytest.mark.parametrize("changed", [ + None, "run", "stored_run", "reservation", "status", "terminal", "digest", + "execution", "eligible", "receipt", "execute_evidence", "finalize_evidence", +]) +async def test_selected_pre_acceptance_requires_exact_current_evidence(changed, monkeypatch): + """T4 locks exact authorized eligible evidence; it issues no prepared capability.""" + request = _source_reservation() + terminal = SimpleNamespace(terminal_digest=SHA, execution=SimpleNamespace(eligible=True), + invocation_receipt=object()) + current = SimpleNamespace(run_id=request.attempt_id, reservation=request, + status="completed", terminal=terminal) + row = SimpleNamespace(execute_evidence_id=new_record_id(), finalize_evidence_id=new_record_id()) + session = SimpleNamespace(get=AsyncMock(return_value=row)) + coordinator = SelectedPreSubmitCoordinator(session, tasks=SimpleNamespace(), + sources=SimpleNamespace(), source_contracts=selected_pre_submit_source_contracts()) + read = AsyncMock(return_value=current) + monkeypatch.setattr(coordinator, "read_current", read) + run_id, digest = request.attempt_id, SHA + if changed == "run": + run_id = new_record_id() + elif changed == "stored_run": + current.run_id = new_record_id() + elif changed == "reservation": + current.reservation = replace(request, actor_profile_id=new_record_id(), + source_contracts=selected_pre_submit_source_contracts()) + elif changed == "status": + current.status = "infrastructure_failed" + elif changed == "terminal": + current.terminal = None + elif changed == "digest": + digest = "sha256:" + "e" * 64 + elif changed == "execution": + terminal.execution = None + elif changed == "eligible": + terminal.execution.eligible = False + elif changed == "receipt": + terminal.invocation_receipt = None + elif changed == "execute_evidence": + row.execute_evidence_id = None + elif changed == "finalize_evidence": + row.finalize_evidence_id = None + if changed: + error = SelectedPreSubmitRequestConflict if changed == "run" else SelectedPreSubmitUnavailable + with pytest.raises(error): + await coordinator.lock_acceptance(run_id=run_id, facts=request, terminal_digest=digest) + else: + assert await coordinator.lock_acceptance(run_id=run_id, facts=request, terminal_digest=digest) is terminal + session.get.assert_awaited_once_with(SelectedPreSubmitRun, str(run_id)) + if changed == "run": + read.assert_not_awaited() + else: + read.assert_awaited_once_with(request) def test_selected_pre_execution_capability_is_exact_and_single_use() -> None: @@ -397,53 +391,28 @@ def test_selected_pre_authority_digests_bind_lease_and_infrastructure_outcome() def test_selected_pre_request_binds_complete_later_admission_lineage() -> None: - manifest = {"schema_version": "submission_manifest.v1", "entries": []} - digest = canonical_json_hash(manifest) - lineage = SelectedPreSubmitAdmissionLineage( - predecessor_submission_id=None, - predecessor_submission_version=None, - checker_remediation_manifest_id=None, - guide_id=new_record_id(), - guide_version="locked-v1", - source_snapshot_id=new_record_id(), - source_snapshot_sha256=SHA, - locked_guide_sha256=SHA, - effective_policy_id=new_record_id(), - effective_policy_sha256=SHA, - pre_submit_policy_id=new_record_id(), - pre_submit_policy_sha256=SHA, - effective_plan_sha256="sha256:" + "1" * 64, - rules_sha256="sha256:" + "2" * 64, - external_checker_policies_sha256=SHA, - post_submit_policy_sha256=_POST_POLICY_SHA256, - post_submit_policy_body=_POST_POLICY, - locked_policy_context_hash=SHA, - semantic_manifest_id=new_record_id(), - semantic_manifest_body=manifest, - packet_sha256=SHA, - storage_scheme="s3", - ) - reservation = replace( - _reservation(), - policy_sha256=lineage.effective_plan_sha256, - semantic_manifest_sha256=digest, - admission_lineage=lineage, - ) + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + reservation = _source_reservation() + lineage = reservation.admission_lineage assert reservation.canonical_body()["admission_lineage"] == lineage.canonical_body() - assert ( - SelectedPreSubmitReservationFacts.from_canonical_body(reservation.canonical_body(), source_contracts=selected_pre_submit_source_contracts()) - == reservation - ) - assert ( - reservation.request_digest - != replace( - reservation, - admission_lineage=replace(lineage, packet_sha256="sha256:" + "9" * 64), - ).request_digest - ) - with pytest.raises(ValueError, match="reservation"): - replace(reservation, semantic_manifest_sha256=SHA) + assert SelectedPreSubmitReservationFacts.from_canonical_body( + reservation.canonical_body(), source_contracts=selected_pre_submit_source_contracts(), + ) == reservation + packet = SubmissionPacketView("different summary", "") + changed = replace(reservation, + default_context=replace(reservation.default_context, packet=packet), + admission_lineage=replace(lineage, packet_sha256=packet.sha256), + source_contracts=selected_pre_submit_source_contracts()) + assert changed.request_digest != reservation.request_digest + with pytest.raises(ValueError): + replace(reservation, admission_lineage=changed.admission_lineage, + source_contracts=selected_pre_submit_source_contracts()) + body = reservation.canonical_body() + body["admission_lineage"]["semantic_manifest_body"] = {"entries": []} + with pytest.raises(ValueError): + SelectedPreSubmitReservationFacts.from_canonical_body( + body, source_contracts=selected_pre_submit_source_contracts()) def test_submission_artifact_request_selects_exactly_one_pre_lineage() -> None: From 7f78891a018cadb2ec7464d3682eb76cf4d57725 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 23:04:18 +0100 Subject: [PATCH 185/513] test(artifacts): supply source contracts in grant lifetime fixture --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 35 +++++++++++++++++++ backend/tests/test_checker_materialization.py | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0745e5cd3..05eb905ba 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6466,3 +6466,38 @@ ID and version guards, and acceptance test detects receipt-guard removal. In-mem probes leave source unchanged (/tmp/submission-coordination-qa-repair.log). No remaining scoped QA/ARCH findings;137pass final suite evidence inspected. Same single draft PR708, with remaining full-spec/provider/CI work still open. + +Model-call preservation scope: tests/checkers_model_calls/test_composed_execution.py. +Hosted953 run43960175985 actual stack shows output storage execute_committed_put +fails fixed ART service context. Source-based material fixture no longer incidentally +provisions old put pipeline; model-generated outputs still legitimately require +ARTIFACT_PUT_RESOLVER and ARTIFACT_VERIFIER per checker_output_storage composition. +Provision those exact identities alongside ARTIFACT_CHECKER_OUTPUT locally, using +idempotent helper that never resets lifecycle. No shared broad grants, product +AUTH changes or removed assertions. Medium downstream authority risk: full eight +composed cases incl MinIO/provider uncertainty/concurrency/recovery, lint/structure +and focused QA review. Human focus is explicit required fixture authority without +weakening model budget/charge/replay or output binding evidence. + +Hosted953 evidence refreshed:15 downloaded backend-lane artifacts,152 failure +entries in /tmp/submission-hosted-failures-953.txt. This is an older head and includes +now-fixed public/coordination cases; do not call it current-head remaining count. +QA model-fixture probe confirms added identities exactly match production output +composition, all existing assertions unchanged, and suspended existing principals +are preserved by helper without reset/recreation. No scoped findings. Full8case +run /tmp/submission-model-composed-v1.log is active (session42607); do not claim +runtime success or commit completion before its terminal receipt. Ruff/record pass. + +Independent bounded fixture repair while model integration runs: allowed file +backend/tests/test_checker_materialization.py. Hosted953 source-read tests stop +before exercising guards because dataclass replace omits explicit source_contracts +InitVar. Supply existing production contract dependency at the fixture copy; +no source-validator bypass or test assertion change. Low implementation risk, +authority test relevance: run full pre_source selection, Ruff and scoped QA. +Existing commit-before-read/lifetime/expiry/cancellation guards must all execute. + +Source grant final selection12pass12deselected12.36s; existing assertions and all +other AST nodes unchanged. QA confirms canonical contract dependency validates +source only and conveys no storage authority; no scoped findings. Ruff/whitespace +pass, shared structure validation passed. Model8case integration remains separately +active42607; its fixture change is not included in this source-grant commit. diff --git a/backend/tests/test_checker_materialization.py b/backend/tests/test_checker_materialization.py index f474856d1..cda8be4f0 100644 --- a/backend/tests/test_checker_materialization.py +++ b/backend/tests/test_checker_materialization.py @@ -277,7 +277,7 @@ def _source_read_fixture(*, failure=None): events = [] payload = b"authorized original bytes" reservation = _source_reservation() - reservation = replace(reservation, source=reservation.source.model_copy(update={ + reservation = replace(reservation, source_contracts=selected_pre_submit_source_contracts(), source=reservation.source.model_copy(update={ "raw_sha256": "sha256:" + hashlib.sha256(payload).hexdigest(), "raw_byte_count": len(payload), })) lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at) From b859bb0b6df38603d02c19b30b6ef256370f9613 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 23:13:33 +0100 Subject: [PATCH 186/513] test(checkers): provision retained model evidence storage authorities --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 45 +++++++++++++++++++ .../test_composed_execution.py | 6 ++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 05eb905ba..19ba09ea3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6501,3 +6501,48 @@ other AST nodes unchanged. QA confirms canonical contract dependency validates source only and conveys no storage authority; no scoped findings. Ruff/whitespace pass, shared structure validation passed. Model8case integration remains separately active42607; its fixture change is not included in this source-grant commit. + +Retry-authority counter scope: tests/checkers/execution/test_checker_retry_authority.py. +Hosted953 six failures show exact outbox totals missing the source T4 finalization +event. Shared _failed_source already asserts exactly1 SubmissionFinalizationRequested. +Increase only affected absolute event totals by1, retain all counts (no filtering), +NOWAIT/observed blocking, revocation, audit rollback and replay/no-effects checks. +Public audit-failure assertion currently interrupts before test-owned trigger cleanup; +correct expected total permits existing cleanup and resolves downstream schema +fingerprint symptom if no separate defect exists. Medium authority-test relevance; +run six affected cases and QA review, lint/structure. No production changes. + +Retry-authority QA confirms entire module AST changes only six integer expectations +by+1; every caller uses exact-one-finalization fixture. Baseline2 is T4+initialPOST; +retry3 adds successorPOST. Authority/lock/revocation/receipt/fence/audit/cleanup +assertions unchanged (/tmp/submission-retry-authority-qa-probe.log). No findings; +run77589 /tmp/submission-retry-authority-v1.log still active, so runtime and schema +cleanup consequence remain unproven. Separate modelrun42607 also remains active. + +Execution integrity scope: tests/checkers/execution/test_execution.py only. Current +material fixture retains operation source ZIP, so old SHA-object damage test fails +before exercising integrity. Recover source operation from exact created admission, +assert stored original bytes, then unlink/corrupt exact local source bundle. Retain +no-checker-before-verification, finalize revocation, cleanup and immutable replay +assertions. Both damaged/nonrecordable tests must compare all exact baseline outbox +IDs (T4+initialPOST) and require that pair's exact types; no filtering/loose totals. +Medium source/authority proof risk: seven affected DB cases, lint/structure/QA. +No production storage, authorization, timers or retained historical fixtures change. + +Execution integrity QA no findings: exact local source layout and admission-bound +operation confirmed; all non-outbox assertions and unrelated test ASTs unchanged. +Corrected independent exact-postexecution snapshot probe detects added, removed, +and type-swapped events (/tmp/submission-execution-integrity-qa-events-v2.log). +Sevencase28715 /tmp/submission-material-failures-v1.log active; model42607 and +retry77589 also active. No runtime completion claim. Ruff/record/whitespace pass; +shared structure check terminal0 before this two-test edit, final validation needed. + +Model composed run terminal0:8passed635.57s,6 existing serializer warnings; +/tmp/submission-model-composed-v1.json confirms database/MinIO cleanup complete. +Coverage includes local+MinIO, paid-effect retry, concurrentcallbacksinglecharge, +operator no-effect/settledfailure recovery and offline OpenRouter completed/ambiguous +transport. QA no findings; exact required principal provision preserved all existing +assertions. Ruff/record/structure pass. This closes the eight hosted953 model-output +authority failures locally, not live paid-provider or full-CI qualification. +Retry77589 and material28715 remain separate active verification; only model fixture +is included in this implementation commit alongside accumulated scoped records. diff --git a/backend/tests/checkers_model_calls/test_composed_execution.py b/backend/tests/checkers_model_calls/test_composed_execution.py index 0cf1b57cb..57b6988aa 100644 --- a/backend/tests/checkers_model_calls/test_composed_execution.py +++ b/backend/tests/checkers_model_calls/test_composed_execution.py @@ -289,7 +289,11 @@ async def publish(_factory, project_id, registry): reservation_ttl_seconds=150.0, ), ) as h: - await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_CHECKER_OUTPUT) + # Model evidence uses the retained put/verifier pipeline independently + # of the source-based submission that supplied the checker material. + for identity in (ServiceIdentity.ARTIFACT_CHECKER_OUTPUT, + ServiceIdentity.ARTIFACT_PUT_RESOLVER, ServiceIdentity.ARTIFACT_VERIFIER): + await provision_post_submit_service(h.factory, identity) creates = [] provider_requests = [] lost_replies = [] From 45ac5a8404169aaa125f166da3f146ee90c31566 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 23:15:20 +0100 Subject: [PATCH 187/513] test(checkers): account for intake handoff in retry authority races --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 17 +++++++++++++++++ .../execution/test_checker_retry_authority.py | 12 ++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 19ba09ea3..5c5e862b9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6546,3 +6546,20 @@ assertions. Ruff/record/structure pass. This closes the eight hosted953 model-ou authority failures locally, not live paid-provider or full-CI qualification. Retry77589 and material28715 remain separate active verification; only model fixture is included in this implementation commit alongside accumulated scoped records. + +Binding unit scope: tests/test_artifact_bindings.py. Hosted953 eight failures stop +on fake admission lacking source_operation_id. Migrate ready-consumption fixture to +explicit current accepted_operation_id and same source_operation_id (not silentNone +historical fallback). Positive binding asserts SQL source-custody check invoked for +exactadmission; negative absent/foreign acceptedoperation rejects before SQL/content +or binding writes. Preserve existing packet/manifest/authority/replay assertions. +Medium authority test risk, no production changes. Run whole unit module plus QA. +Mock SQL participation tests do not qualify database source-custody implementation; +real T5/public revision proofs remain separate evidence. + +Retry-authority terminal0:6passed3deselected371.41s with5existing serializer warnings. +Database+MinIO cleanup complete; public audit-failure trigger cleanup now completes +and schema fingerprint teardown passes. Exact lock/revocation/rollback/replay +proofs retained; QA no findings. Ruff/record/whitespace pass, shared structure prior +run passed. This commit includes only retry-authority implementation; material +integrity and binding unit followups remain in progress separately. diff --git a/backend/tests/checkers/execution/test_checker_retry_authority.py b/backend/tests/checkers/execution/test_checker_retry_authority.py index 135298ff2..c52828efb 100644 --- a/backend/tests/checkers/execution/test_checker_retry_authority.py +++ b/backend/tests/checkers/execution/test_checker_retry_authority.py @@ -520,7 +520,7 @@ async def _assert_real_audit_failure_rolls_back(admin_access, h, retry_path): async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 assert tuple(await session.scalars(select(AuditEvent.id).where( AuditEvent.action_id == ActionId.OPERATIONS_CHECKER_RETRY.value ).order_by(AuditEvent.id))) == evidence_before @@ -888,7 +888,7 @@ async def test_task_wait_holds_no_retry_authority_custody( assert await _retry_facts(h) == ( 1, 0, - 1, + 2, 0, str(h.created.evaluation_attempt_id), ) @@ -898,7 +898,7 @@ async def test_task_wait_holds_no_retry_authority_custody( raise created = await asyncio.wait_for(call, 60) assert created.successor.generation == 2 - assert (await _retry_facts(h))[:4] == (2, 1, 2, 1) + assert (await _retry_facts(h))[:4] == (2, 1, 3, 1) @pytest.mark.parametrize("first", ["retry", "claim"]) @@ -957,7 +957,7 @@ async def pause_holder(repository, *args, **kwargs): assert sum(isinstance(result, TaskAuthorityDenied) for result in results) == 1, [ type(result).__name__ for result in results ] - assert (await _retry_facts(h))[:4] == (2, 1, 2, 1) + assert (await _retry_facts(h))[:4] == (2, 1, 3, 1) async with h.factory() as session: assert await session.scalar( select(func.count()) @@ -1073,13 +1073,13 @@ async def pause_revoke(service, **kwargs): assert grant.status == "revoked" and grant.version == 2 if first == "retry": assert all(not isinstance(result, BaseException) for result in results) - assert (await _retry_facts(h))[:4] == (2, 1, 2, 1) + assert (await _retry_facts(h))[:4] == (2, 1, 3, 1) else: assert sum(isinstance(result, CheckerExecutionUnavailable) for result in results) == 1 assert (await _retry_facts(h)) == ( 1, 0, - 1, + 2, 0, str(h.created.evaluation_attempt_id), ) From 1810d078907c670fae6a4e75b0bd652988611bd2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 23:16:48 +0100 Subject: [PATCH 188/513] test(checkers): exercise retained source corruption and failure custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 7 ++++++ .../checkers/execution/test_execution.py | 24 ++++++++++++------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 5c5e862b9..7e1e6ab8e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6563,3 +6563,10 @@ and schema fingerprint teardown passes. Exact lock/revocation/rollback/replay proofs retained; QA no findings. Ruff/record/whitespace pass, shared structure prior run passed. This commit includes only retry-authority implementation; material integrity and binding unit followups remain in progress separately. + +Material integrity run terminal0:7passed8deselected242.68s, database+MinIO cleanup +complete (/tmp/submission-material-failures-v1.json). Actual source missing/corrupt +cases and all5 nonrecordable cases preserve finalize authority, no checker access, +recoverability, scratch cleanup and exact unchanged T4+POST event set. QA no scoped +findings; final structural validator terminal0, Ruff/record/whitespace pass. This +commit includes material tests only; bindingunit strengthening remains separate. diff --git a/backend/tests/checkers/execution/test_execution.py b/backend/tests/checkers/execution/test_execution.py index f066ce3fc..85759f5e1 100644 --- a/backend/tests/checkers/execution/test_execution.py +++ b/backend/tests/checkers/execution/test_execution.py @@ -322,15 +322,21 @@ async def append(self, value): async def test_unreadable_stored_bytes_terminalize_and_replay( tmp_path, isolated_database_env, monkeypatch, damage ): - from tests.test_local_artifact_store import object_path + from app.modules.artifacts.models import SubmissionBundleAdmission async with material_fixture( tmp_path, isolated_database_env, post_submit_registry_spec=post_registry_spec(), ) as h: assert len(h.request.policy.entries) == 1 reservation = await reserve(h) - digest = h.request.content_sha256 - path = object_path(h.settings.artifact_local_root, f"sha256/{digest[7:9]}/{digest[9:]}") + async with h.factory() as session: + admission = await session.get(SubmissionBundleAdmission, str(h.created.admission_id)) + assert admission.source_operation_id is not None + events_before = dict((await session.execute(select(OutboxEvent.event_id, OutboxEvent.event_type))).all()) + assert sorted(events_before.values()) == ["PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested"] + assert events_before[h.created.evaluation_event_id] == "PostSubmissionEvaluationRequested" + path = (h.settings.artifact_local_root / "objects" / "submission-source" / "v1" + / admission.source_operation_id / "bundle.zip") assert path.read_bytes() == h.data if damage == "missing": path.unlink() @@ -383,9 +389,7 @@ async def retain_finalization(facts): assert run.finalize_evidence_id is not None assert run.routing_recommendation == "not_evaluated" assert await session.scalar(select(func.count()).select_from(CheckerResult)) == 0 - assert list(await session.scalars(select(OutboxEvent.event_id))) == [ - h.created.evaluation_event_id - ] + assert dict((await session.execute(select(OutboxEvent.event_id, OutboxEvent.event_type))).all()) == events_before with pytest.raises(CheckerExecutionUnavailable, match="current_result"): await evaluation_coordinator(session).read_current_result(h.request) @@ -403,6 +407,10 @@ async def test_nonrecordable_material_failure_leaves_attempt_recoverable( async with material_fixture(tmp_path, isolated_database_env) as h: reservation = await reserve(h) + async with h.factory() as session: + events_before = dict((await session.execute(select(OutboxEvent.event_id, OutboxEvent.event_type))).all()) + assert sorted(events_before.values()) == ["PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested"] + assert events_before[h.created.evaluation_event_id] == "PostSubmissionEvaluationRequested" executor = live_executor(h) if failure == "authority": await service_link_state(h.factory, ServiceIdentity.ARTIFACT_MATERIALIZER, active=False) @@ -453,6 +461,4 @@ async def fail_prepare(*args, **kwargs): assert run.status == "running" and run.result_json is None assert run.finalize_evidence_id is None and run.completion_event_id is None assert await session.scalar(select(func.count()).select_from(CheckerResult)) == 0 - assert list(await session.scalars(select(OutboxEvent.event_id))) == [ - h.created.evaluation_event_id - ] + assert dict((await session.execute(select(OutboxEvent.event_id, OutboxEvent.event_type))).all()) == events_before From 017a7121762d504e812c35ebf71740f6b0f634d2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 23:18:12 +0100 Subject: [PATCH 189/513] test(artifacts): bind admission consumption to accepted source operation --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 +++++++++ backend/tests/test_artifact_bindings.py | 30 ++++++++++++++----- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 7e1e6ab8e..e663659c8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6570,3 +6570,17 @@ cases and all5 nonrecordable cases preserve finalize authority, no checker acces recoverability, scratch cleanup and exact unchanged T4+POST event set. QA no scoped findings; final structural validator terminal0, Ruff/record/whitespace pass. This commit includes material tests only; bindingunit strengthening remains separate. + +Binding first run18pass1fail: manually rebuilt wrongversion replay omitted accepted +operation, so it stopped at operation guard; use replace(original,submission_version=2) +to isolate intended version denial (QA-BINDING001). QA-BINDING002 strengthens new +negative fixture with full valid downstream readsequence, so removing operationguard +causes DIDNOTRAISE rather than exhaustedmock. Exact probes now detect missingSQL +participation and foreign/missingoperation invalidacceptance; all existing assertions +retained including historical read. Final19pass1.52s, no remaining QA findings; +Ruff/whitespace pass. Final structure session22457 stillactive at this checkpoint. + +Final binding structural validator terminal0. Scoped tests/review/record checks +complete; commit current accepted-operation fixture and guards without claiming +live database source validation or full-spec readiness. No local test run remains +active from model/retry/material/binding batch. diff --git a/backend/tests/test_artifact_bindings.py b/backend/tests/test_artifact_bindings.py index ed9d17966..296a1904b 100644 --- a/backend/tests/test_artifact_bindings.py +++ b/backend/tests/test_artifact_bindings.py @@ -46,6 +46,7 @@ def _request(*, submission_id=None) -> SubmissionAdmissionConsumptionRequest: pre_submit_policy_bundle_hash=_sha("3"), ) return SubmissionAdmissionConsumptionRequest( + accepted_operation_id=new_record_id(), packet_sha256=SubmissionPacketView("Prepared summary", "Prepared attestation").sha256, admission_id=new_record_id(), submission_id=submission_id or new_record_id(), @@ -72,6 +73,7 @@ def _lineage(request: SubmissionAdmissionConsumptionRequest): **policy_body, "policy_sha256": canonical_json_hash(policy_body), }) admission = SimpleNamespace( + source_operation_id=str(request.accepted_operation_id), id=str(request.admission_id), status="ready", actor_profile_id=str(context.contributor_id), @@ -175,6 +177,9 @@ async def test_ready_admission_creates_exact_binding_and_consumes_once() -> None authority = _Allow() result = await SubmissionAdmissionConsumptionService(session, authority).consume(request) + custody_call = session.execute.await_args_list[0] + assert "require_source_submission_admission" in str(custody_call.args[0]) + assert custody_call.args[1] == {"id": admission.id} binding = session.add.call_args_list[0].args[0] assert result.status == "consumed" assert result.replayed is False @@ -223,6 +228,23 @@ async def test_ready_admission_creates_exact_binding_and_consumes_once() -> None assert result.binding_decision_id == authority.consume.return_value +@pytest.mark.asyncio +@pytest.mark.parametrize("missing", [False, True]) +async def test_source_admission_rejects_foreign_or_missing_accepted_operation(missing): + request = _request() + admission, content = _lineage(request) + session, authority = _session(admission, content, None, datetime.now(UTC)), _Allow() + changed = replace(request, accepted_operation_id=None if missing else new_record_id()) + with pytest.raises(SubmissionAdmissionConsumptionError, match="submission_bundle_admission_unavailable"): + await SubmissionAdmissionConsumptionService(session, authority).consume(changed) + assert session.scalar.await_count == 1 + session.execute.assert_not_awaited() + session.add.assert_not_called() + session.flush.assert_not_awaited() + authority.consume.assert_not_awaited() + assert admission.status == "ready" and admission.consumed_by_submission_id is None + + @pytest.mark.asyncio async def test_final_authority_denial_leaves_ready_admission_unchanged() -> None: request = _request() @@ -331,13 +353,7 @@ async def test_consumed_admission_rejects_different_submission() -> None: @pytest.mark.asyncio async def test_consumed_admission_rejects_wrong_submission_version() -> None: original = _request() - replay = SubmissionAdmissionConsumptionRequest( - packet_sha256=original.packet_sha256, - admission_id=original.admission_id, - submission_id=original.submission_id, - submission_version=2, - task_context=original.task_context, - ) + replay = replace(original, submission_version=2) admission, content = _lineage(original) admission.status = "consumed" admission.consumed_by_submission_id = str(original.submission_id) From d5b809bb90b6c424130bf3bb06b6353a668ce83c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 23:23:49 +0100 Subject: [PATCH 190/513] test(checkers): bind revision acknowledgements before source PRE --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 +++ .../external/test_selected_pre_submit.py | 191 +++++++++--------- 2 files changed, 118 insertions(+), 97 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e663659c8..94c8fd745 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6584,3 +6584,27 @@ Final binding structural validator terminal0. Scoped tests/review/record checks complete; commit current accepted-operation fixture and guards without claiming live database source validation or full-spec readiness. No local test run remains active from model/retry/material/binding batch. + +Current PRE builder scope: tests/checkers/external/test_selected_pre_submit.py, +only revision acknowledgement request digest and current policy/predecessor binding +tests. Replace retired prepared archive fixture with sealed source reservation, +metadata and explicit contract dependency; preserve ack completeness/digest, exact +predecessor/rules/packet and revision lineage assertions. Derived manifest supplied +only after reservation through guest-default derivation, never admission metadata. +Retained publisher tests/helpers remain untouched pending checksum-bound historical +fixture migration. Medium lineage proof risk: targeted tests, Ruff/structure and QA. +No production path/schema changes, fake authority grant or compatibility alias. + +Builder v1 targeted2pass1fail: current default input has no change_gate property. +Repair uses actual bind_submission_change over typed derived commitment/manifest; +assert intrinsic unchanged outcome. Supplemental pure current default gate confirms +changedrules allow and samerules refuse identicalarchive; no secret/byteproof claim. +Final targeted3pass11deselected0.75s; v2comparison-only also3pass1.69s. Ruff/structure/ +record/whitespace pass. Historical publisher/old processor consumers remain explicitly +unmigrated; this is not a whole-module/full-spec completion claim. QA closure pending. + +QA-BUILDER001 closed: exact tests detect ignored acknowledgement fields, removed +changedrules exception and unconditional unchanged acceptance; other test/helper +ASTs unchanged (/tmp/submission-current-builders-qa-probe.log). No scoped findings. +Fresh origin/main fetch has0missing main commits (190ahead beforethiscommit). +Same draftPR708; no broad CI or retained publisher completion claim. diff --git a/backend/tests/checkers/external/test_selected_pre_submit.py b/backend/tests/checkers/external/test_selected_pre_submit.py index cbb9ea2cd..02650f256 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit.py +++ b/backend/tests/checkers/external/test_selected_pre_submit.py @@ -12,7 +12,6 @@ from dataclasses import replace from datetime import UTC, datetime, timedelta from io import BytesIO -import json from pathlib import Path from types import SimpleNamespace from typing import cast @@ -173,7 +172,10 @@ def _selected_admission_reservation(): def test_revision_acknowledgement_changes_selected_request_and_retains_old_bytes() -> None: """A new acknowledgement is frozen; old selected requests keep their digest.""" - _, _, retained = _selected_admission_reservation() + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + from app.modules.checkers.api.default_checker import WorkstreamDefaultPredecessor + + retained = _source_reservation() old_body = retained.canonical_body() assert SelectedPreSubmitReservationFacts.from_canonical_body(old_body, source_contracts=selected_pre_submit_source_contracts()).canonical_body() == old_body assert "revision_preparation_id" not in old_body["admission_lineage"] @@ -189,7 +191,14 @@ def test_revision_acknowledgement_changes_selected_request_and_retains_old_bytes revision_preparation_id=preparation_id, revision_preparation_sha256=_hex_sha("b"), ) - selected = replace(retained, admission_lineage=acknowledged) + predecessor = WorkstreamDefaultPredecessor(predecessor_id, 1, retained.source.raw_sha256, SHA) + selected = replace(retained, admission_lineage=acknowledged, + default_context=replace(retained.default_context, predecessor=predecessor, + current_predecessor=predecessor, predecessor_exists=True, + predecessor_rules_sha256=retained.default_context.current_rules_sha256), + source_contracts=selected_pre_submit_source_contracts()) + assert retained.canonical_body() == old_body + assert selected.request_digest != retained.request_digest body = selected.canonical_body() assert body["admission_lineage"]["revision_preparation_id"] == str(preparation_id) assert body["admission_lineage"]["revision_preparation_sha256"] == _hex_sha("b") @@ -972,107 +981,95 @@ async def test_selected_pre_default_secret_blocker_precedes_external_image( @pytest.mark.asyncio -async def test_selected_admission_binds_unchanged_work_to_current_task_rules( - tmp_path, -) -> None: - request, _inspector, manager, _preparation = await _request(tmp_path) +async def test_selected_admission_binds_unchanged_work_to_current_task_rules() -> None: + """Bind prior content/rules before inspection, then derive unchanged input in PRE.""" + from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata + from app.modules.checkers.api.selected_pre_submit import derive_selected_pre_submit_default_input + from tests.checkers.external.test_selected_pre_submit_coordination import ( + _source_reservation, _source_guard, _source_completed_execution, + ) + + original = _source_reservation() + derived = _source_completed_execution(original) policies = _policies() - project_id = request.selected_reservation.project_id - actor_profile_id = new_record_id() - identity_link_id = new_record_id() - assignment_id = new_record_id() - guide_id = new_record_id() - source_snapshot_id = new_record_id() - effective_policy_id = new_record_id() - pre_submit_policy_id = new_record_id() + lineage = original.admission_lineage predecessor = SubmissionCanonicalPredecessor( - submission_id=new_record_id(), - submission_version=1, - archive_sha256=request.prepared_artifact.commitment.sha256, - semantic_manifest_sha256=request.manifest.sha256, + submission_id=new_record_id(), submission_version=1, + archive_sha256=original.source.raw_sha256, + semantic_manifest_sha256=derived.manifest_sha256, + ) + references = SimpleNamespace( + project_id=original.project_id, guide_version=lineage.guide_version, + source_snapshot_id=lineage.source_snapshot_id, source_snapshot_hash=lineage.source_snapshot_sha256, + effective_policy_id=lineage.effective_policy_id, effective_policy_hash=lineage.effective_policy_sha256, + pre_submit_policy_id=lineage.pre_submit_policy_id, pre_submit_policy_bundle_hash=lineage.pre_submit_policy_sha256, ) task = SimpleNamespace( - contributor_id=actor_profile_id, - task_id=request.task_id, - assignment_id=assignment_id, - checker_remediation_manifest_id=new_record_id(), + contributor_id=original.actor_profile_id, task_id=original.task_id, + assignment_id=original.assignment_id, checker_remediation_manifest_id=new_record_id(), revision_context=SimpleNamespace(preparation_id=new_record_id(), preparation_sha256=SHA), - predecessor=SimpleNamespace( - submission_id=predecessor.submission_id, - version=predecessor.submission_version, - ), - locked_project_context=SimpleNamespace(project_id=project_id), - locked_policy=SimpleNamespace( - model_dump=lambda **_kwargs: { - "locked_guide_version": "v1", - "locked_pre_submit_checker_bundle_hash": SHA, - } - ), + predecessor=SimpleNamespace(submission_id=predecessor.submission_id, version=1), + locked_project_context=references, + locked_policy=SimpleNamespace(model_dump=lambda **kwargs: { + "locked_guide_version": lineage.guide_version, "locked_pre_submit_checker_bundle_hash": SHA, + }), ) - project = SimpleNamespace( - project_id=project_id, - guide_id=guide_id, - guide_version="v1", - source_snapshot_id=source_snapshot_id, - source_snapshot_hash=SHA, - effective_policy_id=effective_policy_id, - effective_policy_hash=SHA, - pre_submit_policy_id=pre_submit_policy_id, - pre_submit_policy_bundle_hash=SHA, - external_checker_policies=SimpleNamespace( - value=json.dumps( - policies.model_dump(mode="json"), - sort_keys=True, - separators=(",", ":"), - ) - ), + project = SimpleNamespace(**vars(references), guide_id=lineage.guide_id, + external_checker_policies=SimpleNamespace(value=policies.model_dump_json())) + packet = original.default_context.packet + metadata = SubmissionIntakeMetadata( + task_id=task.task_id, assignment_id=task.assignment_id, + predecessor_submission_id=predecessor.submission_id, + summary=packet.summary, contributor_attestation=packet.contributor_attestation, + revision_preparation_id=task.revision_context.preparation_id, + revision_preparation_sha256=task.revision_context.preparation_sha256, ) - try: - bound = bind_selected_pre_submit_admission( - task=task, - project=project, - commitment=request.prepared_artifact.commitment, - manifest=request.manifest, - predecessor=predecessor, - predecessor_rules_sha256="sha256:" + "d" * 64, - predecessor_exists=True, - packet=request.packet, - ) - assert bound.change_gate.outcome.value == "unchanged" - assert bound.default_input.predecessor is not None - assert bound.default_input.predecessor_rules_sha256 == "sha256:" + "d" * 64 - assert bound.default_input.current_rules_sha256 == bound.rules_sha256 - assert bound.policy.policy_sha256 == policies.pre_submit.policy_sha256 - reservation = build_selected_pre_submit_reservation( - actor_profile_id=actor_profile_id, - identity_link_id=identity_link_id, - task=task, - project=project, - prepared_generation_id=request.prepared_artifact.generation_id, - attempt_id=new_record_id(), - idempotency_key=new_record_id(), - attempt_request_digest=SHA, - commitment=request.prepared_artifact.commitment, - manifest=request.manifest, - packet=request.packet, - selected=bound, - storage_scheme="s3", - execution_budget_ms=120_000, - ) - assert reservation.admission_lineage is not None - assert reservation.admission_lineage.semantic_manifest_body == (request.manifest.as_dict()) - assert reservation.admission_lineage.packet_sha256 == request.packet.sha256 - assert reservation.admission_lineage.revision_preparation_id == task.revision_context.preparation_id - assert reservation.admission_lineage.revision_preparation_sha256 == task.revision_context.preparation_sha256 - assert reservation.admission_lineage.checker_remediation_manifest_id == ( - task.checker_remediation_manifest_id - ) - assert reservation.admission_lineage.predecessor_submission_id == ( - predecessor.submission_id - ) - finally: - await request.prepared_artifact.close() - manager.close() + source = _source_guard(original).lock_pre_source.return_value.model_copy(update={ + "metadata_sha256": metadata.metadata_sha256(), + }) + bound = bind_selected_pre_submit_admission( + task=task, project=project, predecessor=predecessor, + predecessor_rules_sha256="sha256:" + "d" * 64, predecessor_exists=True, packet=packet, + ) + assert bound.default_context.predecessor.submission_id == predecessor.submission_id + assert bound.default_context.predecessor_rules_sha256 == "sha256:" + "d" * 64 + assert bound.default_context.current_rules_sha256 == bound.rules_sha256 + assert bound.policy.policy_sha256 == policies.pre_submit.policy_sha256 + reservation = build_selected_pre_submit_reservation( + source=source, metadata=metadata, task=task, project=project, + attempt_id=new_record_id(), idempotency_key=new_record_id(), selected=bound, + runtime_profile=original.runtime_profile, + ) + assert "semantic_manifest_body" not in reservation.admission_lineage.canonical_body() + assert reservation.admission_lineage.packet_sha256 == packet.sha256 + assert reservation.admission_lineage.revision_preparation_id == task.revision_context.preparation_id + assert reservation.admission_lineage.revision_preparation_sha256 == task.revision_context.preparation_sha256 + assert reservation.admission_lineage.checker_remediation_manifest_id == task.checker_remediation_manifest_id + assert reservation.admission_lineage.predecessor_submission_id == predecessor.submission_id + lease = SelectedPreSubmitLeaseFacts(reservation, new_record_id(), 1, reservation.pre_deadline_at) + default_input = derive_selected_pre_submit_default_input( + lease, manifest_body=derived.manifest_body, manifest_sha256=derived.manifest_sha256, + source_contracts=selected_pre_submit_source_contracts(), + ) + from app.modules.artifacts.sources import ArtifactCommitment + from app.modules.artifacts.api.submission_manifest import SubmissionManifest + from app.modules.artifacts.submission_manifest import bind_submission_change + + comparison = bind_submission_change( + commitment=ArtifactCommitment(default_input.archive_sha256, default_input.archive_byte_count, + default_input.archive_media_type), + manifest=SubmissionManifest.from_dict(derived.manifest_body, sha256=default_input.semantic_manifest_sha256), + predecessor=predecessor, predecessor_exists=default_input.predecessor_exists, + current_predecessor=predecessor, + ) + assert comparison.outcome.value == "unchanged" + assert default_input.current_rules_sha256 == bound.rules_sha256 + assert default_input.predecessor_rules_sha256 == "sha256:" + "d" * 64 + from app.modules.checkers.default_checker import _change_failure + + assert _change_failure(default_input) is None + assert _change_failure(replace(default_input, + predecessor_rules_sha256=default_input.current_rules_sha256)) == "submission_archive_unchanged" @pytest.mark.asyncio From ffef274db0fc93e639269a902e1284b810e17ab1 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 16 Nov 2026 23:54:30 +0100 Subject: [PATCH 191/513] fix(migrations): require historical PRE drain before source cutover --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 58 +++++++++ .../alembic/versions/0071_source_first_pre.py | 11 ++ backend/scripts/test_lane_catalogue.py | 1 + .../tests/fixtures/pre_cutover_capture.py.txt | 51 ++++++++ .../tests/fixtures/pre_cutover_rows.json.gz | Bin 0 -> 72935 bytes .../migrations/test_source_pre_cutover.py | 122 ++++++++++++++++++ backend/tests/test_ci_lane_catalogue.py | 4 +- 7 files changed, 245 insertions(+), 2 deletions(-) create mode 100644 backend/tests/fixtures/pre_cutover_capture.py.txt create mode 100644 backend/tests/fixtures/pre_cutover_rows.json.gz create mode 100644 backend/tests/migrations/test_source_pre_cutover.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 94c8fd745..bc5f68409 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6608,3 +6608,61 @@ changedrules exception and unconditional unchanged acceptance; other test/helper ASTs unchanged (/tmp/submission-current-builders-qa-probe.log). No scoped findings. Fresh origin/main fetch has0missing main commits (190ahead beforethiscommit). Same draftPR708; no broad CI or retained publisher completion claim. + +Source PRE cutover scope: 0071_source_first_pre.py and focused migration proofs. +The migration currently installs a read-only guard on all v1 PRE rows without +refusing queued/running rows, stranding existing execution owners. Require an +exclusive table lock and refuse those rows before schema mutation. Preserve +terminal history byte-for-byte; never auto-complete, delete, or reinterpret it. +Allowed follow-up files are predecessor migration fixtures and their targeted +tests. Prohibited: restoring the retired admission publisher, changing current +submission authority, or claiming this check drains old put attempts/admissions. +High lifecycle/migration risk; architecture and QA review required. Acceptance: +real PostgreSQL queued/running refusal with rollback, completed historical-row +preservation, and serialization against concurrent old writes. Human review +focus: cutover refusal happens before historical execution becomes read-only. +Architecture agrees this is independently valid but not full spec20.2 cutover. +Archive inventory found completed selected PRE rows only; refusal fixtures still +need a genuine predecessor writer capture, not rewritten completed evidence. + +Cutover preflight draft: syntax, whitespace and Commitrail validation pass. +Fresh isolated PostgreSQL migration through0083 and current PRE source custody +smoke pass (1test23.11s; /tmp/submission-pre-cutover-smoke-v1.json). This verifies +empty-database upgrade and current custody only, not queued/running refusal, +historical preservation or lock concurrency. Those acceptance checks and QA +remain pending; the migration change is not yet committed or qualified. + +Historical refusal proof uses a detached e2b926288 owner checkout and captures +the same real run before execute, after committed claim, and after finalize. +Capture code only observes committed rows through a separate connection; it does +not replace owner decisions or rewrite terminal evidence. First capture passed +but omitted Alembic metadata; corrected capture rerun pending. Test files: +tests/migrations/test_source_pre_cutover.py and checksum-bound fixture/recipe +under tests/fixtures; register the test in scripts/test_lane_catalogue.py so CI +executes it. No gate weakening or current old-writer implementation is allowed. + +Capture v2 passed1test56.11s with complete cleanup; archive SHA256 +49156dd714478ba5d9b446440842b6b40d8372c4f05dcd38e7edb3b6e59f4b59. +The unchanged predecessor owns issuance at0065; current migrations carry each +restored snapshot to0070 before testing the cutover. No snapshot rows rewritten. +CI registration also requires tests/test_ci_lane_catalogue.py fingerprint update: +independently compared old/new sets, exactly one module added and none removed. +First catalogue run58pass1fail detects stale pinned count; exact fingerprint repair +rerun pending. Structural validator and Ruff pass. Migration run remains live. + +Cutover migration proof terminal0:3passed421.85s, database/MinIO cleanup complete +(/tmp/submission-pre-cutover-migration-v1.json). Queued/running refusal preserves +rows/schema/guard/version; queued case observes blocked exclusive lock behind an +old writer; completed evidence upgrades to0083 byte-identically apart from the +new null source column and historical terminal digest still validates. ARCH/SEC +scoped PASS. Catalogue fingerprint repair59passed6.57s. QA omission probes pending. +This evidence is for the dirty candidate based on d5b809bb9, not full-spec CI. + +QA omission proofs: removing only the refusal block makes the exact running case +fail DID NOT RAISE DBAPIError (133.36s); removing only the explicit lock makes the +exact queued case fail "cutover checked rows before excluding old writers" +(124.53s), with observed early drain exception, not an unrelated setup error. +Both isolated probes cleaned database and MinIO completely; current files were +unchanged. Historical reader probe accepts the captured completed row and rejects +an indexed request-digest substitution. Fresh main fetch:191ahead/0missing before +this commit. Full old put/admission cutover and publisher retirement remain open. diff --git a/backend/alembic/versions/0071_source_first_pre.py b/backend/alembic/versions/0071_source_first_pre.py index fc8eefea2..fc9118c9c 100644 --- a/backend/alembic/versions/0071_source_first_pre.py +++ b/backend/alembic/versions/0071_source_first_pre.py @@ -229,6 +229,17 @@ def _update_guard(): def upgrade(): """Retain historical bytes while restricting new writes to source-bound runs.""" op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + # Serialize the drain check with old writers before making their rows + # read-only. A running historical lease must finish under its old guards. + op.execute("LOCK TABLE public.selected_pre_submit_runs IN ACCESS EXCLUSIVE MODE") + op.execute("""DO $$ BEGIN + IF EXISTS (SELECT 1 FROM public.selected_pre_submit_runs + WHERE request_json->>'schema_version'='workstream.selected_pre_submit_reservation.v1' + AND status IN ('queued','running')) THEN + RAISE EXCEPTION 'drain historical PRE runs before source-first cutover' + USING ERRCODE='55000'; + END IF; + END $$""") op.execute("ALTER TABLE public.selected_pre_submit_runs ADD COLUMN source_operation_id uuid") for column in ("prepared_generation_id", "default_input_sha256", "semantic_manifest_sha256"): op.execute(f"ALTER TABLE public.selected_pre_submit_runs ALTER COLUMN {column} DROP NOT NULL") diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 9c24b84a2..a591f2e16 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -188,6 +188,7 @@ class TestLane: "tests/test_local_artifact_store.py", "tests/migrations/test_task_queue_authority.py", "tests/migrations/test_claim_starts_work.py", + "tests/migrations/test_source_pre_cutover.py", "tests/migrations/test_compensation_unit_create_migration.py", "tests/migrations/test_task_read_authority.py", "tests/migrations/test_task_context_authority.py", diff --git a/backend/tests/fixtures/pre_cutover_capture.py.txt b/backend/tests/fixtures/pre_cutover_capture.py.txt new file mode 100644 index 000000000..185757deb --- /dev/null +++ b/backend/tests/fixtures/pre_cutover_capture.py.txt @@ -0,0 +1,51 @@ +"""One-time capture through pinned predecessor owners, never a current writer.""" +import gzip +import json +from pathlib import Path + +import asyncpg + +from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService +from app.modules.checkers.selected_pre_submit_coordination import SelectedPreSubmitCoordinator +from tests.tasks.test_submission_lineage import _prepared_packet + + +async def test_capture(isolated_database_env, tmp_path, monkeypatch): + snapshots = {} + + async def capture(status): + connection = await asyncpg.connect(isolated_database_env.replace('+asyncpg', '')) + try: + async with connection.transaction(isolation='repeatable_read', readonly=True): + assert await connection.fetchval('SHOW session_replication_role') == 'origin' + tables = {} + for table in await connection.fetch("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename"): + name = table['tablename'] + rows = json.loads(await connection.fetchval(f'SELECT coalesce(jsonb_agg(to_jsonb(r)),\'[]\')::text FROM public."{name}" r')) + if rows: + tables[name] = rows + runs = tables['selected_pre_submit_runs'] + assert len(runs) == 1 and runs[0]['status'] == status + snapshots[status] = dict(revision=await connection.fetchval('SELECT version_num FROM alembic_version'), seed={}, tables=tables) + finally: + await connection.close() + + execute = SelectedPreSubmitExecutionService.execute + committed = SelectedPreSubmitCoordinator.committed_execution + + async def wrapped_execute(self, **kwargs): + await capture('queued') + result = await execute(self, **kwargs) + await capture('completed') + return result + + async def wrapped_committed(self, **kwargs): + await capture('running') + return await committed(self, **kwargs) + + monkeypatch.setattr(SelectedPreSubmitExecutionService, 'execute', wrapped_execute) + monkeypatch.setattr(SelectedPreSubmitCoordinator, 'committed_execution', wrapped_committed) + async with _prepared_packet(isolated_database_env, tmp_path): + assert set(snapshots) == {'queued', 'running', 'completed'} + body = dict(schema_version='workstream.pre_cutover_rows.v1', source_revision='e2b926288899bcd9b05e1a560ec19b6bca8cfcfc', source_test='tests/test_capture_pre_cutover.py::test_capture', snapshots=snapshots) + Path('/tmp/pre-cutover-rows.json.gz').write_bytes(gzip.compress(json.dumps(body,sort_keys=True).encode(),mtime=0)) diff --git a/backend/tests/fixtures/pre_cutover_rows.json.gz b/backend/tests/fixtures/pre_cutover_rows.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..6e3d8767b0a90b8960a7f99c42bf22042a635e72 GIT binary patch literal 72935 zcma&MQ*b8E6Zae2wr$(m*mgFyZF|Efwrv}mWMkX5jVC$3|2gNqf2aCls%tK~rlzZV z`uib{g#r2B0t3J5J@+6VOXBjQ_kVL0!p{9H3VfjQZP6|si8Z|3JKBgxm39JYC~Zr) z0s1yofndP#!!(UM{A=4X_%|^@nMO@UPX6u6iRicxkKdz^a_;2k`#fGReQy_Y^3w@-nBA?CRjU1CpS*)~Du`Ni zL=v}kXTg%&Ic~>C*!MZ&Y(d-#IfA>=UF#MDK#AxkW_27DuVHM+c8XKVw^Uoc z_{l-**poSZQqzpplmnsE7DT0GV{-2N)wdHjg~ zcD0)U3CvvaZF#%Dek*VNlVw?*%Q5?LYwBzHYF=G;kx=53aOcRSE z?WK3SpZ$sN=?hu3E{F1#jy0%03Kz|YC4g2+hHOGEx~6 z5Qk!0pnH09SUXiCaAGg4HKZ*Uc6+lWH6+s4%GddEv^DKO$g(9#%_&F>k(EIGYi^2b zrgNc`NLJSy(TX;s6{_C9W>9e0wt|;zfp77g1(eD@F!~ynFjHYyuf8T`Kbrelt2Y$6 z+JtoEm8}D}%YeCM>0 z@M(K2a92V1++T02^!Em4=eF|)x~(+ZWS#) zP}EDkWdY8?Vk^FRVP?D=9nlnGb8`rPw5V9r%x_cK1*C4S50fCEjY+aLLuJ62X=YO2 zgIb0PKi%nYVI~?HbLJ-^kE-qLVutYSYj#DTtnBA>A13Bu*c!&20R$@3Ho{1_8Mc+M ztC6ALu8a()ae-&aCbK)avS_LpJjOYdeo#~(Q)okKH@)2W(qb`S&|sNZMW~FeqQTY}3&jP+&Jvm4+Pow>rQ@RuGR!%`80KOo;})@r5(_KPvX? znj#A6`o{nc%$>PZdUTlmbbCQ-JL)rK!2w-CH&CUz%j~z3g_(J(5gyoxLGh6eR}EnBx-W zO`nan8(ko@z3t$<>QL1IQUMdMY00bT==3IBM`>zBTvTUFDh_(%Am8R>TV7jjx8@J& zCLSCUQUUgD0ULRe${v46bNnWrU1|6N;809!VNAl{{>i%yQgT(PZjrf;CnMpp)v zg%mS#==1^1L}~*0Urbe@qx+eMJ?M<^_lZUVoI^xC^|ar_tJ+}!@>-g8Go^`NpkANS zokf>_w$x!aM@FBseAV%s?LomCxDeZv_Esy_w56seLXGsf=U+duY3eW|^bvc@$kiFP zGe@kW9s!Lghm)S{vfwd^$o6{MLo0#Y-iSiY-qQRa3R34DC#Zp0Sfu#^?~)yA6Z;mf zJ(&_s9r{!a)RRbcQuIsLy}<_y^bg|gE+kvV_PVi%G*8doV?$eZ!d<1i*YUU0K@Rti zo}tlDGy=}xU>s=@f`gq&J3^&F>P#~88F4gf*-%s!O)$+vcEdE~iP+X@%=!-Kzc zTM=@~+`8Ea7&KhppsI+rO4hTTw=28z;~iPjSpE&e?zobcoIhO+)hPLX{#|-v+8*7B zOjqj8x6f1L_J8_jB5EEc%za^fk(`Zk2py@Cskh(KGrEMx*ij_4X*Pb&LNc4 z+Uxb@#+!QW-MpZUvV9#~{G{l_bn(JyTo(SNOWC1tbMPu+)2$TDM0REDqq~0ntDyW@ zyuz{=%9EJX!0Jo{@8bH7d~WUocEvSS#&;&4>B)^m@Y&;&)p!|d*AQ9LJ=a%BN!C}f z*N`sRC1suE@Yy!eBMV{M>g|@pyFaQ*36_|;^;#g#_kPL4Q+T+0@&4>Od?OFC^_q{| z?|x||Peh;Qnpb(F&U6x6$@?euaba~+&^ z5;44UdQiLOD(&0Igj`k#Aap>&IGjcijQ?eQ=X2m-d7b$iczO(dqNQpW{CDe;!+Y5W z-;lAcEY*66`TD5?wk~=}4lcWYe;1KULZfBzg6ksQL$CY1`uY>sZxtzqpxRBoswt#1=1x9!j?R3t{zZ!RDnq_~zHZzO-jQY+|A5wQ^NE!qWdJ(+ z@!O?n$6-}AVVb$w)ARXr8qE&fhMn6x*CI4hpXO46U}@+=IR-4W4_66pl0ZTw8Fl-) z;ijx2^jClS2~t_=wtD9^M|6?gp}VGvas$0V&0`Oi_u9l$~{9YlPNa2Ug1nnmRto~#p-ZV=5{oDRFGrUYJ> z)}q2j+X_IlDMTaz=vF!=%BFkg%m@mw;=qj_AfnRa4Ox$%@J?0lFdGi1LM|NNF851N zNO{R(BZv7Ms6f+%*5v%9;ytNa3Q$Y4uz`u44WWCyTiG6Z(gszXjbVDt!4hIK7(!sn z!GA2AFIC5I!_|m*!0J+!vLI`0xThW_9jYGF$L!~j>t z6IT#HMJHQ+=(n)=L^Q7)J|~wd;03c6&iJ8MUO)@dbW-u*q;PLDRtoV}lTl^bUj!Lb=gI<4TNL z?05f0WDsM(gh-R88AYBz};%DM#YZ>POk8Ub^8Nu}_lvdfozqi}q+&6r1TVACMJ4<4b=TJRAID3eEy}nHM?c`B9eF9u{bvzrGYM(QQ`f@-H|dO#*U?ZHxz@WV(f(s)=*NUag!i|(cSvfjLAv^6lh!Q z^Bg6xqGEn2v?K*7nKhv-(G!8<7nrGv)d9mK1_MdQG>RgrY7fk4(TH}niOGk#W{S9H zS#D>I{*d19_M6~KT$2&Pu+VG*N%KVKd!Z$c{DgZJ&mCJY^FAfc&e|63E92EWE4>`! z$CeIHCxSd*hl)cL`EbnPdJSC>GH;$vYYyFc`v!h!xfQDw@EYess@sjtKJMXjw_s%~ z>blr5x%G{2F4x6;O+0R75D=>7@V)cz94eN=Z7b+ZUCGq*Em55wuu2zUy5^Y8mY2S} z10v+5yW64?!=Pk7xZImC4QxvHqGUd3ub&FQl0)@*r^#n*@spd36d-yssH$CSXbYc^tTh$OPaYbSm-M zhhd1iF(v1YdgH6s?6?V*_zK*)cC36wEXsj+StKK8j4RS+$HinJ#}c?O($cbKNI8RS zD5A6gPFtq2+pR03{45u4q@tbAPo5l50j61-iT8z}Y~Fsl-K(o*GObDHdAVu+wM0qn z+bm6o?6}P@=I1%K7hh$V=2~19y!gPn@O3+vU9TBkRwMXUBQ6?wV#=3cEMGn9(WVk( z}!)RNH=eJ_BX14P1>Gpu<1PK67>CSB^tM{S$^ZAx-z?LObgY7^OkjVu^*T4ZL2FR z4brU0$Gm<Yvf6Nooi-qwz>pn{Iw=V zW9QQ>H-m$MYYy5It@7s0b_b3)MiS505fSffpRq~$_>IS{v|k=ARv2?VgBbXCZB+mM z=LC3CobZHwj+=P~(eX%mg8GZf5`MLbI@!e(=|>3HsHzX;+~RLGhel@S zp?ihMhThM~)1ih#=0w#Mt$gm~vVb&e8JsutRhNLBEJN0UpDpe&Ce~=g)%UFMhY@qI z>*TH0Hnz`qL9i`NaLfF8gflW0|TqS=|KbJu0aUX;FP04Mh56|63 zFUKO{&^-!m=;CYaS_En3u5pf`i#;d z3h&1dSSQ%}7#-_P%I{K)GN2dd-y2SEYrNk?xGhTGv9@HDTn`lQyGa;I)ISMWM`Nrz zs1N<|pr0gP;;+2O!wreA&qv=cBjevk#>En4E$ZX!loeC7(w8A*UL~CK7@FkdhG_OU zY7_G=1jd-((mKDD$UZS69VVtsv<5?yhZUWWIP8iOLHS|_AcQ4eVr``$ia#jUXK57x zNJAQ$JSr*j4aWVhkrJW7#pnT+q?m!wQ! zImG^y^R&QVREc61Ym(iIs&nLzb!MfsfKNdHwLF*;l8~!K!`~f&_$TCv-!w5AGCbka zjE#vhWigu)l#LSu+Pv}~@P)PN+($w+aPh|*Flv|F~Ina4c)hcbj>M9pL+e`39*7xlgl1f!)jFS+!nj#gm zYP2Br27b&z59jxNt1wl>$}PH1hmbg<9I(A9C_wZn-oN-xgb6Iw#4C5EY5*8Oh_||A zUaZ3`N0u)MLpp3_k5wQV?4KgkxcT5GiCDCXCXt+$3{K66L*wAlFh-C?7Q06l*dC>6 zw^JY6I99+vF^QR8QsUeFfjrK4Wz3)+s)pF<$3O2X$J*q&(5$ltl!Y1aixm@Q3Jjps za*d0dYC(pjYEY}NMOAxd=PWY2{1j_oKemI~Xo>L~gLxWr^};u;!rCE93!5e%-gSAe zGWVx=+bNe9jWeK?mbewpQ)zw>Tjt`;+=?K{<05R&6Vzg+Q&bk=wI!5zPu4}g9ske{ zV*ybM8bg+A#Yhj}hl5d-tn-=TB^^CjVOBPZDF++6EO;DI=*Mw7M(z65O_ z?xkKUY>P6MUqJq=XHq+nJ*Q;Ww5%q@6_pYvYct9{pCuX3ki4|s(GTkl_RkJ|cJE55 zB*)76Cj$b-$ysP@nS$-3(%8)`hO8IkP%}{H2!x1Hg;Vn>PfAP2v-f+Hqxd-<}xN-jN!6+9l zCK#9*hPi{Yk{dc|>*iiPOzEWz1ES2*C9d9g&2PpTt z?^|+@?O2pZ9*2;FL*-Oa^G#O-K*b@-ArR-CN7&k1Ij|Vmb3@rQY4)BfAcR!m( zh&=wwBp;}PdPbGho(ys0Nj0qX(-<2u`oYlJp60595Z4S?w#0v)7oqAw!P7)T@FEI2 z$d4?_lBQdg$ZfHc$VS9H>gYp!$+?Jmw$L|!WMHLO%rc9}|(YO6-|o$0-BCm2o{rL#@9I#R+Al_?lNtlq&Yza z+l3E~xX~$ip96Q>bRq_I;-((vNFJNct%6D_L}1?gQM0Q|n7lx+Ic~G;`ke$UA}N}r zG#SB5xU(idv33Yu^c)G9V0;nCYV>c2)zh4i0kjvmo=m&n`Z5ZzsF5^qzSFHO4;+)C zZ}Rlla!eM}=H{^hBSspDC&d~VzAHz^bTNYNps%!WqL(FM9$K2wF4=H;=Uqidy&0HN zyhO4hd0H&=Jv3Ox$$+v!Xy})R-boW+X^4W6)qo}yl`h??jz$iAtg5>p;XGzxt?HYT zo2cu@mzX}&KRmN0lPz>A>waHQJ0_2{u zj4@a2qMK+-&z2cEpp;8pouwGPai}3-)oQJoiny5xM2Ag=xohum0n+m|fFq~R+u26s z)a8Srr6lXa7}0Zq{ns7y9SBGZiD8o}Tqt!t19dW-scMssF&N!Ab{Q1HTlT`@lE}(& zg+^!v2Px(gWw|2jb@p#2;&QyTUMk{xJmXb$CpjjnLFgJN&D*#o%4(zEEH7UJMmuM))beb24`;&40fB$O-YQ}&0`jEVF&Sy#A z*D&XvtM-j$hE%F|o{^iODz^Pzv6ylD$91L1`WMkmn7q(MHCtB4oSby&BUBZkmF#hZ zm^Qsge^o6iuSGCF5o0j5`?V1x63j1NLMo{gV$Q4Iax5tV1QWtfp~#pcu>zcVL|3v2 z&WZ^=xq0Oe-*3pIc>xWoRajj&mCOy9_xls{jbj^jcjXAR%lyO=+m@DdP(4Do)VeS45U5g1a z*etch_o2}&LLe?|y}*4=x^9><3u+TBEfqn0a(0aZN$CLdHx8!=O^wzmPP%B570o!) zEpW$Y`2>wr?{}fJJSOD&FF5)Pi?)?z)k(wN(p)3Yzki=Bv~E6e9MRG#Vx=oX(T*{O z+ZuX88O!O=*bur);}e8@tHG%M!Yeyq91SE8VP7=&_t!q=m3-rWe{=m&4cwTqy2)Xk z&}Q_0$@CrTU7&@TVr0{PlV_!GO%02}0KoV008*j05~pszPc*X_G94vra_$plsh~k^ zF?Y{re2#7QY{H$oYBd~PXk9QRE0-ln582vSRbyw3z2VzUet4e5U3PS)!>J;yWEC)q zwzgpulK#Z+o-4srL2p`_ha;cS@l)FGqxBDs_R1~tmoM3`W~Y+&Nf7eqHmM|Lr};=? zm|=U$eRCoH=@c*24@8I~rXs1-Y^zp_TL+(t?-gCBN^Uxm48dlG@@v8bjr_ zx7)Zne7V<}#IEa2{6ZPyd-K~;p}GIlkKpIhgJe;H@tN5ekZwy}$0he$%t%$lDrgUk zWG5uRG(w09ZKs(;x}nQzKsUN@USr<55D&Xc+XS!*i`vbT?y0JdRzJFHk2$tMoKDh? zlU6RkBfS0=0lOS}10tFFYGurt8#lP+uwO2gXAj4f7IC9)Pf}E6yT5!|*MqLP3<^dr z>PXU9dO}-0TP=1B8AH527F~(>z-6o0q@w7Q@96e}Ki~F`b=%d5Ii*-6HU}y_-$9?b+qd~F; za`<9G;5b!a+mu`2hOkz`(r5f70)&Z4WxP9~=vr#XFn-gSj~A*48TRk~ud@IKJm9VE z$ok%Y8hiy{_wTwseF|#d|9|_DThIUFo(~Xao|KktNmWVYftz9=HR=d3>o>b~I%r}%(SjP29UmYNe@isBI+i0paA=H8 z2N55`KI|H&&6cJeEx#&&Cr3EefXR`?)SgZQV(byElV=oH?>MsQRMhX-F8N{z^xx$W zO13<{)w@@DF2|93f2!~gf2Oy_)kw~ALjT?O_SM$>Blq;kIc)TLKdo}}jAo`kD>{1j zauWbGN$AGIaQ@)Q_hW2~Z%LOwm>B~@DgeO+GW1zXhUP{?dqU=%YMv4j!NnpVVu%CD zVUJiErbdl%M8iTBegk3^Rsfkyx*??S?Y(9^&|gQFQ3ZzaMA>Q(WaXObQmk_qsg8>J zu_5blZf#zY%36pq)hwbbpoQeKfMbu#^8V}cYxBP{X$8e}__8{_KC>F}gF+Uz#-23FuD-xXwvWvnmTeZ`nxvTn=CN z6)>AW`tSE%T)7Hc2KUmt@e4Kd7U{wceYo-lCYTI`m<(c?+DILACWvMZ-ebMLPOb` zs};e3V?_O~KF~|`;_V&(dz&@-`*YlY`0&X88h?zinmck~%wT56CDH#V`hIJB=e}~L zy&WrV+U|>|ubNbW?w7UP-^K4OhNDd6vGToe{MFn&Fh63Gts9$m6lA){nPzj%$&N3Z3~K%6WK19 z)SYG_sxe%kP|y^~5V$%kqRjpwDH&?4cl3pjeW$X~iOHdns-)h=s40%|DWqHuGaU4> zZ9F&IO9wCCqn`GY=m1fZg*m+N*G1gK0W9klPNct7j`B2nl5bYcGXh5l-h>d7+A760 zZpx_*dTMCFV`pj*l+G0rGJup?=egab<6Ppej<)Jaqt%tr8GmVF2H}>7f0_Z>Ofwc~ zYd*QMf6>Z{a_R^e^-0MK$>6K~`4Z_{+H%IP^$UwqaFr`!NC8d9Sa({m!HmiXRPo1! ztk#ACT45M$(3~uo`l%=oJMc(2kPF-k-~xCf-VeO0(1;YpU?G480rW!M`$Q&vXC5tv z#8Gl5i5CnXv3a<*kV>|z2#9R@Necy}aSm9T&0c30Iu`F20_QvVwg-8p8~Oa)*Nsz% zM-nUT>yYL|SmB>Je~p^~y#yk7;- z^JqJZecj$&*jJzhGT(T+TWAch`X~Do9KzZjlXwPU((@1g{(al&e36rjur3caA8raX z_cZSAGVnSVfAn#p6p)AYD~PnDyD55dQW+n#j*e7qM^n2L!exTt(pbIe;xA*Z$?|9J z$3a|4Z(5W04iU@f@x*~BW{3F(WM!&T`ON2-M*mx1wN>Ot0T%}8t_M>Czv<&c?Vw_~ zp9J^4g_qvvkK%+3|Lytp9HNIIrAZFjnqeta4M4e4YGY5qLi3-b@H3dBtZxI5$+$h} zq$pt|JbXsyZt!^$yI0_-NwPi#aW(m~oO$~UexT$2Z?9tLhd`lVLX|j~jU#h?LJ=0c z%GNwMw~xUeg552K*0*Kd;?784@2fM5W{%v}(;aJ|2aX^t=g=oPobA~W zWUAF~9>UaE&c!h5=4CF&8%O>1DVDzeTwY;lC8B&tS;JB8k_%A+&-qr z%~@k-S2LC^voq{rXTlQhuxLSrJU2{FHYejy^js8 zTc;qirf%YCyz$lB>yQ4KHKWda_r9H*h3R!4{>vf2%uKu8YJFt$qq~Q%Cp+xv<;~6Z z_FWthvs5@&^Ry(zJpIT0L(;*S1x@?EK8mYwZ6YZKM%fNL;=9!{<2``U~%F?+QFGKG3GhGN-;B z8sTP)YWpt>cEVLxsmEae?#|Zkz#Xh(%yLJZjV;gs2(`H1kB;!QUdGirXkJL{m_-seyR%=$B#<)*OnerkNM-7#9z{qcHN$Mt#A z|Ezhuy6Xl%B+O0zfdl>$eht*|bVBu5Wj{B~iWt9hXiIK3nM7*gRXPz?f2^ZhfD-HC zbLdxOau&qjjqAD(cx?PyBb4{iBOu{y7jj~F%sVl~<;|B;h^5sw?Xsu2Y%KX?H=P!j zWw!0IqzNZlMCeJBYAjsRpvq@AMK|zvJ*48yqD`(f1J`ByT0W`eqsrBx$KsZrMi0}? zr0}(yZ#${+wTav>>>IGWn)lgpm}vgkBpO}|L@59Jj{4=z7 zc(PPi(3km|oTq|#9$iJy_ja`S%_Fb#@cIDcTbf`X;mW$oFb?{1-p_k>lJljaeCJd! zNjTy02lx@{gUH1fdg5Gepfu+(JFLk)Kvdjg>f_ixi_A5_t-a=}PunjvuW|LON3NHe z`y;P=3Hk0J4}<#|tZsuSi(psz&pKq9K)Yut(waCUOkemb!nK#g0*Ba*#fr3@pw6jOqmXz zd0eULDNP(n;ga%Ggg6s@DI08(cW-m*v;%19>dk2TA_w)|kG{R)x)YKL&X$2pMNfWQ zptiNY{=bLA^EN?x-kj2G@Zn~ylg@8|x~Ngvgk=>SB$zxcpA;S{;uZKtrKHwhFi!8k zx3?EZded*X^E-)%hpm5eGb5=~FMc`B>$I&uj+ueV#Ff zwnISTHYt)|ibDS=EzC5k$0HXMI)ZMgrzu;G&es$Zo-wl8pa)3LI@k%MbwajV^2%%L zf0a~Gi&Fh5NO@Mp?K$}l5v1;e!B4UDs|t82*BoXY3$q2zBpl89z*0vcCkt6#a4hsR z*$LGN$PXSC)rozVOx{vju~1PhHmO=P0leadk|mf)HUFJ%lF1Zm{|!pgjP~Zw?&KW% zYe|Hjg^6@CfT%jI5;0 zIe;CSQvXz}1{G>MU$oMKITNROxLE}muPn}anG%;mp$yd&nPjW^Om;BS1bLZk+W!Q+ zpw_5hTn*zBhmH<(+S=g}q+`dKn>m^A)$!tw(QPbZrAwzl7$JK3*D6p$z1#Dd-5pQt zyM~EC!5;4g#Lmu`j9)!1fr6^D4iVbE%gbWyt4(%e?Vi@-jC03(35z?7qjiIU1kSl< z!?b*bR3mEcA)o7rmXyeAF6@B@)(z5jjU)AqRXbQ((`vQJ^?jAhseLZ>7e|BjH|1|j z)$7?$Rk^p-7K_-vjZP+FicAY7%duY_S-^s;9Kr~l)^x6l)7I?yNcvsPsw<8DF*lbc zsDQoPWya-NE<-FpPMUsdsgLfs>qwM~;crXaapdJZz3L~f*j9$cZX-}iK(R|S>TM58 z+Y;G7v7rCbKN)jyrW@UOEvg(J;tjMf@HS{APwGu;o7}`)_bYP7W zymVe{~`PMzOtMn*;x;G;NEVLs`Jk;KE@) zsL$Vt3f>?KJ)TCztcH2b?98+hBzB|+8pfFMl)cVmV82al zjr88IPl~Z}2HvoAEg^;CS>6jU{VI(E1-DrM@Rs2pX<4N{3P z^xNWpAsWKMXlK0RW-Mr%EJ7k_%;wxkB{$U<{dbxdM6GFSXjemID;kYiAkziHYoZiU z=yRSC7RV|@z)mSpA}h^%Qr(%8-0MBz^@LOl<=X~Swf&RP%E(18L@ANxol6Rm#?2&W>6UubwKWhp%_5+gj^ zqYD%4T~@uu%7o`f&M0_^2^e2PNCh2_8+f)th}Vo?lST?hP!oQ<(eCW0zLd5;^TNMb zwQA-L`?U{8Eq?9)=!No#AgsY|gx@CP#{ZIVO$)9`-wP5`5tZ|dNlYNjlG8*S@e+e@ z;F23c9N(7y`Sv;wUBZJ=`OW#%^!!vzHa?W1YnhfNAjUdpskLl{>mK@_O<9qJ z8m?qw*o41Oq8$hi3rrasB=V7lQHwHSs5zU4h{`mLc*`EBw$zZerXYjoxzEkkx8j!- zcCXxgoO^sd(u}Mg^QmSx1{B)<>?RFI3$px*9kW9YCz4paSxzLCg2?7Kq zzbVX_73n`l*R(N1B9jwBL{F@2c2roqm0)D z7MLWR40!EDwl_MBu`p>L@_LgiDtPb)zsODwFPD;+VRchJwfCLipbv~R1P|KMBU@dX zv_lo}&(KilQ)p}ag8*Rwd#nSwJ_|=;=}&gk9U?2FvnDYI$DwRL8NTuT=B7A2T9t54 z{6gmMlykwk)Ez)*K?&1n+CqaOC15b3DmBn|yna6k1U@$^>9E2_DcDX8j@5)1xLye_ z>Lut}|_lghSZh1QDvnV{cl}6PDEHq!iL&l2lTP__h!^j^j6WV2n(GdV-#{MsSeYeCFa@ zE4-665V`3PY`-DZcpAyV2hN=h#=zxoCiC*$18y#Rylh;#j?9kuU?}jfReme}bJ8=X8H!%1Pqzj|KU;2?|?! z8}ktNsN*^0e}k<~OgR_YI|tZq~t!T?aM*p3&AsFpr_F@@z=8_5IXR`lV$Bh{hw{SW1hgyFW}`) zXyA+9*WBgdYyJ!IS0Q)$?$3Jy5ZadUd&l=qvVR1-HyHR`9r!}@)w+97zxzt$_xQOJ zdi!4pwZaR;LPq{~kv}(xSIGIVdQW5bk>4@E`)0#f;ebWGBjJG6%}wEepXrNG;s1D) zMPdJ)%cthu|3Yc}g_IBM{PmR&Ed7zqhZFv+;s(z4edhl!7{m9+Qy{d_^XUEQtq;S? z>8-EP`y{c?;?I8rio&1c>VVjvbN?6S-6uW2&CSlAo7tECpN+sf_k=T{A5%wy{J@pK zyVD&@;h!e%&e{GO)SuJcC*rSO?mx4iv0v}Vg0PPx<-Ozn^VE^dLbr%lv5r2u0r&Qf z#eHXiFOx#If$xz!^hNHK*;QE7zs;-6x*UNg-dq_xA75{@4D8 zg!&I;pM%HAz?aW6x$pXq#h;7jfY|=8*4MrIUT42&_gi|S=aCVk{;SrvkHtK^?BcI!l9%8(rbI)U!Y!~;P;DvLekH-y(8?;{OM+(-$(g( z=_iq2368nOG7S8??_FLcFB!)|7a{37z6W7L`oO(^+kagJD;t%F^9#AQ$sz;+$ zR6l)~k13S<;Nq)IoobkeOaL&CRR+`L%QghFDx~6G?fK+5^SB2rW#zJ1NLg!ouCD}S z402^5X~j?Z=-M-kM$>L&Lx3M zY@;ffP(Gzg={3*G63McRKYbZ$?(=f_rneGk&dEUCTD)pWpVAq*cicyx7mB*_exTFEk6)N@ zhNGewwUpt>U<(IFAGXY_J)EH=YDQS%(G)AVr@+tZ9XyRo3pTqL+<}PAP?(ya7n5^P z?mcGG(c5ypLA9Yzj!3+@SWMqcJ#cI2s8D-V$)5pwL5zLPIeRhLG$8PS-XA|Z8zi(= zQgw|yuVGx+9gq0fXB|fEjRM*Fl~-Q0ClAg+T6Ts06Q&RyH$yn53DVqu2lxrA2aHB{Kb7hW20CRohcQ#TBCJeua|c|~%{SOIhYZar z^&c=LjH)P#llAP;s1qs*EoP94r3(*DVz6%o+?o(pOZ3dN9!K!(a)s zMY@N~qO0^|^5VpcHjB7iomoko9n`k+`LNik#WMtw@(4-|XTf-lu`l5f>t18MtipRqt z)L8YTHDP|iAof)lay|dPtwd7}9^@O)JC4NeT_fgI1 z90Z-k$_4F1U9}XCn&`n9mnH}Xa}?@_Xa%AF59+c>Nr5O(o2V{_m+=GjY$0kbIjo~s z$d=`sS^o}Yn(C+@+ULStVRq*+Dv01ucq*>NsN{X;8VeW>)2COg5iI+Qpr$OuFZN)< zocb54bBIJ6K%+70+Cwppg%7SOqf#l#O0_79Qr5_sr4?hPQ&%-O#Y5817p}f&98$Gp zUKylI3GS?1H9SsfQJ`+Z2q|q)CNja{b&1;;l${WC8ET3JX7H;PJiJ1Sjg3^g6DI@1 zm}kVvi()MV0Wauj*+?=hiZJF}; zDpOE5=O$_ZYHI}6T=>;gZED)D9iLcD?KzCK4}%a2_b{dtej;HX#s~}uO{U7OlbwVP zsEWFX?pxV%c)&ox{jHFX=%|1UD=H3#y&)Oa5}wzubC6FFKadgj-yUUkB>XD7!gby9 zR!%h@D^B}twQSo;*m4bK+)hjWSI@r|xH0;diCCbR-VPC0$zq$eK5cNl4WausQ*hRN z4b!{74?#GOh+{*c{eVAgjeX)n*!`=^wTlolo2{MoCsfL-?HCL1LLPR)96G@O~quQ7#LGrH{k zUf3YIXK~4ZOAr0xZR>KyDWiFOxgJO$;=UVR1kLC@yL^8jU2-S&_);?r!Tq|pPQS}C zT)qB=Iq>iLxviUJv(>BkpDuq#3cJ6}Rz`F5(~R0Gz?8SZ1aO@56w~1dEMjTn0k!$EbJ1 z(DS?9%D#}MLWTHrEj(q_pG9le(;=njp04SmBArL}BNLs@K;&CKYIT1skyqZqh_yQE6Dl}X+6Z2s zlGd%t2gZ$)fryC!J+&T5v&r77cb4!uYGtJKpiU(3xeHocU_P9Vwe*m?_y}pJnqZ)s zkjww9eSaQeL=}oCgdc_LRA{Lo^CyP8xpu&+3T*07_E#NCKS1cF5Q3VWyJve}cdqTN zIV}#yp@O!xfrYzL@%es&F zr|aX$Nb4vo+V-KodiU#+4uN{V&kJ?zP=(;9C#p|`Uy`qXmh$Qf(c%@#em>~%H41TT zvREZ__3{RkYiBuk7IlVV83j(5O@Q%k0dW;7+CE!jfI2 z2wFL7W?1OX5dCG|+Ksyl`VU@;P*yoq+J~q9rKwrN5N(j2@k5K3b<1X&0 zK*t~z@~zY`hc)%emp-)(SovQLms>uAImy@`#yj5ypq;nwAHUDryNBfvUo}gi=4g0# z(RHqlrt7m+qB@&QGkU|@>LkqF|EQu%IJEEb|LBMJaaN$H9 z-jSdUt3)L~NG-~OOfzc+PUkuD|Do(IgCcvr1YzUu?(Xi^I1LSjTjB2R-nhFo?pC{JmP zYbg>X%1w>iKTCw9t=k9=vAg>+J??T^J_svX(>@Cm6-j?DX!N3Dr zN4CiZ$>6t)=HWQTgQVXk4c1CR7L=OuB*GB!ofe@a*UuKUAj3Do+3KgUpT_RH@U7rz z$%|;h{kc{_9Ksc*DZYyD5ST0p#@)1_ONV~wXqO71n)mhyJt9w{c;wc)~JV;OS=M%LoWm~bt#LOS?BRQ_7+aJWqssA#z}o6%Qr z_eq#Gs23h;g@$pCaDb;dgM(K&D_Ar?BHoGCg~%R+Wx1<+7gI&Kp$~(Fp^uA$N7!6{ z&!A6IziYy0QUSc?qT$fjlfjw#7AiNC47v1W10ck`cVGXp_bU*+P|%K2bI8HW<6VTO_WA?TnNBHXtj&b{6`65a0b zc|div@wAGM3lG1F)|(7;8;&nFtt)^02(!b6b{Q7An%l%24blx~s?!bhHc7#IN|>OI z7^?AT78zA$pzVtJL+cc+2sL7cz_!#hyI6vOS%zf^gfj_6)9T+l%2%1-*y;dOY}bvuBYb~pZSO=o>C{@U-Czf)d`VZfe4?&Mpcrc>;0_$`#rBTmllWf7j_ z@or^>XE$BkJ6=Vf;AbTBu19ZFqK>t6InwRj1?_LPxYj*XiGS*8z_-wR^NnEhNvO4W zv_Hw#s_i_60%p=P_y3U-TRFli4xMLM0dJyFqRV94qn?vwrHADS+by{MHtO$wncQQQ zod50Y*F-g?3V*s8+jpj~Kx*G|w6pHvUuMKHwVG^id+{S)Hp|<(Prn4a8cb>D?vr?y zZ4`4=KbCV8X{^k4Jo$$wiKtMq>JNg{Md1m;NCUL?Qt|o~Wox>Ic=fE+=HwzAryU`y z#Y4IBRlXr{^(vy(_2u&z+b1Cab3Y@_Q3&iL7A<;H-8#g#Gs0e-FdeVT`T_L_AslcP zpGgry0nC)y>jcuajKEdVkh|5T{|Ql^?Ac#-Znm>t-B7xF3qoeUv(ThviyE2Z9fTxoO1E+#Oro7 za}H6W=8>@Lm!3R>>qqXhy?hHdT5pY>u^fCRUBTxud#qRc#zRAhjvVfukokfkgn=2X zbe(9!=v#(733tMAcO! zP?B}g4;3ouK$EhC>}WJpFb`|a63lj(%R)8@jrhAw+V_hPH}P6XeuR8$T9WRJd?%&Y zt3j$LAG0)6E^K8RF>cfF7t7!a`)SpDjK$gqo9$pFh=$%seNC5~+SyI1Hg5}7r@FU! z3b4HJqJ_Erw$26yBJD0etT0KS;SL6}jyC7I9H$V7^I(#2D82XB&*d~=2$LG2K%WW) zQez{>A0O;sF!e9WDil>+-s>mN+EnO~>WOSAeXroT)wrdz)#lH~{6 z(PmtT1G#nwTw#xXvlDObrsMMhEgQ3n8)~$ z8rQ$oHn~Gok_i~3%T|#{fOi|a54)V#Do`Ukp(IL5+n=;kOmjwvfsO72au^3FL1^t4 z=}RABJTV$rVh%khR=28rT)xjxz_U-3I28Ub+2satQ~j_n5yA#yfMJd;w4@}! z9J`P0ji{}*_@~$9IqjJ$i6Lab{2t_p0YKC)|ChF82zwnVvGfXiWtTG$jIhlXjw>s` zUKzHIG>u)>QZE5@Vn;_lWddUXT%U$t4Ey=K{YlC@V07SvIz(l^Kt|2yg(;f1)_U}a zMlQ0TmNUJ5PK^Af^R7dPEkh?umU)_zp(W5-8d!%%|2$kc!445=f}dfE2NyPEVgz%^ z91i6s+Kw>`lfKFc?TK7i)w>kE#W!urH;!3PyS;Hj^D!s$L6V+OedkSEus_P}0scF! zY*`YwXr8_>ITT81U90x`_fGw{*?4$OEJLnhutk+=+A38UO%zW=BMYj=Lfm|3IpYbW zDWpo~{%ckkM7Jap9z)hDI%GUFQ;{kXyRtA4*n23_?-0+b#(-VXC+e2-kSQiij`t3X z8|SgXXF4xF)Hdd>w&j(}G2qKZ^oI+YEeme)5k}#Rg`g;kIF35buoZT;YsfrRx3_4= z*~qB4-gKB7Iy6}A=T^D65VqjALzXmjN|++-v9xP8GeffmB#haeFDdM*=|qO2KiX4R z?sfnrouXA?h7yA~ruQ;#j=Cr#!&V$Cb~-cV3WzZ9R-P;6<=rX_PWn>L==7SLe+L(* z5T%!&i@V$y`rV6ulQR2UNzi*7(bO)KFhveE4GdSHeRt+T0J4y)PH=`llSI>!FoM`L zB>H#8;OP6k1D4<&pt>VMw$g*^e+?%xp*uu6L#d)BVDyV7?|&q@Ev7jpN6hr8P^k3D z)kW?13hwx?lcefwa_;NaDb=BSLsGzM~YdNgb|$i*el@80eN&ZgN*N3YtK#7aELx5N<>ZqM;s!R z0%}S=5Ef!?XoFC^C{7T3b#;X@7a@DM?hGT|H*&#34+{n86pLmjnS$Jtwwi4@iTu65K0Y}T%?M3->#?6Eh#%7fW`Qi4<7%aLn?GY$pv4W$l`N!?8P~{y+l6;nl63K9`-7Z%lHH zgs~!2$&Q^UKjYMukYPrl_tx=ivO|l(NCYn9`g~%zzsMS{S$D)B^IqpUfvrPYOWHA` zyDgXTh|35)o?tS?ASZ-9s=qqT z?gm0MEPE*(m;%3=w6zYZ4n^WDCXmG(mA%x{jNjHvNAN;`7`QzyEtBkPnb>!zJe$f2 z?9e+^mx!t~3KPl1{byQn=s7vRqOg@GUzH%d>!8=JfqE#uc^J?(_K?G&Tly z_*kY4npt#mlIymfCoda#N0h8BF2Hm*TGkf=Rw1*$Qa`)rn7q3KBOqg5RL2B1r;50& zF-)eT{T%2$IzgM1$x_?5pndDXTGx5{_ihX0&D40MHIK8_I7VQXT(X*~&AReHojX*q zfv!w<%jk*5g1FaPmUpN@y9QXmV3x+y!tTYHMkDWux~zRIL9Qj;YU$jb5~(epwv27_ zZBDa<_q5z?WL>(avkDFbxCM+9)w#GP(V>7al9K+UD-1OmpJ@t$xH9BKYp%h*?gqmE zbmtM;a~0<8Qgrso>CF1UrOzlz6vVIn&JDVoqutICz9bd;Ap0mTNQFwnbftW-)!I~H z_k(PRHT1h#gnJvDse(WRRQ7v6g01C?G+yymlL0jfbPBeD9|4kwO(L)nHJ|H~*V7F8 zKANK+3i(R|zxcIT3SoaiCdJK%^x?}f!Evw7G1-hmi;A7(Io9u&02%6&aNveVOzR7U zMO{=SO}YdOx)d(Lj;W`=Y*%ozLro-%x_z6)H^xxZ?J-;a9n1TI3P-*w^yH;TdBEaS?T)RO|=QjaXQUpf2KF%?&Fu?(kN*=rh)X zZxEIKTDTo95T)b7})O+P?y0*rvznqM*M@FY}Roso!IS}9H&CvDD?muRf>Am2E9?Z*RL;A^CJPQW=!sLa zPDe-I?d^57@v*Y}H_Z@0jfVp_m&lv|yFnof)m%Ul*F<4(B$GN%G4ov=I1-&zIXXmB zks&2ps2KvG1U0Flmw|0-^o4uUa9Vi`h0T|40(uC-v=lh3~$`C;x?m_Qoor8D8_=LOk?+&tRm z+5Y6}Bx3Mu2KVW1=Uid5@#zW@csA3Z?7 zjj@Bh*ycax)EmiSzfes25G&qylX<leUQ{xp=Sy!V$thKQe-iJVy z*Ws;o60DDTGXfZ(mAW;8R2}m9{Opza_65u7tZE3i3A79LZU$X}tQ}EL!B%7p^@6Wl z6@=U&Hn=*B;pa5z({c1HQgvCFy#y?XRt#oul1ow4lvX4kL4KE3JA?K4@?Nf?VDxT# zXKioUR7uv?wQ2nHduGJVE;J0sTxn~=TA1m9ORscu%El4K80LHWrlLD0xhB9Z>SS`; zlMKD){*H}7H=yty@#~N+pZscA*KFR1^7y9d>SVe8TM&kZz!z+xP3F^~rmPjqk5&|S zFO%cc_e+Nj+M>m-)CDLhWvz`NH~~9>h9mcw-jEy9+?hJ}R~+wO(*7dI--=Ey3(iTT z7lvq?={5w)I`T&m*jYt4vt2dp!|iJiIFH3@&W@yh*W=1%To=!?VKN?bsep&3%6&7QU`o z5aQuM(Es##42W14O8#sw2R7J9L8lq>&vIoL7U6cII!JW?WPB;M!W?FQ$YYjmYL36V zc8BxXO|K}7*LZP>cUu-8xfmH`jGk@Ts;3@V6OVo;QR%Av&8dqq^fH}YFuQ`b({Mtx z>emux$kY52hq->>BkpZH$-c2A&-Zx@dBI?yY^s^>DLG^BZ>DA8QrD!KhN|77qE9lS z2^Lo{ye0~iZ80W(9Yk1}fLty+C}Ndv<`JCPn0)772mMitfk60KlEXLq#}jBNv2>XE z)g&@T)vl%_ZO6p3$0h@MrDI6swZQHs^jTCK2D%^>Vw^Wy^*^#pJ(jH%qNP`4l@8YE z*(F9CT{_*X{zQ#aXNCS9WnEgT8^`Yt5V!UR8Ggys`NBVkbN`Q=|XhJpxh6kP|fJ? z+LNXnJq~!m#LN!U$~up82lA9=Hn>xtr?)LAMCrfc=c6bawIHNN;65!8Ua(6u`VfA| zQr3zi_c#H8_k7qkj!mjA`thOOtd#uQSM3R-%bdJS;?r~WMJ7W#t`Rq zVF?2{tv=tb%)OqiyjDvyhSV*iYR_gPyzzKV_TbC?@|!MEima+LzG~1=H8Y~PG+ynVccbQ!htH<lP0l%l-ng9lsm@IrCbZE74D87hQ*UkTG~^v2L$& z;7bZGn`cnuGAvuF^(}nn2;%O`h$c$EJ)(Tdpalo&0ZIbd?RY*jBOcj$zqCz72S3(dzmiov^0-ETocS;@X!n}GfMRU zw&i1SN_z=qy0g`M2HV zCmYe6ua67qc)gj=I0sP`8WSE)8@8NgQb_*?J-v~P7Nt1Z&tS#$M}p2wZrKSsGZz=fgsP9omn z3#LD*fAtzPgpVLV;>^_wZzSSi3k|JBZ~z14(f(mok)y4&w6oZ5P%w!g!{{tms~zuG z&u!{+gNG*ms26lJZfp#@3KuBORp=KN< z=X1CciffB_4Hz8`Nzam8>XAlDo-)g7sKUCC+k_-o(TGfpZ{0Ed{+cw0Qi#_=Yo?@y zVoh4^)y~(&NyZweb+O6@sRk2_rbbx(_v~9~UzZXP!I~T3^x|V9(P$PS1%iDMiG%p) zXZfMv>$P9$vOHJE6dC!N@sJGXF=DmB$6vof^nf-A=Dd>%n29WFuiu!mP9{)VJx7Tq zD6PKh5K&A(fI|KP*s##&f%y`?t8Q^-eJyDZj$S9To_R$bVBq`|uahAu*_PuiOjC`Qq1SUM%?+kTr-6W*7l z*poR!9m&`W$ORrVNe`MIvlMeLGZ!}I0KAH3;b_;QtdXSD2DF*QoJ(e=J;4&lah@TV z-G^;Gji(QMMt;nR6WkRNFOnNhhi?vBI5ym^?*lRj`&>D?Uqt9(%f7v9quzwJUe-_r zA7Fee!IUnA4XgG(?*m%Tq$)0&9)D4)H3SGa+cl^YOjk0FOmbhx+Hl!b2jM4pD;Ifq zonP;bC_(twYA7B;|6#i#Ek)C`l9^rh>+7FPPh_2y;9F?1fZbga^K?hcB@X!?o2o=1 zuhTUy5pJp*Gj}VdN;Ok~nXnV?&$o;wTr0non6WO;KbJ+0JjwG$4A0}wYATj?5bh;m z((Tu&v>+vx9#i#4Q_f3yJE7<)IqwX(#%~>Po88V#;i#mUm23Vpn4H``wWl1uorf^{ zqF>^0?R}hy951p?sXO%iHor3uMGN-yc6&lK#$Bhmqv1BMdCpaexHrq1Hn(Aj59Y4s zZj36Lu~*n%#x*{Zs-LcoJ*I~b4i zwNAED6KYl-APHFzJ+PaGI20ZwaG-m2vu6Ux8OpgEXCN* zaiBmO8}Iu)`gP*z_H8wug3nN@fU|cD37*M+XZcO#H=^6BpFMbM6@QnJig94HQ{7&! zwm8!-QFtpcV-H0q>LuBgUioQz8$XiGZY|BL%K{po60H#bc#=~uk6z@X#~T0BraFob zt(>dJx+BiH}4e^tamMC(Jq?UFx$?eQ(-BoXcQGE(y41??|9rjSviasz(S#8 zw~Ok?)47Jr-+!D`v|EwF&CQuZiq(Jy^O%sFA+RopkcRP!_mE(6!{Kw=*-@f6e_IMt z^3P|8>O6Q+k`E+JfGDiT&|I0s3;UA4=p8DwEn<{|^7-t+~&!vmp{e;Yajz+1VpY!<}d3n(x z>)Q*s0s~&QJ;Qp42)Yvt=g}QF;Xx46$AnKnZWKgLr;c$AXKjM_1=~RQ_22=YufQFFfP)7YWGJFro zKfBtwCldGVB=;) zjD*5QpaLxf7A$X!i;OW^atl^{6jV7VZcm`bFC{}_d%%rs~w z5@iv8gs2U=jpYk|0I&^ZylK|)(_`X-V?i1laOo3AAs{v!Fe4P%>VxM)2^P55bZ!&O;6kQy^ zYjh;5$Cw`3(*8_&?_=TN;`q|3-$O9EK}Uu5H8Oh6PA{%uxAon|Tg`(=Yq_Tm)vJYH zQ89281%KEt-=00-;r_Bec6$R=j;YI9&(t2Z!mWR(bTIU+*9%R~)}U31-a!)WqoPwm z>Co=b;^m6Ro z`qjx-=CSn7r{Hy>?ZF^;HOLkoj7-Py+mX1+`s(uKHMT^4_Gf8M(wX&@-Jspxxb|Sv zTS2`vF#ppqiRKaO!a?nIjj@ObS@lPW`E3?i#o5J?xC&UuKX>0*-oDa%d| zEe>2pfG?kTcpdhf94jsh$}cSZ`rXCcGY);wBr@=#`)E${luy4lU$sCdxL~L291vnE zY|_O!{N;bWywb64RsH%_pRu)xo!Kshm+*Xemy7225NllWfZ`ZQ{l%Lyi!I%k`?zC z=IV)Qu0sv$cK$PH<z8L8l4_%r==|cF}mEY?|DoTam3utkw{d9d~t8J|5;-R^{I+?v``?XrmrdC+( z0up)stOo^d^jkiG-R<|fhVBPf zhYdhH#hs6n_M$&WG3~M?!9F8=oWPPn**T-J6qG%#0Hyr=`bv+4@Kne9S?fTqS9u|W z%iKomq9Y3ybL=R4@NNG6=qpDnOXZv%eKSBp~H4HvWWr0-L?yvkMdK>4k2oiVks z2s~!yC{L}j!oQ5dd11k>a6>woU<8ERQXDQn)G>}_?Fqk%dUnRc%}Vm07ZEo#ROE%% zi=t@4=UaK)X~P?>bbm=dkqC&KQLO-Qij8{D{79(lw$qiwAh)!H8L3pEE*jsWxA2VV zvij*kkhBAa^wp)4Q)UNzD1(DE0l4bci$V=4hR>7Asr{VrJtbCNSyOdj377zW$>PU7 z#`ukLw2x*)-T7;Ccp)u0qzg6ouD6GyVNJ+k_6@2YhwWOYgbV}?3sjs_$t`|57@I7d zV*8W4M-iwKktiTgPhe#z3Vi~4X)B@xVJ@2r0a}gFa94p$^qLV*FT2c*Y$q`NRQ>Kb zbxDK>($K>aR8AjT4DVjql;Ks(m~x=maqIMwo3uiwIgjKVCfmO1A5z>X}a?qkUJ{^;L2CAh0|c+ zI92>afojOUm3pl<$d2z$^s5i<_a!#2dIDmtQ?T}cdkLKsD}5-D&9`iOz)9KKnAJx@ z-eWWZ@|C4?-XcuY_8LYwF+n>Jkr1L%YXg}ruCFI3m&=N((t4(mN!^Cf{-465Ae}=NKh)xu zXRKqU0r!&9&`n`*A!btXZanU`XSfqNi7)fBhT)2$5)-tVtjaWY{Qd$93vu^cs~4($ z71%x9;8mwzo^tb&Te7{ofmBOoq`GcHPTxN4$9H-~tO->HMr7;=QTO$Qno|lxLC!~0 zGZxl9=!-2UG1p6~IzA9iB~59fR#|b(20|dW-&hvnJ|7`1Cu9%J7}{Br?%XpDJ~zdW zUu9i}jILyFfVTX_LON+*7G?)fcwwW0x0FBY3oLxIehg%xJ}kW0cAN7iWHB$NcSF9u zot28u+VL(B^M3kys;_y`^ulX*>blhFaC>H&X@Ao)r-vuhmL+-lu6K8Lg#**;s&t?U zGEqsvo>UL9C=3D8>-e>E1B?buKR=f_*>N3KQ=l!;I`u`$3y((0eKMPfdZRI{T8coNv7;NA4xbQ)=y(T#r95ul4LoA;(toT=&Ukg?93VBu_&QRx zwwLZRlD7+G_Sc+jd$Fn83#WYHR=;Ir1Am*f4qsFp;3PCDq<4RlN8snpKRLjdWZmFqXln!xNCGr?-2A^p*UzCp}frGY}QDvJ# zTlRF1xAp}N%6c;%=ALOS)s5F?=I#+_`5M}6^B!m@xGI%ODnVfK*-UB{V)$$9>wkhA zREgTx#5=;nvy{tn2zq@j1!^}_rt1#7IP_6}am%mNRzCKC#0?cMbK2XK?zX-LKT@iG zR^n)4>Zom`w%o+(DwpCuuU*i~TSf+S?u7w8gvL2_2{$YsD;u%fQ_r7 z^>t>!vknwXUYwd6d?TD)kzc{@k+p4$KRF^;aj5CMICmJcJ+smGuX_Ib?nH1&$Z;;v zxja?0@i;&9hFd@PBoFgVmF=`a9rMTbEb^t49+-=9)D zIKXln0W%LynG0$;zh_BF{Mo9g1EZAB`0{HBjzx#6apr22;oHfk2RUkaNfa8{D_b}w z-1Yky=)oX2c%a@MhoL(YzC;j6rAhzbX-F7M4i74vS&h)5f-L_-3DXxn*+|<%#O;0PfqA>{K(6|mTEEq3Ao#)`C}sJya<^hi%t>=43DXTGARLNi_|XGA7m^ZI|h6)H-irwnui*diQ@7{=@&Dg@2gSa^9tfPvL)a zd+BwBEa}))PY=0f{D?I5qsNurdpIWK(nxc+b zEhfux5yg)OgGn}6Nai$|FumDPJ%Q^tOH>z(3S9f`i$Sk zb;?$%)&B3G9Sd&TO)Zg&Whq-=LvOQsuwx*1ns6RvU^a4JgehIIX|%ve4JT#y}nw4iPllc{F} zRIB{eN?r^~TuPGp{Ym;8tz${Ix1-7{Ydvww`TzdL>sB7#f;V!wuV+QI9WruJVN1|^ z{@}N@Na<eT^TKGP*}bE=F|?k`A`JQG=5fXT z3+SJ;&ujnK`Mcy-N^sfJJ9}ISSo~dMW{Ny}R!&aq;4fD1axWM{4#YFP`SAB4~XaOTGrg%~rLeiAvWYO0&eP`pSg z1$vp-==N)d)?aWW?fV#E`rXQhd@bs9jSo74;g9qZsFPvqf&WPUb`A^NVw#V5E~ODE zKp)R?d_Fw@3>!TL-iii@U=+&ytX`ze3)< z$c;?rL*oW6qsUap@gyJ`Sx0fo#;m#b;KtYY`&wVB8+bI~O7Rs2tX-)Sd#^WZ=j+;L zj4|TqrU|=}ABlUAUR$})jGdS1ATgq^xD=*s-we0dta4PG6K>X8uPwKk9kcTg% z*WR2%q*hNL&|o!Xmo-=~$KfE?UHYnDA@#8ks^lq}tGj2y$z`}(zRCgR!^gpR6JaKn zHrGtv6@%VI+z{T&fhrP5!cEE$n(`4hDiJ^}C|3$+Ge&pP^=(59BWgoig&LF-rGA$)y)6qD&zOEmuh)&Kk!q~tS`BhVIVF#GVF}q^WR7SMt`7+ zuA>sN^Z-w4L);~!eiTRCi#bmHP!vm&YvdZolQoMpApDBw{r5A!PtNCQBW^q~y@|-3Y-6QXtvpodEj|?byTlFo zV7}o&(e?}A*?}UNn+5NrwMud$ZL4A$_>S5NXiO7}7!}NkjZtD?hTiVL{ORzKr0N*b z(;3AY%WYBG5$F*~eV?xs&;$NPNi-)yO8UFj&!e;6i+7BBj<*F?Pnx}ZN`4%1dkuZw z3$O;9o2mU;A2U@`=%2&nB`joU=B{9^A;T<5&BdA07^SgzV0$f;v}7)X7FyF}Drz<# z5ygqFwi8DU;1vi=E%D#XdJiuq&&-cQ9_~My@4J$hkUk7aL;s)xgU$@v=YXb6!pU4$ z%M@n(zX|{7u;avkBm6J^7vXQj`!B*DbpfsYQg7NBx*=ZO_!sREfKl%C#yVok=60Ry zD=vPM{ChOxKZHNo^Y#y{8QPC0oP$^PEt3Br{NwrK2g(wjmj2vaF8w!zf7^dg_|N>0 zg#WhWV>IJGgg@DTPxw3hFT%gu@_!`!ss1bBZ}v&}d!RiDwXcHQdSC9g^-T{2SI*we zq2@>z+T_{%)#tbA#rRxwIThI`%72*4QDt?j{n|BP=ERQthPrqaA_F$vZ!wLOx|;Pn z@m)*{NwS^+zO=5L8i!*{%_*yl3W$%#*eT;r-js66b~0m0#|>_I7>kOnRy-u&bzc1L z3HlrZ&yJwpAX_Y3*pobG1-Fw(1%)nDNi>KX1s7yuG&^cg)KF^$Luq4+FdE^H?JBq= z2I6lEBZ?c6?-G}E=8v0S^|f{`4air6BV|lYAn10>;OAZ&sN`kGM-_CU``;y>yiO} zNH<+doyNu(o=+<(b}JX+o*{>$O#w|Ensx&5$9=Fw5chR2P7DZaP5#Sj5yH#iMDVLe z>dyZC9o<`{>dZ#*AKBQ;F}Ekp-vNvNB*~h~3PD^p6s!@_f{mGyWq2QA7Ocfk3afiz|*)iiG6a0*H9%gb@ ziLv=DYz+IJ`l-hj`7B~9Pg-{dXB%KqUP)}ZBsL|d*C{WmQMlMz&~5puOuhtVCkuXi zu3ByJ<~3;jOAAPFE>mD+h`EWVVBq4eW3HaCce{9(G? zW^f>0t}IMF!T3A@O3YTrp;IvoEa*CBxi!#pN&pu@8`42e%+C+4!V;|_r%E@93_IE& zE&aRQ^@)=IO;e*U&=38aHsEaMe8Zfe22Xfn|Gx?U)DNFe!e2rL%Fnl>@1JnukUw}( zj{ei++SD%d>{)aw2egKs<#h zRiz@|Y}aEB`Xx%*ekc&OgB)hG`+)KHj|xHPcxiEDt0;ND><+`b%YhQE!VJfWMYjhuCe%_M^s*-bBkXLYjQJLcn}#%0KwRkk8tRT#xiC34ot)ctbD&`6EZ_kMWKr%(Ku{-^eC2f>#T>KwVm6i< zujo3cSt|z;LXfi>sdNDSDe}5Q`si~PN$!G_oqph!mbz0v|0EQ?^a0_67(-v5IqEKS zeo0lh7hYK*yZs{U+0bElEvkMcybAXo0st# zy-i4}u5%#byB7l(JZ46)n5x&MCbiw#?_&x6Z43%c5VTAuJyc~x^DSFwLU6#fYQbze zq*{Xv?O8n=sRMLA^Jn>pOtg|k0M+?Y8In~pwhSK~f;}U+oTk@=5SO%Ey2o;j70@4u z|D__PgLHUwmR5a8Yu2SI4tEi$->i6Q5FBm5;dUj#9S>n z>5L}40C-i2)^gEWD>S&#z%G8a#2!lJ_Ueu@mNn?JixQvhpexu^Q!g}CHDc5=NbbUI z9H1MKfFHd>Fb~BYf{<&N=lZkLr|*|Q#G}iwdLIg7Yi3*sa>-F2YG<=i=bc6OMPFwK zMg4}$RXS6vhRbFJjxMeuXmP@X*nixh-;YP3n#8hXp`<-J35pLJ(S53W zLrH-$Z{(B1{W>8_Ls-t#Tu>NpRY1!@~zAEX?9RWXtS@F2>GQa_I`27vpkdZ!bN zb`UjNqovRk2lX5*(wF!yOdjs5L4J;=eRat5C{rPTZ5E z%{iI>H^E=#9=!pMR)^h&(?Yps(n8EC#I($blBVZ%saG1?%Q{hjZK}t&#Y)2pmlTGW;jcE7p?F6P&R|}D_}G;rNNN$L9}iK_&Z6`FS)0wg=l+s zq3&*HF|h{5VKvZm!1U2nP?8ZOD@(+rAF(H^)&2sjNfW{&ki=tmp={Y^Nl^SU9{TYw(zo^-YDSN2mlPs>5`|H zp(wd6_&Ml>7LrfWn+nGG$dgo8(N-0KkX`i>;q}@768w|6F2R{O%@U!e%1?Za%x2D)Kmx@B{+JYvuvyy)OxV% zorfhDGKiq6)W4UCoP{p-4WaD1Zt4Y(fkxG_KpMEAF%zr9(#*oahs?ji-u7ov$Gj}K zaWnA>>A967k~+~dX^0tnIkVB!P+R845lCm%-2v+Z)P8}nurdpTrHj1|Z1fV}BL&Hv5c=()df^=kyD47)%UIeOjAhn?zmjd$QL8s}Z_>Ref;_ zXp7opGF67$5n*Cb2gNF;=4^Krq^IX}$xwfC~QlFHDEu6Zl~SZ2|hcRw6@IxW9I8N^%~ zCbwlp52LX7dTea%T&|pPGcLXpTsqW)oURu#A9rY!M!msbFqGga9QP%|hIVuAh1=<} zQ<9tf zHvIBHuwdc1bd|3mn< zuLoRg3rIvSNr*8S-GkX&IgfR9XG7m0mHrlVg-KR3i$PP*-%%fce7YGd&sfzb(k|OP zj1`jiKm!-ba(Vm{we=wJsBMBKEQ?$*@r>2-?}UHlzY+eS|9=R78AxnxAUXnjO3T44 z9ck^h!#^tvKM^lzTL+NP>)W(nZ{zkA^~+ms)t`TBpFe&1_ihJ=-n=w3Dr)UCFQ>E#@`fYAAwO(ca`W5oKx&HIQO~JAPPYgxwZ8wnX+30~&0Sg?-|#^5%ir zlMv6RSLu=GrpfY`0@7yyiiufi`T4A% z3y7~-MahIyLEE6{h*=Gwvn;9&B`5|SWRwd%zt`?O`(xO0B4A8J`}g+eG%3m$0q+7$ z4OZ3J-^}}ifKYOXb2)uGF?2bQ>N{zNu#@4Dp#*d}dLc+_A$!I1C6%ec8(Kf~>}urW zwB8Kz<;o#y_H72#+nWbr&=%gocqyOxICSxMWXTI^(I|nvd>o;QhDr3Fvw#h~Q&J8W zGy2J&Buh(Itmm7_q?!g`p}LU}89vZT-g^bPmqBZS)@n#t06iGwdGJ5(UAKH;zxx=K zP;s`e1rjv`cRY_#izS zivaGSJPAnL?YOP3?!Pzr;y*Sq-&cIcgHU9}at0Jz?_=Mx9b*w~de!2%?Q4bJWQqB% z$m{HVY{ph6hqp%zY%G67?FxMpzL=R3Cs|A30cZWy@eXAHXt+YLx#MDg_P7Jj>1%wd zdT%n}pGQ%(z1s>Rgi=t}6HtNKv0T4}H&s5T1$+4H@QGxKde*MTSmMoA2LLnDFbIt{yqY8o*z?f(?( z+cyZb-=2=A!M_b&jeOfqL0xh1c<$%b>*s+6X|n5(|&JT2LUVg)s&xN8HqlKZ+3lHdXK>ur=CbYCDj z8mhwe!=Px{OEnJ?W+Ap+K>3bis~|OL63w3nI%lRKv1jS#Msw!V1?nEZgtlIKV!iS? z=;R2r_phBepfNNlW0$>S?QYqW5Ixa_*Q+>D`6cvW`#FG%bd1DUW(|VW=$C$TE=$QpopRJ>i_K3uP6S? ztAF_4UOi2CopTNbgib!59KnQy$$Xc04II5GinSp_8yz`Z7cLPSLa{?JtS490-GNIn z3W2l~G!&ze7maxH9(hi?u}4ihc`W9?y!yiXN1Qn|e0PbUsT8wDn$ATKc=E+aDKUba zzTmfW!5__nKfrH|l=-ikXW);-X6x3WEyyuZ{-VAol6xvPIDOsaIQJgp2mSo?>TCb; z>Z?sMp>MVN`OX3~QUBem4^`LR`@g(;i1q_EJb#8vJz4#Woi7U)Cn5Dqe=w7kDD$j8 zF7P8gs5-0tW^hpL`e`+vdS;w<>)(!^p~SRxhB`S1|7N^Nwe?=Kx6%=bY)xh(cE4D! zv`%SlAMS4k6AtZ8fc(#Xx!ahn#SGT-QC@_ahJy3-JyZT-6`DN zU2gUFoilT0=G?hA*{SU8)E_&kM;H|1I*nE#Y z@`cuSSg%~1R9`-j%Jk+tj}CscuVc9la*)<^N(@m@=P5)t^k$4z#MM8{!F#z4O)PVp zY)N-AZ)LUPO{`xhPF3_us*o@u$m%}JWBJ)X7(S3`FCM_2xhvse%X@mdd!w^zhHb}m zxv<-g{MZ3XaTwiNZKXGMld*UJr*yK}`&aI0+tvK)m-aQQqW0Dh4Ex2S6uXVO0Q z`TBO|=g;L>USW0(66q(d}(-nkRxNNlGXBYOgi_eS}f(9EPpEJ-pzPf!Tj1K zz_iS}E`>A9?zK8^8}rzOI_}=l%v-RU-+5L7ud3tHVchP)oQ{8C?26pHW7o0B`})kl zwfzz?lOt7TI5Yg3)XjO#T^-9mcCv$XqwlmP-wRcxX`@7b^TfuFU}CHA3-{0~>p zX`L7;=CZ8N?%W+^Ltv}_7}Pvqktx>L_+GVzm@xf^t3N99v`FdgLrk3exIK5b+bUjx zI@=&SXf9;*$xO?7OKsj;)?RegWu5jJj~q?Em0mx0WVo`?HeAqt_q>(M@CMihD!V`E zzTN+z9}im}^7A(K^qs@Y3c2(vYoM>#J;!(A1`;% zh&F0R2*=wpFWI?w*`bX#ezf1*CvSCZb1tkBt7~eSTNKuL6{+rF9ZQ>)6xQM;-yrBO z1nm{83FloF71Bc-#^`ExTa^_=C&5*JVVgEEV-?7VZ(mi!BM25>Lt3km&EXK0-fMQT zt(m4f0n-=@*`TX=jH6z@3;KAZAZ!ia9b16Zr(+;C0{CRw8TNhLlkNCpZlcCnD=9;R znXA*MdYkye4*CO$E^KYZW~HYyZY4BCSv6zUwRBngfiuo{ z=xc}3;v|>;a}5rhWg{YxOrJRG=|1b1zUB}O8cgLe5hh7cm{4bcHE|vP7QP-kpSm}c zMBnF;@h%sRD9yq`X^GKg3U^YIf)Mvn1F`t0Bl!C3UBx((S(<33K?U_^4;(?Eqn2&NP%RY+ zV^rcB569-&XfUW)-n9*B1+mSKRxRziEv%mmEujiN*4$q{YV00-h(?QNtu<8~Sfrb| zLrm$%9G|F51G=P=CY6-oAW{{aqF9Krm!KOIBdfw7Ey|Gi_~t}gRs^+#c@`Ek9A`Nk zZa_XlL+OB6J#uYzPMd-76(3JBS88XDNim-E=*GYS(zK;?%g5{j3`rbG1M*c_-;7bV z7Lrh~_hJ~nd-Pze4-edsS^=aSACMLlT>jdwz28aR$cxN54`IJ_$Uf7{Y<-)4Gds^v zKqs5-V^0bwU|dEL4uQXDwZVlMr@{37l8&62rtq3L5L6gnhwc-?hZL2#udZbxV;(W3 zHzsjXk=Y(ykR?P|rI%FDTL zCARL4OS_z12Zm<3v={;=;byg2dMvH8Z60o$w0Z!~K?s-of?pi6A`XdlR=UqiO;v>} zDvvFS(k#`RwpKG5cCioZZibEsBWrChFT}KR8z98SGrLu-yO9*4w`{?mB;+l<(9drh&kJQ^fT*1wEn2RGqsh0h}_h8=2(=k z(qyBQ%QRLW5Be^MqT9A)ScP{2;Ti3B9GS49G#CGJMdPzAM!!-dR< zQNI)Rs!h@Hl%n;vBifztJKJd}x?QS&-$AkMw5zOL|3JjYDdo`f_=IkmhTaKyhy_W(#)@I&*b94A^?*K@wHOC>Q9Wzuh z@!I+7-OFaDK%cQc%J3x}MuY!EqE-)>V2T8p44M}qP~pI|RHPwFx$(T4J{Z`{BSV0% z`gwspohyw(uke763ONRY=u&|7iqAxnhIzuiP$Gj-Jsku3@Dp|ZK1jNCMpBzup9J#2 z(F)SphS{O^AFTe2XT|UqZKd0Hs$E_1(xZaBV$JjWPGu-6n)-Ih`B1sQ^CyYj?azez zuCu>$W`S7!*_7q`EgdsG>3?ALg&luk^=Iu1m-J&|v>g6dv<(w*UfBBAg4B-+Py8BR z5zOR*!F&rx)t7cDWaB;i(LeumX5xubX|CNXP-0a2^z|-4RSN=sCY-_0=wbIw+n>o; zxb2=lj5Y8C{BA@rk5Q;sJ#bl!iz@ z!Vy2eUOl2BZIcM@3rm*xbkp2z+ygNDNdwMuq%jxOf(A>fmsFOB`X|~iI8)xh1{kWi z9!}U_`W9c1jd>}Ic-`8AX$eZ@$TamREBM4=XMYgh5u*MwT~Pm)l#0QIwI|Ma(P_NY zdT31C*$^~H*Fhb3{eeX}ZWn)CixsFSkTEX@kV1}9-GnAQtMZk?04@vDXB{Zf{c99w; zSP{przWWM8CT~ouRi7pEA`inB$XWd)snjnx-Pwa z6#Q&#Fb#+crm$erKq4`dDF3F=-9RA)HUakl|DaEC;u>I`<^o^_6yN*cy0#T@EY_>B zPv=Kq>FHroFU3!4FJHw|47Vhqs|NeHRcHqFWv1id8-Kk_rA>=KbyhG_&cU5YlKk=w zaZl}SBXkymkqywGDB2!`2#hz1yh;4kYNjq^0ZjnaahRLq`X65X`MWMVWf$eqck6-Y zw5m5>UoR#bcgS)6=O=4s>nFRN^AJO0rM_FpBEM_pm3cu_hFt#$2+(v81I#L=&rtsE zXtYpp}B5tq}yxO$v_!`0_t7G@PTBYE9itYhwCpuX*+2{6m;y)$57nV;VL_eK~>cqD9`F z43eUH<@;6*A#}cH$Q#_cXOlGK+X{#5K4aJ=G;bhs3$1gBypO?bN$dZ(dK` z$@RthhyTxQ&hkr}?&$?jZ+p@lGwjN)-`UK+YV~;k)apxd7$qYNOhUClJPL`V!!&Zx z@;fPYAr=DZ%6q8Ndwe9VWybE;>hz)AO7*cn;aRhRY-n)34hxNcs-}^n&UFXDVpb@e*k<~eUu97ZSBfH|n zTIQE_dyCI<40hEiiT$eYMmp|%?G(!cLB<36!mSIcjZy-x@w(y%h(39MoP#;U>&FA; zcYi&zZmQ%MIXxncyh!6p>TCu>Ixu>1tb5~J?pjQ%^Y)&6;Fdvt*x}^MY5isa?Rv%c zFynK=wbC3%wWCnz3Cf_5_xqYw5`>PyDj+iPd&O7N7>fM52qq{PJ*ahmHU&P0qz)MT zg>0A~FvwiWu-AEeuWjn#T#Jv$H^M2^rb9e8V#z_ne8=^t)J`FGNuOnu z5?5!Y)ffPehD}>v><7a1oI>xjKq`_{$WojHHPvmwSSWvdn*z24oL8%tZbKa{v{X|I zE+5tUi@7cU^Y{P&$%k4P0JI^*aY8+n10I8`@}g(T<`gu&q4uvM0{#I-T?AUhyY!z=@z}^erOLoD?|Dft+OL|!y z>2QzLbask;u1Meaqw@hqGjoO+i$JPA_l5`A*d}MJd96*t0N92E$$ok(BKaKoAXA0u zb@cZ7H1F!9V7d5$QMkGw#wK3ZD4X=s3~2fmGG6y6mhf^y45;qkanmZFCx(R*+Def9 zSZW-wp?`f)4TRVAVr;qGyZq7Z#nf^+-W&+OflTnUY8nX7kHGixBHM+l_4u}l*Zr~M z8VK);y?%A@fv<&y^!A{ONdLO`&=2p6r}b!3gWvt(@)&aw;`p?>7zqD?wSLvViRb%h zShbC-~QFU#URIrtz~D{7Ao@f$ThI@?e@hM19{E zKD@YoQ(tV94^v-!KBj`c$u4ZEkNS&uSGz5OK(Y7Rr^`OoK>OFDcF@STqnBRQ_t&A` z+mF`)y+hx33%8*UB)*peTj1Tems&r*Ox*jvGj&|v`2n$dCx)0wejJ_0+0FVKU(VFE z16|~>j~m+%%y%}dp@V+W_t#MWpr`GG-rX*&_Q6eB# zKh*nG*M}{xMHlH0RuBCLtMAq7!gT;*^$0+$o(PE5FKz{QBX(auREJ{`Ne+0rl(S?6PnJDe0iu7x*g;_4ahVIWer- z^5b+Fa=h7gW5GPzelTsW+J>%Oo;CNoBK-Lx-eHRE2cy?+D5$5`Lvb&d_XB^Rz1PE@ zA5IqznEyox(6DC*r@RBW_KSsp?X?p?<-ENo@FUWB-9PjOZ<+Xhoaym)eGKJqdUMzsPxgxa>3ShY!sAczeh}pnvso z+d}S#@1K0vKkB=z7an+c=tdBGzPrTJr3Wx(zBl)`dah?91TMA1(b{bX!Z0@X1!CS!Z=wf5++NB0Yf7x zJ97d_vZPBrsbnJvE_S>V9O)dsvwyUDo0$e5ep5D`88S=2}OLY}1O#;>fVQM7JYk zggpAa3Nvq#HhGkjHRZ)ov!qA{Hiv5^CGVKI3<|wDQy)@`;6~u8gN@m4>o9ekwui42 zr`$|98Nap^FPqb+)kp032Fr@P5Y`%|^9<|*&sGV@Na^&Ik7%FxA$PlYu5G;7sRk-RB2eX{55sTf4_c?w-# zg|{JXB>7_Q+x^JvtA*1dTZQ>P!v)&S&P(1iIILT(?wxTQ8)^G}_CzJlBDo!ya( z^-^`GHe}|>8VfYD&R$leB95+rvE@11bZ&P(8P4dFtar@hvv=K2?$)x4%z}(HS|7=< z&Pi!h7f&v@gr-VIY3S$-r~6SMDfKgmZmm<=x;c5H3*tn)Gyd)XumdV)VxSzrH zE?SVrl=P^&N~GNIL3>|+NmH4som~H4w0d$SIWqqvVH7zzCS@Y@V|FF6fqPZC3-ZOw zM>wkET)apLj(~yKF@3x|p#ZcI4xtK1s->RFW>V)grhMjtXvOtSSABpDTm*$+L2`h} zZ?#iaTFNQZkxA^Y+GBlg10qbRj3wv|rulFaYNepWB4HVymBcMlok^&0*IaV(DM|<) zHWLW$IrdgMbVXCfc7Hv-*Zy!geM4FEZU$o=sU?$9A`tKVNH|1=WG>ur!#-b=INfj2?qM7FAkhAM9RDP3&>k= z4w>?zypUMZbR?+}%ke#5U8BTsS{eM)$Z)H*CkrzxY+yP)q3&`wXsfR&6_{3Jqu5RK zX=!%ZI%jzh--4$NSJHP&(s>eAh$8@G$DnaC@s~@>o*G^x}G12X__fG+OZ9}0I7OPnF>Jh zz#pm}=P#<-%reX@6;#_lqF_BpD6m^$)ZVBiBqa70xt;JrUL@#c9cLtYAmu1^9z8QY8@4 zS%Bspn&|~_|GpfMWf`82Hm{T9IU=`R;n;5s)K%uq@6X~Eg}vvoa9{E?k@ne5hG=q9 z)gbOZ(*F?0LF4Ye3{Y6YX2O?!G1RdNthf2Xc97ONX1s*%-ra$~j}MgU>6^DbgE$yQ zLiq1q+wcJE=zmG|i_wQp?Bh=-t4`C{D43Nt9pACQF!UU@A}O=BMOUR>4YnQ9ff@s6 z3>nr&2_SkD+D_9RO-N3k3UQ6&W+088?RtQCnuY(pnEnTQdfUxvau65aLlG-37aQ;? zUID7q-7a_QEV-V=m5mpUzHXMCeV@8{Z_m_uiO8%abwLmE?YwGXudiZpJDS+?Y*S}E zHzpc79I(jjT)$qTX}2WpCkV)BVvsoTJ36lh&_RBaT0t{hI+SLb-*da&KXaOSbQo;@ z1J$p`zEK3End)XD-T@WSf~Ttl{4Md z-HN1F>-4x`=^v>+m^eGMh1SH}Ft8W@tGU&X(@Z>d;a9sr|7E#eyPiz%usUAF_P}>H ztEl@uV%fbuBS&BiGc68ZbMF2mt`7aBmd7b@Efo$$$YQ=Sb?I!?`=^3pdZ;9Am$)&l z!bKHP_3%_V?ZVw?x($6z+;lts=8B^Qzk=brkja=!Kl^wPy$&lhXZiK-y}s9r1c|-Tm(V<=f7sT1VK! z13PeTtNsvvt@!)JgG`^yhJlN%J-yB5Bd#$gd>{T~C14MT9-lDr6G6^pIqKuP)B;lV?MGYtpE!=&5G6Wn zI`xdzoI57@O?_(X1|NXQk{WhG#~a0R-Fw^*oVptZ31Z0X`7Abnta{8pR=v}X&sk@{ z#Q9@4SohG|WODi5Z`VfzdR^KU_Pc#%ymmSEMC(B6Rm@JD&9Y?ih3&gMZ1u}Gn{ID) z|8d_6!S|dCvck1{QO9R^#~u9d9f`j)wOZQUrqMxUm?JxyVCmW%m&&(rQe+8BCpm}Z zEYe6#8umeaSBwQ&gYjks^#U@}DM;c6|;8ow<#l!hg<+$7aM z7KZFQVSm1(3&?99=BkM)-!z|JH+o{tv!bjpgb%-_#K4-$Y)>?(KQ`tpwLFey3WV@4 zt}Tfie(pMlZ%Q^x!Ro3?sQH~ldK}rINsgZKzgqQh|JABDND`KPM?jnS%c{QsTJ`mg zWwcfAGQTE}cwEYcFapY0WJ{Uorr@TqB^2s#t$D-lA2&VtVLDX@fL1-_zgqQ>{;oi) zJ_P1X1)^T!MDq6wtjieOf4Az7{%O@){~N2G{V%KD@xNO2vy-(8=>N^C_xRte`g64L z9tAjJGO;ox+`zshli#S|J0W_Yi2>#!FS4Nb9qzNg+iXIlsZXztc86Ws&Uwnl-|9&s zd)H~#o$aP;8h_>*zV6@ycmrvEJO2h7{anJX5^j&&suiGidR^WG%_;GB-@eUN_-2a~ zXi@r~zI_9*B(QNf{R$LfYPB_7rLr`#n2{Uzy(g`GFFHrQYMva`?5Axn9rwStlhl(3 zN%U_W4(9uBi#L{cFQ0((~5X=Dr`xKSZcW^4_UjjET5TNh~7GL+tO7-?4 zSc7(R?QO%J56#s>sc)l=TVyr;JcW@}B9sXe1vxwwuTDX&zHH4c2pDLiQR}&iWrdCe zV7U$^F2s%;iUc4=9K@lqGg2P1S-}kIGUrKmu@Pez}BnhJOS)^`FuHRVr zZ>qji>fclK^QaJU5~Cd7_4H9G$1RzISg_ zdzD*YcX0=d8zCG5>Xvi|%1CfAFxJ$bNE8RGsZhkfEGHtZA~^(s43$(8l80e|ju9gD znp44~$GhfIl@dWqREEXRQb|zXD3~Dx!G;TZH?7G@t_C>MWA9dcEK zC&y|3T?I+rUk7GsH*!v(5p3iFAn!I%eN(&O@8jmQ@&QwL-*>v4e>DS{Lk=S-g# zG#1>+l9i_H@~3HSkb#7IK+RqmX8Bxi4knQCz@hvOZXT~^*WO8o1bV?FN>+QF4+++1!i6Oi(4v`787UsYq zK#rmc_oo@QHE41s<5sqgCje4@Gsk{llxx=HrBL_OQK2@;PY`6dW;Ik(V{7a5U4{; zOv4N)2$4g52y2>1u*ZH5q`8O;wWe^F*dpq_mMERIIm0z6AgI%qQzTVg?3t4Kw1@V5%fSA;8oTsKl}<^(%mU2!%Kb@hqtK*yXOm zY2Npl>_dLppcU!JJh96zKsrEL?yGO;a*2vDDH6=%GSJXBREFW>#DSz1 z|2=m-rr$NR9X=#MIW{lH;Kn2*QG>7N+=nJONt~y;phvUJ5l^~JD<7kG45~nk73T1& zTNm?;8iRWEMNL8kE)`bA{xt>qwfxMcah{iX0umk)Cy$*lAUB)VN#q}sC6a0jU>GdF zBfkh@sbGyjPzAH_F32|V-MCJ2dOAi`_nPU?)$P`zP6cE`FMTZdMPt71^s%{^X~nuLDdp*10+76_{o{$UWea2Ckv1 zS*Ms$zL8IW_RsIVCPm)UwUjd+O?2E3Nh_#fP9#cmT&OuwVQkzavHl@4m>vUZh`CCb_#Gx7(EpQ(?TurO*u})l!-`^AQYY{R6WdkkQ8~S33AEo@bXiM zL{F_FP+m3D+NM38P#x7Ap!Sr1JN1$yfo1*SO3D*0)M*s7<_v1r9h!Ezg8__9tQ?nE zZqGr{=4|;_#X+c5i~dWsaAmz9tpZxy{Ymw4=sm(OdoUeCYW4XL$+XF%YCrrx0>G!T zr>HHgBTMqXHG*>K-;R@GJG0W*+9COHQ#@J|HX$P#YP$`=2CBboEc2h4EXy2yA?0r$ zKbIY*EbwE1qZV*XqG=BDrz1Sa{E2*T75=aQNUB4R1$MT)o^&k8LO+f4R{Lg7a9<#W zLh?pOU#+RA@q}@Tg4&Jb2`QYc*N~yY+V+hMoD%J$SJQ;j+C~-wE#qg+FO=bRveu{^ z{BRmKq`lQ)+bW}XSq*H|iZI7VcYI{9OmKSX+Af+t7d2R3{n(wAg8L5vUr@u0xrLJ8o}S7j-K8=leGh_>IwaAP=RBJP{Ym|+g;AH68FJ~D*9>ffMk=@1sOYVq zr@)MSItoW%IAk6ace=53D+mR}1-X{h?>Pxll^L+!$5a}XIcPJRGP9_Zp~%Hj07_t= z`;cZMS%@A!YU?Qsmyp!9|0sL)a|cttZzxK@xZ_1Y#AGkp!De_p{nM!=AGB;{Ao;{! z2gqD*KbuCe+qgpmbNYLA6*=6*nit6>_uQHp|Noi#U@k4@KTLhJ$>4gPz!S=yw;zel zQm8X5HTUdo1bdd1r7PT1sCHZdF(3G=!}m-rs&jPZ-Ye`sO#SwU=>>NNPHUC*#|Zic z`=a&p?xt-W?PwR=g0kIIeT4HiLX|)OGNBlD`|ZXC7oOj@uYrW2nf@cmCfIl~OZsPa z_aRa5$NIeh%>AQDw(v)$8)^o>L(x?bL~tRqRfCqdYx1%`|T1RN?+PXJp8 zgUMh{6rTYh8{s_zqMQV25eU0JTsV0b`skUMl=gm<4937I-OAMwDfpL4}7hAs2o zZoQM8vI#Awu9pZ-p%Mz*#QQ*kyQKeij6OGTs|TBdrbL6b4n| zoRtIp8ahHoO^qTNLL`@)=xMfGPq$ai`&gUREEt+9=;z?LcUmLCux3ao6mOjd1fj6j z!Zo&djmoZ}RGeXW?U%s`c5UJnt!dA^a)cnJ648u|ORIPs-@1j>tMK6j4t=Trw6V7Y`E0 zpOQvVEraR_Wc0-HbFwwNS?83cjW4e0wpND)FtJaJ96em65ORl+SNTLYg zBQOhM+xY_Z>vmyGG;l2~g!&=X;G~AKB+xm+syWEQ-hQEZ9{zKoyEr_>vvQ$#IA~M- zGEZutfx=8nKZgwg2#w<>`FNH^Do>0Q3j$Y(~J_-B2=}HM%9p1?a z>6~@GE_Hm6i*&C4Ys|NI6DQ&P=lXEl!5p>KX{Dvf)p1pYhU-f*)#LRH#m^KO(ni_S z(=)*wVm*k}9y-MS#ZxYTDBe1{{2L*cN`Z`#XV(>-vO6{?tHmFP28p2suqbaoi4+FG<;5U}x4Vi&^oMwq|#_ zrOnC$N^ZMt*9+iI9H5z(7tBp@AQPCWV&^j?DP8BO+N~4!1?H@cPX5~l*V0~ep60r% z@2t+3;{DppB8G^Ol?kz__F{5N8?r~qRH=54kjB;KsU3~y7jqW;$tGmu7lCxu*D4HS z9B5^Bbamo=&XSYwu18LX`!am0;J=-hGY@%g{V370m9R|=AhW(vF_FIMjs`bQiGrgWFvvCM8u&K3!Pf?Rhf05xu%FEkZtiA1{j;(&Q;hxV5`3uB zXYY=M9PWyG3@#g_uk^G+o)5{ioMRa2-4{gTFHn5_kn$DhW3brX(I9jgDd4Lcm4vCz zt_G19YFobKKIY==>Z_AoZ@cM7^m=p8I+@%nQuaRLEYoF{%=3#%mUpvAdwp1t<9cAp z;Gj51B2X26L}m90rc#u|3nTT~0+DJk97og#MkU0~xyoP-Vo#T>?YCh0gi_$PZ4o9O+w9fN>v^Tfgu7=T zroKY!{x(gh*9xQkqajEOad-9-2H>{0|CH{r|48@n7)hGse@XXuf28}y_9G4Urq~qu zb?J-Q^s0^3b`G6(-74&+!*!03yf_opn&lO0^Odr%r{{;y@6Tl!!uW+(ePAndZ&z0< zYE`fy&ARTnMYh~n$?OZQZac71ivh`=)4W&~HK#Uh_~|Y5?N>CkyCR)2s#jfi@vN>X z^FKr4vN_b%?D-9~$@w47cgwmQlLuQ@vsBh^`Pd~1L)+z3wfBZ^+qOQMtwSfyQ}#Og z?AtVL%s4gu-5vd#&GK4_uO%+^kw8z7=Atig!a4#Wv*x>gbr~8Lf~*HpkfxDfa{$Dq zN+n~WcTZ^!lW}tSI!jh3S(c~68h;l*Nfjl$gfK4kUhkuK8WTvbvnVvVOpkr5wmtsk zfAq#d%gK~M>gN%O?AQ<8sx?BPc}E8U;*Q|q<8JzmL2*OGIr z^Fgs*xU(}N9kN1tjLqSwzDS<)6vKXO?-w|=I|&U=r8x*(M3h{S5yOfkevPxV#xi_nf=q{9U&3MgT6&$;=r?Jp<)rWBvcO>D?Fg+e4Wn2rRuzopay;hmw+QP8Ziss z4Y2qds7C?<^$Z5$B>xH2D_NZFVa4jidgV0C&{M7%I_`%V4R6VRsKHEb459vNqhpZ| z7&7{yR=c&_+eZDBaLh`fX1%pCAbA1q^>hCE{FDmVc*-x@Sh3GWLFCwMC30>qrfnRD zXf0nxl{h!UB%V`Cs8v#{kLssqj#5@N3Lly~o{Ysi;-2;j3)(~SRVcSv@`f~3U#}wV z5y)ZW!9deF+~}A5oDqpM;Hrk7h_r72 zrV4|;I4abKyh5K$?YAI-Fz6hHGgcQ?%Vew_iPi!yHocBR4_&jAZf;4|vAljRF={Yp ze}CqvL^(HDOT$c3wIA^!Lj_^-3gMmigw&K#2P|UwH0Ha3{hW#f;xHkS^V}X$?wIC`mj1)~AhfiN`m_14 zYl{LLQ$FsX63R@7DK$l-OkxE=26#_t0dClYd>$$2$X%R3CW(+UP0;V7ba#g9&2aRK z!9BpPM~BPUG-fz7OnGK4sV+VaEcFQJnuC5}aN9!7bTp8c7dS_67N#V{aR5<4iw1X2 zO7J|&=1sR`Zsnpnbn{5!Sy?KyMZyz6?%PiOue`iqiQ(mK**b?P3zQRr$V@@%!i(C3 zPt3_tH;3d10025u&C}SAbeO#YL&50+q4?>seuz4d_JHAk;pKI`eajlBi(Z3+^V>(AwNG>bnIAPyhh3gSNX4!cL+?u0NjIeh-OCV%GKfDM zj%bl3d^LQA+s2Ab)>b91F*CAme}>(Naa}wMKFRlo#*Wt?cOUqxt8}V5t9t+(0y%Rt zizS)o;$+SXx(;;r}5qL~~({isW4cEE9snE3` zc3>=v3Ain0>1@C?_R|yzU83qn2h5JH>xF!M)#5f5Z~E&jb9C&xZkg*Xz5|1R7DRmJ zzn%<9hpqmIZ>l1e9J=NWVrG|Zk2_@YvF*!444{V#)uqA1r8>{0X7}Mui#cD{qE|W_ z7?Ca)d=H2>wLW*4wi_=l%3riSHyPMS6q~hN)9p$jSLBb_^y3Vk0I)e)cR%}EK1kx7 zTu4O*gRa-@UxuiMgQKq+jq^4JskQl|&KS&{XKxRerBnfHm>UbPJZD~4} z;Ms8Ya|+w3KxFZOi|<3(#JR4e8uHM!p)Z4@*g)VA)2(0>DAnLN z-d@M1)vTO~;5m<|SAAxN=Nf*wkig6SdWnX;JfigZ@g4YtLK76A~XLgYWMpAm^I)aItWIRF2w?hw0)=+CLBum+$rbdN|YqerT5HVzm{{q zQw*c5izHsNHW6gWFyKCV5%BZ_n1GP^sP=0jmJJVIrMjF?tx;nVq0`gaCq^6||8JgT>cs1)doU&ZdMKPg!}kIXiC1rV z!_d7#JPa*f42k)pNa|0iwDM^KX{As4cjZqco<(w&*~ri&J;O;c%c>YfCdNcRa)ta0 zoVb`~>Q4@nJAzd5ZxUqS6)1Oij=^!9zphwAX`D5r^-6tb=awI?a_Sd+?9kS`IPc3S zZ!c|6i#`T*I%vKb-v2egaIZ_6YR)eJ=oD?a$ZFBq4DkNZr5*CcF~LeIT6j>0d8@*R$n5?oJ# z0gQ&CwLDG7@?GT!^J+(e&M7sGk5Xgu1#cSbCEWIU0W9&AvN8uyXqNPwu?hi}}Zd?0SYgZc;wrVF$>a4}7f# za_8Mg#~x0O-Mie`gU>U z`rcmw0yVo`u~OAM=8Jx9;wzmvWDp=@+Pv?}Gt_zmW+)exADiy0#5nR=@3}+q5mPH4uIBW?G|Y*4a?Lfein>j>^Wa8hgr6; z#qF(wm@9-IC@-@9K-oOpJ4BTXRa0Cuo(N0CkC2-&JHrK&@o(8#zlF0M_h+cs(_ zQ!0WAhKfp}kJB{d0E>|)8Ea|X5vJ0`7Tm;W6^YsYzf$Kw^gI@9XI#=b z3w>i)5>YDm$oxuMJx~Q?VsE^H$rT*4UjwMm9Ag@n#&|iI%|PXYn_g`v9adVdVeEiV>})fud09g zZBcq}Rb4xxQ+&QuarooLl2?HLJUu>mP;7oQX{ESiE@rzl^fOy9TxYcl@5*6_(-&9ZM`ALtTwEk?8M_=U0 zJ0Sfe+R}b%OV83W7=VY$MglTN4vDEVX9HR8?ONqMFfW^*;emXjk?cr+Hf;^Ba^8eu z`$s%4p^~3aFqM_$OzDLAd7UtfM+4{T$?%tWK60GKvJVu`+cU(_hVO+#L$h8qQHJ|E zD!#EJ#;gi_%F3&=oJ=Z|xJL9`cYd!*4SCc{D2^SZcsLS5>sx0D;? z&MKz3^E|cUZqkRY5`y(*2#fg9jclQuuoP%0Oq zau{_Uh=0f0V5|BXj>5tcxT9P;BX4|>$jtL?U1{0}_aEFj`+suhuH7;JgFC;TU--kF z$NUR-UP!&Y^TWS2G2O0{pMwGDcTGHo(tU9`1=Ny&;$VUe{ox;^KvGGAir4zvbTFSW zAd!0d=!}aE2g3FOENn#-Ar+=+NRX+q*N2s&Zde4mW ziAQB5ZH;DWyzgv46E=kW&;*R}rTV_L7kuWmJ+WVHv%Vu}sH~%+ou$qX9MbhB{Pv>& zOt-rd1bVn&1PoIpz|Ejko`&3eePO4`dG(mzOcOpPd9UDK!1E0tcs?Gk;7F;uHJuz~HO4Ejl-mfnjF8O5aF)vuxi z`&s41W)W)hbw{G<uKYnN=!DdsbPU8 zy#3h5VQm*6%wmRL`cR4s_BVKL^l!j(dpwo%wHAEK^NvnDnuifyZG=)A^ttNUuxNU7 zkU0n_144hhFi-k=XCBBLqliRKWbsUjJJJYjwW36-2=B{E$kHx?95KGMXg|dy(`Rd>n-1u<6?_ivu&Q*35ck%JcWqfgtyOT@ zi-g_e-&^v(78qh0r0h=C1}^;Pn#BAkh^=frG*-^Ua*O8)=j!DHSB1ZuVy`5GKykmq zury%zdc-i9i@hF6$$HMr>NOL9t5jZ{A?hh_v_9MxG<-e2Q~06e`np+H9>e|YstEn@ zCcheo$|qy7iXG*7HK$UBkvx;O(+q^pG3J_Rzddf3Rz?eCQl4?jtu)o_MHV;E$=H)M zJjj}@f|b$(C&p&2QX;`^CbQ@8&CIJ{@A)uo2Vw}%mfO}cLXurtU@4H&#Tpq0ihj(! zf&+des#=3rt5!B|&A*ySXhU@HG|caiwUE_qpyzrUcr#bHXuM@KHMSiC*ge_XB^TXR z56Plz0B&jRzKgG~?S;M75D~cLPEuuc0j&|2Qi)Sk#-sEuCX`lbQXfUu3CoG=Q_f13 zhfVH7B~m{VW2$%Fs4FYE`qa-=mFauQ@)nXMe17}a=?n_eR@@g-FdSygOdbJz&`G~c zdn2E?M67t;a+}-ON-WDHW&9LJuV&FvO@>fU>v2z>Q&`9<_MZIJT$Ht;I0IN<@zZv~ zBqc1(2Ag8lMJ!Z9S95(}fwvn~HJ~2A|9?b?{U=uPu$&4S+oi{g&_p z=2X8<**sApn8ZC%sl}*2jqD+B_)NZQs7TyX{6vM1086>=xTkENg34CCtifSqMha2? zN?p#_Tu@2Eg%-5bR5XSAXK<`k3PT{m!JwC!6Xj>x!ZxLlYm7F9ZzjaGO>Cw04Qqi^ zu5MqRmDF)2cAU<{@>0|h>s!lzx;XlF7A}oeOGZZ?2Xs01x8GW471J}|X&oE0^M&|ZzWvDz)N zSa;K{zNk?7^R~F}UklNuqai-WuK5evT#WpDd2WEHY!6`HD+xh#X*+Rs4xOp;*viem zMLa#4y66~NXcX$8$QsC%7ab^MNwSMj&4%geK`2L5B%6+W5&yKX*x{pl^R)X;Cxy*)s?ojx$X|W`8#+(ehY(X_JpQSSR=;sRibv|##`5!> z$phFfY;E2}Cn<8CSD7OUw@@5_1Z|Do(2fFz05 zbz!%yX zH~g)H3Ap=y$#v?we*v4}lM!S`|5K*Ba9X)ohbm1x#fOSzt2$e&3bBndOWV#C?b+pf zRQdh*1r%Mp8^VpOF{eowKQ5;n~lIXF#x)TOkN5ju*N$-8p-g(*=LDbiej^qiaBWc-tENLWNn zHnh?{r(%cx>6{OK$efUD6%JpN|8>q63^wOc+^w4b;hcN4S=hQz;bPi5qKu6mla@ZA z?mim-yL0X_{bCmHyQ?#c+7+_VgKLn^I++kL- z&}@v|g1wMtkMJ_u8BQ`@2sz0wOnh!lvKYe1kcT-M{VFWyXmu^f{1)R*>cuyM^d;`u!Eyam;IXmp`5!|B&uMOR7TI){Tav#vggaT zm6Hb_KIYA%7cULnT7-&m(MXEC4>gI9OuO?o@_f9uzdHoW$(z;ZVM&w}HUK8iFE4rE zbti}GITz96s<@;o_50}}a0c|s;toqoVIVr<51!u(C&9GRqlM^D@~K zvmC7>nW6*;t)jZB7cFC8IG`cFO}3%>J~XT_p!s|W!xoIO!@M3Tslb4ZvxJMSFu@n?qzG-`xz>ZC*7iWLog4FuI8 z%UxvjGD6Pj0`2?VEhGt+-(wTLen{Ln-+t)}_+akg5q_=V)*$xrIp^L{M8W*jlfAOj z%{rGuV3RbKluG7N3K+`@XrQAAkkUkvF<@odC7lUjEW)MT0V=;18$JGmICCRYpci9|bJCl>il2jJm0Xb)IIur!q zme7`~(ZNggr^wi^MEK~O?FLUIwIs>g`e7T4qES+^gJq&=U$X75fNA^>$(L(Drb$Hn^51NH91*Ao+ z6QcC8K(;3!lEaU%N1|Kd#?Tex&RyurlR=VsIm`d%_l&b7x#Cg9gBG_LdBQoE8wMy4BPFym`2fkMg)bYI*ADE?DYYMx&($_ z7kPQ`@aNHc3G!mtqQHccngqpRA4?gN28vYAsG{}5BWj-7Nm8#%KnWFxhHhFR0T?t} z&zB}c3W)KZYYjQteR(S6(-m!R@yP|n$9n0Jj^cZ(>C=9jXN430sRo24Zha9xu-nS? zc{GZjF;kp$=WX~jW_`GZ0ky>_gm=a{K3(0wvmt4|bMiITV@cq9k2`~*rL?mt0VN$h zI8jE%USUfUdK3iwu5dVGWESe)YHRGWf47kg@8&taiv()@>Lt-p>fp#*+>e{R2kV!PUDA^r7o=&mO?FldN)A%NF&ox)T{vz(*G#L|%uC~6puh=Ts5*w@pl3-c?p-nW_4;`U$^quZo!(gA(S8au(s4~_Z!bZ$>ok!;t{=9Y zlt;u>rGD6yG8AC)+ev;120RPDvB%^x*+>o*RKCWhGPO`rS4hrpkjhNBB+U^wg}JP9|ZHKmD4cJr7nZ6 z1Ve1PohplfoiZRB;V0fILsSHYVDp5c2Vyn(G11SD7VS{ZyG%pJ=jDB^C%pa?T|#Cl3gciK1zzwvYq=IB#t4T6O$$RC`M&A#XE*K z={W_dmx@+=RgOqqq#}8kG6)weC>JJp2sbZ5hD#$h_{E(X=t4a)b}5LVNR`-tUerV! za0vSZ6zsL2_4~%OE`JFa_I1>|%GAHsk1Z>i%zrS5c2z-ot=L*?5mCw#HM3Ji;Mvq| zX693XfAZXonjIxTrMrWSGnppW?Svy^3z9^{33Hso?p3(*)_|!X{}K@Pz!m|nLK%dr z+RF;)L4JhkNVhiB1|a?4-Y8%^M;jY%ImQK^rKvBZXiX-^;F^x3sg|K7xxbU zZ{`i`MhPQumLKG*r4sI#0i$*Dn!n$fh9=61FDaO##z5Ucfv%sB{JR$t^6@sX-=M!J zKt|8JN0p3BlWR#sB@6aW)ddu92IE(y;o#9VA+M@)dEDQg}49iDTgkhVwmE zY}bm>;R;y(6zSP|y5|<>-iuCxSX01h279_yI5#*&S&5)xN7myI>J$9GGtT?|X`E*P zjPoE()-XvFMFBm>Q`EUGi^E%oGXD#JMqdW(DgoZSZ;kBLW2yf#@z*#fCHvnS=fYxR zs0%Y-_8N7CAZe+|saa~W@xqahyRugWz{{k~q`40i@Pt1(`K(&$pn-oI7HuJQO)QIf z6GrZlxVJc|o+&5DdAl7h^?_c0Xn9Uhnp z>N!KW*PKuRQa7V9!WeB@n~cP)63=A-#NEucF~3*A3bbmtxRR7yh0@CI2bk{|*g6>v zdx*r@W8c?%T|?22S$O5PbH6nAGU+PVhU0vu#>CsbO7aFH8QrRT$O!PySSq1wSRKmm z%<&AXTJr5muaQ!crA=?RA|*w`Z%Ch=qqhmi;zXImf!9ypprGfbWG0vIpo3nHO zHycHA+@2~?s`eCQcXZ5I`U8W`d~}=%D7Z{Y!66lNuu^Rt*4)+6B^WxZM12jyTml@k zbh)7tib|_T#(_WngkRrBRNHpo`1EB|)|zwQv=6D%Ig-AO1)Nch8=VLs&Pf(;!g`*N zw9hqcwX9?U)@=-P8&sT7c&Go8=h8xnn$J2IDZH0f`fW5DLbewqE^8p9&!+)@JrsjC zblMwKcMzW}w1+>n;e1eQ_02^}c0%9v zpdwZNGje|(n&#{2e)91cMId|h~jpND! zn|J5RZkGeT_#*0X3acP$A;B!S)oqvp7)ghdbh==-Cc zZQ-cmi|W7_7GkNfBT|j(P4;I+Y77LO8&q-TCAKu3NL4;XXB&mF_7Iz>z5-l9V+^nRC!45^|GF zC<0Z!kqi|3jt2IW0@t+dH33SC|9u ztjPEbky%3dJffv3_`)JGmfW~3Gn_|cO|>TOBAfBkBHU?KJYO)XZ!L>bA&J&#Qm*Ue zQe}iW?dWw(LCx6J*f$?Kb1i2bfYOw-UhIeDv-@al;@~dX7K2Rpca0F{7sWc z;tg5({?coE>_jE_#EZg)R*SEYn;XDt_t)Y0SV;Ge`3xq5D- zt%oZ~>Wka6K@Y%%^)p;r)n@S8pc&eV&PcSoN5h-}=B%8%X)JlgWJW<{{{S^;#Pwms zVpBs;2lHR9sm+fp8$w|B)>AKgRvt@;D^`I5&m^oRbm&UUJCA{k!HwedQ&&ekcNM7U z2vMd7`NV~Vu4HExEF>W2AWo+gFjVuxq|1UcR8U&#D7suv-(Ehvf=CVyFiWQEBILtL z8%RS%U)(=@0F#})hqqBFeNXC(l`FT$x9ks}KQmWP`h)-Mn{{vf+c4zYM+eP!$`wUX zfn5rQ`XH~J*Z2<~QX4v$1DfK(22Uv}ff`c{b$D!9(MjjLDUL%hM%87-{%pulf66&i ziYoS32i7i6Ts;COCg9jWof0G#swucXjE1A?hNR3ocjh!Mxc#cr=51NJ`9OXvq^3W8 z7`wVi?fT*L@fE$940$A^!f2r1mh_R3=ib}pa2J#16Tyn)PU-vr&Etbu}_);r=bL3NrW1_GhXj%di{KLR2Wpi zDUPKq+JR;cDGo&Ix1UakiSLV&*Jt-u#VL&hEz->V8{DgK?+Y1Mne=aC7hjqIbKPke z!#-_6XrMD&hl|OgAytK&AlAbt<6km_&|9HZa=2-n%kl!2LFN{VEJyG;U1*UNy8aj* z6ZPqWdf?}$m~`U`!0>bVROFP@=*ZGKC*E;4AFgm_-$F7}7|QEMvc9EyD+_8N`W1|= zD5o088Y6sXEkcEVPH~_BE=yAD<+EuJOXpfmR5n3wCTyQALGVqs$W4e(NQ&8E04%Y3 z&KPyf7eIrJ-d-b1NwJEc{JKH+S*ax>DCtSPPoR)$N=e+JBi;nuU4cBaM!omsT~s)N zL)U51dhBi7Xvpo%`nu`%SYPIFBikdk`f}PKPvl;Xzihhn;gxmsrfh$9`1r|q$}kc} z+5n=NculO{D7kX^y&NRS$qe&t)PA#$)0^E z-*4?=0Jvv{g=$kI+~r1B2z8}*P8M5#c0k04&WEQg&;BXM*G>H8$Y8X4IBdAWYp(`S zBc+Vvd}K4^ddS})XbO6+zM=i165NOxhcEofQaCXp&;{6iH8(Su$6>@6Lbt{B1A5BE zi0^zRXLxwuR|oF+8!?9*Han+E&ptVtjW-==kF zUifii#!jm{cYtS}G$G02Rb}D2WU`ZSi8{h9c|31k)pPnA88L^C4&7J%XJl>QG!RwE z%q#Y6NVZKdHMnBXz&MmtvYD`I1h)`jr3J%-n%%lfbj2r2n}gqko30nj8P&K=uf^j%>P=mz*4yPN2uCx4vh?s3 zMX$}54LD4MCJD$PI~7WE4f_D6Xpo9hf5{b@(1w$XNqfhVepzuwH+X`)-Pu zK#K%#dx*)lu*tt$YY($XMY17+RJ89Mey%>rjDJrSFqoZQ4SK5QCiI7&H8*meCbN^K z*cN#PU}Ze}a6j?D#?=)H0DffB=xvhlHsdR*fCMg;g5rU(6)qgROFVQ8ftst!&Dog8 z^i<$|@2!wknDu_>;BJLkc(lYLamsd)W1C}xeQ;Dz1Wm=GgzNS!9VXRa2}gH*k4(SA3*}Ek zm?g>_P5dA1p%t(J5A%AR1VpR|+R9m&RCOe|*==NG7t*Mm(zG7YVY3m^;oj%r{FUha z1%xi<4SZQl?r1&%Xx7_bk6Zp&OXPKHr%&hC)979SE>~~3srcO1IfzJwjVc{{%rrTi z)oFnTGs+7)0^%pKt;M`f*Vn~c!dhv;J_z2lbfeAV z(x^g2aGl})qpkGAS4@TKeDmIQzp9B0lUWwpx_TCCTCzm>yUjHjGxh%aj|UKft@NLt zF+Z`b=utb|)Ye|K@Dl>K-A6O}E&Gq9_+CI5Y?)lD=Tz|I%=Z*rM1?Od4qPZKyO0L) zybp$|rABTh9|R-yD%R(JwqO{Dxw)m9y4fsq%T%vTFYS}DXPykHO%q>IeIO4#Wk2`s zuM(K4k#2aT*dN%weIHTHw{O=`9r*vlBZLx0zxrqYfzRf1Yb6mT(nd8oPO}fQoIcj%m82eh!tEtSM z0!%9#u~*oCCH4b5+2^i=M&GvPjo)X9ofn0FCH6LxcCR08+#BPzw$;Tu&eiSSZrofu ze!4aJ%XWDp;hrJnohnGgsHhp2r_T!dIkXRLz}(7Q3HA*@q8It=BXmGDlD#6 ze6b`JLw`lKwCB^M$DTs)7ARpC30io#2pLo4sl=XAduOq}&IoEX!3J-_n(FMPiglBW7Nm6y<`@CZ|-8B`=!tL9Cuxr*##zdC-rr$cG*Jx z(=2a5;On;^-vC`(o(Q|6^nbJ1-$!zOpANd$;7_JLb!Z#KVn6WO2!FCneLbBaVz1XM zV$C09KmHKN{DFwG0mL13n{(2+!n?Ibp=V@pWnc9EDlAq@a6|JD6Vb{&rO4Ma?y0;v z56fZMZZ~Qy#A%A5e!EUpnt$X^Z5YkGiUp@wOmgF{DiM;W^b){EgK`=jr~HPehjYm+ z^S7>^Vqmyh4%3i#At7JqALyNxg;z_UyT2H_&eoQT#l%M$jR8}1BuXZZCK4hni5^>N zpp8a;lZsvS`{@^5Hr(ZgqEzxiZme8LmbPB(Ws`~Btds@Xf;FqBlhXp+cTxpcdHVu( zviKfI#ksMA5-Jq55#jxbwgM<>6J2;l^gx7U;8JBlMy(apngs^WtS{R4`1DCOlU{>0EcDBq3q+c-W(!60iX1tZcNOWGM61j8T4pzxtm2|Z0J zA2EUUYxh_zjnW5KxzLi~J`JlQR3**HvsFnbiM@j5CT9hSaHCV)~$vCCzB< zIQHulsS=UWm)6=f?a&z9&;JHa@%+Dz482D~l*0P9ZKcvDH;mu=XE#ENX!vq$*J=|A z+MPSiJRWCx)VdR>j>nZ>q*aRe{U}9-#lPqKd-HQQ9!IF>{cbz|u+i}>#~VN!F!JsU z&m4-^B6;50bS0nm@x*z1Ev05d1+4O#=f3=4iFIYE+(^yk7OiGI`9#$E9>a{;j%z5oiCF8BoQBoww6t@XpIT#c(NF38S zizo#H1=N^CE0KAy3u+4Ip~jW)uCfykW)gWXMWsGgL!PcYAXyc+ zWmp|*rr5kZveC8z13pCuE{?%v_GiTJRo}fiM9Ak0-7946`Pyf6N+iuiWW zF)+oHKv4FB{n6GM-D;-8p&3MyO6)+<@+<1%A;N$Tjue25$RNEGugTgUAbQfxBnJ0S{)GGag|{;aX!+SC|m=ZJ#@xSa?A(a@cY@lz* z&1PFKEmqSWWKYXH8||5;Z$D7=x~N~OK@@X34+i{GGPS;DR3V4tDTIY9NG-DVQ_tpfF>B4_;wc9E<-%R7K z0?Yxb$>=V-I2clL9@raIxJw&LJXl}Vpfw#N99Pt){+P-YLec!;0Fy9f5M45l;6=i% z?6qP|}y0{?P68pkwWr{d<^{aB>=AyokdgF}~kOcM!nP{f)n6CmVW z_eRg&F0&)yBFBGXy;L>4X03@li0QPk{@;O=pBy#ZN$lkyrsb zfQCR87*>sox% z*5NR;tkqKVJu`}71lEqi#_XuO^=ra+wE}9}ixTV;2~Y`^2I?VZxPqCE(LDybqn0Qp zr9m!BfKX)fQ*bo;asKPbSB6p6M*ComeAAqmBU)6q7#TB zjP=7BKpv$4j(ydOOw?1U3#tNAN7Y}2#s4E^m6@^qPYOJDj}-h|*s*y%@blvAjvTsW zjJt`yCh#QaaT;_f531H7M3c-2rF0+X^xbIz9{atY6O^<&$fH{qNE@L%WW#eK za68V@6?4hAY1n=|wSRi-aggt3xUk{J1cn6D8U;&1&+ z_eHL29)-h%-KR?>;}B)!OFxIA+p9{i&rC^A>xX>R!F0NELVu#iRzM{R&6};L9mDNV zQD>DbKntpZ78ECVcBX#=qbOR;R9%rW*#gG3kV!E)>QVKvZ;i>o%>7z`<=E z^45VKlZ}PvX}c56d|25CbS8+L_GS>x0|W(#)fjq77F2IKUA6-9=nblQT~Vf7DOazB zZsI0lp@xI?c90Q=+ivx}0~{zRcey4_53CR0litlA%g)q1IV)Z{+C~$3-*_dH`CuN3 z(({rf7FFlRz|N4ye-X$BT3u>$EY^1P%6*(mz0+cgwXal^4mXuVPABjm{lp(z=S{zA zamgN7y&1u_T|Ns>xlg^y)}eiweLFf@+M1E5^uE$cvE?RMAsc1mRk_@9S%bi0;~V75 zkg1Ar?uL1qv#3;!B*BCVmgD^}T0(E{ye_VW!0385wBH%u`R@B+Y`>Ff2MI8*Kx&H%XKLUX4p>FRF{~2V5{|mB@13>nz{{duAp?^Q=hNSg-R}+zAKd^O z{#CCFz|8Xn{`ow}+`-#IaJ}pft^c^{MxgilLD=?(4=-x(?hk-p=XpLq(nBD7dRYS9 z{d&&?@ac#{H!t?_d|w8H23^m_46XDb``3dJ(xhY0vw>qdBfTq9!ldb_yB`@7>7#OuMDF9N}fK@a}c$Ilx6t&b;t+%0d; z?U1Vw{_S>vC;v3bFX{cXaUBmpdM-nI&APw#{{+J3ei+#sw5)9Ta;wK)eZ8da1Ow=N zh=j|x9ga^nVQ*g?$@Omdr9HbXM9i0~ErgV70->&tVRBz=-Dhie1BQFw_s_(g;4MV@ zcLR5W=M}yRZA>56lIPExr5*8Z{I0#TWbTl;FISG#D+sIC*sIXQw_*LKua^^jeLgs> zmr#00&o?1~S@6rRD`T)TLxmTgjG@uV3@361@<%A}vR8`uUEv1=0$Qv#WAlPJ$x%2Q zoon?MWLbFS7v%)_D2uuYeaNM~sDkvny~Xn&MrK*J2kNy=M7Nq~(*l$4^*O4Ukq*Y; zkB0+-OK*9U+^#pr!AuLJ{d@_RdX!4KFoG->)o%)Dxe#I`4LyrN%2=n`CUwmdN+{xq z@Lh-7{~gF)3IN&VoChS|kpDBtE=$jI7D!&q7cj&;9*))fV^Y?0G)o2d3!V4dMc_yd zd3Ao{3`HewvA&?8S4vPIrP6XegICH5*QNF@<2Zk`5h*yfTHUV|9Iq*JEb-s?=Q1^6 zD+3iB#0~Qh3pi5=jgvpPW98T4S%RFk#Pn`8z zMW4*($^D)6`$6_A$|UoBy*;t~bxH&K$o57{@Z8%rrDn~ofWc~wYsq=KMdGNN<{)W7 z_B!%llb9M$1c6R)W#)5^n!>(n*3}ohh>l1T)2vuUKINA9Mnpx{%)iDfs6~P_r13=C zu~1rTNOHBjB1oz$;8-fzSlO{$W_SM^T9SnRD-sxLlC%m`@GJa+LTx|V{2Qm0y9YR$ z%XEwgDQ@qs*kMhKJW(&S2`gL zPig)~6fLV(5mYz~shPUOvBY3AzQo>s&EF$0&xglP&WD3=tkJtWf-ZeL{A9oDpCEhu zzk}@FN}=|Wl6S-djJZUpDqwTJ%h?ITnUoChC8)kyvdp)#{{gb^k!-yD1=(Xt7C*Mz z#!0ugrX}f5*B{#79DMfcz+6t1n=;PPy)Ry=d`M|`P$8k4vT!vyjcRKD39>ubNjW~A zaxlY2gu%7q2E|c1BA$iXgL6)mhkDF?!s~uJe1JlHRD-mF8!OxUWE{v`R^h-{;`;rrJ~clMa)JBbgOcf zx~F&~*6%#8ro#PxU5a3M$6$dPDuuGBBX{uxcs7W_gnY$7L+RhigwjS9u0sE-7%jg1B492poWd+Z~2uEq0JzNu!(q?=$0uef73szg&8z@A$Ut%`^EXhh6jKEArf zziN1iXf@^PXHL$ajK^2%@LzT^!#JZLD0Gfq}4`A8?X0N^Hnh!uA}WPDh43gb2cA_ zJJuo0=9sMc%pQ4C4YUqFPMO}_y=Kk3*CVdJ?eep&M|R z^PRS^1q}#km!GQ_iuwZ;(U|?Bb_hy3(qh$H>yy}eQ}@_W+U32Y^RdKfKR*Xw7^*ku zUCe*$WS0l;{T@#vSZBcb;9d}uUtCw(J1D}TDE&Iwa60Rgd+2y=9(}Qy{1X>ya`5@1 z?LtI#_xAYgPB7Ii@$6s3a;D|TLDZCocQgwI7qlcb~ZWRK}QX|~) z_nOiOaB$!rQA39wd1N)GBu}8$_4V158E_fQ2=c9sEZL_Co}y>EH1|uj(`@)aMFqw~ z=xIs@nTMBPc>p(u0L|s3c6ScETe^Dj*_zO_Cpbr?h=VF;q6ws+6ow&|8n3nQJ!R7Y zk(8s;sUVZK3fv}=&#D)5I@RLUwVXY`X%aG)N3pfx*WVJ7+N z^GGi`Qs0#|lF#MsraE%#<19d%$wA`Nva{FttCuUVw)s7ad-B8G^g|qT41!we7 zGDdH-Z&Dw>$9&OVd#-+2w`vM@^_#iBSoU_7vgfv!!nz2pu(j5C&s2kIFEEXYcJL~H zm+IQuXs)KJ8H{Be`5K?BNLuq*5cV~&mG&Eu3ZGb^c0$P}9MEbbKCK zfFgO|B*&7ZtsjV5#NC!_rzr_xke+w=9z{eNGl^M*4}{#5tNg6td4LmZEtcnW*BH1Z zsbm<1Y;|cN;B}SSs-F|+HkLy4iPr*K=b+uZ#Y)}Xz`D?f6IuywG5^gTW=48ow$d%Q zB19;;V?Mk&>A|iucQKRjR1O$*As8XTMVZz2j83n0O+g3rmrP z8zfGuuLjb{^-%^+CR}IVl6UVS@&!!)k_&Q5Yn`!oydFFBAlg0|unKCupu@1&qUbmH zTH0hnbv{JrGjFEaG@X_{8z3-J)*!hWvy8&1*fRBl=|sNaAg4n0D~XdgE&E;`*~b2b zt?=caJx0|Y); zoxJ~vWcS(l7s-CIH=4NNyzx^x^X({<2Ew!1YiUNLpDiLF=0*;u%@af;?kovBg<9UO z0(lSLv6ZBDc|q+$)-efCx$pa@#QH8uuR}VBG%GDjW9dE^6?g_(pE{ASYE27gi88Yc zZt{`)0VkbP%y`z`-)=hn)XkVv$1QF(&oK3$o3SJO>h%i-pb_${YHm{dGRw$6tr3QD z(t5x36kF_O9o7^Aq6ZZS zh$ry(&ssg3?WZapb(}${CzDe2y?*CeIl;^dS|slQX`)b|%3$6k9OtJdf#URE%RhhL z=i_#f*kX~LE^xUxSo~IsJHdp>i%wjg(B&NVplftlCp)A@lV)%?+~2`kE?4DYi@&K+ zr)KUUfK%Q{E?4S%mMT|lVX^JbF*Jcof{0qXAE3eyjU7VZr?H!Y*&9n;)zQnYI415%Zh&Y@w&I&izgIsl@7?(5FB;~?nL<~vaJfC1)5K|jOA+@M(l+2^oJh)lXS%|?9msHkxNFTBFv zUBPQ1IvRga)>;y7frQkV`TYO3qZCcr- zT8D6y-L2CE<`mF4uQpUcMu3I2t?)`H-DN`yD~z(1484Hh6!bHimyJUajsh}83f*Qw z1Ctr$mQS9K11(Y&=KOz&?0*0vyVzfmy-DERh%ImnOt#52egjH2!~~peJL!Y30b%qU z{&dkOTS>58rRV=!L5PyaMi1caV^O zK{hD?N-7o~fT32`kI@^2*m-k90lWS`G7UrfDawZwwe zU`oePAyZQq14-C`K+N@mLYz`aZ+kjyJr+izUGB**>jHtD0n8jKMXGY3kdvbx?;?^Z zCo?_`vHuX+q5r=`_TK+dWJmp%$X*W+*(-=L6B$TDyQ=gLhdhf0?5fWmd;Tf1nXHPhe?<2!-e?@mEFiWDZpgS^Za$vjO z^9pp?3$T(brRBN+VAm&UZ*G4Gne=$AD*5M>0Tf~zJ~BxN(T!O{_}?Ixb%l* z@^WMR`FHR$Sl{fH7vKmNpSgAy%3g$mqbmUEt~s{xyl}*$LK?43jaw1UXnd7`oD?*X zT|qMcB%I=Yp46*JI}H9u)grnaQa$@dl;%zRcoaJ-DY`(!w3l%YD+RxoG#{LLm|*26 zJ_Ro64)b(UnyNfXR{XP==(|>1?1Cy{p9cXRn03H95Nv?EYuvY1>CvDgU z*^hWCa|-Ui2n&sPlS zbk#AMOO439Ou;HpHpAN?N_5LAtsMhow+`xiQ-2dZyb)fs!?6D1j@y)6`^u6Mgybmw zXUmI{6armdMK8j2*@!F`89#>pQ^9c{v(~Qn4ZU*8?#IhYb(gKxhjUykZugFN{Y6JR zH|>Z8u5?^g&!PV$7J{FUY_K&#v^^m*^ml_JMYNv7D4MJwx~q{{-NV?2<~mL0y($~z z78h{5=Y)jV330X4{_KVrSS5zj$vI9c=$IViEEnFLG;m8ib@nQeK-1XRmaa&6Glon15 z@QO^7Fzc;ez4JCM{EsfDu|IlJr_SK{u#KnR-v;_Z1R@!rmRHP6rA7J z<$W{W3Bq{zyb=Vjk^PHmVs$m?6Z0+) zQaJrYsMd)*m9}*iN5vwb7D$rphG+$t5_Nsc=>icI$5J2|b1$-mct=^0roJ74*Rzzm0WV>S3V>`d#?)}`5Rmw zMo77dru~%^9>8NSiqrJ~F3(LULQcs;UC8C3{WT}Iq@BOB^Q@LD3z5@~pe9@Uhge zD_D-3V_XE%3a_-^ji1Res5A;B=)Y5{x7$_}Bz!2=8l+wDq{${;}SOVa5y zoIm+kkkW4Q!+BTV##EEP$cWz|^;^{X=YPo84!90gJFK+Oh2phlupzp*ex8+~{Y0q> z`i0FVIoht$SZC+iXouxx&_LEqKn+x<{mbEA|C0(`&_V(`J5p1(SGLQ4=d!)lV!@;D zSA;3M>QlE~l0E3!#zycxd#&Y!MKD2R_t^Af|+VgjtIEF2V}=Qe5o zG02zLyaR|6E(PznQHQw8=8+(LgX0 z#GyCc8?^37i^izGF=W%77>fM2L0qaQolrgUaoobW4aSZ1IVG+P|X&|bN>h7X$n zJOf@eAlX34J`x%l)(ejU%PgPtlGFGh3+@3@Is}_Tu{xanIj8Q|)EWD4!q86WQXmLO zGkcOzr46`N<+L(Nv~jnQkhWh=K2ssDbH+j&V+ibKLX#`R*1c@%=eGT6yOYx(00i@r+x}6AR6^?n&KOaUJ&(hbD^JIm|^*b1`YqZmUXT znR6NRd8bXUpOssI9PXjWb6*gNcFJvX4-$(%it+7h?7B1t`$JqSJ>SLAygtm~sl_xT zE^x>_J?-C%3r*C`i@+aHrCZphrS>ivitE~2hQ*;*qm=qEq*W(M5QFLj%_m}o3%iO$H|b>vE5cj)E7{YkVie%era)cW|QOQE(--+D^uDtf=xpC`1l7CIhwBab$refr3eoTm%*<6YCdZ^vf1C5ru%xk00^ z1;Ax9II#U@55Y`5i6h!#g@3+=(Uu<4w!i!KlM~C|!l>z9oG02$N%_c1R+_HO)KF4Q z%BK^;MF!2+BF0=C+#3a|o-sQDN_6UHz#$9kPbkOw7r2hP$ZKtE`xpa{;(*pG8i;BQ5H|J+!B zuD^m;Ki4ccuj6X*Hcsq6@3M7$(f_^gyjfG*^8IrU&+DHS$y*<})OeR#nw2gnst<}I z=0O-258?VVd!5xpIBb@;=zD`Mm#_cAKphn}ILybG-)b=N0{Ok}o6$9lqy`%QIJXQ( z36@8`rUDdf0l6#Oby<2J+(!smKPtvbZZ9C@6O#H2LOu>~K2FFd(9Kao9<@AtZ0KNu ztS=K12kyoITmlv(GA3qfOij>z;4Gp?U+a6*S}vw#`Dvy5G-4f#w|s^2N@#iD-GibA&F-b^p^4`zzg*`npQ!ioDZRH=vgT>pEp8bbu#>G8 z_b=@0>%Rt1N>e|%&daJhotEDWKDW*whs`3cpQ_i@b94WHX*+awzZu6BF7syG&~m*8 z^LmE2ZK1ix^2qtnL%_NNb;JC2Sl-!;&Xs|D->Gm~0q=p8vWjIMCI1McGmjDnDaFj_ z#tl%vJ*)eeYI33xEAgj(C9Bu>=3KNFAt}tc#Rs2H2C4AjbQ2Bc;<*@d_ubLAYoK-4C z#NMRJC8eT*W%so;hD zc;K4J>|-{%ssQ9=lF-HymZ)qLw)!;q%HpL~i1+rzW&te*loV~OxZvc;1=VV!0yoh> z9nM@>U_=Te7G9JwRm@2zQ(_RQwUuMJ_`C>1(#pT)_>RNr5y{SemC(}*x*bKZP-&t~ zE<{`%(_{=ZuM=s8_e5^4XQCQ%FSBjv#qQ|SN`bKo?9OEa{a)frrFKr?f3dDpEpIjO zK81D#ylTKj0xO}VDuZ`V29$$>fvmBSg$L3obV!+d($hjs!HpcxzrNK%e^Tt&pEQ4D z+Auw6j@-Pr$DW!W@9(iBWf9<>1Li|mXcNJVQZrP0XZLCDHqOmAPZs~}Om}AoW(5|V zC2n_g5$6(Pavb-vs;+S$<@X~Bn0+iu1|@g9pNE5{T@`GgXa*%+){19uO=(MTZzZ6{ zapjVA9y@}sFbIH9mKvADMC$pR?PT$St9V}OP!Vxz|2a1aG_6IAuzp%J8{G%3jEsz1 z$2)o3?{ez5iw!tHnl}kx*bS@caOnQ$ZV`iUL-XtMHIm!0^^)vPRw)s!h|(#c9Lvh$ z52H0SA!k*Lj0M~iQHBzyT9qOTA&v3bgv#RLB|rE=yZv3Z)^3y@_BlBfxsL)j!)gtY znz1+5JBA&hFg>AFN}6k&bpTmuWrO5Zvc|E7KX`m-LKq1bp^7oQLAqH6y(ndDfCMXT zE*a3T@S%dV(AH{5J*8Ea(&Vy|TxlP6Ew=4S!fX0kUl%a!)gtd|mwVH=MI`o-fUf-+ zQaIOd({sPeFcUCU%!x& zy{z4EZ+=tXwhr4gWqn6T*AW{V4My^0i<^7{#X4R7$l!nJEImc{lY+J6ySq~cJcH6b z4Vbi*l~bHMuPCm_RT1!4a|z7oxhgdSjt<~Jl4ZurM1&~$#5x4KdLd*#dEC4{FDK`m z0&zTmWaF))hL7(V@>6vm_a-S4E6{Sg(SE>jyhr1#az2{nCdFk8L9P@MNAE2LNQ>Y0okTXxcAD|Wy5=OF&77FLG> zD7KdNF4%U`zV3z(wXfng`w@_y8r^YLMh1rQIO zJGVRI$Gtqq+xs5(@*H6T+djzs5GQzm;E~K)ya=GkA`)zZ?u5N7@9j2fH@Cqwedrd5 z9kc9$L0Y=}PolrSZprU&eYWo8+k3W|VQ5&5xSJ5)n#i99WPRU=yc02TQzc=#D?b20 zz4qGqWXJHn@y9j*p9GHlG|F5eYtfTmetumoHea5%lK9i!L;Fz%1fth%@H9!d=2NT1 z=P#QznWL)3>KV_|_o~-bSR~wlorz3>5E(0zt1K9KsXhMY62Jg}wD(YFQ`ANZsGp(oRVA(U5S&$&Y!IwU zyk}@rpSKz;Ec=SeDNuNk7YQ5SbXc%iZYmbPlBjcl5sZ*iN$YHfiS4N*yPQBz_Z~_k$Km1Z2R00!^?CKBOb&>0NdO zgrrx#(#olDha!nrr>5Wga^AQK#$5{m;EKP!zO3^whGni|F;}tpA*xs$F824aD>!<1 zYrXG&d~K53Hl(%zh7BCAzq55-_JEsme|B_%=BXp`Zt}4d`0fA=_pj_2NKe%ccqKzg zcqcJ-Uf9}szSm2kR2~1gmoa!Gi*TE?)o05;^@|*+LalnfJ0XReT$HH_g@dYDIB+D0 zP#~!?U+C#Ml{=;%A=P-FYPBU5A|GF8jMSZQk11%i(Pj-bA-|kNC8wehcf9NE1_!^1 zU!FEA|FT}x6X^Q$j&R#4Ee?z2HE1k)XeqT|_7)jIEhsR9H+Hd#V`X=1pns;Ed}8M(J! zc-$7?y2|Sav?9xBYzqw!qm;;_lFG751qoOvf#WM*dMXGFcA6A4FA*~b@UvvE(3%SX zCIcnFfs(tT?X~1@g+8$#PodUvwWv)=^tu23k{`%h@c;sR=*)8uYp~RH_4Q$c-_{uP zam0Bxuje1%-;elqPEcx}+c1v2ADSUQ{k09xucurusCgjd^bnebbawK=iqe8|%iotn z!9vw5pX*uT&;0bfczGY$j{6wEJ#lg#yI4Hex$Mn-8xAv|y4&!wcEBOzIb}S(2V%Qq z8s~w!ad_?h&4Wk3cOIA+4Rt7PcmUP9(C7Q%!o%OZ2qw0}jnZr*W||1M+d^CgKSiM2;A~>uU)oR<;{OxzWTJ2EZ6>W zm8-psYmCmDBa&1jbsA#Ul#jx z4C1wT_{^~X9r-i*g)JT~L8^YGZ>g+#*VRbH>}fXXb_qBOm?^tZa* zaX-_xiX8DU5r`D6wa(SeQkl+RI)>#4p=v_(Hde6-X6zQ#8e-_r^9_v}txkHJp|S`7G`>6- literal 0 HcmV?d00001 diff --git a/backend/tests/migrations/test_source_pre_cutover.py b/backend/tests/migrations/test_source_pre_cutover.py new file mode 100644 index 000000000..a79cf1409 --- /dev/null +++ b/backend/tests/migrations/test_source_pre_cutover.py @@ -0,0 +1,122 @@ +"""Real predecessor PRE jobs must drain before their evidence becomes read-only.""" + +import asyncio +import gzip +import hashlib +import json +from pathlib import Path + +import asyncpg +import pytest +from alembic import command +from sqlalchemy.exc import DBAPIError + +from app.db import session as db_session +from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitTerminal +from tests.conftest import _drop_test_database_schema +from tests.historical_submission_fixtures import _restore_validated_snapshot_rows +from tests.migration_fixtures import _config, current_schema_revision + +pytestmark = pytest.mark.postgres_schema_contract +_ARCHIVE = Path(__file__).resolve().parents[1] / 'fixtures' / 'pre_cutover_rows.json.gz' +_ARCHIVE_SHA256 = '49156dd714478ba5d9b446440842b6b40d8372c4f05dcd38e7edb3b6e59f4b59' +_PREDECESSOR = '0070_submission_intake_authority' + + +def _snapshot(state): + """Load immutable captures from actual pre-cutover reserve/claim/finalize owners.""" + encoded = _ARCHIVE.read_bytes() + assert hashlib.sha256(encoded).hexdigest() == _ARCHIVE_SHA256 + body = json.loads(gzip.decompress(encoded)) + assert body['source_revision'] == 'e2b926288899bcd9b05e1a560ec19b6bca8cfcfc' + assert body['schema_version'] == 'workstream.pre_cutover_rows.v1' + snapshot = body['snapshots'][state] + assert snapshot['revision'] == '0065_claim_starts_work' + assert [r['status'] for r in snapshot['tables']['selected_pre_submit_runs']] == [state] + return snapshot + + +async def _state(url): + """Observe rows and guard definitions so a refusal cannot hide partial DDL.""" + connection = await asyncpg.connect(url.replace('+asyncpg', '')) + try: + return ( + await connection.fetchval('SELECT version_num FROM public.alembic_version'), + json.loads(await connection.fetchval('SELECT jsonb_agg(to_jsonb(r))::text FROM public.selected_pre_submit_runs r')), + await connection.fetchval("SELECT pg_get_functiondef('public.guard_selected_pre_submit_run()'::regprocedure)"), + await connection.fetchval("SELECT array_agg(column_name ORDER BY ordinal_position) FROM information_schema.columns WHERE table_schema='public' AND table_name='selected_pre_submit_runs'"), + ) + finally: + await connection.close() + + +async def _refuse_after_writer_releases(url): + """Require preflight to wait for an old writer before inspecting live rows.""" + writer = await asyncpg.connect(url.replace('+asyncpg', '')) + observer = await asyncpg.connect(url.replace('+asyncpg', '')) + migration = None + try: + async with writer.transaction(): + await writer.execute('LOCK TABLE public.selected_pre_submit_runs IN ROW EXCLUSIVE MODE') + migration = asyncio.create_task(asyncio.to_thread( + command.upgrade, _config(), '0071_source_first_pre', + )) + + async def wait_for_lock(): + while True: + assert not migration.done(), 'cutover checked rows before excluding old writers' + waiting = await observer.fetchval("""SELECT EXISTS ( + SELECT 1 FROM pg_locks WHERE relation='public.selected_pre_submit_runs'::regclass + AND mode='AccessExclusiveLock' AND NOT granted)""") + if waiting: + return + await asyncio.sleep(0.05) + + await asyncio.wait_for(wait_for_lock(), timeout=30) + with pytest.raises(DBAPIError, match='drain historical PRE runs before source-first cutover'): + await migration + finally: + await writer.close() + await observer.close() + if migration is not None: + await asyncio.gather(migration, return_exceptions=True) + + +@pytest.mark.parametrize('state', ['queued', 'running', 'completed']) +async def test_source_pre_cutover_preserves_or_refuses_historical_run( + isolated_database_env, migration_lock, state, +): + """Refuse live historical owners atomically; retain completed evidence unchanged.""" + snapshot = _snapshot(state) + with migration_lock(): + await db_session.dispose_engine() + await _drop_test_database_schema(isolated_database_env) + try: + await asyncio.to_thread(command.upgrade, _config(), snapshot['revision']) + await _restore_validated_snapshot_rows( + isolated_database_env, snapshot, expected_revision=snapshot['revision'], + ) + await asyncio.to_thread(command.upgrade, _config(), _PREDECESSOR) + before = await _state(isolated_database_env) + assert before[0] == _PREDECESSOR + if state != 'completed': + if state == 'queued': + await _refuse_after_writer_releases(isolated_database_env) + else: + with pytest.raises(DBAPIError, match='drain historical PRE runs before source-first cutover'): + await asyncio.to_thread(command.upgrade, _config(), '0071_source_first_pre') + assert await _state(isolated_database_env) == before + else: + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + after = await _state(isolated_database_env) + assert after[0] == current_schema_revision() + assert len(after[1]) == 1 + retained = dict(after[1][0]) + assert retained.pop('source_operation_id') is None + assert [retained] == before[1] + terminal = HistoricalSelectedPreSubmitTerminal.from_canonical_body(retained['terminal_json']) + assert terminal.terminal_digest == retained['terminal_digest'] + finally: + # Return a clean current schema; never force a historical live row terminal. + await _drop_test_database_schema(isolated_database_env) + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 3aef12bb9..10c88dcdc 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -320,8 +320,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 277, - "e9280bafac00f22e4bd54acd1c6dcd3699411a927269f5132f3cc39ca31224a1", + 278, + "76a24837591d210de2d08cd6fd0443693cd2cb6057bb1a2c093b7540f9378797", ), "project": ( 258, From 437958a13f187995f26894b90a41e19276660093 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 00:04:37 +0100 Subject: [PATCH 192/513] fix(artifacts): require accepted source custody for new bindings --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 32 +++++++++++++++++++ .../modules/artifacts/submission_bindings.py | 20 +++--------- backend/tests/test_artifact_bindings.py | 13 +++++--- 3 files changed, 46 insertions(+), 19 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index bc5f68409..8025b341a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6666,3 +6666,35 @@ Both isolated probes cleaned database and MinIO completely; current files were unchanged. Historical reader probe accepts the captured completed row and rejects an indexed request-digest substitution. Fresh main fetch:191ahead/0missing before this commit. Full old put/admission cutover and publisher retirement remain open. + +Current binding cutover scope: app/modules/artifacts/submission_bindings.py and +tests/test_artifact_bindings.py. Current consume compares nullable operation IDs; +two absent IDs pass, allowing an old ready admission into the current writer. +Require a nonnull accepted source operation before any content/binding mutation. +Preserve the separate read_consumed authority/receipt path for historical data. +Acceptance: valid old ready lineage with both IDs absent rejects before SQL/content +or writes; current T5 binding remains valid; consumed historical evidence replays +without new writes. Prohibited: old ready auto-acceptance, deletion, historical +reader changes, authority shortcuts. High lifecycle/authority risk; ARCH and QA +review, targeted unit regression and real public initial submit/T5/replay proof. +Human review focus: retained data is readable but cannot become a new accepted +submission without the current operation owner. Full old writer retirement remains +separate; this closes a live consumption boundary rather than reviving that path. + +Binding regression reproduced before production repair: historical_ready with +both operation IDs absent reached consumption (DID NOT RAISE,3.03s). Require exact +UUID accepted ID/matching source and unconditional SQL source validation; remove +tautological source-nonnull OR revision branches from consume-only lineage helper. +Historical read_consumed is unchanged. Final units21passed5.61s; Ruff, structure, +record and whitespace pass. QA independently verifies AUTH-before-disclosure, +UUID-string rejection, no downstream mutation, old-guard regression detection and +historical read preservation. ARCH agrees removed branches were unreachable. +Public initial/T5/replay v1 passed104.89s but may have imported before dead-code +cleanup; frozen final v2 pending. TASK create replay-only and SQL old ready-to- +consumed barrier remain required follow-ups; no full old-writer closure claim. + +Frozen binding public v2 terminal0:1passed75.71s, database/MinIO cleanup complete +(/tmp/submission-binding-cutover-public-v2.json). Current signed raw ZIP acceptance, +durable T5, retained history and accepted replay remain valid with the final guard +and dead-branch cleanup. No code changes after this run; final reviewer closure +requested on these results. Same single draft PR708; full goal remains active. diff --git a/backend/app/modules/artifacts/submission_bindings.py b/backend/app/modules/artifacts/submission_bindings.py index 48f27de9a..f01c4e643 100644 --- a/backend/app/modules/artifacts/submission_bindings.py +++ b/backend/app/modules/artifacts/submission_bindings.py @@ -114,13 +114,13 @@ async def consume( raise SubmissionAdmissionConsumptionError( "submission_bundle_admission_unavailable" ) - if admission.source_operation_id != ( - str(request.accepted_operation_id) if request.accepted_operation_id else None + if ( + type(request.accepted_operation_id) is not UUID + or admission.source_operation_id != str(request.accepted_operation_id) ): raise SubmissionAdmissionConsumptionError("submission_bundle_admission_unavailable") - if admission.source_operation_id is not None: - await self._session.execute(text("SELECT public.require_source_submission_admission(a) " - "FROM public.submission_bundle_admissions a WHERE id=:id"), {"id": admission.id}) + await self._session.execute(text("SELECT public.require_source_submission_admission(a) " + "FROM public.submission_bundle_admissions a WHERE id=:id"), {"id": admission.id}) if admission.status == "stale": raise SubmissionAdmissionConsumptionError( "submission_bundle_admission_stale" @@ -311,7 +311,6 @@ def _task_lineage_matches( context = request.task_context references = context.locked_project_context predecessor = context.predecessor - revision = context.revision_context return bool( admission.actor_profile_id == str(context.contributor_id) and admission.project_id == str(references.project_id) @@ -323,15 +322,6 @@ def _task_lineage_matches( == (predecessor.version if predecessor is not None else None) and admission.checker_remediation_manifest_id == context.checker_remediation_manifest_id - and (admission.source_operation_id is not None or predecessor is None or ( - revision is not None and revision.disposition == "ready" - and revision.source_submission_id == predecessor.submission_id - and revision.source_routing_manifest_id == context.checker_remediation_manifest_id - )) - and (admission.source_operation_id is not None or ( - admission.revision_preparation_id == (revision.preparation_id if revision is not None else None) - and admission.revision_preparation_sha256 == (revision.preparation_sha256 if revision is not None else None) - )) and admission.guide_version == references.guide_version and admission.source_snapshot_id == str(references.source_snapshot_id) and admission.source_snapshot_sha256 == references.source_snapshot_hash diff --git a/backend/tests/test_artifact_bindings.py b/backend/tests/test_artifact_bindings.py index 296a1904b..1abe51da4 100644 --- a/backend/tests/test_artifact_bindings.py +++ b/backend/tests/test_artifact_bindings.py @@ -229,12 +229,14 @@ async def test_ready_admission_creates_exact_binding_and_consumes_once() -> None @pytest.mark.asyncio -@pytest.mark.parametrize("missing", [False, True]) -async def test_source_admission_rejects_foreign_or_missing_accepted_operation(missing): +@pytest.mark.parametrize("operation", ["foreign", "missing", "historical_ready"]) +async def test_source_admission_rejects_foreign_or_missing_accepted_operation(operation): request = _request() admission, content = _lineage(request) session, authority = _session(admission, content, None, datetime.now(UTC)), _Allow() - changed = replace(request, accepted_operation_id=None if missing else new_record_id()) + changed = replace(request, accepted_operation_id=new_record_id() if operation == "foreign" else None) + if operation == "historical_ready": + admission.source_operation_id = None with pytest.raises(SubmissionAdmissionConsumptionError, match="submission_bundle_admission_unavailable"): await SubmissionAdmissionConsumptionService(session, authority).consume(changed) assert session.scalar.await_count == 1 @@ -307,9 +309,12 @@ async def test_broken_art_lineage_denies_without_staling_admission() -> None: @pytest.mark.asyncio -async def test_matching_consumed_admission_replays_exact_binding() -> None: +@pytest.mark.parametrize("historical", [False, True]) +async def test_matching_consumed_admission_replays_exact_binding(historical) -> None: request = _request() admission, content = _lineage(request) + if historical: + admission.source_operation_id = None admission.status = "consumed" decision_id = new_record_id() admission.consumed_by_submission_id = str(request.submission_id) From e52a215c379a7ccdf2b639639bbb75df4c308012 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 00:34:43 +0100 Subject: [PATCH 193/513] fix(migrations): enforce source-bound submission consumption --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 60 ++++++++ backend/alembic/env.py | 5 +- .../0084_submission_source_binding.py | 32 +++++ backend/tests/conftest.py | 2 +- .../fixtures/pre_cutover_admissions.json.gz | Bin 0 -> 57029 bytes .../pre_cutover_admissions_capture.py.txt | 42 ++++++ .../fixtures/pre_cutover_writer_proof.py.txt | 53 +++++++ .../migrations/test_source_pre_cutover.py | 129 ++++++++++++++++++ 8 files changed, 321 insertions(+), 2 deletions(-) create mode 100644 backend/alembic/versions/0084_submission_source_binding.py create mode 100644 backend/tests/fixtures/pre_cutover_admissions.json.gz create mode 100644 backend/tests/fixtures/pre_cutover_admissions_capture.py.txt create mode 100644 backend/tests/fixtures/pre_cutover_writer_proof.py.txt diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8025b341a..7137d2511 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6698,3 +6698,63 @@ Frozen binding public v2 terminal0:1passed75.71s, database/MinIO cleanup complet durable T5, retained history and accepted replay remain valid with the final guard and dead-branch cleanup. No code changes after this run; final reviewer closure requested on these results. Same single draft PR708; full goal remains active. + +Database consumption cutover scope: new0084 migration, focused migration test and +checksum-bound ready/consumed predecessor fixtures with observation-only capture +recipe, current schema fingerprint and exact test-lane registration if needed. +The ART application guard alone does not prevent an old ready admission from a +direct database ready-to-consumed transition. Add a guarded SQL refusal for rows +without source_operation_id; preserve consumed historical rows and ready-to-stale +owner transitions. No automatic submissions, row deletion, receipt rewrites or +generic producer changes. High lifecycle/schema risk, ARCH/QA required. Proof: +capture real old ready and consumed states through pinned owners, upgrade both +without changing retained evidence, reject old consumption with exact guard error, +allow staling, and retain current public source T5. Verify schema fingerprint +delta and CI registration without weakening either gate. TASK old API removal is +being traced independently; this database change is not full cutover completion. + +QA-SQL-BIND002: real split0083->0084 upgrade refused by stale env.py supported +revision list (still0081), before exercising newguard. Expand scope to env.py: +admit exact0081/0082/0083 predecessors and0084head, preserving unknown stamps. +Migration proof will traverse0082->0083->0084 and repeathead upgrade; rerun existing +unknown-stamp refusal. Do not infer schema fingerprint from preflight refusal. +QA-SQL-BIND001: raw ready update alone may lack later Submission/FK receipts. +It proves exactnewguard/order only; stronger pinned-old-writer control is running +at0083(success) and0084(exactrefusal/all-table rollback) in isolatedoldcode process. + +Fresh0084 schema measurement (separate isolated read-only diagnostic, not the +failedupgrade) yields e028a3b353a8112bddd77309722cd0dd69e6fe0c871dfa00c50f6da88651a90b. +Update tests/conftest.py exactexpected fingerprint; retain its full assertion. +The migration suite must still prove only the intended public function changed +and no captured rows changed. V2 adds explicit0082->0083->0084 and current-head +no-op upgrade plus existing unknown0030 stamp refusal. These runs are pending. + +Pinned old-writer control terminal0:2passed233.74s with complete cleanup +(/tmp/submission-source-binding-old-writer-v1.json). Production owner code is +e2b926288; only current0066..0084 migration files were copied into its isolated +checkout. The observed test recipe is retained as pre_cutover_writer_proof.py.txt, +not installed as a current compatibility writer. Each case creates genuine0065 +ready custody, upgrades schema, then calls the unchanged old composed command: +0083 commits one Submission and consumed admission;0084 raises the exact new +source-custody guard error and preserves every public table row. This supplies +the otherwise-valid transaction control missing from the raw UPDATE assertion. +Current migration-v2 and public0084T5 tests remain live; no readiness claim yet. + +Migration v2 terminal0:3passed321.59s with complete cleanup. Captured ready/consumed +graphs survive unchanged; only guard_submission_bundle_admission_lineage changes. +Split0082/0083/0084 and repeatedhead upgrades succeed; unknown0030 stamp remains +rejected without mutation, closing QA-SQL-BIND002. Current public0084 T5/replay +passed59.25s and full cleanup; canonical schema assertion remains enabled. +QA-SQL-BIND001 closed by the genuine old-writer control, not the raw SQL probe. +QA-SQL-BIND003 adds actual writer serialization to ready case: hold ROW EXCLUSIVE, +observe waiting ACCESS EXCLUSIVE, then release and require completed upgrade. +Final ready-case run and independent omitted-lock mutation remain pending. + +Final0084 ready lock case passed248.03s with complete cleanup. The independent +copy with only0084 LOCK removed fails exactly "source binding cutover did not +wait for the old writer" (238.93s), also with complete cleanup. No current files +were changed by the probe. Structural validator, Ruff, record and whitespace +checks pass; ARCH/SEC scoped PASS. QA-SQL-BIND001/002/003 evidence now complete. +This closes the A33 admission-transition portion, not physical-provider/history +qualification or full operational cutover. TASK old command, ART old publisher +and preparation retirement remain next; keep full A01-A35/C01-C07 goal active. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 2de71f052..a9f9a3bf8 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0081_operation_read_authority" +_CURRENT_HEAD_REVISION = "0084_submission_source_binding" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -135,6 +135,9 @@ def do_run_migrations(connection: Connection) -> None: ("0078_submission_cleanup",), ("0079_cleanup_authority",), ("0080_cleanup_decisions",), + ("0081_operation_read_authority",), + ("0082_policy_phase_cardinality",), + ("0083_accepted_revision",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0084_submission_source_binding.py b/backend/alembic/versions/0084_submission_source_binding.py new file mode 100644 index 000000000..2f52cbc19 --- /dev/null +++ b/backend/alembic/versions/0084_submission_source_binding.py @@ -0,0 +1,32 @@ +"""Require accepted source custody for new admission consumption.""" + +from alembic import op +from sqlalchemy import text + +revision = "0084_submission_source_binding" +down_revision = "0083_accepted_revision" +branch_labels = None +depends_on = None + + +def upgrade(): + """Preserve retained rows while closing the retired consumption transition.""" + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.submission_bundle_admissions IN ACCESS EXCLUSIVE MODE") + signature = "public.guard_submission_bundle_admission_lineage()" + body = op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))" + ), {"signature": signature}).scalar_one() + anchor = " if old.status<>'ready' or new.status not in ('consumed','stale') then" + if body.count(anchor) != 1: + raise RuntimeError("source binding predecessor changed: " + signature) + guard = """ if old.status='ready' and new.status='consumed' + and old.source_operation_id is null then + raise exception 'new submission binding requires accepted source custody' using errcode='55000'; + end if; +""" + op.execute(body.replace(anchor, guard + anchor)) + + +def downgrade(): + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 199c2d077..d2a028b58 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "4f2fa4c887c1fe29c555b4af534227535c7b28b2ddccc53013c1e62eba8625a5" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "e028a3b353a8112bddd77309722cd0dd69e6fe0c871dfa00c50f6da88651a90b" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/fixtures/pre_cutover_admissions.json.gz b/backend/tests/fixtures/pre_cutover_admissions.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..13977f8d10ef2baa47f0179c903ce932f1ceeb04 GIT binary patch literal 57029 zcma&NV{j$R7d{x+tnYQ>Z;S# zb*fL-Ip=wrGzJdre**&Ys^=U?Io81K&xrZ=d`@Yt_w2XhRAc;V(MU`jR+PStX(E&f z6Xh@B&ez+D8<=_9YA7)jzAz$o8sCaq>U7$sMviYkc6gV?7Q$|&!-*g6ZubjSF(%T7 zziF3Tfoth)hXA;yb2u+p7GqS}F99FUEakh!AXW(H=~|8IpxC9Y z{cb+-6rwOjo^BGwQfI+jq)FHd81=_Dmp8wQzgqVCKr?;<)Cl$+#mFVE(5n5Jx#Q9A zncM9+86WS|JINhE4*-2O<6%)9;I*?+afCrKNg^o%ePU|tLj`t{@jAMi$*cm%U`3hP z5}ovMK4FHPYrNaQcL$(I+x5(8>b?(FC}FpFmC;V3m*aq0^Bk!>V6JIxEv ztg^7V@IqizgyMzLnWZ9ia{fC$Azt8*)WNTs00hwz}o6xTId2j4N*~Y4ZPZuMqRoHaJ{ zGy7>MT;T&{{h<4m^Q|HQQp&(wN`o0gl?3jiEkSgIc2>A<2cA-@R4L8quwFv8EfoQb z_)0GaAPHpWT&R$Ru~?K?0#_5kvjpgM)iHo8%+2p{U+Bu*WB%+5)4=z8 z^i&#}(YK5yYDz9^)|sc~mg?6YiUhxHxI}p~do3`m9)y39`nY_V!c)s8D^^CvIA%3y zq6a-%lWypg2I0o#ky$6*7rR8&;pzPxBQSmh{{rHXJ0iSg!_c#wegQPwEoeH52JiBdt8 zfxbwRA4DCEJ@%=^S|jZ=TyJt8Qx7Xcfn(bMt1oaY2`iB{P!jVaq=Qg_xs}5>YVjk95E0;Ryn2}C zv39j*qgPPZ0vxeRv!Lc<0{m`7lXN!JMm)@VQ`MvQNR7tio|LRPF%WeRIOh1esCB8k zIRlPV>dPZ9zz*3Y1d~TxppHjX7Pxqv0iD2SMZW%N#Us>4){V`0Prhm#=Ai1P$u&`# z0lMh-XuUaix|MW_wg4I3u8NgbYYqqbZ;+(;)`~Zqm@_uoI!M*B=U&79k~1=4CKw}5 zW2lX-nPNeGWT(e*;_e!!J5t?Ao84%74`{^U5U;a|qU~6_Q;x(c1GJeGRQXW9PEr!=sH<=M zD>YZ(HA!c;F^EsrAOlFI?>l=wD{v&vo@CB|f1?abW6X-AZEOMCBTufp9X-HX7@iyc z=ePYo*VXzk%IckZ=P0F>8{UvwsI^N^Gv&_9Go?iiPt-^cKVn}E;p{m0I@m6kc7@rw zI+S=CUiXhzZfvrvl9fnvcSgIaf5?>efDvr=*a1rmk{9NQICdgI9|nR|n#}?6r$X~9 zH%3hY3)tQ+C$%t-9=F2Jc*8AzYv%z;+X#GuQR^4C6g3#zG+y_gWG%UVqBiKBY(h2F zFX!iWLnO-@YN39f39|rqJmhDcH*j0q0N6|V$zq{T6&qjvggoD>FSL65P?tK`s?OP- zG1?NLF5@|DxsH4HjQbC2S%F`XH}-G80fBu{l`8P8DVv^7qe6c6UAap4HTlyf(?F7AY}x4^ zWZdLUhu3r(BCsOI>eC>cEq6=L-&#=Z>tDS`| zOfV|<=a-dCk5O$ZPPV|3SKIUF43;CNy#`NUZfWQz5zVC}(emJhDhML97ylRH6p^G_ z4rAq60hY&)+t4TtAQY1e3Tb$YK}NGzV*9UI_Gd%-IB~FG7NJ@ z>rCY&P;pqNZqY>RFF*9-8>J3d8hJ4md_}<_5w^A70GTp;W`PU?1kLIao+V{ zWT`@c-TiMx{nHNV6nE# zqqRqjwS+9}sfZ_r6q<84qQmRUS}EaC#yG*2=`r*8D(a=)q34uVww;}%}27G5x=T4K@T)?Xq6f?`!mE!j2|NRTE1XEE(a0D73yBY}}>1;jMb zM$r#~$yVf36y4z^R$fxtc<@}KWhvRoD04API>HYN1GE+&i)}aWnSsCIzZeYch)u6) z5ohE>Xg95rb-e?h{DQiF(5#oK)a!$9a-daH7wDQAvYmUwec)qOm!Y3UfYpC0I!VbX z%8xzN8PTp+WdHp;T;YLOSu?f}vZ<6J;J}<~_ob?^?^QZewg3F1(>5H#tXO-DyguOY zCZPLd@l~K+n=MLvfQhwbjO{a3tC81Z?; znz8Ax;$>cPK5xHQTxX+UCy0hF4XG$W!!JrZIXzZ>OXz6HK_n^ZHsXgGUzS}-H?_P% zA%@%YWUMi2XcxhB4}pifEalnXD;ndH0b4lXB8d0 z5~I-><6n@Nb7;zg9&@!;F`PKrkM4SDNC7jpONG zu1rTcMfb5svTcW5LV#_JZo<1oXOazJ>Tmqro4lm=(whmjafSsZaBBr4H?<|;$bWg> zS|+CL!yRoJ5`Xj2?^x;47ziGzlkmjon$ql zu@1!<0qBF_4^OSzU2X?2D9a+Nb6-oSmjjw>V#W;%DdyD6sj9Wzhs!I~<4vxHodI-I zvzJmj#{tbgJ+Cq3Ui~^l-=>z}!>^-w3ilU(7dcSb2#b{NGzqN=yMeJQj=|p)0KduQhSP0>+foVLw%C&lYW9jW-9| z7qKylI@!tVZM>TM-v8b2yru?R?<{OQ4fsmGCNcQ9i80-vAJ*l|lc&WZnZw3HQBN$*7LoBy!h%#s9hOtuXUyZc zUqJkm3i3IANLU(f$S7@t;6ex&=WEoRHaDdqmcJT{ZeA=ztd3u)QGrTK8wUE=vd3@k z%1wN3a;IU$jHuN|g(GG9o?!SFmyNFXF&q~l1}eHaIY^m(Ir7i%2qze7wzi)KENHs} z3N!it(4I+eZmTv1ti|x4ZxXQ7mH*VCHJysmacn2fge29gxF4l*@oO>YDtITR?A}^7 zkyS_OM>A27le3+N(W|L$(ji5DD$-enz*bQ{SO3T{GO7XwkGU#uO~O|u*=hh(8HO>d1vOV6h~YMN?Zm{_AAma zE8al>ytv4dtVter2nmC+mryaOOMm}w_~ykUP$hu4X!Qo^V6l!K(3`(@ZcQIFF= zo=$34JNKphNC{TPo#$Ej&)2~;A+U!Sf~KZ)ZM)iMyKd-mgUelFL!=y54^D>Upm@Eg z1>_;z;eqE7p)Y@k!Q31YM3&-&29QmQnt*4B_%sCxprpGhIN%#8GPqLr+kwmDxWhKo z6l8cG(#rKII{?q(nmN-_tNjGLqLj@HcEvq9?sLl>FS!@;5*}v#kn5(`DrnkDXi-5LFs=u>nJlZv9ek@_|>(~ z>5w?HfQ`hJh1Pm`1`7PDi{bQ!&9t}c3TMV~5iOstoyVy!m zt+w>O6wECnQ*B#-AS~kL8^b_V{xdA)`2c>|#w1ubYK7yTq4N)ZTW0A4p|c{PytA?s zxPWolzSpvNlsLW4ve8Yn>rN$$j=RU1GhErHHCi}d#|qn5pj!6{LQ}s?k;fsit7*GZYM{NQk=WfGn$m)9Y%-; zcB;n-PyW;E>F^c*@T#^eQSMGkhKn&nX6v?{D0`t(SWH8|mc*u4st!MxBVx4aW(^n@ zvW~VJd%QM`?NMP_Yq;|xbf5Sm@5Pxx*fP!O-2VLV4Vj9^2T7sCj@3}&!6gaZGMcTG zgUx@%H^V;$*T$ z>Aqnkjdyl(4=sH~9W?KN9h#8S&B6o$XJcU1TT7TQAH zKOW26D$Y)Qta4OR)e^;(gRk9dxCs3kgyiPk!kKP_qQd9lJF5T5h&D{#8}A zz}kYA8D~>LC}tv&Z^DD;uP=^Ze$W(7ubk45Xb=Ahv)ZLfPh$^JmeY`7HxI5z$5p~7 zZ_&euwW@Q7H!qCT=yj%T$mh?TfH84m{xuaa)TySJRd}2xi|M2kU2n+ZonmY(r4SRl9#TL)b`K3`zuyO+fY=bQ9r^KZYa)56OR`ELwx46t#q z5iHx_sf3zTh(C&aC8?Se(p5$jX>?XO`#<5pT=O=Dn-LDE<$|P4|AqqvIg;gnNQ5M% zAl4YyKkf0+vg&+nDNwA)<9{?geJ2zLX{5L1txb8Vw}Ji%;oI+JpVj5=K=okqOU{N- zY-~(Zm2tR<6+f|oN71f2(8Ma@#bIyy?rSdN9Gt6d^C=R{DU~OYbqz;f0i;6s+1$x0%VOj32L5N4vBiVs;R+ z6^I<3G5?$zkM5sDY5G+M=RsY=jQdSL|G5w`)!INPn zsIk#p<@}a?RQ{pw1b}3dMdK9jx}M%wj~$$%QZryIrT>5|JfC__l#4sYGDm)7%^6TO zPcHv9PM@bekX_u(MbRX)fJV##<+;EO(L|rcSc%r{w*oUMXP<#z3(Mr#nXP@GL7GkdV3{&U!#1( z?vrL63nC4P@23Bkk~SrOnd*&jD(()4%-Awm*)>{H+0zO&|I}f^P?4I|hLX=H+RT#m z84nW^5(HhHroc}Z*Xo)#C+Vjz6-sL>LX)uPDmnyYT&-z3cy3$QdB~+7ArS4wjr5H* zElZ(~rgv?0*(eJeZn)HN?-aMI%wJ1Hdx`m}iw%b*$tG$=_~{o1Egw_iBiom?d#Pz{ zmZ)z~b;#p8Wc=3)PD4R^CGOy51>Il01_{7Ire$(U>qtcX%NTX?iL;^p;=IrKB(o&; zK9|Hw(YMe5&dR~Pk7J@Qs}E_>GnfEEfXgxB=%9$Pdt`Pq1<|D1YMn-i?qLp@C?b}Y z=>>#=FYwk%hBD$tD>w?%!Bx>}m{o;CMSHn}O|NaXMiPV2r>OaJzg+xEf zax{$EZCGe`BPqzR6p3}K+fCs?KVv2h{26HF!L9}G)o(SS#H^UysHAqb7$&NV^Z8*~ z2wz=r(@Eo`WtTRb;B9*y4?KV8Li}9Tp?4UC#H~l@aosMkp)uQ}Kp&tbRhV>!rbD+f zO>2Vt%tN#{be9tbK}3-p>>}u)k0?=xd!{NGYFojCn)Au*qiBF7>Do3OVu@npmlHW2 zb2X)E9^2Z3QW|l)`Re`t^Ek9A*0jn;@xBPUv7WV3YM57QY;X$Ps;b_(7LGV*+RN_~ zvu>Z;q5{VC?*w?TbTa&adQcDfT8> z*``u3K2gu85H}-j!Hw2xoLpuCY1Q!ftVuP~j7|-5(dHluavS%rT5-FUAuNr!6%twz z+@dxNjcp0}mJ>z2WFfyK=uzP=kNt{{{w8AtSIAWhyb3!y3z5l$@BZGrLiGxpSmD}Q%{OyPED9Ft;Trfl=<7}pkB5n zRV@A50K-vRn3g)3ifG$0Hl3aS(jqGV)H22^0FYtAL2i_T`LONfabOSo%NORyqBEuF4Ut>FDHly)Ez z()BSYj@=eu8B*R*su;(ho`T(q9|~&QOz*#~bW}h_A7E2RrU^Y2ImHDS?2j42J?$Gk zg!M*-fo~swI`q+Wb*g&Mp(ZB{VEeH$EQIx(F&-oI%4`8i=+_cB41*b_f+@DP65<^3 zZbV>T{bOM)YDk4i+Le=MA$s0XY1GO-o{{uWkd!7DhgjkjjU`QY)Y%9Xw#zweWtb}u z#|&XRZVx~uIFD!rML|N$kjr6?F*L{03JmphND?`%%#!}*gfKZ@ZG10P{Ftn}V<_3K zdZ&D(ygoNp~ ztu*s7dty$pIZVign?px)MAsOfKtl3!Y;j{wiD4a+T)pMQYer`D#87E`#BnNoyY2o1JWI^ssj4_< zptu9BHcV-cXwY~G-3Wb?Askf(7mz(Sr-`dd(1R2!zK5BO?Y3O6ia?E?hi#>n{vl2c zAO1AxyJ%^J1Im`Av=A2LG$IQZ=7*whOd4BXpA0=?tfrWQX6?EIE=^r$CZ|^;rmQOF zXbnuML$`4TapiRTcPHTcHk1G(?scVgVZoU+-XhfmkNZWQ80mxi1aJ|O(9xVJw)AFdMg{QyZy@G6->(G z)vZ%JkUie7utta%>a{$?LUqsSM@N6SRo7Yb7jE4jEh?h^!NpW=+Vdzl5d()rbTP9j zL-DET>N@K9Mg=B|xW* zvhmGHaBm8jSBS_tr44>72$ZE$jrEDMSURasQ6-9H#RQdCvx6U!1ywg6qiZf;3SBzg ze@ZP=!S`oekCEf|R~)bc*M~3oOm3?Q{<^~WSLDtXz=W1f1?=La1%a zledT-O`4%rrHxgj7N7wki#jj%k66^>dnmTKV6?4?okOJHZ;>{+c4K5Wgj?|<{2OXR zRK}M;m4%M3U7(6PPQ*GDUEQJstXLz*6PM3M(Kj@Dp7H$(_R-K>MiVm5wc%f9wzL>S zayE$ESLz>o)~Ns+r-qNx0cF6%Ke}rk=ZDg+nnRyvs_o#f>aeD&Zu`&_>HF z4r0t=0}kc>KatR>?MvEQvg-{yx+3YS95HFZ5a!x6Wy5exigy;Lh=h!uPcm5em~XsY1j_ z=(-XE7yAk;*4@R~9b$6!o`qnTqI()wxyGmze!Tr0>+~92fNm~aK8l+zv(Y5#Acjsb z=0SK11p@Go%q`A&Q(sTbAxYUk!az^VI`yFSS=*Z&_R006u63Im;#c`HGB$1|zH~)) z#+H<@D6C6tw2eX2h4y2wAU8%O{&F~5SO+0i_IZqQYS6Z&np3s`A6~n$oZF#B&p-(r zqO9#LGPY>7?x-wtgoFjtcEt0c-sDktQx>8UQauEh8XT?I{G`*hQjlm^iW!w2J~(l4 z*ikH;v|N!7zmj{L;w_Q-YsYRr(mlsdeD_J1X(#4oBDH#q3M?usI5e076l~dK(};f6 zv{=1#GT&}l&D*nu&3kQi`!%`pm?Q}}aS#kahGj)sC$csHD{^ct^m0qqO=UUxy76AV z-;$cl=PGVpOqyQQyD{|cEM--=Px_zN)2G_V_7F$O*n4Fi@(^<>TC&*fgA-|LV`P`W zT{h6>p*qHptdZ5h1%MT+czH=~JfW>7-TaIJ?TnviQoff zS7ib@%_ueRY))q3V6E!+d!D@>`^&XHg57>PSDiWnfp*Psm#NoIuTW;r4`|Ad+CI8!jsY8BKTgt)iECE;-0xA6U$#1*KZvv5 zT4@qzM(y{QjMl4g`(j5$R7%NuFXJP4W_Ds`U>si;p!KVr5zXO;40Qc)9Zs%CC?d*4 z1kHT-?B^IU@xa)*3~7HjC%lL9F)tZk8I(Ux2{2}nkU{WspB_B3K)$fH7B`NN`KKUh z;!crYxqc30Fi@}j&fS}Hg=r=YT~uGMzK4WpalCgU56;I{TBU{QCT2pHp8%Sp$}>pD z=V{EpP2GQ{^7_uWH(2JBmzSuaLvAH@Z$nY}og7hrejyb^WHjyFUcCx@e&rSJ-R^?^ zZ#)~=_x~>6T)ie^Av9QCxGE2W%vOr0$zfSZR&P(e-PKmgyqi&3U|_%c!xrep6n;bz zkF__U@gdxC`5pq+(x&pQ>J87Y14Rsf-I9#1mFbS7!KtoOr4@FE*f7gGQpn{QTpP(j zicZ#-B4>bQp5Us9 z^QJOCjpD zp`a<-t#$Gp(j*)66zat=qt^G&ru-&pScXfCsgMZY?<96Xuo$Vjo+oWYQ6ELD^w#zI zV1hhxYh#~0@Wa@N?Zl&!We~((mksslIkinl1!Zu+OG!usSE|{jcH&eNeZAa5dbWJv zf37MA<{2Z5mUDYyJ{jS=rajGxFS1TI%{p5*$!X!dtp56~iM4hJG6w|#VjvDV3nt}@ z%;=-@PuSF$pvh%c&rxy`gl}T6$U0m7F%D=#PYjPKb@*nxScYL}|yDrDn)^d{@XjUa_068T=%ipRSw7)YK zgdy0}_xsvRpm#2_Jb~tHC8H}ydBM1gjfnhG_7+r0+@rf;2V12yy@}jYI z;>ruwiNVerdaHR>*F{tMfpQsCFS4T5&OuIaf4yQ8Aes3i{obZKle#25B>M#oSPk+yE8l!bgp5*{VxhJG3s#qTQy_43~n89+)9RVfe)FG1wjdJ*X1c9S`d12&7kNiCrwDyF)kxZ>3mDuD03Y zT!ojj>u2uc0!2h2?8n79EH4Ta*rsW+hVbHsn?%R+(Xh4=UxJWC+&BKhRn>q@=s93? z=^=-McqTR2@^)JCwV?H_1evsLQc;>1Te3J{5t{7>g*tEGeNG|G4gD&ns()N7kg8;o zIw|!>^YD9*X+y7@va$1WST_Kv|5uQ$8m5sF`s9MEG$UbVMKP0)pWR~4WdKDV$&Fiu z*xk~t0MllUBB>EJ_}@K55dtOJrG_r%$ZD6m#b!p|bRHhuE;x1Z1^xezkU|719~dA9 zZxa1oxy4$&n=-!rud-t}rq!>y@;^#ozxK!zkNW~<@)&0cDuf``d8-(PP`<}PF==bk zmtLMlQmLOa5pW!v1>>pneUg+t3;uJ2@t=_dT&^Klu7MOi%k3MGjWofWO>QJMx0SL# z=iqie$1af5|Lf$S46^ZlTtST4A~!m(Z-4I@gp7|+2?_guE8|LbIc*ADo1Z3AMI<>g zTU@r8H58L=j-8*STaT@wDLqy3VSw9bA-*i zyRhqreWKY(>I}&ibPR*0> z+snb?-|N_lq@jqh|I?v-E5$g;sK@b?2)Dd(lCf0vT|92z_kH2>YfTSsG$cF*3xf=2 zI7^!(cva=F;p1+XoqZ|sExUwkMVcvLCmL4z2xD-a+c^V53R5Fiw1xo>S5RGM(Z^25 z3GC0vpV1rAECH)n{cyu_L~eZd{ZP?KRz+OM6tsV!CR31Ls74{_R@P=*mTBG)jC$IZ zX}+S@E0wcOf_j{kqgo({Tr8xxH*t3gcGmiBdwZPCsyzcEqt$ro3+XR(_7*>+X9Ns7 z15H}$UxHhVU39=5Zk;bay)Ucxa3f#0_Sp8e^1Z(78K2kA>U(x?Zvvi`UbDA+yNyu#%5wfnki_O?9az5)^7J_EYym=~P7_DYDQhvV5KgB+0;v_%2ZoPqsN zAFeC5!hB6NSu-AwUDqeAeTYsQglC=}9oKGCP#)=1lr6ceZHupsR{L>YK&5O)FZUM{ zBhUPKhwLdAB_U^plSn>Wp|Yl`I0h3Kp_HjhS<=6CQRT6&m6PB(vO=L39J#Ikdd!o5 z1v`UaNXn83Id+Em!XU>pX9Grmomw3(3-NeO*NO=$vX(h-x9O(m)xd0XY4@7!VDK(? z^eO|H!EV>zi9b7WSAcCu$;YYpcOG((U6Mm)00PL773-G^nxVlzw_rzuG2T7Oa(rO^ z_#sR>G&aY<*j47&&m*eZIdHk~6OV#<->-WyzR4%nojIYQN=JujrRPifaS!2$0l%B{ zj1WrBz-O&bfz{1{@09gz<6po?9F|z+Anql5~ouIe4YQaA&be~C&RmC zgIw5mPDWh|?kTm5|X;!mu+aWoQ^DKZdxpjQD^E^6xqviIdg!KH3MUh}r z>24IgVPvUuWwK4|CyRUs*FYFf2@0X3k%4L1BfGjyM!Nh+xw-7mzOW&RHFDc^f=!;l z+H+ecwRGyvA8t-s>0WCmp|g}$!n%RBJbG;pLqH&R)9~tr4U2q+Oubg6I#N-iuBx3a z*kCd&Q0iQ`NuZsAQwABy7!7uq4HXARNfuitF1$agS!rRwW)52q2Bt773}4rOQYNvH zBIlvl9K@n-){L4Msc4IkqLv2kM|3i%&k`W$HnMNnAWDGRk6v-4_g^~v*j!m= zGS0BNl+~zi1(0?@HHatMNG0DmCUdYX{J_?&>cqC|mFQ`#s4(=TWB)IJFhuU^9 zM59-)=LR{!Qs#KG~MAh}*ZQm{tv#YjmB(B%C?;Bl&OG!_Io!PvzrVy2%n_V3tI>udF zytm}C4pnbItaW?c+DLYHUb>s;h~{c>{)I0*J9TCPV!U>SQ4Ob^op;#sv{`DJo8f#= z$am7D40j-mAlq#<6?FZzIYIB7{67-=8Q#aKYs^+Yi9a~xOE&(l3pxWvbLtFR8`Sk_ zPLk+t#NvrxRjSy7J{iV{uOcwg<=tFm$1Q#~bB?Ae5o@zcm^u1It)}Sg5nL^gdD+q! zqqnhX0-~I-rJY1R93)nDIdUPsq)@ zS#j#6k$7;O`pL4DKbp#oa~#eetjPH3M}3%Dfv9)Rz<$ueBrqpe*9`oJ9=mUjLw8_Z2TfMAl=Ci z{AlExTmTrJ6gxc3iojytZgN@gj08orwQTV8t!1a~@eAjb*+}k<{0y*m2wKE8%%Qu= zd}3D`^!64os;KX_g5E?pek5G!t^hUL2pZ*<=A$fk<;2z2b;{tM2E12nWxg*|f4*An zE_So(%$8N1L}SSEZ>*+1w@>%%j!Su;_$a@+m(2gib>c2+InsHgPMl7!4>KE^bh-Yr z-mITM88UG+t`ulb*lRI&4P6!#FHaR~jKpzrnC%?%#3Q*t^dBUtDZ4HetmwNYkNt}L zA)iAs@OyR8`yy~^NuaTk_8L#1hw-k!uyQ5&by4_d=m)qE`hU<_Fv{gLT3~k;B2HTp&&_8jr&mEo56CO_NrBQ= z&(FW6MgF1TJ!7d4Ta;Fre*FN~uE(Wo1xzng)>}1KjXAQIb?y*7g$ap{FhlDJx2j@L zUL=rrmbWMuKIAfm%6N`p0?oZJ!rDofW|@$@;>E9b^|BQ?OOt?87605S{Qn_w5{_(= z2Tmj-V>AYkTa4yPAL&kfq#*Tw$p6_~2j(3Oati4!lTS!hQn9nZ2KW8ahH1+xd z{MnAqK74t1Qg@fq!cvR>eN9E05Ono(v zOV-X9w51rCXYzFFxZIOk9MSwy#5U{Q=BEp48B=V}ErOZ`m@pw`Y+Z};Kbjv??^bmy znc7xOa{if$vr$-8a6y4TtDDnhNLDcoJT)YViH`nZE{p9D6|WeyZ32pG92c(084{%o zWV4rsx^c+WcxxI)IM!g%^B$+b@We!|8vZ99V9VMc<#+0~;byN1Sx-IkivKy_&{mW! zmxcKj#L8_`Bp6PIbmPfSNGduiQY{$JmT(-o<5>vo# z87-$vYU}001!~xq;TWM~YW}8c&)8Y*7~N7vA|tuHoawbA>a_CzzP|nown^%2adTGY zLvqZE(3FH#?dH(1rKYlUeBn2C)J_D z*F`o}1RJo8PoB}Xv~gW($d;CZIf{0f8UvFw%oZ1p5uxDO0OWQE?qyk32(JD!b{dWw z{HH^R-uOrt?otBUOUdVg}id z-MB#oxO#r@+RALt)#LDgk>``&N*f(vB}zQH*U7(THi-G{{t4jc?X_ng9N7u6oDGzP zUmA0bJ6!VZNIjeh*?^-?QSLzI$Pg!HUq<>J!Dm!qj1$uiFl$-}x zV1sgAl-WI*|8=3SB`W6>V%e(;YSXuyY}e10wHZ$DX_M$uwXPqm>#n%O6rEJ8PT=k> z!^)d<=y)^~>oma&KihxM^w^JmR_Z;C=rj3eBqYaR-91x@RNIS`KgdR!X(N{+fB0Nm zKJ9O|r84+E-x?9{=|k^5&R?8}t7ogk_!i3JbE_19V?&-J7Fiq#0>Cw27xEmAW3*`z z^JjaMBk9S8Y^kt)^))p2)npIxyoT(^R3DAQoDyuo4a6_x8HyAb=>Ad`%WI4F+4`dP3n`N$ zyOae;^+ELMBB~oX0lr@CtV}X(HhY=NK4h9E^5ra+Rt0qN#|m>cXLUM5YEDax+h*3x z8s}5w(UGDkQkIQqv?5A$?@f~#u{)Ex6x07E`9T{fY4$Ujy|)yz2Bv`Xt|h2HIha9*t8cLrN)+OEXg zTN;{z?SA2*dpIMr7rnx!T7?!D_S$q zu(8`PsSQ`?lwK3sXW2<17kHZMo2xkgRwmF1;9%F-W*emW33MuXft8sv(_%tyFc%zP zK{>p5zjqx@@t1kwXK1A4f;hGf8=nDCy=x2we!At|Ow!Wo!CI>ySt~OIr^c+H?2cuhs5o z+YFGR4r=ng!(dr#EI$89I@q7JdFQ!{p|#VXrh~{-wE%}D)qYZ)zBLAjE27~X8}<-K zC~}aRnbfj9wX=jxvmE9tTt_)-d3e;hZAgr`J&MI{ECmgSE(k|Nzt*JS7AOd==^1?( zla*mQGc@dw97{teIC`)6v{Kj@8=E;0Zc|w-jwU+8@wwZBI}Hq=?0Cr{l%~NUe8=V0 zOyvff*=C3=<$=oihY5-t!$(3zrW^^47Vl00V#la0gX<848(Rz&4Zc3~p}35h zsT3K_Z>=~*QS3h?(J;OP^ixz(Dk=UgTpP9iWpj4AOO3JSf3Y(>;SdbI?H%e1!v3ZHhmn7E*t#L|NwV}o1Qbg3%#Ya0;$P&O zWxy#cG)64P?IL?Gs)_WiIA=uM=yzS7W-qYn(D$;OCT<@6MKt;h64@ba6AT?J-GOvQ zbn@{#cK!&k(&PtogI*_8pfRnx74#ShW^|~lYXw%^P$uEaMXNN9%l9|s?2tz5zH?EoNnl* z0bps4;HmZpS#6n{twi~(LqT~MyK@IYixM^vk_U#mn?WzzC}|iEaR~|Yz!Kdf1I0Y% zk|RqLTnM1aB#NaP60a0%xh67SFWY1xsH;t5P(P~iAWf8g1w^_|P3x*skWpmzRJd{p zm}RH=8Dj<+x@JwXxW+jZY?K3o48ueq+29G{7`M>ISRA1ENydR@hp`&n8Yg49MqTnZGI#qpnjwNs5lMrHiUrL+HMH<97wbFbu|{a`uS=iM6E~xD zLAhoKY4;3>hptIKqh_l*Zyn+d5MHQWdY}uBU;(9F-QE8C`wYBQZ=(n2ws@u#PnGecSmTT8sF|?<9w6Q`r{J>pqQM7(FSqnpkNm+{B ztzQq!k3QAZ_cIfZjzrhI9~K*`hJ}Unr(#wG^?kngdyDw7`VfGEe-mj5jbmb;l}uT= zyAcIzu%OM19|7JG@oETS5*HX!QOs08e_E7jL8~2U!|TuqdXby5TVu zom|I!i?%<690dQ?k1;C*?}Cw;7b_XP?jGxVA@z#J*R+9s|IL5@XZC7jHahhleiD~$ zEqF)I;npT@4j6UMH@BPDs z2mi9srI<5g*L565^JOzJf65uMf!@1y{SQZt)->NdI5D5~4n>%GjCze7ADK+_FloHh zeyL}}-Rvs8;-fLIk*L%C?{hQ-O*Tdn>S};ONN-rr$GjHr zR)uXFDJas?Rg#zG3nAT`Z?yvU5;K-j41LXxgWiS{x9lh~S?AHWCH<>8ekfb;qVZOO zP94!SGTO96ABdK!DXDQ@1X|r0TH^3xA-dGvJtzx&;QN;rUbJJmNF{D~B4sOQdgF65 zwat=w>*Jn0y!ki@ZEA2_=cP^5)|M|}2WA^V1g&K+92C2?|CL7cft-V@#d#~#_ z_^rGnA~~@zs;a(d)`zY&+A&mT@Zs?y?~mO~o__nRCNC`h|9ox-aldqWKia+avt9gf zdvE(5;#K@`1J43p;z@%Ry6(n|34{JVdi5X%U5nhe^*ymXb^RM-{lxA4u=pO_`_JNh zW{kA&y6xU5i0S*S(`(=4i#G7A<-RQb6ZhXX;neScA9CM=o0#8cMsMBU!>2uQU*}Un z&n*5cK?ha0|JlE5+z!5e>HOQhJxBfhf6?{M(U}C_-fwJs;)$(^Z992lPi%8yO>En? zolI=o&J)|X`JHp#_uhBid)Mk!U0vOOlzMe_?Y+OBD!u2suY2ytok&ZlK&P<@UqUW5QLBX4iGf7m)2WW!f{!=XLlqSi$q)8mR9z@CDp{t+_9|o@eyx z|GMw^y3l=Aze?)yS?akqsUhiKBnc<=GvI(yyjJ{P#@>6-q$$oNFx zepI{keJ%LNsd>fjzC_(L%ejBOSuOeaZn^hk1EXi)+xZ#cjqjt}*FOQzkLOB((VUN& z1g0F{4ZMwGZ^!5N2EAeauj1vCL z^QglJehKdzxtNBYlZIhz-z)uRi7(o(_j=zvO8%Z_^`5BigRgplcSeE#^m&aZcK7MS z{&<0JysBI z`>Y>_*nJP^ta|qLXIF`S_lNpd5|QWm&8EH=`u*nDcc*M(^VvREBSUnbH4M9L-xn^p zZ9nJ(;S;a^Gi}~tzScUffdXFGuMr;~EnP3qpZdOM`p@0pjRSUHJ?&q4FFZYU4}5s} z@_&AM$HaZz*x12+tsbxY`n;!nkLDY;r|#D=k-(+?^Y;|XdBuLs`Iuh|{xo|Fzsk{n z@OpLWiK{3f%j;GwSI!zv; z6=cBKE9ieSx>s40gcqqxzGs?4MD*sdnbZq8F7n^ZDxEPcjcttc3l= zcB^Gw4k}2NRh@NHw90x~<4wjgdTl@Cp!pAH-Pw3{sTQ!@J4Iw#E_J&kl!y76J~XsR z081OUV_KNBDV4vpP-!y|9`2~hf_Y4%j3a5u3cgL9$(mz3jTGV>N`ml|`;SlP!*8={ z(S2F#M4Byuwa+)EU^CbO#v%_CeIV9qZfR3Z72q`N3I_3%y3<~vg(>fF_ z9h*oWNX?Jr7MtgVV3-naSZ%o<+BSdBb*@5;LBu5=k^n4c5 z^BIj~EhdGI9)DZrp;F%)b<8UV;o3zEx8Mw)@#}|4F?oZDQR3UK;jNdcR+TB9ZV&u*qb*?^8WYiP2)T8~irV z

Uu3c zZ65Z^FAg!=yB4xazj#5U3}45cb`qPzD*oPPUh=x;pdK7GaL{S6Er_0d1|s3#iI}Zh zDTQ0jaA5)Th!#!SGVlr9C#yO&7?oT(NLpQcreZK#=$HQfVF9^lQBPJv=+9`j z)%+D=(pH-M>->{q?q;FGC`Tf%NZRy;%;D7S8i_4&*7I`Ag2|% z=$&&Kf+dV5zblVCSJYY3C*(Z)YtbE9C62P)lJ4QlK}*oe%LbWYQ%OG)HF;YN9eb%#hXY$+?b3kSy_H3mkB9}TgfM(p#r zILxm;xl!{vF(Hext~tT(A1IJ;a9@cU>(U-SjcFv-s{U|70?Lui(cKS&)G%8Vi~UD) zGi;VR>Q3Ld9DF<>0e(mvk+^x9*TncltbgM@D>{o1&_*fy!Kq!UYt3N|2sAP+b{zH$ zTkwl>b@nnr;*9DWF#I7hlBUb>iOBKuCvX_YZ}eh{AWs#RI{aXR{7J%WKnGkQ0W$k-i+cPhyR8N8MImZ$Z(cjM&e6?sYW z=d+#XK!u3FCljk4B=hP~Tg|P;ioNB4d3lFS>*1H#rUcWA-C4v3?Xz+lV3e13^hxE@ zuLh6|4y%=+*ne>N(>R_b0ZWl!p~~0hj-VUq4dnh3mpC!(0XE>jqQ)$boi2>&=7{re;gxC6tkSs?m3c z|J!XnP3Cp)W^XR1PiPaG{=DN%=dAc&w^Q|3?)cqhg;R%I-~;^D6lLk|6i@rCnsgF@ zccGnc99M17k`kg1{D4M(RFt>av%LUY2_|+Dt)$D-LsqZ_s;vD@T1OlDZ z5?gOb*cA!m3k{{<1(~9@e`0Gn{~Ewb4u=c`!iCr|rC+7cuP{tRa6++pOCWsy!{kGopyx8vwkBLIZ9PFh zP~5q_f&%VX&T|nLrAF)UnI;cD)o+wmUlxd=-{kdGL%~o2>}Vf%;1v1_xvLR{&2idq*Y@o6+Oeo7@XVw0K$*xNN6}y6y=BgWFea z7ppkWDM0crT`~wOTzV&RYBm`l#bwtBey^NN#;rx%Tt8$03vUi1Yx+i-aPgx)m;%zU z^>v)@);_fCCL0@mX>i*f9T$5d%Z7YOJqQgTPA~X*9D+)pesNE4v|l^%RbT#gywPy# z5WO-u`ux>-ab7vFxV0PynleB8usEo&8G2+?krwTlM1d_p|A*>WH0Jx5=9?|R)0>q3 z>`1Du-v7Xg=8Y50jv!)48(0^|O}CHdE8-btK2F zJ*pC_|2*{wurmaV8ld@R*9^yC6MeY*GepST?hju1cEa>Kq+)XHnLA@j^w8xqUT2bI zy*a`1cn8jQ^)>pNCK-DZyf?Ic1;N_5JI+Xv!uw~Jqzn()}<{o5hv*lrX zVl~P-)4sqPpY_{2LT0DU07c{Tn=>YS^nXgPjhPZ@QUA45DukELZ{B54r0vo<9RuH^ zk+wf;y_NSp@%r{=}(;?D1Tw=;k9q+=SG*uqhQwDO8d3@Pl}hrM(xsdTDWpc6HW5VbuvmWNN@M7 z+Q2HzHEQ?FnyW%bGrxPpZav6I{}sw27|`1j-oeeTjXKGeB8@VU1Fd?;pQbUvptH*! zR4IwLi+-Nwx_?4mM0e?Ri=Arkk8#FEy|@j}pkb|g;qWjmc5c+aA6uE3EMegK9g=Ja z4HD9h<~UI66ZPbK7Z%2c@+u$ZCK{d;U0uj*k{`fz5P(4q;i8DY$t`+9Q<7 z-rb6H7?Uy)CFr2pbL3PCb;W*83?TrVOf4WWu~{%9iG+|i6T0_m!5hBz_~A@^X;K2l zWOu9xI)U;H=y|DRldX?me^Rx1sv=Pmy+H$qRq`g^?(zgv-cBB!Igs?Uawon*PtJz=x?{||ZSYkm3+tVpErcKJibETgB zWHR-}a{MuN=X03GIQ5qF-&v2I+fMzLfhXE0v(v-mnI!9b%IUVZL?@u@z`e;UTd*d2 z=zArHv)fhH<<^Y%fcLD#h9fU_p%+>S0!0QvjCLnS)Z?ZqqT8}&KoxcU73sv~;aOU@ zHn$l&hI~V~S!oXhXskay+Py(?r04}17Hn#k*dFzL0Vb#?oT#l_Q1JwDiLrdv3ZHJ0 zvwYS7qqO2BqG_m784ZFw<>yTsn?ZI(4_X=N(mh~yseWmz*9}Ug2&V ze>{8Lvx*PB+{rIPX7%wyEVdc=3lLebA`s`>$;ubF$-=h`<+2c?!GFLI7+(JqR*g2V z##v$!v=jcq%E=7cSc&U585T0O7d#vDOkbfuj}e0t9y-^tCxMf$s)HTbkP=M&4nxJr zPo~8=B6pBbbMfS33dsMt^=j>pWgMf5ayiT};})f{yiC11e;ef^)~hvd#I> z&%;!l67Q$wPramxEulB7Gkkj8dIiD*YjMsy-dycPCB+~3{xu*^|A|Q@7G_hlUV)X5 z2Z#0>Q#HyoBXnV{Hr_o@4b;N{3E!KM+hMfl+%Z1*wxOgMCI*qY`Xy{O4YUL#_~`l5 za~@tJ+X%Bj2ewaY94F4$5-{=oxyeruE*IO%`enckUK|P{d&XZdC~w8JB#>4(_48}g z*ggw{>=adYxZ(AAvsckJZ`2X$er8K@F!;rvE&!=K|7O$KnO ziXYxiHZH}CvU?VNPDKU|YO`-TkYGxfpxQcZk#dI5^W(PD963weYUwC|fDuVd9qLx$ zz^SY;AUA7wJn-FlCQhhwMzzM}U0Q?n=AWFz^id<>`?zs?L2IoduavzHLE5Ar6HDFF z867%tMDI|sb!U(@akyh~q9K;$ENxX*uI%3}Jnp!rJ|!J+MnU()(`i}9no?vb3b0%V z|0~Qw*+wN4eHo8<}(+kje5H3IC)f!6W~+=PR?*mZ9S!B-{Zz?)svm9D#`{K3XO=$p_oA9 z(QA*0@9JF$vEU+kQ$u^1*kw!%8criE4vj(Y=t}%H{m^k6rV87rR$;a|r%gGBF&!%R z)(_dg+5lhGl_N`U9yPi93v6wEx@e2d2S$wxp6X-5AXFEX>d!pH*?R#ei5R~j3!y9F zue%bX6j02-RubZsN2IMGN;6efSdKw1`!1#8ArC+VNfAKoQyzMGQ&H-ah5T@8*@F~A z5@9m^Oe!&zP&_MZO&G0Bbz^U8ga*bnLhk^l_Sv!YoziDk)5eS+wo+esDAwz)rX2c| z)x=^yAV}^o&?w+f{8j(qF)+G)-~vhk)aK9;-C!xPdvw=v!sB3M_>Moski6m1*{F5_ zBRC9FVAnE#A(VJDNm!WhjAX!H%)uT|=FnVA?Q5UCH~!+R(^ep1I#_2?WLd6zDY$4d zNlK!F%(&Pb`}A*Ar(M%1*P1?`HBLg8F1-|Yx={B$798tWd0sUob~xYFShUe{4`=`? zLr)4wvyCt$^`}?`HKIAC;naSS-zvkBh{AFoAoL>qVtl~dr$O^{yNfXv1#Sc)LOV&z z)tX1D#j90eK>b}zN|hH1Gln#qML0oxJKg%#FT+S=2xz;#Iiw)wJhpEo z44vX)b0-a)J90?nZ_Sc3w$Gn?)m-P!lT{(EJ55fLpCw^ZTH)m5{wD_Dq^m%kL_&PKw09@7bl z>)AC!8=3&+3P#}YGx2UlLQrj%tX7qb#65LGQ4Z<=1e}El<^hLEK`1JMX>%H>OB#$f zBe05BO@CDR{$KH45TzY}eJ3UA5*PFe#$CW3Y){Re*xF@KhL#0JQY8tmKS0t1;4Gv_ zcTBZm(dQqpVF{ew>DAr=E}zLdK}6}JOSkGngTVv1!F0J~a8Od3K>Z|}FGS?0QJ=%= zOgUib@RG+@;{3m&!Dp(?v6@;W7UT-nK(d(LjxeLz*XZn+pn7yM-kX0mGa~*bh`b5! ztNeJ%%yDh7DY=h~zq+h_n@0zv|Z>Ke|-2E|-C6>Apmo8egO8 zC+8hcy2os^df3wCWo!f|h8jFzb2-(CdfJQk6&88#@7t#Y-A-;GehI@JDT4>Vv&~!W zcB|2g>fNxA0Ppl_hKIh8c_G7!KCfm5AlJ7`4wYT1ll+)4aoTFHfhS6>)lnh^PHtx^ z5TRV^+B_0YcouC-v!=$OdJsGyseW$m54{EliP`IG1A7|>pK%E!DBACeTjzs4xSw;zP-P~9?OX2KH~!uoVcj}r5S3OHsp^Sw_FFI({g4XLwlYY>|v z_Rjp6r#KBjI-DjhpY_o|I@P2%y8fA2sEA3k&N@qm4OBy@&jdPS*!V}ieBFHv9bwK6 zDX1rewYAawQ*9?3XUn<&6q#b&-?r$Pp`jqgmWc14MHIZ?JKGj3IfOoLGRJjP=fKnf z_!c|e2M;sxuN#yAQmZSY@Zp^>W_P1|@|f;}?=wO+P9WvbPMAKodw%mcZaZFo-?064 z3_vY?k>k4y(>?#5(rqd#%yUw1Lskvn4sU2Z z6%Nn5TE>d zr_$x1*G+(gqJaE*@+YeT=5eKLlAdyLsd+! zpg3Jr4vZSat^IR)LhPTIwv9X@})?PSt!`nei+qLS7*o^3*V~hdWDV zKX}`7B%bb0d2@(pdBq! zpJ^9n-GoV}D;;ipXRq*ucDV*4HGM#&*iLoUKTW9glHc4l$kA;G?=V?yy1W6`lzPlg zF1kssn?cuLgIh zv1GaQ>k28v<2Nw*MlX9!p}6ctQ{G8K%*0Op*9qS|I=jNJchZR?U7`N9D{UA@O3+XK zGK+H;M zWmsE-R++J2wRI8Qc~bLbNghuKml)mc8jIhB>tq*Ox$5(neAe5g)9UVN)9__}+S#F6 zZ-(d|%MXNjq>uuU4cE%Nj1k3e+go94UNVM{_xJAU(+)Egvy=*XTYLV(7TK^3sq6yU zPv%wvQwb%o2q8{u;oU}8)BQ)95d=@$q{!@f-mkrJnPv!8LmkCl+adGzav1BBPJ#0J z=(*#j_I_`NSV5}~WYOk`Sf5r$(Aw?O8$M4Tlx}psQ3b9X`@BnL;Tzb$=bU$nYsy?t zOGwAa4c6A46}c#3%^7^v1=wcGS|^_EE7SyP|Af&`fCoD;#Z*;Y(9iOM>a?XzqFg;2OXS=yn2 zngID}fF2IK{DO`jMu0Lf(GvGPTZj(F74#?3?1CA}t)ZV2_fH}r4ro}9nY-)myg&kD z@3i=pemp*VSPhg24(6n(1<3X%+laA(hIBiva!zjCRh_^t+c-g_aVZVngVp!C-LI>tW$%Ycrds>-R3( zH1{*YbZwHF4gN}EgUx_;R3AK&D{Gm>G;3_t%G?>^1D@;ew=e_52uKu`Wgy5Tx#tObF73K1($=~_wTr(>|@2;z;u)lt5=8x%H(nBwudM{=wZdcFJ zVH8iZI|3VuQUAawourP3L92mDY5bS2aR8=h8rU8<>WyE4)n51#PaE5=xdX0_diT3w z!NI>13?W2ad%4x-E;R8uuN58Xr$6}2Ch81E-mgd9*b;|J@j65Ce@E8piGx(*yoPXg zY0M`LjNEBp6&T3Kotnw6M+o*&@rY#&D4w=iJjy2zC)JImq{{8ug5s6%{{23RHDxJ< z@lfNZ(A0>MvqzCz!ZkFW*y_WIuSK*Z8gagL*|Yj*H7ol1D;OJp6RyVk(v&222_+#3 znTe)XmtToNEVl~1^}Q3N+BfVF>%49TW2#=w+QxXuf3|_Ky*GV~$%ZyoB#6s2!4k*u z4j6mG8V1z>SN*Nq`yB``$Uf|OWdaH3~6)s#UH#!7M^Q?oMgy?r0Rzg zbkL>IZ&Thmd2!M}%K>$kW;=<*6NDH*;oLVE4h4P!Ey9WJHHoO|$<nA3vY6Z3(^Ub))ta@^&kBJ=ek0RA!dNREV%R%SBIoCd6epVX(>SjWY(#>Lqzf)~xgJyw ziE%BjIu()WQ1WK1uUY2j9s*{fgsTg=#ANOTb9>kv4r~`yp=4%7VPA+^=@u$)1DfPtvzf+T-{%_NlX}|5!wUm&h1IT5Ty3S@Obw}E-HpF~ z>k)|-oa@TKL3{6|u!wtSb4sLP1|td@kRX7j8B8*p(bk7^7N}`~9ly9e0 z19`>ZY4v&Y+XQ`3irSewWBKx`#Hdi=%&OC@rLwI`L_kh=2UNLPED{ll_SHD5QU`pA zTff)8?`z8=y!js zYWeSca@(s?M=zwMOo-agGOHSkDvH=(R1kI%F`WKLieSP&t zIv^sRC&HFdQ)@64kvmiNK$u6ops+shK)*<=_FsKC;8T4Cd&?};$Xb2^qZDtLi242X zRw;p$N%$R}0XDI(&F^blKQkaydfm3bn}Hx>U>M0_C!XXg&VB=gGe0_&Pf!M={HL<| zBby$T*g@+e2%w={`;$>t-dFIogqK|CeAoE$9{|PdtutE|YPRXXb)**eQQUEbx%WCw zQCH&xyb&wKRQi_g5Tzmie#3Gs4+_u)Ye%);tpWE{0I*zrq1+%8R;9F}zLPGn^JA}e zwT%sfY=X;ttY`jWiJT*e-6wjSYH)VsZ|&Yiz5}#o4f;Bh@P~cms@BTo&-Q?}291_E zqju{1?A3b0Ge#{kt*rx7=tP@v#D8Zox+zaz z(OEiShxa8`HN1Au>2?V<+u=>=+P=Fa!5&%+gqiw@@C$f7RiV%SIG$ANg&f1aECc5) zMfTU+KAYz+JYy|+s=6Lwl2~)2buyfjLherIn5__bU80Js0JR47=CdWdZa7cmiLKkA zo3tL#3=^y4Xty*rqpNF(oH{tg}%1$kCU5vwWQG&=OBOCxrN$fdyXn|3@L) zWuKG!a$A3UQP%O3)h*?dsbH0eNr&@G7Haz2x0HelPX}{!(4;Vdx)$DfQek@lALOXM zs8PaE7w%y>#Mmxzha+W%2hr)N6ezSiBd^;-0t5e3CBpb5k$!sFD$(&6@8p)EZnj;^ zrUAbB@XJnJMS-8yv?}A|#rT))R`Q;1_B7#@UT-D(dqLKKt_}Ov!&uB_4x0MpWgZg- zGo`UBE*$Q^OkIe1)6_nSf3?O!+1OFuw@jhZAotnpN=mhiX^X!$X8rL(T zajLR+dsK6Yv441F-~3QY6L3ON*F#PG5V4wZ>Hdwu7+?Tcf;FJ}IB(V*wl9v@OAV8} zV2y_9I;^Xc8NSr>dcN8ydcL~KTUzdxwYOq?Y|Wx9GVnjrM~FO)KgOt=LKC#yFkLP+ zx}llX9t~4enIUH6gvG$~BL3~_Lp6nl3mo;y^-LWl9JUNM;eOUX%($j2`j#cNQb)N)Gv=yJeg13e#tkc?$H85LEr#pYKFbIaB zzGyQ`SY~%Ww7GzR%d|b|@|NnaR2{yhKYSjq+$&d?5^|Ta4X|H)9@Wd6-Ys>_J+E%^ zfdntdmm9-;lrvy!NxPefi$At_=+`IP-q~A0&Uhi!r%mQznOykgGAPG%`;E3$n;lll zM+SVjS{yyP)Z%7c54I|`9F%Ovaq+zu_?VF%ZNy zzTRXs^EoU($2hgWJWK=hjrE~>-&BY9_pOeJ6+19RV=z%GJ9+!oW-cHBo8^1-zQ2QX z@~t1er_SoZ{@lxl(B0$wjenQZ4lkXLela?#6-06j?MK}}cQN}ElmcVynJ>cASSnST zHL;vXGdqO3u*IE_PrEKuxY|J^k-F?M6*z?zQ7P$AH}UeT8*dQ|fz52mLGr->HO*A? zB)BCsLd}0lmkskFsT~oh{9v2FE{M~!j?d}-Q%caH2+-cD;18=1f7>pT32Y*8;bFfS zW@2Xq7y@u%33q{iZ~yD!zsm1V|J=BO)?@&>KGK=HJY{PL=PQQqPyajHWl_Lkb6*^_ z)i|5M?l~`Rw{{|j_kR~McfC&BpK@vnq8g&9A4ydTzcb3DK5PB}+q7nsTH*ZF2f{Sg zgR%cIk-R7&{MXf(!n&x@mY(LOKJ9<2q7?lg#e4sBvzC9^J+P?HWc7$Y!(U7iFjwBQ zHq-BOX_BG#cAIZzJ|<+tDEk*@JPtYm7&xOJK(`NS^!e?VRn{7(r9}l>f|^to8MQ+R zHr|^Mm2(9!P6XLOJ?>JOA)E0lx+y3iB!gUY5dsyB+RHBeIg zk|KUfWgZ2K_aotQh3p*@Bm%)fPsQNo#?CWuiwnciAPo0FVxMS-{nyTlZ2G1=|#sXG(jS{|4Cx^~f895f-Tw(w^6s$5SbqB#SZDX{4w{W#@N_pDd~*Im$UeY&Hy zameiFm1_ZiiE%4DqXg4CDPPMhFV0mh;T2>NO=RXb*TDEe?4(dpU`$$v%7TbHq#h6| zoKFIfPJ>u7QeOFku|hyCRyS3*vZkq=zAH{eRVKOXK|~Ght2_@LbWCs_MJ`h(5AXHQ zJeYu<4MQMEf+_$Zf7y5hbuSY;b__)*d>(-q%K}(3o`qHHBEq3&a6G&28SyQvYU;3p zH5V>2A#4eGj2{e$7e30w?TiclJB)xGXVmb^$=`^-{03;#WkMk82_U+>+%f?in(TA( zIBt7Z0=K)g&R%_rpHW=r0wJj?q|;qZQcF_hs}Ui-(wYX0@GvK4M70 zav2anjm9!0qc}8#Mq)V51%zFpfiwbD*9h`BwOLYzpw*ce9acA+^5$DQi*bX9)Xo=K zwN`60C!RyZQs-GGvzjRNs4HnHE^nMN^4*HU;vZtQJX>sqfr{GqMoxzD~wp)SnP z(Q;aL>p0%bysW)JsarX|q+<1vh?me2m$FYobyq&nQ7|<}lW~KAh0og=va~t8>|yb? ziHob#8aBjJ`r)Jt8FSQg+2flLwX2fDNslg zZgjQM;H8#g^vH2qkok%O-YV0~wJD{jqyuY>=zegp4wtp&=LJLBkO!E9yVA!iKnsJ=G#i(m*vA|P*x6eLL&YFf!xZta>mtCm=_dX7(V!ILR5DBNf53fvG zrkk2mo{TJ15e3{XnY&6`SHtSJWQ39)@8}qeqzO5hnJAMquI2__{*@bdW8tS$&5W}5 zbjH*f>h_|=y7|zS&nrt#;zzMp2=+n1Lyqqpn2*cA?6CK`y=3V&sz z0F2!SZN$UxlCUi2(ak7Se9QYYcDicFyDPMinnN$XS8KO1ZVC+@3^=ViRU5%T2;Yu= zna!S!U^Em}-|pvc!EJm6{uG)9M7q|q@SROLtd(shZ%`;Yysq~U#qLVPz$g)2u00V?J=@;3qcZSp18+NW=0 z^Ga@qb-9O#W%IVRj44OR<85AAvX5#K+&&$@FOv-CQiXKeeu8GZW7kiDW}F#=LRiFC zbVj4XKwV7^L1px({6?jv8yVVT+5*xD?%9vRHfml9Me+4DM@wKQQ3|nK1V;4r9sCZ) zMne!l@&;;z)x}9GiR5$0J0Z^Vng5_uf6aZ1|FOfJ008Muob}L9mkp8>TOeLeRl%T< zk#VnA9n%s1bNWo4YKb~iUL~;D3ZZRhfGSX3Xdd)ZnA~{i@`c2v9>IdLBki$CPrQo# zB2fil<#pym?2+7X7jq?mwD84$ifms8v4jlKSF3sxoyMGj#MfpUk_jr+X%E7s4rg&CF7A4v^P@85A&;f{fVn5DHYi*?0zI z;uV zcQX@$ROPC!wDh{yL+rqf^+tSePNR?b4#SOchu@G5QYU7}9*b7uxa0UyAM6Y&47rB~ zBPdP$V5MEogvoA_#EDBBdsyQETvm;rm0?4rDp;l@s?d3+|7Il}!eie0dm|pnVbqDb z?+q8Jj=j*$)!pzkKtnNUbF*pJFHC;;1TJxn*mPf|%;4HvtCSWq_DA*TH|rQq6w6*6 zYD|>7_1|IF(AX`sOeq%yh(qN{2Dz`-inB^(nQ7bovnWz&{-Cl9Uj7C3;fUAxZrFnw zFQm`A8c$Cjt%&vNqj}vRfa&LVu z`)H+Hqk}U&7Gs&M!Mjb{AHDbeD_^^^ys-oU8OYichQRh@+@xeTx`FZRd`FSr{^ zbH--Oaqf3;fUnKC8^F!{9{v9-{DsyG9Yh%rdWYqKCgxpDzi zJDRgJ+;EX#tLRSrVZ<~78T5u~t;Y>g;L6k2aV)OZCN8Ijda|UU87eu;M4ob_R_F~h zh}>|=>mn#wb&lr~`LUQ?Z;4*kunh{EeO@8+uZrNK`}FRr@f3S7H^K>y>S6B`+S zdAZGF;CYNPTw&sgKLpJ7R2)c=Q8J$h7?sc>u~NPQ;tCA0CC5jpv;FC;?$}+jM5zz7 zv26o*cmtBQPX5tzH4g(Xy#cM4x<{CAxoUYG1g5Mu|1letFiJ0E|3n#vQZ|RO_9Hwn zNG0Y>nZ~|5QOprPUSAsU!|I0$8Ct(s#dtQ}#sxvm8Yj6Hc$-kYksYL#N zxSu`kI-HKqDgVv=?CWI{($r{6#6vRdxQ%N6Vy1Cb6y`aV4@U%TACofp=k!YnxKlsFASky8iD+Et#17b;&iV9j~L! zPL=O1pX!ob)5|$covLwS`lM{>W@i3Z4UROX$CbD>13!_ z{^kF{ABZ4ZW^)JsLy7IaN}jKpulJ>;%6@rxbor&7;kPAEsjSSqh&S1XJRuP1l|Gd{ zuO@My&NWn;-i4k@{u_^S)tlq5Gj=vej;NP)l4F3 zgFlHiuB=-BD*v^MPY>uk#a-@$oeG=dRlZ87?R{q7N%-F!&tzdKtlALh@pT_zJjTrq zWNn4Z%@_g&egQk{r=?$;?dNgpKusFsm zm7mb)RT;wV)Q6Y1ZMc!+{BWd5k{%qJnh&v9g~aJJqDA@mh?%};GCf3`aeTFa7BlS5 zIC?utqonxHsa)`?zo!t-;6lERf~{$MHUC9V^NVxcS&>9F4TnN&$vi(OB0)Fn4~r91 z)&-$rt5Wm3a5G7p(w7*9l=JgDjdltOJeRp!5xBgLfvj^g7OagP|7rw9);Tn;lqd+=d~tz5 zQO`Bbi)B9m&mS+m+VZOnFE3?o$Fm2eIMozi`)xo>`ny~DmyT$Y6l_l78j|jixBIvF z+=PtM2kA{au=B!Qq6bZ#@VC>A}-9k~wTQ`lA z(iF9z0c<~|;5`WCn@Vs#aOkERH$c7xX|0PMrW@Dm4G7U!$`?^FowTfW)=o%a47TNm zXG<$lPJdEOX30{AmN{QkY!H2SsyxcpF zDG^7gl)9)s=H-)jOxLRLWeb zlfsl^y`a#iuk|Bos)+M&uu=R&hQp~ySc?Y61|-UP{b^!!?z-3kytvO~FO9;Sr%~-BX>Jl`Sqzr>6>3!nfv+A~>z-^DQ zYNKy_X%qv9e}RZOjI<7llewL|f?Uwc_Fut@);6x&W_kDIJ}ILJv;T+BS+vdNe8F*s zD+rGkWy0T(DU%_x!nkBSl|@YBh218jsfB(M_J6=R3H}GpiT^)vP8liE!F5m38}dRA zZIqLP0-cZQf^1OT^NTy>_~helRQWqH+nA$+GrvWP;_!h!S>8cV>_I>zf>O@NXnYrwHfKyZ#nK-`OeK%k$?s1G zFW1S=*e)E)bRzkhfgw>)`Qs*@fAp|&!fGlA7S7Rn#!s9@`kdzb;+yE%<3rC%9YvchUHqh?^gKv?mH2tG3ztrAEhSSvgm%Z#uglM zFzmKm5uY?hHUUe!ISaT2`I1|&x<$)$DtW5&k4c8yOKy3Ms`C`OVN+EUDi{7xV{K#u zmSQ&2imidiz7l%G)~1r{}TD_CV- z(CdTshC?2CBcvAQq!cCzpvE{a-?4${r-cXe`t>N4R2-%XRjHCT@?XkRt_=zxgNg9k z$Wj2q<{_GNlUg9m8`DrDrm|I>VKvM@7Yofk;W8%uXqlOj%wPUqDQHa-t2ioZvE*z2 z>R%RDhLap?BLQ0ux?I=MGyJ21AM3R-sQ>I!OqxSHr-KJO>o%n*A@35nGygx}mT#ly zP9jz>f2_2_sIDXgZ|&+SV;B|A%eaz64@JPz1$Guv28J znhYMg~EV#YA2&h8KKjp95PYdu`xSn2i~YPA5_10rD&0oL$ktw=D3jdVFac;l_Te zYc}n1MNodj)D!v&+2`{fsXf&9JLLwS&f4NX-LTteFIiQg4@%cQ%w~#xy;4t)(caRX zQ{jo#Gzr*+M5Fz5*C68{u>X{{vAMksd2JW1%0m2(W29!~8-lX28`-HKX?-J@89T<~ z^RTn!B@q2+>UjG3@xlu#i<>OFQRT6blQ5hjaT2nJUXA^Ywanfta2PwnO8DFt0yZ;YgKmv=&F)Qk7(KS>vvmX181@sTucz5Q0aSPQ!&WP+E?%o= zEz6$Mjf!Vr@}H-yKADN8&aWdX(rb2VwJ+d-qhpP9G#3r)(MeS+27bC1LyF>^;`lDf zAv?Jid?%&SF7xnsoH^R!_;;C|9G{b=1qdfpJ;q|sQ%XvAwaIN^+9st%%OTTBJPZMk zU#KN1ebexm>oThkD*pVY&W95B5r*8f(HCl|v}UgWxH>^9lf|D$Rg=y6lam`0?Uuil zL3+nl(BhrV&&`FfFBR29>hF*<~AGtvv-z6=1R7F1ko!4 zX>x@S|9VlJ@GE8e=cEwJcZnMI0eQ0F3_Xl4?xG);U>Nk{%u?rClh&c*RoHk)*#v#u zZ0M0{Irxn8vT&515gqQdI*k0qqN$*~;|H>g_o#=yby5?A){g#knzT!UTiW=W9;W;m z^sa_{k|5XdT;NQi#>VRq^4~ydYN2zZr;#$Fv8kpd;caWTS!nT6XiN|L99r*|w3Y8C zCE+H$1*ty4LwP$k&h1$`CwY0aKk%CJ*sY6f3e$jWq}ptaE9-@D`gl26#`+f(%pUI; z(D(H`e(*oTa4MT==nx<)&;^v7J1t8rbb?{mI2?pu%Jo+5e_hjI%B_M6Y` z7B*17AjD1{d>revH3Iao50y<+3S*TGcyz5MhV-lp`Z;unD=zg0g^$47?;hPaqB6zq zCxW{NMsA3`^oRXZ5>Hh_m6!PQS8f?AK12^y?<~B(a7!AO7LzaBa(p#g;(nf`^ej)I zKR@nu?(5}KE0pe#Q8rb^DsUd@XbK-9Cpp%C`N`Ta9M#0SP^+)Y@18*=JS@G3+KkQ= z#~BD!O4cHJR^u{UR5#*KDKD4JRZYoBBOQ40!8%(_`FveOcJV2}L(elKN%Q@-Cd<&c z$3z9Eh!(Z69E?JPYr^w95B{kHmCUQP)C}=X)8R)@o>AFxUX$uXu8JQkzsjT}$S*9N z_;d@|li0`yaoQ5WhL=y*8A;--p zb<(xe|T*YBs zy=}+9rCt+?@%H&ozRl>7UP{toK7#v22)?6{x?!D*P%N`6*gx zRXSS0_mwx(U4^AXw_@C?$9}oQ2bSFA24YE9HnEneBFQ{1iUq`!ffoy)e^*XEeKg%N*%_vSsS*sfpoER52d+T?Jc3nKzm3zgt{FdK zp``0n9n~RIZgv$4@dh+KpI0wgyjPj4HZVoIfOt6qnS2sL3zSW?08G%RL>YQ7=E-W} zTiuHKOYrTla7j&z5kgs*m~`Kh)w2{{0aYPB9kBDcocJ^1Q(th^mEcv**-PbEpF|J@ z2s<|wgx(&zzDWrvle(laUTVO+NqPXKDDoQ~5-`!^w~SOZAy10q8mP!_g;~;XWndit z1T3APN`D4;+yIKYJ1LdmwIX6>Kh@(uWNQ}O^)J_CH)vmCRPf&|^1FZjL>-qqLgGRV zH#Ym0kU2UI9yi+$MwG2llg7ki$fag}8l zhZvr4JSN#miTzZkkNpleV+X!jT0p8GD5El~jTs&d7w)Mw<6|t(UwtH?Wc-|Z1X%=4 zRK)+AlkVklB)(-1G!5uG^mp0|l$yXPke8{jQRt+itJ?PkA<9_v(O!r`xKf$x(d$%H z4rDxBL~g(4UmG;)rV_nvqjwXLJ;+n8?o)VoM4wVBDwZ^DuEB7x(%= z$We40v@NiCmzJr7`wkb7LLT=DEJ81oUQ*vm9^+98?nH08DXBN*K62=PPZ@Q5+w=KK z3zB{c(R0iWlq9};Dg2c7*)}F3ly(4*b{*c?+SNSChuS^tJmagU?5;j*QOoeon{z#S$Qx+SXLE>SAdntd zvaMck1m+557?0TT*F1|jE!bnpJT2N;wp8jfrqri_Uz)+KO0AnnQ3nvLNme~-j`|DX zW`e%zOM^!*H2DMAagL*$%eQ1Xxi>gbL8?^lS`CL@6f|JWq!u?-xkR8#OsoIBlqACivx@pKyKOB!rY zYUIki`q>J)K(sW%hX+c%l#Kp8tV#&dhFV36f@A8ZKJ{QZ zC6@_z;w9NJQrC~z8>m^6DgXk~hBgsKCi;RyxzX6~(ec=st)nw$c`W@(`4ELu1IUoS z7@smE94dYx$OMjJ5s4ueR>8?kOMP!%6EO%AaS2B|eB9zVq7KnJ;jQq^8Xwa=K!L=<~FUST|~k|f3`aVpxV zLjKlh%qNADPRYt-djBQ)Z}5oZ2pKda2kx#(d&aW&NGIz6 zP%P3EO)q&x+h<+a6j+}<1q-ksL5iCJSMh%E#x1v0%uMH$rspFsk z(p@2wA$;Ik=)nwZm2x_>vhZoE`R$zeEMwl^9>5DuhG4M`#dit{3eQORs%6t-AiWP< z4*<5IKYY)sH9&iv$$=8jig$i6XJu(Sj7tG`(UW&%G*l~2wX=rCNQ#)&c(d5sMUXQIGD zB*$5ejU8Vr1T`RVOPeMS7gCx1S`XJ{f<>IEAE2JPU=1=b*pv236QxiF#JJOODd=n+q1KLV_&#eO=gLopT~Ipc<+!l|}N; zue97+l&n2sCR^5mEQM?5e6OC!`icTZqbMini|QAS!}dg4^c<|-u*)(-Dj0F)>gI^Hqd(^S+)N*;xyj1Bo{6&18}r0!j-H*z*e~s%L^Wv(U{)G9*UD z#8a0+p;jJuV{l3cbtaU7#R4%psFy-vV2*7!D5j~CSB+(bSRP^bG+mnc8fD{JJ&v-} zxC=cs6%fJLr27?@gv@9QOgPXc;Ahg+e3&9dXQ_uPPe_%!nS*CGwcD0CzE2>Mk_VN! z_;hdqEs}qM%e~=Is508J$Z96?H{!1lVYgE@K2gvk4=of1hIZNNH3y3w3+NtWB1S{! z$V|v*0BjV&*Ym*xkb6nqleK-xy-(M#rl@!uo@BZuysDxpZHyk89~sos&;Tc z6j|CDva%-;`>A7|ijA@`vx(%ke~T)`JMIxSG`q1oeLC)AJWHzT^mV!Kqo3=y5nCzga5DEG2R_e3geMs$K`>b9rNMr#;b|Yi(FZ#%T&e8QZg!td0`PK|) ze(t!2)amTO_#q#4F#5f+R}^wtWh`)jKIBVAi(B|OMcBPt;ZGHi*P(r0v4YVgPA-Cx zUdQ8MCz8)49;Xs*#5;gM2+)-dWHqmf^)X}({nQgKqtn8G3Dr!?L?NwZ>W%5-I6GUe zYt8=+#q1A7U5f=<{8O-Ueb+P63`wb%<)9O7-6|(xGA_aT`#4R#3~7t_RtvZ#u}EVJ zP*W{8EsCxJgB$(EgMt

psu9mj@A&9*4GwkOLT8V|z%76HlO8@dLYuWMs&9_AT z$G3bMCG-7*ZYx6t{{!pT9&_xz###*eo@$ZTNX9=U%n;hmv5Q;k8gSV zzxbBtSrZ3eKYmQ2o&|(k0(t}+IWk`C_AdCSNQO{H>9aLT6nn=6=-W{ueCnE3DObJ$ zxe~R+C=wBzFg{HzMK7FR9vyZAgV3E@Tq!?OLDij_lKWrZQtAKkEz@h@BfG%oThb@L z@}RBtbC^2!D@(ji5edJ1%dqDtgpN+};3&Y-_T%H75vT+BN+{NDR<$tLpoE+tR_owI zlvJi%w)a-uU*8hu|N53JU%q8yUP5?pi$iF-e@sUal4*LeL~A`p$uSmdpzJGjD#d=6DaaOyzky<^HZgYZkZ947Ki zfKkz3l;+%d2w+y#D)-^+&e?@C7l0@#s@2>jL@M16&w+&ot1_?WXWl+H2vd+sj^v{% zL*g@)6WYxgzEs~iVw)R`cgW9A788ZD7QX?&#{Qk@oIQRE#Q7oCy>;}6`|f=?bLrZ& z^L0?LWq0=)<=s7V$?@_&`S2#9Q}^>v>|?QW>2NS~GHs9h@HZFe#hIydc9OK|a#rBPG;JXr zf8AmtG`{gOiGq2!2jECHt5TU2<(+y&rWsADrq)gF-#o^^^`PT-)W5>}x$7pSdUg0^ zH^0jZ;pkFaq3+?#f0G&PQ36j`q8u%PV)fDU^Kp~+*7ZZ|PbDbF1ZW7qMZ#wFXEvx$ z<~%h-b7IyW_BkH;S@BqWqWtKx@xQ;`^OPF80;0p{e3;dy2imVw)LH$}4`JyBlLpua zKtz6{a1xJCQKE(MyyQ>JEP2d?E@l9GSV=*^SyTzO&=zGNZSJ8E6|kdz{+i}ii~`&l zu?ki*DUV)Rek9%z3eVPzH*DINI!US`JgiJ?siG~defgFGU%ut(U*FQm;ID7V`q#I_ zeE2WlG9<}_?#s8#X{jFlnuYZIr*9edFW+)C3Gd6d%>ME%^TevHE^MuuKIp!D%hrGM zEqM$nx;??Ro{))O-u#ysQiuj-rLCAVyahs2>L$>%4Kr_(?u6>LooZL#)+eRM;}aW* zN2O{k;?v!J^XJve^M5Pw0yB^+!jn55LhHcfRr-+$1$VX8#jH0(OIszq3t_7|NKW77 zhHjypaFiNr`lyu>te66AF(Q>g%v3X_sK)DNNj4W*I)w}7VJz>h+A)3s&lZ@o2em~? zhM>==M`FbW?Cmh0=!>Nvl$k$40=iMJxENjkFkwR9O(}!oK}@7Jue$1l)WBNinA}4V z6U})8V8o9(8>ykO5)xO63lJ?7)AZ2Rgmui`lQbV?$+rKau49^(bk?Jwm^vW`RRtd* z(9-NWA53Y0O4t-+y}!ys5D??9h|s{#c~P&tzJ^u0o#&iQ(N{`h-OGPq6J(3+do8a{#w3RLT}a~C|hw> zky_VT_2&ROBsqh<^c9ON`s#crahYqVyMi;aR!N`mEG2fZj>Ss&xg9D z_WGfJ`85Z0DWbP7?|)AdxA2H-d_UKBhnq3387~%Hf4_~$nMjVdH~;e z8QTDN2uSRC_kD}L)uGM;P%P4%%E#gAY$^9ax{BOC1=XdqbHDmn0$qikhv+?EHRxRs zeOk>zxrW}fWl=skKCDylpPNI5u}Rv}o)%HvE3rB(iq0nT+P(S_oFV-t=jbHLTabT? zISBN47VfMGhtcxcmA;w$3RCDOL08gmrtQhzxy&2!cw&EkIUlpbWRtn@{^OH5x9Q$c z^v8-U)3$TB!+Mqi^R^>>z~hEvN+$8FUdFu)Y~y;-zf3bKXONJsRDwLfI*MzxCL^lD zLGB2o z<#w0b80nhBl!S@E=8Fb*{q|eEu_LV&&lRW4P8?MD&7}g3B&bdIRMZ=88fVtCo*8 z-vx<8Icb8ZK^Dtj9sWlD^}z~yv(n4?>Z^fh)2w|%`@OE0!Nwu1v|qwud+{rF#XLdE zouJbvM8^?3(uY2MLt5{AkLUE z>J~;wOM9^7TmK8k;l!2a+O4%Br%zh-8*Hau9%9Ud=vqoji5W*&OOkXzoZ6#3ap9q3 z=;`!J77%8DC3M7;rC6Ph7$gIV2D!dlAzS53tF*puLL>Of&l=nS=0n;Po65xGuvX*I zrjw%651S(#0kyzuV~)gM>gf^6wh#!-G`gQBe{%WxjZ&XD0p)zYm~2L8VlVs-h>%vL zhGK)#NXGlWz&!eGp(3>zTeYH;FE6Xzw_YO*He0$rd$B5{bUR;{{UF=GVlvt&GOJNY z^~N$uq}`cD*;I$vAyyP)TyH;$2!VmoI5OI6j`O+{&FuW;j{^pq^ce`G zL|aAsD98SM+tMS@DHOYooPM-}hS@v*vix1F|X*uP*Jz z2EX$qJ(C{jEJgyqk?ri$vY4-2w$d5vZMD9g^YeMtJeIZ2R6JL-A8325g$#~;NpYPr zDN);Nc;_E>9C$To6dfDpQ^(h)1sl%0qXsQ&&95~H`{xiI?%tUpYw(Y6y8y@j>+nf^ zx^nH=5%=HS8*bwvYx1{$n&&*T*MHJxT-$Q@hTzIyHS_$!c&uSQ*fBMd+xf2Z3m5UR zMLRmBFN#tF(QS=7`3l)m-|%;aoRjyOSLT)@W{v?hx>H#*u^rpdZO7fI90$5dC-dje zQz1eD|pM!d$$POXpT>Q=rT*@JFBSI7H!10D=Ad(U(bOl4OA-L9wfN@(%Gm+25+N_Ely@VL>*@Y-<2ZNE{U z8ovFAJaU3tM*R7}!Pl$0y%8))I7c#0IW;C!ck{J%4deB)tF$eTW;R&3jr(U;b-8zU zCZF6Zvd@N&_o+OE7b8M!x^_*bG=~yLO4+T&DsLT-72SiZ2~YZ+n{+Besq^|AsWSCl zYVvjvYZQDDLRyE>5JlI`^~{77t1_9kML?bD6JvYKNhUvkmBu+pCtD^;i}+Pb6Vqn<*3Cn7<%urOknJUmCw+?L{Y7VE z&33N0sJzJ6A#Tmi8sIRxWd`_760fJ`%%Yq>67qDx6L2}k_E6rk+0q%;9d-M8_!7WQ zuzU=6(kJ(to%^00(rN2UDh8Ok+qBEcu}-|Kt&RDm^xugh5p&o4^L-a9j=|ksD*9^2(3Q_uRW%}bl|VmP7tN`gRVsC2m)p>Z$J5RX z@klT1h&v$<{!?3Z>ZwM^*8Vb1tK8bh3&6B@cI{Bls{-Di+=ft?g8``A3vPwfJ@Ix4 zpWrgds+a|@txxv*o@Mk87pMQzwZ17WV<4wGv?p8~zn zRkHGs4pAN&Ym+8dUYX;}30YUBidy*puEov#cP)-{9%?7lw|6SrOg>^B`AMMrjA7Lt zRuOC6>6pwtGxF2u>JC6WR#UPTeYR(uMj#(CNl@+dO8+k{uJ~?8dh>;Xaj$Gzj=qhA zz0@N2^+pG?$CC0I=vu>Pb3J1yOndlIK)@B++{Y)nwIrua*wO(*PfGf5Q@vs>+CAeU zq`O_DhHd6!=^Qx_TDFj-k+m+2E^VCkdgqKUpJTJ&IU+~CkDlEEXjFZ@m7L1M*mbmR zs<63*xFns3A>&<$+pQpA)5)g|H+Vj)c`m2gID?g9&E)r27|ZuvL31^(H`6)K?Qyc4 z+-?+kIjOwPsqsb0T`(zbCn@EDYpd^A1!~X)La0JimVx_aU6;CX`-2f(bmCA4=QsPU zcVFE<1%<{~-z(J_a3oOrIT56=7_0)!Y-}p0m!j3CLEoP0u1Ju0TQ~+I@E{GnN)6;r zVCF#*_jC8?KkeNVq2LC{)%<&}F>yt7?e)4q^dc2OA0-G4UCK00cpNFe?XsFCGu1XAst?V7Q1Wz^fd-*p4OjR(%yQ0b)92y}f3uoVviAO> z!C>&X&PB9akJc(D?o7;hE-tb@jH#V|`D> z#n-kT-S*A)gK2fMx*J1bxoVoCg^ahh^7lfJEWTiD92uUwTQ$?WIS|ohG5ofx}36L@Qei2$57SY zs*?~}BhoD|E}_3mWr@}|YEj_ysImBAJ0o`J zE7f#OF!#U}xmhS5+#34tLN7y6?o~)EjVADW{xQ0*N49V}FCz!~JCJuBMq%5k`OD#J zdDqS1ZF$x4kt#zr-s3*gL!nUzA<{mmSUpJ6`DPe1kYRmIT|1t`wKHn6E{zTPMHK$ zSFAq?)E|5fln+RcV#JyB+etn&k1kp}Bb^eM02;nYsX<$#bR=4hpK;j!D2;tzL*fX) zj14m#%fITIA`~Td2=#hJS9>dUV4_rwWO5f}So->Z%=XKy$Dg^!!Cn zjF<@&b0}~=7A&W%|GRxUHGbzPE3|3tyBdqBE{xa@%#5y457RM2M&L43rs|%=tlVt` z3QbFmT53qWseAN@$BXRMKdZl|$f@eVlqL?^1z+IH_kKXd)@HEZ9NshbRJY%2eZB-H zt>v;r^ZnRoSb=d;R#LzZfbke!?eFI15(fRVjWfhGDIvaFj}omsVQq?VlJ-p@1^8)q zp!exck7p`(NYb2vTIxArq#n0bQ-$9-v^qW;j?d$$onP8eDk%hykrckAE z%@<&Hlvs~M2A*((W?`=Y#v8s3(nvQ6S5it$6J80NC8)u4)c@d}8?mO>;c4R)qMfUO z8rLv<;9CthjfTle5wD4%0S;#znhKQcJIKHl!qTJ}UYWK{41=w;u~JdoIpU$l4P~1I zoZFN;TaG1&Iz%o{OiR+d2?Mzr+}JY`@B5AjRvvEpMs*scwTN5rKZrWMP_XMXmt^FU zYU0Dln*plh4inDSBNLL&j=&)XPnuXK_ALxzkqGm~lFIoi8E)*OA96*^wP`Tnzug)R zRTTRwf6tCmb*Q&h#!;TCnJ)LE&TlLdOY{RXTmL{nn*Od94kC@x9At4oq#W-Af*N8R zPfT(7`T4L}A!$phjrmTC-%*3#dfH9(tGy zce_nW9|#N=^rzq!rfwBL0;iCK%&!0w)sqyoZY`TqJ@JaAT+N&=wO-qUH%<~J8m!jq zYM9SdOM;Y8ql%yAOVeXVhI0g7LYF|qA9uRIZrpy89Y0rFqKYBa16B(Z38pEU7Fqmf zKwKMM5|pZaEJNM({aXq##^HDJ=dQMw9-D?qzxEg3UQ!+FsNYVH)yX*iD+Z%IfFZ#( ztD@Xk6?Qnwf2cdp^nX!zr#V!5O$BG~#Ut5vZ`=3az^DXG1hkI=CytdJ$9@%cH<9oW z*Gwhma=|nLD~HL2tPn(8q(m4|WX$`f+i*BxqSQJPI_<0fn{-FuiF2hV{@!7;&P2cA z@^guCiKAP$_=)C_)J60ZQup=q-ILY!8R*3)5_KKI=J{Y&H^u2cr8_6`FX_%THh0G# zNEWEh%pW$FKK4grDiv!>PnY5kGUv4fT{CDmmgXpNRba)0ad3hm#pWcLyx&`rhY^r2 z9Y<}jRj2H>bZYeK+mX?3<&GIs|Dx{Z2aM11dvHlAYz(Bbn4D5FLusAc(aXgU-XLt@ zq`qD?+1ts&m@$g6F$PBHPHOQ6OqWbp{XpE!OEr9{a={4Kutw^9a!ukM2A=w+s*Mh! zHSsidy>7&K8<+R-R%z+w)l;HV#m)|vwvQ@i%zwp%Qd)%i)0Fbq@+Ce<_i<%g<*Z(y~0kAQ&$ zV|`74?w)`ix~eZ18^c{t^!?-dZv$IOEM!Oe9`#DQ#fPrM(ogq~fdNp(5CgMhNap_O z#_C+qQc4WY1?XD=B)|nmzd}@Do-)`u*3|J$etAsnc!*bxel)@$C^x?++6b7e#c(VC zj3IpXK0Kb7@C=)RT$0$`p4>cCT(wh{c>U`8&K`5F0TL^Ptmikz?@>$@%Zt{`Gte!J zU7e40;}<40^uj`uYEG_STE8C1lubUkC1b!Ebmzz3bU3fZq48X-7D=#r8@ZX@U$Gx= z=rEB@#mncf3JA*eW1t1CKnM?5LJ{kLQQV@m56u4CekA`X_q{Gi0g^#Xc_F`;!hcyK zHl*yAhk$88IPGi|b9If-%4uC+0gv;lwWBNIoEL=1SW^gEc;S!qjL^a2!1>3&*d2dJ z=gYD#XM536G+}*+u>^9obax+@ZM5uhFGYX@In@pgJq8zt)9?5k`pFmXrbCmJ;T0FJ zZ>C$r3WXRw2(Z15Eqg>XWue8h;^-B!P7cS!BFBL|Zn6zDY4j*p^$er_Tm%mhxn;(;PA10dHM~ z+Q!SVg96&?I)XyS5%wH89F}a-{=!tAcPk}c+GiJi0^QUMp6@OWe=GoFErjTp+1*qO zp6Z)7ms1h20_ZjGPX#4|K`{|#o^QuvJAIh@p^TrJI#eYe*Btvnb^;8Hp87g&dX>Y& zjH6~9blv+~Q{k`z$)w&i+1DfD`$6&%cF%heQ=_m}q#wFEPi=VDF3ffEUC(vDu57q= z)-Jx3ZaO>ava4IW@Tt$YeIIm8Z#vuOor;@2jzQio zH_h5*%q?`g=bO2m+wQlv)R&a4MADB6xAT;#F=WQ@tXK8trq7q=j;l(dwiN#=5dcqBh8uMObd-bBnDCg_HnNbKZW@Y*``ev7{cbAu zlhd0fdFf4`7Ym26xhdGN*G96C68VTU{`cai!Y*n? zw4K}InEh{3BcHO*&s&~)(N8yPJAEx*-x{FSv7e!&2}^Q716@` zny=Akwtpe;+U7YF1FrtDBtA$#)lF{;&^t*v+(Q56^>OL{q@RfBrARY{nUhG$Pfzi% z)39Tu@2SUM@b-qOkLmw0*aE)QMb-LeFyaQg=*IKfD^FkVO=I&$xtD;kn+oG-zdIbz z;i+ZcKZXL;LASEIe=982>8ZJ?1e2KZcVJu;FowhCd@ATralE!;4!V0j?xySqU5>&A z6~0zy4nLBgymo!1ETx=Yzq^8ye!hy<1qvj3zV?fM(lL7K=}{Gb^bZpzVe)?sAtgO3 z{nwGzpqr+mo!38Wj>S`>X1vcFp1W|_8f`UHOqio)U&270#1Bc!Auv@5v~Oecb-|mR;3okB24&wth%aS@@c;e%LAtL{s*?c$W=6j~Ioec-FwXVlJ;%Icf%m zV3Di??1|&`DM>A?LTXh=DB-4;0Y&F3O5zX;akva&if?BtxVkab$OUIXhd z!lLN(bbKG$X~%9WR$P|qir<4x3Q}`E@ydOOfNR(*y-^tK1Yw^e%@cELf6FS_RqqbQ zN~*PwiQ*`Yt(vrjx@HBMi*syb%FY$ErX1d?lmHs$x(!!sy>X)gKS-i79_lYJyGaLT zPBEa{y?9_Fs%xCSLuPrje43CKS339$XxcE;FDmVAlO*z;cYA;jVwIfv;u(DbX7`-5 z&uB2=%F06Vf*kwZD^P|MzeZZewb2rjS7~hks>-&xxmV)R_2r3}!o`{6=KH(Ur8=%! z89lU=jpe_BSm0$KHn^7&jTQtbm#*$$Xh898vDkzgwuLzP&5_9O)d14iWbyLBknud3 z26OR`a_;?&9N}(eckgJ4(wV51^cd~QB(Vlo`=^PhAy6Sy--gCAm-p+MlGltoVKoHB zuiDRnzWB1F1f1Yxk+gtzjQJq{muDdU=VM<}wf0Ba(|94dak~pG>fsMOe-EPbMi|7L zI9$E%Hrr@>M~T~;P@^Yds&c4eS(Jq?9I3pPffLfU%R}|e&cD4F)y#yb)GLJ z=(X!R*+0DST4A6eH#O4;j?z7`ouZ z!5XBdbevC0QBe;=t}&TRmUtOykC1o+Qfee6Sj2# zR#EWC98ySWXlTSV)dM@J4mWU=w^2J{(H(_M6}pV7xpEc+O1j8(KTRP;u>OPMS0rlE zPMxL!YVe_O|0XZAiXA>l;E6IIa-_|M33&d+csAPVxv{y z^vuAMF~^zZ;c9rWgJ$^p<-^GY%iXuv@SkE#j)HLCSftlVM;&+#9_z~inr!Zx3z1dc zMLhY;0qtF_+2BV{D=uF^oUDAkpx@)05(QChEs`gVx?$%*iBQBZ^XMCxh2BY;*i zb~cC^E*Z>KcIC@f+sY=q4kUQrl}8wDazD#1d~;t1)KK-tiB~arOj(b_tS9s&S3Ak? zsgs^{AN}}|g1K3M)|?!9*s{x2)7-n#2FG(dzBy&Gj1K7Tf)fznHFwsr9gKmhV;UXJ z5%b>2wq1UPC0)*J#}8hMl#EC8*Gw^g-KL(kKix2r z&|(6gd$5w0&&Yjqv2blq77r-seEm59rtTWC_HB!$f8~4vyXW`)bF)tBxmJg&aTY#r zIre;mL)@|#b7{u8+D3T4EilrFo=cD-H>8X}mqWWTR^5?Yq+vnJh>H9{gL;h}X4O~H z7r2=1{Px896iF(;ZI@|+_R+(Mb*^f1aMoc?d>j)Lqv2Ch7G^Y<8Qwq-TTt@0dnT2G z;ceD)$t@KxxJlqU!9mh%&PvA2h?Gv2R|2E6w}+F<^WNcguAX(%*v#4N&d5{%q6y74 zThi0Zw6tgI%D!&3=lsq}5=l1VwKklE(Y{tDk;PYI022sAQ}c|fn4-C1mFHe7N+q0) z64%|Zu2oYFCSVj3qn(}#+_9zLcfvj&Vhtu|525inaNcztLmaLx1x?$5tle9}?+1_T^Y?@3?0|;@$K->JkR}0+psyWA z%(`s?Vllb>p`Vji9{k=mUFk8NV;*kaRzsZ@cYG~QnCZdwy7nfIxh>$;C#lA?dW;Ld z!*5-`(z(E!-|B#$_4ODXThALF?l2FA;A7nw;#xVKmaZ%5fifW?I_jV&U!0b2Z^BL~ zW9OG#;(>+Xpn83Efj)Zp{Vk#TMexz;naOgDzF#XL0zt3I)4ai@?zy>Cui}QjrOR?{^iZo1)M+lkz_@ZU-jd=NdW57ZvfB5y{ zfy{&Fwq8Pzv5%a(0npQ22KLQk2*G1M(?5N;i$P>S2$+UU`igi`<8IUGi4KD~h=o-u zM4Ip1Ia(y{`-R@CVBrN1AT%7d_LW{gK{9w&Ws;O3XZ1zxicsPDrGeTP5cB#fXhbWL zB>#-ib}^GEHU!iXm*gjfye_y}we8?|sZ zUwZ54Rg*0o_M}g`aP+#)@YfC#8^>@M|ULe4D_ z+*=eeAH~^A950i8DINpkTbVmYF>ceVn6!JB+Gh?wy(#lLqG(~ zT?!FbE-H-)-ET6iAq`Nn<_B$X;mF>Qqab-4T6~E>x*;_S5NCL8KfxxlIBU6J;-=)D zME=?yi)>vyzSo}ep=Ugsx@8j1skQF`EU!LCLmA(kIXo`gx5B43?skJex_pF7<+MRR zdIq(5lzFeNj*)j=Rw)VpByqwOe4aDOxVk=I+r-u_Tc<9zili+PD~=<0oLJlA{T4ie z3c$q3cNB3NtW5!SM}6UV-6Pu@ipF8!L5b@H&Z0eiA7E#@UM?guuFQg!6A>z7V=r2F zAV8wH5djM--G>PVFsv)mig*6@SD8UV9AfYFf6jHMCAEx;XvTv2iIj!v>_%D2 z!tE|ScTYC7axi7VZ9J$3=|FQvK*cUOGxoFTb1#??tWr1nbPUxfz9P5aEw}9y?|V@h zjH~}xWO^-+dJj=nYDZ6oL>8$tR!gd8?tNrpuzKn+7-s05H5GzHVsrFbG@<=c+E=s3RDJ#M<9rg2+Q{61 ze-$x}zls>azZ5a9zlxY$4BA0hir0)^i>I-Dtk zlL=R?G{z$IBB;FY;Htg+saD-%y~k~NxV5sOBa)YL|G4gEh4}NusI7Ri(`k9xAb;Tx z-2XzvEKhmq(69hZh<=9F^htgb5Y)&qEADH?ES>mptR}#KG|ybu(a>DHW@v8N{5bT#M+yd}k-!gStU?s2M`#B$<xu$QREgr^RzG(r3uqn{PK`Hy3}hp1lZ9%M=&HFwbsO!e zG6D=Zl-aY1(vk&9LTK7^8gd6lBS6+5?aM6)%v?XD0$udY-g`uNzYu& zQkp3ujsQiXeLDgeM!7Rsn`1H)5rY*dP~6#S$hv^|wtOTTkEFqhWosln_S2;U&?@po ze)B^pw}lFBE~@EPSH7yc2_S&_>0GGSE@;`?9P4!S8v%2w%UgE;obBRyVw~bl#oGDD zoydN%7;nnl82LO%o^R~7vYom=BEnhN3dV#sEQ-$AnbmrGkPnRy%~pM>=! zV+FZ3t6Dj*wEw5ByMBwRTl)YG(%ndRNq46Th%%%!gCN~V4@0Lk2m>RHgh+RT2!hlA z(lE4y|LWZ6xnN&d{W z`WnY;r7j)od2(1faC_#;MJ&80)VBAlHEGh;jHbc;x~pXQFyl?~1YOWbHt{~u=hGBj zBtn5%lIaRJH>jn1zt*mQ4<1NFm7eORsgl|^WX@8iKCzci%ei|*aQ#^{PCq_@BN%FwA zN~Q!4n`hikHo}Qqo~|fdM?A()a&=C2ZiD#Ca}zhmZpup4%~9hJNiM%#){a-CYi_H{ zYO!5u5_ zQ+nMG9-QDQk{77=3`j}_5sa8c1XUlX|Kvjqt9R9U$d@ z!ZydK!u?hwaP3r}LeYKn=PL8#+8y`}bmNi#Yy3QD;82=cs3!HKdsIto z1XT;J!3fvmkK@?9{N*l;Fuk925k6WrW|C84pm zIkz!+#^k~?AI|eYPN?2R(&p_)gX2)JUighq0f(c2XPh!jrJJ6DAfxnFPIsL-v`2xi zv^p&A1;70zyLq#E=8q(E*X$TBnR~mHPn|^Sc-CSroScZ4Gs7za&iSI3kIU(D)NQb^ zJs^aMYJMb|a_sxRr>nb->)y?_t5NIP6;b}r3W~kxGN7S9tDN<={szV5 z{|3c2QJ@$YZE^I!L9w6p_CbTMGB4}0{{@O|qd>8azd*51e$?aIIpM!WY_a&utem}4 zKM|Cx^bFRqNS0}EdS+OQo6DfRBu*5pS4iWSLUy;E5N(_%p`1VF*e0`|sNXr_Vjdj7&Q?5{ z=!??F$TBW$Isnb^|94nj^o3^J43+8Mf&S2;!v ze?0-`U5E>keIB)F*9Q7)3t%RAHa;+qgKSRoIRIG~-7sCLrw!VJf~J;md^~X2?Jlv> z+yU*}FfB=ik7KoU?&ddC_AQ{9>vg&McLy@Cd{HOt+10w17Io6LEi^8KRjy%97#E)8 za`RfiEi`BWs4~p!Wx5qQ&pU{1K|x@8dKMkbZ7h^KqJA>Wjmrs<2=k$q)>AS^-oC0l znizAcnCPzvt41T{<9Pr9woJ=l_r)I@2Hgc9Uwqdp{M-zZkRn{1AuV8*ItUKAE8VS{ znCuluzi7@Qd7%K9bM!;f<@_PV+z{Ixv7~Hf^SV;GzcbiBd2GpiOI;6*n?$5gwKS;q zDo#f{P)K;WGHQP)B{7n3wK3esgrC1cNMzl<>^yT{gEGaOcei(zfqq7U`e3u%?b^80 zMPf0UL|VM;efnGWrO})4=)_eiicPf#x3<2Zws{4}GKC}aNwQjoYwpV_U7M&ZoR@P` zN6!O(o*ODY#M+j1*Ow)M2}?-)ii}RR_)^XRS;LO*C^mO!`dwxnfaw}A8O@|}SNr2e zf=XK!FnNR*Ai?;(@0{`M3f~V2;-c~x$u_78(q%)Gu2?%4uMPN99M$jGe)qkH%j$yN z9*yRuGHD}aBm?}f4`jt(bbioT6j|pgJzcCFC6O!mZsHcS2$PP0f*8zMe+-F=$C>jYWg z7(Xw=W^Q2Ilo-_L=iTi5#XtWW3y+G`ba|!Ko{m)QFUuiVOY;tc_2snfQWptw^)5l%7b9>GxW$#`n9F} zl#7Dw+{n&J*3r_V&2TT)LVs8M62G_@v!#0vt>xf z5m?H%WyfS?3^6JD@zC*y|5os4hlLLz8=Qnujjf@uS)c||i_yx@-pJ4B;hofUgLhkF zXme9YV5edRy;fgG3&W?~4(jNuSb*@#7E!`nLWcUczgRKg1wdS++BY-4F`WV?Yw@*X z3^1ECR)J#0*x%GQZUpzWuiQ$~4H<}erV8!{`^kdD0+!jr7~Jfw-srB5)|mdjZ#ruy z`CN%jZBYuJLAhcQP$}F_TN0Q=YNj?bHtu|5fm_ro)>C3?Z}Zsa>fdVR%ncICmT0p~ zrZNOpxqo7=MNEflhr2al>~%c!xex=Kd%uRAI$plJf&oWp4lF@laohFDT<)fi;H?hS z4MuYSlq+^5TIDYa=M42uV1am_(Df(?MG14S{VH@l`dMkcNg~^uxx2mYV<`AL8O~r3 zJm(-&JNxsaZ_I#iq8+PPkSlv;_pEq02`fIMm(NDnmNK~^eU&4r&%a@@D(4?@8GLP$ z>kf7F=0=M5|G;8F9srBxDikb+S{gi0M!{k;g3Mp9e=Xi+F+!a4H=P2>|FnK^Sq(Px zMATYQtsf{&-t*ox0*#^ezhyB3lq^=t^x4*T89K7X=cJ+Gr1iHf24jWU=#ZWAzv61D zrHfx<$*Pp-9W(~xm_6&2bO>b0Y%mgACAEm*nnXNWvf9V))T{n4SuB@AdNmJkZnZxU z-xuPD4_@GD78JGqHsze}6D9$%S~O&d!Sx#Dnh~{;k)5UieE3osUg0So?_-Fc0_)Ce zv!EC>f-GCGl=5y$)HtJLvGYH&Sk}K}v2w2JSk^)`LBM5j1jZ!7oo=Ewwv6X0hGU1i zJSLeCcHS*!!T6fQmX*?72z(%BH^resqiY zdY^UD2lBCch9UQ-uD}F*Kh~t=S6`qdYZaaL_!#;j z&~p*fVTV*>S|XBP+!*cZ?bBi-^i$L3f}wR)`e~{L^iqZ)3z>P}M^6t5!%xeA`a`;6 z4q*A^r;Z7c7L3{K2(iZPRj$l|y-P0>F1@4{L85 zR(e7YK!(zklfChcsm3^khRo^ojCq2Q};uq-!v{Cq(`E(+_w{NZe;0qGhret z^nP#;v*h5#_8z`x3w9#Sr?r*Z8H2-3mQ@#62mY7$y9%lXAth{#R~dXI;t}aTUaCB! zw=h%r6lG#}GDqi$N${;G@|>LXm>)yYN?Idw4~myMMYQ^5@H_LnJE5HxDWgpK9R>vs z;!x~u+e*vYMi3F>CR%MmUoyR|U0G#W^U-gUX&3(Y*yi^rBo>o*R>CUYY9jxBFz)!#1; zhn=f6)QeBeF}j_wu0q{4kQE1{3n>6MmKqf+$^2_NHCi0vm`_<-?=f{6hD;K_*%rH3 zk)z$=Kj4fkh%GlU1zne+-K^(Thh>|MHhck2qpwzYZ%qXX-6~@Bo%L+Lc0~BJ$H+$t zL~9>FU(4KnpvZ)^C{kxyctW`FiercD=q>FhU%Hq;FTGO7Bg8$Qp(p9cuHPIZDDPOJ#=geF-nr@MHY%QSd)N2P`YjuC zLEfb+``3pS9s4;%dOMdjg3?tY;z>a}E4DER-JJ3FfVJw=SXX}U@?6D!CltPg6x9l(Vh(!S*L zk-M=!z{`%3t!|Vw=F{-O0^`3^ivKDJ1N#r_;-y!RETqdVjDd}ewDF~T)Ysek1cCyO zRA@7{U?i|<2Bn=rdD!=&Yx&jSwlC5XNl1v5x;na4-Y4BGc$)noTu;7YN6N_F5A_xQ z`#WHxQiOh7ZR^_@g2D(k_Qw~y7(5WC6pxhYz%8w^!p_F+dxr%w7C-M|Zm7WQaaf9u z3%7nG;$b`1FDI-CuQj*&@`OTFPXyLb^i2Qp-ksH=T%>Z^*H*f^E;Hgd?2c zE_zT%&E{_KQBy~nsT7JAGYQ5N!M>^0E;q)SaDA*wP}tDBu5IW3>%)Zw6TfaFUUM^w0P2V<|8>HS=jqD|?!Ca7LQ z0Gf4@4>PGfzGZENswQEM4Sb0fNsKh6RmR&@eyzmS@h+=`o+PcW_IzjItO9a&eN>LYJ=+^ojAgXI*xOifbnmve4fZE<9k^)lT<7zTE>@#6`8>T` z2&Ida{96}0`bQU23i?|YTQnxA=v#MR(Bf47KF0aYIwekw#=qOw$2zzUO^&BGn!~3! zLK%J;kQs)h$lXFzCjTA3xid7ePwV_TU+Jy*xuQbppv`KYgjX`<>o?WnuV5?|eq==U zGR&UkfblVy$QM~&ytom3IQ9b^z9;&g+J*%!frwd$`ibG-~51c$}ootC{S{Af?Yg@C{z7FU};;8)r%nmZ`;!hcN=YR*CL zStH7tIviViS%dbfxM(WuH#xU+k;nU2F**tGQ~7Oo-}+y|(<#6TGkKT_je%niRCDH% zKAmYTnLzaN_ZYpB|E^#bO^#H*;HJovssRX@HC|PH)gix&YiXTGk_`i=9@w+1;oT(m zZu6+T1+_8%{%I8njjvx>>=gJ=am{)O$b2H*u#__dUZWj2PT#HdmgT=wCV8={+jAV_ z!L?ssQfK<1q7t`_JX?BtFF=_R`8>D5^;*sT*I?nVL?qq~4*5nT=Lhv<2i}Cvuww81 zz2}b$_Xhb0ybAQbnD(;2nE&SLJIlLvWNm%1<{Kc0el;M7=nK8>(wU5Cy8py^XC19n z-DNwRmiK`5qw?S*QcwKIoCmDjE=pE6|J?jlKm94cdxXIxmF<5gp>KMUZYW!Yt5s=~)Kd(7f+b{I5+*21#9oQ~D7rxL6=4n+BVVde$UWT(WHrWXF9 z$|R?WMLDjRU-z%&z@D$@XC-}6Y`|{MC<~ZfVg9QD1bM;RC*SYArxrnnRyP*1wup}& zQaZR#kub;QF19P@)YFjja><_Zy%V4nEbW*7ZkK;nJeGHJK?CMu+e!hcQhhc7z5EPj zx$guvp8$&v2E&SIVrI~Qj85`G8m|*LpFTK{{+DFcRbzq~jBK7Iw+lm4)K*lK^>TCW zhWn|0macp+`Z5?h$64QC$=J3j{=2%m{DC2P#@dj=ulwsBW9g~&-M)K;s9d(ua*rY560jyM#j(qw#55&0d3 z@ojm%>(`dR<{VS|!G~#bsk9!H>7bVz%Q~UfsKjCeYIEAoNaWp?wVa92h<{6Kt;nD>OL4<(i1u;i(h9~&(N`tt00Fp|=NhA2^_YDZ>=WJJp!2Z;5vrUw#0Y%*mn}Uj%h7WWTfF?bpsoP2CHJrI zy=SOA(gB=)Oe1c6pG@E%WH5IM(`Vk-^9FPf3glmb|&zSFn*8Vz1mqS(LkXvk*`YRz|Zd7@}> zG4RuXR&68FgQ=ASV|XL4 zDj!LuzPdQ|ksTq96C+(SL3k*cDHjXwDUG?EI7g_A8*z*u!q(vzQ%Tp_U>+X_OId2n zijwDffs>5=Qu=O+WsGb3^2o!OUrpX>uPE((6i|$sb$@se6e!W~HDs!P=HS|`qv@VJ1NNSwb`kUE$icA-Mr5HgiVI{Ew>3R`c-k{W&*C7 z1|LK%nMTgSFKE(#iCsK<<+QY~-Cl|Ev(MT5z;H>7%jZ$ShQ>e%<4nei&Nm_EE3L-f zUyp)wJ_a0`hOiMdde1?m=+`U>;ykOWnGAi3I@Egt90>S=XZhOXe=4@Za{hoxN=?*5 z*wgp5Md3iwn!Y}S)Br{SRXYBSpm5$Oj&8W~pKid#wq|uMJ71VE*w&d*%22w+9>yA=o%*{{#A! B>ly$6 literal 0 HcmV?d00001 diff --git a/backend/tests/fixtures/pre_cutover_admissions_capture.py.txt b/backend/tests/fixtures/pre_cutover_admissions_capture.py.txt new file mode 100644 index 000000000..91f681d81 --- /dev/null +++ b/backend/tests/fixtures/pre_cutover_admissions_capture.py.txt @@ -0,0 +1,42 @@ +"""One-time capture through pinned predecessor owners, never a current writer.""" +import gzip +import json +from pathlib import Path + +import asyncpg + +from app.api.deps.authorization import compose_hidden_submission_creation_command +from app.core.identifiers import new_record_id +from tests.tasks.test_submission_lineage import _prepared_packet + + +async def test_capture(isolated_database_env, tmp_path, monkeypatch): + snapshots = {} + + async def capture(status): + connection = await asyncpg.connect(isolated_database_env.replace('+asyncpg', '')) + try: + async with connection.transaction(isolation='repeatable_read', readonly=True): + assert await connection.fetchval('SHOW session_replication_role') == 'origin' + tables = {} + for table in await connection.fetch("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename"): + name = table['tablename'] + rows = json.loads(await connection.fetchval(f'SELECT coalesce(jsonb_agg(to_jsonb(r)),\'[]\')::text FROM public."{name}" r')) + if rows: + tables[name] = rows + runs = tables['selected_pre_submit_runs'] + assert len(runs) == 1 and runs[0]['status'] == 'completed' + assert [r['status'] for r in tables['submission_bundle_admissions']] == [status] + snapshots[status] = dict(revision=await connection.fetchval('SELECT version_num FROM alembic_version'), seed={}, tables=tables) + finally: + await connection.close() + + async with _prepared_packet(isolated_database_env, tmp_path) as h: + await capture('ready') + async with h.factory() as session: + await compose_hidden_submission_creation_command( + session, h.context, request_id=new_record_id(), correlation_id=new_record_id(), + ).create(h.creation) + await capture('consumed') + body = dict(schema_version='workstream.pre_cutover_admissions.v1', source_revision='e2b926288899bcd9b05e1a560ec19b6bca8cfcfc', source_test='tests/test_capture_pre_cutover_admissions.py::test_capture', snapshots=snapshots) + Path('/tmp/pre-cutover-admissions.json.gz').write_bytes(gzip.compress(json.dumps(body,sort_keys=True).encode(),mtime=0)) diff --git a/backend/tests/fixtures/pre_cutover_writer_proof.py.txt b/backend/tests/fixtures/pre_cutover_writer_proof.py.txt new file mode 100644 index 000000000..a0b6c0298 --- /dev/null +++ b/backend/tests/fixtures/pre_cutover_writer_proof.py.txt @@ -0,0 +1,53 @@ +"""One-time genuine predecessor writer against both sides of SQL cutover.""" +import asyncio +import json + +import asyncpg +import pytest +from alembic import command +from sqlalchemy.exc import DBAPIError + +from app.api.deps.authorization import compose_hidden_submission_creation_command +from app.core.identifiers import new_record_id +from app.db import session as db_session +from tests.conftest import _drop_test_database_schema +from tests.migration_fixtures import _config +from tests.tasks.test_submission_lineage import _prepared_packet + +pytestmark = pytest.mark.postgres_schema_contract + + +async def snapshot(url): + c = await asyncpg.connect(url.replace('+asyncpg', '')) + try: + result = {} + for row in await c.fetch("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename"): + name = row['tablename'] + result[name] = await c.fetchval(f'SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY to_jsonb(r)::text),\'[]\')::text FROM public."{name}" r') + return result + finally: + await c.close() + + +@pytest.mark.parametrize('cutover', [False, True]) +async def test_old_writer(isolated_database_env, tmp_path, migration_lock, cutover): + with migration_lock(): + await db_session.dispose_engine() + await _drop_test_database_schema(isolated_database_env) + await asyncio.to_thread(command.upgrade, _config(), '0065_claim_starts_work') + async with _prepared_packet(isolated_database_env, tmp_path) as h: + await asyncio.to_thread(command.upgrade, _config(), '0084_submission_source_binding' if cutover else '0083_accepted_revision') + before = await snapshot(isolated_database_env) + async with h.factory() as session: + old = compose_hidden_submission_creation_command(session, h.context, request_id=new_record_id(), correlation_id=new_record_id()) + if cutover: + with pytest.raises(DBAPIError, match='new submission binding requires accepted source custody'): + await old.create(h.creation) + else: + await old.create(h.creation) + after = await snapshot(isolated_database_env) + if cutover: + assert after == before + else: + assert len(json.loads(after['submissions'])) == 1 + assert [r['status'] for r in json.loads(after['submission_bundle_admissions'])] == ['consumed'] diff --git a/backend/tests/migrations/test_source_pre_cutover.py b/backend/tests/migrations/test_source_pre_cutover.py index a79cf1409..f7efc42d4 100644 --- a/backend/tests/migrations/test_source_pre_cutover.py +++ b/backend/tests/migrations/test_source_pre_cutover.py @@ -120,3 +120,132 @@ async def test_source_pre_cutover_preserves_or_refuses_historical_run( # Return a clean current schema; never force a historical live row terminal. await _drop_test_database_schema(isolated_database_env) await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + + +def _admission_archive(): + """Read both sides of the same genuine predecessor admission consumption.""" + encoded = _ARCHIVE.with_name('pre_cutover_admissions.json.gz').read_bytes() + assert hashlib.sha256(encoded).hexdigest() == '37bfa6433b233fb2a82b3c60c42b2946e747168452d51ca84203c64be5fee520' + body = json.loads(gzip.decompress(encoded)) + assert body['schema_version'] == 'workstream.pre_cutover_admissions.v1' + assert body['source_revision'] == 'e2b926288899bcd9b05e1a560ec19b6bca8cfcfc' + assert body['source_test'] == 'tests/test_capture_pre_cutover_admissions.py::test_capture' + snapshots = body['snapshots'] + for state, snapshot in snapshots.items(): + assert snapshot['revision'] == '0065_claim_starts_work' + assert [r['status'] for r in snapshot['tables']['submission_bundle_admissions']] == [state] + assert snapshots['ready']['tables']['submission_bundle_admissions'][0]['id'] == snapshots['consumed']['tables']['submission_bundle_admissions'][0]['id'] + return snapshots + + +async def _retained_rows_and_functions(url, tables): + """Compare all captured nonempty tables and all public function definitions.""" + connection = await asyncpg.connect(url.replace('+asyncpg', '')) + try: + rows = {} + for table in tables: + if table != 'alembic_version': + rows[table] = await connection.fetchval( + f'SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY to_jsonb(r)::text),\'[]\')::text FROM public."{table}" r' + ) + functions = dict(await connection.fetch("""SELECT p.oid::regprocedure::text, pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='public' AND p.prokind='f'""")) + return rows, functions + finally: + await connection.close() + + +async def _refuse_old_consumption_and_allow_stale(url, consumed): + """Use captured consumption fields; require the new guard before other constraints.""" + from uuid import UUID + + connection = await asyncpg.connect(url.replace('+asyncpg', '')) + try: + row_id = UUID(consumed['id']) + query = 'SELECT to_jsonb(a)::text FROM public.submission_bundle_admissions a WHERE id=$1' + before = await connection.fetchval(query, row_id) + with pytest.raises(asyncpg.ObjectNotInPrerequisiteStateError, match='new submission binding requires accepted source custody'): + async with connection.transaction(): + await connection.execute("""UPDATE public.submission_bundle_admissions + SET (status,consumed_at,consumed_by_submission_id,consumed_by_submission_version)= + (SELECT status,consumed_at,consumed_by_submission_id,consumed_by_submission_version + FROM jsonb_populate_record(NULL::public.submission_bundle_admissions,$1::jsonb)) + WHERE id=$2""", json.dumps(consumed), row_id) + assert await connection.fetchval(query, row_id) == before + await connection.execute("""UPDATE public.submission_bundle_admissions + SET status='stale',stale_at=clock_timestamp(),stale_reason='submission_flow_cutover' + WHERE id=$1""", row_id) + after = json.loads(await connection.fetchval(query, row_id)) + assert after['status'] == 'stale' and after['stale_at'] is not None + assert after['stale_reason'] == 'submission_flow_cutover' + original = json.loads(before) + mutable = {'status','stale_at','stale_reason'} + assert {k:v for k,v in after.items() if k not in mutable} == {k:v for k,v in original.items() if k not in mutable} + finally: + await connection.close() + + +async def _upgrade_admission_guard_behind_writer(url): + """Observe real cutover serialization before replacing the admission guard.""" + writer = await asyncpg.connect(url.replace('+asyncpg', '')) + observer = await asyncpg.connect(url.replace('+asyncpg', '')) + migration = None + try: + async with writer.transaction(): + await writer.execute('LOCK TABLE public.submission_bundle_admissions IN ROW EXCLUSIVE MODE') + migration = asyncio.create_task(asyncio.to_thread(command.upgrade, _config(), current_schema_revision())) + + async def wait_for_lock(): + while True: + if migration.done(): + await migration + raise AssertionError('source binding cutover did not wait for the old writer') + if await observer.fetchval("""SELECT EXISTS ( + SELECT 1 FROM pg_locks WHERE relation='public.submission_bundle_admissions'::regclass + AND mode='AccessExclusiveLock' AND NOT granted)"""): + return + await asyncio.sleep(0.05) + + await asyncio.wait_for(wait_for_lock(), timeout=30) + await migration + finally: + await writer.close() + await observer.close() + if migration is not None: + await asyncio.gather(migration, return_exceptions=True) + + +@pytest.mark.parametrize('state', ['ready', 'consumed']) +async def test_source_binding_cutover_preserves_history_and_closes_old_consumption( + isolated_database_env, migration_lock, state, +): + """Replace only the admission transition guard; never rewrite retained rows.""" + snapshots = _admission_archive() + snapshot = snapshots[state] + with migration_lock(): + await db_session.dispose_engine() + await _drop_test_database_schema(isolated_database_env) + try: + await asyncio.to_thread(command.upgrade, _config(), snapshot['revision']) + await _restore_validated_snapshot_rows(isolated_database_env, snapshot, expected_revision=snapshot['revision']) + await asyncio.to_thread(command.upgrade, _config(), '0082_policy_phase_cardinality') + await asyncio.to_thread(command.upgrade, _config(), '0083_accepted_revision') + before, old_functions = await _retained_rows_and_functions(isolated_database_env, snapshot['tables']) + if state == 'ready': + await _upgrade_admission_guard_behind_writer(isolated_database_env) + else: + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + after, new_functions = await _retained_rows_and_functions(isolated_database_env, snapshot['tables']) + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + assert await _retained_rows_and_functions(isolated_database_env, snapshot['tables']) == (after, new_functions) + assert after == before + assert set(old_functions) == set(new_functions) + assert {k for k in old_functions if old_functions[k] != new_functions[k]} == {'guard_submission_bundle_admission_lineage()'} + if state == 'ready': + await _refuse_old_consumption_and_allow_stale( + isolated_database_env, snapshots['consumed']['tables']['submission_bundle_admissions'][0], + ) + finally: + await _drop_test_database_schema(isolated_database_env) + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) From 473c32677ac1310a841e66bdf9a34356dd802417 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 00:52:46 +0100 Subject: [PATCH 194/513] test(tasks): migrate dispatch proofs to accepted finalization --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 33 ++++++ .../submission_dispatch/test_composition.py | 105 +++++++++++------- 2 files changed, 99 insertions(+), 39 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 7137d2511..e611d2d2a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6758,3 +6758,36 @@ checks pass; ARCH/SEC scoped PASS. QA-SQL-BIND001/002/003 evidence now complete. This closes the A33 admission-transition portion, not physical-provider/history qualification or full operational cutover. TASK old command, ART old publisher and preparation retirement remain next; keep full A01-A35/C01-C07 goal active. + +Dispatch proof migration scope: update tests/tasks/submission_dispatch/test_composition.py +from the obsolete hidden creation command to accepted T5 and retained dispatch reads. +Preserve exact dispatch/POST custody, reject mismatched receipt identifiers without +participant writes, and force the deferred SQL missing-dispatch failure through +real OUTBOX finalization. Rollback must preserve accepted T4/source custody while +removing all T5 writes. Internal retained reads are not fresh human authorization +proof; public intake replay and lost-ack outbox tests retain those distinct proofs. +No production behavior or compatibility helper is added. This removes one test +consumer blocking old TASK command deletion, not the complete deletion itself. +QA/test-delta review and focused isolated PostgreSQL tests required. + +Dispatch migration v1: 3 failures in97.07s, cleanup complete. Two new assertions +used nonexistent OutboxEvent.id; correct to native UUID event_id. The injected +missing dispatch correctly reaches SQL23514 at the current accepted-operation +closure guard (0074), before the older dispatch-required guard. Assert that exact +current error and preserve the no-dispatch injection and staged-write checks. +Also assert accepted receipt, sealed nonzero source charge, and active TASK pointer +survive T5 rollback. Structural and record validators passed; rerun after repairs. + +Dispatch migration v2 terminal0: 3passed63.85s, database and MinIO cleanup complete +(/tmp/submission-dispatch-current-v2.json and .log). Frozen test blob +232a026b0ef5934398d4aa68333adf0ead354f99. Current composed accepted owner returns +exact retained dispatch; each mismatched receipt key fails without POST creation; +real deferred missing-dispatch failure rolls back T5 while retaining T4 acceptance, +sealed charged source, active TASK pointer and exact finalization event. Tests ran +on these modified bytes with precommit HEAD e52a215c3, not a clean commit execution. +Existing T1 changed-metadata/revocation/post-body reauthorization and real OUTBOX +lost-ack tests retain distinct public/worker replay obligations. Scoped QA found no +actionable issue: selector coverage and current T4/T5 rollback semantics agree +with their owners. QA inspected shared execution evidence; no independent PG +rerun or mutation is claimed. Old TASK command removal and full end-to-end +qualification remain open. diff --git a/backend/tests/tasks/submission_dispatch/test_composition.py b/backend/tests/tasks/submission_dispatch/test_composition.py index 5ac8acf4d..232a026b0 100644 --- a/backend/tests/tasks/submission_dispatch/test_composition.py +++ b/backend/tests/tasks/submission_dispatch/test_composition.py @@ -1,8 +1,10 @@ -"""Real ART admission and AUTH through the canonical hidden transaction.""" +"""Accepted T5 dispatch custody, exact retained reads, and atomic rollback.""" +import pytest from sqlalchemy import select, func, text -from app.api.deps.authorization import compose_hidden_submission_creation_command +from app.adapters.artifacts import submission_admission_consumption_port +from app.adapters.tasks import accepted_submission_creation_service from app.core.identifiers import new_record_id from app.modules.checkers.models import CheckerRun from app.modules.outbox.models import OutboxEvent @@ -10,7 +12,22 @@ from tests.post_submit_materialization_helpers import material_fixture -async def test_creation_commits_exact_dispatch_and_fresh_transport_replay(tmp_path, isolated_database_env): +def _accepted_tasks(session, settings): + return accepted_submission_creation_service( + session, settings=settings, + admissions=submission_admission_consumption_port( + session, request_id=new_record_id(), correlation_id=new_record_id(), + ), + ) + + +def _receipt_key(result): + return dict(submission_id=result.submission_id, admission_id=result.admission_id, + creation_decision_id=result.creation_decision_id) + + +async def test_creation_commits_exact_dispatch_and_retained_read(tmp_path, isolated_database_env): + """T5 commits exact POST custody; its internal retained read creates nothing.""" async with material_fixture(tmp_path, isolated_database_env) as h: result = h.created async with h.factory() as session: @@ -27,68 +44,61 @@ async def test_creation_commits_exact_dispatch_and_fresh_transport_replay(tmp_pa assert event.payload["creation_decision_id"] == str(result.creation_decision_id) assert event.payload["binding_decision_id"] == str(result.binding_decision_id) assert await session.scalar(text("SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d WHERE submission_id=:id"), {"id": result.submission_id}) is True + events = set((await session.execute(select(OutboxEvent.event_id, OutboxEvent.event_type))).all()) + assert len(events) == 2 + assert (result.evaluation_event_id, event.event_type) in events + assert sum(kind == "SubmissionFinalizationRequested" for _, kind in events) == 1 allows = await session.scalar(select(func.count()).select_from(AuditEvent).where( AuditEvent.action_id.in_(["submission.create", "artifact.submission.binding.create"]), )) assert allows == 2 async with h.factory() as session: - replay = await compose_hidden_submission_creation_command( - session, h.actor_context.model_copy(update={"request_id": new_record_id(), "correlation_id": new_record_id()}), - request_id=new_record_id(), correlation_id=new_record_id(), - ).create(h.creation_request) - assert replay == result + assert await _accepted_tasks(session, h.settings).read_finalized(**_receipt_key(result)) == result async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(SubmissionDispatch)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert set((await session.execute(select(OutboxEvent.event_id, OutboxEvent.event_type))).all()) == events assert await session.scalar(select(func.count()).select_from(AuditEvent).where( AuditEvent.action_id.in_(["submission.create", "artifact.submission.binding.create"]), )) == allows -async def test_changed_request_cannot_create_or_repair_dispatch(tmp_path, isolated_database_env, monkeypatch): - from dataclasses import replace - import pytest - from app.modules.tasks.api import SubmissionCreationUnavailable, TaskSubmissionContextUnavailable +async def test_changed_receipt_key_cannot_create_or_repair_dispatch(tmp_path, isolated_database_env, monkeypatch): + """Every internal receipt identifier must match, without entering creation.""" + from app.modules.tasks.api import SubmissionCreationUnavailable from app.modules.checkers.execution_coordination import EvaluationCoordinator from app.modules.outbox.service import OutboxService async with material_fixture(tmp_path, isolated_database_env) as h: + async with h.factory() as session: + events = set((await session.execute(select(OutboxEvent.event_id))).scalars()) async def forbidden(*args, **kwargs): - pytest.fail("retry entered a creation participant") + pytest.fail("retained read entered a creation participant") monkeypatch.setattr(EvaluationCoordinator, "reserve_current_evaluation", forbidden) monkeypatch.setattr(OutboxService, "append", forbidden) - for field, value in { - "task_id": new_record_id(), "assignment_id": new_record_id(), - "contributor_id": new_record_id(), "admission_id": new_record_id(), - "predecessor_submission_id": new_record_id(), - "summary": "Different complete packet summary", "contributor_attestation": "Different valid attestation", - }.items(): + key = _receipt_key(h.created) + for field in key: async with h.factory() as session: - with pytest.raises((SubmissionCreationUnavailable, TaskSubmissionContextUnavailable)): - await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), correlation_id=new_record_id(), - ).create(replace(h.creation_request, **{field: value})) + with pytest.raises(SubmissionCreationUnavailable, match="finalized dispatch differs"): + await _accepted_tasks(session, h.settings).read_finalized(**{**key, field: new_record_id()}) async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(SubmissionDispatch)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 - async with h.factory() as session: - assert await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), correlation_id=new_record_id(), - ).create(h.creation_request) == h.created + assert set((await session.execute(select(OutboxEvent.event_id))).scalars()) == events + assert await _accepted_tasks(session, h.settings).read_finalized(**key) == h.created async def test_missing_dispatch_receipt_rejects_real_commit_and_rolls_back(tmp_path, isolated_database_env, monkeypatch): - import pytest + """A deferred T5 failure preserves accepted source custody for worker retry.""" from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.exc import IntegrityError from app.modules.artifacts.models import SubmissionBundleAdmission, SubmissionBindingReceipt + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge from app.modules.tasks.models import Submission from app.modules.tasks.submission_composition import TaskSubmissionCreationService add = AsyncSession.add - create = TaskSubmissionCreationService.create + create = TaskSubmissionCreationService.create_accepted staged = [] def omit_only_dispatch(session, instance, **kwargs): @@ -97,27 +107,44 @@ def omit_only_dispatch(session, instance, **kwargs): return return add(session, instance, **kwargs) - async def observe_before_commit(service, request): - result = await create(service, request) - for model in (Submission, SubmissionBindingReceipt, CheckerRun, OutboxEvent): + async def observe_before_commit(service, request, **kwargs): + result = await create(service, request, **kwargs) + for model in (Submission, SubmissionBindingReceipt, CheckerRun): assert await service._session.scalar(select(func.count()).select_from(model)) == 1 + assert await service._session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 assert await service._session.scalar(select(SubmissionBundleAdmission.status)) == "consumed" return result monkeypatch.setattr(AsyncSession, "add", omit_only_dispatch) - monkeypatch.setattr(TaskSubmissionCreationService, "create", observe_before_commit) - with pytest.raises(IntegrityError, match="submission dispatch required"): + monkeypatch.setattr(TaskSubmissionCreationService, "create_accepted", observe_before_commit) + with pytest.raises(AssertionError, match="expected successful retained source finalization") as failure: async with material_fixture(tmp_path, isolated_database_env): pytest.fail("incomplete creation committed") + assert isinstance(failure.value.__cause__, IntegrityError) + assert "submission finalization closure mismatch" in str(failure.value.__cause__) assert len(staged) == 1 and staged[0].evaluation_event_id is not None engine = create_async_engine(isolated_database_env) try: async with async_sessionmaker(engine)() as session: - for model in (Submission, SubmissionDispatch, SubmissionBindingReceipt, CheckerRun, OutboxEvent): + for model in (Submission, SubmissionDispatch, SubmissionBindingReceipt, SubmissionBundleAdmission, CheckerRun): assert await session.scalar(select(func.count()).select_from(model)) == 0 - assert await session.scalar(select(SubmissionBundleAdmission.status)) == "ready" + operation = (await session.execute(select(SubmissionIntakeOperation))).scalar_one() + assert operation.state == "finalization_pending" + assert operation.finalized_submission_id is None + assert operation.acceptance_receipt["status"] == "accepted" + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.state == "sealed" and charge.accounted_bytes > 0 + task = await session.get(WorkstreamTask, operation.task_id) + assert task.status == "evaluation_pending" + assert task.active_submission_operation_id == operation.id + event = (await session.execute(select(OutboxEvent))).scalar_one() + assert str(event.event_id) == str(operation.finalization_event_id) + assert event.event_type == "SubmissionFinalizationRequested" assert await session.scalar(select(func.count()).select_from(AuditEvent).where( - AuditEvent.action_id.in_(["submission.create", "artifact.submission.binding.create"]), + AuditEvent.action_id == "artifact.submission.binding.create", )) == 0 + assert await session.scalar(select(func.count()).select_from(AuditEvent).where( + AuditEvent.action_id == "submission.create", + )) == 1 finally: await engine.dispose() From b388401ba53fe48954822da1c0f924961f731f19 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 00:59:41 +0100 Subject: [PATCH 195/513] test(tasks): verify submission acceptance authority provenance --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 23 +++++++++ .../tasks/submission_dispatch/test_storage.py | 51 +++++++++++++++---- 2 files changed, 63 insertions(+), 11 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e611d2d2a..b716b1496 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6791,3 +6791,26 @@ actionable issue: selector coverage and current T4/T5 rollback semantics agree with their owners. QA inspected shared execution evidence; no independent PG rerun or mutation is claimed. Old TASK command removal and full end-to-end qualification remain open. + +Dispatch authority proof migration scope: test_storage.py still intercepts the +obsolete PreparedSubmissionCreationAuthorization, while its fixture now accepts +through source T4. Move the unrelated-allow substitution to current +SubmissionIntakeAuthorization.consume_acceptance. Preserve a genuine unrelated +persisted authority event, real preparation/consume, exact SQL rejection, and +assert no accepted handoff or Submission/POST is persisted. Foreground failure +must retain sealed source obligations for cleanup. Run all three storage tests +including independent SQL member substitution and immutability controls. This +removes another old AUTH test consumer; it does not claim old path retirement. +Required QA/security review limited to the changed attack and its owner mapping. + +Storage authority migration v1 terminal0:3passed115.98s at schema0084 with database +and MinIO cleanup complete (/tmp/submission-dispatch-authority-v1.json and .log). +Exact frozen test blob57dd8707b80ba6587848acf28d2b2a17e5708549; execution used modified +bytes over473c32677, not a clean postcommit execution. Unchanged independent SQL +substitution/immutability controls pass. Current T4 wrong-action allow reaches the +exact accepted-authority SQL refusal; genuine consume audit rolls back, unrelated +allow persists, no accepted/T5 writes survive, and sealed cleanup charge remains. +QA/security inspection found no actionable issue and confirmed unchanged control +ASTs. Verdict is limited to wrong-action/provenance substitution; no exhaustive +authority or provider qualification and no independent rerun/mutation is claimed. +Ruff, structural validator, Commitrail and whitespace checks passed. diff --git a/backend/tests/tasks/submission_dispatch/test_storage.py b/backend/tests/tasks/submission_dispatch/test_storage.py index 15544df92..57dd8707b 100644 --- a/backend/tests/tasks/submission_dispatch/test_storage.py +++ b/backend/tests/tasks/submission_dispatch/test_storage.py @@ -54,11 +54,20 @@ async def test_dispatch_and_bound_submission_remain_immutable(tmp_path, isolated assert await session.scalar(text("SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d WHERE submission_id=:id"), {"id": h.created.submission_id}) is True -async def test_unrelated_allow_cannot_substitute_for_creation_allow_at_commit(tmp_path, isolated_database_env, monkeypatch): - from sqlalchemy import select - from app.modules.authorization.submission_creation_authorization import PreparedSubmissionCreationAuthorization - from app.modules.tasks.models import AuditEvent - original = PreparedSubmissionCreationAuthorization.consume +async def test_unrelated_allow_cannot_substitute_for_acceptance_allow_at_commit(tmp_path, isolated_database_env, monkeypatch): + """T4 rejects a real unrelated allow and leaves no accepted handoff or T5 writes.""" + from uuid import UUID + from sqlalchemy import func, select + from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + from app.modules.authorization.submission_intake import SubmissionIntakeAuthorization + from app.modules.artifacts.intake.repository import IntakeCustodyConflict + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from app.modules.artifacts.models import SubmissionBundleAdmission, SubmissionBindingReceipt + from app.modules.checkers.models import CheckerRun + from app.modules.outbox.models import OutboxEvent + from app.modules.tasks.models import AuditEvent, Submission, SubmissionDispatch, WorkstreamTask + + original = SubmissionIntakeAuthorization.consume_acceptance substituted = [] async def wrong_receipt(self, handle, facts): @@ -68,14 +77,34 @@ async def wrong_receipt(self, handle, facts): AuditEvent.action_id.not_in(("submission.create", "artifact.submission.binding.create")), ).order_by(AuditEvent.id).limit(1)) assert unrelated is not None and unrelated != str(real) - from uuid import UUID substituted.append((real, UUID(unrelated))) return UUID(unrelated) - monkeypatch.setattr(PreparedSubmissionCreationAuthorization, "consume", wrong_receipt) - # The event and dispatch are both built from the substituted value. IDs, - # digests, FK targets and all other participants remain valid and complete. - with pytest.raises(IntegrityError, match="submission dispatch custody mismatch"): + monkeypatch.setattr(SubmissionIntakeAuthorization, "consume_acceptance", wrong_receipt) + # The complete accepted receipt and event use the unrelated existing allow. + # No selector is nonexistent; only the authority provenance is wrong. + with pytest.raises(IntakeCustodyConflict, match="intake_acceptance_conflict") as denied: async with material_fixture(tmp_path, isolated_database_env): - pytest.fail("an unrelated allow was accepted as creation authority") + pytest.fail("an unrelated allow was accepted as submission authority") assert len(substituted) == 1 + assert isinstance(denied.value.__cause__, IntegrityError) + assert "accepted authority mismatch" in str(denied.value.__cause__) + engine = create_async_engine(isolated_database_env) + try: + async with async_sessionmaker(engine)() as session: + operation = (await session.execute(select(SubmissionIntakeOperation))).scalar_one() + assert operation.state == "failed" + assert operation.acceptance_decision_id is None + assert operation.acceptance_receipt is None + assert operation.finalization_event_id is None + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.state == "sealed" and charge.accounted_bytes > 0 + task = await session.get(WorkstreamTask, operation.task_id) + assert task.status == "in_progress" and task.active_submission_operation_id is None + for model in (Submission, SubmissionDispatch, SubmissionBundleAdmission, + SubmissionBindingReceipt, CheckerRun, OutboxEvent): + assert await session.scalar(select(func.count()).select_from(model)) == 0 + assert await session.get(AuditEvent, str(substituted[0][0])) is None + assert await session.get(AuditEvent, str(substituted[0][1])) is not None + finally: + await engine.dispose() From b2e621581f6cae2013695abcfb77d70a428e89d9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 01:11:34 +0100 Subject: [PATCH 196/513] test(tasks): migrate retained dispatch replay and caller authority proofs --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 31 +++++ .../tasks/submission_dispatch/test_replay.py | 129 ++++++++++-------- 2 files changed, 103 insertions(+), 57 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b716b1496..d32f02f3c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6814,3 +6814,34 @@ QA/security inspection found no actionable issue and confirmed unchanged control ASTs. Verdict is limited to wrong-action/provenance substitution; no exhaustive authority or provider qualification and no independent rerun/mutation is claimed. Ruff, structural validator, Commitrail and whitespace checks passed. + +Retained replay test migration scope: replace test_replay.py's obsolete hidden +creation command with composed TASK read_finalized for retained generation, +foreign receipt selectors and unavailable/invalid SQL custody. Old request-field +mutations map to T1 metadata/actor controls and SQL independent foreign-member +validation, not invented fields on the new internal read. Move actor suspension +checks to configured contributor operation read and binding-service suspension to +the actual PreparedSubmissionFinalizationAuthorization gate. This latter component +check is not an end-to-end outbox replay claim; existing lost-ack outbox proof owns +that composition. Preserve valid controls, exact persisted event identities, no +creation participant entry and no repair. Old individual Python-owner missing-read +mocks are obsolete: current TASK reads one SQL-valid dispatch; actual SQL member +substitution/immutability proofs remain in test_storage.py (3pass previous scope). +QA/security review required for coverage mapping and precise evidence limitations. + +Replay migration v1 terminal0:4passed203.03s, complete database/MinIO cleanup +(/tmp/submission-retained-replay-v1.json/.log). QA-REPLAY001 confirms human denial +must assert code submission_unavailable, not any SubmissionIntakeFailure (which +also includes infrastructure errors). Add that exact code assertion; retain real +suspension and positive controls. No other scoped finding. Rerun changed security +case on final bytes; other three tests are unchanged. One Pydantic serialization +warning from the existing generation2 fixture is not suppressed or claimed fixed. + +Final replay security v2 terminal0:1passed32.20s, all cleanup complete +(/tmp/submission-retained-replay-security-v2.json/.log). QA-REPLAY001 closed by exact +submission_unavailable refusal with positive controls. Final test blob +1953d6286901b2061831447125cfc48af114dc8d; the other three v1 tests remain unchanged. +Scoped QA/security inspection found no remaining issues. Evidence is shared +executions on frozen modified bytes over b388401ba, not an independent rerun or +clean postcommit execution. Broader old-command removal and final qualification +remain open. Same draft PR708 only. diff --git a/backend/tests/tasks/submission_dispatch/test_replay.py b/backend/tests/tasks/submission_dispatch/test_replay.py index 6196fb124..1953d6286 100644 --- a/backend/tests/tasks/submission_dispatch/test_replay.py +++ b/backend/tests/tasks/submission_dispatch/test_replay.py @@ -1,33 +1,31 @@ """Retained creation cannot reset generations or borrow another owner's admission.""" -from dataclasses import replace - import pytest from sqlalchemy import func, select, text from app.adapters.checkers import evaluation_coordinator -from app.api.deps.authorization import compose_hidden_submission_creation_command +from tests.tasks.submission_dispatch.test_composition import _accepted_tasks, _receipt_key from app.core.identifiers import new_record_id from app.modules.actors.models import ActorProfile from app.modules.actors.api import ServiceIdentity -from app.modules.tasks.api import SubmissionCreationAdmissionError from app.modules.checkers.models import CheckerRun, CheckerSubmissionFence from app.modules.outbox.models import OutboxEvent -from app.modules.tasks.api import SubmissionCreationUnavailable, TaskSubmissionContextUnavailable +from app.modules.tasks.api import SubmissionCreationUnavailable from app.modules.tasks.models import SubmissionDispatch from tests.checkers.post_submit.support import change_request from tests.post_submit_materialization_helpers import material_fixture -async def replay(h, request=None): +async def replay(h, key=None): + """Read exact retained custody, without claiming current caller authority.""" async with h.factory() as session: - return await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), correlation_id=new_record_id(), - ).create(request or h.creation_request) + return await _accepted_tasks(session, h.settings).read_finalized(**(key or _receipt_key(h.created))) -async def test_later_generation_does_not_change_original_creation_replay(tmp_path, isolated_database_env): +async def test_later_generation_preserves_original_retained_dispatch(tmp_path, isolated_database_env): async with material_fixture(tmp_path, isolated_database_env) as h: + async with h.factory() as session: + events = set((await session.execute(select(OutboxEvent.event_id))).scalars()) successor = change_request(h.request, evaluation_request_id=new_record_id(), evaluation_generation=2) async with h.factory.begin() as session: newer = await evaluation_coordinator(session).reserve_current_evaluation(successor) @@ -36,100 +34,117 @@ async def test_later_generation_does_not_change_original_creation_replay(tmp_pat fence = await session.get(CheckerSubmissionFence, str(h.created.submission_id)) assert fence.current_run_id == str(newer.attempt_id) assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 2 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert set((await session.execute(select(OutboxEvent.event_id))).scalars()) == events -async def test_valid_foreign_ownership_cannot_be_mixed_into_creation_replay(tmp_path, isolated_database_env): +async def test_valid_foreign_receipt_members_cannot_be_mixed_into_retained_read(tmp_path, isolated_database_env): async with material_fixture(tmp_path / "first", isolated_database_env) as h: async with material_fixture(tmp_path / "foreign", isolated_database_env, provision_services=False, storage_settings=h.settings) as foreign: - for field in ("task_id", "assignment_id", "contributor_id", "admission_id"): - with pytest.raises((SubmissionCreationUnavailable, TaskSubmissionContextUnavailable)): - await replay(h, replace(h.creation_request, **{field: getattr(foreign.creation_request, field)})) + for field in _receipt_key(h.created): + assert getattr(h.created, field) != getattr(foreign.created, field) + with pytest.raises(SubmissionCreationUnavailable, match="finalized dispatch differs"): + await replay(h, {**_receipt_key(h.created), field: getattr(foreign.created, field)}) assert await replay(h) == h.created assert await replay(foreign) == foreign.created async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(SubmissionDispatch)) == 2 assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 2 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 2 + assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 4 + +async def test_live_suspension_denies_current_read_and_worker_authority(tmp_path, isolated_database_env): + """Caller gates recheck live identities; internal retained reads grant no authority.""" + from uuid import UUID + from app.adapters.artifacts import ConfiguredSubmissionOperationReader + from app.modules.artifacts.api.submission_command import SubmissionOperationSelector + from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization + from app.modules.authorization.prepared import PreparedAuthorizationUnsupported -async def test_live_revocation_and_service_suspension_deny_retained_replay(tmp_path, isolated_database_env): async with material_fixture(tmp_path, isolated_database_env) as h: - async with h.factory.begin() as session: + async with h.factory() as session: + operation = (await session.execute(select(SubmissionIntakeOperation))).scalar_one() + selector = SubmissionOperationSelector(operation_id=UUID(operation.id)) binding_actor = await session.scalar(select(ActorProfile.id).where( ActorProfile.service_identity == ServiceIdentity.ARTIFACT_BINDING.value, )) - for actor_id in (str(h.actor_context.actor_profile_id), binding_actor): + events = set((await session.execute(select(OutboxEvent.event_id))).scalars()) + reader = ConfiguredSubmissionOperationReader(sessions=h.factory, context=h.actor_context) + async def read(): + return await reader.read(h.request.task_id, selector) + async def authorize_worker(): + async with h.factory.begin() as session: + authority = PreparedSubmissionFinalizationAuthorization( + session, request_id=new_record_id(), correlation_id=selector.operation_id) + try: + await authority.authorize() + finally: + authority.close() + initial = await read() + await authorize_worker() + for actor_id, call, error in ( + (str(h.actor_context.actor_profile_id), read, SubmissionIntakeFailure), + (binding_actor, authorize_worker, PreparedAuthorizationUnsupported), + ): async with h.factory.begin() as session: await session.execute(text("UPDATE public.actor_profiles SET status='suspended', suspended_by='dispatch-test', suspended_at=clock_timestamp(), suspension_reason='Recheck live authority' WHERE id=:id"), {"id": actor_id}) try: - with pytest.raises((SubmissionCreationUnavailable, SubmissionCreationAdmissionError)): - await replay(h) + with pytest.raises(error) as denied: + await call() + if error is SubmissionIntakeFailure: + assert denied.value.code == "submission_unavailable" finally: async with h.factory.begin() as session: await session.execute(text("UPDATE public.actor_profiles SET status='active', suspended_by=NULL, suspended_at=NULL, suspension_reason=NULL, reactivated_by='dispatch-test', reactivated_at=clock_timestamp(), reactivation_reason='Restore valid control' WHERE id=:id"), {"id": actor_id}) + assert await read() == initial + await authorize_worker() assert await replay(h) == h.created async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(SubmissionDispatch)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert set((await session.execute(select(OutboxEvent.event_id))).scalars()) == events -async def test_missing_retained_owners_never_trigger_repair(tmp_path, isolated_database_env, monkeypatch): +async def test_missing_or_invalid_retained_dispatch_never_triggers_repair(tmp_path, isolated_database_env, monkeypatch): + """Missing dispatch or non-true SQL custody cannot trigger new participant writes.""" from sqlalchemy.ext.asyncio import AsyncSession - from app.modules.audit.service import AuditService - from app.modules.artifacts.models import SubmissionBindingReceipt from app.modules.checkers.execution_coordination import EvaluationCoordinator - from app.modules.checkers.api.execution import CheckerExecutionUnavailable - from app.modules.outbox.repository import OutboxRepository from app.modules.outbox.service import OutboxService - from app.modules.outbox.api import OutboxIdempotencyConflict async with material_fixture(tmp_path, isolated_database_env) as h: + async with h.factory() as session: + events = set((await session.execute(select(OutboxEvent.event_id))).scalars()) async def forbidden(*args, **kwargs): - pytest.fail("retained replay tried to create missing custody") + pytest.fail("retained read tried to repair missing custody") original_scalar, original_get = AsyncSession.scalar, AsyncSession.get - original_audit = AuditService.get_authority_event - for missing in ("dispatch", "creation_allow", "binding_receipt", "binding_allow", "reservation", "event"): + for unavailable in ("dispatch", False, None): seen = [] async def read_scalar(session, statement, *args, **kwargs): - model = SubmissionDispatch if missing == "dispatch" else CheckerRun if missing == "reservation" else None - if model is not None and any(value.get("entity") is model for value in getattr(statement, "column_descriptions", ())): - seen.append(missing) - return None + if "public.submission_dispatch_valid(d)" in str(statement): + seen.append("validation") + parameters = kwargs.get("params") if "params" in kwargs else args[0] + assert parameters["id"] == str(h.created.submission_id) + return unavailable return await original_scalar(session, statement, *args, **kwargs) async def read_get(session, entity, ident, **kwargs): - if missing == "binding_receipt" and entity is SubmissionBindingReceipt: - assert ident == str(h.created.admission_id) - seen.append(missing) + if unavailable == "dispatch" and entity is SubmissionDispatch: + assert ident == str(h.created.submission_id) + seen.append("dispatch") return None return await original_get(session, entity, ident, **kwargs) - async def read_audit(service, identifier): - selected = h.created.creation_decision_id if missing == "creation_allow" else h.created.binding_decision_id if missing == "binding_allow" else None - if identifier == selected: - seen.append(missing) - return None - return await original_audit(service, identifier) - async def read_event(repository, identifier, value): - assert identifier == h.created.evaluation_event_id - seen.append(missing) - return None with monkeypatch.context() as patch: patch.setattr(EvaluationCoordinator, "reserve_current_evaluation", forbidden) patch.setattr(OutboxService, "append", forbidden) - patch.setattr(AsyncSession, "scalar", read_scalar) patch.setattr(AsyncSession, "get", read_get) - patch.setattr(AuditService, "get_authority_event", read_audit) - if missing == "event": - patch.setattr(OutboxRepository, "read_exact", read_event) - with pytest.raises((SubmissionCreationUnavailable, TaskSubmissionContextUnavailable, - SubmissionCreationAdmissionError, CheckerExecutionUnavailable, - OutboxIdempotencyConflict)): + if unavailable != "dispatch": + patch.setattr(AsyncSession, "scalar", read_scalar) + with pytest.raises(SubmissionCreationUnavailable, match="finalized dispatch differs"): await replay(h) - assert seen == [missing] + assert seen == ["dispatch" if unavailable == "dispatch" else "validation"] assert await replay(h) == h.created async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(SubmissionDispatch)) == 1 assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 - assert await session.scalar(select(func.count()).select_from(OutboxEvent)) == 1 + assert set((await session.execute(select(OutboxEvent.event_id))).scalars()) == events From a091cb7d652e7479bf2d2b96c17c16cda207f001 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 01:21:09 +0100 Subject: [PATCH 197/513] test(tasks): exercise accepted revision dispatch tampering --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 28 ++++ .../test_predecessor_receipt.py | 154 +++++++++++------- 2 files changed, 123 insertions(+), 59 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d32f02f3c..e44081588 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6845,3 +6845,31 @@ Scoped QA/security inspection found no remaining issues. Evidence is shared executions on frozen modified bytes over b388401ba, not an independent rerun or clean postcommit execution. Broader old-command removal and final qualification remain open. Same draft PR708 only. + +Predecessor receipt proof migration scope: replace the old verified-ready admission +and hidden TASK creation in test_predecessor_receipt.py with current source T1/PRE/ +T4 and production OUTBOX T5. Use genuine local and foreign routed failures. Change +only the new dispatch remediation manifest. Force its deferred constraint after +T5 has staged finalized operation custody, not prematurely inside create_accepted. +Add matching valid revision control to exclude incomplete-finalization false proof. +Require exact23514 replacement-cause guard, no T5 owner effects after rollback, +and preserved accepted operation/source/event/task pointer. QA/security review and +isolated PostgreSQL positive/negative cases required. Old producer retirement is +still incomplete; this ports another required negative test before deletion. + +Accepted predecessor v1 terminal0:2passed120.19s, complete cleanup +(/tmp/submission-predecessor-receipt-v1.json/.log). The matching valid revision +commits; changing only its dispatch manifest reaches exact23514 replacement +currentness refusal after complete T5 staging. Strengthen negative rollback with +explicit absent candidate Submission/CheckerRun/POST event and retained exact T4 +event. Rerun only changed foreign case; valid control remains unchanged. + +Final foreign predecessor case v2 terminal0:1passed58.76s, complete database/MinIO +cleanup (/tmp/submission-predecessor-receipt-v2.json/.log). Final test blob +e0b0633363349f61867dda1809b0a5b0219baabc; valid v1 control unchanged. QA/security +inspection found no actionable issue. This explicitly forced deferred-constraint +check proves cause validation after complete staging and rollback, not native +COMMIT constraint ordering. Retained T4 event is checked by its persisted ID, +type and operation association, not full payload byte equality. Shared executed +content over b2e621581 is the evidence; no independent or clean-commit rerun claim. +Ruff, structure, record and whitespace checks passed. Full retirement remains open. diff --git a/backend/tests/tasks/submission_dispatch/test_predecessor_receipt.py b/backend/tests/tasks/submission_dispatch/test_predecessor_receipt.py index 1ee693376..e0b063336 100644 --- a/backend/tests/tasks/submission_dispatch/test_predecessor_receipt.py +++ b/backend/tests/tasks/submission_dispatch/test_predecessor_receipt.py @@ -1,88 +1,124 @@ -"""Deferred replacement receipt currentness after valid canonical successor staging.""" +"""Deferred accepted-revision receipt rejects a genuine foreign routed cause.""" + +from uuid import UUID import pytest -from sqlalchemy import event, text +from sqlalchemy import event, select, text from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import AsyncSession -from app.api.deps.authorization import compose_hidden_submission_creation_command -from app.core.identifiers import new_record_id -from app.modules.artifacts.models import SubmissionBundleAdmission -from app.modules.tasks.api import SubmissionCreationRequest -from app.modules.tasks.models import SubmissionDispatch +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata +from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge +from app.modules.tasks.models import Submission, SubmissionDispatch, WorkstreamTask +from app.modules.checkers.models import CheckerRun +from app.modules.outbox.models import OutboxEvent from app.modules.tasks.submission_composition import TaskSubmissionCreationService +from tests.post_submit_materialization_helpers import create_source_submission, _submit_current_source from tests.tasks.post_submit_routing.remediation_support import remediation_source, no_economic_effects from tests.tasks.post_submit_routing.support import revision_archive -from tests.tasks.submission_lineage_support import _verified_admission -from tests.test_submission_predecessor_custody import ( - _fixture_revision_context, _replacement_request, _snapshot, -) +from tests.test_submission_predecessor_custody import _fixture_revision_context +from tests.selected_predecessor_fixtures import _snapshot -async def test_deferred_dispatch_rejects_foreign_manifest_after_valid_successor_insert( - tmp_path, isolated_database_env, monkeypatch, +@pytest.mark.parametrize("foreign_cause", [False, True], ids=["valid", "foreign-manifest"]) +async def test_deferred_dispatch_checks_accepted_successor_cause( + tmp_path, isolated_database_env, monkeypatch, foreign_cause, ): + """Only the foreign dispatch cause fails after otherwise complete real T5 staging.""" async with remediation_source(tmp_path / "local", isolated_database_env) as local: async with remediation_source( tmp_path / "foreign", isolated_database_env, provision_services=False, storage_settings=local.settings, ) as foreign: - await _fixture_revision_context(local) + local_source = await _fixture_revision_context(local) foreign_source = await _fixture_revision_context(foreign) - request = _replacement_request( - local, revision_archive(local.data), - predecessor_id=local.created.submission_id, idempotency_key=new_record_id(), - ) - admission_id = await _verified_admission( - local.factory, local.store, local.namespace, local.settings, - local.actor_context, request, - ) - before = await _snapshot(local) - creation = SubmissionCreationRequest( + assert local_source != foreign_source + metadata = SubmissionIntakeMetadata( task_id=local.request.task_id, assignment_id=local.request.assignment_id, - contributor_id=local.actor_context.actor_profile_id, predecessor_submission_id=local.created.submission_id, - admission_id=admission_id, summary=request.summary, - contributor_attestation=request.contributor_attestation, + revision_preparation_id=UUID(str(local.revision_preparation_id)), + revision_preparation_sha256=local.revision_preparation_sha256, + summary=local.creation_request.summary, + contributor_attestation=local.creation_request.contributor_attestation, ) - staged = [] - original_create = TaskSubmissionCreationService.create + accepted, staged, checked = [], [], [] + original_create, original_commit = TaskSubmissionCreationService.create_accepted, AsyncSession.commit + + async def observe_acceptance(factory, context, command, selected, data): + receipt = await _submit_current_source(factory, context, command, selected, data) + accepted.append((receipt, await _snapshot(local))) + return receipt def foreign_dispatch_cause(_mapper, _connection, dispatch): - # Earlier owners use the real local preparation; only the - # deferred receipt carries a foreign routed cause. - dispatch.checker_remediation_manifest_id = foreign_source + assert dispatch.task_id == str(local.request.task_id) + assert dispatch.checker_remediation_manifest_id == local_source + if foreign_cause: + dispatch.checker_remediation_manifest_id = foreign_source + + async def observe_creation(service, selected, **kwargs): + result, decision = await original_create(service, selected, **kwargs) + staged.append(result) + service._session.info["predecessor_receipt_test"] = result + return result, decision - async def check_deferred_receipt(service, selected): - result = await original_create(service, selected) - assert await service._session.scalar(text( - "SELECT count(*) FROM public.submission_dispatches WHERE submission_id=:id" - ), {"id": result.submission_id}) == 1 - staged.append(result.submission_id) - await service._session.execute(text( - "SET CONSTRAINTS submission_dispatch_complete IMMEDIATE" - )) - return result + async def check_complete_commit(session): + result = session.info.pop("predecessor_receipt_test", None) + if result is not None: + operation = await session.scalar(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.finalized_submission_id == str(result.submission_id))) + assert operation is not None and operation.state == "finalized" + assert await session.scalar(text( + "SELECT count(*) FROM public.submission_dispatches WHERE submission_id=:id" + ), {"id": result.submission_id}) == 1 + checked.append(result.submission_id) + await session.execute(text("SET CONSTRAINTS submission_dispatch_complete IMMEDIATE")) + return await original_commit(session) - monkeypatch.setattr(TaskSubmissionCreationService, "create", check_deferred_receipt) + monkeypatch.setattr(TaskSubmissionCreationService, "create_accepted", observe_creation) + monkeypatch.setattr(AsyncSession, "commit", check_complete_commit) event.listen(SubmissionDispatch, "before_insert", foreign_dispatch_cause) try: - with pytest.raises( - IntegrityError, match="replacement dispatch evaluation is not current", - ) as denied: - async with local.factory() as session: - await compose_hidden_submission_creation_command( - session, local.actor_context, request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(creation) - assert denied.value.orig.sqlstate == "23514" + async def submit(): + return await create_source_submission( + local.factory, local.actor_context, local.store.wrapped, local.namespace, + local.settings, metadata, revision_archive(local.data), submit_source=observe_acceptance) + if foreign_cause: + with pytest.raises(AssertionError, match="expected successful retained source finalization") as denied: + await submit() + error = denied.value.__cause__ + assert isinstance(error, IntegrityError) + assert error.orig.sqlstate == "23514" + assert "replacement dispatch evaluation is not current" in str(error) + else: + result = await submit() + assert result.submission_version == 2 finally: event.remove(SubmissionDispatch, "before_insert", foreign_dispatch_cause) - assert len(staged) == 1 - assert await _snapshot(local) == before + assert len(accepted) == len(staged) == len(checked) == 1 + assert checked[0] == staged[0].submission_id + receipt, before = accepted[0] async with local.factory() as session: - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert admission.status == "ready" - assert await session.scalar(text( - "SELECT status FROM public.workstream_tasks WHERE id=:id" - ), {"id": local.request.task_id}) == "needs_revision" + operation = await session.get(SubmissionIntakeOperation, receipt["operation_id"]) + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.state == "sealed" and charge.accounted_bytes > 0 + task = await session.get(WorkstreamTask, str(local.request.task_id)) + assert task.status == "evaluation_pending" + if foreign_cause: + assert await _snapshot(local) == before + assert operation.state == "finalization_pending" and operation.acceptance_receipt == receipt + assert operation.finalized_submission_id is None + assert task.active_submission_operation_id == operation.id + assert await session.get(SubmissionDispatch, str(staged[0].submission_id)) is None + assert await session.get(Submission, str(staged[0].submission_id)) is None + assert await session.get(CheckerRun, str(staged[0].evaluation_attempt_id)) is None + assert await session.get(OutboxEvent, staged[0].evaluation_event_id) is None + finalization = await session.get(OutboxEvent, UUID(operation.finalization_event_id)) + assert finalization.event_type == "SubmissionFinalizationRequested" + assert finalization.payload["operation_id"] == operation.id + else: + assert operation.state == "finalized" + assert operation.finalized_submission_id == str(result.submission_id) + dispatch = await session.get(SubmissionDispatch, str(result.submission_id)) + assert dispatch.checker_remediation_manifest_id == local_source + assert task.active_submission_operation_id is None await no_economic_effects(session) From 559617e9f3c0e88ac50fff6a932db3790a5103ea Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 01:35:44 +0100 Subject: [PATCH 198/513] test(tasks): verify accepted revision rollback and durable retry --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 38 +++++ .../test_replacement_creation.py | 131 +++++++++++++----- 2 files changed, 134 insertions(+), 35 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e44081588..0b6374e72 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6873,3 +6873,41 @@ COMMIT constraint ordering. Retained T4 event is checked by its persisted ID, type and operation association, not full payload byte equality. Shared executed content over b2e621581 is the evidence; no independent or clean-commit rerun claim. Ruff, structure, record and whitespace checks passed. Full retirement remains open. + +Revision POST-insert rollback/retry migration scope: port the late outbox failure +case in test_replacement_creation.py from old ready admission/create to real source +acceptance and OUTBOX T5. Keep actual SQL insert-trigger failure with nontransactional +sequence witness. Compare retained product/binding/checker/creation-audit snapshots, +retain accepted source/task/event custody, then remove fault and retry the same +finalization event after actual recorded retry/continuation deadlines. No clock +patches or fabricated ready state. Assert one version2 successor with exact local +cause and one new POST event. Remaining stale-cause/race tests are separate pending +consumers; this change does not claim their coverage or production retirement. +QA/security review and isolated PostgreSQL execution required. + +POST rollback v1:1failed50.17s, cleanup complete. Actual handler returned the +expected OutboxPersistenceError, but the test wrongly expected its SQL cause to +be exposed. OUTBOX's payload-free error frame deliberately removes that cause. +Assert exact stable error and absent cause, retaining the nontransactional sequence +witness of the unconditional SQL fault. Do not expose diagnostics or weaken owner +error handling for the test. Retry/post-rollback assertions were not yet reached. + +POST rollback v2 terminal0:1passed121.89s, complete cleanup. QA-ROLLBACK001 tightens +stable error to equality (substring allowed leaked suffix). QA-ROLLBACK002 adds +existing ART snapshot at accepted baseline and after failure: source registration +now creates artifact_contents/artifact_replicas inside T5, unlike old ready/create, +so preserved binding/admission rows alone would miss orphaned registered rows. +Retain that helper's content/replica counts plus other ART owner counts, and keep +existing projected product snapshot (four mutable Submission status/time fields +excluded by its preexisting definition). No claim of byte-identical every-row +state. Both repairs will run together on final bytes, including real retry. + +Final POST rollback/retry v3 terminal0:1passed125.71s, schema0084 and complete +DB/MinIO cleanup (/tmp/submission-revision-post-rollback-v3.json/.log). Frozen test +blob facd01d41abba1933ac3a36c9de1f5484b11acd9. Exact sanitized error/SQL witness, +ART registration counts, retained projected product state and same-event real +retry all pass. QA-ROLLBACK001/002 code findings closed with final executed +repairs; scoped QA/security reports no further finding. Other two tests/helpers +in module AST-unchanged and still pending migration. Shared modified-content +execution over a091cb7d6 only; no independent or clean-commit rerun claim. Final +Ruff/structure/record/whitespace checks passed. Full retirement and goal open. diff --git a/backend/tests/tasks/submission_dispatch/test_replacement_creation.py b/backend/tests/tasks/submission_dispatch/test_replacement_creation.py index fbcb737c7..facd01d41 100644 --- a/backend/tests/tasks/submission_dispatch/test_replacement_creation.py +++ b/backend/tests/tasks/submission_dispatch/test_replacement_creation.py @@ -277,16 +277,62 @@ async def pause_with_task_lock(repository, *args, **kwargs): assert await _creation_snapshot(h) == committed -async def test_late_outbox_insert_failure_rolls_back_and_ready_retry_succeeds( - tmp_path, - isolated_database_env, +async def test_late_outbox_insert_failure_rolls_back_and_accepted_retry_succeeds( + tmp_path, isolated_database_env, ): + """Real failed POST INSERT leaves T4 custody; the same event retries real T5.""" + from datetime import timedelta + from uuid import UUID + from app.adapters.artifacts import submission_finalization_handler + from app.adapters.auth import outbox_dispatch_authorization + from app.adapters.outbox import outbox_delivery + from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from app.modules.outbox.api import DeliveryOptions + from app.modules.outbox.registry import HandlerRegistry + from tests.artifacts.test_submission_pre_source import _source_runtime + from tests.post_submit_materialization_helpers import _submit_current_source + from tests.retained_material_fixtures import _foreground + from tests.selected_predecessor_fixtures import _snapshot as artifact_snapshot + async with remediation_source(tmp_path, isolated_database_env) as h: source_id = await _fixture_revision_context(h) - prepared, admission_id = await _ready_replacement(h, revision_archive(h.data)) - creation = _creation_request(h, prepared, admission_id) + data = revision_archive(h.data) + runtime_root = tmp_path / "revision-runtime" + runtime_root.mkdir() + runtime, errors = _source_runtime(data, runtime_root, "completed") + command = _foreground(h.factory, h.actor_context, h.namespace, h.store.wrapped, runtime) + metadata = SubmissionIntakeMetadata( + task_id=h.request.task_id, assignment_id=h.request.assignment_id, + predecessor_submission_id=h.created.submission_id, + revision_preparation_id=UUID(str(h.revision_preparation_id)), + revision_preparation_sha256=h.revision_preparation_sha256, + summary=h.creation_request.summary, + contributor_attestation=h.creation_request.contributor_attestation, + ) + receipt = await _submit_current_source(h.factory, h.actor_context, command, metadata, data) + assert receipt["status"] == "accepted" and not errors, errors + operation_id = receipt["operation_id"] + async with h.factory() as session: + operation = await session.get(SubmissionIntakeOperation, operation_id) + event_id, project_id = UUID(operation.finalization_event_id), UUID(operation.project_id) + event_ids = set((await session.execute(select(OutboxEvent.event_id))).scalars()) before = await _creation_snapshot(h) - + artifacts_before = await artifact_snapshot(h) + handler = submission_finalization_handler(sessions=h.factory, settings=h.settings, + store=h.store.wrapped, lease_duration=timedelta(seconds=40)) + failures = [] + async def observed(envelope): + try: + return await handler(envelope) + except Exception as error: + failures.append(error) + raise + event_type = "SubmissionFinalizationRequested" + delivery = outbox_delivery(h.factory, authorization_factory=outbox_dispatch_authorization, + registry=HandlerRegistry([(event_type, 1, observed)], replay_safe=frozenset({(event_type, 1)})), + options=DeliveryOptions(lease_seconds=60, handler_timeout_seconds=50, + retry_base_seconds=1, retry_cap_seconds=1)) async with h.factory() as session, session.begin(): await session.execute( text("CREATE SEQUENCE public.test_replacement_outbox_attempt") @@ -317,21 +363,32 @@ async def test_late_outbox_insert_failure_rolls_back_and_ready_retry_succeeds( ) try: - with pytest.raises( - OutboxPersistenceError, match="outbox_persistence_failed" - ): - await _create(h, creation) + assert await delivery.deliver(event_id, project_id, "failed-revision-worker") is not None + assert len(failures) == 1 and isinstance(failures[0], OutboxPersistenceError) + assert str(failures[0]) == "outbox_persistence_failed" + # OUTBOX deliberately suppresses provider/database details; the sequence + # below independently proves the real SQL fault executed. + assert failures[0].__cause__ is None async with h.factory() as session: - assert ( - await session.execute( - text( - "SELECT last_value,is_called " - "FROM public.test_replacement_outbox_attempt" - ) - ) - ).one() == (1, True) - assert await _creation_snapshot(h) == before - assert await _admission_status(h, admission_id) == "ready" + assert (await session.execute(text( + "SELECT last_value,is_called FROM public.test_replacement_outbox_attempt" + ))).one() == (1, True) + operation = await session.get(SubmissionIntakeOperation, operation_id) + assert operation.state == "finalization_pending" and operation.acceptance_receipt == receipt + assert operation.finalized_submission_id is None + charge = await session.get(SubmissionSourceCharge, operation_id) + assert charge.state == "sealed" and charge.accounted_bytes > 0 + event = await session.get(OutboxEvent, event_id) + assert event.delivery_state == "retryable" and event.attempt_count == 1 + assert set((await session.execute(select(OutboxEvent.event_id))).scalars()) == event_ids + ready_at = max(event.next_attempt_at, operation.continuation_expires_at) + remaining = (ready_at - await session.scalar(select(func.clock_timestamp()))).total_seconds() + after = await _creation_snapshot(h) + # OUTBOX delivery state and continuation authority legitimately advance; + # product/ART/checker rows, human/binding allows and TASK remain unchanged. + assert after[:8] == before[:8] + assert await artifact_snapshot(h) == artifacts_before + assert after[9] == before[9] finally: async with h.factory() as session, session.begin(): await session.execute( @@ -353,19 +410,23 @@ async def test_late_outbox_insert_failure_rolls_back_and_ready_retry_succeeds( ) ) - created = await _create(h, creation) - assert created.submission_version == 2 - assert created.admission_id == admission_id - assert await _admission_status(h, admission_id) == "consumed" + await asyncio.sleep(max(0, remaining) + 0.05) + assert await delivery.deliver(event_id, project_id, "retry-revision-worker") is not None + assert len(failures) == 1 async with h.factory() as session: - dispatch = await session.get(SubmissionDispatch, str(created.submission_id)) - assert dispatch is not None - assert dispatch.checker_remediation_manifest_id == source_id - assert await session.scalar( - text( - "SELECT public.submission_dispatch_valid(d) " - "FROM public.submission_dispatches d " - "WHERE d.submission_id=:submission_id" - ), - {"submission_id": created.submission_id}, - ) is True + operation = await session.get(SubmissionIntakeOperation, operation_id) + assert operation.state == "finalized" and operation.continuation_generation == 2 + event = await session.get(OutboxEvent, event_id) + assert event.delivery_state == "acknowledged" and event.attempt_count == 2 + dispatch = await session.get(SubmissionDispatch, operation.finalized_submission_id) + assert dispatch.submission_version == 2 and dispatch.checker_remediation_manifest_id == source_id + submission = await session.get(Submission, operation.finalized_submission_id) + assert submission.supersedes_submission_id == str(h.created.submission_id) + admission = await session.get(SubmissionBundleAdmission, operation.finalized_admission_id) + assert admission.status == "consumed" and admission.source_operation_id == operation_id + assert await session.scalar(select(func.count()).select_from(Submission).where( + Submission.task_id == str(h.request.task_id), Submission.version == 2)) == 1 + assert set((await session.execute(select(OutboxEvent.event_id))).scalars()) == event_ids | {UUID(str(dispatch.evaluation_event_id))} + assert await session.scalar(text( + "SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d WHERE d.submission_id=:id" + ), {"id": dispatch.submission_id}) is True From f9d1b2529f6f5b5637695ce3bb877b4e13817609 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 01:47:46 +0100 Subject: [PATCH 199/513] test(tasks): verify current revision admission races and stale cause --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 35 +++ .../test_replacement_creation.py | 248 ++++++++++-------- 2 files changed, 167 insertions(+), 116 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0b6374e72..e2e28a702 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6911,3 +6911,38 @@ repairs; scoped QA/security reports no further finding. Other two tests/helpers in module AST-unchanged and still pending migration. Shared modified-content execution over a091cb7d6 only; no independent or clean-commit rerun claim. Final Ruff/structure/record/whitespace checks passed. Full retirement and goal open. + +Remaining revision admission proof migration scope: port stale-cause and competing +ready-admission tests to current source owners, then remove their obsolete local +preparation/hidden-create helpers/imports. Stale cause: execute genuine eligible +PRE, reserve a newer predecessor evaluation before T4, require refused acceptance +and retained failed-source cleanup custody without new Submission/POST. Competition: +two real commands with distinct keys, observe actual blocked PostgreSQL TASK lock, +hold winner body until loser exits so refusal occurs against receiving custody, +require loser never reads bytes, winner accepted once, finalize via production +OUTBOX and replay same immutable receipt without new product writes. Preserve prior +POST rollback test unchanged and run all three module cases. QA/security review +required; does not claim removal of other modules' obsolete consumers. + +Revision admission v1 terminal0:3passed151.09s/allcleanuptrue. Dependency search +found indirect old-helper consumers in test_alembic, revision_capacity, +revision_exhaustion_recovery, checker_retry_history_replay and related modules. +Restore existing shared helpers/imports unchanged; no compatibility alias or new +old writer. AST comparison confirms all five prior helpers and previous rollback +case unchanged. Those dependents remain explicit retirement work. Scope removes +old-path calls only from this module's two test bodies, not the shared helper API. +QA-REVISION001 requires exact context-invalid refusal and current-checker cause; +QA-REVISION002 adds unchanged OUTBOX rows at the post-PRE/pre-T4 baseline, since +no delivery mutation is legitimate here. Run repaired stale case and collection +of shared consumers; current race/rollback v1 bodies remain unchanged. Existing +Pydantic generation-fixture serialization warning is retained, not suppressed. + +Final stale-cause v2 terminal0:1passed54.72s/schema0084/allcleanuptrue +(/tmp/submission-revision-admission-v2.json/.log). Exact context-invalid and checker +cause plus unchanged OUTBOX snapshot pass, addressing QA-REVISION001/002. Final +blob862eb2621b00a54fe32a07ed96560639406cadcc; race and prior POST rollback ASTs +unchanged from v1 three-pass run. Six shared-helper consumer modules collect +92tests19.12s; collection is not runtime qualification. All five shared helper +ASTs restored unchanged; broader old-path dependencies remain. Ruff/structure/ +record/whitespace checks passed. Evidence is shared execution of modified content +over559617e9f, not clean-commit execution or independent rerun. Full goal open. diff --git a/backend/tests/tasks/submission_dispatch/test_replacement_creation.py b/backend/tests/tasks/submission_dispatch/test_replacement_creation.py index facd01d41..862eb2621 100644 --- a/backend/tests/tasks/submission_dispatch/test_replacement_creation.py +++ b/backend/tests/tasks/submission_dispatch/test_replacement_creation.py @@ -9,7 +9,6 @@ from app.api.deps.authorization import compose_hidden_submission_creation_command from app.core.identifiers import new_record_id from app.modules.artifacts.models import SubmissionBundleAdmission -from app.modules.checkers.models import CheckerRun from app.modules.outbox.api import OutboxPersistenceError from app.modules.outbox.models import OutboxEvent from app.modules.tasks.api import ( @@ -83,6 +82,26 @@ async def _create(h, request, *, context=None, label=None): ).create(request) +def _revision_command(h, root, data): + """Build current foreground owners with exact routed revision acknowledgement.""" + from uuid import UUID + from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata + from tests.artifacts.test_submission_pre_source import _source_runtime + from tests.retained_material_fixtures import _foreground + root.mkdir() + runtime, errors = _source_runtime(data, root, "completed") + command = _foreground(h.factory, h.actor_context, h.namespace, h.store.wrapped, runtime) + metadata = SubmissionIntakeMetadata( + task_id=h.request.task_id, assignment_id=h.request.assignment_id, + predecessor_submission_id=h.created.submission_id, + revision_preparation_id=UUID(str(h.revision_preparation_id)), + revision_preparation_sha256=h.revision_preparation_sha256, + summary=h.creation_request.summary, + contributor_attestation=h.creation_request.contributor_attestation, + ) + return command, metadata, errors + + async def _creation_snapshot(h): """Capture every mutable owner participating in canonical creation.""" async with h.factory() as session: @@ -130,151 +149,148 @@ async def _admission_status(h, admission_id): return admission.status -async def test_stale_routed_cause_denies_before_ready_admission_consumption( - tmp_path, - isolated_database_env, +async def test_stale_routed_cause_denies_acceptance_after_successful_pre( + tmp_path, isolated_database_env, monkeypatch, ): + """A newer predecessor evaluation between PRE and T4 prevents acceptance.""" + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from app.modules.tasks.models import WorkstreamTask + from app.modules.checkers.api.execution import CheckerExecutionUnavailable + from tests.post_submit_materialization_helpers import _submit_current_source + async with remediation_source(tmp_path, isolated_database_env) as h: await _fixture_revision_context(h) - prepared, admission_id = await _ready_replacement(h, revision_archive(h.data)) - creation = _creation_request(h, prepared, admission_id) - - successor = change_request( - h.request, - evaluation_request_id=new_record_id(), - evaluation_generation=h.request.evaluation_generation + 1, - ) - async with h.factory() as session, session.begin(): - reserved = await evaluation_coordinator(session).reserve_current_evaluation(successor) - assert reserved.request_id == successor.evaluation_request_id - assert await _admission_status(h, admission_id) == "ready" - before = await _creation_snapshot(h) - - with pytest.raises(TaskSubmissionContextUnavailable): - await _create(h, creation) - - assert await _creation_snapshot(h) == before - assert await _admission_status(h, admission_id) == "ready" + data = revision_archive(h.data) + command, metadata, errors = _revision_command(h, tmp_path / "stale-runtime", data) + execute = command._execute + observed = [] + async def supersede_after_pre(reservation): + completion = await execute(reservation) + assert completion.terminal.execution.eligible is True + successor = change_request(h.request, evaluation_request_id=new_record_id(), + evaluation_generation=h.request.evaluation_generation + 1) + async with h.factory.begin() as session: + reserved = await evaluation_coordinator(session).reserve_current_evaluation(successor) + assert reserved.request_id == successor.evaluation_request_id + observed.append((reservation, await _creation_snapshot(h))) + return completion + monkeypatch.setattr(command, "_execute", supersede_after_pre) + with pytest.raises(TaskSubmissionContextUnavailable, match="^task_submission_context_invalid$") as denied: + await _submit_current_source(h.factory, h.actor_context, command, metadata, data) + assert isinstance(denied.value.__cause__, CheckerExecutionUnavailable) + assert len(observed) == 1 and not errors, errors + assert (await _creation_snapshot(h))[:9] == observed[0][1][:9] async with h.factory() as session: - assert await session.scalar( - select(func.count()).select_from(Submission).where( - Submission.task_id == str(h.request.task_id), - Submission.version == 2, - ) - ) == 0 + operation = await session.get(SubmissionIntakeOperation, + str(observed[0][0].source.location.operation_id)) + assert operation is not None and operation.state == "failed" + assert operation.acceptance_receipt is None and operation.finalization_event_id is None + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.state == "sealed" and charge.accounted_bytes > 0 + task = await session.get(WorkstreamTask, str(h.request.task_id)) + assert task.status == "needs_revision" and task.active_submission_operation_id is None + assert await session.scalar(select(func.count()).select_from(Submission).where( + Submission.task_id == str(h.request.task_id), Submission.version == 2)) == 0 -async def test_competing_ready_admissions_commit_one_and_winner_replays_exactly( - tmp_path, - isolated_database_env, - monkeypatch, +async def test_competing_revision_intakes_commit_one_and_winner_replays_exactly( + tmp_path, isolated_database_env, monkeypatch, ): + """Real T1 row-lock contention denies the loser before bytes; one winner reaches T5.""" + from contextvars import ContextVar + from types import SimpleNamespace + from uuid import UUID + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from tests.retained_material_fixtures import finalize_retained_intake + async with remediation_source(tmp_path, isolated_database_env) as h: source_id = await _fixture_revision_context(h) - first_prepared, first_admission = await _ready_replacement( - h, revision_archive(h.data) - ) - second_prepared, second_admission = await _ready_replacement( - h, revision_archive(revision_archive(h.data)) - ) - assert first_admission != second_admission - first_request = _creation_request(h, first_prepared, first_admission) - second_request = _creation_request(h, second_prepared, second_admission) - assert await _admission_status(h, first_admission) == "ready" - assert await _admission_status(h, second_admission) == "ready" - - held = asyncio.Event() - release = asyncio.Event() - contender_entered = asyncio.Event() - contender_pid = [] + first_data = revision_archive(h.data) + second_data = revision_archive(first_data) + commands = [_revision_command(h, tmp_path / name, data) for name, data in ( + ("first-runtime", first_data), ("second-runtime", second_data))] + keys = [new_record_id(), new_record_id()] + label = ContextVar("revision_intake_contender", default=None) + held, release, entered, loser_done = (asyncio.Event() for _ in range(4)) + contender_pid, body_reads = [], [] original_get_task = TaskRepository.get_task - async def pause_with_task_lock(repository, *args, **kwargs): - label = repository._session.info.pop( - "replacement_creation_contender", None - ) - if label == "second": - contender_pid.append( - await repository._session.scalar( - text("SELECT pg_catalog.pg_backend_pid()") - ) - ) - contender_entered.set() + selected = label.get() + if selected is not None: + label.set(None) + if selected == 1: + contender_pid.append(await repository._session.scalar(text("SELECT pg_catalog.pg_backend_pid()"))) + entered.set() task = await original_get_task(repository, *args, **kwargs) - if label == "first": + if selected == 0: held.set() - await asyncio.wait_for(release.wait(), 15) + await asyncio.wait_for(release.wait(), 30) return task - + async def body(index): + if index == 0: + await asyncio.wait_for(loser_done.wait(), 30) + body_reads.append(index) + yield first_data if index == 0 else second_data + async def submit(index): + label.set(index) + command, metadata, _ = commands[index] + try: + return await command.submit(metadata, body(index), + actor_id=h.actor_context.actor_profile_id, identity_link_id=h.actor_context.identity_link_id, + idempotency_key=keys[index], declared_raw_bytes=len(first_data if index == 0 else second_data)) + finally: + if index == 1: + loser_done.set() first = second = None with monkeypatch.context() as patch: patch.setattr(TaskRepository, "get_task", pause_with_task_lock) try: - first = asyncio.create_task( - _create(h, first_request, label="first") - ) - await asyncio.wait_for(held.wait(), 15) - second = asyncio.create_task( - _create(h, second_request, label="second") - ) - await asyncio.wait_for(contender_entered.wait(), 15) + first = asyncio.create_task(submit(0)) + await asyncio.wait_for(held.wait(), 30) + second = asyncio.create_task(submit(1)) + await asyncio.wait_for(entered.wait(), 30) async with h.factory() as observer: - async with asyncio.timeout(10): - while not await observer.scalar( - text( - "SELECT cardinality(pg_catalog.pg_blocking_pids(:pid)) > 0" - ), - {"pid": contender_pid[0]}, - ): + async with asyncio.timeout(15): + while not await observer.scalar(text( + "SELECT cardinality(pg_catalog.pg_blocking_pids(:pid)) > 0" + ), {"pid": contender_pid[0]}): await asyncio.sleep(0.02) assert not second.done() release.set() - results = await asyncio.wait_for( - asyncio.gather(first, second, return_exceptions=True), 30 - ) + winner, loser = await asyncio.wait_for( + asyncio.gather(first, second, return_exceptions=True), 90) finally: release.set() + loser_done.set() for pending in (first, second): if pending is not None and not pending.done(): pending.cancel() - await asyncio.gather( - *(pending for pending in (first, second) if pending is not None), - return_exceptions=True, - ) - - winner, loser = results + await asyncio.gather(*(pending for pending in (first, second) if pending is not None), + return_exceptions=True) assert not isinstance(winner, BaseException), winner assert isinstance(loser, TaskSubmissionContextUnavailable), loser - assert winner.admission_id == first_admission - assert await _admission_status(h, first_admission) == "consumed" - assert await _admission_status(h, second_admission) == "ready" - + assert str(loser) == "task_submission_operation_in_progress" + assert body_reads == [0] + assert all(not errors for _, _, errors in commands) + assert winner["status"] == "accepted" and winner["replayed"] is False async with h.factory() as session: - dispatch = await session.get(SubmissionDispatch, str(winner.submission_id)) - run = await session.get(CheckerRun, str(winner.evaluation_attempt_id)) - event = await session.get(OutboxEvent, winner.evaluation_event_id) - assert dispatch is not None - assert dispatch.checker_remediation_manifest_id == source_id - assert dispatch.creation_kind == "checker_remediation" - assert run is not None and run.evaluation_generation == 1 - assert event is not None - assert await session.scalar( - select(func.count()).select_from(Submission).where( - Submission.task_id == str(h.request.task_id), - Submission.version == 2, - ) - ) == 1 - - committed = await _creation_snapshot(h) - fresh_context = h.actor_context.model_copy( - update={ - "request_id": new_record_id(), - "correlation_id": new_record_id(), - } - ) - replay = await _create(h, first_request, context=fresh_context) - assert replay == winner - assert await _creation_snapshot(h) == committed + assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.idempotency_key.in_([str(key) for key in keys]))) == 1 + operation = await session.get(SubmissionIntakeOperation, winner["operation_id"]) + assert operation.idempotency_key == str(keys[0]) and operation.state == "finalization_pending" + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.state == "sealed" and charge.accounted_bytes == len(first_data) + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(winner["operation_id"]), store=h.store.wrapped, + namespace=h.namespace, settings=h.settings)) + async with h.factory() as session: + dispatch = await session.get(SubmissionDispatch, submission_id) + assert dispatch.submission_version == 2 and dispatch.checker_remediation_manifest_id == source_id + assert await session.scalar(select(func.count()).select_from(Submission).where( + Submission.task_id == str(h.request.task_id), Submission.version == 2)) == 1 + before = await _creation_snapshot(h) + assert await submit(0) == dict(winner, replayed=True) + assert await _creation_snapshot(h) == before async def test_late_outbox_insert_failure_rolls_back_and_accepted_retry_succeeds( From 11e7c36c7f62c841b834ac3512a52a29d8f04664 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 01:55:27 +0100 Subject: [PATCH 200/513] test(checkers): replay retry history after accepted revision --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 31 ++++++++++++++ .../test_checker_retry_history_replay.py | 40 +++++++++++-------- 2 files changed, 55 insertions(+), 16 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e2e28a702..d6bac93c0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6946,3 +6946,34 @@ unchanged from v1 three-pass run. Six shared-helper consumer modules collect ASTs restored unchanged; broader old-path dependencies remain. Ruff/structure/ record/whitespace checks passed. Evidence is shared execution of modified content over559617e9f, not clean-commit execution or independent rerun. Full goal open. + +Checker retry history migration scope: replace test_checker_retry_history_replay's +old ready-admission/hidden-create helpers with current source T1/PRE/T4/OUTBOX T5 +for the later revision. Preserve real prior failed execution, authorized retry, +selected checker completion and governed needs_revision cause. Keep exact durable +state snapshot for same-key historical replay and refusal of new-key old-source +retry after a later Submission. Extend provider traps from old open() to current +open_source()/observe_sealed_source() without changing retry production code. +This removes one indirect shared-helper consumer; QA/security review and focused +isolated PostgreSQL test required, not full history/provider qualification. + +History v1 failed43.07s before later-submission creation at unchanged selected +execution request count (0). QA-HISTORY001 diagnosis: delivery_fixture captures its +own ControlledSelectedExecution through configured_post_submit_external_execution; +the test's older lower-factory monkeypatch observes an unused port. Use explicit +returned delivery.selected, assert it was not invoked by the initial missing-source +failure, set its verdict to failed before retry, and retain all actual execution/ +completion/needs_revision assertions. No product runtime or routing policy change. +No downstream history qualification was reached in the failed run. + +History v2 terminal0:1passed44.57s/schema0084/allcleanuptrue +(/tmp/submission-checker-history-current-v2.json/.log). Finalblob +e0c7018e5e77bbc182c42db1b2be9a8c90a714a7. QA-HISTORY001 resolved: actual captured +checker port executes once and produces governed remediation; later accepted +revision finalizes through real OUTBOX/T5 before historical replay assertions. +All22 original Assert ASTs retained; new empty-port/v2 controls added. Same-key +receipt/full retained-state equality and new-key refusal pass with old/current +source-read traps. QA/security inspection has no remaining finding. Existing +Pydantic fixture warning retained. Shared modified-content execution overf9d1b2529, +not independent or clean-commit rerun; no provider/native runtime qualification. +This removes one old shared-helper consumer; full retirement remains open. diff --git a/backend/tests/checkers/execution/test_checker_retry_history_replay.py b/backend/tests/checkers/execution/test_checker_retry_history_replay.py index 8e3320354..e0c7018e5 100644 --- a/backend/tests/checkers/execution/test_checker_retry_history_replay.py +++ b/backend/tests/checkers/execution/test_checker_retry_history_replay.py @@ -11,27 +11,18 @@ from app.modules.tasks.api import TaskSubmissionContextRequest from tests.authorization.post_submit_routing.support import provision_router from tests.checkers.external.support import post_registry_spec -from tests.checkers.execution.support import ControlledSelectedExecution from app.modules.checkers.models import CheckerRun from tests.checkers.execution.test_checker_retry import _command, _failed_source, _operator_for from tests.tasks.evaluation_delivery.support import outcome from tests.tasks.post_submit_routing.outcome_support import invoked_completion from tests.tasks.post_submit_routing.support import revision_archive, source_values -from tests.tasks.submission_dispatch.test_replacement_creation import ( - _create, - _creation_request, - _ready_replacement, -) +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata +from tests.post_submit_materialization_helpers import create_source_submission async def test_retry_replays_after_real_later_submission_without_reopening_old_source( tmp_path, isolated_database_env, monkeypatch, ): - selected_execution = ControlledSelectedExecution(verdict="failed") - monkeypatch.setattr( - "app.adapters.checkers.configured_external_checker_execution", - lambda _settings: selected_execution, - ) async with _failed_source( tmp_path, isolated_database_env, @@ -40,6 +31,10 @@ async def test_retry_replays_after_real_later_submission_without_reopening_old_s ) as (h, delivery): from app.adapters.artifacts.local import LocalStorageAdapter + selected_execution = delivery.selected + assert selected_execution.requests == [] + selected_execution.verdict = "failed" + operator = await _operator_for(h) command = _command(h, operator) async with h.factory.begin() as session: @@ -91,8 +86,19 @@ async def test_retry_replays_after_real_later_submission_without_reopening_old_s assert current.revision_context is not None h.revision_preparation_id = current.revision_context.preparation_id h.revision_preparation_sha256 = current.revision_context.preparation_sha256 - prepared, admission_id = await _ready_replacement(h, revision_archive(h.data)) - later = await _create(h, _creation_request(h, prepared, admission_id)) + metadata = SubmissionIntakeMetadata( + task_id=h.request.task_id, assignment_id=h.request.assignment_id, + predecessor_submission_id=h.created.submission_id, + revision_preparation_id=current.revision_context.preparation_id, + revision_preparation_sha256=current.revision_context.preparation_sha256, + summary=h.creation_request.summary, + contributor_attestation=h.creation_request.contributor_attestation, + ) + later = await create_source_submission( + h.factory, h.actor_context, h.store.wrapped, h.namespace, h.settings, + metadata, revision_archive(h.data), + ) + assert later.submission_version == 2 async def retained_state(): async with h.factory() as session: @@ -129,11 +135,12 @@ async def retained_state(): assert before[-1]["status"] == "evaluation_pending" provider_opens = len(h.store.opens) - def forbidden_open(_store, _reference): + def forbidden_open(*args, **kwargs): pytest.fail("historical retry replay touched artifact bytes") with monkeypatch.context() as patch: - patch.setattr(LocalStorageAdapter, "open", forbidden_open) + for method in ("open", "open_source", "observe_sealed_source"): + patch.setattr(LocalStorageAdapter, method, forbidden_open) async with h.factory.begin() as session: replay = await checker_retry_service(session, operator).retry(command) assert replay == created @@ -145,7 +152,8 @@ def forbidden_open(_store, _reference): "request_id": other_key, "correlation_id": other_key, }) with monkeypatch.context() as patch: - patch.setattr(LocalStorageAdapter, "open", forbidden_open) + for method in ("open", "open_source", "observe_sealed_source"): + patch.setattr(LocalStorageAdapter, method, forbidden_open) # A new key must pass current TASK ownership; the later Submission # makes the old source fail the shared latest-Submission guard. with pytest.raises( From 0c801dc84cf1c97097ca170f786fb9d0e50fd0f8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 02:13:27 +0100 Subject: [PATCH 201/513] test(tasks): prove revision cap through raw ZIP acceptance --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 43 +++++++++ .../test_submission_foreground_command.py | 4 +- .../test_revision_capacity.py | 87 +++++++++++++------ 3 files changed, 105 insertions(+), 29 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d6bac93c0..dee2977d3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -6977,3 +6977,46 @@ source-read traps. QA/security inspection has no remaining finding. Existing Pydantic fixture warning retained. Shared modified-content execution overf9d1b2529, not independent or clean-commit rerun; no provider/native runtime qualification. This removes one old shared-helper consumer; full retirement remains open. + +Two-revision public cap proof scope: migrate test_two_revisions_then_public_and_sql_refusal +in test_revision_capacity.py from old preparation+JSON admission to raw ZIP202 +acceptance and real finalization OUTBOX. Retain two governed checker failure rounds, +unchanged policy window duration, terminal exhaustion, historical accepted replay, +and rawSQL excess/invalid-version refusal with exact lineage. Configure the existing +controlled PRE transport on the already-claimed16MiB test namespace. Require one +PRE per accepted revision, exact source-backed finalized dispatch, and no additional +intake on exhausted-assignment refusal. Other capacity tests/shared helpers remain +unchanged and unqualified by this run. QA/security review and targeted PG/public +journey required; no real guest/provider or final specification qualification claim. + +Public cap v1 failed105.62s during the rawZIP revision loop with response500 +(sanitized middleware), before cap refusal assertions. Teardown also logged an async connection +cross-loop close error; do not assume it is the request's cause. Use an untracked +test-only diagnostic plugin to rethrow the active sanitized middleware exception; +no production disclosure change or qualification from that diagnostic run. +Structural validator also found test function130lines vs120limit. Extract exact +raw-ZIP header construction into a cohesive local helper; leave policy/ledger +unchanged and rerun validator. Both are open until discriminating evidence arrives. + +Diagnostic v2 failed94.49s: actual request cause is FileExistsError for pre-tree. +Repeated configure_source_http calls share its test-runtime scratch root; second +PRE collides even though durable namespace should remain identical. Expand bounded +scope to that helper: allocate unique runtime-only scratch subdirectory per +configuration while _settings(tmp_path) retains the same durable namespace/profile. +No product storage/configuration change. Prior first-revision attribution corrected; +teardown loop-close logs are not this cause. Remove redundant saved-header/response +initialization (the fixed two-round loop assigns both) to stay within120lines. +Run normal cap journey and existing one-revision public control without diagnostic +plugin; rerun structural validator with no policy/ledger relaxation. + +Normal cap/control v3 terminal0:2passed128.15s/schema0084/allcleanuptrue +(/tmp/submission-public-revision-cap-v3.json/.log), without diagnostic plugin. +Two accepted source revisions finalize, exact window/terminal exhaustion and +fresh-intake refusal/historical replay pass, with unchanged SQL excess/invalid +version attacks. Existing one-revision public control also passes after runtime +scratch isolation. Structural validator now passes with policy/ledger unchanged; +Ruff/record/whitespace pass. Final blobs: capacity114921339529fe0d5542d4b37f5148faa9fb828e, +foreground96751781c3aeffb398b4bdf677539ba0101835e8. Scoped QA/security reports no +remaining actionable finding. Shared modified-content execution over11e7c36c7, +not independent or clean-commit rerun. Other capacity cases and full old-producer/ +provider/specification qualification remain open; same single draft PR708. diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py index 9644776e4..96751781c 100644 --- a/backend/tests/artifacts/test_submission_foreground_command.py +++ b/backend/tests/artifacts/test_submission_foreground_command.py @@ -25,7 +25,9 @@ async def configure_source_http(factory, client, tmp_path, monkeypatch, payload, from tests.checkers.execution.support import provision_post_submit_service from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation from tests.test_artifact_admission import _settings - runtime, errors = _source_runtime(payload, tmp_path, outcome, project_findings=project_findings) + runtime_root = tmp_path / f"source-http-{new_record_id()}" + runtime_root.mkdir() + runtime, errors = _source_runtime(payload, runtime_root, outcome, project_findings=project_findings) calls, original = [], runtime.execute_pre async def execute(lease, grant): calls.append(lease.reservation.attempt_id) diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index 92e54588d..114921339 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -86,11 +86,29 @@ async def _fail_current_submission(h, *, findings=None, route=True, terminal=Fal await _fixture_revision_context(h) +def _revision_upload_headers(h): + """Build the current raw-ZIP command with its exact revision acknowledgement.""" + return { + "Content-Type": "application/zip", + "X-Task-Assignment-Id": str(h.request.assignment_id), + "Idempotency-Key": str(new_record_id()), + "X-Predecessor-Submission-Id": str(h.created.submission_id), + "X-Revision-Preparation-Id": str(h.revision_preparation_id), + "X-Revision-Preparation-Sha256": h.revision_preparation_sha256, + "X-Submission-Summary": h.creation_request.summary, + "X-Contributor-Attestation": h.creation_request.contributor_attestation, + } + + async def test_two_revisions_then_public_and_sql_refusal( tmp_path, isolated_database_env, monkeypatch, ): """Initial0 and revisions1/2 commit; the final failure closes without a window.""" - from app.modules.tasks.schemas import AdmissionBackedSubmissionResponse + from types import SimpleNamespace + from app.modules.tasks.models import SubmissionDispatch + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.retained_material_fixtures import finalize_retained_intake from app.modules.tasks.revision.models import TaskRevisionPreparation async with remediation_source(tmp_path, isolated_database_env) as h: @@ -105,19 +123,35 @@ async def test_two_revisions_then_public_and_sql_refusal( "WHERE t.id=:id" ), {"id": h.request.task_id}) == 2 initial_id = h.created.submission_id - saved_payload = None + all_calls = [] async with _client(h, monkeypatch, isolated_database_env) as client: route = f"/api/v1/tasks/{h.request.task_id}/submissions" for round_number in (1, 2): h.data = revision_archive(h.data) - prepared, admission = await _ready_replacement(h, h.data) - payload = _payload(prepared, admission) - response = await client.post(route, json=payload) - assert response.status_code == 201, response.text - assert response.json()["submission_version"] == round_number + 1 - h.created = AdmissionBackedSubmissionResponse.model_validate(response.json()) - saved_payload = payload - saved_response = response.json() + client, settings, errors, calls = await configure_source_http( + h.factory, client, tmp_path, monkeypatch, h.data, "completed") + settings = settings.model_copy(update={"submission_execution_profile": { + **settings.submission_execution_profile, + "capacity": {"maximum_total_bytes": 16 * 1024**2}, + }}) + monkeypatch.setattr(client._transport.app.state, "settings", settings) + headers = _revision_upload_headers(h) + response = await client.post(route, headers=headers, content=h.data) + assert response.status_code == 202, response.text + accepted = response.json() + assert accepted["status"] == "accepted" and accepted["replayed"] is False + assert len(calls) == 1 and not errors, errors + all_calls.append(calls) + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(accepted["operation_id"]), store=h.store.wrapped, + namespace=h.namespace, settings=settings)) + async with h.factory() as session: + dispatch = await session.get(SubmissionDispatch, submission_id) + h.created = dispatch.result() + assert h.created.submission_version == round_number + 1 + operation = await session.get(SubmissionIntakeOperation, accepted["operation_id"]) + assert operation.finalized_submission_id == str(h.created.submission_id) + saved_headers, saved_response = headers, accepted outcome = await _fail_current_submission(h, terminal=round_number == 2) async with h.factory() as session: if round_number == 1: @@ -135,25 +169,22 @@ async def test_two_revisions_then_public_and_sql_refusal( before = await _creation_snapshot(h) # The exhausted assignment cannot submit a new ZIP, including with # its preceding preparation acknowledgement. No pending window exists. - denied = await client.post( - f"/api/v1/tasks/{h.request.task_id}/submission-bundle-preparations", - headers={ - "Content-Type": "application/zip", - "X-Task-Assignment-Id": str(h.request.assignment_id), - "X-Predecessor-Submission-Id": str(h.created.submission_id), - "Idempotency-Key": str(new_record_id()), - "X-Revision-Preparation-Id": str(h.revision_preparation_id), - "X-Revision-Preparation-Sha256": h.revision_preparation_sha256, - }, content=b"not a zip", - ) - assert denied.status_code == 409, denied.text - assert denied.json()["error"]["code"] == "conflict" - assert denied.json()["error"]["message"] == "Request conflict" - assert denied.json()["detail"] == "submission_bundle_preparation_context_changed" + async with h.factory() as session: + intake_ids = set(await session.scalars(select(SubmissionIntakeOperation.id))) + assert len(intake_ids) == 3 + denied = await client.post(route, headers=saved_headers | { + "Idempotency-Key": str(new_record_id()), + "X-Predecessor-Submission-Id": str(h.created.submission_id), + }, content=b"not a zip") + assert denied.status_code == 404, denied.text + assert denied.json()["error"]["code"] == "submission_unavailable" assert await _creation_snapshot(h) == before - replay = await client.post(route, json=saved_payload) - assert replay.status_code == 201, replay.text - assert replay.json() == saved_response + async with h.factory() as session: + assert set(await session.scalars(select(SubmissionIntakeOperation.id))) == intake_ids + replay = await client.post(route, headers=saved_headers, content=h.data) + assert replay.status_code == 202, replay.text + assert replay.json() == dict(saved_response, replayed=True) + assert all(len(calls) == 1 for calls in all_calls) async with h.factory() as session: original = await session.scalar(text( From 25fb117f951975c87ad896a95b24bee96de598d0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 02:23:37 +0100 Subject: [PATCH 202/513] test(tasks): verify zero-cap coverage and accepted policy rebase --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 22 ++++ .../test_revision_capacity.py | 113 +++++++++++------- 2 files changed, 91 insertions(+), 44 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index dee2977d3..744fc595b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7020,3 +7020,25 @@ foreground96751781c3aeffb398b4bdf677539ba0101835e8. Scoped QA/security reports n remaining actionable finding. Shared modified-content execution over11e7c36c7, not independent or clean-commit rerun. Other capacity cases and full old-producer/ provider/specification qualification remain open; same single draft PR708. + +Zero-cap and rebase public proof scope: migrate coverage-return and policy-rebase +cases in test_revision_capacity.py to rawZIP202 acceptance/OUTBOX T5. Preserve +zero-round coverage semantics, actual terminal exhaustion/status timestamps and +backfill parity. Rebase must replay original accepted source using its persisted +key/metadata despite new guide, reject wrong acknowledgement before PRE, finalize +one v2 under exact acknowledgement, and preserve old Submission/checker evidence +and preparation immutability. Extract shared test runtime/profile composition for +these and existing two-revision cap case; preserve16MiB already-claimed namespace. +Run all three public journeys. Other capacity/recovery helpers remain unchanged; +QA/security review required, no provider or full specification claim. + +Zero-cap/rebase/cap control v1 terminal0:3passed171.12s/schema0084/allcleanuptrue +(/tmp/submission-zero-cap-rebase-v1.json/.log). Frozenblob +7e89f998d9d4b3553ce0b643275142087913faaa. Zero-cap coverage preserves round0 and +exact terminal status/time/backfill semantics; rebase replays initial accepted +source without PRE, refuses wrong acknowledgement before PRE, then finalizes v2 +without changing original Submission/checker custody. Existing two-round cap +control passes after shared runtime extraction. Ruff/structure/record/whitespace +pass. Scoped QA/security inspection found no actionable gap. Shared modified +content over0c801dc84, not independent or clean-commit rerun. Remaining capacity/ +recovery consumers, producer retirement and full specification qualification open. diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index 114921339..7e89f998d 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -100,6 +100,19 @@ def _revision_upload_headers(h): } +async def _revision_http_runtime(h, client, tmp_path, monkeypatch, data): + """Use controlled PRE with the already claimed source namespace capacity.""" + from tests.artifacts.test_submission_foreground_command import configure_source_http + _, settings, errors, calls = await configure_source_http( + h.factory, client, tmp_path, monkeypatch, data, "completed") + settings = settings.model_copy(update={"submission_execution_profile": { + **settings.submission_execution_profile, + "capacity": {"maximum_total_bytes": 16 * 1024**2}, + }}) + monkeypatch.setattr(client._transport.app.state, "settings", settings) + return settings, errors, calls + + async def test_two_revisions_then_public_and_sql_refusal( tmp_path, isolated_database_env, monkeypatch, ): @@ -107,7 +120,6 @@ async def test_two_revisions_then_public_and_sql_refusal( from types import SimpleNamespace from app.modules.tasks.models import SubmissionDispatch from app.modules.artifacts.intake.models import SubmissionIntakeOperation - from tests.artifacts.test_submission_foreground_command import configure_source_http from tests.retained_material_fixtures import finalize_retained_intake from app.modules.tasks.revision.models import TaskRevisionPreparation @@ -128,13 +140,8 @@ async def test_two_revisions_then_public_and_sql_refusal( route = f"/api/v1/tasks/{h.request.task_id}/submissions" for round_number in (1, 2): h.data = revision_archive(h.data) - client, settings, errors, calls = await configure_source_http( - h.factory, client, tmp_path, monkeypatch, h.data, "completed") - settings = settings.model_copy(update={"submission_execution_profile": { - **settings.submission_execution_profile, - "capacity": {"maximum_total_bytes": 16 * 1024**2}, - }}) - monkeypatch.setattr(client._transport.app.state, "settings", settings) + settings, errors, calls = await _revision_http_runtime( + h, client, tmp_path, monkeypatch, h.data) headers = _revision_upload_headers(h) response = await client.post(route, headers=headers, content=h.data) assert response.status_code == 202, response.text @@ -231,7 +238,9 @@ async def test_coverage_return_spends_no_round_under_a_zero_revision_policy( its genuine failure exhausts the assignment immediately. Counting the coverage return would make v2 a round beyond the policy instead. """ - from app.modules.tasks.schemas import AdmissionBackedSubmissionResponse + from types import SimpleNamespace + from app.modules.tasks.models import SubmissionDispatch + from tests.retained_material_fixtures import finalize_retained_intake from app.modules.tasks.revision.models import TaskRevisionPreparation from tests.tasks.submission_dispatch.test_revision_exhaustion import terminal_facts @@ -247,12 +256,19 @@ async def test_coverage_return_spends_no_round_under_a_zero_revision_policy( route = f"/api/v1/tasks/{h.request.task_id}/submissions" async with _client(h, monkeypatch, isolated_database_env) as client: h.data = revision_archive(h.data) - prepared, admission = await _ready_replacement(h, h.data) - payload = _payload(prepared, admission) - response = await client.post(route, json=payload) - assert response.status_code == 201, response.text - assert response.json()["submission_version"] == 2 - h.created = AdmissionBackedSubmissionResponse.model_validate(response.json()) + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, h.data) + headers = _revision_upload_headers(h) + response = await client.post(route, headers=headers, content=h.data) + assert response.status_code == 202, response.text + accepted = response.json() + assert accepted["status"] == "accepted" and accepted["replayed"] is False + assert len(calls) == 1 and not errors, errors + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(accepted["operation_id"]), store=h.store.wrapped, + namespace=h.namespace, settings=settings)) + async with h.factory() as session: + h.created = (await session.get(SubmissionDispatch, submission_id)).result() + assert h.created.submission_version == 2 outcome = await _fail_current_submission(h, terminal=True) receipt = await terminal_facts(h, outcome, expected_round=0) async with h.factory() as session: @@ -265,9 +281,10 @@ async def test_coverage_return_spends_no_round_under_a_zero_revision_policy( ["checker_coverage_incomplete", "revision_limit_reached"], [first.requested_at, receipt.exhausted_at], ) - replay = await client.post(route, json=payload) - assert replay.status_code == 201, replay.text - assert replay.json() == response.json() + replay = await client.post(route, headers=headers, content=h.data) + assert replay.status_code == 202, replay.text + assert replay.json() == dict(accepted, replayed=True) + assert len(calls) == 1 await assert_backfill_matches_live(h.factory) @@ -334,7 +351,10 @@ async def test_rebase_keeps_history_and_requires_exact_acknowledgement( tmp_path, isolated_database_env, monkeypatch, ): """A real v2 activation rebases only the next attempt and preserves v1 evidence.""" - from app.modules.tasks.models import WorkstreamTask, TaskAssignment + from types import SimpleNamespace + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from app.modules.tasks.models import WorkstreamTask, TaskAssignment, SubmissionDispatch + from tests.retained_material_fixtures import finalize_retained_intake from app.modules.tasks.revision.models import TaskRevisionPreparation from tests.tasks.post_submit_routing.support import activate_successor_guide @@ -373,34 +393,39 @@ async def test_rebase_keeps_history_and_requires_exact_acknowledgement( assert view["preparation_id"] == str(h.revision_preparation_id) assert view["outcome"] == "rebased" and view["disposition"] == "ready" assert "contribution" in {change["component"] for change in view["changes"]} - replayed_initial = await client.post( - f"/api/v1/tasks/{h.request.task_id}/submissions", - json=_payload(h.creation_request, h.creation_request.admission_id), - ) - assert replayed_initial.status_code == 201, replayed_initial.text - assert replayed_initial.json()["submission_id"] == str(h.created.submission_id) - assert replayed_initial.json()["submission_version"] == 1 + data = revision_archive(h.data) + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + route = f"/api/v1/tasks/{h.request.task_id}/submissions" + async with h.factory() as session: + initial = await session.scalar(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.finalized_submission_id == str(h.created.submission_id))) + replayed_initial = await client.post(route, headers={ + "Content-Type": "application/zip", "Idempotency-Key": initial.idempotency_key, + "X-Task-Assignment-Id": initial.assignment_id, + "X-Submission-Summary": initial.command_metadata["summary"], + "X-Contributor-Attestation": initial.command_metadata["contributor_attestation"], + }, content=h.data) + assert replayed_initial.status_code == 202, replayed_initial.text + assert replayed_initial.json() == dict(initial.acceptance_receipt, replayed=True) + assert calls == [] before = await _creation_snapshot(h) - refused = await client.post( - f"/api/v1/tasks/{h.request.task_id}/submission-bundle-preparations", - headers={ - "Content-Type": "application/zip", - "X-Task-Assignment-Id": str(h.request.assignment_id), - "X-Predecessor-Submission-Id": str(h.created.submission_id), - "X-Revision-Preparation-Id": str(new_record_id()), - "X-Revision-Preparation-Sha256": h.revision_preparation_sha256, - "Idempotency-Key": str(new_record_id()), - }, content=b"not a zip", - ) + headers = _revision_upload_headers(h) + refused = await client.post(route, headers=headers | { + "X-Revision-Preparation-Id": str(new_record_id()), + }, content=b"not a zip") assert refused.status_code == 409, refused.text assert refused.json()["error"]["code"] == "revision_context_changed" - assert await _creation_snapshot(h) == before - prepared, admission = await _ready_replacement(h, revision_archive(h.data)) - created = await client.post( - f"/api/v1/tasks/{h.request.task_id}/submissions", json=_payload(prepared, admission), - ) - assert created.status_code == 201, created.text - assert created.json()["submission_version"] == 2 + assert await _creation_snapshot(h) == before and calls == [] + created = await client.post(route, headers=headers, content=data) + assert created.status_code == 202, created.text + assert len(calls) == 1 and not errors, errors + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(created.json()["operation_id"]), store=h.store.wrapped, + namespace=h.namespace, settings=settings)) + async with h.factory() as session: + dispatch = await session.get(SubmissionDispatch, submission_id) + assert dispatch.submission_version == 2 + assert dispatch.checker_remediation_manifest_id == source_id async with h.factory() as session: assert await session.scalar(text( "SELECT to_jsonb(s)-ARRAY['attempt_status','status_reason','decided_at','updated_at'] FROM public.submissions s WHERE id=:id" From e2ee4ada1cd65dec7354a10a977bcd733a1a99a7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 02:28:11 +0100 Subject: [PATCH 203/513] test(tasks): verify source submission after assignment expiry --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 27 ++++++++++ .../test_revision_capacity.py | 54 +++++++++---------- 2 files changed, 52 insertions(+), 29 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 744fc595b..636310018 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7042,3 +7042,30 @@ control passes after shared runtime extraction. Ruff/structure/record/whitespace pass. Scoped QA/security inspection found no actionable gap. Shared modified content over0c801dc84, not independent or clean-commit rerun. Remaining capacity/ recovery consumers, producer retirement and full specification qualification open. + +Reclaimed-assignment public source scope: migrate only + test_expiry_allows_new_assignment_initial_at_next_global_version in +backend/tests/tasks/submission_dispatch/test_revision_capacity.py from obsolete +prepared admission/JSON creation to raw ZIP acceptance and real OUTBOX T5. +Preserve genuine expiry delivery with lost ACK, public reclaim, global version2 +with no predecessor, new assignment round1 policy window and old-event replay +isolation. Require exact accepted replay and one PRE. Existing retained-expiry +fixture stays unchanged; this is not historical migration qualification. +Allowed files are this record and that test module; no production/SQL policy, +shared expiry helper or historical fixture changes. Lifecycle proof risk requires +QA/test-delta/security review. Verify the isolated PG journey, cleanup, Ruff, +structural/record/whitespace gates. Human review focus: assignment lineage and +old-expiry replay cannot affect the new assignment or reset its window. + +Reclaim source v1 terminal0:1passed78.24s/schema0084/allcleanuptrue +(/tmp/submission-reclaim-source-v1.json/.log). First launch from repository root +failed module discovery before executing tests; corrected backend launch above. +Finalblob e316d39842e02fa76053667e5f8406ffa077eade. Exact accepted replay performs +no second PRE; real finalization creates globalv2/newassignment/no predecessor. +Actual checker failure opens fresh round1; recovered old lost-ACK expiry leaves +new window, task, assignment and expiration count unchanged. Ruff/structure/ +record/whitespace pass; scoped QA/security inspection found no actionable gap. +Evidence is shared modified-content execution over25fb117f9, not independent or +clean-commit rerun. Existing synthetic retained-expiry setup is unchanged and +not historical migration proof. Fetched main has0 missing commits. Old producer +retirement, deployment/provider qualification and full specification remain open. diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index 7e89f998d..e316d3984 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -655,13 +655,11 @@ async def test_expiry_allows_new_assignment_initial_at_next_global_version( tmp_path, isolated_database_env, monkeypatch, ): """The same eligible contributor can claim again with a fresh round zero.""" - from app.modules.artifacts.api import SubmissionBundlePreparationRequest - from app.modules.authorization.api import ActorIdentityFacts, ActorKind + from types import SimpleNamespace + from app.modules.tasks.models import SubmissionDispatch from app.modules.tasks.revision.models import TaskRevisionPreparation - from app.modules.tasks.schemas import AdmissionBackedSubmissionResponse - from tests.archive_fixtures import byte_source + from tests.retained_material_fixtures import finalize_retained_intake from tests.tasks.submission_dispatch.test_revision_expiry import expire_retained_revision - from tests.tasks.submission_lineage_support import _verified_admission async with remediation_source(tmp_path, isolated_database_env) as h: old_submission_id = h.created.submission_id @@ -687,29 +685,25 @@ async def test_expiry_allows_new_assignment_initial_at_next_global_version( assert new_assignment_id != old_assignment_id assert claim.json()["task"]["status"] == "in_progress" - preparation = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - h.actor_context.actor_profile_id, - h.actor_context.identity_link_id, - ActorKind.HUMAN, - ), - request_id=new_record_id(), correlation_id=new_record_id(), - task_id=h.request.task_id, assignment_id=new_assignment_id, - predecessor_submission_id=None, idempotency_key=new_record_id(), - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, - media_type="application/zip", byte_source=byte_source(h.data), - ) - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, - h.actor_context, preparation, - ) + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, h.data) + headers = { + "Content-Type": "application/zip", + "Idempotency-Key": str(new_record_id()), + "X-Task-Assignment-Id": str(new_assignment_id), + "X-Submission-Summary": h.creation_request.summary, + "X-Contributor-Attestation": h.creation_request.contributor_attestation, + } route = f"/api/v1/tasks/{h.request.task_id}/submissions" - created = await client.post(route, json=_payload(preparation, admission_id)) - assert created.status_code == 201, created.text - assert created.json()["submission_version"] == 2 - replay = await client.post(route, json=_payload(preparation, admission_id)) - assert replay.status_code == 201 and replay.json() == created.json() + created = await client.post(route, headers=headers, content=h.data) + assert created.status_code == 202, created.text + assert len(calls) == 1 and not errors, errors + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(created.json()["operation_id"]), store=h.store.wrapped, + namespace=h.namespace, settings=settings)) + replay = await client.post(route, headers=headers, content=h.data) + assert replay.status_code == 202, replay.text + assert replay.json() == dict(created.json(), replayed=True) + assert len(calls) == 1 async with h.factory() as session: submissions = (await session.scalars(select(Submission).where( @@ -721,13 +715,15 @@ async def test_expiry_allows_new_assignment_initial_at_next_global_version( (2, str(new_assignment_id), None), ] assert submissions[0].id == str(old_submission_id) - assert submissions[1].id == created.json()["submission_id"] + assert submissions[1].id == str(submission_id) assert await session.scalar(text( "SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d " "WHERE d.submission_id=:id" ), {"id": submissions[1].id}) is True - h.created = AdmissionBackedSubmissionResponse.model_validate(created.json()) + async with h.factory() as session: + h.created = (await session.get(SubmissionDispatch, submission_id)).result() + assert h.created.submission_version == 2 await _fail_current_submission(h) async with h.factory() as session: fresh = await session.get(TaskRevisionPreparation, h.revision_preparation_id) From 40baa0f15037746ded6815878218e90920be7aa3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 17 Nov 2026 02:33:48 +0100 Subject: [PATCH 204/513] test(tasks): verify source submission after PM revision repair --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 +++++++++++++++++++ .../test_revision_capacity.py | 24 +++++++++++++++---- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 636310018..9516cd0c5 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7069,3 +7069,27 @@ Evidence is shared modified-content execution over25fb117f9, not independent or clean-commit rerun. Existing synthetic retained-expiry setup is unchanged and not historical migration proof. Fetched main has0 missing commits. Old producer retirement, deployment/provider qualification and full specification remain open. + +PM recovered-revision source scope: migrate only + test_pm_recovers_retained_source_and_repairs_without_resetting_window in +backend/tests/tasks/submission_dispatch/test_revision_capacity.py to raw ZIP202 +and real OUTBOX T5; remove now-unused old preparation/payload imports from this +module. Preserve root PM recovery/replay, child rebase/exact parent/stale refusal, +original deadline/limit, post-finalization blocked replay and immutable parent +lineage. Require exact source manifest/v2 and one PRE. Allowed files: this record +and test module. No production, shared helper, historical fixture, policy or +SQL guard changes. Existing synthetic retained setup does not qualify historical +migration. QA/test-delta/security review and isolated changed journey plus PM +superseded-source negative control; Ruff/structure/record/diff gates required. +Human focus: recovered permission must not reset policy windows or old evidence. + +PM source v1 terminal0:2passed151.59s/schema0084/allcleanuptrue +(/tmp/submission-pm-source-v1.json/.log). Frozenblob +716aa0b9c5c610cbb550479a522f706d96ade335. Recovery/rebase retains original +window, exact source and parent lineage through real T5; superseded-source +negative control passes. Existing Pydantic fixture serialization warning remains. +Ruff/structure/record/whitespace pass; scoped reviewer inspection no actionable +finding. Shared modified-content execution overe2ee4ada1, not independent or +clean-commit rerun. Synthetic retained setup unchanged, no historical migration +qualification. One old preparation endpoint test remains in this module; full +producer retirement/provider/specification readiness remain open. diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index e316d3984..716aa0b9c 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -19,9 +19,9 @@ from tests.tasks.post_submit_routing.remediation_support import remediation_source from tests.tasks.post_submit_routing.support import revision_archive from tests.tasks.submission_dispatch.test_replacement_creation import ( - _creation_snapshot, _ready_replacement, + _creation_snapshot, ) -from tests.tasks.test_public_submission_intake import _client, _payload +from tests.tasks.test_public_submission_intake import _client from tests.test_submission_predecessor_custody import _fixture_revision_context @@ -449,6 +449,9 @@ async def test_pm_recovers_retained_source_and_repairs_without_resetting_window( tmp_path, isolated_database_env, monkeypatch, ): """Explicit PM recovery and later rebase keep the original failure's window.""" + from types import SimpleNamespace + from app.modules.tasks.models import SubmissionDispatch + from tests.retained_material_fixtures import finalize_retained_intake from app.modules.tasks.revision.models import TaskRevisionPreparation from tests.tasks.post_submit_routing.support import activate_successor_guide @@ -495,9 +498,20 @@ async def test_pm_recovers_retained_source_and_repairs_without_resetting_window( assert stale.status_code == 409, stale.text h.revision_preparation_id = UUID(child["preparation_id"]) h.revision_preparation_sha256 = child["preparation_sha256"] - prepared, admission = await _ready_replacement(h, revision_archive(h.data)) - created = await client.post(f"/api/v1/tasks/{h.request.task_id}/submissions", json=_payload(prepared, admission)) - assert created.status_code == 201, created.text + data = revision_archive(h.data) + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + created = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=_revision_upload_headers(h), content=data) + assert created.status_code == 202, created.text + assert len(calls) == 1 and not errors, errors + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(created.json()["operation_id"]), store=h.store.wrapped, + namespace=h.namespace, settings=settings)) + async with h.factory() as session: + dispatch = await session.get(SubmissionDispatch, submission_id) + assert dispatch.submission_version == 2 + assert dispatch.checker_remediation_manifest_id == source_id replay = await client.post(route, json=child_payload, headers={"Idempotency-Key": child_key}) assert replay.status_code == 200, replay.text assert replay.json()["preparation_id"] == child["preparation_id"] From 03594094d525af56ee786e56bff4c052b6793b13 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 10:37:56 +0100 Subject: [PATCH 205/513] test(tasks): verify expired revision refusal through source intake --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 23 +++++++++++++++++++ .../test_revision_capacity.py | 6 ++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 9516cd0c5..a283625d3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7093,3 +7093,26 @@ finding. Shared modified-content execution overe2ee4ada1, not independent or clean-commit rerun. Synthetic retained setup unchanged, no historical migration qualification. One old preparation endpoint test remains in this module; full producer retirement/provider/specification readiness remain open. + +Expired-window public refusal scope: replace the last obsolete preparation +endpoint in test_revision_capacity.py with current raw ZIP submission. Preserve +PM blocked recovery/replay, exact original anchor/deadline, exact409 expiry code, +unchanged creation snapshot and needs_revision state. Configure controlled PRE +and assert no invocation; malformed body ensures expiry precedes ZIP validation. +Allowed files: this record and that test module. No production, historical +fixture or SQL guard edits. Existing synthetic retained setup remains limited to +runtime recovery, not historical migration proof. Lifecycle/authority test risk +requires QA/test-delta/security inspection; run changed test plus live two-round +cap control, Ruff/structure/record/diff gates. Human focus: timely refusal before +PRE without extending the original revision window or creating product facts. + +Expired-window v1 terminal0:2passed191.42s/schema0084/allcleanuptrue +(/tmp/submission-expired-window-v1.json/.log). Frozenblob +7f7f4a94eda3e20918bc035104c8b1f15ef3f4ae reverified unchanged after user pause. +Exact409 revision_deadline_expired precedes malformed ZIP validation with no PRE; +all10 prior assertions retained. Two-round public cap control also passes. +Ruff/structural/record/whitespace checks passed before pause. Shared modified +content execution over40baa0f15, not independent or clean-commit rerun. Existing +synthetic retained setup does not qualify historical migrations. This removes +last obsolete preparation endpoint from capacity module; expiry-race consumers, +production retirement and full goal qualification remain open. diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index 716aa0b9c..7f7f4a94e 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -602,11 +602,14 @@ async def test_expired_retained_failure_recovers_without_a_new_window( assert (row.requested_at, row.deadline_at) == (anchor, deadline) replay = await client.post(route, json=payload, headers=headers) assert replay.status_code == 200 and replay.json() == receipt + _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, h.data) before = await _creation_snapshot(h) denied = await client.post( - f"/api/v1/tasks/{h.request.task_id}/submission-bundle-preparations", + f"/api/v1/tasks/{h.request.task_id}/submissions", headers={ "Content-Type": "application/zip", + "X-Submission-Summary": h.creation_request.summary, + "X-Contributor-Attestation": h.creation_request.contributor_attestation, "X-Task-Assignment-Id": str(h.request.assignment_id), "X-Predecessor-Submission-Id": str(h.created.submission_id), "Idempotency-Key": str(new_record_id()), @@ -617,6 +620,7 @@ async def test_expired_retained_failure_recovers_without_a_new_window( assert denied.status_code == 409, denied.text assert denied.json()["error"]["code"] == "revision_deadline_expired" assert await _creation_snapshot(h) == before + assert calls == [] and not errors, errors async with h.factory() as session: assert await session.scalar(text("SELECT status FROM public.workstream_tasks WHERE id=:id"), {"id": h.request.task_id}) == "needs_revision" From f33a8440a26c3df29574ef3e9be4ba805ef4253b Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 10:38:35 +0100 Subject: [PATCH 206/513] docs(submission): scope current main integration --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a283625d3..3b527a239 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7116,3 +7116,17 @@ content execution over40baa0f15, not independent or clean-commit rerun. Existing synthetic retained setup does not qualify historical migrations. This removes last obsolete preparation endpoint from capacity module; expiry-race consumers, production retirement and full goal qualification remain open. + +Current-main integration scope: integrate origin/main a2154e8a4 (33 commits since +previous base) into the same submission branch/PR. Preserve main's Keycloak/native +login and shared external-services package relocation together with branch source +custody/PRE contracts and submission tests. Merge preview identifies9conflicts in +behavior ownership inventory/tests, MCP workflow/hosted tests, PRE interfaces/ +model adapter/selected execution, retained fixtures and trusted-intake tests. +Allowed: merge incoming main changes and resolve overlapping files, regenerate +owned inventory only through canonical tooling where necessary; this record. +Prohibited: removing security checks, restoring obsolete PRE paths, losing source +expiry/receipt fields or weakening CI to make merge pass. Review architecture, +QA/security and CI affected intersections; verify syntax/imports, ownership/gates, +focused merged contract tests then current submission public regression. Human +review focus: preserve both current authentication and exact source execution. From a420f3e3c96e1a4d96270e76af26114de79410ce Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 11:25:45 +0100 Subject: [PATCH 207/513] test(tasks): preserve accepted coverage revision across deadline --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 44 +++++++++++++++++++ .../checkers/execution/completion_fixture.py | 4 +- .../test_revision_expiry.py | 28 +++++++++--- 3 files changed, 68 insertions(+), 8 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 78bfda384..cb0538256 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7154,3 +7154,47 @@ without restart: no PG lock blockers, two finalized operations then third PRE confirmed forward progress. Required scoped architecture/security/CI reviews found no actionable issue. Ruff/record/whitespace pass. Full CI, hosted container/native provider qualification and remaining spec scenarios are still open. + +Late coverage/accepted deadline scope: migrate + test_late_coverage_return_inherits_the_expired_window_and_expires_once in +backend/tests/tasks/submission_dispatch/test_revision_expiry.py to raw ZIP T4 and +real OUTBOX T5. Wait across the actual original PG deadline after acceptance and +before finalization to verify accepted custody survives it. Preserve zero-round +coverage semantics, inherited anchor/deadline, stale first expiry no-effect and +exact single second-source expiration/statuses/taskrelease. Add accepted-before/ +finalized-after deadline assertions and one PRE. Allowed files are that test and +this record; no product/SQL/shared helper changes or historical qualification. +Use existing controlled runtime and source finalizer, retain75second window unless +measured evidence requires test scheduling allowance. Required QA/security/test +review, isolated PG journey plus Ruff/structure/record/diff gates. Review focus: +T4 owns deadline eligibility; T5 cannot invalidate accepted work after deadline. + +Late coverage v1 failed155.17s after actual T5: test assumed nonexistent +Submission.created_at. Correct assertion uses owner-persisted intake.finalized_at +and exact finalized_submission_id. Acceptance beat unchanged75second deadline; +no timing allowance needed. Cleanuptrue. Teardown cross-loop log is secondary to +explicit AttributeError. No product change or downstream expiry qualification +from v1; rerun full targeted journey with the corrected owner timestamp. + +Late coverage v2 failed359.67s in unchanged completed_evidence fixture before +entering changed journey: initial POST routing_recommendation mismatch; actual +status/source were absent from assertion. Cleanuptrue. Host load was high, but +no timeout root cause is established. Expand allowed test-only scope to +backend/tests/checkers/execution/completion_fixture.py assertion diagnostics: +retain exact comparison, report status/outcome_source/routing_recommendation on +failure. No deadlines or policy changes. This distinguishes infrastructure or +lease outcome from a policy-routing mismatch on next run; a pass alone will not +claim v2 root cause resolved. + +Late coverage v3 terminal0:1passed261.72s/schema0084/allcleanuptrue +(/tmp/submission-late-coverage-v3.json/.log). Testblob +70b4abce4b885a32ebae091427fca139f0c65d1c; diagnosticfixtureblob +2430d602328e062520eb7ce912d880f9f7aafd9c. Real acceptance precedes unchanged75s +window, owner-recorded finalization follows it, inherited coverage round0/window +and exactly one second-source expiration/status/task release pass. V2 initial +fixture mismatch remains unexplained; successful v3 is not root-cause proof. +Ruff/record/whitespace passed; structural v2 passed before diagnostic-only two-line +fixture assertion change. Scoped reviewer found no weakening or owner mismatch. +Shared modified-content execution overa326bec95, not independent/cleancommit +rerun or full policy-duration/native-provider qualification. Old expiry-race +creation consumers and full A01-A35/C01-C07 goal remain open. diff --git a/backend/tests/checkers/execution/completion_fixture.py b/backend/tests/checkers/execution/completion_fixture.py index 33e1a05ff..2430d6023 100644 --- a/backend/tests/checkers/execution/completion_fixture.py +++ b/backend/tests/checkers/execution/completion_fixture.py @@ -43,7 +43,9 @@ async def completed_evidence( ).evaluate_post_submission(h.request) async with h.factory() as session: h.run = await session.get(CheckerRun, str(h.result.attempt_id)) - assert h.run.routing_recommendation == recommendation + assert h.run.routing_recommendation == recommendation, ( + h.run.status, h.run.outcome_source, h.run.routing_recommendation, + ) event = await session.scalar(select(OutboxEvent).where( OutboxEvent.event_id == h.run.completion_event_id, )) diff --git a/backend/tests/tasks/submission_dispatch/test_revision_expiry.py b/backend/tests/tasks/submission_dispatch/test_revision_expiry.py index 4ed1e3c08..70b4abce4 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_expiry.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_expiry.py @@ -374,9 +374,11 @@ async def test_late_coverage_return_inherits_the_expired_window_and_expires_once Both coverage sources share one deadline: the superseded first source's expiry acknowledges without effect and only the second attempt is rejected. """ - from app.modules.tasks.schemas import AdmissionBackedSubmissionResponse + from app.modules.tasks.models import SubmissionDispatch + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from tests.retained_material_fixtures import finalize_retained_intake from tests.tasks.submission_dispatch.test_revision_capacity import ( - COVERAGE_GAP, _fail_current_submission, + COVERAGE_GAP, _fail_current_submission, _revision_http_runtime, _revision_upload_headers, ) async with remediation_source( @@ -388,17 +390,29 @@ async def test_late_coverage_return_inherits_the_expired_window_and_expires_once deliver=False, window_seconds=75, ) async with _client(h, monkeypatch, isolated_database_env) as client: - prepared, admission = await _ready_replacement(h, revision_archive(h.data)) + data = revision_archive(h.data) + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) created = await client.post( - f"/api/v1/tasks/{h.request.task_id}/submissions", json=_payload(prepared, admission), + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=_revision_upload_headers(h), content=data, ) - assert created.status_code == 201, created.text - h.created = AdmissionBackedSubmissionResponse.model_validate(created.json()) - await _fail_current_submission(h, findings=COVERAGE_GAP, route=False) + assert created.status_code == 202, created.text + assert len(calls) == 1 and not errors, errors deadline = datetime.fromisoformat(first_window["deadline_at"]) + assert datetime.fromisoformat(created.json()["accepted_at"].replace("Z", "+00:00")) < deadline async with h.factory() as session: remaining = (deadline - await session.scalar(select(func.clock_timestamp()))).total_seconds() await asyncio.sleep(max(0, remaining) + 0.5) + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(created.json()["operation_id"]), store=h.store.wrapped, + namespace=h.namespace, settings=settings)) + async with h.factory() as session: + h.created = (await session.get(SubmissionDispatch, submission_id)).result() + assert h.created.submission_version == 2 + operation = await session.get(SubmissionIntakeOperation, UUID(created.json()["operation_id"])) + assert operation.finalized_submission_id == str(submission_id) + assert operation.finalized_at >= deadline + await _fail_current_submission(h, findings=COVERAGE_GAP, route=False) second_source = await _fixture_revision_context(h) async with h.factory() as session: window = await session.get(TaskRevisionPreparation, h.revision_preparation_id) From fb80e635e0daa90f55fa463ca412427f7acbd8b7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 11:53:16 +0100 Subject: [PATCH 208/513] fix(tasks): defer revision expiry while foreground intake owns task --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 59 +++++++++ backend/app/modules/tasks/revision/expiry.py | 4 + .../test_revision_expiry.py | 117 +++++++++++++++--- 3 files changed, 163 insertions(+), 17 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index cb0538256..d5835ace6 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7198,3 +7198,62 @@ fixture assertion change. Scoped reviewer found no weakening or owner mismatch. Shared modified-content execution overa326bec95, not independent/cleancommit rerun or full policy-duration/native-provider qualification. Old expiry-race creation consumers and full A01-A35/C01-C07 goal remain open. + +Expiry-wins T4 race scope: migrate only + test_due_expiry_and_ready_final_submission_wait_for_task_lock in +backend/tests/tasks/submission_dispatch/test_revision_expiry.py. Complete real +rawZIP PRE then pause before T4; cross original PG deadline and queue expiry +before T4 on real TASK lock, observing both database waits. Preserve expiry +receipt, rejected predecessor/released assignment/taskready/no economic effects. +Replace obsolete ready-admission assertion with failed intake/no acceptance or +finalization event and retained sealed charge. Compare product snapshot after +PRE so legitimate PRE evidence is not mistaken for new product creation. +Allowed files: testmodule and this record; add cohesive test-only outcome helper. +No production/clock/SQL guard changes, no historical migration claim. Required +QA/security/testdelta inspection, isolated race, Ruff/structural/record/diff gates. +Existing creation-boundary tests/shared helpers remain until separately migrated. + +Expiry T4 race v1 failed173.81s beforelockrace: reused15second creation-stage +observer expired while newrequest still performs upload/PRE. Initial attempt to +add timeout selector had failed wrongcwd before run; v1executed unchanged helper. +Add optional test-observation timeout(default15 preserved), select60 for full +foreground journey only; no product/policy/lease/window changes. QA-EXPIRY001 +requires sealed/exactpositive sourcecharge; QA-EXPIRY002 compares finalization +and POST eventrows against afterPREbaseline. Independent reviewer counterprobes +showed releasedcharge/orphanfinalization would evade v1assertions; batch both +repairs before v2. No production failure inferred from these oracle gaps. + +Expiry T4 race v2 failed220.58s with actual23514 'intake task custody mismatch' +at expirycommit, allcleanuptrue: expiry tries to release assignment/TASK while +live prechecking source still owns locked context. Expand scope to +backend/app/modules/tasks/revision/expiry.py: after authorized/fenced/current +source checks, return explicit safe RETRY while TASK has an active source owner. +Foreground T4 still fails original expired deadline and its own finish clears +pointer; same expiry event redelivers and releases once. Accepted pending task +remains stale ACK, not expiry eligible. No ART imports, forced terminalization, +lease theft, SQL relaxation or new capability. Architecture/security review +required alongside QA. Test asserts first explicit retry/no expiration/economic +facts, then waits actual next_attempt_at and delivers sameevent for exacteffect. +Current race plus accepted-afterdeadline/coverage control verify both branches. + +Architecture review confirms safe guard placement after authority/fence/currentness +and before expiration writes. Important open liveness gap: default OUTBOX5attempts +with5/10/20/40second backoff may exhaust before a long foreground PRE hard deadline +(up to4h) and its reaper. Explicit same-event test redelivery proves ordering, not +production eventual expiry. C05/recovery envelope must be resolved for fullgoal; +no readiness claim or invented deployment defaults. v3 initial root-cwd launch +failed module discovery before tests; corrected backend launch uses same candidate. + +Expiry T4 race v3 terminal0:2passed276.06s/schema0084/allcleanuptrue +(/tmp/submission-expiry-t4-race-v3.json/.log). Productblob +39925240bf85b3db65329bb022706ff81742352b; testblob +9ff0d893420e4a1c9f2f58ac780b3e42732ba417. Race proves real PRE, both TASK lock +waits, known RETRY_REQUESTED (not unknown23514), originaldeadline refusal, +foreground-owned pointer release, actual sameeventgeneration+1 redelivery, +exactoneexpiration/sealedpositivecharge/noorphanT5orPOST. Accepted-afterdeadline +coverage control also passes. AUTH attempted-action decisions may persist on +RETRY; no-product-expiry effect does not mean no audit. Ruff/structure/record/ +whitespace pass. Review QA-EXPIRY001/002 closed with independent assertion probes. +Shared modified-content execution overa420f3e3c, not cleancommit/independent rerun. +C05 finite retry-envelope liveness remains unresolved and blocks full readiness; +no automatic eventual expiry, native provider or whole-spec qualification claim. diff --git a/backend/app/modules/tasks/revision/expiry.py b/backend/app/modules/tasks/revision/expiry.py index e27d314e1..39925240b 100644 --- a/backend/app/modules/tasks/revision/expiry.py +++ b/backend/app/modules/tasks/revision/expiry.py @@ -127,6 +127,10 @@ async def expire(self, envelope: OutboxEventEnvelope) -> HandlerOutcome: or task.assigned_to != str(target.contributor_id) or assignment.status != "active" or assignment.released_at is not None): return HandlerOutcome.ACKNOWLEDGE + if task.active_submission_operation_id is not None: + # Foreground custody must drain through its owner. T4 still + # rechecks the original deadline before accepting this source. + return HandlerOutcome.RETRY return await self._record_expiration( target=target, envelope=envelope, head=head, authority=authority, facts=facts, task=task, assignment=assignment, diff --git a/backend/tests/tasks/submission_dispatch/test_revision_expiry.py b/backend/tests/tasks/submission_dispatch/test_revision_expiry.py index 70b4abce4..9ff0d8934 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_expiry.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_expiry.py @@ -515,12 +515,12 @@ async def _ready_expiry_race_replacement(h): ) from exc -async def _wait_for_staged_submission(staged, final_request): +async def _wait_for_staged_submission(staged, final_request, *, timeout=15): """Retain an early real POST failure instead of hiding it behind a stage timeout.""" observed = asyncio.create_task(staged.wait()) try: done, _ = await asyncio.wait( - (observed, final_request), timeout=15, return_when=asyncio.FIRST_COMPLETED, + (observed, final_request), timeout=timeout, return_when=asyncio.FIRST_COMPLETED, ) if final_request in done: response = final_request.result() @@ -528,7 +528,7 @@ async def _wait_for_staged_submission(staged, final_request): "final POST ended before staged creation: " f"status={response.status_code}; body={response.text[:1200]}" ) - assert observed in done, "actual final creation did not reach staging within 15 seconds" + assert observed in done, f"request did not reach the observed stage within {timeout} seconds" finally: observed.cancel() await asyncio.gather(observed, return_exceptions=True) @@ -571,19 +571,92 @@ async def _assert_expired_creation_absent(h, source_id, admission_id, before): await no_economic_effects(session) +async def _assert_expired_intake_absent(h, source_id, operation_id, before): + """Losing T4 keeps sealed-byte cleanup custody without creating product facts.""" + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + after = await _creation_snapshot(h) + assert after[:8] == before[:8] + assert [e for e in after[8] if e["event_type"] in {"PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested"}] == [ + e for e in before[8] if e["event_type"] in {"PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested"}] + async with h.factory() as session: + operation = await session.get(SubmissionIntakeOperation, operation_id) + assert operation.state == "failed" and operation.acceptance_receipt is None + assert operation.finalization_event_id is None and operation.finalized_submission_id is None + charge = await session.get(SubmissionSourceCharge, operation_id) + assert charge is not None and charge.state == "sealed" + assert charge.accounted_bytes == operation.raw_byte_count > 0 + assert await session.scalar(text( + "SELECT count(*) FROM public.task_revision_expirations WHERE routing_manifest_id=:source" + ), {"source": source_id}) == 1 + assert (await session.execute(text( + "SELECT attempt_status,status_reason FROM public.submissions WHERE id=:id" + ), {"id": h.created.submission_id})).one() == ("rejected", "revision_deadline_expired") + assert (await session.execute(text( + "SELECT status,assigned_to,active_submission_operation_id FROM public.workstream_tasks WHERE id=:task" + ), {"task": h.request.task_id})).one() == ("ready", None, None) + assert await session.scalar(text( + "SELECT status FROM public.task_assignments WHERE id=:assignment" + ), {"assignment": h.request.assignment_id}) == "revision_expired" + await no_economic_effects(session) + + +async def _redeliver_deferred_expiry(h, source_id, event_id, delivered): + """Active foreground drains before the same due expiry releases its assignment.""" + assert delivered is not None + outcome = json.loads(delivered.outcome_json) + assert outcome["delivery_state"] == "retryable" and outcome["error_code"] == "RETRY_REQUESTED" + assert outcome["invocation_unknown"] is False + assert h.expiry_handler_outcome == HandlerOutcome.RETRY.value + assert getattr(h, "expiry_handler_error", None) is None + async with h.factory() as session: + assert await session.scalar(select(func.count(TaskRevisionExpiration.id))) == 0 + assert await session.scalar(select(func.count(OutboxEvent.event_id)).where( + OutboxEvent.event_type == REVISION_EXPIRED_EVENT)) == 0 + assert (await session.execute(text( + "SELECT status,active_submission_operation_id FROM public.workstream_tasks WHERE id=:id" + ), {"id": h.request.task_id})).one() == ("needs_revision", None) + assert await session.scalar(text( + "SELECT status FROM public.task_assignments WHERE id=:id" + ), {"id": h.request.assignment_id}) == "active" + await no_economic_effects(session) + event = await session.get(OutboxEvent, str(event_id)) + assert event.idempotency_key == f"task.revision.expire:{source_id}" + delay = (event.next_attempt_at - await session.scalar(select(func.clock_timestamp()))).total_seconds() + await asyncio.sleep(max(0, delay) + 0.2) + retried = await h.expiry_delivery.deliver(event_id, h.request.project_id, "expiry-after-foreground-drain") + _assert_race_expiry_acknowledged(h, retried) + assert retried.claim.event_id == delivered.claim.event_id + assert retried.claim.claim_generation == delivered.claim.claim_generation + 1 + + async def test_due_expiry_and_ready_final_submission_wait_for_task_lock( tmp_path, isolated_database_env, monkeypatch, ): - """Expiry wins TASK custody over an actual, independently verified final POST.""" + """Expiry wins TASK custody after real PRE but before accepted handoff.""" + from contextvars import ContextVar + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from tests.tasks.submission_dispatch.test_revision_capacity import ( + _revision_http_runtime, _revision_upload_headers, + ) + accepting = ContextVar("expiry_race_accepting", default=False) + pre_done, release = asyncio.Event(), asyncio.Event() + original_accept = ForegroundIntakeAdmission.accept + operations = [] + + async def pause_accept(admission, owner, *args, **kwargs): + operations.append(owner.operation_id) + pre_done.set() + await asyncio.wait_for(release.wait(), 90) + token = accepting.set(True) + try: + return await original_accept(admission, owner, *args, **kwargs) + finally: + accepting.reset(token) async with remediation_source(tmp_path, isolated_database_env) as h: source_id, _, event_id = await expire_retained_revision( h, monkeypatch=monkeypatch, isolated_database_env=isolated_database_env, deliver=False, window_seconds=60, ) - prepared, admission_id = await _ready_expiry_race_replacement(h) - assert await _admission_status(h, admission_id) == "ready" - before = await _creation_snapshot(h) - await _wait_until_revision_due(h, event_id) expiry_name = f"expiry-final-race-{new_record_id().hex}" final_name = f"submission-final-race-{new_record_id().hex}" original_expiry_lock = TaskRepository.lock_project_task @@ -596,7 +669,7 @@ async def expiry_lock(repository, *args, **kwargs): return await original_expiry_lock(repository, *args, **kwargs) async def final_lock(repository, *args, **kwargs): - if kwargs.get("for_update"): + if accepting.get() and kwargs.get("for_update"): await repository._session.execute(text( "SELECT set_config('application_name',:name,true)" ), {"name": final_name}) @@ -604,10 +677,20 @@ async def final_lock(repository, *args, **kwargs): pending = [] async with _client(h, monkeypatch, isolated_database_env) as client: + data = revision_archive(h.data) + _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) with monkeypatch.context() as patch: + patch.setattr(ForegroundIntakeAdmission, "accept", pause_accept) patch.setattr(TaskRepository, "lock_project_task", expiry_lock) patch.setattr(TaskRepository, "get_task", final_lock) try: + pending.append(asyncio.create_task(client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=_revision_upload_headers(h), content=data))) + await _wait_for_staged_submission(pre_done, pending[0], timeout=60) + assert len(calls) == 1 and not errors, errors + before = await _creation_snapshot(h) + await _wait_until_revision_due(h, event_id) async with h.factory() as holder, holder.begin(): await holder.execute(text( "SELECT id FROM public.workstream_tasks WHERE id=:task FOR UPDATE" @@ -618,23 +701,23 @@ async def final_lock(repository, *args, **kwargs): await asyncio.wait_for(wait_for_named_database_lock( isolated_database_env, expiry_name, ), 15) - pending.append(asyncio.create_task(client.post( - f"/api/v1/tasks/{h.request.task_id}/submissions", - json=_payload(prepared, admission_id), - ))) + release.set() await asyncio.wait_for(wait_for_named_database_lock( isolated_database_env, final_name, ), 15) assert all(not contender.done() for contender in pending) - delivered, final = await asyncio.wait_for(asyncio.gather(*pending), 30) + final, delivered = await asyncio.wait_for(asyncio.gather(*pending), 30) finally: + release.set() for contender in pending: if not contender.done(): contender.cancel() await asyncio.gather(*pending, return_exceptions=True) - _assert_race_expiry_acknowledged(h, delivered) - assert final.status_code in {404, 409}, final.text - await _assert_expired_creation_absent(h, source_id, admission_id, before) + assert final.status_code == 409, final.text + assert final.json()["error"]["code"] == "revision_deadline_expired" + await _redeliver_deferred_expiry(h, source_id, event_id, delivered) + assert len(operations) == 1 + await _assert_expired_intake_absent(h, source_id, operations[0], before) @pytest.mark.parametrize("commit_before_deadline", [True, False]) From 532984f331d1d5b7373b2806b47de501daa90a08 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 12:15:07 +0100 Subject: [PATCH 209/513] fix(tasks): atomically expire unaccepted revision intake --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 62 ++++++ backend/app/adapters/artifacts/__init__.py | 7 + backend/app/adapters/tasks/__init__.py | 3 +- .../app/api/routes/artifact_submissions.py | 4 +- .../artifacts/intake/foreground_admission.py | 27 ++- .../artifacts/intake/foreground_command.py | 4 + .../app/modules/artifacts/intake/progress.py | 2 +- .../modules/artifacts/intake/repository.py | 21 ++ .../app/modules/tasks/api/revision_expiry.py | 7 + backend/app/modules/tasks/revision/expiry.py | 10 +- .../test_revision_expiry.py | 190 ++++++++++++++---- .../test_revision_expiry_security.py | 2 + docs/spec_submission_execution.md | 4 +- 13 files changed, 290 insertions(+), 53 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d5835ace6..3daca8481 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7257,3 +7257,65 @@ whitespace pass. Review QA-EXPIRY001/002 closed with independent assertion probe Shared modified-content execution overa420f3e3c, not cleancommit/independent rerun. C05 finite retry-envelope liveness remains unresolved and blocks full readiness; no automatic eventual expiry, native provider or whole-spec qualification claim. + +User correction supersedes fb80e635e's foreground-deferral policy: expiry must +ACK without release once TASK is evaluation_pending, but may expire a current +needs_revision assignment even while upload/PRE is active. It must atomically +invalidate that intake before ready/reclaim; late PRE cannot accept or affect a +new assignment. Replace RETRY-behind-PRE rather than extend retry budgets. The +C05 concern caused by that deferral is superseded for this race. Whether T4 may +accept after clock deadline when T1 started earlier remains a pending user +clarification; do not implement the assistant's proposed relaxation by assumption. + +Bounded correction scope: TASK expiry operation/API and composition adapter; +ART-owned intake invalidation via a narrow injected port using current root +transaction, exact task/assignment/actor/predecessor and consumed expiry authority; +foreground terminal-error projection if needed; focused race/security tests and +this record/current specification explanation. Preserve SQL ownership closure, +generation fencing, source receipts/bytecharges and accepted work. No runtime +wait inside expiry, storage deletion, cross-owner private model access, new +service identity or relaxed authorization. Test both lock winners, receiving/PRE +invalidation, late callback/refusal, exact reclaim isolation, rollback and sealed +charge retention. Architecture/security and QA review required before closure; +focused PG and structural/record/owner checks, then single PR708 commit. Human +review focus: one atomic state winner and truthful reclaim guidance. + +Atomic expiry correction implements the existing TASK expiry root with an injected +ART participant. It checks exact task/assignment/actor/predecessor and fences only +receiving/PRE generations before clearing the task pointer; source charges remain. +Foreground exception resolution uses fresh own-operation read authority and exact +original lease/generation, actor/key/metadata. Receiving expiry with no committed +EOF is a terminal observation without reading/resuming the body; sealed replay +still checks hash/count. HTTP and operation-status reads preserve the expiry code. +The current T4 deadline cutoff is unchanged. No new worker, timeout policy or +contributor claim-expiry feature is added. + +Review QA-ATOMIC001/002 require reclaim-before-late-PRE and rollback with active +intake; the added focused control exercises both with actual HTTP PRE, a committed +expiry invocation, late injected failure, public reclaim and the old callback. +The new assignment has no new active intake; this is assignment-isolation proof, +not a claim to have exercised replacement of a newer non-null intake pointer. +Architecture review found no authority/atomicity bypass. A lease crossing between +clock samples can still cause the authoritative SQL guard to roll back expiry; +normal delivery recovery retries it. No single-attempt availability claim or SQL +relaxation is made. This corrects an already scoped capability, without changing +roadmap delivery/readiness claims or qualifying providers/full-goal completion. + +Atomic correction proof: initial PRE race plus inherited late coverage control +passed 2 tests in190.34s, schema0084, complete database/MinIO cleanup +(/tmp/submission-expiry-atomic-v1.log/.json). The active-intake rollback and +late-PRE-after-public-reclaim control passed1 in101.85s with complete cleanup +(/tmp/submission-expiry-atomic-custody-v1.log/.json), including the operation-read +expiry-code assertion. Its pytest child started12:10:29 after the final functional +progress/test edits12:10:28; subsequent admission edit only clarified a docstring. +Shared worktree evidence overfb80e635e, not clean-commit execution. QA design +findings001/002 are covered by that executed control. Ruff, Commitrail, whitespace, +test-structure and changed Markdown-link gates pass. + +Expanded atomic expiry run passed5 in346.38s/schema0084/all cleanup complete +(/tmp/submission-expiry-atomic-v2.log/.json): receiving and PRE lock-race winners, +same-key terminal replay, inherited expired-window routing, invalid service and +committed-resource substitution, and late outbox/audit rollback. Separate custody +control above proves active-intake rollback/reclaim isolation. Module/authorization +boundary suite passed92 in101.54s. These are bounded shared local proofs; full-suite +CI, provider qualification and remaining specification work are still required. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 9f6b86eac..d82d26ef8 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -936,6 +936,13 @@ def submission_bundle_preparation_reader(session: AsyncSession): return SubmissionBundlePreparationReader(session, runs=selected_pre_submit_run_reader(session)) +def submission_intake_revision_expiry_port(session): + """Bind ART invalidation to the authorized expiry's existing root transaction.""" + from app.adapters.tasks import intake_task_custody_port + from app.modules.artifacts.intake.repository import SubmissionIntakeRepository + return SubmissionIntakeRepository(session, intake_task_custody_port(session)) + + def submission_intake_pre_source_port(session): """Compose ART's locked source participation in the caller-owned T3 root.""" from app.adapters.tasks import intake_task_custody_port diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py index c3e6592ff..3775958cb 100644 --- a/backend/app/adapters/tasks/__init__.py +++ b/backend/app/adapters/tasks/__init__.py @@ -139,6 +139,7 @@ def __init__(self, session_factory, *, observer, authorization_factory): async def __call__(self, envelope): from app.adapters.audit import task_revision_expiry_audit + from app.adapters.artifacts import submission_intake_revision_expiry_port from app.adapters.outbox import outbox_append, outbox_invocation_fence from app.modules.tasks.api.revision_expiry import TaskRevisionExpiryUnavailable from app.modules.tasks.revision.expiry import TaskRevisionExpiryOperation @@ -150,7 +151,7 @@ async def __call__(self, envelope): fence=outbox_invocation_fence(session), authorization=self._authorization(session), audit=task_revision_expiry_audit(session), - outbox=outbox_append(session), + outbox=outbox_append(session), intake=submission_intake_revision_expiry_port(session), ).expire(envelope) return outcome except TaskRevisionExpiryUnavailable: diff --git a/backend/app/api/routes/artifact_submissions.py b/backend/app/api/routes/artifact_submissions.py index 4637008a4..6d9bcc2e3 100644 --- a/backend/app/api/routes/artifact_submissions.py +++ b/backend/app/api/routes/artifact_submissions.py @@ -88,7 +88,9 @@ async def submit_source( details = {"status": "failed", "eligible_to_submit": False, "results": exc.pre_submission_results or []} return error_response( request, status_code=_failure_status(exc.code), code=exc.code, - message="Submission unavailable" if exc.code == "submission_unavailable" else exc.code, + message=("Your assignment expired. Reclaim the task if it is still available." + if exc.code == "revision_deadline_expired" else + "Submission unavailable" if exc.code == "submission_unavailable" else exc.code), details=details, retryable=exc.code in {"submission_capacity_exceeded", "submission_infrastructure_unavailable", "submission_outcome_unknown"}, ) return SubmissionAcceptedResponse.model_validate(receipt) diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py index 3ae209c29..bfb6836b7 100644 --- a/backend/app/modules/artifacts/intake/foreground_admission.py +++ b/backend/app/modules/artifacts/intake/foreground_admission.py @@ -315,6 +315,25 @@ async def finish(self, owner: IntakeReservationOwner, *, state: str, failure_cod ) return True + async def revision_expired( + self, owner: IntakeReservationOwner, metadata: SubmissionIntakeMetadata, *, + actor_id: UUID, idempotency_key: UUID, + ) -> bool: + """Resolve an expiry-fenced foreground owner under current read authority.""" + async with self._root() as (session, authority): + repository = SubmissionIntakeRepository(session, self._tasks(session)) + row = await repository._lock(owner.operation_id) + await authority.authorize_read(IntakeOperationReadFacts( + UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id))) + if (row.actor_profile_id != str(actor_id) or row.idempotency_key != str(idempotency_key) + or row.metadata_sha256 != metadata.metadata_sha256()): + raise IntakeCustodyConflict("submission_idempotency_conflict") + expired = (row.state in {"cancelled", "abandoned"} + and row.failure_code == "revision_deadline_expired" + and row.lease_id == str(owner.lease_id) + and row.lease_generation == owner.generation + 1) + return expired + @staticmethod def _match_acceptance_command(row, request, terminal_digest, *, accepted): if (row.id != str(request.source.location.operation_id) @@ -403,7 +422,7 @@ async def replay_failure( self, metadata: SubmissionIntakeMetadata, *, actor_id: UUID, idempotency_key: UUID, operation_id: UUID, checkers: Callable[[AsyncSession], SelectedPreSubmitCoordinationPort], ) -> dict: - """Project retained failure after verified-byte replay and fresh read authority.""" + """Project retained failure under fresh read authority after replay/terminal observation.""" async with self._root() as (session, authority): repository = SubmissionIntakeRepository(session, self._tasks(session)) row = await repository._lock(operation_id) @@ -416,7 +435,7 @@ async def replay_failure( return await self._accepted_receipt(session, authority, row) if row.state in {"receiving", "pre_checking"}: raise IntakeCustodyConflict("submission_operation_in_progress") - if row.raw_sha256 is None or row.raw_byte_count is None: + if (row.raw_sha256 is None or row.raw_byte_count is None) and row.failure_code != "revision_deadline_expired": raise IntakeCustodyConflict("submission_operation_terminal") if row.state == "rejected" and row.failure_code == "pre_submission_checker_failed": terminal = await checkers(session).read_source_terminal(source_operation_id=operation_id) @@ -433,7 +452,7 @@ async def replay_failure( else: code = row.failure_code if row.failure_code in { "submission_packet_invalid", "submission_archive_limit_exceeded", - "submission_upload_timeout", "submission_infrastructure_unavailable", + "submission_upload_timeout", "submission_infrastructure_unavailable", "revision_deadline_expired", } else "submission_operation_terminal" failure = SubmissionIntakeFailure(code) # Commit the current read authorization before returning QC feedback. @@ -450,6 +469,8 @@ async def replay( metadata = SubmissionIntakeMetadata.model_validate(metadata) original = await self._read(metadata, actor_id, idempotency_key) if original.raw_sha256 is None or original.raw_byte_count is None: + if original.state in {"cancelled", "abandoned"} and original.failure_code == "revision_deadline_expired": + return original code = "submission_operation_in_progress" if original.state in {"receiving", "pre_checking"} else "submission_operation_terminal" raise IntakeCustodyConflict(code) raw = await hash_submission_replay( diff --git a/backend/app/modules/artifacts/intake/foreground_command.py b/backend/app/modules/artifacts/intake/foreground_command.py index 2a2de1cc6..06c09c759 100644 --- a/backend/app/modules/artifacts/intake/foreground_command.py +++ b/backend/app/modules/artifacts/intake/foreground_command.py @@ -124,6 +124,10 @@ async def run(_operation_id, _lease_id, _generation): raise IntakeCommitUnknown("submission terminal outcome is unresolved") from None else: if not finished and not isinstance(exc, asyncio.CancelledError): + if await self._admission.revision_expired( + owner, metadata, actor_id=actor_id, idempotency_key=idempotency_key, + ): + raise SubmissionIntakeFailure("revision_deadline_expired") from None raise IntakeCommitUnknown("submission foreground ownership has changed") from None if isinstance(exc, SubmissionUploadTimeout): raise SubmissionIntakeFailure(code) from None diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py index c51071304..0e43ef0dc 100644 --- a/backend/app/modules/artifacts/intake/progress.py +++ b/backend/app/modules/artifacts/intake/progress.py @@ -184,7 +184,7 @@ async def read(self, task_id, selector, *, actor_id): if code is not None and code not in { "submission_packet_invalid", "submission_archive_limit_exceeded", "submission_upload_timeout", "submission_infrastructure_unavailable", "pre_submission_checker_failed", - "submission_foreground_expired", "submission_operation_cancelled", + "submission_foreground_expired", "submission_operation_cancelled", "revision_deadline_expired", }: code = "submission_operation_terminal" return SubmissionOperationResponse( diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py index 782f1c132..38d548a5a 100644 --- a/backend/app/modules/artifacts/intake/repository.py +++ b/backend/app/modules/artifacts/intake/repository.py @@ -28,6 +28,7 @@ from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity from app.modules.artifacts.models import ArtifactStorageNamespace from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort +from app.modules.tasks.api.revision_expiry import TaskRevisionExpiryTarget from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest @@ -262,6 +263,26 @@ async def terminalize(self, operation_id: UUID, lease_id: UUID, generation: int, row = await self._owned(operation_id, lease_id, generation) await self._terminal(row, state, failure_code) + async def expire_revision(self, operation_id: UUID, target: TaskRevisionExpiryTarget) -> None: + """Participate only after TASK consumed expiry authority and fenced its event. + + This primitive grants no authority. The composition root shares the + authorized TASK transaction; any mismatch rolls back the entire expiry. + """ + target = TaskRevisionExpiryTarget.model_validate(target) + row = await self._lock(operation_id) + metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + if (row.state not in {"receiving", "pre_checking"} + or row.eligible_task_status != "needs_revision" + or (row.project_id, row.task_id, row.assignment_id, row.actor_profile_id) != ( + str(target.project_id), str(target.task_id), str(target.assignment_id), str(target.contributor_id)) + or metadata.predecessor_submission_id != target.source_submission_id): + raise IntakeCustodyConflict("revision_intake_expiry_mismatch") + await self._tasks.require_active(target.task_id, operation_id) + now = await self._session.scalar(select(func.clock_timestamp())) + state = "abandoned" if row.lease_expires_at <= now else "cancelled" + await self._terminal(row, state, "revision_deadline_expired") + async def abandon_expired(self, operation_id: UUID) -> bool: """Recovery can end expired foreground custody, never resume or accept it.""" row = await self._lock(operation_id) diff --git a/backend/app/modules/tasks/api/revision_expiry.py b/backend/app/modules/tasks/api/revision_expiry.py index 698f3a595..009e39b29 100644 --- a/backend/app/modules/tasks/api/revision_expiry.py +++ b/backend/app/modules/tasks/api/revision_expiry.py @@ -77,6 +77,13 @@ async def consume(self, facts: TaskRevisionExpiryAuthorityFacts) -> TaskRevision ... +class TaskRevisionExpiryIntakePort(Protocol): + """Caller-authorized participant in the same fenced TASK expiry transaction.""" + async def expire_revision(self, operation_id: UUID, target: TaskRevisionExpiryTarget) -> None: + """Fence only this assignment's unaccepted intake and retain source charges.""" + ... + + class TaskRevisionExpiryAuthorizationPort(Protocol): """Prepare fixed-service authority within the caller-owned transaction.""" def prepare_revision_expiry( diff --git a/backend/app/modules/tasks/revision/expiry.py b/backend/app/modules/tasks/revision/expiry.py index 39925240b..c9a9b1d96 100644 --- a/backend/app/modules/tasks/revision/expiry.py +++ b/backend/app/modules/tasks/revision/expiry.py @@ -12,7 +12,7 @@ from app.modules.tasks.api.revision_expiry import ( REVISION_EXPIRY_EVENT, TaskRevisionExpiryAuthorityFacts, TaskRevisionExpiryEvidence, TaskRevisionExpiryTarget, TaskRevisionExpiryUnavailable, - revision_expiry_resource_digest, + revision_expiry_resource_digest, TaskRevisionExpiryIntakePort, ) from app.modules.tasks.models import Submission from app.modules.tasks.repository import TaskRepository @@ -25,12 +25,12 @@ class TaskRevisionExpiryOperation: """Release the exact overdue assignment without changing its Submission.""" - def __init__(self, session, *, observer, fence, authorization, audit, outbox): + def __init__(self, session, *, observer, fence, authorization, audit, outbox, intake: TaskRevisionExpiryIntakePort): """Use owner ports and the caller session for one atomic expiry effect.""" self._session, self._repo = session, TaskRepository(session) self._observer, self._fence = observer, fence self._authorization, self._audit = authorization, audit - self._outbox = outbox + self._outbox, self._intake = outbox, intake async def expire(self, envelope: OutboxEventEnvelope) -> HandlerOutcome: """Revalidate TASK-first custody, then expire or replay the exact window.""" @@ -128,9 +128,7 @@ async def expire(self, envelope: OutboxEventEnvelope) -> HandlerOutcome: or assignment.status != "active" or assignment.released_at is not None): return HandlerOutcome.ACKNOWLEDGE if task.active_submission_operation_id is not None: - # Foreground custody must drain through its owner. T4 still - # rechecks the original deadline before accepting this source. - return HandlerOutcome.RETRY + await self._intake.expire_revision(UUID(task.active_submission_operation_id), target) return await self._record_expiration( target=target, envelope=envelope, head=head, authority=authority, facts=facts, task=task, assignment=assignment, diff --git a/backend/tests/tasks/submission_dispatch/test_revision_expiry.py b/backend/tests/tasks/submission_dispatch/test_revision_expiry.py index 9ff0d8934..6183d29f6 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_expiry.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_expiry.py @@ -571,7 +571,7 @@ async def _assert_expired_creation_absent(h, source_id, admission_id, before): await no_economic_effects(session) -async def _assert_expired_intake_absent(h, source_id, operation_id, before): +async def _assert_expired_intake_absent(h, source_id, operation_id, before, *, phase): """Losing T4 keeps sealed-byte cleanup custody without creating product facts.""" from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge after = await _creation_snapshot(h) @@ -580,11 +580,19 @@ async def _assert_expired_intake_absent(h, source_id, operation_id, before): e for e in before[8] if e["event_type"] in {"PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested"}] async with h.factory() as session: operation = await session.get(SubmissionIntakeOperation, operation_id) - assert operation.state == "failed" and operation.acceptance_receipt is None + assert operation.state in {"cancelled", "abandoned"} and operation.acceptance_receipt is None + assert operation.failure_code == "revision_deadline_expired" + assert operation.lease_generation == 2 assert operation.finalization_event_id is None and operation.finalized_submission_id is None charge = await session.get(SubmissionSourceCharge, operation_id) - assert charge is not None and charge.state == "sealed" - assert charge.accounted_bytes == operation.raw_byte_count > 0 + assert charge is not None and charge.accounted_bytes > 0 + if phase == "pre_checking": + assert charge.state == "sealed" + assert charge.accounted_bytes == operation.raw_byte_count + else: + assert charge.state == "reserved" + assert charge.accounted_bytes == charge.reserved_bytes + assert operation.raw_byte_count is None assert await session.scalar(text( "SELECT count(*) FROM public.task_revision_expirations WHERE routing_manifest_id=:source" ), {"source": source_id}) == 1 @@ -600,49 +608,33 @@ async def _assert_expired_intake_absent(h, source_id, operation_id, before): await no_economic_effects(session) -async def _redeliver_deferred_expiry(h, source_id, event_id, delivered): - """Active foreground drains before the same due expiry releases its assignment.""" - assert delivered is not None - outcome = json.loads(delivered.outcome_json) - assert outcome["delivery_state"] == "retryable" and outcome["error_code"] == "RETRY_REQUESTED" - assert outcome["invocation_unknown"] is False - assert h.expiry_handler_outcome == HandlerOutcome.RETRY.value - assert getattr(h, "expiry_handler_error", None) is None - async with h.factory() as session: - assert await session.scalar(select(func.count(TaskRevisionExpiration.id))) == 0 - assert await session.scalar(select(func.count(OutboxEvent.event_id)).where( - OutboxEvent.event_type == REVISION_EXPIRED_EVENT)) == 0 - assert (await session.execute(text( - "SELECT status,active_submission_operation_id FROM public.workstream_tasks WHERE id=:id" - ), {"id": h.request.task_id})).one() == ("needs_revision", None) - assert await session.scalar(text( - "SELECT status FROM public.task_assignments WHERE id=:id" - ), {"id": h.request.assignment_id}) == "active" - await no_economic_effects(session) - event = await session.get(OutboxEvent, str(event_id)) - assert event.idempotency_key == f"task.revision.expire:{source_id}" - delay = (event.next_attempt_at - await session.scalar(select(func.clock_timestamp()))).total_seconds() - await asyncio.sleep(max(0, delay) + 0.2) - retried = await h.expiry_delivery.deliver(event_id, h.request.project_id, "expiry-after-foreground-drain") - _assert_race_expiry_acknowledged(h, retried) - assert retried.claim.event_id == delivered.claim.event_id - assert retried.claim.claim_generation == delivered.claim.claim_generation + 1 - - +@pytest.mark.parametrize("phase", ["receiving", "pre_checking"]) async def test_due_expiry_and_ready_final_submission_wait_for_task_lock( - tmp_path, isolated_database_env, monkeypatch, + tmp_path, isolated_database_env, monkeypatch, phase, ): - """Expiry wins TASK custody after real PRE but before accepted handoff.""" + """Expiry fences upload/PRE before acceptance, retaining charged source custody.""" from contextvars import ContextVar from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.artifacts.intake.repository import SubmissionIntakeRepository from tests.tasks.submission_dispatch.test_revision_capacity import ( _revision_http_runtime, _revision_upload_headers, ) accepting = ContextVar("expiry_race_accepting", default=False) pre_done, release = asyncio.Event(), asyncio.Event() original_accept = ForegroundIntakeAdmission.accept + original_eof = SubmissionIntakeRepository.record_eof operations = [] + async def pause_eof(repository, operation_id, *args, **kwargs): + operations.append(operation_id) + pre_done.set() + await asyncio.wait_for(release.wait(), 90) + token = accepting.set(True) + try: + return await original_eof(repository, operation_id, *args, **kwargs) + finally: + accepting.reset(token) + async def pause_accept(admission, owner, *args, **kwargs): operations.append(owner.operation_id) pre_done.set() @@ -679,16 +671,20 @@ async def final_lock(repository, *args, **kwargs): async with _client(h, monkeypatch, isolated_database_env) as client: data = revision_archive(h.data) _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + headers = _revision_upload_headers(h) with monkeypatch.context() as patch: - patch.setattr(ForegroundIntakeAdmission, "accept", pause_accept) + if phase == "pre_checking": + patch.setattr(ForegroundIntakeAdmission, "accept", pause_accept) + else: + patch.setattr(SubmissionIntakeRepository, "record_eof", pause_eof) patch.setattr(TaskRepository, "lock_project_task", expiry_lock) patch.setattr(TaskRepository, "get_task", final_lock) try: pending.append(asyncio.create_task(client.post( f"/api/v1/tasks/{h.request.task_id}/submissions", - headers=_revision_upload_headers(h), content=data))) + headers=headers, content=data))) await _wait_for_staged_submission(pre_done, pending[0], timeout=60) - assert len(calls) == 1 and not errors, errors + assert len(calls) == (1 if phase == "pre_checking" else 0) and not errors, errors before = await _creation_snapshot(h) await _wait_until_revision_due(h, event_id) async with h.factory() as holder, holder.begin(): @@ -707,6 +703,11 @@ async def final_lock(repository, *args, **kwargs): ), 15) assert all(not contender.done() for contender in pending) final, delivered = await asyncio.wait_for(asyncio.gather(*pending), 30) + replay = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", headers=headers, content=data) + assert replay.status_code == 409, replay.text + assert replay.json()["error"]["code"] == "revision_deadline_expired" + assert len(calls) == (1 if phase == "pre_checking" else 0) finally: release.set() for contender in pending: @@ -715,9 +716,9 @@ async def final_lock(repository, *args, **kwargs): await asyncio.gather(*pending, return_exceptions=True) assert final.status_code == 409, final.text assert final.json()["error"]["code"] == "revision_deadline_expired" - await _redeliver_deferred_expiry(h, source_id, event_id, delivered) + _assert_race_expiry_acknowledged(h, delivered) assert len(operations) == 1 - await _assert_expired_intake_absent(h, source_id, operations[0], before) + await _assert_expired_intake_absent(h, source_id, operations[0], before, phase=phase) @pytest.mark.parametrize("commit_before_deadline", [True, False]) @@ -893,3 +894,112 @@ async def test_expired_notice_retries_after_unknown_ack_without_new_effect( "WHERE event_type='TaskRevisionExpired' " "AND event_payload->'references'->>'routing_manifest_id'=:source" ), {"source": str(source_id)}) == 1 + + +async def test_active_intake_expiry_rollback_and_late_pre_after_reclaim( + tmp_path, isolated_database_env, monkeypatch, +): + """A late expiry failure restores intake; a late PRE cannot alter a new claim.""" + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.tasks.revision.expiry import TaskRevisionExpiryOperation + from tests.tasks.submission_dispatch.test_revision_capacity import ( + _revision_http_runtime, _revision_upload_headers, + ) + from tests.tasks.submission_dispatch.test_revision_expiry_security import ( + _expiry_operation, _invocation, _snapshot, ParticipantFailure, + ) + staged, release = asyncio.Event(), asyncio.Event() + owners = [] + original_accept = ForegroundIntakeAdmission.accept + original_expiration = TaskRevisionExpiryOperation._record_expiration + + async def delayed_accept(admission, owner, *args, **kwargs): + owners.append(owner) + staged.set() + try: + await release.wait() + except asyncio.CancelledError: + # Exercise a PRE completion that arrives after foreground cancellation. + await release.wait() + return await original_accept(admission, owner, *args, **kwargs) + + async def intake_custody(h): + async with h.factory() as session: + return (await session.execute(text( + "SELECT o.state,o.lease_generation,o.failure_code,o.acceptance_receipt," + "o.finalization_event_id,to_jsonb(c),t.active_submission_operation_id " + "FROM public.submission_intake_operations o " + "JOIN public.submission_source_charges c ON c.operation_id=o.id " + "JOIN public.workstream_tasks t ON t.id=o.task_id WHERE o.id=:id" + ), {"id": owners[0].operation_id})).one() + + async def fail_after_expiration(operation, **kwargs): + assert await original_expiration(operation, **kwargs) is HandlerOutcome.ACKNOWLEDGE + row = (await operation._session.execute(text( + "SELECT state,lease_generation FROM public.submission_intake_operations WHERE id=:id" + ), {"id": owners[0].operation_id})).one() + assert row == ("cancelled", owners[0].generation + 1) + raise ParticipantFailure("after active intake expiry staging") + + async with remediation_source(tmp_path, isolated_database_env) as h: + _, _, event_id = await expire_retained_revision( + h, monkeypatch=monkeypatch, isolated_database_env=isolated_database_env, + deliver=False, window_seconds=60, + ) + async with _client(h, monkeypatch, isolated_database_env) as client: + data = revision_archive(h.data) + _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + monkeypatch.setattr(ForegroundIntakeAdmission, "accept", delayed_accept) + pending = asyncio.create_task(client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=_revision_upload_headers(h), content=data)) + try: + await _wait_for_staged_submission(staged, pending, timeout=60) + assert len(calls) == 1 and not errors, errors + await _wait_until_revision_due(h, event_id) + envelope = await _invocation(h, event_id) + before, intake_before = await _snapshot(h), await intake_custody(h) + with monkeypatch.context() as patch: + patch.setattr(TaskRevisionExpiryOperation, "_record_expiration", fail_after_expiration) + with pytest.raises(ParticipantFailure, match="after active intake expiry staging"): + async with h.factory() as session, session.begin(): + await _expiry_operation(h, session).expire(envelope) + assert await _snapshot(h) == before + assert await intake_custody(h) == intake_before + async with h.factory() as session, session.begin(): + assert await _expiry_operation(h, session).expire(envelope) is HandlerOutcome.ACKNOWLEDGE + claimed = await client.post( + f"/api/v1/tasks/{h.request.task_id}/claim", + headers={"Idempotency-Key": str(new_record_id())}) + assert claimed.status_code == 200, claimed.text + new_assignment = UUID(claimed.json()["assignment"]["id"]) + assert new_assignment != h.request.assignment_id + async with h.factory() as session: + new_custody = (await session.execute(text( + "SELECT to_jsonb(t),to_jsonb(a) FROM public.workstream_tasks t " + "JOIN public.task_assignments a ON a.task_id=t.id WHERE a.id=:id" + ), {"id": new_assignment})).one() + release.set() + final = await asyncio.wait_for(pending, 30) + assert final.status_code == 409, final.text + assert final.json()["error"]["code"] == "revision_deadline_expired" + async with h.factory() as session: + assert (await session.execute(text( + "SELECT to_jsonb(t),to_jsonb(a) FROM public.workstream_tasks t " + "JOIN public.task_assignments a ON a.task_id=t.id WHERE a.id=:id" + ), {"id": new_assignment})).one() == new_custody + await no_economic_effects(session) + terminal = await intake_custody(h) + assert terminal[0] == "cancelled" and terminal[1] == owners[0].generation + 1 + assert terminal[3] is None and terminal[4] is None + assert terminal[5] == intake_before[5] + progress = await client.get( + f"/api/v1/tasks/{h.request.task_id}/submission-operations", + params={"operation_id": str(owners[0].operation_id)}) + assert progress.status_code == 200, progress.text + assert progress.json()["failure_code"] == "revision_deadline_expired" + finally: + release.set() + if not pending.done(): + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) diff --git a/backend/tests/tasks/submission_dispatch/test_revision_expiry_security.py b/backend/tests/tasks/submission_dispatch/test_revision_expiry_security.py index 15f788d83..4231b5859 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_expiry_security.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_expiry_security.py @@ -8,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.adapters.audit import task_revision_expiry_audit +from app.adapters.artifacts import submission_intake_revision_expiry_port from app.adapters.auth import revision_expiry_authorization from app.adapters.outbox import outbox_append, outbox_invocation_fence from app.adapters.tasks import task_revision_recovery @@ -107,6 +108,7 @@ def _expiry_operation(h, session): fence=outbox_invocation_fence(session), authorization=revision_expiry_authorization(session), audit=task_revision_expiry_audit(session), outbox=outbox_append(session), + intake=submission_intake_revision_expiry_port(session), ) diff --git a/docs/spec_submission_execution.md b/docs/spec_submission_execution.md index af6b89751..db1da0955 100644 --- a/docs/spec_submission_execution.md +++ b/docs/spec_submission_execution.md @@ -414,7 +414,9 @@ Cleanup state is orthogonal: `not_claimed`, `claimed`, `deleted`. It records a d - Existing historical `submitted` records may remain valid; the new path does not need to persist that intermediate state. - Assignment release/replacement/readiness operations must respect the active/pending operation guard. Absence of a Submission is not evidence that an accepted assignment may be recycled. -No new contributor claim-expiry feature is introduced. Existing assignment/lifecycle operations must simply reject incompatible mutations while an operation owns the task. +Existing revision expiry acts only on the current `needs_revision` task and its due revision window. Under the same task lock and authorized expiry transaction, it fences any receiving/PRE intake for that assignment, preserves source cleanup obligations, and returns the task to `ready`. Late foreground work cannot accept and reports `revision_deadline_expired`, with guidance to reclaim if available. An accepted `evaluation_pending` task is untouched and the expiry event is acknowledged. If later routing returns the task to `needs_revision`, that routing schedules its own expiry event; an inherited deadline already in the past makes the event immediately due. + +No new contributor claim-expiry feature is introduced. Other assignment/lifecycle operations must reject incompatible mutations while an operation owns the task. ## 8. Durable data and constraints From b9a26bd605ffb3444dceb5c57611f343cdcad93d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 12:36:39 +0100 Subject: [PATCH 210/513] fix(artifacts): report revision deadline refusal at T4 commit --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 66 ++++++ backend/alembic/env.py | 3 +- ...0085_revision_acceptance_deadline_error.py | 34 +++ .../artifacts/intake/foreground_admission.py | 2 + backend/tests/conftest.py | 2 +- .../test_revision_expiry.py | 214 +++++++++--------- 6 files changed, 217 insertions(+), 104 deletions(-) create mode 100644 backend/alembic/versions/0085_revision_acceptance_deadline_error.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3daca8481..0ab7e6322 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7319,3 +7319,69 @@ committed-resource substitution, and late outbox/audit rollback. Separate custod control above proves active-intake rollback/reclaim isolation. Module/authorization boundary suite passed92 in101.54s. These are bounded shared local proofs; full-suite CI, provider qualification and remaining specification work are still required. + +Next bounded cutover proof: replace the remaining JSON creation commit-boundary +race in test_revision_expiry.py with raw ZIP/PRE/T4 and actual T5 continuation. +The old test still calls the removed public JSON contract and patches the old +TaskSubmissionCreationService. Preserve both timing branches: committed timely +T4 protects pending work; a transaction held beyond its existing eligibility +cutoff rolls back acceptance and lets due expiry release the assignment. Do not +relax current deadlines or alter production behavior. Inspect/delete only the +now-unreferenced local old-path helper/imports; shared consumers remain intact. +Allowed files: that test and this record. QA/architecture review focuses on real +transaction locks, no orphan accepted event/product facts, exact retained source +charge, timely accepted continuation and unchanged historical source. Run both +PostgreSQL branches plus relevant static gates. Single PR708; no merge/readiness +claim. This advances A11/A12/A31/A35 and old-producer retirement without treating +fixture success as complete specification/provider qualification. + +Commit-boundary v1: timely branch passed; late branch failed180.62s with expected +SQL23514 'revision acceptance is no longer eligible' at deferred commit, but API +returned503 submission_infrastructure_unavailable. Cleanup complete. This is a +conclusive acceptance rollback mislabeled by generic IntegrityError translation, +not unknown commit. Expand scope narrowly to foreground_admission.py: after that +rollback, fresh authorized exact-owner read plus canonical TASK context recheck +may classify a confirmed expired revision as revision_deadline_expired. Do not +infer expiry from SQL text or map other integrity errors to expiry. Preserve +unknown-commit handling and all deadline/SQL rules. Late-race terminal proof must +permit foreground to finish failed with the known expiry code before worker +invalidation, as well as worker cancelled/abandoned; both retain exact charge, +fence and no acceptance. QA/architecture review required for the added projection. +The structural gate found a133-line test; factor finalized-state assertions into +one named helper without weakening or relaxing the gate. + +Review refinement: a post-rollback expired context alone cannot identify the cause +of an unrelated integrity error. Replace that broad classifier with a dedicated +constraint identifier on the revision-deadline SQL rejection. Add migration0085 +which separates that predicate from other existing acceptance-currentness guards; +no eligibility relaxation or retained-row mutation. Only the named deadline +violation maps to409; all other integrity failures retain their original handling. +Add a real unrelated-integrity failure while the revision window is valid, as +QA-COMMIT001 requests. This expands allowed scope to that migration and the same +foreground translation/test paths, avoiding ambiguous cause inference. + +0085 integration includes the canonical Alembic head pin (and retained0084 +upgrade starting point) in alembic/env.py, plus tests/conftest.py's exact schema +fingerprint. Actual isolated PostgreSQL upgrade applied0085 successfully; v3 +then refused all4 fixture setups at the intentional old fingerprint gate39.59s, +complete cleanup. Measured new canonical hash: +4dd5956392e13454b03eccbe6001ad4f8251a88934539465ea9bc0b049cd4844. +Only the acceptance-currentness function body changes in this migration; no +rows/tables/privileges are replaced. Pin that measured result, not a guessed hash. +Intermediate broad-classifier v2 passed2/232.18s and initial-lease control passed +1/62.39s on0084, but those results do not qualify the superseding named-error fix. + +Final named-error candidate: v4 passed4 in283.03s/schema0085/all cleanup complete +(/tmp/submission-t4-commit-boundary-v4.log/.json). Timely T4 remains pending through +stale expiry then real T5 finalizes one dispatch; late deferred revision deadline +returns409 and exact replay without another PRE; unrelated real revision SQL +integrity failure returns503 with no accepted/expiry facts; initial lease-expiry +control remains a generic custody conflict. QA-COMMIT001 is covered. Schema parity +probe (/tmp/submission-0085-schema-parity.py/.log/.json) passed on separate owned +PG: reversing only this function change inside a rolled-back transaction restores +the exact full0084 catalog fingerprint, and rollback restores exact0085 fingerprint. +Cleanup complete. Ruff/structure/record/Markdown links/whitespace pass. Evidence +is shared modified-content execution over532984f33, not independent or cleancommit +execution. Fresh origin/main remainsa2154e8a4 and is already contained. This fixes +existing error semantics and retires this module's old JSON creation dependency; +remaining old producers, full-suite CI and provider/spec readiness remain open. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index a9f9a3bf8..e8aaf4d58 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0084_submission_source_binding" +_CURRENT_HEAD_REVISION = "0085_revision_deadline_error" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -138,6 +138,7 @@ def do_run_migrations(connection: Connection) -> None: ("0081_operation_read_authority",), ("0082_policy_phase_cardinality",), ("0083_accepted_revision",), + ("0084_submission_source_binding",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0085_revision_acceptance_deadline_error.py b/backend/alembic/versions/0085_revision_acceptance_deadline_error.py new file mode 100644 index 000000000..90e59f778 --- /dev/null +++ b/backend/alembic/versions/0085_revision_acceptance_deadline_error.py @@ -0,0 +1,34 @@ +"""Identify a conclusive revision-deadline rejection without masking custody errors.""" +from alembic import op +from sqlalchemy import text + +revision = "0085_revision_deadline_error" +down_revision = "0084_submission_source_binding" +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.workstream_tasks, public.submission_intake_operations, " + "public.task_revision_preparations IN ACCESS EXCLUSIVE MODE") + body = op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_functiondef(" + "'public.require_submission_acceptance_current(public.submission_intake_operations)'::regprocedure)" + )).scalar_one() + old_deadline = "OR p.deadline_at IS NULL OR p.deadline_at<=clock_timestamp()" + old_end = """ RAISE EXCEPTION 'revision acceptance is no longer eligible' USING ERRCODE='23514'; + END IF;""" + if body.count(old_deadline) != 1 or body.count(old_end) != 1: + raise RuntimeError("revision acceptance deadline predecessor changed") + body = body.replace(old_deadline, "OR p.deadline_at IS NULL") + body = body.replace(old_end, old_end + """ + IF p.deadline_at<=clock_timestamp() THEN + RAISE EXCEPTION 'revision acceptance deadline expired' + USING ERRCODE='23514', CONSTRAINT='ck_submission_revision_acceptance_deadline'; + END IF;""") + op.execute(body) + + +def downgrade(): + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py index bfb6836b7..ef6e723d2 100644 --- a/backend/app/modules/artifacts/intake/foreground_admission.py +++ b/backend/app/modules/artifacts/intake/foreground_admission.py @@ -286,6 +286,8 @@ async def accept( request, terminal_digest, checkers, outbox) return receipt except IntegrityError as exc: + if integrity_constraint_name(exc) == "ck_submission_revision_acceptance_deadline": + raise SubmissionIntakeFailure("revision_deadline_expired") from None raise IntakeCustodyConflict("intake_acceptance_conflict") from exc except IntakeCommitUnknown: async with self._root() as (session, authority): diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index d2a028b58..b92eb623a 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "e028a3b353a8112bddd77309722cd0dd69e6fe0c871dfa00c50f6da88651a90b" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "4dd5956392e13454b03eccbe6001ad4f8251a88934539465ea9bc0b049cd4844" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/tasks/submission_dispatch/test_revision_expiry.py b/backend/tests/tasks/submission_dispatch/test_revision_expiry.py index 6183d29f6..edc07deaf 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_expiry.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_expiry.py @@ -31,18 +31,16 @@ ) from app.modules.tasks.revision.expiry_event import revision_expiry_event from app.modules.tasks.revision.models import TaskRevisionExpiration, TaskRevisionPreparation -from app.modules.tasks.revision.service import project_current_revision from app.modules.tasks.repository import TaskRepository -from app.modules.tasks.submission_composition import TaskSubmissionCreationService from tests.tasks.post_submit_routing.backfill_support import assert_backfill_matches_live from tests.auth_concurrency_support import wait_for_named_database_lock from tests.tasks.post_submit_routing.remediation_support import remediation_source, no_economic_effects from tests.tasks.post_submit_routing.support import revision_archive from tests.tasks.submission_dispatch.test_revision_capacity import _retain_pre_revision_source from tests.tasks.submission_dispatch.test_replacement_creation import ( - _admission_status, _creation_snapshot, _ready_replacement, + _creation_snapshot, ) -from tests.tasks.test_public_submission_intake import _client, _payload +from tests.tasks.test_public_submission_intake import _client from tests.test_submission_predecessor_custody import _fixture_revision_context @@ -499,22 +497,6 @@ async def _wait_until_revision_due(h, event_id): assert await session.scalar(select(func.clock_timestamp())) >= deadline -async def _ready_expiry_race_replacement(h): - """Diagnose a real PRE failure before the contenders reach final creation.""" - try: - return await _ready_replacement(h, revision_archive(h.data)) - except Exception as exc: - async with h.factory() as session: - root = await session.get(TaskRevisionPreparation, h.revision_preparation_id) - view = await project_current_revision(session, root) - now = await session.scalar(select(func.clock_timestamp())) - raise AssertionError( - f"race PRE failed: {type(exc).__name__}; " - f"remaining_database_seconds={(root.deadline_at - now).total_seconds():.3f}; " - f"disposition={view.disposition}" - ) from exc - - async def _wait_for_staged_submission(staged, final_request, *, timeout=15): """Retain an early real POST failure instead of hiding it behind a stage timeout.""" observed = asyncio.create_task(staged.wait()) @@ -543,35 +525,10 @@ def _assert_race_expiry_acknowledged(h, delivered): ) -async def _assert_expired_creation_absent(h, source_id, admission_id, before): - # Delivery changes OUTBOX custody and TASK status. Every finalization owner - # before those two snapshot columns must remain exactly as before the race. - after = await _creation_snapshot(h) - assert after[:8] == before[:8] - assert [event for event in after[8] - if event["event_type"] == "PostSubmissionEvaluationRequested"] == [ - event for event in before[8] - if event["event_type"] == "PostSubmissionEvaluationRequested" - ] - assert await _admission_status(h, admission_id) == "ready" - async with h.factory() as session: - assert await session.scalar(text( - "SELECT count(*) FROM public.task_revision_expirations WHERE routing_manifest_id=:source" - ), {"source": source_id}) == 1 - # Expiry, not the losing final POST, decided the source attempt. - assert (await session.execute(text( - "SELECT attempt_status,status_reason FROM public.submissions WHERE id=:id" - ), {"id": h.created.submission_id})).one() == ("rejected", "revision_deadline_expired") - assert (await session.execute(text( - "SELECT status,assigned_to FROM public.workstream_tasks WHERE id=:task" - ), {"task": h.request.task_id})).one() == ("ready", None) - assert await session.scalar(text( - "SELECT status FROM public.task_assignments WHERE id=:assignment" - ), {"assignment": h.request.assignment_id}) == "revision_expired" - await no_economic_effects(session) - - -async def _assert_expired_intake_absent(h, source_id, operation_id, before, *, phase): +async def _assert_expired_intake_absent( + h, source_id, operation_id, before, *, phase, + terminal_states=frozenset({"cancelled", "abandoned"}), +): """Losing T4 keeps sealed-byte cleanup custody without creating product facts.""" from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge after = await _creation_snapshot(h) @@ -580,7 +537,7 @@ async def _assert_expired_intake_absent(h, source_id, operation_id, before, *, p e for e in before[8] if e["event_type"] in {"PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested"}] async with h.factory() as session: operation = await session.get(SubmissionIntakeOperation, operation_id) - assert operation.state in {"cancelled", "abandoned"} and operation.acceptance_receipt is None + assert operation.state in terminal_states and operation.acceptance_receipt is None assert operation.failure_code == "revision_deadline_expired" assert operation.lease_generation == 2 assert operation.finalization_event_id is None and operation.finalized_submission_id is None @@ -721,32 +678,39 @@ async def final_lock(repository, *args, **kwargs): await _assert_expired_intake_absent(h, source_id, operations[0], before, phase=phase) -@pytest.mark.parametrize("commit_before_deadline", [True, False]) +@pytest.mark.parametrize("commit_outcome", ["timely", "late", "integrity_failure"]) async def test_final_submission_commit_boundary_serializes_expiry( - tmp_path, isolated_database_env, monkeypatch, commit_before_deadline, + tmp_path, isolated_database_env, monkeypatch, commit_outcome, ): - """A timely final commit wins; a late commit rolls back every staged owner.""" + """Timely T4 protects pending work; late T4 rolls back before expiry wins.""" + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.submission_dispatch.test_revision_capacity import ( + _revision_http_runtime, _revision_upload_headers, + ) async with remediation_source(tmp_path, isolated_database_env) as h: source_id, _, event_id = await expire_retained_revision( h, monkeypatch=monkeypatch, isolated_database_env=isolated_database_env, deliver=False, window_seconds=60, ) - prepared, admission_id = await _ready_expiry_race_replacement(h) - before = await _creation_snapshot(h) staged, release = asyncio.Event(), asyncio.Event() - holder_pid = [] + holder_pid, operations = [], [] expiry_name = f"expiry-commit-wait-{new_record_id().hex}" - original_create = TaskSubmissionCreationService.create + original_accept = ForegroundIntakeAdmission._accept_new original_authority = OutboxDelivery._authority - async def pause_staged_creation(service, request): - # Execute actual creation, verified consumption, evaluation and - # outbox append; retain its root transaction before deferred checks. - result = await original_create(service, request) - assert result.submission_version == 2 - holder_pid.append(await service._session.scalar(text("SELECT pg_backend_pid()"))) + async def pause_staged_acceptance(admission, session, authority, repository, row, owner, *args): + result = await original_accept(admission, session, authority, repository, row, owner, *args) + await session.flush() + operations.append(owner.operation_id) + holder_pid.append(await session.scalar(text("SELECT pg_backend_pid()"))) staged.set() await asyncio.wait_for(release.wait(), 75) + if commit_outcome == "integrity_failure": + await session.execute(text( + "UPDATE public.submission_intake_operations SET lease_generation=0 WHERE id=:id" + ), {"id": owner.operation_id}) return result @asynccontextmanager @@ -759,27 +723,36 @@ async def named_delivery_authority(delivery, session, **selectors): pending = [] async with _client(h, monkeypatch, isolated_database_env) as client: + data = revision_archive(h.data) + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + headers = _revision_upload_headers(h) with monkeypatch.context() as patch: - patch.setattr(TaskSubmissionCreationService, "create", pause_staged_creation) + patch.setattr(ForegroundIntakeAdmission, "_accept_new", pause_staged_acceptance) patch.setattr(OutboxDelivery, "_authority", named_delivery_authority) try: pending.append(asyncio.create_task(client.post( f"/api/v1/tasks/{h.request.task_id}/submissions", - json=_payload(prepared, admission_id), + headers=headers, content=data, ))) - await _wait_for_staged_submission(staged, pending[0]) - assert (await _creation_snapshot(h))[:8] == before[:8] - assert await _admission_status(h, admission_id) == "ready" - if commit_before_deadline: - # OUTBOX cannot claim a future expiry. Finalization wins - # by committing before the due worker can acquire TASK. + await _wait_for_staged_submission(staged, pending[0], timeout=60) + assert len(calls) == 1 and not errors, errors + before = await _creation_snapshot(h) + async with h.factory() as session: + operation = await session.get(SubmissionIntakeOperation, operations[0]) + assert operation.state == "pre_checking" + assert operation.acceptance_receipt is None and operation.finalization_event_id is None + if commit_outcome != "late": + # OUTBOX cannot claim a future expiry. assert await h.expiry_delivery.deliver( event_id, h.request.project_id, "predeadline-final-proof", ) is None release.set() final = await asyncio.wait_for(pending[0], 15) - assert final.status_code == 201, final.text - assert final.json()["submission_version"] == 2 + if commit_outcome == "integrity_failure": + await _assert_unrelated_integrity_refusal(h, final, operations[0], before) + return + assert final.status_code == 202, final.text + assert final.json()["operation_id"] == str(operations[0]) await _wait_until_revision_due(h, event_id) delivered = await h.expiry_delivery.deliver( event_id, h.request.project_id, "stale-expiry-final-proof", @@ -789,8 +762,7 @@ async def named_delivery_authority(delivery, session, **selectors): pending.append(asyncio.create_task(h.expiry_delivery.deliver( event_id, h.request.project_id, "deferred-final-expiry-proof", ))) - # Fully staged creation also holds owner custody used by - # OUTBOX's claim. Observe its real wait before release. + # Observe expiry's actual wait behind staged T4. await asyncio.wait_for(wait_for_named_database_lock( isolated_database_env, expiry_name, expected_blocker_pid=holder_pid[0], @@ -800,6 +772,11 @@ async def named_delivery_authority(delivery, session, **selectors): final, delivered = await asyncio.wait_for(asyncio.gather(*pending), 30) assert final.status_code == 409, final.text assert final.json()["error"]["code"] == "revision_deadline_expired" + replay = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", headers=headers, content=data) + assert replay.status_code == 409, replay.text + assert replay.json()["error"]["code"] == "revision_deadline_expired" + assert len(calls) == 1 finally: release.set() for contender in pending: @@ -807,38 +784,71 @@ async def named_delivery_authority(delivery, session, **selectors): contender.cancel() await asyncio.gather(*pending, return_exceptions=True) _assert_race_expiry_acknowledged(h, delivered) - if not commit_before_deadline: - await _assert_expired_creation_absent(h, source_id, admission_id, before) + if commit_outcome == "late": + await _assert_expired_intake_absent( + h, source_id, operations[0], before, phase="pre_checking", + terminal_states={"failed", "cancelled", "abandoned"}) return - assert await _admission_status(h, admission_id) == "consumed" async with h.factory() as session: - assert await session.scalar(text( - "SELECT count(*) FROM public.task_revision_expirations WHERE routing_manifest_id=:source" - ), {"source": source_id}) == 0 - assert await session.scalar(text( - "SELECT count(*) FROM public.outbox_events WHERE event_type='TaskRevisionExpired'" - )) == 0 - assert (await session.execute(text( - "SELECT status,assigned_to FROM public.workstream_tasks WHERE id=:task" - ), {"task": h.request.task_id})).one() == ( - "evaluation_pending", h.actor_context.actor_profile_id, - ) - assert await session.scalar(text( - "SELECT status FROM public.task_assignments WHERE id=:assignment" - ), {"assignment": h.request.assignment_id}) == "active" + operation = await session.get(SubmissionIntakeOperation, operations[0]) + assert operation.state == "finalization_pending" + assert operation.acceptance_receipt is not None and operation.finalization_event_id is not None assert await session.scalar(text( "SELECT count(*) FROM public.submissions WHERE task_id=:task AND version=2" - ), {"task": h.request.task_id}) == 1 - assert await session.scalar(text( - "SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d " - "WHERE d.submission_id=:submission" - ), {"submission": final.json()["submission_id"]}) is True - assert await session.scalar(text( - "SELECT to_jsonb(s)-ARRAY['attempt_status','status_reason','decided_at','updated_at'] " - "FROM public.submissions s WHERE id=:submission" - ), {"submission": h.created.submission_id}) == before[0][0] - await no_economic_effects(session) + ), {"task": h.request.task_id}) == 0 + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=operations[0], store=h.store.wrapped, namespace=h.namespace, settings=settings)) + await _assert_timely_revision_finalized(h, source_id, submission_id, before) + +async def _assert_unrelated_integrity_refusal(h, response, operation_id, before): + """An unrelated SQL failure is not reported as revision expiry.""" + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "submission_infrastructure_unavailable" + after = await _creation_snapshot(h) + assert after[:8] == before[:8] + assert after[8] == before[8] + async with h.factory() as session: + assert (await session.execute(text( + "SELECT o.state,o.failure_code,o.acceptance_receipt,o.finalization_event_id," + "t.status,t.active_submission_operation_id,c.state,c.accounted_bytes=o.raw_byte_count " + "FROM public.submission_intake_operations o JOIN public.workstream_tasks t ON t.id=o.task_id " + "JOIN public.submission_source_charges c ON c.operation_id=o.id WHERE o.id=:id" + ), {"id": operation_id})).one() == ( + "failed", "submission_infrastructure_unavailable", None, None, "needs_revision", None, "sealed", True) + assert await session.scalar(select(func.count(TaskRevisionExpiration.id))) == 0 + await no_economic_effects(session) + + +async def _assert_timely_revision_finalized(h, source_id, submission_id, before): + """T5 preserves timely accepted custody and the prior immutable source.""" + async with h.factory() as session: + assert await session.scalar(text( + "SELECT count(*) FROM public.task_revision_expirations WHERE routing_manifest_id=:source" + ), {"source": source_id}) == 0 + assert await session.scalar(text( + "SELECT count(*) FROM public.outbox_events WHERE event_type='TaskRevisionExpired'" + )) == 0 + assert (await session.execute(text( + "SELECT status,assigned_to FROM public.workstream_tasks WHERE id=:task" + ), {"task": h.request.task_id})).one() == ( + "evaluation_pending", h.actor_context.actor_profile_id, + ) + assert await session.scalar(text( + "SELECT status FROM public.task_assignments WHERE id=:assignment" + ), {"assignment": h.request.assignment_id}) == "active" + assert await session.scalar(text( + "SELECT count(*) FROM public.submissions WHERE task_id=:task AND version=2" + ), {"task": h.request.task_id}) == 1 + assert await session.scalar(text( + "SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d " + "WHERE d.submission_id=:submission" + ), {"submission": submission_id}) is True + assert await session.scalar(text( + "SELECT to_jsonb(s)-ARRAY['attempt_status','status_reason','decided_at','updated_at'] " + "FROM public.submissions s WHERE id=:submission" + ), {"submission": h.created.submission_id}) == before[0][0] + await no_economic_effects(session) async def test_expired_notice_retries_after_unknown_ack_without_new_effect( tmp_path, isolated_database_env, monkeypatch, From a2988686136bbee213d7e3d3c3edcd2cc4412353 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 12:47:11 +0100 Subject: [PATCH 211/513] test(tasks): prove predecessor checker fence at T4 handoff --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 49 ++++++ .../test_submission_predecessor_custody.py | 148 ++++++++++-------- 2 files changed, 129 insertions(+), 68 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0ab7e6322..d1c5afd32 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7385,3 +7385,52 @@ is shared modified-content execution over532984f33, not independent or cleancomm execution. Fresh origin/main remainsa2154e8a4 and is already contained. This fixes existing error semantics and retires this module's old JSON creation dependency; remaining old producers, full-suite CI and provider/spec readiness remain open. + +Next bounded retirement: replace test_dispatch_commit_requires_current_predecessor_checker_fence +in test_submission_predecessor_custody.py. The remaining test uses an old ready +admission and hidden create command; current acceptance must instead reject a +stale checker generation at T4 even if a deliberately frozen TASK context port +returns the earlier valid context. Use public raw ZIP and real PRE, advance the +real checker fence after PRE, retain real AUTH/ART/CHECKERS/SQL, and require no +accepted event/product facts plus retained sealed charge. Positive control uses +current context and real T5 to verify the routed predecessor dispatch. Allowed: +that test module and this record; remove its now-unused old creation-service +import only after checking callers. Shared historical fixtures and other old +consumers remain untouched. No production behavior/SQL/authorization changes. +Risk: lineage/currentness proof; QA and architecture/security review required. +Run both real PostgreSQL branches, static/structure/record gates, then commit to +single PR708. A12/A24/A31/A35 evidence advances; full old-producer retirement, +provider qualification and all-goal completion are not inferred from this test. + +QA-FENCE001: generic503 plus rollback alone could credit an unrelated deferred +failure. Preserve cause proof by observing only the staged T4 session's real +commit, capturing and rethrowing its IntegrityError unchanged. Require23514 and +'revision acceptance is no longer eligible' for the stale case, and no commit +error for the valid case. This restores the old test's cause-specific assertion +at the new T4 boundary without exposing SQL diagnostics through the public API. + +Fence v1 passed positive T4/T5 but failed stale-case stage observation126.43s: +CHECKERS lock_acceptance independently obtains the same canonical TASK context +through selected_pre_submit_task_guard and refuses the advanced fence before +staging. This is an earlier valid guard, not a product bypass. To retain the +intended independent SQL guard proof, freeze the TASK context factory for that +T4 consumer too, after first proving the genuine canonical port rejects. Keep +CHECKERS validation/source locking and all writers real. Existing broad TASK +factory replacement was also the old test's fault injection; no production +change or additional owner authority is introduced. v2 includes QA's exact +commit-cause observation plus both port instances of that one stale TASK reader. + +Fence v2 passed2 in61.85s/schema0085/all database+MinIO cleanup complete +(/tmp/submission-current-predecessor-fence-v2.log/.json). One existing Pydantic +serialization warning comes from the synthetic next-request fixture; no warning +is suppressed. The stale case stages real T4, then observes exact23514 currentness +refusal and full rollback/charged-source custody; valid context reaches real T5 +and a valid version2 routed dispatch. QA-FENCE001 counterprobe independently +rejects unrelated23514, wrong SQLSTATE and missing error +(/tmp/submission-predecessor-fence-qa-cause-probe.json). Existing + test_stale_routed_cause_denies_acceptance_after_successful_pre separately covers +normal context denial; this new boundary is intentionally SQL-backstop proof. +Shared modified-content execution overb9a26bd60, not clean-commit or independent +runtime execution. This removes the old creation-service dependency from this +test, not all remaining hidden old producers or broader qualification work. +Ruff, test-structure, Commitrail record and whitespace gates pass on final content. diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 932c81242..00e2b5401 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -51,7 +51,6 @@ TaskSubmissionContextUnavailable, ) from app.modules.tasks.models import SubmissionDispatch -from app.modules.tasks.submission_composition import TaskSubmissionCreationService from app.modules.tasks.submission_context import TaskSubmissionContextService from app.adapters.tasks import task_submission_context_port from tests.auth_concurrency_support import wait_for_named_database_lock @@ -759,94 +758,107 @@ async def test_sql_selected_pre_reservation_and_admission_reject_foreign_routed_ async def test_dispatch_commit_requires_current_predecessor_checker_fence( tmp_path, isolated_database_env, monkeypatch, advance_fence, ): + """T4 rejects a superseded cause despite a stale port; current T4 reaches T5.""" + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.submission_dispatch.test_revision_capacity import ( + _revision_http_runtime, _revision_upload_headers, + ) + from tests.tasks.submission_dispatch.test_replacement_creation import _creation_snapshot + from tests.tasks.test_public_submission_intake import _client + async with remediation_source(tmp_path, isolated_database_env) as h: source_id = await _fixture_revision_context(h) - request = _replacement_request( - h, revision_archive(h.data), predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ) - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, h.actor_context, request, - ) async with h.factory.begin() as session: - frozen = await task_submission_context_port(session).lock_submission_context( - _context_request(h) - ) + frozen = await task_submission_context_port(session).lock_submission_context(_context_request(h)) assert frozen.checker_remediation_manifest_id == source_id - creation = SubmissionCreationRequest( - task_id=h.request.task_id, - assignment_id=h.request.assignment_id, - contributor_id=h.actor_context.actor_profile_id, - predecessor_submission_id=h.created.submission_id, - admission_id=admission_id, - summary=request.summary, - contributor_attestation=request.contributor_attestation, - ) - - if advance_fence: - await reserve(h, await next_request(h)) - async with h.factory.begin() as session: - with pytest.raises(TaskSubmissionContextUnavailable): - await task_submission_context_port(session).lock_submission_context( - _context_request(h) - ) class FrozenTaskContextPort: async def lock_submission_context(self, selected): assert selected == _context_request(h) return frozen - staged = [] - original_create = TaskSubmissionCreationService.create + operations, snapshots, staged, commit_errors = [], [], [], [] + original_accept = ForegroundIntakeAdmission.accept + original_stage = ForegroundIntakeAdmission._accept_new - async def traced_create(service, selected): - result = await original_create(service, selected) - assert await service._session.scalar(text( - "SELECT count(*) FROM public.submission_dispatches WHERE submission_id=:id" - ), {"id": result.submission_id}) == 1 - staged.append(result.submission_id) + async def accept_after_fence_change(admission, owner, *args, **kwargs): + operations.append(owner.operation_id) + if advance_fence: + await reserve(h, await next_request(h)) + async with h.factory.begin() as session: + with pytest.raises(TaskSubmissionContextUnavailable): + await task_submission_context_port(session).lock_submission_context(_context_request(h)) + # Freeze only the TASK context reader. All writers and SQL guards remain real. + monkeypatch.setattr(admission, "_contexts", lambda _session: FrozenTaskContextPort()) + monkeypatch.setattr( + "app.adapters.tasks.task_submission_context_port", lambda _session: FrozenTaskContextPort()) + snapshots.append(await _creation_snapshot(h)) + return await original_accept(admission, owner, *args, **kwargs) + + async def trace_staged_acceptance(admission, session, authority, repository, row, owner, *args): + result = await original_stage(admission, session, authority, repository, row, owner, *args) + await session.flush() + assert row.state == "finalization_pending" and row.finalization_event_id is not None + staged.append(owner.operation_id) + original_commit = session.commit + + async def observed_commit(): + try: + await original_commit() + except IntegrityError as exc: + commit_errors.append((exc.orig.sqlstate, str(exc.orig))) + raise + + monkeypatch.setattr(session, "commit", observed_commit) return result - monkeypatch.setattr(TaskSubmissionCreationService, "create", traced_create) + monkeypatch.setattr(ForegroundIntakeAdmission, "accept", accept_after_fence_change) + monkeypatch.setattr(ForegroundIntakeAdmission, "_accept_new", trace_staged_acceptance) + data = revision_archive(h.data) + async with _client(h, monkeypatch, isolated_database_env) as client: + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + response = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=_revision_upload_headers(h), content=data) + assert len(calls) == 1 and not errors, errors + assert len(operations) == 1 and staged == operations + operation_id = operations[0] if advance_fence: - # Deliberately stale TASK port only: the writer still executes real - # AUTH, ART consumption, CHECKERS reservation, outbox and SQL commit. - monkeypatch.setattr( - "app.adapters.tasks.task_submission_context_port", - lambda _session: FrozenTaskContextPort(), - ) - with pytest.raises( - IntegrityError, match="revision context unavailable for new submission", - ): - async with h.factory() as session: - await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(creation) - assert staged == [] # The INSERT guard stops before any dispatch is staged. + assert len(commit_errors) == 1 + assert commit_errors[0][0] == "23514" + assert "revision acceptance is no longer eligible" in commit_errors[0][1] + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "submission_infrastructure_unavailable" + after, before = await _creation_snapshot(h), snapshots[0] + assert after[:8] == before[:8] + assert after[8] == before[8] async with h.factory() as session: - assert await session.scalar(text("SELECT count(*) FROM public.submissions")) == 1 - assert await session.scalar(text("SELECT count(*) FROM public.submission_dispatches")) == 1 - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert admission.status == "ready" - assert await session.scalar(text( - "SELECT status FROM public.workstream_tasks WHERE id=:id" - ), {"id": h.request.task_id}) == "needs_revision" + operation = await session.get(SubmissionIntakeOperation, operation_id) + assert operation.state == "failed" and operation.acceptance_receipt is None + assert operation.finalization_event_id is None and operation.finalized_submission_id is None + charge = await session.get(SubmissionSourceCharge, operation_id) + assert charge.state == "sealed" and charge.accounted_bytes == operation.raw_byte_count > 0 + assert (await session.execute(text( + "SELECT status,active_submission_operation_id FROM public.workstream_tasks WHERE id=:id" + ), {"id": h.request.task_id})).one() == ("needs_revision", None) + await no_economic_effects(session) else: + assert commit_errors == [] + assert response.status_code == 202, response.text + assert response.json()["operation_id"] == str(operation_id) + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=operation_id, store=h.store.wrapped, namespace=h.namespace, settings=settings)) async with h.factory() as session: - created = await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(creation) - assert staged == [created.submission_id] - assert created.submission_version == 2 - async with h.factory() as session: - dispatch = await session.get(SubmissionDispatch, str(created.submission_id)) + dispatch = await session.get(SubmissionDispatch, str(submission_id)) + assert dispatch.submission_version == 2 assert dispatch.checker_remediation_manifest_id == source_id assert await session.scalar(text( "SELECT public.submission_dispatch_valid(d) " "FROM public.submission_dispatches d WHERE d.submission_id=:id" - ), {"id": created.submission_id}) is True + ), {"id": submission_id}) is True + await no_economic_effects(session) async def test_foreign_predecessor_stops_at_task_context_before_art_effects( From 9b946765304153e1403ed069cbcca809a3479b50 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 12:57:25 +0100 Subject: [PATCH 212/513] test(artifacts): verify replacement replay through raw ZIP and T5 --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 32 +++ .../test_submission_predecessor_custody.py | 204 ++++++++---------- 2 files changed, 121 insertions(+), 115 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d1c5afd32..a6c014b57 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7434,3 +7434,35 @@ Shared modified-content execution overb9a26bd60, not clean-commit or independent runtime execution. This removes the old creation-service dependency from this test, not all remaining hidden old producers or broader qualification work. Ruff, test-structure, Commitrail record and whitespace gates pass on final content. + +Next bounded predecessor cutover batch: move the successful replacement/replay +matrix (human-review true/false) and dispatch SQL cause/receipt substitution test +to public raw ZIP, T4 receipt replay before and after actual T5, and finalized +source-backed admissions. Preserve one physical upload/one PRE, changed raw and +semantic content, exact predecessor/cause lineage, prior immutable history, +consumed admission and valid dispatch, all four SQL substitution refusals and no +economic effects. Allowed: test_submission_predecessor_custody.py, existing test +fixture helper only if required for the file boundary, and this record. Inventory +shared helpers before edits; parameterize only the existing provider-write trace +with unchanged defaults for remaining consumers. No production/migration/authority +changes or hidden old-create calls added. Required QA/architecture review, three +real PostgreSQL cases, Ruff/structure/record/whitespace gates, single PR708 commit. +This removes two more old writer consumers while retaining A05/A22/A24/A31 proof; +full old-producer deletion and specification/provider qualification remain open. + +Predecessor replay v1 passed3 in113.87s/schema0085/all cleanup complete +(/tmp/submission-predecessor-replay-v1.log/.json). The full creation-snapshot +replay assertion was added at12:53 after the pytest child began12:52:41; do not +credit v1 with that added assertion. Freeze final content and run v2 including +that stronger no-extra-product/event oracle. Review found lineage/substitution +checks preserved and default trace consumers unchanged. No production gap found. + +Frozen predecessor replay v2 passed3 in95.81s/schema0085/all database+MinIO +cleanup complete (/tmp/submission-predecessor-replay-v2.log/.json). Both review +policy branches prove stable replay before/after actual T5, unchanged preparation +and creation graphs, exact one traced physical upload and one PRE, intact prior +history and consumed source-backed lineage; the SQL test retains all four +substitution refusals. Ruff, test-structure, record and whitespace gates pass. +Shared worktree proof overa29886861, not clean-commit/independent execution. Scope +is test cutover, so roadmap capability/readiness claims do not change. Remaining +old preparation/creation consumers and full qualification remain explicit work. diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 00e2b5401..b20033505 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -69,9 +69,9 @@ ) -def _trace_provider_writes(monkeypatch: pytest.MonkeyPatch) -> list[str]: +def _trace_provider_writes(monkeypatch: pytest.MonkeyPatch, *, operations=("put", "observe_put_result")) -> list[str]: calls: list[str] = [] - for operation in ("put", "observe_put_result"): + for operation in operations: original = getattr(LocalStorageAdapter, operation) async def traced(self, *args, _original=original, _operation=operation, **kwargs): @@ -205,47 +205,74 @@ def _context_request(h) -> TaskSubmissionContextRequest: ) +async def _replacement_history(h, source_id, predecessor_id): + """Retain exact prior Submission, routing and checker evidence across replacement.""" + async with h.factory() as session: + return (await session.execute(text(""" + SELECT (SELECT to_jsonb(s) FROM public.submissions s WHERE s.id=:prior), + (SELECT to_jsonb(m) FROM public.task_post_submit_routing_manifests m WHERE m.id=:cause), + (SELECT to_jsonb(r) FROM public.checker_results r WHERE r.id=:result) + """), {"prior": predecessor_id, "cause": source_id, + "result": h.completion.reference.result_id})).one() + + @pytest.mark.parametrize("human_review_required", [True, False]) async def test_real_replacement_compares_consumed_predecessor_and_replays_exactly( - tmp_path, - isolated_database_env, - monkeypatch, - human_review_required, + tmp_path, isolated_database_env, monkeypatch, human_review_required, ): - provider_writes = _trace_provider_writes(monkeypatch) + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.submission_dispatch.test_revision_capacity import ( + _revision_http_runtime, _revision_upload_headers, + ) + from tests.tasks.test_public_submission_intake import _client + from tests.tasks.submission_dispatch.test_replacement_creation import _creation_snapshot + async with remediation_source( tmp_path, isolated_database_env, human_review_required=human_review_required, ) as h: await _assert_dispatch_valid(h) source_id = await _fixture_revision_context(h) - provider_writes.clear() predecessor_id = h.created.submission_id - changed_data = revision_archive(h.data) - idempotency_key = new_record_id() - changed_request = _replacement_request( - h, - changed_data, - predecessor_id=predecessor_id, - idempotency_key=idempotency_key, - ) - admission_id = await _verified_admission( - h.factory, - h.store, - h.namespace, - h.settings, - h.actor_context, - changed_request, - ) - assert provider_writes == ["put"] - + immutable_before = await _replacement_history(h, source_id, predecessor_id) + writes = _trace_provider_writes(monkeypatch, operations=( + "begin_source_upload", "upload_source_part", "complete_source_upload", "put", "observe_put_result")) + data = revision_archive(h.data) + async with _client(h, monkeypatch, isolated_database_env) as client: + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + headers = _revision_upload_headers(h) + url = f"/api/v1/tasks/{h.request.task_id}/submissions" + response = await client.post(url, headers=headers, content=data) + assert response.status_code == 202, response.text + accepted = response.json() + operation_id = UUID(accepted["operation_id"]) + async with h.factory() as session: + operation = await session.get(SubmissionIntakeOperation, operation_id) + assert operation.state == "finalization_pending" and operation.finalized_submission_id is None + assert await session.scalar(text("SELECT count(*) FROM public.submissions")) == 1 + for finalized in (False, True): + if finalized: + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=operation_id, store=h.store.wrapped, namespace=h.namespace, settings=settings)) + before = await _snapshot(h) + creation_before = await _creation_snapshot(h) + replay = await client.post(url, headers=headers, content=data) + assert replay.status_code == 202, replay.text + assert replay.json() == dict(accepted, replayed=True) + assert await _snapshot(h) == before + assert await _creation_snapshot(h) == creation_before + assert writes == ["begin_source_upload", "upload_source_part", "complete_source_upload"] + assert len(calls) == 1 and not errors, errors async with h.factory() as session: - predecessor_admission = await session.get( - SubmissionBundleAdmission, str(h.creation_request.admission_id) - ) - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) + operation = await session.get(SubmissionIntakeOperation, operation_id) + assert operation.state == "finalized" and operation.finalized_submission_id == str(submission_id) + charge = await session.get(SubmissionSourceCharge, operation_id) + assert charge.state == "sealed" and charge.accounted_bytes == operation.raw_byte_count > 0 + predecessor_admission = await session.get(SubmissionBundleAdmission, str(h.creation_request.admission_id)) + admission = await session.get(SubmissionBundleAdmission, operation.finalized_admission_id) selected = await session.get(SelectedPreSubmitRun, admission.selected_pre_submit_run_id) - assert predecessor_admission.status == "consumed" - assert admission.status == "ready" + assert predecessor_admission.status == admission.status == "consumed" + assert admission.source_operation_id == str(operation_id) assert admission.predecessor_submission_id == str(predecessor_id) assert admission.predecessor_submission_version == 1 assert admission.checker_remediation_manifest_id == source_id @@ -256,69 +283,19 @@ async def test_real_replacement_compares_consumed_predecessor_and_replays_exactl assert lineage["predecessor_submission_version"] == 1 assert lineage["checker_remediation_manifest_id"] == str(source_id) assert admission.archive_sha256 != predecessor_admission.archive_sha256 - assert ( - admission.semantic_manifest_sha256 != predecessor_admission.semantic_manifest_sha256 - ) - - ready = await _snapshot(h) - replay = await _prepare( - h, - _replacement_request( - h, - changed_data, - predecessor_id=predecessor_id, - idempotency_key=idempotency_key, - ), - ) - assert replay.replayed is True - assert replay.admission_id == admission_id - assert await _snapshot(h) == ready - assert provider_writes == ["put"] - - async with h.factory() as session: - immutable_before = (await session.execute(text(""" - SELECT (SELECT to_jsonb(s) FROM public.submissions s WHERE s.id=:prior), - (SELECT to_jsonb(m) FROM public.task_post_submit_routing_manifests m WHERE m.id=:cause), - (SELECT to_jsonb(r) FROM public.checker_results r WHERE r.id=:result) - """), {"prior": predecessor_id, "cause": source_id, - "result": h.completion.reference.result_id})).one() - creation = SubmissionCreationRequest( - task_id=h.request.task_id, - assignment_id=h.request.assignment_id, - contributor_id=h.actor_context.actor_profile_id, - predecessor_submission_id=predecessor_id, - admission_id=admission_id, - summary=changed_request.summary, - contributor_attestation=changed_request.contributor_attestation, - ) - async with h.factory() as session: - created = await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(creation) - assert created.submission_version == 2 - async with h.factory() as session: - receipt = await session.get(SubmissionDispatch, str(created.submission_id)) - assert receipt is not None - assert receipt.creation_kind == "checker_remediation" + assert admission.semantic_manifest_sha256 != predecessor_admission.semantic_manifest_sha256 + receipt = await session.get(SubmissionDispatch, str(submission_id)) + assert receipt.submission_version == 2 and receipt.creation_kind == "checker_remediation" assert receipt.checker_remediation_manifest_id == source_id - assert await session.scalar(text(""" - SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d - WHERE d.submission_id=:id - """), {"id": created.submission_id}) is True - immutable_after = (await session.execute(text(""" - SELECT (SELECT to_jsonb(s) FROM public.submissions s WHERE s.id=:prior), - (SELECT to_jsonb(m) FROM public.task_post_submit_routing_manifests m WHERE m.id=:cause), - (SELECT to_jsonb(r) FROM public.checker_results r WHERE r.id=:result) - """), {"prior": predecessor_id, "cause": source_id, - "result": h.completion.reference.result_id})).one() - assert immutable_after == immutable_before + assert await session.scalar(text( + "SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d WHERE d.submission_id=:id" + ), {"id": submission_id}) is True + assert await session.scalar(text("SELECT count(*) FROM public.submissions")) == 2 + assert await session.scalar(text( + "SELECT count(*) FROM public.submission_intake_operations WHERE idempotency_key=:key" + ), {"key": UUID(headers["Idempotency-Key"])}) == 1 await no_economic_effects(session) - async with h.factory() as session: - assert await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(creation) == created + assert await _replacement_history(h, source_id, predecessor_id) == immutable_before async def test_replacement_without_routed_cause_denied_before_bytes( @@ -521,34 +498,31 @@ async def traced_load(self, task_context): async def test_replacement_dispatch_sql_rejects_cause_and_receipt_substitution( - tmp_path, isolated_database_env, + tmp_path, isolated_database_env, monkeypatch, ): + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.submission_dispatch.test_revision_capacity import ( + _revision_http_runtime, _revision_upload_headers, + ) + from tests.tasks.test_public_submission_intake import _client + async with remediation_source(tmp_path, isolated_database_env) as h: source_id = await _fixture_revision_context(h) - request = _replacement_request( - h, revision_archive(h.data), predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ) - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, h.actor_context, request, - ) - async with h.factory() as session: - created = await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(SubmissionCreationRequest( - task_id=h.request.task_id, - assignment_id=h.request.assignment_id, - contributor_id=h.actor_context.actor_profile_id, - predecessor_submission_id=h.created.submission_id, - admission_id=admission_id, - summary=request.summary, - contributor_attestation=request.contributor_attestation, - )) + data = revision_archive(h.data) + async with _client(h, monkeypatch, isolated_database_env) as client: + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + response = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=_revision_upload_headers(h), content=data) + assert response.status_code == 202, response.text + assert len(calls) == 1 and not errors, errors + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(response.json()["operation_id"]), store=h.store.wrapped, + namespace=h.namespace, settings=settings)) async with h.factory() as session: dispatch_body = await session.scalar(text( "SELECT to_jsonb(d) FROM public.submission_dispatches d WHERE submission_id=:id" - ), {"id": created.submission_id}) + ), {"id": submission_id}) assert dispatch_body["checker_remediation_manifest_id"] == str(source_id) validate = text( "SELECT public.submission_dispatch_valid(" From b6c3452c188b6cef1ecea3eec5c47f790e998917 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 13:18:33 +0100 Subject: [PATCH 213/513] fix(tasks): fence historical checker work during accepted handoff --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 57 +++ backend/alembic/env.py | 3 +- ...0086_pending_submission_checker_custody.py | 30 ++ .../post_submit_routing/evaluation_guard.py | 4 + backend/tests/conftest.py | 2 +- .../test_submission_predecessor_custody.py | 324 ++++++++---------- 6 files changed, 246 insertions(+), 174 deletions(-) create mode 100644 backend/alembic/versions/0086_pending_submission_checker_custody.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a6c014b57..929f19984 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7466,3 +7466,60 @@ substitution refusals. Ruff, test-structure, record and whitespace gates pass. Shared worktree proof overa29886861, not clean-commit/independent execution. Scope is test cutover, so roadmap capability/readiness claims do not change. Remaining old preparation/creation consumers and full qualification remain explicit work. + +Next bounded predecessor batch removes this module's last hidden creation-command +consumers: foreign predecessor denial and replacement-versus-successor locking. +Use public raw ZIP with a forbidden upload/body to prove foreign lineage rejects +before ART effects, then valid T4/T5 for the retained foreign-cause SQL refusal. +Move the lock race to a real staged T4 root: a successor evaluation of the old +Submission must wait on TASK, then be refused once the new intake is accepted +and pending T5; afterwards T5 must create one valid consumed dispatch. Preserve +all original cross-task/assignment/actor/predecessor denials, exact blocker PID, +old checker-fence/run/routing immutability and final counts. Allowed: this test +module, an existing fixture helper if needed, and this record. No production or +SQL changes assumed; diagnose any concrete reproduced gap before expanding scope. +QA and architecture/security review required; both PG cases and static gates, +same PR708. Shared old preparation helpers remain until their consumers migrate. + +Custody v1 passed foreign denial and failed the real post-T4 successor race +(1pass1fail75.83s/schema0085/cleanup complete): the old-source reservation did +not raise. This reproduces A13, not a test timeout. Expand scope to TASK's +post_submit_routing/evaluation_guard.py and migration0086 with normal Alembic +head/fingerprint integration. While TASK is evaluation_pending with an active +intake pointer, a non-evaluation_pending latest attempt is historical and cannot +start a new evaluation. Return False after exact scope validation to preserve +stored replay. Receiving/PRE remains needs_revision and can still observe fence +changes; T5 inserts its new evaluation_pending attempt before its own reservation. +0049 requires that initial attempt state and forbids needs_revision resurrection. +Mirror the predicate in the existing checker INSERT trigger under TASK lock; no +cross-owner private read, new state, service authority or timeout. Add exact replay +and forced-stale TASK reader SQL-denial controls, plus prior fence immutability. +Existing staged T4/T5 race is the regression, with prior PRE stale-fence case as +control. QA/architecture review must verify the initial T5 path stays allowed. + +0086 schema probe passed with complete database/MinIO cleanup. Reversing only +the new function predicate restored the exact full 0085 catalog fingerprint; +transaction rollback restored the measured 0086 fingerprint +`b04738514ef38518dc476645c9a9b381d8d893387090b6f8479a1802cc61e3a9`. +Evidence: /tmp/submission-0086-schema-parity.log/.json. Pin this measured catalog +before the focused custody race, historical replay and PRE fence controls. + +Custody v2: 3 passed, 1 failed in 229.56s. The real successor race now refuses +correctly and historical replay passes. The SQL negative control expected a raw +IntegrityError, but the existing CHECKERS coordinator translates it to +CheckerRequestConflict. Correct the test to inspect its retained exception +context for the exact SQLSTATE/constraint; no production change. Rerun only this +failed case; the other three controls passed on unchanged product/schema content. +Module/authorization boundaries passed 92 checks; test-structure and Ruff pass. + +Custody v3 passed the corrected race case in 45.03s on schema0086 with complete +database/MinIO cleanup (/tmp/submission-predecessor-custody-v3.log/.json). It proves +TASK lock serialization, old-source successor refusal, exact historical replay, +named SQL refusal under a stale application reader, unchanged predecessor facts +and real T5 success. The other three unchanged controls passed in v2; do not +describe all four as rerun after the assertion repair. The existing synthetic +next_request Pydantic warning remains visible. Shared precommit worktree proof +over9b9467653, not an independent or clean-commit execution. QA and ARCH/SEC +inspected the exception translation assertion and found no weakening. This is +A13 handoff protection only; full acceptance/provider/CI qualification remains +open, with the same single draft PR708 and no merge-readiness claim. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index e8aaf4d58..6c5c71836 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0085_revision_deadline_error" +_CURRENT_HEAD_REVISION = "0086_pending_checker_custody" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -139,6 +139,7 @@ def do_run_migrations(connection: Connection) -> None: ("0082_policy_phase_cardinality",), ("0083_accepted_revision",), ("0084_submission_source_binding",), + ("0085_revision_deadline_error",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0086_pending_submission_checker_custody.py b/backend/alembic/versions/0086_pending_submission_checker_custody.py new file mode 100644 index 000000000..0ae06bd64 --- /dev/null +++ b/backend/alembic/versions/0086_pending_submission_checker_custody.py @@ -0,0 +1,30 @@ +"""Keep old attempts historical while an accepted replacement awaits finalization.""" +from alembic import op +from sqlalchemy import text + +revision = "0086_pending_checker_custody" +down_revision = "0085_revision_deadline_error" +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.workstream_tasks, public.submissions, public.checker_runs " + "IN ACCESS EXCLUSIVE MODE") + body = op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_functiondef('public.require_new_checker_task_stamps()'::regprocedure)" + )).scalar_one() + anchor = "THEN RAISE EXCEPTION 'checker task context differs' USING ERRCODE='23514'; END IF;" + if body.count(anchor) != 1: + raise RuntimeError("checker pending-custody predecessor changed") + op.execute(body.replace(anchor, anchor + """ + IF t.status='evaluation_pending' AND t.active_submission_operation_id IS NOT NULL + AND s.attempt_status<>'evaluation_pending' THEN + RAISE EXCEPTION 'accepted submission supersedes checker target' + USING ERRCODE='23514', CONSTRAINT='ck_checker_pending_submission_current'; + END IF;""")) + + +def downgrade(): + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/modules/tasks/post_submit_routing/evaluation_guard.py b/backend/app/modules/tasks/post_submit_routing/evaluation_guard.py index 4f531cff0..88eb9cec8 100644 --- a/backend/app/modules/tasks/post_submit_routing/evaluation_guard.py +++ b/backend/app/modules/tasks/post_submit_routing/evaluation_guard.py @@ -101,6 +101,10 @@ async def lock_evaluation_scope(self, request: PostSubmissionExecutionRequest) - and _context_matches(request, facts.context) ): raise CheckerExecutionUnavailable("checker_reservation_scope_unavailable") + if (task.status == "evaluation_pending" and task.active_submission_operation_id is not None + and latest.attempt_status != "evaluation_pending"): + # Accepted replacement owns current work until T5 inserts its new attempt. + return False if task.status in {"accepted", "rejected"}: return False if task.status not in { diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index b92eb623a..abb4f21fa 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "4dd5956392e13454b03eccbe6001ad4f8251a88934539465ea9bc0b049cd4844" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "b04738514ef38518dc476645c9a9b381d8d893387090b6f8479a1802cc61e3a9" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index b20033505..52b377af5 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -18,7 +18,6 @@ from sqlalchemy.exc import DBAPIError, IntegrityError from starlette.requests import Request -from app.api.deps.authorization import compose_hidden_submission_creation_command from app.adapters.checkers import evaluation_coordinator from app.adapters.artifacts import get_submission_bundle_preparation_command from app.adapters.tasks import task_post_submit_outcome @@ -45,13 +44,11 @@ ) from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.checkers.api.execution import CheckerExecutionUnavailable -from app.modules.tasks.api import SubmissionCreationRequest from app.modules.tasks.api.submission_context import ( TaskSubmissionContextRequest, TaskSubmissionContextUnavailable, ) from app.modules.tasks.models import SubmissionDispatch -from app.modules.tasks.submission_context import TaskSubmissionContextService from app.adapters.tasks import task_submission_context_port from tests.auth_concurrency_support import wait_for_named_database_lock from tests.artifact_store_helpers import artifact_byte_stream @@ -836,16 +833,16 @@ async def observed_commit(): async def test_foreign_predecessor_stops_at_task_context_before_art_effects( - tmp_path, - isolated_database_env, - monkeypatch, + tmp_path, isolated_database_env, monkeypatch, ): - provider_writes = _trace_provider_writes(monkeypatch) + from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.test_public_submission_intake import _client + async with remediation_source(tmp_path / "local", isolated_database_env) as local: async with remediation_source( - tmp_path / "foreign", - isolated_database_env, - provision_services=False, + tmp_path / "foreign", isolated_database_env, provision_services=False, storage_settings=local.settings, ) as foreign: await _assert_dispatch_valid(local) @@ -853,86 +850,60 @@ async def test_foreign_predecessor_stops_at_task_context_before_art_effects( local_source = await _fixture_revision_context(local) foreign_source = await _fixture_revision_context(foreign) async with local.factory.begin() as session: - contexts = task_submission_context_port(session) - own = _context_request(local) - assert (await contexts.lock_submission_context( - own - )).checker_remediation_manifest_id == local_source + contexts, own = task_submission_context_port(session), _context_request(local) + assert (await contexts.lock_submission_context(own)).checker_remediation_manifest_id == local_source for field, value in ( - ("task_id", foreign.request.task_id), - ("assignment_id", foreign.request.assignment_id), + ("task_id", foreign.request.task_id), ("assignment_id", foreign.request.assignment_id), ("contributor_id", foreign.actor_context.actor_profile_id), ("predecessor_submission_id", foreign.created.submission_id), ): with pytest.raises(TaskSubmissionContextUnavailable): await contexts.lock_submission_context(replace(own, **{field: value})) - provider_writes.clear() - baseline = await _snapshot(local) - - async def forbidden_load(*_args, **_kwargs): - pytest.fail("foreign predecessor reached ART predecessor loading") - - original_load = PreparedSubmissionBundlePreparationCommand._load_predecessor - monkeypatch.setattr( - PreparedSubmissionBundlePreparationCommand, - "_load_predecessor", - forbidden_load, - ) - request = _replacement_request( - local, - revision_archive(local.data), - predecessor_id=foreign.created.submission_id, - idempotency_key=new_record_id(), - ) - with pytest.raises( - SubmissionBundlePreparationRejected, - match="submission_bundle_preparation_context_changed", - ): - await _prepare(local, request) - assert await _snapshot(local) == baseline - assert provider_writes == [] - monkeypatch.setattr( - PreparedSubmissionBundlePreparationCommand, - "_load_predecessor", - original_load, - ) - - changed_data = revision_archive(local.data) - admission_id = await _verified_admission( - local.factory, local.store, local.namespace, local.settings, - local.actor_context, - _replacement_request( - local, changed_data, predecessor_id=local.created.submission_id, - idempotency_key=new_record_id(), - ), - ) - async with local.factory() as session: - created = await compose_hidden_submission_creation_command( - session, local.actor_context, request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(SubmissionCreationRequest( - task_id=local.request.task_id, - assignment_id=local.request.assignment_id, - contributor_id=local.actor_context.actor_profile_id, - predecessor_submission_id=local.created.submission_id, - admission_id=admission_id, - summary=local.creation_request.summary, - contributor_attestation=local.creation_request.contributor_attestation, - )) + writes = _trace_provider_writes(monkeypatch, operations=( + "begin_source_upload", "upload_source_part", "complete_source_upload", "put", "observe_put_result")) + data = revision_archive(local.data) + async with _client(local, monkeypatch, isolated_database_env) as client: + settings, errors, calls = await _revision_http_runtime( + local, client, tmp_path / "local", monkeypatch, data) + baseline = await _snapshot(local) + async with local.factory() as session: + intake_before = await session.scalar(text("SELECT count(*) FROM public.submission_intake_operations")) + async def forbidden_upload(*_args, **_kwargs): + pytest.fail("foreign predecessor reached ART upload") + headers = _revision_upload_headers(local) + with monkeypatch.context() as guard: + guard.setattr(ForegroundSourceUpload, "receive", forbidden_upload) + refused = await client.post( + f"/api/v1/tasks/{local.request.task_id}/submissions", + headers=headers | {"X-Predecessor-Submission-Id": str(foreign.created.submission_id)}, + content=_forbidden_bytes()) + assert refused.status_code == 409, refused.text + assert refused.json()["error"]["code"] == "task_submission_predecessor_changed" + assert await _snapshot(local) == baseline and writes == [] and calls == [] + async with local.factory() as session: + assert await session.scalar(text("SELECT count(*) FROM public.submission_intake_operations")) == intake_before + accepted = await client.post( + f"/api/v1/tasks/{local.request.task_id}/submissions", + headers=_revision_upload_headers(local), content=data) + assert accepted.status_code == 202, accepted.text + assert len(calls) == 1 and not errors, errors + submission_id = await finalize_retained_intake(local.factory, SimpleNamespace( + operation_id=UUID(accepted.json()["operation_id"]), store=local.store.wrapped, + namespace=local.namespace, settings=settings)) async with local.factory() as session: body = await session.scalar(text( "SELECT to_jsonb(d) FROM public.submission_dispatches d WHERE submission_id=:id" - ), {"id": created.submission_id}) + ), {"id": submission_id}) assert body["checker_remediation_manifest_id"] == str(local_source) validate = text( "SELECT public.submission_dispatch_valid(" - "pg_catalog.jsonb_populate_record(NULL::public.submission_dispatches, " - "CAST(:body AS jsonb)))" + "pg_catalog.jsonb_populate_record(NULL::public.submission_dispatches, CAST(:body AS jsonb)))" ) assert await session.scalar(validate, {"body": json.dumps(body)}) is True assert await session.scalar(validate, {"body": json.dumps( body | {"checker_remediation_manifest_id": str(foreign_source)} )}) is False + await no_economic_effects(session) @pytest.mark.parametrize("outcome", ["infrastructure_failed", "completed"]) @@ -1024,120 +995,129 @@ async def superseding_bytes(): ) +async def _predecessor_fence_snapshot(h, source_id): + """Observe immutable predecessor routing and its current checker generation.""" + async with h.factory() as session: + return (await session.execute(text(""" + SELECT f.current_run_id, + (SELECT count(*) FROM public.checker_runs WHERE submission_id=:prior), + (SELECT to_jsonb(m) FROM public.task_post_submit_routing_manifests m WHERE m.id=:source) + FROM public.checker_submission_fences f WHERE f.submission_id=:prior + """), {"prior": h.created.submission_id, "source": source_id})).one() + + +async def _assert_pending_handoff_checker_guard(h, prior_request, successor, monkeypatch): + """Exact historical replay remains read-only; a stale TASK guard cannot insert.""" + from app.db.errors import integrity_constraint_name + from app.modules.checkers.api.execution import CheckerRequestConflict + from app.modules.tasks.post_submit_routing.evaluation_guard import TaskEvaluationGuard + + replay = await reserve(h, prior_request) + assert replay.attempt_id == h.completion.reference.attempt_id + assert replay.result_id == h.completion.reference.result_id + original = TaskEvaluationGuard.lock_evaluation_scope + async def stale_guard(guard, request): + assert request == successor + assert await original(guard, request) is False + return True + with monkeypatch.context() as patch: + patch.setattr(TaskEvaluationGuard, "lock_evaluation_scope", stale_guard) + with pytest.raises(CheckerRequestConflict) as denied: + await reserve(h, successor) + database_error = denied.value.__context__ + assert isinstance(database_error, IntegrityError) + assert database_error.orig.sqlstate == "23514" + assert integrity_constraint_name(database_error) == "ck_checker_pending_submission_current" + + async def test_replacement_holds_task_custody_against_successor_generation( tmp_path, isolated_database_env, monkeypatch, ): + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.submission_dispatch.test_revision_expiry import _wait_for_staged_submission + from tests.tasks.test_public_submission_intake import _client + async with remediation_source(tmp_path, isolated_database_env) as h: source_id = await _fixture_revision_context(h) - request = _replacement_request( - h, revision_archive(h.data), predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ) - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, h.actor_context, request, - ) - creation = SubmissionCreationRequest( - task_id=h.request.task_id, assignment_id=h.request.assignment_id, - contributor_id=h.actor_context.actor_profile_id, - predecessor_submission_id=h.created.submission_id, - admission_id=admission_id, summary=request.summary, - contributor_attestation=request.contributor_attestation, - ) + prior_request = h.request successor = await next_request(h) - async with h.factory() as session: - prior = (await session.execute(text(""" - SELECT f.current_run_id, - (SELECT count(*) FROM public.checker_runs WHERE submission_id=:prior), - (SELECT to_jsonb(m) FROM public.task_post_submit_routing_manifests m - WHERE m.id=:source) - FROM public.checker_submission_fences f WHERE f.submission_id=:prior - """), {"prior": h.created.submission_id, "source": source_id})).one() - + prior = await _predecessor_fence_snapshot(h, source_id) held, release = asyncio.Event(), asyncio.Event() - creator_pid: list[int] = [] - original = TaskSubmissionContextService.lock_submission_context - - async def pause_after_real_context(service, selected): - facts = await original(service, selected) - if service._session.info.get("replacement_race"): - assert facts.checker_remediation_manifest_id == source_id - creator_pid.append(await service._session.scalar(text("SELECT pg_backend_pid()"))) - held.set() - await asyncio.wait_for(release.wait(), 30) - return facts - - async def create_replacement(): - async with h.factory() as session: - session.info["replacement_race"] = True - return await compose_hidden_submission_creation_command( - session, h.actor_context, request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(creation) + creator_pid, operations = [], [] + original = ForegroundIntakeAdmission._accept_new - waiter_name = "replacement-successor-" + new_record_id().hex + async def pause_staged_acceptance(admission, session, authority, repository, row, owner, *args): + result = await original(admission, session, authority, repository, row, owner, *args) + await session.flush() + assert row.state == "finalization_pending" + creator_pid.append(await session.scalar(text("SELECT pg_backend_pid()"))) + operations.append(owner.operation_id) + held.set() + await asyncio.wait_for(release.wait(), 30) + return result + waiter_name = "replacement-successor-" + new_record_id().hex async def reserve_successor(): async with h.factory() as session, session.begin(): - await session.execute(text( - "SELECT set_config('application_name',:name,true)" - ), {"name": waiter_name}) + await session.execute(text("SELECT set_config('application_name',:name,true)"), {"name": waiter_name}) return await evaluation_coordinator(session).reserve_current_evaluation(successor) - with monkeypatch.context() as patch: - patch.setattr(TaskSubmissionContextService, "lock_submission_context", pause_after_real_context) - creator = asyncio.create_task(create_replacement()) - waiter = None - try: - await asyncio.wait_for(held.wait(), 30) - waiter = asyncio.create_task(reserve_successor()) - await asyncio.wait_for(wait_for_named_database_lock( - isolated_database_env, waiter_name, expected_blocker_pid=creator_pid[0], - ), 15) - async with h.factory() as observer: - waiting_query = await observer.scalar(text( - "SELECT query FROM pg_stat_activity " - "WHERE application_name=:name AND wait_event_type='Lock'" - ), {"name": waiter_name}) - assert waiting_query is not None and "workstream_tasks" in waiting_query - assert not waiter.done() - release.set() - created = await asyncio.wait_for(creator, 60) - with pytest.raises( - CheckerExecutionUnavailable, match="checker_reservation_scope_unavailable", - ): - await asyncio.wait_for(waiter, 30) - finally: - release.set() - for pending in (creator, waiter): - if pending is not None and not pending.done(): - pending.cancel() - await asyncio.gather( - *(pending for pending in (creator, waiter) if pending is not None), - return_exceptions=True, - ) - - assert created.submission_version == 2 + data = revision_archive(h.data) + async with _client(h, monkeypatch, isolated_database_env) as client: + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + with monkeypatch.context() as patch: + patch.setattr(ForegroundIntakeAdmission, "_accept_new", pause_staged_acceptance) + creator = asyncio.create_task(client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=_revision_upload_headers(h), content=data)) + waiter = None + try: + await _wait_for_staged_submission(held, creator, timeout=60) + waiter = asyncio.create_task(reserve_successor()) + await asyncio.wait_for(wait_for_named_database_lock( + isolated_database_env, waiter_name, expected_blocker_pid=creator_pid[0]), 15) + async with h.factory() as observer: + waiting_query = await observer.scalar(text( + "SELECT query FROM pg_stat_activity WHERE application_name=:name AND wait_event_type='Lock'" + ), {"name": waiter_name}) + assert waiting_query is not None and "workstream_tasks" in waiting_query + assert not waiter.done() + release.set() + accepted = await asyncio.wait_for(creator, 60) + assert accepted.status_code == 202, accepted.text + with pytest.raises(CheckerExecutionUnavailable, match="checker_reservation_scope_unavailable"): + await asyncio.wait_for(waiter, 30) + finally: + release.set() + for pending in (creator, waiter): + if pending is not None and not pending.done(): + pending.cancel() + await asyncio.gather(*(pending for pending in (creator, waiter) if pending is not None), return_exceptions=True) + assert len(calls) == 1 and not errors, errors + await _assert_pending_handoff_checker_guard(h, prior_request, successor, monkeypatch) + assert await _predecessor_fence_snapshot(h, source_id) == prior async with h.factory() as session: - after = (await session.execute(text(""" - SELECT f.current_run_id, - (SELECT count(*) FROM public.checker_runs WHERE submission_id=:prior), - (SELECT to_jsonb(m) FROM public.task_post_submit_routing_manifests m - WHERE m.id=:source) - FROM public.checker_submission_fences f WHERE f.submission_id=:prior - """), {"prior": h.created.submission_id, "source": source_id})).one() - assert after == prior + operation = await session.get(SubmissionIntakeOperation, operations[0]) + assert operation.state == "finalization_pending" and operation.finalized_submission_id is None assert await session.scalar(text( "SELECT count(*) FROM public.submissions WHERE task_id=:task" - ), {"task": h.request.task_id}) == 2 - assert await session.scalar(text( - "SELECT count(*) FROM public.submission_dispatches WHERE task_id=:task" - ), {"task": h.request.task_id}) == 2 - assert await session.scalar(text( - "SELECT public.submission_dispatch_valid(d) " - "FROM public.submission_dispatches d WHERE d.submission_id=:id" - ), {"id": created.submission_id}) is True - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) + ), {"task": h.request.task_id}) == 1 + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=operations[0], store=h.store.wrapped, namespace=h.namespace, settings=settings)) + async with h.factory() as session: + operation = await session.get(SubmissionIntakeOperation, operations[0]) + admission = await session.get(SubmissionBundleAdmission, operation.finalized_admission_id) assert admission.status == "consumed" + for table in ("submissions", "submission_dispatches"): + assert await session.scalar(text(f"SELECT count(*) FROM public.{table} WHERE task_id=:task"), + {"task": h.request.task_id}) == 2 assert await session.scalar(text( - "SELECT status FROM public.workstream_tasks WHERE id=:task" - ), {"task": h.request.task_id}) == "evaluation_pending" + "SELECT public.submission_dispatch_valid(d) FROM public.submission_dispatches d WHERE d.submission_id=:id" + ), {"id": submission_id}) is True + assert await session.scalar(text("SELECT status FROM public.workstream_tasks WHERE id=:task"), + {"task": h.request.task_id}) == "evaluation_pending" + await no_economic_effects(session) + assert await _predecessor_fence_snapshot(h, source_id) == prior From d627bfffc82a48a3020f709c4e98917b76e59466 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 13:39:58 +0100 Subject: [PATCH 214/513] test(migrations): enforce retained policy refusal through public intake --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 63 +++++++++++++++ backend/tests/test_alembic.py | 78 +++++++++++++++---- 2 files changed, 128 insertions(+), 13 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 929f19984..b764b2f10 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7523,3 +7523,66 @@ over9b9467653, not an independent or clean-commit execution. QA and ARCH/SEC inspected the exception translation assertion and found no weakening. This is A13 handoff protection only; full acceptance/provider/CI qualification remains open, with the same single draft PR708 and no merge-readiness claim. + +Next bounded migration proof: replace the post-upgrade hidden creation call in +`test_revision_upgrade_retains_policy_source_and_running_window` with public +raw ZIP, real PRE/T4 and durable OUTBOX/T5. Preserve genuine guarded 0047 source +creation, whole retained-row equality across upgrade, unchanged policy/window +and historical routing evidence afterward. Assert accepted operation, one PRE, +consumed source-backed admission and valid v2 dispatch. Allowed files: this +record and backend/tests/test_alembic.py; existing fixture correction only if +a concrete mismatch is diagnosed. No product/schema changes or disabling guards. +Risk: migration/lineage proof; QA/test-delta and architecture/security reviewers. +Run this PostgreSQL migration case plus Ruff/structure/record gates. Human focus +is historical evidence preserved while only new work uses current submission. +The older 0047 cap fixture still uses shared preparation helpers before upgrade; +do not delete those helpers until that historical fixture has a retained-data +replacement. Same draft PR708; full qualification remains open. + +Retained-window v1 reached the new public call after successful 0047-to-0086 +upgrade/history checks but returned infrastructure503 (137.58s). No private +diagnostic appeared in the public envelope. Add failure-only PRE terminal code +and controlled runtime diagnostics to the test before rerunning; do not change +production behavior or replace this historical lineage with a fresh fixture. + +The v2 diagnostic shows no runtime call and no new PRE terminal; the archived +0047 policy has `compiled_bundle.entries=[]`. Specification section 20.2 (line1135) +explicitly requires an incompatible locked task to remain blocked pending a +governed rebase/re-release, never silently relocked. Therefore successful new +submission is an obsolete expectation of this particular historical fixture, +not a product defect to bypass. Correct the bounded proof to preserve its +window/history checks and require exact cardinality denial through public HTTP +before body/provider/PRE, with no intake or creation effects. Compatible new +revision acceptance/T5 remains covered by the prior raw-ZIP revision tests. +No policy mutation, historical evidence deletion, or production exception. + +V3 confirms exact `IntakeCustodyConflict('intake_requires_one_pre_and_post_checker')` +before runtime, rather than an unknown infrastructure fault (183.69s; cleanup +complete). V4 executes the corrected refusal proof with exact before/after +intake, source-charge, historical PRE, audit and full creation snapshots; body +and source-upload callbacks must not execute. Public503 remains the existing +generic mapping, not an actionable rebase-message claim. No successful migration +T5 claim applies to this zero-PRE fixture. QA and ARCH/SEC independently verified +its pinned archive and specification20.2 before approving the expectation change. + +Reviewers found a snapshot SQL defect: source charges use operation_id, not id. +Use explicit table/key pairs for deterministic before/after comparison. This +changes only the snapshot query; no product behavior or refusal assertion. V4 +was already running the earlier query; final proof must use corrected V5. + +Stopped the confirmed-live V4 pytest child with SIGTERM after the reviewer +identified its invalid snapshot query, saving an unnecessary full historical +rebuild. The isolated runner completed cleanup. V4 is interrupted, not passing +evidence or a timeout. Launch V5 only after that authoritative termination. + +Final retained-window V5 passed1 in138.42s at schema0086; database and MinIO +cleanup complete (/tmp/submission-retained-window-v5.log/.json). Genuine0047 +window creation and upgrade/history equality remain proved; current public +intake refuses the incompatible zero-PRE lock with the exact cardinality cause, +without reading body, uploading, invoking PRE or changing intake/charge/PRE/ +audit/creation facts. Ruff, structure, record and whitespace gates pass. Shared +frozen-worktree evidence overb6c3452c1, not clean-head or native-provider proof. +This removes the post-upgrade hidden-create consumer from test_alembic; the +before-upgrade cap fixture still needs its historical writer replacement. +No capability/readiness claim changed; full cleanup/provider/CI and acceptance +audit remain open under the same goal and draft PR708. diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 4af7b0602..418f00faa 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -1372,13 +1372,74 @@ async def seed_old_proof(factory, namespace_fingerprint): await engine.dispose() -async def test_revision_upgrade_retains_policy_source_and_running_window( +async def _assert_upgraded_incompatible_revision_blocked(h, tmp_path, database_url, monkeypatch): + """Preserve zero-PRE history without admitting new work under incompatible locks.""" + from sqlalchemy import text + from app.adapters.artifacts import ConfiguredSubmissionCommand + from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload + from app.modules.artifacts.intake.repository import IntakeCustodyConflict + from tests.tasks.post_submit_routing.support import revision_archive + from tests.tasks.submission_dispatch.test_replacement_creation import _creation_snapshot + from tests.tasks.submission_dispatch.test_revision_capacity import ( + _revision_http_runtime, _revision_upload_headers, + ) + from tests.tasks.test_public_submission_intake import _client + + async def intake_snapshot(): + async with h.factory() as session: + return tuple([await session.scalar(text( + f"SELECT jsonb_agg(to_jsonb(r) ORDER BY {key}) FROM public.{table} r" + )) for table, key in (("submission_intake_operations", "id"), + ("submission_source_charges", "operation_id"), + ("selected_pre_submit_runs", "id"), ("audit_events", "id"))]) + + async def forbidden_body(): + pytest.fail("incompatible locked policy consumed the request body") + yield b"unreachable" + + async def forbidden_upload(*args, **kwargs): + pytest.fail("incompatible locked policy reached source upload") + + command_errors, submit = [], ConfiguredSubmissionCommand._submit + async def observe_command(command, *args, **kwargs): + try: + return await submit(command, *args, **kwargs) + except IntakeCustodyConflict as exc: + command_errors.append(str(exc)) + raise + + async with h.factory() as session: + policy = await session.scalar(text(""" + SELECT p.compiled_bundle FROM public.pre_submit_checker_policies p + JOIN public.workstream_tasks t ON t.locked_pre_submit_checker_policy_id=p.id + WHERE t.id=:task + """), {"task": h.request.task_id}) + assert policy["entries"] == [] + async with _client(h, monkeypatch, database_url) as client: + _, errors, calls = await _revision_http_runtime( + h, client, tmp_path, monkeypatch, revision_archive(h.data)) + before, creation = await intake_snapshot(), await _creation_snapshot(h) + with monkeypatch.context() as patch: + patch.setattr(ConfiguredSubmissionCommand, "_submit", observe_command) + patch.setattr(ForegroundSourceUpload, "receive", forbidden_upload) + response = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=_revision_upload_headers(h), content=forbidden_body()) + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "submission_infrastructure_unavailable" + assert command_errors == ["intake_requires_one_pre_and_post_checker"] + assert calls == [] and errors == [] + assert await intake_snapshot() == before + assert await _creation_snapshot(h) == creation + + +async def test_revision_upgrade_retains_window_and_blocks_incompatible_policy( tmp_path, isolated_database_env, migration_lock, monkeypatch, ): - """A genuine guarded 0047 window survives and remains usable on the new head.""" + """A genuine 0047 window survives; incompatible locked policy cannot admit new work.""" from sqlalchemy import select, text from app.adapters.tasks import task_post_submit_outcome from app.modules.tasks.revision.models import TaskRevisionPreparation @@ -1392,12 +1453,6 @@ async def test_revision_upgrade_retains_policy_source_and_running_window( retained_revision_rows, ) from tests.tasks.post_submit_routing.outcome_support import invoked_completion - from tests.tasks.post_submit_routing.support import revision_archive - from tests.tasks.submission_dispatch.test_replacement_creation import ( - _create, - _creation_request, - _ready_replacement, - ) with migration_lock(): await _execute(isolated_database_env, "drop schema public cascade; create schema public") @@ -1454,11 +1509,8 @@ async def test_revision_upgrade_retains_policy_source_and_running_window( assert view.deadline_at == preparation.deadline_at h.revision_preparation_id = preparation.id h.revision_preparation_sha256 = preparation.preparation_sha256 - prepared, admission_id = await _ready_replacement(h, revision_archive(h.data)) - creation = _creation_request(h, prepared, admission_id) - successor = await _create(h, creation) - assert successor.submission_version == 2 - assert successor.submission_id != h.created.submission_id + await _assert_upgraded_incompatible_revision_blocked( + h, tmp_path, isolated_database_env, monkeypatch) async with h.factory() as session: retained = await retained_revision_rows(session, outcome.routing_manifest_id) for owner in ( From 8a854f7a698b662728dfc0b2522774ac7ff50980 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 14:05:28 +0100 Subject: [PATCH 215/513] fix(tasks): cancel unaccepted intake during assignment invalidation --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 66 ++++ backend/app/adapters/artifacts/__init__.py | 4 +- backend/app/adapters/tasks/__init__.py | 6 +- .../artifacts/intake/foreground_admission.py | 18 +- .../artifacts/intake/foreground_command.py | 7 +- .../app/modules/artifacts/intake/progress.py | 1 + .../modules/artifacts/intake/repository.py | 17 + .../tasks/api/assignment_invalidation.py | 8 + .../modules/tasks/assignment_invalidation.py | 6 +- backend/tests/tasks/invalidation_support.py | 75 +--- .../test_revision_expiry_security.py | 4 +- .../tasks/test_assignment_invalidation.py | 7 +- .../test_assignment_invalidation_races.py | 343 +++++++++++++----- 13 files changed, 394 insertions(+), 168 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b764b2f10..fa3efe7ed 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7586,3 +7586,69 @@ This removes the post-upgrade hidden-create consumer from test_alembic; the before-upgrade cap fixture still needs its historical writer replacement. No capability/readiness claim changed; full cleanup/provider/CI and acceptance audit remain open under the same goal and draft PR708. + +Next bounded change migrates assignment-invalidation race proof from hidden +creation to public source intake at T4. Both lock winners must preserve authority: +accepted pending work cannot be released; invalidation-first cannot accept. Run +real PRE before the race, observe exact TASK blocker PID, actual invalidation +handler and actual T5 for accepted winner. Preserve assignment/audit uniqueness, +source custody and no premature Submission. Allowed: test_assignment_invalidation_ +races.py, its sole-use prepare_submission helper in invalidation_support.py, and +this record. Trace helper consumers before removing old preparation imports. +No product or migration change assumed; expand only on reproduced defect. Risk +is authority/workflow/concurrency; QA/test-delta and ARCH/SEC review required. +Verification: both PG race cases, affected shared fixture tests as needed, Ruff, +structure, record and whitespace. Human focus: exact acceptance cutover versus +committed revocation cause, no authority bypass, same PR708 and full goal active. + +Race review found an invalid fixture hook: TASK context reads also use the +repository method patched for the invalidation winner. Restrict that hook to +the uniquely named invalidation coroutine; foreground and heartbeat locks stay +unchanged. Stop V1 known-invalid child and let its runner clean up, then run V2. +Strengthen refusal to exact404/submission_unavailable and no accepted/event facts; +assert sealed bytes stay charged, and bind accepted response to observed intake. +Baseline Ruff fixture-import shadowing is removed by importing the fixture module +and exposing the same fixture objects, with no wrapper or changed fixture scope. + +V2 reproduced production gap: acceptance winner passed, invalidation winner +failed its root commit with23514 `intake task custody mismatch` (1pass1fail +152.41s). Expand allowed scope to TASK assignment-invalidation API/operation, +TASK/ART composition, ART intake repository and foreground terminal/read mapping, +and the direct-constructor test in test_assignment_invalidation.py. Add a required +TASK-owned ART cancellation participant after exact consumed service authority +and event fence, before release. Validate project/task/assignment/actor, initial +in_progress status and unaccepted state; cancel/abandon by DB lease time, bump +generation, clear pointer, preserve charge in the same root. Reuse existing +submission_unavailable error and current-read authorization for late foreground +and replay. Preserve revision expiry mapping. No migration or new authority. +Add rollback after real intake terminalization before release, exact terminal +code/generation and replay/no extra release assertions. Verify both lock winners, +existing invalidation behavior and focused revision-expiry control. + +Rename ART composition to submission_intake_assignment_release_port for both +existing expiry and invalidation participants; update traced expiry-security +test consumer too, with no alias. Add it to allowed files. Expiry still calls +its distinct expire_revision contract; only common terminal read now returns +the exact stored release failure after matching owner/key/metadata/generation. + +QA requested one distinct receiving/no-raw control for the new known-failure +replay branch. Add a real HTTP body gate after upload ownership, invalidate via +existing handler, require404 without receipt or PRE/Submission, retain reserved +bytes, and replay with a forbidden body. Own GET must preserve the known code. +This covers the changed no-raw and progress allowlists separately from sealed +PRE/T4 races. Existing V3 cases remain unchanged; execute added case separately. + +Final focused evidence: invalidation V3 passed4 in512.33s; receiving V1 passed1 +in100.17s. Both schema0086 receipts have complete database/MinIO cleanup +(/tmp/submission-invalidation-race-v3.log/.json and +/tmp/submission-invalidation-receiving-v1.log/.json). V3 proves both exact TASK +lock winners, actual accepted T5, forced post-cancellation rollback, late known +denial/sealed replay, original root/prior-receipt guard and revision-expiry +rollback/late-PRE-after-reclaim. Added receiving case independently proves no-raw +known denial, forbidden replay body, reserved charge and own progress code. +92 module/authorization boundary checks passed in504.63s. Runtime was slower in +the shared busy environment; all runs terminated normally, no timeout credited. +Ruff/record/whitespace pass. Shared precommit proof overd627bfffc, not independent +or clean-head execution. Test-only fixture alias cleanup preserves the same +objects/scopes; it does not change the product evidence. Full goal qualification +and remaining hidden/preparation consumers remain open, same draft PR708. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index d82d26ef8..32383a584 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -936,8 +936,8 @@ def submission_bundle_preparation_reader(session: AsyncSession): return SubmissionBundlePreparationReader(session, runs=selected_pre_submit_run_reader(session)) -def submission_intake_revision_expiry_port(session): - """Bind ART invalidation to the authorized expiry's existing root transaction.""" +def submission_intake_assignment_release_port(session): + """Bind ART cancellation to the authorized TASK release transaction.""" from app.adapters.tasks import intake_task_custody_port from app.modules.artifacts.intake.repository import SubmissionIntakeRepository return SubmissionIntakeRepository(session, intake_task_custody_port(session)) diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py index 3775958cb..9313faf63 100644 --- a/backend/app/adapters/tasks/__init__.py +++ b/backend/app/adapters/tasks/__init__.py @@ -113,6 +113,7 @@ async def __call__(self, envelope): committed_authority_invalidation, ) from app.adapters.outbox import outbox_invocation_fence + from app.adapters.artifacts import submission_intake_assignment_release_port try: async with self._sessions() as session, session.begin(): @@ -123,6 +124,7 @@ async def __call__(self, envelope): causes=committed_authority_invalidation(self._sessions), authorization=self._authorization(session), audit=assignment_invalidation_audit(session), + intake=submission_intake_assignment_release_port(session), ).reconcile(envelope) return outcome except AssignmentInvalidationUnavailable: @@ -139,7 +141,7 @@ def __init__(self, session_factory, *, observer, authorization_factory): async def __call__(self, envelope): from app.adapters.audit import task_revision_expiry_audit - from app.adapters.artifacts import submission_intake_revision_expiry_port + from app.adapters.artifacts import submission_intake_assignment_release_port from app.adapters.outbox import outbox_append, outbox_invocation_fence from app.modules.tasks.api.revision_expiry import TaskRevisionExpiryUnavailable from app.modules.tasks.revision.expiry import TaskRevisionExpiryOperation @@ -151,7 +153,7 @@ async def __call__(self, envelope): fence=outbox_invocation_fence(session), authorization=self._authorization(session), audit=task_revision_expiry_audit(session), - outbox=outbox_append(session), intake=submission_intake_revision_expiry_port(session), + outbox=outbox_append(session), intake=submission_intake_assignment_release_port(session), ).expire(envelope) return outcome except TaskRevisionExpiryUnavailable: diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py index ef6e723d2..07b579e4c 100644 --- a/backend/app/modules/artifacts/intake/foreground_admission.py +++ b/backend/app/modules/artifacts/intake/foreground_admission.py @@ -317,11 +317,11 @@ async def finish(self, owner: IntakeReservationOwner, *, state: str, failure_cod ) return True - async def revision_expired( + async def assignment_release_failure( self, owner: IntakeReservationOwner, metadata: SubmissionIntakeMetadata, *, actor_id: UUID, idempotency_key: UUID, - ) -> bool: - """Resolve an expiry-fenced foreground owner under current read authority.""" + ) -> str | None: + """Resolve a release-fenced foreground owner under current read authority.""" async with self._root() as (session, authority): repository = SubmissionIntakeRepository(session, self._tasks(session)) row = await repository._lock(owner.operation_id) @@ -330,11 +330,12 @@ async def revision_expired( if (row.actor_profile_id != str(actor_id) or row.idempotency_key != str(idempotency_key) or row.metadata_sha256 != metadata.metadata_sha256()): raise IntakeCustodyConflict("submission_idempotency_conflict") - expired = (row.state in {"cancelled", "abandoned"} - and row.failure_code == "revision_deadline_expired" + released = (row.state in {"cancelled", "abandoned"} + and row.failure_code in {"revision_deadline_expired", "submission_unavailable"} and row.lease_id == str(owner.lease_id) and row.lease_generation == owner.generation + 1) - return expired + code = row.failure_code if released else None + return code @staticmethod def _match_acceptance_command(row, request, terminal_digest, *, accepted): @@ -437,7 +438,7 @@ async def replay_failure( return await self._accepted_receipt(session, authority, row) if row.state in {"receiving", "pre_checking"}: raise IntakeCustodyConflict("submission_operation_in_progress") - if (row.raw_sha256 is None or row.raw_byte_count is None) and row.failure_code != "revision_deadline_expired": + if (row.raw_sha256 is None or row.raw_byte_count is None) and row.failure_code not in {"revision_deadline_expired", "submission_unavailable"}: raise IntakeCustodyConflict("submission_operation_terminal") if row.state == "rejected" and row.failure_code == "pre_submission_checker_failed": terminal = await checkers(session).read_source_terminal(source_operation_id=operation_id) @@ -455,6 +456,7 @@ async def replay_failure( code = row.failure_code if row.failure_code in { "submission_packet_invalid", "submission_archive_limit_exceeded", "submission_upload_timeout", "submission_infrastructure_unavailable", "revision_deadline_expired", + "submission_unavailable", } else "submission_operation_terminal" failure = SubmissionIntakeFailure(code) # Commit the current read authorization before returning QC feedback. @@ -471,7 +473,7 @@ async def replay( metadata = SubmissionIntakeMetadata.model_validate(metadata) original = await self._read(metadata, actor_id, idempotency_key) if original.raw_sha256 is None or original.raw_byte_count is None: - if original.state in {"cancelled", "abandoned"} and original.failure_code == "revision_deadline_expired": + if original.state in {"cancelled", "abandoned"} and original.failure_code in {"revision_deadline_expired", "submission_unavailable"}: return original code = "submission_operation_in_progress" if original.state in {"receiving", "pre_checking"} else "submission_operation_terminal" raise IntakeCustodyConflict(code) diff --git a/backend/app/modules/artifacts/intake/foreground_command.py b/backend/app/modules/artifacts/intake/foreground_command.py index 06c09c759..1e218403f 100644 --- a/backend/app/modules/artifacts/intake/foreground_command.py +++ b/backend/app/modules/artifacts/intake/foreground_command.py @@ -124,10 +124,11 @@ async def run(_operation_id, _lease_id, _generation): raise IntakeCommitUnknown("submission terminal outcome is unresolved") from None else: if not finished and not isinstance(exc, asyncio.CancelledError): - if await self._admission.revision_expired( + release_failure = await self._admission.assignment_release_failure( owner, metadata, actor_id=actor_id, idempotency_key=idempotency_key, - ): - raise SubmissionIntakeFailure("revision_deadline_expired") from None + ) + if release_failure is not None: + raise SubmissionIntakeFailure(release_failure) from None raise IntakeCommitUnknown("submission foreground ownership has changed") from None if isinstance(exc, SubmissionUploadTimeout): raise SubmissionIntakeFailure(code) from None diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py index 0e43ef0dc..5b5ff5fe9 100644 --- a/backend/app/modules/artifacts/intake/progress.py +++ b/backend/app/modules/artifacts/intake/progress.py @@ -185,6 +185,7 @@ async def read(self, task_id, selector, *, actor_id): "submission_packet_invalid", "submission_archive_limit_exceeded", "submission_upload_timeout", "submission_infrastructure_unavailable", "pre_submission_checker_failed", "submission_foreground_expired", "submission_operation_cancelled", "revision_deadline_expired", + "submission_unavailable", }: code = "submission_operation_terminal" return SubmissionOperationResponse( diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py index 38d548a5a..63a97dc84 100644 --- a/backend/app/modules/artifacts/intake/repository.py +++ b/backend/app/modules/artifacts/intake/repository.py @@ -29,6 +29,7 @@ from app.modules.artifacts.models import ArtifactStorageNamespace from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort from app.modules.tasks.api.revision_expiry import TaskRevisionExpiryTarget +from app.modules.tasks.api.assignment_invalidation import AssignmentInvalidationTarget from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest @@ -283,6 +284,22 @@ async def expire_revision(self, operation_id: UUID, target: TaskRevisionExpiryTa state = "abandoned" if row.lease_expires_at <= now else "cancelled" await self._terminal(row, state, "revision_deadline_expired") + async def cancel_assignment(self, operation_id: UUID, target: AssignmentInvalidationTarget) -> None: + """End exact initial intake inside the authorized TASK invalidation root.""" + target = AssignmentInvalidationTarget.model_validate(target) + row = await self._lock(operation_id) + metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + if (row.state not in {"receiving", "pre_checking"} + or row.eligible_task_status != "in_progress" + or (row.project_id, row.task_id, row.assignment_id, row.actor_profile_id) != ( + str(target.project_id), str(target.task_id), str(target.assignment_id), str(target.contributor_id)) + or metadata.predecessor_submission_id is not None): + raise IntakeCustodyConflict("assignment_intake_cancellation_mismatch") + await self._tasks.require_active(target.task_id, operation_id) + now = await self._session.scalar(select(func.clock_timestamp())) + state = "abandoned" if row.lease_expires_at <= now else "cancelled" + await self._terminal(row, state, "submission_unavailable") + async def abandon_expired(self, operation_id: UUID) -> bool: """Recovery can end expired foreground custody, never resume or accept it.""" row = await self._lock(operation_id) diff --git a/backend/app/modules/tasks/api/assignment_invalidation.py b/backend/app/modules/tasks/api/assignment_invalidation.py index 1d62bf586..e6ec60052 100644 --- a/backend/app/modules/tasks/api/assignment_invalidation.py +++ b/backend/app/modules/tasks/api/assignment_invalidation.py @@ -28,6 +28,14 @@ class AssignmentInvalidationTarget(BaseModel): authority_invalidation_event_id: UUID +class AssignmentInvalidationIntakePort(Protocol): + """Caller-authorized participant in the fenced assignment release transaction.""" + + async def cancel_assignment(self, operation_id: UUID, target: AssignmentInvalidationTarget) -> None: + """End only this assignment's unaccepted intake and retain source charges.""" + ... + + class AssignmentInvalidationAuthorityFacts(BaseModel): """Complete effect target consumed under TASK and exact-assignment locks.""" diff --git a/backend/app/modules/tasks/assignment_invalidation.py b/backend/app/modules/tasks/assignment_invalidation.py index 474aa8b82..fc7147767 100644 --- a/backend/app/modules/tasks/assignment_invalidation.py +++ b/backend/app/modules/tasks/assignment_invalidation.py @@ -20,6 +20,7 @@ AssignmentInvalidationAuthorityFacts, AssignmentInvalidationAuthorizationPort, AssignmentInvalidationEvidence, + AssignmentInvalidationIntakePort, AssignmentInvalidationTarget, AssignmentInvalidationUnavailable, ) @@ -57,10 +58,11 @@ def __init__( causes: AuthorityInvalidationPort, authorization: AssignmentInvalidationAuthorizationPort, audit: AssignmentInvalidationAuditPort, + intake: AssignmentInvalidationIntakePort, ): self._session, self._repo = session, TaskRepository(session) self._observer, self._fence, self._causes = observer, fence, causes - self._authorization, self._audit = authorization, audit + self._authorization, self._audit, self._intake = authorization, audit, intake async def reconcile(self, envelope: OutboxEventEnvelope) -> HandlerOutcome: """Never commit; the handler acknowledges only after its root commit.""" @@ -143,6 +145,8 @@ async def reconcile(self, envelope: OutboxEventEnvelope) -> HandlerOutcome: raise AssignmentInvalidationUnavailable( "assignment reconciliation custody unavailable" ) + if task.active_submission_operation_id is not None: + await self._intake.cancel_assignment(UUID(task.active_submission_operation_id), target) assignment.status, assignment.released_at = "authority_revoked", custody.observed_at task.status, task.assigned_to = "ready", None await self._audit.record_release( diff --git a/backend/tests/tasks/invalidation_support.py b/backend/tests/tasks/invalidation_support.py index 9ee91eea2..8afb9a27e 100644 --- a/backend/tests/tasks/invalidation_support.py +++ b/backend/tests/tasks/invalidation_support.py @@ -289,65 +289,22 @@ async def snapshot(s): return dict(task), [dict(row) for row in assignments], [dict(row) for row in events] -async def prepare_submission(s, settings): - """Prepare real ZIP custody for the existing assignment before invalidation.""" - from app.modules.artifacts.api import SubmissionBundlePreparationRequest - from app.modules.authorization.api import ActorIdentityFacts, ActorKind +async def submission_packet(s): + """Build raw bytes and headers for the claimed task without preparing old custody.""" from app.modules.projects.models import EffectiveProjectSubmissionArtifactPolicy - from app.modules.tasks.api import SubmissionCreationRequest - from tests.tasks.submission_lineage_support import _seed_services, _verified_admission - from tests.test_artifact_admission import _namespace, _local_store, _context - from tests.archive_fixtures import byte_source as _bytes, submission_archive as _archive + from tests.archive_fixtures import submission_archive from tests.test_tasks import complete_submission_payload - context = _context( - actor_profile_id=UUID(s.grant["actor_profile_id"]), identity_link_id=UUID(s.link_id) - ) - namespace = _namespace(settings) - bootstrap, store = _local_store(settings, namespace) - try: - async with s.sessions() as session: - task = await session.get(WorkstreamTask, s.task["id"]) - policy = await session.get( - EffectiveProjectSubmissionArtifactPolicy, - task.locked_effective_project_submission_artifact_policy_id, - ) - body = policy.effective_policy - assert [item["path"] for item in body["required_artifacts"]] == ["answer.md"] - assert [item["key"] for item in body["required_evidence"]] == ["required-evidence-001"] - await _seed_services(s.sessions) - request = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - context.actor_profile_id, context.identity_link_id, ActorKind.HUMAN - ), - request_id=context.request_id, - correlation_id=context.correlation_id, - task_id=UUID(s.task["id"]), - assignment_id=UUID(s.assignment["id"]), - predecessor_submission_id=None, - idempotency_key=new_record_id(), - summary="Completed the required project work and included evidence.", - contributor_attestation=( - complete_submission_payload()["worker_attestation"] - + " " - + " ".join(body["attestation_terms"]) - ), - media_type="application/zip", - byte_source=_bytes( - _archive(path="answer.md", evidence_path="evidence/required-evidence-001") - ), - ) - admission_id = await _verified_admission( - s.sessions, store, namespace, settings, context, request - ) - return context, SubmissionCreationRequest( - task_id=request.task_id, - assignment_id=request.assignment_id, - contributor_id=context.actor_profile_id, - predecessor_submission_id=None, - admission_id=admission_id, - summary=request.summary, - contributor_attestation=request.contributor_attestation, - ) - finally: - bootstrap.close() + async with s.sessions() as session: + task = await session.get(WorkstreamTask, s.task["id"]) + policy = await session.get(EffectiveProjectSubmissionArtifactPolicy, + task.locked_effective_project_submission_artifact_policy_id) + body = policy.effective_policy + assert [item["path"] for item in body["required_artifacts"]] == ["answer.md"] + assert [item["key"] for item in body["required_evidence"]] == ["required-evidence-001"] + return submission_archive(path="answer.md", evidence_path="evidence/required-evidence-001"), { + "Content-Type": "application/zip", "X-Task-Assignment-Id": s.assignment["id"], + "X-Submission-Summary": "Completed the required project work and included evidence.", + "X-Contributor-Attestation": complete_submission_payload()["worker_attestation"] + + " " + " ".join(body["attestation_terms"]), + } diff --git a/backend/tests/tasks/submission_dispatch/test_revision_expiry_security.py b/backend/tests/tasks/submission_dispatch/test_revision_expiry_security.py index 4231b5859..d45a9134b 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_expiry_security.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_expiry_security.py @@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.adapters.audit import task_revision_expiry_audit -from app.adapters.artifacts import submission_intake_revision_expiry_port +from app.adapters.artifacts import submission_intake_assignment_release_port from app.adapters.auth import revision_expiry_authorization from app.adapters.outbox import outbox_append, outbox_invocation_fence from app.adapters.tasks import task_revision_recovery @@ -108,7 +108,7 @@ def _expiry_operation(h, session): fence=outbox_invocation_fence(session), authorization=revision_expiry_authorization(session), audit=task_revision_expiry_audit(session), outbox=outbox_append(session), - intake=submission_intake_revision_expiry_port(session), + intake=submission_intake_assignment_release_port(session), ) diff --git a/backend/tests/tasks/test_assignment_invalidation.py b/backend/tests/tasks/test_assignment_invalidation.py index 3984b0ae8..d5943c2ec 100644 --- a/backend/tests/tasks/test_assignment_invalidation.py +++ b/backend/tests/tasks/test_assignment_invalidation.py @@ -24,7 +24,7 @@ set_dev_actor, admit_and_grant_project_submitter, ) -from tests.test_tasks import task_client as task_client, task_database_env as task_database_env +from tests import test_tasks as task_fixtures from tests.tasks.invalidation_support import ( TracedFeatureAuthority, setup_assignment, @@ -34,6 +34,9 @@ ) +task_client = task_fixtures.task_client +task_database_env = task_fixtures.task_database_env + @pytest.mark.parametrize("kind", ["grant", "suspend", "deactivate", "link"]) async def test_exact_real_cause_releases_only_pre_submit_assignment( task_client, monkeypatch, kind @@ -353,6 +356,7 @@ async def test_release_requires_root_transaction_and_exact_prior_receipt(task_cl from types import SimpleNamespace from app.adapters.audit import assignment_invalidation_audit, committed_authority_invalidation from app.adapters.outbox import outbox_invocation_fence + from app.adapters.artifacts import submission_intake_assignment_release_port from app.modules.audit.repository import AuditRepository from app.modules.tasks.assignment_invalidation import AssignmentInvalidationOperation from app.modules.tasks.api.assignment_invalidation import AssignmentInvalidationUnavailable @@ -369,6 +373,7 @@ async def test_release_requires_root_transaction_and_exact_prior_receipt(task_cl causes=committed_authority_invalidation(s.sessions), authorization=TracedFeatureAuthority(session, []), audit=assignment_invalidation_audit(session), + intake=submission_intake_assignment_release_port(session), ) with pytest.raises(AssignmentInvalidationUnavailable, match="root transaction"): await operation.reconcile(envelope) diff --git a/backend/tests/tasks/test_assignment_invalidation_races.py b/backend/tests/tasks/test_assignment_invalidation_races.py index cff30c2df..328abe13c 100644 --- a/backend/tests/tasks/test_assignment_invalidation_races.py +++ b/backend/tests/tasks/test_assignment_invalidation_races.py @@ -1,4 +1,4 @@ -"""Independent PostgreSQL ordering at the hidden effect and real TASK boundaries.""" +"""Independent PostgreSQL ordering at acceptance and real TASK invalidation boundaries.""" import asyncio from app.core.identifiers import new_record_id @@ -11,13 +11,13 @@ from app.modules.outbox.delivery import OutboxDelivery from app.modules.tasks.models import WorkstreamTask from app.modules.tasks.repository import TaskRepository -from tests.test_tasks import ( - task_client as task_client, - task_database_env as task_database_env, - auth_headers, -) +from tests import test_tasks as task_fixtures +from tests.test_tasks import auth_headers from tests.tasks.invalidation_support import setup_assignment, revoke, invoked, snapshot +task_client = task_fixtures.task_client +task_database_env = task_fixtures.task_database_env + async def test_expired_delivery_waiting_for_task_cannot_release( task_client, task_database_env, monkeypatch @@ -110,110 +110,273 @@ async def test_restored_authority_does_not_cancel_pending_assignment_release(tas assert await snapshot(s) == after +async def _assert_intake_invalidation_rollback(s, envelope, monkeypatch): + from app.modules.artifacts.intake.repository import SubmissionIntakeRepository + + async def intake_facts(): + async with s.sessions() as session: + return (await session.execute(text(""" + SELECT o.state,o.lease_generation,o.failure_code,o.raw_sha256,o.raw_byte_count, + c.state,c.accounted_bytes, + (SELECT jsonb_agg(to_jsonb(e) ORDER BY e.id) FROM public.audit_events e) + FROM public.submission_intake_operations o + JOIN public.submission_source_charges c ON c.operation_id=o.id WHERE o.task_id=:task + """), {"task": s.task["id"]})).one() + + before, intake = await snapshot(s), await intake_facts() + terminal, reached = SubmissionIntakeRepository._terminal, [] + async def fail_after_terminal(repository, row, state, code): + await terminal(repository, row, state, code) + assert row.state == "cancelled" and row.failure_code == "submission_unavailable" + reached.append(row.id) + raise RuntimeError("after real intake cancellation") + with monkeypatch.context() as patch: + patch.setattr(SubmissionIntakeRepository, "_terminal", fail_after_terminal) + with pytest.raises(RuntimeError, match="after real intake cancellation"): + await s.handler(envelope) + assert len(reached) == 1 + assert await snapshot(s) == before + assert await intake_facts() == intake + + +async def _race_acceptance_and_invalidation(s, envelope, payload, headers, database_url, winner, monkeypatch): + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.tasks.intake_custody import IntakeTaskCustody + from tests.tasks.submission_dispatch.test_revision_expiry import _wait_for_staged_submission + + pre_done, begin_accept, held, release = (asyncio.Event() for _ in range(4)) + blocker_pid = [] + names = {kind: f"assignment-{kind}-{new_record_id().hex}" for kind in ("submission", "invalidation")} + accept, stage = ForegroundIntakeAdmission.accept, ForegroundIntakeAdmission._accept_new + intake_lock, invalidation_lock = IntakeTaskCustody.lock, TaskRepository.lock_project_task + + async def before_accept(owner, *args, **kwargs): + pre_done.set() + await asyncio.wait_for(begin_accept.wait(), 60) + return await accept(owner, *args, **kwargs) + + async def staged(owner, session, *args, **kwargs): + result = await stage(owner, session, *args, **kwargs) + if winner == "submission": + blocker_pid.append(await session.scalar(text("SELECT pg_backend_pid()"))) + held.set() + await asyncio.wait_for(release.wait(), 60) + return result + + async def named_intake(owner, *args, **kwargs): + if begin_accept.is_set() and asyncio.current_task().get_name().startswith("submission-foreground:"): + await owner._session.execute(text("SELECT set_config('application_name',:name,true)"), + {"name": names["submission"]}) + return await intake_lock(owner, *args, **kwargs) + + async def named_invalidation(owner, *args, **kwargs): + if asyncio.current_task().get_name() != names["invalidation"]: + return await invalidation_lock(owner, *args, **kwargs) + await owner._session.execute(text("SELECT set_config('application_name',:name,true)"), + {"name": names["invalidation"]}) + result = await invalidation_lock(owner, *args, **kwargs) + if winner == "invalidation": + blocker_pid.append(await owner._session.scalar(text("SELECT pg_backend_pid()"))) + held.set() + await asyncio.wait_for(release.wait(), 60) + return result + + with monkeypatch.context() as patch: + patch.setattr(ForegroundIntakeAdmission, "accept", before_accept) + patch.setattr(ForegroundIntakeAdmission, "_accept_new", staged) + patch.setattr(IntakeTaskCustody, "lock", named_intake) + patch.setattr(TaskRepository, "lock_project_task", named_invalidation) + submitting = asyncio.create_task(s.client.post( + f"/api/v1/tasks/{s.task['id']}/submissions", headers=headers, content=payload)) + invalidating = None + try: + await _wait_for_staged_submission(pre_done, submitting, timeout=90) + if winner == "submission": + begin_accept.set() + await _wait_for_staged_submission(held, submitting, timeout=60) + invalidating = asyncio.create_task(s.handler(envelope), name=names["invalidation"]) + else: + await _assert_intake_invalidation_rollback(s, envelope, monkeypatch) + invalidating = asyncio.create_task(s.handler(envelope), name=names["invalidation"]) + await _wait_for_staged_submission(held, invalidating, timeout=60) + begin_accept.set() + loser = "invalidation" if winner == "submission" else "submission" + await asyncio.wait_for(wait_for_named_database_lock( + database_url, names[loser], expected_blocker_pid=blocker_pid[0]), 30) + release.set() + return await asyncio.wait_for(asyncio.gather( + submitting, invalidating, return_exceptions=True), 90) + finally: + begin_accept.set() + release.set() + pending = [job for job in (submitting, invalidating) if job is not None] + for job in pending: + if not job.done(): + job.cancel() + await asyncio.gather(*pending, return_exceptions=True) + + @pytest.mark.parametrize("winner", ["submission", "invalidation"]) async def test_real_submission_and_invalidation_serialize( - task_client, task_database_env, monkeypatch, tmp_path, winner + task_client, task_database_env, monkeypatch, tmp_path, winner, ): - from app.api.deps.authorization import compose_hidden_submission_creation_command - from app.modules.artifacts.models import SubmissionBundleAdmission - from app.modules.tasks.api import TaskSubmissionContextUnavailable - from app.modules.tasks.api.submission_command import SubmissionCreationResult + from types import SimpleNamespace + from uuid import UUID + from app.modules.artifacts.intake.models import SubmissionIntakeOperation from app.modules.tasks.models import Submission - from tests.tasks.invalidation_support import prepare_submission - - from tests.test_artifact_admission import _settings + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.invalidation_support import submission_packet + from tests.test_artifact_admission import _settings, _namespace, _local_store + from tests.test_tasks import set_dev_actor settings = _settings(tmp_path, maximum_bytes=1024 * 1024) s = await setup_assignment(task_client, monkeypatch, artifact_settings=settings) - context, creation = await prepare_submission(s, settings) + payload, headers = await submission_packet(s) await revoke(s, "suspend") restored = await s.client.post( f"/api/v1/actors/{s.grant['actor_profile_id']}/reactivate", - headers=auth_headers(), - json={"reason": "Allow real submission to compete with pending invalidation"}, - ) + headers=auth_headers(), json={"reason": "Allow submission to compete with pending invalidation"}) assert restored.status_code == 200, restored.text _, envelope = await invoked(s) - acquired, release = asyncio.Event(), asyncio.Event() - names = {kind: f"assignment-{kind}-{new_record_id().hex}" for kind in ("submission", "invalidation")} - loser = "invalidation" if winner == "submission" else "submission" - original_get, original_lock = TaskRepository.get_task, TaskRepository.lock_project_task + set_dev_actor(monkeypatch, roles="project_submitter", subject="invalidation-submitter") + _, settings, errors, calls = await configure_source_http( + s.sessions, s.client, tmp_path, monkeypatch, payload, "completed") + headers |= auth_headers() + response, invalidated = await _race_acceptance_and_invalidation( + s, envelope, payload, headers, task_database_env, winner, monkeypatch) + assert invalidated is HandlerOutcome.ACKNOWLEDGE, repr(invalidated) + assert len(calls) == 1 and errors == [], errors + task, assignments, events = await snapshot(s) + releases = [row for row in events if row["event_type"] == "TaskAssignmentAuthorityRevoked"] + async with s.sessions() as session: + operations = (await session.scalars(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.task_id == s.task["id"]))).all() + assert len(operations) == 1 + operation = operations[0] + assert (await session.scalars(select(Submission).where( + Submission.task_id == s.task["id"]))).all() == [] + assert operation.finalized_submission_id is None + charge = (await session.execute(text(""" + SELECT accounted_bytes, state FROM public.submission_source_charges + WHERE operation_id=:id + """), {"id": operation.id})).one() + assert charge == (len(payload), "sealed") + if winner == "submission": + assert response.status_code == 202, response.text + assert operation.state == "finalization_pending" + assert response.json()["operation_id"] == str(operation.id) + assert task["status"] == "evaluation_pending" + assert assignments[0]["status"] == "active" and assignments[0]["released_at"] is None + assert releases == [] + namespace = _namespace(settings) + bootstrap, store = _local_store(settings, namespace) + try: + submission_id = await finalize_retained_intake(s.sessions, SimpleNamespace( + operation_id=UUID(response.json()["operation_id"]), store=store, + namespace=namespace, settings=settings)) + finally: + bootstrap.close() + async with s.sessions() as session: + facts = (await session.execute(text(""" + SELECT s.task_assignment_id::text, a.status, a.consumed_by_submission_id::text, + public.submission_dispatch_valid(d) + FROM public.submissions s JOIN public.submission_bundle_admissions a + ON a.id=s.submission_bundle_admission_id + JOIN public.submission_dispatches d ON d.submission_id=s.id WHERE s.id=:id + """), {"id": submission_id})).one() + assert facts == (s.assignment["id"], "consumed", str(submission_id), True) + else: + assert response.status_code == 404, response.text + assert response.json()["error"]["code"] == "submission_unavailable" + assert operation.acceptance_receipt is None and operation.finalization_event_id is None + assert operation.state == "cancelled" and operation.lease_generation == 2 + assert operation.failure_code == "submission_unavailable" + assert task["status"] == "ready" and task["assigned_to"] is None + assert task["active_submission_operation_id"] is None + assert assignments[0]["status"] == "authority_revoked" and assignments[0]["released_at"] is not None + assert len(releases) == 1 + replay = await s.client.post(f"/api/v1/tasks/{s.task['id']}/submissions", headers=headers, content=payload) + assert replay.status_code == 404 and replay.json()["error"]["code"] == "submission_unavailable" + before = await snapshot(s) + assert await s.handler(envelope) is HandlerOutcome.ACKNOWLEDGE + assert await snapshot(s) == before + assert len(calls) == 1 - async def lock(owner, method, *args, **kwargs): - name = asyncio.current_task().get_name() - await owner._session.execute( - text("select set_config('application_name', :name, true)"), {"name": name} - ) - result = await method(owner, *args, **kwargs) - if name == names[winner]: - acquired.set() - await asyncio.wait_for(release.wait(), 10) - return result - async def get_task(owner, *args, **kwargs): - if kwargs.get("for_update"): - return await lock(owner, original_get, *args, **kwargs) - return await original_get(owner, *args, **kwargs) +async def test_invalidation_during_receiving_retains_charge_and_replays_without_body( + task_client, task_database_env, monkeypatch, tmp_path, +): + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.tasks.invalidation_support import submission_packet + from tests.tasks.submission_dispatch.test_revision_expiry import _wait_for_staged_submission + from tests.test_artifact_admission import _settings + from tests.test_tasks import set_dev_actor - async def project_task(owner, *args, **kwargs): - return await lock(owner, original_lock, *args, **kwargs) + settings = _settings(tmp_path, maximum_bytes=1024 * 1024) + s = await setup_assignment(task_client, monkeypatch, artifact_settings=settings) + payload, headers = await submission_packet(s) + await revoke(s, "suspend") + restored = await s.client.post( + f"/api/v1/actors/{s.grant['actor_profile_id']}/reactivate", headers=auth_headers(), + json={"reason": "Exercise receiving intake against committed release cause"}) + assert restored.status_code == 200, restored.text + _, envelope = await invoked(s) + set_dev_actor(monkeypatch, roles="project_submitter", subject="invalidation-submitter") + _, _, errors, calls = await configure_source_http( + s.sessions, s.client, tmp_path, monkeypatch, payload, "completed") + headers |= auth_headers() | {"Content-Length": str(len(payload))} + receiving, release = asyncio.Event(), asyncio.Event() - monkeypatch.setattr(TaskRepository, "get_task", get_task) - monkeypatch.setattr(TaskRepository, "lock_project_task", project_task) + async def held_body(): + receiving.set() + await release.wait() + yield payload - async def submit(): + async def forbidden_body(): + pytest.fail("known unsealed assignment cancellation consumed replay body") + yield b"unreachable" + + async def facts(): async with s.sessions() as session: - return await compose_hidden_submission_creation_command( - session, - context, - request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(creation) - - calls = {"submission": submit, "invalidation": lambda: s.handler(envelope)} - pending = [] + return (await session.execute(text(""" + SELECT o.id::text,o.state,o.lease_generation,o.failure_code,o.raw_sha256, + o.raw_byte_count,o.acceptance_receipt,o.finalization_event_id, + c.state,c.accounted_bytes, + (SELECT count(*) FROM public.submissions WHERE task_id=:task), + (SELECT count(*) FROM public.selected_pre_submit_runs WHERE task_id=:task) + FROM public.submission_intake_operations o + JOIN public.submission_source_charges c ON c.operation_id=o.id WHERE o.task_id=:task + """), {"task": s.task["id"]})).one() + + route = f"/api/v1/tasks/{s.task['id']}/submissions" + request = asyncio.create_task(s.client.post(route, headers=headers, content=held_body())) try: - pending.append(asyncio.create_task(calls[winner](), name=names[winner])) - await asyncio.wait_for(acquired.wait(), 10) - pending.append(asyncio.create_task(calls[loser](), name=names[loser])) - await asyncio.wait_for(wait_for_named_database_lock(task_database_env, names[loser]), 10) + await _wait_for_staged_submission(receiving, request, timeout=90) + before = await facts() + assert before[1:4] == ("receiving", 1, None) + assert await s.handler(envelope) is HandlerOutcome.ACKNOWLEDGE release.set() - results = dict( - zip( - (winner, loser), - await asyncio.wait_for(asyncio.gather(*pending, return_exceptions=True), 15), - ) - ) + response = await asyncio.wait_for(request, 60) finally: release.set() - await asyncio.gather(*pending, return_exceptions=True) - assert results["invalidation"] is HandlerOutcome.ACKNOWLEDGE + if not request.done(): + request.cancel() + await asyncio.gather(request, return_exceptions=True) + assert response.status_code == 404 and response.json()["error"]["code"] == "submission_unavailable" + after = await facts() + assert after == (before[0], "cancelled", 2, "submission_unavailable", None, None, + None, None, "reserved", len(payload), 0, 0) + replay = await s.client.post(route, headers=headers, content=forbidden_body()) + assert replay.status_code == 404 and replay.json()["error"]["code"] == "submission_unavailable" + progress = await s.client.get(f"/api/v1/tasks/{s.task['id']}/submission-operations", + headers=auth_headers(), params={"operation_id": before[0]}) + assert progress.status_code == 200, progress.text + assert progress.json()["failure_code"] == "submission_unavailable" + assert progress.json()["operation_state"] == "cancelled" + assert await facts() == after + assert calls == [] and errors == [] task, assignments, events = await snapshot(s) - releases = [row for row in events if row["event_type"] == "TaskAssignmentAuthorityRevoked"] - async with s.sessions() as session: - submissions = ( - await session.scalars(select(Submission).where(Submission.task_id == s.task["id"])) - ).all() - admission = await session.get(SubmissionBundleAdmission, str(creation.admission_id)) - if winner == "submission": - result = results["submission"] - assert isinstance(result, SubmissionCreationResult), result - assert len(submissions) == 1 - submission = submissions[0] - assert submission.id == str(result.submission_id) - assert submission.task_assignment_id == s.assignment["id"] - assert submission.artifact_binding_id == str(result.artifact_binding_id) - assert submission.artifact_content_id == str(result.artifact_content_id) - assert admission.status == "consumed" - assert admission.consumed_by_submission_id == submission.id - assert task["status"] == "evaluation_pending" - assert assignments[0]["status"] == "active" and assignments[0]["released_at"] is None - assert not releases - else: - assert isinstance(results["submission"], TaskSubmissionContextUnavailable), results - assert not submissions - assert admission.status == "ready" and admission.consumed_by_submission_id is None - assert task["status"] == "ready" and task["assigned_to"] is None - assert assignments[0]["status"] == "authority_revoked" - assert assignments[0]["released_at"] is not None - assert len(releases) == 1 + assert task["status"] == "ready" and task["active_submission_operation_id"] is None + assert assignments[0]["status"] == "authority_revoked" + assert len([event for event in events if event["event_type"] == "TaskAssignmentAuthorityRevoked"]) == 1 From 168e5268f103989e6d8b9dcb7f813b16b9087b3c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 14:18:56 +0100 Subject: [PATCH 216/513] test(submissions): prove checked packet lineage through accepted finalization --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 38 +++ .../tests/tasks/test_submission_lineage.py | 237 ++++++++++-------- 2 files changed, 172 insertions(+), 103 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index fa3efe7ed..9e54e81f8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7652,3 +7652,41 @@ Ruff/record/whitespace pass. Shared precommit proof overd627bfffc, not independe or clean-head execution. Test-only fixture alias cleanup preserves the same objects/scopes; it does not change the product evidence. Full goal qualification and remaining hidden/preparation consumers remain open, same draft PR708. + +Next bounded lineage cutover replaces the remaining hidden-create consumer in +backend/tests/tasks/test_submission_lineage.py. Public ZIP/PRE/T4 establishes the +accepted packet; one real service claim/observation drives production T5 roots. +Retain missing-admission substitution and both packet-field consumption refusals after staged +Submission, both immediate packet SQL guard attacks after real finalization AUTH, +full rollback, concurrent identical finalization, exact contribution/assignment/ +binding/content lineage, and all existing post-bind immutability attacks. Deliver +the existing durable event after T5 to prove exact completed replay; this latter +step is delivery replay, not initial T5-through-worker proof (covered elsewhere). +Allowed: this test module and record; no product/schema changes assumed. Keep +shared preparation helpers until traced consumers migrate. QA/test-delta and +ARCH/SEC review for custody-test change; run focused PG case, Ruff/structure/ +record/whitespace. Human focus: preserve independent packet-guard and rollback +oracles rather than replace them with happy-path assertions. Same PR708. + +Lineage V1 reached the real staged Submission/ART missing-admission guard but +failed on the expected exception wrapper (52.59s; cleanup complete). The removed +hidden transaction command alone translated ART failure to TASK failure; current +T5 exposes SubmissionAdmissionConsumptionError directly to its durable owner. +Assert that exact ART exception and unchanged code, retaining every snapshot +rollback check. No product change. Later packet/concurrency checks were not +executed by V1; V2 reruns the entire focused case. Refreshed main remainsa2154e8a4 +fully contained by this branch (HEAD..origin/main count0). + +Lineage V2 passed1 in41.93s; receipt records schema0086 and complete database/ +MinIO cleanup (/tmp/submission-lineage-t5-v2.log/.json). All three exact ART +refusals, both independent immediate SQL packet guards and complete rollback +snapshots passed, followed by concurrent identical T5, completed durable replay, +exact source/assignment/contribution-policy lineage and bound-packet immutability. +Proof uses controlled PRE and local store, direct production T5 and later worker +replay; it is shared precommit evidence over8a854f7a6, not clean-head/provider +qualification. No product/schema change; full goal remains active on draft PR708. + +Scoped QA and ARCH/SEC inspection found no remaining actionable finding after +V2; QA-LINEAGE001 resolved by exact direct ART exception oracle. Ruff, record +and whitespace pass; structure validation passed, subsequent oracle correction +only removed lines. Reviewed test blob30964b2a432124d548d430124743a0314cd73e72. diff --git a/backend/tests/tasks/test_submission_lineage.py b/backend/tests/tasks/test_submission_lineage.py index 65ac1e211..30964b2a4 100644 --- a/backend/tests/tasks/test_submission_lineage.py +++ b/backend/tests/tasks/test_submission_lineage.py @@ -1,4 +1,4 @@ -"""Real ZIP, ART custody and hidden TASK creation with exact contribution lineage.""" +"""Real ZIP, ART custody and accepted TASK creation with exact contribution lineage.""" import asyncio from tests.checkers.external.support import pre_registry_spec @@ -13,7 +13,6 @@ from sqlalchemy.exc import DBAPIError, IntegrityError from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine -from app.api.deps.authorization import compose_hidden_submission_creation_command from app.modules.artifacts.api import SubmissionBundlePreparationRequest, SubmissionAdmissionConsumptionError from app.modules.artifacts.models import ( SubmissionBundleAdmission, @@ -29,12 +28,11 @@ from app.modules.actors.api.service_identities import ServiceIdentity from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.tasks.api import ( - SubmissionCreationAdmissionError, SubmissionCreationRequest, TaskRetainedSubmissionParentsRequest, TaskSubmissionContextUnavailable, ) -from app.modules.tasks.models import AuditEvent, Submission, TaskAssignment, WorkstreamTask +from app.modules.tasks.models import Submission, TaskAssignment, WorkstreamTask from app.adapters.tasks import task_submission_context_port from tests.selected_policy_fixtures import approved_selected_policy_fixture from tests.submission_preparation_auth_helpers import install_submitter_grant @@ -357,114 +355,147 @@ async def observe_job_lock(owner, job_id): ] -async def test_real_zip_admission_and_hidden_creation_copy_exact_assignment( +async def _t5_lineage_snapshot(h): + from tests.tasks.submission_dispatch.test_replacement_creation import _creation_snapshot + + async with h.factory() as session: + retained = tuple([await session.scalar(text( + f"SELECT jsonb_agg(to_jsonb(r) ORDER BY {key}) FROM public.{table} r" + )) for table, key in (("artifact_contents", "id"), ("artifact_replicas", "id"), + ("submission_intake_operations", "id"), + ("submission_source_charges", "operation_id"), ("audit_events", "id"))]) + return await _creation_snapshot(h), retained + + +def _lineage_finalizer(h, settings, operation_id): + from datetime import timedelta + from app.adapters.artifacts import submission_admission_consumption_port + from app.adapters.checkers import selected_pre_submit_coordinator + from app.adapters.tasks import accepted_submission_creation_service, intake_task_custody_port + from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization + from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization + + return AcceptedSubmissionFinalization( + h.factory, tasks=intake_task_custody_port, checkers=selected_pre_submit_coordinator, + store=h.store, lease_duration=timedelta(seconds=300), + submissions=lambda session: accepted_submission_creation_service( + session, settings=settings, admissions=submission_admission_consumption_port( + session, request_id=new_record_id(), correlation_id=operation_id)), + authorization=lambda session: PreparedSubmissionFinalizationAuthorization( + session, request_id=new_record_id(), correlation_id=operation_id)) + + +async def _assert_t5_packet_refusals(h, finalizer, operation_id, claim, observation, monkeypatch): + from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization + from app.modules.tasks.submission_composition import TaskSubmissionCreationService + + before = await _t5_lineage_snapshot(h) + create = TaskSubmissionCreationService.create_accepted + for field in ("admission_id", "summary", "contributor_attestation"): + reached = [] + async def substitute_request(service, request, **kwargs): + reached.append(field) + value = new_record_id() if field == "admission_id" else getattr(request, field) + " Changed." + return await create(service, replace(request, **{field: value}), **kwargs) + with monkeypatch.context() as patch: + patch.setattr(TaskSubmissionCreationService, "create_accepted", substitute_request) + with pytest.raises(SubmissionAdmissionConsumptionError) as denied: + await finalizer._finalize(operation_id, claim, observation) + assert denied.value.code == "submission_bundle_admission_unavailable" + assert reached == [field] + assert await _t5_lineage_snapshot(h) == before + + consume = PreparedSubmissionFinalizationAuthorization.consume + for column in ("summary", "worker_attestation"): + reached = [] + async def substitute_packet(authority, *, prepared_authorization, facts): + decision = await consume(authority, prepared_authorization=prepared_authorization, facts=facts) + assert facts.phase == "commit" + changed = await authority._session.scalar(text( + f"UPDATE public.submissions SET {column}={column} || ' Changed.' " + "WHERE id=:id RETURNING id"), {"id": facts.submission_id}) + assert str(changed) == str(facts.submission_id) + reached.append(column) + await authority._session.execute(text("SET CONSTRAINTS submission_packet_custody IMMEDIATE")) + return decision + with monkeypatch.context() as patch: + patch.setattr(PreparedSubmissionFinalizationAuthorization, "consume", substitute_packet) + with pytest.raises(IntegrityError, match="submission packet differs from checked evidence") as denied: + await finalizer._finalize(operation_id, claim, observation) + assert denied.value.orig.sqlstate == "23514" + assert reached == [column] + assert await _t5_lineage_snapshot(h) == before + + +async def test_public_zip_and_t5_copy_exact_assignment_and_checked_packet( isolated_database_env, tmp_path, monkeypatch, ): - async with _prepared_packet(isolated_database_env, tmp_path) as h: - factory, context = h.factory, h.context - task_id, assignment_id = h.task_id, h.assignment_id - admission_id, creation = h.admission_id, h.creation - # ART rejection occurs after TASK insertion; the command must roll the - # entire root transaction back without stranding a staged Submission. - async with factory() as session: - with pytest.raises(SubmissionCreationAdmissionError) as denied: - await compose_hidden_submission_creation_command( - session, - context, - request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(replace(creation, admission_id=new_record_id())) - assert denied.value.code == "submission_bundle_admission_unavailable" - assert isinstance(denied.value.__cause__, SubmissionAdmissionConsumptionError) - async with factory() as session: - assert await session.scalar(select(func.count()).select_from(Submission)) == 0 - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert admission.status == "ready" - - async def assert_unconsumed(): - async with factory() as check: - assert await check.scalar(select(func.count()).select_from(Submission)) == 0 - assert await check.scalar(select(func.count()).select_from(ArtifactBinding).where( - ArtifactBinding.resource_type == "submission", - )) == 0 - assert await check.scalar(select(func.count()).select_from(AuditEvent).where( - AuditEvent.action_id.in_(["submission.create", "artifact.submission.binding.create"]), - )) == 0 - assert (await check.get(SubmissionBundleAdmission, str(admission_id))).status == "ready" - assert (await check.get(WorkstreamTask, str(task_id))).status == "in_progress" - - # Each field is independently bound to the packet that actually passed. - for field in ("summary", "contributor_attestation"): - async with factory() as session: - with pytest.raises(SubmissionCreationAdmissionError, match="submission_bundle_admission_unavailable"): - await compose_hidden_submission_creation_command( - session, context, request_id=new_record_id(), correlation_id=new_record_id(), - ).create(replace(creation, **{field: getattr(creation, field) + " Changed."})) - await assert_unconsumed() - - # Change only the stored packet after real ART/AUTH consumption, before - # dispatch sealing. Force only the deferred checked-packet constraint - # so a later dispatch constraint cannot mask this independent proof. - from app.modules.authorization.submission_creation_authorization import PreparedSubmissionCreationAuthorization - consume = PreparedSubmissionCreationAuthorization.consume - for column in ("summary", "worker_attestation"): - async def substitute_packet(owner, handle, facts): - decision = await consume(owner, handle, facts) - await owner._session.execute(text( - f"UPDATE public.submissions SET {column} = {column} || ' Changed.' " - "WHERE submission_bundle_admission_id = :admission" - ), {"admission": admission_id}) - await owner._session.execute(text("SET CONSTRAINTS submission_packet_custody IMMEDIATE")) - return decision - - with monkeypatch.context() as patch: - patch.setattr(PreparedSubmissionCreationAuthorization, "consume", substitute_packet) - async with factory() as session: - with pytest.raises(IntegrityError, match="submission packet differs from checked evidence"): - await compose_hidden_submission_creation_command( - session, context, request_id=new_record_id(), correlation_id=new_record_id(), - ).create(creation) - await assert_unconsumed() - - async def create(): - async with factory() as session: - return await compose_hidden_submission_creation_command( - session, - context, - request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(creation) + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.test_public_submission_intake import _client - results = await asyncio.wait_for( - asyncio.gather(create(), create(), return_exceptions=True), 30 - ) - successes = [value for value in results if not isinstance(value, BaseException)] - failures = [value for value in results if isinstance(value, BaseException)] - assert len(successes) == 2 and not failures, results - assert successes[0] == successes[1] - created = successes[0] - async with factory() as session: - task = await session.get(WorkstreamTask, str(task_id)) - assignment = await session.get(TaskAssignment, str(assignment_id)) + async with _submission_task(isolated_database_env, tmp_path) as h: + h.creation = SimpleNamespace( + summary=r'Completed the "required" project work in folder \results with evidence.', + contributor_attestation="I confirm no confidential client data, credentials, or copied source material " + "is included in this submission; rights_confirmed. " + " ".join(h.policy["attestation_terms"])) + headers = { + "Content-Type": "application/zip", "Idempotency-Key": str(new_record_id()), + "X-Task-Assignment-Id": str(h.assignment_id), "X-Submission-Summary": h.creation.summary, + "X-Contributor-Attestation": h.creation.contributor_attestation, + } + async with _client(h, monkeypatch, isolated_database_env) as client: + _, settings, errors, calls = await configure_source_http( + h.factory, client, tmp_path, monkeypatch, h.archive_bytes, "completed") + route = f"/api/v1/tasks/{h.task_id}/submissions" + accepted = await client.post(route, headers=headers, content=h.archive_bytes) + assert accepted.status_code == 202, accepted.text + assert len(calls) == 1 and errors == [], errors + operation_id = UUID(accepted.json()["operation_id"]) + before = await _t5_lineage_snapshot(h) + for name in ("X-Submission-Summary", "X-Contributor-Attestation"): + changed = await client.post(route, headers=headers | {name: headers[name] + " Changed."}, + content=h.archive_bytes) + assert changed.status_code == 409, changed.text + assert changed.json()["error"]["code"] == "submission_idempotency_conflict" + assert await _t5_lineage_snapshot(h) == before + async with h.factory() as session: + assert await session.scalar(select(func.count()).select_from(Submission)) == 0 + finalizer = _lineage_finalizer(h, settings, operation_id) + claim = await finalizer._claim(operation_id, new_record_id()) + observation = await h.store.observe_sealed_source(claim.source) + await _assert_t5_packet_refusals(h, finalizer, operation_id, claim, observation, monkeypatch) + first, second = await asyncio.wait_for(asyncio.gather( + finalizer._finalize(operation_id, claim, observation), + finalizer._finalize(operation_id, claim, observation)), 90) + assert first == second + created, h.admission_id = first, first.admission_id + assert await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=operation_id, store=h.store, namespace=h.namespace, settings=settings, + )) == str(created.submission_id) + async with h.factory() as session: + task = await session.get(WorkstreamTask, str(h.task_id)) + assignment = await session.get(TaskAssignment, str(h.assignment_id)) submission = await session.get(Submission, str(created.submission_id)) - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) + admission = await session.get(SubmissionBundleAdmission, str(h.admission_id)) binding = await session.get(ArtifactBinding, str(created.artifact_binding_id)) - assert ( - submission.contribution_policy_version_id - == assignment.submitter_contribution_policy_version_id - == task.locked_contribution_policy_version_id - ) + operation = await session.get(SubmissionIntakeOperation, operation_id) + assert submission.contribution_policy_version_id == assignment.submitter_contribution_policy_version_id + assert submission.contribution_policy_version_id == task.locked_contribution_policy_version_id assert submission.task_assignment_id == assignment.id assert submission.submission_bundle_admission_id == admission.id assert submission.artifact_binding_id == binding.id - assert ( - submission.artifact_content_id - == binding.content_id - == admission.artifact_content_id - ) - assert admission.status == "consumed" - assert admission.consumed_by_submission_id == submission.id + assert submission.artifact_content_id == binding.content_id == admission.artifact_content_id + assert admission.status == "consumed" and admission.consumed_by_submission_id == submission.id + assert admission.source_operation_id == str(operation_id) + assert admission.put_attempt_id is admission.durable_intent_id is admission.verification_receipt_id is None + assert operation.state == "finalized" and operation.finalized_submission_id == submission.id + assert task.status == "evaluation_pending" and task.active_submission_operation_id is None assert await session.scalar(select(func.count()).select_from(Submission)) == 1 + assert await session.scalar(text("SELECT public.submission_dispatch_valid(d) " + "FROM public.submission_dispatches d WHERE submission_id=:id"), {"id": submission.id}) is True + assert len(calls) == 1 and errors == [] await _assert_bound_packet_immutable(h, created) From d31a45773ba08e61aa0287b429c9962b361feea6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 14:38:17 +0100 Subject: [PATCH 217/513] fix(submissions): translate locked policy custody failures at intake --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 45 +++++ backend/app/adapters/artifacts/__init__.py | 3 +- .../task_authority/test_submission_policy.py | 158 ++++++++---------- 3 files changed, 113 insertions(+), 93 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 9e54e81f8..c5e9ea1df 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7690,3 +7690,48 @@ Scoped QA and ARCH/SEC inspection found no remaining actionable finding after V2; QA-LINEAGE001 resolved by exact direct ART exception oracle. Ruff, record and whitespace pass; structure validation passed, subsequent oracle correction only removed lines. Reviewed test blob30964b2a432124d548d430124743a0314cd73e72. + +Next bounded change migrates locked-policy refusal tests from hidden creation +to public raw-ZIP T1. Allowed: backend/tests/authorization/task_authority/ +test_submission_policy.py and this record initially. Preserve detached corrupt +effective/compiled policy, malformed TASK lock and crossed POST sidecar cases; +assert exact owner error plus public envelope and no body/PRE/intake/charge/ +Submission writes. Retain SQL lock mutation guard and rollback, remove only +unreachable creation after failing flush. No policy relaxation, schema or +historical-data changes. Risk: authorization/custody proof cutover; QA and +ARCH/SEC review, focused isolated PG module, Ruff/structure/record checks. +Human focus: precise refusal must precede unrelated cardinality/provider errors. + +Policy HTTP V1 reproduced exact PROJECT custody refusal followed by generic500 +internal_error instead of existing503 submission_infrastructure_unavailable; +3 SQL guards passed, first public case failed (205.10s), schema0086 and cleanup +complete (/tmp/submission-policy-http-v1.log/.json). Expand allowed scope only +to backend/app/adapters/artifacts/__init__.py: include the existing PROJECT +owner exception in ConfiguredSubmissionCommand.submit translation. Preserve +private diagnostics and all existing error semantics; no new public code. +Rerun all7 cases and module/authorization boundaries. Structure scanner first +exited139 without output; diagnostic rerun active, no pass claimed for first. + +Current product fix passed92 module/authorization boundaries in386.93s +(/tmp/submission-policy-boundaries.log). Unchanged full structure checker +passed under system Python3.12.3. UV Python3.12.13 crashed twice with139; +faulthandler points to validate_assertion_maps call at line736. No checker or +policy bypass/edit; /tmp/submission-policy-structure-v2.log retains crash and +/tmp/submission-policy-structure-system.log is the successful system run. +Scoped ARCH/SEC and QA code inspection found no actionable issue; integration +closure remains subject to terminal V2 evidence. No provider qualification. + +Policy HTTP V2 passed all7 in289.97s; schema0086 and all database/MinIO cleanup +complete (/tmp/submission-policy-http-v2.log/.json). Three SQL lock mutation +guards and four public refusal cases preserve rollback and exact owner errors. +PROJECT faults now yield existing503; malformed TASK context remains404. +Forbidden body, no PRE, and full selected custody/audit/outbox snapshots pass. +Evidence is shared precommit over168e5268f, not independent frozen-head or +provider qualification. Product blob1474a120c3b8167034369496abef3153b1d30f03; +test blobba939131bd87423af06ce32f268d9bce62c3e411. Full goal remains active. + +Remaining traced old writer dependencies are composition authorization tests, +the isolated ART final-denial composition test, named old commit-race tests, +and a real0047 cap-source fixture using replacement creation. Retire shared +writer only with those contracts preserved, including historical-row proof; +current create_accepted remains production T5. No new PR or merge request. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 32383a584..1474a120c 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -28,6 +28,7 @@ from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService, SelectedPreSubmitSourceReads from app.modules.artifacts.service import artifact_storage_namespace_spec from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied +from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextUnavailable from app.modules.checkers.api.source_contracts import source_contracts_context from app.modules.checkers.api.selected_pre_submit import ( SelectedPreSubmitAuthorityUnavailable, SelectedPreSubmitInfrastructureUnavailable, @@ -1142,7 +1143,7 @@ async def submit(self, metadata, chunks, *, actor_id, identity_link_id, idempote raise except (IntakeCommitUnknown, IntakeAuthorityDenied, IntakeCustodyConflict, SubmissionSourceCapacityConflict, TaskSubmissionContextUnavailable, - ArtifactStoreError, ExternalServiceAdapterError, SQLAlchemyError, ValidationError, + ProjectLockedPolicyContextUnavailable, ArtifactStoreError, ExternalServiceAdapterError, SQLAlchemyError, ValidationError, SelectedPreSubmitAuthorityUnavailable, SelectedPreSubmitInfrastructureUnavailable, SelectedPreSubmitRequestConflict, SelectedPreSubmitUnavailable) as exc: failure = _submission_public_failure(exc) diff --git a/backend/tests/authorization/task_authority/test_submission_policy.py b/backend/tests/authorization/task_authority/test_submission_policy.py index 1b9233bcc..ba939131b 100644 --- a/backend/tests/authorization/task_authority/test_submission_policy.py +++ b/backend/tests/authorization/task_authority/test_submission_policy.py @@ -1,64 +1,77 @@ -"""Real locked-policy rejection before hidden Submission persistence or ART access.""" - -from app.core.config import get_settings - -from app.adapters.tasks import task_service, task_submission_context_port - -from uuid import UUID, uuid4 -from unittest.mock import AsyncMock +"""Locked-policy rejection through public raw-ZIP intake before source custody.""" import pytest from httpx import AsyncClient -from sqlalchemy import select +from sqlalchemy import select, text from sqlalchemy.exc import IntegrityError from app.db import session as db_session from app.db import models as db_models -from app.api.deps.authorization import compose_hidden_submission_creation_command from app.modules.projects.models import ( PostSubmitCheckerPolicy, ) -from app.modules.authorization.prepared import PreparedSubmissionCreationAuthorization -from app.modules.tasks.api import SubmissionCreationRequest, TaskSubmissionContextUnavailable +from app.modules.tasks.api import TaskSubmissionContextUnavailable +from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextUnavailable from app.modules.tasks.models import AuditEvent, Submission, TaskAssignment, WorkstreamTask from app.modules.tasks.repository import TaskRepository -from app.modules.tasks.service import TaskLockedContextInvalid -from app.modules.tasks.submission_composition import TaskSubmissionCreationService -from tests.authorization.task_authority.test_concurrency import actor_context from tests.projects.policy_read_faults import corrupt_locked_policy_reads +from tests import test_tasks as task_fixtures from tests.test_tasks import ( - task_database_env as task_database_env, - task_client as task_client, + auth_headers, create_active_project, create_started_task, ) -async def _create_hidden_submission(task_id: str): - """Exercise real TASK/AUTH composition; invalid policy must precede ART lookup. - - The deliberately nonexistent admission cannot produce successful creation. - If policy validation regresses, admission denial is a different failure and - does not satisfy these tests' precise locked-policy error assertions. - """ - async with db_session.get_session_factory()() as session: +task_database_env = task_fixtures.task_database_env +task_client = task_fixtures.task_client + + +async def _reject_public_submission(client, task_id, tmp_path, monkeypatch, expected): + """Keep exact owner refusal observable while exercising the real HTTP mapping.""" + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from tests.artifacts.test_submission_foreground_command import configure_source_http + factory = db_session.get_session_factory() + _, _, errors, calls = await configure_source_http( + factory, client, tmp_path, monkeypatch, b"unused", "completed") + tables = ("submission_intake_operations", "submission_source_charges", "submissions", + "checker_runs", "checker_results", "audit_events", "outbox_events") + async def snapshot(): + async with factory() as session: + return {table: list(await session.scalars(text( + f"SELECT to_jsonb(r)::text FROM public.{table} r ORDER BY to_jsonb(r)::text" + ))) for table in tables} + before = await snapshot() + async with factory() as session: assignment = await session.scalar(select(TaskAssignment).where( - TaskAssignment.task_id == task_id, TaskAssignment.status == "active", - )) - assert assignment is not None - assignment_id = UUID(assignment.id) - contributor_id = UUID(assignment.contributor_id) - context = await actor_context(str(contributor_id)) - async with db_session.get_session_factory()() as session: - command = compose_hidden_submission_creation_command( - session, context, request_id=context.request_id, correlation_id=context.correlation_id, - ) - return await command.create(SubmissionCreationRequest( - task_id=UUID(task_id), assignment_id=assignment_id, - contributor_id=contributor_id, admission_id=uuid4(), - predecessor_submission_id=None, summary="Completed work", - contributor_attestation="This submission is my work.", - )) + TaskAssignment.task_id == task_id, TaskAssignment.status == "active")) + assignment_id = assignment.id + failures = [] + validate = ForegroundIntakeAdmission._validate_context + async def observe(owner, *args): + try: + return await validate(owner, *args) + except expected as exc: + failures.append(exc) + raise + async def forbidden_body(): + pytest.fail("invalid locked policy read the request body") + yield b"never" + with monkeypatch.context() as patch: + patch.setattr(ForegroundIntakeAdmission, "_validate_context", observe) + response = await client.post(f"/api/v1/tasks/{task_id}/submissions", + headers=auth_headers() | {"Content-Type": "application/zip", + "X-Task-Assignment-Id": assignment_id}, content=forbidden_body()) + assert len(failures) == 1 + expected_code = ("task_submission_context_invalid" if expected is TaskSubmissionContextUnavailable + else "project_locked_policy_context_changed") + assert failures[0].code == expected_code + assert response.status_code == (404 if expected is TaskSubmissionContextUnavailable else 503), response.text + assert response.json()["error"]["code"] == ( + "submission_unavailable" if expected is TaskSubmissionContextUnavailable + else "submission_infrastructure_unavailable") + assert await snapshot() == before + assert calls == [] and errors == [] @pytest.mark.parametrize("field", [ @@ -71,17 +84,6 @@ async def test_invalid_locked_policy_never_reaches_art_or_submission( ): project = await create_active_project(task_client) task_response = await create_started_task(task_client, project["id"], monkeypatch) - async with db_session.get_session_factory()() as session: - assignment = await session.scalar(select(TaskAssignment).where( - TaskAssignment.task_id == task_response["id"], - TaskAssignment.status == "active", - )) - assignment_id = UUID(assignment.id) - contributor_id = UUID(assignment.contributor_id) - context = await actor_context(str(contributor_id)) - admissions = AsyncMock() - admissions.consume.side_effect = AssertionError("invalid policy reached ART") - async with db_session.get_session_factory()() as session: with pytest.raises(IntegrityError, match="task revision context lacks current preparation"): async with session.begin(): @@ -92,24 +94,6 @@ async def test_invalid_locked_policy_never_reaches_art_or_submission( # guard precedes policy FK checks and any ART participation. setattr(task, field, {} if field.endswith("body") else "sha256:" + "f" * 64) await session.flush() - await TaskSubmissionCreationService( - session, - authorization=PreparedSubmissionCreationAuthorization(session, context), - admissions=admissions, evaluations=AsyncMock(), events=AsyncMock(), - contexts=task_service(session, settings=get_settings()), - submission_contexts=task_submission_context_port(session), - ).create( - SubmissionCreationRequest( - task_id=UUID(task.id), - assignment_id=assignment_id, - contributor_id=contributor_id, - admission_id=uuid4(), - predecessor_submission_id=None, - summary="Completed work", - contributor_attestation="This submission is my work.", - ) - ) - admissions.consume.assert_not_awaited() assert await session.scalar(select(Submission).where( Submission.task_id == task_response["id"], )) is None @@ -120,17 +104,14 @@ async def test_invalid_locked_policy_never_reaches_art_or_submission( async def test_submission_pre_submit_rejects_mutated_effective_policy_body( task_client: AsyncClient, - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, tmp_path, ) -> None: project = await create_active_project(task_client) started_task = await create_started_task(task_client, project["id"], monkeypatch) await corrupt_locked_policy_reads(monkeypatch, started_task["id"], "stale_effective") - with pytest.raises(TaskLockedContextInvalid) as rejected: - await _create_hidden_submission(started_task["id"]) - assert rejected.value.status_code == 422 - assert rejected.value.code == "task_locked_context_invalid" - assert str(rejected.value) == "task locked policy custody is invalid" + await _reject_public_submission(task_client, started_task["id"], tmp_path, monkeypatch, + ProjectLockedPolicyContextUnavailable) async with db_session.get_session_factory()() as session: submissions = ( @@ -149,7 +130,7 @@ async def test_submission_pre_submit_rejects_mutated_effective_policy_body( async def test_submission_rejects_malformed_locked_post_submit_policy_body_without_side_effects( task_client: AsyncClient, - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, tmp_path, ) -> None: project = await create_active_project(task_client) started_task = await create_started_task(task_client, project["id"], monkeypatch) @@ -177,9 +158,8 @@ async def corrupt_task_read(repository, task_id, **kwargs): monkeypatch.setattr(TaskRepository, "get_task", corrupt_task_read) - with pytest.raises(TaskSubmissionContextUnavailable) as rejected: - await _create_hidden_submission(started_task["id"]) - assert rejected.value.code == "task_submission_context_invalid" + await _reject_public_submission(task_client, started_task["id"], tmp_path, monkeypatch, + TaskSubmissionContextUnavailable) async with db_session.get_session_factory()() as session: task = await session.get(WorkstreamTask, started_task["id"]) submissions = ( @@ -236,17 +216,14 @@ async def corrupt_task_read(repository, task_id, **kwargs): async def test_submission_pre_submit_rejects_mutated_compiled_checker_bundle( task_client: AsyncClient, - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, tmp_path, ) -> None: project = await create_active_project(task_client) started_task = await create_started_task(task_client, project["id"], monkeypatch) await corrupt_locked_policy_reads(monkeypatch, started_task["id"], "stale_bundle") - with pytest.raises(TaskLockedContextInvalid) as rejected: - await _create_hidden_submission(started_task["id"]) - assert rejected.value.status_code == 422 - assert rejected.value.code == "task_locked_context_invalid" - assert str(rejected.value) == "task locked policy custody is invalid" + await _reject_public_submission(task_client, started_task["id"], tmp_path, monkeypatch, + ProjectLockedPolicyContextUnavailable) async with db_session.get_session_factory()() as session: submissions = ( @@ -265,7 +242,7 @@ async def test_submission_pre_submit_rejects_mutated_compiled_checker_bundle( async def test_submission_rejects_crossed_post_submit_policy_sidecar( task_client: AsyncClient, - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, tmp_path, ) -> None: project = await create_active_project(task_client) started_task = await create_started_task(task_client, project["id"], monkeypatch) @@ -285,13 +262,10 @@ async def test_submission_rejects_crossed_post_submit_policy_sidecar( from tests.projects.post_submit_fixtures import crossed_post_policy_read with crossed_post_policy_read(policy_id) as seen: - with pytest.raises(TaskLockedContextInvalid) as rejected: - await _create_hidden_submission(started_task["id"]) + await _reject_public_submission(task_client, started_task["id"], tmp_path, monkeypatch, + ProjectLockedPolicyContextUnavailable) assert seen - assert rejected.value.status_code == 422 - assert rejected.value.code == "task_locked_context_invalid" - assert str(rejected.value) == "task locked policy custody is invalid" async with db_session.get_session_factory()() as session: task = await session.get(WorkstreamTask, started_task["id"]) From 884a326ef111f2c9c1b91efbba552f8931db5395 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 15:17:10 +0100 Subject: [PATCH 218/513] test(submissions): retire historical cap writer and reconcile completion checklist --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 115 ++++++++------- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 102 +++++++++++--- .../fixtures/retained_cap_capture.py.txt | 79 +++++++++++ .../fixtures/retained_cap_source.json.gz | Bin 0 -> 51017 bytes backend/tests/fixtures/retained_cap_source.md | 33 +++++ backend/tests/migration_revision_fixtures.py | 12 +- .../test_replacement_creation.py | 59 -------- .../test_revision_exhaustion_recovery.py | 132 ++++++------------ backend/tests/test_alembic.py | 4 +- 9 files changed, 299 insertions(+), 237 deletions(-) create mode 100644 backend/tests/fixtures/retained_cap_capture.py.txt create mode 100644 backend/tests/fixtures/retained_cap_source.json.gz create mode 100644 backend/tests/fixtures/retained_cap_source.md diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 033303108..46193d60f 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -1,75 +1,70 @@ -# WS-SUBMIT-001 — One-request submission and durable continuation +# WS-SUBMIT-001 — Submission execution completion checklist - Disposition: Planned -- Intent: implement the user-approved [specification](../../../docs/spec_submission_execution.md), preserving downstream authority and retained evidence. +- Target: the complete [submission execution specification](../../../docs/spec_submission_execution.md). +- Delivery: one PR, #708, with focused commits; no merge request before complete verification. -The user authorized the complete specification on 11 November 2026. Completion -requires D01–D18, I01–I12, T1–T5 and evidence for A01–A35. This record does not -authorize merge or production deployment. +## Implemented on this branch -## Current boundary +Checked items describe implementation with focused proof. They do not mean the +complete acceptance matrix or deployment is qualified. Detailed runs and their +limits are in [the change record](WS-SUBMIT-001-01.md). -[WS-SUBMIT-001-01](WS-SUBMIT-001-01.md) establishes exact command/source value -contracts and hidden pre-handoff database custody with TASK/source/lease guards. Per-operation physical source reservations are implemented with explicit limits. -Hidden S3-compatible source methods and a backpressured receiver now provide -bounded parts, conditional completion, exact-version reads and scoped uncertain -upload discovery. Local source methods keep one ZIP inode through sealing, verify -exact generations and preserve completed bytes on late abort. Private upload -composition commits intent before provider begin, handle before parts, and EOF -before provider completion, then binds known source facts before fenced sealing. Full foreground authorization/heartbeat -integration, confirmed physical reclamation, AWS qualification and accepted authority remain -to implement and integrate. -The existing public flow stays active until coordinated cutover. +- [x] Exact intake/source identities, durable custody, leases and physical byte reservations. +- [x] Streaming Local/MinIO source upload and source-bound PRE orchestration. +- [x] Atomic T4 acceptance: pending task custody, accepted receipt and durable finalization event. +- [x] T5 formal Submission/binding/POST dispatch through existing owners, with replay and rollback tests. +- [x] Public raw-ZIP API and corresponding CLI/MCP submission/progress contracts. +- [x] One-image-per-phase policy guards and retained-policy refusal. +- [x] Revision expiry and assignment invalidation serialize with acceptance; accepted input remains protected. +- [x] Pending-revision protection prevents dispatch against the older Submission. +- [x] Cleanup claim, retention barriers, exact-generation deletion and confirmed charge release owners. +- [x] Historical cap fixture no longer depends on the old writer; capture, restore/recovery and neighboring upgrade controls passed. -## Delivery sequence +Recent focused evidence includes atomic invalidation (`8a854f7a6`), public +ZIP/T5 lineage (`168e5268f`), and policy-error translation (`d31a45773`). The +last change passed seven PostgreSQL cases and 92 boundary checks. These are +bounded results, not full-head qualification. -1. Owner contracts/schema: exact identities, ART operation, TASK guard, accepted - authority, PRE evidence and database constraints. -2. Streaming receipt, completion reconciliation, physical accounting and cleanup. -3. One-session PRE, trusted defaults, isolation and provider substitution proof. -4. Foreground T1–T4, exact replay and durable accepted receipt. -5. Worker T5, recovery and existing POST dispatch. -6. Single API/CLI/MCP mutation and truthful progress reads. -7. Image cardinality, readiness, migration/cutover and integrated proof. +## Remaining work, in execution order -The user requires one PR for the complete work, with focused commits for each -stage and end-to-end testing before requesting merge. Maintain the single -WS-SUBMIT-001-01 change record as implementation proceeds. This explicit -instruction supersedes the repository default of separate PRs per stage. -Authorization covers the sequence; do not stop for intermediate merges or -repeat discovery or verification without a relevant changed assumption. +| Order | Required outcome | Concrete finishing evidence | +| --- | --- | --- | +| 1 | Integrate production source cleanup scheduling/startup and uncertain/unsealed reconciliation | Real worker callers of the cleanup owner; restart and repeated sweeps; interrupted multipart and lost acknowledgements; accepted/stalled source survives; confirmed cleanup releases charge once. | +| 2 | Remove superseded preparation/submission writers and remaining consumers | Trace all remaining callers, preserve their distinct authority/history contracts, then delete obsolete implementation. Current T5 `create_accepted` remains. | +| 3 | Complete native/runtime/provider and resource qualification | Actual Smol one-session/isolation proof; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | +| 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. | +| 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. | -## Acceptance tracking +The concrete next runtime gap is order 1: the ART cleanup execution and provider +factory exist, but the current production worker tree has no caller. Further +optional test migration must not displace closing this integration. -All integrated scenarios remain Planned. Contract unit tests do not complete -them. Final evidence must name the executed test/drill and proved boundary. +## Acceptance evidence still to close -| Scenarios | Proof required | Disposition | -|---|---|---| -| A01–A03 | Public success and PRE failures | Planned | -| A04–A08 | Replay, concurrency, interruptions and unknown commit | Planned | -| A09–A13 | Worker recovery, authority and pending reads | Planned | -| A14–A18 | Cleanup races, protection, versions and physical charges | Planned | -| A19–A23 | Bounded ingress, framing, archives, identity and safe findings | Planned | -| A24–A30 | Substitution, runtime isolation/recovery, capacity and adapters | Planned | -| A31–A35 | Downstream behavior, migration, policy and clients | Planned | +No row below is declared fully complete merely because some related tests pass. +This is the final qualification queue, not a claim that all listed code is absent. -## Configuration and reconciliation +| IDs | Existing implementation/focused evidence | Required closure | +| --- | --- | --- | +| A01–A03 | Public ZIP flow, default/project PRE and formal finalization tests | Complete API/CLI journey with required real runtime and POST evidence. | +| A04–A08 | Metadata/body replay, competing custody, interruption and T4 uncertainty tests | Reconcile exact cases and execute integrated final-head failure/retry matrix. | +| A09–A13 | T5 rollback/redelivery, accepted authority, pending reads and old-POST guard | Real worker crash/broker-unavailable drill and final-head reconciliation. | +| A14–A18 | Cleanup lock/retention/charge owners and Local/MinIO provider tests | Production sweeps, accepted-source survival, AWS versions and uncertain multipart ownership. | +| A19–A23 | Streaming/framing, safe archives, semantic identity and bounded findings code/tests | Measured permitted maxima/slow-provider memory bounds and complete safety matrix. | +| A24–A30 | Source/result/fence contracts and runtime/capacity/substitution tests | Actual native isolation/failure/cleanup, multiple replicas/nodes, saturation and adapter qualification. | +| A31–A32 | Existing governed POST/revision/acceptance owners preserved with focused journeys | Final combined downstream tests, exact ContributionRecord/award facts, both review branches. | +| A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | Finish old-writer retirement and full current-head migration/client convergence proof. | -C01–C07 remain unresolved as specified; fixtures are not approved deployment -defaults. Current Caddy allows 16 KiB total headers; target packet text permits -64 KiB each. Human-review execution remains unavailable in current main and is -not delivered by preserving its guards. +## Configuration and external evidence -Initial main is `a4e485edea03db90c71189c51eac85cf4c3b1139`. The 14 commits after -the spec baseline change deployment/identity, not submission owners. At initial -intake, open PR #698 changed CLI preparation and #707 changed public access/profile -behavior. Reconcile affected surfaces without modifying their branches. +C01–C07 remain open until individually reconciled with the specification and +actual deployment evidence. Test-only leases/profiles are not approved defaults. +Current local inspection found no `/dev/kvm` or `smol` executable, so this host +cannot currently provide the required native Smol qualification. AWS source +qualification remains separate from MinIO and existing SHA-object activation. +Request only concrete missing access or decisions after the corresponding drill +and proposed values are prepared. -PR #707 merged during the first change. Reconciled current main `94334ccf4`, -including issuer-owned profile metadata, public Swagger and schema head 0068. -Its roadmap paragraph is preserved; no new submission behavior was introduced. - -Real PostgreSQL, S3/MinIO and Smol proof is required where claimed. Request -missing live access when a concrete drill is prepared. Historical old-flow -drills cannot establish this implementation's completion. +The full goal includes D01–D18, I01–I12, T1–T5 and A01–A35. A partial green +suite, fixture capture, review approval or a single commit does not complete it. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c5e9ea1df..3f7f7c32e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -17,29 +17,11 @@ manifest facts. ## Implementation snapshot -This branch has tested internal source contracts/custody, physical reservations, -bounded Local/MinIO streaming, foreground upload/lease owners, source-bound PRE -contracts/runtime implementation, atomic T4 acceptance, T5 registration and -source-backed POST. Controlled/portable PRE tests do not qualify native Smol; -MinIO tests do not qualify AWS. Detailed evidence below belongs to its stated -commit or worktree, not automatically to every later head. - -Finalization now has production OUTBOX registration and invocation fencing, with -real PostgreSQL recovery proof. A dedicated local worker queue and internal -authorized stall projection are implemented. Full Celery/provider execution, -independent worker capacity and public progress/operator endpoints remain unfinished. -Internal audited finalization recovery now reuses the existing Operator gate-repair -action, preserves the original delivery and runs the same T5 under a live child lease. -Private sealed-source cleanup claims, retention barriers and atomic charge-release -custody are now implemented and database-tested. Cleanup claims and confirmations now require exact audited service decisions. -Internal Local/S3 exact-generation deletion now composes committed audited claims -with separately observed settlement and charge release. Local database/provider -and MinIO protocol/principal tests cover that private path; native AWS cleanup is -not qualified. Worker startup/scheduling and uncertain/unsealed reconciliation -remain uncomposed. -Remaining work includes durable-worker deployment, complete cleanup, public API/CLI/MCP -cutover, real revision/review/ContributionRecord journeys, policy cardinality and -the A01–A35/C01–C07 completion audit. No public end-to-end readiness is claimed. +The current completion checklist and next blocking integration live in +[OVERVIEW.md](OVERVIEW.md). This record retains chronological implementation and +verification evidence; older entries are not the current work queue. Evidence +belongs to its stated commit/worktree and provider, not automatically to later +heads. The full specification remains unfinished. ## Original behavior being replaced @@ -7735,3 +7717,77 @@ the isolated ART final-denial composition test, named old commit-race tests, and a real0047 cap-source fixture using replacement creation. Retire shared writer only with those contracts preserved, including historical-row proof; current create_accepted remains production T5. No new PR or merge request. + +Next bounded retirement removes live hidden-writer dependency from the retained +0047 cap recovery fixture. Capture its genuine guarded v2 cap-blocked rows once +at d31a45773, after null-only projections are removed and before current upgrade; +retain checksum/provenance and capture source as non-executable documentation. +Current test will restore exact predecessor rows, check guards and retained-row +invariance through real upgrade, then exercise current recovery/replay/authority. +Allowed: migration_revision_fixtures.py, test_revision_exhaustion_recovery.py, +test_replacement_creation.py (only traced unused historical helpers), new +checksum-bound cap archive/capture provenance under backend/tests/fixtures and +this record; temporary capture test removed after run. No runtime, migration, +policy or data deletion changes. Risk: retained history/security proof; required +QA/test-delta and ARCH/SEC review, isolated cap recovery and neighboring upgrade +control, Ruff/structure/record checks. Human focus: data snapshot is setup, not +a fabricated current writer or a claim that rawZIP existed in0047. Preserve +replay and revocation proof; incompatible retained policy must remain blocked +under spec20.2 rather than silently relocked for a new successful submission. + +Capture V1 failed before producing rows: current ORM reads source_operation_id +on genuine0047 admissions, where the column does not exist (204.29s; allcleanup). +Use detached pre-cutover e2b926288899bcd9b05e1a560ec19b6bca8cfcfc owners for +the one-time capture instead of extending current compatibility projections. +Keep explicit historical0047 adaptations documented. No output from V1 credited. +Captured invocation leases also cannot authorize future replay: restore uses +current authorized delivery continuation rather than extending archived clocks. + +Extend allowed scope to test_alembic.py existing incompatible-policy helper: +accept explicit initial-submission headers so cap reclaim reuses the same +exact private-cardinality/HTTP/no-body/no-upload/rollback proof without copying +it. Capture completes the known historical routing invocation with authorized +RETRY before its lease expires (explicit test-only600s lease/1s backoff). Restore +will claim the same event afresh through existing dispatcher authority; no +archived lease extension, unsafe unknown replay or production registry change. + +Pinned capture V2 passed1 in134.47s, sourcee2b926288, schema0065 final receipt +and complete cleanup (/tmp/submission-cap-capture-v2.log/.json). Archived rows +are genuine0047 before upgrade,71nonempty tables/twoSubmissions, canonical v2 +ZIP hash/length verified and both object bytes retained. Source completion is +retryable with RETRY_REQUESTED from actual authority. Archive SHA256 +62f9ae1c767182e3c91dd705a0e282133b44e882921634f7fbc4a41ad3decbde. +Capture/provenance files retained under fixtures; no temporary current test. + +User requested correction of fragmented goal tracking. Replace the stale overview +and duplicated implementation snapshot with one current completion checklist. +This expands allowed documentation scope to OVERVIEW.md. Current source trace +shows submission_source_cleanup_execution and its provider factory exist but +have no production worker caller; close that runtime integration before further +optional test migration. Preserve full A01–A35 and C01–C07 requirements. + +Current restore V1:2controls passed, cap fixture failed before recovery at strict +UUID decoding of archived routing outcome (575.27s, schema0086, completecleanup). +Use JSON-mode validation consistent with other archived Pydantic values. No +migration/product defect or cap recovery pass claimed. Rerun only the failed +cap case; unchanged assignment-backfill and retained-window controls remain valid. + +Cap V2 runner exited migration_failed before pytest, without migration output +or metadata (metadata is written only after migration). No pass or receipt +claimed. The runner reached normal cleanup without reporting a cleanup failure. +Use isolated systemPython3.12.3 environment with the same existing dependency +packages and faulthandler enabled for V3; the unchanged structure checker already +passed on that interpreter after UV3.12.13 native crashes. No product/gate changes +and no root-cause claim for the V2 setup failure. JSON-mode archive parsing also +passed directly against the exact v2 Submission selector before the rerun. + +Cap restore V3 passed1 in123.38s under systemPython3.12.3, schema0086 and +complete database/MinIO cleanup (/tmp/submission-cap-restore-v3.log/.json). +Exact0047 restore/real upgrade/history invariance, recovery denial/rollback, +one release, new assignment with incompatible-policy refusal, live invocation +replay and revoked-service denial all executed. The two unchanged neighboring +upgrade controls passed in V1. These are shared precommit proofs over d31a45773, +not an independent final-head/native-provider/full-suite qualification. +SystemPython full structure validation passed; Ruff, record, link and whitespace +checks passed. Overview now checks this fixture cutover complete and puts the +missing production source-cleanup integration first. Full goal remains active. diff --git a/backend/tests/fixtures/retained_cap_capture.py.txt b/backend/tests/fixtures/retained_cap_capture.py.txt new file mode 100644 index 000000000..7a2be63e8 --- /dev/null +++ b/backend/tests/fixtures/retained_cap_capture.py.txt @@ -0,0 +1,79 @@ +"""One-time capture of guarded historical cap source; not a current writer.""" +import base64 +import gzip +import json +from dataclasses import asdict, is_dataclass +from pathlib import Path + +import asyncpg +import pytest +from pydantic import TypeAdapter + +from tests.tasks.submission_dispatch import test_revision_exhaustion_recovery as recovery + +pytestmark = pytest.mark.postgres_schema_contract + + +def encoded(value): + if hasattr(value, 'model_dump'): + return value.model_dump(mode='json') + return TypeAdapter(dict).dump_python(asdict(value) if is_dataclass(value) else vars(value), mode='json') + + +async def test_capture(isolated_database_env, tmp_path, migration_lock, monkeypatch): + from app.modules.outbox.api import DeliveryOptions, FinalizationCause + from tests.tasks.post_submit_routing import outcome_support + snapshot = {} + compose = outcome_support.outbox_delivery + def delivery(*args, **kwargs): + kwargs['options'] = DeliveryOptions(lease_seconds=600, handler_timeout_seconds=599, + retry_base_seconds=1, retry_cap_seconds=1) + return compose(*args, **kwargs) + monkeypatch.setattr(outcome_support, 'outbox_delivery', delivery) + fail_current = recovery._fail_current_submission + async def complete_for_retry(h, **kwargs): + routed = await fail_current(h, **kwargs) + receipt = await h.completion_delivery.finalize(h.envelope.claim, FinalizationCause.RETRY) + assert json.loads(receipt.outcome_json)['error_code'] == 'RETRY_REQUESTED' + return routed + monkeypatch.setattr(recovery, '_fail_current_submission', complete_for_retry) + leave = recovery.leave_predecessor_owner_shape + + async def capture_after_leave(execute, database_url): + await leave(execute, database_url) + connection = await asyncpg.connect(database_url.replace('+asyncpg', '')) + try: + async with connection.transaction(isolation='repeatable_read', readonly=True): + assert await connection.fetchval('SHOW session_replication_role') == 'origin' + assert await connection.fetchval("SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND NOT t.tgisinternal AND t.tgenabled NOT IN ('O','A')") == 0 + snapshot['revision'] = await connection.fetchval('SELECT version_num FROM alembic_version') + assert snapshot['revision'] == '0047_revision_recovery' + snapshot['tables'] = {} + for row in await connection.fetch("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename"): + name = row['tablename'] + rows = json.loads(await connection.fetchval(f'SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY to_jsonb(r)::text),\'[]\')::text FROM public."{name}" r')) + if rows: + snapshot['tables'][name] = rows + assert len(snapshot['tables']['submissions']) == 2 + assert any(row['outcome'] == 'blocked' and row['blocked_reason'] == 'revision_limit_reached' + and row['next_revision_round'] == 2 and row['max_revision_rounds'] == 1 + for row in snapshot['tables']['task_revision_preparations']) + finally: + await connection.close() + + monkeypatch.setattr(recovery, 'leave_predecessor_owner_shape', capture_after_leave) + with migration_lock(): + async with recovery._retained_cap_source(tmp_path, isolated_database_env, monkeypatch) as (h, routed, before): + snapshot['seed'] = { + 'request': encoded(h.request), 'created': encoded(h.created), + 'actor_context': encoded(h.actor_context), 'creation_request': encoded(h.creation_request), + 'source': TypeAdapter(dict).dump_python(h.source, mode='json'), + 'data_base64': base64.b64encode(h.data).decode(), + 'envelope': encoded(h.envelope), 'routed': encoded(routed), + 'objects': {ref: base64.b64encode(data).decode() for ref, data in h.store.objects.items()}, + } + body = dict(schema_version='workstream.retained_cap_source.v1', + source_revision='e2b926288899bcd9b05e1a560ec19b6bca8cfcfc', + source_test='tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py::_retained_cap_source', + snapshot=snapshot) + Path('/tmp/retained-cap-source.json.gz').write_bytes(gzip.compress(json.dumps(body, sort_keys=True).encode(), mtime=0)) diff --git a/backend/tests/fixtures/retained_cap_source.json.gz b/backend/tests/fixtures/retained_cap_source.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..bcbf119ec7a9be88093732cdd94a2ff4eed26567 GIT binary patch literal 51017 zcmV)nK%KuIiwFP!000021MI!&a%0D_E&M7S{r7WGH4pv8{n3&w9sAnyk!)GEjvb5| z*|0!@2SZCOhu;0J+8ZD@rVS9yCJ7Q93W@~wP?eRna%EOl<$qpJ;=6q5&)?_qWH7pV z{pQu{pGM;!C)08EmuKTV^@FRN&ZECRpNwYXn9ts`*S~r7dUEBjC+|j6-0+{**mjx5I_fDpMI-At{@b}<-uHVGbc$|lRTHCk& zOiPTAinv@najZnH0>ukVy>pQA)pRiZa6TMd{kY*?O^jlaSepgO!8sqfG_l0>dpEUf zod0*0C({kjHF$0`#3pBm^wc_`lcP4g{&ni*;vJ?id6f;Qc_9=YO?V$QR*Ts z+9sY|w88RXG>=*ungZ9^(X!<|YyFgg7>b5ksSEU2G3{a!PPnxPOlHGPa>D&eC=#6K z#0evuq&!61+&`IxZR#nRBgPo~7MLem*c_an$ z-E%nn{VRM~2II?DSEKgV1_%7`RU8iR+pFZK{x`4CkNM}5-@F=)apmJ|*pYwdIDOT$5Ble*XD4Zx{c5 z|IO!LTz&S-<(Ku3_VYi~AL*+vfAJp_4V+EB7vH{%e44(vRPVy~-?=}C&p!n2F8}b; z^*4X{=}*7=^5$u8-@X06zl24S!{5JT{_lSn z{_q9sd`^G*({I1zKm7d<*FRhihd;dC@a(UC{POeZkJI|cADgEBqdxmX`d-c=fA>?o zbpQLq_g~ZB|Mu+8U!{{2^9zmHdc82$s#{^5(yssHM`3;#X)DSY*}DP%+c@%L}*b+a#qpa1dgH^2Yx z?a#Z%@AlspZ{Ic_e~#yTJ^tg>x9`LEKcm0D`{K*DfBNqBvfsTO|9SSy-!6Wgys+|=i{()}U6Z^q@ze{AaWj~D58tK)?}fA>}U{WotvfBV~6 z{q3(8ziU2ejL6mdJRDu;7O5{T#`yy1c1MeQd*Ad!^QhNgvGK<|J|E8-<{15KvSyLz zND+sAaM`@R`3-n?4SWCuHU^hdt_kcl7k_2)4P|dAJyVoPBYt?jxcMCLm&Xf?XEz^@ ze!|D~A>+|(3PwW!IiqrO8<2AS9pa5zeaB`Jkt%~LC07QQi8Ma>VwB0cv8~ts!*Jx& zI&&!8XB`Za;7ec+lm=!Uw}D%3boKyP<{UG^bL*tjrBH4yWt@RgaB$cbejDUmMMah^ zXkFBfSZyQ$(FGxKG1F{YX1a-J@5wZ(1Quia-=oR&FE^G$G;~n5BSeNU+155oIzz5)&?^9 z=j%8B>AIx1o=>1bU@m+hyB4rb8`n=N2Bp znpbp5ar4}JV#V_wEV%G$leenq{Jw?)ueU1YVnyauB+iUhGEt%7M`{K!Dl0L|RS`vi z=-O;BxPe+uB{eepA~d7jr*DwsHiq5Yw(QL}_g-W6w4@3CS=C@nlljv-gZFEFXNy{m z(|!pWoED?-&(~M*-6uD0efz2|4_j&Fb~@kOI;U96n%2Xy(7XmvMxpBHq`~f1*q>4R z87R4wqF_W#q)GF_w0Ay;Kyy}}=j@;+hG(uyP&uX)SkYRTnBjxv6JI;=wG&_4&e!Ji zEYZ(A7Z%hY^XRmIT`HMb4Wr;ib)iL6&RC&@3>vgVMqpY{(Mh2s&q1H&*&XKD+Pm&^ zo?UO$^KY&{v+7;*vhQx>x2)%HSI1_fE^i!z&cENk{rt~A;s0M@u7CgSFkF5;{G<58 zF#i2-*O)gy{_*?H=YM_s)1UsfaeiNa{!RFykmId6KX%d9t{U@2;TY0yH2lI5XsRLO;Uly$fP#K*=Us!yd+J@=b7JFTvK( z|17+5#wE&|7q7l!b-+0q?Q<86}m7TzX=psfRwEdf;6VEH#YTBqiJ%5q0;CTUtw7J|BqJaP1lH*H%j>wOHIc**HmVzFAe{ zTug!*CJ({dM3qk_IS3Pe8-OJwMwyFH6s0^|2Z*R7m29=%@Qj>Xdh3=pGYYN99xkDP zL&p;|FlNVPY#i}6X1&%fCGq;?6kb@0$W9dassg@}F4doeB4-+zs!(AITm=Eg$cCJm z3$X;&dGcBmqT(TZWMUnh2aJ%3cuNjhHCWtsqQ!t3f6mo^_@Dp0ZbH)+vm2@Yrwv(j zK3s=BDH(h@FMtL@8|xWh!Y76<#_rA5L-`FS`BkKMR9c zgYZ@K|EfXud1$Bg=$dhwyRKW>ezrVZx7V+YQG!JUz7<#`sCIUW!S65lLs(aX1DFs+ zLU^2E@P`3~35jo&) zy$C2+tdJ~HQ-CEEMF6j8Z%~>!W}Sp>M%yKIx+oYPTNn&QyJk4J^cQ*k(f%Xw$qyWu`5?63T z9Se@S1nWSRG{Q#OJ9hKn*S+6NZu#ag}d{1HmqYBS^!2xT=a^_ zQYhGB;w8>gB3jIELq73(c78b+4hQv5aD%$=mVFuyuJZY1{Y+5We0u4B9$d~Y&lllN zP~zrmZnUjm=gSeAviO(@$(b?S{@OvR4qu;#M$Z~KFG8=)&`dE2S4ZI2f8E%e4ff+6 z_}aQc+-PQZuC+}#TPVxjBlw++l(l}`M>;}p;?X1zTMFOp(!4o~45a(bCOB~Ax5i8t z$v2yA`AXwFNGvgd!~bFmbH0buQFq5OpLA+h z`l|(fntzGL+V!iFtb3>eY~WRvKJ0psTR@21o1 z$(zqUn`;9pgP*6faXza_F!jozpERp-gEHu)O;Q>|&HqQ~8`_w?+N~WoC>YJP8$z?n zw|G0Sr26Bxlx?o}-OrmlRzGip558TzyZQ3{=*P7OwVy3Nr2TC5{!KZ5P{@XD+?tt% z1j)W5H-E%R_9T>Mw?ddUh~k7VM6fKV4>1KHH!B3Jyyu=c_-{mdAbc*_8p-!k2ogr4 zX(bcacUKLim~ki7*dR-??`R&bBtce;!(+2@B!bAAlB2SgZd8(rh|FselCeZ3txYVz z>9T?vx0ap^u3GZ4MI+_{+CAo0IK{V&d4*qeE|Dg}wh-g7X+eh`Ehy^<5yqI=w|1YH(sS@xx2C z00?bXh=sF47MVDQG6pz+%J94BgtO9#XJi)EMA`c2qcPccFb~#|qVZU5z*mcfCnJ2O zQAQrQ-J~N$Lq{T$aPmt6nRHGk9iwQo%RUuoXic5Ii-O<=uAY;E>^okEssZP9^&%vT zCniNQ+}I#YaYb&j9k@Ey)h|W@Q;JaOij#>_!Q!V=194VYk@)^UIKHci4Jq zXmKLjEv7h7Tw@a`BE}Xrxv=6?U8Fb->tVy%C;g8Z*1(7{3f`0nony5SV|MiNS*rm!iB>Zu79hrKU!a0E<8@ zO)A9TK;AytY&C{%bBY%6hhrbvz5)1%k+lZ%-=vx#;c7I!C>@zhC2V9(*4TPjKp{bL zxXQ4xCRtXp%b#Lo<(adBxosm`J#H#9_eVaq{X=lb*tQF|I#i_*5(A|$T3JgIoXuW( zwKTSit7|kaQHf!VnkeOyqP*@GliSuu&JJE5x!IaX-$-*-H+fpOWt4AU_h#~8GR>E7 zZdRC%c#&i@n}*TPXK66G_ESLAxOb@kwRYaj<=|qG28nm(dDiH#=JPl5UnJSn&aUR$ zRGE2m8x3GhPSQNPVfBjkHOqqsE6LbjseQxj8!FDI7OoS7Sj(JYzq#qiZDK$@lb{|+ zu-NUnNL0EQ=Lvbw-gpl~ZG-ey+vueb6jLR!5VCYGIR_-9i8<|@)J`Ysa?RbPE`ZZS z5SiDTUb51PD-2#d(oq z$ST8q@j)h=84EQtJ@UdB(+uMfoK&5><4^GLb*)=Uqk2gA;e_MKU& zt4rdGJC*}kY0E@UTPAwyo9K1k4gH7nD}R|+=EL4uDGlIFa=uz>4n)iPvY*qJmLDS?qU!|27-+tPCZTsnD(@SU9=`JJOF7#&t)*0uWp&%Mn)fJ*)|bd}0@Pdz55>CoOfv^2t>K!?^-RGy+$+mT>$(x*N3X=SuOi9W5SxjYq2+L4}e(xJU| zXlaB$iEFpM^ta;Lb=UqLMV0!JVvg0DTO7T8wm2hr@XI{V{ixd3)r1$SZGE{qN3U&l zTXo%>J$!%CwkM%&eJMmouWj=s&y%J-1x@SAYC3vNTdb9y6z$O!tvAo=SQTxaDRoxQ zFS|XmH0J5mX&VbjKPOg#l0GItg5&<`|n|uut!1K%&&Ag zz>`M9e10+ZSJQd&SM&Sr3l_(Jyn=N7MIOJJhxK1AC22M{?KnrpYQb(5baBV#Q{v{` z>Rz{%o;CNopfcCMdBuQMD(9w5K!Oi~2gV zE%&ru-YQQG9kJ@A1nEX=i_>l%8UcG#tvKY`FZN|12&#znWb(&!*Dc95vmXMU4wS%)>nM)y4DM z!sPK?ZRR}Qvs|)CiKa})WMzNnO~KNhFejYxr6Un{N6I;+R<0)g)tFxQxc}Su+M)s! z6wm}2oC;JX>+5LQ9J2FVMjd56HG~7ru5 zps7W^rn@O$4@V!Gk`p(j^}3}?=ttJro6m{7*h+O%9d~z#Txc!LQi9+~EgQ8o^$aUR zy!M(1PFdl>dQHvospZm3-t2t_+$#DuEkEh+vFI7Db_#G?zD;JDbPn=hZ@)GzYm< z!$D1my?G3kP+fiBSg}haD|4oqz)z*m2dUc;cKE&t%@K-VPgmovJzJXK^Q~M<2P)oe z9mr3o<3X4;c4X1OnjYSK*yf$oKR1+W2iLCY{k0ID;ED(vL0x=OzAc}*Td303jp?^S zU3-3AE%CA*BpVo^n!>1QbV4@3I2>IJq92|w*5f*5Ps8jg4fFYEJh&LlPnA7vQLgR) zhJf6Kzm61=I2r2sigB_qz%vf$B)J^pb@#!QVhKRz!?Zgqlo%;yz$y1}XF$BR!Oi;t%2%M<9<3!Bfhg)N>V#MSIFH0PZ+ z9%8#!@q9eHTAHy9w$`Vu(v>lMpM{TC`vCi*pq`2-lMImszc~Sqj51?mFe=FQ1pT{D z+mxq%Fl-uM``65^#fj5{nz6G6k}z-v+?BY92EeaOB9%mSahp+~5Tmnz7wKziX;GMi zO!!540LW?tAc`N(f6QG!wn#~75>cj59Mf>00mQu4MUS}In510^zGzsD%)Ck2aHfUx zn8`}dkG5Vh3X8Jvi-Bvn+N|MX^HT9`R#u!ihw;rDm0v;~ z0*B8B%1ff-AcrbN!FMP>&lK7W`r(GHx*xpdb zW!>FPk52hzC8a`vIKwJHKuT8wE+Tsv<#!=KpP7->41}VC1foe^vWIc1F|(8;h+N2t z=TfK$Q5l$sl&k=nsZXl>_qZB;cLKBD{MeGmsX69~<`@i-pbv>-`Wiu%bp6_YA6-32 z`&*?yuUlg)weHgCo|(|L`m;no`}hUyo=L)0Eih}cB3@ESlmG<7#}t&MyG;_XP%tkV z0`WA}D(BL`D}j7V?42Z1Tj+X{GI8_{lnE1tN1bT_MKT5U7c(!^Q^fIwkvanOB6m3$ z(C<{r15A?p2!7w4*&a4Y7Bo0vl7xy_tZ-7C6~H|pr;z=V!IHrx`uz4#^Mz^a=S=EPuMEi*IyJaWeF-W>J z%kQaqeOancpm}{sh)J*lEL^*9relbd`RpU3glm}qv_oWIFKYwi4AwGzIGB$1 zt_8S}vt0V02bZ%;kdB%h&~&nDh1x67>@V}=8vguw0ins`xb zdi?lKYP2=UW5<~po%>o%UkpT}Py3~T9JX4swEnSoK=P?Y)jr7r$I|A)IZubHRR-hB zHs(_~z6YM)PL1`I?b`*mr2`3WKfXoA`FAy|Vd>)b12{P2>3MevZSi#;U)B}7J~d^I zc2|;bZUJn}hP78|TU=|8N*CQZu)Yv-GBJ-}V(u1w?Tad&Ow2YDb05*?mu+Ht!~Rb# zc6~B2{U(Mx%(TZbF^g?-TW!p}1f4ge%RRD^ux?R-3IvUeW$$J(3q?akZl zjgLQGjeY_iU)=L9*R96pUKVejhOz12Y4gCwX0HhA$=H0#9ZwsL&GM?RkQ$)+Y>mxc z%h6A5vGh~!$a<#6rhixB#~7QvH>b_DXt9!={PncS1Obx8Hb39L_k*DigCS=6`OWsY z*;Q>sTMKkwo3VKZ%Z^mF`^bIo^W}l2`C`1SZ%s{tddAvS#1voN{P+;ad~XSVi{~uB zYB9p(J>PR0-O+(w-2!nV-FdRge1&swg`0oc;_OGN+(&Pk+P$}+kMM6$x%YlJNLv+d z^TsXd81G2?5!LZtv+h2bw|WdK^`~m#tiTZ2jn^3x}%e@^&)DDD75B zdVE#ApWL@kqpHiY1J9t^?60az)_tu7J$62TSLC)x(amSOjjt3|7`>`qogUtHKIKUq zgXfOwd-rbxo>lAhK*$+p@0JHnKAY3c&NbuFXu8QQVa8f#Ljv@OlE zVzF9eaB}WTNH!{6xYO3aghpp{5j#iw*N4{Xjg43u`z1yBH@vy!WW|L`$389&aA#Aw z)1P1Q+t(v-vZf4BVuNNx!F*8fgM?7~J@bVR-pNx^TV3CFdunsQ$KhGv)rq}YABUCg zs)s}jZ(X9BdB0ygYn3x>b1}M)y`wc-QLO1xR%+t4EhO2*XyK7^ z79UW__6kKEq-1-U{yQjHzqLP9$$IQy57I4f0NvyKgB2>+qdIGo6aWOc=ERoZ2$Lx| z5p3|Lp=NFTY<|wg$|~Z`cb_CY-`OD0mGNdB*$-OVqdaz=8?Z`N_7UcMe?C|6(xarr zXPQY(r&C_QVQ&*ewg|I{l5ZF0eT1LxEX>^y(rWK44W{S${q4U0db0e@CYpI9@vN13 z<7;d>LSjccMtcv4(@p)!wUFiflF=~VY?|=}Q}(=0tx3z&hQrZM4I)p+v)nx`p>bM% z-VjaXAt)WBE((^BrIcl{z%MYZY@E;(Qs!P}BXjU96%0ZuAVky&R?{MKL#S#YhIuUQ zhUY9-pnyRfjq^=Y7mEx-Ke#-fT>0zCyHRb`e}3J#QOQduOpOV-TF^;GXub#4BD(lQ zUC>DdwkHdgigVN5g>*GQTjTPwM8itgN61_RDMkVL0+>A&~aN#gqS1t4-F@25-Bscsn2Zo6DEa zz`)q&afSB5WHM{G{LK=~{ENw~A?vr_l=0~D{KmFys|VF9lkP?==yrw$jNPiESB;B0 zU%BwJYOCMpmBJEB7tJd<%;!kY6|EDwxL|?-c;6^whpb#SH9*tW3LSkF|3)#+#^W7@ z5DnKIrgL45YbUt90XR0*s=6(FvaC@VeV*OyA6qOIv`;o52*N9jjES5`rwj3wI2g-{ zQJB}VT~yh2E)P17i&-ri#4;x$W*vl~S-Z_guq@i$_T=`Ahqc-pOQW*-&C00W4&)sd zX*xG9u(Wd;+H|z6(~CoYZpUR&A$y!JY9Y@L^IzJ7wYFe;Z~d=F!*(S=Jc27FahH?9 zUlC3<{-CPVl#(KYEQ*B?lGBn#*a0q!DKx_P`Qjb~+q+V`Zs!~c?nhNBB=A5?)8m5TAu znH)r++~9K~tdTZl>Wmbc6=e&rU&@kPD)B+^Un%ajlC{($3q%HH!ScO@H%7C9pIk8R z`{BP5+8zr3B?1w^D7>s*2H+rYygwTGg5kecCdUl_y_J>sfq!MRb$d|z7CqXMcOR2= zba&$rUD8bAVa#L+7oeU1DO4m>q$s6JoI2HS9CkEmvkP#XjDKmk7CAu+#=~QNDse5ctTUO zMX~}}@Rtkz{W5vc;IFk5;spNB6Z~s2fk6vVXLF%$NB;f-+mD9)bsYm#KUtBvirM=R z7#EB)6)cBhNXe2dzEG>-B^p7sqSmP-L25i&{~*Zkq>gaJ6UmNw=qTrn07;5o>!2Mq zYR|Bb#$ZTyAoLqwSMMY7*}#X6+-C-_$h5`0UnunV%H)Wlzv#*{5)_SjNo?RY`DihB z>7LN9Ew`HQ3;o-$Bc_xc91?nDU0W#vfpqV55VYQEk7@fLkql$O?&bX^j& z@bojcbt?&DHL*@4ssv0~;Q;7Jb#mPCkduk{2G+$q@WMbbH3XOwaTs61lk#x2XpAN8 zXCbTJg7b`kPh5gifF1V5`dPkk3IR(mt4?ZdbN*;^h3QZLz zaW7<%rr6|SD2$tI0)Lo{;*04>I{v-9}&2-VSW0O(J7j2U@!=&xYT zFm=&zhHW)Jkw zrBvX1pBFgs7={28UDDJZ5L}2#_z@gMk0g^ZT3Z6o{f5BSB~2k}NLCO4MPSAVR(2SI z?Qr>gEJB{nuImn=vvwoQ(HQ_IbI3|rQ)DsOYRHEx;JvLUtythTqd`R}Z4lgPQ;JB6 zN-mRdxV5N<$@e$HsX`@@$pxY$L>cOV*USqR9OpovJr@UHGGN{gGywG&ksu`T)EFWo zjERMKtWq!70QAb_85;m75_{SyKTLZrHOFI1MSbIVeRd?7Y3F>(n8`cne}HS3>j_MC zkpQz^a)VYy&Gw=H4KS9veQ@5`dj9yq@Y zBaeainOQHCGQ=C_FsVwdm~A|<^-O6iT|H|2l;yKw*qYHiZv3a&Ib~?@DadSTN?sQZ zGvMl>R|kY$d^)Qe%f$bFnY?KHcT6*OEch=eJTPJvEkxE7 zM6aroETYL;2^W<);s5>-eSclgY&t$$&}4MlpluFbh+?TJO4Fb-Wr0Q*2B+aAz!$I} zd*I)o2d3fEAwf(0!}tQS*4s#eksP!qO5~dES(9d+QPd?-qD=eQ0zvD!6o=UYF6ueG z34VyN77tEvmqcOSyx@?2zf4}TEf7X4eKbLTQ@13CEMeVKgtuMIL2!Xk$sP4BGab~9 zpuZ=^J4I}9i3H|s6jTD_+@V4L%h}W)f5`uOG@18udb6eYxEFzgg`)r}UTVz9G3u!b zDGEusjjV_aLyIM!>ts4DLmOWszAG@gNo>IjRMxnLrOCQLY~6O>-d`E-zFa z%{P2Miy?*K=D;-o7))ZQNyK{12+dK}@*Oti@PaKyuS}ln8UXaj)|v>%Vh+Lx2TxXVFufZOpPG{>r*%?EaVL|z&LwYQoHOsG(O za!ag8isWDfu&uZvA9>X|hI)Q2giC&o;ubJRH*TXWvvYm!t!-6flFH?rSD2ceHO~aotOWq4ZrSc?=sN zBP*ELnkZpQwGpuSTqokt{49;tDfDNS@&X%?RNc-aFekZnn$?Y`d~=Yg3!!tP@O*4R zyY_sfwjf27a)y1^rqumFieU^B@ZVADvUN30AIuzloh1=5&WdF%K?()fgqP*mY=N_k z9k`JIZWA%0=0O=e)iY0Xj8b~_au1ooNU1hvjx|)FdR(Y9i15nUP-uk z4xT^50E!|sH9k8lJ*|6;f%sHJT~sMfL9A9Y*bU~hu#9slkIW2c&gr36K*$;-(Zta# zh!DP>sg{}ZFWCz8%H%~`0a2~v$qGDQE3mv_q<;1O7&B3`Q!WW7c_>yU%M_)>6mN8d zr!Q5Zz6k3Tw-tbmW4JBz8)r#1)2@JufYwxSIMHWM$=02G=&he zm6iqz3jVMM$#D^ZHiE+rWW|Z5-hh61%eCAO{f#!NTb1)p=pSQSDAZ-1@NScNF3u_X zf)|eaWpc#)Uj%flFb_qmdvUGQj+S6(yCZ8K^ta&8`y4gepvPl?f48&M)PYXWXGvmQENYXYdUnqXcC zFLH@VY+6jM6Jirk4)cWvkSuk54KG*p|3(S#-|+pW8H*nwvke~Y0)96*%QZ(EoY`v) zEj7YR?{eWWb{^QtCfS{%{mxI`b?dLAV~(b1YDvu)nbf8@8?A!bEQu=>xMAF+TuU-p zFJ<;RLs`9nbC)PTv>9t1<)wDi635^dFyZRv6&-o&?atq@v0leokCcowC#Q5QrHJeV zJW%v9gQC_M9-YfHvU6)|b5;GC+uBWc7 zJ?hrVzJA|*QBO+DO7A3^AJKtYW}11bLrRP(Of{dOl#FWQ>RE}!3wT~T zltKX7$6#b}8r}xJ3jOcg)@uRwSOb-|=tvU&jzUGov+q1^XY9S8K57k#GdxCH zEuGY2owigPy^U5uF$;csAGMb z4=<~gxq!@<>$8+xHh zU9Bh9LX~rH&POf{7|)7Lst(`EAOd1y2#%S$te+DT+BvI>=dchJgbD;+GJr)n3j1dj z)iEVmOOOJJ7I}aRuKD)czrHGipQp2Nel@s)Q{soOT0eMjbTQy13#1pO{O9Dono;i()k?hpLkCMR793n0h1G z{WN8b&{m?d?B-75==#=L-j$)^X*VqNb(>W3YxCZ@=QPzf>&)$U1J>th!|oX~>k6oJ~xu}sag*()>uaMeRyeB4{@bPovV_?$PlcPHTLhjUfg z;t)Q_0aUMVyRakd2WJYh$VV6Vvx<2SBBF&5A%a+$>>?-%h+&8ZEM4&;@HtaV3CR?< zh6P%z4_O9l#S4o2Nmh$QaYyRre8LO0prh4bmX{m%>zBz(j{8|nnGvVB-zn~Qiu*mq zxZg(`zEj-q6!$yD{Z4VeQ{3+q_q%i4Ptw#vjIY7Jz!f)+`kImUY2$u%qmPt9F$NHo znDO;Y;ZjtREI4Li43(BF23RHUq^R=8WVEH$cul6{?QuVRnm&A*SYP591`8rnBJp6f zw;pCWWN2haF=c^^6w@)3@uIzP9=6F}?-MJ-a0tXA6=sxVoNA;kiQ( z2lcG{-r%3BhxvPABhSRktW?b415!S2eQ|0e%K<(K72wq-7X?ZoIF(LeBEu|&V8G0r z79mrwnt*rGEPBIrT?KlG;9r!IGY*eQ7npAeLP&zn9){0*Bfzji*z53lc}6*0g9B5( zWwFEr>WQz%b2BZeij}RF7kuDkzf7L%@nO&->z1|zg8d(2K+wO?GV`tp2Xvx z7g>bSHj11q6A)ENCSb}6rd;*tf>us2W}J((&=7=_vY29MVAjJFF!jKzJ+i=GuN9A- z*M@kNOr)NnnPoq~XH;5oV98iG6vQ|ls>x;~fIxdDV{y*DT)^*_$@2w#puOtd!r6-u zkFlcDKXbO@{C>ABlyd@yE>4$2aPvyq&jRM>MX-(!=YwPQWcC!3%K&i3sLj+_O`R&y z+nlK73h*zu_Zs*gLHJo@PIDh`Wx@8vzpm1Qq_UI_Twj&#r44XRlc6)Bo%SFc;Z-zTm_2G zn*ETNQ)=abC$y_*hzShDGTBII%DUPwC-@5vvGmL2i1VwYLdSTh`^*g^R7#)wc+(K#Kw1k==BV*olc>MwUpLm zG<@F+pLM+&@EHo{M2TkMI8s&0tU5wHXO_x<6MvIyRn;Z!|3NECOyj9lSAT0p!R2>M?Mbtxn60y=n!nI?` z2Fo*j!9`g6W%7LavXB&>*FJIZEg;dqym$~DR={z}6|u&E*ZNQkA8=c!IbrPyYaat^ zwU&pLEYh{OXJoZpl88ijrhHb#)%eVd#oB(EJY%dijA?no+6Tj0sPmuQ`B9^V-5wW}L~waCFT zBUzv_ng<43Ei9yHR85GaggIA$W6_8Z_5)kV@Q4Eg!CF>e@dfY3pDGnDSxtipFPPZ& z%jEfjtz=*$dnI^mLy7xGTP+OGwp4_Hr;%+vhFOSO`S*mjC$xPOv=u;u1JBUbb%}{u zN^B^UXl_DsGJBt1a5c_;nLJ~(mA#8@C#=0^tnCEG1D-Lsy66PRw*fA^;1UI~In)IS z3F$bI?IRyvP|MFmOS!42>Zyj0u9fr7a&35EkusOz8y20IklEmWI(tbyH<{@|<3j_k zC>n^83Kl{K&4t_(aBa;PKM-(hWyeS(aj-VTV?a40_{rhF|d^x?gRx`6t?($}gcobsaJ9oCDe9^=( zu7L8!5yoNXE%07$Ik91}1M&FtmAgatd^Vx8T2-Z3(I3@#^}4OoOUH!<+w1hD3icuvS5*V z#~2ks9T~_wD)^x>9jh2Ii6vq)fgRxqrDR-!GHri}FtP=KSq~h!eU$S#%%G zreXB+SsF~PtAcC*^qSQYi4GOeg#^J-oRO@h3C?COy?WfGS5<^#6dr_QrZ_Kos3(>x zU4%$rWwa!vMWG=_U+{$$xt=Ul>uMFD5`7RrFD^fP?$~I z0G-u|$iy2(-$-*-&&0ZOuFHG`qXu|MUPy4pfTG%ZoFW{t^b+gE?fNKq*FjG%@Qbs#pU1-e(J_gEX6=1|uU_S7~Xr?tXZymsurw4&? z$FswWRn40LSiqJL8?z>gX$N%o7+$p>j7w`+w-ooCV7x$)a?-?U;Ydo+tK^jNFLF1| zUNU*UFs_t#=Bc8%*OL2sKD1G;5E&J$EVvFxHDyeLT7$5iP`r!cO$nB+6Ez<7E}g<0 z5@Ql2fjfxV7NsMTsf6;_OQ+EYp5QuxmPhzq#eh{Y$9YrD&jz0ihClHfqNF?*9Yxgm zLubzXgGJI?@G!h^n8dnuOqvKaqY)%q+3fOuU=HwS-OAc`0P`vqVp4*;3E^ORSSgKU zLgesb!F-2Io-3HUGYLlKTo0OWhld9Zu8dG+&!tP4Yx>new}ZU zwbusK#=74k5En%~xK3EAcT;-f5H^qfsTr~%- zcmNBKnkrMO4?t^FM~C7A=Yb{Wr3*17V}W+sDDA1wECX+hW;8s^$tvD6cpEN}kWJ0c zt4G^Kn}~B-!aKD-N4E$4SMjLQ{k!$KC zbId3&qXoh@ne)|?;n@c$x=y9KHA2F7wCsW7J)zRwprNQH8Nw+GMr%%ujQapSJF}b# zb0FYn505Sx4JUzGl9UVD_{_5?FBkCpW%67BpPx}qh1FcMHY;ErLBNN?^2?H>J%`W!TsUz9~IE^GbL(uii3dO zvdC&+MG;ri&qQK%(>Tl{WiJ-!cgW=V0=+d%xg#m(a02>MIftikHo@`?a?mej4ntz? zDKYf~K^MFy%qtp<<3e-wa*?=SCNJx3g07~`ORTw5Ifv5`;~!6#6=O-(1HVjhOo0a% zZL^g+gcO)`Mo_~_$}$A&Jx?;%YduXONSgzX4@{R;hVeEz!w3N$1m)ga;{t1q&@Pac zXUbAa56gqGwwCa%F#vcvl<;7WoS! zs6Aor>45ROfUVT3BqNHI%y1b>7FL#!s`H@(kOcTO?llv9K`Lpe`D@*+=YdqUfXM_Y3S1*H10Sg+%?lmyTC zP0~bM)KSSGl6Nn6Z{!Y{JXf@Z9@(n>C$v2kbU37f4gi&5U}BQO8LzVus%}l>k@7%U z;ZAa?gmisllqWs(X4{&!ZFf)Gp0@F8+qSJ~+qP}nwryL}+J66g_S5cuspO<`>gFb? zRC1sD+(J_KAji@gGAd-xTO@)<%skx<3fduU3`SKUA1~6{?IAaWsxM7#g06DiW97L$b2TTs_3_fyNX0;v42?P!wDNkUWK%q<10L)&WFEzW zs3_tQ+(6Xi6ymFeno~R9+G=n>Cqp?pup{a3Gb&aV?gt0<;+xp9iK+Bj(@2<49vZI6 zP#xw~NW)uAy=*h!c9_*!+6*PpP(#l5B~7aEurx=2dt8>37PMw$jIu|G-woUq|Mfd`vJ=PNR|MS|Qr0e}kqWiH8lM^YTyJbR zZ6sGgWXl{z7Vk?RrD(8|w3%W3VO#}f49wA1n!Mqpb!I2@f}t``^!vI`zyQKZv-r2vcCa*2M`q#}kEY6k{yBr7X0}ln zwkzQ8ismPyAHH!Evbvn&Y~pA?-d+13S1OY~CB%d)DA&Lxw^F2(qh7aE8188ic%}Vd z&bBc@+Ddunu2;&>LMbI;`vjHnI;QG0I?q*|McQ8`Qi$=?I=cTi9Ip17luN`@kY|Z? zMbSaqaY_XH^&Wha-qN-F^p;dXD`V81Q39Y@y4REzK43nJX_HJk(u2vWvc{>B+LC(` zXF-RXkOuwDn6w-OdDYPW3!YD)Fe-9&5cZD653G2w?7=giqum~p?j=#vz@ZNaf+lx8 zQLL&8`uJ#A$K_{X3uskcRR2;|$h^=PSO*FV9C4asLCJ6qK1kekz?gb~9?CHkg`~EM zO#C^@L{le4Vx9H2HlVUmk|e3J+KVNVmO6Edq-l-4$|)6;dG4Y*F_Z-qn1R`mj(hNs ziMK-rjW!abT8D8=;dJ++bq>$8Ao!H7}5J5as-_Xe|^*j+_(C3_%nlTWdU zk62?rF6_0Cf>Y`IDRY##R-V}#T6E;V{hi~<8;UpjVt&qfnHrz*b4@yODL<*jREA_4 zQZ6s#joamk#mL<3m3zX~G2#t1j9FU6%`)lzD^P|+T}SDsr4C5-C26HzTsHorMbgzw z3znUvmd$CLl}yb8)g>244ZIV8It3CZ>9Ow~$GU4-WGeaF;yLf-V=|xpx^_UR^8mBY z0_iqo2#R{5Dc-LuMYB%-XTQMEs#)++SU^DS!MO z1F!OJ#g^-#8u-tyh3L|ECqls->SCYn!NJ6Zezwcqw-hZeyBsEv!gv9LjxJsM{Jyw6@?-5lTDPvz-4I1ADy!I5RhX(nyvUc$e zt=!foGGAl(?422xu8NfFyNsX0Tb<&LM73vg$pgMX@hfk$^zGK}{?>)Bbsgx0b$maq zikAB3FTP4Rvr-!z9^jOWa28^0MqFcSN3~(pFtl*ZG9M1#6N;PmCHX+{AERzO3~m3z z!jDn+0-KHDe~h}F*_WnyJ38Z+&MsK!t5_+NJFn4AcYBxww$@t)+5elOeD9L*Jp@PC zSzXdr+>IIgtC}=UnOsBfRamj*Ws`dL;>9WqmO)1=X{)!!nTor=>^LClRPn-+R;e#p zhAyN}h4?xaT>RRZc=3IL4k0bnCkZF7k4kIpr4x!Bn;gky#`e zrc#LvHnd*dcSg+ZdKdzRhqb{Juj`S!tz2ID3dg1R+nHB&Pqxi^AjSd)?}d4m@P_lz z<|$cod4}78Z~PT?-W+P!2G_06+BnN5yg++UNBD|P!KY-TMX7aHYs>ewd%G>29yT#( zou=RQZn15J^-7hP+P9&#vSR|?%>VIi?WJ-48In%jYEA*h|46pf#fOzpqI&a?>Jc2G zVKl9I(cpiy!~5jPqH5!wqwz2YyPn}tjoG|9ueAn{8iOlr$h;yL+&7tgU@>g*6b$J6 z>6z;!hc$3QA!pf!3{DAEV8Jz`*zpzR{FqpQ(s(4)xvYim`O4@wvsxPT@fK!50Ob4m zY9h%(N-$w5t;)wO&b$Xtmmdy{xCrMt;q${S_vRd}<0mOkzXi=7&WgU>?KnGla$?+G z8LhJkTj!d6vKaoDjqe+hlbR0Oy<0+-aWQppj#&zy-Oei==r87_86a0j3kU}thnQ~p zh@9ku=1s0K{%&dOcVL!vhcxB0^r(Z%Ncizg^K;@;?%R(wQ*9?z_q|`NeKk&#BP$0%_8` zcw|=YYiz^BluRtJ1`#19YPJfCS59jL*W^<-=UMQ2w5jlB>~(eMSdYY(@a3f1UR!m6 z5yvfHj$4XqWa-=j5wk+n@4!s*n1_bJs9 znH~$#=H+Qt)BsNGVj<-+0VSLqKk(Vo& zeM=Q+=jA+|cM~&927TL|>xu5y;fPw&i!0=jt`xpZ#1rf>$M@~H?y-*F>EXX>40if- zzf_u5`{7@1Mj9HrrB)bZ$9?%LQZYOX_=MZ^%rPdcJl-fp8$(iuX$1ijMW5})c1y9X zQS$YhcMZu|D=#yQ;3V75Ocs<@?AwT`IYVcaRU-Ax(nSuu@t8{afI#zn+*eu2@O{k7?HD?m|F?nTl)iYUPn*RJ+Y3JBqpB(TTG)$j- zELJ1Sagd6&qC8Xvm_i}a+NIU`O1Bv_YAx6FOGg;i~9inkN{FOaS1lq!O1)UEn5f`!y9cjC^X zq8X|nY1w+LeB)Fq@hvlUKb2%lV>HlA^LKqvHlH(6mPb0a6xyI(Y%UB%IS8f70^mMe*+O)l<7~BQvtscTl6%sRxsz5E$blV*|3hK zI)|KLFU4zA^5hGa@wP8^*(7xdxhqm}y1Rj}DI6t8AY2k8b|ia=M>1nDy-K?8k&1gs zP^Nl&7Cc&8tyJGQIr-9 zohz-=G@%S_P+ZqaeFkcN>WCi%i$_MGWE5hRQ8r6a&iGKqo5T4lFWIQydPaV^SV{iw zCKJ%RiH?ph<6m&~v{~HZS~W6QdeW~U^*cruw#r~^a{1x3v$U$lfK`e^`O@aHBA@KMg1yTyT`!+y|-K zvS%&9l-Z`Jym1+Zqe~2;E8fn^Pg7|<`m?ND#%bGgFBc+ZDXT^b7WGR`hIyqqROgv6 zL?7h=gTi6}0_#a3WF&#)_87}YyX25I3Fm+E}ld~A#BFp&PbY}4P(=ARN^tRB7ucm&& z-epTbg2`*nO$I`W^)-0*aI_U1))W8LVyeQ!wf(FaWwiz0)7HPYqdAi0 z7})No?^Ax6=lrEv-s!O3-XIeF^tw>RnYt2*(e}OEOLS>H@9uEZT(EviR25*cm;X5M z{rcSU7_Hg7eg5`pVM1yj4y6zi+Hkfp0G+CQ9ux}Q>0rfNAARy+Y4mYAG{W0%nVupe zTsQx#Akvs-hrwr2(nCZZuA82E>e`iR)-ssI&}udC^6CmLu*6_XEI-vuCoG@Qv*%Fj zUO~Y|*@yyK@HrP6UqhZ&bflxZ{R`Ln@ec#ndd_iKbgIX#kC&4SM9!=3Z#M>^_Aq3G z)zMG=`7KX(3nTj-o$4XUnWw0ziknX#0Q~F)O&8h?bb+<~Lf+#VHpdlgv;CnH%VhKH zS-O|jutMMa zoFKW3;O)aso98kx`H_sf=l7!S^+NY)e;{`G(Q8TzDPAcQn^qJ}>sIR;O+12Dt*5dZ z0xb*afC+T9YOGda68(x`ZZ9WRe~^5QnY&SwjbpB1>_$QN+Pl^6!k|7t4C8Daun72` zbMlZ!3YbYDq`p$Gj-Vu{>N#9kCutx`zmOAg*es6cWM{XtGWH-M%VRct}w zp-Q(jb$EVE&&J>j5AbBK@wEX>i!6T-!9RVBda{ z#&-S4&ps295Z=+UKYC>hGjN>9N8F3$oOd6=7aR>cU8nxR5TgT)e&hC8s2?L z%byyN&AU=mUD2|JQ-DTU6~N)oul61yP1{l0(M7!^a|>b?>gD!>O9VY^gPVdwC%+xt zLS9552%t`nN8Om24<=e`L^FCYJJHrsZL06s!*d_BD}a$nuV@8Y3>I;TC_Qc)%$-#@ zj9;p-Pgac-~_$}_ml8alM316o!3e?b074jUW?r9neaip)j8>fc^p z&p|_hveX1Sls9G25s*t|+u5~l@&$R0q_p^e_m5PoBViPD#Pcd9GFn;ah@Q`%+U;Y} z$ml6_A(m)jGzn?d^@Pkgd$fGcnYCs^#X&J%Gifq=CPL*vq2F;qfxi z5mL4$Q7FboRiLeV*t1cL1d+Tf`t~)NPX9-aq2jbqEnH<4)TMB01D7z;K>a<;h9{K)ODW832(EHk_Z1ebq+DG$wAm z{Ofl}*8$!F0IH%)4Z4}uPK|yWQsQUG0+G>wrm(F9fM@cJQxdQVi~dvi|4^14d~vGC zfDq`ZFmeb*5y7VmD`H{^g`oECoR`eFPO1u}e7;CK3Us@s&_6m3Mpbz7LIuMUHoe2d z9{f*IG^1Yf!Nd?B9aa++Yx`LdkTmp5zfP2T*=^O9a= zuLXgOv0I|beY$6L!<39t+;ztd0q>xm`TWBCGsgmbM?9JUbxC4rz_BdHDFJ%_a5P$5 zp_-&R*0?%aT3vYhAXr7-5o={S4P`)k*F1zaAy6g{5^N<9ZRTzLq82S@E!=X+Z98r& z^?_5c{x@7TC4@JLpX?dXBO{KB=|%O@#d?y0&eK|{5>>OcX^nybXkUj8V@Kj?H{Ql= z@`0-F0+igw)02z3{q_BTid5)Cw{MmrW@Aga@5Od|(~AlP74$$gryACk@R8XfRRCy1 zx#JQWTO2lHM3L%C`8@)3G#RqrnmhQ0q;h|(Rv-0o(xVO}e5EL|^{7Qi)J3X^^<1*{ zJKL81J0NpP)8ida$GwZu+$_V5)jUS?+{;#m{P%2KBr+|592d5tLq}l~y_u;q%y#Ln zQq~$W&|c{%BW7v=S0B{g@_6&ef}K)Em#r`E)%p3#oX2eS%#Lj`!Mcy4=9_*KM~1q= z)B9f!Y< zqIY-y(pn!yE~$ie8pGs6ci|CRtN;#%97p?H|T-q zBn6E!*82TMk)*I-iR6hiHB6@e3y8m|3fpii7FFIzHHq?KW1MCqTo%r#Kmq-J=+LWY zN=e<%`8j|oE~S-#)JM09MRzgMyJJWC(x-1p>RcVF<@qT=9{|12Q0L1weMghjJFZzj zalB(&qkHu?UOg!TJTF^scm!jYRqysDYdwxzvG8p@@#$brVpb~jmZrShwJVWj#{FVi zUTn~3Xi}ENG@7jth_+H>wD`?`L$v14E8CYo2+-Kvf!vTpCG*)!;i%1cem*YEZIX}p zJh)IIwB8; zPoUlD$ZH{1pJlasSm^rg?dtDOT{d4=HdXo8&Y%@`*66(+!X!x&n%iZv5gZ8Sn2Z05F$XR_eZIKp6=b{lXq@3N<&6=WTbEy;yIXYz^u?+ zTK=J~dGDgb$j2RMby%s9Iyq%$r=j}^l3IoVXVdW~MWkPJ-}JVe9NF2S`B~s#{I$VVBBOm`nVGc7;Bxp?~i zMm)i}{z`dY!y2KH^sOtMmY}F0`aYO6)XDNqS3Ai%{=DpzT8ngDhSte)4>-~8OKSCv zX2LMVaYV1#@6U2?{pL7vqsnv-c=9{RGT_9Qx%v&~zHB}{(-HmPSiMgtU1Y$pBzD*a z(Umjf12)T7L3t7NMsR}vc#cKxp;NbMp0QXt`*)$-GUiBJq5AhqY5*q1@WJ%q7s%BBgH~J~37h zVW$h0f051Xo2{*#ZtCt}{_?V9D5~eWyu0ISeFIKwxzP6BrG{oCSIcl&`=e*g+xpqL z2VV8adS>k5KJwHMZdG?}JI5I^#grR@+*>+=F=wk~%<1Zn)tZ046(0az#aUP-sFCzV z9^-`iEI0+xm3;-{qU`QTtNTXIB+bU-UaLK>y-kZdr#gc>o%~L-m|2#6>mpjqBumz^ z-IO{Qe*x5uNP8qiaV4$OaG2cw?s$00_l(T*8S~5FK^1RL_^Svl0;lj8B}n5<{CP9q z`moY-1z|wg+n-^z;HiEq(e$Z>H?-~>S2pZ{A{9g7wJNGI(w93YhSIm9paoZ+`z$($Uw)Uk}aoa|G5lh8`zi!p;EvQ)e zmU4(PDHlsdk8;i2GH!p}zMjWrMT*vzxjg;+PVVKNkIJ^Z z>Z`rg`6Ytg6|ta+ude^HSS?b`TQhI1k7^mX5AMW*G9`9`*4-vadG4Y2$FB*?>JO4u z3F)1iszivqVww4Jh_O)DuXu}|6YGLwh~h$khI*Qn;Stqy8p@t%#dt@-%7uGF7s?vW zxOU46t3=!ZF{aqC#24L;=u^~}&?X@^gd`rbeRw&Rv0c!T@1En47bV-08fcGlWJ)(D|L`xkgOE2;dQpP zox286waLTh|!-?OMPd~EN$@0Wpoo3q)07N-;2eDPQ2beZ9+Ftnbyo)Zq~>y~H{E_j9~M6XdQGO$~Qg?#;4iqN@7 zY~)TniW)iysD_%!8DMgK=o09ISs#0)58@|oD^w$+8jDnd`kTUGdc*RzL*_5Pk?R{9 zj53lN-xp}#hrMfr?Hasf7~4&2raKK!*x#?Mx0@B{KvvwvE4*Ddl=7}S`c?wn-v5Bp zWWAk$Z=Q1wjHkft(lA&AjM1QCc#g$^a+mkVq7K_)+L%Jx(>tqvf06? z)bvKX2Bv8@C&7lPP9iClOUeU4F6u7-@aF^<=*mKdrv7vL=GgbhhfcxAzp+%rg=T^= z?++-&Rj6a`JJSQxD-*vkF5Q%~QC-Q=vOeBu!bv_^Z%Ji!Mk{Mxw!bMf52U8=uAE8e za;WKV%Gm1k(Arh0!QU=ayL#!iVDoOnkV1qwJaj(C5w*O*S}V`Q0z?H34JIViH>Ueb zBUI97$y)>~m8xE}u>~<%B<;?n&Lc-+>$`W6zeoF2GflQCYImU(U~5`Fbz{r8%q=Ob z=6lvah&|LuV<^e2swdf}#Umz>g{zQ@T}2W38$Vqr4Y$oNm%{A-QNgXmBpp@#^#C`H z*`CdPq!pl0(nw?M6v#%T2(5_*mh<;nVuG+0ZCQNEfU3a~v=SghRuW2On6EzFy2YGN z=~N3xON}2nOyfk{hm%&fxta7O8)sUPI!!GUL^&z>#yjqoVry0z`FUX7Df@%O!CZGQ za`7prxVRFONaxJZwV9HcBAy-hCNx>@xMwDZZbDuy#?u)1TU`?%Ln>B?#{6h^tGX%P9Q%6g&?{!LZpVC;2WB^)L2|1*EW3)#Je z=J?cmbz39u?ee=z70iyrlB;yHll~iMuOt#Mn>0tPg8Mhhlc+FvPq`CPxWF@r3FM1Rl4qRHiB2XRyhQ1*l0^D*Z^L!vC>sNNn;n$%Sp5I$IVl0ZL?LW!K-n>&oT z%QxdAO4XU*vW7}E`o_19dQ(TcOYch&`Q+BYemPZu%hKh>x@+U`QTCsIE_c16ykd}s z1JfI&X1TRzeb`WuR@>)`Wr+V78!p!X++ECZ7WnZmni~4qNIuyWk+4A&El(dAriFqC6yyNA8wdnLT63VvTEkqnJc77F4Z7m25n7%MglR*D){TXGpFKx*9l?3mO&l9`g4 zmc>@D2&#K`9FjhgWN0G~x{%(wf_ZCebEdjwGSRS@b}vw>&KWZVnG_E+s?78Lx>+Et zp2+$;l-DyU6`Uu2a}27^x-A9#_8!&TZn75&IaUAx76b-iwQba1YOxn3Bw4vo5PxL< z&e^gn5~+op*c5R>62&+YLrZU+w1HMUu`Ni$=ypwtk$%L3GoxrU9U4DBR&b#R)wH+_zqO#kW|1$!0SjckKSXxelB^gYN%W( zPry1|-~;BCgYQqkVxTxu4v;o;`Cu+^fI>DVSyl@iH%6EAp}{KYL9@U#vI;?`xFDSH zzSK<~2r_AgYc%;O@+zN%UK?p4U&5j~MX9|GnUZ7)RkjM-YE==&_c{8xO(XQY9eJ0` zByf(~HKTTod3`q16fTR5!|eLD2cym3F;B5Ts7%ulNf615)kH_C92f3l@}zoT){4_y zNy2+KJtT5cAXZKJRKz&_Xmlqr^}BNk?84`0MR5YVpo$?Y`jG{$$ZfrGrpqXabY+ub z*3vLLOnW!|e2{ZS5J(L7b3X?|bT|;)XKm#o{fxz30fmanrk6;LsRu4)P4(PkNo3$D zKxTG$_F9{20*haLN4MwaYSfzLKi2UWz>g)5m1qSLuwEEg1wEU}WIS7CPtT=_EeW92 ziAP@vu|Drm_koEZWyfJ;{Kdd!{Ai6gWO-WM)Zx?G^?t@Rv~t8~xe;ShX8C>co?t)GF{-wm zN$X*^Z2#@_sHnNE+p!Thz8E`BgtDs*4KG`1f=(%~1fO-v0=fqiVSZri@1d~l2R=ad zHxTpJ&qn?f!w|e&6JR?l-?mR|KnOpJwI~p0i*NuG?htCL3;{N+FK!2< zTr#j9A;pSq6*dxftAPabGL^SN5aYRp?RlGth0Z2YkI(c9B4T0Hj2g{tNBwLML1Bv9yyZFvu za&$>Nq0f>u-`C^6lp?kq>M~5|exLMyDxetB24T{AN>~T!(G}9^Z9)SWQTyRyBxNL` z54YUga!90X@4IEUSH|AC+;u5#E)Ko3I%^VMod5rYu9x1t*QcxJZmu+CDaefy!u*9P z+;mxKtQdud-1{+wnIXW(bT#Z9iSU49;}ucRX99P5`L}>;j-eqz9r*&ZND3vYczsVs zbm73K=aLpgDQF-FNFkuG2H@A_`8`|oWTd-st`wlDykrg(S||jO2G{n4JF#=bzCsWNGl)WqV>! zq;RONse+UB-jumuAxpvYARo=^b2%#j17k0~;&m8-p6h}`JLZ~`-lh#Haxs%#u8W8F zU3i392=6kXpTz?{UB$y!x4a`aJXLrz#OnrhT!2C@X7EdhCKL{dF_19Wh#8c~@buAi*Uk2f zbeJA9)%Clh# zj_dp9t?tS#oqafIF?l+sT)m&YlR@f=Lc$dflpR9TxekWV+Kh0``D9(Y@9;sKucYrXK0ymRqi|GFY7SpRtRJkK9< zbCo%tdSA?2-;i{Wt}U00f4DFxw?}G$usd)BZzCf=DT2;>C?Y?O*6V;?B>%_RMPG0a+|BDn z4kSj1()Ym00Icu(z-|8yBt|!G)L=&~ATEh^rSj=0OYr0>g*-EuHVj z#Ge7!0`4!S*4wk&XgNrf_k)vfY^~Rg+vpze-#=mrejb9wcmJ{{-ScVm*`M=e$ymql z&D?3o5yKC!c3BVu>FV`(q!-8k&!e`5!299oUoijoiry^0FEi%j0Y4mr7Yku%%r`UP zSIjq;myvidfiK_dM@-MxO<%AtJpS7R#QWF5KVigcyj2*TaLoAJui<$4mob-VY;y?|ko% zZu|Lv?ijU>=6G?(GUoVjytc}P9^Rf&1crJ4JJOq#>%q2KEE!nwVLSYs`C@T9Y>0tG zerX`$^m<;?E6(xedrh7R!F^gw0iFJ`8pY4~^mf}L7-;!;c-RZ}fBm@B9bgKH|9;pz z@%_5{>7_4gyFJ@LcdxIZUAi2^p`jfW?ZFr4>Zh+aOX_Niu-Mmg zL*KTKW~`I{`?n{1pmUu?IZCB z4em)R+{i<;NV|fOz!dhRMzaBBc+%OUG}LMXg147VV{$oa@?XO>KEcP<&o`sSl)w0m z!I>s2<9(VPkTSM)PD=A8pI6UWD``1Ia|7~qX64||MdpYCC<_(m-&b6nY@~%l zBR~poYE2A+*+PU|nu#jFcslCHvBA-O!F?E6QLV+gxxcULLttUpCm4-lSpQI9Iw)|E zO;X`g5$ZUtPv)Z9nBbG~OdeJrW(sFR`!X&sEYz0_kC$8wqVer~*T2CGN|VGW>3Rt< zBo6{BihS0n8D4$r%4HXuI`^zI*t<3n9)Oi(R8p6$*GLZ>@0-gNcbK-TVV2oujJKxD z^PNT}VxuN%i_4VgS5N5Lgx?<4q5nb7hvFNu z&`I;2cPEwUI%>+sG~w2M3i_C{q$ED!TUA(UJ70I=)ffks?6AQ%`BE`uz&{UsTTo|@s>mJ=_X!N=HiOUPl zNx~-6*fv#z9VbdP8%7=q#0l^r{fk$pO?1JjtGb?gQzcGIOXIaRcSb+z(Gi}maG0|+JDb57QR^ClB zHO^X&-k4|i|7#@Z)1Ju)8(DN3*~?F&5KAhnSROXA<)8jL*5LgL!+T1lMjvC`o?2w9Bq%h5n23TM+ z-ribkDlooaLk(n8b&bw#+T6`bcrUBvEKRf&nUp9=VbN-0VBqJB*-9-Q#hQCHb^W@{ z6j1!s1YZ*=Q$%|Z11#({#F&jE2KKY7dQM!8m)pj!Ja_f#%ZLb{*Oo1(H2zBw=LD+b z7Ec2L)|Gcfm#_0W$=!mDBPlJeh-!RC9qwHFc^&c{87&VzRZHo$6@N6MZJ50!yJK0IGZ(eIOFm2r=fZ@*2eL?)Is;9xC zq5AW#{Dx=)ltM*LBh_cIOkpxk#lMi*>OpnyJLAe9`cY%wlP?70-ukigI&1T$%b%~G zWPV2z_uUoaCH8g$2hL0sTf>+yEQ+hZ1}j!o7&_*Q*sy}Umq@-Co{4Ht%WN|dAOWN` z-AE`R06q%`uO}!kOF1d`kjZ=!I{MA))F%AZ!UwCshYY~U{FBGuDv>=}Xf}V6@;xmu zV2@=e9TcMI95^x0r=Va^JEZDqnzTnGInG;jBp+ETh_k22`SnzN)H7aAs06)KYAvci z0evuDH%E8xyCzdFLCYl$KWlBFCzIHt*Wg-EeTvTLFRzuKMAB$uVnlc;sM~M5jCQq= zV5zcUpj;Kp__EkWz^<>C9!B4M^QeqM5(o<2?a1bbLZdyr?pm9NxDDg5NpzWmk zK^{E&!Wkh|0k&m=RG6dW2Day#wf57O;o+y5>c*vyN#gZ@m+<#u?9cg&x+ixM^CA*D zPLm+PdkC_ICI8_s)V|gPIfsKVVObga@Mr3V_^GxE`r*#@& zE+Mtuk8Y^(VCIhGV_eZM>ks=ln{99#`1+NAI4GyE z6-EO_DT!Ny8t+2n*Q_6J`b8{c&QKmmSwu24xuEUUgQta~kIWjavr62qpw`&5 z3XT^VUzRmRMC+XGilvaQtFqB~jAsZ+G8aq4W^sG_CR)zMZNg7pY$4P8aNZtbE2e<( zqf?TlB*a>ANi1rJ2x%nxoeJVjo2%L1>fA^H-2wu;nt4A^X8yQ=FI`Ip>ngMO-6G*! z#H>D~^}7#VGm`_`vi`vC)DZrKnUwU=zPNJ>pA3ld%w*kpwKk>FxWrH|4N77e&qO8a zLS7{&LyPd1GpW9$4jXimzOu?3y3f-Zvf)l(JGa?GPT{p1a*=GXkqAV-R`D;3vPNg= zb#TgGIO3}0^+thrA;whzd7*?;^|Hf6_VSKEOy`XD2r8Ux%)K~;s=~iP6>tMV22X{* z2(_Sz;57%+z_tjy>y&aoMI6!wEY=FIlP}a(`Vx{_5Zsam#886XW-re?m0fSPuep_Y z?zh&wx#M~PTUDxWPB%MBjaz5kT@>q<8{VE$lNfc7$U>y%r|pD_1`6q^hkNbUUijTh zd@3|=PknjsK4KUxcPd!mjYmr@~%H8;X^R+XtZtZ77v*y*1pXLH z)0ZoLM?87cGfw2zY|(?_-^EOT*a<$`(Im z>Roqz2cW2JISD1VxL3lji$K!XDX3{=%+SfoUBD(i=2NgLSeCqVRzi;E??>Z|Qs_B>sYEbJl1<@p^nWyrskH z4OzWTy<+cdx4T$agt1o$8S8K1EYYf`pCXc1`Y`5JWLzhQ4Cef|JrSFMY(jlJ4TjS2 zBC&+_{KIoXb^Tz~M|VvUfSS)qTSFL*kxz*e&@)0|LUScM=AnCknPo!pR3B1Uueh=B zd2JN4vFv!}0HvG&uBwz;+SHBkIy@t0sq=vD=82Um`{-RdYQPu(-7UbrzJ%j;; z2W1S8k1wd`w`MhNOEiHiR#mE)oh^(2`xWkTz*XGs$gjSr_clxErM?9QcDC? z7rLK6uC|BAXb)R?yQ)VjUimn0d@}F5KcOUFU6*WUX)U?Z&pThE_mB;4U!X&Gd@{mD z(CEcwgbe#wIo;i-G_4;xUkevh)P+W%PM9F9TXb!y&URK6cd7HzsU}_Q6b00)GTJ8w zFoUrjxuc=Hxk9y)L4=Nbv(6W&OU&KEPZ?H91*NfO;fDil1cPS!JL0SR&w_Q7$8*i1}+h&0>+^zZP5U+r}@fYA-B>$lTH z<|k`5;3}O}QeZk69#Q4kl%+Q@y9u^2l&P(rJ>m4~lZ=4$MjWww^m&Z-bvG1bbkSUKdi?$4h+)L#I`X$+;_)e?s zR_W)(Q**;pb?C$9McziQn1;1-zmgGud^Mc!uFE&RVLZHf4Yzi;s_Il(F8=dLPUt}0JmDw=)1j{4ubHa9k=z+65qn(>#RQ;uQFweFd}(ixHQ z21$2+=kb~DnvChk)*B@d2bmi^3O&*2Od@FyR#uuJSY<+9#>po7y5 z^43e@+On&8B~g<%C3<#6QuxV)vmWEU0Y7r51+NDEMIhU~`EsMS^DFimXW_1<bURA&oG2EIK5%FVuQx_y957m-4pvhNLixu7`Ea#nDw zrUZdPw=zN2y;WTe>RoNwMr-9SD-avsZ|a)#<|e*B9_KAkCiw%osr*UwesLYYb_LeU1-;F{EDFWTid^ zq3rsv#CzYuI&-)u)@IAgMa>lyfP913ZCw{;frIZ5F;8B$6>JiK69zfCEH6jHXmX*u z>8XE*)2?pb!sv5R(e5~$k7fJ?1&}XaE{Y!o_PKe}x2W#1Sl-aC8D-X9p$SsZoe{9< z>7@R``B<~l)#yy$N<3}sxlXX7kfpy!^=ze&u91bR>?xSCkbRmA<+0P$)n>AslCWk#Sz>!HW$1NATgn@NO(QO(*noq3PSSy z+vBB?rrRe&YkT=aYY|xW`g`iyb8fwr@4Xmkd0=bmY3SuMBe`+bEWKVTBH|{+XRTvH zNO;JmeCOjPqK`b%V0H31-r>;5NmBjV*xYYKUjTdrE>$yV{v`7p%rX1|mD46H9SgH~ zNUmw?7OPtVCC*Wzd|3qR033s*SkX>4ma^eleSEhe1>b61e`%dol)f#K2nK6Cs02S6 z4^EdFAm|~4dM5oBgu7UTC$JCTAjIkKoJA|4MX4XgnhAz-mq%oI?fz&qEAPYD-t^;b z?4MmlKIb8**nc7}?CzIWX0WU-22P^A3Iv<@KOi9piAUP#Q0$m(gzlpa-#TJZ7b1`3 z4M_>r`Ds=`7?nAi6vzZwmbA2@X;$vAds1Z6{C^N(C)Mtz;Yu7h{JXYC24+z9{ic4q z&VmuIVY(po@nL4~pf@KILBdO9h~gI=w=~fh`S{$05J#r>c*w7+{NJb(`R;l|8puJY z=%~lSMyUnhSqcylo08asWq3uA>U~KSORkVHD@uep*D%^Hthmz8xV-R)moDj2^o0_2 z^1y1Cg$U-*6H!bkhI{d%p5mb0$8iw#oBH6T_8dy_i9!39AmK7^|fUB!@7v}i8 z7b0^(*d4_$`Q>gtZC#A8AfQF%Gf7b~T54)nBi2eU<6a7lLg#ZEI!8Iq)j2FLSyaUr zGGl{c@3A>b3V6}aD@H_#BLvA;m#!+4;dWa5!L(U0(j;TYH0t~nOe&`y({z&K%(=Y% zIJgABF&r@9sjJbO(|M?n8HEz9V>;vcdmod*+&$uF`A(b%LS>|Jp~qiFHgp&`P5K3Fm)N z_D;c>Mq9UVY^!4@9ox2T+qTnrW2a-=&KujdZFlUXGx;*Qs+eYSx%Ht5!X= zo>g;=Ii@NR&0k25n=4cB0PKp-JP^ez#iGah9tgd`-Yh|{vcAhtt;5Bc-9>Uy5Q1G$ zvDC|lVOmc-A#HtwAKrM?7}J~osRzIs_= z_;SoO=zJq6j;B5WCRVcw>%#7P9=%5bl$??!63G&3W{F6|m!`jsFOylFIwyhvguc$z z)nlZ^USn#vj(z5D_rE%DlC9uluBBA8s(&jny`xNH+wRa7bZdx|$ub*;j@Mw`xpC>~09~B9uCsiivU`2F z#1g6XlkM>E=P91#{c25Dde|`zezTE=#}!azl^h+S&*NC^t|WuVPthtfb;!Kiv$)x@B;!-b9+8wjOmexe>!L*&C^rVR6F&}ml{!Ub|d#+hnaNr>%BA_Fabr>;D z;MR~>0-^Z@VC(puh11N6`-GvklHd-1tb`>b)q?^*Rzv9AjxHp?JPl!v_a{m$lYYLR zbv!(?zc3e04v4ejwM+RbLfbYdJ$q`?&$dW+Wb(*KXVz~D)=9}^lzn7)=W3Z+le5!T@ zM7=29eNpcS4!{50{!hm18{;PLKbdb&jGNt?5VoMkUw-cqtX_o}r*|pxXi+0~`L1va z>HAC+bX-+cC^cK$-Fw&f7<$@grpVjlGOA@XLLCtrL(!80P=qw+D&}(I(U`J|H3CJ7SR&h<^lc*H=k%baMVnPi zlb-1aZps*hSpjhq7JUw< zl5A9!N;(y`aB<{Vib6vqU)io`5lIS)Z0fSZB+kMkim~|qlYW3%O&EE8kR=Y75%w$s z(NH&8NhXCYoJr18`Qswyn@TH|uFjt6i-~XmwI;(W$TAAC zfP7uSeA_{#np`rnX^{2-DT(kfj5IRwRn8vTC31Xh4p4*}&Ksp-bY~BC4I$`pgitX; z9T%)8dnHut-!QTKs56I+$KfZiSlgh723Rp9+WV%K&Cf2i={0;*y8t}D>r$fCJRidf zhX*x2MM;JoD#iUVz%%PfCp%f*UJ4gd(f2iz+`F4Ic5FKioQTnTo0D25%t#z;1FeXt ztQ=$TDxy4}^CXL%k|_0DWeF3c@%+FMIq!MpRXHLUl9i|oBl@NkACgf5jFgrH9Q#jM zacZzXAoOW&&rml}2p4o1oWpIuSIki&qy~Qa^0hD<2~_z*!WvbAG!nTGwzRAF`r9=Q zs<*)(We=M-gB}UR+MEKRV>AHiCpTL7zQlCJt6+A0(UxJ#X(Ce-))pBFEN7))chOMXS*Qw{u0Fh6)Z4g_rxd(# znguXYbV`9Zoqdr75-y0;pzxaz^wiJ~l-MiG6Cl-An5}^+Hd7@M273csN;E*0`ly9c zmjw9)|kaz zM85W1L>%>WneGb3OkF_0nG>{Agih3DloHs4w&6}m)7-A+%OE=?JtYy1%SDfgXYV4G zHTrJT)Yx&$p1K9nj{Q1Sheb)O7ip885(jP(83bd30A$V6wJara{t16dQoOm-T{Ped zw^)nFsfAiGjtVKRFrp?<%jApE@_!Oa2=hKbNO-1&{fum%;IW{^icr{7Do4HpqZ&hz zf%LD#XkrgG4$ikx5KlQob$6EZ^q;d1-=<(xtae>b&4|%A^2KYpgV>|!7m$T)@~Y&6 z!LqH4Fhu~%Q~?8{JHhys0%DxV9lnZtJm*hdJFdJ8%!IlJ$UrVFF*{S83+e$hi#Tjn^;lnWpm4E` z-a#@17-E@GVi0$%?VfJZd`p$}%!w#(#h(F_Nzh+IaOlcngA1A)NDGV#Qu_pSLb1#j z86GO_86I}`FxyW*9>C&>GS#o(-gjRZS1vX#j+K5Mxw&iJ`00B*UD426Pi`@;w%WRX zTm6>l7lU^`tPXz4t_~>;5^;-#d&EXA)M8gWkwwdqMmh?e z@tG(+e%vZQqQgzrR*)qX?=Gm6i}(Wrj+!?`Migck;8_yBQ(uBvBxJQvSQn)X>#yue5;C42@ES zz+P%<&B;rCq^?qSR>$4ktD%8Zn|t7~J>U}#93xCnSwI3ig6SrZrM(oQuuDw2z_^Ws zT(&Mb)C|N33wH_aSv~3IZleMKrQ+{rBSx=ae)dR%mr&15t~m!C$5R)i%Ds1KmjT#)e=cbticd)ZH3!q4*vDk7}~dpV(tcy(5m?DmLa zg7llT#WY^#PgIC*%tJFPVaDT_ACt+jNX`H5S%WznFgWz6ol3R0SfS<1Rvnwoz zY7_oW53AOytvqn~Mu;8>3;Do7$ax{_K#eZWjN%1GzD~5Dhmi3Fo?Iu1;@1Bt(S|qm z-DknElM{w-C6WA58`#(Y#{6a%QMsDkJJ1s7CV9CVL)jgv&t<;! z46}N6+cV*Dx}#+Pu7yYFHejmAEflk`BI-^Ed6ude7r3oLaf*pXXB<>dGsBOF0Z8C$ z!~j<^hvxe`;27J9f0!^?vf*%YJLC7=ZV%{~|F+_hDsJQ4t7E%jk_U)*xzLMNu=i?| zz=hW@>>v&nioO#Jq$B?5rmSO5p&_`)DIS?$*hjXlpL-tdup@PwF7=GQ-VOm?>1O~n zQ=XI6ks%iz>4;VOl9*B~CJ9o;Q45U_SIIewklrfqN-RK0%D)}&`vl32|dy+U> z;5Q8GEYtvuZQ!BHQUQn4`bGDnyQ=!1{kKW2n@1rS;ZJpDVRz8nLf99#Y%Q1*0#;*K zpkXUJ+t-7@Ni+d|dv=IRPx1+R!xE=EM&$r)S5TEv!7c11TuDusPZ1?vf$_YSOjHdx zhR`OQPk5udb_xwhjjfP)uF)YAeXK%e+C&s!mSwXmp=Ol>o0!E+r2#?2nw~L71DLM0 z+0r)p*H*EgsdytrBrZMJB}QvaP~kM%RD6)t%nzT!Fs|a-xebCQcNUNH`}jc5#Hy}A zK&zWyIj72GsmD~#RL(I`e**y9c|Nj4xYfPm$g*E0Y_9=zBixp%4}wrlTvJWa?B19?}3J6q&T4 z-(yg!E1Cu-jRor8f+6omgDqk+XA@Z|wVX=qHZ^hY2cdx9ZN`e+)w`??RF*sIyjWtV zgNVGULjj|0{l>9$0+c2#L1QX!Yf42qX_QLFPqG7uyz0ZRPJ?USt8LWpzrOX|l~NU^ zCr97Cv<4rxM?+>Y7VI7-6_G5jXH*3xsUBXDBy^SenwV-E%UyG&S>zf~#$MWCrLBGSH|0$amJ@UO<9zdE* zvp=V}^U*DKEp}GVZM6Kncrw3=i_XC7KbJ_+ZB6-1DnZa;?mUtxojL7;pzWrRlTSn zQ-|m&6?&i_&ZZH3#h~i9?y?vbuAt18C9#q3k?L7(jpiW|qv-57l&-*`#Hmiz?xBQQxyd!I2h09)Vpd7{w_KumT+0qP>4PyTf-o3 z6OXuvC9$=Uw=D@+)o*GhBL2LTsVi9)z7KCnUQc_1>vgFEd|PnV5&qD3O-|i1VCS1x z0xGUff^!=UUNkeH{%f(JC$OBej0D2CUl-FsBxWGSNc~Y^U@Zf}1(HRl%uuaFOPZ>o zC_xR}zrEw`Zq$l^$iNNzgn~eo?Yx~gwzP#KHT+P*J1CEWM|If_{v^2d!z2TQwQOa` z<#iqe0Ta`AMDi*GOAjC~q;$CZmSntuAmrdR7$8O=+?OPz3j9^Aj~|=>%USDkz%m)tY>g3g~B zHAbANNBnycD2=6m(T%FZVQdHQiiwkgfCbwH9r)93TsA!T?Cn`UJsUkYO15gwYE&Ly%~YZpU<-lR-oj>pnDWF@+gg)H0Aw>Q;2z%h( zg({w=7L>Wj7(X9H7c~E$CP_NY4O9e&xB!&&&e_zuPrd0n2jaQhi~QkM=iC%mMw6GwJhAh(WmR5PB%k;bAUJP z4XdsD=qB97;#e5I@KQmc5P?54`VUxsDhaYLq=;N8SW#~%$_8nPO1%_>ed>Y?~i}-wdehOc{uu&yEU8i?(HI|czybR$S?l(yje?e z4)#d}YVD@GEmhl3e9y}9Ai>D6a+fF#h)0k;nDX?G#ypz?+&_1hWtm9k8LH>HZlkUy znX}KiGwaqC4n-P$T^(i+Ae2KAdpPNt03*coA}&c)z=FpDdO1`?ik^)hSo?}I0u|d= zA~JhUkBzFq)=_#oK6;X=iHn?ET;w=2GdCsW=+OTrc^26ScZ>}SCn_+E8vEQgZ~-`) zD%%KZ{&Gl$W`Rk7fv8Yvk^niCeyviBX1BwP($d-)JL}8t$?Ec-7F3@$=pfIQd_IFU zw-cw>fF>$u;(nN{FedPl0rVjWmFhlKjWzmIO3I93DYg@G);t!%fMA^8w2YI~aU*Fd zw_bA7+Dg$uObVDB%xc3nRZ*?gGH5}WLc?Cuxg`5{F>#&L`*)s6w_Xes{1ki&u)llz zLq>B-^2^x9s5h9z@k;+yKJC*B5mlRvqd4T|!(h`D=fnQLjDa7nS+Cd!O~ze($1UV@ zio~(fQeP})Y~{77?pyzoOshgvmo&2D_4#Q&5~1-BT|oa4Uea~p&UnZ160O~3w{6eC zvZ!|R^>dDO3>H-KWf^me;^obiF?%`rA$;55fRSJXxXOSCa`?LLQ4e+`78Qi91r0S! z^+q}W+-GTvp~yk^RMvq+2__1XW@Xcq0}myi{KJP~^>stmvPOZf5B$HEcunn~gz`Ab z)Y5vD3km;Eub09691&0Z2OEbrYfTe7&s~?7&I?a@#_h1Gg09vlKdm!sp3?1UTPG+J zC_gW+>>Cmh?3`|flSxU1;(=yo1+qa38W}-R4ZbNX*!TD}xJNFPe;-_?V`W-z-%xXZ zE?nMq8lvgOw(ZjQZ=^79)3ek&LdQ*7`B}Fvu4!Y;lxF>zd{0HiwXL0fqJ0NKMjw(* zk$61V+wk?LCzBU755;1fgJ7Lh`y91xWwY4KwDQ`b?PkCGs~W#rsPv15aZtgQc__%E zkrjC8*nWM;HPeQCpe`96vb)Uhe0ehaKd4LF9zMOL{ZglA`YvGx@;{q^{+#wb1BYGL zQ-~JrhMF6iqI>$`{CIdJt51IOk6)Y2io+F5{Oq|Wu9pukkL&j3nqJ-ZKK_br(bit} z%LO&v*_N%WYw)9NnEpL8dA`++SUe8D>Fel4d|%?|xo5C+;yh(;dID#i#4!$YxJ8TV zaQe(yxqzR8F#UEN=(wovMuS8G#mUBU1Z%IFFyrYvn7h>QeWrI~ ztmi&RZEeKuKJqZIch_0#fMRgBAjkn3fVL5lld4Q+KYp@EO{z&%kD>MRvH!)J>m9t= zlRSOUBI%Un%Y|fMoM}rf{ag6tNEUmuzF?2Rz{4921leNb7@CvmK!_dKya;dnuNg>5 zhruVwXP&A^;4YnGiyfkmzyAw5)Ok5D&=}~k=pRerpc)lz&e|anzr=O;Ui7{rs(B7$ z<3S=?v^b@$Y%Dx6sIZHwP}8JHa_Rw7qBXlccVhugmU_5xBOXytLhZ zEMW@-UBqxkx{Tp@(3Wq1q05E-G-u7JNuxu+KT`vT&Xw4!L-SPRhtZ~rvzHl$IL_sz#lx6#EzdHUt>-YEyq(@%?dLrtvkOlXAR8;6cdr{-4lrS@j@-(Ntpo^@ z5$-`dPXuUw_s&J8RFzXm#X zK9@R^s@`VAJ7%`8o9;_rI>f=a`KAUAXm+O^algJ3^s7G`a_ziw2v_iQ7$le+sc$vt z*(6EpAc#^?fDS_2Fuj3eygGBraLH++A^E{a<8qPl2oYk#;E)7D&E`q@x{iRiYw>O4 z((zo0YHYYlVr_b2$>=6UivY$`3!b95GUju%6LuZQkBu4WvvAZOUZG-v0C z0AFo5A|c*y$?oYip7um6&IEJ9mQ#+r)L_pQ7#~hG@aIP z3Iexs5zqq(n~<^Z-vLMQ!@xSylNCFOMXSHW2+;E6t4Yh9$<$Ye1&1ZPQfi|8x(5M{ zdc@FLO1J3&OU6*a9JG)U5;%M;gTGS7c|CeihVP#^2~>*&XhV_dNkKl&V3Wl&2m#fU z6)E=rBi;b54U~*ykKk}oMq6?Drf=Nb&?D>tBZI|DX~6YS<)uRoG?xSN2&-h}^Qt!p zeF4*DR}``0&<0^4Fw#LC>->pV8&_Ek(G8+07iOvXOfFKr%-b>(P1xxNZJ;D*9fO=f zO4fB;>;1Y=Y6D^@U_4Z<;B0C%?CecOYUj;Cyb5aXvm>JbqDg4XA$^=sJS@}fr-YM2l*a;(p*=t#)NJvWNiG?hbcW^pG9ep8Cd8^c) z>`4Da_^bKGWXgA$<>eM#r(CwVc#*9q_g+8xLRiKpys2r)+=rf77_zTQaN{cO`TFO5 zHNl{&GUAGaj)y?M0wD*87I1#ZN2>A$$biuBUz@3zO!8@7w6kMoWhPeR1Q|`FH8EI{ zN5i6(78}SEMuJOgALK;L2+v9XkfJs}i1?k3zV2mkPM(3otENug?VFRS%3UK_y9VdH zLifmWWGP z=!6yoT2g`5lTf4DI_$9v*c-9{SgdH4b+lz8xP+?cZ^w6vFNQCbMtF#4KkJ6Q_xsDI zLzVcicl(+%-yfss7(p&mfx$~{3v)L4!aph|crf3&LCJj*3Lae++J>l`!b!E~_w;5) z*iH7I?CzKxE!?sEb2*?jOkUN}`7=CEgRAH$jUh5PAWj)qc zS`2joJT*1B)<49oO9>9E@1*^hd#k|PpDI00PW`_RdUtCPj@G!Lcoz3&R#Sy@?skjk z>@(hv-#luriO9tFxZu~1s=@UXH5RH#s`MGANccdaqdtH1eNVOKTH5^Zkt3mnmgq!d zR-6p)^V5ICCw5txkFeD*>6#Qc{-;`rJ~q>RVIp(-)<8Lb-|auc58-NRP^aNVVYp!I zO%y0vcnjf1C4x!8)aj=`9j4x=Xe`)k@|cXo3;*f`u1{X?d-`-37FW>(aP*;M(o$cI~e)YP(8sR)ECExW-qy7;yaKz%ci-i6(I%>yTRg6g5MR?V>dE*JVaLq>DNU-5s@lPYD zk7+(=l)HXBOtIc&n>EX)>*nAOKYpvPh;6M-?S2^GGjIg^oeSc`EgsliSipA@gvo*| z{I+lsVtU+kyY6k#j3)F-c$)@7Dvo4_skf`y8T6QyAUCL;^AXjk;))Dm5S|(J{?ajn z-0q3Y9;d6~q#xii4Q-kxQ-xP86`L}Bjms%icH)Wfm6tP6*FlR(BJbo4@x~^rg#w_0 zLCdYlZ^C!1?|K9z%q2IO74y(Ek<;Pjh3u0jBqB(#=WgB-h~$2dJb`9ThUXD+%y6d` zZIg=8Y5@*3G(f{xG+i!PL#4owTI9&(G{As5eh3uQNqR^nFr-hgt`7c8c%^&+UEL6B z0g?~qM@Q@o^GTE8omm&tuFqlpr3GugsweiM+$Ux^aGCJ5_6+OuOdp}aR7OJkZTtte zc4HKKw7AlIsj1zEZL?XdZI z=`ze-K6a>iWSig(g@AFNl5>AL$e*11pelA3XFj~4yLI;hw)K!t8pHEbM&;^-BeZ2Ux6J)HDX zph^FBhrM#|8ql~zC7K#jvsf9E8amH=0(7ZEyh&hkX=P!aL(&0C;n}&3PT&}ClFa&- z>Hv;uAXt>@ag&qVg7#i+42e8!oYNU0-YN z>^DU9iL&+CzdY;*7H|w7EdJ?{)UUQ|3;m-pPR@*-k3R~%EM`7h2oK=@d6{reWXL{y zWa${-xt8@jyvGVJ=BRC2U%9WUNY+kkFNQtX5Dm+K8+J-8uFz;LZuqC2A`J?JxmcXq zJcM@v{vK{0f)AL$<2RriAG>&3X}_3rIm=@;pr3)O2B2nB>PuFzJsW+X0!CK)uA#!udRc4t~L9FZ_E zLuO$+0CyPW8jMxY{Hzj7t^|omT;;Doav~{@$j|!ck{l_rDP}lCWZflS7!B+(U>b$H zus6H_dqrD+)F6F@irxCK7?~x9)z8UQB45&)r3~0(I%+R2n_DN!Qmw&wbcXt&hkwh+ zoJT~&s1%r-Ks&Ee0Wvd{xxhz?H$dU&jy$%q*8|(54Dgi`4d(wReUO9i4Wq-G4KBRkjnQ1=4o%h<*0%2!3Zv?uG*P^5RmxG zwxY-&f3uMeuyZTQ1o)f=xM!@TS+A#A}qm5We%9Gs*x?6oqS*oHIN;$ zrL=DaV=eQ4NO}(MDz$pa5Y3V=jxk-I0~{qRy7y>N5kt3{k=079FPKi*KPdEEa>{#o zGTfEHKNR3L)t!lunKgWIqGr4*wU!u)7YG*jCuKzl*)t_Tso=0dY-M`K#6#0$!8^t4*10 z(PUgEr<8cRj!()GO^(LGje>ZXcKnXhHn}=GRl*9JMK5F5F8&(wy+l&DBiJw3H`pzH zUTJk{vDl0WBby}3mf@a`oHfc)lI2Gr)Cr8G9=IBJlp$AmO;yO7eS2>nO0loU_nqUs z_q#)oo5U$qO#U1kk_4*;tv8Xe8i*~NxfpCseLQI>0|;MWQz!)`h9ZD<$^13u^k#;+ zS-!sOiEEju_?BU2SNcW@gpy4RT?y2EPG@EkLHRmJxv*)wn8qu;yJWx2j0rs!^x{M; zkYJnn^u|N-xb(qu@wM~pW83lYBWJmcsL$7Oe}xQbk6F~vi0k zvTVD}Sr2jORGU@QYh%tWE@6M`GrCkv=rnl56Z4)h$*WnINsJtPeYA(aS5lp@QeJps zL-E=&E3C@&Uf_Bh*m{iwf@Q?0N>NA!)Wup;nNd9Zl`2#sAu;MAwA@oKbGG8;y>HsQJ_)`Q-)mgZb58w-dT~pq05N`gG*}v8AqXjp8=X*+rYhSDkc#{r2Ztkbl~eF^@6OnOWJzjmiZNXW(0AGI`Rrk`5FRRBaPRBB=Y#E~F@gZ7S1^f^Oo6iYt6vBd zY3`Re%cHLALzptYgyTX2)dXsG{v5KihefnP>2A zK;!9iXSgliF2{3e_3yD>Ajc150pDNRvZU=p?!&r4APkV$a<)@Aj3JZLAF|f zUf7qSI6(>+&&g0WVe%Fs#T&mlHp?};+pIX`cTUi|L5w}2I95=}F@zTQjva)X(MoXq z2zsk?)40td05i8TnG*e%s=#?tgp2^Zu89q35jO~(77DY0eZ$aa>U#LTmAKKw^5FiS zhxL8<80Ts~I0R1#mtxt#mWL-Wn$(opdJGzk0lKM#Hk7AjgYOHZ1LH=h7j~=g$@GK* zBoE|(x9)~AK8{+C(8U)peLAFCsA%Isqg#JsRlLI|zOmox*b`Xjwc16I#j)%_9Z>Fa zN{W4zAMPA{_EqY1k+w|Jxn3J6;-vd<=u{?U(!Ol<+c8EtNpo8CMry@MB6t8!%$v4O zg6&H>%}JIH98BwKu)S0rY>jGj;-j4HOWpCMg%6O^jI+}CkaZYKe%Q{=cDpbKnJhp* ztUZu{7|-Mg7|;^lX?m1O@SR|rj(pG2@WD(0?x7!U}^z9O{G0E#xq z#fH+a!>D65Hp}rC4)#bG8#+b|y+n^hs~mh_+-VgtUGAol^e|?` zh)|jK=`aj40ORl?^-qX%xC)%DUXRjZ&huYZ-wm#{CA_P*nGLQHz$BShwFqS^siBfo zT}eZ)l-i>W72+KhukT18uMJLLKvGf>Y!Sbz`UBYi)Bt8gF7BR2boJ}$KCGVM z+liyjJJ#khVxqy0$u=@-Xhp=F*G1^?%yBLD6+^v0!+{&W%139e9eN*0&>BF708tqL zo;bZ9T5RVYDZTs6C>$0MjO?HY<5j_jAuzS^YTO`lFBKstUz=%(1>4?AGrSUOK=INWa3Gqw$-IO<)TK<@z{rU^&Q-)TQWzdO3#r$NbfiC zD%n_g9C1KVazV-kf5HWU7Ou51H~az@73Nxrnl$un7TEUe6Ou*EU|Xrm2vV3jdU1ao zn98VWDXGn>cW3_|FSgk@4D%t#++rckZ&KYEq~(s52e)&4FJ?X!1juBc(olL0u3{%` z&}VJbdwuxMCsD(*wag3P2~RbKR!JWXqy{xm zCQu!&`XAAbROf8-uhozpr4hQt)h9wXI){>A=a<8;K4V<7kbC4}=DA_{5n>jK*wJ5~#t+~~ zh8l$=chElJ-$^rVR&W<=z@i&Y!98}c{#jc0m4H4sVWuhgk>RjE#f?JHILMp~;9RK- ztdQL85SQsVBpMPD?G{QXNbe#h2qkUXubJQ}{VUqeaIXrs=0F{sY7MCOGn(M}N%&y; zP)Ns6$mN&^Rrp{;LMAw8>S*XG*>&s+vSh}?fpv8FVCC*khP4hOvX-%UvhyJQ!Jp5B z=RxX8+leoFdaZlgwWX-gI(c?55r9ZI<*ch5+{S_e1)E> zdJvb41}~ObC{w7p15M0wQxmM?p6a?5DH95!f5FuunM9K-eOm3bemu6j8yH{Ih@)QE zg?5}mRVU_6F+r1HBGY5 z--Z21iC_QcuEq5MNneXo)d58q~UCJi+IsI%ItMJE`dTF?>Eb+e=ph zNxu+81&i-`{+ebGN)8=k5^8Joa+K(xFl>b#Gw65l`orSSH8_*$yu?itsu;d2$O*1M z--{DSsn1vCY2E)L?5sV!K#lsZbbHwHeXLHiFgv#ZNJW17U^E{jwG!7@0Cp2ahD=}Q z)x7#$oS5r0FQ2=MOsl-~!hEsv-?tz<+d$B`i zrCc$tCSbEiFJY5NJc_*4Mb>KCu(=SeKM8$~rPY&s#0o-#3PL>hv*zKZoNMlr+rWjw zfTSg;qA_(v*XFPeLM@Y14q?W|QjhT>A0N^tg@2UeuW_yw=Cg*#BT@0302W0RD^3D? z+U2e!mB!FYvrN#<{JNjWFVl=gpBU&g*Q6SlAsU9xMXn(y-v@z?#Dl5ZVF*ba>;~u? zAfGM(%03$VxFloAcepy*;}u(%L8D?ZLW<+JSq*&uP#cFBXl!XUE|Dl&+4me3hfyv$ zsjkuFgM&k%T6{DgQOCl;7tv_U-^@VHcrz>!5bvuWKK`z;`*UofSVB+iupTW@Ky*LJ zb0V@w5cQ}4RTfh4z-)IYagWDbl`PVlo= zBf&4s(xpOa=3s-EC!}tJLqcKau|ZlxVGRIr?kQ&IDR&f=guJH8<_I7;Yt_o4nI}U8U z@xT$jsm0H+INbaL(7y2c{*4nGc8=2!IJ=i-h^;*b(>6z``d`4O#+6U&Z+ce^mGm4q z(-Z`uZh+13j%(?-FoY!?Md_q=!)o@hNWT%@4GAWNE%{>HpFVsL54=;>V{Vfeqd@J6 zJ7+ddd`h~GbCEv<^W3by_I#l`u!LP8a!d+RQmT(L(ozOF{Ef^KWiW4jIFF!4bVn8jq&Vd8ems6 z*zLxrx*F85D=*&_x+TA3E{elCcikY6F8nWAW?ou8R@5Q%jTJoWpbxy6X8;Uza&Xci zMz{|cODG_R#I<2YRX5}hxt1^JIj2^zsvURY@={2_`hT#kT2YI3}!iF(Op(CeqnApPBh$`(PDiH3 zrz1)I%-M*wh&}(Br>V2!uX#-TGT&X#4GSILB{hr(E<$U1v`&eO6{~IB8r>py+a`zD zmCr?q3qp-VJd{0Le*TXIdKgo9W(P>(f5Jm@*{5=R0Q8#kY!(DGEw6>uorlEYBkycO z!P_WitIFHyZN$}KV(0b7U#?4bY;;^KEKE5|9jF$mpSY%h#lQvcRB>ePsshUhl1vr! zP$x8fmBsFL6A&K5*l_yzK(RY)^}Pfoze7~h)}bCn+}+klb=4JAAUDrcYNVJ*uVge1 z9N`}AtCX=iRJ9>B0ki;kaV$$_qJ}OkT{A!b#s{4a!u^pQxKSA%)NQ;-gIov~zA&v! z`^|2Acgy#ay8vERw&;ffzm7(~4P+H&wFXe?dqAbx_X|rb*N{XDHdb`PEdw4I{juyZ7zt|5ZnC?8cgMoNh)TzN* zoza}lM=$Hn7G+^2`QtuJhG&9eYLW3eT?jCz&w`FR^gID=-hLf84eiNZi&;*BgS`%g zzRm&du*Xw+@9zhUoQkenuY7|rZn}3Tpm0tG8&g^`J4u3!1_6SL4H&jW$!>Fx|fw0kvc#itX$8!n< zOv_~)7b@?o7K(3c!#8-re-GPWukK$C#!S}mhUT5HQmwG zIEDW={CBhdXV=`(v~-keOfBc-<`4Z-&NGwQp<^Mu3twl zxaDSe&~`XzPE{tNY;9TidM|ljw=D{Fjf_i2gGULFOGTMlf+b#`jP4aXoYJw*U}Z{?!;nvu#^BHp*w@di7wLUTvVZXL~`C zkF*mpSxKUr59eZG`RP(pCf0~zpfceaqOQ?UAFij62Wq8U#FYkjyJ?!hMe9{BByL6t zk4a@0()993Mt4{aK8Js}lonzMO!X!O($d)>V*7`gk+w&1o55}=%zbA&k?8J=TJ9kI zgnJ(h5wC1h2_~DetO22~dv~-dD`CNPo0|p$^G)b&>Zp3!->Qj>Nh@0{yCFKnAT1lu zrhvh_vH2t6H~NsT1?9i#(f*l#4TZeC*NJ?l2s=9euhV&^5hR(P2N>p^&fnBM6ae~R z@w<*74zCv3%IYG0!}{DMOr0Cr%dU0vFLRN)Cqcg&L8)N$V3SK>3cA0o!lT@tI&QOj zn#P2ApJ8u*X;{-o6JPU=V~XX=@z?k;;#+es7c|n=hkd>hNUA}no+lYAa9HeL^+uLz zWtV?QecE7yuD3OSC|R$)V(a4#|M!xS;ZFthyc`I7wEZWc=WbEHK75k3);_Nwqt`ns zyu5VBD6z>Ykbq-9ltWlF-u?@?IdBHE4YZ$XX_%k9CS5RXm1G@1z0C}0E%izlevW|= ziAobtVluhGNc`OEGg2dQiVh;Bq`9FPslu)^>597hPjI6cc$cqzkVXWtOF!OSFKPA# zq5S>V8mF0`$=~t^s#k0Y$aSqR70$J_g!ya z8b8(XV~RmKZ7_=L3e(8a@C@&AtZ(3L&nkWo&0gVqh|U=y3LKj^T60dm@p@QhK_Ss< zcM?0ZM$7LB2=Q56m`PH+$T~@eG5>Qp10+uH)YPBKXp4@?jA4{TyTQg7x28_r^Pm|q zp8+7)@7j2kT!kf?m6-61jPD+s6UYMiUexm@6SZsll^Iq}mk2qi82RIoT4x`d?#g3h z+6*Ko9BL|S09{4?Q;CM@%W`T z0D;L&ZYoYn15?M^5*@f9Iolnk1ImXY<|;~kYkI__LrOxI+~h$Tlk2bJ^3ag9$k6-A zg3KN~Ug~}rf|Txo25c<`HPdU(&89kLGNNIAWzn4Y zZ2KQrI7)AcdRrJC6Td=a$&q7j>}dOYua`G=qM%_3gDEa)CHK@p@xdA}%q z9gfZNr2=o@PDNLYtV^X`_&7Fvgp@&cBswsNB__E$q9>l!F`Y0h|87eaRRSo<5_bB) zA?-n@uuL4XiEB|4(BXY!tY&ME0t@5QJrk8+<~SdO?0ZZ-&w91m9EkT_QmNQQc!f-? zN{TNHkk!JZ%eqELPjgYz*>gqG|7%%Tj$%Xa(PX+-u3ds3aSxpYb3-;ODOpTTr?j>8)*sWj}UgDU=RqJ7n z99D?M#{^_00&Cp7mTJ93KCY6@``@DL!7HFCpr$u9Tvq34C8Z1zE&$Ln&{hQto(wP) zfC3#JfH{?vk+Eg)a&i_5M86*eVIs|Pw;Z+ezdwMtXACqPe~8mD)^}78=X#3B3ALmz z0rCR zdbyOw8COLWupmV(CQ_T!^eKZ<6nNTy?}#K6=?#Ja=<{-u>C?=b(Pi>nHr@A=5uuUc zK0Nf~{@mHA%7H@(k3MjAIviCSb~HM033YUP9A-a?GmL5L)H6_H&uZw(n~dgok;D{w z3DIDJQjrA}Zf$<0WpMTXftzh`ceV=GIZ5%lQ3a&((E{}#mDZ95>v$-iRVnj|jY$QA z!5IIv=OfHl;UZTI38gZ+mY@(T=^fK%6EhGP88zk}7IHh$tk~Z(RM)I6(r6i~d)1yM zD+D+BE-1mV&wVsuGSv<_{u6|Y=6@lPDqoE0KepNekl%-|F)&reCJEGb5zg}V^WUB= z`V62k0gM(|ASl93E>j%Mz*ZIr;_e!ny&CG_ykX&|B&z&w$%?mQZgPG9n=-AL)WRn! zS^kOpQ|^g-a4+z>)}$&~UO_k;NS=-=rU0QN}9e(G~&=OU6_r*V##1`A5{?GbMwd#q{ zwm;%KrsGA8zbbkcviOeKd;10ORBp={zD!;CwoS8B$Ud(07jOJ?XLC>d3A5AIZ^CCj zRBb|DCG(6cwt6Uf*Wa4Q5td^vVkj&yk0Q+x5k^4p2paTSJ37gZTVFr^xk~Avp+!od zD4Rig_DtI7m)6RD=@IZO7pVRZ>@E~64zoO6rFA^Awz$o64A7b4SM^l9m7Zr+I#&J* zPDK0{p{Et`xIPiDz^-@idUHzL-s_M>@9L3Tdq0rBbZ9L@cfX#V7>PVIhz6UHS7`*F z_pump;O>*tesQS*s{P-YF~>F}>r#kqvmBQ1HoEF|7p|uDF&nPq2+YSikdWE4-mY(` z#KLIxNg9xgM9c29hXgfCm3oZIDWmo zX}Rm`E2CY_`qCseE8?b+<9R+TWSU(Kj*5?uApfrbnFMD0zqBe@_wZ3!vRy0Th>1L0 zn{5AFURuuU&|Iz+D7)4-b}a4p{jj!FS^LXq#7Dwts#w{k^qH(yHWqB#;C$;bQ}xQ$ z2acYI^FI|RSwXu6=kfrhI!OdFLTM|)Y zK9hU6n`FB0Iym`#7}ilt;YL1;-)B#+i|&+OH2|vtSPj5x09FI=yG4-qZs(J7g30O>QfNbt@`MvbOX@BnZVbYNWCfc>C- z%FeSy6XA|smXX8F)`I!^{tg#*q##(oW4o}(`t?m;q5i_Fdr z6!1_7mI$XbMp8hM5eF&6ZE*uj?;yYd`H6tUqnS&KX--Z+FcH`bDRchk2^9F=Q+!Es zfwOW5tl(3NLWax%t2AGulJvL#{W;x~1~=|8-VCVoW`R|=$X{+=aJ5xlcdInorR>4e zrLOs1HRU&4^R0n#%6rx^XTLaNTHte^hr|zm>++qX_RHGu?r!iY-uUi&-81&Z@A!N5 z;c=GpEWjumtyL_V*+bh){1=wN?C}*qe{_Ao$*Vc+ubeQSL+!&=vTCnIoE|FkJz`Z5k3L)3zn zB|)^a@9Sjd?dtyRXu=Dr%+a&g*V@-3#QKuPY*Q|cSj;hsxsb%{1mudt92*T6{%@6i zero0qP26Gfa^Kut%JA)-yEWeO3SZVymf!7jTDG$MJsRPae3{}ZHzdj=RXLJW2f_&U z5S3$bx8x}|W!e-?IWGIM=;}W$Ny?J-myj|1c__biB<0OclCoTGNy?iwlCpr=5lMNo zK~lEkyNjc2r{<;Oxz=W&MWbs3<(0XN?FF%)oop9NWnC)kQdyU`V_hyF7D}V?(vgAM z8#{~NAnagDeOe5#smIYnxxjuXhTFS~^OU!K8+02i|5tb4%dXu;_XY#JZ_+>KW%hF4 zKH=|!wOnp0H@`l|Qw-g&zqV3#+1LK9MT#+B7Nar7!itEtPy*CRMG_RJFVX$5XF^vK zb@;3v{gnSM{@U98e;pZ2akh9a7UW;c_0{aAKR&zHMV|>X!0MfUxqJTd%P;ur#m$PT U50KoOEVp0(9}@B#+{}mu0MKaYp8x;= literal 0 HcmV?d00001 diff --git a/backend/tests/fixtures/retained_cap_source.md b/backend/tests/fixtures/retained_cap_source.md new file mode 100644 index 000000000..83efbcb4e --- /dev/null +++ b/backend/tests/fixtures/retained_cap_source.md @@ -0,0 +1,33 @@ +# Retained 0047 cap source + +`retained_cap_source.json.gz` contains a checksum-bound fixture for the current +revision-cap recovery test. It is historical setup data, not a supported writer. +The archive contains 71 nonempty tables, two submissions, and the second +submission's blocked revision preparation (round 2, maximum 1). + +The capture used detached commit `e2b926288899bcd9b05e1a560ec19b6bca8cfcfc` +and its `_retained_cap_source` fixture. That fixture explicitly adapts source +selection and preparation insertion to the 0047 contract. Its temporary ORM +projection columns were removed before capture. The capture then checked +`0047_revision_recovery`, origin replication mode, and enabled user triggers, +and read the rows in one read-only repeatable-read transaction. These are +guarded historical outcomes, not claims about an untouched current writer. + +[Capture source](retained_cap_capture.py.txt) records the one-time operation. +After the real routing effect, the actual authorized dispatcher recorded a +positive retry while its lease was live. The capture used test-only 600-second +leases and one-second retry backoff. The restored test obtains fresh dispatcher +authority and a new invocation of the same completion event; it never extends +archived timestamps or enables unknown replay. Both stored artifact byte strings +are included; the current evaluation request's length and SHA-256 match its ZIP. + +The isolated capture passed on schema 0065 with complete database and MinIO +cleanup. The archive itself is at 0047, before that capture run's upgrade. +Current tests restore through the shared exact-row, column-inventory and +foreign-key validator, then compare retained rows through the real upgrade. +Restore is setup and is not credited as executing the historical writer anew. + +The checksum is enforced in `migration_revision_fixtures.py`. No retained policy +is relocked: reclaim succeeds, but an incompatible inherited policy refuses new +raw-ZIP intake under specification section 20.2. Compatible-policy reclaim and +new submission remain covered by the current revision-exhaustion tests. diff --git a/backend/tests/migration_revision_fixtures.py b/backend/tests/migration_revision_fixtures.py index ddb0eab56..699da55c1 100644 --- a/backend/tests/migration_revision_fixtures.py +++ b/backend/tests/migration_revision_fixtures.py @@ -95,7 +95,16 @@ async def _restore_historical_revision_rows( database_url: str, snapshot_name: str ) -> dict[str, object]: """Restore captured setup rows; this setup step is not a writer-guard proof.""" - snapshot = _historical_revision_snapshots()[snapshot_name] + if snapshot_name == "0047_retained_cap_blocked": + archive = _REVISION_ARCHIVE.with_name("retained_cap_source.json.gz").read_bytes() + assert hashlib.sha256(archive).hexdigest() == "62f9ae1c767182e3c91dd705a0e282133b44e882921634f7fbc4a41ad3decbde" + body = json.loads(gzip.decompress(archive)) + assert body["schema_version"] == "workstream.retained_cap_source.v1" + assert body["source_revision"] == "e2b926288899bcd9b05e1a560ec19b6bca8cfcfc" + snapshot = body["snapshot"] + assert snapshot["revision"] == "0047_revision_recovery" + else: + snapshot = _historical_revision_snapshots()[snapshot_name] return await _restore_validated_snapshot_rows( database_url, snapshot, @@ -188,6 +197,7 @@ def archived_bootstrap(_settings, *, activation_guard): ) creation = seed["creation_request"] yield SimpleNamespace( + historical_seed=seed, factory=factory, engine=engine, request=SelectedPostSubmissionEvaluationRequest.model_validate_json( diff --git a/backend/tests/tasks/submission_dispatch/test_replacement_creation.py b/backend/tests/tasks/submission_dispatch/test_replacement_creation.py index 862eb2621..27496c214 100644 --- a/backend/tests/tasks/submission_dispatch/test_replacement_creation.py +++ b/backend/tests/tasks/submission_dispatch/test_replacement_creation.py @@ -6,13 +6,11 @@ from sqlalchemy import func, select, text from app.adapters.checkers import evaluation_coordinator -from app.api.deps.authorization import compose_hidden_submission_creation_command from app.core.identifiers import new_record_id from app.modules.artifacts.models import SubmissionBundleAdmission from app.modules.outbox.api import OutboxPersistenceError from app.modules.outbox.models import OutboxEvent from app.modules.tasks.api import ( - SubmissionCreationRequest, TaskSubmissionContextUnavailable, ) from app.modules.tasks.models import Submission, SubmissionDispatch @@ -20,68 +18,11 @@ from tests.checkers.post_submit.support import change_request from tests.tasks.post_submit_routing.remediation_support import remediation_source from tests.tasks.post_submit_routing.support import revision_archive -from tests.tasks.submission_lineage_support import _verified_admission from tests.test_submission_predecessor_custody import ( _fixture_revision_context, - _prepare, - _replacement_request, ) -async def _ready_replacement(h, data: bytes): - """Prepare once, then replay through the independent verifier to ready.""" - idempotency_key = new_record_id() - request = _replacement_request( - h, - data, - predecessor_id=h.created.submission_id, - idempotency_key=idempotency_key, - ) - prepared = await _prepare(h, request) - assert prepared.replayed is False - assert prepared.put_attempt_id is not None - assert prepared.admission_id is None - replay = _replacement_request( - h, - data, - predecessor_id=h.created.submission_id, - idempotency_key=idempotency_key, - ) - admission_id = await _verified_admission( - h.factory, - h.store, - h.namespace, - h.settings, - h.actor_context, - replay, - ) - return request, admission_id - - -def _creation_request(h, prepared, admission_id): - return SubmissionCreationRequest( - task_id=h.request.task_id, - assignment_id=h.request.assignment_id, - contributor_id=h.actor_context.actor_profile_id, - predecessor_submission_id=h.created.submission_id, - admission_id=admission_id, - summary=prepared.summary, - contributor_attestation=prepared.contributor_attestation, - ) - - -async def _create(h, request, *, context=None, label=None): - async with h.factory() as session: - if label is not None: - session.info["replacement_creation_contender"] = label - return await compose_hidden_submission_creation_command( - session, - context or h.actor_context, - request_id=new_record_id(), - correlation_id=new_record_id(), - ).create(request) - - def _revision_command(h, root, data): """Build current foreground owners with exact routed revision acknowledgement.""" from uuid import UUID diff --git a/backend/tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py b/backend/tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py index edf5b9ef5..55610e7e9 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py @@ -2,7 +2,9 @@ import asyncio from contextlib import asynccontextmanager -from types import SimpleNamespace +import base64 +import json +from uuid import UUID from alembic import command import pytest @@ -14,125 +16,61 @@ from app.modules.actors.api import ServiceIdentity from app.modules.authorization.runtime import AuthorizationDenied, PreparedAuthorizationUnsupported from app.modules.outbox.service import OutboxService -from app.modules.projects.api import ProjectLockedPolicyContextRequest -from app.modules.tasks.post_submit_routing.source import TaskRoutingSourcePreparer from app.modules.tasks.revision.models import TaskRevisionExhaustion -from app.modules.tasks.revision.service import select_candidate from tests.checkers.execution.support import service_link_state from tests.migration_fixtures import current_schema_revision from tests.migration_revision_fixtures import ( assert_historical_revision_guards, enter_predecessor_owner_shape, - historical_revision_source, leave_predecessor_owner_shape, insert_0047_preparation, + historical_revision_source, leave_predecessor_owner_shape, drop_retained_owner_read_projection, retained_revision_rows, ) from tests.tasks.post_submit_routing.outcome_support import invoked_completion -from tests.tasks.post_submit_routing.support import revision_archive -from tests.tasks.submission_dispatch.test_replacement_creation import ( - _create, _creation_request, _ready_replacement, -) -from tests.tasks.submission_dispatch.test_revision_capacity import _fail_current_submission from tests.tasks.submission_dispatch.test_revision_exhaustion import ( StagedFailure, _apply, _assert_exhausted_assignment_immutable, _history_rejects_source, - _snapshot, _submit_initial_after_reclaim, + _snapshot, ) from tests.tasks.submission_dispatch.test_revision_expiry import _provision_expirer from tests.tasks.test_public_submission_intake import _client from tests.test_alembic import ( _alembic_config, _execute, - _historical_artifact_lineage_projection, + _historical_artifact_lineage_projection, _assert_upgraded_incompatible_revision_blocked, ) pytestmark = pytest.mark.postgres_schema_contract -async def _0047_head(session, manifest_id): - """Read actual historical columns while current ORM has additive clock fields.""" - row = (await session.execute(text(""" - SELECT p.* FROM public.task_revision_preparations p - WHERE p.routing_manifest_id=:id AND NOT EXISTS( - SELECT 1 FROM public.task_revision_preparations child WHERE child.predecessor_id=p.id) - """), {"id": manifest_id})).mappings().one_or_none() - return None if row is None else SimpleNamespace( - **row, remaining_microseconds=None, clock_observed_at=None, - ) - - @asynccontextmanager async def _retained_cap_source(tmp_path, database_url, monkeypatch): - """Execute old source selection before real AUTH with every 0047 guard enabled.""" + """Upgrade checksum-bound guarded 0047 rows without the superseded writer.""" + from app.modules.tasks.api.routing_outcome import TaskRoutingOutcome await _execute(database_url, "drop schema public cascade; create schema public") await asyncio.to_thread(command.upgrade, _alembic_config(), "0047_revision_recovery") - shape = pytest.MonkeyPatch() - await enter_predecessor_owner_shape(_execute, database_url, shape) - original = TaskRoutingSourcePreparer.prepare - - async def old_source(preparer, *args, **kwargs): - source = await original(preparer, *args, **kwargs) - if source.exhaustion is None: - return source - policy = source.source.locked_policy - context = await preparer._projects.lock_locked_policy_context(ProjectLockedPolicyContextRequest( - project_id=source.source.project_id, guide_version=policy.locked_guide_version, - source_snapshot_id=policy.locked_guide_source_snapshot_id, - source_snapshot_hash=policy.locked_guide_source_snapshot_hash, - effective_policy_id=policy.locked_effective_project_submission_artifact_policy_id, - effective_policy_hash=policy.locked_effective_project_submission_artifact_policy_hash, - pre_submit_policy_id=policy.locked_pre_submit_checker_policy_id, - pre_submit_policy_bundle_hash=policy.locked_pre_submit_checker_bundle_hash, - )) - candidate = await select_candidate(preparer._projects, context) - assert candidate.max_revision_rounds == 1 - return source.model_copy(update={"exhaustion": None, "revision_candidate": candidate}) - async with historical_revision_source( - tmp_path, - database_url, - monkeypatch, - "0047_revision_source_cap_one", + tmp_path, database_url, monkeypatch, "0047_retained_cap_blocked", ) as h: - async with _historical_artifact_lineage_projection(database_url): - await assert_historical_revision_guards(h.factory, "0047_revision_recovery") - h.envelope = await invoked_completion(h) - await assert_historical_revision_guards(h.factory, "0047_revision_recovery") - with monkeypatch.context() as patch: - patch.setattr(TaskRoutingSourcePreparer, "prepare", old_source) - patch.setattr( - "app.modules.tasks.post_submit_routing.outcome.prepare_revision", - insert_0047_preparation, - ) - patch.setattr("app.modules.tasks.revision.service.head_for_source", _0047_head) - patch.setattr("app.modules.tasks.submission_context.head_for_source", _0047_head) - initial = await _apply(h) - async with h.factory() as session: - first = await _0047_head(session, initial.routing_manifest_id) - h.revision_preparation_id = first.id - h.revision_preparation_sha256 = first.preparation_sha256 - h.data = revision_archive(h.data) - prepared, admission = await _ready_replacement(h, h.data) - h.created = await _create(h, _creation_request(h, prepared, admission)) - assert h.created.submission_version == 2 - retained = await _fail_current_submission(h, terminal=True) - async with h.factory() as session: - blocked = await _0047_head(session, retained.routing_manifest_id) - assert (blocked.outcome, blocked.blocked_reason) == ( - "blocked", - "revision_limit_reached", - ) - assert blocked.next_revision_round == 2 and blocked.max_revision_rounds == 1 - before = await retained_revision_rows(session, retained.routing_manifest_id) - assert await session.scalar(text(""" - SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid - JOIN pg_namespace n ON n.oid=c.relnamespace - WHERE n.nspname='public' AND NOT t.tgisinternal AND t.tgenabled='D' - """)) == 0 - shape.undo() - await leave_predecessor_owner_shape(_execute, database_url) + seed = h.historical_seed + routed = TaskRoutingOutcome.model_validate_json(json.dumps(seed["routed"])) + h.store.objects.update({ref: base64.b64decode(data) for ref, data in seed["objects"].items()}) + await assert_historical_revision_guards(h.factory, "0047_revision_recovery") + async with h.factory() as session: + before = await retained_revision_rows(session, routed.routing_manifest_id) + blocked = (await session.execute(text(""" + SELECT outcome,blocked_reason,next_revision_round,max_revision_rounds + FROM public.task_revision_preparations WHERE routing_manifest_id=:id + """), {"id": routed.routing_manifest_id})).one() + assert blocked == ("blocked", "revision_limit_reached", 2, 1) + async with h.engine.begin() as connection: + await drop_retained_owner_read_projection(connection) + await connection.execute(text("ALTER TABLE public.checker_runs DROP COLUMN input_context_custody")) await asyncio.to_thread(command.upgrade, _alembic_config(), current_schema_revision()) async with h.factory() as session: - assert await retained_revision_rows(session, retained.routing_manifest_id) == before - yield h, retained, before + assert await retained_revision_rows(session, routed.routing_manifest_id) == before + # The archive retained a positively requested retry, not a live lease. + # Fresh dispatcher authority supplies this test's current invocation. + h.envelope = await invoked_completion(h) + yield h, routed, before async def _recover(h, manifest_id): @@ -216,8 +154,18 @@ async def fail_after_append(owner, *args, **kwargs): assert await _snapshot(h) == committed async with _client(h, monkeypatch, isolated_database_env) as client: await _history_rejects_source(h, client, h.created.submission_id) - h.created = await _submit_initial_after_reclaim(h, client) - assert h.created.submission_version == 3 + claim = await client.post(f"/api/v1/tasks/{h.request.task_id}/claim", + headers={"Idempotency-Key": str(new_record_id())}) + assert claim.status_code == 200, claim.text + assignment = UUID(claim.json()["assignment"]["id"]) + assert assignment != h.request.assignment_id + assert claim.json()["task"]["status"] == "in_progress" + await _assert_upgraded_incompatible_revision_blocked( + h, tmp_path, isolated_database_env, monkeypatch, + headers={"Content-Type": "application/zip", "Idempotency-Key": str(new_record_id()), + "X-Task-Assignment-Id": str(assignment), + "X-Submission-Summary": h.creation_request.summary, + "X-Contributor-Attestation": h.creation_request.contributor_attestation}) async with h.factory() as session: assert await session.scalar(text( "SELECT public.task_revision_exhaustion_complete(:id)" diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 418f00faa..83d73cc11 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -1372,7 +1372,7 @@ async def seed_old_proof(factory, namespace_fingerprint): await engine.dispose() -async def _assert_upgraded_incompatible_revision_blocked(h, tmp_path, database_url, monkeypatch): +async def _assert_upgraded_incompatible_revision_blocked(h, tmp_path, database_url, monkeypatch, *, headers=None): """Preserve zero-PRE history without admitting new work under incompatible locks.""" from sqlalchemy import text from app.adapters.artifacts import ConfiguredSubmissionCommand @@ -1424,7 +1424,7 @@ async def observe_command(command, *args, **kwargs): patch.setattr(ForegroundSourceUpload, "receive", forbidden_upload) response = await client.post( f"/api/v1/tasks/{h.request.task_id}/submissions", - headers=_revision_upload_headers(h), content=forbidden_body()) + headers=headers if headers is not None else _revision_upload_headers(h), content=forbidden_body()) assert response.status_code == 503, response.text assert response.json()["error"]["code"] == "submission_infrastructure_unavailable" assert command_errors == ["intake_requires_one_pre_and_post_checker"] From 1f9ddef554b26135311f0ed1e10144cba469b147 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 15:43:39 +0100 Subject: [PATCH 219/513] feat(artifacts): schedule audited sealed-source reclamation --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 35 +++- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 50 ++++++ backend/alembic/env.py | 3 +- .../0087_source_cleanup_candidates.py | 18 ++ backend/app/adapters/artifacts/__init__.py | 16 ++ .../artifacts/source_cleanup_worker.py | 84 ++++++++++ backend/app/core/config.py | 1 + .../artifacts/api/submission_cleanup.py | 25 +++ .../app/modules/artifacts/intake/cleanup.py | 43 ++++- .../app/modules/artifacts/intake/models.py | 3 + backend/app/workers/celery_app.py | 22 ++- backend/app/workers/source_cleanup.py | 15 ++ .../app/workers/source_cleanup_topology.py | 58 +++++++ backend/scripts/test_lane_catalogue.py | 2 + .../artifacts/test_source_cleanup_topology.py | 88 ++++++++++ .../artifacts/test_source_cleanup_worker.py | 155 ++++++++++++++++++ .../test_submission_intake_admission.py | 11 +- backend/tests/conftest.py | 2 +- docs/operations_artifact_storage.md | 46 ++++++ 19 files changed, 663 insertions(+), 14 deletions(-) create mode 100644 backend/alembic/versions/0087_source_cleanup_candidates.py create mode 100644 backend/app/adapters/artifacts/source_cleanup_worker.py create mode 100644 backend/app/workers/source_cleanup.py create mode 100644 backend/app/workers/source_cleanup_topology.py create mode 100644 backend/tests/artifacts/test_source_cleanup_topology.py create mode 100644 backend/tests/artifacts/test_source_cleanup_worker.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 46193d60f..9ada8638c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -26,19 +26,42 @@ ZIP/T5 lineage (`168e5268f`), and policy-error translation (`d31a45773`). The last change passed seven PostgreSQL cases and 92 boundary checks. These are bounded results, not full-head qualification. +## Execution deployment decision + +The API/application server and microVM execution run on separate infrastructure. +The user reports a new t3.large EC2 application instance; this is deployment +context, not independently verified provisioning evidence. Do not require nested +virtualization, a Smol binary, host sockets or local KVM on the API instance. +Self-hosted microVM execution will use dedicated runner infrastructure. A paid +sandbox may implement the same qualified execution capability later. + +One PRE session means one isolated execution session per PRE operation, not one +machine shared by the API and execution provider. Preserve source identity, +request/result binding, authenticated remote execution and session cleanup at +that boundary; keep host-specific controls inside the selected adapter. Test +native runtime behavior on its actual runner infrastructure. Missing local KVM +is not an API deployment blocker or a reason to build a local fallback. + +Challenge existing implementation assumptions before adding mechanisms: reuse +one source object, one intake operation, one acceptance transaction and existing +durable delivery. Remove shared-host coupling and obsolete writers; do not grow +parallel local/remote product workflows. A named paid provider needs its own +qualification, not a redesign of submission ownership. + ## Remaining work, in execution order | Order | Required outcome | Concrete finishing evidence | | --- | --- | --- | | 1 | Integrate production source cleanup scheduling/startup and uncertain/unsealed reconciliation | Real worker callers of the cleanup owner; restart and repeated sweeps; interrupted multipart and lost acknowledgements; accepted/stalled source survives; confirmed cleanup releases charge once. | | 2 | Remove superseded preparation/submission writers and remaining consumers | Trace all remaining callers, preserve their distinct authority/history contracts, then delete obsolete implementation. Current T5 `create_accepted` remains. | -| 3 | Complete native/runtime/provider and resource qualification | Actual Smol one-session/isolation proof; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | +| 3 | Complete separate-runner integration and runtime/provider/resource qualification | Authenticated remote execution replacing the current API-side Unix-socket coupling; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. | | 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. | -The concrete next runtime gap is order 1: the ART cleanup execution and provider -factory exist, but the current production worker tree has no caller. Further -optional test migration must not displace closing this integration. +The concrete next runtime gap is order 1. Production sealed-source worker wiring +is now implemented in the working tree, with verification and review unfinished. +Unsealed/uncertain reconciliation remains unimplemented. Further optional test +migration must not displace closing this integration. ## Acceptance evidence still to close @@ -60,8 +83,8 @@ This is the final qualification queue, not a claim that all listed code is absen C01–C07 remain open until individually reconciled with the specification and actual deployment evidence. Test-only leases/profiles are not approved defaults. -Current local inspection found no `/dev/kvm` or `smol` executable, so this host -cannot currently provide the required native Smol qualification. AWS source +Native Smol qualification must run on the dedicated execution infrastructure, +not the API host. The current local environment does not supply that evidence. AWS source qualification remains separate from MinIO and existing SHA-object activation. Request only concrete missing access or decisions after the corresponding drill and proposed values are prepared. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3f7f7c32e..1f62c341f 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7791,3 +7791,53 @@ not an independent final-head/native-provider/full-suite qualification. SystemPython full structure validation passed; Ruff, record, link and whitespace checks passed. Overview now checks this fixture cutover complete and puts the missing production source-cleanup integration first. Full goal remains active. + +Production cleanup integration scope: connect the existing sealed-source owner +to an exclusive prefork cleanup queue and a12-hour scheduled bounded sweep. +Require an explicit cleanup profile (page, run and lease bounds, upload-principal +identifier for separately credentialed S3 cleanup); no deployment values invented. +Discover only aged terminal sealed operations in the configured retained namespace, +under current cleanup-service authority. Exclude accepted/retained/released/live +claims, then recheck existing custody and consume exact authority on every claim. +Provider I/O remains outside roots; confirmed absence/settlement alone releases +charge. Repeated or concurrent sweeps and process loss recover through existing +claim generations. Fair ordering moves attempted unresolved work behind older +unattempted eligible work. Explicitly leave unsealed/uncertain-begin/completion +and genuine-orphan reconciliation open until separately implemented and proved. +Allowed: cleanup API/profile and owner, ART worker composition, dedicated worker +module/topology, existing Celery wiring/Settings, intake model+0087candidate-index +migration+Alembic predecessor gate+measured test schema fingerprint; focused +worker/real-PG+Local provider tests, deployment example documentation, overview +and record. No new public/admin deletion surface, retention relaxation, provider +qualification or API upload credential expansion. Risk: security/workflow; QA and +ARCH/SEC reviews required. Proof: registered schedule and bounded/exclusive worker, +real owner+provider sweep, replay/concurrent/uncertain retries, namespace/service +denial and protected accepted custody; migrations/current/predecessor and boundary +checks. Human focus: an indexed candidate is never deletion authority. + +User deployment correction: API/application infrastructure and microVM execution +must be separate. The reported t3.large application instance is not required to +provide nested virtualization or local KVM. Dedicated execution infrastructure +and future paid sandbox adapters share the provider-independent core contract; +one PRE session does not mean one shared API/runner host. Inspect and remove +shared-host assumptions within execution integration. Native proof belongs on +the selected runner; do not treat missing API-host KVM as a deployment blocker. +Cleanup test scope also includes the existing stalled-accepted protection test +and registration of the two new test modules in the existing CI lane catalogue; +no lane exclusions or gate weakening are authorized. + +Cleanup verification in progress: measured0087 schema fingerprint is +094801f2d9fab469983e8b49ca3a0b260ded61dacd7e823380626637e440be25. +The isolated probe restored the exact0086 fingerprint by dropping only the new +index, then executed the actual0086-to0087 upgrade and recovered the new exact +fingerprint; database/MinIO cleanup completed. First worker run passed the real +reclamation/live-PRE/repeated-sweep case and failed three tests: one test's +one-second lease timed out before committing its intended uncertain claim, and +two denial cases imported their exception from the wrong module. Corrected to +an explicit30-second test lease and the actual exception owner; rerun includes +concurrent sweeps and stalled accepted-source protection. No production profile +value was inferred from those test values. Boundary discovery exposed private +ART imports in the worker adapter; moved candidate composition into the existing +ART root and reused configured namespace composition. Startup validation now +runs before fork, outside Celery's short child-init window, and disposes resources +before return. A failed startup cannot mark the parent validated. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 6c5c71836..14b932a3f 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0086_pending_checker_custody" +_CURRENT_HEAD_REVISION = "0087_source_cleanup_candidates" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -140,6 +140,7 @@ def do_run_migrations(connection: Connection) -> None: ("0083_accepted_revision",), ("0084_submission_source_binding",), ("0085_revision_deadline_error",), + ("0086_pending_checker_custody",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0087_source_cleanup_candidates.py b/backend/alembic/versions/0087_source_cleanup_candidates.py new file mode 100644 index 000000000..517b21c14 --- /dev/null +++ b/backend/alembic/versions/0087_source_cleanup_candidates.py @@ -0,0 +1,18 @@ +"""Index terminal source candidates without weakening cleanup custody.""" +from alembic import op + +revision = "0087_source_cleanup_candidates" +down_revision = "0086_pending_checker_custody" +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute("""CREATE INDEX ix_submission_intake_cleanup_candidates + ON public.submission_intake_operations (terminal_at,id) + WHERE state IN ('rejected','failed','abandoned','cancelled') + AND accepted_at IS NULL AND sealed_at IS NOT NULL""") + + +def downgrade(): + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 1474a120c..0c9d121d6 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -1046,6 +1046,22 @@ def worker_submission_finalization_recovery_handler(*, sessions, delivery_option ) +async def submission_source_cleanup_candidates(sessions, namespace, limit): + """Discover candidates under the fixed service through ART ownership.""" + from app.adapters.tasks import intake_task_custody_port + from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization + from app.modules.artifacts.intake.cleanup import SealedSourceCleanup + from app.core.identifiers import new_record_id + async with sessions.begin() as session: + authority = PreparedSubmissionSourceCleanupAuthorization( + session, request_id=new_record_id(), correlation_id=new_record_id()) + try: + return await SealedSourceCleanup(session, intake_task_custody_port(session), authority).candidates( + namespace, limit=limit) + finally: + authority.close() + + def submission_source_cleanup_execution(*, sessions, provider, lease_duration): """Compose deletion with the fixed cleanup service and TASK custody owner.""" from app.adapters.tasks import intake_task_custody_port diff --git a/backend/app/adapters/artifacts/source_cleanup_worker.py b/backend/app/adapters/artifacts/source_cleanup_worker.py new file mode 100644 index 000000000..11bd957f4 --- /dev/null +++ b/backend/app/adapters/artifacts/source_cleanup_worker.py @@ -0,0 +1,84 @@ +"""Bounded worker composition for audited, exact sealed-source reclamation.""" +import asyncio +from datetime import timedelta + +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.adapters.artifacts import ( + create_artifact_store_bootstrap, create_submission_source_cleanup_provider, + submission_source_cleanup_execution, submission_source_cleanup_candidates, + configured_artifact_storage_namespace, IntakeCustodyConflict, +) +from app.core.config import get_settings +from app.core.identifiers import new_record_id +from app.db.session import get_database_url +from app.interfaces.artifacts import ArtifactStoreError, ArtifactStoreNamespaceClaim +from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupProfile +from workstream_external_services import ExternalServiceAdapterError + + +def _configuration(settings): + profile = SubmissionSourceCleanupProfile.model_validate(settings.submission_source_cleanup_profile) + bootstrap = create_artifact_store_bootstrap(settings, activation_guard=None) + try: + namespace = configured_artifact_storage_namespace(settings, bootstrap) + claim = ArtifactStoreNamespaceClaim(bootstrap.identity, bootstrap.namespace_identity, + namespace.namespace_fingerprint) + return profile, namespace, claim + finally: + bootstrap.close() + + +async def validate_source_cleanup_startup(): + """Validate dedicated credentials, namespace and current service before consumption.""" + settings = get_settings() + profile, namespace, claim = _configuration(settings) + engine = create_async_engine(get_database_url(), pool_pre_ping=True) + try: + async with asyncio.timeout(profile.run_seconds): + await submission_source_cleanup_candidates(async_sessionmaker(engine, expire_on_commit=False), namespace, 1) + provider = create_submission_source_cleanup_provider( + settings=settings, namespace_claim=claim, upload_principal=profile.upload_principal) + provider.close() + finally: + await engine.dispose() + + +async def sweep_sealed_submission_sources(sessions, settings): + """One finite page; prior process loss leaves recoverable durable claims.""" + profile, namespace, namespace_claim = _configuration(settings) + candidates, confirmed, timed_out, provider = (), 0, False, None + try: + async with asyncio.timeout(profile.run_seconds): + candidates = await submission_source_cleanup_candidates(sessions, namespace, profile.maximum_candidates) + if candidates: + provider = create_submission_source_cleanup_provider( + settings=settings, namespace_claim=namespace_claim, upload_principal=profile.upload_principal) + execution = submission_source_cleanup_execution( + sessions=sessions, provider=provider, lease_duration=timedelta(seconds=profile.lease_seconds)) + for operation in candidates: + try: + async with asyncio.timeout(profile.lease_seconds): + await execution.run(operation, new_record_id()) + except (IntakeCustodyConflict, ArtifactStoreError, ExternalServiceAdapterError, TimeoutError): + # An uncertain attempt retains its claim/charge. A later + # sweep must regain authority and re-observe the target. + continue + confirmed += 1 + except TimeoutError: + timed_out = True + finally: + if provider is not None: + provider.close() + return {"candidates": len(candidates), "confirmed": confirmed, + "deferred": len(candidates) - confirmed, "timed_out": timed_out} + + +async def run_source_cleanup_sweep(): + """Own DB/provider resources for one Celery process invocation.""" + engine = create_async_engine(get_database_url(), pool_pre_ping=True) + try: + return await sweep_sealed_submission_sources( + async_sessionmaker(engine, expire_on_commit=False), get_settings()) + finally: + await engine.dispose() diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 4a37bba10..7a2ce88d6 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -285,6 +285,7 @@ class Settings(BaseSettings): # Required source-intake envelopes and runtime/capacity profile. No old # preparation timers or unmeasured deployment defaults are inherited. submission_execution_profile: dict[str, object] | None = None + submission_source_cleanup_profile: dict[str, object] | None = None artifact_intake_image_digest: str | None = None artifact_intake_config_digest: str | None = None external_checker_service_socket: Path | None = None diff --git a/backend/app/modules/artifacts/api/submission_cleanup.py b/backend/app/modules/artifacts/api/submission_cleanup.py index 1721ba5d7..b48e0fd48 100644 --- a/backend/app/modules/artifacts/api/submission_cleanup.py +++ b/backend/app/modules/artifacts/api/submission_cleanup.py @@ -3,6 +3,8 @@ from typing import Literal, Protocol from uuid import UUID +from pydantic import BaseModel, ConfigDict, Field, model_validator + from workstream_external_services import ExternalServiceAdapter from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceUpload @@ -41,3 +43,26 @@ async def remove(self, source: SealedSubmissionSource, upload: SubmissionSourceU def close(self) -> None: """Release the separately composed cleanup capability resources.""" ... + + +# The sweep interval/age are specification policy. Batch/timing values below +# must be supplied explicitly by the deployment, not inferred from scratch work. +SUBMISSION_SOURCE_SWEEP_SECONDS = 12 * 60 * 60 +SUBMISSION_SOURCE_CLEANUP_HARD_LIMIT_SECONDS = 360 + + + +class SubmissionSourceCleanupProfile(BaseModel): + """Explicit finite worker envelope; no unqualified operational defaults.""" + + model_config = ConfigDict(extra="forbid", strict=True, frozen=True) + maximum_candidates: int = Field(ge=1, le=1000) + run_seconds: int = Field(ge=1, le=300) + lease_seconds: int = Field(ge=1, le=300) + upload_principal: str | None = Field(default=None, min_length=1, max_length=512) + + @model_validator(mode="after") + def ordered_bounds(self): + if self.lease_seconds > self.run_seconds: + raise ValueError("cleanup lease exceeds sweep execution envelope") + return self diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py index 88209c430..25bcf2298 100644 --- a/backend/app/modules/artifacts/intake/cleanup.py +++ b/backend/app/modules/artifacts/intake/cleanup.py @@ -4,16 +4,19 @@ This owner retains uncertain targets and releases charges only with both exact object absence and settled upload-part obligations supplied by that coordinator. """ -from dataclasses import dataclass +from dataclasses import asdict, dataclass from datetime import datetime, timedelta from uuid import UUID -from sqlalchemy import func, select, text +from sqlalchemy import func, or_, select, text from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceUpload from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity -from app.modules.artifacts.intake.models import SubmissionSourceCleanupClaim, SubmissionSourceUploadReceipt +from app.modules.artifacts.intake.models import ( + SubmissionIntakeOperation, SubmissionSourceCharge, SubmissionSourceCleanupClaim, SubmissionSourceUploadReceipt, +) +from app.modules.artifacts.models import ArtifactStorageNamespace, ArtifactReplica, SubmissionBundleAdmission from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository # Match the existing bounded durable finalization delivery lease, not a default. @@ -49,6 +52,40 @@ def __init__(self, session, tasks, authorization): self._authorization = authorization self._intake = SubmissionIntakeRepository(session, tasks) + async def candidates(self, namespace, *, limit: int) -> tuple[UUID, ...]: + """Discover a bounded page; every result still requires an exact claim.""" + if type(limit) is not int or not 1 <= limit <= 1000: + raise ValueError("source cleanup candidate bound is invalid") + await self._authorization.authorize() + await self._authorization.revalidate() + persisted = await self._session.get(ArtifactStorageNamespace, "primary") + if persisted is None or any(getattr(persisted, key) != value for key, value in asdict(namespace).items()): + raise IntakeCustodyConflict("source_cleanup_namespace_unavailable") + operation, claim, charge = SubmissionIntakeOperation, SubmissionSourceCleanupClaim, SubmissionSourceCharge + now = await self._session.scalar(select(func.clock_timestamp())) + retained = select(ArtifactReplica.id).where(or_( + ArtifactReplica.source_operation_id == operation.id, + (ArtifactReplica.storage_namespace_id == operation.namespace_id) + & (ArtifactReplica.namespace_fingerprint == operation.namespace_fingerprint) + & (ArtifactReplica.provider_object_ref == operation.object_ref), + )).exists() + admitted = select(SubmissionBundleAdmission.id).where( + SubmissionBundleAdmission.source_operation_id == operation.id).exists() + identifiers = await self._session.scalars(select(operation.id) + .join(charge, charge.operation_id == operation.id) + .outerjoin(claim, claim.operation_id == operation.id) + .where(operation.namespace_id == "primary", + operation.namespace_fingerprint == namespace.namespace_fingerprint, + operation.state.in_(("rejected", "failed", "abandoned", "cancelled")), + operation.accepted_at.is_(None), operation.provider_generation.is_not(None), + operation.sealed_at.is_not(None), operation.terminal_at <= now - timedelta(hours=2), + operation.sealed_at <= now - timedelta(hours=2), charge.state == "sealed", + claim.confirmed_at.is_(None), + or_(claim.operation_id.is_(None), claim.lease_expires_at <= now), + ~retained, ~admitted) + .order_by(func.coalesce(claim.claimed_at, operation.terminal_at), operation.id).limit(limit)) + return tuple(UUID(identifier) for identifier in identifiers) + async def _locked(self, operation_id): await self._authorization.authorize() operation = await self._intake._lock(operation_id) diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py index 8a8429c91..d459197ad 100644 --- a/backend/app/modules/artifacts/intake/models.py +++ b/backend/app/modules/artifacts/intake/models.py @@ -57,6 +57,9 @@ class SubmissionIntakeOperation(Base): UniqueConstraint("acceptance_decision_id", name="uq_intake_acceptance_decision"), UniqueConstraint("finalization_event_id", name="uq_intake_finalization_event"), Index("uq_submission_intake_active_task", "task_id", unique=True, postgresql_where=text("state in ('receiving','pre_checking','finalization_pending')")), + Index("ix_submission_intake_cleanup_candidates", "terminal_at", "id", + postgresql_where=text("state in ('rejected','failed','abandoned','cancelled') " + "and accepted_at is null and sealed_at is not null")), Index("ix_submission_intake_expiry", "lease_expires_at", "id", postgresql_where=text("state in ('receiving','pre_checking')")), ) diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py index 220379e85..18fe5edb5 100644 --- a/backend/app/workers/celery_app.py +++ b/backend/app/workers/celery_app.py @@ -8,6 +8,13 @@ OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE, FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE, is_finalization_worker_process, ) +from app.workers.source_cleanup_topology import ( + SOURCE_CLEANUP_QUEUE, SOURCE_CLEANUP_TASK, SOURCE_CLEANUP_SCHEDULE, + is_source_cleanup_worker_process, +) +from app.modules.artifacts.api.submission_cleanup import ( + SUBMISSION_SOURCE_SWEEP_SECONDS, SubmissionSourceCleanupProfile, +) from app.workers.project_setup_topology import ( CELERY_VISIBILITY_TIMEOUT_SECONDS, PROJECT_GUIDE_CONSUMER_MARKER, @@ -43,6 +50,7 @@ { OUTBOX_DELIVERY_TASK, FINALIZATION_DELIVERY_TASK, + SOURCE_CLEANUP_TASK, "workstream.outbox.scan_pending", "workstream.tasks.scan_retained_revisions", "workstream.project_setup.derive_post_policy", @@ -62,6 +70,9 @@ @worker_process_init.connect def initialize_artifact_runtime_for_process(**_kwargs: object) -> None: """Claim and initialize the artifact provider once per Celery child.""" + if is_source_cleanup_worker_process(): + # Parent validated cleanup startup; each sweep rechecks current authority. + return if is_finalization_worker_process(): # Finalized replay needs retained SQL facts only. Unfinished finalization # leases/initializes the same provider through _WorkerSourceObservation. @@ -108,6 +119,8 @@ def create_celery_app() -> Celery: Configured Celery application for durable background jobs. """ settings = get_settings() + if settings.submission_source_cleanup_profile is not None: + SubmissionSourceCleanupProfile.model_validate(settings.submission_source_cleanup_profile) broker_url = settings.celery_broker_url if broker_url is None: if settings.celery_task_always_eager: @@ -122,6 +135,7 @@ def create_celery_app() -> Celery: backend=settings.celery_result_backend_url, include=[ "app.workers.artifacts", + "app.workers.source_cleanup", "app.workers.project_setup", "app.workers.post_policy", "app.workers.outbox", @@ -129,8 +143,9 @@ def create_celery_app() -> Celery: ], ) celery_app.conf.update( - task_queues=(Queue("celery"), Queue(OUTBOX_QUEUE), Queue(FINALIZATION_QUEUE)), - task_routes={OUTBOX_DELIVERY_TASK: {"queue": OUTBOX_QUEUE}, + task_queues=(Queue("celery"), Queue(OUTBOX_QUEUE), Queue(FINALIZATION_QUEUE), Queue(SOURCE_CLEANUP_QUEUE)), + task_routes={SOURCE_CLEANUP_TASK: {"queue": SOURCE_CLEANUP_QUEUE}, + OUTBOX_DELIVERY_TASK: {"queue": OUTBOX_QUEUE}, FINALIZATION_DELIVERY_TASK: {"queue": FINALIZATION_QUEUE}}, accept_content=["json"], result_serializer="json", @@ -149,6 +164,9 @@ def create_celery_app() -> Celery: worker_disable_prefetch=True, **{PROJECT_GUIDE_CONSUMER_MARKER: True}, beat_schedule={ + **({SOURCE_CLEANUP_SCHEDULE: { + "task": SOURCE_CLEANUP_TASK, "schedule": SUBMISSION_SOURCE_SWEEP_SECONDS, + }} if settings.submission_source_cleanup_profile is not None else {}), "outbox-delivery-recovery": { "task": "workstream.outbox.scan_pending", "schedule": 60.0, }, diff --git a/backend/app/workers/source_cleanup.py b/backend/app/workers/source_cleanup.py new file mode 100644 index 000000000..7c6756b20 --- /dev/null +++ b/backend/app/workers/source_cleanup.py @@ -0,0 +1,15 @@ +"""Scheduled sealed-source reclamation through the existing ART custody owner.""" +from app.adapters.artifacts.source_cleanup_worker import run_source_cleanup_sweep +from app.modules.artifacts.api.submission_cleanup import SUBMISSION_SOURCE_CLEANUP_HARD_LIMIT_SECONDS +from app.workers.async_runner import run_async_task +from app.workers.celery_app import celery_app +from app.workers.source_cleanup_topology import SOURCE_CLEANUP_TASK, require_source_cleanup_worker + + +@celery_app.task(name=SOURCE_CLEANUP_TASK, bind=True, acks_late=True, + reject_on_worker_lost=True, acks_on_failure_or_timeout=True, + time_limit=SUBMISSION_SOURCE_CLEANUP_HARD_LIMIT_SECONDS) +def sweep_submission_sources(self): + """Broker redelivery rechecks current authority and durable deletion claims.""" + require_source_cleanup_worker(self) + return run_async_task(run_source_cleanup_sweep) diff --git a/backend/app/workers/source_cleanup_topology.py b/backend/app/workers/source_cleanup_topology.py new file mode 100644 index 000000000..03f1ed636 --- /dev/null +++ b/backend/app/workers/source_cleanup_topology.py @@ -0,0 +1,58 @@ +"""Keep deletion credentials and bounded reclamation on a dedicated worker.""" +import os + +from celery.concurrency import get_implementation +from celery.concurrency.prefork import TaskPool +from celery.exceptions import WorkerShutdown +from celery.signals import worker_init + +from app.adapters.artifacts.source_cleanup_worker import validate_source_cleanup_startup +from app.workers.async_runner import run_async_task +from app.core.config import get_settings +from app.modules.artifacts.api.submission_cleanup import ( + SUBMISSION_SOURCE_CLEANUP_HARD_LIMIT_SECONDS, SubmissionSourceCleanupProfile, +) + +SOURCE_CLEANUP_QUEUE = "workstream.source_cleanup" +SOURCE_CLEANUP_TASK = "workstream.artifacts.sweep_submission_sources" +SOURCE_CLEANUP_SCHEDULE = "submission-source-cleanup" +_validated_parent = None + + +@worker_init.connect +def validate_source_cleanup_worker(sender, **_kwargs): + """Reject mixed queues, eager execution and unsupported pools before startup.""" + global _validated_parent + _validated_parent = None + queues = set(sender.app.amqp.queues.consume_from) + if SOURCE_CLEANUP_QUEUE not in queues: + return + pool = sender.pool_cls + if isinstance(pool, str): + pool = get_implementation(pool) + if queues != {SOURCE_CLEANUP_QUEUE} or pool is not TaskPool or sender.app.conf.task_always_eager: + raise WorkerShutdown("source cleanup requires an exclusive non-eager prefork worker") + try: + SubmissionSourceCleanupProfile.model_validate(get_settings().submission_source_cleanup_profile) + # Run before forking: Celery gives child-init receivers only four seconds. + # This validator disposes all of its DB/provider resources before return. + run_async_task(validate_source_cleanup_startup) + except Exception as error: + raise WorkerShutdown("source cleanup startup validation failed") from error + _validated_parent = os.getpid() + + +def is_source_cleanup_worker_process(): + return _validated_parent is not None and os.getppid() == _validated_parent + + +def require_source_cleanup_worker(task): + """Reject direct invocation and broker attempts to replace the hard bound.""" + if (not is_source_cleanup_worker_process() or task.app.conf.task_always_eager + or task.request.is_eager or task.request.called_directly): + raise RuntimeError("source cleanup requires a validated prefork worker") + message_limit = (task.request.timelimit or (None, None))[0] + if (type(task.time_limit) is not int or task.time_limit != SUBMISSION_SOURCE_CLEANUP_HARD_LIMIT_SECONDS + or message_limit is not None and (type(message_limit) is not int + or message_limit != SUBMISSION_SOURCE_CLEANUP_HARD_LIMIT_SECONDS)): + raise RuntimeError("source cleanup requires its bounded hard time limit") diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index a591f2e16..1b7acb33e 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -55,6 +55,8 @@ class TestLane: "tests/artifacts/test_submission_intake_contracts.py", "tests/artifacts/test_submission_intake_custody.py", "tests/artifacts/test_submission_source_cleanup.py", + "tests/artifacts/test_source_cleanup_worker.py", + "tests/artifacts/test_source_cleanup_topology.py", "tests/artifacts/test_submission_pre_source.py", "tests/artifacts/test_submission_intake_admission.py", "tests/artifacts/test_submission_intake_progress.py", diff --git a/backend/tests/artifacts/test_source_cleanup_topology.py b/backend/tests/artifacts/test_source_cleanup_topology.py new file mode 100644 index 000000000..87d834f1e --- /dev/null +++ b/backend/tests/artifacts/test_source_cleanup_topology.py @@ -0,0 +1,88 @@ +"""Production cleanup routing and process-bound deletion entry.""" +import os +from types import SimpleNamespace + +import pytest +from celery.concurrency.prefork import TaskPool +from celery.exceptions import WorkerShutdown + +from app.workers import source_cleanup_topology as topology + + +@pytest.fixture(autouse=True) +def cleanup_configuration(monkeypatch): + monkeypatch.setattr(topology, "_validated_parent", None) + monkeypatch.setattr(topology, "run_async_task", lambda operation: None) + monkeypatch.setattr(topology, "get_settings", lambda: SimpleNamespace( + submission_source_cleanup_profile={"maximum_candidates": 10, "run_seconds": 60, "lease_seconds": 30})) + + +def worker(*, queues=(topology.SOURCE_CLEANUP_QUEUE,), pool=TaskPool, eager=False): + return SimpleNamespace(pool_cls=pool, app=SimpleNamespace( + conf=SimpleNamespace(task_always_eager=eager), + amqp=SimpleNamespace(queues=SimpleNamespace(consume_from=queues)))) + + +@pytest.mark.parametrize("options", [ + {"queues": (topology.SOURCE_CLEANUP_QUEUE, "celery")}, + {"pool": "solo"}, {"pool": "threads"}, {"eager": True}, +]) +def test_deletion_worker_rejects_unsafe_topology(options): + with pytest.raises(WorkerShutdown): + topology.validate_source_cleanup_worker(worker(**options)) + assert topology._validated_parent is None + + +@pytest.mark.parametrize("mode", ["direct", "eager", "parent", "unvalidated", "extended_limit"]) +def test_cleanup_entry_rejects_before_async_work(monkeypatch, mode): + configured = worker() + topology.validate_source_cleanup_worker(configured) + monkeypatch.setattr(topology.os, "getppid", lambda: 1 if mode == "parent" else os.getpid()) + if mode == "unvalidated": + topology._validated_parent = None + task = SimpleNamespace(app=configured.app, time_limit=360, request=SimpleNamespace( + called_directly=mode == "direct", is_eager=mode == "eager", + timelimit=(361 if mode == "extended_limit" else 360, None))) + with pytest.raises(RuntimeError): + topology.require_source_cleanup_worker(task) + + +def test_validated_child_enters_with_fixed_bound(monkeypatch): + configured = worker(pool="prefork") + topology.validate_source_cleanup_worker(configured) + monkeypatch.setattr(topology.os, "getppid", os.getpid) + topology.require_source_cleanup_worker(SimpleNamespace(app=configured.app, time_limit=360, + request=SimpleNamespace(called_directly=False, is_eager=False, timelimit=(360, None)))) + + +@pytest.mark.parametrize("enabled", [False, True]) +def test_schedule_requires_explicit_profile_and_routes_to_cleanup_queue(monkeypatch, enabled): + import json + from app.core.config import get_settings + monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true") + monkeypatch.delenv("WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE", raising=False) + if enabled: + monkeypatch.setenv("WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE", json.dumps({ + "maximum_candidates": 10, "run_seconds": 60, "lease_seconds": 30})) + get_settings.cache_clear() + from app.workers.celery_app import create_celery_app + app = create_celery_app() + try: + assert app.amqp.router.route({}, topology.SOURCE_CLEANUP_TASK)["queue"].name == topology.SOURCE_CLEANUP_QUEUE + schedule = app.conf.beat_schedule.get(topology.SOURCE_CLEANUP_SCHEDULE) + if enabled: + assert schedule == {"task": topology.SOURCE_CLEANUP_TASK, "schedule": 12 * 60 * 60} + else: + assert schedule is None + finally: + app.close() + get_settings.cache_clear() + + +def test_startup_failure_cannot_authorize_a_cleanup_child(monkeypatch): + def unavailable(operation): + raise RuntimeError("namespace unavailable") + monkeypatch.setattr(topology, "run_async_task", unavailable) + with pytest.raises(WorkerShutdown, match="startup validation failed"): + topology.validate_source_cleanup_worker(worker()) + assert topology._validated_parent is None diff --git a/backend/tests/artifacts/test_source_cleanup_worker.py b/backend/tests/artifacts/test_source_cleanup_worker.py new file mode 100644 index 000000000..6e6f93658 --- /dev/null +++ b/backend/tests/artifacts/test_source_cleanup_worker.py @@ -0,0 +1,155 @@ +"""Scheduled cleanup composition with real custody, bytes and retry ownership.""" +import asyncio +from datetime import UTC, datetime, timedelta +from uuid import UUID + +import pytest +from sqlalchemy import text + +from app.adapters.artifacts import source_cleanup_worker as composition +from app.modules.actors.api import ServiceIdentity +from app.modules.artifacts.api.submission_cleanup import SubmissionSourceRemoval +from app.modules.artifacts.intake.repository import IntakeCustodyConflict +from tests.artifacts import test_submission_source_cleanup as cleanup_fixtures +from tests.artifacts.test_submission_intake_custody import repository, reserve +from tests.checkers.execution.support import service_link_state +from tests.test_artifact_admission import _settings +from tests.test_local_artifact_store import initialize_local_store, local_source_completion + +intake = cleanup_fixtures.intake +capacity_limits = cleanup_fixtures.capacity_limits +provision_cleanup_identity = cleanup_fixtures.provision_cleanup_identity + + +def settings_for(intake): + return _settings(intake.durable_root.parent).model_copy(update={ + "submission_source_cleanup_profile": { + "maximum_candidates": 10, "lease_seconds": 30, "run_seconds": 60, + }, + }) + + +async def sealed_local_source(intake, *, terminal=True): + store = initialize_local_store(root=intake.durable_root) + try: + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation, lease = UUID(row.id), UUID(row.lease_id) + intent = await repository(session).prepare_upload( + operation, lease, 1, part_bytes=5 * 1024**2, idle_timeout_seconds=20.0) + upload = await store.begin_source_upload(intent) + async with intake.factory.begin() as session: + await repository(session).record_upload(operation, lease, 1, upload=upload) + completion = await local_source_completion(store, upload, b"worker-source") + async with intake.factory.begin() as session: + await repository(session).record_eof(operation, lease, 1, completion=completion) + source = await store.complete_source_upload(completion) + async with intake.factory.begin() as session: + deadline = datetime.now(UTC) + timedelta(minutes=2) + await repository(session).seal(operation, lease, 1, provider_generation=source.provider_generation, + pre_deadline_at=deadline, lease_expires_at=deadline) + if terminal: + async with intake.factory.begin() as session: + await repository(session).terminalize(operation, lease, 1, state="rejected", failure_code="pre_failed") + return operation, source + finally: + store.close() + + +async def state(intake): + async with intake.factory() as session: + return tuple([await session.scalar(text( + f"SELECT jsonb_agg(to_jsonb(r) ORDER BY to_jsonb(r)::text) FROM public.{table} r" + )) for table in ("submission_intake_operations", "submission_source_charges", + "submission_source_cleanup_claims", "audit_events")]) + + +async def test_sweep_reclaims_real_source_once_and_leaves_live_pre_input(intake): + operation, source = await sealed_local_source(intake) + settings = settings_for(intake) + assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["candidates"] == 0 + await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) + live, protected = await sealed_local_source(intake, terminal=False) + result = await composition.sweep_sealed_submission_sources(intake.factory, settings) + assert result == {"candidates": 1, "confirmed": 1, "deferred": 0, "timed_out": False} + after = await state(intake) + for _ in range(2): + assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["candidates"] == 0 + assert await state(intake) == after + store = initialize_local_store(root=intake.durable_root) + try: + assert await store.observe_sealed_source(source) is None + assert await store.observe_sealed_source(protected) is not None + finally: + store.close() + async with intake.factory() as session: + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation}) == 0 + assert await session.scalar(text("SELECT state FROM submission_intake_operations WHERE id=:id"), + {"id": live}) == "pre_checking" + assert await session.scalar(text("SELECT count(*) FROM submission_source_cleanup_claims WHERE confirmed_at IS NOT NULL")) == 1 + + +async def test_sweep_retains_uncertain_claim_then_recovers_under_new_generation(intake, monkeypatch): + operation, source = await sealed_local_source(intake) + await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) + settings = settings_for(intake).model_copy(update={"submission_source_cleanup_profile": { + "maximum_candidates": 10, "lease_seconds": 30, "run_seconds": 60, + }}) + async def uncertain_remove(self, candidate, upload): + assert candidate == source + async with intake.factory.begin() as session: + await session.execute(text("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE NOWAIT"), {"id": intake.task}) + assert await session.scalar(text("SELECT generation FROM submission_source_cleanup_claims WHERE operation_id=:id"), + {"id": operation}) == 1 + return SubmissionSourceRemoval(candidate, False, False, False) + with monkeypatch.context() as patch: + from app.adapters.artifacts.source_cleanup import LocalSubmissionSourceCleanup + patch.setattr(LocalSubmissionSourceCleanup, "remove", uncertain_remove) + first = await composition.sweep_sealed_submission_sources(intake.factory, settings) + assert first["deferred"] == 1 and first["confirmed"] == 0 + async with intake.factory() as session: + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation}) > 0 + remaining = await session.scalar(text("SELECT extract(epoch FROM lease_expires_at-clock_timestamp()) " + "FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation}) + assert remaining is not None, "uncertain removal must retain a committed cleanup claim" + await asyncio.sleep(max(0, float(remaining)) + 0.05) + assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["confirmed"] == 1 + async with intake.factory() as session: + assert await session.scalar(text("SELECT generation FROM submission_source_cleanup_claims WHERE operation_id=:id"), + {"id": operation}) == 2 + + +@pytest.mark.parametrize("denial", ["service", "namespace"]) +async def test_sweep_denial_precedes_cleanup_provider_and_preserves_custody(intake, monkeypatch, denial): + operation, _ = await sealed_local_source(intake) + await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) + settings = settings_for(intake) + if denial == "service": + await service_link_state(intake.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP, active=False) + else: + foreign_root = intake.durable_root.parent / "foreign" + foreign_root.mkdir(mode=0o700) + settings = settings.model_copy(update={"artifact_local_root": foreign_root}) + def forbidden(**kwargs): + pytest.fail("denied sweep constructed deletion capability") + monkeypatch.setattr(composition, "create_submission_source_cleanup_provider", forbidden) + before = await state(intake) + from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError + from app.modules.authorization.runtime import AuthorizationDenied, PreparedAuthorizationUnsupported + with pytest.raises((IntakeCustodyConflict, ArtifactAuthorityDeniedError, AuthorizationDenied, PreparedAuthorizationUnsupported)): + await composition.sweep_sealed_submission_sources(intake.factory, settings) + assert await state(intake) == before + + +async def test_concurrent_sweeps_release_charge_only_once(intake): + operation, _ = await sealed_local_source(intake) + await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) + results = await asyncio.gather(*(composition.sweep_sealed_submission_sources( + intake.factory, settings_for(intake)) for _ in range(2))) + assert sum(result["confirmed"] for result in results) == 1 + async with intake.factory() as session: + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation}) == 0 + assert await session.scalar(text("SELECT count(*) FROM submission_source_cleanup_claims WHERE confirmed_at IS NOT NULL")) == 1 diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py index e54da0a57..13a086247 100644 --- a/backend/tests/artifacts/test_submission_intake_admission.py +++ b/backend/tests/artifacts/test_submission_intake_admission.py @@ -31,7 +31,7 @@ ) -async def test_stalled_accepted_source_is_protected_from_cleanup(recovery_intake): +async def test_stalled_accepted_source_is_protected_from_cleanup(recovery_intake, tmp_path, monkeypatch): """Exhausted finalizer delivery never turns accepted input into garbage.""" from sqlalchemy.exc import DBAPIError from sqlalchemy import text @@ -40,6 +40,15 @@ async def test_stalled_accepted_source_is_protected_from_cleanup(recovery_intake from app.modules.actors.api import ServiceIdentity f, operation = recovery_intake.f, recovery_intake.owner.operation_id await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP) + from app.adapters.artifacts import source_cleanup_worker + settings = _settings(tmp_path).model_copy(update={"submission_source_cleanup_profile": { + "maximum_candidates": 10, "run_seconds": 60, "lease_seconds": 30, + }}) + def forbidden(**kwargs): + pytest.fail("stalled accepted source reached deletion capability") + monkeypatch.setattr(source_cleanup_worker, "create_submission_source_cleanup_provider", forbidden) + for _ in range(2): + assert (await source_cleanup_worker.sweep_sealed_submission_sources(f.factory, settings))["candidates"] == 0 with pytest.raises(DBAPIError, match="cleanup is protected"): async with f.factory.begin() as session: await owner(session).claim( diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index abb4f21fa..7cfcc910b 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "b04738514ef38518dc476645c9a9b381d8d893387090b6f8479a1802cc61e3a9" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "094801f2d9fab469983e8b49ca3a0b260ded61dacd7e823380626637e440be25" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/docs/operations_artifact_storage.md b/docs/operations_artifact_storage.md index 340d37298..24287e974 100644 --- a/docs/operations_artifact_storage.md +++ b/docs/operations_artifact_storage.md @@ -248,3 +248,49 @@ retired upload-session/item shape and version-1 receipt contract are not an upgrade source. Recreate pre-v0.1 development databases; for production data, use a separately reviewed evidence-preserving maintenance migration rather than deleting, detaching, rewriting, or restamping rows. + +## Submission source reclamation + +Sealed, terminal submission sources use the dedicated +`workstream.artifacts.sweep_submission_sources` task. Configure +`WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE` as a JSON object with explicit +`maximum_candidates` (1–1000), `run_seconds` (1–300), and `lease_seconds` +(1–300, no greater than `run_seconds`). These are validation bounds, not +recommended deployment values. Size the page and execution envelope from +measured provider latency and terminal-source arrival rates. An absent profile +disables the Beat entry; it does not constitute a deployed cleanup service. + +Supply the profile to Beat and the dedicated worker. Run the worker with only +its cleanup queue and the prefork pool: + +```bash +celery -A app.workers.celery_app:celery_app worker --pool=prefork -Q workstream.source_cleanup +``` + +Other worker processes must select their own queues explicitly. Mixed queues, +eager execution, and other pools are rejected for cleanup. Startup checks the +persisted namespace, current cleanup-service authority and provider configuration +before forking. Each sweep repeats current authority checks. The task has a +fixed 360-second process hard limit; broker messages cannot extend it. + +Beat schedules a bounded sweep every 12 hours. Sources must have been both sealed +and terminal for at least two hours. Candidate discovery grants no deletion +permission: the existing owner locks task/source custody, rejects accepted or +retained sources, and commits an audited exact-generation claim before provider +I/O. Only confirmed object absence and settled upload obligations release the +charge. A failed or interrupted attempt retains its charge; a later sweep can +claim a new generation after the old lease expires. Repeated sweeps do not +release the same charge again. + +For S3-compatible storage, supply separate cleanup credentials to this worker +through its storage settings and put the upload access-key identity in the +profile's `upload_principal`. The provider factory rejects the upload principal +as the cleanup principal. Do not give these deletion credentials to API or +ordinary workers. Native AWS source cleanup remains unavailable until its +separate source-capability qualification is implemented and passed; existing +SHA-object activation and MinIO tests do not qualify it. + +This worker currently covers sealed terminal sources. Unsealed uploads, +uncertain begin/completion results and genuine orphan reconciliation remain +unfinished requirements of the submission execution specification. Do not treat +this schedule as proof that every abandoned byte is reclaimed. From 8928f39244f90402ce796fddac0d8a938a672bce Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 15:50:18 +0100 Subject: [PATCH 220/513] fix(workers): reject foreign tasks on cleanup workers --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 33 +++++++++++++++++++ .../artifacts/source_cleanup_worker.py | 2 +- backend/app/workers/celery_app.py | 3 +- .../app/workers/source_cleanup_topology.py | 10 ++++++ .../artifacts/test_source_cleanup_topology.py | 26 +++++++++++++++ .../artifacts/test_source_cleanup_worker.py | 4 ++- docs/operations_artifact_storage.md | 4 ++- 7 files changed, 78 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 1f62c341f..d8dcdc202 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7841,3 +7841,36 @@ ART imports in the worker adapter; moved candidate composition into the existing ART root and reused configured namespace composition. Startup validation now runs before fork, outside Celery's short child-init window, and disposes resources before return. A failed startup cannot mark the parent validated. + +Required reviews of clean1f9ddef55 found CLEANUP-WORKER-ISOLATION-01: +exclusive queue selection does not reject foreign registered task names delivered +to that queue. Accepted repair: use the existing Celery application's task +execution boundary to reject every non-cleanup task in a validated cleanup child, +before task code can initialize ordinary ART capabilities from cleanup settings. +A Celery signal exception is insufficient because signal dispatch can suppress +receiver errors. Add an actual registered-task trace negative and ordinary-worker +positive; retain the existing queue and process guards. No second Celery app or +submission workflow is introduced. Also clarify that successful confirmation +observations include already-confirmed replay; concurrent sweeps may both observe +confirmation, while the database proves exactly one charge release. The test +must assert the durable single-release fact without assuming a particular race +schedule. + +Shared cleanup verification closure: V2 passed five selected integration cases in +148.86s, with one namespace fixture error; V3 passed the corrected namespace +case in19.73s. Both isolated receipts report0087 and complete database/MinIO +cleanup. The first boundary/topology run passed104 and failed the new private +edge; the repaired repository boundary passed in28.35s. Structure, scoped Ruff, +record and link checks passed before the review repair. These are modified-tree +runs over884a, not a clean-head full-system or native-provider qualification. + +CLEANUP-WORKER-ISOLATION-01 regression executed through the registered +resolve_put_attempt Celery task. Before repair, the cleanup-child negative failed +with DID NOT RAISE RuntimeError while the ordinary-worker positive passed +(/tmp/submission-cleanup-isolation-before.log). The existing application's task +base now rejects foreign task names in before_start; this is a task execution +hook, not a signal receiver. After repair all15 cleanup topology cases passed +in7.82s (/tmp/submission-cleanup-isolation-after.log). The charge concurrency +assertion now allows either one or two successful confirmation observations, +while preserving its exact single durable claim and zero-charge checks. +The source owner/provider semantics are unchanged by this repair. diff --git a/backend/app/adapters/artifacts/source_cleanup_worker.py b/backend/app/adapters/artifacts/source_cleanup_worker.py index 11bd957f4..8530af03f 100644 --- a/backend/app/adapters/artifacts/source_cleanup_worker.py +++ b/backend/app/adapters/artifacts/source_cleanup_worker.py @@ -45,7 +45,7 @@ async def validate_source_cleanup_startup(): async def sweep_sealed_submission_sources(sessions, settings): - """One finite page; prior process loss leaves recoverable durable claims.""" + """One finite page; confirmed counts include already-confirmed replay.""" profile, namespace, namespace_claim = _configuration(settings) candidates, confirmed, timed_out, provider = (), 0, False, None try: diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py index 18fe5edb5..5f0c4d561 100644 --- a/backend/app/workers/celery_app.py +++ b/backend/app/workers/celery_app.py @@ -10,7 +10,7 @@ ) from app.workers.source_cleanup_topology import ( SOURCE_CLEANUP_QUEUE, SOURCE_CLEANUP_TASK, SOURCE_CLEANUP_SCHEDULE, - is_source_cleanup_worker_process, + is_source_cleanup_worker_process, WorkerTaskBoundary, ) from app.modules.artifacts.api.submission_cleanup import ( SUBMISSION_SOURCE_SWEEP_SECONDS, SubmissionSourceCleanupProfile, @@ -131,6 +131,7 @@ def create_celery_app() -> Celery: ) celery_app = Celery( "workstream", + task_cls=WorkerTaskBoundary, broker=broker_url, backend=settings.celery_result_backend_url, include=[ diff --git a/backend/app/workers/source_cleanup_topology.py b/backend/app/workers/source_cleanup_topology.py index 03f1ed636..1ec634367 100644 --- a/backend/app/workers/source_cleanup_topology.py +++ b/backend/app/workers/source_cleanup_topology.py @@ -1,6 +1,7 @@ """Keep deletion credentials and bounded reclamation on a dedicated worker.""" import os +from celery import Task from celery.concurrency import get_implementation from celery.concurrency.prefork import TaskPool from celery.exceptions import WorkerShutdown @@ -56,3 +57,12 @@ def require_source_cleanup_worker(task): or message_limit is not None and (type(message_limit) is not int or message_limit != SUBMISSION_SOURCE_CLEANUP_HARD_LIMIT_SECONDS)): raise RuntimeError("source cleanup requires its bounded hard time limit") + + +class WorkerTaskBoundary(Task): + """Keep foreign registered tasks away from a cleanup child's credentials.""" + + def before_start(self, task_id, args, kwargs): + if is_source_cleanup_worker_process() and self.name != SOURCE_CLEANUP_TASK: + raise RuntimeError("dedicated source cleanup worker rejects foreign tasks") + return super().before_start(task_id, args, kwargs) diff --git a/backend/tests/artifacts/test_source_cleanup_topology.py b/backend/tests/artifacts/test_source_cleanup_topology.py index 87d834f1e..2e6ca9bf3 100644 --- a/backend/tests/artifacts/test_source_cleanup_topology.py +++ b/backend/tests/artifacts/test_source_cleanup_topology.py @@ -86,3 +86,29 @@ def unavailable(operation): with pytest.raises(WorkerShutdown, match="startup validation failed"): topology.validate_source_cleanup_worker(worker()) assert topology._validated_parent is None + + +@pytest.mark.parametrize("cleanup_child", [True, False]) +def test_registered_foreign_task_cannot_use_cleanup_credentials(monkeypatch, cleanup_child): + from app.core.config import get_settings + from app.core.identifiers import new_record_id + monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true") + get_settings.cache_clear() + from app.workers import artifacts + calls = [] + async def operation(kind, identifier): + calls.append((kind, identifier)) + monkeypatch.setattr(artifacts, "run_artifact_internal_operation", operation) + monkeypatch.setattr(topology, "_validated_parent", os.getpid() if cleanup_child else None) + monkeypatch.setattr(topology.os, "getppid", os.getpid) + identifier = new_record_id() + try: + if cleanup_child: + with pytest.raises(RuntimeError, match="dedicated source cleanup"): + artifacts.resolve_put_attempt.apply(args=(str(identifier),), throw=True) + assert calls == [] + else: + artifacts.resolve_put_attempt.apply(args=(str(identifier),), throw=True) + assert calls == [("put", identifier)] + finally: + get_settings.cache_clear() diff --git a/backend/tests/artifacts/test_source_cleanup_worker.py b/backend/tests/artifacts/test_source_cleanup_worker.py index 6e6f93658..824eea1f6 100644 --- a/backend/tests/artifacts/test_source_cleanup_worker.py +++ b/backend/tests/artifacts/test_source_cleanup_worker.py @@ -148,7 +148,9 @@ async def test_concurrent_sweeps_release_charge_only_once(intake): await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) results = await asyncio.gather(*(composition.sweep_sealed_submission_sources( intake.factory, settings_for(intake)) for _ in range(2))) - assert sum(result["confirmed"] for result in results) == 1 + # Both pages may discover the source before either confirms; the second + # execution may then observe an already-confirmed claim. + assert 1 <= sum(result["confirmed"] for result in results) <= 2 async with intake.factory() as session: assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": operation}) == 0 diff --git a/docs/operations_artifact_storage.md b/docs/operations_artifact_storage.md index 24287e974..1c6de5b37 100644 --- a/docs/operations_artifact_storage.md +++ b/docs/operations_artifact_storage.md @@ -268,7 +268,9 @@ celery -A app.workers.celery_app:celery_app worker --pool=prefork -Q workstream. ``` Other worker processes must select their own queues explicitly. Mixed queues, -eager execution, and other pools are rejected for cleanup. Startup checks the +eager execution, and other pools are rejected for cleanup. The task execution +boundary also rejects foreign registered task names delivered to this worker. +Startup checks the persisted namespace, current cleanup-service authority and provider configuration before forking. Each sweep repeats current authority checks. The task has a fixed 360-second process hard limit; broker messages cannot extend it. From 2d3d1ac07ed7f2b7a699d7b8b60b984a936e64c7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 15:52:27 +0100 Subject: [PATCH 221/513] docs: record cleanup worker proof and remaining runtime gaps --- .commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md | 11 +++++++---- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 9ada8638c..78b3bb4bd 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -19,6 +19,7 @@ limits are in [the change record](WS-SUBMIT-001-01.md). - [x] Revision expiry and assignment invalidation serialize with acceptance; accepted input remains protected. - [x] Pending-revision protection prevents dispatch against the older Submission. - [x] Cleanup claim, retention barriers, exact-generation deletion and confirmed charge release owners. +- [x] Production sealed-source sweep wiring: explicit profile, dedicated worker/task isolation, 12-hour schedule, indexed discovery and focused real-storage retry/retention proof. - [x] Historical cap fixture no longer depends on the old writer; capture, restore/recovery and neighboring upgrade controls passed. Recent focused evidence includes atomic invalidation (`8a854f7a6`), public @@ -52,15 +53,17 @@ qualification, not a redesign of submission ownership. | Order | Required outcome | Concrete finishing evidence | | --- | --- | --- | -| 1 | Integrate production source cleanup scheduling/startup and uncertain/unsealed reconciliation | Real worker callers of the cleanup owner; restart and repeated sweeps; interrupted multipart and lost acknowledgements; accepted/stalled source survives; confirmed cleanup releases charge once. | +| 1 | Finish expired-foreground, uncertain/unsealed and genuine-orphan reconciliation | Wire the existing expired-foreground owner; reconcile interrupted multipart and lost acknowledgements; retained/stalled sources survive; actual absence and settled writes release charges once; exercise worker loss/restart. | | 2 | Remove superseded preparation/submission writers and remaining consumers | Trace all remaining callers, preserve their distinct authority/history contracts, then delete obsolete implementation. Current T5 `create_accepted` remains. | | 3 | Complete separate-runner integration and runtime/provider/resource qualification | Authenticated remote execution replacing the current API-side Unix-socket coupling; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. | | 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. | -The concrete next runtime gap is order 1. Production sealed-source worker wiring -is now implemented in the working tree, with verification and review unfinished. -Unsealed/uncertain reconciliation remains unimplemented. Further optional test +The concrete next runtime gap is order 1. Sealed-source scheduling and task +isolation passed scoped implementation review at `8928f3924`; focused integration +cases passed across two runs. This is not deployed-provider or broker-crash +qualification. `abandon_expired()` has no production caller; unsealed/uncertain +and genuine-orphan reconciliation remain unfinished. Further optional test migration must not displace closing this integration. ## Acceptance evidence still to close diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d8dcdc202..ea00e94ce 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7874,3 +7874,18 @@ in7.82s (/tmp/submission-cleanup-isolation-after.log). The charge concurrency assertion now allows either one or two successful confirmation observations, while preserving its exact single durable claim and zero-charge checks. The source owner/provider semantics are unchanged by this repair. + +Repair verification/review closure at clean8928f39244f90402ce796fddac0d8a938a672bce: +ARCH/SEC scoped PASS; QA/test-delta PASS WITH LOW RISKS. QA independently removed +the execution hook in memory and the registered-task negative failed; restoring +the hook passed (/tmp/submission-cleanup-isolation-qa-probe.json). No other +blocking scoped finding remains. System-Python structure validation passed after +the repair. Existing worker regression run passed35; six API startup tests failed +because the --noconftest command omitted the standard test pagination HMAC secret. +Supplying that exact test-only conftest setting passed all six in21.52s; no product +change or gate weakening was made. Record/link/Ruff/whitespace checks passed. +The two implementation commits close sealed-source worker integration only. +Next runtime work is expired foreground abandonment plus unsealed/uncertain and +orphan reconciliation, followed by separate-runner integration and final goal +qualification. No broker-crash, native AWS, production deployment or full-goal +completion claim is made. One draft PR708 remains the delivery vehicle. From 9d0e56f30740a61ec4ad03af1e8e2e08f1a1a6be Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 16:06:33 +0100 Subject: [PATCH 222/513] fix(artifacts): recover expired foreground custody during cleanup --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 40 +++++++++++ backend/app/adapters/artifacts/__init__.py | 35 ++++++++++ .../artifacts/source_cleanup_worker.py | 7 +- .../app/modules/artifacts/intake/cleanup.py | 37 ++++++++++- .../artifacts/test_source_cleanup_worker.py | 66 ++++++++++++++++++- docs/operations_artifact_storage.md | 8 ++- 6 files changed, 184 insertions(+), 9 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index ea00e94ce..89534626b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7889,3 +7889,43 @@ Next runtime work is expired foreground abandonment plus unsealed/uncertain and orphan reconciliation, followed by separate-runner integration and final goal qualification. No broker-crash, native AWS, production deployment or full-goal completion claim is made. One draft PR708 remains the delivery vehicle. + +Next runtime scope: recover expired receiving/PRE owners through the existing +source-cleanup worker and existing abandon_expired primitive, then extend the +same cleanup ownership to interrupted/unsealed provider obligations. No alternate +submission lifecycle, PRE worker, accepted-work expiration or source charge +release from mere lease expiry. First recovery step uses the existing indexed +expiry candidates, exact configured namespace and current cleanup service; +each operation gets its own TASK-first root and an after-lock authority recheck. +State/lease are rechecked by the current primitive, which fences the old owner +and releases only its task pointer. Source bytes remain charged. The existing +12-hour sweep is the periodic caller; this step does not claim prompt runtime +reaping or change revision expiry. Allowed files: existing ART intake cleanup, +repository/capacity and their SQL guards as required for later unsealed custody; +ART composition, cleanup provider/worker/API, focused integration tests and +required migration/head/fingerprint files; current runbook and this checklist. +Prohibited: weakening accepted-source retention, synthesizing a sealed source to +release partial-upload charges, using absence or an abort acknowledgement as +settlement, broad provider deletion, introducing deployment defaults. Risk: +security/workflow. Required QA and architecture/security review. First proof: +expired receiving/PRE clears only its exact task guard and rejects late owners; +live and accepted operations survive; revoked service/foreign namespace cannot +mutate custody; source charges remain until separately confirmed cleanup. +Unsealed reconciliation is not considered implemented by this first step. + +Expired-foreground first-step evidence: V1 passed eight PostgreSQL cases in +255.14s, including the existing cleanup/retry/accepted-protection cases and both +receiving/PRE abandonment cases. Before finalizing the change, recovery attempts +were individually bounded using the existing explicit profile lease interval, +and the expiry query was changed to bind a database-clock value so the existing +expiry index can supply candidates. V2 passed seven affected cases in164.77s: +both foreground phases, real TASK-lock timeout followed by successful next-sweep +recovery, and service/namespace denial against both sealed and expired targets. +Both isolated runs used schema0087 and report complete resource cleanup. +Logs/receipts: /tmp/submission-expired-foreground-v1.log/.json and +/tmp/submission-expired-foreground-v2.log/.json. The exact module boundary passed +in44.39s; structure, Ruff, record/link and whitespace checks passed. No schema +change, new worker queue, PRE retry or source-charge release was introduced. +These proofs do not implement or qualify unsealed-byte reclamation. The periodic +caller is explicitly the existing12-hour sweep; prompt runtime reaping remains +separate. Required focused review follows against the clean candidate. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 0c9d121d6..5a4dfeed7 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -1062,6 +1062,41 @@ async def submission_source_cleanup_candidates(sessions, namespace, limit): authority.close() +async def abandon_expired_submission_foregrounds(sessions, namespace, limit, *, operation_timeout_seconds): + """Recover one bounded page with an independent custody root per operation.""" + import asyncio + from app.adapters.tasks import intake_task_custody_port + from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization + from app.modules.artifacts.intake.cleanup import SealedSourceCleanup + from app.core.identifiers import new_record_id + from contextlib import asynccontextmanager + + @asynccontextmanager + async def root(): + async with sessions.begin() as session: + authority = PreparedSubmissionSourceCleanupAuthorization( + session, request_id=new_record_id(), correlation_id=new_record_id()) + try: + yield SealedSourceCleanup(session, intake_task_custody_port(session), authority) + finally: + authority.close() + + async with root() as owner: + candidates = await owner.expired_foreground(namespace, limit=limit) + abandoned = 0 + for operation in candidates: + try: + async with asyncio.timeout(operation_timeout_seconds): + async with root() as owner: + changed = await owner.abandon_expired(operation, namespace) + abandoned += changed + except TimeoutError: + # A busy task cannot consume every operation's recovery opportunity. + # Any uncertain commit is resolved from durable state on the next pass. + continue + return abandoned + + def submission_source_cleanup_execution(*, sessions, provider, lease_duration): """Compose deletion with the fixed cleanup service and TASK custody owner.""" from app.adapters.tasks import intake_task_custody_port diff --git a/backend/app/adapters/artifacts/source_cleanup_worker.py b/backend/app/adapters/artifacts/source_cleanup_worker.py index 8530af03f..910e20233 100644 --- a/backend/app/adapters/artifacts/source_cleanup_worker.py +++ b/backend/app/adapters/artifacts/source_cleanup_worker.py @@ -7,6 +7,7 @@ from app.adapters.artifacts import ( create_artifact_store_bootstrap, create_submission_source_cleanup_provider, submission_source_cleanup_execution, submission_source_cleanup_candidates, + abandon_expired_submission_foregrounds, configured_artifact_storage_namespace, IntakeCustodyConflict, ) from app.core.config import get_settings @@ -47,9 +48,11 @@ async def validate_source_cleanup_startup(): async def sweep_sealed_submission_sources(sessions, settings): """One finite page; confirmed counts include already-confirmed replay.""" profile, namespace, namespace_claim = _configuration(settings) - candidates, confirmed, timed_out, provider = (), 0, False, None + candidates, confirmed, timed_out, provider, abandoned = (), 0, False, None, 0 try: async with asyncio.timeout(profile.run_seconds): + abandoned = await abandon_expired_submission_foregrounds( + sessions, namespace, profile.maximum_candidates, operation_timeout_seconds=profile.lease_seconds) candidates = await submission_source_cleanup_candidates(sessions, namespace, profile.maximum_candidates) if candidates: provider = create_submission_source_cleanup_provider( @@ -71,7 +74,7 @@ async def sweep_sealed_submission_sources(sessions, settings): if provider is not None: provider.close() return {"candidates": len(candidates), "confirmed": confirmed, - "deferred": len(candidates) - confirmed, "timed_out": timed_out} + "deferred": len(candidates) - confirmed, "timed_out": timed_out, "abandoned": abandoned} async def run_source_cleanup_sweep(): diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py index 25bcf2298..9bf14f5cd 100644 --- a/backend/app/modules/artifacts/intake/cleanup.py +++ b/backend/app/modules/artifacts/intake/cleanup.py @@ -52,15 +52,46 @@ def __init__(self, session, tasks, authorization): self._authorization = authorization self._intake = SubmissionIntakeRepository(session, tasks) + async def _require_namespace(self, namespace): + persisted = await self._session.get(ArtifactStorageNamespace, "primary") + if persisted is None or any(getattr(persisted, key) != value for key, value in asdict(namespace).items()): + raise IntakeCustodyConflict("source_cleanup_namespace_unavailable") + + async def expired_foreground(self, namespace, *, limit: int) -> tuple[UUID, ...]: + """Discover expired pre-handoff owners; discovery cannot change custody.""" + if type(limit) is not int or not 1 <= limit <= 1000: + raise ValueError("source cleanup candidate bound is invalid") + await self._authorization.authorize() + await self._authorization.revalidate() + await self._require_namespace(namespace) + operation = SubmissionIntakeOperation + now = await self._session.scalar(select(func.clock_timestamp())) + identifiers = await self._session.scalars(select(operation.id).where( + operation.namespace_id == "primary", + operation.namespace_fingerprint == namespace.namespace_fingerprint, + operation.state.in_(("receiving", "pre_checking")), + operation.lease_expires_at <= now, + ).order_by(operation.lease_expires_at, operation.id).limit(limit)) + return tuple(UUID(identifier) for identifier in identifiers) + + async def abandon_expired(self, operation_id: UUID, namespace) -> bool: + """Fence a dead foreground owner without deleting bytes or releasing charges.""" + await self._authorization.authorize() + operation = await self._intake._lock(operation_id) + await self._authorization.revalidate() + await self._require_namespace(namespace) + if (operation.namespace_id != "primary" + or operation.namespace_fingerprint != namespace.namespace_fingerprint): + raise IntakeCustodyConflict("source_cleanup_namespace_unavailable") + return await self._intake.abandon_expired(operation_id) + async def candidates(self, namespace, *, limit: int) -> tuple[UUID, ...]: """Discover a bounded page; every result still requires an exact claim.""" if type(limit) is not int or not 1 <= limit <= 1000: raise ValueError("source cleanup candidate bound is invalid") await self._authorization.authorize() await self._authorization.revalidate() - persisted = await self._session.get(ArtifactStorageNamespace, "primary") - if persisted is None or any(getattr(persisted, key) != value for key, value in asdict(namespace).items()): - raise IntakeCustodyConflict("source_cleanup_namespace_unavailable") + await self._require_namespace(namespace) operation, claim, charge = SubmissionIntakeOperation, SubmissionSourceCleanupClaim, SubmissionSourceCharge now = await self._session.scalar(select(func.clock_timestamp())) retained = select(ArtifactReplica.id).where(or_( diff --git a/backend/tests/artifacts/test_source_cleanup_worker.py b/backend/tests/artifacts/test_source_cleanup_worker.py index 824eea1f6..fb71f3339 100644 --- a/backend/tests/artifacts/test_source_cleanup_worker.py +++ b/backend/tests/artifacts/test_source_cleanup_worker.py @@ -71,7 +71,7 @@ async def test_sweep_reclaims_real_source_once_and_leaves_live_pre_input(intake) await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) live, protected = await sealed_local_source(intake, terminal=False) result = await composition.sweep_sealed_submission_sources(intake.factory, settings) - assert result == {"candidates": 1, "confirmed": 1, "deferred": 0, "timed_out": False} + assert result == {"candidates": 1, "confirmed": 1, "deferred": 0, "timed_out": False, "abandoned": 0} after = await state(intake) for _ in range(2): assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["candidates"] == 0 @@ -122,8 +122,9 @@ async def uncertain_remove(self, candidate, upload): @pytest.mark.parametrize("denial", ["service", "namespace"]) -async def test_sweep_denial_precedes_cleanup_provider_and_preserves_custody(intake, monkeypatch, denial): - operation, _ = await sealed_local_source(intake) +@pytest.mark.parametrize("target", ["sealed", "expired"]) +async def test_sweep_denial_precedes_cleanup_provider_and_preserves_custody(intake, monkeypatch, denial, target): + operation, _ = await sealed_local_source(intake, terminal=target == "sealed") await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) settings = settings_for(intake) if denial == "service": @@ -155,3 +156,62 @@ async def test_concurrent_sweeps_release_charge_only_once(intake): assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": operation}) == 0 assert await session.scalar(text("SELECT count(*) FROM submission_source_cleanup_claims WHERE confirmed_at IS NOT NULL")) == 1 + + +@pytest.mark.parametrize("phase", ["receiving", "pre_checking"]) +async def test_sweep_fences_expired_foreground_without_releasing_source_charge(intake, monkeypatch, phase): + if phase == "pre_checking": + operation, _ = await sealed_local_source(intake, terminal=False) + else: + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation = UUID(row.id) + settings = settings_for(intake) + def forbidden(**kwargs): + pytest.fail("foreground abandonment constructed deletion capability") + monkeypatch.setattr(composition, "create_submission_source_cleanup_provider", forbidden) + assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["abandoned"] == 0 + async with intake.factory() as session: + lease = await session.scalar(text("SELECT lease_id FROM submission_intake_operations WHERE id=:id"), {"id": operation}) + charged = await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation}) + await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) + result = await composition.sweep_sealed_submission_sources(intake.factory, settings) + assert result["abandoned"] == 1 and result["candidates"] == 0 + async with intake.factory() as session: + row = (await session.execute(text("SELECT state,lease_generation,failure_code FROM submission_intake_operations WHERE id=:id"), + {"id": operation})).one() + assert tuple(row) == ("abandoned", 2, "submission_foreground_expired") + assert await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), + {"id": intake.task}) is None + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation}) == charged > 0 + async with intake.factory.begin() as session: + replacement = await reserve(intake, session, with_upload=False) + replacement_id = replacement.id + with pytest.raises(IntakeCustodyConflict, match="owner_stale"): + async with intake.factory.begin() as session: + await repository(session).heartbeat(operation, UUID(str(lease)), 1, lease_duration=timedelta(seconds=30)) + assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["abandoned"] == 0 + async with intake.factory() as session: + assert str(await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), + {"id": intake.task})) == replacement_id + + +async def test_busy_expired_task_defers_then_recovers_on_next_sweep(intake): + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation = UUID(row.id) + await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) + bounded = settings_for(intake).model_copy(update={"submission_source_cleanup_profile": { + "maximum_candidates": 10, "lease_seconds": 2, "run_seconds": 60, + }}) + async with intake.factory.begin() as blocker: + await blocker.execute(text("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE"), {"id": intake.task}) + async with asyncio.timeout(10): + result = await composition.sweep_sealed_submission_sources(intake.factory, bounded) + assert result["abandoned"] == 0 and result["timed_out"] is False + assert await blocker.scalar(text("SELECT state FROM submission_intake_operations WHERE id=:id"), + {"id": operation}) == "receiving" + result = await composition.sweep_sealed_submission_sources(intake.factory, settings_for(intake)) + assert result["abandoned"] == 1 and result["confirmed"] == 0 diff --git a/docs/operations_artifact_storage.md b/docs/operations_artifact_storage.md index 1c6de5b37..5ab44abfd 100644 --- a/docs/operations_artifact_storage.md +++ b/docs/operations_artifact_storage.md @@ -275,7 +275,13 @@ persisted namespace, current cleanup-service authority and provider configuratio before forking. Each sweep repeats current authority checks. The task has a fixed 360-second process hard limit; broker messages cannot extend it. -Beat schedules a bounded sweep every 12 hours. Sources must have been both sealed +Beat schedules a bounded sweep every 12 hours. Its recovery pass first fences +expired receiving/PRE operations, rechecking each under its task lock and current +service authority. This clears only the old operation's task pointer; it neither +resumes PRE nor releases storage charges. Live and accepted operations remain +protected. Recovery uses the sweep's explicit page/run limits and bounds each +attempt by the configured lease interval. This is periodic foreground recovery, +not the prompt runtime-session reaper. Sources must have been both sealed and terminal for at least two hours. Candidate discovery grants no deletion permission: the existing owner locks task/source custody, rejects accepted or retained sources, and commits an audited exact-generation claim before provider From 81d69a20745b1a8f6870c6b0af652d11e48520b8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 16:18:02 +0100 Subject: [PATCH 223/513] fix(artifacts): preserve cleanup progress during foreground contention --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 37 ++++++++++++ .../artifacts/source_cleanup_worker.py | 10 +++- .../artifacts/test_source_cleanup_worker.py | 60 +++++++++++++++++-- docs/operations_artifact_storage.md | 4 +- 4 files changed, 103 insertions(+), 8 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 89534626b..9406e8578 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7929,3 +7929,40 @@ change, new worker queue, PRE retry or source-charge release was introduced. These proofs do not implement or qualify unsealed-byte reclamation. The periodic caller is explicitly the existing12-hour sweep; prompt runtime reaping remains separate. Required focused review follows against the clean candidate. + +Review of9d0e56f30 found a liveness issue: a blocked expired operation can consume +the whole run envelope before sealed work starts. Repair reserves half the +existing run envelope for foreground recovery, leaving sealed processing time; +no new deployment setting or queue. The held-lock test now includes an unrelated +aged sealed source and equal operation/run limits. QA-EXPIRED-001 also requests +a discriminating real PostgreSQL race: authorize discovery, block mutation on +TASK, revoke cleanup service, release TASK, and prove operation/generation/charge +and task pointer unchanged. Both findings are accepted and repaired together. + +Unsealed-path inspection, for continuation: current charge_shape requires +sealed_at even for released charges, so partial-source release needs an explicit +SQL/owner extension, never a fabricated seal. Reuse the existing cleanup claim +and authority mechanism with a typed unsealed target. An absent initiation +receipt, checked under operation custody, proves foreground never obtained write +permission; a receipt with uncertain +begin requires scoped handle discovery and settlement; committed EOF permits +exact completion observation. An observed completed version must become a durable +exact cleanup target before deletion, with fresh age protection for late writes. +Local can settle partial writers under its existing operation lock and retained +abort tombstone. S3 abort acknowledgement or one empty observation is insufficient +for writes_settled. Preserve conservative charge for unresolved remote outcomes. +This is implementation guidance, not completed reconciliation or provider proof. + +Repair proof: the held-TASK/unrelated-sealed regression failed against9d0e56f30 +with confirmed0 rather than1 in58.98s. With half-envelope recovery isolation, +both foreground phase controls and the contention regression passed in the +four-case repair run. Its revocation case reached the correct authorization +denial but expected the wrong exception class; fixed the test to expect the +actual PreparedAuthorizationUnsupported boundary. Exact revocation replay passed +in24.31s and checked unchanged operation/generation/charge/audit state plus the +original task pointer. Logs: /tmp/submission-expired-starvation-before.log/.json, +/tmp/submission-expired-repair.log/.json (3 pass,1 expected-error mismatch), and +/tmp/submission-expired-revocation.log/.json (1 pass). All isolated receipts report +schema0087 and completed cleanup. System-Python structure validation passed after +the repair; Ruff, record/link and whitespace checks passed. No production denial +was suppressed or broadened to satisfy the test. Clean review replay follows. diff --git a/backend/app/adapters/artifacts/source_cleanup_worker.py b/backend/app/adapters/artifacts/source_cleanup_worker.py index 910e20233..534dbbd9b 100644 --- a/backend/app/adapters/artifacts/source_cleanup_worker.py +++ b/backend/app/adapters/artifacts/source_cleanup_worker.py @@ -51,8 +51,14 @@ async def sweep_sealed_submission_sources(sessions, settings): candidates, confirmed, timed_out, provider, abandoned = (), 0, False, None, 0 try: async with asyncio.timeout(profile.run_seconds): - abandoned = await abandon_expired_submission_foregrounds( - sessions, namespace, profile.maximum_candidates, operation_timeout_seconds=profile.lease_seconds) + try: + # Reserve at least half the envelope for sealed sources even + # when expired foreground custody is blocked on a TASK lock. + async with asyncio.timeout(profile.run_seconds / 2): + abandoned = await abandon_expired_submission_foregrounds( + sessions, namespace, profile.maximum_candidates, operation_timeout_seconds=profile.lease_seconds) + except TimeoutError: + timed_out = True candidates = await submission_source_cleanup_candidates(sessions, namespace, profile.maximum_candidates) if candidates: provider = create_submission_source_cleanup_provider( diff --git a/backend/tests/artifacts/test_source_cleanup_worker.py b/backend/tests/artifacts/test_source_cleanup_worker.py index fb71f3339..e4b8afe0c 100644 --- a/backend/tests/artifacts/test_source_cleanup_worker.py +++ b/backend/tests/artifacts/test_source_cleanup_worker.py @@ -199,19 +199,69 @@ def forbidden(**kwargs): async def test_busy_expired_task_defers_then_recovers_on_next_sweep(intake): + from types import SimpleNamespace + from app.core.identifiers import new_record_id + from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test + sealed_operation, _ = await sealed_local_source(intake) + await cleanup_fixtures.age_fixture(intake, sealed_operation, preserve_upload_deadline=True) + other = SimpleNamespace(**vars(intake)) + other.task, other.assignment = new_record_id(), new_record_id() + async with intake.engine.begin() as connection: + project = await connection.scalar(text("SELECT project_id FROM workstream_tasks WHERE id=:id"), {"id": intake.task}) + await seed_started_task_for_artifact_test(connection, dict( + task=str(other.task), assignment=str(other.assignment), project=str(project), + actor=str(intake.actor.actor_profile_id))) async with intake.factory.begin() as session: - row = await reserve(intake, session, with_upload=False) + row = await reserve(other, session, with_upload=False) operation = UUID(row.id) await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) bounded = settings_for(intake).model_copy(update={"submission_source_cleanup_profile": { - "maximum_candidates": 10, "lease_seconds": 2, "run_seconds": 60, + "maximum_candidates": 10, "lease_seconds": 30, "run_seconds": 30, }}) async with intake.factory.begin() as blocker: - await blocker.execute(text("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE"), {"id": intake.task}) - async with asyncio.timeout(10): + await blocker.execute(text("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE"), {"id": other.task}) + async with asyncio.timeout(40): result = await composition.sweep_sealed_submission_sources(intake.factory, bounded) - assert result["abandoned"] == 0 and result["timed_out"] is False + assert result["abandoned"] == 0 and result["timed_out"] is True + assert result["confirmed"] == 1 assert await blocker.scalar(text("SELECT state FROM submission_intake_operations WHERE id=:id"), {"id": operation}) == "receiving" result = await composition.sweep_sealed_submission_sources(intake.factory, settings_for(intake)) assert result["abandoned"] == 1 and result["confirmed"] == 0 + + +async def test_expired_recovery_rechecks_service_after_waiting_for_task(intake, monkeypatch): + from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization + from app.modules.authorization.runtime import PreparedAuthorizationUnsupported + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation = UUID(row.id) + await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) + authorized = asyncio.Event() + original = PreparedSubmissionSourceCleanupAuthorization.authorize + calls = 0 + async def observe_authorization(self): + nonlocal calls + await original(self) + calls += 1 + if calls == 2: # Discovery committed; this is the mutation root's preflight. + authorized.set() + monkeypatch.setattr(PreparedSubmissionSourceCleanupAuthorization, "authorize", observe_authorization) + recovery = None + try: + async with intake.factory.begin() as blocker: + await blocker.execute(text("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE"), {"id": intake.task}) + recovery = asyncio.create_task(composition.sweep_sealed_submission_sources(intake.factory, settings_for(intake))) + await asyncio.wait_for(authorized.wait(), timeout=10) + await service_link_state(intake.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP, active=False) + before = await state(intake) + with pytest.raises(PreparedAuthorizationUnsupported): + await asyncio.wait_for(recovery, timeout=10) + assert await state(intake) == before + async with intake.factory() as session: + assert str(await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), + {"id": intake.task})) == str(operation) + finally: + if recovery is not None and not recovery.done(): + recovery.cancel() + await asyncio.gather(recovery, return_exceptions=True) diff --git a/docs/operations_artifact_storage.md b/docs/operations_artifact_storage.md index 5ab44abfd..103eef678 100644 --- a/docs/operations_artifact_storage.md +++ b/docs/operations_artifact_storage.md @@ -280,7 +280,9 @@ expired receiving/PRE operations, rechecking each under its task lock and curren service authority. This clears only the old operation's task pointer; it neither resumes PRE nor releases storage charges. Live and accepted operations remain protected. Recovery uses the sweep's explicit page/run limits and bounds each -attempt by the configured lease interval. This is periodic foreground recovery, +attempt by the configured lease interval. Foreground recovery can use at most +half the run envelope, preserving time for unrelated sealed cleanup even when a +task lock is held. This is periodic foreground recovery, not the prompt runtime-session reaper. Sources must have been both sealed and terminal for at least two hours. Candidate discovery grants no deletion permission: the existing owner locks task/source custody, rejects accepted or From 6297de2ac0a5b4547762d663ac3c0f11c6718955 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 16:21:19 +0100 Subject: [PATCH 224/513] docs: record foreground recovery closure and next cleanup scope --- .commitrail/INDEX.md | 2 +- .commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md | 13 +++++++------ .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 ++++++++++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index eae0bedd3..d070ae7d7 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Hidden foreground custody, physical source reservations and bounded S3-compatible/local source methods and private upload composition; next shared foreground lifecycle/cleanup, AWS source qualification, one-session PRE, handoff/finalization and client/cutover proof. The active flow remains preparation plus admission-consuming creation. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP intake, PRE/T4/T5 and CLI/MCP implementation have focused proof; sealed-source scheduling and expired-foreground recovery are wired. Next: interrupted/unsealed and orphan reclamation, obsolete-writer retirement, separate-runner integration, native/provider qualification and full acceptance/configuration closure. See the overview for checked implementation versus remaining evidence. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 78b3bb4bd..4c0afd146 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -20,12 +20,12 @@ limits are in [the change record](WS-SUBMIT-001-01.md). - [x] Pending-revision protection prevents dispatch against the older Submission. - [x] Cleanup claim, retention barriers, exact-generation deletion and confirmed charge release owners. - [x] Production sealed-source sweep wiring: explicit profile, dedicated worker/task isolation, 12-hour schedule, indexed discovery and focused real-storage retry/retention proof. +- [x] Expired receiving/PRE recovery through the sweep: current authority and task-lock recheck, old-owner fencing, exact pointer release, retained source charge and separate time for sealed cleanup. - [x] Historical cap fixture no longer depends on the old writer; capture, restore/recovery and neighboring upgrade controls passed. Recent focused evidence includes atomic invalidation (`8a854f7a6`), public -ZIP/T5 lineage (`168e5268f`), and policy-error translation (`d31a45773`). The -last change passed seven PostgreSQL cases and 92 boundary checks. These are -bounded results, not full-head qualification. +ZIP/T5 lineage (`168e5268f`), and policy-error translation (`d31a45773`). These and the cleanup/recovery runs recorded below are bounded results, not +full-head qualification. ## Execution deployment decision @@ -53,7 +53,7 @@ qualification, not a redesign of submission ownership. | Order | Required outcome | Concrete finishing evidence | | --- | --- | --- | -| 1 | Finish expired-foreground, uncertain/unsealed and genuine-orphan reconciliation | Wire the existing expired-foreground owner; reconcile interrupted multipart and lost acknowledgements; retained/stalled sources survive; actual absence and settled writes release charges once; exercise worker loss/restart. | +| 1 | Finish uncertain/unsealed and genuine-orphan reconciliation | Reconcile interrupted multipart and lost acknowledgements; retained/stalled sources survive; actual absence and settled writes release charges once; exercise worker loss/restart. | | 2 | Remove superseded preparation/submission writers and remaining consumers | Trace all remaining callers, preserve their distinct authority/history contracts, then delete obsolete implementation. Current T5 `create_accepted` remains. | | 3 | Complete separate-runner integration and runtime/provider/resource qualification | Authenticated remote execution replacing the current API-side Unix-socket coupling; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. | @@ -62,8 +62,9 @@ qualification, not a redesign of submission ownership. The concrete next runtime gap is order 1. Sealed-source scheduling and task isolation passed scoped implementation review at `8928f3924`; focused integration cases passed across two runs. This is not deployed-provider or broker-crash -qualification. `abandon_expired()` has no production caller; unsealed/uncertain -and genuine-orphan reconciliation remain unfinished. Further optional test +qualification. Expired-foreground recovery passed scoped review at `81d69a207`, +including blocked-task progress and after-lock service revocation. Unsealed/ +uncertain and genuine-orphan reconciliation remain unfinished. Further optional test migration must not displace closing this integration. ## Acceptance evidence still to close diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 9406e8578..27546b3f0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7966,3 +7966,17 @@ original task pointer. Logs: /tmp/submission-expired-starvation-before.log/.json schema0087 and completed cleanup. System-Python structure validation passed after the repair; Ruff, record/link and whitespace checks passed. No production denial was suppressed or broadened to satisfy the test. Clean review replay follows. + +Clean81d69a20745b1a8f6870c6b0af652d11e48520b8 review closure: scoped ARCH/SEC +PASS and QA/test-delta PASS WITH LOW RISKS. Independent exact-case mutation +removed only after-lock revalidation; the PostgreSQL revocation test failed on +unchanged-state equality because abandonment incorrectly committed, even though +later discovery still raised the expected authorization denial. Evidence: +/tmp/submission-expired-qa-mutant.log/.json, expected1failure19.08s, schema0087, +complete cleanup. Both scoped findings are closed. No unsealed/provider/full-goal +qualification is claimed. Refresh this initiative overview and its INDEX.md +navigation row to remove the obsolete no-production-caller/preparation-only +summary; full capability-ledger/export reconciliation remains in final delivery +scope. The next implementation boundary is interrupted/unsealed and genuine +orphan reconciliation using existing cleanup ownership, followed by the remaining +writer retirement, remote execution and acceptance/configuration qualification. From e6844b38ca0a74d88b3fe1deb32058434205fea8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:08:38 +0100 Subject: [PATCH 225/513] Recover unsealed submission sources through existing cleanup custody --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 17 ++ .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 67 +++++++ backend/alembic/env.py | 3 +- .../versions/0088_unsealed_source_cleanup.py | 129 +++++++++++++ backend/app/adapters/artifacts/__init__.py | 8 +- .../artifacts/local_submission_source.py | 44 +++++ .../app/adapters/artifacts/source_cleanup.py | 34 +++- .../artifacts/source_cleanup_worker.py | 8 +- .../artifacts/api/submission_cleanup.py | 84 ++++++++- .../app/modules/artifacts/intake/capacity.py | 2 +- .../app/modules/artifacts/intake/cleanup.py | 99 +++++++--- .../artifacts/intake/cleanup_execution.py | 24 ++- .../app/modules/artifacts/intake/models.py | 8 +- backend/scripts/test_lane_catalogue.py | 2 + .../artifacts/test_source_cleanup_worker.py | 26 +-- .../test_submission_intake_admission.py | 2 +- .../test_submission_source_cleanup.py | 11 +- .../artifacts/test_unsealed_source_cleanup.py | 176 ++++++++++++++++++ backend/tests/conftest.py | 2 +- .../test_unsealed_source_cleanup.py | 94 ++++++++++ backend/tests/test_s3_artifact_store.py | 34 ++++ 21 files changed, 812 insertions(+), 62 deletions(-) create mode 100644 backend/alembic/versions/0088_unsealed_source_cleanup.py create mode 100644 backend/tests/artifacts/test_unsealed_source_cleanup.py create mode 100644 backend/tests/migrations/test_unsealed_source_cleanup.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 4c0afd146..61d8803be 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -49,6 +49,16 @@ durable delivery. Remove shared-host coupling and obsolete writers; do not grow parallel local/remote product workflows. A named paid provider needs its own qualification, not a redesign of submission ownership. +Keep the implementation boundary concrete: Workstream owns intake, immutable +source references, task state and acceptance; artifact storage owns durable ZIP +bytes; the selected execution adapter owns remote session creation, execution, +results and teardown. Runner scratch is disposable and never the sole retained +copy. Carry the intake/attempt identity and exact source identity across the +request and result so failures can be traced across services. Validate separation +with the API and runner on different hosts and no shared filesystem. A provider +change must not require a second submission lifecycle. These are implementation +and verification requirements, not claims that remote transport is complete. + ## Remaining work, in execution order | Order | Required outcome | Concrete finishing evidence | @@ -67,6 +77,13 @@ including blocked-task progress and after-lock service revocation. Unsealed/ uncertain and genuine-orphan reconciliation remain unfinished. Further optional test migration must not displace closing this integration. +The current unsealed change extends that same cleanup owner: Local incomplete +uploads can be reclaimed, and an observed late completion is retained until a +fresh aged claim identifies its exact version. Focused Local/PostgreSQL and MinIO +checks passed, as did the existing cleanup-owner suite. Remote partial-write +settlement and genuine-orphan reconciliation remain open; do not treat this +partial implementation as completion of order 1. + ## Acceptance evidence still to close No row below is declared fully complete merely because some related tests pass. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 27546b3f0..cdc7f3a27 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -7980,3 +7980,70 @@ summary; full capability-ledger/export reconciliation remains in final delivery scope. The next implementation boundary is interrupted/unsealed and genuine orphan reconciliation using existing cleanup ownership, followed by the remaining writer retirement, remote execution and acceptance/configuration qualification. + +Unsealed implementation boundary: generalize the existing cleanup claim target +with an explicit unsealed source value bound to operation location, initiation +fence/handle and committed EOF identity. Preserve existing sealed target bytes +and digest domain; no alias or second cleanup subsystem. Carry exact initiation, +handle and completion facts through the same owner/claim/confirmation execution. +Extend SQL target validation/audit digest and permit a reserved charge to become +released only through the same confirmed cleanup tombstone. No-initiation cleanup +uses locked durable absence of write permission. Local partial cleanup uses its +existing operation lock plus an immutable abort tombstone; a discovered completed +source is retained until exact-version custody and fresh age are recorded. +Unknown remote begin/completion remains charged until provider settlement is +proved. Scope includes existing cleanup API, owner/execution/capacity/model, +provider adapters and their source primitives, worker/composition and callers, +0088 migration/head/fingerprint plus focused Local/MinIO/PG retained-data controls. +Do not mark all unsealed reconciliation complete while late completion or remote +settlement is unresolved. Required reviews remain QA and architecture/security. + +Unsealed recovery verification on the uncommitted 0088 candidate: the initial +observation run passed nine cases and failed its historical timestamp fixture +because deferred PostgreSQL trigger events prevented restoring the guard. Flush +constraints before restoring that guard, as the existing age fixture does; do +not weaken production triggers. The exact late-completion replay then passed +in 21.88s (`/tmp/submission-unsealed-v3.log/.json`, schema0088, isolated resources +cleaned). It proves observation retains the ZIP and charge, invalidates the old +target decision, and requires an aged fresh exact-version claim before removal. +Add direct SQL substitution probes for operation/hash/fence and old-claim release. +Rename the existing sweep to `sweep_submission_sources` with all callers updated; +there is one sweep, not parallel sealed/unsealed workers. Replace the superseded +test forbidding all terminal unsealed claims with recent-age denial and aged +unsealed eligibility, retaining live-input and competing-claim protection. +Scoped Ruff, module-boundary, structure, link and record checks passed before the +combined rerun. Remote unsealed settlement, orphan reconciliation, retained-row +migration proof and focused review remain required; these local results do not +qualify them. + +The combined 0088 Local/PostgreSQL rerun passed all 11 cases in 204.10s +(`/tmp/submission-unsealed-v4.log/.json`): five unfinished-upload phases, recent +partial/completed retention, late-completion age and fresh-version authority, +direct SQL source-substitution rejection, existing sealed-source/live-PRE cleanup, +and stalled accepted-source protection. This run includes the sweep rename. +The full existing cleanup-owner suite and two real-MinIO unsealed adapter cases +are separate verification runs; do not infer their results from these 11 cases. + +The two MinIO adapter cases passed in 18.11s +(`/tmp/submission-unsealed-minio-v1.log/.json`, schema0088, isolated cleanup +complete): completed-but-unrecorded bytes are observed and preserved, while +unfinished multipart abort confirms handle absence without falsely reporting +complete write settlement. The Local/PostgreSQL combined-run receipt also +confirms isolated cleanup complete. Native AWS and complete remote settlement +remain unqualified. + +The complete existing cleanup-owner module passed all 28 cases in 554.87s +(`/tmp/submission-cleanup-owner-v4.log/.json`, schema0088, isolated cleanup +complete). This covers retained-source barriers, service revocation, decision +substitution, competing claims, stale takeover, transaction rollback and charge +release, including the updated terminal-unsealed age rule. Add a focused actual +0087-to-0088 retained-row test: create outstanding and confirmed sealed claims +using predecessor SQL guards and real authorization decisions, compare source, +charge, upload, operation and audit facts across upgrade, then replay through +the current owner. This uses no fabricated seal or disabled cleanup guard. + +The first retained-migration probe stopped in predecessor setup: two volatile +clock reads made its five-minute lease exceed the maximum by microseconds. +Use the same statement timestamp for both endpoints, preserving the production +bound. The direct source-substitution probe now uses a well-formed alternative +SHA-256 identity, so its negative assertion cannot rely on malformed input. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 14b932a3f..fc9c137e8 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0087_source_cleanup_candidates" +_CURRENT_HEAD_REVISION = "0088_unsealed_source_cleanup" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -141,6 +141,7 @@ def do_run_migrations(connection: Connection) -> None: ("0084_submission_source_binding",), ("0085_revision_deadline_error",), ("0086_pending_checker_custody",), + ("0087_source_cleanup_candidates",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0088_unsealed_source_cleanup.py b/backend/alembic/versions/0088_unsealed_source_cleanup.py new file mode 100644 index 000000000..894c83205 --- /dev/null +++ b/backend/alembic/versions/0088_unsealed_source_cleanup.py @@ -0,0 +1,129 @@ +"""Admit exact unsealed cleanup targets without synthesizing sealed custody.""" +from alembic import op +from sqlalchemy import text + +revision = "0088_unsealed_source_cleanup" +down_revision = "0087_source_cleanup_candidates" +branch_labels = None +depends_on = None + + +def _definition(name): + return op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_functiondef(CAST(:name AS regprocedure))" + ), {"name": name}).scalar_one() + + +def _replace(body, old, new): + if body.count(old) != 1: + raise RuntimeError("unsealed cleanup predecessor shape changed") + return body.replace(old, new) + + +def upgrade(): + """Retain old source/claim/audit values; broaden only proved cleanup release.""" + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.submission_intake_operations, public.submission_source_charges, " + "public.submission_source_cleanup_claims, public.submission_source_upload_receipts " + "IN ACCESS EXCLUSIVE MODE") + op.execute("ALTER TABLE public.submission_source_cleanup_claims ADD COLUMN observed_source jsonb, " + "ADD COLUMN observed_at timestamptz") + op.execute("ALTER TABLE public.submission_source_cleanup_claims ADD CONSTRAINT " + "ck_submission_source_cleanup_claims_observed_shape CHECK " + "((observed_source is null and observed_at is null) or " + "(jsonb_typeof(observed_source)='object' and observed_at is not null))") + requirement = _definition("public.require_sealed_source_cleanup(public.submission_intake_operations)") + requirement = requirement.replace("require_sealed_source_cleanup", "require_submission_source_cleanup") + requirement = _replace(requirement, + "OR o.accepted_at IS NOT NULL OR o.provider_generation IS NULL OR o.sealed_at IS NULL", + "OR o.accepted_at IS NOT NULL") + requirement = _replace(requirement, + "greatest(o.terminal_at,o.sealed_at)", + "greatest(o.terminal_at,o.sealed_at,(SELECT observed_at FROM public.submission_source_cleanup_claims WHERE operation_id=o.id))") + op.execute(requirement) + op.execute(_TARGET) + for name in ("guard_submission_source_cleanup", "guard_submission_source_charge", "check_submission_source_accounting"): + body = _definition("public." + name + "()") + body = body.replace("require_sealed_source_cleanup", "require_submission_source_cleanup") + if name == "guard_submission_source_cleanup": + start = body.index(" expected:=jsonb_build_object") + end = body.index(" IF NEW.source", start) + body = body[:start] + " expected:=public.submission_source_cleanup_target(o);\n" + body[end:] + body = _replace(body, " IF TG_OP='INSERT' THEN", _OBSERVATION + "\n IF TG_OP='INSERT' THEN") + body = _replace(body, "IF NEW.generation<>1 OR NEW.confirmed_at IS NOT NULL OR NEW.confirmation_decision_id IS NOT NULL THEN", + "IF NEW.generation<>1 OR NEW.confirmed_at IS NOT NULL OR NEW.confirmation_decision_id IS NOT NULL " + "OR NEW.observed_source IS NOT NULL OR NEW.observed_at IS NOT NULL THEN") + elif name == "guard_submission_source_charge": + body = _replace(body, "OLD.state NOT IN ('sealed','released')", "OLD.state NOT IN ('reserved','sealed','released')") + op.execute(body) + op.execute("DROP FUNCTION public.require_sealed_source_cleanup(public.submission_intake_operations)") + authority = _definition("public.source_cleanup_authority_valid(public.submission_source_cleanup_claims,text)") + authority = _replace(authority, + "c.source || jsonb_build_object('schema_version','workstream.sealed_submission_source.v1')", + "CASE WHEN c.observed_source IS NOT NULL THEN jsonb_build_object(" + "'schema_version','workstream.observed_submission_source_cleanup.v1'," + "'source',c.source,'observed_source',c.observed_source) ELSE c.source || " + "jsonb_build_object('schema_version',CASE WHEN c.source->>'kind'='unsealed' " + "THEN 'workstream.unsealed_submission_source.v1' ELSE 'workstream.sealed_submission_source.v1' END) END") + op.execute(authority) + op.execute("ALTER TABLE public.submission_source_charges DROP CONSTRAINT ck_submission_source_charges_charge_shape") + op.execute("ALTER TABLE public.submission_source_charges ADD CONSTRAINT ck_submission_source_charges_charge_shape CHECK " + "((state='reserved' and accounted_bytes=reserved_bytes and sealed_at is null) " + "or (state='sealed' and sealed_at is not null and accounted_bytes>0) " + "or (state='released' and accounted_bytes=0))") + op.drop_index("ix_submission_intake_cleanup_candidates", table_name="submission_intake_operations") + op.create_index("ix_submission_intake_cleanup_candidates", "submission_intake_operations", ["terminal_at", "id"], + postgresql_where=text("state in ('rejected','failed','abandoned','cancelled') and accepted_at is null")) + + +def downgrade(): + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") + + +_TARGET = """ +CREATE FUNCTION public.submission_source_cleanup_target(o public.submission_intake_operations) +RETURNS jsonb LANGUAGE sql STABLE SET search_path=pg_catalog,public,pg_temp AS $$ + SELECT CASE WHEN o.sealed_at IS NOT NULL THEN jsonb_build_object( + 'location',jsonb_build_object('operation_id',o.id::text,'namespace_id',o.namespace_id, + 'namespace_fingerprint',o.namespace_fingerprint,'provider_profile',o.provider_profile), + 'provider_generation',o.provider_generation,'raw_sha256',o.raw_sha256,'raw_byte_count',o.raw_byte_count, + 'sealed_upload_fence',o.sealed_upload_fence,'media_type','application/zip') + ELSE jsonb_build_object( + 'kind','unsealed', + 'location',jsonb_build_object('operation_id',o.id::text,'namespace_id',o.namespace_id, + 'namespace_fingerprint',o.namespace_fingerprint,'provider_profile',o.provider_profile), + 'upload_fence',r.upload_fence,'provider_upload_id',r.provider_upload_id, + 'raw_sha256',o.raw_sha256,'raw_byte_count',o.raw_byte_count) + END FROM (SELECT 1) singleton LEFT JOIN public.submission_source_upload_receipts r ON r.operation_id=o.id +$$ +""" + + +_OBSERVATION = """ + IF TG_OP='UPDATE' AND OLD.observed_source IS NULL AND NEW.observed_source IS NOT NULL THEN + IF OLD.confirmed_at IS NOT NULL OR OLD.lease_expires_at<=clock_timestamp() + OR OLD.source->>'kind' IS DISTINCT FROM 'unsealed' OR o.sealed_at IS NOT NULL + OR o.raw_sha256 IS NULL OR o.raw_byte_count IS NULL + OR (to_jsonb(NEW)-ARRAY['observed_source','observed_at']) IS DISTINCT FROM + (to_jsonb(OLD)-ARRAY['observed_source','observed_at']) + OR NOT public.source_cleanup_authority_valid(OLD,'claim') + OR NOT EXISTS(SELECT 1 FROM public.submission_source_upload_receipts + WHERE operation_id=o.id AND completion_parts IS NOT NULL AND provider_upload_id IS NOT NULL) + OR coalesce(length(NEW.observed_source->>'provider_generation'),0) NOT BETWEEN 1 AND 2048 + OR (o.provider_profile='aws-s3-v1' AND NEW.observed_source->>'provider_generation'='null') + OR NEW.observed_source IS DISTINCT FROM jsonb_build_object( + 'location',OLD.source->'location','provider_generation',NEW.observed_source->>'provider_generation', + 'raw_sha256',o.raw_sha256,'raw_byte_count',o.raw_byte_count, + 'sealed_upload_fence',OLD.source->'upload_fence','media_type','application/zip') THEN + RAISE EXCEPTION 'source cleanup completion observation differs' USING ERRCODE='23514'; + END IF; + NEW.observed_at:=clock_timestamp(); + -- The old claim no longer authorizes deletion. A later aged generation must + -- obtain a fresh decision bound to this exact observed version. + RETURN NEW; + END IF; + IF TG_OP='UPDATE' AND (NEW.observed_source IS DISTINCT FROM OLD.observed_source + OR NEW.observed_at IS DISTINCT FROM OLD.observed_at) THEN + RAISE EXCEPTION 'source cleanup observation is immutable' USING ERRCODE='23514'; + END IF; +""" diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 5a4dfeed7..4b9baefdc 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -1050,13 +1050,13 @@ async def submission_source_cleanup_candidates(sessions, namespace, limit): """Discover candidates under the fixed service through ART ownership.""" from app.adapters.tasks import intake_task_custody_port from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization - from app.modules.artifacts.intake.cleanup import SealedSourceCleanup + from app.modules.artifacts.intake.cleanup import SubmissionSourceCleanupOwner from app.core.identifiers import new_record_id async with sessions.begin() as session: authority = PreparedSubmissionSourceCleanupAuthorization( session, request_id=new_record_id(), correlation_id=new_record_id()) try: - return await SealedSourceCleanup(session, intake_task_custody_port(session), authority).candidates( + return await SubmissionSourceCleanupOwner(session, intake_task_custody_port(session), authority).candidates( namespace, limit=limit) finally: authority.close() @@ -1067,7 +1067,7 @@ async def abandon_expired_submission_foregrounds(sessions, namespace, limit, *, import asyncio from app.adapters.tasks import intake_task_custody_port from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization - from app.modules.artifacts.intake.cleanup import SealedSourceCleanup + from app.modules.artifacts.intake.cleanup import SubmissionSourceCleanupOwner from app.core.identifiers import new_record_id from contextlib import asynccontextmanager @@ -1077,7 +1077,7 @@ async def root(): authority = PreparedSubmissionSourceCleanupAuthorization( session, request_id=new_record_id(), correlation_id=new_record_id()) try: - yield SealedSourceCleanup(session, intake_task_custody_port(session), authority) + yield SubmissionSourceCleanupOwner(session, intake_task_custody_port(session), authority) finally: authority.close() diff --git a/backend/app/adapters/artifacts/local_submission_source.py b/backend/app/adapters/artifacts/local_submission_source.py index 5f1c14d7e..956ba22d3 100644 --- a/backend/app/adapters/artifacts/local_submission_source.py +++ b/backend/app/adapters/artifacts/local_submission_source.py @@ -352,6 +352,50 @@ def parts_absent(self, upload: SubmissionSourceUpload) -> bool: # A missing metadata file is not proof the staging bytes are gone. return False + def delete_unsealed(self, value) -> bool: + """Drain Local writers and retain an abort tombstone before unlinking parts.""" + from datetime import timedelta + from app.modules.artifacts.api.submission_cleanup import UnsealedSourceCleanupInput + if type(value) is not UnsealedSourceCleanupInput or value.intent is None: + raise ArtifactOperationConflictError("unsealed cleanup input is invalid") + with self.locked(value.source.location, create=True) as directory: + if self.exists(directory, "seal.json"): + # Completion may have won before its SQL receipt was recorded. + # Never delete this generation under a partial-upload claim. + return False + stored = None + if self.exists(directory, "upload.json"): + stored = SubmissionSourceUpload.model_validate_json(self.read(directory, "upload.json")) + if stored.intent != value.intent or (value.upload is not None and stored != value.upload): + raise ArtifactOperationConflictError("unsealed cleanup upload differs") + elif value.upload is not None or self.exists(directory, "bundle.zip"): + raise ArtifactIntegrityError("unsealed cleanup provenance is missing") + marker = {"cleanup_source": value.source.model_dump(mode="json")} + if self.exists(directory, "aborted.json"): + existing = json.loads(self.read(directory, "aborted.json")) + if existing != marker and (stored is None or existing != {"provider_upload_id": stored.provider_upload_id}): + raise ArtifactIntegrityError("unsealed cleanup tombstone differs") + else: + self.publish(directory, "aborted.json", marker) + try: + descriptor = os.open("bundle.zip", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + except FileNotFoundError: + return True + try: + info = self.store._assert_private_regular(descriptor) + if stat.S_IMODE(info.st_mode) != 0o600: + raise ArtifactIntegrityError("unsealed cleanup inode is not staging") + if datetime.fromtimestamp(info.st_mtime, UTC) > datetime.now(UTC) - timedelta(hours=2): + return False + current = os.stat("bundle.zip", dir_fd=directory, follow_symlinks=False) + if (current.st_dev, current.st_ino) != (info.st_dev, info.st_ino): + raise ArtifactIntegrityError("unsealed cleanup inode changed") + os.unlink("bundle.zip", dir_fd=directory) + os.fsync(directory) + return not self.exists(directory, "bundle.zip") + finally: + os.close(descriptor) + def delete_sealed(self, source: SealedSubmissionSource, upload: SubmissionSourceUpload) -> None: """Private cleanup primitive; caller must hold committed cleanup authority. diff --git a/backend/app/adapters/artifacts/source_cleanup.py b/backend/app/adapters/artifacts/source_cleanup.py index 3b3007a5b..e5ac627e7 100644 --- a/backend/app/adapters/artifacts/source_cleanup.py +++ b/backend/app/adapters/artifacts/source_cleanup.py @@ -1,7 +1,9 @@ """Private deletion capabilities, kept off the upload/read ArtifactStore port.""" from app.adapters.artifacts.local_submission_source import LocalSubmissionSource from workstream_external_services import ExternalServiceAdapterIdentity -from app.modules.artifacts.api.submission_cleanup import SUBMISSION_SOURCE_CLEANUP_CAPABILITY, SubmissionSourceRemoval +from app.modules.artifacts.api.submission_cleanup import ( + SUBMISSION_SOURCE_CLEANUP_CAPABILITY, SubmissionSourceRemoval, UnsealedSourceCleanupInput, +) class LocalSubmissionSourceCleanup: @@ -30,6 +32,15 @@ async def remove(self, source, upload): absent = await self._store.observe_sealed_source(source) is None return SubmissionSourceRemoval(source, absent, True, parts_absent) + async def remove_unsealed(self, value: UnsealedSourceCleanupInput): + """Use the same operation lock and retained abort marker as Local writers.""" + if value.completion is not None: + completed = await self._store.observe_source_upload(value.completion) + if completed is not None: + return SubmissionSourceRemoval(value.source, False, False, False, completed) + absent = await self._store._source_io(self._source.delete_unsealed, value) + return SubmissionSourceRemoval(value.source, absent, absent, absent) + class S3SubmissionSourceCleanup: """Exact-version capability over a separately credentialed cleanup store. @@ -116,3 +127,24 @@ async def remove(self, source, upload): and versions.get("Versions", []) == [] and versions.get("DeleteMarkers", []) == []) return SubmissionSourceRemoval(source, absent, parts_absent and not handles and versions_absent, parts_absent) + + async def remove_unsealed(self, value: UnsealedSourceCleanupInput): + """Abort known scoped handles; retain charge until remote writes are settled.""" + if value.intent is None: + return SubmissionSourceRemoval(value.source, False, False, False) + if value.completion is not None: + completed = await self._store.observe_source_upload(value.completion) + if completed is not None: + return SubmissionSourceRemoval(value.source, False, False, False, completed) + handles = await self._store.discover_source_uploads(value.intent) + if value.upload is not None and value.upload not in handles: + handles = (*handles, value.upload) + for upload in handles: + await self._store.request_source_abort(upload) + parts_absent = True + for upload in handles: + parts_absent = parts_absent and await self._store.source_upload_parts_absent(upload) + # Unknown begin retries and a racing completion are not settled by one + # LIST/abort response. Exact completed-version reconciliation follows + # through durable cleanup custody; never infer capacity release here. + return SubmissionSourceRemoval(value.source, False, False, parts_absent) diff --git a/backend/app/adapters/artifacts/source_cleanup_worker.py b/backend/app/adapters/artifacts/source_cleanup_worker.py index 534dbbd9b..393ac5758 100644 --- a/backend/app/adapters/artifacts/source_cleanup_worker.py +++ b/backend/app/adapters/artifacts/source_cleanup_worker.py @@ -1,4 +1,4 @@ -"""Bounded worker composition for audited, exact sealed-source reclamation.""" +"""Bounded worker composition for audited submission-source reclamation.""" import asyncio from datetime import timedelta @@ -45,14 +45,14 @@ async def validate_source_cleanup_startup(): await engine.dispose() -async def sweep_sealed_submission_sources(sessions, settings): +async def sweep_submission_sources(sessions, settings): """One finite page; confirmed counts include already-confirmed replay.""" profile, namespace, namespace_claim = _configuration(settings) candidates, confirmed, timed_out, provider, abandoned = (), 0, False, None, 0 try: async with asyncio.timeout(profile.run_seconds): try: - # Reserve at least half the envelope for sealed sources even + # Reserve at least half the envelope for source cleanup even # when expired foreground custody is blocked on a TASK lock. async with asyncio.timeout(profile.run_seconds / 2): abandoned = await abandon_expired_submission_foregrounds( @@ -87,7 +87,7 @@ async def run_source_cleanup_sweep(): """Own DB/provider resources for one Celery process invocation.""" engine = create_async_engine(get_database_url(), pool_pre_ping=True) try: - return await sweep_sealed_submission_sources( + return await sweep_submission_sources( async_sessionmaker(engine, expire_on_commit=False), get_settings()) finally: await engine.dispose() diff --git a/backend/app/modules/artifacts/api/submission_cleanup.py b/backend/app/modules/artifacts/api/submission_cleanup.py index b48e0fd48..e5ab7e600 100644 --- a/backend/app/modules/artifacts/api/submission_cleanup.py +++ b/backend/app/modules/artifacts/api/submission_cleanup.py @@ -6,7 +6,12 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator from workstream_external_services import ExternalServiceAdapter -from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceUpload +from app.core.hashing import canonical_json_hash +from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, SubmissionSourceUpload, SubmissionSourceUploadIntent, + SubmissionSourceCompletion, SubmissionSourceLocation, Sha256, +) SUBMISSION_SOURCE_CLEANUP_CAPABILITY = "submission_source_cleanup" @@ -23,14 +28,85 @@ class SubmissionSourceCleanupAuthorityFacts: phase: Literal["claim", "confirm"] +class UnsealedSubmissionSource(BaseModel): + """Exact unfinished write custody; never a completed-object or read grant.""" + + model_config = ConfigDict(extra="forbid", strict=True, frozen=True) + kind: Literal["unsealed"] = "unsealed" + location: SubmissionSourceLocation + upload_fence: int | None = Field(default=None, ge=1) + provider_upload_id: str | None = Field(default=None, min_length=1, max_length=2048, repr=False) + raw_sha256: Sha256 | None = None + raw_byte_count: int | None = Field(default=None, ge=1, le=MAXIMUM_SUBMISSION_ZIP_BYTES) + + @model_validator(mode="after") + def receipt_shape(self): + if self.upload_fence is None and (self.provider_upload_id is not None or self.raw_sha256 is not None): + raise ValueError("unsealed source requires initiation custody") + if (self.raw_sha256 is None) != (self.raw_byte_count is None): + raise ValueError("unsealed EOF identity must be complete") + if self.raw_sha256 is not None and self.provider_upload_id is None: + raise ValueError("unsealed EOF requires a recorded upload handle") + return self + + def source_sha256(self) -> str: + """Bind the unfinished obligation without inventing a provider generation.""" + return canonical_json_hash({"schema_version": "workstream.unsealed_submission_source.v1", + **self.model_dump(mode="json")}) + + +@dataclass(frozen=True, slots=True) +class UnsealedSourceCleanupInput: + """Provider input recovered under an exact committed cleanup claim.""" + + source: UnsealedSubmissionSource + intent: SubmissionSourceUploadIntent | None + upload: SubmissionSourceUpload | None + completion: SubmissionSourceCompletion | None + + def __post_init__(self): + if self.source.upload_fence is None: + if any(value is not None for value in (self.intent, self.upload, self.completion)): + raise ValueError("uninitiated cleanup has no provider input") + return + if (self.intent is None or self.intent.location != self.source.location + or self.intent.upload_fence != self.source.upload_fence): + raise ValueError("unsealed cleanup intent differs") + if self.source.provider_upload_id is None: + if self.upload is not None: + raise ValueError("unsealed cleanup handle differs") + elif (self.upload is None or self.upload.intent != self.intent + or self.upload.provider_upload_id != self.source.provider_upload_id): + raise ValueError("unsealed cleanup handle differs") + if self.source.raw_sha256 is None: + if self.completion is not None: + raise ValueError("unsealed cleanup EOF differs") + elif (self.completion is None or self.completion.upload != self.upload + or self.completion.raw_sha256 != self.source.raw_sha256 + or self.completion.raw_byte_count != self.source.raw_byte_count): + raise ValueError("unsealed cleanup EOF differs") + + +def cleanup_target_sha256(source, observed_source=None) -> str: + """Bind a later exact version as well as its original unfinished obligation.""" + if observed_source is None: + return source.source_sha256() + return canonical_json_hash({ + "schema_version": "workstream.observed_submission_source_cleanup.v1", + "source": source.model_dump(mode="json"), + "observed_source": observed_source.model_dump(mode="json"), + }) + + @dataclass(frozen=True, slots=True) class SubmissionSourceRemoval: """Trusted provider observations; no field by itself releases a charge.""" - source: SealedSubmissionSource + source: SealedSubmissionSource | UnsealedSubmissionSource object_absent: bool writes_settled: bool parts_absent: bool + observed_source: SealedSubmissionSource | None = None class SubmissionSourceCleanupProvider(ExternalServiceAdapter, Protocol): @@ -40,6 +116,10 @@ async def remove(self, source: SealedSubmissionSource, upload: SubmissionSourceU """Remove exact sealed-source bytes and return independent settlement observations.""" ... + async def remove_unsealed(self, value: UnsealedSourceCleanupInput) -> SubmissionSourceRemoval: + """Reclaim exact unfinished obligations; unresolved writes retain their charge.""" + ... + def close(self) -> None: """Release the separately composed cleanup capability resources.""" ... diff --git a/backend/app/modules/artifacts/intake/capacity.py b/backend/app/modules/artifacts/intake/capacity.py index 27266e472..609c3572f 100644 --- a/backend/app/modules/artifacts/intake/capacity.py +++ b/backend/app/modules/artifacts/intake/capacity.py @@ -90,7 +90,7 @@ async def release_confirmed(self, operation: SubmissionIntakeOperation) -> None: charge = await self._session.scalar(select(SubmissionSourceCharge).where( SubmissionSourceCharge.operation_id == operation.id, ).with_for_update().execution_options(populate_existing=True)) - if claim is None or claim.confirmed_at is None or charge is None or charge.state not in {"sealed", "released"}: + if claim is None or claim.confirmed_at is None or charge is None or charge.state not in {"reserved", "sealed", "released"}: raise SubmissionSourceCapacityConflict("source_cleanup_unconfirmed") charge.state, charge.accounted_bytes = "released", 0 await self._session.flush() diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py index 9bf14f5cd..78a02ca30 100644 --- a/backend/app/modules/artifacts/intake/cleanup.py +++ b/backend/app/modules/artifacts/intake/cleanup.py @@ -1,4 +1,4 @@ -"""Authorized sealed-source cleanup custody; provider I/O stays outside this owner. +"""Authorized submission-source cleanup custody; provider I/O stays outside this owner. The composition root must supply current authority and act only on a committed claim. This owner retains uncertain targets and releases charges only with both exact @@ -10,8 +10,12 @@ from sqlalchemy import func, or_, select, text -from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionSourceUpload -from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts +from app.modules.artifacts.api.submission_intake import ( + SealedSubmissionSource, SubmissionSourceUpload, SubmissionSourceLocation, SubmissionSourceCompletion, +) +from app.modules.artifacts.api.submission_cleanup import ( + SubmissionSourceCleanupAuthorityFacts, UnsealedSubmissionSource, UnsealedSourceCleanupInput, cleanup_target_sha256, +) from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity from app.modules.artifacts.intake.models import ( SubmissionIntakeOperation, SubmissionSourceCharge, SubmissionSourceCleanupClaim, SubmissionSourceUploadReceipt, @@ -24,27 +28,30 @@ @dataclass(frozen=True, slots=True) -class SealedSourceCleanupClaim: +class SourceCleanupClaim: """Exact durable deletion target; a copied value grants no deletion authority.""" claim_id: UUID generation: int - source: SealedSubmissionSource + source: SealedSubmissionSource | UnsealedSubmissionSource lease_expires_at: datetime confirmed: bool + observed_source: SealedSubmissionSource | None = None -def _claim_value(row: SubmissionSourceCleanupClaim) -> SealedSourceCleanupClaim: +def _claim_value(row: SubmissionSourceCleanupClaim) -> SourceCleanupClaim: """Recover typed source facts from persisted canonical JSON.""" import json - return SealedSourceCleanupClaim( + return SourceCleanupClaim( UUID(row.claim_id), row.generation, - SealedSubmissionSource.model_validate_json(json.dumps(row.source)), + (UnsealedSubmissionSource if row.source.get("kind") == "unsealed" else SealedSubmissionSource) + .model_validate_json(json.dumps(row.source)), row.lease_expires_at, row.confirmed_at is not None, + SealedSubmissionSource.model_validate_json(json.dumps(row.observed_source)) if row.observed_source is not None else None, ) -class SealedSourceCleanup: +class SubmissionSourceCleanupOwner: """Flush-only ownership: caller supplies current authority and root commits.""" def __init__(self, session, tasks, authorization): @@ -108,9 +115,9 @@ async def candidates(self, namespace, *, limit: int) -> tuple[UUID, ...]: .where(operation.namespace_id == "primary", operation.namespace_fingerprint == namespace.namespace_fingerprint, operation.state.in_(("rejected", "failed", "abandoned", "cancelled")), - operation.accepted_at.is_(None), operation.provider_generation.is_not(None), - operation.sealed_at.is_not(None), operation.terminal_at <= now - timedelta(hours=2), - operation.sealed_at <= now - timedelta(hours=2), charge.state == "sealed", + operation.accepted_at.is_(None), + func.greatest(operation.terminal_at, operation.sealed_at, claim.observed_at) <= now - timedelta(hours=2), + charge.state.in_(("reserved", "sealed")), claim.confirmed_at.is_(None), or_(claim.operation_id.is_(None), claim.lease_expires_at <= now), ~retained, ~admitted) @@ -121,20 +128,37 @@ async def _locked(self, operation_id): await self._authorization.authorize() operation = await self._intake._lock(operation_id) await self._authorization.revalidate() - await self._session.execute(text( - "SELECT public.require_sealed_source_cleanup(o) " - "FROM public.submission_intake_operations o WHERE id=:id" - ), {"id": operation.id}) row = await self._session.scalar(select(SubmissionSourceCleanupClaim).where( SubmissionSourceCleanupClaim.operation_id == operation.id, ).with_for_update().execution_options(populate_existing=True)) + now = await self._session.scalar(select(func.clock_timestamp())) + if row is not None and row.observed_at is not None and row.observed_at > now - timedelta(hours=2): + raise IntakeCustodyConflict("source_cleanup_recent_completion") + await self._session.execute(text( + "SELECT public.require_submission_source_cleanup(o) " + "FROM public.submission_intake_operations o WHERE id=:id" + ), {"id": operation.id}) return operation, row + async def _target(self, operation): + if operation.sealed_at is not None: + return self._intake._sealed_source(operation) + receipt = await self._session.get(SubmissionSourceUploadReceipt, operation.id) + return UnsealedSubmissionSource( + location=SubmissionSourceLocation(operation_id=UUID(operation.id), namespace_id=operation.namespace_id, + namespace_fingerprint=operation.namespace_fingerprint, provider_profile=operation.provider_profile), + upload_fence=receipt.upload_fence if receipt is not None else None, + provider_upload_id=receipt.provider_upload_id if receipt is not None else None, + raw_sha256=operation.raw_sha256, raw_byte_count=operation.raw_byte_count, + ) + async def _decision(self, operation, claim_id, generation, phase): - source = self._intake._sealed_source(operation) + source = await self._target(operation) + row = await self._session.get(SubmissionSourceCleanupClaim, operation.id) + observed = _claim_value(row).observed_source if row is not None else None facts = SubmissionSourceCleanupAuthorityFacts( operation_id=UUID(operation.id), project_id=UUID(operation.project_id), - task_id=UUID(operation.task_id), source_sha256=source.source_sha256(), + task_id=UUID(operation.task_id), source_sha256=cleanup_target_sha256(source, observed), claim_id=claim_id, claim_generation=generation, phase=phase, ) handle = await self._authorization.prepare(facts=facts, idempotency_key=facts.claim_id) @@ -151,7 +175,7 @@ async def _require_claim_authority(self, operation_id): if valid is not True: raise IntakeCustodyConflict("source_cleanup_authority_unavailable") - async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: timedelta) -> SealedSourceCleanupClaim: + async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: timedelta) -> SourceCleanupClaim: """Claim only a stable eligible source; never resume foreground work.""" if (type(claim_id) is not UUID or claim_id.version != 7 or type(lease_duration) is not timedelta @@ -177,7 +201,7 @@ async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: tim else: row = SubmissionSourceCleanupClaim( operation_id=operation.id, claim_id=str(claim_id), generation=1, - source=self._intake._sealed_source(operation).model_dump(mode="json"), + source=(await self._target(operation)).model_dump(mode="json"), claimed_at=now, lease_expires_at=now + lease_duration, ) self._session.add(row) @@ -186,14 +210,32 @@ async def claim(self, operation_id: UUID, claim_id: UUID, *, lease_duration: tim await self._session.refresh(row) return _claim_value(row) - async def confirm(self, claim: SealedSourceCleanupClaim, *, object_absent: bool, + async def record_completion_observation(self, claim: SourceCleanupClaim, source: SealedSubmissionSource) -> None: + """Retain late completion without granting deletion under the old claim.""" + source = SealedSubmissionSource.model_validate(source) + operation, row = await self._locked(claim.source.location.operation_id) + now = await self._session.scalar(select(func.clock_timestamp())) + if (not isinstance(claim.source, UnsealedSubmissionSource) or row is None + or row.claim_id != str(claim.claim_id) or row.generation != claim.generation + or row.confirmed_at is not None or row.lease_expires_at <= now + or row.source != claim.source.model_dump(mode="json") or row.observed_source is not None + or source.location != claim.source.location or source.raw_sha256 != operation.raw_sha256 + or source.raw_byte_count != operation.raw_byte_count + or source.sealed_upload_fence != claim.source.upload_fence): + raise IntakeCustodyConflict("source_cleanup_observation_mismatch") + await self._require_claim_authority(operation.id) + row.observed_source, row.observed_at = source.model_dump(mode="json"), now + await self._session.flush() + + async def confirm(self, claim: SourceCleanupClaim, *, object_absent: bool, writes_settled: bool, parts_absent: bool) -> None: """Commit exact absence and charge release together, never on an ACK.""" if object_absent is not True or writes_settled is not True or parts_absent is not True: raise IntakeCustodyConflict("source_cleanup_unresolved") operation, row = await self._locked(claim.source.location.operation_id) if (row is None or row.claim_id != str(claim.claim_id) or row.generation != claim.generation - or row.source != claim.source.model_dump(mode="json")): + or row.source != claim.source.model_dump(mode="json") + or row.observed_source != (claim.observed_source.model_dump(mode="json") if claim.observed_source is not None else None)): raise IntakeCustodyConflict("source_cleanup_stale") if row.confirmed_at is not None: return @@ -206,7 +248,7 @@ async def confirm(self, claim: SealedSourceCleanupClaim, *, object_absent: bool, await self._session.flush() await SubmissionSourceCapacity(self._session).release_confirmed(operation) - async def upload_for_claim(self, claim: SealedSourceCleanupClaim) -> SubmissionSourceUpload: + async def upload_for_claim(self, claim: SourceCleanupClaim) -> SubmissionSourceUpload | UnsealedSourceCleanupInput: """Recover the exact upload under the same live audited deletion claim.""" operation, row = await self._locked(claim.source.location.operation_id) now = await self._session.scalar(select(func.clock_timestamp())) @@ -216,6 +258,17 @@ async def upload_for_claim(self, claim: SealedSourceCleanupClaim) -> SubmissionS raise IntakeCustodyConflict("source_cleanup_stale") await self._require_claim_authority(operation.id) receipt = await self._session.get(SubmissionSourceUploadReceipt, operation.id) + if isinstance(claim.source, UnsealedSubmissionSource): + intent = await self._intake._upload_intent(operation, receipt) if receipt is not None else None + upload = (SubmissionSourceUpload(intent=intent, provider_upload_id=receipt.provider_upload_id) + if receipt is not None and receipt.provider_upload_id is not None else None) + completion = None + if receipt is not None and receipt.completion_parts is not None: + import json + completion = SubmissionSourceCompletion.model_validate_json(json.dumps({ + "upload": upload.model_dump(mode="json"), "raw_sha256": operation.raw_sha256, + "raw_byte_count": operation.raw_byte_count, "parts": receipt.completion_parts})) + return UnsealedSourceCleanupInput(claim.source, intent, upload, completion) if receipt is None or receipt.provider_upload_id is None or receipt.completion_parts is None: raise IntakeCustodyConflict("source_cleanup_unresolved") return SubmissionSourceUpload( diff --git a/backend/app/modules/artifacts/intake/cleanup_execution.py b/backend/app/modules/artifacts/intake/cleanup_execution.py index ab8f97204..52383f703 100644 --- a/backend/app/modules/artifacts/intake/cleanup_execution.py +++ b/backend/app/modules/artifacts/intake/cleanup_execution.py @@ -5,9 +5,9 @@ from app.core.cancellation import await_completion_preserving_cancellation from app.modules.artifacts.api.submission_cleanup import ( - SubmissionSourceCleanupProvider, SubmissionSourceRemoval, + SubmissionSourceCleanupProvider, SubmissionSourceRemoval, UnsealedSubmissionSource, ) -from app.modules.artifacts.intake.cleanup import MAXIMUM_CLEANUP_LEASE, SealedSourceCleanup +from app.modules.artifacts.intake.cleanup import MAXIMUM_CLEANUP_LEASE, SubmissionSourceCleanupOwner from app.modules.artifacts.intake.repository import IntakeCustodyConflict @@ -27,7 +27,7 @@ async def _root(self): authority = self._authorization(session) try: await session.begin() - yield SealedSourceCleanup(session, self._tasks(session), authority) + yield SubmissionSourceCleanupOwner(session, self._tasks(session), authority) # If acknowledgement is lost, propagate uncertainty and retain the # same claim ID for replay. Never proceed to deletion on that path. await await_completion_preserving_cancellation(session.commit()) @@ -41,9 +41,23 @@ async def run(self, operation_id: UUID, claim_id: UUID) -> None: upload = None if claim.confirmed else await owner.upload_for_claim(claim) if claim.confirmed: return - observed = await self._provider.remove(claim.source, upload) - if type(observed) is not SubmissionSourceRemoval or observed.source != claim.source: + expected = claim.observed_source or claim.source + if claim.observed_source is not None: + observed = await self._provider.remove(claim.observed_source, upload.upload) + elif isinstance(claim.source, UnsealedSubmissionSource): + # No initiation receipt means no provider call was ever authorized. + observed = (SubmissionSourceRemoval(claim.source, True, True, True) + if claim.source.upload_fence is None else await self._provider.remove_unsealed(upload)) + else: + observed = await self._provider.remove(claim.source, upload) + if type(observed) is not SubmissionSourceRemoval or observed.source != expected: raise IntakeCustodyConflict("source_cleanup_observation_mismatch") + if observed.observed_source is not None: + if claim.observed_source is not None or not isinstance(claim.source, UnsealedSubmissionSource): + raise IntakeCustodyConflict("source_cleanup_observation_mismatch") + async with self._root() as owner: + await owner.record_completion_observation(claim, observed.observed_source) + raise IntakeCustodyConflict("source_cleanup_recent_completion") async with self._root() as owner: await owner.confirm(claim, object_absent=observed.object_absent, writes_settled=observed.writes_settled, diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py index d459197ad..40ffe09aa 100644 --- a/backend/app/modules/artifacts/intake/models.py +++ b/backend/app/modules/artifacts/intake/models.py @@ -59,7 +59,7 @@ class SubmissionIntakeOperation(Base): Index("uq_submission_intake_active_task", "task_id", unique=True, postgresql_where=text("state in ('receiving','pre_checking','finalization_pending')")), Index("ix_submission_intake_cleanup_candidates", "terminal_at", "id", postgresql_where=text("state in ('rejected','failed','abandoned','cancelled') " - "and accepted_at is null and sealed_at is not null")), + "and accepted_at is null")), Index("ix_submission_intake_expiry", "lease_expires_at", "id", postgresql_where=text("state in ('receiving','pre_checking')")), ) @@ -153,7 +153,7 @@ class SubmissionSourceCharge(Base): CheckConstraint("state in ('reserved','sealed','released')", name="charge_state"), CheckConstraint("(state='reserved' and accounted_bytes=reserved_bytes and sealed_at is null) " "or (state='sealed' and sealed_at is not null and accounted_bytes>0) " - "or (state='released' and sealed_at is not null and accounted_bytes=0)", name="charge_shape"), + "or (state='released' and accounted_bytes=0)", name="charge_shape"), ) operation_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True) @@ -175,6 +175,8 @@ class SubmissionSourceCleanupClaim(Base): name="fk_source_cleanup_operation"), CheckConstraint("generation>0 and lease_expires_at>claimed_at and lease_expires_at<=claimed_at+interval '300 seconds'", name="claim_bounds"), CheckConstraint("jsonb_typeof(source)='object'", name="source_shape"), + CheckConstraint("(observed_source is null and observed_at is null) or " + "(jsonb_typeof(observed_source)='object' and observed_at is not null)", name="observed_shape"), CheckConstraint("(get_byte(uuid_send(claim_id),6)>>4)=7 and (get_byte(uuid_send(claim_id),8)&192)=128", name="claim_uuid7"), Index("ix_source_cleanup_pending", "lease_expires_at", postgresql_where=text("confirmed_at is null")), @@ -186,6 +188,8 @@ class SubmissionSourceCleanupClaim(Base): source: Mapped[dict] = mapped_column(JSONB) claimed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) lease_expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + observed_source: Mapped[dict | None] = mapped_column(JSONB(none_as_null=True)) + observed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) confirmed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) claim_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) confirmation_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 1b7acb33e..f1fbafec4 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -56,6 +56,7 @@ class TestLane: "tests/artifacts/test_submission_intake_custody.py", "tests/artifacts/test_submission_source_cleanup.py", "tests/artifacts/test_source_cleanup_worker.py", + "tests/artifacts/test_unsealed_source_cleanup.py", "tests/artifacts/test_source_cleanup_topology.py", "tests/artifacts/test_submission_pre_source.py", "tests/artifacts/test_submission_intake_admission.py", @@ -191,6 +192,7 @@ class TestLane: "tests/migrations/test_task_queue_authority.py", "tests/migrations/test_claim_starts_work.py", "tests/migrations/test_source_pre_cutover.py", + "tests/migrations/test_unsealed_source_cleanup.py", "tests/migrations/test_compensation_unit_create_migration.py", "tests/migrations/test_task_read_authority.py", "tests/migrations/test_task_context_authority.py", diff --git a/backend/tests/artifacts/test_source_cleanup_worker.py b/backend/tests/artifacts/test_source_cleanup_worker.py index e4b8afe0c..2ef8e17bf 100644 --- a/backend/tests/artifacts/test_source_cleanup_worker.py +++ b/backend/tests/artifacts/test_source_cleanup_worker.py @@ -67,14 +67,14 @@ async def state(intake): async def test_sweep_reclaims_real_source_once_and_leaves_live_pre_input(intake): operation, source = await sealed_local_source(intake) settings = settings_for(intake) - assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["candidates"] == 0 + assert (await composition.sweep_submission_sources(intake.factory, settings))["candidates"] == 0 await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) live, protected = await sealed_local_source(intake, terminal=False) - result = await composition.sweep_sealed_submission_sources(intake.factory, settings) + result = await composition.sweep_submission_sources(intake.factory, settings) assert result == {"candidates": 1, "confirmed": 1, "deferred": 0, "timed_out": False, "abandoned": 0} after = await state(intake) for _ in range(2): - assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["candidates"] == 0 + assert (await composition.sweep_submission_sources(intake.factory, settings))["candidates"] == 0 assert await state(intake) == after store = initialize_local_store(root=intake.durable_root) try: @@ -106,7 +106,7 @@ async def uncertain_remove(self, candidate, upload): with monkeypatch.context() as patch: from app.adapters.artifacts.source_cleanup import LocalSubmissionSourceCleanup patch.setattr(LocalSubmissionSourceCleanup, "remove", uncertain_remove) - first = await composition.sweep_sealed_submission_sources(intake.factory, settings) + first = await composition.sweep_submission_sources(intake.factory, settings) assert first["deferred"] == 1 and first["confirmed"] == 0 async with intake.factory() as session: assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), @@ -115,7 +115,7 @@ async def uncertain_remove(self, candidate, upload): "FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation}) assert remaining is not None, "uncertain removal must retain a committed cleanup claim" await asyncio.sleep(max(0, float(remaining)) + 0.05) - assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["confirmed"] == 1 + assert (await composition.sweep_submission_sources(intake.factory, settings))["confirmed"] == 1 async with intake.factory() as session: assert await session.scalar(text("SELECT generation FROM submission_source_cleanup_claims WHERE operation_id=:id"), {"id": operation}) == 2 @@ -140,14 +140,14 @@ def forbidden(**kwargs): from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError from app.modules.authorization.runtime import AuthorizationDenied, PreparedAuthorizationUnsupported with pytest.raises((IntakeCustodyConflict, ArtifactAuthorityDeniedError, AuthorizationDenied, PreparedAuthorizationUnsupported)): - await composition.sweep_sealed_submission_sources(intake.factory, settings) + await composition.sweep_submission_sources(intake.factory, settings) assert await state(intake) == before async def test_concurrent_sweeps_release_charge_only_once(intake): operation, _ = await sealed_local_source(intake) await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) - results = await asyncio.gather(*(composition.sweep_sealed_submission_sources( + results = await asyncio.gather(*(composition.sweep_submission_sources( intake.factory, settings_for(intake)) for _ in range(2))) # Both pages may discover the source before either confirms; the second # execution may then observe an already-confirmed claim. @@ -170,13 +170,13 @@ async def test_sweep_fences_expired_foreground_without_releasing_source_charge(i def forbidden(**kwargs): pytest.fail("foreground abandonment constructed deletion capability") monkeypatch.setattr(composition, "create_submission_source_cleanup_provider", forbidden) - assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["abandoned"] == 0 + assert (await composition.sweep_submission_sources(intake.factory, settings))["abandoned"] == 0 async with intake.factory() as session: lease = await session.scalar(text("SELECT lease_id FROM submission_intake_operations WHERE id=:id"), {"id": operation}) charged = await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": operation}) await cleanup_fixtures.age_fixture(intake, operation, preserve_upload_deadline=True) - result = await composition.sweep_sealed_submission_sources(intake.factory, settings) + result = await composition.sweep_submission_sources(intake.factory, settings) assert result["abandoned"] == 1 and result["candidates"] == 0 async with intake.factory() as session: row = (await session.execute(text("SELECT state,lease_generation,failure_code FROM submission_intake_operations WHERE id=:id"), @@ -192,7 +192,7 @@ def forbidden(**kwargs): with pytest.raises(IntakeCustodyConflict, match="owner_stale"): async with intake.factory.begin() as session: await repository(session).heartbeat(operation, UUID(str(lease)), 1, lease_duration=timedelta(seconds=30)) - assert (await composition.sweep_sealed_submission_sources(intake.factory, settings))["abandoned"] == 0 + assert (await composition.sweep_submission_sources(intake.factory, settings))["abandoned"] == 0 async with intake.factory() as session: assert str(await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": intake.task})) == replacement_id @@ -221,12 +221,12 @@ async def test_busy_expired_task_defers_then_recovers_on_next_sweep(intake): async with intake.factory.begin() as blocker: await blocker.execute(text("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE"), {"id": other.task}) async with asyncio.timeout(40): - result = await composition.sweep_sealed_submission_sources(intake.factory, bounded) + result = await composition.sweep_submission_sources(intake.factory, bounded) assert result["abandoned"] == 0 and result["timed_out"] is True assert result["confirmed"] == 1 assert await blocker.scalar(text("SELECT state FROM submission_intake_operations WHERE id=:id"), {"id": operation}) == "receiving" - result = await composition.sweep_sealed_submission_sources(intake.factory, settings_for(intake)) + result = await composition.sweep_submission_sources(intake.factory, settings_for(intake)) assert result["abandoned"] == 1 and result["confirmed"] == 0 @@ -251,7 +251,7 @@ async def observe_authorization(self): try: async with intake.factory.begin() as blocker: await blocker.execute(text("SELECT id FROM workstream_tasks WHERE id=:id FOR UPDATE"), {"id": intake.task}) - recovery = asyncio.create_task(composition.sweep_sealed_submission_sources(intake.factory, settings_for(intake))) + recovery = asyncio.create_task(composition.sweep_submission_sources(intake.factory, settings_for(intake))) await asyncio.wait_for(authorized.wait(), timeout=10) await service_link_state(intake.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP, active=False) before = await state(intake) diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py index 13a086247..55bde9edb 100644 --- a/backend/tests/artifacts/test_submission_intake_admission.py +++ b/backend/tests/artifacts/test_submission_intake_admission.py @@ -48,7 +48,7 @@ def forbidden(**kwargs): pytest.fail("stalled accepted source reached deletion capability") monkeypatch.setattr(source_cleanup_worker, "create_submission_source_cleanup_provider", forbidden) for _ in range(2): - assert (await source_cleanup_worker.sweep_sealed_submission_sources(f.factory, settings))["candidates"] == 0 + assert (await source_cleanup_worker.sweep_submission_sources(f.factory, settings))["candidates"] == 0 with pytest.raises(DBAPIError, match="cleanup is protected"): async with f.factory.begin() as session: await owner(session).claim( diff --git a/backend/tests/artifacts/test_submission_source_cleanup.py b/backend/tests/artifacts/test_submission_source_cleanup.py index 2dd824f29..2afc9b727 100644 --- a/backend/tests/artifacts/test_submission_source_cleanup.py +++ b/backend/tests/artifacts/test_submission_source_cleanup.py @@ -10,7 +10,7 @@ from app.adapters.tasks import intake_task_custody_port from app.core.identifiers import new_record_id -from app.modules.artifacts.intake.cleanup import SealedSourceCleanup +from app.modules.artifacts.intake.cleanup import SubmissionSourceCleanupOwner from app.modules.artifacts.intake.repository import IntakeCustodyConflict from tests.artifacts.test_submission_intake_custody import ( SHA, reserve, record_eof, repository, @@ -30,7 +30,7 @@ async def provision_cleanup_identity(intake): def owner(session): """Use the same TASK custody adapter as foreground and finalization.""" from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization - return SealedSourceCleanup(session, intake_task_custody_port(session), + return SubmissionSourceCleanupOwner(session, intake_task_custody_port(session), PreparedSubmissionSourceCleanupAuthorization(session, request_id=new_record_id(), correlation_id=new_record_id())) @@ -156,11 +156,14 @@ async def test_cleanup_rejects_live_input_and_serializes_competing_claims(intake await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5)) async with intake.factory.begin() as session: await repository(session).terminalize(operation, UUID(row.lease_id), 1, state="failed", failure_code="upload_failed") - # Unsealed terminal input cannot enter the sealed cleanup/release path. - await age_fixture(intake, operation) + # Terminal input is still protected until the minimum cleanup age. with pytest.raises(DBAPIError, match="cleanup is protected"): async with intake.factory.begin() as session: await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5)) + await age_fixture(intake, operation) + async with intake.factory.begin() as session: + unsealed = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5)) + assert unsealed.source.kind == "unsealed" operation = await terminal_source(intake) await age_fixture(intake, operation) diff --git a/backend/tests/artifacts/test_unsealed_source_cleanup.py b/backend/tests/artifacts/test_unsealed_source_cleanup.py new file mode 100644 index 000000000..b78a6c69e --- /dev/null +++ b/backend/tests/artifacts/test_unsealed_source_cleanup.py @@ -0,0 +1,176 @@ +"""Real unsealed charge release, Local tombstones and uncertain completion retention.""" +import os +import time +import json +from uuid import UUID + +import pytest +from sqlalchemy import text +from sqlalchemy.exc import DBAPIError + +from app.adapters.artifacts import source_cleanup_worker as composition +from app.interfaces.artifacts import ArtifactPreconditionFailedError +from tests.artifacts.test_source_cleanup_worker import settings_for +from tests.artifacts.test_submission_intake_custody import repository, reserve +from tests.artifacts.test_submission_source_cleanup import ( + intake as intake, capacity_limits as capacity_limits, + provision_cleanup_identity as provision_cleanup_identity, age_fixture, +) +from tests.test_local_artifact_store import initialize_local_store, local_source_completion + + +async def unfinished(intake, phase, *, old_bytes=True): + store = initialize_local_store(root=intake.durable_root) + upload = completion = source = intent = None + try: + async with intake.factory.begin() as session: + row = await reserve(intake, session, with_upload=False) + operation, lease = UUID(row.id), UUID(row.lease_id) + if phase != "no_intent": + intent = await repository(session).prepare_upload( + operation, lease, 1, part_bytes=5 * 1024**2, idle_timeout_seconds=20.0) + if intent is not None: + upload = await store.begin_source_upload(intent) + if phase != "begin_unknown": + async with intake.factory.begin() as session: + await repository(session).record_upload(operation, lease, 1, upload=upload) + if phase == "partial": + await store.upload_source_part(upload, 1, b"unfinished bytes") + if phase in {"eof", "completed_unknown"}: + completion = await local_source_completion(store, upload, b"unaccepted source bytes") + async with intake.factory.begin() as session: + await repository(session).record_eof(operation, lease, 1, completion=completion) + if phase == "completed_unknown": + source = await store.complete_source_upload(completion) + async with intake.factory.begin() as session: + await repository(session).terminalize(operation, lease, 1, state="failed", failure_code="upload_interrupted") + await age_fixture(intake, operation, preserve_upload_deadline=True) + path = intake.durable_root / "objects" / "submission-source" / "v1" / str(operation) / "bundle.zip" + if path.exists() and old_bytes: + # Prepare historical provider activity alongside historical SQL ages. + past = time.time() - 3 * 3600 + os.utime(path, (past, past)) + return operation, intent, upload, completion, source, path + finally: + store.close() + + +@pytest.mark.parametrize("phase", ["no_intent", "begin_unknown", "handle", "partial", "eof"]) +async def test_unsealed_cleanup_releases_reserved_bytes_without_a_seal(intake, phase): + operation, intent, upload, completion, _, path = await unfinished(intake, phase) + result = await composition.sweep_submission_sources(intake.factory, settings_for(intake)) + assert result["confirmed"] == 1 and not path.exists() + async with intake.factory() as session: + row = (await session.execute(text("SELECT state,accounted_bytes,sealed_at FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation})).one() + assert tuple(row) == ("released", 0, None) + assert await session.scalar(text("SELECT provider_generation FROM submission_intake_operations WHERE id=:id"), + {"id": operation}) is None + target = await session.scalar(text("SELECT source FROM submission_source_cleanup_claims WHERE operation_id=:id"), + {"id": operation}) + assert target["kind"] == "unsealed" + assert (await composition.sweep_submission_sources(intake.factory, settings_for(intake)))["candidates"] == 0 + if intent is not None: + store = initialize_local_store(root=intake.durable_root) + try: + with pytest.raises(ArtifactPreconditionFailedError): + await store.begin_source_upload(intent) + with pytest.raises(ArtifactPreconditionFailedError): + await store.upload_source_part(upload, 1, b"late") + if completion is not None: + with pytest.raises(ArtifactPreconditionFailedError): + await store.complete_source_upload(completion) + finally: + store.close() + + +@pytest.mark.parametrize("phase", ["partial", "completed_unknown"]) +async def test_recent_parts_and_unrecorded_completed_version_remain_charged(intake, phase): + operation, _, _, _, source, path = await unfinished(intake, phase, old_bytes=False) + result = await composition.sweep_submission_sources(intake.factory, settings_for(intake)) + assert result["confirmed"] == 0 and result["deferred"] == 1 + assert path.exists() + async with intake.factory() as session: + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation}) > 0 + assert await session.scalar(text("SELECT confirmed_at FROM submission_source_cleanup_claims WHERE operation_id=:id"), + {"id": operation}) is None + if source is not None: + store = initialize_local_store(root=intake.durable_root) + try: + assert await store.observe_sealed_source(source) is not None + finally: + store.close() + + +async def test_late_completion_requires_new_age_and_version_bound_claim(intake): + from datetime import timedelta + from app.core.identifiers import new_record_id + from app.modules.artifacts.intake.repository import IntakeCustodyConflict + from tests.artifacts.test_submission_source_cleanup import owner + operation, _, _, _, source, path = await unfinished(intake, "completed_unknown", old_bytes=False) + first = await composition.sweep_submission_sources(intake.factory, settings_for(intake)) + assert first["deferred"] == 1 and path.exists() + async with intake.factory() as session: + assert await session.scalar(text("SELECT observed_source FROM submission_source_cleanup_claims WHERE operation_id=:id"), + {"id": operation}) == source.model_dump(mode="json") + assert await session.scalar(text("SELECT public.source_cleanup_authority_valid(c,'claim') " + "FROM submission_source_cleanup_claims c WHERE operation_id=:id"), {"id": operation}) is False + with pytest.raises(IntakeCustodyConflict, match="recent_completion"): + async with intake.factory.begin() as session: + await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(seconds=30)) + assert (await composition.sweep_submission_sources(intake.factory, settings_for(intake)))["candidates"] == 0 + assert intake.engine.url.database.startswith("workstream_test_") + async with intake.engine.begin() as connection: + # Only prepare historical observation/lease timestamps; target and + # authority values remain untouched, and the guard is restored here. + await connection.execute(text("ALTER TABLE submission_source_cleanup_claims DISABLE TRIGGER submission_source_cleanup_guard")) + await connection.execute(text("UPDATE submission_source_cleanup_claims SET observed_at=observed_at-interval '3 hours', " + "claimed_at=claimed_at-interval '3 hours',lease_expires_at=lease_expires_at-interval '3 hours' WHERE operation_id=:id"), + {"id": operation}) + await connection.execute(text("SET CONSTRAINTS ALL IMMEDIATE")) + await connection.execute(text("ALTER TABLE submission_source_cleanup_claims ENABLE TRIGGER submission_source_cleanup_guard")) + assert (await composition.sweep_submission_sources(intake.factory, settings_for(intake)))["confirmed"] == 1 + assert not path.exists() + async with intake.factory() as session: + assert await session.scalar(text("SELECT generation FROM submission_source_cleanup_claims WHERE operation_id=:id"), + {"id": operation}) == 2 + assert await session.scalar(text("SELECT public.source_cleanup_authority_valid(c,'confirm') " + "FROM submission_source_cleanup_claims c WHERE operation_id=:id"), {"id": operation}) is True + assert (await session.execute(text("SELECT state,accounted_bytes,sealed_at FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation})).one() == ("released", 0, None) + + +async def test_completion_observation_rejects_substituted_source_and_old_claim(intake): + from datetime import timedelta + from app.core.identifiers import new_record_id + from app.modules.artifacts.intake.repository import IntakeCustodyConflict + from tests.artifacts.test_submission_source_cleanup import owner + + operation, _, _, _, source, path = await unfinished(intake, "completed_unknown") + async with intake.factory.begin() as session: + claim = await owner(session).claim(operation, new_record_id(), lease_duration=timedelta(minutes=5)) + original = source.model_dump(mode="json") + substitutions = [ + {**original, "location": {**original["location"], "operation_id": str(new_record_id())}}, + {**original, "raw_sha256": "sha256:" + "0" * 64}, + {**original, "sealed_upload_fence": original["sealed_upload_fence"] + 1}, + ] + for substituted in substitutions: + # Bypass Python validation to exercise the persisted authority boundary. + with pytest.raises(DBAPIError, match="completion observation differs"): + async with intake.factory.begin() as session: + await session.execute(text("UPDATE submission_source_cleanup_claims " + "SET observed_source=CAST(:source AS jsonb),observed_at=clock_timestamp() " + "WHERE operation_id=:id"), {"id": operation, "source": json.dumps(substituted)}) + async with intake.factory.begin() as session: + await owner(session).record_completion_observation(claim, source) + with pytest.raises(IntakeCustodyConflict, match="recent_completion"): + async with intake.factory.begin() as session: + await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True) + async with intake.factory() as session: + assert await session.scalar(text("SELECT observed_source FROM submission_source_cleanup_claims WHERE operation_id=:id"), + {"id": operation}) == original + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation}) > 0 + assert path.exists() diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 7cfcc910b..f319eb268 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "094801f2d9fab469983e8b49ca3a0b260ded61dacd7e823380626637e440be25" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "998744d3ca52bd4e13b463695f5ac4c05e24b07fdfa8f985b4816a14a21b210b" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/migrations/test_unsealed_source_cleanup.py b/backend/tests/migrations/test_unsealed_source_cleanup.py new file mode 100644 index 000000000..1db5dd66c --- /dev/null +++ b/backend/tests/migrations/test_unsealed_source_cleanup.py @@ -0,0 +1,94 @@ +"""Upgrade real predecessor cleanup claims without rewriting their authority.""" +import asyncio +from datetime import timedelta + +import pytest +from alembic import command +from sqlalchemy import text + +from app.core.identifiers import new_record_id +from app.db import session as db_session +from app.modules.actors.api import ServiceIdentity +from app.modules.artifacts.intake.models import SubmissionIntakeOperation +from tests.artifacts.test_submission_intake_custody import intake as intake, capacity_limits as capacity_limits, repository +from tests.artifacts.test_submission_source_cleanup import age_fixture, cleanup_decision, owner, terminal_source +from tests.checkers.execution.support import provision_post_submit_service +from tests.conftest import _drop_test_database_schema +from tests.migration_fixtures import _config, current_schema_revision + +pytestmark = pytest.mark.postgres_schema_contract + + +@pytest.fixture(autouse=True) +async def predecessor_schema(isolated_database_env, migration_lock): + """Build the actual predecessor before the ordinary intake fixture runs.""" + with migration_lock(): + await db_session.dispose_engine() + await _drop_test_database_schema(isolated_database_env) + try: + await asyncio.to_thread(command.upgrade, _config(), "0087_source_cleanup_candidates") + yield + finally: + await db_session.dispose_engine() + await _drop_test_database_schema(isolated_database_env) + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + + +async def retained_rows(factory, *, upgraded=False): + """Compare every retained fact in the owners touched by this migration.""" + tables = ( + "submission_intake_operations", "submission_source_upload_receipts", + "submission_source_charges", "submission_source_cleanup_claims", "audit_events", + ) + async with factory() as session: + result = {} + for table in tables: + value = "to_jsonb(r)" + if upgraded and table == "submission_source_cleanup_claims": + assert await session.scalar(text("SELECT count(*) FROM submission_source_cleanup_claims " + "WHERE observed_source IS NOT NULL OR observed_at IS NOT NULL")) == 0 + value += "-ARRAY['observed_source','observed_at']" + result[table] = await session.scalar(text( + f"SELECT jsonb_agg({value} ORDER BY to_jsonb(r)::text) FROM {table} r")) + return result + + +async def test_upgrade_preserves_sealed_claims_charges_and_audit_decisions(intake): + await provision_post_submit_service(intake.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP) + claims = [] + for confirmed in (False, True): + operation = await terminal_source(intake) + await age_fixture(intake, operation) + claim_id = new_record_id() + async with intake.factory.begin() as session: + row = await session.get(SubmissionIntakeOperation, str(operation)) + source = repository(session)._sealed_source(row).model_dump_json() + decision = await cleanup_decision(session, operation, claim_id) + # Use actual 0087 SQL guards and real authority decisions. The new + # Python cleanup owner cannot run against this predecessor schema. + await session.execute(text("INSERT INTO submission_source_cleanup_claims " + "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at,claim_decision_id) " + "VALUES (:id,:claim,1,CAST(:source AS jsonb),statement_timestamp()," + "statement_timestamp()+interval '5 minutes',:decision)"), + {"id": operation, "claim": claim_id, "source": source, "decision": decision}) + if confirmed: + confirmation = await cleanup_decision(session, operation, claim_id, phase="confirm") + await session.execute(text("UPDATE submission_source_cleanup_claims " + "SET confirmed_at=clock_timestamp(),confirmation_decision_id=:decision WHERE operation_id=:id"), + {"id": operation, "decision": confirmation}) + await session.execute(text("UPDATE submission_source_charges SET state='released',accounted_bytes=0 " + "WHERE operation_id=:id"), {"id": operation}) + claims.append((operation, claim_id, confirmed)) + before = await retained_rows(intake.factory) + await intake.engine.dispose() + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + assert await retained_rows(intake.factory, upgraded=True) == before + for operation, claim_id, confirmed in claims: + async with intake.factory.begin() as session: + claim = await owner(session).claim(operation, claim_id, lease_duration=timedelta(minutes=5)) + assert claim.confirmed is confirmed + assert claim.observed_source is None + await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True) + async with intake.factory() as session: + assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), + {"id": operation}) == 0 diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py index 95efe1d90..0952fda2c 100644 --- a/backend/tests/test_s3_artifact_store.py +++ b/backend/tests/test_s3_artifact_store.py @@ -1274,6 +1274,40 @@ async def test_source_cleanup_keeps_source_when_another_upload_is_unresolved(sou cleanup_store.close() +@pytest.mark.asyncio +@pytest.mark.parametrize("completed", [False, True]) +async def test_unsealed_cleanup_observes_completion_without_premature_release(source_store, completed): + from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup + from app.modules.artifacts.api.submission_cleanup import UnsealedSubmissionSource, UnsealedSourceCleanupInput + + completion = await source_completion(source_store, b"unrecorded-completion") + source = await source_store.complete_source_upload(completion) if completed else None + upload = completion.upload + value = UnsealedSourceCleanupInput( + source=UnsealedSubmissionSource( + location=upload.intent.location, upload_fence=upload.intent.upload_fence, + provider_upload_id=upload.provider_upload_id, + raw_sha256=completion.raw_sha256, raw_byte_count=completion.raw_byte_count, + ), intent=upload.intent, upload=upload, completion=completion, + ) + # Real MinIO protocol behavior; production credential qualification is separate. + cleanup_store = initialize_minio_store(private_prefix=source_store._private_prefix) + try: + result = await S3SubmissionSourceCleanup(cleanup_store).remove_unsealed(value) + assert result.source == value.source + assert result.object_absent is result.writes_settled is False + assert result.observed_source == source + if completed: + retained = await source_store.observe_sealed_source(source) + assert retained is not None + assert retained.provider_generation == source.provider_generation + else: + assert result.parts_absent is True + assert await source_store.source_upload_parts_absent(upload) is True + finally: + cleanup_store.close() + + @pytest.mark.asyncio @pytest.mark.parametrize("code,status,bucket_error", [ ("NoSuchBucket", 404, None), From 89ed11f584909265301a4afc91d149f8d275a173 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:13:28 +0100 Subject: [PATCH 226/513] Prove cleanup fences delayed upload initiation --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 20 +++++++++++++++++++ .../artifacts/test_unsealed_source_cleanup.py | 15 ++++++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index cdc7f3a27..15eca3562 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8047,3 +8047,23 @@ clock reads made its five-minute lease exceed the maximum by microseconds. Use the same statement timestamp for both endpoints, preserving the production bound. The direct source-substitution probe now uses a well-formed alternative SHA-256 identity, so its negative assertion cannot rely on malformed input. + +Retained-migration replay passed in 177.84s +(`/tmp/submission-unsealed-migration-v2.log/.json`), and the well-formed source +substitution replay passed in 46.31s +(`/tmp/submission-unsealed-substitution-v2.log/.json`). Both receipts report +schema0088 and complete isolated cleanup. Scoped reviews at clean `e6844b38c` +found no production defect, but QA-UNSEALED-001 identified a distinct omitted +case: a committed initiation intent before provider begin. QA's independent +real-Local probe showed that omitting only abort-tombstone publication permits +late begin despite reported settlement +(`/tmp/submission-unsealed-intent-only-qa-probe.json`). Extend the existing phase +matrix with `intent_only`, require charge release without a seal, inspect the +exact tombstone and absence of upload.json, and require late begin refusal while +the original upload deadline is still valid. Architecture/security agreed this +must discriminate tombstone protection from expiry. No production change is +needed for the finding; the focused test closes its missing regression proof. + +The intent-only case passed in 21.11s +(`/tmp/submission-unsealed-intent-only-v1.log/.json`, schema0088, complete +isolated cleanup). Scoped Ruff and whitespace checks passed on the repair. diff --git a/backend/tests/artifacts/test_unsealed_source_cleanup.py b/backend/tests/artifacts/test_unsealed_source_cleanup.py index b78a6c69e..e1f753810 100644 --- a/backend/tests/artifacts/test_unsealed_source_cleanup.py +++ b/backend/tests/artifacts/test_unsealed_source_cleanup.py @@ -2,6 +2,7 @@ import os import time import json +from datetime import UTC, datetime from uuid import UUID import pytest @@ -29,7 +30,7 @@ async def unfinished(intake, phase, *, old_bytes=True): if phase != "no_intent": intent = await repository(session).prepare_upload( operation, lease, 1, part_bytes=5 * 1024**2, idle_timeout_seconds=20.0) - if intent is not None: + if intent is not None and phase != "intent_only": upload = await store.begin_source_upload(intent) if phase != "begin_unknown": async with intake.factory.begin() as session: @@ -55,7 +56,7 @@ async def unfinished(intake, phase, *, old_bytes=True): store.close() -@pytest.mark.parametrize("phase", ["no_intent", "begin_unknown", "handle", "partial", "eof"]) +@pytest.mark.parametrize("phase", ["no_intent", "intent_only", "begin_unknown", "handle", "partial", "eof"]) async def test_unsealed_cleanup_releases_reserved_bytes_without_a_seal(intake, phase): operation, intent, upload, completion, _, path = await unfinished(intake, phase) result = await composition.sweep_submission_sources(intake.factory, settings_for(intake)) @@ -73,10 +74,16 @@ async def test_unsealed_cleanup_releases_reserved_bytes_without_a_seal(intake, p if intent is not None: store = initialize_local_store(root=intake.durable_root) try: + assert intent.upload_deadline_at > datetime.now(UTC) + if phase == "intent_only": + assert not (path.parent / "upload.json").exists() + marker = json.loads((path.parent / "aborted.json").read_text()) + assert marker == {"cleanup_source": target} with pytest.raises(ArtifactPreconditionFailedError): await store.begin_source_upload(intent) - with pytest.raises(ArtifactPreconditionFailedError): - await store.upload_source_part(upload, 1, b"late") + if upload is not None: + with pytest.raises(ArtifactPreconditionFailedError): + await store.upload_source_part(upload, 1, b"late") if completion is not None: with pytest.raises(ArtifactPreconditionFailedError): await store.complete_source_upload(completion) From 6fcbcfa0e35f0ff3179ec24d041cc5995e4ae70a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:14:28 +0100 Subject: [PATCH 227/513] Record unsealed cleanup verification and scoped review --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 15eca3562..87a033810 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8067,3 +8067,12 @@ needed for the finding; the focused test closes its missing regression proof. The intent-only case passed in 21.11s (`/tmp/submission-unsealed-intent-only-v1.log/.json`, schema0088, complete isolated cleanup). Scoped Ruff and whitespace checks passed on the repair. + +Clean `89ed11f584909265301a4afc91d149f8d275a173` review closure: +architecture/security PASS and QA/test-delta PASS WITH LOW RISKS. +QA-UNSEALED-001 is resolved. Both reviewers inspected the exact test/record +repair; production code remains the reviewed `e6844b38c` implementation. +Start/end review snapshots matched. Test receipts identify their precommit +worktrees; clean commits were inspected, not falsely presented as exact-head +suite reruns. Remote write settlement, orphan reconciliation, native AWS and the +separate-runner integration remain open under the full goal. From 49e280d0542fa212745fc833c9157bd8e372818b Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:20:21 +0100 Subject: [PATCH 228/513] Prevent implicit retries of uncertain S3 storage requests --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 36 +++++++++++++++ .../app/adapters/artifacts/s3_compatible.py | 4 +- backend/tests/test_s3_artifact_store.py | 44 +++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 87a033810..03c91df72 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8076,3 +8076,39 @@ Start/end review snapshots matched. Test receipts identify their precommit worktrees; clean commits were inspected, not falsely presented as exact-head suite reruns. Remote write settlement, orphan reconciliation, native AWS and the separate-runner integration remain open under the full goal. + +Remote settlement boundary: remove SDK-managed duplicate storage attempts before +adding reconciliation authority. The data-plane S3 client currently configures +`max_attempts=1`, which permits one retry after the original request. Multipart +initiation is not idempotent, so this can create an unrecorded second handle. +Use one total SDK attempt; existing durable owners retain their explicit +observe/retry behavior. Scope: S3 adapter data-plane configuration, focused SDK +wire-level failure tests and neighboring source/cleanup controls, plus this +record. Do not change STS credential acquisition, widen deletion authority, +fabricate settlement for retained ambiguous uploads, add a new retry workflow, +or declare remote reconciliation complete. Acceptance: a retryable multipart +start failure sends exactly one HTTP creation request and surfaces uncertainty; +normal upload/observation and lost-ack cleanup controls remain valid. Risk: +provider transport behavior; required review is QA and architecture/security. +Human focus: distinguish eliminating new duplicate attempts from proving old +uncertain writes settled. Botocore's official Config reference defines +`total_max_attempts=1` as one request including the initial attempt. + +The real SDK/HTTP regression failed before repair in 6.57s: one +`begin_source_upload` call sent two POST creation requests after a retryable503 +response (`/tmp/submission-source-sdk-retry-before.log/.json`). The endpoint +supplies normal bucket-versioning metadata, so failure reaches actual multipart +initiation. `AWS_MAX_ATTEMPTS=9` is set to verify the explicit adapter bound wins +over environment retry policy. Change only the data-plane AioConfig to +`total_max_attempts=1`; STS configuration remains unchanged. The +[official Config reference](https://docs.aws.amazon.com/botocore/latest/reference/config.html) +defines this distinction. This repair prevents new hidden retries; it does not +retroactively settle a retained unknown handle or authorize charge release. + +After repair, the SDK HTTP regression and neighboring real-MinIO source, +lost-begin/lost-completion, exact-version deletion/lost-delete acknowledgment, +uncertain SHA-object put and unsealed observation controls passed:14 passed, +46 explicitly deselected in33.51s +(`/tmp/submission-source-sdk-retry-after.log/.json`). These selections exercise +the changed data-plane retry behavior and preserve explicit recovery; they are +not a whole-suite result. Ruff, structure and whitespace checks passed. diff --git a/backend/app/adapters/artifacts/s3_compatible.py b/backend/app/adapters/artifacts/s3_compatible.py index c8ae1b1ff..e209b9ba6 100644 --- a/backend/app/adapters/artifacts/s3_compatible.py +++ b/backend/app/adapters/artifacts/s3_compatible.py @@ -505,7 +505,9 @@ def __init__( read_timeout=float(read_timeout_seconds), max_pool_connections=max_pool_connections, proxies={}, - retries={"max_attempts": 1, "mode": "standard"}, + # Durable owners observe uncertain outcomes before retrying. In + # particular, CreateMultipartUpload has no idempotency token. + retries={"total_max_attempts": 1, "mode": "standard"}, request_checksum_calculation="when_required", response_checksum_validation="when_required", s3={ diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py index 0952fda2c..9ef9d15c6 100644 --- a/backend/tests/test_s3_artifact_store.py +++ b/backend/tests/test_s3_artifact_store.py @@ -1035,6 +1035,50 @@ def source_intent(store, **updates): }) +@pytest.mark.asyncio +async def test_source_begin_does_not_retry_an_uncertain_creation(monkeypatch): + """Exercise the real SDK retry stack against a retryable HTTP failure.""" + from aiohttp import web + + creations = [] + + async def respond(request): + if request.method == "GET" and "versioning" in request.query: + return web.Response(content_type="application/xml", text= + '' + 'Enabled') + assert request.method == "POST" and "uploads" in request.query + creations.append(request.path) + return web.Response(status=503, content_type="application/xml", text= + 'ServiceUnavailableuncertain creation') + + application = web.Application() + application.router.add_route("*", "/{path:.*}", respond) + runner = web.AppRunner(application) + await runner.setup() + store = None + try: + await web.TCPSite(runner, "127.0.0.1", 0).start() + host, port = runner.addresses[0] + settings = minio_settings(private_prefix="retry-proof").model_copy(update={ + "artifact_s3_endpoint_url": f"http://{host}:{port}", + }) + monkeypatch.setenv("AWS_MAX_ATTEMPTS", "9") + bootstrap = create_artifact_store_bootstrap(settings, activation_guard=None) + namespace = bootstrap.namespace_identity + _, fingerprint = artifact_store_namespace_material( + backend="s3_compatible", adapter_identity=bootstrap.identity, namespace_identity=namespace) + store = bootstrap.initialize_after_namespace_claim( + ArtifactStoreNamespaceClaim(bootstrap.identity, namespace, fingerprint)) + with pytest.raises(ArtifactStoreUnavailableError): + await store.begin_source_upload(source_intent(store)) + assert len(creations) == 1, "an uncertain initiation must not create another upload handle" + finally: + if store is not None: + store.close() + await runner.cleanup() + + async def source_completion(store, payload, **intent_updates): """Send parts sequentially as the eventual durable owner must do.""" upload = await store.begin_source_upload(source_intent(store, **intent_updates)) From c3ea39c719d1c6b13d4abd0459865f49de9c0bc8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:21:57 +0100 Subject: [PATCH 229/513] Record S3 retry regression and scoped review --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 03c91df72..b6206c2a1 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8112,3 +8112,12 @@ uncertain SHA-object put and unsealed observation controls passed:14 passed, (`/tmp/submission-source-sdk-retry-after.log/.json`). These selections exercise the changed data-plane retry behavior and preserve explicit recovery; they are not a whole-suite result. Ruff, structure and whitespace checks passed. + +Clean `49e280d0542fa212745fc833c9157bd8e372818b` scoped review closure: +architecture/security PASS and QA/test-delta PASS WITH LOW RISKS, no findings. +QA independently replayed the exact wire test successfully and restored the old +retry configuration in memory; that mutation failed the same request-count +assertion (`/tmp/submission-source-sdk-retry-qa-probe.json`). Both clean review +snapshots matched. Shared suite receipts identify the precommit worktree, not an +exact-head launch. This closes the SDK duplicate-attempt defect only; existing +unknown upload settlement and orphan reconciliation remain open. From 31f59daf456827757741d8c44651cae6e7118074 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:31:26 +0100 Subject: [PATCH 230/513] Confirm known multipart cleanup after independent settlement checks --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 7 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 50 ++++++++++++ .../app/adapters/artifacts/source_cleanup.py | 32 +++++--- backend/scripts/test_lane_catalogue.py | 1 + .../tests/artifacts/intake_post_support.py | 2 + .../artifacts/test_source_cleanup_minio.py | 74 +++++++++++++++++ backend/tests/test_s3_artifact_store.py | 79 +++++++++++++++++-- docs/operations_artifact_storage.md | 35 +++++--- 8 files changed, 248 insertions(+), 32 deletions(-) create mode 100644 backend/tests/artifacts/test_source_cleanup_minio.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 61d8803be..4f0d63581 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -80,8 +80,11 @@ migration must not displace closing this integration. The current unsealed change extends that same cleanup owner: Local incomplete uploads can be reclaimed, and an observed late completion is retained until a fresh aged claim identifies its exact version. Focused Local/PostgreSQL and MinIO -checks passed, as did the existing cleanup-owner suite. Remote partial-write -settlement and genuine-orphan reconciliation remain open; do not treat this +checks passed, as did the existing cleanup-owner suite. Recorded MinIO multipart +handles now settle only after parts/handle/version absence; a real PostgreSQL +lost-abort/replay case proves conservative charge retention then one release. +Remote initiation without a recorded handle and genuine-orphan reconciliation +remain open; do not treat this partial implementation as completion of order 1. ## Acceptance evidence still to close diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b6206c2a1..88b6d3e12 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8121,3 +8121,53 @@ assertion (`/tmp/submission-source-sdk-retry-qa-probe.json`). Both clean review snapshots matched. Shared suite receipts identify the precommit worktree, not an exact-head launch. This closes the SDK duplicate-attempt defect only; existing unknown upload settlement and orphan reconciliation remain open. + +Known-handle remote settlement scope: reuse the existing cleanup claim and +confirmation operation to release a recorded unfinished upload only after scoped +abort, authoritative NoSuchUpload/parts absence, fresh handle discovery and +absence of every object version/delete marker at its managed key. Re-observe +committed EOF after abort so a racing completion becomes the existing durable +exact-version observation, never deletion under a partial claim. Factor the +existing sealed-cleanup version-absence check for both paths. Allowed files: +source cleanup adapter and existing provider/owner tests plus record. Prohibited: +new lifecycle/schema, broad deletion, release on abort acknowledgment alone, +inferred settlement of missing-handle initiation, AWS qualification claims or +changed retained-object policy. Acceptance: real MinIO known partial upload and +lost-abort replay settle; racing completion, surviving parts/versions and unknown +initiation remain protected; late part/complete against the aborted handle fail. +Risk: storage reclamation; QA and architecture/security reviews required. + +The affected test scope includes `tests/artifacts/test_source_cleanup_minio.py` +and its existing shared-foundation lane registration: use the current T1 owner, +real PostgreSQL and MinIO, then the existing cleanup execution composition to +prove lost-abort uncertainty retains the reservation and a confirmed replay +releases it once without fabricating sealed custody. Provider-level phase cases +cover completion-before-abort and completion-during-abort, not merely mocked +absence booleans. Surviving parts, unexplained versions/delete markers and +missing-handle initiation remain negative controls. Fresh `origin/main` is fully +contained in the working branch; no integration merge was needed. + +Provider selection passed18 cases in95.55s (48 explicitly deselected, +`/tmp/submission-known-upload-settlement-v1.log/.json`). The integrated charge +probe initially failed before provider work because the existing MinIO fixture's +claimed reopenable factory reused one bootstrap/adapter for two simultaneous +clients. Repair that test helper to create a fresh bootstrap per invocation, +retaining the exact same namespace, and include the existing pinned-version POST +test in its rerun. No production bootstrap contract is weakened. + +CI on prior head also exposed stale vocabulary in the cleanup operations guide +(`agent-gates`, run45215714126). Reconcile that affected guide with the current +sealed/unsealed behavior and explicitly name Celery processes; do not exempt +the text or weaken the documentation checker. These fixture and ordinary-doc +repairs are within the affected cleanup integration, not a broader migration. + +The combined PostgreSQL/MinIO charge test and existing retained-version POST +control passed2 cases in80.86s +(`/tmp/submission-known-upload-charge-v2.log/.json`, schema0088, complete +isolated cleanup). Lost abort acknowledgment left the1024-byte reservation and +unconfirmed claim intact; exact replay released it to zero once without a seal +or fabricated provider generation. Provider results18passed and this integrated +pair are bounded proofs, not native AWS qualification. Ruff, structure, +protected-module boundary, record/link, stale-authorization-doc and whitespace +checks passed. The overview now distinguishes recorded-handle settlement from +the still-open missing-handle and genuine-orphan paths. diff --git a/backend/app/adapters/artifacts/source_cleanup.py b/backend/app/adapters/artifacts/source_cleanup.py index e5ac627e7..62d96d69e 100644 --- a/backend/app/adapters/artifacts/source_cleanup.py +++ b/backend/app/adapters/artifacts/source_cleanup.py @@ -119,14 +119,19 @@ async def remove(self, source, upload): # Any additional generation or delete marker remains an operation-owned # reconciliation obligation. Removing our exact version cannot release # its charge while other bytes at the same managed key are unexplained. - async with self._store._source_client(source.location, ArtifactProviderOperationEvidence()) as client: + versions_absent = await self._versions_absent(source.location) + return SubmissionSourceRemoval(source, absent, parts_absent and not handles and versions_absent, parts_absent) + + async def _versions_absent(self, location): + """Only a complete empty version listing settles the managed key.""" + from app.interfaces.artifacts import ArtifactProviderOperationEvidence + async with self._store._source_client(location, ArtifactProviderOperationEvidence()) as client: versions = await client.list_object_versions( - Bucket=self._store._bucket, Prefix=self._store._source_key(source.location), MaxKeys=1, + Bucket=self._store._bucket, Prefix=self._store._source_key(location), MaxKeys=1, ) - versions_absent = (versions.get("IsTruncated") is False - and versions.get("Versions", []) == [] - and versions.get("DeleteMarkers", []) == []) - return SubmissionSourceRemoval(source, absent, parts_absent and not handles and versions_absent, parts_absent) + return (versions.get("IsTruncated") is False + and versions.get("Versions", []) == [] + and versions.get("DeleteMarkers", []) == []) async def remove_unsealed(self, value: UnsealedSourceCleanupInput): """Abort known scoped handles; retain charge until remote writes are settled.""" @@ -144,7 +149,14 @@ async def remove_unsealed(self, value: UnsealedSourceCleanupInput): parts_absent = True for upload in handles: parts_absent = parts_absent and await self._store.source_upload_parts_absent(upload) - # Unknown begin retries and a racing completion are not settled by one - # LIST/abort response. Exact completed-version reconciliation follows - # through durable cleanup custody; never infer capacity release here. - return SubmissionSourceRemoval(value.source, False, False, parts_absent) + if value.upload is None or not parts_absent: + # Discovery cannot prove that an unacknowledged initiation has + # finished. Keep its charge, including when no handle was listed. + return SubmissionSourceRemoval(value.source, False, False, parts_absent) + if value.completion is not None: + completed = await self._store.observe_source_upload(value.completion) + if completed is not None: + return SubmissionSourceRemoval(value.source, False, False, parts_absent, completed) + remaining = await self._store.discover_source_uploads(value.intent) + absent = await self._versions_absent(value.source.location) + return SubmissionSourceRemoval(value.source, absent, not remaining and absent, parts_absent) diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index f1fbafec4..091e8afce 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -57,6 +57,7 @@ class TestLane: "tests/artifacts/test_submission_source_cleanup.py", "tests/artifacts/test_source_cleanup_worker.py", "tests/artifacts/test_unsealed_source_cleanup.py", + "tests/artifacts/test_source_cleanup_minio.py", "tests/artifacts/test_source_cleanup_topology.py", "tests/artifacts/test_submission_pre_source.py", "tests/artifacts/test_submission_intake_admission.py", diff --git a/backend/tests/artifacts/intake_post_support.py b/backend/tests/artifacts/intake_post_support.py index c3fbe6886..36f326f59 100644 --- a/backend/tests/artifacts/intake_post_support.py +++ b/backend/tests/artifacts/intake_post_support.py @@ -97,7 +97,9 @@ async def minio_source_fixture(): settings = minio_settings(private_prefix=f"post-source/{new_record_id()}", buffer_bytes=65536) bootstrap = create_artifact_store_bootstrap(settings, activation_guard=None) namespace = artifact_storage_namespace_spec(settings, bootstrap) + bootstrap.close() def factory(): + bootstrap = create_artifact_store_bootstrap(settings, activation_guard=None) return bootstrap.initialize_after_namespace_claim(ArtifactStoreNamespaceClaim( bootstrap.identity, bootstrap.namespace_identity, namespace.namespace_fingerprint)) store = factory() diff --git a/backend/tests/artifacts/test_source_cleanup_minio.py b/backend/tests/artifacts/test_source_cleanup_minio.py new file mode 100644 index 000000000..cfe7b9a12 --- /dev/null +++ b/backend/tests/artifacts/test_source_cleanup_minio.py @@ -0,0 +1,74 @@ +"""Real PostgreSQL charge custody across uncertain MinIO partial-upload cleanup.""" +from datetime import timedelta +from types import SimpleNamespace + +import pytest +from sqlalchemy import text + +from app.adapters.artifacts import submission_source_cleanup_execution +from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup +from app.core.identifiers import new_record_id +from app.interfaces.artifacts import ArtifactStoreUnavailableError +from app.modules.actors.api import ServiceIdentity +from tests.artifacts.test_submission_intake_admission import ( + admission_intake as admission_intake, admin_access as admin_access, + auth_database_env as auth_database_env, clear_settings_cache as clear_settings_cache, + rsa_signing_material as rsa_signing_material, signed_access as signed_access, admit_new, +) +from tests.artifacts.test_submission_intake_custody import repository +from tests.artifacts.test_submission_source_cleanup import age_fixture +from tests.checkers.execution.support import provision_post_submit_service + + +@pytest.mark.parametrize("admission_intake", ["minio"], indirect=True) +async def test_partial_upload_charge_survives_lost_abort_then_releases_once(admission_intake, monkeypatch): + f = admission_intake + await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP) + foreground = await admit_new(f) + operation = foreground.operation_id + store = f.source_store_factory() + cleanup_store = f.source_store_factory() + cleanup = S3SubmissionSourceCleanup(cleanup_store) + try: + async with f.factory.begin() as session: + intent = await repository(session).prepare_upload(operation, foreground.lease_id, foreground.generation, + part_bytes=5 * 1024**2, idle_timeout_seconds=20.0) + upload = await store.begin_source_upload(intent) + async with f.factory.begin() as session: + await repository(session).record_upload(operation, foreground.lease_id, foreground.generation, upload=upload) + await store.upload_source_part(upload, 1, b"interrupted ZIP") + async with f.factory.begin() as session: + await repository(session).terminalize(operation, foreground.lease_id, foreground.generation, + state="failed", failure_code="upload_interrupted") + await age_fixture(SimpleNamespace(engine=f.factory.kw["bind"]), operation, preserve_upload_deadline=True) + abort = cleanup_store.request_source_abort + + async def lose_acknowledgment(target): + await abort(target) + raise ArtifactStoreUnavailableError("abort acknowledgment lost") + + monkeypatch.setattr(cleanup_store, "request_source_abort", lose_acknowledgment) + execution = submission_source_cleanup_execution(sessions=f.factory, provider=cleanup, + lease_duration=timedelta(seconds=60)) + claim_id = new_record_id() + with pytest.raises(ArtifactStoreUnavailableError, match="acknowledgment lost"): + await execution.run(operation, claim_id) + async with f.factory() as session: + assert (await session.execute(text("SELECT state,accounted_bytes,sealed_at " + "FROM submission_source_charges WHERE operation_id=:id"), {"id": operation})).one() == ("reserved", 1024, None) + assert await session.scalar(text("SELECT confirmed_at FROM submission_source_cleanup_claims " + "WHERE operation_id=:id"), {"id": operation}) is None + monkeypatch.setattr(cleanup_store, "request_source_abort", abort) + await execution.run(operation, claim_id) + await execution.run(operation, claim_id) + async with f.factory() as session: + assert (await session.execute(text("SELECT state,accounted_bytes,sealed_at " + "FROM submission_source_charges WHERE operation_id=:id"), {"id": operation})).one() == ("released", 0, None) + assert await session.scalar(text("SELECT public.source_cleanup_authority_valid(c,'confirm') " + "FROM submission_source_cleanup_claims c WHERE operation_id=:id"), {"id": operation}) is True + assert await session.scalar(text("SELECT provider_generation FROM submission_intake_operations " + "WHERE id=:id"), {"id": operation}) is None + assert await store.source_upload_parts_absent(upload) is True + finally: + cleanup.close() + store.close() diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py index 9ef9d15c6..d079aaa7c 100644 --- a/backend/tests/test_s3_artifact_store.py +++ b/backend/tests/test_s3_artifact_store.py @@ -1319,13 +1319,13 @@ async def test_source_cleanup_keeps_source_when_another_upload_is_unresolved(sou @pytest.mark.asyncio -@pytest.mark.parametrize("completed", [False, True]) -async def test_unsealed_cleanup_observes_completion_without_premature_release(source_store, completed): +@pytest.mark.parametrize("phase", ["unfinished", "completed", "completion_race", "lost_abort"]) +async def test_unsealed_cleanup_settles_known_upload_or_retains_completed_version(source_store, monkeypatch, phase): from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup from app.modules.artifacts.api.submission_cleanup import UnsealedSubmissionSource, UnsealedSourceCleanupInput completion = await source_completion(source_store, b"unrecorded-completion") - source = await source_store.complete_source_upload(completion) if completed else None + source = await source_store.complete_source_upload(completion) if phase == "completed" else None upload = completion.upload value = UnsealedSourceCleanupInput( source=UnsealedSubmissionSource( @@ -1337,18 +1337,83 @@ async def test_unsealed_cleanup_observes_completion_without_premature_release(so # Real MinIO protocol behavior; production credential qualification is separate. cleanup_store = initialize_minio_store(private_prefix=source_store._private_prefix) try: - result = await S3SubmissionSourceCleanup(cleanup_store).remove_unsealed(value) + abort = cleanup_store.request_source_abort + + async def interrupted_abort(target): + nonlocal source + if phase == "completion_race": + source = await source_store.complete_source_upload(completion) + await abort(target) + if phase == "lost_abort": + raise ArtifactStoreUnavailableError("abort acknowledgment lost") + + monkeypatch.setattr(cleanup_store, "request_source_abort", interrupted_abort) + cleanup = S3SubmissionSourceCleanup(cleanup_store) + if phase == "lost_abort": + with pytest.raises(ArtifactStoreUnavailableError, match="acknowledgment lost"): + await cleanup.remove_unsealed(value) + monkeypatch.setattr(cleanup_store, "request_source_abort", abort) + result = await cleanup.remove_unsealed(value) assert result.source == value.source - assert result.object_absent is result.writes_settled is False assert result.observed_source == source - if completed: + if source is not None: + assert result.object_absent is result.writes_settled is False retained = await source_store.observe_sealed_source(source) assert retained is not None assert retained.provider_generation == source.provider_generation else: - assert result.parts_absent is True + assert result.object_absent is result.writes_settled is result.parts_absent is True assert await source_store.source_upload_parts_absent(upload) is True + assert await cleanup.remove_unsealed(value) == result + with pytest.raises(ArtifactObjectMissingError): + await source_store.upload_source_part(upload, 1, b"late") + with pytest.raises(ArtifactObjectMissingError): + await source_store.complete_source_upload(completion) + finally: + cleanup_store.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("obligation", ["unknown_begin", "surviving_parts", "version", "delete_marker"]) +async def test_unsealed_cleanup_preserves_unresolved_obligations(source_store, monkeypatch, obligation): + from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup + from app.modules.artifacts.api.submission_cleanup import UnsealedSubmissionSource, UnsealedSourceCleanupInput + + intent = source_intent(source_store) + upload = await source_store.begin_source_upload(intent) + if obligation != "unknown_begin": + await source_store.upload_source_part(upload, 1, b"unfinished") + value = UnsealedSourceCleanupInput( + source=UnsealedSubmissionSource(location=intent.location, upload_fence=intent.upload_fence, + provider_upload_id=None if obligation == "unknown_begin" else upload.provider_upload_id), + intent=intent, upload=None if obligation == "unknown_begin" else upload, completion=None, + ) + cleanup_store = initialize_minio_store(private_prefix=source_store._private_prefix) + try: + if obligation == "surviving_parts": + async def acknowledged_without_settlement(_upload): + pass + monkeypatch.setattr(cleanup_store, "request_source_abort", acknowledged_without_settlement) + if obligation in {"version", "delete_marker"}: + # Admin fixture introduces an unexplained version/marker. Cleanup + # must preserve it, never manufacture a source identity to delete it. + async with source_store._client() as client: + key = source_store._source_key(intent.location) + await client.put_object(Bucket=MINIO_BUCKET, Key=key, Body=b"unexplained") + if obligation == "delete_marker": + await client.delete_object(Bucket=MINIO_BUCKET, Key=key) + result = await S3SubmissionSourceCleanup(cleanup_store).remove_unsealed(value) + assert result.writes_settled is False + assert result.observed_source is None + if obligation == "surviving_parts": + assert result.parts_absent is False + if obligation in {"version", "delete_marker"}: + async with source_store._client() as client: + retained = await client.list_object_versions(Bucket=MINIO_BUCKET, Prefix=key) + assert len(retained["Versions"]) == 1 + assert bool(retained.get("DeleteMarkers")) is (obligation == "delete_marker") finally: + await source_store.request_source_abort(upload) cleanup_store.close() diff --git a/docs/operations_artifact_storage.md b/docs/operations_artifact_storage.md index 103eef678..172992492 100644 --- a/docs/operations_artifact_storage.md +++ b/docs/operations_artifact_storage.md @@ -251,7 +251,7 @@ than deleting, detaching, rewriting, or restamping rows. ## Submission source reclamation -Sealed, terminal submission sources use the dedicated +Terminal submission sources use the dedicated `workstream.artifacts.sweep_submission_sources` task. Configure `WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE` as a JSON object with explicit `maximum_candidates` (1–1000), `run_seconds` (1–300), and `lease_seconds` @@ -260,16 +260,16 @@ recommended deployment values. Size the page and execution envelope from measured provider latency and terminal-source arrival rates. An absent profile disables the Beat entry; it does not constitute a deployed cleanup service. -Supply the profile to Beat and the dedicated worker. Run the worker with only +Supply the profile to Beat and the dedicated Celery process. Run that process with only its cleanup queue and the prefork pool: ```bash celery -A app.workers.celery_app:celery_app worker --pool=prefork -Q workstream.source_cleanup ``` -Other worker processes must select their own queues explicitly. Mixed queues, +Other Celery processes must select their own queues explicitly. Mixed queues, eager execution, and other pools are rejected for cleanup. The task execution -boundary also rejects foreign registered task names delivered to this worker. +boundary also rejects foreign registered task names delivered to this process. Startup checks the persisted namespace, current cleanup-service authority and provider configuration before forking. Each sweep repeats current authority checks. The task has a @@ -281,10 +281,11 @@ service authority. This clears only the old operation's task pointer; it neither resumes PRE nor releases storage charges. Live and accepted operations remain protected. Recovery uses the sweep's explicit page/run limits and bounds each attempt by the configured lease interval. Foreground recovery can use at most -half the run envelope, preserving time for unrelated sealed cleanup even when a +half the run envelope, preserving time for unrelated source cleanup even when a task lock is held. This is periodic foreground recovery, -not the prompt runtime-session reaper. Sources must have been both sealed -and terminal for at least two hours. Candidate discovery grants no deletion +not the prompt runtime-session reaper. Sources must have been terminal for at +least two hours; a newly observed completed version starts a fresh two-hour +protection period. Candidate discovery grants no deletion permission: the existing owner locks task/source custody, rejects accepted or retained sources, and commits an audited exact-generation claim before provider I/O. Only confirmed object absence and settled upload obligations release the @@ -292,15 +293,23 @@ charge. A failed or interrupted attempt retains its charge; a later sweep can claim a new generation after the old lease expires. Repeated sweeps do not release the same charge again. -For S3-compatible storage, supply separate cleanup credentials to this worker +For S3-compatible storage, supply separate cleanup credentials to this Celery process through its storage settings and put the upload access-key identity in the profile's `upload_principal`. The provider factory rejects the upload principal as the cleanup principal. Do not give these deletion credentials to API or -ordinary workers. Native AWS source cleanup remains unavailable until its +ordinary Celery processes. Native AWS source cleanup remains unavailable until its separate source-capability qualification is implemented and passed; existing SHA-object activation and MinIO tests do not qualify it. -This worker currently covers sealed terminal sources. Unsealed uploads, -uncertain begin/completion results and genuine orphan reconciliation remain -unfinished requirements of the submission execution specification. Do not treat -this schedule as proof that every abandoned byte is reclaimed. +The sweep covers sealed sources, Local unfinished uploads and recorded MinIO +multipart handles. Local cleanup retains an abort tombstone to reject late +initiation. Remote cleanup requires parts absence after abort, fresh handle +discovery and no remaining versions or delete markers. A completion discovered +before or during abort becomes a retained exact-version target; it requires a +fresh aged cleanup claim before deletion. An abort acknowledgment alone does not +release storage charges. The S3 data-plane SDK makes one total attempt per call; +durable owners control observation and retries. + +Uncertain remote initiation without a recorded handle and genuine orphan +reconciliation remain unfinished requirements. Do not treat this schedule as +proof that every abandoned byte is reclaimed. From 96c91c718bc39c627caf31bc439f726d437ad271 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:36:31 +0100 Subject: [PATCH 231/513] Isolate delete marker protection in cleanup regression --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ backend/tests/test_s3_artifact_store.py | 7 ++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 88b6d3e12..b8e0cf14a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8171,3 +8171,18 @@ pair are bounded proofs, not native AWS qualification. Ruff, structure, protected-module boundary, record/link, stale-authorization-doc and whitespace checks passed. The overview now distinguishes recorded-handle settlement from the still-open missing-handle and genuine-orphan paths. + +Clean31f59daf4 review: architecture/security/documentation scoped PASS; QA found +QA-KNOWN-001, a masked delete-marker negative. Its fixture retained both a data +version and marker, so MaxKeys1/truncation or the version guard could still deny +settlement when the marker guard was omitted. QA's isolated omission mutant +passed that exact test in21.38s +(`/tmp/submission-known-marker-qa-mutant.log/.json`,0088, complete cleanup), +demonstrating the coverage gap rather than a production defect. Repair only the +fixture: after making the marker, remove the exact admin-seeded data version; +assert zero versions and one marker. Keep the separate version-only control. +No production guard or ownership rule changes for this finding. + +The repaired marker-only and retained-version controls passed together +(`/tmp/submission-known-marker-only-v1.log/.json`, schema0088, complete +isolated cleanup). Ruff and whitespace checks passed on this test-only repair. diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py index d079aaa7c..c7115bd2c 100644 --- a/backend/tests/test_s3_artifact_store.py +++ b/backend/tests/test_s3_artifact_store.py @@ -1399,9 +1399,10 @@ async def acknowledged_without_settlement(_upload): # must preserve it, never manufacture a source identity to delete it. async with source_store._client() as client: key = source_store._source_key(intent.location) - await client.put_object(Bucket=MINIO_BUCKET, Key=key, Body=b"unexplained") + seeded = await client.put_object(Bucket=MINIO_BUCKET, Key=key, Body=b"unexplained") if obligation == "delete_marker": await client.delete_object(Bucket=MINIO_BUCKET, Key=key) + await client.delete_object(Bucket=MINIO_BUCKET, Key=key, VersionId=seeded["VersionId"]) result = await S3SubmissionSourceCleanup(cleanup_store).remove_unsealed(value) assert result.writes_settled is False assert result.observed_source is None @@ -1410,8 +1411,8 @@ async def acknowledged_without_settlement(_upload): if obligation in {"version", "delete_marker"}: async with source_store._client() as client: retained = await client.list_object_versions(Bucket=MINIO_BUCKET, Prefix=key) - assert len(retained["Versions"]) == 1 - assert bool(retained.get("DeleteMarkers")) is (obligation == "delete_marker") + assert len(retained.get("Versions", [])) == (0 if obligation == "delete_marker" else 1) + assert len(retained.get("DeleteMarkers", [])) == (1 if obligation == "delete_marker" else 0) finally: await source_store.request_source_abort(upload) cleanup_store.close() From a46c317a2d834f28a75f4e7b74ab660dbf2ca8de Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:38:41 +0100 Subject: [PATCH 232/513] Record known upload settlement proof and review --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b8e0cf14a..05a7c324b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8186,3 +8186,13 @@ No production guard or ownership rule changes for this finding. The repaired marker-only and retained-version controls passed together (`/tmp/submission-known-marker-only-v1.log/.json`, schema0088, complete isolated cleanup). Ruff and whitespace checks passed on this test-only repair. + +Clean `96c91c718bc39c627caf31bc439f726d437ad271` review closure: +architecture/security/documentation PASS and QA/test-delta PASS WITH LOW RISKS. +QA-KNOWN-001 is resolved. The same independent marker-guard omission now fails +the repaired exact case at `writes_settled is False`, because the mutant returns +true (`/tmp/submission-known-marker-qa-mutant-repair.log/.json`, expected failure +in7.91s,0088, complete cleanup). Review snapshots match; production code remains +the reviewed31f59daf4 change. Supplied suite receipts identify precommit +worktrees rather than exact-head launches. Missing-handle initiation, genuine +orphans, native AWS and full-goal qualification remain open. From 09701e433e8445ef67eea8f677968c0230614160 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 17:59:40 +0100 Subject: [PATCH 233/513] Retain discovered multipart handles before cleanup aborts --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 19 +++- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 38 ++++++++ backend/alembic/env.py | 3 +- .../versions/0089_observed_upload_cleanup.py | 81 ++++++++++++++++ .../app/adapters/artifacts/source_cleanup.py | 24 ++++- .../artifacts/api/submission_cleanup.py | 26 +++++- .../app/modules/artifacts/intake/cleanup.py | 31 ++++++- .../artifacts/intake/cleanup_execution.py | 6 ++ .../app/modules/artifacts/intake/models.py | 4 + .../artifacts/test_source_cleanup_minio.py | 86 +++++++++++++++-- backend/tests/conftest.py | 2 +- .../test_unsealed_source_cleanup.py | 93 ++++++++++++++++--- backend/tests/test_s3_artifact_store.py | 26 ++++-- docs/operations_artifact_storage.md | 10 +- 14 files changed, 406 insertions(+), 43 deletions(-) create mode 100644 backend/alembic/versions/0089_observed_upload_cleanup.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 4f0d63581..2bdc4acd0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -59,6 +59,17 @@ with the API and runner on different hosts and no shared filesystem. A provider change must not require a second submission lifecycle. These are implementation and verification requirements, not claims that remote transport is complete. +ZIP preservation means retaining the exact uploaded source in artifact storage +and binding acceptance/results to that source; it does not require preserving a +VM, runner disk, or a second durable ZIP per execution. Transfer or mount only +what the selected execution capability needs into disposable scratch. Keep the +failure cases concrete: interrupted upload, lost storage acknowledgement, and +accepted input awaiting finalization. Extend existing custody and cleanup for +those cases; do not introduce provider orchestration or extra lifecycle states +solely to anticipate future sandbox vendors. Moving execution off the API host +removes its virtualization dependency; the chosen runner/provider still must +satisfy its own runtime requirements. + ## Remaining work, in execution order | Order | Required outcome | Concrete finishing evidence | @@ -83,9 +94,11 @@ fresh aged claim identifies its exact version. Focused Local/PostgreSQL and MinI checks passed, as did the existing cleanup-owner suite. Recorded MinIO multipart handles now settle only after parts/handle/version absence; a real PostgreSQL lost-abort/replay case proves conservative charge retention then one release. -Remote initiation without a recorded handle and genuine-orphan reconciliation -remain open; do not treat this -partial implementation as completion of order 1. +Remote initiation without a recorded handle now retains discovered IDs before +abort and binds them to a fresh cleanup authorization. Focused PostgreSQL/MinIO +checks cover growing observations and lost-abort replay. Empty ambiguous +discovery remains charged; genuine-orphan reconciliation and operational crash +drills remain open. This partial implementation does not complete order 1. ## Acceptance evidence still to close diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 05a7c324b..0ca6f6ec1 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8196,3 +8196,41 @@ in7.91s,0088, complete cleanup). Review snapshots match; production code remains the reviewed31f59daf4 change. Supplied suite receipts identify precommit worktrees rather than exact-head launches. Missing-handle initiation, genuine orphans, native AWS and full-goal qualification remain open. + +Missing-handle recovery boundary: persist a bounded, canonical set of discovered +multipart handle IDs on the existing cleanup claim before aborting those handles. +Bind that set into the next exact cleanup authorization; recording or enlarging +the set invalidates the previous decision. Preserve original upload receipts and +source identities. A lost abort response can then replay all recorded handles +even when LIST no longer returns them. Empty discovery remains unresolved; do +not infer that an unacknowledged begin never happened. Reuse the existing sweep, +claim lease and confirmation/charge release, with no new submission state. +Allowed scope: cleanup API/model/owner/execution/provider, migration0089 and +head/fingerprint, focused Local/MinIO/PostgreSQL and retained-migration controls, +lane selection and affected cleanup documentation. No broad inventory deletion, +retained-data rewrite, new caller authority or native-AWS qualification claim. +Acceptance: discovered handles are durably audited before abort; old or altered +observations cannot authorize removal; lost-abort replay releases once after all +known handles/versions settle; unresolved/no-handle discovery stays charged; +existing sealed and observed-version claims survive upgrade unchanged. Risk: +authorization and storage reclamation; QA and architecture/security review. + +0089 implementation evidence: focused real PostgreSQL/MinIO proofs passed for +known/missing handle charge settlement (2 cases, 49.72s), observation growth +before any abort (1 case, 68.96s), empty/unknown initiation controls (2 cases, +18.77s), and the bounded inventory failure (1 case, 31.37s). Logs and isolated +metadata are `/tmp/submission-observed-upload-v2`, +`/tmp/submission-observed-upload-growth-v1`, +`/tmp/submission-observed-upload-empty-v1`, and +`/tmp/submission-observed-upload-bound-v1` (`.log/.json` each). Metadata confirms +0089 and complete resource cleanup. These runs used an uncommitted candidate +based on a46c317a2, not an exact committed-head launch. + +The actual 0088 predecessor upgrade passed in 179.95s +(`/tmp/submission-observed-upload-migration-v1.log/.json`), preserving outstanding, +confirmed and observed-version claims and their prior audit identities. This +run covers the 0088 parameter; the 0087 parameter was not rerun for this change. +The measured 0089 schema fingerprint is +`fb82d1094faebbf8c2ae35a71987772af7cd2519944423b5ab91a6902e3c3580`. +Scoped Ruff passed. Native AWS, genuine orphan reconciliation and full-system +qualification are not established by these focused proofs. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index fc9c137e8..4b2461ef4 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0088_unsealed_source_cleanup" +_CURRENT_HEAD_REVISION = "0089_observed_upload_cleanup" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -142,6 +142,7 @@ def do_run_migrations(connection: Connection) -> None: ("0085_revision_deadline_error",), ("0086_pending_checker_custody",), ("0087_source_cleanup_candidates",), + ("0088_unsealed_source_cleanup",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0089_observed_upload_cleanup.py b/backend/alembic/versions/0089_observed_upload_cleanup.py new file mode 100644 index 000000000..623747b15 --- /dev/null +++ b/backend/alembic/versions/0089_observed_upload_cleanup.py @@ -0,0 +1,81 @@ +"""Retain discovered multipart handles before uncertain abort operations.""" +from alembic import op +from sqlalchemy import text + +revision = "0089_observed_upload_cleanup" +down_revision = "0088_unsealed_source_cleanup" +branch_labels = None +depends_on = None + + +def _definition(name): + return op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_functiondef(CAST(:name AS regprocedure))" + ), {"name": name}).scalar_one() + + +def _replace(body, old, new): + if body.count(old) != 1: + raise RuntimeError("observed upload cleanup predecessor shape changed") + return body.replace(old, new) + + +def upgrade(): + """Extend existing claims; preserve every prior source and audit digest.""" + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.submission_intake_operations, public.submission_source_cleanup_claims, " + "public.submission_source_upload_receipts IN ACCESS EXCLUSIVE MODE") + op.execute("ALTER TABLE public.submission_source_cleanup_claims ADD COLUMN observed_upload_ids jsonb") + op.execute("ALTER TABLE public.submission_source_cleanup_claims ADD CONSTRAINT " + "ck_submission_source_cleanup_claims_observed_upload_shape CHECK " + "(observed_upload_ids is null or (jsonb_typeof(observed_upload_ids)='array' " + "and jsonb_array_length(observed_upload_ids) between 1 and 100 and observed_source is null))") + authority = _definition("public.source_cleanup_authority_valid(public.submission_source_cleanup_claims,text)") + authority = _replace(authority, "CASE WHEN c.observed_source IS NOT NULL THEN", + "CASE WHEN c.observed_upload_ids IS NOT NULL THEN jsonb_build_object(" + "'schema_version','workstream.observed_submission_uploads_cleanup.v1'," + "'source',c.source,'observed_upload_ids',c.observed_upload_ids) " + "WHEN c.observed_source IS NOT NULL THEN") + op.execute(authority) + guard = _definition("public.guard_submission_source_cleanup()") + marker = " IF TG_OP='UPDATE' AND OLD.observed_source IS NULL AND NEW.observed_source IS NOT NULL THEN" + guard = _replace(guard, marker, _OBSERVATION + "\n" + marker) + guard = _replace(guard, "OR NEW.observed_source IS NOT NULL OR NEW.observed_at IS NOT NULL THEN", + "OR NEW.observed_source IS NOT NULL OR NEW.observed_at IS NOT NULL " + "OR NEW.observed_upload_ids IS NOT NULL THEN") + op.execute(guard) + + +def downgrade(): + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") + + +_OBSERVATION = """ + IF TG_OP='UPDATE' AND NEW.observed_upload_ids IS DISTINCT FROM OLD.observed_upload_ids THEN + IF OLD.confirmed_at IS NOT NULL OR OLD.lease_expires_at<=clock_timestamp() + OR OLD.source->>'kind' IS DISTINCT FROM 'unsealed' + OR OLD.source->'provider_upload_id' IS DISTINCT FROM 'null'::jsonb + OR o.provider_profile NOT IN ('minio-v1','aws-s3-v1') + OR o.sealed_at IS NOT NULL OR o.raw_sha256 IS NOT NULL OR OLD.observed_source IS NOT NULL + OR (to_jsonb(NEW)-'observed_upload_ids') IS DISTINCT FROM (to_jsonb(OLD)-'observed_upload_ids') + OR NOT public.source_cleanup_authority_valid(OLD,'claim') + OR NOT EXISTS(SELECT 1 FROM public.submission_source_upload_receipts + WHERE operation_id=o.id AND provider_upload_id IS NULL AND completion_parts IS NULL) + OR NEW.observed_upload_ids IS NULL OR jsonb_typeof(NEW.observed_upload_ids)<>'array' THEN + RAISE EXCEPTION 'source cleanup upload observation differs' USING ERRCODE='23514'; + END IF; + IF jsonb_array_length(NEW.observed_upload_ids) NOT BETWEEN 1 AND 100 + OR NOT coalesce(OLD.observed_upload_ids,'[]'::jsonb) <@ NEW.observed_upload_ids + OR jsonb_array_length(NEW.observed_upload_ids)<=jsonb_array_length(coalesce(OLD.observed_upload_ids,'[]'::jsonb)) + OR EXISTS(SELECT 1 FROM jsonb_array_elements(NEW.observed_upload_ids) v + WHERE jsonb_typeof(v)<>'string' OR length(v #>> '{}') NOT BETWEEN 1 AND 2048) + OR NEW.observed_upload_ids IS DISTINCT FROM + (SELECT jsonb_agg(value ORDER BY value COLLATE "C") FROM + (SELECT DISTINCT value FROM jsonb_array_elements_text(NEW.observed_upload_ids)) canonical) THEN + RAISE EXCEPTION 'source cleanup upload observation is not canonical growth' USING ERRCODE='23514'; + END IF; + -- Old authority cannot authorize deletion of newly discovered handles. + -- A later claim generation binds the complete retained handle set. + RETURN NEW; + END IF; +""" diff --git a/backend/app/adapters/artifacts/source_cleanup.py b/backend/app/adapters/artifacts/source_cleanup.py index 62d96d69e..647bf2a48 100644 --- a/backend/app/adapters/artifacts/source_cleanup.py +++ b/backend/app/adapters/artifacts/source_cleanup.py @@ -135,6 +135,9 @@ async def _versions_absent(self, location): async def remove_unsealed(self, value: UnsealedSourceCleanupInput): """Abort known scoped handles; retain charge until remote writes are settled.""" + from app.interfaces.artifacts import ArtifactOperationConflictError + from app.modules.artifacts.api.submission_intake import SubmissionSourceUpload + if value.intent is None: return SubmissionSourceRemoval(value.source, False, False, False) if value.completion is not None: @@ -142,21 +145,34 @@ async def remove_unsealed(self, value: UnsealedSourceCleanupInput): if completed is not None: return SubmissionSourceRemoval(value.source, False, False, False, completed) handles = await self._store.discover_source_uploads(value.intent) - if value.upload is not None and value.upload not in handles: + if value.upload is None: + discovered = tuple(sorted(set(value.observed_upload_ids) | {item.provider_upload_id for item in handles})) + if len(discovered) > 100: + raise ArtifactOperationConflictError("source cleanup upload inventory exceeded bound") + if discovered != value.observed_upload_ids: + return SubmissionSourceRemoval(value.source, False, False, False, observed_upload_ids=discovered) + if not discovered: + return SubmissionSourceRemoval(value.source, False, False, False) + handles = tuple(SubmissionSourceUpload(intent=value.intent, provider_upload_id=handle) for handle in discovered) + elif value.upload not in handles: handles = (*handles, value.upload) for upload in handles: await self._store.request_source_abort(upload) parts_absent = True for upload in handles: parts_absent = parts_absent and await self._store.source_upload_parts_absent(upload) - if value.upload is None or not parts_absent: - # Discovery cannot prove that an unacknowledged initiation has - # finished. Keep its charge, including when no handle was listed. + if not parts_absent: return SubmissionSourceRemoval(value.source, False, False, parts_absent) if value.completion is not None: completed = await self._store.observe_source_upload(value.completion) if completed is not None: return SubmissionSourceRemoval(value.source, False, False, parts_absent, completed) remaining = await self._store.discover_source_uploads(value.intent) + if value.upload is None and remaining: + discovered = tuple(sorted(set(value.observed_upload_ids) | {item.provider_upload_id for item in remaining})) + if len(discovered) > 100: + raise ArtifactOperationConflictError("source cleanup upload inventory exceeded bound") + if discovered != value.observed_upload_ids: + return SubmissionSourceRemoval(value.source, False, False, parts_absent, observed_upload_ids=discovered) absent = await self._versions_absent(value.source.location) return SubmissionSourceRemoval(value.source, absent, not remaining and absent, parts_absent) diff --git a/backend/app/modules/artifacts/api/submission_cleanup.py b/backend/app/modules/artifacts/api/submission_cleanup.py index e5ab7e600..6a4e4b075 100644 --- a/backend/app/modules/artifacts/api/submission_cleanup.py +++ b/backend/app/modules/artifacts/api/submission_cleanup.py @@ -1,5 +1,5 @@ """Exact source cleanup selectors; values alone grant no deletion authority.""" -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Literal, Protocol from uuid import UUID @@ -63,8 +63,13 @@ class UnsealedSourceCleanupInput: intent: SubmissionSourceUploadIntent | None upload: SubmissionSourceUpload | None completion: SubmissionSourceCompletion | None + observed_upload_ids: tuple[str, ...] = field(default=(), repr=False) def __post_init__(self): + validate_observed_upload_ids(self.observed_upload_ids) + if self.observed_upload_ids and (self.intent is None or self.upload is not None + or self.source.provider_upload_id is not None): + raise ValueError("observed uploads require missing-handle custody") if self.source.upload_fence is None: if any(value is not None for value in (self.intent, self.upload, self.completion)): raise ValueError("uninitiated cleanup has no provider input") @@ -87,8 +92,24 @@ def __post_init__(self): raise ValueError("unsealed cleanup EOF differs") -def cleanup_target_sha256(source, observed_source=None) -> str: +def validate_observed_upload_ids(values: tuple[str, ...]) -> None: + """Bound and canonicalize observation identity without granting authority.""" + if (type(values) is not tuple or len(values) > 100 + or any(type(value) is not str or not 1 <= len(value) <= 2048 for value in values) + or tuple(sorted(set(values))) != values): + raise ValueError("observed upload identities are invalid") + + +def cleanup_target_sha256(source, observed_source=None, observed_upload_ids=()) -> str: """Bind a later exact version as well as its original unfinished obligation.""" + validate_observed_upload_ids(observed_upload_ids) + if observed_upload_ids: + if observed_source is not None: + raise ValueError("upload and completion observations cannot be combined") + return canonical_json_hash({ + "schema_version": "workstream.observed_submission_uploads_cleanup.v1", + "source": source.model_dump(mode="json"), "observed_upload_ids": list(observed_upload_ids), + }) if observed_source is None: return source.source_sha256() return canonical_json_hash({ @@ -107,6 +128,7 @@ class SubmissionSourceRemoval: writes_settled: bool parts_absent: bool observed_source: SealedSubmissionSource | None = None + observed_upload_ids: tuple[str, ...] = field(default=(), repr=False) class SubmissionSourceCleanupProvider(ExternalServiceAdapter, Protocol): diff --git a/backend/app/modules/artifacts/intake/cleanup.py b/backend/app/modules/artifacts/intake/cleanup.py index 78a02ca30..81d4f0886 100644 --- a/backend/app/modules/artifacts/intake/cleanup.py +++ b/backend/app/modules/artifacts/intake/cleanup.py @@ -4,7 +4,7 @@ This owner retains uncertain targets and releases charges only with both exact object absence and settled upload-part obligations supplied by that coordinator. """ -from dataclasses import asdict, dataclass +from dataclasses import asdict, dataclass, field from datetime import datetime, timedelta from uuid import UUID @@ -15,6 +15,7 @@ ) from app.modules.artifacts.api.submission_cleanup import ( SubmissionSourceCleanupAuthorityFacts, UnsealedSubmissionSource, UnsealedSourceCleanupInput, cleanup_target_sha256, + validate_observed_upload_ids, ) from app.modules.artifacts.intake.capacity import SubmissionSourceCapacity from app.modules.artifacts.intake.models import ( @@ -37,6 +38,7 @@ class SourceCleanupClaim: lease_expires_at: datetime confirmed: bool observed_source: SealedSubmissionSource | None = None + observed_upload_ids: tuple[str, ...] = field(default=(), repr=False) def _claim_value(row: SubmissionSourceCleanupClaim) -> SourceCleanupClaim: @@ -48,6 +50,7 @@ def _claim_value(row: SubmissionSourceCleanupClaim) -> SourceCleanupClaim: .model_validate_json(json.dumps(row.source)), row.lease_expires_at, row.confirmed_at is not None, SealedSubmissionSource.model_validate_json(json.dumps(row.observed_source)) if row.observed_source is not None else None, + tuple(row.observed_upload_ids or ()), ) @@ -158,7 +161,8 @@ async def _decision(self, operation, claim_id, generation, phase): observed = _claim_value(row).observed_source if row is not None else None facts = SubmissionSourceCleanupAuthorityFacts( operation_id=UUID(operation.id), project_id=UUID(operation.project_id), - task_id=UUID(operation.task_id), source_sha256=cleanup_target_sha256(source, observed), + task_id=UUID(operation.task_id), source_sha256=cleanup_target_sha256( + source, observed, tuple(row.observed_upload_ids or ()) if row is not None else ()), claim_id=claim_id, claim_generation=generation, phase=phase, ) handle = await self._authorization.prepare(facts=facts, idempotency_key=facts.claim_id) @@ -235,6 +239,7 @@ async def confirm(self, claim: SourceCleanupClaim, *, object_absent: bool, operation, row = await self._locked(claim.source.location.operation_id) if (row is None or row.claim_id != str(claim.claim_id) or row.generation != claim.generation or row.source != claim.source.model_dump(mode="json") + or tuple(row.observed_upload_ids or ()) != claim.observed_upload_ids or row.observed_source != (claim.observed_source.model_dump(mode="json") if claim.observed_source is not None else None)): raise IntakeCustodyConflict("source_cleanup_stale") if row.confirmed_at is not None: @@ -254,6 +259,8 @@ async def upload_for_claim(self, claim: SourceCleanupClaim) -> SubmissionSourceU now = await self._session.scalar(select(func.clock_timestamp())) if (row is None or row.claim_id != str(claim.claim_id) or row.generation != claim.generation or row.source != claim.source.model_dump(mode="json") + or tuple(row.observed_upload_ids or ()) != claim.observed_upload_ids + or row.observed_source != (claim.observed_source.model_dump(mode="json") if claim.observed_source else None) or row.confirmed_at is not None or row.lease_expires_at <= now): raise IntakeCustodyConflict("source_cleanup_stale") await self._require_claim_authority(operation.id) @@ -268,10 +275,28 @@ async def upload_for_claim(self, claim: SourceCleanupClaim) -> SubmissionSourceU completion = SubmissionSourceCompletion.model_validate_json(json.dumps({ "upload": upload.model_dump(mode="json"), "raw_sha256": operation.raw_sha256, "raw_byte_count": operation.raw_byte_count, "parts": receipt.completion_parts})) - return UnsealedSourceCleanupInput(claim.source, intent, upload, completion) + return UnsealedSourceCleanupInput(claim.source, intent, upload, completion, claim.observed_upload_ids) if receipt is None or receipt.provider_upload_id is None or receipt.completion_parts is None: raise IntakeCustodyConflict("source_cleanup_unresolved") return SubmissionSourceUpload( intent=await self._intake._upload_intent(operation, receipt), provider_upload_id=receipt.provider_upload_id, ) + + async def record_upload_observation(self, claim: SourceCleanupClaim, handles: tuple[str, ...]) -> None: + """Remember discovered handles; only a fresh exact claim may abort them.""" + validate_observed_upload_ids(handles) + operation, row = await self._locked(claim.source.location.operation_id) + now = await self._session.scalar(select(func.clock_timestamp())) + if (not isinstance(claim.source, UnsealedSubmissionSource) + or claim.source.provider_upload_id is not None or claim.source.upload_fence is None + or claim.source.location.provider_profile not in {"minio-v1", "aws-s3-v1"} + or row is None or row.claim_id != str(claim.claim_id) or row.generation != claim.generation + or row.confirmed_at is not None or row.lease_expires_at <= now + or row.source != claim.source.model_dump(mode="json") or row.observed_source is not None + or tuple(row.observed_upload_ids or ()) != claim.observed_upload_ids + or not set(handles) > set(claim.observed_upload_ids)): + raise IntakeCustodyConflict("source_cleanup_observation_mismatch") + await self._require_claim_authority(operation.id) + row.observed_upload_ids = list(handles) + await self._session.flush() diff --git a/backend/app/modules/artifacts/intake/cleanup_execution.py b/backend/app/modules/artifacts/intake/cleanup_execution.py index 52383f703..95edf6d1e 100644 --- a/backend/app/modules/artifacts/intake/cleanup_execution.py +++ b/backend/app/modules/artifacts/intake/cleanup_execution.py @@ -52,6 +52,12 @@ async def run(self, operation_id: UUID, claim_id: UUID) -> None: observed = await self._provider.remove(claim.source, upload) if type(observed) is not SubmissionSourceRemoval or observed.source != expected: raise IntakeCustodyConflict("source_cleanup_observation_mismatch") + if observed.observed_upload_ids: + if observed.observed_source is not None or not isinstance(claim.source, UnsealedSubmissionSource): + raise IntakeCustodyConflict("source_cleanup_observation_mismatch") + async with self._root() as owner: + await owner.record_upload_observation(claim, observed.observed_upload_ids) + raise IntakeCustodyConflict("source_cleanup_upload_observed") if observed.observed_source is not None: if claim.observed_source is not None or not isinstance(claim.source, UnsealedSubmissionSource): raise IntakeCustodyConflict("source_cleanup_observation_mismatch") diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py index 40ffe09aa..3817ca29e 100644 --- a/backend/app/modules/artifacts/intake/models.py +++ b/backend/app/modules/artifacts/intake/models.py @@ -177,6 +177,9 @@ class SubmissionSourceCleanupClaim(Base): CheckConstraint("jsonb_typeof(source)='object'", name="source_shape"), CheckConstraint("(observed_source is null and observed_at is null) or " "(jsonb_typeof(observed_source)='object' and observed_at is not null)", name="observed_shape"), + CheckConstraint("observed_upload_ids is null or (jsonb_typeof(observed_upload_ids)='array' " + "and jsonb_array_length(observed_upload_ids) between 1 and 100 " + "and observed_source is null)", name="observed_upload_shape"), CheckConstraint("(get_byte(uuid_send(claim_id),6)>>4)=7 and (get_byte(uuid_send(claim_id),8)&192)=128", name="claim_uuid7"), Index("ix_source_cleanup_pending", "lease_expires_at", postgresql_where=text("confirmed_at is null")), @@ -190,6 +193,7 @@ class SubmissionSourceCleanupClaim(Base): lease_expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) observed_source: Mapped[dict | None] = mapped_column(JSONB(none_as_null=True)) observed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + observed_upload_ids: Mapped[list[str] | None] = mapped_column(JSONB(none_as_null=True)) confirmed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) claim_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) confirmation_decision_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) diff --git a/backend/tests/artifacts/test_source_cleanup_minio.py b/backend/tests/artifacts/test_source_cleanup_minio.py index cfe7b9a12..909c2e0b8 100644 --- a/backend/tests/artifacts/test_source_cleanup_minio.py +++ b/backend/tests/artifacts/test_source_cleanup_minio.py @@ -1,27 +1,45 @@ """Real PostgreSQL charge custody across uncertain MinIO partial-upload cleanup.""" from datetime import timedelta +from dataclasses import replace +import json from types import SimpleNamespace import pytest from sqlalchemy import text +from sqlalchemy.exc import DBAPIError from app.adapters.artifacts import submission_source_cleanup_execution from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup from app.core.identifiers import new_record_id from app.interfaces.artifacts import ArtifactStoreUnavailableError from app.modules.actors.api import ServiceIdentity +from app.modules.artifacts.intake.repository import IntakeCustodyConflict from tests.artifacts.test_submission_intake_admission import ( admission_intake as admission_intake, admin_access as admin_access, auth_database_env as auth_database_env, clear_settings_cache as clear_settings_cache, rsa_signing_material as rsa_signing_material, signed_access as signed_access, admit_new, ) from tests.artifacts.test_submission_intake_custody import repository -from tests.artifacts.test_submission_source_cleanup import age_fixture +from tests.artifacts.test_submission_source_cleanup import age_fixture, owner from tests.checkers.execution.support import provision_post_submit_service +async def expire_cleanup_claim(f, operation): + """Prepare only historical lease timestamps in the isolated test database.""" + engine = f.factory.kw["bind"] + assert engine.url.database.startswith("workstream_test_") + async with engine.begin() as connection: + await connection.execute(text("ALTER TABLE submission_source_cleanup_claims DISABLE TRIGGER submission_source_cleanup_guard")) + await connection.execute(text("UPDATE submission_source_cleanup_claims SET " + "claimed_at=claimed_at-interval '2 minutes',lease_expires_at=lease_expires_at-interval '2 minutes' " + "WHERE operation_id=:id"), {"id": operation}) + await connection.execute(text("SET CONSTRAINTS ALL IMMEDIATE")) + await connection.execute(text("ALTER TABLE submission_source_cleanup_claims ENABLE TRIGGER submission_source_cleanup_guard")) + + @pytest.mark.parametrize("admission_intake", ["minio"], indirect=True) -async def test_partial_upload_charge_survives_lost_abort_then_releases_once(admission_intake, monkeypatch): +@pytest.mark.parametrize("missing_handle", [False, True]) +async def test_partial_upload_charge_survives_lost_abort_then_releases_once(admission_intake, monkeypatch, missing_handle): f = admission_intake await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP) foreground = await admit_new(f) @@ -34,16 +52,30 @@ async def test_partial_upload_charge_survives_lost_abort_then_releases_once(admi intent = await repository(session).prepare_upload(operation, foreground.lease_id, foreground.generation, part_bytes=5 * 1024**2, idle_timeout_seconds=20.0) upload = await store.begin_source_upload(intent) - async with f.factory.begin() as session: - await repository(session).record_upload(operation, foreground.lease_id, foreground.generation, upload=upload) - await store.upload_source_part(upload, 1, b"interrupted ZIP") + handles = [upload] + if missing_handle: + # Reconcile multiple handles left by an older implicit SDK retry. + handles.append(await store.begin_source_upload(intent)) + handle_ids = sorted(item.provider_upload_id for item in handles) + if not missing_handle: + async with f.factory.begin() as session: + await repository(session).record_upload(operation, foreground.lease_id, foreground.generation, upload=upload) + await store.upload_source_part(upload, 1, b"interrupted ZIP") async with f.factory.begin() as session: await repository(session).terminalize(operation, foreground.lease_id, foreground.generation, state="failed", failure_code="upload_interrupted") await age_fixture(SimpleNamespace(engine=f.factory.kw["bind"]), operation, preserve_upload_deadline=True) abort = cleanup_store.request_source_abort + aborted = [] async def lose_acknowledgment(target): + if missing_handle: + async with f.factory() as session: + assert await session.scalar(text("SELECT observed_upload_ids FROM submission_source_cleanup_claims " + "WHERE operation_id=:id"), {"id": operation}) == handle_ids + assert await session.scalar(text("SELECT public.source_cleanup_authority_valid(c,'claim') " + "FROM submission_source_cleanup_claims c WHERE operation_id=:id"), {"id": operation}) is True + aborted.append(target.provider_upload_id) await abort(target) raise ArtifactStoreUnavailableError("abort acknowledgment lost") @@ -51,6 +83,42 @@ async def lose_acknowledgment(target): execution = submission_source_cleanup_execution(sessions=f.factory, provider=cleanup, lease_duration=timedelta(seconds=60)) claim_id = new_record_id() + if missing_handle: + async with f.factory.begin() as session: + await owner(session).claim(operation, claim_id, lease_duration=timedelta(seconds=60)) + for invalid in ([], [handle_ids[0], handle_ids[0]], list(reversed(handle_ids))): + with pytest.raises(DBAPIError, match="canonical growth"): + async with f.factory.begin() as session: + await session.execute(text("UPDATE submission_source_cleanup_claims " + "SET observed_upload_ids=CAST(:handles AS jsonb) WHERE operation_id=:id"), + {"id": operation, "handles": json.dumps(invalid)}) + with pytest.raises(IntakeCustodyConflict, match="upload_observed"): + await execution.run(operation, claim_id) + assert aborted == [] + assert await store.source_upload_parts_absent(upload) is False + with pytest.raises(IntakeCustodyConflict, match="authority_unavailable"): + await execution.run(operation, claim_id) + await expire_cleanup_claim(f, operation) + claim_id = new_record_id() + async with f.factory.begin() as session: + current = await owner(session).claim(operation, claim_id, lease_duration=timedelta(seconds=60)) + with pytest.raises(DBAPIError, match="canonical growth"): + async with f.factory.begin() as session: + await session.execute(text("UPDATE submission_source_cleanup_claims " + "SET observed_upload_ids=CAST(:handles AS jsonb) WHERE operation_id=:id"), + {"id": operation, "handles": json.dumps(handle_ids[:1])}) + with pytest.raises(IntakeCustodyConflict, match="cleanup_stale"): + async with f.factory.begin() as session: + await owner(session).upload_for_claim(replace(current, observed_upload_ids=tuple(handle_ids[:1]))) + # A later discovered handle enlarges custody, not the authority of + # an already issued claim. Nothing is aborted under the old target. + handles.append(await store.begin_source_upload(intent)) + handle_ids = sorted(item.provider_upload_id for item in handles) + with pytest.raises(IntakeCustodyConflict, match="upload_observed"): + await execution.run(operation, claim_id) + assert aborted == [] + await expire_cleanup_claim(f, operation) + claim_id = new_record_id() with pytest.raises(ArtifactStoreUnavailableError, match="acknowledgment lost"): await execution.run(operation, claim_id) async with f.factory() as session: @@ -68,7 +136,13 @@ async def lose_acknowledgment(target): "FROM submission_source_cleanup_claims c WHERE operation_id=:id"), {"id": operation}) is True assert await session.scalar(text("SELECT provider_generation FROM submission_intake_operations " "WHERE id=:id"), {"id": operation}) is None - assert await store.source_upload_parts_absent(upload) is True + if missing_handle: + assert await session.scalar(text("SELECT provider_upload_id FROM submission_source_upload_receipts " + "WHERE operation_id=:id"), {"id": operation}) is None + assert await session.scalar(text("SELECT generation FROM submission_source_cleanup_claims " + "WHERE operation_id=:id"), {"id": operation}) == 3 + for target in handles: + assert await store.source_upload_parts_absent(target) is True finally: cleanup.close() store.close() diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index f319eb268..3b52a2826 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "998744d3ca52bd4e13b463695f5ac4c05e24b07fdfa8f985b4816a14a21b210b" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "fb82d1094faebbf8c2ae35a71987772af7cd2519944423b5ab91a6902e3c3580" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/migrations/test_unsealed_source_cleanup.py b/backend/tests/migrations/test_unsealed_source_cleanup.py index 1db5dd66c..41df7678c 100644 --- a/backend/tests/migrations/test_unsealed_source_cleanup.py +++ b/backend/tests/migrations/test_unsealed_source_cleanup.py @@ -1,6 +1,7 @@ """Upgrade real predecessor cleanup claims without rewriting their authority.""" import asyncio from datetime import timedelta +from uuid import UUID import pytest from alembic import command @@ -10,7 +11,9 @@ from app.db import session as db_session from app.modules.actors.api import ServiceIdentity from app.modules.artifacts.intake.models import SubmissionIntakeOperation -from tests.artifacts.test_submission_intake_custody import intake as intake, capacity_limits as capacity_limits, repository +from tests.artifacts.test_submission_intake_custody import ( + intake as intake, capacity_limits as capacity_limits, repository, reserve, record_eof, SHA, +) from tests.artifacts.test_submission_source_cleanup import age_fixture, cleanup_decision, owner, terminal_source from tests.checkers.execution.support import provision_post_submit_service from tests.conftest import _drop_test_database_schema @@ -19,22 +22,22 @@ pytestmark = pytest.mark.postgres_schema_contract -@pytest.fixture(autouse=True) -async def predecessor_schema(isolated_database_env, migration_lock): +@pytest.fixture(autouse=True, params=["0087_source_cleanup_candidates", "0088_unsealed_source_cleanup"]) +async def predecessor_schema(isolated_database_env, migration_lock, request): """Build the actual predecessor before the ordinary intake fixture runs.""" with migration_lock(): await db_session.dispose_engine() await _drop_test_database_schema(isolated_database_env) try: - await asyncio.to_thread(command.upgrade, _config(), "0087_source_cleanup_candidates") - yield + await asyncio.to_thread(command.upgrade, _config(), request.param) + yield request.param finally: await db_session.dispose_engine() await _drop_test_database_schema(isolated_database_env) await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) -async def retained_rows(factory, *, upgraded=False): +async def retained_rows(factory, *, new_columns=()): """Compare every retained fact in the owners touched by this migration.""" tables = ( "submission_intake_operations", "submission_source_upload_receipts", @@ -44,16 +47,16 @@ async def retained_rows(factory, *, upgraded=False): result = {} for table in tables: value = "to_jsonb(r)" - if upgraded and table == "submission_source_cleanup_claims": + if new_columns and table == "submission_source_cleanup_claims": assert await session.scalar(text("SELECT count(*) FROM submission_source_cleanup_claims " - "WHERE observed_source IS NOT NULL OR observed_at IS NOT NULL")) == 0 - value += "-ARRAY['observed_source','observed_at']" + "WHERE " + " OR ".join(f"{column} IS NOT NULL" for column in new_columns))) == 0 + value += "-ARRAY[" + ",".join(f"'{column}'" for column in new_columns) + "]" result[table] = await session.scalar(text( f"SELECT jsonb_agg({value} ORDER BY to_jsonb(r)::text) FROM {table} r")) return result -async def test_upgrade_preserves_sealed_claims_charges_and_audit_decisions(intake): +async def test_upgrade_preserves_sealed_claims_charges_and_audit_decisions(intake, predecessor_schema): await provision_post_submit_service(intake.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP) claims = [] for confirmed in (False, True): @@ -78,17 +81,79 @@ async def test_upgrade_preserves_sealed_claims_charges_and_audit_decisions(intak {"id": operation, "decision": confirmation}) await session.execute(text("UPDATE submission_source_charges SET state='released',accounted_bytes=0 " "WHERE operation_id=:id"), {"id": operation}) - claims.append((operation, claim_id, confirmed)) + claims.append((operation, claim_id, confirmed, None)) + if predecessor_schema == "0088_unsealed_source_cleanup": + claims.append(await observed_version_claim(intake)) before = await retained_rows(intake.factory) await intake.engine.dispose() await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) - assert await retained_rows(intake.factory, upgraded=True) == before - for operation, claim_id, confirmed in claims: + columns = ("observed_upload_ids",) if predecessor_schema == "0088_unsealed_source_cleanup" else ( + "observed_source", "observed_at", "observed_upload_ids") + assert await retained_rows(intake.factory, new_columns=columns) == before + for operation, claim_id, confirmed, observed in claims: async with intake.factory.begin() as session: claim = await owner(session).claim(operation, claim_id, lease_duration=timedelta(minutes=5)) assert claim.confirmed is confirmed - assert claim.observed_source is None + assert claim.observed_source == observed + assert claim.observed_upload_ids == () await owner(session).confirm(claim, object_absent=True, writes_settled=True, parts_absent=True) async with intake.factory() as session: assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": operation}) == 0 + + +async def observed_version_claim(intake): + """Create an actual 0088 claim whose audit binds a recovered completed version.""" + from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupAuthorityFacts, cleanup_target_sha256 + from app.modules.artifacts.api.submission_intake import SealedSubmissionSource + from app.modules.artifacts.authorization import PreparedSubmissionSourceCleanupAuthorization + + async with intake.factory.begin() as session: + row = await reserve(intake, session) + operation, lease = UUID(row.id), UUID(row.lease_id) + async with intake.factory.begin() as session: + await record_eof(session, operation, lease, 1, raw_sha256=SHA, raw_byte_count=100) + await repository(session).terminalize(operation, lease, 1, state="failed", failure_code="upload_interrupted") + await age_fixture(intake, operation) + + async def decision(session, source, claim_id, generation, observed=None): + row = await session.get(SubmissionIntakeOperation, str(operation)) + facts = SubmissionSourceCleanupAuthorityFacts(operation_id=operation, project_id=UUID(row.project_id), + task_id=UUID(row.task_id), source_sha256=cleanup_target_sha256(source, observed), + claim_id=claim_id, claim_generation=generation, phase="claim") + authority = PreparedSubmissionSourceCleanupAuthorization(session, + request_id=new_record_id(), correlation_id=new_record_id()) + prepared = await authority.prepare(facts=facts, idempotency_key=claim_id) + return await authority.consume(prepared_authorization=prepared, facts=facts) + + claim_id = new_record_id() + async with intake.factory.begin() as session: + row = await session.get(SubmissionIntakeOperation, str(operation)) + source = await owner(session)._target(row) + observed = SealedSubmissionSource(location=source.location, provider_generation="retained-observed-version", + raw_sha256=SHA, raw_byte_count=100, sealed_upload_fence=1) + authorization = await decision(session, source, claim_id, 1) + await session.execute(text("INSERT INTO submission_source_cleanup_claims " + "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at,claim_decision_id) " + "VALUES (:id,:claim,1,CAST(:source AS jsonb),statement_timestamp()," + "statement_timestamp()+interval '5 minutes',:decision)"), + {"id": operation, "claim": claim_id, "source": source.model_dump_json(), "decision": authorization}) + await session.execute(text("UPDATE submission_source_cleanup_claims " + "SET observed_source=CAST(:source AS jsonb),observed_at=clock_timestamp() WHERE operation_id=:id"), + {"id": operation, "source": observed.model_dump_json()}) + assert intake.engine.url.database.startswith("workstream_test_") + async with intake.engine.begin() as connection: + await connection.execute(text("ALTER TABLE submission_source_cleanup_claims DISABLE TRIGGER submission_source_cleanup_guard")) + await connection.execute(text("UPDATE submission_source_cleanup_claims SET observed_at=observed_at-interval '3 hours', " + "claimed_at=claimed_at-interval '3 hours',lease_expires_at=lease_expires_at-interval '3 hours' WHERE operation_id=:id"), + {"id": operation}) + await connection.execute(text("SET CONSTRAINTS ALL IMMEDIATE")) + await connection.execute(text("ALTER TABLE submission_source_cleanup_claims ENABLE TRIGGER submission_source_cleanup_guard")) + claim_id = new_record_id() + async with intake.factory.begin() as session: + authorization = await decision(session, source, claim_id, 2, observed) + await session.execute(text("UPDATE submission_source_cleanup_claims SET claim_id=:claim,generation=2, " + "claimed_at=statement_timestamp(),lease_expires_at=statement_timestamp()+interval '5 minutes', " + "claim_decision_id=:decision WHERE operation_id=:id"), + {"id": operation, "claim": claim_id, "decision": authorization}) + return operation, claim_id, False, observed diff --git a/backend/tests/test_s3_artifact_store.py b/backend/tests/test_s3_artifact_store.py index c7115bd2c..5077cc361 100644 --- a/backend/tests/test_s3_artifact_store.py +++ b/backend/tests/test_s3_artifact_store.py @@ -1374,19 +1374,21 @@ async def interrupted_abort(target): @pytest.mark.asyncio -@pytest.mark.parametrize("obligation", ["unknown_begin", "surviving_parts", "version", "delete_marker"]) +@pytest.mark.parametrize("obligation", ["no_begin", "unknown_begin", "inventory_bound", "surviving_parts", "version", "delete_marker"]) async def test_unsealed_cleanup_preserves_unresolved_obligations(source_store, monkeypatch, obligation): from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup from app.modules.artifacts.api.submission_cleanup import UnsealedSubmissionSource, UnsealedSourceCleanupInput intent = source_intent(source_store) - upload = await source_store.begin_source_upload(intent) - if obligation != "unknown_begin": + upload = None if obligation == "no_begin" else await source_store.begin_source_upload(intent) + missing_handle = obligation in {"no_begin", "unknown_begin", "inventory_bound"} + if not missing_handle: await source_store.upload_source_part(upload, 1, b"unfinished") value = UnsealedSourceCleanupInput( source=UnsealedSubmissionSource(location=intent.location, upload_fence=intent.upload_fence, - provider_upload_id=None if obligation == "unknown_begin" else upload.provider_upload_id), - intent=intent, upload=None if obligation == "unknown_begin" else upload, completion=None, + provider_upload_id=None if missing_handle else upload.provider_upload_id), + intent=intent, upload=None if missing_handle else upload, completion=None, + observed_upload_ids=tuple(f"retained-{number:03d}" for number in range(100)) if obligation == "inventory_bound" else (), ) cleanup_store = initialize_minio_store(private_prefix=source_store._private_prefix) try: @@ -1403,9 +1405,20 @@ async def acknowledged_without_settlement(_upload): if obligation == "delete_marker": await client.delete_object(Bucket=MINIO_BUCKET, Key=key) await client.delete_object(Bucket=MINIO_BUCKET, Key=key, VersionId=seeded["VersionId"]) + if obligation == "inventory_bound": + with pytest.raises(ArtifactOperationConflictError, match="inventory exceeded bound"): + await S3SubmissionSourceCleanup(cleanup_store).remove_unsealed(value) + assert await source_store.source_upload_parts_absent(upload) is False + return result = await S3SubmissionSourceCleanup(cleanup_store).remove_unsealed(value) assert result.writes_settled is False assert result.observed_source is None + if obligation == "no_begin": + assert result.observed_upload_ids == () + assert result.object_absent is result.parts_absent is False + if obligation == "unknown_begin": + assert result.observed_upload_ids == (upload.provider_upload_id,) + assert await source_store.source_upload_parts_absent(upload) is False if obligation == "surviving_parts": assert result.parts_absent is False if obligation in {"version", "delete_marker"}: @@ -1414,7 +1427,8 @@ async def acknowledged_without_settlement(_upload): assert len(retained.get("Versions", [])) == (0 if obligation == "delete_marker" else 1) assert len(retained.get("DeleteMarkers", [])) == (1 if obligation == "delete_marker" else 0) finally: - await source_store.request_source_abort(upload) + if upload is not None: + await source_store.request_source_abort(upload) cleanup_store.close() diff --git a/docs/operations_artifact_storage.md b/docs/operations_artifact_storage.md index 172992492..67e76957e 100644 --- a/docs/operations_artifact_storage.md +++ b/docs/operations_artifact_storage.md @@ -310,6 +310,10 @@ fresh aged cleanup claim before deletion. An abort acknowledgment alone does not release storage charges. The S3 data-plane SDK makes one total attempt per call; durable owners control observation and retries. -Uncertain remote initiation without a recorded handle and genuine orphan -reconciliation remain unfinished requirements. Do not treat this schedule as -proof that every abandoned byte is reclaimed. +For remote initiation whose response was lost, discovered multipart IDs are +saved on the existing cleanup claim before abort. A fresh authorization binds +that retained set; newly discovered IDs invalidate the previous authorization. +Retries check every retained handle even when discovery no longer lists it. +Empty discovery cannot prove that an uncertain initiation never happened, so +that case remains charged. Genuine orphan reconciliation remains unfinished. +Do not treat this schedule as proof that every abandoned byte is reclaimed. From e858c5e8271e0f95881ee5c5a24d62e769307ebf Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 18:06:54 +0100 Subject: [PATCH 234/513] Repair cleanup test collection and CI ownership inventory --- .ci/behavior-ownership/partition.v1.json | 14 +++++++- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 35 +++++++++++++++++++ backend/scripts/behavior_ownership.py | 3 ++ backend/scripts/test_lane_catalogue.py | 2 +- ...test_unsealed_source_cleanup_migration.py} | 0 backend/tests/test_behavior_ownership.py | 3 ++ backend/tests/test_ci_lane_catalogue.py | 4 +-- 7 files changed, 57 insertions(+), 4 deletions(-) rename backend/tests/migrations/{test_unsealed_source_cleanup.py => test_unsealed_source_cleanup_migration.py} (100%) diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 36e2f7306..88fb882b5 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -32,6 +32,10 @@ "group": "artifacts", "target": "backend/app/adapters/artifacts/source_cleanup.py" }, + { + "group": "artifacts", + "target": "backend/app/adapters/artifacts/source_cleanup_worker.py" + }, { "group": "artifacts", "target": "backend/app/adapters/artifacts/trusted_intake.py" @@ -2612,6 +2616,14 @@ "group": "shared", "target": "backend/app/workers/revision_recovery.py" }, + { + "group": "shared", + "target": "backend/app/workers/source_cleanup.py" + }, + { + "group": "shared", + "target": "backend/app/workers/source_cleanup_topology.py" + }, { "group": "lifecycle", "target": "backend/app/workers/task_settings.py" @@ -2773,7 +2785,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "243abe36c015d6d06b7c114de7cb0c1d9104b69b75a4b3c059b114fab5b49880", + "authority_digest": "09e7f0ea136d434065582f1d4709092a27ad1b6f883768f26f055da52ffae5c8", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0ca6f6ec1..a8bd75593 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8234,3 +8234,38 @@ The measured 0089 schema fingerprint is `fb82d1094faebbf8c2ae35a71987772af7cd2519944423b5ab91a6902e3c3580`. Scoped Ruff passed. Native AWS, genuine orphan reconciliation and full-system qualification are not established by these focused proofs. + +Clean 09701e433 scoped review: architecture/security/docs PASS and QA/test-delta +PASS WITH LOW RISKS. Independent early-abort mutation failed the exact +missing-handle test because the cross-session durable handle set was NULL +(`/tmp/submission-observed-before-abort-qa-mutant.log/.json`, expected failure +51.67s, 0089, complete cleanup). Structure, record, links and stale-doc gates +passed. This closes the bounded implementation review, not the full goal. + +CI repair scope: a46c317a2 hosted preflight fails partition_target_mismatch; +full collection fails on identical artifact/migration test basenames. Reproduced +locally in `/tmp/submission-cleanup-partition-before.log` and +`/tmp/submission-cleanup-collection-before.log`. Rename only the migration test +and update its lane selector; add exactly the three existing cleanup modules to +the current submission partition allowance and canonical partition, preserving +its protected base and every prior target. Update the existing exact-additions +negative test. Allowed files: that migration test, lane catalogue, +behavior_ownership.py, partition.v1.json, test_behavior_ownership.py and this +record. No workflow, skip, threshold or assertion weakening. Acceptance: full +collection succeeds, partition validates against origin/main, arbitrary neighbor +additions still fail and existing migration tests retain selection. Risk: +CI selection; focused CI-integrity and QA/test-delta review required. + +Affected CI scope also includes test_ci_lane_catalogue.py: the existing family +fingerprint predates five intentionally added shared cleanup test modules (four +artifact controls and the cleanup migration). Reconcile its exact count/hash, +without moving any existing test between families. Preserve negative controls. + +CI repair verification: exact partition and lane catalogue controls passed +61 tests in 14.26s (`/tmp/submission-cleanup-ci-repair-tests-v2.log`), including +refusal of unapproved additions/removals. Behavior ownership validation passed +against origin/main (`/tmp/submission-cleanup-partition-after-v2.log`). The +initial system-Python validation's secondary stale_catalogue_test error came +from local plugin imports; no catalogue record was changed to suppress it. +Ruff, Commitrail and whitespace checks passed. Full collection is checked +separately; collection success is not execution of the full backend suite. diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 73788c7f8..eb3dab458 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -940,6 +940,9 @@ "backend/app/modules/artifacts/intake/foreground_command.py", "backend/app/api/submission_intake.py", "backend/app/adapters/artifacts/source_cleanup.py", + "backend/app/adapters/artifacts/source_cleanup_worker.py", + "backend/app/workers/source_cleanup.py", + "backend/app/workers/source_cleanup_topology.py", "backend/app/modules/artifacts/api/submission_cleanup.py", "backend/app/modules/artifacts/api/submission_finalization.py", "backend/app/modules/artifacts/api/submission_manifest.py", diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 091e8afce..eb7084081 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -193,7 +193,7 @@ class TestLane: "tests/migrations/test_task_queue_authority.py", "tests/migrations/test_claim_starts_work.py", "tests/migrations/test_source_pre_cutover.py", - "tests/migrations/test_unsealed_source_cleanup.py", + "tests/migrations/test_unsealed_source_cleanup_migration.py", "tests/migrations/test_compensation_unit_create_migration.py", "tests/migrations/test_task_read_authority.py", "tests/migrations/test_task_context_authority.py", diff --git a/backend/tests/migrations/test_unsealed_source_cleanup.py b/backend/tests/migrations/test_unsealed_source_cleanup_migration.py similarity index 100% rename from backend/tests/migrations/test_unsealed_source_cleanup.py rename to backend/tests/migrations/test_unsealed_source_cleanup_migration.py diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index 4ac38bca1..1274153d5 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2768,6 +2768,9 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ "backend/app/api/submission_intake.py", target, "backend/app/modules/artifacts/intake/models.py", "backend/app/adapters/artifacts/source_cleanup.py", + "backend/app/adapters/artifacts/source_cleanup_worker.py", + "backend/app/workers/source_cleanup.py", + "backend/app/workers/source_cleanup_topology.py", "backend/app/modules/artifacts/api/submission_cleanup.py", "backend/app/modules/artifacts/api/submission_finalization.py", "backend/app/modules/artifacts/api/submission_manifest.py", diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 10c88dcdc..136450dcb 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -320,8 +320,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 278, - "76a24837591d210de2d08cd6fd0443693cd2cb6057bb1a2c093b7540f9378797", + 283, + "3850ea17ffaa65b0e806a37efecbdf13c1cb37e5d675cc5fbdbea799244befec", ), "project": ( 258, From 6be0767c63daab6d137cb88b7fd5817d7267c779 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Mon, 23 Nov 2026 18:09:30 +0100 Subject: [PATCH 235/513] Record cleanup and CI repair review evidence --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a8bd75593..6f5f7e5a4 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8269,3 +8269,16 @@ initial system-Python validation's secondary stale_catalogue_test error came from local plugin imports; no catalogue record was changed to suppress it. Ruff, Commitrail and whitespace checks passed. Full collection is checked separately; collection success is not execution of the full backend suite. + +Clean e858c5e82 CI-integrity/QA/test-delta PASS WITH LOW RISKS. Independent +allowance-expansion mutation is rejected by the existing exact-set test. The +migration rename is byte-identical; exactly five shared test additions account +for the fingerprint delta, with no family moves. Affected pair collection passed +12 tests in 18.82s (`/tmp/submission-cleanup-paired-collection-after.log`, exit 0). + +Full local collection is NOT passed: one run printed 12,597 collected tests but +exited 139; a diagnostic run reproduced SIGSEGV in pytest fixture ordering +(`/tmp/submission-cleanup-collection-after-v2.log` and +`/tmp/submission-cleanup-collection-diagnostic.log`, Python 3.12.3). The cause is +not established. Do not substitute the paired collection or focused execution +for full-head qualification. Hosted CI must run on the repaired pushed head. From fb041d35cd3425c73a0103d19dfbedd9a0f60105 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 10:48:58 +0100 Subject: [PATCH 236/513] Keep app-host finalization delivery compatible with scoped event exclusions --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 22 ++++++++++++++ backend/app/adapters/outbox/__init__.py | 2 +- .../tests/outbox/test_worker_postgresql.py | 30 +++++++++++-------- 3 files changed, 41 insertions(+), 13 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 71e03a9e6..1714126ab 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8316,3 +8316,25 @@ lacked the repository external-services package. Installing that local package without dependency changes repaired the actual subprocess environment; the exact test passed with both subcases (`/tmp/submission-main-hosted-loader-v3.log`). No test assertion or deployment process was weakened for that environment issue. + +Merge review found OUTBOX-MERGE-01 (High): app-profile POST exclusions were +passed to the finalization-only registry, so construction raised before T5. +Both reviewers reproduced the same composition failure. Repair intersects the +exclusions with the already selected registry and extends the existing real +PostgreSQL finalization-worker isolation test across app/single-host profiles. +Retain the existing app-host POST deferral/completion test as the general-worker +control. Allowed repair: outbox composition, that worker test and this record; +no delivery guard relaxation or new registry path. + +OUTBOX-MERGE-01 repair passed all five real PostgreSQL controls in 27.63s +(`/tmp/submission-main-app-finalization.log/.json`): the finalization worker +rejects both pending and already-claimed POST events under both app and +single-host profiles; the existing app general-worker case retains POST work +while allowing completion delivery. Constructor exclusion validation is intact. +The two retained-upgrade nodes passed in 231.72s: +`tests/test_alembic.py::test_retiring_provider_proof_drops_only_its_tables_and_preserves_artifacts` +and `tests/migrations/test_unsealed_source_cleanup_migration.py::test_upgrade_preserves_sealed_claims_charges_and_audit_decisions[0088_unsealed_source_cleanup]`. +Metadata confirms 0090 and complete isolated resource cleanup. Structure, +protected module boundary, record/link, stale-artifact-contract and Ruff gates +passed on the merge candidate. The repair changes only the exclusion selector +and extends the existing integration test. diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py index f21a889cb..d79b02bdc 100644 --- a/backend/app/adapters/outbox/__init__.py +++ b/backend/app/adapters/outbox/__init__.py @@ -190,7 +190,7 @@ def production_outbox_delivery(session_factory, *, finalization_worker: bool | N registry=registry, options=DeliveryOptions(), event_options={key: value for key, value in event_options.items() if key in registry.keys}, excluded_events=( - frozenset({(REQUEST_EVENT, 1), (RECONCILIATION_EVENT, 1)}) + frozenset({(REQUEST_EVENT, 1), (RECONCILIATION_EVENT, 1)}).intersection(registry.keys) if get_settings().hosted_profile == "app" else frozenset() ), diff --git a/backend/tests/outbox/test_worker_postgresql.py b/backend/tests/outbox/test_worker_postgresql.py index 59a746668..5280eeb8f 100644 --- a/backend/tests/outbox/test_worker_postgresql.py +++ b/backend/tests/outbox/test_worker_postgresql.py @@ -401,7 +401,8 @@ def test_delivery_task_has_independent_hard_limit(worker): @pytest.mark.parametrize("expired", [False, True]) -async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery_harness, expired): +@pytest.mark.parametrize("profile", ["single-host", "app"]) +async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery_harness, monkeypatch, expired, profile): from app.adapters.outbox import production_outbox_delivery h = delivery_harness kind = "PostSubmissionEvaluationRequested" @@ -411,14 +412,19 @@ async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery assert await owner.claim(event.event_id, h.project, "post-worker") is not None async with h.factory() as session: await session.execute(text("select pg_sleep(3.05)")) - finalization = production_outbox_delivery(h.factory, finalization_worker=True) - assert finalization._registry.keys == (("SubmissionFinalizationRequested", 1), ("SubmissionFinalizationRecoveryRequested", 1)) - assert await finalization.deliver(event.event_id, h.project, "wrong-worker", registered_only=True) is None - async with h.factory() as session: - stored = await session.get(OutboxEvent, event.event_id) - assert stored.delivery_state == ("claimed" if expired else "pending") - attempts = list(await session.scalars(select(OutboxDeliveryAttempt))) - assert len(attempts) == int(expired) - if expired: - assert attempts[0].stage == "claimed" - assert h.handled == [] + monkeypatch.setenv("WORKSTREAM_HOSTED_PROFILE", profile) + get_settings.cache_clear() + try: + finalization = production_outbox_delivery(h.factory, finalization_worker=True) + assert finalization._registry.keys == (("SubmissionFinalizationRequested", 1), ("SubmissionFinalizationRecoveryRequested", 1)) + assert await finalization.deliver(event.event_id, h.project, "wrong-worker", registered_only=True) is None + async with h.factory() as session: + stored = await session.get(OutboxEvent, event.event_id) + assert stored.delivery_state == ("claimed" if expired else "pending") + attempts = list(await session.scalars(select(OutboxDeliveryAttempt))) + assert len(attempts) == int(expired) + if expired: + assert attempts[0].stage == "claimed" + assert h.handled == [] + finally: + get_settings.cache_clear() From 43ab8938576179535e4c81895a055ba90ca62e91 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 10:51:01 +0100 Subject: [PATCH 237/513] Record main integration review and parallel runner ownership --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 1714126ab..2911090d8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8338,3 +8338,12 @@ Metadata confirms 0090 and complete isolated resource cleanup. Structure, protected module boundary, record/link, stale-artifact-contract and Ruff gates passed on the merge candidate. The repair changes only the exclusion selector and extends the existing integration test. + +Clean fb041d35c review closure: ARCH/SEC PASS and QA/test-delta PASS WITH LOW +RISKS; OUTBOX-MERGE-01 resolved. Both reviewers verified matching clean targets, +registry intersection and the expanded real PostgreSQL cases. Prior scoped +main-integration review stands. This integrates origin/main d713594eb; it does +not establish separate-runner or full-system readiness. The user's explicitly +requested runner worktree now owns infrastructure plus authenticated remote +PRE/POST execution and removal of shared-host material assumptions. The lead +retains submission lifecycle/cleanup and final integration in PR708. From 0c8b3d47a37727b214e298d5750863cbe1395670 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:03:32 +0100 Subject: [PATCH 238/513] Retire admission-only submission creation path --- .ci/behavior-ownership/partition.v1.json | 22 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 40 +++ backend/app/adapters/tasks/__init__.py | 99 ------- backend/app/api/deps/authorization.py | 45 ---- .../modules/tasks/submission_composition.py | 162 +----------- .../modules/tasks/submission_participants.py | 18 +- .../app/modules/tasks/submission_replay.py | 114 -------- backend/scripts/behavior_ownership.py | 11 +- .../tasks/test_revision_error_mapping.py | 27 -- backend/tests/test_artifact_bindings_db.py | 92 ------- backend/tests/test_behavior_ownership.py | 12 + backend/tests/test_submission_composition.py | 245 +++--------------- 12 files changed, 112 insertions(+), 775 deletions(-) delete mode 100644 backend/app/modules/tasks/submission_replay.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index af4438b18..8302e21b5 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -20,14 +20,6 @@ "group": "artifacts", "target": "backend/app/adapters/artifacts/s3_compatible.py" }, - { - "group": "artifacts", - "target": "backend/app/adapters/artifacts/s3_compatible.py" - }, - { - "group": "artifacts", - "target": "backend/app/adapters/artifacts/s3_compatible.py" - }, { "group": "artifacts", "target": "backend/app/adapters/artifacts/source_cleanup.py" @@ -432,14 +424,6 @@ "group": "shared", "target": "backend/app/interfaces/artifacts.py" }, - { - "group": "shared", - "target": "backend/app/interfaces/artifacts.py" - }, - { - "group": "shared", - "target": "backend/app/interfaces/artifacts.py" - }, { "group": "auth", "target": "backend/app/interfaces/auth.py" @@ -2536,10 +2520,6 @@ "group": "lifecycle", "target": "backend/app/modules/tasks/submission_participants.py" }, - { - "group": "lifecycle", - "target": "backend/app/modules/tasks/submission_replay.py" - }, { "group": "lifecycle", "target": "backend/app/modules/tasks/submitted_bundle.py" @@ -2781,7 +2761,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "2d59facc4e33f68f8b2da6712e6497e91b7cda4c8df13c226842d9841918b084", + "authority_digest": "4e1cb7d1dbc23133efd77854a6c6f5c7ecaee7a75f928845c5b81ca86c20b66c", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2911090d8..113849174 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8347,3 +8347,43 @@ not establish separate-runner or full-system readiness. The user's explicitly requested runner worktree now owns infrastructure plus authenticated remote PRE/POST execution and removal of shared-host material assumptions. The lead retains submission lifecycle/cleanup and final integration in PR708. + + +### Retire admission-only TASK submission entry + +Intent: make accepted intake custody the sole TASK Submission creation entry; +remove the unused admission-only command and HTTP composition. Risk: high +(authorization and transaction sequencing). Allowed files: TASK composition, +participants, replay helper and adapter; authorization HTTP dependency wiring; +affected composition/binding/revision tests; exact module ownership inventory +and this record. Prohibited: retained rows/schema/audit parsers, ART binding +concurrency behavior, accepted-custody guards, runner-owned files, deployment. +Acceptance: no callable admission-only writer; accepted T5 still atomically +creates one Submission, binding and POST dispatch and replays exactly. +Preserve accepted authority closure and invalid ART-result refusal with focused +replacement tests. Old human-entry denial tests are superseded by T1 revoked +admission/replay and T4 revocation tests; finalization uses service custody. +The old DB final-denial test refused before any write; retain real binding +rollback/concurrency proof and exercise current T5 transactional proof instead. +Remove only old-entry revision mapping tests; retain repair/ART mapping and T4 +expiry winner-order coverage. Retained SUBMISSION_CREATE audit parsers stay. +Verification: focused composition, binding, revision, T1/T4/T5 PostgreSQL tests, +Ruff and affected ownership/structure checks. Reviewers: scoped ARCH/SEC and QA +on clean candidate. Human review focus: no bypass of accepted custody or loss +of rollback/replay proof. Same PR708 per explicit user instruction. + +The exact inventory check exposed pre-existing duplicate entries at 43ab89385: +s3_compatible.py and interfaces/artifacts.py each appeared three times with +identical groups. Deduplicate those exact entries and refresh the digest; +retain duplicate rejection and all ownership checks. The removed TASK replay +module is permitted only while all accepted-finalization owners remain. + +Retirement candidate: 24 focused composition/parser/revision checks passed +(12.55s), including replacement accepted-service authority denial, policy +failure closure, and invalid ART result refusal before dispatch. Test-structure +validation and scoped Ruff passed. Ownership suite: 171 cases passed initially; +exact inventory then passed after removing duplicate entries, sorting and +staging the deleted module (inventory intentionally reads the Git index). +The new accepted-owner-required retirement control passed. PostgreSQL receipt +`/tmp/submission-retire-writer.log/.json` is still running at candidate freeze; +no integration success is claimed yet. No schema or retained-data changes. diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py index 9313faf63..1ec716f32 100644 --- a/backend/app/adapters/tasks/__init__.py +++ b/backend/app/adapters/tasks/__init__.py @@ -4,22 +4,14 @@ from app.modules.tasks.api.submitted_bundle import SubmittedBundlePort from app.modules.tasks.api.evaluation_revision import TaskEvaluationRevisionPort from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.exc import IntegrityError from app.core.config import Settings -from app.db.errors import integrity_constraint_name from uuid import UUID from app.modules.artifacts.api import ( SubmissionAdmissionConsumptionPort, SubmissionAdmissionConsumptionRequest, - SubmissionAdmissionConsumptionError, ) from app.modules.tasks.api import ( - SubmissionCreationAuthorizationPort, - SubmissionCreationRequest, - SubmissionCreationResult, - SubmissionCreationAdmissionError, - TaskSubmissionContextUnavailable, TaskSubmissionContextPort, TaskSubmissionContextRequest, ) @@ -32,10 +24,7 @@ from app.modules.tasks.submission_participants import ( SubmissionArtifactAdmissionRequest, SubmissionArtifactAdmissionResult, - SubmissionArtifactReplayRequest, - SubmissionArtifactBindingFacts, ) -from app.modules.artifacts.api.submission_admission import ConsumedSubmissionAdmissionRequest from app.modules.tasks.submission_composition import TaskSubmissionCreationService from app.modules.tasks.assignment_invalidation import AssignmentInvalidationOperation from app.modules.tasks.api.assignment_invalidation import AssignmentInvalidationUnavailable @@ -222,7 +211,6 @@ async def __call__(self, envelope): "TransactionalTaskRevisionExhaustedNoticeHandler", "task_commands", "task_service", - "TransactionalSubmissionCreationCommand", "task_submission_context_port", ) @@ -374,92 +362,6 @@ async def consume( ), ) - async def read_consumed( - self, request: SubmissionArtifactReplayRequest - ) -> SubmissionArtifactBindingFacts: - result = await self._admissions.read_consumed( - ConsumedSubmissionAdmissionRequest( - admission_id=request.admission_id, - project_id=request.project_id, - task_id=request.task_id, - assignment_id=request.assignment_id, - contributor_id=request.contributor_id, - submission_id=request.submission_id, - submission_version=request.submission_version, - packet_sha256=request.packet_sha256, - ) - ) - if ( - result.binding_id is None - or result.material is None - or result.binding_decision_id is None - or result.status != "consumed" - ): - raise RuntimeError("retained admission custody unavailable") - from app.adapters.checkers import selected_submission_evaluation_content - from app.modules.checkers.api.external_policy import ( - validate_stored_external_post_policy, - ) - - selected_post_policy = validate_stored_external_post_policy( - result.selected_post_submit_policy_body - ) - return SubmissionArtifactBindingFacts( - binding_id=result.binding_id, - content_id=result.content_id, - binding_decision_id=result.binding_decision_id, - archive_sha256=result.material.archive_sha256, - byte_count=result.material.archive_byte_count, - selected_evaluation_content=selected_submission_evaluation_content( - request.task_context, selected_post_policy - ), - ) - - -class TransactionalSubmissionCreationCommand: - """Open the sole root transaction and delegate sequencing to TASK.""" - - def __init__( - self, - session: AsyncSession, - *, - authorization: SubmissionCreationAuthorizationPort, - admissions: SubmissionAdmissionConsumptionPort, - settings: Settings, - ) -> None: - self._session = session - self._settings = settings - self._authorization = authorization - self._admissions = admissions - - async def create(self, request: SubmissionCreationRequest) -> SubmissionCreationResult: - if self._session.in_transaction(): - raise RuntimeError("submission composition requires a transaction-free session") - from app.adapters.checkers import evaluation_coordinator - from app.adapters.outbox import outbox_append - - try: - async with self._session.begin(): - return await TaskSubmissionCreationService( - self._session, - contexts=task_service(self._session, settings=self._settings), - submission_contexts=task_submission_context_port(self._session), - authorization=self._authorization, - admissions=_ArtifactAdmissionAdapter(self._admissions), - evaluations=evaluation_coordinator(self._session), - events=outbox_append(self._session), - ).create(request) - except SubmissionAdmissionConsumptionError as exc: - raise SubmissionCreationAdmissionError(exc.code) from exc - except IntegrityError as exc: - name = integrity_constraint_name(exc) - if name == "ck_revision_submission_deadline_expired": - raise TaskSubmissionContextUnavailable("revision_deadline_expired") from exc - if name == "ck_revision_submission_context_changed": - raise TaskSubmissionContextUnavailable("revision_context_changed") from exc - raise - - def assignment_invalidation_targets(session: AsyncSession): """Compose the TASK-owned nonlocking exact-target projection.""" return TaskRepository(session) @@ -735,7 +637,6 @@ def accepted_submission_creation_service(session, *, settings, admissions): from app.adapters.outbox import outbox_append return TaskSubmissionCreationService( session, contexts=task_service(session, settings=settings), - submission_contexts=task_submission_context_port(session), authorization=None, admissions=_ArtifactAdmissionAdapter(admissions), evaluations=evaluation_coordinator(session), events=outbox_append(session), ) diff --git a/backend/app/api/deps/authorization.py b/backend/app/api/deps/authorization.py index 0c753a7f3..08f75ac76 100644 --- a/backend/app/api/deps/authorization.py +++ b/backend/app/api/deps/authorization.py @@ -56,34 +56,6 @@ logger = logging.getLogger(__name__) -def compose_hidden_submission_creation_command( - session: AsyncSession, - context: AuthorizationContext, - *, - request_id: UUID, - correlation_id: UUID, -): - """Wire the sole admission-backed TASK/ART transaction for internal and HTTP callers.""" - from app.adapters.artifacts import submission_admission_consumption_port - from app.adapters.tasks import TransactionalSubmissionCreationCommand - from app.modules.authorization.prepared import ( - PreparedSubmissionCreationAuthorization, - ) - - from app.core.config import get_settings - - return TransactionalSubmissionCreationCommand( - session, - settings=get_settings(), - authorization=PreparedSubmissionCreationAuthorization(session, context), - admissions=submission_admission_consumption_port( - session, - request_id=request_id, - correlation_id=correlation_id, - ), - ) - - def _authorization_context( resolved: ResolvedActor, request_id: UUID, @@ -259,23 +231,6 @@ async def get_authorization_actor_identity( ) -async def get_submission_creation_command( - request: Request, - resolved: Annotated[ResolvedActor, Depends(get_authorization_actor)], - session: Annotated[AsyncSession, Depends(get_db_session)], -): - """Bind the existing atomic writer after actor resolution releases its read root.""" - request_id, correlation_id = (UUID(value) for value in request_ids(request)) - context = _authorization_context(resolved, request_id, correlation_id) - await session.rollback() - return compose_hidden_submission_creation_command( - session, - context, - request_id=request_id, - correlation_id=correlation_id, - ) - - async def resolve_authorization_actor( request: Request, result: AuthVerificationResult, diff --git a/backend/app/modules/tasks/submission_composition.py b/backend/app/modules/tasks/submission_composition.py index 113277edf..20d341ba0 100644 --- a/backend/app/modules/tasks/submission_composition.py +++ b/backend/app/modules/tasks/submission_composition.py @@ -1,4 +1,4 @@ -"""TASK-owned immutable Submission command for the hidden composed transaction.""" +"""TASK-owned immutable Submission creation from accepted intake custody.""" from __future__ import annotations @@ -9,31 +9,20 @@ from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import text, select, func -from sqlalchemy.exc import DBAPIError -from app.modules.projects.api.policy_lineage import RevisionPolicySemantics -from app.modules.tasks.api.submission_context import require_revision_capacity from app.modules.tasks.api import ( - SubmissionCreationAuthorizationPort, - SubmissionCreationAuthorityFacts, - SubmissionCreationPreparationFacts, SubmissionCreationRequest, - SubmissionCreationResult, SubmissionCreationUnavailable, - TaskSubmissionContextRequest, - TaskSubmissionContextPort, ) from app.modules.checkers.api.pre_submit_material import SubmissionPacketView from app.modules.tasks.models import EvidenceItem, Submission from app.modules.tasks.submission_participants import ( SubmissionArtifactAdmissionPort, SubmissionArtifactAdmissionRequest, - SubmissionArtifactAdmissionResult, SubmissionArtifactReplayRequest, + SubmissionArtifactAdmissionResult, ) from app.modules.tasks.submission_dispatch import ( SubmissionDispatch, creation_request_digest, evaluation_request_event, ) -from app.modules.tasks.submission_replay import read_creation_replay -from app.modules.tasks.lifecycle import ensure_allowed_transition from app.modules.checkers.api.execution import EvaluationCoordinationPort from app.modules.checkers.api.selected_post_submit import ( make_selected_post_submit_request, @@ -106,105 +95,23 @@ def __init__( self, session: AsyncSession, *, - authorization: SubmissionCreationAuthorizationPort | None, admissions: SubmissionArtifactAdmissionPort, contexts: TaskService, - submission_contexts: TaskSubmissionContextPort, evaluations: EvaluationCoordinationPort, events: OutboxAppendPort, ) -> None: self._session = session - self._authorization = authorization self._admissions = admissions self._repository = TaskRepository(session) self._contexts = contexts - self._submission_contexts = submission_contexts self._evaluations = evaluations self._events = events - async def create(self, request: SubmissionCreationRequest) -> SubmissionCreationResult: - """Create one Submission without opening or committing a transaction.""" - if self._authorization is None: - raise SubmissionCreationUnavailable("submission creation authority is unavailable") - if not self._session.in_transaction() or self._session.in_nested_transaction(): - raise RuntimeError("submission creation requires one root transaction") - preliminary = SubmissionCreationPreparationFacts( - task_id=request.task_id, - assignment_id=request.assignment_id, - contributor_id=request.contributor_id, - admission_id=request.admission_id, - predecessor_submission_id=request.predecessor_submission_id, - ) - await self._authorization.authorize(preliminary) - connection = await self._session.connection() - if connection.in_nested_transaction(): - raise RuntimeError("submission creation requires one root transaction") - try: - await self._session.execute(text("SELECT pg_catalog.pg_export_snapshot()")) - except DBAPIError as exc: - if getattr(exc.orig, "sqlstate", None) != "25001": - raise - raise RuntimeError("submission creation requires one root transaction") from exc - task = await self._repository.get_task(str(request.task_id), for_update=True) - if task is None: - raise SubmissionCreationUnavailable("submission creation is unavailable") - replay = await read_creation_replay(self._session, task, request) - if replay is not None: - return await self._replay(request, *replay) - context = await self._submission_contexts.lock_submission_context( - TaskSubmissionContextRequest( - task_id=request.task_id, - assignment_id=request.assignment_id, - contributor_id=request.contributor_id, - predecessor_submission_id=request.predecessor_submission_id, - ) - ) - # Version orders every Submission on the task; the revision allowance - # belongs to this assignment and is carried separately in the context. - latest_task_submission = await self._repository.get_latest_submission_for_task(task.id) - version = latest_task_submission.version + 1 if latest_task_submission else 1 - if context.predecessor is not None and version != context.predecessor.version + 1: - raise SubmissionCreationUnavailable("submission creation is unavailable") - submission_id = new_record_id() - final = SubmissionCreationAuthorityFacts( - task_id=preliminary.task_id, - assignment_id=preliminary.assignment_id, - contributor_id=preliminary.contributor_id, - admission_id=preliminary.admission_id, - predecessor_submission_id=preliminary.predecessor_submission_id, - submission_id=submission_id, - submission_version=version, - task_context=context, - ) - prepared_authorization = await self._authorization.prepare(final) - try: - project = await self._contexts._load_locked_task_context(task) - if context.predecessor is not None: - selected_revision = project.facts.activation_receipt.command.revision - require_revision_capacity( - context, project_id=project.facts.project_id, - policy_id=selected_revision.policy_id, - policy_generation=selected_revision.generation, - policy_hash=selected_revision.policy_hash, - max_revision_rounds=RevisionPolicySemantics.model_validate_json( - project.facts.revision_policy.value, - ).max_revision_rounds, - ) - async def authorize_creation(): - return await self._authorization.consume(prepared_authorization, final) - receipt = await self._create_bound_submission( - request, task, context, project, submission_id, version, authorize_creation, - accepted_operation_id=None, - ) - finally: - self._authorization.close(prepared_authorization) - return receipt.result() - async def create_accepted( self, request: SubmissionCreationRequest, *, authority_facts, finalization_authority, snapshot_sha256: str, eligible_status: str, remediation_id: UUID | None, ): - """Continue accepted service custody through the same Submission writer.""" + """Continue accepted service custody through the sole Submission writer.""" from dataclasses import replace from app.modules.tasks.accepted_submission import accepted_submission_context if not self._session.in_transaction() or self._session.in_nested_transaction(): @@ -246,7 +153,7 @@ async def _create_bound_submission( self, request, task, context, project, submission_id, version, authorize_creation, *, accepted_operation_id, ): - """The sole Submission/binding/POST writer for either authorized entry.""" + """Atomically create Submission, binding and POST from accepted custody.""" submission = build_submission( submission_id=str(submission_id), task=task, contribution_policy_version_id=context.submitter_contribution_policy_version_id, @@ -310,11 +217,9 @@ async def _create_bound_submission( policy=selected.policy, **request_fields, ) - if accepted_operation_id is None: - ensure_allowed_transition(task.status, "submitted") - task.status = "submitted" - await self._session.flush() - elif task.status != "evaluation_pending" or task.active_submission_operation_id != str(accepted_operation_id): + if (not isinstance(accepted_operation_id, UUID) + or task.status != "evaluation_pending" + or task.active_submission_operation_id != str(accepted_operation_id)): raise SubmissionCreationUnavailable("accepted task custody differs") reservation = await self._evaluations.reserve_current_evaluation(evaluation) if (reservation.request_id != evaluation.evaluation_request_id @@ -338,8 +243,6 @@ async def _create_bound_submission( event = await self._events.append(evaluation_request_event(receipt)) receipt.evaluation_event_id = event.event_id self._session.add(receipt) - if accepted_operation_id is None: - ensure_allowed_transition(task.status, "evaluation_pending") task.status = "evaluation_pending" await self._session.flush() return receipt @@ -355,54 +258,3 @@ async def read_finalized(self, submission_id: UUID, admission_id: UUID, creation if valid is not True: raise SubmissionCreationUnavailable("finalized dispatch differs") return receipt.result() - - async def _replay(self, request, receipt, context) -> SubmissionCreationResult: - """Verify the complete original commit under fresh authority, without repair.""" - facts = SubmissionCreationAuthorityFacts( - task_id=request.task_id, assignment_id=request.assignment_id, - contributor_id=request.contributor_id, admission_id=request.admission_id, - predecessor_submission_id=request.predecessor_submission_id, - submission_id=UUID(receipt.submission_id), submission_version=receipt.submission_version, - task_context=context, - ) - prepared = await self._authorization.prepare(facts) - try: - await self._authorization.validate_replay(prepared, facts, UUID(receipt.creation_decision_id)) - consumed = await self._admissions.read_consumed(SubmissionArtifactReplayRequest( - admission_id=request.admission_id, project_id=UUID(receipt.project_id), - task_id=request.task_id, assignment_id=request.assignment_id, - contributor_id=request.contributor_id, submission_id=UUID(receipt.submission_id), - submission_version=receipt.submission_version, - packet_sha256=SubmissionPacketView(request.summary, request.contributor_attestation).sha256, - task_context=context, - )) - if (consumed.binding_id, consumed.content_id, consumed.binding_decision_id) != ( - UUID(receipt.artifact_binding_id), UUID(receipt.artifact_content_id), UUID(receipt.binding_decision_id), - ): - raise SubmissionCreationUnavailable("submission creation is unavailable") - stored = await self._evaluations.read_reserved_evaluation( - project_id=UUID(receipt.project_id), task_id=UUID(receipt.task_id), - submission_id=UUID(receipt.submission_id), request_id=UUID(receipt.evaluation_request_id), - ) - evaluation, reservation = stored.request, stored.reservation - if ( - reservation.request_digest != receipt.evaluation_request_digest - or reservation.attempt_id != UUID(receipt.evaluation_attempt_id) - or reservation.result_id != UUID(receipt.evaluation_result_id) - or reservation.evaluation_generation != 1 - or evaluation.assignment_id != UUID(receipt.assignment_id) - or evaluation.submission_version != receipt.submission_version - or evaluation.binding_id != consumed.binding_id - or evaluation.content_id != consumed.content_id - or evaluation.content_sha256 != consumed.archive_sha256 - or evaluation.byte_count != consumed.byte_count - or consumed.selected_evaluation_content is None - or evaluation.project_id != consumed.selected_evaluation_content.project_id - or evaluation.expected_context != consumed.selected_evaluation_content.expected_context - or evaluation.policy != consumed.selected_evaluation_content.policy - ): - raise SubmissionCreationUnavailable("submission creation is unavailable") - await self._events.require_existing(receipt.evaluation_event_id, evaluation_request_event(receipt)) - return receipt.result() - finally: - self._authorization.close(prepared) diff --git a/backend/app/modules/tasks/submission_participants.py b/backend/app/modules/tasks/submission_participants.py index 22a494cc7..39c793078 100644 --- a/backend/app/modules/tasks/submission_participants.py +++ b/backend/app/modules/tasks/submission_participants.py @@ -19,7 +19,7 @@ class SubmissionArtifactAdmissionRequest: task_context: TaskSubmissionContextFacts project_context: ProjectLockedPolicyContextFacts packet: SubmissionPacketView - accepted_operation_id: UUID | None = None + accepted_operation_id: UUID @dataclass(frozen=True, slots=True) @@ -46,22 +46,6 @@ def __post_init__(self) -> None: raise ValueError("external POST admission policy differs") -@dataclass(frozen=True, slots=True) -class SubmissionArtifactReplayRequest: - admission_id: UUID - project_id: UUID - task_id: UUID - assignment_id: UUID - contributor_id: UUID - submission_id: UUID - submission_version: int - packet_sha256: str - task_context: TaskSubmissionContextFacts - - class SubmissionArtifactAdmissionPort(Protocol): async def consume(self, request: SubmissionArtifactAdmissionRequest) -> SubmissionArtifactAdmissionResult: """Consume once and project real material using already-locked policy facts.""" - - async def read_consumed(self, request: SubmissionArtifactReplayRequest) -> SubmissionArtifactBindingFacts: - """Select and reauthorize retained binding custody without new consumption.""" diff --git a/backend/app/modules/tasks/submission_replay.py b/backend/app/modules/tasks/submission_replay.py deleted file mode 100644 index 2ae85693a..000000000 --- a/backend/app/modules/tasks/submission_replay.py +++ /dev/null @@ -1,114 +0,0 @@ -"""TASK-owned retained creation reads, independent of today's task lifecycle state.""" - -import json -from uuid import UUID - -from sqlalchemy import func, select -from sqlalchemy.ext.asyncio import AsyncSession - -from app.modules.tasks.submission_attempts import COVERAGE_RETURN_REASON -from app.modules.tasks.api import ( - SubmissionCreationRequest, SubmissionCreationUnavailable, SubmissionPredecessorFacts, - TaskLockedProjectContextReferences, TaskPolicyLineage, TaskSubmissionContextFacts, -) -from app.modules.tasks.models import Submission, TaskAssignment, WorkstreamTask -from app.modules.tasks.submission_dispatch import SubmissionDispatch, creation_request_digest - - -async def read_creation_replay( - session: AsyncSession, task: WorkstreamTask, request: SubmissionCreationRequest, -) -> tuple[SubmissionDispatch, TaskSubmissionContextFacts] | None: - """Caller holds TASK; scope all replay selectors before taking child locks.""" - receipt = await session.scalar(select(SubmissionDispatch).where( - SubmissionDispatch.project_id == task.project_id, - SubmissionDispatch.task_id == str(request.task_id), - SubmissionDispatch.assignment_id == str(request.assignment_id), - SubmissionDispatch.contributor_id == str(request.contributor_id), - SubmissionDispatch.admission_id == str(request.admission_id), - ).execution_options(populate_existing=True)) - if receipt is None: - return None - invalid = SubmissionCreationUnavailable("submission creation is unavailable") - if receipt.request_digest != creation_request_digest(request): - raise invalid - assignment = await session.scalar(select(TaskAssignment).where( - TaskAssignment.project_id == task.project_id, - TaskAssignment.task_id == task.id, - TaskAssignment.id == str(request.assignment_id), - TaskAssignment.contributor_id == str(request.contributor_id), - ).with_for_update().execution_options(populate_existing=True)) - submission = await session.scalar(select(Submission).where( - Submission.id == str(receipt.submission_id), Submission.task_id == task.id, - Submission.task_assignment_id == str(request.assignment_id), - Submission.contributor_id == str(request.contributor_id), - Submission.submission_bundle_admission_id == str(request.admission_id), - ).with_for_update().execution_options(populate_existing=True)) - if assignment is None or submission is None: - raise invalid - predecessor_id = str(request.predecessor_submission_id) if request.predecessor_submission_id else None - if ( - submission.version != receipt.submission_version - or submission.supersedes_submission_id != predecessor_id - or submission.summary != request.summary - or submission.worker_attestation != request.contributor_attestation - or submission.artifact_binding_id != str(receipt.artifact_binding_id) - or submission.artifact_content_id != str(receipt.artifact_content_id) - or receipt.creation_kind != ("checker_remediation" if predecessor_id else "initial") - or receipt.creation_status != ("needs_revision" if predecessor_id else "in_progress") - or (receipt.checker_remediation_manifest_id is None) != (predecessor_id is None) - ): - raise invalid - predecessor = None - if predecessor_id: - original = await session.scalar(select(Submission).where( - Submission.id == predecessor_id, Submission.task_id == task.id, - Submission.contributor_id == submission.contributor_id, - Submission.task_assignment_id == submission.task_assignment_id, - )) - if original is None or original.version + 1 != submission.version: - raise invalid - revision_round = await session.scalar(select(func.count(Submission.id)).where( - Submission.task_assignment_id == submission.task_assignment_id, - Submission.version <= original.version, - Submission.status_reason.is_distinct_from(COVERAGE_RETURN_REASON), - )) - predecessor = SubmissionPredecessorFacts( - request.predecessor_submission_id, original.version, revision_round - ) - elif await session.scalar(select(func.count(Submission.id)).where( - Submission.task_assignment_id == submission.task_assignment_id, - Submission.version < submission.version, - )) != 0: - raise invalid - try: - policy = TaskPolicyLineage.model_validate_json(json.dumps({ - name: str(value) if isinstance(value, UUID) else value - for name in TaskPolicyLineage.model_fields - for value in (getattr(submission, name if name != "locked_contribution_policy_version_id" - else "contribution_policy_version_id"),) - })) - refs = TaskLockedProjectContextReferences( - project_id=UUID(task.project_id), - locked_contribution_policy_version_id=submission.contribution_policy_version_id, - guide_version=policy.locked_guide_version, - source_snapshot_id=policy.locked_guide_source_snapshot_id, - source_snapshot_hash=policy.locked_guide_source_snapshot_hash, - effective_policy_id=policy.locked_effective_project_submission_artifact_policy_id, - effective_policy_hash=policy.locked_effective_project_submission_artifact_policy_hash, - pre_submit_policy_id=policy.locked_pre_submit_checker_policy_id, - pre_submit_policy_bundle_hash=policy.locked_pre_submit_checker_bundle_hash, - ) - # These are the original creation facts recorded by this receipt, not a - # claim that the task still has its pre-submission lifecycle status. - context = TaskSubmissionContextFacts( - task_id=request.task_id, assignment_id=request.assignment_id, - contributor_id=request.contributor_id, status=receipt.creation_status, - kind=receipt.creation_kind, predecessor=predecessor, - submitter_contribution_policy_version_id=submission.contribution_policy_version_id, - locked_project_context=refs, locked_policy=policy, - acceptance_criteria=task.acceptance_criteria, - checker_remediation_manifest_id=receipt.checker_remediation_manifest_id, - ) - except (ValueError, TypeError, AttributeError) as exc: - raise invalid from exc - return receipt, context diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 7726090ac..071f73eb0 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -439,9 +439,14 @@ REV_04B_ACCEPTANCE_TARGETS = frozenset({"backend/app/modules/reviews/acceptance/models.py", "backend/app/modules/reviews/acceptance/schemas.py"}) REV_04A_SOURCE_TARGETS = frozenset({"backend/app/modules/reviews/decision/models.py", "backend/app/modules/reviews/decision/schemas.py"}) REV_03B_PACKET_TARGETS = frozenset({'backend/app/modules/reviews/packet/models.py', 'backend/app/modules/reviews/packet/repository.py', 'backend/app/modules/reviews/packet/schemas.py'}) +SUBMISSION_INTAKE_REMOVED_TARGETS = frozenset({"backend/app/modules/tasks/submission_replay.py"}) +SUBMISSION_INTAKE_FINALIZATION_TARGETS = frozenset({ + "backend/app/modules/tasks/submission_composition.py", + "backend/app/modules/tasks/accepted_submission.py", + "backend/app/modules/artifacts/intake/finalization.py", +}) ARCH_04E1BB6_DISPATCH_TARGETS = frozenset({ "backend/app/modules/tasks/submission_dispatch.py", - "backend/app/modules/tasks/submission_replay.py", "backend/app/modules/tasks/submission_participants.py", "backend/app/modules/authorization/prepared_submission_replay.py", }) @@ -1169,12 +1174,14 @@ def _validate_additive_partition_transition( raise BehaviorOwnershipError("untrusted_partition_change") if removed & AWS_ARTIFACT_PROOF_REMOVED_TARGETS and not AWS_DIRECT_USER_TARGETS.issubset(current_by_target): raise BehaviorOwnershipError("untrusted_partition_change") + if removed & SUBMISSION_INTAKE_REMOVED_TARGETS and not SUBMISSION_INTAKE_FINALIZATION_TARGETS.issubset(current_by_target): + raise BehaviorOwnershipError("untrusted_partition_change") retained_trusted = [ item for item in trusted_assignments if item["target"] not in removed ] if ( trusted_targets != sorted(trusted_targets) - or removed - (NEUTRAL_GUIDE_RUNTIME_REMOVED_TARGETS | REV_04C_REMOVED_TARGETS | ARCH_04D2_REMOVED_TARGETS | ARCH_03D_REMOVED_TARGETS | TASK_CHECKER_CLEANUP_REMOVED_TARGETS | ARCH_03C2_REMOVED_TARGETS | OUTBOX_IDENTITY_REMOVED_TARGETS | V01_BASELINE_REMOVED_TARGETS | POL_03B_REMOVED_TARGETS | POL_04B_REMOVED_TARGETS | POL_05A_REMOVED_TARGETS | ARCH_03A_GUIDE_CONTEXT_REMOVED_TARGETS | ARCH_04B_SEAM_REMOVED_TARGETS | PILOT_04_RETIRED_CATALOGUE_TARGETS | FORGE_PROOF_FACTS_REMOVED_TARGETS | SHARED_ADAPTER_PACKAGE_REMOVED_TARGETS | AWS_ARTIFACT_PROOF_REMOVED_TARGETS) + or removed - (NEUTRAL_GUIDE_RUNTIME_REMOVED_TARGETS | REV_04C_REMOVED_TARGETS | ARCH_04D2_REMOVED_TARGETS | ARCH_03D_REMOVED_TARGETS | TASK_CHECKER_CLEANUP_REMOVED_TARGETS | ARCH_03C2_REMOVED_TARGETS | OUTBOX_IDENTITY_REMOVED_TARGETS | V01_BASELINE_REMOVED_TARGETS | POL_03B_REMOVED_TARGETS | POL_04B_REMOVED_TARGETS | POL_05A_REMOVED_TARGETS | ARCH_03A_GUIDE_CONTEXT_REMOVED_TARGETS | ARCH_04B_SEAM_REMOVED_TARGETS | PILOT_04_RETIRED_CATALOGUE_TARGETS | FORGE_PROOF_FACTS_REMOVED_TARGETS | SHARED_ADAPTER_PACKAGE_REMOVED_TARGETS | AWS_ARTIFACT_PROOF_REMOVED_TARGETS | SUBMISSION_INTAKE_REMOVED_TARGETS) or [current_by_target[item["target"]] for item in retained_trusted] != retained_trusted ): diff --git a/backend/tests/tasks/test_revision_error_mapping.py b/backend/tests/tasks/test_revision_error_mapping.py index b26c44d30..de383544c 100644 --- a/backend/tests/tasks/test_revision_error_mapping.py +++ b/backend/tests/tasks/test_revision_error_mapping.py @@ -6,9 +6,7 @@ import pytest from sqlalchemy.exc import IntegrityError -from app.adapters.tasks import TransactionalSubmissionCreationCommand from app.modules.artifacts.service import ArtifactStorageOrchestrator -from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable from app.modules.tasks.authorized_commands import AuthorizedTaskCommands, TaskRevisionRepairError @@ -16,31 +14,6 @@ def _constraint(name: str) -> IntegrityError: return IntegrityError("INSERT", {}, SimpleNamespace(constraint_name=name)) -@pytest.mark.parametrize(("name", "code"), [ - ("ck_revision_submission_deadline_expired", "revision_deadline_expired"), - ("ck_revision_submission_context_changed", "revision_context_changed"), -]) -async def test_submission_commit_maps_only_named_revision_races(monkeypatch, name, code): - class Root: - async def __aenter__(self): - return self - - async def __aexit__(self, *_): - raise _constraint(name) - - session = SimpleNamespace(in_transaction=lambda: False, begin=Root) - monkeypatch.setattr( - "app.adapters.tasks.TaskSubmissionCreationService", - lambda *_args, **_kwargs: SimpleNamespace(create=AsyncMock(return_value=object())), - ) - command = TransactionalSubmissionCreationCommand( - session, authorization=None, admissions=None, settings=None, - ) - with pytest.raises(TaskSubmissionContextUnavailable) as caught: - await command.create(None) - assert caught.value.code == code - - async def test_repair_commit_maps_named_deadline_race(): command = AuthorizedTaskCommands.__new__(AuthorizedTaskCommands) command._repair_revision_context_root = AsyncMock( diff --git a/backend/tests/test_artifact_bindings_db.py b/backend/tests/test_artifact_bindings_db.py index 4663f625d..0eb9ddc76 100644 --- a/backend/tests/test_artifact_bindings_db.py +++ b/backend/tests/test_artifact_bindings_db.py @@ -20,13 +20,8 @@ SubmissionAdmissionConsumptionService, ) from app.modules.artifacts.api import SubmissionAdmissionConsumptionError -from app.adapters.tasks import TransactionalSubmissionCreationCommand -from app.modules.tasks.api import SubmissionCreationRequest, SubmissionCreationUnavailable from app.modules.tasks.models import Submission, SubmissionDispatch from app.modules.tasks.models import AuditEvent -from app.modules.tasks.repository import TaskRepository -from app.modules.tasks.submission_context import TaskSubmissionContextService -from app.modules.tasks.service import TaskService from test_artifact_bindings import _Allow, _lineage, _request, _replay_request @@ -130,93 +125,6 @@ async def _seed(session, schema: str, request) -> None: ) -class _FinalDeny: - async def authorize(self, facts) -> None: - del facts - - async def prepare(self, facts) -> object: - del facts - raise SubmissionCreationUnavailable("submission creation is unavailable") - - async def consume(self, prepared_authorization, facts) -> None: - del prepared_authorization, facts - raise AssertionError("unreachable") - - def close(self, prepared_authorization) -> None: - del prepared_authorization - - -@pytest.mark.asyncio -async def test_composed_final_denial_rolls_back_task_and_art_rows( - isolated_database_env: str, monkeypatch: pytest.MonkeyPatch, -) -> None: - art_request = _request() - context = art_request.task_context - task = type("LockedTask", (), { - "id": str(context.task_id), "project_id": str(context.locked_project_context.project_id), - "locked_guide_version": "1", - "locked_post_submit_checker_policy_id": str(new_record_id()), - "locked_post_submit_checker_policy_version": "1", - "locked_post_submit_checker_policy_hash": "sha256:" + "4" * 64, - "locked_post_submit_checker_policy_body": {}, - "locked_review_policy_id": str(new_record_id()), "locked_review_policy_generation": 1, - "locked_review_policy_hash": "sha256:" + "5" * 64, - "locked_revision_policy_id": str(new_record_id()), "locked_revision_policy_generation": 1, - "locked_revision_policy_hash": "sha256:" + "6" * 64, - "locked_guide_source_snapshot_id": str(context.locked_project_context.source_snapshot_id), - "locked_guide_source_snapshot_hash": context.locked_project_context.source_snapshot_hash, - "locked_effective_project_submission_artifact_policy_id": str(context.locked_project_context.effective_policy_id), - "locked_effective_project_submission_artifact_policy_hash": context.locked_project_context.effective_policy_hash, - "locked_pre_submit_checker_policy_id": str(context.locked_project_context.pre_submit_policy_id), - "locked_pre_submit_checker_bundle_hash": context.locked_project_context.pre_submit_policy_bundle_hash, - })() - - async def lock_context(self, request): - del self, request - return context - - async def get_task(self, task_id, **kwargs): - del self, task_id, kwargs - return task - - async def validate_context(self, candidate): - # This isolated ART schema deliberately doubles the TASK owner. Full - # policy rejection is proved in task_authority/test_submission_policy.py. - assert candidate is task - - monkeypatch.setattr(TaskSubmissionContextService, "lock_submission_context", lock_context) - monkeypatch.setattr(TaskRepository, "get_task", get_task) - monkeypatch.setattr(TaskService, "_load_locked_task_context", validate_context) - async with _isolated_binding_schema(isolated_database_env) as (schema, factory): - async with factory.begin() as seed: - await _seed(seed, schema, art_request) - request = SubmissionCreationRequest( - admission_id=art_request.admission_id, task_id=context.task_id, - assignment_id=context.assignment_id, contributor_id=context.contributor_id, - predecessor_submission_id=None, summary="Prepared summary", - contributor_attestation="Prepared attestation", - ) - async with factory() as session: - await session.execute(text(f'set search_path to "{schema}"')) - await session.commit() - from app.core.config import get_settings - - command = TransactionalSubmissionCreationCommand( - session, - settings=get_settings(), authorization=_FinalDeny(), - admissions=SubmissionAdmissionConsumptionService(session, _Allow()), - ) - with pytest.raises(SubmissionCreationUnavailable): - await command.create(request) - async with factory() as session: - await _set_schema(session, schema) - assert await session.scalar(text("select count(*) from submissions")) == 0 - assert await session.scalar(text("select count(*) from artifact_bindings")) == 0 - status = await session.scalar( - text("select status from submission_bundle_admissions where id=:id"), - {"id": str(request.admission_id)}, - ) - assert status == "ready" @pytest.mark.asyncio async def test_postgresql_consumption_is_concurrent_and_rollback_safe( isolated_database_env: str, diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py index a70b54d13..502df11e5 100644 --- a/backend/tests/test_behavior_ownership.py +++ b/backend/tests/test_behavior_ownership.py @@ -2824,3 +2824,15 @@ def test_partition_allows_only_the_shared_adapter_package_relocation() -> None: current, _partition(sorted([retained, removed, "backend/app/interfaces/forge_facts.py"])), ) + + +def test_submission_replay_retirement_requires_accepted_finalization_owners() -> None: + owners = ownership.SUBMISSION_INTAKE_FINALIZATION_TARGETS + retired = "backend/app/modules/tasks/submission_replay.py" + trusted = _partition(sorted({retired, *owners})) + ownership._validate_additive_partition_transition(_partition(sorted(owners)), trusted) + for missing in owners: + with pytest.raises(ownership.BehaviorOwnershipError, match="untrusted_partition_change"): + ownership._validate_additive_partition_transition( + _partition(sorted(owners - {missing})), trusted, + ) diff --git a/backend/tests/test_submission_composition.py b/backend/tests/test_submission_composition.py index 51db55825..06d55513b 100644 --- a/backend/tests/test_submission_composition.py +++ b/backend/tests/test_submission_composition.py @@ -1,8 +1,6 @@ -"""Focused behavior proof for hidden admission-backed Submission composition.""" +"""Accepted Submission composition and retained authorization fact contracts.""" -from app.core.config import get_settings -from app.adapters.tasks import task_service from types import SimpleNamespace from unittest.mock import AsyncMock @@ -21,19 +19,6 @@ from app.modules.tasks.submission_composition import TaskSubmissionCreationService from app.modules.authorization.catalogue import ActionId from app.modules.authorization.submission_consumption import parse_consumption_binding -from app.api.deps.authorization import compose_hidden_submission_creation_command -from app.adapters.tasks import TransactionalSubmissionCreationCommand -from app.modules.artifacts.submission_bindings import SubmissionAdmissionConsumptionService -from app.modules.artifacts.authorization import PreparedSubmissionBindingAuthorization -from app.modules.authorization.prepared import ( - PreparedSubmissionCreationAuthorization, -) -from app.modules.authorization.runtime import ( - ActorKind, - ActorStatus, - HumanAuthorizationContext, - IdentityLinkStatus, -) class _Session: @@ -100,207 +85,61 @@ def _task(): return SimpleNamespace(**values) -@pytest.mark.parametrize( - ("actor_status", "link_status"), - [ - (ActorStatus.SUSPENDED, IdentityLinkStatus.ACTIVE), - (ActorStatus.ACTIVE, IdentityLinkStatus.REVOKED), - ], -) -@pytest.mark.asyncio -async def test_human_lifecycle_denial_precedes_task_state( - actor_status, link_status, -): - request = _request() - context = HumanAuthorizationContext( - actor_profile_id=request.contributor_id, - actor_kind=ActorKind.HUMAN, - actor_status=actor_status, - identity_link_id=new_record_id(), - identity_link_status=link_status, - request_id=new_record_id(), - correlation_id=new_record_id(), - ) - authority = PreparedSubmissionCreationAuthorization(object(), context) - service = TaskSubmissionCreationService( - _Session(), - authorization=authority, - evaluations=None, events=None, - admissions=None, - contexts=task_service(_Session(), settings=get_settings()), - submission_contexts=SimpleNamespace(lock_submission_context=AsyncMock(side_effect=AssertionError("TASK state was revealed"))), - ) - with pytest.raises(SubmissionCreationUnavailable): - await service.create(request) - - -@pytest.mark.asyncio -async def test_foreign_contributor_denial_precedes_task_lookup(): - request = _request() - context = HumanAuthorizationContext( - actor_profile_id=new_record_id(), actor_kind=ActorKind.HUMAN, - actor_status=ActorStatus.ACTIVE, identity_link_id=new_record_id(), - identity_link_status=IdentityLinkStatus.ACTIVE, - request_id=new_record_id(), correlation_id=new_record_id(), - ) - service = TaskSubmissionCreationService( - _Session(), - authorization=PreparedSubmissionCreationAuthorization(object(), context), - evaluations=None, events=None, - admissions=None, - contexts=task_service(_Session(), settings=get_settings()), - submission_contexts=SimpleNamespace(lock_submission_context=AsyncMock(side_effect=AssertionError("foreign task was inspected"))), - ) - with pytest.raises(SubmissionCreationUnavailable): - await service.create(request) - - -@pytest.mark.asyncio -async def test_denial_precedes_task_lock_and_all_mutation(): - class Authority: - async def authorize(self, facts): raise SubmissionCreationUnavailable - async def prepare(self, facts): raise AssertionError("unreachable") - async def consume(self, handle, facts): raise AssertionError("unreachable") - def close(self, handle): raise AssertionError("unreachable") - - service = TaskSubmissionCreationService( - _Session(), - authorization=Authority(), - evaluations=None, events=None, - admissions=None, - contexts=task_service(_Session(), settings=get_settings()), - submission_contexts=SimpleNamespace(lock_submission_context=AsyncMock(side_effect=AssertionError("TASK state was revealed"))), - ) - with pytest.raises(SubmissionCreationUnavailable): - await service.create(_request()) - - -@pytest.mark.parametrize("revocation", ["identity_link_revoked", "submitter_grant_missing"]) @pytest.mark.asyncio -async def test_fresh_authority_denial_precedes_art_and_mutation(revocation): - request = _request() - events = [] - - class Authority: - async def authorize(self, facts): pass - async def prepare(self, facts): - events.append(revocation) - raise SubmissionCreationUnavailable("submission creation is unavailable") - async def consume(self, handle, facts): raise AssertionError("unreachable") - def close(self, handle): raise AssertionError("unreachable") - - class Admissions: - async def consume(self, value): - raise AssertionError("ART admission state was inspected") - - service = TaskSubmissionCreationService( - _Session(), - authorization=Authority(), - evaluations=None, events=None, - admissions=Admissions(), - contexts=task_service(_Session(), settings=get_settings()), - submission_contexts=SimpleNamespace(lock_submission_context=AsyncMock(return_value=_context(request))), - ) - persisted = [] +@pytest.mark.parametrize("failure", ["authority", "policy", "admission"]) +async def test_accepted_creation_denial_closes_authority_and_stops_dispatch(monkeypatch, failure): + from unittest.mock import Mock + from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationAuthorityFacts - class Repository: - async def get_task(self, task_id, **kwargs): return _task() - async def get_latest_submission_for_task(self, task_id): return None - async def add_submission(self, submission): persisted.append(submission) - - service._repository = Repository() - # This test isolates authority sequencing, not policy validation behavior. - service._contexts = SimpleNamespace(_load_locked_task_context=AsyncMock()) - with pytest.raises(SubmissionCreationUnavailable): - await service.create(request) - assert events == [revocation] - assert persisted == [] - - -@pytest.mark.asyncio -async def test_invalid_admission_result_denies_before_lineage_and_final_authority(): request = _request() - events = [] - - class Authority: - async def authorize(self, facts): events.append("authorize") - async def prepare(self, facts): - events.append("prepare") - return "prepared" - async def consume(self, handle, facts): events.append("final") - def close(self, handle): assert handle == "prepared" - - class Admissions: - async def consume(self, value): - events.append("art") - return SimpleNamespace(binding_id=None, content_id=new_record_id()) - - service = TaskSubmissionCreationService( - _Session(), - authorization=Authority(), - evaluations=None, events=None, - admissions=Admissions(), - contexts=task_service(_Session(), settings=get_settings()), - submission_contexts=SimpleNamespace(lock_submission_context=AsyncMock(return_value=_context(request))), + facts = SubmissionFinalizationAuthorityFacts( + operation_id=new_record_id(), project_id=new_record_id(), + task_id=request.task_id, assignment_id=request.assignment_id, + contributor_id=request.contributor_id, acceptance_decision_id=new_record_id(), + accepted_context_sha256="a" * 64, acceptance_receipt_sha256="b" * 64, + source_sha256="c" * 64, continuation_lease_id=new_record_id(), + continuation_generation=1, phase="claim", ) - persisted = [] - - class Repository: - async def get_task(self, task_id, **kwargs): return _task() - async def get_latest_submission_for_task(self, task_id): return None - async def add_submission(self, submission): persisted.append(submission) - - service._repository = Repository() - # This test isolates ART result validation, not policy validation behavior. - service._contexts = SimpleNamespace(_load_locked_task_context=AsyncMock()) - with pytest.raises(SubmissionCreationUnavailable, match="submission creation is unavailable"): - await service.create(request) - assert events == ["authorize", "prepare", "art"] - assert len(persisted) == 1 - assert persisted[0].artifact_binding_id is None - - -def test_hidden_composition_uses_both_active_authority_adapters() -> None: - session = SimpleNamespace() - context = SimpleNamespace() - command = compose_hidden_submission_creation_command( - session, context, request_id=new_record_id(), correlation_id=new_record_id() + monkeypatch.setattr( + "app.modules.tasks.accepted_submission.accepted_submission_context", + AsyncMock(return_value=_context(request)), ) - assert type(command) is TransactionalSubmissionCreationCommand - assert type(command._authorization) is PreparedSubmissionCreationAuthorization - assert type(command._admissions) is SubmissionAdmissionConsumptionService - assert type(command._admissions._authorization) is PreparedSubmissionBindingAuthorization - - -@pytest.mark.asyncio -async def test_policy_failure_closes_prepared_authority_before_any_submission_or_art_write(): - request = _request() authority = SimpleNamespace( - authorize=AsyncMock(), prepare=AsyncMock(return_value=object()), - consume=AsyncMock(), close=lambda handle: closed.append(handle), + prepare=AsyncMock(return_value=object()), consume=AsyncMock(), close=Mock(), ) - closed = [] - admissions = SimpleNamespace(consume=AsyncMock()) + admissions = SimpleNamespace(consume=AsyncMock(return_value=SimpleNamespace(binding_id=None))) + contexts = SimpleNamespace(_load_locked_task_context=AsyncMock(return_value=SimpleNamespace(facts=object()))) + if failure == "authority": + authority.prepare.side_effect = SubmissionCreationUnavailable("authority denied") + elif failure == "policy": + contexts._load_locked_task_context.side_effect = SubmissionCreationUnavailable("policy denied") service = TaskSubmissionCreationService( - _Session(), - authorization=authority, - evaluations=None, events=None, - admissions=admissions, - contexts=SimpleNamespace( - _load_locked_task_context=AsyncMock(side_effect=ValueError("custody changed")) - ), - submission_contexts=SimpleNamespace(lock_submission_context=AsyncMock(return_value=_context(request))), + _Session(), admissions=admissions, contexts=contexts, + evaluations=SimpleNamespace(reserve_current_evaluation=AsyncMock()), + events=SimpleNamespace(append=AsyncMock()), ) service._repository = SimpleNamespace( get_task=AsyncMock(return_value=_task()), add_submission=AsyncMock(), get_latest_submission_for_task=AsyncMock(return_value=None), ) - with pytest.raises(ValueError, match="custody changed"): - await service.create(request) - assert closed == [authority.prepare.return_value] - service._repository.add_submission.assert_not_awaited() - admissions.consume.assert_not_awaited() + with pytest.raises(SubmissionCreationUnavailable): + await service.create_accepted(request, authority_facts=facts, + finalization_authority=authority, snapshot_sha256="d" * 64, + eligible_status="in_progress", remediation_id=None) authority.consume.assert_not_awaited() + service._evaluations.reserve_current_evaluation.assert_not_awaited() + service._events.append.assert_not_awaited() + if failure == "authority": + authority.close.assert_not_called() # No prepared handle was issued. + contexts._load_locked_task_context.assert_not_awaited() + else: + authority.close.assert_called_once_with() + if failure == "admission": + service._repository.add_submission.assert_awaited_once() + assert service._repository.add_submission.await_args.args[0].artifact_binding_id is None + else: + service._repository.add_submission.assert_not_awaited() + admissions.consume.assert_not_awaited() def test_task_and_assignment_policy_facts_reject_substitution(): From 91116d97b52302e220f10b7114b11742257cf9b2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:05:41 +0100 Subject: [PATCH 239/513] Preserve accepted operation in binding concurrency fixture --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 6 ++++++ backend/tests/test_artifact_bindings_db.py | 9 +-------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 113849174..923463c0c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8387,3 +8387,9 @@ staging the deleted module (inventory intentionally reads the Git index). The new accepted-owner-required retirement control passed. PostgreSQL receipt `/tmp/submission-retire-writer.log/.json` is still running at candidate freeze; no integration success is claimed yet. No schema or retained-data changes. + +QA-RETIRE-001: retained ART concurrency fixture reconstructed a request without +accepted_operation_id, so it would reject before reaching concurrency. Preserve +that exact identity with dataclasses.replace. This isolated ART schema proves +binding concurrency/rollback only; real accepted-source SQL custody remains +covered by the full-schema T5 cases, not this narrow fixture. diff --git a/backend/tests/test_artifact_bindings_db.py b/backend/tests/test_artifact_bindings_db.py index 0eb9ddc76..c4c530b7f 100644 --- a/backend/tests/test_artifact_bindings_db.py +++ b/backend/tests/test_artifact_bindings_db.py @@ -129,14 +129,7 @@ async def _seed(session, schema: str, request) -> None: async def test_postgresql_consumption_is_concurrent_and_rollback_safe( isolated_database_env: str, ) -> None: - request = _request() - request = type(request)( - packet_sha256=request.packet_sha256, - admission_id=request.admission_id, - submission_id=request.submission_id, - submission_version=2, - task_context=request.task_context, - ) + request = replace(_request(), submission_version=2) async with _isolated_binding_schema(isolated_database_env) as (schema, factory): async with factory.begin() as seed: await _seed(seed, schema, request) From 481e5a90140056b1893298d355c4b9fafbf411db Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:08:01 +0100 Subject: [PATCH 240/513] Record submission writer retirement verification --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 923463c0c..d02c0a743 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8393,3 +8393,15 @@ accepted_operation_id, so it would reject before reaching concurrency. Preserve that exact identity with dataclasses.replace. This isolated ART schema proves binding concurrency/rollback only; real accepted-source SQL custody remains covered by the full-schema T5 cases, not this narrow fixture. + +Writer-retirement review closure at clean 91116d97b: ARCH/SEC PASS and QA +PASS WITH LOW RISKS; QA-RETIRE-001 resolved. Original PostgreSQL receipt finished +8 passed/1 failed in 306.10s; only the obsolete binding fixture failed. Exact +repaired fixture passed in 3.55s at 91116d97b. Both metadata receipts show schema +0090 and complete cleanup. These are eight precommit integration passes plus +one exact-head repair pass, not a full-suite final-head result. QA independently +omitted authority closure and the replacement denial test failed as intended. +Commitrail, changed Markdown links, stale artifact contracts and diff checks +passed. This closes the admission-only TASK writer retirement; genuine-orphan +cleanup, remote execution/AWS qualification, operational crash evidence and +full end-to-end acceptance remain open under the unchanged goal. From 5ed89c93b8ce6c3ebb32553c2cfb1bc8d3c49c56 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:12:23 +0100 Subject: [PATCH 241/513] Exercise finalizer recovery after actual process loss --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 17 +++ backend/scripts/test_lane_catalogue.py | 1 + ...est_submission_finalization_worker_loss.py | 136 ++++++++++++++++++ backend/tests/test_ci_lane_catalogue.py | 4 +- 4 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 backend/tests/artifacts/test_submission_finalization_worker_loss.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d02c0a743..418d4ef58 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8405,3 +8405,20 @@ Commitrail, changed Markdown links, stale artifact contracts and diff checks passed. This closes the admission-only TASK writer retirement; genuine-orphan cleanup, remote execution/AWS qualification, operational crash evidence and full end-to-end acceptance remain open under the unchanged goal. + + +### Process-loss finalization qualification + +Intent: close the exception-only worker-loss proof gap with actual SIGKILL +before source observation and after committed T5. Allowed: a focused ART +integration test, exact lane registration and this record. Prohibited: +production behavior/leases/schema/provider changes, runner files, broker or +full-system qualification claims. Risk: medium verification change across +transaction custody; use existing scoped QA/ARCH reviewers. Acceptance: a child +process dies by SIGKILL at each boundary; persisted claim remains unresolved; +after real lease expiry the existing recovery/delivery owners finalize exactly +one Submission/binding/POST dispatch, preserving accepted source identity. +Finalized replay must not reread the provider. Verify real PostgreSQL, child +cleanup, existing structure/lane checks. Human focus: real process death and +committed-state assertions, without fabricated expired timestamps. This does +not replace the distinct lost-ACK tests or prove broker outage behavior. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 0e818006c..fa93905d7 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -62,6 +62,7 @@ class TestLane: "tests/artifacts/test_submission_pre_source.py", "tests/artifacts/test_submission_intake_admission.py", "tests/artifacts/test_submission_intake_progress.py", + "tests/artifacts/test_submission_finalization_worker_loss.py", "tests/artifacts/test_submission_foreground_command.py", "tests/authorization/post_submit/test_atomicity.py", "tests/authorization/post_submit/test_concurrency.py", diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py new file mode 100644 index 000000000..9600c1c35 --- /dev/null +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -0,0 +1,136 @@ +"""Actual process death retains accepted custody before and after T5 commit.""" +import asyncio +from datetime import timedelta +import multiprocessing +import os +import signal +from uuid import UUID + +import pytest +from sqlalchemy import func, select, text +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.adapters.artifacts import submission_finalization_handler +from app.adapters.auth import outbox_dispatch_authorization +from app.adapters.checkers import selected_pre_submit_coordinator +from app.adapters.outbox import outbox_append, outbox_delivery +from app.modules.actors.api import ServiceIdentity +from app.modules.artifacts.intake.models import SubmissionIntakeOperation +from app.modules.outbox.api import DeliveryOptions, HandlerOutcome +from app.modules.outbox.models import OutboxEvent +from app.modules.outbox.registry import HandlerRegistry +from tests.artifact_store_helpers import initialize_local_store +from tests.artifacts.intake_acceptance_support import completed_source +from tests.artifacts.test_submission_intake_admission import admission_intake as admission_intake +from tests.authentication.fixtures import ( + auth_database_env as auth_database_env, clear_settings_cache as clear_settings_cache, + rsa_signing_material as rsa_signing_material, +) +from tests.authorization.admin_access.fixtures import ( + signed_access as signed_access, admin_access as admin_access, +) +from tests.checkers.execution.support import provision_post_submit_service +from tests.test_artifact_admission import _settings + + +def _delivery(factory, path, *, kill_at=None, observations=None, forbid_observation=False): + store = initialize_local_store(root=path / "durable", buffer_bytes=256 * 1024) + + class ObservedStore: + async def observe_sealed_source(self, source): + if kill_at == "before_observation": + os.kill(os.getpid(), signal.SIGKILL) + assert not forbid_observation, "committed finalization reread source" + if observations is not None: + observations.append(source) + return await store.observe_sealed_source(source) + + handler = submission_finalization_handler(sessions=factory, settings=_settings(path), + store=ObservedStore(), lease_duration=timedelta(seconds=15)) + + async def invoke(envelope): + result = await handler(envelope) + assert result == HandlerOutcome.ACKNOWLEDGE + if kill_at == "after_commit": + os.kill(os.getpid(), signal.SIGKILL) + return result + + event = ("SubmissionFinalizationRequested", 1) + return outbox_delivery(factory, authorization_factory=outbox_dispatch_authorization, + registry=HandlerRegistry([(*event, invoke)], replay_safe=frozenset({event})), + options=DeliveryOptions(lease_seconds=15, handler_timeout_seconds=14, + retry_base_seconds=1, retry_cap_seconds=1)), store + + +def _crash_worker(database_url, path, event_id, project_id, kill_at): + """Use fresh SQL resources in a process which cannot run cleanup on SIGKILL.""" + async def run(): + engine = create_async_engine(database_url) + delivery, store = _delivery(async_sessionmaker(engine, expire_on_commit=False), path, kill_at=kill_at) + try: + await delivery.deliver(event_id, project_id, "killed-finalizer") + finally: + store.close() + await engine.dispose() + asyncio.run(run()) + + +@pytest.mark.parametrize("kill_at", ["before_observation", "after_commit"]) +async def test_sigkill_finalizer_recovers_exact_accepted_operation(admission_intake, tmp_path, kill_at): + f = admission_intake + owner, request, terminal = await completed_source(f, tmp_path) + await f.admission.accept(owner, request, terminal.terminal_digest, + checkers=selected_pre_submit_coordinator, outbox=outbox_append) + for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER): + await provision_post_submit_service(f.factory, identity) + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + event_id = UUID(row.finalization_event_id) + process = multiprocessing.get_context("fork").Process(target=_crash_worker, args=( + f.factory.kw["bind"].url, tmp_path, event_id, f.project, kill_at)) + observations = [] + delivery, store = _delivery(f.factory, tmp_path, observations=observations, + forbid_observation=kill_at == "after_commit") + process.start() + try: + await asyncio.to_thread(process.join, 45) + assert not process.is_alive(), "finalizer did not reach crash boundary" + assert process.exitcode == -signal.SIGKILL + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + event = await session.get(OutboxEvent, event_id) + assert event.delivery_state == "claimed" and event.attempt_count == 1 + assert row.state == ("finalized" if kill_at == "after_commit" else "finalization_pending") + original_submission = row.finalized_submission_id + ready_at = max(event.claim_expires_at, row.continuation_expires_at) + remaining = (ready_at - await session.scalar(select(func.clock_timestamp()))).total_seconds() + await asyncio.sleep(max(0, remaining) + 0.05) + assert await delivery.recover(event_id, f.project) is not None + async with f.factory() as session: + event = await session.get(OutboxEvent, event_id) + assert event.delivery_state == "retryable" + remaining = (event.next_attempt_at - await session.scalar(select(func.clock_timestamp()))).total_seconds() + await asyncio.sleep(max(0, remaining) + 0.05) + assert await delivery.deliver(event_id, f.project, "replacement-finalizer") is not None + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + event = await session.get(OutboxEvent, event_id) + assert row.state == "finalized" and event.delivery_state == "acknowledged" + assert event.attempt_count == 2 + assert row.continuation_generation == (1 if kill_at == "after_commit" else 2) + if original_submission is not None: + assert row.finalized_submission_id == original_submission + for table in ("submissions", "submission_dispatches", "checker_runs"): + assert await session.scalar(text(f"SELECT count(*) FROM {table} WHERE task_id=:id"), {"id": f.task}) == 1 + assert await session.scalar(text("SELECT count(*) FROM artifact_bindings WHERE resource_id=:id"), + {"id": row.finalized_submission_id}) == 1 + assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE project_id=:id " + "AND event_type='PostSubmissionEvaluationRequested'"), {"id": f.project}) == 1 + assert observations == ([] if kill_at == "after_commit" else [request.source]) + finally: + if process.is_alive(): + process.kill() + await asyncio.to_thread(process.join, 5) + assert not process.is_alive(), "crash worker cleanup failed" + process.close() + store.close() diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 1c675e095..a90ba31a8 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -320,8 +320,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 278, - "e05f606f3ad84b818a62ca7d00d00a1c8d277e2417ebf822cfce9d9d0658b3b0", + 279, + "42ff87480abaeb4e69c3756b83bbe053a26fb2f84db726a1018596369c7bcc30", ), "project": ( 258, From d18c85511f3f25b67aef3846b103bf4dc8398ca7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:14:06 +0100 Subject: [PATCH 242/513] Use database expiry and spawned finalizer in crash proof --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 7 +++++++ ...est_submission_finalization_worker_loss.py | 20 ++++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 418d4ef58..12011bdee 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8422,3 +8422,10 @@ Finalized replay must not reread the provider. Verify real PostgreSQL, child cleanup, existing structure/lane checks. Human focus: real process death and committed-state assertions, without fabricated expired timestamps. This does not replace the distinct lost-ACK tests or prove broker outage behavior. + +Initial crash receipt: both processes reached SIGKILL; after-commit passed, +before-observation recovery returned not-ready after a client-clock sleep. +Use a bounded PostgreSQL-clock expiry wait rather than a fixed 50ms margin, +without retrying or weakening the recovery assertion. Switch fork to spawn so +the child cannot inherit pytest threads. Rerun both cases for these harness +changes; no production timing changes. diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py index 9600c1c35..824e4a917 100644 --- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -75,6 +75,17 @@ async def run(): asyncio.run(run()) +async def _wait_until_database_time(factory, target): + """The lease uses PostgreSQL wall time, not the test process's sleep clock.""" + async with asyncio.timeout(30): + while True: + async with factory() as session: + now = await session.scalar(select(func.clock_timestamp())) + if now >= target: + return + await asyncio.sleep(min(0.1, (target - now).total_seconds())) + + @pytest.mark.parametrize("kill_at", ["before_observation", "after_commit"]) async def test_sigkill_finalizer_recovers_exact_accepted_operation(admission_intake, tmp_path, kill_at): f = admission_intake @@ -86,7 +97,7 @@ async def test_sigkill_finalizer_recovers_exact_accepted_operation(admission_int async with f.factory() as session: row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) event_id = UUID(row.finalization_event_id) - process = multiprocessing.get_context("fork").Process(target=_crash_worker, args=( + process = multiprocessing.get_context("spawn").Process(target=_crash_worker, args=( f.factory.kw["bind"].url, tmp_path, event_id, f.project, kill_at)) observations = [] delivery, store = _delivery(f.factory, tmp_path, observations=observations, @@ -103,14 +114,13 @@ async def test_sigkill_finalizer_recovers_exact_accepted_operation(admission_int assert row.state == ("finalized" if kill_at == "after_commit" else "finalization_pending") original_submission = row.finalized_submission_id ready_at = max(event.claim_expires_at, row.continuation_expires_at) - remaining = (ready_at - await session.scalar(select(func.clock_timestamp()))).total_seconds() - await asyncio.sleep(max(0, remaining) + 0.05) + await _wait_until_database_time(f.factory, ready_at) assert await delivery.recover(event_id, f.project) is not None async with f.factory() as session: event = await session.get(OutboxEvent, event_id) assert event.delivery_state == "retryable" - remaining = (event.next_attempt_at - await session.scalar(select(func.clock_timestamp()))).total_seconds() - await asyncio.sleep(max(0, remaining) + 0.05) + ready_at = event.next_attempt_at + await _wait_until_database_time(f.factory, ready_at) assert await delivery.deliver(event_id, f.project, "replacement-finalizer") is not None async with f.factory() as session: row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) From 1e37a5e65912023645fe0e83e253976e3ca319c6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:20:23 +0100 Subject: [PATCH 243/513] Keep crash proof aligned with prefork worker topology --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 7 +++++++ .../artifacts/test_submission_finalization_worker_loss.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 12011bdee..72b812e05 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8429,3 +8429,10 @@ Use a bounded PostgreSQL-clock expiry wait rather than a fixed 50ms margin, without retrying or weakening the recovery assertion. Switch fork to spawn so the child cannot inherit pytest threads. Rerun both cases for these harness changes; no production timing changes. + +Spawn rerun failed both startup bounds before reaching either crash boundary; +therefore it supplies no crash/recovery proof. Restore the repository's existing +prefork test approach (matching durable worker topology), whose first run +reached both SIGKILL boundaries. Keep the database-clock gate and fresh child +engine. Record the fork/thread warning as a harness limitation, not production +qualification. No extra retries or enlarged startup bound. diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py index 824e4a917..4c457ed39 100644 --- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -97,7 +97,7 @@ async def test_sigkill_finalizer_recovers_exact_accepted_operation(admission_int async with f.factory() as session: row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) event_id = UUID(row.finalization_event_id) - process = multiprocessing.get_context("spawn").Process(target=_crash_worker, args=( + process = multiprocessing.get_context("fork").Process(target=_crash_worker, args=( f.factory.kw["bind"].url, tmp_path, event_id, f.project, kill_at)) observations = [] delivery, store = _delivery(f.factory, tmp_path, observations=observations, From 221f14e854ccb2e71a511f155b42e22a9e3cdfb6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:28:56 +0100 Subject: [PATCH 244/513] Bound crash proof independently of short synthetic handler timing --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ .../test_submission_finalization_worker_loss.py | 11 ++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 72b812e05..10190d140 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8436,3 +8436,12 @@ prefork test approach (matching durable worker topology), whose first run reached both SIGKILL boundaries. Keep the database-clock gate and fresh child engine. Record the fork/thread warning as a harness limitation, not production qualification. No extra retries or enlarged startup bound. + +V3: before-observation SIGKILL/recovery passed; after-commit child returned +normally instead of reaching SIGKILL (test correctly failed). Host observed +4 CPUs/load16.23; the harness's 14-second handler deadline can terminate the +real T5 transaction before the kill hook under this load. Use bounded 60-second +custody/55-second handler window (production unchanged), 90-second process +supervision and 75-second DB-clock wait. An unexpected child delivery return +now fails with its delivery receipt for diagnosis. Run the two cases again; +do not credit the failed after-commit run or retry it inside the test. diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py index 4c457ed39..9996c0342 100644 --- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -46,7 +46,7 @@ async def observe_sealed_source(self, source): return await store.observe_sealed_source(source) handler = submission_finalization_handler(sessions=factory, settings=_settings(path), - store=ObservedStore(), lease_duration=timedelta(seconds=15)) + store=ObservedStore(), lease_duration=timedelta(seconds=60)) async def invoke(envelope): result = await handler(envelope) @@ -58,7 +58,7 @@ async def invoke(envelope): event = ("SubmissionFinalizationRequested", 1) return outbox_delivery(factory, authorization_factory=outbox_dispatch_authorization, registry=HandlerRegistry([(*event, invoke)], replay_safe=frozenset({event})), - options=DeliveryOptions(lease_seconds=15, handler_timeout_seconds=14, + options=DeliveryOptions(lease_seconds=60, handler_timeout_seconds=55, retry_base_seconds=1, retry_cap_seconds=1)), store @@ -68,7 +68,8 @@ async def run(): engine = create_async_engine(database_url) delivery, store = _delivery(async_sessionmaker(engine, expire_on_commit=False), path, kill_at=kill_at) try: - await delivery.deliver(event_id, project_id, "killed-finalizer") + result = await delivery.deliver(event_id, project_id, "killed-finalizer") + raise AssertionError(f"worker returned before SIGKILL: {result}") finally: store.close() await engine.dispose() @@ -77,7 +78,7 @@ async def run(): async def _wait_until_database_time(factory, target): """The lease uses PostgreSQL wall time, not the test process's sleep clock.""" - async with asyncio.timeout(30): + async with asyncio.timeout(75): while True: async with factory() as session: now = await session.scalar(select(func.clock_timestamp())) @@ -104,7 +105,7 @@ async def test_sigkill_finalizer_recovers_exact_accepted_operation(admission_int forbid_observation=kill_at == "after_commit") process.start() try: - await asyncio.to_thread(process.join, 45) + await asyncio.to_thread(process.join, 90) assert not process.is_alive(), "finalizer did not reach crash boundary" assert process.exitcode == -signal.SIGKILL async with f.factory() as session: From 88100a0302c05d9a7ce8571268583a8363d60b77 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:35:47 +0100 Subject: [PATCH 245/513] Separate AWS submission source upload and cleanup policies --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 37 +++++ backend/scripts/aws_direct_user_config.py | 130 ++++++++---------- backend/tests/test_aws_direct_user_config.py | 129 +++++++++-------- docs/operations_aws_s3_credentials.md | 58 +++++--- 4 files changed, 206 insertions(+), 148 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 10190d140..ba82efcb4 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8445,3 +8445,40 @@ custody/55-second handler window (production unchanged), 90-second process supervision and 75-second DB-clock wait. An unexpected child delivery return now fails with its delivery receipt for diagnosis. Run the two cases again; do not credit the failed after-commit run or retry it inside the test. + + +### AWS source policy preparation + +Intent: extend the existing direct-user policy generator for the managed +submission-source prefix and a distinct cleanup principal. The current sha256 +only policy cannot support the source adapter. Allowed: aws_direct_user_config, +its focused tests, operations_aws_s3_credentials.md and this record. Risk: high +(storage authority/retention). Prohibited: applying IAM/bucket policies or +reading credentials in this change, app deployment, enabling the AWS intake +gate before actual qualification, deleting retained sources, generic policy +frameworks or expiring activation. Acceptance: runtime has conditional source +writes/exact-version reads but no delete/abort; cleanup has exact-version delete +and multipart abort only inside managed source namespace, no writes or retained +sha256 artifact access; foreign principals and insecure transport denied. +Multipart initiation/parts must be exempt from conditional-header enforcement, +while PutObject and completion still require If-None-Match (AWS official +conditional-writes-enforce documentation). Preserve existing artifact runtime +access. Both principal ARNs must be distinct exact IAM users in the same account +and partition. Verify focused policy controls; ARCH/SEC and QA review before +any actual AWS policy application. Static tests do not establish deployed IAM +behavior; actual AWS qualification remains separately required. + +AWS policy candidate checks: 15 focused policy boundary tests passed in 0.83s; +Ruff and diff checks passed. Official AWS action reference confirms multipart +LIST has no s3:prefix condition key: bucket metadata listing is explicit, while +object reads/abort/deletion are source-scoped and version listing is prefix +restricted. No policies applied or source qualification claimed. + +Process-loss evidence update: V4 targeted after-commit test passed in 172.42s +at 221f14e85, schema0090, complete cleanup. V3 before-observation case passed +separately at the shorter fixture timing. These results prove local direct +worker process loss, not real broker/native execution or production timing. +The final test file has not been run as an aggregate at one final head. Keep +fork/thread warning and all failed preliminary receipts explicit. Later work +in this candidate only changes AWS policy generation/docs; crash-test code is +unchanged from the exact-head V4 launch. diff --git a/backend/scripts/aws_direct_user_config.py b/backend/scripts/aws_direct_user_config.py index b251ec9ee..0c83d02c7 100644 --- a/backend/scripts/aws_direct_user_config.py +++ b/backend/scripts/aws_direct_user_config.py @@ -9,83 +9,62 @@ from app.core.s3_validation import is_canonical_s3_bucket, is_canonical_s3_prefix -def generate_policies(*, bucket: str, private_prefix: str, user_arn: str) -> dict: - """Bind one IAM user to the existing content-addressed artifact namespace.""" - principal = re.fullmatch( - r"arn:(aws|aws-us-gov|aws-cn):iam::[0-9]{12}:user/" - r"(?:[A-Za-z0-9+=,.@_/-]+/)?[A-Za-z0-9+=,.@_-]{1,64}", - user_arn, - ) - if ( - principal is None - or not is_canonical_s3_bucket(bucket) - or not is_canonical_s3_prefix(private_prefix) - ): - raise ValueError("exact IAM user, bucket and private prefix are required") - bucket_arn = f"arn:{principal.group(1)}:s3:::{bucket}" - objects = f"{bucket_arn}/{private_prefix}/sha256/*" +def generate_policies(*, bucket: str, private_prefix: str, user_arn: str, cleanup_user_arn: str) -> dict: + """Separate source upload and cleanup while retaining immutable artifact access.""" + pattern = (r"arn:(aws|aws-us-gov|aws-cn):iam::([0-9]{12}):user/" + r"(?:[A-Za-z0-9+=,.@_-]+/)*[A-Za-z0-9+=,.@_-]{1,64}") + runtime, cleanup = re.fullmatch(pattern, user_arn), re.fullmatch(pattern, cleanup_user_arn) + if (runtime is None or cleanup is None or runtime.groups() != cleanup.groups() + or user_arn == cleanup_user_arn or not is_canonical_s3_bucket(bucket) + or not is_canonical_s3_prefix(private_prefix)): + raise ValueError("distinct same-account IAM users, exact bucket and private prefix are required") + bucket_arn = f"arn:{runtime.group(1)}:s3:::{bucket}" + artifacts = f"{bucket_arn}/{private_prefix}/sha256/*" + source_prefix = f"{private_prefix}/submission-source/v1/" + sources = f"{bucket_arn}/{source_prefix}*/bundle.zip" all_objects = f"{bucket_arn}/*" + # Multipart LIST has no s3:prefix IAM condition key. The adapter limits + # discovery to the exact managed key; object/abort rights remain scoped. + bucket_reads = [ + {"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketVersioning", "s3:ListBucketMultipartUploads"], "Resource": bucket_arn}, + {"Effect": "Allow", "Action": "s3:ListBucketVersions", + "Resource": bucket_arn, "Condition": {"StringLike": {"s3:prefix": source_prefix + "*"}}}, + ] return { - "user_policy": { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": ["s3:GetObject", "s3:PutObject"], - "Resource": objects, - }, - # HEAD of a missing key needs ListBucket to distinguish 404 from - # access denial. No object data outside the prefix is granted. - { - "Effect": "Allow", - "Action": "s3:ListBucket", - "Resource": bucket_arn, - }, - ], - }, - "bucket_policy": { - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "DenyInsecureTransport", - "Effect": "Deny", - "Principal": "*", - "Action": "s3:*", - "Resource": [bucket_arn, all_objects], - "Condition": {"Bool": {"aws:SecureTransport": "false"}}, - }, - { - "Sid": "DenyForeignObjectAccess", - "Effect": "Deny", - "Principal": "*", - "Action": "s3:*", - "Resource": all_objects, - "Condition": {"ArnNotEquals": {"aws:PrincipalArn": user_arn}}, - }, - { - "Sid": "DenyOutsideArtifactNamespace", - "Effect": "Deny", - "Principal": "*", - "Action": ["s3:GetObject", "s3:GetObjectVersion", "s3:PutObject"], - "NotResource": objects, - }, - { - "Sid": "DenyArtifactDeletion", - "Effect": "Deny", - "Principal": "*", - "Action": ["s3:DeleteObject", "s3:DeleteObjectVersion"], - "Resource": all_objects, - }, - { - "Sid": "DenyUnconditionalPut", - "Effect": "Deny", - "Principal": "*", - "Action": "s3:PutObject", - "Resource": all_objects, - "Condition": {"Null": {"s3:if-none-match": "true"}}, - }, - ], - }, + "user_policy": {"Version": "2012-10-17", "Statement": [ + {"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": artifacts}, + {"Effect": "Allow", "Action": ["s3:GetObject", "s3:GetObjectVersion", "s3:PutObject", + "s3:ListMultipartUploadParts"], "Resource": sources}, + *bucket_reads, + ]}, + "cleanup_policy": {"Version": "2012-10-17", "Statement": [ + {"Effect": "Allow", "Action": ["s3:GetObject", "s3:GetObjectVersion", "s3:DeleteObjectVersion", + "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"], "Resource": sources}, + *bucket_reads, + ]}, + "bucket_policy": {"Version": "2012-10-17", "Statement": [ + {"Sid": "DenyInsecureTransport", "Effect": "Deny", "Principal": "*", "Action": "s3:*", + "Resource": [bucket_arn, all_objects], "Condition": {"Bool": {"aws:SecureTransport": "false"}}}, + {"Sid": "DenyForeignObjectAccess", "Effect": "Deny", "Principal": "*", "Action": "s3:*", + "Resource": all_objects, + "Condition": {"ArnNotEquals": {"aws:PrincipalArn": [user_arn, cleanup_user_arn]}}}, + {"Sid": "DenyOutsideArtifactNamespace", "Effect": "Deny", "Principal": "*", "Action": "s3:*", + "NotResource": [bucket_arn, artifacts, sources]}, + {"Sid": "DenyCleanupOutsideSource", "Effect": "Deny", "Principal": "*", "Action": "s3:*", + "NotResource": [bucket_arn, sources], "Condition": {"ArnEquals": {"aws:PrincipalArn": cleanup_user_arn}}}, + {"Sid": "DenyCleanupWrites", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", + "Resource": all_objects, "Condition": {"ArnEquals": {"aws:PrincipalArn": cleanup_user_arn}}}, + {"Sid": "DenyRuntimeDestruction", "Effect": "Deny", "Principal": "*", + "Action": ["s3:DeleteObject", "s3:DeleteObjectVersion", "s3:AbortMultipartUpload"], + "Resource": all_objects, "Condition": {"ArnNotEquals": {"aws:PrincipalArn": cleanup_user_arn}}}, + {"Sid": "DenyUnversionedDeletion", "Effect": "Deny", "Principal": "*", + "Action": "s3:DeleteObject", "Resource": all_objects}, + {"Sid": "DenyArtifactDeletion", "Effect": "Deny", "Principal": "*", + "Action": ["s3:DeleteObject", "s3:DeleteObjectVersion"], "Resource": artifacts}, + {"Sid": "DenyUnconditionalPut", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", + "Resource": all_objects, "Condition": {"Null": {"s3:if-none-match": "true"}, + "Bool": {"s3:ObjectCreationOperation": "true"}}}, + ]}, } @@ -94,6 +73,7 @@ def main() -> None: parser.add_argument("--bucket", required=True) parser.add_argument("--private-prefix", required=True) parser.add_argument("--user-arn", required=True) + parser.add_argument("--cleanup-user-arn", required=True) arguments = parser.parse_args() try: policies = generate_policies(**vars(arguments)) diff --git a/backend/tests/test_aws_direct_user_config.py b/backend/tests/test_aws_direct_user_config.py index 7aa0a9f71..dc0dd5552 100644 --- a/backend/tests/test_aws_direct_user_config.py +++ b/backend/tests/test_aws_direct_user_config.py @@ -1,70 +1,85 @@ """Security boundaries of the generated dedicated S3 identity policies.""" - import pytest - from scripts.aws_direct_user_config import generate_policies +RUNTIME = "arn:aws:iam::123456789012:user/workstream-storage" +CLEANUP = "arn:aws:iam::123456789012:user/workstream-source-cleanup" +BUCKET = "arn:aws:s3:::example-artifacts" +ARTIFACTS = BUCKET + "/workstream/sha256/*" +SOURCES = BUCKET + "/workstream/submission-source/v1/*/bundle.zip" + + +def _arguments(): + return dict(bucket="example-artifacts", private_prefix="workstream", + user_arn=RUNTIME, cleanup_user_arn=CLEANUP) -def test_runtime_cannot_administer_or_delete_artifacts(): - policies = generate_policies( - bucket="example-artifacts", - private_prefix="workstream", - user_arn="arn:aws:iam::123456789012:user/workstream-storage", - ) + +def test_runtime_cannot_administer_delete_or_abort_sources(): + policies = generate_policies(**_arguments()) statements = policies["user_policy"]["Statement"] - assert statements == [ - { - "Effect": "Allow", - "Action": ["s3:GetObject", "s3:PutObject"], - "Resource": "arn:aws:s3:::example-artifacts/workstream/sha256/*", - }, - { - "Effect": "Allow", - "Action": "s3:ListBucket", - "Resource": "arn:aws:s3:::example-artifacts", - }, - ] + assert statements[0] == {"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": ARTIFACTS} + assert statements[1] == {"Effect": "Allow", "Action": ["s3:GetObject", "s3:GetObjectVersion", "s3:PutObject", + "s3:ListMultipartUploadParts"], "Resource": SOURCES} + denials = {row["Sid"]: row for row in policies["bucket_policy"]["Statement"]} + assert all(row["Effect"] == "Deny" and row["Principal"] == "*" for row in denials.values()) + assert denials["DenyRuntimeDestruction"]["Action"] == ["s3:DeleteObject", "s3:DeleteObjectVersion", "s3:AbortMultipartUpload"] + assert denials["DenyRuntimeDestruction"]["Resource"] == BUCKET + "/*" + assert denials["DenyRuntimeDestruction"]["Condition"] == {"ArnNotEquals": {"aws:PrincipalArn": CLEANUP}} + assert denials["DenyForeignObjectAccess"]["Condition"] == {"ArnNotEquals": {"aws:PrincipalArn": [RUNTIME, CLEANUP]}} + assert denials["DenyOutsideArtifactNamespace"]["NotResource"] == [BUCKET, ARTIFACTS, SOURCES] + + +def test_cleanup_cannot_write_or_delete_retained_artifacts_or_create_delete_markers(): + policies = generate_policies(**_arguments()) + statements = policies["cleanup_policy"]["Statement"] + assert statements[0] == {"Effect": "Allow", "Action": ["s3:GetObject", "s3:GetObjectVersion", "s3:DeleteObjectVersion", + "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"], "Resource": SOURCES} denials = {row["Sid"]: row for row in policies["bucket_policy"]["Statement"]} - assert all(row["Effect"] == "Deny" for row in denials.values()) - assert denials["DenyArtifactDeletion"]["Action"] == [ - "s3:DeleteObject", "s3:DeleteObjectVersion" - ] + assert denials["DenyCleanupOutsideSource"]["NotResource"] == [BUCKET, SOURCES] + assert denials["DenyCleanupOutsideSource"]["Condition"] == {"ArnEquals": {"aws:PrincipalArn": CLEANUP}} + assert denials["DenyCleanupWrites"]["Action"] == "s3:PutObject" + assert denials["DenyCleanupWrites"]["Resource"] == BUCKET + "/*" + assert denials["DenyCleanupWrites"]["Condition"] == {"ArnEquals": {"aws:PrincipalArn": CLEANUP}} + assert denials["DenyUnversionedDeletion"]["Action"] == "s3:DeleteObject" + assert denials["DenyUnversionedDeletion"]["Resource"] == BUCKET + "/*" + assert denials["DenyArtifactDeletion"]["Resource"] == ARTIFACTS + assert denials["DenyArtifactDeletion"]["Action"] == ["s3:DeleteObject", "s3:DeleteObjectVersion"] + + +def test_multipart_discovery_uses_supported_bucket_conditions(): + policies = generate_policies(**_arguments()) + for name in ("user_policy", "cleanup_policy"): + bucket_statements = policies[name]["Statement"][-2:] + assert bucket_statements == [ + {"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketVersioning", "s3:ListBucketMultipartUploads"], "Resource": BUCKET}, + {"Effect": "Allow", "Action": "s3:ListBucketVersions", "Resource": BUCKET, + "Condition": {"StringLike": {"s3:prefix": "workstream/submission-source/v1/*"}}}, + ] + + +def test_conditional_completion_is_required_without_blocking_multipart_parts(): + statements = generate_policies(**_arguments())["bucket_policy"]["Statement"] + denials = {row["Sid"]: row for row in statements} assert denials["DenyUnconditionalPut"] == { - "Sid": "DenyUnconditionalPut", - "Effect": "Deny", - "Principal": "*", - "Action": "s3:PutObject", - "Resource": "arn:aws:s3:::example-artifacts/*", - "Condition": {"Null": {"s3:if-none-match": "true"}}, - } - assert denials["DenyForeignObjectAccess"]["Condition"] == { - "ArnNotEquals": { - "aws:PrincipalArn": "arn:aws:iam::123456789012:user/workstream-storage" - } + "Sid": "DenyUnconditionalPut", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", + "Resource": BUCKET + "/*", "Condition": {"Null": {"s3:if-none-match": "true"}, + "Bool": {"s3:ObjectCreationOperation": "true"}}, } - assert denials["DenyOutsideArtifactNamespace"]["NotResource"] == ( - "arn:aws:s3:::example-artifacts/workstream/sha256/*" - ) + assert denials["DenyInsecureTransport"]["Condition"] == {"Bool": {"aws:SecureTransport": "false"}} + assert denials["DenyInsecureTransport"]["Resource"] == [BUCKET, BUCKET + "/*"] -@pytest.mark.parametrize( - "field,value", - [ - ("user_arn", "arn:aws:iam::123456789012:user/*"), - ("user_arn", "arn:aws:iam::123456789012:role/runtime"), - ("user_arn", "arn:aws:iam::123456789012:user/ops/"), - ("user_arn", "arn:aws:iam::123456789012:user//"), - ("bucket", "*"), - ("private_prefix", "*"), - ("private_prefix", "../other"), - ], -) +@pytest.mark.parametrize("field,value", [ + ("user_arn", "arn:aws:iam::123456789012:user/*"), + ("user_arn", "arn:aws:iam::123456789012:role/runtime"), + ("user_arn", "arn:aws:iam::123456789012:user/ops/"), + ("user_arn", "arn:aws:iam::123456789012:user//"), + ("cleanup_user_arn", RUNTIME), + ("cleanup_user_arn", "arn:aws:iam::999999999999:user/cleanup"), + ("cleanup_user_arn", "arn:aws-cn:iam::123456789012:user/cleanup"), + ("cleanup_user_arn", "arn:aws:iam::123456789012:role/cleanup"), + ("bucket", "*"), ("private_prefix", "*"), ("private_prefix", "../other"), +]) def test_rejects_unbounded_or_foreign_identity_configuration(field, value): - arguments = { - "bucket": "example-artifacts", - "private_prefix": "workstream", - "user_arn": "arn:aws:iam::123456789012:user/workstream-storage", - } - arguments[field] = value with pytest.raises(ValueError): - generate_policies(**arguments) + generate_policies(**(_arguments() | {field: value})) diff --git a/docs/operations_aws_s3_credentials.md b/docs/operations_aws_s3_credentials.md index 0a897c9e5..69ddd85b8 100644 --- a/docs/operations_aws_s3_credentials.md +++ b/docs/operations_aws_s3_credentials.md @@ -4,16 +4,18 @@ Workstream stores file bytes in a private S3 bucket. PostgreSQL holds the metadata and ownership used to authorize access. Contributors, reviewers, setup agents and external checker guests do not receive the bucket credential. -The hosted application uses one dedicated IAM user's access key. This works +The hosted application uses a dedicated IAM user's access key. Source cleanup +uses a separate IAM user and private key file in its dedicated worker. This works on AWS or another hosting provider. No certificate authority, certificate renewal, three-identity verification job or expiring database activation is required. ## Provision the dedicated identity -Create a dedicated IAM user in the bucket owner’s AWS account, without console -access, group membership or other attached policies. This policy does not grant -cross-account access. Generate its restricted policy and the bucket policy using +Create two distinct IAM users in the bucket owner’s AWS account, without console +access, group membership or other attached policies: the runtime uploader/reader +and the source-cleanup worker. The generator rejects cross-account or identical +principals. Generate their restricted policies and the bucket policy using the deployment's actual bucket and existing private prefix: ```bash @@ -21,30 +23,48 @@ cd backend python -m scripts.aws_direct_user_config \ --bucket YOUR_BUCKET \ --private-prefix YOUR_EXISTING_PREFIX \ - --user-arn arn:aws:iam::YOUR_ACCOUNT:user/workstream-storage + --user-arn arn:aws:iam::YOUR_ACCOUNT:user/workstream-storage \ + --cleanup-user-arn arn:aws:iam::YOUR_ACCOUNT:user/workstream-source-cleanup ``` -The output contains `user_policy` and `bucket_policy`. Attach the former to -the dedicated user and apply the latter to the dedicated artifact bucket. +The output contains `user_policy`, `cleanup_policy` and `bucket_policy`. Attach +each identity policy only to its corresponding user; apply the bucket policy +to the dedicated artifact bucket. Review existing bucket users before replacing a bucket policy. Do not change the prefix of an existing deployment: retained objects must remain readable. -The user can read and conditionally create objects only in Workstream's -content-addressed prefix. It cannot delete objects, administer IAM or modify -bucket settings. `ListBucket` is granted for this bucket so a missing-object -HEAD request returns an authoritative absence rather than an access denial; -it exposes key names to the trusted storage service, not other object bytes. -The application must never interpret an access-denied response as absence. +The runtime can read and conditionally create content-addressed artifacts and +operation-owned `submission-source/v1//bundle.zip` objects. It can +read exact source versions, but cannot delete versions or abort multipart uploads. +Cleanup can read, abort and delete exact versions only in the managed source +prefix; it cannot write sources or access content-addressed artifact bytes. +Unversioned deletion is denied to both users, preventing delete-marker creation. + +Bucket-level listing permits authoritative HEAD absence checks and multipart +handle discovery. It exposes bucket key/handle metadata to the trusted storage +services, not unrelated object bytes. AWS does not support an `s3:prefix` IAM +condition on `ListBucketMultipartUploads`; the adapter must still use bounded +exact-key discovery. Version listing is prefix-restricted. See the +[AWS S3 action/condition reference](https://docs.aws.amazon.com/service-authorization/latest/reference/list_s3.html). +Never interpret access denial as absence. + +Failed and retained submission sources share the same prefix. IAM cannot tell +which source is accepted: the ART owner's committed cleanup claim, retention +checks and exact-version confirmation remain the deletion authority. Never +expose a general delete-by-key operation or cleanup credentials to API workers. Keep S3 Block Public Access enabled, bucket-owner-enforced ownership, versioning and default SSE-S3 (`AES256`) encryption enabled. This policy does not grant KMS permissions; it does not qualify an SSE-KMS deployment. Do not configure lifecycle expiration of retained artifacts. The bucket policy rejects insecure transport, foreign -object access, unconditional puts and deletion of objects or versions. +object access, unconditional final writes and deletion of content-addressed +artifacts. Conditional-header enforcement exempts multipart initiation/parts +using `s3:ObjectCreationOperation`; completing the upload still requires +`If-None-Match`. This follows [AWS conditional-write enforcement](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes-enforce.html). ## Keep credentials private -Create an access key for this dedicated user. Store its two values in a private +Create an access key for each dedicated user. Store each pair in a separate private JSON file readable only by the runtime service user: ```json @@ -56,13 +76,19 @@ Git, logs or chat. Mount the file read-only only into services performing artifact operations. Beat, MCP, the document parser and checker guests do not need it. Configure the exact IAM user ARN alongside the private file path; startup must reject an unexpected identity or an ambient credential source. +The cleanup worker uses its own credential-file and IAM-ARN settings and an +explicit upload-principal ARN; composition rejects identical principals. ## Verify and rotate Before cutover, test a synthetic artifact using the real restricted identity: conditional creation, complete hash/size readback, safe replay, missing-object handling, and rejection of overwrites, deletion, foreign-prefix writes and -anonymous reads. Confirm guide reads and submission upload/recovery through +anonymous reads. Qualify source multipart initiation/completion, pinned-version +reads, lost acknowledgments, separate-principal abort, exact-version removal +and retained-source survival. Runtime deletion and cleanup writes/foreign-prefix +access must fail with actual restricted credentials. The AWS intake gate stays +closed until this source qualification is complete. Confirm guide reads and submission upload/recovery through Workstream as well. These tests qualify the deployment; they do not create a time-limited permission record required by ordinary storage operations. From d43d530d7098111d501d0bc3a2fb10c8efef4efb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:40:54 +0100 Subject: [PATCH 246/513] Record crash proof and AWS policy review outcomes --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index ba82efcb4..32ae7e8e6 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8482,3 +8482,18 @@ The final test file has not been run as an aggregate at one final head. Keep fork/thread warning and all failed preliminary receipts explicit. Later work in this candidate only changes AWS policy generation/docs; crash-test code is unchanged from the exact-head V4 launch. + +Review closure: crash scope ARCH/SEC PASS and QA PASS WITH LOW RISKS pinned to +221f14e85 with separate V3/V4 receipts and stated limits. AWS policy scope +ARCH/SEC PASS and QA PASS WITH LOW RISKS at clean 88100a030; no findings. +Independent QA mutations adding runtime abort or removing multipart exception +were rejected by focused tests. No live policy application was performed. +Read-only AWS preflight through the intended workstream-provisioner confirmed +bucket versioning Enabled and retained the existing bucket policy (SHA256 +201a11a52f1f9984962190e3a71fceb89b896db9a16a3846928103a1aa191fae). +IAM ListUserPolicies on workstream-storage returned AccessDenied. Prepared +non-secret exact runtime/cleanup/bucket policy files and a two-user-scoped IAM +setup grant under local aws-source-qualification-20261124; requested admin +access/application. No alternate/default AWS credentials used. Runner owner +confirmed no concurrent bucket/IAM work; app configuration remains untouched. +AWS gate and live provider qualification remain open pending access and proof. From 631ece31199844015959a2c7a52953cb217648a3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:52:32 +0100 Subject: [PATCH 247/513] Prepare reviewed live AWS submission source qualification drill --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 33 +++ docs/operations_aws_s3_credentials.md | 11 + scripts/qualify_submission_source.py | 255 ++++++++++++++++++ 3 files changed, 299 insertions(+) create mode 100644 scripts/qualify_submission_source.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 32ae7e8e6..36fcaa626 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8497,3 +8497,36 @@ setup grant under local aws-source-qualification-20261124; requested admin access/application. No alternate/default AWS credentials used. Runner owner confirmed no concurrent bucket/IAM work; app configuration remains untouched. AWS gate and live provider qualification remain open pending access and proof. + + +### Prepare live source adapter qualification + +Allowed: local non-secret qualification script in +aws-source-qualification-20261124 and this record. Risk: high when executed +(provider writes/exact-version deletion); preparation is side-effect free. +Use existing production source/cleanup adapters and private direct-user files, +new UUIDv7 synthetic operation keys only, durable local target journal before +provider creation, and exact upload/version cleanup only for those targets. +Never touch product rows or retained product keys. Refuse ambient AWS settings +and require explicit runtime/cleanup principals. Check conditional multipart, +exact readback, runtime delete/abort denial, lost begin/completion/delete ACK, +and retained independent source survival. Return non-secret results and keep +uncertain targets in the journal. No execution before access is supplied and +bounded ARCH/SEC review of the script hash. This qualifies provider behavior, +not SQL ownership, broker execution, native PRE/POST or the complete journey. + +LIVE-AWS-DRILL-01 pre-execution finding: lost-response checks must compare the +reconciled handle/version with the exact successful provider response retained +by the fault injector. The local drill now retains those identifiers in memory +and its fsynced journal, refuses a different discovered upload before abort, +and requires the recovered/deleted VersionId to match. No drill execution or +AWS mutation has occurred; re-review the new script hash before use. + +Qualification preparation closure: ARCH/SEC PASS for script SHA256 + a94f860a2efc01f6ac5612c47e5d12fae43bf9aae5b7b56b812ae5ed44aa5ff9. +Compile, Ruff, help/import and optimized-mode rejection before provider/report +I/O passed. No credential contents read or AWS drill executed. Retain an +identical copy as scripts/qualify_submission_source.py in this same PR, with +pilot-specific invocation/limits in operations_aws_s3_credentials.md; these two +paths extend this preparation scope for reproducibility. IAM admin action is +still pending. Runtime file permissions were inspected only and are already0400. diff --git a/docs/operations_aws_s3_credentials.md b/docs/operations_aws_s3_credentials.md index 69ddd85b8..5015b0fb5 100644 --- a/docs/operations_aws_s3_credentials.md +++ b/docs/operations_aws_s3_credentials.md @@ -92,6 +92,17 @@ closed until this source qualification is complete. Confirm guide reads and subm Workstream as well. These tests qualify the deployment; they do not create a time-limited permission record required by ordinary storage operations. +The reviewed pilot drill is [qualify_submission_source.py](../scripts/qualify_submission_source.py). +It is deliberately pinned to the current pilot bucket, prefix and two principal +ARNs; it is not a generic cleanup command. Run from the repository root with +`PYTHONPATH=backend`, explicit `--runtime-key-file`, `--cleanup-key-file` and a +new private `--report` JSONL path. Both key files must have mode `0400`. +It creates only new synthetic operation keys, journals each target before +provider I/O, and cleans only their exact handles/versions. A failed run retains +its journal and uncertain targets for reconciliation. It does not test product +SQL ownership or the public submission journey and must not be counted as those +proofs. Do not run it before the reviewed IAM policies are applied. + To rotate, create the replacement key, write a new private file, verify the identity and storage operations, restart affected consumers with the new file, and disable the old key. Delete the old key after verifying that no service diff --git a/scripts/qualify_submission_source.py b/scripts/qualify_submission_source.py new file mode 100644 index 000000000..80d083327 --- /dev/null +++ b/scripts/qualify_submission_source.py @@ -0,0 +1,255 @@ +"""Explicit live AWS adapter drill; synthetic keys only, no product SQL writes. + +Run with the reviewed backend on PYTHONPATH. Private key files must already have +mode0400. This script never applies policies and never sweeps existing objects. +A failed run keeps its private JSONL journal for exact-target reconciliation. +""" +import argparse +import asyncio +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta +import hashlib +import json +import os +from pathlib import Path +import subprocess + +from botocore.exceptions import ClientError +from app.adapters.artifacts import create_artifact_store_bootstrap +from app.adapters.artifacts.source_cleanup import S3SubmissionSourceCleanup +from app.core.config import Settings +from app.core.identifiers import new_record_id +from app.interfaces.artifacts import ( + ArtifactStoreNamespaceClaim, artifact_store_namespace_material, + ArtifactPreconditionFailedError, ArtifactStoreUnavailableError, ArtifactIntegrityError, +) +from app.modules.artifacts.api.submission_intake import ( + SubmissionSourceLocation, SubmissionSourceUploadIntent, SubmissionSourceCompletion, +) + +BUCKET = "flow-workstream-pilot-artifacts" +PREFIX = "workstream/artifacts" +RUNTIME = "arn:aws:iam::094032936130:user/workstream-storage" +CLEANUP = "arn:aws:iam::094032936130:user/workstream-source-cleanup" + + +def store_for(key_file, principal): + limits = {f"artifact_admission_{scope}_maximum_bytes": 6 * 1024**2 + for scope in ("task", "producer", "project", "deployment")} + settings = Settings(environment="production", artifact_store_backend="s3_compatible", + artifact_s3_provider_profile="aws_s3", artifact_s3_region="eu-north-1", + artifact_s3_bucket=BUCKET, artifact_s3_private_prefix=PREFIX, + artifact_s3_credential_mode="aws_access_key", artifact_s3_runtime_user_arn=principal, + artifact_s3_direct_user_credential_file=key_file, + artifact_stream_buffer_bytes=65536, artifact_s3_operation_total_timeout_seconds=60, + **limits) + bootstrap = create_artifact_store_bootstrap(settings) + identity = bootstrap.namespace_identity + _, fingerprint = artifact_store_namespace_material(backend="s3_compatible", + adapter_identity=bootstrap.identity, namespace_identity=identity) + return bootstrap.initialize_after_namespace_claim( + ArtifactStoreNamespaceClaim(bootstrap.identity, identity, fingerprint)) + + +@asynccontextmanager +async def lose_ack(store, operation, emit): + original = store._client + effect = {} + + class Client: + def __init__(self, inner): + self.inner = inner + + def __getattr__(self, name): + method = getattr(self.inner, name) + if name != operation: + return method + + async def lost(**kwargs): + result = await method(**kwargs) + # Record the returned handle/version privately before injecting loss. + effect.update(upload_id=result.get("UploadId"), version_id=result.get("VersionId")) + emit("provider_effect_before_lost_ack", operation=operation, **effect) + raise OSError("injected response loss after successful provider operation") + return lost + + @asynccontextmanager + async def wrapped(): + async with original() as client: + yield Client(client) + store._client = wrapped + try: + yield effect + finally: + store._client = original + + +async def denied(store, operation, **kwargs): + async with store._client() as client: + try: + await getattr(client, operation)(Bucket=BUCKET, **kwargs) + except ClientError as error: + if error.response.get("Error", {}).get("Code") in {"AccessDenied", "403"}: + return + raise AssertionError("unexpected denial classification") from None + raise AssertionError("restricted operation unexpectedly permitted") + + +async def qualify(runtime, cleanup_store, emit): + cleanup = S3SubmissionSourceCleanup(cleanup_store) + owned = set() + + def intent(): + location = SubmissionSourceLocation(operation_id=new_record_id(), namespace_id="primary", + namespace_fingerprint=runtime._expected_namespace_fingerprint(), provider_profile="aws-s3-v1") + owned.add(location.operation_id) + value = SubmissionSourceUploadIntent(location=location, upload_fence=1, + maximum_raw_bytes=6 * 1024**2, declared_raw_bytes=None, part_bytes=5 * 1024**2, + idle_timeout_seconds=30.0, upload_deadline_at=datetime.now(UTC) + timedelta(minutes=10)) + emit("owned_target_before_provider_io", intent=value.model_dump(mode="json")) + return value + + async def completion(value, body): + upload = await runtime.begin_source_upload(value) + emit("upload", upload=upload.model_dump(mode="json")) + parts = [] + for offset in range(0, len(body), value.part_bytes): + parts.append(await runtime.upload_source_part(upload, len(parts) + 1, body[offset:offset + value.part_bytes])) + result = SubmissionSourceCompletion(upload=upload, parts=tuple(parts), + raw_sha256="sha256:" + hashlib.sha256(body).hexdigest(), raw_byte_count=len(body)) + emit("completion_ready", completion=result.model_dump(mode="json")) + return result + + async def read_exact(source, body): + digest, count = hashlib.sha256(), 0 + async for chunk in runtime.open_source(source): + assert 0 < len(chunk) <= 65536 + count += len(chunk) + digest.update(chunk) + assert count == len(body) and digest.hexdigest() == hashlib.sha256(body).hexdigest() + + async def remove_owned(source, upload): + assert source.location.operation_id in owned and source.location == upload.intent.location + result = await cleanup.remove(source, upload) + assert result.object_absent and result.writes_settled and result.parts_absent + emit("exact_source_removal_confirmed", source=source.model_dump(mode="json")) + + body = b"qualification-source\n" * (5 * 1024**2 // 21 + 2000) + first_intent, retained_intent = intent(), intent() + first_upload = await completion(first_intent, body) + first = await runtime.complete_source_upload(first_upload) + emit("sealed", source=first.model_dump(mode="json")) + assert first.provider_generation not in {"", "null"} and len(first_upload.parts) == 2 + await read_exact(first, body) + assert await runtime.observe_source_upload(first_upload) == first + retained_upload = await completion(retained_intent, body) + retained = await runtime.complete_source_upload(retained_upload) + emit("sealed", source=retained.model_dump(mode="json")) + assert first.raw_sha256 == retained.raw_sha256 and first.location != retained.location + competitor = await completion(first_intent.model_copy(update={"upload_fence": 2}), b"different") + try: + await runtime.complete_source_upload(competitor) + except ArtifactPreconditionFailedError: + pass + else: + raise AssertionError("conditional source overwrite accepted") + key = runtime._source_key(first.location) + await denied(runtime, "delete_object", Key=key, VersionId=first.provider_generation) + await denied(runtime, "abort_multipart_upload", Key=key, UploadId=competitor.upload.provider_upload_id) + await cleanup_store.request_source_abort(competitor.upload) + assert await cleanup_store.source_upload_parts_absent(competitor.upload) + await denied(cleanup_store, "put_object", Key=key, Body=b"forbidden", IfNoneMatch="*") + await denied(cleanup_store, "get_object", Key=PREFIX + "/sha256/00/" + "0" * 62) + emit("passed", check="conditional_versioned_multipart_and_separate_principals") + async with lose_ack(cleanup_store, "delete_object", emit) as delete_effect: + try: + await remove_owned(first, first_upload.upload) + except ArtifactStoreUnavailableError: + pass + else: + raise AssertionError("lost deletion response did not remain uncertain") + assert delete_effect["version_id"] == first.provider_generation + await remove_owned(first, first_upload.upload) + await read_exact(retained, body) + emit("passed", check="lost_delete_ack_and_independent_retained_source_survival") + await remove_owned(retained, retained_upload.upload) + + missing_handle = intent() + async with lose_ack(runtime, "create_multipart_upload", emit) as begin_effect: + try: + await runtime.begin_source_upload(missing_handle) + except ArtifactStoreUnavailableError: + pass + else: + raise AssertionError("lost begin response did not remain uncertain") + handles = await cleanup_store.discover_source_uploads(missing_handle) + assert len(handles) == 1 and handles[0].provider_upload_id == begin_effect["upload_id"] + emit("discovered_handles_before_abort", uploads=[v.model_dump(mode="json") for v in handles]) + await cleanup_store.request_source_abort(handles[0]) + assert await cleanup_store.source_upload_parts_absent(handles[0]) + assert await cleanup_store.discover_source_uploads(missing_handle) == () + emit("passed", check="lost_begin_ack_exact_handle_discovery_and_abort") + + lost_completion = await completion(intent(), b"response-loss-source") + async with lose_ack(runtime, "complete_multipart_upload", emit) as complete_effect: + try: + await runtime.complete_source_upload(lost_completion) + except ArtifactStoreUnavailableError: + pass + else: + raise AssertionError("lost completion response did not remain uncertain") + recovered = await runtime.observe_source_upload(lost_completion) + assert recovered is not None and recovered.provider_generation == complete_effect["version_id"] + emit("recovered_sealed", source=recovered.model_dump(mode="json")) + await read_exact(recovered, b"response-loss-source") + try: + await runtime.observe_source_upload(lost_completion.model_copy(update={"raw_sha256": "sha256:" + "0" * 64})) + except ArtifactIntegrityError: + pass + else: + raise AssertionError("substituted raw hash accepted") + await remove_owned(recovered, lost_completion.upload) + emit("passed", check="lost_completion_ack_exact_bytes_and_hash_substitution_refusal") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--runtime-key-file", required=True, type=Path) + parser.add_argument("--cleanup-key-file", required=True, type=Path) + parser.add_argument("--report", required=True, type=Path) + args = parser.parse_args() + if not __debug__: + parser.error("qualification requires Python assertions enabled; do not use -O") + # Never load the invalid default AWS profile or ambient credentials. + for key in tuple(os.environ): + if key.startswith(("AWS_", "BOTOCORE_")): + os.environ.pop(key) + fd = os.open(args.report, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + runtime = cleanup_store = None + with os.fdopen(fd, "w") as output: + def emit(event, **facts): + output.write(json.dumps({"event": event, "at": datetime.now(UTC).isoformat(), **facts}) + "\n") + output.flush() + os.fsync(output.fileno()) + try: + head = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() + emit("started", commit=head, bucket=BUCKET, prefix=PREFIX, runtime=RUNTIME, cleanup=CLEANUP, + script_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()) + runtime = store_for(args.runtime_key_file.resolve(), RUNTIME) + cleanup_store = store_for(args.cleanup_key_file.resolve(), CLEANUP) + asyncio.run(asyncio.wait_for(qualify(runtime, cleanup_store, emit), timeout=900)) + emit("completed", result="passed") + print("AWS source adapter qualification passed; see private report") + except BaseException as error: + emit("failed", error_type=type(error).__name__) + print("AWS source adapter qualification failed; retain journal and owned targets") + raise SystemExit(1) from None + finally: + if runtime is not None: + runtime.close() + if cleanup_store is not None: + cleanup_store.close() + + +if __name__ == "__main__": + main() From 521898c4fac4ed9c8c12b334b42da4876ccc6d16 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 11:58:16 +0100 Subject: [PATCH 248/513] Verify source finalization reaches automatic acceptance and awards --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 18 +++++++ .../test_submission_intake_admission.py | 10 +++- .../test_submission_intake_progress.py | 50 +++++++++++++++++-- 3 files changed, 74 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 36fcaa626..e63522445 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8530,3 +8530,21 @@ identical copy as scripts/qualify_submission_source.py in this same PR, with pilot-specific invocation/limits in operations_aws_s3_credentials.md; these two paths extend this preparation scope for reproducibility. IAM admin action is still pending. Runtime file permissions were inspected only and are already0400. + + +### Join source-preserving finalization to automatic acceptance proof + +Concrete gap: source T5/POST integration currently ends at review_pending; +automatic acceptance/award tests use a separate routing source fixture. Extend +the existing source integration with one approved human_review_required=false +policy and money/project_points definitions, using real Operator lifecycle +transitions. Allowed: intake admission fixture, source progress integration test +and this record. Prohibited: production/schema changes, changing default-true +policy behavior, test timestamps/fences, real payments, native/AWS/public-ZIP +qualification claims. Acceptance: the exact source-backed Submission reaches +shared FinalAcceptance, one accepted_submission ContributionRecord with exact +contributor/assignment/source hash/policy, exact configured award definitions, +no Review/reviewer contribution; finalized replay does not duplicate effects. +Verify the added real-PostgreSQL case and default-true control, structure/Ruff; +scoped QA/ARCH review. This joins an owner path, not the pending deployed +public-API/runner proof. Keep other required work in the unchanged goal. diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py index 55bde9edb..19c73e8ac 100644 --- a/backend/tests/artifacts/test_submission_intake_admission.py +++ b/backend/tests/artifacts/test_submission_intake_admission.py @@ -69,6 +69,7 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques factory = async_sessionmaker(engine, expire_on_commit=False) namespace = _namespace(_settings(tmp_path)) source_store_factory = None + automatic_acceptance = getattr(request, "param", None) == "automatic_acceptance" if getattr(request, "param", None) == "minio": from tests.artifacts.intake_post_support import minio_source_fixture namespace, source_store_factory = await minio_source_fixture() @@ -89,9 +90,16 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques from tests.checkers.external.support import pre_registry_spec, post_registry_spec plan, _ = await approved_selected_policy_fixture( factory, namespace, guide_version="v1", + human_review_required=not automatic_acceptance, + contribution_awards=("money", "project_points") if automatic_acceptance else (), pre_submit_registry_spec=pre_registry_spec(), post_submit_registry_spec=post_registry_spec(), ) + if automatic_acceptance: + from tests.reviews.lifecycle.transition_support import command_for, transition + await admin_access.signed.grant(admin_access.admin, admin_access.target) + await transition(await command_for(admin_access.target.id, "shadow")) + await transition(await command_for(admin_access.target.id, "live")) project = plan.lineage.project_id manager = await project_manager(admin_access, project) grant_id = await grant(admin_access, manager, project) @@ -109,7 +117,7 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques yield SimpleNamespace(factory=factory, actor=actor, task=task, assignment=assignment, admission=admission, project=project, namespace=namespace, access=admin_access, manager=manager, grant_id=grant_id, - source_store_factory=source_store_factory) + source_store_factory=source_store_factory, automatic_acceptance=automatic_acceptance) finally: await engine.dispose() diff --git a/backend/tests/artifacts/test_submission_intake_progress.py b/backend/tests/artifacts/test_submission_intake_progress.py index 574cbf26d..f2a6af745 100644 --- a/backend/tests/artifacts/test_submission_intake_progress.py +++ b/backend/tests/artifacts/test_submission_intake_progress.py @@ -129,7 +129,10 @@ async def _assert_retained_custody(f, owner, request, result, expired_claim): selectors=selectors, evaluation_selectors=evaluation_selectors) -@pytest.mark.parametrize("expired_claim,post_failure", [(False, False), (True, False), (False, True)]) +@pytest.mark.parametrize("admission_intake,expired_claim,post_failure", [ + (None, False, False), (None, True, False), (None, False, True), + ("automatic_acceptance", False, False), +], indirect=["admission_intake"]) async def test_t5_finalizes_same_source_with_one_submission_and_post_dispatch(admission_intake, tmp_path, monkeypatch, expired_claim, post_failure): f = admission_intake @@ -242,8 +245,49 @@ def missing_source(*_args, **_kwargs): assert delivery_outcome(delivered)["delivery_state"] == "acknowledged", delivery_outcome(delivered) async with f.factory.begin() as session: governed = await submission_history_repository(session).read_operation_outcome(**selectors) - assert governed.status == "review_pending" - await public_progress("review_pending", result.evaluation_request_id, governed=True) + assert governed.status == ("accepted" if f.automatic_acceptance else "review_pending") + assert await finalizer.run(owner.operation_id) == result + if f.automatic_acceptance: + await _assert_automatic_acceptance(f, result, request.source) + await public_progress(governed.status, result.evaluation_request_id, governed=True) finally: store.close() + + +async def _assert_automatic_acceptance(f, result, source): + from sqlalchemy import select, func + from app.modules.tasks.models import Submission + from app.modules.reviews.acceptance.models import FinalAcceptance + from app.modules.contributions.records.models import ContributionRecord + from app.modules.contributions.models import ContributionAwardDefinition + from app.modules.compensation.awards.models import CompensationAward + + async with f.factory() as session: + acceptance = (await session.scalars(select(FinalAcceptance).where( + FinalAcceptance.task_id == str(f.task)))).one() + record = (await session.scalars(select(ContributionRecord).where( + ContributionRecord.task_id == str(f.task)))).one() + submission = await session.get(Submission, str(result.submission_id)) + assert acceptance.submission_id == record.submission_id == submission.id + assert record.contribution_type == "accepted_submission" + assert record.contributor_id == str(f.actor.actor_profile_id) + assert record.source_task_assignment_id == str(f.assignment) + assert record.source_final_acceptance_id == acceptance.id + assert record.source_review_id is record.source_review_lease_id is None + assert record.artifact_hash == source.raw_sha256 + assert record.contribution_policy_version_id == submission.contribution_policy_version_id + assert await session.scalar(text("SELECT count(*) FROM reviews WHERE task_id=:id"), {"id": f.task}) == 0 + awards = (await session.scalars(select(CompensationAward).where( + CompensationAward.contribution_record_id == record.id))).all() + definitions = (await session.scalars(select(ContributionAwardDefinition).where( + ContributionAwardDefinition.contribution_policy_version_id == record.contribution_policy_version_id, + ContributionAwardDefinition.contribution_type == record.contribution_type))).all() + assert len(awards) == len(definitions) == 2 + assert {a.instrument_type for a in awards} == {"money", "project_points"} + actual = {(a.award_definition_id, a.adapter_binding_id, a.instrument_type, a.unit_code, a.quantity) for a in awards} + expected = {(d.id, d.adapter_binding_id, d.instrument_type, d.unit_code, d.quantity) for d in definitions} + assert actual == expected + assert all(a.contributor_id == record.contributor_id and a.project_id == record.project_id + and a.contribution_policy_version_id == record.contribution_policy_version_id for a in awards) + assert await session.scalar(select(func.count()).select_from(ContributionRecord)) == 1 From f3e83e20022339e463c61784160e581f2b23168f Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:03:26 +0100 Subject: [PATCH 249/513] Record source-backed acceptance verification and review --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e63522445..d3f56e65a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8548,3 +8548,13 @@ no Review/reviewer contribution; finalized replay does not duplicate effects. Verify the added real-PostgreSQL case and default-true control, structure/Ruff; scoped QA/ARCH review. This joins an owner path, not the pending deployed public-API/runner proof. Keep other required work in the unchanged goal. + +Verification closure at 521898c4f: the automatic-acceptance case and default +human-review control passed together (2 passed in 90.00s); isolated receipt +/tmp/submission-source-autoaccept.json confirms schema0090 and complete database +and MinIO cleanup. The launcher recorded precommit631ece311 with the final test +worktree, so this is compatible evidence, not an exact-head launch. Structure, +scoped Ruff and diff checks passed. ARCH/SEC PASS and QA PASS WITH LOW RISKS +reported no findings; independent QA probes rejected substituted source hash +and award quantity. This proves the source-backed owner path and public progress +read, not public ZIP/native/AWS execution or the aggregate four-case matrix. From 1c4768d0af38cf354411c999bb1a1413805402d4 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:09:00 +0100 Subject: [PATCH 250/513] Reconcile remaining submission work with verified recovery evidence --- .commitrail/INDEX.md | 2 +- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 31 +++++++++++-------- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++++++ 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index d070ae7d7..d36498ac9 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP intake, PRE/T4/T5 and CLI/MCP implementation have focused proof; sealed-source scheduling and expired-foreground recovery are wired. Next: interrupted/unsealed and orphan reclamation, obsolete-writer retirement, separate-runner integration, native/provider qualification and full acceptance/configuration closure. See the overview for checked implementation versus remaining evidence. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP intake, PRE/T4/T5, unsealed cleanup and both POST review-policy branches have focused proof; admission-only TASK writer is removed. Next: separate-runner integration and live provider qualification, remaining preparation-writer retirement and orphan reconciliation, then full acceptance/configuration closure. See the overview for checked implementation versus remaining evidence. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 4a5f6aade..526a7716d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -22,6 +22,10 @@ limits are in [the change record](WS-SUBMIT-001-01.md). - [x] Production sealed-source sweep wiring: explicit profile, dedicated worker/task isolation, 12-hour schedule, indexed discovery and focused real-storage retry/retention proof. - [x] Expired receiving/PRE recovery through the sweep: current authority and task-lock recheck, old-owner fencing, exact pointer release, retained source charge and separate time for sealed cleanup. - [x] Historical cap fixture no longer depends on the old writer; capture, restore/recovery and neighboring upgrade controls passed. +- [x] Unsealed cleanup and discovered multipart handles use durable cleanup ownership; ambiguous empty discovery retains its charge. +- [x] Admission-only TASK writer removed; accepted-source finalization remains the sole Submission writer. +- [x] Source-backed POST reaches both default human review and automatic acceptance with exact contribution/award lineage and replay checks. +- [x] Actual finalizer process death before source observation and after commit has separate recovery receipts; real broker qualification remains open. Recent focused evidence includes atomic invalidation (`8a854f7a6`), public ZIP/T5 lineage (`168e5268f`), and policy-error translation (`d31a45773`). These and the cleanup/recovery runs recorded below are bounded results, not @@ -80,19 +84,18 @@ journey. The remaining cleanup and verification requirements below still apply. | Order | Required outcome | Concrete finishing evidence | | --- | --- | --- | -| 1 | Finish uncertain/unsealed and genuine-orphan reconciliation | Reconcile interrupted multipart and lost acknowledgements; retained/stalled sources survive; actual absence and settled writes release charges once; exercise worker loss/restart. | -| 2 | Remove superseded preparation/submission writers and remaining consumers | Trace all remaining callers, preserve their distinct authority/history contracts, then delete obsolete implementation. Current T5 `create_accepted` remains. | +| 1 | Finish remaining uncertain/orphan reconciliation | Reconcile interrupted multipart and lost acknowledgements; retained/stalled sources survive; actual absence and settled writes release charges once; exercise worker loss/restart. | +| 2 | Retire remaining superseded preparation writers and consumers | Trace all remaining callers, preserve their distinct authority/history contracts, then delete obsolete implementation. Current T5 `create_accepted` remains. | | 3 | Complete separate-runner integration and runtime/provider/resource qualification | Authenticated remote execution replacing the current API-side Unix-socket coupling; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. | | 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. | -The concrete next runtime gap is order 1. Sealed-source scheduling and task -isolation passed scoped implementation review at `8928f3924`; focused integration -cases passed across two runs. This is not deployed-provider or broker-crash -qualification. Expired-foreground recovery passed scoped review at `81d69a207`, -including blocked-task progress and after-lock service revocation. Unsealed/ -uncertain and genuine-orphan reconciliation remain unfinished. Further optional test -migration must not displace closing this integration. +The next integration boundary is the separate runner and live source provider, +in parallel with the remaining writer audit. Ordinary unsealed cleanup is +implemented; genuine-orphan reconciliation remains open. AWS policy and adapter +drill preparation are reviewed, but IAM administration access is pending and no +live source qualification has run. Do not repeat completed local proofs as a +substitute for connecting and testing the deployed journey. The current unsealed change extends that same cleanup owner: Local incomplete uploads can be reclaimed, and an observed late completion is retained until a @@ -103,8 +106,10 @@ lost-abort/replay case proves conservative charge retention then one release. Remote initiation without a recorded handle now retains discovered IDs before abort and binds them to a fresh cleanup authorization. Focused PostgreSQL/MinIO checks cover growing observations and lost-abort replay. Empty ambiguous -discovery remains charged; genuine-orphan reconciliation and operational crash -drills remain open. This partial implementation does not complete order 1. +discovery remains charged; genuine-orphan reconciliation and deployed operational +drills remain open. Actual local finalizer SIGKILL recovery has separate passing +before-observation and after-commit receipts, not a real broker crash proof. +This partial implementation does not complete order 1. ## Acceptance evidence still to close @@ -115,11 +120,11 @@ This is the final qualification queue, not a claim that all listed code is absen | --- | --- | --- | | A01–A03 | Public ZIP flow, default/project PRE and formal finalization tests | Complete API/CLI journey with required real runtime and POST evidence. | | A04–A08 | Metadata/body replay, competing custody, interruption and T4 uncertainty tests | Reconcile exact cases and execute integrated final-head failure/retry matrix. | -| A09–A13 | T5 rollback/redelivery, accepted authority, pending reads and old-POST guard | Real worker crash/broker-unavailable drill and final-head reconciliation. | +| A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Celery/broker-unavailable drill and final-head reconciliation. | | A14–A18 | Cleanup lock/retention/charge owners and Local/MinIO provider tests | Production sweeps, accepted-source survival, AWS versions and uncertain multipart ownership. | | A19–A23 | Streaming/framing, safe archives, semantic identity and bounded findings code/tests | Measured permitted maxima/slow-provider memory bounds and complete safety matrix. | | A24–A30 | Source/result/fence contracts and runtime/capacity/substitution tests | Actual native isolation/failure/cleanup, multiple replicas/nodes, saturation and adapter qualification. | -| A31–A32 | Existing governed POST/revision/acceptance owners preserved with focused journeys | Final combined downstream tests, exact ContributionRecord/award facts, both review branches. | +| A31–A32 | Source-backed POST reaches review_pending or shared automatic FinalAcceptance with exact contribution/awards and replay checks | Complete public-API/native journey and final combined downstream tests, including human acceptance. | | A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | Finish old-writer retirement and full current-head migration/client convergence proof. | ## Configuration and external evidence diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d3f56e65a..793dd1e6d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8558,3 +8558,13 @@ scoped Ruff and diff checks passed. ARCH/SEC PASS and QA PASS WITH LOW RISKS reported no findings; independent QA probes rejected substituted source hash and award quantity. This proves the source-backed owner path and public progress read, not public ZIP/native/AWS execution or the aggregate four-case matrix. + +Recovery controls at f3e83e200 also passed: expired finalization ownership and +POST infrastructure failure/retry (2 passed in53.58s). Receipt +/tmp/submission-source-recovery-controls.json confirms schema0090 and complete +database/MinIO cleanup. One existing Pydantic serialization warning remains in +the retry fixture. Together with the prior two-case run this covers all four +parameters, across separate runs rather than a single final-head aggregate. +Reconcile the overview/index to these completed boundaries; remaining native, +AWS, broker, preparation-writer and orphan requirements stay open. This is an +evidence update, not a deployed-capability claim or goal completion. From 9c3305a56c13860a8dec310e943a9dff99296297 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:12:50 +0100 Subject: [PATCH 251/513] Bound historical verifier fixture retirement and record stale dependency --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 793dd1e6d..d7b8b4853 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8568,3 +8568,29 @@ parameters, across separate runs rather than a single final-head aggregate. Reconcile the overview/index to these completed boundaries; remaining native, AWS, broker, preparation-writer and orphan requirements stay open. This is an evidence update, not a deployed-capability claim or goal completion. + +### Preserve retained verifier setup before preparation-writer retirement + +The retained-verification tests still manufacture historical SHA admissions +through the superseded preparation command. Capture its pending-verification +rows and exact bytes once, then replace that test setup with checksum-bound +restore using the existing isolated snapshot validator. Allowed: lineage test +fixtures, a bounded historical archive/provenance, and this record. Preserve +the actual verifier, parent locks, rollback, and contributor-lifecycle tests; +do not claim restore executes the old writer. No production, migration, runner, +or retained-data deletion changes. First capture must verify enabled database +guards and exact schema in a read-only consistent transaction. Subsequent +restore must verify row/column/FK custody before running the unchanged verifier +contracts. Risk: medium test-custody change; scoped ARCH/QA review required +before retiring the old fixture. This removes a concrete test dependency, not +the shared preparation service used by guide/import/POST consumers. + +Current-head capture diagnosed the stale dependency rather than producing an +archive: old PreSubmitMaterializationPreparationFacts no longer matches current +source-read authorization (AttributeError before pending verification). Receipt +/tmp/submission-pending-capture.json confirms complete cleanup. Do not repair +the obsolete production authorization path to manufacture test setup. Capture +instead from clean detached e2b926288, schema0065, in the separate local +worktree /tmp/workstream-pending-verifier-capture; preserve source provenance +and then exercise real upgrades before current verifier assertions. The failed +capture produced no retained fixture and is not acceptance evidence. From c982e19ee403ab880752c5b1894253c76db109b6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:19:23 +0100 Subject: [PATCH 252/513] Replace obsolete preparation setup with retained verifier snapshot --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 ++++ .../fixtures/retained_pending_capture.py.txt | 65 ++++++++++++++ .../retained_pending_verification.json.gz | Bin 0 -> 27099 bytes .../tests/historical_pending_verification.py | 71 ++++++++++++++++ .../tests/tasks/test_submission_lineage.py | 79 +++--------------- 5 files changed, 164 insertions(+), 66 deletions(-) create mode 100644 backend/tests/fixtures/retained_pending_capture.py.txt create mode 100644 backend/tests/fixtures/retained_pending_verification.json.gz create mode 100644 backend/tests/historical_pending_verification.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d7b8b4853..c799124b0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8594,3 +8594,18 @@ instead from clean detached e2b926288, schema0065, in the separate local worktree /tmp/workstream-pending-verifier-capture; preserve source provenance and then exercise real upgrades before current verifier assertions. The failed capture produced no retained fixture and is not acceptance evidence. + +Historical capture V3 passed on clean writer e2b926288/schema0065 (36.76s, +isolated cleanup complete): 55 tables and exactly the pending job's replica +bytes. Archive SHA2561305eaa9de3083d2ca4188f3cdba40a42fa912f211fc90c99ea36989d45e3e38; +capture source retained as tests/fixtures/retained_pending_capture.py.txt. +The initial historical run refused invalid terminal timing; the diagnostic +rerun preserved the timing validator and reached pending verification, then +revealed synthetic guide references cannot be read through the real local +provider. V3 captures only the actual pending job's object; all DB rows remain +literal. No timestamp or authority guards were changed. Retained setup now +restores exact schema0065 rows through the existing validator, performs the real +upgrade, and checks object hash before yielding current verifier tests. Removed +the old _prepared_packet producer from test_submission_lineage.py; preserve its +four lifecycle/rollback/locking cases and mark their actual schema operations. +This does not yet retire other callers of the old preparation command. diff --git a/backend/tests/fixtures/retained_pending_capture.py.txt b/backend/tests/fixtures/retained_pending_capture.py.txt new file mode 100644 index 000000000..1aad78db9 --- /dev/null +++ b/backend/tests/fixtures/retained_pending_capture.py.txt @@ -0,0 +1,65 @@ +"""One-time guarded capture; removed after recording its source and receipt.""" +import base64 +import gzip +import json +from pathlib import Path + +import asyncpg + +from tests.tasks.test_submission_lineage import _prepared_packet +from tests.historical_submission_fixtures import ( + _assert_database_guards_enabled, _identifier, +) + + +async def test_capture_pending_verification(isolated_database_env, tmp_path, monkeypatch): + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitTerminalFacts + validate = SelectedPreSubmitTerminalFacts.__post_init__ + def observe(self): + print("PRE_TIMES", self.queued_at, self.started_at, self.completed_at) + return validate(self) + monkeypatch.setattr(SelectedPreSubmitTerminalFacts, '__post_init__', observe) + async with _prepared_packet(isolated_database_env, tmp_path, verify=False) as h: + connection = await asyncpg.connect(isolated_database_env.replace('+asyncpg', '')) + try: + async with connection.transaction(isolation='repeatable_read', readonly=True): + await _assert_database_guards_enabled(connection) + revision = await connection.fetchval('SELECT version_num FROM alembic_version') + assert revision == '0065_claim_starts_work' + tables = {} + for name in await connection.fetch('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', 'public'): + table = name['tablename'] + rows = json.loads(await connection.fetchval( + f"SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY to_jsonb(r)::text),'[]')::text FROM public.{_identifier(table)} r" + )) + if rows: + tables[table] = rows + assert len(tables['artifact_verification_jobs']) == 1 + assert not tables.get('submission_bundle_admissions') + assert not tables.get('submissions') + finally: + await connection.close() + objects = {} + pending = tables['artifact_verification_jobs'][0]['replica_id'] + for replica in tables['artifact_replicas']: + if replica['id'] != pending: + continue + ref = replica['provider_object_ref'] + data = b''.join([part async for part in h.store.open(ref)]) + objects[ref] = base64.b64encode(data).decode() + assert len(objects) == 1 + seed = { + 'context': h.context.model_dump(mode='json'), + 'task_id': str(h.task_id), 'assignment_id': str(h.assignment_id), + 'project_id': str(h.project_id), 'put_attempt_id': str(h.put_attempt_id), + 'objects': objects, + } + body = { + 'schema_version': 'workstream.retained_pending_verification.v1', + 'source_revision': 'e2b926288899bcd9b05e1a560ec19b6bca8cfcfc', + 'source_fixture': 'tests/tasks/test_submission_lineage.py::_prepared_packet(verify=False)', + 'snapshot': {'revision': revision, 'tables': tables, 'seed': seed}, + } + Path('/tmp/retained-pending-verification.json.gz').write_bytes( + gzip.compress(json.dumps(body, sort_keys=True).encode(), mtime=0) + ) diff --git a/backend/tests/fixtures/retained_pending_verification.json.gz b/backend/tests/fixtures/retained_pending_verification.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..d428caa1ddcb64f8c8ebf0c909251d17ef57a717 GIT binary patch literal 27099 zcma&NWmFwJur>-5ExvIpx^Z`>xVvuLU5dL?Tv}k`?(XhVpg0?ME$;5{z2|)Q-rqMX zD{EGMB$KRUW-`wc(ilXj|0ytE&bn<}iKH8t-?Xvcye@3o9)>Uh4rCil5#3ph4q9B3(fy-%(b)*0$GN4G&@{UYv-)jNezws zp3Zg?c8(se&6C$Posy|*0<(Ab6+7bJPg9FQB9Eb&c@CFc-A`Lqczbr9906Qe+Y6tD zv9qTiRit9cT_|6cdOL`f*R9!m7=@N5GV`O@uwd&-il`Z&IY&>NtjH$6(qBK#ct{xZJh6wpnG65wz6@^QB} zozwf|y!kqkEBrY!i6GTeG4j0kMpP}rk{kHaB@i(2TzFXfaXotB-16af{Z{Do(f1kf zf#oU^$aAG_gx<3oNE&7o(1D~a^8T?fU41Ab__;TvOzM9R5&7UF`ZF@!>!s?GbN>){ zst7lkYH&U)hOHHXTTt7j(bJGF`7>C6*&shJb8WOZQ(<;N@la9oH=}EDGaQGSErVp) z&}XO)6@!z~x)-YGsg4bnnMDDD4beck^Y9w+DVtIjX_0eGV5&^l+tuesXZBCFY!w@2 zeTyg*u*Ts-fefw6WF!O!dat4DBrhShjB=XA$q zZIbxjnr=aIL^e*mz|reVop@SY^?C>G(~NN~H>1vZ|>BRI{)pQ0J4O zpW~-c#ZHz3A{4Xhi4v*GHurhVSWtkBODfRK**iQ!QL)(!^3HwHD0aeJJ8Y&0uTJ2T zViv~r{!Xs23vC)-VNKh_%=EQj@aCFkj@$kFd~~_S@WU}T#Gr=RJ;6+Xcl0k z`^$)RRtIOHqfA>GtA@E06P%uNvfqD|ph`%?^R<=?W}s4B0t!K%qo)>;mIZ&ZYWX{w zPE_X3GHMPz`B|r@G)FhO2 zGHZpbbz$q7xK|-$Aq}1~RP(Po=bZ+gc`$!7f6+$DH$)$h>6kK$zgCron6AKN>rR>v z1>rPN2g`1XqDZ1?=soy}P(>O5#g5`+uENt!WaVE;Dgy;EBt}@D$r~8(!VtWs_v;s> z#_!iMVy4lWhUgg4f%xuYz~8gpdI@Wb4wZqa4w`+DT0>(NIzOmOuoE#s!}siZIDXS6 z2OPQd3}K2eZL+X|n~Q}l?x!bPHhMAPG)*r2xb=iljf8>iO#yny{OUn4D;Tju7IH=N zEiqG5YaN#@j(YC`4wYq1*sKRtcS8lp`r``V#?w~K0xnE&f~>|A%^s)OL{g)pkc(bx z^~bQoyTkt5S;eQz{6w*z0N2MeD=mW8eMQ91x%)GBf9COvJ0XhGtc7bq6TV0H8ull& z{^In0Tg6(z^TbVx2^Q^pa2k5~^RFwz>$TR2f8bmBm)_ebMl_s)Oy0}k7oc~n>=WtDP5sdX`)Ip# z9wBk3b+ayeK2^P8L%$w`_QLnn4}6jmAFPGuHBP`9(DCQt5g`VMY@9MGdU3Zx zH146c-go8vWpKm+h4ghVGuYSF`@BXig7iTcQZcm7TYOr)V_cp=`RF1T2&S$LcQ3v0 zVDB2x8L+rWxXM8$j~k)EGdEaW0~QPef92io49z`QWtQ%_lXiDUMV$SRm+eO9Y`S0m zryx#Kn4jJtm=V25e8Z>?IZ)4O{jR+>J&9JpaJ5-Yq(Al0y>UVwY4_Sbr$^b&%$H?o zU(F|_OWo#vvD+$YtA`#uMPVQ4V|)1^G&46wFkc7>SyTQsMb$)u#N>1(q%w2zykM3r zBcPN!^{j2~Wisqmu%w|S8kDa~-D zun!^H?Ed)g&Kw10?9)#}KVuKleS(ywZiPZCb*I6`=k8?oxR>H{Jm1)o4xBCl-@)E? zeJm=rY^_dJtESA=xUE>4eSJB z%R^I7VN6LjJgeO4iovMG-r|Bo1r9Gqsj}OllQw~T%0?aAyp&llsiT>hFYlH}+?fCV z#2J>1?i)BJHSeO@rnj(2_PYgg5#u zhw+*dbNB`KQp0z&kxo*EbKSny9czTJbukyaR|%(5D2y`apmFbx%zt4RV?C}^r3#S# zbj=iGZGv$ZSZGVg#C6oK^-a(A)F_wLk?b;;*YtINb>KOH643v!Y}QHz*iwH3>EA6@ zW5Z43PR=QJA+1;snDE@vDEA%EVcO)XnBbJIqG#z+lEg_@67yy$0w;vfyMC@33^Id4 z)DohZJ+tsOc??#+nW z|JveD%?0WkZW%hrUe9-lxJxX=@Yig8tsP@6Mm$gjivJE3s!wWo?Uxi; zyWd}}sjW=aX@CLe1UnQ??GJh9XL}GIq*24VWDWB8QzjD>99p}6G)aFx?8brLLkH?P z**d`7n{$tQiGMCB5&Uh*mc-Sse|Cev&@_kw(P++2vT9&7A0_Wos za@7Iet{%^e7uyacVUTIk2Wu3qN}r~ezaMMUJ#2{CZmpw~@TH2h+1!vCp-XGK2bp)B z{UOtzPaX1^^I(|Ouq8!=KrGF=7iM>Q?URYaOtaZ@QIi5wbY`vGtZU#$-~OFpP~G{AEApdRKa=8k0Jb>{2WWKtbWEU&{kI zD04w-8>edwMpi6ksg+SVZNwXfEPUyf(=Isl`~W2p+X=|0)sDP$6^&e&WdiFkf0)3uDEiY|?Ihwrba?m$1&% zZ^3u(p8MvYj%v7>D-W0^h)jt|TXj-a0(lqFnX2@KguPo*uy6QTiQ(oo!mC_#94K=< zv!JL46WE99|AX2D&tjsfP+L2XhPCD()R=O)s-98%nrka8$+F~1N^K69i z-s`NFkxh#!j~I@%9x@hwMu0`FX6dB_8xzm83z?zSp{2W&*=A?UGdoWEnMF2%$rFd` zt9ND=#wM1e;w`EGG;aWNP-#L0E|OySWnPTWzJ&MbY6^q&*et@ZHDH6Xn$NxrYSZK} z3<{MKA5l}0RE?Snyc*Y(d%bc@(3a$(<2NcG6}ZkK;U~`IMHO-a@#+51ruWIQ@A$G2 z*4=gv3!{yfkp=nv&Jr6Zb2rB&5kz^Vt^2x2>S6AZLnFiZC4?&4Od1D&ROW(grbq_E z?Fk;$n32f~O#uXW)3eOQ(jAX5i+Sg@-{4a}*8Q{lK3|vlwW381%S`aBv?)7KiEZI^ zJ2%{6aq((-K%RyH!MSu5=CuK|!hO(p%&D#Ar4tNII3gOWn%dHk9tB{JX9ZND7^<8% zV>6a2gtkH}WO#q2_9j5R<(DN&Hyb6Age#K4Cc$3LIhplda=vxyXcIhJKl(msC##fY z>7_S~zWH(0(h;%sU(5dmon({xWZizf<8;TJDJ(;MKZW(zOQ=9b0>h@kteU_tkVViA zE`Xt@otTD4XZNjr_2kAy+MlFw5e?q?cpBT$&i|3!faM-cq!`QQ1< zNArc|7WGpA~xK1yzb)<+ylu9Ndet|#h6w) z_-m<2)0eAz{n&H@HZQn8EE5Y_0h={tk<5}IPV%ylbKMiF0I&tqP)<;auJ2i=s5}JA zru^Qqhot2>^eFEbvM*2^sQQ4^YhNM*K`j&Mm#v7jl+1lo71-P_(-fG8>7nYo5- zTHP(KsZ0At;BUy9RL2>w7uD%Mz56^Nz`l%Q!8RzCTOSn1Us%r0>)@k^s}Id~d%OqV zzKdq-2jI$i`WnDPs7}|kk2y`aQX}97v&fb$8H5?&1dQUjC##jFp+ATXBNAi0Wrc;q zjD=TZ536$1>oU%N+-IDRN+E<494JBF%53U8=0eNL58wKc9IeVA8{+9L^4m1BKWK!| zx~z2dJEaAzon@(OP>f^T?tTrI%UW;-wsZyr)n`;;sMrO>l#g(tQ3i$Xl$EFS9AeC9 zk3NP1m44wM@AG{aR}|_wNDc0olO)FghN+|2R{9FIWkE_5`BHlLSF)mQdC(Byp|h&R zez+gKdsK+0L9Xjl-5;m38Fp7#C&@% zI68|%w&Q(vxe^+g+lvlo%El}#1<~XC8{TyjRcNB(_;|Nsyb-_%n@#A!>7>f)Wtuta zK^y06A8UfSZpJ?%j#LxItZ#+XOQT0ENNs5YE4tYq?Za-7i9x5uZXqs~g4$1+*V|f3^c)BExt!uvb4lM(#4Je-dSwHuR9 z3w5z4y@A!JGIGHJHVS2kMT9zJ>0`Fj^oNXR8MM|pmiYp0PsmhO*WrxnqfPj8wiku` zo-Acp)Gk8=BX89zQ40dR{x*(=+>M{g9C2x4*=N;`I<&{^XtnyE9SaSh(t{DAM@v>W z=N7WbLD2M8DwW;-!_(~pO^$MFz@{JH1gWo4YD;exo@u79S&0Z^^e@H0(Lxh{o-UKF zxaYi3wjea;lTj9+JyAk(#savRDb3ZQg`8D98n;Elm6sjeUh1G!__i2V}^~| z02=^cR6{L5_5E9m}RSk0Y<~lgh{@%3K1@#EXi;9BFrq{ngV_hrKS7CZzED zY|=Hoa*G19)1wiV0U+(JDg;mRxuMD0Zcyr-tSh^os%)cGQ4j%qh0XDdmSMT66KO(%|kZ~IN+E|u)e zxS%}GRR`FG1a1}8__qGH5iMt~ZRpI34rBVt|&>Q;?#lo0-njt2x+B`l70bm{NM~d3- z6Xc^`UdRbs2cWaDv)M>~1AA9mx>nLS+;9TnB!7CtQW(#V39;$zK1s z`7{;{z~3Vw`z(zZy$lOH;yw&G!n?VMbF9tHI-@a^5U&bJdsKq05xnjftq~|UXqhPc z71{vtEd;1j6ZBCz+AlIBa|YN*`OHe_EMB1>+Hh1KjE`I@4iwLcMfbJ$yre=7+H-^oLVkj`0W zbbrdq1~OwE>a*IR&}c|UIUiTKFp@*BrZI*9<|C@c48$|Vkkr)pO>y~YM!!kCq-szy z0(1!o$=}D-_;bC14Tnm|Wt4}HNgo&r3Z#cbav>>g2u$?K$(1O`n|3K7wzC)AxwHSP z_bjPCMck_ROKFz6!IBv@&1N_StD(=|42^c{legdS0D~Jjq&-Hi6}sFOdYBx+aC3JH z{jXqmSt1&O*w6E5lcg?kbq7Ay5|Jgji5uTL*(= zG9rHM7Hf6LQD}V!5NvmA%n$NbOh~rG|8yDkBc)^Z(N!(EcUD`E1dNnvSbQ19*$aPF zFn;>+@*#J9Zg=w`^%xm~$GdSD=?RMMLiNt==Kk&|$(ddd%>gGf_UmyX;(K?|c7|*6 zbcREv=dI0nAdYJoUp~}?xEsb9IRlel&~MCGDqX@d1VI;mHNwQN;a|Et^W+A~648&z z|B2uzWk~23yI_NV8KzhR)KxDMLrn7dwir6pA848A>f@6>aW`zlIM3?r87>HDVr2&1 zy#n_?AGo{&_j}LSqD4+*|9<{5@i-2eN}~b)5Y?cL()g`bse|Rzt#0+)+bg}bksNcN ztc)j7o5ZS1O$X=9{nwa+XE+QtEL&DVqBAYMR88Q7vQYLUE$BWB8x5V5IxWJB)V!U` zu&&gcU8_!6W1o=`hW6`a`I<5w{v=pvwwN?#T^@py!Uk?gR=I2k%k}nl82@*#dON<~ z<1aNBM7%o-ypJ!KA6AuTsbC)j(L#4cYcoclRjbaxcV>O$!#M4a5wg%LBOlEQdR@f3 zzZh*OZ3fHt@eE$Or4&<3BvJgcA%zhzMTBM@kz&w+6>}90vEsBPH~zHz?yf9Hfr#qL zOPGOD@-OV3O(3btKMjK{HYDkfF|&l0Y>vA{61HYMImSS9FlK$iu!@jk7}*VP+;2*c znS61qbU5*2{=#_AHK-SWHC z6eawzUqCQ!k_z-ebHj-K$GW-PH=*TU2h#6(ec2w(z}UAZqn?T22(g%CADk(Q(v_n2 zW0zAGFE^L7U=E96-!tJPD8frPmPv^ok*to8)Nb%9t%B#Z63c4t>#T%Jsf|s}H53_DC=BMWAg=G1E6|t)egn@W3!eGo zh3o`F0P-ev(GxUyaLL-`_#>vfJ0^)pz$$>InkLMH4Dcrg_$QMZl5O=}mxSbbITY2x zjN=F$RJC|MjjDH*4zM9M+E%vBH}I0;Oeg8_@v84GmR#PZ@|#%+#N`UNtvrocldp;! zOpc*moRzF*jC0zOgD-)T2Ml!vYldkGGhk*Z|Nc=wlHFMT*YAdAtoXs$2?dhGU5d4; ziga5o8#rzMOVDc!YM+s972#6B3(!E0H=WrfPX zM&@;lu!I52EeNV1hqWW&u2twOiB&=jaO`^h)L5VSVFq zhjBpYXTd5@)Y7M(wzfW-$e!JLXq$JdH7{(w^J2i1VyaP7aYsv&LsV;5^V}E-f!}+E z833^5NHnqBH%sPBuU2E#ga#<>C|Yw4W`~^$yANJ6^0zKsoJUR#V4TA4lXbgcP|2$s z{Z1u$$;H|^#xXL86?}{5(ldih{kbGGBhauNJ1#$j6XCN9;ZkzmJgLJ`Y!Hxp1rzn! zzTO(6f&iiM0B)~5vEx`L{Bk}F#-v#e#q=7iFsi*U86{v$xoxEb)!DL1)uud@pOUCq zffm>oiP4x!Y=8Y_U^S6sgTN-06%MmlR?6JuOOyXYO>#$LI&yk95`<=dOw-4%-E&b= z*Kr9eEn@TRZS!lH;(l6Y=a_Ug{bBj-Z!-+;8n@<|2E1CE(ZZ4*v(`@V81HL+D$biW31uF5ru`vtmfKeKeAaQ6;f# z7)F_PNxxj-&tOPP(5lv4el%go`94=T4?#wj@nWP0UpLAT8Z z%MQ0X$0<2R&RU;|QPRJx(enEwi}O|`YD)GC3ce}hP&)_E_5d-*Wb$z9{mNb!`5p90 zC>2E{Xm_@4U;G83uMPZlY}-`Z3IbdIcWsUj==rt)mL8E+-t)j|Xdh z^80o*7af12$g^;rGIHWDe%wjc;KmO_PYgLRW&26uD1xtE?Dv>-`wGlMQ^JZMfg1dd z)kpTDYS;(_M5=^NV@0fih2ESn6!VEBj-25~qABu9cnj#E+R`5Tu88M4Y*S_fG=}LJ zDHZo#u9rTLz^${xf-!Ek{1<*k9y z+o#u21Rgk16%0Qonura=ik8BWqsm1FWHL0|Mq#A@G%;s**tIJV#Pn3(16sykkL?DVM;#x`326`UxsS^p*916i~^;zUvZl4z63$T0}WT=}Hyc+S|V?Rc`J zZEb}j=qC7kWVE%eWZWK#_6h`jXl;>hYsoa-i2h$B8qGSbcY{Gh?Q4mB0m`zGcMw~4 z^gh(F6K`QW{xJZo@&Ivl%;P2tme=S-Tm5>=$|FLzP#(^c=o7>}E@lyn4tCMe%R{Bu zyEwaj5g+jB!uJ^|ictmP*{z6LFifW*i2Y_om6(X_s)ZZ&tQi$Z7pW?tq%7L>DYRnd zYKe|Uh`rcM`necNb=G9wG|Tq2OKbKo;)n(&hU5`vDVj zu)r4`ey3sXT}| zG0{2+ernSw_&=|)sTn-&TdZ6Ed#&b&BMv5dKv83oJNMTYA)`#yLwsC=G{)EMlIEr@ zBt8+Q(EB^s?pBQsTH5PAvx!5%01$DS8IHj#K3R?khJzhTw(Ta!d6V!IFaZVivlMvb ztt`WwAo;KeHAFugY>HEEZ_bIR2ugl=$GQ9OP;TJd?XNr8l{}HK?=l|eh85+mSykUo z9Hdp)pT!XgRj}3|pw)#C&V3!uhe$SCRCBqm9_Bq_4SgLhU>k|r{cBe2kPPOjA-2Z^ zp$T|J-@W4u{m+vhLFZ>*aMsD!rW6f1EQ63nKF=LfQWK`UySVu^mFJMo(ox+lT|Z5v ze#?SCV%CNP1ciyenz*aWPwx=B_XNU@CYgi<(t|MMxvH;!T=`T!DPYj2Xfq>LagF~k zGodvTeF^3xMTg9>&!FRI0P>5>&{QW0^yZ;ZutjhY%=i2}Chc~Xv2T8^e}6MFjT2eJ`Y`!J96Nzyl9 zYE3U$%{TpjfIh!QC za|`lcw)b|>Uo7dVgnnf08lnDn4_oP8<;Dinn?NRbH}v2)bVA|4inixHLHfDY=(H8u zAK$fmW|daP2r+1iN|jrR!0z@XDKC;XN)aNZX$Wm9F0BGodwL4qS*A2!8}Gd|$(TRe z7y*a9aj7joo|oVm7%K;hbNOHEYDS4!6awD{qIVb+( zRM;N<=lxcp`-S!XNeeFq^BsGJ23Sp>xM!a~h>0y#9GDJTwp{FRA^L<5g+*PGe( zxGbOKUQll~Kx@$aY|EP65sdaLN#lo?e_uPR?7UERt;pvKuC#}VZ?VvdfRhSPVb}_lLVRK>%&pFUdiwrBT>orxto-E|l2l51#7seR`x3G68}6sKo#1V<3udJ1 zEWT5}Otj2b;jtkr)JpQ%D(>qEY*h!-4B!oDkT)|(2iZX>^`AkwseEPA0I=o{_DmS+ zqx%c)g|~|oC(bM>K`JrA-ers>PvVl>70257MOgjXOQS@jz*-=Ju9^X{(nRm8z_c*_M>DD*R z&%L2Ahqe_odP za5d%_K5pzU3S!}7R&z#Jm`5?OMdqj|5fo3_C~qit_noRyI4WV!XZn1kzNA@kSd$Dh zKj(^a({+roJB_u&2Mh0L(Ra^}8?dvv@q>~Yt9)N((E_2OiQ?DC-9WiC3e$xrX<@5t zg>k4PC-Wsor&lfA6$Ase%sx(nm{ zU+eim5XIIZ`qia&(tlANBef^ z?3dGyosrTNRO0A`2dfR0QEThwXI5QrV%NS~_eN1=(!Iy*PloJl#}yxz*Q7aj4}Vv# zucfCK2a}4QVedG_BHy%2i;^T$KV5f)S(HU4#^=y(O9EGm?Oz0rp;(j!`{ru4#n!i^ zbN7<&R}xa4&y?0TKC>Env6Te-ItJ&^>R}U9e9;YZ+|ml?YW9wjE4@(F%a`SwF}*94 zoTS`wmXo3zv~oXPPn1|LP4Y@{>`-lm+ynQp9(a5<(91JSk6uq61C=(e_k~cOZvK7A zK?!uCx67$%6+pRYrN*-m!HYPnDE8R@I5XNX?7u>)jb3Prw9S0!>_8oU|D?iyN^*Cw zP3>3vB6lKE&CSF7X1JDjZs`JHjJw)fKeHd{s-C)NaNMvfc+ZF*&uCKITsbt}HE18M z>U>iEEa85&>~+`LuT4ohye5D|;MXbJUn+Nm-qv--%aYFV#=h_*6^F$Wc^GG4xIc(< zomNoHeV5Tjm|9Aw@lD!U$RoMrAsTl&?=M;!f>v`qB^hBqwc$<)zO|WY!Vl#d&J1rL zlnaflS36=;>_fJ}Ad)k%ydmJ=hJdxT9W@HmDOThvw&4biswLPV;6UN66=lzN(L zCakh~_-JqYw`){NUlw;GAlwW2P*g}?ZnWWTO;LJwWs~$>Mtyn85mH=8x;Ea(WVv*1 zAHKMse{G_Uf<{FXPm1Zz!SS$WL~u_P$y_cNO>YYZoT!6D*Y!chGK4 z0%5xfu*l)Z@9qv9*ghG)yD-=o`n#GCUhqtVuP=);`>Ls%u|e<8Pun9q3z~rqOu9)A zGP2t3)Vi*&DJc2l-F-?Saf@kg?V=bG?eb)jvc8ynw3O@_%!}HOiE?`2ZMmWN7xGY1V!7(rK7wRSxf zL!SKkyo$;oRa9stoRkgLooi7`Ni=#I8Bae)JA<`zQ{vhUl-dy+sqIgPq>q<1?`nPO zY6Xq|==7?y>Tyw+euixqAj&wN&BnCuZiY19>5du>;ivm2j6+_OR_z#~?Z&{G-*aTN zmlU*_C()uI0IOzJI;Lzy&W1zk1F7tx9zBVrt@R1VKz~*TC{Zn=uVh>`Yc~!U0ocov z<_<&HR4sWF*5WD3l#cIZq-YL(yF zps|YbqU8{bz_yPfDi;lh|eKw?3`DIoHDHve}UYtyj$o6ZGzk3tec1J zI~F{GB5{&N)+-}$62f}={r)E(87eR-N}MiJjrgy)KR=D&?W>KMosF#DNp^f5wiy5? zi~#4$Fd+p{<$9Y-yM{zfmzmrLoz@|&p6+kefQLgD&StIc-aS&1l1U`2r@Af4MWupO zHTqo1qZQ~vXY_;0;M|+f)+Q&S+#4}qMv19|0=JCr+S^zCFeeLb*QI9e5z?<-k-pEG zeO$Y!eENHcq-yM-VPj*_nuwUsJnkrJ$(jIq!{T>}zNzblK4vmg!&Pa{ty)kZ=FyiCL<-@5!?)0vSC`{>`DaQ8`Ic<@^G3WwegC?*MF;V-x^OOI zA{1SWa0Du6F6iN)JIq-HC`y+RCij(`-mbeA>b1(AIN%J8QACdX-ig{k8j|?UT)lB@ z!SuB^f#G#5m*;jsx%PE%?b;$~_@H5>wb*+C%g@Qb*a6?OYrgWxc%iOQmaw|4wxPHR zkgrh;R@H*HOeO;%TV>qFCidP>$;JtEuPe#9oZ~oh!@m)gYo!OPhsMZ#_v%b8P_K&! z8C`LP8-)i;`oYhcovp*8vRh>+&6&@Guogp#?h$bF^iiX z!w$zPptZyv$ZD#MqsTb>x#3co;LJTJ)wj$6X2aEml-{l61rYO z2>;)787{*%PB1Sr_F4+NX9gWf_ZTOVrA)Z7IjgEV>uk(?6(k&zkw~2aOFNBSpFo!I zU$U%wsm?eFrR&?NP|1aXNYi=xZznkwbEG1|_(eW%vPdA~&-1ED-x)oX{= zUMI3>j0EXA*z*#<78RhmSv5??lg@1Wp5aML(t(GNGRfDNjIWS0>hB`~XMT6EKo*wq+eL$k? z#f;hy!9Ns}`%9cfDXISiO%_aacqNg2>$+2QL9;Pw#0GKnlc!tEAcF)axi*5d-bQQcb`kY;~ScQbi^Ho!C* zw;9fbS(p&&P+DSC_4Sdbn@5hms?}r3gGqXl{@wkDNhCra`hYWZm?ftEgYujwIju09 zhA>kcI2(#yhFgeaG??XtL8d6Jv#bMHvTT-WF)KFY6Wk^G7EKD0vWhvpUSndsfJ>w^ z@qF@bDg~Y(!xRfy7aiNAksA}Upyc);V)yPf`K@CYLYb!7Jgq(jM+TYlpr3o3eEz0~ zx{9+v-qqmsGoX{h(Hmw#WEF4y zVD-jwyGGj$8jRMb5B(rjobQeEK}7iN02w+1$`p^e=ogplrbJAzm}?Bm3mN>8yuQ7_ zJN^C$^a7v#Em`miHZ5)wFj9j=@`KEsCBDLwt(vK+V9mTC*i0WK1=XH)*}o1Ik%xc+ zNdf5h zuxsKY;S0g^25-RrfJ%v2rIuv1@?&7_X;}uPGa@#RXVi3k3K76y9s$BxDXmh5K2W|XRlsv zh2Wa$V*hg^4ZV|yuYsGWG}v40xmK^8!7frPNCD9vRp1LQa$ikKyj-J-xG$)R>B}}{`3=7qIzICFSE)|blU>J;LSIA_W6#yD zBzSl#*}Na#bYc@`Y!}wteYis+u=&gizqFtZ@LZX_@S!oa2o&Vgs_2QtCI-FRFDVr+ z&-{gajixu38Xxcf|B0l_uRhBg^+Twa%GytsOBMDhalQUAxF z{&E%991q7KuOz4eoRBuGAp@)BjaeB#!dQa-@`?AeV_-X!cZfUToz<84rT4SvH3roKt-8f@ zr5mk&y@hTZ#7tMu>s)FAZ84AS;NpCxB7eAYc6ytRR47WE=qhdy^bbhCTtqrcn)4#A zZfH8}f++97w#0Q5EDe~u-&ayS+*>k|fespF+;Bl+(Qj|nU_s-_p%LI-laYWI!Mrt< z;Eh{bg_tBhZ)FM((1kBk#(`@}WgjXi?ix+1L!Q3+7CJe3{_S1>=?}#M+Lmn5*!=Dg zF%|fj6{ppc$4*n9#sGbF(nV$JPG_W0ptcEg7{I6SsJaYO1#6jeSTo^}^c-JuO0^iTz4&9$&`Ciyu>JhWWi)kjs<)|UNWu1e%@Ndb?q`un zwf3ZC(_6U$PryA5vp|Z@0$2FLz8){ttjm;`M~R&i_%d3>{BYNAW#swI?_Tq;KjwmA zOYlEd-Nl(e(|7uct z13|?7o8J;BA))8;;ac32StM}H`)b-T#z?^5@2%@~J84Q^_+zbf1A&1l;6m`JVr{o_ zs!#aiB{v&k%T3Sk*6gs~lhpIu+p_4i+-yUTMwP2eTUSrSVpQ^(#@QKxBcz^2Xh zv1hjA$6dtKX28py=Qz6Xt8eMtbkCXF%kzIKVI44*?Tj-w1Gf!{k)sIA>5Jpd3tfz`_Z+w8{@=}-g6wgcj_cy^xVO~ z+~W$bwR=uaQZEC} zV(&V01^#^cx6WO5j@`Z{bTSDaqny1e3pBoe+&YqO90z`CO3ws-Dn>Zw5*PsSzcPCim7aZHCK*vSn158)-u;+2NXQL1W4)Q) z@=Uo(W#0O@d274~o$f^E7ysNZJlsGabtm;(_n&z`8(~22$UUd;G3q&vzgu%8-KuFi zQu=(o&<{AOI%W~^pm~(Hdi;F0u`=%UAb4KF%kF+}COd|C{1iGH?9eIdAuSel**n-o znuzL-hlx5T5Ho&d78H{YX9hJx+R?DXg(ty^^qQ(f4qp^kW~dY4JbnmGEt3j}q-A8Y zTEg3?dGaxRum(GDUa%0Q-#3-i<4Ye{J2^5=M3Zvb*s)x^e@#8Z91Pp|gik%PkxX~o zc;;u`Q9le1QwAT5YQ?MSVOFY_D8Zg`Z@d(wsMt7^g^U#eqUy&ww&^buDU<2#N*!OZ zEK_Waju639T3X?}>I5d;bL&Wj_NO-kg*~1w=sYt`JfIktg)r~%YSq$pehjmt;S0~3!c!Ee*zXbS4^M6@q z5TNKqIB{d+ZVpGpOcR9-;&F+vU%L`rJj>yu+llbWVEY!@cAAmi$CNi}%D9%GpSQox zl9@wAl;f2k_fP)PUDIanNfU`5`yW{wG?@=NF}v45>%bRtXTOEs9Na3KgSs-T+qJd) z7fK|rcEfu~d=ydS{m3$R5fgpeBDC7Q{Wl7bN2qhg7NcFtG5e+xP-3ow`M~}JFv;O8 zEXNmjlKt^zocpbCA+fS!pBMGU{<<`5`DLBgq?P8KH7CWr<~YcJ@x1|CP3yIfCB-hL zN&}mZ7hym4fz(ih4Tx3&OW_O5NNbp*r&V{9c21>t0@pPC4Hqp_S^EBe`uN7!N}#se z>eM!-wvE%NF?FXlPHo$^ZQHgzwauw*ciQ>p{c@B0O<9eTt_}Sv@Ist$S!Oz_MiXpw*h|1&eP<@J5-q%2eUlSF?(=fBxu9=4W2^L zlx~V&>S#Ch;L;4o;{4^~!6)37y{UcJ#&)V$>^8RN~$CFSPepYsr-s3xsG z72C0`yuUvA$O}q8`v5_`VKEgyY*AWC#^*A;D8RL1LT(4%G?f-73HB*hyW(+VNSs0- zfL`lGYr$bNrqqR!(9HU;JdWv>>Tmlb_={BDY(|Bl9GK4e)CoF5pA4fm0})SISd+t@ z(1?0|dJ5JoCt`8U+6Un|)mX6*($vZFSYRm^mUts{C3ttQtyjVY~!ge_+R5xcu3R-W6_yA7LyGswtbjb1`DMyt49qHP_XN6Uf z4HDe1P*)rg1Wh_})?aWLa!jkH)`-1KI=B|d5kejCv&^jrwWifE=H_K3G*7m5w%7%E zBbv=2AdOiXP;}}+b3~=}7^J+Q+A?vK7ID>i>oUisqYsCv{p!$#uYcl=e%fR#AzVTA z^UNklRcZzm)JsLJ!zJaBPo%Bn+8)0AGm^san*;oXB^x~xzKylUmzYyWXM@~x1hvnX zBmP*o!|g?**_8i@o?;+ln%4CS)0VxU;~1dTS=W-R&pP1m9S4=`-5#2*fz>Z}4vRRC zj_CbSlQqxTO9!T*)?XjXCa+ho`SY%wSi5Ayv8pSd6-R41^H=$}DIWL_e(T}#+~za- z`Xy${2>a_QKmi$C2yD=wDI9Iy5wk_h{n=5bvhgg>Uk!qzukVZ7?d{-gSc0TbSfvYl zG3@%;Z-(^x3>b0`2Y#FA9#u76=B;E)cO7ZUlLn(yIDRfpV9P!@k-gc8FS3NQvtsae z9CkmoWbIwP=kh%uvGZji=7C4+yl`!YtXGc^h;wlUYXgH!t+zVXe1PiQSv8%Maoe~g zOFh|CKQcT)rdL*dG684@XA!K?kH>7wBjtbZmyNf0oPMZ-4z-YwC3=YmrXHAQ!aR493l)XBB4%m!)FYT?DP~?ui zG9Isv@&@sblr-?yB|)bc40!5kuGywcQC^V3VQwwy(1m@q+f+XlqlZYRtZ4`k6&$r><#1FR!&C113AF_k; zdIqj_bJ$2czHw{z-F&zl?mgE;paZ$>H^kr3N=OB_Ax$@gJhfK}bg$iL5@Mrf0ZuKx;<}IDs+X1ni+0c}F@;x9E4VV7ezGL5p#?hfo zDJ#bOr1M>Bg}$TjL)pxA_2Zve!h$iS7*@Wu7@PshhWPE=HB6`7BYg;eh*|`-b5q%O zufKPDx9sgKWzHHOiooG#0@UTdzgGoSmC81v)wwPIN_=p0dr$?mzBWL=>FdPFbY7WF z-!V_ckjA@9B>;VoYY&>J!0j`&4_oAJtzA(!FP_^yp`?6fq(T!#*jbA>VO|%R5GqL# zFeydvH~^KHXhq^ckulw*A1Le9N#ZKPtl$7$UDDqlbcTtN>j+3zrn2 zI@v%YY2|3n;z7{l5Xqx3UKEH7RFGayq9zNVxG|EVl5FZ)qvzMeA#0XFn_{o2Bf0s$ z#(ELk4!UN8gvz5uOCeEFsXxD+Jxy7RbVWuCclY=YcB4Z;+ zUVcrO`<74Euc^53OkD~o+C{&h~Y#d}098YE0wAww&nZb=|Ez{4nx59(Ju;0&#$b(7a5y?Fe~syQg!dFHL>A&>^l zo6Mf2pFK%2>*dK)&;8%>zfH8gr!+CO4Lj4mWPi6t zi26>zbbgg)u35freK!K*2KF(x7oN_rsUZS>Q%O ze>BhW>hM@ZNGe(Gg&4L^k(E*xFb~I~Ii@IPr<$<68yo88tg@^1w7u5TY)mot6eg%@ zq5fIncQGST)XZT|8-pnXuZk|O7Jp3{NdjYTG7V0NektXk<9LMBYY~m!UMER@5_m`^ zPS{P^&s{P|0!<%TN5l?zgJ2wpUK|&S1TXYFEnM84)!O_eXV3%cM`8Iz4#y$@X8^-LgLsR z$=>x3m3c+4T6p#bsqeEyf9)8gpKXqqHJ6rGAuDOyWIG~L)rUCDCSqhvs(9NV{xJ0C z5C4fvPFX$}k(_NjvU*~pqMg`o-4Tw6oZi_;MBO@Y2|Ni52qUp@Nq()Lp_3S;m>)Gp zOU@VY@8@*TD0D1PJ_|QE&(6$TfH5Etp6n5~ucw|+4HeEcA`Y~S?CaTFGmWaUC-?=7 zn6v~O(m;6Q!_^?h#1Dsn<&5cw)oxP=)z93(IQq+Kc5Q4>#Sc-+&;msGVUhxBpj1k! z=Z$*YrL-wa;>`2$rlgP#0~wiiyy$5|8a*CK%=ia0Ea#07hIh?aUy=5Vy|C6}_KLIA zL6Gw6e?>3ir*`sf`B#9H&DsFj7yZ`#;&{tk_Y=hQ8UHf@u*J$*bKeE6+NZd&3YT#| zzTR$WF!U!xs-n&J_wg8ln5Nzo%@Q5 z@LOY5B1tJnQ&I_{T)fOZo?B-gZ7#Li-_2PeeVa(lYDxAf$7LuFt|y&)cRV2q+6@>5 zM|IRVeh;AP1Yr|~naS=FQ>!Tz7_F6IVhA#=hBQE410rVV6;=@s zYhB=yng^2E91vAd+&nS}Nd!02zX0uQL>}aezGr8nnaDTDKo|XsaXcf$G=oU@?$`ur zeJhxj_0a{MoqLU*!q>~N?YpT{7L{^TQ+T9YerG!a;w?vryNMJFGZ3VQPRctP4yafs zQF`N)GD7f!PZML+;*(p;eb>%8jTw>+4dO%lj^0aXcTb%CbQ6oWu2t8@#*3`ugk$d- zVX5lON@o=Wjm}DUl}~uL3obhXn6C&P6^$tc8&B_!s5km&S1|_Z7=rR6<^3l}GZ@+Z z1((eCg}5O?1Cn%{;GY}y!1m9@>QSc7&>azJlUZ#f5%&RN)|fG9y^KvJ^wy>c33qiR z;b~4}GhR}|9b-1X-&%Ula;=MZQxAPIwVQ`Pd>rqhL8$DI^m+6Vy{I-Zd(FO{)I4 zN{zILOjvPb0u>fY;eGZt=`a;$6q)@s9y!xan*-po!vM)YK~IabB~6-gWH^XxdcoOa#}%1w(#G4PKGMw+aWP)XhQ(O^KG_f_j9{&OKK^R6mQ0 z6md;5Ts&La`^E55{e{*eKWLuezivQa7$*xg!?|`#mTO41F*3!1dQ~15O$ApOVhoiW z5>j*H;)CtO%;V)1T~~k#N6J#2sX7X$AT?zP3D5xo>?l_>HymD&B1_ z_zgy{e>?g&Tm~*I-p2dkhQYLk!Eias{DKBJF-fCm1mxxw_>K?gVcOeAeznr|*wGtw z>2^&RIwSg==sH=37Ox~TUaY#f(=r3|)p)S#e@)*uSdHiMQ z)8KjTJo6=0?w$eQ>s9$)TkM(uSF}q-oEM_0jo-DLo`koVEv>aIL?iJN-p2*mNEdBqdH zu`2o>%JWHa*@lWRqy))RxM*7vmYx%nJ>=Vgz-FFZiLk_6e|*fxT2%-f3E`|>V^8Q6 z^rI|#3mf%P)TN|JQCW0r9~v^$QZf|}O8CN{-{S2>4`1ie&Th=M?F*~hhK8w~T~--G z;%1xdq>rVS$!hwYQKg!zi}*e4b`8bSYlPWily9y%Mqi#v;gHeqUgNymGesQc=teV@ zzINqqT?O0xOFwpRONJtcm|Yeszj}-euTozWHrx){kgL?XC6iT@tu~Z~>Rq9V1$Cu* zxMt7P7ezciyF5ekI?TZQKda2z4!)iy&63p5)|0n#Ir-)l>VF2k6$q@^*C(%8o_(he zd;IqO0E5JEe{Qc46}I0HBqpK>LF1@F%p&B$x`@{zeQO>KFQN!ZUXiPRpcADHWfkzJ z*aX^z%xvSmiL0ZFs8IqH;2y3MW(;`}rl2Waa@oM9&r1 z^eQ(f3BD$i65nq{6s64?Ym2Em!qaWlJ$v(c(dkp=eq}l*MoTXX`$g|JU=EFl1$WPA zivZ5{?-8zK*-@jM7GI12#j$iaK&n7SN zjENcJVPM43BO9yyuf{^=w?N&U^IBK_VmyL}-A~qC%?#D$C;Vy2U@$4&5kt0d(C`a@ z95?xBV$_`=jjOF$k!!iR#`4rf8xgYNlyrR#U|vIDfw+M(F&4w>!U z;M;{=Xzuj;U!ip2a8GTCL1?+qinh_Ja7#`rwQ_hqd2npnezLc$q&^@(qZlj-6O;hK z@HGdHjpbH##1s-;7Jo-fYuuf(dD2zl<;{I~n4ZG}$iTGkX z_o%+UlX?$g4j7NXQw@Ydu+uUMRV&Wdq`=tw71jq84?O+`G!OAgr~4vz)DHl@c!H_J zuFu|Bma@*yY{Sh2I13RtyLX+hcI6YdX2(CX{~P@=a}?Z-6>l|JW$J4(=ent2)V7}i z@DBV2W-iF`ma^qU34ODVFFoARluOr_9i48<6zDXm?bs`nn?0ldtt-urvh)2006rz! zr4uBESsX8>y(Tau-7VM6Jv0W<8~wnR$(Zk{K(EYlP=5L?W!Fq;@u?|we?QTP3`q4~ z=!iqEYgN{X!QK{tD*&=WUYQozGAfud+LpYPL~ya%S8XpCrh3VjjXnDJ;`3X#mRI(v zn<*ss+GV3VAA~I-<^tPu9wy%-Ak8&5XPaqZhT>|CL8pgD)xwQu+mJ~bs-)=`q$#e9 zC7;uXhE|~6zl+1YTl3Pab>Q$-2ahw;<<%BBcPc-QK8`hEVI))TWnfdlM4)8qmv|$D zAhJ7cmjRFS%k&@9#yi8jO@|=*>kl3$aT6$S5P#N8n!{DR80x$cFHf*wAILnCY>u)-Jqrz;mTUy@=Sbp5Glm0}kBU>klZg?9R-yjm|P=Eu@)(`U0 z*LRV+i8U--xjCIDek2NYXcUpy{V>bd%XWZ`JF+g_fm>tb(AP|nRiQWt6bnZ7uDd!) zJ@I4d(gjupN#n$sx|^sQOOHTkqhrS7?a{BQl)k$>&GtCLUzt5L0T)j-K-QbJ+Mmx4 zs;b%rsUeKfF9n$>JvpVy>p6Kr1hDLTL#}NCOu<0LxBPVZk0|;O`=wbIrL_REzj&2~ zU2ET0i`Dx8qO;+9{F zwXMkW_FGzD)+_#^0vTMeZ6*{0nXJMo%L3{56nKjCDOHtqx~q#^M1DuEsWeo}bS?90 z^Xj6FblO(F$|4q}b)RAebC-5qQ8}osJ1*w=LEyGFmftEikhn8tTYPM?lI z7=qATp-;~!r)vhst~K*_0`U6=JRN`rDlEcW@Rb#s)EdmDigTJh?N{#?Ni_ zyljt8BJt_8eLhu_NC7x$_+@NCeEdqy2j{`oWbt8|9h1ZezDdnm^IG_8%~yY3`X!83 zngmPvoSZ>TcoZ(Ek5qqvgPcn)j=zui+RZV=6rF!G2$sznH%e;mzP@nT<$+ z4^?r(90l80Uhb`qhd%1|lhfSJOKOi5cWYi2v%+#+3iLBUmtJ=qd%(=5wTqs!TQ< z0qQNdKtMD;?jS1;;U3Q3NhMwa3nkAIn2vTa89f}(!`lCEl}zvGKGiaW2_JjaG+er> zAEgdDQ=89e+f}|+^xRy6aYb9TZoZ}e;-AT4>)s!ndKfo|()Qqd9}p*2y!TgQfP?2u zdTw>ISKos}^q-+l74F79R2#B^2zI%SB_($7xT8c>uiZ!RTbzMM1HXyf@x!;ZwM8(l z0`+XY>!>R|yj{CSrPSJDo5U$eAzc=d+ILy%s&=6no%C9^UQNu^%jUU*#%%b84Z7;H zPU^M#RzCi!Kl8ksezR(S+;rfdoQ67ffv>B}2P%5pT^0oStAd|vy`sV+c*CCke@Kg%!wE zWI;Zqmd(&+&?Qt|nmsh`hhRyE%9WxuAElIya@bp9YA)b(*g*c!dngl$FmO;i35qSN zAMHEUFUoSf|G~Q#BZ(Gl*h(XPoxhAr4r~))nW!kB9A^#7O(Uf-bh2ki{od_I%9v#E znmnRClKMhi0Luzg-4Uy+IN`7l@>Nl6cOR}Yi6FwF@>ha9uVWZl!u}UloxdAh-S4l@ zB)}+3>4ubko7b~#aKzirmMNP%z*Hsc?`TT(BLySU45OxengGZCk4Lh0lhYmSC1)gN zYGb37oW^LvPD(Q?Jp5Fc1C20_kxKriE-h6iR80pGNN2Bd0aM%*V4nLN0<{TraS*Fl z;2#{rNCb;Kvakh!;M#uVAu5eQD=6mP%R;moclV3!F*7){SaTxY=Izo?vCu2CO<*d5 z@dkCVp6|*vYk%H3WA!f}phQbF5DlPf1@1W|pae~pDS2cS&ASoKBD^Qa|G?3eAMAi2 zh)rN1;&Yr#R_N$DejUGwy;OwWk)LoBazlnTG&;eM0_v@;lg%Qj?rlb6?GON%EbgJI`GjcbQ#gWg0Lo44O6nD|tAUl}r%%-SCx;x!9gg{e*G#!-%ok!p?2|aFA4VbXRt;r zYpZV!yC(LlW&N+pL){5@XZcV5s2@{MnhR?qI8AVy&aD-z6B+pUTED4PU z&l^2IiDS>tuCS9qAKpZ9=6)_bO|t`Pim2p_2>UYRz-g>9KvXAX8&OuNaVqBEJ0GS( zd+;&HM@YJQc%oboyM%87%#T|BS%N}r%w;v(Z)~i&%hF#i_+7wd7i-%B?jJFf+f12RMcV%w^LGWnurb(IAJCiiO7I4tD zLsmX9i4x?P&35`eTf8sr9y582y<+tF#vmtDh>()-b7;^76@n9>;IBJf(@4fe|H#M0 zo~o=*NG!Z~r7U1Oi3cHkjQ;3BxwiU~UlfICXuPqlW0Z^MrU>b+|5Qk<;FqwLkrojEK}3^}^eh5sArqt+Jk6N`Pl!sM?eH+3$z_tfP6qKt7>!5xlm zx9-Q)v1XPWpJ313B6Rp{?`c~)Ji6hlI!2}%T8vfR+hq0TQ~6S>TGtEg$hUkooeP~5 z&lA;Es3&aq3M(1y3=k;6Tzq#>t7tbTMzL@9!S0^0okhKi@i8UubbaEV*v6_=c{3-t zw!U#lBzryZ|DoOjQn@WbuM*ZE};i|h~;uukIk`&a!s5f zQ`Vsj!yiAS#cB4qQS))1997>B+mkw`#yz*jEWr%O=lE_s++LEn_+G02OnegSXO;mk zPbL_qh1G3R?Y?iX@zlp&C^l6E`P0uXkxX9Q5kD<D7ul`#1?{Qjj)@6Xq~ZY%f4 zMZ}9y`i7>#2Crxz`u$0O#x8f!vzYwF7U%3$DzQ*>EO9Fk%Lq*OM0p977eD)tgY%uj z;~3w?QQ5L*gOA76^zA|MJckU;;F6rvi!ev%Q_)J)Pv%XzD+B$$LLYBEjhg8}0~lxY zjW;=73KpOKsxKW%gqF2lv;OIoExY=Ng#LtYQ_U3|!{y+V#o!S(S*OyKrM7F;mzm4@ z%sT=x$6cR_IlRh02mdndRK3{tZF;rU4Y8NaNB`ONK0gS+G6%Df=-#Z=+UK9Nei^%; zJO!(M!qnkU^`Y)Z|1i>Q3pYc`5*5wZufL9r81k%j^4Puzoi9BZD93k6xN_RLT*Pu~ z;6x;FghB!&FYWwPvP!P*N#8r^71RYwHm4!02(TQe0AkIIl85?P*o8-OW1#<5iJ$Oy zF~?!nU~q!KtZ7;8Xri3OgC){XfSqrcw1yp!8j`ecRyJ>nTXpAa*DU2PN97^Cn@H7y z^J^OWdoOC-(6-L%6>%AsWGWCZtRoP>=$L}S9$qF;m`;StY^K?5oU<0!N>Shb!RmETcOJHl(FV zZM1GgHgk%YaV~Q1*?Q8ky-&vM&y)XmyzBB7$WS|<1vBN$m0)x_i=_SEraH_mH?#dN z%gdROQny#6+t0ge+8zFXllks1hjKDI&Ht4!Z+uO=y~tVXY@Uh>_Ew%^->Zz6k-htl zYmb+$RMpNjNIbzQg`tB;htE0TCy5+M0H?Oh7w-zIVzc@>uJ?&4 zJ&&HJkfF<(di~Yl@^HjwWJ0;~07Of?!ZMwS_@F50AS4Jc6y*~BG$E`;hG1kDQU~)M zeCn2Lw|7i((53j=vll3r4nSP@cg020>=c)B>2zEk61el`mMJi1* zTO680GsU$NSTxF?YbV&-I;`b4po4^HbtC(foqOr#|6MJ2Bg(i=n^4&MJObk1ou;Yw zlGO9qs~lpbK7VKCIv<_mHszFCx35H_nlmDIzD!tQu$qQ=A>AV2#th6CLBh)F=4ir= zf24dAC0f-Ig`}SSY?Hn0!%fLS&wd_AqyOL&TUxnd1e1LAP!!+l** z&;eaM+fHIEsn$+wd^~n)pEgYuk@E4Daoci?9nPh|xM6|D4qgzi!ZYmK;2$>?=6v;l z=f(U7&3~yh6)YP{K8>AF)gn`q(Rf4kbCHAiXYQc`+k3ZX{S_EN6fBeoy0F^l^)zbs z@b+qA>>wE=XCnVe$HDHht(07z(wKbUArkZhPYCRq`p(d+6ioNE5eP{VhgPPl!7rMt zgf3k{52$HL6~xTg#(<5Y9;-}B43pZ&`mXqSidzL*jiN)N6Sx-C|0DXSz$XMotQGe$ z1Wo6H(aUFjXA>fv_aoD+i`Vb%>q64>9!~0t?g9~OfG6Vm&Td-MoAdBIngu;1sy#l8*qg!kpl6xHz|pG$*#4PC{`ht1lw(7A2V zWF~T0{E5o>EdovQDcG}%5g9#42Mx`_OBV|o^A*T|}K$b4trjkc>Qrq%n4o(Bsetr~Ac8~4g% zOj$MewS5fg8&@foR=qkOEN|8Pi2$t)&WIPnZ`HzzQ)G4qs*9ax5SInL_XjsM309Lo zawl+9f9lZ87!33h34NyJV0{a6MRph(UZ6Y-dh+z&%>iZ!T-Z z)U3IrWK<)KvM@@fpzP|U5W}6hUA%*iL5SZ2BF7V9f#-qtF*DT*fVlNX0W&Tl3-oEe zW_AvgqL4YYfgP>*!{9sgQ5jrjgYN$nAIcy;4eXbr*4NrlR`GF)9>(4elk5fzKS4*R z-8pH$Ef{YuM43@Oya(ecX71yly*K{J_aO?fY~Pfgkj@dwpMuW%bAe4y+j*$oIqN*= zh$5O)f-CxiMsRVIe6B=9+TG$ww-#62S>N;7E^#L!ubZ2tNo}C9u=9*k%~Nc_ANt-Z z0@Vd=K243YGn4KLhBfJ+E^bJwJgreFZc2_+1GS?0*0-Asrq7 literal 0 HcmV?d00001 diff --git a/backend/tests/historical_pending_verification.py b/backend/tests/historical_pending_verification.py new file mode 100644 index 000000000..c4587de65 --- /dev/null +++ b/backend/tests/historical_pending_verification.py @@ -0,0 +1,71 @@ +"""Retained verifier input, restored before real upgrades and owner assertions.""" +import asyncio +import base64 +from contextlib import asynccontextmanager +import gzip +import hashlib +import json +from pathlib import Path +from types import SimpleNamespace +from uuid import UUID + +from alembic import command +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.db import session as db_session +from app.modules.artifacts.models import ArtifactStorageNamespace +from app.modules.artifacts.service import ArtifactStorageNamespaceSpec +from app.modules.authorization.runtime import HumanAuthorizationContext +from tests.conftest import _drop_test_database_schema +from tests.historical_submission_fixtures import _restore_validated_snapshot_rows +from tests.migration_fixtures import _config, current_schema_revision +from tests.retained_material_fixtures import MemoryStore +from tests.test_artifact_admission import _settings + + +@asynccontextmanager +async def retained_pending_verification(database_url, tmp_path, migration_lock): + encoded = (Path(__file__).with_name('fixtures') / 'retained_pending_verification.json.gz').read_bytes() + assert hashlib.sha256(encoded).hexdigest() == '1305eaa9de3083d2ca4188f3cdba40a42fa912f211fc90c99ea36989d45e3e38' + body = json.loads(gzip.decompress(encoded)) + assert body['schema_version'] == 'workstream.retained_pending_verification.v1' + assert body['source_revision'] == 'e2b926288899bcd9b05e1a560ec19b6bca8cfcfc' + snapshot = body['snapshot'] + assert snapshot['revision'] == '0065_claim_starts_work' + with migration_lock(): + await db_session.dispose_engine() + await _drop_test_database_schema(database_url) + try: + await asyncio.to_thread(command.upgrade, _config(), snapshot['revision']) + seed = await _restore_validated_snapshot_rows( + database_url, snapshot, expected_revision=snapshot['revision'], + ) + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + engine = create_async_engine(database_url) + factory = async_sessionmaker(engine, expire_on_commit=False) + try: + async with factory() as session: + row = await session.get(ArtifactStorageNamespace, 'primary') + assert row is not None + namespace = ArtifactStorageNamespaceSpec( + row.backend, row.adapter, row.provider_profile, + row.namespace_descriptor, row.namespace_fingerprint, + ) + store = MemoryStore(namespace) + for ref, value in seed['objects'].items(): + data = base64.b64decode(value, validate=True) + digest = hashlib.sha256(data).hexdigest() + assert ref == 'sha256/' + digest[:2] + '/' + digest[2:] + store.objects[ref] = data + yield SimpleNamespace( + factory=factory, context=HumanAuthorizationContext.model_validate_json(json.dumps(seed['context'])), + task_id=UUID(seed['task_id']), assignment_id=UUID(seed['assignment_id']), + project_id=UUID(seed['project_id']), put_attempt_id=UUID(seed['put_attempt_id']), + settings=_settings(tmp_path, maximum_bytes=1024 * 1024), + namespace=namespace, store=store, + ) + finally: + await engine.dispose() + finally: + await db_session.dispose_engine() + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) diff --git a/backend/tests/tasks/test_submission_lineage.py b/backend/tests/tasks/test_submission_lineage.py index 30964b2a4..d5d0b3f3d 100644 --- a/backend/tests/tasks/test_submission_lineage.py +++ b/backend/tests/tasks/test_submission_lineage.py @@ -13,7 +13,7 @@ from sqlalchemy.exc import DBAPIError, IntegrityError from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine -from app.modules.artifacts.api import SubmissionBundlePreparationRequest, SubmissionAdmissionConsumptionError +from app.modules.artifacts.api import SubmissionAdmissionConsumptionError from app.modules.artifacts.models import ( SubmissionBundleAdmission, ArtifactBinding, @@ -26,9 +26,7 @@ from app.modules.artifacts.repository import ArtifactRepository from app.modules.artifacts.submission_admission import SubmissionBundleAdmissionPublisher from app.modules.actors.api.service_identities import ServiceIdentity -from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.tasks.api import ( - SubmissionCreationRequest, TaskRetainedSubmissionParentsRequest, TaskSubmissionContextUnavailable, ) @@ -44,13 +42,13 @@ _context, _seed_human_actor, ) -from tests.archive_fixtures import byte_source as _bytes, submission_archive as _archive +from tests.archive_fixtures import submission_archive as _archive +from tests.historical_pending_verification import retained_pending_verification + from tests.tasks.submission_lineage_support import ( - _prepare_put_attempt, _seed_services, - _verified_admission, _verify_put_attempt, ) @@ -97,63 +95,6 @@ async def _submission_task( await engine.dispose() -@asynccontextmanager -async def _prepared_packet( - isolated_database_env, tmp_path, *, verify=True, pre_submit_registry_spec=pre_registry_spec(), -): - async with _submission_task( - isolated_database_env, tmp_path, pre_submit_registry_spec=pre_submit_registry_spec, - ) as task: - factory, context = task.factory, task.context - task_id, assignment_id = task.task_id, task.assignment_id - store, namespace, settings = task.store, task.namespace, task.settings - archive_bytes, policy = task.archive_bytes, task.policy - request = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - context.actor_profile_id, context.identity_link_id, ActorKind.HUMAN - ), - request_id=context.request_id, - correlation_id=context.correlation_id, - task_id=task_id, - assignment_id=assignment_id, - predecessor_submission_id=None, - idempotency_key=new_record_id(), - summary='Completed the "required" project work in folder \\results with evidence.', - contributor_attestation="I confirm no confidential client data, credentials, or copied source material is included in this submission; rights_confirmed. " - + " ".join(policy["attestation_terms"]), - media_type="application/zip", - byte_source=_bytes(archive_bytes), - ) - if verify: - admission_id = await _verified_admission( - factory, store, namespace, settings, context, request - ) - put_attempt_id = None - creation = SubmissionCreationRequest( - task_id=task_id, - assignment_id=assignment_id, - contributor_id=context.actor_profile_id, - predecessor_submission_id=None, - admission_id=admission_id, - summary=request.summary, - contributor_attestation=request.contributor_attestation, - ) - else: - put_attempt_id = await _prepare_put_attempt( - factory, settings, context, request - ) - admission_id = None - creation = None - yield SimpleNamespace( - factory=factory, context=context, task_id=task_id, assignment_id=assignment_id, - project_id=task.project_id, - admission_id=admission_id, creation=creation, - preparation_request=request, archive_bytes=archive_bytes, settings=settings, - store=store, namespace=namespace, - put_attempt_id=put_attempt_id, - ) - - @pytest.mark.parametrize("changed_owner", ("project", "task", "assignment", "contributor")) async def test_retained_submission_parent_lock_rejects_identity_substitution( isolated_database_env, @@ -186,12 +127,14 @@ async def test_retained_submission_parent_lock_rejects_identity_substitution( @pytest.mark.parametrize("lifecycle_owner", ("profile", "identity_link")) +@pytest.mark.postgres_schema_contract async def test_retained_verification_does_not_reauthorize_contributor_lifecycle( isolated_database_env, + migration_lock, tmp_path, lifecycle_owner, ): - async with _prepared_packet(isolated_database_env, tmp_path, verify=False) as h: + async with retained_pending_verification(isolated_database_env, tmp_path, migration_lock) as h: async with h.factory.begin() as session: if lifecycle_owner == "profile": await session.execute( @@ -228,11 +171,13 @@ async def test_retained_verification_does_not_reauthorize_contributor_lifecycle( assert admission is not None and admission.status == "ready" +@pytest.mark.postgres_schema_contract async def test_submission_verifier_missing_task_port_rolls_back_terminal_effects( isolated_database_env, + migration_lock, tmp_path, ): - async with _prepared_packet(isolated_database_env, tmp_path, verify=False) as h: + async with retained_pending_verification(isolated_database_env, tmp_path, migration_lock) as h: async with h.factory() as session: job = await session.scalar( select(ArtifactVerificationJob).where( @@ -311,8 +256,10 @@ async def test_retained_submission_parent_port_holds_task_and_assignment_locks( ) is not None +@pytest.mark.postgres_schema_contract async def test_submission_verifier_locks_task_parents_before_terminal_art( isolated_database_env, + migration_lock, tmp_path, monkeypatch, ): @@ -330,7 +277,7 @@ async def observe_job_lock(owner, job_id): events.append("artifact_job") return result - async with _prepared_packet(isolated_database_env, tmp_path, verify=False) as h: + async with retained_pending_verification(isolated_database_env, tmp_path, migration_lock) as h: monkeypatch.setattr( SubmissionBundleAdmissionPublisher, "lock_retained_submission_parents", From 0f80e0135bd5f9e417a8ab54447be3764cc7271a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:29:51 +0100 Subject: [PATCH 253/513] Preserve historical verifier decoding and immutable conflict receipts --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 13 +++++++ backend/app/modules/artifacts/service.py | 38 +++++++++---------- .../modules/artifacts/submission_admission.py | 23 +++++------ .../tests/tasks/test_submission_lineage.py | 37 ++++++++++++++++++ 4 files changed, 79 insertions(+), 32 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c799124b0..479a1fa52 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8609,3 +8609,16 @@ upgrade, and checks object hash before yielding current verifier tests. Removed the old _prepared_packet producer from test_submission_lineage.py; preserve its four lifecycle/rollback/locking cases and mark their actual schema operations. This does not yet retire other callers of the old preparation command. + +The four-case verifier run completed with3fail/1pass (492.26s, cleanup complete). +The unchanged missing-TASK rollback test passed. Actual retained verification +exposed two production defects: publisher decodes archived v1 PRE using the new +source-bound request type, and publication conflict mutates an already-inserted +immutable verification receipt. Extend this bounded scope to the retained +publisher in submission_admission.py and verification completion in service.py. +Use the existing read-only historical PRE decoder, never a new live v1 path. +On publication failure, roll back the verified transaction and retry the exact +job fence under fresh authority with one immutable conflict receipt. Preserve +trigger immutability, bytes and retained parent locks; add a focused publication +failure regression. ARCH/SEC and QA review remain required; the red run is not +successful historical-continuation evidence. diff --git a/backend/app/modules/artifacts/service.py b/backend/app/modules/artifacts/service.py index 6cce1abe1..948d1f3a3 100644 --- a/backend/app/modules/artifacts/service.py +++ b/backend/app/modules/artifacts/service.py @@ -1348,6 +1348,8 @@ async def _complete_verification( *, submission_task_contexts: TaskSubmissionContextPort | None = None, ) -> str: + from app.modules.artifacts.submission_admission import SubmissionBundleAdmissionPublicationError + claim_id, claim_generation = claimed.id, claimed.execution_generation try: return await self._complete_verification_transaction( @@ -1355,12 +1357,12 @@ async def _complete_verification( observed_sha256, observed_size, submission_task_contexts=submission_task_contexts, ) - except IntegrityError as exc: - if integrity_constraint_name(exc) != "ck_revision_admission_deadline_expired": + except (IntegrityError, SubmissionBundleAdmissionPublicationError) as exc: + if isinstance(exc, IntegrityError) and integrity_constraint_name(exc) != "ck_revision_admission_deadline_expired": raise # The failed root rolled back every verifier and admission effect. # Recheck the same job fence under fresh authority and retain a - # terminal conflict instead of retrying an expired admission. + # terminal conflict for inadmissible retained custody. return await self._complete_verification_transaction( claim_id, claim_generation, executor_id, expected_facts, outcome, observed_sha256, observed_size, @@ -1461,6 +1463,10 @@ async def _complete_verification_transaction( states ) replica.last_reconciled_at = now + if publication_conflict: + outcome = "conflict" + observed_sha256 = None + observed_size = None verification_receipt = await self._repo.add_verification_receipt( ArtifactVerificationReceipt( id=str(new_record_id()), @@ -1472,24 +1478,14 @@ async def _complete_verification_transaction( ) ) if outcome == "verified": - try: - if publication_conflict: - raise SubmissionBundleAdmissionPublicationError( - "submission admission retained identity is invalid" - ) - await publisher.publish_verified( - verification_job_id=job.id, - verification_receipt_id=verification_receipt.id, - retained_parents=retained_parents, - ) - except SubmissionBundleAdmissionPublicationError: - # Valid bytes can still have permanently inadmissible - # submission lineage. Keep one fenced terminal receipt and - # prevent an endless verifier retry loop. - outcome = "conflict" - verification_receipt.outcome = "conflict" - verification_receipt.observed_sha256 = None - verification_receipt.observed_byte_count = None + # Publication failure rolls back this entire transaction. The + # caller rechecks authority/fence and inserts one conflict fact; + # an inserted verification receipt must never be rewritten. + await publisher.publish_verified( + verification_job_id=job.id, + verification_receipt_id=verification_receipt.id, + retained_parents=retained_parents, + ) job.status = outcome job.next_run_at = None job.terminal_result_code = outcome diff --git a/backend/app/modules/artifacts/submission_admission.py b/backend/app/modules/artifacts/submission_admission.py index a1125e47e..2cf5960d9 100644 --- a/backend/app/modules/artifacts/submission_admission.py +++ b/backend/app/modules/artifacts/submission_admission.py @@ -2,8 +2,6 @@ from __future__ import annotations -from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts - from collections.abc import Callable from contextlib import AbstractAsyncContextManager, AsyncExitStack import asyncio @@ -80,12 +78,14 @@ from app.modules.artifacts.selected_pre_submit_execution import ( SelectedPreSubmitExecutionService, ) +from app.modules.checkers.api.historical_selected_pre_submit import ( + HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal, +) from app.modules.checkers.api.selected_pre_submit import ( SelectedPreSubmitCompletion, SelectedPreSubmitCoordinationPort, SelectedPreSubmitCurrentFacts, SelectedPreSubmitExecutionFacts, - SelectedPreSubmitReservationFacts, SelectedPreSubmitRequestConflict, SelectedPreSubmitUnavailable, ) @@ -338,10 +338,7 @@ async def lock_retained_submission_parents( if task_contexts is None: raise RuntimeError("submission verification TASK composition is unavailable") try: - selected = SelectedPreSubmitReservationFacts.from_canonical_body( - row.selected_request_json, - source_contracts=ArtifactPreSubmitSourceContracts(), - ) + selected = HistoricalSelectedPreSubmitReservation.from_canonical_body(row.selected_request_json) except (TypeError, ValueError) as exc: raise SubmissionBundleAdmissionPublicationError( "selected PRE request snapshot is invalid" @@ -397,10 +394,7 @@ async def publish_verified( if intent.pre_submit_evidence_set_id is not None or intent.selected_pre_submit_run_id is None: raise SubmissionBundleAdmissionPublicationError("external PRE durable intent is unavailable") try: - selected = SelectedPreSubmitReservationFacts.from_canonical_body( - intent.selected_request_json, - source_contracts=ArtifactPreSubmitSourceContracts(), - ) + selected = HistoricalSelectedPreSubmitReservation.from_canonical_body(intent.selected_request_json) except (TypeError, ValueError) as exc: raise SubmissionBundleAdmissionPublicationError( "selected PRE request snapshot is invalid" @@ -425,6 +419,12 @@ async def publish_verified( if existing is not None: return existing terminal = intent.selected_terminal_json + try: + retained_terminal = HistoricalSelectedPreSubmitTerminal.from_canonical_body(terminal) + except (TypeError, ValueError) as exc: + raise SubmissionBundleAdmissionPublicationError( + "selected PRE terminal snapshot is invalid" + ) from exc if ( selected.admission_lineage is None or selected.attempt_id != UUID(intent.selected_pre_submit_run_id) @@ -435,6 +435,7 @@ async def publish_verified( or terminal.get("outcome") != "completed" or type(terminal.get("execution")) is not dict or terminal["execution"].get("eligible") is not True + or retained_terminal.lease.reservation != selected ): raise SubmissionBundleAdmissionPublicationError( "selected PRE terminal snapshot is invalid" diff --git a/backend/tests/tasks/test_submission_lineage.py b/backend/tests/tasks/test_submission_lineage.py index d5d0b3f3d..529eaf824 100644 --- a/backend/tests/tasks/test_submission_lineage.py +++ b/backend/tests/tasks/test_submission_lineage.py @@ -518,3 +518,40 @@ async def test_packet_custody_upgrade_preserves_retained_submission( "SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgname='submission_packet_custody'" )) == 1 await asyncio.to_thread(command.upgrade, _config(), "head") + + +@pytest.mark.postgres_schema_contract +async def test_retained_publication_failure_inserts_one_immutable_conflict( + isolated_database_env, tmp_path, migration_lock, monkeypatch, +): + from app.modules.artifacts.submission_admission import SubmissionBundleAdmissionPublicationError + calls = [] + + async def refuse_publication(self, **kwargs): + calls.append(kwargs['verification_receipt_id']) + # The tentative verified receipt really exists before publication fails. + receipt = await self._session.get(ArtifactVerificationReceipt, kwargs['verification_receipt_id']) + assert receipt.outcome == 'verified' + raise SubmissionBundleAdmissionPublicationError('controlled publication rejection') + + async with retained_pending_verification(isolated_database_env, tmp_path, migration_lock) as h: + monkeypatch.setattr(SubmissionBundleAdmissionPublisher, 'publish_verified', refuse_publication) + async with h.factory() as session: + job_id = await session.scalar(select(ArtifactVerificationJob.id).where( + ArtifactVerificationJob.originating_put_attempt_id == str(h.put_attempt_id))) + await session.rollback() + authority = PreparedArtifactInternalAuthority( + session, service_identity=ServiceIdentity.ARTIFACT_VERIFIER, + request_id=new_record_id(), correlation_id=new_record_id(), + ) + result = await ArtifactStorageOrchestrator( + session, h.store, h.namespace, h.settings, authority, + ).verify_object(UUID(job_id), submission_task_contexts=task_submission_context_port(session)) + assert result == 'conflict' + async with h.factory() as session: + receipt = (await session.scalars(select(ArtifactVerificationReceipt))).one() + assert receipt.outcome == 'conflict' + assert receipt.observed_sha256 is receipt.observed_byte_count is None + assert len(calls) == 1 and receipt.id != calls[0] + assert (await session.get(ArtifactVerificationJob, job_id)).status == 'conflict' + assert await session.scalar(select(func.count()).select_from(SubmissionBundleAdmission)) == 0 From cab012915860a3516db070c1a3568402cf5a4fde Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:39:03 +0100 Subject: [PATCH 254/513] Record retained verifier repair evidence and deployment limits --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 479a1fa52..ee2829669 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8622,3 +8622,18 @@ job fence under fresh authority with one immutable conflict receipt. Preserve trigger immutability, bytes and retained parent locks; add a focused publication failure regression. ARCH/SEC and QA review remain required; the red run is not successful historical-continuation evidence. + +Repair verification at0f80e0135: profile suspension + forced late publication +failure passed2/2 in170.70s (/tmp/submission-retained-verifier-repair.json; +precommit launcher c982e19ee with final repair bytes). Identity-link revocation +and original lock ordering passed2/2 in184.04s at exact0f80e0135 +(/tmp/submission-retained-verifier-remaining.json). Both receipts confirm +schema0090 and complete database/MinIO cleanup. Missing-TASK rollback passed in +the earlier four-case run. Structure, authorization boundary, Ruff and diff +checks passed. ARCH/SEC PASS at clean0f80e0135; no guard weakening or live v1 +execution restored. QA inspected unchanged original assertion bodies, archive +checksum/byte identity, and the unrelated-integrity-error propagation control. +These separate runs close the retained verifier regression scope, not a single +aggregate final-head run. Spec20.2 still requires deployed old unsubmitted work +to be drained or explicitly stale before cutover; restored historical test +inputs do not authorize deploying with pending old submissions. From cfdd0101d06817afd4d1579ceda9b108f40949d4 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:45:11 +0100 Subject: [PATCH 255/513] Move revision rejection proofs to public raw ZIP intake --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 ++ .../tests/selected_predecessor_fixtures.py | 46 ++++++ .../test_revision_capacity.py | 4 +- .../test_submission_predecessor_custody.py | 136 +++++++----------- 4 files changed, 117 insertions(+), 83 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index ee2829669..1f2db0022 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8637,3 +8637,17 @@ These separate runs close the retained verifier regression scope, not a single aggregate final-head run. Spec20.2 still requires deployed old unsubmitted work to be drained or explicitly stale before cutover; restored historical test inputs do not authorize deploying with pending old submissions. + +### Move revision rejection controls to the raw-ZIP command + +Allowed: the unchanged-archive/semantic-manifest and secret-rejection cases in +test_submission_predecessor_custody.py, their selected_predecessor_fixtures +assertions, the existing revision HTTP runtime helper, and this record. Replace +their old prepare/ready-admission calls with public raw-ZIP requests and current +operation receipts. Preserve exact rejection codes, no project execution after +default failure, persisted terminal/authority/source binding, unchanged retained +artifact/Submission/POST facts, needs_revision task state, missing-attestation +warning and a corrected fresh-key acceptance. New source uploads are expected +and remain charged/cleanup-owned; no SHA-artifact put is permitted. No production, +schema, runner or broader test deletion. Risk: medium workflow-test migration; +run both cases on PostgreSQL, structure/Ruff, then scoped QA/ARCH review. diff --git a/backend/tests/selected_predecessor_fixtures.py b/backend/tests/selected_predecessor_fixtures.py index 64bbdd264..1dc46ace3 100644 --- a/backend/tests/selected_predecessor_fixtures.py +++ b/backend/tests/selected_predecessor_fixtures.py @@ -48,6 +48,52 @@ async def _snapshot(h) -> tuple[tuple[str, int], ...]: return tuple(rows) +async def assert_public_revision_rejection(h, response, key, data, before, code): + """Keep rejected source custody without changing retained submission facts.""" + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + assert response.status_code == 422, response.text + error = response.json()['error'] + assert error['code'] == 'pre_submission_checker_failed' + assert error['details']['eligible_to_submit'] is False + results = error['details']['results'] + assert [r['failure_code'] for r in results if r['status'] == 'failed'] == [code] + assert not any(r['source'] == 'project_external_checker' for r in results) + expected = dict(before) + expected['selected_pre_submit_runs'] += 1 + assert dict(await _snapshot(h)) == expected + async with h.factory() as session: + operation = (await session.scalars(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.task_id == str(h.request.task_id), + SubmissionIntakeOperation.idempotency_key == str(key), + ))).one() + assert operation.state == 'rejected' and operation.finalized_submission_id is None + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.accounted_bytes == len(data) and charge.state == 'sealed' + run = (await session.scalars(select(SelectedPreSubmitRun).where( + SelectedPreSubmitRun.source_operation_id == operation.id, + ))).one() + terminal = SelectedPreSubmitTerminalFacts.from_canonical_body( + run.terminal_json, source_contracts=selected_pre_submit_source_contracts()) + reservation = terminal.lease.reservation + assert run.status == terminal.outcome == 'completed' and run.eligible is False + assert terminal.execution.eligible is False and terminal.execution.external_members == () + assert terminal.terminal_digest == run.terminal_digest + assert reservation.request_digest == run.request_digest + assert reservation.task_id == h.request.task_id + assert reservation.assignment_id == h.request.assignment_id + assert reservation.actor_profile_id == h.actor_context.actor_profile_id + assert reservation.source.location.operation_id == UUID(operation.id) + assert reservation.admission_lineage.predecessor_submission_id == h.created.submission_id + assert await session.scalar(text( + "SELECT public.selected_pre_submit_receipt_valid(r,'execute',false) " + "AND public.selected_pre_submit_receipt_valid(r,'finalize',false) " + "FROM selected_pre_submit_runs r WHERE id=:id"), {'id': run.id}) is True + assert await session.scalar(text('SELECT count(*) FROM submissions')) == 1 + assert await session.scalar(text('SELECT status FROM workstream_tasks WHERE id=:id'), + {'id': h.request.task_id}) == 'needs_revision' + return results + + def _secret_archive(data: bytes) -> bytes: """Keep the real changed packet and introduce one known secret signature.""" output = BytesIO(data) diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index 7f7f4a94e..9ba199f26 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -100,11 +100,11 @@ def _revision_upload_headers(h): } -async def _revision_http_runtime(h, client, tmp_path, monkeypatch, data): +async def _revision_http_runtime(h, client, tmp_path, monkeypatch, data, *, outcome="completed"): """Use controlled PRE with the already claimed source namespace capacity.""" from tests.artifacts.test_submission_foreground_command import configure_source_http _, settings, errors, calls = await configure_source_http( - h.factory, client, tmp_path, monkeypatch, data, "completed") + h.factory, client, tmp_path, monkeypatch, data, outcome) settings = settings.model_copy(update={"submission_execution_profile": { **settings.submission_execution_profile, "capacity": {"maximum_total_bytes": 16 * 1024**2}, diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 52b377af5..35dd842d8 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -332,99 +332,73 @@ async def test_replacement_without_routed_cause_denied_before_bytes( async def test_unchanged_replacement_archive_or_manifest_denied( tmp_path, isolated_database_env, monkeypatch, ): + from tests.selected_predecessor_fixtures import assert_public_revision_rejection + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.test_public_submission_intake import _client + provider_writes = _trace_provider_writes(monkeypatch) async with remediation_source(tmp_path, isolated_database_env) as h: - await _fixture_revision_context(h) - baseline = await _snapshot(h) + source_id = await _fixture_revision_context(h) + retained = await _replacement_history(h, source_id, h.created.submission_id) provider_writes.clear() - predecessor_id = h.created.submission_id - for data, expected in ( - (h.data, "submission_archive_unchanged"), - ( - _same_semantics_different_archive(h.data), - "submission_manifest_unchanged", - ), - ): - request = _replacement_request( - h, data, predecessor_id=predecessor_id, idempotency_key=new_record_id(), - ) - with pytest.raises(SubmissionBundlePreparationCheckFailed) as failure: - await _prepare(h, request) - await _assert_default_failure(h, request, failure.value, baseline, expected) - baseline = await _snapshot(h) + async with _client(h, monkeypatch, isolated_database_env) as client: + route = f"/api/v1/tasks/{h.request.task_id}/submissions" + for data, expected in ( + (h.data, "submission_archive_unchanged"), + (_same_semantics_different_archive(h.data), "submission_manifest_unchanged"), + ): + before = await _snapshot(h) + _, errors, calls = await _revision_http_runtime( + h, client, tmp_path, monkeypatch, data, outcome="rejected") + headers = _revision_upload_headers(h) + response = await client.post(route, headers=headers, content=data) + await assert_public_revision_rejection( + h, response, UUID(headers['Idempotency-Key']), data, before, expected) + assert len(calls) == 1 and not errors, errors + assert provider_writes == [] + assert await _replacement_history(h, source_id, h.created.submission_id) == retained + corrected = revision_archive(h.data) + _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, corrected) + accepted = await client.post(route, headers=_revision_upload_headers(h), content=corrected) + assert accepted.status_code == 202, accepted.text + assert accepted.json()['status'] == 'accepted' and accepted.json()['replayed'] is False + assert len(calls) == 1 and not errors, errors assert provider_writes == [] - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, h.actor_context, - _replacement_request( - h, revision_archive(h.data), predecessor_id=predecessor_id, - idempotency_key=new_record_id(), - ), - ) - async with h.factory() as session: - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert admission.status == "ready" - async def test_blocked_replacement_precheck_preserves_revision_state( - tmp_path, - isolated_database_env, - monkeypatch, + tmp_path, isolated_database_env, monkeypatch, ): + from tests.selected_predecessor_fixtures import assert_public_revision_rejection + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.test_public_submission_intake import _client + provider_writes = _trace_provider_writes(monkeypatch) async with remediation_source(tmp_path, isolated_database_env) as h: - await _fixture_revision_context(h) + source_id = await _fixture_revision_context(h) + retained = await _replacement_history(h, source_id, h.created.submission_id) provider_writes.clear() changed_data = revision_archive(h.data) - baseline = await _snapshot(h) - request = replace( - _replacement_request( - h, - _secret_archive(changed_data), - predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ), - contributor_attestation="", - ) - with pytest.raises(SubmissionBundlePreparationCheckFailed) as blocked: - await _prepare(h, request) - await _assert_default_failure( - h, - request, - blocked.value, - baseline, - "high_confidence_secret_detected", - ) - assert tuple( - warning.code for warning in blocked.value.facts.workstream_default.warnings - ) == ("submission_attestation_missing",) - assert provider_writes == [] - async with h.factory() as session: - assert await session.scalar(text("SELECT count(*) FROM public.submissions")) == 1 - assert ( - await session.scalar( - text("SELECT status FROM public.workstream_tasks WHERE id=:id"), - {"id": h.request.task_id}, - ) - == "needs_revision" - ) - - admission_id = await _verified_admission( - h.factory, - h.store, - h.namespace, - h.settings, - h.actor_context, - _replacement_request( - h, - changed_data, - predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ), - ) - async with h.factory() as session: - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert admission.status == "ready" + data = _secret_archive(changed_data) + before = await _snapshot(h) + async with _client(h, monkeypatch, isolated_database_env) as client: + route = f"/api/v1/tasks/{h.request.task_id}/submissions" + _, errors, calls = await _revision_http_runtime( + h, client, tmp_path, monkeypatch, data, outcome="rejected") + headers = _revision_upload_headers(h) | {'X-Contributor-Attestation': ''} + response = await client.post(route, headers=headers, content=data) + results = await assert_public_revision_rejection( + h, response, UUID(headers['Idempotency-Key']), data, before, 'high_confidence_secret_detected') + assert [r['warning_code'] for r in results if r['status'] == 'warning'] == ['submission_attestation_missing'] + assert len(calls) == 1 and not errors, errors + assert provider_writes == [] + assert await _replacement_history(h, source_id, h.created.submission_id) == retained + _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, changed_data) + accepted = await client.post(route, headers=_revision_upload_headers(h), content=changed_data) + assert accepted.status_code == 202, accepted.text + assert accepted.json()['status'] == 'accepted' and accepted.json()['replayed'] is False + assert len(calls) == 1 and not errors, errors + assert provider_writes == [] async def test_replacement_loads_exact_consumed_predecessor( From abe88c0d2ebf3fa0d7dd52e84fc04e1cbf1d37a7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:47:45 +0100 Subject: [PATCH 256/513] Bind public revision feedback to persisted PRE terminal --- backend/tests/selected_predecessor_fixtures.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/tests/selected_predecessor_fixtures.py b/backend/tests/selected_predecessor_fixtures.py index 1dc46ace3..c6fd48d95 100644 --- a/backend/tests/selected_predecessor_fixtures.py +++ b/backend/tests/selected_predecessor_fixtures.py @@ -51,6 +51,7 @@ async def _snapshot(h) -> tuple[tuple[str, int], ...]: async def assert_public_revision_rejection(h, response, key, data, before, code): """Keep rejected source custody without changing retained submission facts.""" from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from app.modules.artifacts.api.submission_preparation import public_pre_submission_results assert response.status_code == 422, response.text error = response.json()['error'] assert error['code'] == 'pre_submission_checker_failed' @@ -77,6 +78,7 @@ async def assert_public_revision_rejection(h, response, key, data, before, code) reservation = terminal.lease.reservation assert run.status == terminal.outcome == 'completed' and run.eligible is False assert terminal.execution.eligible is False and terminal.execution.external_members == () + assert public_pre_submission_results(terminal.execution) == results assert terminal.terminal_digest == run.terminal_digest assert reservation.request_digest == run.request_digest assert reservation.task_id == h.request.task_id From 59abae501cc0cdf5c7dd2e736b38bcadb8f1a5b7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:51:44 +0100 Subject: [PATCH 257/513] Record public revision rejection verification and review repair --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 1f2db0022..418ac9dfb 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8651,3 +8651,14 @@ warning and a corrected fresh-key acceptance. New source uploads are expected and remain charged/cleanup-owned; no SHA-artifact put is permitted. No production, schema, runner or broader test deletion. Risk: medium workflow-test migration; run both cases on PostgreSQL, structure/Ruff, then scoped QA/ARCH review. + +Both migrated cases passed initially (112.31s). QA-REVISION-REJECTION-001 found +that expected HTTP feedback was not compared with the persisted typed terminal. +Added exact public projection equality; the repeated pair passed in106.66s at +abe88c0d2, schema0090, complete database/MinIO cleanup +(/tmp/submission-public-revision-feedback.json). QA's bounded mutation probe +rejects substituted persisted failure code, warning code and finding count. +Structure, Ruff, diff and Commitrail checks passed; scoped ARCH/SEC reported no +finding. These are real HTTP/SQL with controlled guest transport, not native +provider or full deployed journey qualification. Other obsolete preparation +callers remain outside this two-case retirement. From 179395685c1e43a8b3ffb68d33940f3277bb59f7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:44:58 +0100 Subject: [PATCH 258/513] Move checker execution to dedicated remote runner --- .../changes/flow-self-service-signup.md | 39 +- backend/app/adapters/artifacts/__init__.py | 24 +- .../app/adapters/artifacts/trusted_intake.py | 77 ++- backend/app/adapters/checkers/__init__.py | 45 +- .../app/adapters/checkers/external_service.py | 134 +++- .../app/adapters/checkers/model_runtime.py | 14 +- .../adapters/checkers/remote_model_bridge.py | 161 +++++ backend/app/core/config.py | 60 +- .../interfaces/external_checker_execution.py | 23 +- .../artifacts/post_submit_materialization.py | 4 +- backend/app/modules/artifacts/preparation.py | 120 +++- .../artifacts/submission_materialization.py | 1 + .../checkers/external/test_remote_node.py | 299 +++++++++ .../tests/checkers/external/test_runtime.py | 262 +++----- backend/tests/test_trusted_intake.py | 82 ++- deploy/hosted/SINGLE_HOST.md | 167 ----- deploy/hosted/compose.native-checker.yml | 20 - deploy/hosted/compose.py | 51 -- deploy/hosted/compose.yml | 75 ++- deploy/hosted/preflight.py | 165 ++--- deploy/hosted/release.env.example | 22 +- .../public_intake_observer.py | 12 +- .../deploy/remote-node.example.json | 12 + .../deploy/workstream-checker.service | 3 +- .../deploy/workstream-remote-node.service | 28 + external_checkers/intake/Dockerfile | 1 + external_checkers/remote_node.py | 597 ++++++++++++++++++ .../workstream-checker-service/src/main.rs | 4 + 28 files changed, 1886 insertions(+), 616 deletions(-) create mode 100644 backend/app/adapters/checkers/remote_model_bridge.py create mode 100644 backend/tests/checkers/external/test_remote_node.py delete mode 100644 deploy/hosted/SINGLE_HOST.md delete mode 100644 deploy/hosted/compose.native-checker.yml create mode 100644 external_checkers/deploy/remote-node.example.json create mode 100644 external_checkers/deploy/workstream-remote-node.service create mode 100644 external_checkers/remote_node.py diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index 1df875797..902d60c4b 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -138,8 +138,8 @@ hosting and storage contracts remain in the bounded sections below; they are implementation scopes within this delivery, not separate merge gates. Preserve identity accounts, database state and public URLs during migration. Verify login/API/MCP and unavailable checker behavior before moving the Elastic -IP and stopping the old host. Separate KVM execution qualification remains an -explicit follow-up boundary, not a claim made by app-only startup. +IP and stopping the old host. KVM execution runs on the separately qualified, +always-on runner described below; the app host remains KVM-free. ## App-only hosting scope @@ -159,11 +159,12 @@ delivery owner as ordinary assignment, revision and completion effects. ## Bounded change - Add an explicit hosted app profile in `deploy/hosted/{compose.py,preflight.py,compose.yml,release.env.example}` - and an overlay for native-only configuration if needed. The app profile + and a mutually authenticated remote-runner boundary. The app profile preserves existing API, parser, inference proxy, storage qualification, database, broker, and identity validation and activates without local checker files, mounts, native systemd start, or KVM readiness. Reject conflicting native or - trial configuration in this profile. Keep the existing single-host mode. + trial configuration in this profile. Remove the superseded single-host + API-plus-microVM deployment rather than retaining a fallback mode. - Compose a fixed checker-delivery exclusion in `backend/app/core/config.py`, `backend/app/adapters/outbox/__init__.py`, `backend/app/modules/outbox/delivery.py` and `delivery_repository.py`. Filter @@ -409,3 +410,33 @@ service. PRE remains unavailable and POST requests are excluded from ordinary delivery, as proved by the focused API/outbox tests. Live ZIP intake and checker execution require a qualified checker host. The complete public OAuth and MCP drill passed on a clean Chrome rerun after a startup crash. + +## Dedicated remote runner scope — 2026-11-24 + +Replace the unreleased shared-host checker wiring with one provider-neutral +typed capability whose hosted provider is an always-on, on-demand AWS runner. +Allowed implementation paths are `external_checkers/**`, the CHECKERS and +trusted-intake adapters/interfaces, ART's descriptor-relative material export, +hosted configuration/composition/preflight, their focused tests, and affected +operator documentation. Submission lifecycle, TASK state, S3 source admission, +intake cleanup ownership, and alternate managed-provider claims remain outside +this scope. + +The app opens TLS 1.3 connections authenticated by a dedicated client +certificate. PRE source and POST material bytes cross that boundary in bounded +frames; no API-host filesystem path crosses it. The runner verifies exact +request/source/grant bindings, stages one private runner-local workspace, invokes +the existing native Unix service, and removes the exact session on success, +failure, timeout or disconnect. A persistent outbound app model-proxy bridge +preserves request-bound model callbacks without opening inbound access to the +app host. Future managed providers must implement the same typed task/source/ +result contract; no E2B, Daytona or other vendor is claimed supported here. + +Live evidence on instance `i-0936c305f8f67d835` proves m7i.large nested KVM, +Smol health with two pinned manifests, a completed request-bound remote POST, +and a completed streamed-ZIP PRE. PRE reported native Smol isolation and +`cleanup=destroyed`; POST and PRE left material workspaces, model relays and +Smol leases empty. Focused local remote transport/intake coverage passed 85 +tests. Successful-checker public acceptance and a real model-callback provider +journey remain explicit integration qualifications, not claims from the +transport smoke tests. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 98675a1d6..6396f09ab 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -80,7 +80,7 @@ ) from workstream_external_services import ExternalServiceAdapterFactory, ExternalServiceConfigurationError from app.interfaces.trusted_submission_intake import TrustedSubmissionIntakeAdapter -from app.adapters.artifacts.trusted_intake import CAPABILITY, PROVIDER, UnixSocketTrustedIntakeAdapter +from app.adapters.artifacts.trusted_intake import CAPABILITY, PROVIDER, RemoteTlsTrustedIntakeAdapter from app.modules.artifacts.preparation import ( ArtifactPreparationLimits, ArtifactPreparationService, @@ -109,13 +109,25 @@ def trusted_submission_intake(settings: Settings) -> TrustedSubmissionIntakeAdapter: """Register the sole ART capability provider with explicit pinned identity.""" - if any(value is None for value in (settings.artifact_intake_service_socket, - settings.artifact_intake_image_digest, - settings.artifact_intake_config_digest)): + if any(value is None for value in ( + settings.external_runner_host, + settings.external_runner_port, + settings.external_runner_server_name, + settings.external_runner_ca_path, + settings.external_runner_certificate_path, + settings.external_runner_private_key_path, + settings.artifact_intake_image_digest, + settings.artifact_intake_config_digest, + )): raise ExternalServiceConfigurationError() factory = ExternalServiceAdapterFactory[TrustedSubmissionIntakeAdapter](CAPABILITY) - factory.register(PROVIDER, lambda: UnixSocketTrustedIntakeAdapter( - socket_path=settings.artifact_intake_service_socket, + factory.register(PROVIDER, lambda: RemoteTlsTrustedIntakeAdapter( + host=settings.external_runner_host, + port=settings.external_runner_port, + server_name=settings.external_runner_server_name, + ca_path=settings.external_runner_ca_path, + certificate_path=settings.external_runner_certificate_path, + private_key_path=settings.external_runner_private_key_path, image_digest=settings.artifact_intake_image_digest, config_digest=settings.artifact_intake_config_digest, )) diff --git a/backend/app/adapters/artifacts/trusted_intake.py b/backend/app/adapters/artifacts/trusted_intake.py index 93bcde95d..7d0f5433e 100644 --- a/backend/app/adapters/artifacts/trusted_intake.py +++ b/backend/app/adapters/artifacts/trusted_intake.py @@ -10,6 +10,7 @@ from pathlib import Path import re import socket +import ssl import struct import threading import time @@ -42,8 +43,9 @@ ) CAPABILITY = "trusted_submission_intake" -PROVIDER = "unix_socket" +PROVIDER = "remote_tls" _PROTOCOL = "trusted_submission_intake.v1" +_REMOTE_PROTOCOL = "workstream.remote_runner.v1" _MAX_FRAME = 64 * 1024 * 1024 _MAX_COMMAND = 4 * 1024 * 1024 _MAX_ARCHIVE = 512 * 1024 * 1024 @@ -85,24 +87,60 @@ def _entry(value: object) -> SubmissionArchiveEntry: ) -class UnixSocketTrustedIntakeAdapter: - """Construct one local session; the node owns all preparation retry decisions.""" +class RemoteTlsTrustedIntakeAdapter: + """Construct one authenticated remote session owned by the dedicated node.""" - def __init__(self, *, socket_path: Path, image_digest: str, config_digest: str) -> None: - """Bind an absolute private socket to operator-pinned image and config identities.""" + def __init__( + self, + *, + host: str, + port: int, + server_name: str, + ca_path: Path, + certificate_path: Path, + private_key_path: Path, + image_digest: str, + config_digest: str, + ) -> None: + """Bind a pinned TLS identity to operator-pinned image and config identities.""" if ( - not socket_path.is_absolute() - or socket_path.is_symlink() + type(host) is not str + or not host + or len(host) > 255 + or type(port) is not int + or not 1 <= port <= 65_535 + or type(server_name) is not str + or not server_name + or len(server_name) > 255 + or any(not path.is_absolute() or path.is_symlink() for path in ( + ca_path, certificate_path, private_key_path + )) or any( type(v) is not str or re.fullmatch(r"sha256:[0-9a-f]{64}", v) is None for v in (image_digest, config_digest) ) ): raise ValueError("trusted intake configuration invalid") - self._path = socket_path + self._host, self._port, self._server_name = host, port, server_name + self._ca_path = ca_path + self._certificate_path = certificate_path + self._private_key_path = private_key_path self._image = image_digest self._config = config_digest + def _tls_context(self) -> ssl.SSLContext: + context = ssl.create_default_context( + ssl.Purpose.SERVER_AUTH, + cafile=str(self._ca_path), + ) + context.minimum_version = ssl.TLSVersion.TLSv1_3 + context.check_hostname = True + context.load_cert_chain( + certfile=str(self._certificate_path), + keyfile=str(self._private_key_path), + ) + return context + @property def identity(self) -> ExternalServiceAdapterIdentity: """Identify this typed capability and its explicitly registered provider.""" @@ -149,7 +187,7 @@ class _Session: def __init__( self, - adapter: UnixSocketTrustedIntakeAdapter, + adapter: RemoteTlsTrustedIntakeAdapter, deadline: float, request: TrustedIntakePreparation | None = None, ) -> None: @@ -157,7 +195,7 @@ def __init__( self._adapter = adapter self._deadline = deadline self._request = request - self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._lock = threading.Lock() self._aborted = threading.Event() self._state = "new" @@ -280,11 +318,24 @@ def _response(self, operation: str, *, cleanup: bool = False) -> dict: return body["payload"] def _connect(self) -> None: - """Connect only to the configured private socket within the lease deadline.""" + """Connect only to the authenticated runner within the lease deadline.""" self._timeout() try: - self._socket.connect(str(self._adapter._path)) - except OSError as exc: + self._socket.connect((self._adapter._host, self._adapter._port)) + self._socket = self._adapter._tls_context().wrap_socket( + self._socket, + server_hostname=self._adapter._server_name, + ) + control = json.dumps( + { + "protocol_version": _REMOTE_PROTOCOL, + "operation": "proxy", + "capability": CAPABILITY, + }, + separators=(",", ":"), + ).encode() + self._send(struct.pack(">I", len(control)) + control) + except (OSError, ssl.SSLError) as exc: raise ExternalServiceUnavailableError(self._adapter.identity) from exc def _health(self) -> TrustedIntakeIdentity: diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py index 3a35ab4fc..7621f3aeb 100644 --- a/backend/app/adapters/checkers/__init__.py +++ b/backend/app/adapters/checkers/__init__.py @@ -5,7 +5,7 @@ from app.adapters.checkers.external_service import ( EXTERNAL_CHECKER_CAPABILITY_KEY, EXTERNAL_CHECKER_PROVIDER_KEY, - UnixSocketExternalCheckerAdapter, + RemoteTlsExternalCheckerAdapter, ) from app.interfaces.external_checker_execution import ( ExternalCheckerExecutionAdapter, @@ -54,17 +54,29 @@ def revision_feedback_port(session) -> RevisionFeedbackPort: def external_checker_execution_factory( - *, socket_path: Path, timeout_seconds: float -) -> ExternalServiceAdapterFactory[UnixSocketExternalCheckerAdapter]: - """Compose the sole instance-local external checker adapter factory.""" + *, + host: str, + port: int, + server_name: str, + ca_path: Path, + certificate_path: Path, + private_key_path: Path, + timeout_seconds: float, +) -> ExternalServiceAdapterFactory[RemoteTlsExternalCheckerAdapter]: + """Compose the sole dedicated-node external checker adapter factory.""" from app.adapters.artifacts import selected_pre_submit_source_contracts - factory = ExternalServiceAdapterFactory[UnixSocketExternalCheckerAdapter]( + factory = ExternalServiceAdapterFactory[RemoteTlsExternalCheckerAdapter]( EXTERNAL_CHECKER_CAPABILITY_KEY ) factory.register( EXTERNAL_CHECKER_PROVIDER_KEY, - lambda: UnixSocketExternalCheckerAdapter( - socket_path=socket_path, + lambda: RemoteTlsExternalCheckerAdapter( + host=host, + port=port, + server_name=server_name, + ca_path=ca_path, + certificate_path=certificate_path, + private_key_path=private_key_path, timeout_seconds=timeout_seconds, source_contracts=selected_pre_submit_source_contracts(), ), @@ -146,12 +158,21 @@ def openrouter_provider(): def configured_external_checker_execution_factory(settings): """Map configured image-execution settings into the sole adapter factory.""" if ( - settings.external_checker_service_socket is None - or settings.external_checker_material_root is None + settings.external_runner_host is None + or settings.external_runner_port is None + or settings.external_runner_server_name is None + or settings.external_runner_ca_path is None + or settings.external_runner_certificate_path is None + or settings.external_runner_private_key_path is None ): raise ValueError("external checker service is not configured") return external_checker_execution_factory( - socket_path=settings.external_checker_service_socket, + host=settings.external_runner_host, + port=settings.external_runner_port, + server_name=settings.external_runner_server_name, + ca_path=settings.external_runner_ca_path, + certificate_path=settings.external_runner_certificate_path, + private_key_path=settings.external_runner_private_key_path, timeout_seconds=float(settings.external_checker_service_timeout_seconds), ) @@ -179,8 +200,8 @@ def pre_runtime_provider(self) -> Literal["smolvm", "managed"]: def _resolve(self) -> ExternalCheckerExecutionAdapter: """Create the fixed provider or report absent runtime configuration.""" if ( - self._settings.external_checker_service_socket is None - and self._settings.external_checker_material_root is None + self._settings.external_runner_host is None + and self._settings.external_runner_port is None ): raise ExternalServiceUnavailableError(self._identity) return configured_external_checker_execution_factory(self._settings).create( diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py index 4a5d08890..8a365f304 100644 --- a/backend/app/adapters/checkers/external_service.py +++ b/backend/app/adapters/checkers/external_service.py @@ -1,4 +1,4 @@ -"""Unix-socket adapter for the privileged external checker service.""" +"""Mutually authenticated remote adapter for the dedicated checker node.""" from __future__ import annotations @@ -9,6 +9,7 @@ import hashlib from datetime import datetime, timezone from pathlib import Path +import ssl import struct from typing import Literal @@ -51,26 +52,50 @@ ) EXTERNAL_CHECKER_CAPABILITY_KEY = "external_checker_execution" -EXTERNAL_CHECKER_PROVIDER_KEY = "unix_socket" +EXTERNAL_CHECKER_PROVIDER_KEY = "remote_tls" _PROTOCOL = "external_checker_service.v1" +_REMOTE_PROTOCOL = "workstream.remote_runner.v1" _MAXIMUM_RESPONSE_BYTES = MAX_RESULT_BYTES + 16_384 _EXECUTION_OVERHEAD_SECONDS = EXTERNAL_CHECKER_EXECUTION_CLEANUP_MARGIN_MS / 1000 -class UnixSocketExternalCheckerAdapter: - """Speak one length-framed strict request over a private Unix socket.""" +class RemoteTlsExternalCheckerAdapter: + """Speak the existing service protocol through one authenticated remote node.""" - def __init__(self, *, socket_path: Path, timeout_seconds: float, source_contracts: SelectedPreSubmitSourceContracts) -> None: - """Validate immutable local transport settings without opening the socket.""" + def __init__( + self, + *, + host: str, + port: int, + server_name: str, + ca_path: Path, + certificate_path: Path, + private_key_path: Path, + timeout_seconds: float, + source_contracts: SelectedPreSubmitSourceContracts, + ) -> None: + """Validate immutable endpoint settings without opening a connection.""" if ( - not socket_path.is_absolute() - or socket_path.is_symlink() + type(host) is not str + or not host + or len(host) > 255 + or type(port) is not int + or not 1 <= port <= 65_535 + or type(server_name) is not str + or not server_name + or len(server_name) > 255 + or any(not path.is_absolute() or path.is_symlink() for path in ( + ca_path, certificate_path, private_key_path + )) or type(timeout_seconds) is not float or not 0.1 <= timeout_seconds <= 3_700.0 ): raise ValueError("external checker service configuration is invalid") self._source_contracts = source_contracts - self._socket_path = socket_path + self._host, self._port, self._server_name = host, port, server_name + self._ca_path = ca_path + self._certificate_path = certificate_path + self._private_key_path = private_key_path self._timeout_seconds = timeout_seconds self._identity = ExternalServiceAdapterIdentity( EXTERNAL_CHECKER_CAPABILITY_KEY, @@ -84,9 +109,50 @@ def identity(self) -> ExternalServiceAdapterIdentity: @property def pre_runtime_provider(self) -> Literal["smolvm"]: - """The native socket factory accepts only Smol runtime evidence.""" + """The dedicated native node accepts only Smol runtime evidence.""" return "smolvm" + def _tls_context(self) -> ssl.SSLContext: + context = ssl.create_default_context( + ssl.Purpose.SERVER_AUTH, + cafile=str(self._ca_path), + ) + context.minimum_version = ssl.TLSVersion.TLSv1_3 + context.check_hostname = True + context.load_cert_chain( + certfile=str(self._certificate_path), + keyfile=str(self._private_key_path), + ) + return context + + async def _open(self) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]: + return await asyncio.open_connection( + self._host, + self._port, + ssl=self._tls_context(), + server_hostname=self._server_name, + ) + + @staticmethod + async def _send_frame(writer: asyncio.StreamWriter, payload: bytes) -> None: + if not payload or len(payload) > 64 * 1024 * 1024: + raise ValueError("remote runner frame is invalid") + writer.write(struct.pack(">I", len(payload)) + payload) + await writer.drain() + + async def _proxy_connection(self) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]: + reader, writer = await self._open() + control = json.dumps( + { + "protocol_version": _REMOTE_PROTOCOL, + "operation": "proxy", + "capability": EXTERNAL_CHECKER_CAPABILITY_KEY, + }, + separators=(",", ":"), + ).encode() + await self._send_frame(writer, control) + return reader, writer + async def execute_pre( self, lease: SelectedPreSubmitLeaseFacts, grant: ExternalPreSubmitSourceGrant, ) -> SelectedPreSubmitInvocationResult: @@ -110,7 +176,7 @@ async def execute_pre( raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded") deadline = asyncio.get_running_loop().time() + timeout async with asyncio.timeout_at(deadline): - reader, writer = await asyncio.open_unix_connection(self._socket_path) + reader, writer = await self._proxy_connection() try: writer.write(struct.pack(">I", len(payload)) + payload) await writer.drain() @@ -223,10 +289,46 @@ async def _exchange(self, request, grant, *, model_grant, locate): if self._timeout_seconds < required_timeout: raise ExternalServiceUnavailableError(self._identity) async with asyncio.timeout(self._timeout_seconds): - reader, writer = await asyncio.open_unix_connection(self._socket_path) + reader, writer = await self._open() try: - writer.write(struct.pack(">I", len(payload)) + payload) - await writer.drain() + manifest = grant.source.manifest + files = grant.source.files + if ( + type(manifest) is not bytes + or not 0 < len(manifest) <= 2 * 1024 * 1024 + or len(files) > 4_000 + ): + raise ValueError("external material export is invalid") + total_bytes = sum(item.byte_count for item in files) + if total_bytes > 1024 * 1024 * 1024: + raise ValueError("external material export is too large") + control = json.dumps( + { + "protocol_version": _REMOTE_PROTOCOL, + "operation": "execute", + "capability": EXTERNAL_CHECKER_CAPABILITY_KEY, + "service_request": json.loads(payload), + "manifest_byte_count": len(manifest), + "file_count": len(files), + "total_byte_count": total_bytes, + }, + ensure_ascii=False, + allow_nan=False, + separators=(",", ":"), + ).encode() + await self._send_frame(writer, control) + await self._send_frame(writer, manifest) + for item in files: + stream = grant.source.open_file(item) + try: + async for chunk in stream: + if type(chunk) is not bytes or not 0 < len(chunk) <= 64 * 1024: + raise ValueError("external material export chunk is invalid") + await self._send_frame(writer, chunk) + finally: + await await_cancellation_resistant(stream.aclose()) + writer.write(struct.pack(">I", 0)) + await writer.drain() size = struct.unpack(">I", await reader.readexactly(4))[0] if size == 0 or size > _MAXIMUM_RESPONSE_BYTES: raise ExternalServiceProtocolError(self._identity) @@ -289,7 +391,7 @@ async def health(self) -> ExternalCheckerServiceHealth: ).encode("utf-8") try: async with asyncio.timeout(self._timeout_seconds): - reader, writer = await asyncio.open_unix_connection(self._socket_path) + reader, writer = await self._proxy_connection() try: writer.write(struct.pack(">I", len(payload)) + payload) await writer.drain() @@ -344,5 +446,5 @@ async def health(self) -> ExternalCheckerServiceHealth: __all__ = ( "EXTERNAL_CHECKER_CAPABILITY_KEY", "EXTERNAL_CHECKER_PROVIDER_KEY", - "UnixSocketExternalCheckerAdapter", + "RemoteTlsExternalCheckerAdapter", ) diff --git a/backend/app/adapters/checkers/model_runtime.py b/backend/app/adapters/checkers/model_runtime.py index 60a208fed..2cf86a836 100644 --- a/backend/app/adapters/checkers/model_runtime.py +++ b/backend/app/adapters/checkers/model_runtime.py @@ -30,6 +30,7 @@ trial_evidence_reservations, ) from app.adapters.checkers.model_proxy_transport import ModelProxyTransport +from app.adapters.checkers.remote_model_bridge import RemoteModelProxyBridge from app.adapters.checkers.trial_proxy import CheckerTrialProxy from app.modules.checkers.api.trial_profiles import load_trial_authority_manifest from app.adapters.model_usage import setup_model_usage_service @@ -160,7 +161,18 @@ def reservations(session, request): trial_handler=trial_proxy.handle if trial_proxy is not None else None, shutdown_timeout_seconds=7200.0, ): - yield + if settings.external_runner_host is None: + raise ValueError("model proxy requires the configured external runner") + async with RemoteModelProxyBridge( + host=settings.external_runner_host, + port=settings.external_runner_port, + server_name=settings.external_runner_server_name, + ca_path=settings.external_runner_ca_path, + certificate_path=settings.external_runner_certificate_path, + private_key_path=settings.external_runner_private_key_path, + socket_path=settings.checker_model_proxy_socket, + ): + yield finally: if manager is not None: manager.close() diff --git a/backend/app/adapters/checkers/remote_model_bridge.py b/backend/app/adapters/checkers/remote_model_bridge.py new file mode 100644 index 000000000..773c97d5b --- /dev/null +++ b/backend/app/adapters/checkers/remote_model_bridge.py @@ -0,0 +1,161 @@ +"""Outbound authenticated bridge for runner-local checker model callbacks.""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +import ssl +import struct + + +_PROTOCOL = "workstream.remote_runner.v1" +_MAXIMUM_FRAME_BYTES = 64 * 1024 * 1024 + + +async def _read_frame(reader: asyncio.StreamReader) -> bytes: + size = struct.unpack(">I", await reader.readexactly(4))[0] + if size == 0 or size > _MAXIMUM_FRAME_BYTES: + raise ValueError("remote model bridge frame is invalid") + return await reader.readexactly(size) + + +async def _write_frame(writer: asyncio.StreamWriter, body: bytes) -> None: + if not body or len(body) > _MAXIMUM_FRAME_BYTES: + raise ValueError("remote model bridge frame is invalid") + writer.write(struct.pack(">I", len(body)) + body) + await writer.drain() + + +class RemoteModelProxyBridge: + """Reconnect one app-owned Unix model proxy to the dedicated runner edge.""" + + def __init__( + self, + *, + host: str, + port: int, + server_name: str, + ca_path: Path, + certificate_path: Path, + private_key_path: Path, + socket_path: Path, + ) -> None: + self._host, self._port, self._server_name = host, port, server_name + self._ca_path = ca_path + self._certificate_path = certificate_path + self._private_key_path = private_key_path + self._socket_path = socket_path + self._stopping = asyncio.Event() + self._task: asyncio.Task[None] | None = None + + def _tls_context(self) -> ssl.SSLContext: + context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=str(self._ca_path)) + context.minimum_version = ssl.TLSVersion.TLSv1_3 + context.check_hostname = True + context.load_cert_chain( + certfile=str(self._certificate_path), keyfile=str(self._private_key_path) + ) + return context + + async def start(self) -> None: + if self._task is not None: + raise RuntimeError("remote model bridge is already started") + self._task = asyncio.create_task(self._run(), name="remote-model-proxy-bridge") + + async def close(self) -> None: + self._stopping.set() + if self._task is not None: + self._task.cancel() + await asyncio.gather(self._task, return_exceptions=True) + self._task = None + + async def __aenter__(self) -> "RemoteModelProxyBridge": + await self.start() + return self + + async def __aexit__(self, *_: object) -> None: + await self.close() + + async def _run(self) -> None: + delay = 0.25 + while not self._stopping.is_set(): + try: + await self._session() + delay = 0.25 + except asyncio.CancelledError: + raise + except (OSError, ssl.SSLError, asyncio.IncompleteReadError, ValueError): + try: + await asyncio.wait_for(self._stopping.wait(), timeout=delay) + except TimeoutError: + pass + delay = min(5.0, delay * 2) + + async def _session(self) -> None: + reader, writer = await asyncio.open_connection( + self._host, + self._port, + ssl=self._tls_context(), + server_hostname=self._server_name, + ) + try: + control = json.dumps( + { + "protocol_version": _PROTOCOL, + "operation": "model_bridge", + "capability": "external_checker_execution", + }, + separators=(",", ":"), + ).encode() + await _write_frame(writer, control) + acknowledgement = json.loads(await _read_frame(reader)) + if acknowledgement != { + "protocol_version": _PROTOCOL, + "operation": "model_bridge", + "status": "ready", + }: + raise ValueError("remote model bridge acknowledgement is invalid") + while not self._stopping.is_set(): + header = json.loads(await _read_frame(reader)) + if ( + type(header) is not dict + or set(header) != {"protocol_version", "operation", "channel_id"} + or header.get("protocol_version") != _PROTOCOL + or header.get("operation") != "model_request" + or type(header.get("channel_id")) is not str + ): + raise ValueError("remote model request header is invalid") + request = await _read_frame(reader) + response = await self._exchange_local(request) + response_header = json.dumps( + { + "protocol_version": _PROTOCOL, + "operation": "model_response", + "channel_id": header["channel_id"], + }, + separators=(",", ":"), + ).encode() + await _write_frame(writer, response_header) + await _write_frame(writer, response) + finally: + writer.close() + try: + await writer.wait_closed() + except (OSError, ssl.SSLError): + pass + + async def _exchange_local(self, request: bytes) -> bytes: + reader, writer = await asyncio.open_unix_connection(self._socket_path) + try: + await _write_frame(writer, request) + return await _read_frame(reader) + finally: + writer.close() + try: + await writer.wait_closed() + except OSError: + pass + + +__all__ = ("RemoteModelProxyBridge",) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index b0f757a8d..90c70174d 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -143,7 +143,7 @@ class Settings(BaseSettings): ) guide_document_parser_socket: Path = Path("/var/lib/workstream/guide-runtime/guide.sock") celery_broker_url: str | None = None - hosted_profile: Literal["single-host", "app"] = "single-host" + hosted_profile: Literal["app"] = "app" celery_result_backend_url: str | None = None celery_task_always_eager: bool = False observability_log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO" @@ -254,15 +254,18 @@ class Settings(BaseSettings): gt=0, le=86_400, ) - artifact_intake_service_socket: Path | None = None # Required source-intake envelopes and runtime/capacity profile. No old # preparation timers or unmeasured deployment defaults are inherited. submission_execution_profile: dict[str, object] | None = None submission_source_cleanup_profile: dict[str, object] | None = None artifact_intake_image_digest: str | None = None artifact_intake_config_digest: str | None = None - external_checker_service_socket: Path | None = None - external_checker_material_root: Path | None = None + external_runner_host: str | None = None + external_runner_port: int | None = Field(default=None, ge=1, le=65_535) + external_runner_server_name: str | None = None + external_runner_ca_path: Path | None = None + external_runner_certificate_path: Path | None = None + external_runner_private_key_path: Path | None = None checker_model_proxy_socket: Path | None = None checker_trial_authority_manifest_path: Path | None = None checker_trial_authority_manifest_digest: str | None = Field( @@ -699,32 +702,35 @@ def validate_artifact_storage(self) -> Settings: "artifact scratch and durable local storage roots must be separate" ) external_values = ( - self.external_checker_service_socket, - self.external_checker_material_root, + self.external_runner_host, + self.external_runner_port, + self.external_runner_server_name, + self.external_runner_ca_path, + self.external_runner_certificate_path, + self.external_runner_private_key_path, ) - if self.hosted_profile == "app" and any(value is not None for value in ( - *external_values, - self.artifact_intake_service_socket, + if any(value is not None for value in external_values): + if any(value is None for value in external_values): + raise ValueError("external runner TLS settings must be complete") + assert self.external_runner_host is not None + assert self.external_runner_server_name is not None + if not self.external_runner_host or len(self.external_runner_host) > 255: + raise ValueError("external runner host is invalid") + if not self.external_runner_server_name or len(self.external_runner_server_name) > 255: + raise ValueError("external runner server name is invalid") + for path in external_values[3:]: + assert isinstance(path, Path) + if not path.is_absolute(): + raise ValueError("external runner TLS paths must be absolute") + if any(value is not None for value in ( self.artifact_intake_image_digest, self.artifact_intake_config_digest, - self.checker_trial_authority_manifest_path, - self.checker_trial_authority_manifest_digest, + )) and any(value is None for value in ( + self.artifact_intake_image_digest, + self.artifact_intake_config_digest, + *external_values, )): - raise ValueError("the hosted app profile cannot configure native checker execution") - if any(value is not None for value in external_values): - if any(value is None for value in external_values): - raise ValueError("external checker service settings must be complete") - socket, material = external_values - assert socket is not None and material is not None - if not socket.is_absolute() or not material.is_absolute(): - raise ValueError("external checker service paths must be absolute") - if self.artifact_scratch_root is None or ( - material.resolve(strict=False) - != self.artifact_scratch_root.resolve(strict=False) - ): - raise ValueError( - "external checker material root must equal the artifact scratch root" - ) + raise ValueError("trusted intake requires the configured external runner") trial_path, trial_digest = ( self.checker_trial_authority_manifest_path, self.checker_trial_authority_manifest_digest, @@ -738,6 +744,8 @@ def validate_artifact_storage(self) -> Settings: if self.checker_model_proxy_socket is not None: if not self.checker_model_proxy_socket.is_absolute(): raise ValueError("checker model proxy socket must be absolute") + if any(value is None for value in external_values): + raise ValueError("checker model proxy requires the external runner") if self.artifact_store_backend == "disabled": raise ValueError("checker model proxy requires enabled artifact storage") if self.artifact_store_backend == "disabled": diff --git a/backend/app/interfaces/external_checker_execution.py b/backend/app/interfaces/external_checker_execution.py index 29a34cc37..b186f45a3 100644 --- a/backend/app/interfaces/external_checker_execution.py +++ b/backend/app/interfaces/external_checker_execution.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import dataclass, field -from collections.abc import AsyncGenerator +from collections.abc import AsyncGenerator, AsyncIterator import re from typing import Literal, Protocol @@ -35,6 +35,7 @@ class ExternalCheckerMaterialGrant: grant_id: Identifier binding_digest: Sha256 + source: ExternalCheckerMaterialSource = field(repr=False, compare=False) def __post_init__(self) -> None: """Reject path-like identifiers and malformed binding digests.""" @@ -45,6 +46,25 @@ def __post_init__(self) -> None: raise ValueError("external checker material grant is invalid") +class ExternalCheckerMaterialFile(Protocol): + """One immutable file descriptor supplied by ART without a host path.""" + + relative_path: str + byte_count: int + sha256: Sha256 + executable: bool + + +class ExternalCheckerMaterialSource(Protocol): + """Callback-scoped export of one manifest-bound material grant.""" + + manifest: bytes + files: tuple[ExternalCheckerMaterialFile, ...] + + def open_file(self, item: ExternalCheckerMaterialFile) -> AsyncIterator[bytes]: + """Yield the exact sealed member in bounded nonempty chunks.""" + + @dataclass(frozen=True, slots=True) class ExternalCheckerModelGrant: """Opaque invocation relay selector, never sufficient authority to spend.""" @@ -204,6 +224,7 @@ async def health(self) -> ExternalCheckerServiceHealth: "ExternalCheckerExecutionResponse", "ExternalCheckerIsolationReceipt", "ExternalCheckerMaterialGrant", + "ExternalCheckerMaterialSource", "ExternalCheckerModelGrant", "ExternalCheckerServiceHealth", ) diff --git a/backend/app/modules/artifacts/post_submit_materialization.py b/backend/app/modules/artifacts/post_submit_materialization.py index edadc4278..5b2b5c3d0 100644 --- a/backend/app/modules/artifacts/post_submit_materialization.py +++ b/backend/app/modules/artifacts/post_submit_materialization.py @@ -327,7 +327,9 @@ def external_checker_grant(self, request): ) as grant: self._issued_requests[checked.request_digest] = checked yield ExternalCheckerMaterialGrant( - grant_id=grant.grant_id, binding_digest=grant.binding_digest + grant_id=grant.grant_id, + binding_digest=grant.binding_digest, + source=grant, ) def __reduce__(self): diff --git a/backend/app/modules/artifacts/preparation.py b/backend/app/modules/artifacts/preparation.py index 0392b8a3e..00cb0beb4 100644 --- a/backend/app/modules/artifacts/preparation.py +++ b/backend/app/modules/artifacts/preparation.py @@ -433,12 +433,95 @@ def __post_init__(self) -> None: object.__setattr__(self, "_identity_json", identity) +@dataclass(frozen=True, slots=True) +class ExternalMaterialExportFile: + """One sealed regular file in a callback-scoped material export.""" + + relative_path: str + byte_count: int + sha256: str + executable: bool + + @dataclass(frozen=True, slots=True) class ExternalMaterialGrant: - """Opaque grant identity safe to send across the checker service boundary.""" + """Opaque grant plus a process-local, bounded export source.""" grant_id: str binding_digest: str + manifest: bytes = field(repr=False) + files: tuple[ExternalMaterialExportFile, ...] = field(repr=False) + _root: Path = field(repr=False, compare=False) + + def open_file(self, item: ExternalMaterialExportFile) -> AsyncIterator[bytes]: + """Read one already-sealed member without exposing its host path.""" + if type(item) is not ExternalMaterialExportFile or item not in self.files: + raise ArtifactScratchIntegrityError("external material export file is invalid") + + async def stream() -> AsyncIterator[bytes]: + parts = Path(item.relative_path).parts + if ( + not parts + or Path(item.relative_path).is_absolute() + or any(part in {"", ".", ".."} for part in parts) + ): + raise ArtifactScratchIntegrityError("external material export path is invalid") + descriptors: list[int] = [] + try: + descriptor = os.open( + self._root, + os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0), + ) + descriptors.append(descriptor) + for part in parts[:-1]: + descriptor = os.open( + part, + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0), + dir_fd=descriptor, + ) + descriptors.append(descriptor) + file_descriptor = os.open( + parts[-1], + os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0), + dir_fd=descriptor, + ) + descriptors.append(file_descriptor) + metadata = os.fstat(file_descriptor) + expected_mode = 0o500 if item.executable else 0o400 + if ( + not stat_module.S_ISREG(metadata.st_mode) + or metadata.st_mode & 0o777 != expected_mode + or metadata.st_size != item.byte_count + ): + raise ArtifactScratchIntegrityError( + "external material export identity differs" + ) + digest, count = hashlib.sha256(), 0 + while True: + chunk = await asyncio.to_thread(os.read, file_descriptor, 64 * 1024) + if not chunk: + break + count += len(chunk) + digest.update(chunk) + yield chunk + if ( + count != item.byte_count + or "sha256:" + digest.hexdigest() != item.sha256 + ): + raise ArtifactScratchIntegrityError( + "external material export content differs" + ) + except OSError as exc: + raise ArtifactScratchIntegrityError( + "external material export unavailable" + ) from exc + finally: + for descriptor in reversed(descriptors): + os.close(descriptor) + + return stream() @dataclass(frozen=True, slots=True) @@ -997,7 +1080,22 @@ def _publish_external_grant_sync( os.close(workspace_fd) finally: os.close(root_fd) - return ExternalMaterialGrant(grant_id=grant_id, binding_digest=binding_digest) + export_files = tuple( + ExternalMaterialExportFile( + relative_path=f"workspace/{item.normalized_path}", + byte_count=item.byte_count, + sha256=item.sha256, + executable=item.executable, + ) + for item in request.files + ) + return ExternalMaterialGrant( + grant_id=grant_id, + binding_digest=binding_digest, + manifest=payload, + files=export_files, + _root=self._root / "workspaces" / grant_id, + ) def _publish_external_post_grant_sync( self, @@ -1110,7 +1208,23 @@ def _publish_external_post_grant_sync( finally: os.close(descriptor) os.fsync(root_fd) - return ExternalMaterialGrant(grant_id=grant_id, binding_digest=binding_digest) + export_files = tuple( + ExternalMaterialExportFile( + relative_path=f"materials/{item.role}/{entry.normalized_path}", + byte_count=entry.byte_count, + sha256=entry.sha256, + executable=entry.executable, + ) + for item in request.materials + for entry in item.files + ) + return ExternalMaterialGrant( + grant_id=grant_id, + binding_digest=binding_digest, + manifest=payload, + files=export_files, + _root=self._root / "workspaces" / grant_id, + ) except (OSError, ValueError) as exc: raise ArtifactScratchIntegrityError( "external POST material publication failed" diff --git a/backend/app/modules/artifacts/submission_materialization.py b/backend/app/modules/artifacts/submission_materialization.py index b4bfe8563..d0d588d0d 100644 --- a/backend/app/modules/artifacts/submission_materialization.py +++ b/backend/app/modules/artifacts/submission_materialization.py @@ -209,6 +209,7 @@ def issue( yield ExternalCheckerMaterialGrant( grant_id=grant.grant_id, binding_digest=grant.binding_digest, + source=grant, ) diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py new file mode 100644 index 000000000..2f90f9306 --- /dev/null +++ b/backend/tests/checkers/external/test_remote_node.py @@ -0,0 +1,299 @@ +"""Dedicated runner authentication, material binding and cleanup proofs.""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timedelta, timezone +import hashlib +import importlib.util +import json +from pathlib import Path +import ssl +import struct + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +import pytest + +from app.adapters.checkers.remote_model_bridge import RemoteModelProxyBridge + + +_SPEC = importlib.util.spec_from_file_location( + "workstream_remote_node", + Path(__file__).resolve().parents[4] / "external_checkers/remote_node.py", +) +assert _SPEC is not None and _SPEC.loader is not None +_REMOTE = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(_REMOTE) + + +def _certificate_files(tmp_path: Path) -> dict[str, Path]: + now = datetime.now(timezone.utc) + ca_key = rsa.generate_private_key(public_exponent=65_537, key_size=2048) + ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "runner-test-ca")]) + ca = ( + x509.CertificateBuilder() + .subject_name(ca_name) + .issuer_name(ca_name) + .public_key(ca_key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=1)) + .not_valid_after(now + timedelta(hours=1)) + .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) + .sign(ca_key, hashes.SHA256()) + ) + + def issue(name: str, usage: ExtendedKeyUsageOID) -> tuple[bytes, bytes]: + key = rsa.generate_private_key(public_exponent=65_537, key_size=2048) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]) + certificate = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(ca.subject) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=1)) + .not_valid_after(now + timedelta(hours=1)) + .add_extension(x509.SubjectAlternativeName([x509.DNSName(name)]), critical=False) + .add_extension(x509.ExtendedKeyUsage([usage]), critical=False) + .sign(ca_key, hashes.SHA256()) + ) + return ( + certificate.public_bytes(serialization.Encoding.PEM), + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ), + ) + + values = {"ca": ca.public_bytes(serialization.Encoding.PEM)} + server_certificate, server_key = issue("runner.test", ExtendedKeyUsageOID.SERVER_AUTH) + client_certificate, client_key = issue("app.test", ExtendedKeyUsageOID.CLIENT_AUTH) + values.update( + server_certificate=server_certificate, + server_key=server_key, + client_certificate=client_certificate, + client_key=client_key, + ) + paths = {} + for name, value in values.items(): + path = tmp_path / f"{name}.pem" + path.write_bytes(value) + path.chmod(0o600) + paths[name] = path + return paths + + +async def _read_frame(reader: asyncio.StreamReader) -> bytes: + size = struct.unpack(">I", await reader.readexactly(4))[0] + return await reader.readexactly(size) + + +def _frame(value: bytes) -> bytes: + return struct.pack(">I", len(value)) + value + + +@pytest.mark.asyncio +async def test_remote_post_stages_bound_material_and_removes_session(tmp_path: Path): + certificates = _certificate_files(tmp_path) + material_root = tmp_path / "materials" + material_root.mkdir(mode=0o700) + socket_path = tmp_path / "native.sock" + grant_id = "extract_" + "a" * 32 + request_digest = "sha256:" + "b" * 64 + content = b"remote material\n" + content_digest = "sha256:" + hashlib.sha256(content).hexdigest() + observed = asyncio.Event() + + async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + request = json.loads(await _read_frame(reader)) + root = material_root / "workspaces" / grant_id + path = root / "materials" / "submission_archive" / "work.txt" + assert request["request"]["request_digest"] == request_digest + assert path.read_bytes() == content + assert path.stat().st_mode & 0o777 == 0o400 + assert (root / ".external-checker-grant.json").stat().st_mode & 0o777 == 0o400 + observed.set() + writer.write(_frame(b'{"native":"ok"}')) + await writer.drain() + writer.close() + await writer.wait_closed() + + native_server = await asyncio.start_unix_server(native, socket_path) + node = _REMOTE.RemoteNode( + { + "listen_host": "127.0.0.1", + "listen_port": 1, + "client_name": "app.test", + "socket_path": str(socket_path), + "model_proxy_socket_path": str(tmp_path / "model-proxy.sock"), + "material_root": str(material_root), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), + "session_timeout_seconds": 10, + } + ) + server = await asyncio.start_server( + node.handle, "127.0.0.1", 0, ssl=node.ssl_context, + ) + port = server.sockets[0].getsockname()[1] + client_context = ssl.create_default_context( + ssl.Purpose.SERVER_AUTH, cafile=str(certificates["ca"]) + ) + client_context.minimum_version = ssl.TLSVersion.TLSv1_3 + client_context.load_cert_chain( + certificates["client_certificate"], certificates["client_key"] + ) + + material = { + "phase": "post_submit", + "role": "submission_archive", + } + manifest_body = { + "protocol_version": _REMOTE.GRANT_PROTOCOL, + "grant_id": grant_id, + "request_digest": request_digest, + "phase": "post_submit", + "identity": {}, + "evaluation_context_sha256": None, + "materials": [ + { + "material": material, + "directories": [], + "files": [ + { + "normalized_path": "work.txt", + "byte_count": len(content), + "sha256": content_digest, + "executable": False, + } + ], + } + ], + "visible_roles": ["submission_archive"], + } + canonical = json.dumps( + manifest_body, sort_keys=True, separators=(",", ":"), ensure_ascii=False + ).encode() + binding = "sha256:" + hashlib.sha256(canonical).hexdigest() + manifest = json.dumps( + {**manifest_body, "binding_digest": binding}, + sort_keys=True, + separators=(",", ":"), + ).encode() + service_request = { + "protocol_version": "external_checker_service.v1", + "operation": "execute", + "request": {"request_digest": request_digest}, + "grant": {"grant_id": grant_id, "binding_digest": binding}, + "model_grant": None, + } + control = json.dumps( + { + "protocol_version": _REMOTE.PROTOCOL, + "operation": "execute", + "capability": _REMOTE.CHECKER_CAPABILITY, + "service_request": service_request, + "manifest_byte_count": len(manifest), + "file_count": 1, + "total_byte_count": len(content), + }, + separators=(",", ":"), + ).encode() + + try: + reader, writer = await asyncio.open_connection( + "127.0.0.1", port, ssl=client_context, server_hostname="runner.test" + ) + writer.write(_frame(control) + _frame(manifest) + _frame(content) + struct.pack(">I", 0)) + await writer.drain() + assert await _read_frame(reader) == b'{"native":"ok"}' + await asyncio.wait_for(observed.wait(), 1) + writer.close() + await writer.wait_closed() + for _ in range(100): + if not list((material_root / "workspaces").iterdir()): + break + await asyncio.sleep(0.01) + assert list((material_root / "workspaces").iterdir()) == [] + finally: + server.close() + native_server.close() + await server.wait_closed() + await native_server.wait_closed() + + +@pytest.mark.asyncio +async def test_model_callback_uses_outbound_authenticated_bridge(tmp_path: Path): + certificates = _certificate_files(tmp_path) + material_root = tmp_path / "materials" + material_root.mkdir(mode=0o700) + native_path = tmp_path / "native.sock" + app_proxy_path = tmp_path / "app-model.sock" + runner_proxy_path = tmp_path / "runner-model.sock" + + async def app_proxy(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + request = await _read_frame(reader) + writer.write(_frame(b"app:" + request)) + await writer.drain() + writer.close() + await writer.wait_closed() + + native_server = await asyncio.start_unix_server( + lambda _reader, writer: writer.close(), native_path + ) + app_server = await asyncio.start_unix_server(app_proxy, app_proxy_path) + node = _REMOTE.RemoteNode( + { + "listen_host": "127.0.0.1", + "listen_port": 1, + "client_name": "app.test", + "socket_path": str(native_path), + "model_proxy_socket_path": str(runner_proxy_path), + "material_root": str(material_root), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), + "session_timeout_seconds": 10, + } + ) + await node.start_model_proxy() + server = await asyncio.start_server( + node.handle, "127.0.0.1", 0, ssl=node.ssl_context, + ) + port = server.sockets[0].getsockname()[1] + bridge = RemoteModelProxyBridge( + host="127.0.0.1", + port=port, + server_name="runner.test", + ca_path=certificates["ca"], + certificate_path=certificates["client_certificate"], + private_key_path=certificates["client_key"], + socket_path=app_proxy_path, + ) + try: + await bridge.start() + for _ in range(100): + if node._model_bridge is not None: + break + await asyncio.sleep(0.01) + assert node._model_bridge is not None + reader, writer = await asyncio.open_unix_connection(runner_proxy_path) + writer.write(_frame(b"bound model call")) + await writer.drain() + assert await _read_frame(reader) == b"app:bound model call" + writer.close() + await writer.wait_closed() + finally: + await bridge.close() + server.close() + native_server.close() + app_server.close() + await server.wait_closed() + await native_server.wait_closed() + await app_server.wait_closed() + await node.close() diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py index ec29d6a7a..324771c66 100644 --- a/backend/tests/checkers/external/test_runtime.py +++ b/backend/tests/checkers/external/test_runtime.py @@ -22,23 +22,20 @@ from app.adapters.checkers import ( configured_external_checker_execution, - external_checker_execution_factory, ) from app.adapters.checkers.external_service import ( EXTERNAL_CHECKER_CAPABILITY_KEY, EXTERNAL_CHECKER_PROVIDER_KEY, - UnixSocketExternalCheckerAdapter, + RemoteTlsExternalCheckerAdapter, ) from app.core.config import Settings from app.core.hashing import canonical_json_hash from app.interfaces.external_checker_execution import ( ExternalCheckerIsolationReceipt, - ExternalCheckerMaterialGrant, ExternalCheckerServiceHealth, ) from workstream_external_services import ( ExternalServiceUnavailableError, - UnknownExternalServiceProviderError, ) from app.modules.artifacts.preparation import ( HARD_MAXIMUM_ARTIFACT_BYTES, @@ -73,7 +70,6 @@ PreSubmitExternalCheckerMaterial, external_checker_json_hash, make_external_checker_execution_request, - make_external_checker_execution_result, ) from tests.checkers.external.support import SHA, execution_identity, registry_entry @@ -133,23 +129,19 @@ def test_shared_rust_fixtures_preserve_python_contract_and_derived_digests(): ) -def test_external_service_settings_share_the_art_scratch_root(tmp_path: Path): - scratch = tmp_path / "scratch" +def test_external_service_settings_require_one_complete_remote_identity(tmp_path: Path): settings = Settings( - artifact_scratch_root=scratch, - external_checker_service_socket=tmp_path / "service" / "checker.sock", - external_checker_material_root=scratch, + external_runner_host="runner.internal", + external_runner_port=9443, + external_runner_server_name="runner.internal", + external_runner_ca_path=tmp_path / "ca.crt", + external_runner_certificate_path=tmp_path / "app.crt", + external_runner_private_key_path=tmp_path / "app.key", ) - assert settings.external_checker_material_root == scratch + assert settings.external_runner_host == "runner.internal" assert settings.external_checker_service_timeout_seconds == 3660.0 with pytest.raises(ValidationError, match="must be complete"): - Settings(external_checker_service_socket=tmp_path / "checker.sock") - with pytest.raises(ValidationError, match="must equal"): - Settings( - artifact_scratch_root=scratch, - external_checker_service_socket=tmp_path / "service" / "checker.sock", - external_checker_material_root=tmp_path / "other", - ) + Settings(external_runner_host="runner.internal") with pytest.raises(ValueError, match="isolation receipt"): ExternalCheckerIsolationReceipt( repository="--network/host", @@ -240,155 +232,6 @@ def test_receipts_cannot_misrepresent_an_engine_as_another_isolation(runtime, is ) -@pytest.mark.parametrize( - "runtime,isolation_mode", - [("runsc", "gvisor"), ("runc", "docker-dev"), ("smolvm", "smol-microvm")], -) -@pytest.mark.asyncio -async def test_unix_adapter_revalidates_exact_result_and_factory_is_closed( - tmp_path: Path, - runtime: str, - isolation_mode: str, -): - request = _request() - result = make_external_checker_execution_result( - request_digest=request.request_digest, - registry_entry_id=request.registry.registry_entry_id, - registry_entry_digest=request.registry.entry_digest, - phase="pre_submit", - outcome="completed", - verdict="passed", - findings=(), - infrastructure_failure_code=None, - ) - socket = tmp_path / "checker.sock" - - async def handle(reader, writer): - size = struct.unpack(">I", await reader.readexactly(4))[0] - received = json.loads(await reader.readexactly(size)) - if received["operation"] == "health": - body = json.dumps( - { - "protocol_version": "external_checker_service.v1", - "operation": "health", - "status": "ready", - "operating_system": "linux", - "architecture": "amd64", - "runtime": runtime, - "isolation_mode": isolation_mode, - "cached_platform_manifests": 1, - "sandbox_uid": 65532, - "sandbox_gid": 65532, - }, - separators=(",", ":"), - ).encode() - writer.write(struct.pack(">I", len(body)) + body) - await writer.drain() - writer.close() - return - assert received["request"]["request_digest"] == request.request_digest - assert received["model_grant"] is None - body = json.dumps( - { - "protocol_version": "external_checker_service.v1", - "result": result.model_dump(mode="json"), - "isolation": { - "repository": "registry.example/workstream/checker", - "platform_manifest_digest": request.registry.image_digest, - "platform_manifest_media_type": ("application/vnd.oci.image.manifest.v1+json"), - "platform_manifest_byte_count": 1367, - "operating_system": "linux", - "architecture": "amd64", - "config_image_id": "sha256:" + "b" * 64, - "runtime": runtime, - "isolation_mode": isolation_mode, - "sandbox_uid": 65532, - "sandbox_gid": 65532, - }, - }, - separators=(",", ":"), - ).encode() - writer.write(struct.pack(">I", len(body)) + body) - await writer.drain() - writer.close() - - server = await asyncio.start_unix_server(handle, socket) - try: - factory = external_checker_execution_factory(socket_path=socket, timeout_seconds=90.0) - adapter = factory.create("unix_socket") - health = await adapter.health() - assert health.runtime == runtime - assert health.isolation_mode == isolation_mode - assert health.cached_platform_manifests == 1 - response = await adapter.execute( - request, - ExternalCheckerMaterialGrant( - grant_id="extract_" + "a" * 32, - binding_digest="sha256:" + "c" * 64, - ), - ) - assert response.result == result - assert response.isolation is not None - assert response.isolation.runtime == runtime - assert response.isolation.isolation_mode == isolation_mode - with pytest.raises(UnknownExternalServiceProviderError): - factory.create("docker") - short = external_checker_execution_factory(socket_path=socket, timeout_seconds=2.0).create( - "unix_socket" - ) - with pytest.raises(ExternalServiceUnavailableError): - await short.execute( - request, - ExternalCheckerMaterialGrant( - grant_id="extract_" + "a" * 32, - binding_digest="sha256:" + "c" * 64, - ), - ) - finally: - server.close() - await server.wait_closed() - - -@pytest.mark.asyncio -async def test_unix_adapter_cancellation_closes_the_service_connection(tmp_path: Path): - socket = tmp_path / "checker.sock" - received = asyncio.Event() - disconnected = asyncio.Event() - - async def handle(reader, writer): - try: - size = struct.unpack(">I", await reader.readexactly(4))[0] - await reader.readexactly(size) - received.set() - assert await reader.read() == b"" - finally: - disconnected.set() - writer.close() - - server = await asyncio.start_unix_server(handle, socket) - try: - adapter = external_checker_execution_factory( - socket_path=socket, timeout_seconds=90.0 - ).create("unix_socket") - task = asyncio.create_task( - adapter.execute( - _request(), - ExternalCheckerMaterialGrant( - grant_id="extract_" + "a" * 32, - binding_digest="sha256:" + "c" * 64, - ), - ) - ) - await asyncio.wait_for(received.wait(), 2) - task.cancel() - with pytest.raises(asyncio.CancelledError): - await task - await asyncio.wait_for(disconnected.wait(), 2) - finally: - server.close() - await server.wait_closed() - - @pytest.mark.asyncio async def test_prepared_zip_issues_request_bound_grant_only_inside_callback(tmp_path: Path): archive = io.BytesIO() @@ -1099,22 +942,22 @@ async def test_public_trace_preserves_execution_arguments(monkeypatch, tmp_path, from types import SimpleNamespace from unittest.mock import AsyncMock - from app.adapters.artifacts.trusted_intake import UnixSocketTrustedIntakeAdapter - from app.adapters.checkers.external_service import UnixSocketExternalCheckerAdapter + from app.adapters.artifacts.trusted_intake import RemoteTlsTrustedIntakeAdapter + from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter trace = tmp_path / "trace.jsonl" monkeypatch.setenv("WORKSTREAM_PROBE_INTAKE_TRACE", str(trace)) - original_prepare = UnixSocketTrustedIntakeAdapter.prepare - monkeypatch.setattr(UnixSocketTrustedIntakeAdapter, "prepare", original_prepare) + original_prepare = RemoteTlsTrustedIntakeAdapter.prepare + monkeypatch.setattr(RemoteTlsTrustedIntakeAdapter, "prepare", original_prepare) expected = object() execute = AsyncMock(return_value=expected) - monkeypatch.setattr(UnixSocketExternalCheckerAdapter, "execute", execute) + monkeypatch.setattr(RemoteTlsExternalCheckerAdapter, "execute", execute) probe = Path(__file__).resolve().parents[4] / "experiments/pilot04_external_checker_runtime/public_intake_observer.py" runpy.run_path(str(probe)) adapter, grant = object(), object() model_grant = object() if with_model_grant else None request = SimpleNamespace(request_digest="sha256:" + "a" * 64) - actual = await UnixSocketExternalCheckerAdapter.execute( + actual = await RemoteTlsExternalCheckerAdapter.execute( adapter, request, grant, model_grant=model_grant, ) assert actual is expected @@ -1124,21 +967,26 @@ async def test_public_trace_preserves_execution_arguments(monkeypatch, tmp_path, ] -def _pre_transport_processor(lease, socket, changed): +def _pre_transport_processor(lease, endpoint, changed): """Exercise direct transport and both real production composition wrappers.""" from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor - adapter = UnixSocketExternalCheckerAdapter( - socket_path=socket, timeout_seconds=0.2 if changed == "slow_decode" else 5.0, - source_contracts=selected_pre_submit_source_contracts()) + adapter = RemoteTlsExternalCheckerAdapter( + **endpoint, + timeout_seconds=0.2 if changed == "slow_decode" else 5.0, + source_contracts=selected_pre_submit_source_contracts(), + ) if changed in {"configured", "model_wrapper"}: from app.adapters.checkers import ( selected_pre_submit_checker_execution, configured_post_submit_external_execution, SelectedPreSubmitCheckerExecutionAdapter, ) settings = Settings( - external_checker_service_socket=socket, - external_checker_material_root=socket.parent / "scratch", - artifact_scratch_root=socket.parent / "scratch", + external_runner_host=endpoint["host"], + external_runner_port=endpoint["port"], + external_runner_server_name=endpoint["server_name"], + external_runner_ca_path=endpoint["ca_path"], + external_runner_certificate_path=endpoint["certificate_path"], + external_runner_private_key_path=endpoint["private_key_path"], ) if changed == "configured": processor = selected_pre_submit_checker_execution(settings=settings).build(lease) @@ -1240,7 +1088,26 @@ def delayed_decode(cls, value, *, source_contracts): grant = Grant() socket = tmp_path / "pre.sock" server = await asyncio.start_unix_server(handle, socket) - processor = _pre_transport_processor(lease, socket, changed) + from tests.checkers.external.test_remote_node import _certificate_files, _REMOTE + certificates = _certificate_files(tmp_path) + materials = tmp_path / "runner-materials" + materials.mkdir(mode=0o700) + node = _REMOTE.RemoteNode({ + "listen_host": "127.0.0.1", "listen_port": 1, "client_name": "app.test", + "socket_path": str(socket), "material_root": str(materials), + "model_proxy_socket_path": str(tmp_path / "runner-model.sock"), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), "session_timeout_seconds": 10, + }) + remote = await asyncio.start_server(node.handle, "127.0.0.1", 0, ssl=node.ssl_context) + endpoint = { + "host": "127.0.0.1", "port": remote.sockets[0].getsockname()[1], + "server_name": "runner.test", "ca_path": certificates["ca"], + "certificate_path": certificates["client_certificate"], + "private_key_path": certificates["client_key"], + } + processor = _pre_transport_processor(lease, endpoint, changed) try: if changed in {None, "configured", "model_wrapper"}: assert (await processor.process(grant)).execution == execution @@ -1263,7 +1130,9 @@ def delayed_decode(cls, value, *, source_contracts): assert "grant" not in requests[0] and "prepared_generation_id" not in requests[0] finally: server.close() + remote.close() await server.wait_closed() + await remote.wait_closed() @pytest.mark.asyncio @@ -1281,7 +1150,14 @@ class NoSource: def open_source(self, **kwargs): raise AssertionError("expired execution opened source") - adapter = UnixSocketExternalCheckerAdapter(socket_path=tmp_path / "absent.sock", timeout_seconds=5.0, source_contracts=selected_pre_submit_source_contracts()) + from tests.checkers.external.test_remote_node import _certificate_files + certificates = _certificate_files(tmp_path) + adapter = RemoteTlsExternalCheckerAdapter( + host="127.0.0.1", port=1, server_name="runner.test", + ca_path=certificates["ca"], certificate_path=certificates["client_certificate"], + private_key_path=certificates["client_key"], timeout_seconds=5.0, + source_contracts=selected_pre_submit_source_contracts(), + ) with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="deadline_exceeded"): await adapter.execute_pre(lease, NoSource()) @@ -1314,7 +1190,25 @@ async def handle(reader, writer): socket = tmp_path / "cancel.sock" server = await asyncio.start_unix_server(handle, socket) - adapter = UnixSocketExternalCheckerAdapter(socket_path=socket, timeout_seconds=5.0, source_contracts=selected_pre_submit_source_contracts()) + from tests.checkers.external.test_remote_node import _certificate_files, _REMOTE + certificates = _certificate_files(tmp_path) + materials = tmp_path / "runner-materials" + materials.mkdir(mode=0o700) + node = _REMOTE.RemoteNode({ + "listen_host": "127.0.0.1", "listen_port": 1, "client_name": "app.test", + "socket_path": str(socket), "material_root": str(materials), + "model_proxy_socket_path": str(tmp_path / "runner-model.sock"), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), "session_timeout_seconds": 10, + }) + remote = await asyncio.start_server(node.handle, "127.0.0.1", 0, ssl=node.ssl_context) + adapter = RemoteTlsExternalCheckerAdapter( + host="127.0.0.1", port=remote.sockets[0].getsockname()[1], server_name="runner.test", + ca_path=certificates["ca"], certificate_path=certificates["client_certificate"], + private_key_path=certificates["client_key"], timeout_seconds=5.0, + source_contracts=selected_pre_submit_source_contracts(), + ) processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter, source_contracts=selected_pre_submit_source_contracts()) task = asyncio.create_task(processor.process(Grant())) try: @@ -1329,4 +1223,6 @@ async def handle(reader, writer): task.cancel() await asyncio.gather(task, return_exceptions=True) server.close() + remote.close() await server.wait_closed() + await remote.wait_closed() diff --git a/backend/tests/test_trusted_intake.py b/backend/tests/test_trusted_intake.py index 7088d7fec..bb2b1250a 100644 --- a/backend/tests/test_trusted_intake.py +++ b/backend/tests/test_trusted_intake.py @@ -19,7 +19,7 @@ import pytest -from app.adapters.artifacts.trusted_intake import UnixSocketTrustedIntakeAdapter +from app.adapters.artifacts.trusted_intake import RemoteTlsTrustedIntakeAdapter from app.core.identifiers import new_record_id from workstream_external_services import ExternalServiceProtocolError from app.interfaces.trusted_submission_intake import TrustedIntakePreparation @@ -48,6 +48,43 @@ _CONFIG = "sha256:" + "d" * 64 +async def _remote_adapter(tmp_path: Path, socket_path: Path): + from tests.checkers.external.test_remote_node import _certificate_files, _REMOTE + + certificates = _certificate_files(tmp_path) + materials = tmp_path / "runner-materials" + materials.mkdir(mode=0o700, exist_ok=True) + node = _REMOTE.RemoteNode({ + "listen_host": "127.0.0.1", "listen_port": 1, "client_name": "app.test", + "socket_path": str(socket_path), "material_root": str(materials), + "model_proxy_socket_path": str(tmp_path / "runner-model.sock"), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), "session_timeout_seconds": 60, + }) + server = await asyncio.start_server(node.handle, "127.0.0.1", 0, ssl=node.ssl_context) + adapter = RemoteTlsTrustedIntakeAdapter( + host="127.0.0.1", port=server.sockets[0].getsockname()[1], + server_name="runner.test", ca_path=certificates["ca"], + certificate_path=certificates["client_certificate"], + private_key_path=certificates["client_key"], image_digest=_IMAGE, + config_digest=_CONFIG, + ) + return server, adapter + + +def _unconnected_adapter(tmp_path: Path) -> RemoteTlsTrustedIntakeAdapter: + from tests.checkers.external.test_remote_node import _certificate_files + + certificates = _certificate_files(tmp_path) + return RemoteTlsTrustedIntakeAdapter( + host="127.0.0.1", port=1, server_name="runner.test", + ca_path=certificates["ca"], certificate_path=certificates["client_certificate"], + private_key_path=certificates["client_key"], image_digest=_IMAGE, + config_digest=_CONFIG, + ) + + def _frame(value: dict) -> bytes: raw = json.dumps(value).encode() return struct.pack(">I", len(raw)) + raw @@ -159,9 +196,7 @@ def node(): thread = threading.Thread(target=node) thread.start() - adapter = UnixSocketTrustedIntakeAdapter( - socket_path=path, image_digest=_IMAGE, config_digest=_CONFIG - ) + remote, adapter = await _remote_adapter(tmp_path, path) pending = asyncio.create_task(adapter.prepare(_request())) assert await asyncio.to_thread(entered.wait, 3) pending.cancel() @@ -169,6 +204,8 @@ def node(): await asyncio.wait_for(pending, 2) assert await asyncio.to_thread(disconnected.wait, 2) thread.join(2) + remote.close() + await remote.wait_closed() assert not thread.is_alive() @@ -215,12 +252,12 @@ def node(): thread = threading.Thread(target=node) thread.start() - adapter = UnixSocketTrustedIntakeAdapter( - socket_path=path, image_digest=_IMAGE, config_digest=_CONFIG - ) + remote, adapter = await _remote_adapter(tmp_path, path) with pytest.raises(ExternalServiceProtocolError): await adapter.health() thread.join(2) + remote.close() + await remote.wait_closed() assert not thread.is_alive() @@ -274,7 +311,12 @@ def consume(): @pytest.mark.parametrize( "missing", [ - "artifact_intake_service_socket", + "external_runner_host", + "external_runner_port", + "external_runner_server_name", + "external_runner_ca_path", + "external_runner_certificate_path", + "external_runner_private_key_path", "artifact_intake_image_digest", "artifact_intake_config_digest", ], @@ -285,7 +327,12 @@ def test_composition_requires_every_trusted_intake_identity(tmp_path, missing): from workstream_external_services import ExternalServiceConfigurationError settings = Settings( - artifact_intake_service_socket=tmp_path / "intake.sock", + external_runner_host="runner.internal", + external_runner_port=9443, + external_runner_server_name="runner.internal", + external_runner_ca_path=tmp_path / "ca.crt", + external_runner_certificate_path=tmp_path / "app.crt", + external_runner_private_key_path=tmp_path / "app.key", artifact_intake_image_digest=_IMAGE, artifact_intake_config_digest=_CONFIG, ) @@ -299,16 +346,18 @@ def test_intake_factory_is_independent_of_project_engine(tmp_path): adapter = trusted_submission_intake( Settings( - artifact_intake_service_socket=tmp_path / "intake.sock", + external_runner_host="runner.internal", + external_runner_port=9443, + external_runner_server_name="runner.internal", + external_runner_ca_path=tmp_path / "ca.crt", + external_runner_certificate_path=tmp_path / "app.crt", + external_runner_private_key_path=tmp_path / "app.key", artifact_intake_image_digest=_IMAGE, artifact_intake_config_digest=_CONFIG, - external_checker_service_socket=tmp_path / "project.sock", - external_checker_material_root=tmp_path / "material", - artifact_scratch_root=tmp_path / "material", ) ) assert adapter.identity.capability_key == "trusted_submission_intake" - assert adapter.identity.provider_key == "unix_socket" + assert adapter.identity.provider_key == "remote_tls" @pytest.mark.asyncio @@ -322,8 +371,7 @@ async def test_interrupted_export_disconnects_before_cleanup_can_read_raw_bytes( inspection = SubmissionArchiveInspector(SubmissionArchiveLimits()).inspect( BytesIO(_archive(content=content))) entry = inspection.entries[0] - adapter = UnixSocketTrustedIntakeAdapter( - socket_path=tmp_path / "unused.sock", image_digest=_IMAGE, config_digest=_CONFIG) + adapter = _unconnected_adapter(tmp_path) session = _Session(adapter, time.monotonic() + 60, _request()) session._socket.close() session._socket, peer = socket.socketpair() @@ -371,7 +419,7 @@ def test_inspect_size_substitution_is_rejected_before_command_or_archive_bytes(t from app.adapters.artifacts.trusted_intake import _Session data = _archive() - adapter = UnixSocketTrustedIntakeAdapter(socket_path=tmp_path / "unused.sock", image_digest=_IMAGE, config_digest=_CONFIG) + adapter = _unconnected_adapter(tmp_path) session = _Session(adapter, time.monotonic() + 10, _request(archive_byte_count=len(data))) session._state = "prepared" commands = [] diff --git a/deploy/hosted/SINGLE_HOST.md b/deploy/hosted/SINGLE_HOST.md deleted file mode 100644 index 71d6cf27e..000000000 --- a/deploy/hosted/SINGLE_HOST.md +++ /dev/null @@ -1,167 +0,0 @@ -# Clean single-host installation - -Use this path for a new deployment with PostgreSQL and Redis on the application -host. Both services are required; managed services remain an alternative to the -local overlay. This procedure does not reset an existing installation or import -demo accounts. A successful installation still needs the journey checks below. - -## Host and release preparation - -Use a dedicated Linux amd64 host with working KVM and cgroup v2 delegation for -[the native Smol node](../../external_checkers/README.md#smol-microvm-engine). -The proposed MVP target is 2 vCPU, 8 GiB RAM and 100 GiB encrypted persistent -storage. This is a qualification target, not a published capacity guarantee. -Enable nested virtualization on a supported instance type before boot and verify -`/dev/kvm` on the actual host. Start with one Celery process and one native -execution slot; preserve the node's measured memory and disk limits. - -For EC2, associate a tagged Elastic IP with the instance and retain its allocation -identity. Point the identity hostname at that address. Open SSH only to the -operator's current address, and HTTP/HTTPS for the reviewed TLS ingress. Never -publish PostgreSQL, Redis, native sockets or the Docker daemon. Do not replace -an uncertain cloud create with another create: inspect the recorded request and -resource IDs first. - -Build and publish images on a builder, not this host. Follow the -[release image instructions](README.md#prepare-source-images), recording reviewed -source, registry digests and native asset hashes. Install Docker Engine and its -Compose plugin, Python 3, and the reviewed native assets. Copy this directory -from that same reviewed checkout. Use one Compose project name for the deployment. - -Authenticate the deployment operator to the approved image registry before -Compose pulls. For private ECR, obtain a short-lived login token through that -operator's AWS identity and pass it to Docker through private stdin. Use a -root-owned private Docker configuration directory, remove its registry token -when deployment operations finish, and refresh it before later pulls. Do not put -provisioning access keys in application containers or copy them onto the host. -Normal Docker container restart uses the already installed image; an explicit -Compose reconciliation can pull and needs valid registry authentication again. - -Configure Docker's `local` logging driver with `max-size=10m` and `max-file=3` -before creating containers. Preserve any other required daemon settings; validate -the configuration before restarting Docker. Bound systemd journal retention too. -Do not keep a build daemon or development registry on the application host. -Inspect disk with `df`, `docker system df` and owner-scoped directory sizes. -Remove only explicitly identified retired images and owned temporary files after -checking running containers and recovery evidence. Never use volume pruning as -an upgrade or scratch-cleanup procedure. - -## Initialize private backing services - -Copy [release.env.example](release.env.example) to a root-owned private -`/etc/workstream/release.env` and fill the canonical release configuration. -Choose reviewed digest-qualified PostgreSQL 16 bookworm and Redis 7 bookworm -images whose service identity is `999:999`. Do not substitute an Alpine image -with a different numeric identity. - -On a fresh host: - -```sh -sudo python3 deploy/hosted/initialize-local-data.py -``` - -The command creates `/var/lib/workstream-local-data` and prints only file paths. -It refuses an existing directory, including an incomplete previous attempt. -Inspect failures explicitly; rerunning must never rotate live credentials. -The PostgreSQL bootstrap administrator password is separate from the non-superuser -Workstream database account. Redis requires its own generated password. Secrets -are private files, not values to paste into the release environment or logs. - -Set the seven printed `WORKSTREAM_*` file/directory entries in the release file, -plus `WORKSTREAM_POSTGRES_IMAGE` and `WORKSTREAM_REDIS_IMAGE`. The database and -broker URL files are consumed by the existing application secret loader. -No database or broker port is published. Keep persistent backing data outside -`WORKSTREAM_DEPLOYMENT_ROOT`, which is reserved for runtime scratch and sockets. - -Generate the API rate-limit and pagination HMAC secrets independently as 32 -random bytes encoded in canonical padded Base64, not hexadecimal. Write each -directly to its configured private secret file without printing it. Preserve -these keys on restart; do not regenerate them during deployment reconciliation. -The application validates their encoding before migration or startup. - -After completing the release environment, initialize only the backing services: - -```sh -sudo python3 deploy/hosted/compose.py --env-file /etc/workstream/release.env start local-data -``` - -This waits for their health checks without starting API, workers, identity or the -native node. Health alone does not prove application database access; the next -migration step exercises the non-superuser connection. - -## Identity, storage and application activation - -Initialize fresh accounts through the independent -[Keycloak identity provider](../identity/README.md). -Follow its offline temporary-administrator setup, authenticated HTTPS administration and -persistent database ownership. An issuer administrator is not a Workstream administrator. Bootstrap -Workstream authority using its existing supported operator command, not database -edits or saved fixture tokens. - -Configure the issuer's trusted HTTPS origin and JWKS URL. Use the existing -[Caddy deployment instructions](PUBLIC_ACCESS.md). -Public participant access requires DNS and a trusted public certificate. The -documented private access profile remains suitable only for authorized operators; -never disable TLS verification to bypass missing DNS. - -Prepare the dedicated S3 credential using the -[S3 runbook](../../docs/operations_aws_s3_credentials.md). Retain the bucket -and its immutable objects during a compute rebuild. Install the native node -configuration, pinned cache and systemd unit using the canonical node -instructions. Keep private credentials out of checker guests. - -Follow the [ordered startup commands](README.md#start-and-inspect): migrate, -qualify S3 storage access, start the model proxy when enabled, start the native -unit, run full preflight, then start the application. Start identity through its -bootstrap command before any step requiring token verification. Native readiness -is required for the single-host checker topology. - -After the API is healthy, complete admission and authorization bootstrap: - -Log in to the issuer, then call `GET /api/v1/actors/me` with that access token to -admit the initial human actor. Use the returned actor ID with -[`bootstrap_access_administrator.py`](../../backend/scripts/bootstrap_access_administrator.py), -following [bootstrap custody and result codes](../../docs/operations_authorization_service.md#bootstrap-custody), -first with `--dry-run`, then `--execute`, in the configured API image with its -normal private database secret. Provision the journey's fixed service identities -through `POST /api/v1/service-actors` under that administrator's fresh access -token. The identity list in -[`provision_local_service_actors.py`](../../backend/scripts/provision_local_service_actors.py) -is a reference; that local-development script's token issuer is not the hosted -Keycloak login path. Do not import its fixture tokens into this installation. - - -Install the [host boot recovery unit](README.md#reconcile-an-installed-host-after-reboot) -after initial activation. Set its checkout path to this installed release and -enable it for subsequent boots. It restores prerequisite readiness and reconnects -MCP to the current API namespace using cached images; it does not migrate or -initialize account/database state. Docker restart policies alone do not establish -this host-level startup order. - -## Qualification, restart and retirement - -With fresh participant logins, exercise API, CLI and the configured private MCP -service. Prove claim, malformed ZIP feedback with no Submission, valid upload, -verified S3 custody, external POST, governed acceptance, ContributionRecord, -applicable award and exact replay. Check denied identities and infrastructure -recovery separately. Record source/image/configuration identities and bounded -results without participant tokens or document contents. Keep participant passwords -in a private persistent operator credential store; temporary `/run` files are -suitable for short-lived tokens, not the only copy of account credentials. - -Measure peak memory, filesystem use and scratch cleanup during this actual -journey. Confirm the database role is not superuser and cannot create roles or -databases. Verify Redis rejects unauthenticated access. Drain through the hosted -wrapper: backing services stop after their consumers. Restart backing services -first, then repeat the canonical readiness/start order. Confirm accounts, -contribution facts and pending recoverable work survive; never reinitialize state. - -The [backup/restore requirements](README.md#backup-and-restore-proof) apply to -retained work. An explicitly disposable test environment can be retired without -preserving its database only with its owner's authorization. Identify the exact -instance, volume and deployment directories before deletion; retain unrelated -resources, S3 objects and the stable address needed by the replacement. Confirm -old billable compute is terminated after the replacement is qualified. - -The [single-host qualification report](../../docs/reports/mvp-single-host-2026-11-11.md) -records the bounded private demo and restart proof, including its limits. diff --git a/deploy/hosted/compose.native-checker.yml b/deploy/hosted/compose.native-checker.yml deleted file mode 100644 index 7ab27fc21..000000000 --- a/deploy/hosted/compose.native-checker.yml +++ /dev/null @@ -1,20 +0,0 @@ -x-native-checker-environment: &native-checker-environment - WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/checker-runtime/checker.sock - WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST: ${WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST:?set the pinned trusted intake image digest} - WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST: ${WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST:?set the pinned trusted intake config digest} - WORKSTREAM_EXTERNAL_CHECKER_MATERIAL_ROOT: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/scratch - WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/checker-runtime/checker.sock - -x-native-checker-mount: &native-checker-mount - type: bind - source: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/checker-runtime - target: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/checker-runtime - read_only: true - -services: - api: - environment: *native-checker-environment - volumes: [*native-checker-mount] - worker: - environment: *native-checker-environment - volumes: [*native-checker-mount] diff --git a/deploy/hosted/compose.py b/deploy/hosted/compose.py index 5f0f979cc..6515857c7 100644 --- a/deploy/hosted/compose.py +++ b/deploy/hosted/compose.py @@ -5,23 +5,15 @@ import argparse from pathlib import Path -import subprocess import sys -import time from preflight import ( PreflightError, - compose_environment, - local_checker_enabled, - load_checker_config, parse_environment, render_compose, run_compose, run_shutdown, - validate_checker_config, validate_compose, - validate_smol_runtime, - validate_trusted_intake, validate_environment, validate_private_host_inputs, validate_identity_host_inputs, @@ -38,10 +30,6 @@ def parse_args() -> argparse.Namespace: def resume_release(environment_path: Path, values: dict[str, str]) -> int: """Reconcile an installed release after reboot, without pulling or migrating.""" - checker_config = None - if local_checker_enabled(values): - checker_config = load_checker_config(Path(values["WORKSTREAM_CHECKER_CONFIG_FILE"])) - validate_checker_config(checker_config, values) validate_private_host_inputs(values, require_node=False) phases: list[list[str]] = [] if values.get("WORKSTREAM_POSTGRES_IMAGE"): @@ -55,10 +43,6 @@ def resume_release(environment_path: Path, values: dict[str, str]) -> int: result = run_compose(environment_path, values, phase, cached_images=True) if result: return result - if checker_config is not None: - result = resume_native_checker(checker_config, values) - if result: - return result return run_compose( environment_path, values, ["up", "--detach", "--wait", "--wait-timeout", "120"], @@ -66,32 +50,6 @@ def resume_release(environment_path: Path, values: dict[str, str]) -> int: ) -def resume_native_checker(checker_config, values: dict[str, str]) -> int: - """Start and qualify the local native service before releasing its clients.""" - try: - for operation in ("reset-failed", "start"): - result = subprocess.run( - ["systemctl", operation, "workstream-checker.service"], - check=False, timeout=60, env=compose_environment(values), - ) - if result.returncode: - return result.returncode - except (OSError, subprocess.SubprocessError) as exc: - raise PreflightError("native checker startup did not complete") from exc - deadline = time.monotonic() + 120 - while True: - try: - validate_private_host_inputs(values) - validate_smol_runtime(checker_config, values) - validate_trusted_intake(values) - break - except PreflightError: - if time.monotonic() >= deadline: - raise - time.sleep(2) - return 0 - - def main() -> int: args = parse_args() try: @@ -128,20 +86,11 @@ def main() -> int: if proxy_bootstrap and values["WORKSTREAM_MODEL_PROXY_ENABLED"] != "true": raise PreflightError("model proxy bootstrap requires an enabled proxy") if launch or migration or points: - checker_config = None - if local_checker_enabled(values): - checker_config = load_checker_config( - Path(values["WORKSTREAM_CHECKER_CONFIG_FILE"]) - ) - validate_checker_config(checker_config, values) if proxy_bootstrap or migration or points: # No API, worker or producer is released in these fixed stages. validate_private_host_inputs(values, require_node=False) else: validate_private_host_inputs(values) - if checker_config is not None: - validate_smol_runtime(checker_config, values) - validate_trusted_intake(values) if args.compose_arguments and args.compose_arguments[0] == "stop": if args.compose_arguments == ["stop", "worker"]: return run_compose(args.env_file, values, args.compose_arguments) diff --git a/deploy/hosted/compose.yml b/deploy/hosted/compose.yml index 86152e370..db6a51e90 100644 --- a/deploy/hosted/compose.yml +++ b/deploy/hosted/compose.yml @@ -1,7 +1,7 @@ name: ${COMPOSE_PROJECT_NAME:?set COMPOSE_PROJECT_NAME in the release environment file} x-backend-environment: &backend-environment - WORKSTREAM_HOSTED_PROFILE: ${WORKSTREAM_HOSTED_PROFILE:-single-host} + WORKSTREAM_HOSTED_PROFILE: app WORKSTREAM_ARTIFACT_ADMISSION_DEPLOYMENT_MAXIMUM_BYTES: "4294967296" WORKSTREAM_ARTIFACT_ADMISSION_PRODUCER_MAXIMUM_BYTES: "268435456" WORKSTREAM_ARTIFACT_ADMISSION_PROJECT_MAXIMUM_BYTES: "1073741824" @@ -113,6 +113,14 @@ services: WORKSTREAM_API_RATE_LIMIT_KEY_SECRET_FILE: /run/secrets/api_rate_limit_key WORKSTREAM_PAGINATION_CURSOR_HMAC_SECRET_FILE: /run/secrets/pagination_cursor_hmac WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE: /run/workstream-artifact-credentials/aws-access-key.json + WORKSTREAM_EXTERNAL_RUNNER_HOST: ${WORKSTREAM_EXTERNAL_RUNNER_HOST:?set the private runner address} + WORKSTREAM_EXTERNAL_RUNNER_PORT: ${WORKSTREAM_EXTERNAL_RUNNER_PORT:-9443} + WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME: ${WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME:?set the runner certificate name} + WORKSTREAM_EXTERNAL_RUNNER_CA_PATH: /run/secrets/external_runner_ca + WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH: /run/secrets/external_runner_certificate + WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH: /run/secrets/external_runner_private_key + WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST: ${WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST:?set the pinned trusted intake image digest} + WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST: ${WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST:?set the pinned trusted intake config digest} secrets: - source: database_url target: database_url @@ -134,6 +142,21 @@ services: uid: "${WORKSTREAM_RUNTIME_UID}" gid: "${WORKSTREAM_RUNTIME_GID}" mode: 0400 + - source: external_runner_ca + target: external_runner_ca + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: external_runner_certificate + target: external_runner_certificate + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: external_runner_private_key + target: external_runner_private_key + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 command: - python - -m @@ -171,6 +194,14 @@ services: WORKSTREAM_CELERY_BROKER_URL_FILE: /run/secrets/celery_broker_url WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/guide-runtime/guide.sock WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE: /run/workstream-artifact-credentials/aws-access-key.json + WORKSTREAM_EXTERNAL_RUNNER_HOST: ${WORKSTREAM_EXTERNAL_RUNNER_HOST:?set the private runner address} + WORKSTREAM_EXTERNAL_RUNNER_PORT: ${WORKSTREAM_EXTERNAL_RUNNER_PORT:-9443} + WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME: ${WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME:?set the runner certificate name} + WORKSTREAM_EXTERNAL_RUNNER_CA_PATH: /run/secrets/external_runner_ca + WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH: /run/secrets/external_runner_certificate + WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH: /run/secrets/external_runner_private_key + WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST: ${WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST:?set the pinned trusted intake image digest} + WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST: ${WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST:?set the pinned trusted intake config digest} secrets: - source: database_url target: database_url @@ -182,6 +213,21 @@ services: uid: "${WORKSTREAM_RUNTIME_UID}" gid: "${WORKSTREAM_RUNTIME_GID}" mode: 0400 + - source: external_runner_ca + target: external_runner_ca + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: external_runner_certificate + target: external_runner_certificate + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: external_runner_private_key + target: external_runner_private_key + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 command: - python - -m @@ -231,12 +277,33 @@ services: WORKSTREAM_DATABASE_URL_FILE: /run/secrets/database_url WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/model-runtime/model.sock WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE: /run/workstream-artifact-credentials/aws-access-key.json + WORKSTREAM_EXTERNAL_RUNNER_HOST: ${WORKSTREAM_EXTERNAL_RUNNER_HOST:?set the private runner address} + WORKSTREAM_EXTERNAL_RUNNER_PORT: ${WORKSTREAM_EXTERNAL_RUNNER_PORT:-9443} + WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME: ${WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME:?set the runner certificate name} + WORKSTREAM_EXTERNAL_RUNNER_CA_PATH: /run/secrets/external_runner_ca + WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH: /run/secrets/external_runner_certificate + WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH: /run/secrets/external_runner_private_key secrets: - source: database_url target: database_url uid: "${WORKSTREAM_RUNTIME_UID}" gid: "${WORKSTREAM_RUNTIME_GID}" mode: 0400 + - source: external_runner_ca + target: external_runner_ca + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: external_runner_certificate + target: external_runner_certificate + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: external_runner_private_key + target: external_runner_private_key + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 command: [python, -m, app.workers.checker_model_proxy] volumes: - type: bind @@ -307,3 +374,9 @@ secrets: file: ${WORKSTREAM_API_RATE_LIMIT_KEY_SECRET_FILE:?set the private rate-limit key file} pagination_cursor_hmac: file: ${WORKSTREAM_PAGINATION_CURSOR_HMAC_SECRET_FILE:?set the private cursor key file} + external_runner_ca: + file: ${WORKSTREAM_EXTERNAL_RUNNER_CA_FILE:?set the runner CA certificate file} + external_runner_certificate: + file: ${WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE:?set the app runner client certificate file} + external_runner_private_key: + file: ${WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE:?set the app runner client key file} diff --git a/deploy/hosted/preflight.py b/deploy/hosted/preflight.py index 959a77abd..874de359e 100644 --- a/deploy/hosted/preflight.py +++ b/deploy/hosted/preflight.py @@ -23,7 +23,6 @@ COMPOSE_PATH = Path(__file__).with_name("compose.yml") -NATIVE_CHECKER_COMPOSE_PATH = Path(__file__).with_name("compose.native-checker.yml") INFERENCE_COMPOSE_PATH = Path(__file__).with_name("compose.inference.yml") TRIAL_COMPOSE_PATH = Path(__file__).with_name("compose.trials.yml") TRIAL_MANIFEST_TARGET = Path("/etc/workstream/trial-authority.json") @@ -56,29 +55,31 @@ "WORKSTREAM_GITHUB_APP_INSTALLATION_ID", ) DEFAULT_DEPLOYMENT_ROOT = Path("/var/lib/workstream") -DEFAULT_CHECKER_SERVICE_BINARY = Path("/opt/workstream/bin/workstream-checker-service") INTAKE_DIGEST_KEYS = ( "WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST", "WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST", ) HOSTED_PROFILE_KEY = "WORKSTREAM_HOSTED_PROFILE" -NATIVE_REQUIRED_KEYS = ( - "WORKSTREAM_CHECKER_CONFIG_FILE", - "WORKSTREAM_CHECKER_SERVICE_BINARY_SHA256", +REMOTE_RUNNER_KEYS = ( + "WORKSTREAM_EXTERNAL_RUNNER_HOST", + "WORKSTREAM_EXTERNAL_RUNNER_PORT", + "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME", + "WORKSTREAM_EXTERNAL_RUNNER_CA_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE", *INTAKE_DIGEST_KEYS, ) -NATIVE_ENVIRONMENT_KEYS = ( - "WORKSTREAM_EXTERNAL_CHECKER_MATERIAL_ROOT", - "WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET", - "WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET", +REMOTE_RUNNER_ENVIRONMENT_KEYS = ( + "WORKSTREAM_EXTERNAL_RUNNER_HOST", + "WORKSTREAM_EXTERNAL_RUNNER_PORT", + "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME", + "WORKSTREAM_EXTERNAL_RUNNER_CA_PATH", + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH", + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH", *INTAKE_DIGEST_KEYS, ) -def local_checker_enabled(values: dict[str, str]) -> bool: - return values.get(HOSTED_PROFILE_KEY, "single-host") == "single-host" - - @dataclass(frozen=True) class HostedPaths: root: Path @@ -122,14 +123,6 @@ def deployment_paths(values: dict[str, str]) -> HostedPaths: ) -def checker_service_binary(values: dict[str, str]) -> Path: - return Path( - values.get( - "WORKSTREAM_CHECKER_SERVICE_BINARY", str(DEFAULT_CHECKER_SERVICE_BINARY) - ) - ) - - GUIDE_PARSER_UID = 10002 GUIDE_PARSER_GID = 10001 DOCKER_SOCKET = Path("/var/run/docker.sock") @@ -152,6 +145,9 @@ def checker_service_binary(values: dict[str, str]) -> Path: "WORKSTREAM_CELERY_BROKER_URL_FILE", "WORKSTREAM_API_RATE_LIMIT_KEY_SECRET_FILE", "WORKSTREAM_PAGINATION_CURSOR_HMAC_SECRET_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CA_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE", ) MODEL_PROXY_SECRET_FILE_KEYS = ( "WORKSTREAM_MODEL_PROXY_OPENAI_API_KEY_FILE", @@ -188,6 +184,15 @@ def checker_service_binary(values: dict[str, str]) -> Path: "pagination_cursor_hmac", "/run/secrets/pagination_cursor_hmac", ), + "WORKSTREAM_EXTERNAL_RUNNER_CA_FILE": ( + "external_runner_ca", "/run/secrets/external_runner_ca", + ), + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE": ( + "external_runner_certificate", "/run/secrets/external_runner_certificate", + ), + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE": ( + "external_runner_private_key", "/run/secrets/external_runner_private_key", + ), "WORKSTREAM_MODEL_PROXY_OPENAI_API_KEY_FILE": ( "model_proxy_openai_api_key", "/run/secrets/model_proxy_openai_api_key", @@ -203,16 +208,27 @@ def checker_service_binary(values: dict[str, str]) -> Path: "WORKSTREAM_CELERY_BROKER_URL_FILE", "WORKSTREAM_API_RATE_LIMIT_KEY_SECRET_FILE", "WORKSTREAM_PAGINATION_CURSOR_HMAC_SECRET_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CA_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE", ), "worker": ( "WORKSTREAM_DATABASE_URL_FILE", "WORKSTREAM_CELERY_BROKER_URL_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CA_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE", ), "beat": ( "WORKSTREAM_DATABASE_URL_FILE", "WORKSTREAM_CELERY_BROKER_URL_FILE", ), - "model-proxy": ("WORKSTREAM_DATABASE_URL_FILE",), + "model-proxy": ( + "WORKSTREAM_DATABASE_URL_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CA_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE", + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE", + ), } FORBIDDEN_RELEASE_KEYS = ( "WORKSTREAM_GITHUB_APP_PRIVATE_KEY", @@ -316,17 +332,16 @@ def checker_service_binary(values: dict[str, str]) -> Path: *AWS_S3_IDENTITY_KEYS, *TIMEOUT_KEYS, *BASE_SECRET_FILE_KEYS, + *REMOTE_RUNNER_KEYS, ) OPTIONAL_RELEASE_KEYS = ( HOSTED_PROFILE_KEY, - *NATIVE_REQUIRED_KEYS, *LOCAL_DATA_KEYS, "WORKSTREAM_MCP_IMAGE", *IDENTITY_KEYS, *MCP_OAUTH_KEYS, *GITHUB_APP_KEYS, "WORKSTREAM_DEPLOYMENT_ROOT", - "WORKSTREAM_CHECKER_SERVICE_BINARY", *TRIAL_KEYS, "WORKSTREAM_API_HOST_PORT", "WORKSTREAM_CELERY_WORKER_CONCURRENCY", @@ -487,13 +502,8 @@ def validate_environment(values: dict[str, str]) -> None: raise PreflightError( f"release environment contains an unsupported key: {unknown[0]}" ) - if values.get(HOSTED_PROFILE_KEY, "single-host") not in {"single-host", "app"}: - raise PreflightError("unsupported hosted profile") - local_checker = local_checker_enabled(values) - if not local_checker and any(values.get(key) for key in ( - *NATIVE_REQUIRED_KEYS, "WORKSTREAM_CHECKER_SERVICE_BINARY", *TRIAL_KEYS, - )): - raise PreflightError("app profile cannot configure a native checker or trial authority") + if values.get(HOSTED_PROFILE_KEY, "app") != "app": + raise PreflightError("hosted releases require the external-runner app profile") if "WORKSTREAM_MCP_IMAGE" in values and not IMAGE_REFERENCE.fullmatch(values["WORKSTREAM_MCP_IMAGE"]): raise PreflightError("MCP image must be digest-qualified") validate_identity_environment(values) @@ -520,12 +530,9 @@ def validate_environment(values: dict[str, str]) -> None: ): raise PreflightError("GitHub App key file must use a canonical absolute path") root = deployment_paths(values).root - binary = checker_service_binary(values) - if values.get("WORKSTREAM_DEPLOYMENT_ROOT", str(root)) != str(root) or ( - local_checker and values.get("WORKSTREAM_CHECKER_SERVICE_BINARY", str(binary)) != str(binary) - ): + if values.get("WORKSTREAM_DEPLOYMENT_ROOT", str(root)) != str(root): raise PreflightError("deployment paths must use canonical spelling") - for path in (root, binary) if local_checker else (root,): + for path in (root,): if ( not path.is_absolute() or path != path.resolve(strict=False) @@ -533,8 +540,6 @@ def validate_environment(values: dict[str, str]) -> None: or len(path.parts) < 3 ): raise PreflightError("deployment paths must be canonical absolute paths") - if local_checker and (root == binary or binary.is_relative_to(root) or root.is_relative_to(binary)): - raise PreflightError("native service asset overlaps deployment data") for key in REQUIRED_RELEASE_KEYS: _required(values, key) for key in ( @@ -548,11 +553,23 @@ def validate_environment(values: dict[str, str]) -> None: "WORKSTREAM_RUNTIME_GID", ): _positive_id(values, key) - if local_checker: - for key in NATIVE_REQUIRED_KEYS: - value = _required(values, key) - if key != "WORKSTREAM_CHECKER_CONFIG_FILE" and not DIGEST.fullmatch(value): - raise PreflightError(f"trusted intake requires a pinned digest: {key}") + for key in INTAKE_DIGEST_KEYS: + if not DIGEST.fullmatch(_required(values, key)): + raise PreflightError(f"trusted intake requires a pinned digest: {key}") + runner_host = _required(values, "WORKSTREAM_EXTERNAL_RUNNER_HOST") + runner_name = _required(values, "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME") + if ( + len(runner_host) > 255 + or len(runner_name) > 255 + or any(character.isspace() for character in runner_host + runner_name) + ): + raise PreflightError("external runner endpoint is invalid") + try: + runner_port = int(_required(values, "WORKSTREAM_EXTERNAL_RUNNER_PORT")) + except ValueError as exc: + raise PreflightError("external runner port is invalid") from exc + if not 1 <= runner_port <= 65_535: + raise PreflightError("external runner port is invalid") for key in FORBIDDEN_RELEASE_KEYS: if values.get(key): raise PreflightError( @@ -1111,20 +1128,11 @@ def validate_private_host_inputs( gid = _positive_id(values, "WORKSTREAM_RUNTIME_GID") _private_metadata(paths.root, kind="directory", uid=uid, gid=gid, mode=0o700) _private_metadata(paths.scratch, kind="directory", uid=uid, gid=gid, mode=0o700) - local_checker = local_checker_enabled(values) - if local_checker: - _private_metadata(paths.socket_root, kind="directory", uid=uid, gid=gid, mode=0o700) - if require_node: - _validate_native_socket(paths.socket, uid, gid) model_proxy_enabled = values["WORKSTREAM_MODEL_PROXY_ENABLED"] == "true" if model_proxy_enabled: _private_metadata( paths.model_root, kind="directory", uid=uid, gid=gid, mode=0o700 ) - if local_checker: - _private_metadata( - paths.model_relays, kind="directory", uid=uid, gid=gid, mode=0o700 - ) _private_metadata( paths.guide_root, kind="directory", @@ -1164,7 +1172,6 @@ def validate_private_host_inputs( ): raise PreflightError("model proxy socket has unsafe retained state") private_paths = [ - *((Path(values["WORKSTREAM_CHECKER_CONFIG_FILE"]),) if local_checker else ()), *((Path(values[TRIAL_KEYS[0]]),) if values.get(TRIAL_KEYS[0]) else ()), *(Path(values[key]) for key in _secret_file_keys(values)), Path(values[DIRECT_USER_CREDENTIAL_HOST_FILE_KEY]), @@ -1176,12 +1183,8 @@ def validate_private_host_inputs( paths.scratch.resolve(strict=True), paths.guide_root.resolve(strict=True), ] - if local_checker: - shared_roots.append(paths.socket_root.resolve(strict=True)) if model_proxy_enabled: shared_roots.append(paths.model_root.resolve(strict=True)) - if local_checker: - shared_roots.append(paths.model_relays.resolve(strict=True)) resolved_paths = [path.resolve(strict=True) for path in private_paths] except (OSError, RuntimeError) as exc: raise PreflightError("private host input identity is unavailable") from exc @@ -1235,8 +1238,6 @@ def _run_json( def _compose_file_arguments(values: dict[str, str]) -> list[str]: arguments = ["--file", str(COMPOSE_PATH)] - if local_checker_enabled(values): - arguments.extend(("--file", str(NATIVE_CHECKER_COMPOSE_PATH))) if values.get("WORKSTREAM_POSTGRES_IMAGE"): arguments.extend(("--file", str(LOCAL_DATA_COMPOSE_PATH))) if values.get("WORKSTREAM_MCP_IMAGE"): @@ -1833,8 +1834,6 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: shared_backend_mounts = { str(paths.scratch): (str(paths.scratch), False), } - if local_checker_enabled(values): - shared_backend_mounts[str(paths.socket_root)] = (str(paths.socket_root), True) expected_mounts = { "api": shared_backend_mounts | direct_user_credential_mount, "worker": shared_backend_mounts @@ -2062,7 +2061,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: "WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET", "WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET", DIRECT_USER_CREDENTIAL_FILE_KEY, - *NATIVE_ENVIRONMENT_KEYS, + *REMOTE_RUNNER_ENVIRONMENT_KEYS, *TRIAL_KEYS, *GITHUB_APP_KEYS, } @@ -2083,7 +2082,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: "WORKSTREAM_ARTIFACT_S3_ADDRESSING_STYLE": "virtual", DIRECT_USER_CREDENTIAL_FILE_KEY: str(DIRECT_USER_CREDENTIAL_TARGET), "WORKSTREAM_ARTIFACT_SCRATCH_ROOT": str(paths.scratch), - HOSTED_PROFILE_KEY: values.get(HOSTED_PROFILE_KEY, "single-host"), + HOSTED_PROFILE_KEY: "app", } for key, value in exact.items(): if str(environment.get(key, "")).lower() != value: @@ -2110,18 +2109,35 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: ) for name, service in services.items(): environment = service.get("environment") or {} - expected_native = ( + expected_remote = ( { - "WORKSTREAM_EXTERNAL_CHECKER_MATERIAL_ROOT": str(paths.scratch), - "WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET": str(paths.socket), - "WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET": str(paths.socket), - **{key: values[key] for key in INTAKE_DIGEST_KEYS}, + "WORKSTREAM_EXTERNAL_RUNNER_HOST": values["WORKSTREAM_EXTERNAL_RUNNER_HOST"], + "WORKSTREAM_EXTERNAL_RUNNER_PORT": values["WORKSTREAM_EXTERNAL_RUNNER_PORT"], + "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME": values[ + "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME" + ], + "WORKSTREAM_EXTERNAL_RUNNER_CA_PATH": "/run/secrets/external_runner_ca", + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH": ( + "/run/secrets/external_runner_certificate" + ), + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH": ( + "/run/secrets/external_runner_private_key" + ), + **( + {key: values[key] for key in INTAKE_DIGEST_KEYS} + if name in {"api", "worker"} + else {} + ), } - if local_checker_enabled(values) and name in {"api", "worker"} + if name in {"api", "worker"} or (name == "model-proxy" and model_proxy_enabled) else {} ) - if {key: environment[key] for key in NATIVE_ENVIRONMENT_KEYS if key in environment} != expected_native: - raise PreflightError(f"rendered native checker environment is unsafe: {name}") + if { + key: environment[key] + for key in REMOTE_RUNNER_ENVIRONMENT_KEYS + if key in environment + } != expected_remote: + raise PreflightError(f"rendered external runner environment is unsafe: {name}") expected_trial = ( { TRIAL_KEYS[0]: str(TRIAL_MANIFEST_TARGET), @@ -2440,10 +2456,6 @@ def main() -> int: try: values = parse_environment(args.env_file) validate_environment(values) - checker_config = None - if local_checker_enabled(values): - checker_config = load_checker_config(Path(values["WORKSTREAM_CHECKER_CONFIG_FILE"])) - validate_checker_config(checker_config, values) validate_compose(render_compose(args.env_file, values), values) if args.configuration_only: print( @@ -2451,9 +2463,6 @@ def main() -> int: ) return 0 validate_private_host_inputs(values) - if checker_config is not None: - validate_smol_runtime(checker_config, values) - validate_trusted_intake(values) except PreflightError as exc: print(f"hosted release preflight failed: {exc}", file=sys.stderr) return 1 diff --git a/deploy/hosted/release.env.example b/deploy/hosted/release.env.example index 2a1503245..4eb036494 100644 --- a/deploy/hosted/release.env.example +++ b/deploy/hosted/release.env.example @@ -1,16 +1,13 @@ # Copy this non-secret template to a private operator file. Every image must be # an immutable repository@sha256 reference produced from the reviewed source. COMPOSE_PROJECT_NAME=workstream-release -# For an app host without local KVM, set app and remove the checker binary, -# checker configuration, trusted intake image/config and trial selectors. -WORKSTREAM_HOSTED_PROFILE=single-host +# Hosted application processes always use the separately administered runner. +WORKSTREAM_HOSTED_PROFILE=app WORKSTREAM_BACKEND_IMAGE=registry.example/workstream/backend@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa WORKSTREAM_MODEL_PROXY_IMAGE=registry.example/workstream/backend-agents@sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd -WORKSTREAM_CHECKER_SERVICE_BINARY_SHA256=sha256:9999999999999999999999999999999999999999999999999999999999999999 WORKSTREAM_MODEL_PROXY_ENABLED=true WORKSTREAM_DEPLOYMENT_ROOT=/var/lib/workstream -WORKSTREAM_CHECKER_SERVICE_BINARY=/opt/workstream/bin/workstream-checker-service WORKSTREAM_RUNTIME_UID=10001 WORKSTREAM_RUNTIME_GID=10001 WORKSTREAM_API_HOST_PORT=8000 @@ -108,11 +105,18 @@ WORKSTREAM_OBSERVABILITY_OTLP_ENDPOINT= WORKSTREAM_OBSERVABILITY_TRACE_SAMPLE_RATIO=0.1 WORKSTREAM_OBSERVABILITY_LOG_LEVEL=INFO -WORKSTREAM_CHECKER_CONFIG_FILE=/etc/workstream/checker-service.json +# The app and runner certificates are issued by a dedicated private CA. These +# files are runtime-owned 0400 files; the private key is mounted only into API +# and worker. The runner firewall admits port 9443 only from the app security group. +WORKSTREAM_EXTERNAL_RUNNER_HOST=172.31.21.182 +WORKSTREAM_EXTERNAL_RUNNER_PORT=9443 +WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME=runner.workstream.internal +WORKSTREAM_EXTERNAL_RUNNER_CA_FILE=/etc/workstream/runner-tls/ca.crt +WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE=/etc/workstream/runner-tls/app.crt +WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE=/etc/workstream/runner-tls/app.key -# Provision the trusted Smol intake node before launching API/Celery. Its private -# socket is /var/lib/workstream/checker-runtime/checker.sock, owned by 10001:10001. -# Replace both placeholders with identities verified from the built intake image. +# Replace both placeholders with identities verified from the runner's pinned +# trusted-intake image. They remain app-side response-verification facts. WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST=sha256:1111111111111111111111111111111111111111111111111111111111111111 WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST=sha256:2222222222222222222222222222222222222222222222222222222222222222 diff --git a/experiments/pilot04_external_checker_runtime/public_intake_observer.py b/experiments/pilot04_external_checker_runtime/public_intake_observer.py index 3c093259d..b4f9f9a89 100644 --- a/experiments/pilot04_external_checker_runtime/public_intake_observer.py +++ b/experiments/pilot04_external_checker_runtime/public_intake_observer.py @@ -6,12 +6,12 @@ import time from uuid import uuid4 -from app.adapters.artifacts.trusted_intake import UnixSocketTrustedIntakeAdapter -from app.adapters.checkers.external_service import UnixSocketExternalCheckerAdapter +from app.adapters.artifacts.trusted_intake import RemoteTlsTrustedIntakeAdapter +from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter _TRACE = Path(os.environ["WORKSTREAM_PROBE_INTAKE_TRACE"]) -_prepare = UnixSocketTrustedIntakeAdapter.prepare -_execute = UnixSocketExternalCheckerAdapter.execute +_prepare = RemoteTlsTrustedIntakeAdapter.prepare +_execute = RemoteTlsExternalCheckerAdapter.execute def _record(event, identifier, **facts): @@ -52,6 +52,6 @@ async def _observe_execute(self, request, grant, *, model_grant=None): # This explicitly selected proof entry point delegates all work to the original # typed adapter. Production app imports and ordinary workers never install it. -UnixSocketTrustedIntakeAdapter.prepare = _observe_prepare -UnixSocketExternalCheckerAdapter.execute = _observe_execute +RemoteTlsTrustedIntakeAdapter.prepare = _observe_prepare +RemoteTlsExternalCheckerAdapter.execute = _observe_execute from app.main import app as app # noqa: E402 diff --git a/external_checkers/deploy/remote-node.example.json b/external_checkers/deploy/remote-node.example.json new file mode 100644 index 000000000..f8b8e4b48 --- /dev/null +++ b/external_checkers/deploy/remote-node.example.json @@ -0,0 +1,12 @@ +{ + "listen_host": "172.31.21.182", + "listen_port": 9443, + "client_name": "app.workstream.internal", + "socket_path": "/var/lib/workstream/checker-runtime/checker.sock", + "material_root": "/var/lib/workstream/checker-runtime/materials", + "model_proxy_socket_path": "/var/lib/workstream/checker-runtime/model-proxy.sock", + "tls_certificate_path": "/etc/workstream/runner-tls/server.crt", + "tls_private_key_path": "/etc/workstream/runner-tls/server.key", + "tls_ca_path": "/etc/workstream/runner-tls/ca.crt", + "session_timeout_seconds": 3700 +} diff --git a/external_checkers/deploy/workstream-checker.service b/external_checkers/deploy/workstream-checker.service index d975c8b2d..0fccca144 100644 --- a/external_checkers/deploy/workstream-checker.service +++ b/external_checkers/deploy/workstream-checker.service @@ -1,6 +1,7 @@ [Unit] Description=Workstream private checker node -After=local-fs.target +Requires=workstream-remote-node.service +After=local-fs.target workstream-remote-node.service StartLimitIntervalSec=60 StartLimitBurst=5 diff --git a/external_checkers/deploy/workstream-remote-node.service b/external_checkers/deploy/workstream-remote-node.service new file mode 100644 index 000000000..82138caf7 --- /dev/null +++ b/external_checkers/deploy/workstream-remote-node.service @@ -0,0 +1,28 @@ +[Unit] +Description=Workstream authenticated remote checker edge +Before=workstream-checker.service +After=network-online.target +Wants=network-online.target +StartLimitIntervalSec=60 +StartLimitBurst=5 + +[Service] +Type=simple +User=10001 +Group=10001 +UMask=0077 +ExecStart=/usr/bin/python3 /opt/workstream/bin/workstream-remote-node --config /etc/workstream/remote-node.json +ExecStartPost=/usr/bin/python3 -c 'import pathlib,time; p=pathlib.Path("/var/lib/workstream/checker-runtime/model-proxy.sock"); raise SystemExit(next((0 for _ in range(100) if p.is_socket() or (time.sleep(.05) and False)),1))' +Restart=on-failure +RestartSec=2 +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict +ReadWritePaths=/var/lib/workstream/checker-runtime +MemoryMax=512M +MemorySwapMax=0 +TasksMax=128 + +[Install] +WantedBy=multi-user.target diff --git a/external_checkers/intake/Dockerfile b/external_checkers/intake/Dockerfile index 7aa7fac4e..82e11334a 100644 --- a/external_checkers/intake/Dockerfile +++ b/external_checkers/intake/Dockerfile @@ -3,6 +3,7 @@ FROM python:3.12-slim-bookworm@sha256:4766d8b510c428e595d74b9cc5bbb2fae8e26316ff COPY --from=ghcr.io/astral-sh/uv:0.12.3@sha256:2d890623d310b57771ce840f0da5eed5fc6d657da05ffaa45d82797b53fa3abc /uv /bin/uv ENV PATH="/opt/venv/bin:$PATH" PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 UV_PROJECT_ENVIRONMENT=/opt/venv UV_PYTHON_DOWNLOADS=never WORKDIR /opt/workstream/backend +COPY packages/external-services /opt/workstream/packages/external-services COPY backend/pyproject.toml backend/uv.lock backend/LICENSE ./ COPY backend/app ./app RUN uv sync --locked --no-dev --no-editable && rm -rf build workstream_backend.egg-info diff --git a/external_checkers/remote_node.py b/external_checkers/remote_node.py new file mode 100644 index 000000000..1dc65964f --- /dev/null +++ b/external_checkers/remote_node.py @@ -0,0 +1,597 @@ +#!/usr/bin/env python3 +"""Authenticated network edge for one dedicated native checker node.""" + +from __future__ import annotations + +import argparse +import asyncio +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import ssl +import stat +import struct +from typing import Any +import uuid + + +PROTOCOL = "workstream.remote_runner.v1" +CHECKER_CAPABILITY = "external_checker_execution" +INTAKE_CAPABILITY = "trusted_submission_intake" +GRANT_PROTOCOL = "workstream.external_checker_material_grant.v2" +MAXIMUM_CONTROL_BYTES = 2 * 1024 * 1024 +MAXIMUM_FRAME_BYTES = 64 * 1024 * 1024 +MAXIMUM_MATERIAL_BYTES = 1024 * 1024 * 1024 +MAXIMUM_FILES = 4_000 +_GRANT_ID = re.compile(r"extract_[0-9a-f]{32}") +_SHA256 = re.compile(r"sha256:[0-9a-f]{64}") + + +class ProtocolError(Exception): + """A remote peer sent a malformed or unbound request.""" + + +class ModelBridge: + """Serialize runner-local callbacks over one app-authenticated TLS session.""" + + def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + self.reader, self.writer = reader, writer + self.lock = asyncio.Lock() + self.closed = asyncio.Event() + + async def exchange(self, request: bytes) -> bytes: + async with self.lock: + if self.closed.is_set(): + raise ProtocolError("model bridge is unavailable") + channel_id = uuid.uuid4().hex + header = json.dumps( + { + "protocol_version": PROTOCOL, + "operation": "model_request", + "channel_id": channel_id, + }, + separators=(",", ":"), + ).encode() + try: + await _write_frame(self.writer, header) + await _write_frame(self.writer, request) + response_header = _decode_object( + await _read_frame(self.reader, MAXIMUM_CONTROL_BYTES) + ) + if response_header != { + "protocol_version": PROTOCOL, + "operation": "model_response", + "channel_id": channel_id, + }: + raise ProtocolError("model response header differs") + return await _read_frame(self.reader, MAXIMUM_FRAME_BYTES) + except (OSError, ssl.SSLError, asyncio.IncompleteReadError): + self.close() + raise ProtocolError("model bridge is unavailable") from None + + def close(self) -> None: + if not self.closed.is_set(): + self.closed.set() + self.writer.close() + + +def _closed_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + value: dict[str, Any] = {} + for key, item in pairs: + if key in value: + raise ProtocolError("duplicate JSON member") + value[key] = item + return value + + +def _decode_object(raw: bytes) -> dict[str, Any]: + try: + value = json.loads( + raw.decode("utf-8"), + parse_constant=lambda _: (_ for _ in ()).throw(ProtocolError("JSON constant")), + object_pairs_hook=_closed_object, + ) + except (UnicodeError, ValueError, RecursionError) as exc: + raise ProtocolError("invalid JSON") from exc + if type(value) is not dict: + raise ProtocolError("JSON root is not an object") + return value + + +async def _read_frame( + reader: asyncio.StreamReader, + maximum: int, + *, + allow_empty: bool = False, +) -> bytes: + size = struct.unpack(">I", await reader.readexactly(4))[0] + if size == 0 and allow_empty: + return b"" + if size == 0 or size > maximum: + raise ProtocolError("frame is unbounded") + return await reader.readexactly(size) + + +async def _write_frame(writer: asyncio.StreamWriter, body: bytes) -> None: + if not body or len(body) > MAXIMUM_FRAME_BYTES: + raise ProtocolError("response frame is unbounded") + writer.write(struct.pack(">I", len(body)) + body) + await writer.drain() + + +def _peer_name(writer: asyncio.StreamWriter) -> set[str]: + certificate = writer.get_extra_info("peercert") + if type(certificate) is not dict: + return set() + return { + value + for kind, value in certificate.get("subjectAltName", ()) + if kind == "DNS" and type(value) is str + } + + +def _relative_path(value: object) -> PurePosixPath: + if type(value) is not str or not value or len(value.encode("utf-8")) > 4_096: + raise ProtocolError("material path is invalid") + path = PurePosixPath(value) + if path.is_absolute() or "\\" in value or any(part in {"", ".", ".."} for part in path.parts): + raise ProtocolError("material path is invalid") + return path + + +def _manifest_files( + manifest: dict[str, Any], +) -> tuple[tuple[PurePosixPath, int, str, bool], ...]: + if manifest.get("protocol_version") != GRANT_PROTOCOL: + raise ProtocolError("material protocol differs") + materials = manifest.get("materials") + if type(materials) is not list or not 1 <= len(materials) <= 2: + raise ProtocolError("material inventory is invalid") + values: list[tuple[PurePosixPath, int, str, bool]] = [] + roles: set[str] = set() + for item in materials: + if type(item) is not dict or set(item) != {"material", "directories", "files"}: + raise ProtocolError("material descriptor is invalid") + material = item["material"] + if type(material) is not dict or material.get("role") not in { + "submission_archive", "predecessor_submission_archive" + }: + raise ProtocolError("material role is invalid") + role = material["role"] + if role in roles: + raise ProtocolError("material role is duplicated") + roles.add(role) + directories = item["directories"] + files = item["files"] + if type(directories) is not list or type(files) is not list: + raise ProtocolError("material inventory is invalid") + seen: set[str] = set() + for value in directories: + path = _relative_path(value) + if str(path) in seen: + raise ProtocolError("material path is duplicated") + seen.add(str(path)) + for entry in files: + if type(entry) is not dict or set(entry) != { + "normalized_path", "byte_count", "sha256", "executable" + }: + raise ProtocolError("material file is invalid") + path = _relative_path(entry["normalized_path"]) + count, digest, executable = ( + entry["byte_count"], entry["sha256"], entry["executable"] + ) + if ( + str(path) in seen + or type(count) is not int + or count < 0 + or type(digest) is not str + or _SHA256.fullmatch(digest) is None + or type(executable) is not bool + ): + raise ProtocolError("material file is invalid") + seen.add(str(path)) + values.append((PurePosixPath("materials", role, *path.parts), count, digest, executable)) + if len(values) > MAXIMUM_FILES: + raise ProtocolError("material file count is unbounded") + return tuple(values) + + +def _mkdir_inventory(root: Path, manifest: dict[str, Any]) -> None: + materials_root = root / "materials" + materials_root.mkdir(mode=0o700) + for item in manifest["materials"]: + role_root = materials_root / item["material"]["role"] + role_root.mkdir(mode=0o700) + for value in item["directories"]: + path = _relative_path(value) + (role_root / Path(*path.parts)).mkdir(mode=0o700, parents=True, exist_ok=True) + + +def _seal_directories(root: Path) -> None: + directories = sorted( + (path for path in root.rglob("*") if path.is_dir()), + key=lambda path: len(path.parts), + reverse=True, + ) + for path in directories: + os.chmod(path, 0o500, follow_symlinks=False) + + +def _remove_tree(path: Path) -> None: + if not path.exists(): + return + for current, directories, files in os.walk(path, topdown=False, followlinks=False): + for name in files: + os.chmod(Path(current, name), 0o600, follow_symlinks=False) + for name in directories: + os.chmod(Path(current, name), 0o700, follow_symlinks=False) + os.chmod(path, 0o700, follow_symlinks=False) + shutil.rmtree(path) + + +def _write_descriptor(descriptor: int, body: bytes) -> None: + view = memoryview(body) + while view: + written = os.write(descriptor, view) + if written <= 0: + raise OSError("material write made no progress") + view = view[written:] + + +class RemoteNode: + """Route authenticated sessions into one private native service socket.""" + + def __init__(self, config: dict[str, Any]) -> None: + expected = { + "listen_host", "listen_port", "client_name", "socket_path", "material_root", + "model_proxy_socket_path", + "tls_certificate_path", "tls_private_key_path", "tls_ca_path", "session_timeout_seconds", + } + if set(config) != expected: + raise ValueError("remote node configuration shape is invalid") + self.host = config["listen_host"] + self.port = config["listen_port"] + self.client_name = config["client_name"] + self.socket_path = Path(config["socket_path"]) + self.model_proxy_socket_path = Path(config["model_proxy_socket_path"]) + self.material_root = Path(config["material_root"]) + self.timeout = float(config["session_timeout_seconds"]) + if ( + type(self.host) is not str + or type(self.port) is not int + or not 1 <= self.port <= 65_535 + or type(self.client_name) is not str + or not self.client_name + or not self.socket_path.is_absolute() + or not self.model_proxy_socket_path.is_absolute() + or not self.material_root.is_absolute() + or not 1 <= self.timeout <= 3_700 + ): + raise ValueError("remote node configuration is invalid") + self.workspaces = self.material_root / "workspaces" + metadata = self.material_root.stat() + if ( + not self.material_root.is_dir() + or self.material_root.is_symlink() + or metadata.st_mode & 0o077 + or self.material_root.resolve() != self.material_root + ): + raise ValueError("remote node material root is not private") + self.workspaces.mkdir(mode=0o700, exist_ok=True) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_3 + context.verify_mode = ssl.CERT_REQUIRED + context.load_cert_chain(config["tls_certificate_path"], config["tls_private_key_path"]) + context.load_verify_locations(config["tls_ca_path"]) + self.ssl_context = context + self._execution = asyncio.Lock() + self._model_bridge: ModelBridge | None = None + self._model_server: asyncio.AbstractServer | None = None + + async def start_model_proxy(self) -> None: + """Own the runner-local socket used by the native model relay.""" + parent = self.model_proxy_socket_path.parent + metadata = parent.stat() + if ( + not parent.is_dir() + or parent.is_symlink() + or metadata.st_mode & 0o077 + or parent.resolve() != parent + ): + raise ValueError("model proxy parent is not private") + try: + occupied = self.model_proxy_socket_path.lstat() + except FileNotFoundError: + pass + else: + if ( + not stat.S_ISSOCK(occupied.st_mode) + or occupied.st_uid != os.getuid() + or self.model_proxy_socket_path.is_symlink() + ): + raise ValueError("model proxy socket is occupied") + self.model_proxy_socket_path.unlink() + self._model_server = await asyncio.start_unix_server( + self._handle_model_proxy, + path=self.model_proxy_socket_path, + limit=MAXIMUM_FRAME_BYTES + 4, + ) + os.chmod(self.model_proxy_socket_path, 0o600, follow_symlinks=False) + + async def close(self) -> None: + if self._model_server is not None: + self._model_server.close() + await self._model_server.wait_closed() + if self._model_bridge is not None: + self._model_bridge.close() + try: + metadata = self.model_proxy_socket_path.lstat() + if stat.S_ISSOCK(metadata.st_mode) and metadata.st_uid == os.getuid(): + self.model_proxy_socket_path.unlink() + except FileNotFoundError: + pass + + async def _handle_model_proxy( + self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter + ) -> None: + try: + async with asyncio.timeout(self.timeout): + request = await _read_frame(reader, MAXIMUM_FRAME_BYTES) + bridge = self._model_bridge + if bridge is None: + raise ProtocolError("model bridge is unavailable") + response = await bridge.exchange(request) + await _write_frame(writer, response) + if await reader.read(1): + raise ProtocolError("model proxy request contains trailing data") + except (ProtocolError, TimeoutError, OSError, asyncio.IncompleteReadError): + pass + finally: + writer.close() + try: + await writer.wait_closed() + except OSError: + pass + + async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + try: + async with asyncio.timeout(self.timeout): + if self.client_name not in _peer_name(writer): + raise ProtocolError("client identity differs") + control = _decode_object(await _read_frame(reader, MAXIMUM_CONTROL_BYTES)) + if control.get("protocol_version") != PROTOCOL: + raise ProtocolError("remote protocol differs") + operation = control.get("operation") + capability = control.get("capability") + if operation == "proxy": + if set(control) != {"protocol_version", "operation", "capability"} or capability not in { + CHECKER_CAPABILITY, INTAKE_CAPABILITY + }: + raise ProtocolError("proxy request is invalid") + await self._proxy(reader, writer) + elif operation == "model_bridge": + if set(control) != {"protocol_version", "operation", "capability"} or capability != CHECKER_CAPABILITY: + raise ProtocolError("model bridge request is invalid") + await self._serve_model_bridge(reader, writer) + elif operation == "execute": + if capability != CHECKER_CAPABILITY: + raise ProtocolError("execute capability differs") + await self._execute(control, reader, writer) + else: + raise ProtocolError("remote operation is invalid") + except (ProtocolError, TimeoutError, OSError, ssl.SSLError, asyncio.IncompleteReadError): + pass + finally: + writer.close() + try: + await writer.wait_closed() + except (OSError, ssl.SSLError): + pass + + async def _serve_model_bridge( + self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter + ) -> None: + bridge = ModelBridge(reader, writer) + previous = self._model_bridge + self._model_bridge = bridge + if previous is not None: + previous.close() + await _write_frame( + writer, + json.dumps( + { + "protocol_version": PROTOCOL, + "operation": "model_bridge", + "status": "ready", + }, + separators=(",", ":"), + ).encode(), + ) + try: + await bridge.closed.wait() + finally: + if self._model_bridge is bridge: + self._model_bridge = None + + async def _proxy(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + native_reader, native_writer = await asyncio.open_unix_connection(self.socket_path) + + async def copy(source: asyncio.StreamReader, target: asyncio.StreamWriter) -> None: + while chunk := await source.read(64 * 1024): + target.write(chunk) + await target.drain() + + tasks = { + asyncio.create_task(copy(reader, native_writer)), + asyncio.create_task(copy(native_reader, writer)), + } + done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + for task in pending: + task.cancel() + await asyncio.gather(*done, *pending, return_exceptions=True) + native_writer.close() + try: + await native_writer.wait_closed() + except OSError: + pass + + async def _execute( + self, + control: dict[str, Any], + reader: asyncio.StreamReader, + writer: asyncio.StreamWriter, + ) -> None: + expected = { + "protocol_version", "operation", "capability", "service_request", + "manifest_byte_count", "file_count", "total_byte_count", + } + if set(control) != expected or type(control["service_request"]) is not dict: + raise ProtocolError("execute request is invalid") + request = control["service_request"] + if request.get("operation") not in {"execute", "locate_forge_change"}: + raise ProtocolError("service operation is invalid") + grant = request.get("grant") + checked = request.get("request") + if type(grant) is not dict or type(checked) is not dict: + raise ProtocolError("service request binding is invalid") + grant_id = grant.get("grant_id") + binding = grant.get("binding_digest") + if ( + type(grant_id) is not str + or _GRANT_ID.fullmatch(grant_id) is None + or type(binding) is not str + or _SHA256.fullmatch(binding) is None + ): + raise ProtocolError("grant reference is invalid") + raw_manifest = await _read_frame(reader, MAXIMUM_CONTROL_BYTES) + if len(raw_manifest) != control["manifest_byte_count"]: + raise ProtocolError("manifest byte count differs") + manifest = _decode_object(raw_manifest) + body = dict(manifest) + supplied_binding = body.pop("binding_digest", None) + canonical = json.dumps( + body, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False + ).encode() + observed_binding = "sha256:" + hashlib.sha256(canonical).hexdigest() + if ( + supplied_binding != binding + or observed_binding != binding + or manifest.get("grant_id") != grant_id + or manifest.get("request_digest") != checked.get("request_digest") + ): + raise ProtocolError("material binding differs") + files = _manifest_files(manifest) + if ( + type(control["file_count"]) is not int + or control["file_count"] != len(files) + or type(control["total_byte_count"]) is not int + or control["total_byte_count"] != sum(item[1] for item in files) + or control["total_byte_count"] > MAXIMUM_MATERIAL_BYTES + ): + raise ProtocolError("material bounds differ") + async with self._execution: + await self._stage_and_execute( + grant_id, raw_manifest, manifest, files, request, reader, writer + ) + + async def _stage_and_execute( + self, + grant_id: str, + raw_manifest: bytes, + manifest: dict[str, Any], + files: tuple[tuple[PurePosixPath, int, str, bool], ...], + request: dict[str, Any], + reader: asyncio.StreamReader, + writer: asyncio.StreamWriter, + ) -> None: + target = self.workspaces / grant_id + incoming = self.workspaces / f".incoming-{uuid.uuid4().hex}" + native_writer: asyncio.StreamWriter | None = None + if target.exists(): + raise ProtocolError("grant is already active") + incoming.mkdir(mode=0o700) + try: + _mkdir_inventory(incoming, manifest) + for relative, expected_count, expected_digest, executable in files: + path = incoming / Path(*relative.parts) + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + digest, count = hashlib.sha256(), 0 + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + while chunk := await _read_frame(reader, 64 * 1024, allow_empty=True): + count += len(chunk) + if count > expected_count: + raise ProtocolError("material file is too large") + digest.update(chunk) + _write_descriptor(descriptor, chunk) + if count != expected_count or "sha256:" + digest.hexdigest() != expected_digest: + raise ProtocolError("material file content differs") + os.fsync(descriptor) + finally: + os.close(descriptor) + os.chmod(path, 0o500 if executable else 0o400, follow_symlinks=False) + manifest_path = incoming / ".external-checker-grant.json" + descriptor = os.open(manifest_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o400) + try: + _write_descriptor(descriptor, raw_manifest) + os.fsync(descriptor) + finally: + os.close(descriptor) + _seal_directories(incoming) + os.chmod(incoming, 0o700, follow_symlinks=False) + os.rename(incoming, target) + native_reader, native_writer = await asyncio.open_unix_connection(self.socket_path) + encoded = json.dumps( + request, ensure_ascii=False, allow_nan=False, separators=(",", ":") + ).encode() + await _write_frame(native_writer, encoded) + response_task = asyncio.create_task(_read_frame(native_reader, MAXIMUM_FRAME_BYTES)) + disconnect_task = asyncio.create_task(reader.read(1)) + done, _ = await asyncio.wait( + {response_task, disconnect_task}, return_when=asyncio.FIRST_COMPLETED + ) + if disconnect_task in done: + response_task.cancel() + raise ProtocolError("remote client disconnected") + disconnect_task.cancel() + response = await response_task + await _write_frame(writer, response) + finally: + if native_writer is not None: + native_writer.close() + try: + await native_writer.wait_closed() + except OSError: + pass + _remove_tree(target) + _remove_tree(incoming) + + +async def _main(config_path: Path) -> None: + raw = config_path.read_bytes() + if len(raw) > 64 * 1024: + raise ValueError("remote node configuration is too large") + node = RemoteNode(_decode_object(raw)) + await node.start_model_proxy() + try: + server = await asyncio.start_server( + node.handle, + node.host, + node.port, + ssl=node.ssl_context, + limit=MAXIMUM_FRAME_BYTES + 4, + ) + async with server: + await server.serve_forever() + finally: + await node.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + arguments = parser.parse_args() + asyncio.run(_main(arguments.config)) diff --git a/external_checkers/workstream-checker-service/src/main.rs b/external_checkers/workstream-checker-service/src/main.rs index dd83905d1..87fcea473 100644 --- a/external_checkers/workstream-checker-service/src/main.rs +++ b/external_checkers/workstream-checker-service/src/main.rs @@ -885,6 +885,10 @@ fn serve_connection( { return match smol::serve_pre(config, stream, bytes) { Err(error) if error == UNSETTLED_RESOURCE_ERROR => Err(error), + Err(error) => { + eprintln!("PRE request rejected: {error}"); + Ok(()) + } _ => Ok(()), }; } From 9defe33b2028c14befe750b9466bcaeb86ca55cf Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:56:08 +0100 Subject: [PATCH 259/513] Record runner integration and outstanding security findings --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 418ac9dfb..c21685b6c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8662,3 +8662,19 @@ Structure, Ruff, diff and Commitrail checks passed; scoped ARCH/SEC reported no finding. These are real HTTP/SQL with controlled guest transport, not native provider or full deployed journey qualification. Other obsolete preparation callers remain outside this two-case retirement. + +The two-case QA/test-delta review closed PASS WITH LOW RISKS at clean59abae501; +QA-REVISION-REJECTION-001 is resolved. Runner commitdc7fe4b4a was integrated as +179395685 without conflicts. Import-only application/worker checks passed with +an explicit memory broker URL (not broker delivery qualification). The runner +owner reports real mTLS health, native POST and streamed ZIP PRE with exact +bindings and empty workspaces afterward; expected checker failures in those +smokes are not successful governed acceptance. + +Frozen runner ARCH/SEC review requires three repairs before app deployment: +REMOTE-MODEL-01 binds callbacks to the issuing connection instead of a global +replaceable app bridge; REMOTE-PROXY-02 drains copy tasks and closes the native +socket on cancellation/timeout; REMOTE-STAGE-03 reconciles or safely quarantines +staged files left by process death before admitting work. The runner owner owns +the batch repair and regression tests. No app configuration or restart occurred. +These are concrete runtime findings; no native production-ready claim is made. From 2b318e914ebfaa626908bec67c73ad062e83178d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:59:22 +0100 Subject: [PATCH 260/513] Verify unrouted revisions refuse the public ZIP body --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 +++ .../test_submission_predecessor_custody.py | 66 ++++++++++++------- 2 files changed, 49 insertions(+), 25 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c21685b6c..6aad1e5df 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8678,3 +8678,11 @@ socket on cancellation/timeout; REMOTE-STAGE-03 reconciles or safely quarantines staged files left by process death before admitting work. The runner owner owns the batch repair and regression tests. No app configuration or restart occurred. These are concrete runtime findings; no native production-ready claim is made. + +Next test-only retirement replaces the remaining no-routed-cause preparation +case with raw-ZIP HTTP. Allowed: that case in test_submission_predecessor_custody +and this record. Preserve refusal before body/upload/PRE/reservation, unchanged +ART facts, and successful fresh-key acceptance/finalization after the real +routing owner creates revision context, with exact remediation lineage. No +production or runner edits. Verify the one real PostgreSQL case, Ruff/diff, +and focused QA review; existing authority checks remain unchanged. diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 35dd842d8..8cfbd9d49 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -298,35 +298,51 @@ async def test_real_replacement_compares_consumed_predecessor_and_replays_exactl async def test_replacement_without_routed_cause_denied_before_bytes( tmp_path, isolated_database_env, monkeypatch, ): - provider_writes = _trace_provider_writes(monkeypatch) + from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.test_public_submission_intake import _client + async with remediation_source(tmp_path, isolated_database_env) as h: + writes = _trace_provider_writes(monkeypatch, operations=( + "begin_source_upload", "upload_source_part", "complete_source_upload", "put", "observe_put_result")) before_route = await _snapshot(h) - provider_writes.clear() - with pytest.raises( - SubmissionBundlePreparationRejected, - match="submission_bundle_preparation_context_changed", - ): - await _prepare(h, replace( - _replacement_request( - h, revision_archive(h.data), predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ), - byte_source=_forbidden_bytes(), - )) - assert await _snapshot(h) == before_route - assert provider_writes == [] - - source_id = await _fixture_revision_context(h) - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, h.actor_context, - _replacement_request( - h, revision_archive(h.data), predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ), - ) + data = revision_archive(h.data) + async with _client(h, monkeypatch, isolated_database_env) as client: + settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + route = f"/api/v1/tasks/{h.request.task_id}/submissions" + headers = { + 'Content-Type': 'application/zip', 'Idempotency-Key': str(new_record_id()), + 'X-Task-Assignment-Id': str(h.request.assignment_id), + 'X-Predecessor-Submission-Id': str(h.created.submission_id), + } + async with h.factory() as session: + before_operations = await session.scalar(text('SELECT count(*) FROM submission_intake_operations')) + async def forbidden_upload(*_args, **_kwargs): + pytest.fail('unrouted replacement reached source upload') + with monkeypatch.context() as guard: + guard.setattr(ForegroundSourceUpload, 'receive', forbidden_upload) + refused = await client.post(route, headers=headers, content=_forbidden_bytes()) + assert refused.status_code == 404, refused.text + assert refused.json()['error']['code'] == 'submission_unavailable' + assert await _snapshot(h) == before_route + assert writes == [] and calls == [] and not errors + async with h.factory() as session: + assert await session.scalar(text('SELECT count(*) FROM submission_intake_operations')) == before_operations + source_id = await _fixture_revision_context(h) + accepted = await client.post(route, headers=_revision_upload_headers(h), content=data) + assert accepted.status_code == 202, accepted.text + assert len(calls) == 1 and not errors, errors + assert writes == ['begin_source_upload', 'upload_source_part', 'complete_source_upload'] + submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( + operation_id=UUID(accepted.json()['operation_id']), store=h.store.wrapped, + namespace=h.namespace, settings=settings)) async with h.factory() as session: - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) + admission = (await session.execute(text( + 'SELECT checker_remediation_manifest_id,status FROM submission_bundle_admissions ' + 'WHERE consumed_by_submission_id=:id'), {'id': submission_id})).one() assert admission.checker_remediation_manifest_id == source_id + assert admission.status == 'consumed' async def test_unchanged_replacement_archive_or_manifest_denied( From 9836bfcd53a4b4522fe593d872fab6cb0dd390e8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 12:59:58 +0100 Subject: [PATCH 261/513] Record public unrouted revision continuation proof --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6aad1e5df..abe70d548 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8686,3 +8686,12 @@ ART facts, and successful fresh-key acceptance/finalization after the real routing owner creates revision context, with exact remediation lineage. No production or runner edits. Verify the one real PostgreSQL case, Ruff/diff, and focused QA review; existing authority checks remain unchanged. + +The public no-route control and routed positive continuation passed together +in30.30s on the integrated runner code; isolated metadata +/tmp/submission-public-unrouted-revision.json confirms schema0090 and complete +cleanup. The launcher recorded9defe33b2 with the final test worktree before +commit2b318e914. The positive path reaches consumed admission through T5 with +the exact routing manifest, not an old ready-only preparation. Ruff/diff and +Commitrail checks passed. This remains controlled runtime evidence, not live +AWS/native public acceptance. From 02920f9fff2378a4446a042aa228b9d1e028ca3a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:09:30 +0100 Subject: [PATCH 262/513] Replace private predecessor probe with public custody assertions --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 18 +++++ .../test_submission_predecessor_custody.py | 79 ++----------------- 2 files changed, 24 insertions(+), 73 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index abe70d548..fa8260bcd 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8695,3 +8695,21 @@ commit2b318e914. The positive path reaches consumed admission through T5 with the exact routing manifest, not an old ready-only preparation. Ruff/diff and Commitrail checks passed. This remains controlled runtime evidence, not live AWS/native public acceptance. + +Retire the implementation-only _load_predecessor probe in the same predecessor +test module. Its five-call count belongs to the removed preparation workflow; +raw/semantic refusal and secret/warning behavior are retained in the reviewed +public cases above, and acceptance/replay/consumed lineage in +test_real_replacement_compares_consumed_predecessor_and_replays_exactly. Move +the exact predecessor ID/version/raw hash/semantic hash assertions into that +public case's persisted PRE context before deleting the private probe/import. +Allowed: this test module and record only. No production/retained data changes. +Verify both review-policy parameters of the retained public replacement test, +Ruff/diff, and QA assertion-preservation review. Other old writer callers remain. + +Both retained public replacement/replay policy cases passed in57.17s with the +explicit predecessor context assertions. Receipt +/tmp/submission-public-predecessor-context.json records schema0090 and complete +PostgreSQL/MinIO cleanup; its launcher HEAD was9836bfcd5 with these test edits. +This removes only the duplicated private-method probe; the remaining old SQL +reservation/admission fixtures still require migration before writer retirement. diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 8cfbd9d49..8769d2b62 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -27,7 +27,6 @@ from app.modules.actors.api.service_identities import ServiceIdentity from app.interfaces.artifacts import ArtifactStoreUnavailableError from app.modules.artifacts.api import ( - SubmissionBundlePreparationCheckFailed, SubmissionBundlePreparationRejected, SubmissionBundlePreparationRequest, ) @@ -39,9 +38,6 @@ from app.modules.artifacts.models import ( SubmissionBundleAdmission, ) -from app.modules.artifacts.submission_admission import ( - PreparedSubmissionBundlePreparationCommand, -) from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.checkers.api.execution import CheckerExecutionUnavailable from app.modules.tasks.api.submission_context import ( @@ -61,8 +57,7 @@ from tests.tasks.post_submit_routing.support import next_request, revision_archive from tests.tasks.submission_lineage_support import _verified_admission from tests.selected_predecessor_fixtures import ( - _snapshot, _secret_archive, _assert_default_failure, - _queued_selected_body, _insert_selected_reservation, + _snapshot, _secret_archive, _queued_selected_body, _insert_selected_reservation, ) @@ -275,6 +270,11 @@ async def test_real_replacement_compares_consumed_predecessor_and_replays_exactl assert admission.checker_remediation_manifest_id == source_id assert admission.pre_submit_evidence_set_id is None assert selected is not None and selected.eligible + assert selected.request_json["default_context"]["predecessor"] == { + "submission_id": str(predecessor_id), "submission_version": 1, + "archive_sha256": predecessor_admission.archive_sha256, + "semantic_manifest_sha256": predecessor_admission.semantic_manifest_sha256, + } lineage = selected.request_json["admission_lineage"] assert lineage["predecessor_submission_id"] == str(predecessor_id) assert lineage["predecessor_submission_version"] == 1 @@ -417,73 +417,6 @@ async def test_blocked_replacement_precheck_preserves_revision_state( assert provider_writes == [] -async def test_replacement_loads_exact_consumed_predecessor( - tmp_path, isolated_database_env, monkeypatch, -): - loaded = [] - original_load = PreparedSubmissionBundlePreparationCommand._load_predecessor - - async def traced_load(self, task_context): - predecessor = await original_load(self, task_context) - loaded.append((task_context.predecessor, predecessor)) - return predecessor - - monkeypatch.setattr( - PreparedSubmissionBundlePreparationCommand, "_load_predecessor", traced_load, - ) - async with remediation_source(tmp_path, isolated_database_env) as h: - predecessor_id = h.created.submission_id - await _fixture_revision_context(h) - loaded.clear() - for data in (h.data, _same_semantics_different_archive(h.data)): - with pytest.raises(SubmissionBundlePreparationCheckFailed): - await _prepare(h, _replacement_request( - h, data, predecessor_id=predecessor_id, - idempotency_key=new_record_id(), - )) - changed_data = revision_archive(h.data) - baseline = await _snapshot(h) - secret_request = _replacement_request( - h, _secret_archive(changed_data), predecessor_id=predecessor_id, - idempotency_key=new_record_id(), - ) - with pytest.raises(SubmissionBundlePreparationCheckFailed) as blocked: - await _prepare(h, secret_request) - await _assert_default_failure( - h, secret_request, blocked.value, baseline, "high_confidence_secret_detected", - ) - idempotency_key = new_record_id() - admission_id = await _verified_admission( - h.factory, h.store, h.namespace, h.settings, h.actor_context, - _replacement_request( - h, changed_data, predecessor_id=predecessor_id, - idempotency_key=idempotency_key, - ), - ) - replay = await _prepare(h, _replacement_request( - h, changed_data, predecessor_id=predecessor_id, - idempotency_key=idempotency_key, - )) - assert replay.admission_id == admission_id - async with h.factory() as session: - predecessor_admission = await session.get( - SubmissionBundleAdmission, str(h.creation_request.admission_id) - ) - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert admission.status == "ready" - assert len(loaded) == 5 - for task_predecessor, artifact_predecessor in loaded: - assert task_predecessor.submission_id == predecessor_id - assert task_predecessor.version == 1 - assert artifact_predecessor.submission_id == predecessor_id - assert artifact_predecessor.submission_version == 1 - assert artifact_predecessor.archive_sha256 == predecessor_admission.archive_sha256 - assert ( - artifact_predecessor.semantic_manifest_sha256 - == predecessor_admission.semantic_manifest_sha256 - ) - - async def test_replacement_dispatch_sql_rejects_cause_and_receipt_substitution( tmp_path, isolated_database_env, monkeypatch, ): From b976a7d2d23d4fd335acb9cb26d4f5f2380e104a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:13:50 +0100 Subject: [PATCH 263/513] Verify public replacement refusal for nonremediation outcomes --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 18 +++++++ .../test_submission_predecessor_custody.py | 51 ++++++++++++------- 2 files changed, 51 insertions(+), 18 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index fa8260bcd..8db646bd7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8713,3 +8713,21 @@ explicit predecessor context assertions. Receipt PostgreSQL/MinIO cleanup; its launcher HEAD was9836bfcd5 with these test edits. This removes only the duplicated private-method probe; the remaining old SQL reservation/admission fixtures still require migration before writer retirement. + +Next bounded test migration: the infrastructure-failed/allow-review POST cases +must still refuse a replacement before reading bytes. Allowed files: predecessor +custody test and this record. Replace their obsolete preparation call with public +raw-ZIP HTTP; retain real POST outcomes, exact public refusal, unchanged ART and +intake counts, no source upload or PRE execution. No production, schema or runner +changes. Medium workflow-test risk; run both parameters on isolated PostgreSQL, +Ruff/diff and focused QA review. Human focus is authority before body consumption. + +QA closed the preceding private-probe retirement PASS WITH LOW RISKS at02920f9ff: +all four predecessor-field substitutions fail the new public assertion. +The nonremediation pair first exposed a stale fixture: failing ArtifactStore.open +no longer fails POST because current retained inputs use open_source. Moved the +injected failure to that port and asserted it was reached. Both public refusal +cases then passed in45.39s; /tmp/submission-public-nonremediation-repair.json +records schema0090 and complete database/MinIO cleanup (launcher02920f9ff with +final test edits). Structure, Ruff and diff checks passed. This is controlled +storage failure plus real HTTP/SQL authority proof, not live provider acceptance. diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 8769d2b62..5b0fdc4e1 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -836,18 +836,26 @@ async def test_nonremediation_outcome_cannot_authorize_replacement_before_bytes( monkeypatch, outcome, ): - provider_writes = _trace_provider_writes(monkeypatch) + from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime + from tests.tasks.test_public_submission_intake import _client + + provider_writes = _trace_provider_writes(monkeypatch, operations=( + "begin_source_upload", "upload_source_part", "complete_source_upload", "put", "observe_put_result")) async with material_fixture(tmp_path, isolated_database_env) as h: await reserve(h) + failed_reads = [] with monkeypatch.context() as failure: if outcome == "infrastructure_failed": async def unavailable(*_args, **_kwargs): + failed_reads.append(True) raise ArtifactStoreUnavailableError("selected input unavailable") yield b"" # Preserve ArtifactStore.open's async-iterator port. - failure.setattr(h.store, "open", unavailable) + failure.setattr(h.store, "open_source", unavailable) result = await live_executor(h).evaluate_post_submission(h.request) + assert bool(failed_reads) == (outcome == "infrastructure_failed") assert result.outcome == outcome async with h.factory() as session: run = await session.get(CheckerRun, str(result.attempt_id)) @@ -857,24 +865,31 @@ async def unavailable(*_args, **_kwargs): ) before = await _snapshot(h) provider_writes.clear() - with pytest.raises( - SubmissionBundlePreparationRejected, - match="submission_bundle_preparation_context_changed", - ): - await _prepare( - h, - replace( - _replacement_request( - h, - revision_archive(h.data), - predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ), - byte_source=_forbidden_bytes(), - ), - ) + async with h.factory() as session: + before_operations = await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) + + async def forbidden_upload(*_args, **_kwargs): + pytest.fail("nonremediation replacement reached source upload") + + async with _client(h, monkeypatch, isolated_database_env) as client: + _, errors, calls = await _revision_http_runtime( + h, client, tmp_path, monkeypatch, revision_archive(h.data)) + monkeypatch.setattr(ForegroundSourceUpload, "receive", forbidden_upload) + refused = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers={ + "Content-Type": "application/zip", "Idempotency-Key": str(new_record_id()), + "X-Task-Assignment-Id": str(h.request.assignment_id), + "X-Predecessor-Submission-Id": str(h.created.submission_id), + }, content=_forbidden_bytes()) + assert refused.status_code == 404, refused.text + assert refused.json()["error"]["code"] == "submission_unavailable" + assert calls == [] and not errors assert await _snapshot(h) == before assert provider_writes == [] + async with h.factory() as session: + assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == before_operations + await no_economic_effects(session) async def test_source_superseded_during_zip_read_stops_before_art_effects( From 8fa9ae12cf6630fb1934203f14840f6fa66cf587 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:13:42 +0100 Subject: [PATCH 264/513] Bind runner callbacks to each execution --- .../changes/flow-self-service-signup.md | 9 +- backend/app/adapters/checkers/__init__.py | 3 + .../app/adapters/checkers/external_service.py | 71 ++- .../app/adapters/checkers/model_runtime.py | 14 +- .../adapters/checkers/remote_model_bridge.py | 161 ------ backend/app/core/config.py | 2 - backend/scripts/test_lane_catalogue.py | 1 + backend/tests/checkers/external/support.py | 58 ++ .../checkers/external/test_forge_locator.py | 50 +- .../checkers/external/test_model_transport.py | 40 +- .../checkers/external/test_remote_node.py | 289 ++++++++-- .../tests/checkers/external/test_runtime.py | 7 +- backend/tests/test_ci_lane_catalogue.py | 1 + deploy/hosted/README.md | 391 ++++---------- deploy/hosted/compose.yml | 21 - deploy/hosted/preflight.py | 501 ------------------ deploy/hosted/release.env.example | 4 +- .../deploy/runner-qualification-20261124.md | 95 ++++ external_checkers/remote_node.py | 304 +++++++---- 19 files changed, 853 insertions(+), 1169 deletions(-) delete mode 100644 backend/app/adapters/checkers/remote_model_bridge.py create mode 100644 external_checkers/deploy/runner-qualification-20261124.md diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index 902d60c4b..4d7c60484 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -427,9 +427,12 @@ certificate. PRE source and POST material bytes cross that boundary in bounded frames; no API-host filesystem path crosses it. The runner verifies exact request/source/grant bindings, stages one private runner-local workspace, invokes the existing native Unix service, and removes the exact session on success, -failure, timeout or disconnect. A persistent outbound app model-proxy bridge -preserves request-bound model callbacks without opening inbound access to the -app host. Future managed providers must implement the same typed task/source/ +failure, timeout or disconnect. Model, trial-evidence and setup-model callback +frames are multiplexed over the exact invocation's authenticated execute +connection; losing that app-process owner fails the callback and stops native +execution without selecting another replica. Startup refuses stale staged +material until the stopped native service and exact bounded residue have been +reconciled. Future managed providers must implement the same typed task/source/ result contract; no E2B, Daytona or other vendor is claimed supported here. Live evidence on instance `i-0936c305f8f67d835` proves m7i.large nested KVM, diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py index 7621f3aeb..95df6d315 100644 --- a/backend/app/adapters/checkers/__init__.py +++ b/backend/app/adapters/checkers/__init__.py @@ -61,6 +61,7 @@ def external_checker_execution_factory( ca_path: Path, certificate_path: Path, private_key_path: Path, + model_proxy_socket_path: Path | None, timeout_seconds: float, ) -> ExternalServiceAdapterFactory[RemoteTlsExternalCheckerAdapter]: """Compose the sole dedicated-node external checker adapter factory.""" @@ -77,6 +78,7 @@ def external_checker_execution_factory( ca_path=ca_path, certificate_path=certificate_path, private_key_path=private_key_path, + model_proxy_socket_path=model_proxy_socket_path, timeout_seconds=timeout_seconds, source_contracts=selected_pre_submit_source_contracts(), ), @@ -173,6 +175,7 @@ def configured_external_checker_execution_factory(settings): ca_path=settings.external_runner_ca_path, certificate_path=settings.external_runner_certificate_path, private_key_path=settings.external_runner_private_key_path, + model_proxy_socket_path=settings.checker_model_proxy_socket, timeout_seconds=float(settings.external_checker_service_timeout_seconds), ) diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py index 8a365f304..bff3fb8d1 100644 --- a/backend/app/adapters/checkers/external_service.py +++ b/backend/app/adapters/checkers/external_service.py @@ -9,6 +9,7 @@ import hashlib from datetime import datetime, timezone from pathlib import Path +import re import ssl import struct from typing import Literal @@ -57,6 +58,7 @@ _REMOTE_PROTOCOL = "workstream.remote_runner.v1" _MAXIMUM_RESPONSE_BYTES = MAX_RESULT_BYTES + 16_384 _EXECUTION_OVERHEAD_SECONDS = EXTERNAL_CHECKER_EXECUTION_CLEANUP_MARGIN_MS / 1000 +_CHANNEL_ID = re.compile(r"[0-9a-f]{32}") class RemoteTlsExternalCheckerAdapter: @@ -71,6 +73,7 @@ def __init__( ca_path: Path, certificate_path: Path, private_key_path: Path, + model_proxy_socket_path: Path | None, timeout_seconds: float, source_contracts: SelectedPreSubmitSourceContracts, ) -> None: @@ -87,6 +90,8 @@ def __init__( or any(not path.is_absolute() or path.is_symlink() for path in ( ca_path, certificate_path, private_key_path )) + or model_proxy_socket_path is not None + and (not model_proxy_socket_path.is_absolute() or model_proxy_socket_path.is_symlink()) or type(timeout_seconds) is not float or not 0.1 <= timeout_seconds <= 3_700.0 ): @@ -96,6 +101,7 @@ def __init__( self._ca_path = ca_path self._certificate_path = certificate_path self._private_key_path = private_key_path + self._model_proxy_socket_path = model_proxy_socket_path self._timeout_seconds = timeout_seconds self._identity = ExternalServiceAdapterIdentity( EXTERNAL_CHECKER_CAPABILITY_KEY, @@ -153,6 +159,24 @@ async def _proxy_connection(self) -> tuple[asyncio.StreamReader, asyncio.StreamW await self._send_frame(writer, control) return reader, writer + @staticmethod + async def _read_frame(reader: asyncio.StreamReader, maximum: int) -> bytes: + size = struct.unpack(">I", await reader.readexactly(4))[0] + if size == 0 or size > maximum: + raise ValueError("remote runner frame is invalid") + return await reader.readexactly(size) + + async def _exchange_local_callback(self, payload: bytes) -> bytes: + if self._model_proxy_socket_path is None: + raise ValueError("model proxy callback is unavailable") + reader, writer = await asyncio.open_unix_connection(self._model_proxy_socket_path) + try: + await self._send_frame(writer, payload) + return await self._read_frame(reader, 64 * 1024 * 1024) + finally: + writer.close() + await await_cancellation_resistant(writer.wait_closed()) + async def execute_pre( self, lease: SelectedPreSubmitLeaseFacts, grant: ExternalPreSubmitSourceGrant, ) -> SelectedPreSubmitInvocationResult: @@ -329,15 +353,48 @@ async def _exchange(self, request, grant, *, model_grant, locate): await await_cancellation_resistant(stream.aclose()) writer.write(struct.pack(">I", 0)) await writer.drain() - size = struct.unpack(">I", await reader.readexactly(4))[0] - if size == 0 or size > _MAXIMUM_RESPONSE_BYTES: - raise ExternalServiceProtocolError(self._identity) - raw = await reader.readexactly(size) - if await reader.read(1): - raise ExternalServiceProtocolError(self._identity) + while True: + header = json.loads(await self._read_frame(reader, 16_384)) + if ( + type(header) is not dict + or header.get("protocol_version") != _REMOTE_PROTOCOL + ): + raise ValueError("remote runner response header is invalid") + operation = header.get("operation") + if operation == "callback_request": + if ( + set(header) + != {"protocol_version", "operation", "channel_id"} + or type(header["channel_id"]) is not str + or _CHANNEL_ID.fullmatch(header["channel_id"]) is None + ): + raise ValueError("remote callback header is invalid") + callback = await self._read_frame(reader, 64 * 1024 * 1024) + response = await self._exchange_local_callback(callback) + await self._send_frame( + writer, + json.dumps( + { + "protocol_version": _REMOTE_PROTOCOL, + "operation": "callback_response", + "channel_id": header["channel_id"], + }, + separators=(",", ":"), + ).encode(), + ) + await self._send_frame(writer, response) + continue + if operation != "execution_result" or set(header) != { + "protocol_version", "operation" + }: + raise ValueError("remote execution result header is invalid") + raw = await self._read_frame(reader, _MAXIMUM_RESPONSE_BYTES) + if await reader.read(1): + raise ValueError("remote execution result contains trailing data") + break finally: writer.close() - await writer.wait_closed() + await await_cancellation_resistant(writer.wait_closed()) except ExternalServiceProtocolError: raise except (TimeoutError, OSError, asyncio.IncompleteReadError) as exc: diff --git a/backend/app/adapters/checkers/model_runtime.py b/backend/app/adapters/checkers/model_runtime.py index 2cf86a836..60a208fed 100644 --- a/backend/app/adapters/checkers/model_runtime.py +++ b/backend/app/adapters/checkers/model_runtime.py @@ -30,7 +30,6 @@ trial_evidence_reservations, ) from app.adapters.checkers.model_proxy_transport import ModelProxyTransport -from app.adapters.checkers.remote_model_bridge import RemoteModelProxyBridge from app.adapters.checkers.trial_proxy import CheckerTrialProxy from app.modules.checkers.api.trial_profiles import load_trial_authority_manifest from app.adapters.model_usage import setup_model_usage_service @@ -161,18 +160,7 @@ def reservations(session, request): trial_handler=trial_proxy.handle if trial_proxy is not None else None, shutdown_timeout_seconds=7200.0, ): - if settings.external_runner_host is None: - raise ValueError("model proxy requires the configured external runner") - async with RemoteModelProxyBridge( - host=settings.external_runner_host, - port=settings.external_runner_port, - server_name=settings.external_runner_server_name, - ca_path=settings.external_runner_ca_path, - certificate_path=settings.external_runner_certificate_path, - private_key_path=settings.external_runner_private_key_path, - socket_path=settings.checker_model_proxy_socket, - ): - yield + yield finally: if manager is not None: manager.close() diff --git a/backend/app/adapters/checkers/remote_model_bridge.py b/backend/app/adapters/checkers/remote_model_bridge.py deleted file mode 100644 index 773c97d5b..000000000 --- a/backend/app/adapters/checkers/remote_model_bridge.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Outbound authenticated bridge for runner-local checker model callbacks.""" - -from __future__ import annotations - -import asyncio -import json -from pathlib import Path -import ssl -import struct - - -_PROTOCOL = "workstream.remote_runner.v1" -_MAXIMUM_FRAME_BYTES = 64 * 1024 * 1024 - - -async def _read_frame(reader: asyncio.StreamReader) -> bytes: - size = struct.unpack(">I", await reader.readexactly(4))[0] - if size == 0 or size > _MAXIMUM_FRAME_BYTES: - raise ValueError("remote model bridge frame is invalid") - return await reader.readexactly(size) - - -async def _write_frame(writer: asyncio.StreamWriter, body: bytes) -> None: - if not body or len(body) > _MAXIMUM_FRAME_BYTES: - raise ValueError("remote model bridge frame is invalid") - writer.write(struct.pack(">I", len(body)) + body) - await writer.drain() - - -class RemoteModelProxyBridge: - """Reconnect one app-owned Unix model proxy to the dedicated runner edge.""" - - def __init__( - self, - *, - host: str, - port: int, - server_name: str, - ca_path: Path, - certificate_path: Path, - private_key_path: Path, - socket_path: Path, - ) -> None: - self._host, self._port, self._server_name = host, port, server_name - self._ca_path = ca_path - self._certificate_path = certificate_path - self._private_key_path = private_key_path - self._socket_path = socket_path - self._stopping = asyncio.Event() - self._task: asyncio.Task[None] | None = None - - def _tls_context(self) -> ssl.SSLContext: - context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=str(self._ca_path)) - context.minimum_version = ssl.TLSVersion.TLSv1_3 - context.check_hostname = True - context.load_cert_chain( - certfile=str(self._certificate_path), keyfile=str(self._private_key_path) - ) - return context - - async def start(self) -> None: - if self._task is not None: - raise RuntimeError("remote model bridge is already started") - self._task = asyncio.create_task(self._run(), name="remote-model-proxy-bridge") - - async def close(self) -> None: - self._stopping.set() - if self._task is not None: - self._task.cancel() - await asyncio.gather(self._task, return_exceptions=True) - self._task = None - - async def __aenter__(self) -> "RemoteModelProxyBridge": - await self.start() - return self - - async def __aexit__(self, *_: object) -> None: - await self.close() - - async def _run(self) -> None: - delay = 0.25 - while not self._stopping.is_set(): - try: - await self._session() - delay = 0.25 - except asyncio.CancelledError: - raise - except (OSError, ssl.SSLError, asyncio.IncompleteReadError, ValueError): - try: - await asyncio.wait_for(self._stopping.wait(), timeout=delay) - except TimeoutError: - pass - delay = min(5.0, delay * 2) - - async def _session(self) -> None: - reader, writer = await asyncio.open_connection( - self._host, - self._port, - ssl=self._tls_context(), - server_hostname=self._server_name, - ) - try: - control = json.dumps( - { - "protocol_version": _PROTOCOL, - "operation": "model_bridge", - "capability": "external_checker_execution", - }, - separators=(",", ":"), - ).encode() - await _write_frame(writer, control) - acknowledgement = json.loads(await _read_frame(reader)) - if acknowledgement != { - "protocol_version": _PROTOCOL, - "operation": "model_bridge", - "status": "ready", - }: - raise ValueError("remote model bridge acknowledgement is invalid") - while not self._stopping.is_set(): - header = json.loads(await _read_frame(reader)) - if ( - type(header) is not dict - or set(header) != {"protocol_version", "operation", "channel_id"} - or header.get("protocol_version") != _PROTOCOL - or header.get("operation") != "model_request" - or type(header.get("channel_id")) is not str - ): - raise ValueError("remote model request header is invalid") - request = await _read_frame(reader) - response = await self._exchange_local(request) - response_header = json.dumps( - { - "protocol_version": _PROTOCOL, - "operation": "model_response", - "channel_id": header["channel_id"], - }, - separators=(",", ":"), - ).encode() - await _write_frame(writer, response_header) - await _write_frame(writer, response) - finally: - writer.close() - try: - await writer.wait_closed() - except (OSError, ssl.SSLError): - pass - - async def _exchange_local(self, request: bytes) -> bytes: - reader, writer = await asyncio.open_unix_connection(self._socket_path) - try: - await _write_frame(writer, request) - return await _read_frame(reader) - finally: - writer.close() - try: - await writer.wait_closed() - except OSError: - pass - - -__all__ = ("RemoteModelProxyBridge",) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 90c70174d..f33d848e6 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -744,8 +744,6 @@ def validate_artifact_storage(self) -> Settings: if self.checker_model_proxy_socket is not None: if not self.checker_model_proxy_socket.is_absolute(): raise ValueError("checker model proxy socket must be absolute") - if any(value is None for value in external_values): - raise ValueError("checker model proxy requires the external runner") if self.artifact_store_backend == "disabled": raise ValueError("checker model proxy requires enabled artifact storage") if self.artifact_store_backend == "disabled": diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index fa93905d7..dd96c738a 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -554,6 +554,7 @@ class TestLane: "tests/checkers/default/test_contract.py", "tests/checkers/default/test_execution.py", "tests/checkers/external/test_contracts.py", + "tests/checkers/external/test_remote_node.py", "tests/checkers/external/test_runtime.py", "tests/checkers/external/test_pre_invocation.py", "tests/checkers/external/test_migration.py", diff --git a/backend/tests/checkers/external/support.py b/backend/tests/checkers/external/support.py index eeeeced8b..9a0304e0d 100644 --- a/backend/tests/checkers/external/support.py +++ b/backend/tests/checkers/external/support.py @@ -3,9 +3,13 @@ from __future__ import annotations from datetime import datetime, timedelta, timezone +import hashlib +import json +from typing import Any from uuid import uuid4 from app.core.identifiers import new_record_id +from app.interfaces.external_checker_execution import ExternalCheckerMaterialGrant from app.modules.checkers.api.external import ( POST_SUBMIT_INPUT_SCHEMA_ID, PRE_SUBMIT_INPUT_SCHEMA_ID, @@ -25,6 +29,60 @@ SHA = "sha256:" + "a" * 64 +class EmptyExternalMaterialSource: + """One valid descriptor-relative grant with no material file payloads.""" + + files: tuple[()] = () + + def __init__(self, manifest: bytes) -> None: + self.manifest = manifest + + async def open_file(self, item: Any): + raise AssertionError(f"empty material source opened an unexpected file: {item!r}") + yield b"" # pragma: no cover - retain the async-iterator contract + + +def empty_external_material_grant(request, *, suffix: str = "a"): + """Build a canonical empty grant bound to one normalized request.""" + grant_id = "extract_" + suffix * 32 + body = { + "protocol_version": "workstream.external_checker_material_grant.v2", + "grant_id": grant_id, + "request_digest": request.request_digest, + "phase": request.identity.phase, + "identity": request.identity.model_dump(mode="json"), + "evaluation_context_sha256": None, + "materials": [ + { + "material": request.materials[0].model_dump(mode="json"), + "directories": [], + "files": [], + } + ], + "visible_roles": [request.materials[0].role], + } + canonical = json.dumps( + body, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode() + binding = "sha256:" + hashlib.sha256(canonical).hexdigest() + manifest = json.dumps( + {**body, "binding_digest": binding}, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode() + return ExternalCheckerMaterialGrant( + grant_id=grant_id, + binding_digest=binding, + source=EmptyExternalMaterialSource(manifest), + ) + + def schema(schema_id: str, *, required: tuple[str, ...] = ()) -> ExternalCheckerSchema: document = {"type": "object"} if schema_id != RESULT_SCHEMA_ID: diff --git a/backend/tests/checkers/external/test_forge_locator.py b/backend/tests/checkers/external/test_forge_locator.py index bcedd2c2f..c3618fbcc 100644 --- a/backend/tests/checkers/external/test_forge_locator.py +++ b/backend/tests/checkers/external/test_forge_locator.py @@ -13,7 +13,6 @@ from app.adapters.checkers import external_checker_execution_factory from app.adapters.checkers.model_execution import ModelAwareExternalExecution -from app.interfaces.external_checker_execution import ExternalCheckerMaterialGrant from workstream_external_services import ExternalServiceProtocolError from app.modules.checkers.api.external import ( ExternalCheckerContractError, @@ -30,6 +29,7 @@ ) from tests.checkers.external.support import ( SHA, + empty_external_material_grant, execution_identity, execution_material, registry_entry, @@ -150,21 +150,25 @@ async def handle(reader, writer): await writer.wait_closed() server = await asyncio.start_unix_server(handle, socket) + from tests.checkers.external.test_remote_node import remote_adapter_endpoint + try: - yield ( - external_checker_execution_factory( - socket_path=socket, - timeout_seconds=90.0, - ).create("unix_socket"), - received, - ) + async with remote_adapter_endpoint(tmp_path, socket) as endpoint: + yield ( + external_checker_execution_factory( + **endpoint, + timeout_seconds=90.0, + ).create("remote_tls"), + received, + ) finally: server.close() await server.wait_closed() + socket.unlink(missing_ok=True) -def _grant(): - return ExternalCheckerMaterialGrant(grant_id="extract_" + "a" * 32, binding_digest=SHA) +def _grant(request): + return empty_external_material_grant(request) @pytest.mark.parametrize("url", [None, "https://forge.example/o/r/pull/2", "汉" * 2048]) @@ -180,13 +184,17 @@ def test_locator_parser_accepts_bound_null_and_character_bounded_urls(url): async def test_locator_socket_uses_separate_operation_and_no_model_grant(tmp_path, url): request = _request() async with _service(tmp_path, request, _locator(request, url)) as (adapter, received): - response = await adapter.locate_forge_change(request, _grant()) + grant = _grant(request) + response = await adapter.locate_forge_change(request, grant) assert response.result.change_url == url assert response.isolation is not None assert received[0]["operation"] == "locate_forge_change" assert received[0]["request"]["request_digest"] == request.request_digest assert received[0]["model_grant"] is None - assert received[0]["grant"] == {"grant_id": _grant().grant_id, "binding_digest": SHA} + assert received[0]["grant"] == { + "grant_id": grant.grant_id, + "binding_digest": grant.binding_digest, + } @pytest.mark.asyncio @@ -208,7 +216,7 @@ async def test_locator_socket_rejects_resigned_substitutions_and_invalid_values( request = _request() async with _service(tmp_path, request, _locator(request, **changes)) as (adapter, _): with pytest.raises(ExternalServiceProtocolError): - await adapter.locate_forge_change(request, _grant()) + await adapter.locate_forge_change(request, _grant(request)) @pytest.mark.asyncio @@ -225,8 +233,7 @@ async def test_locator_socket_rejects_changed_digest_missing_isolation_and_compl ]: async with _service(tmp_path, request, value, isolation=isolation) as (adapter, _): with pytest.raises(ExternalServiceProtocolError): - await adapter.locate_forge_change(request, _grant()) - (tmp_path / "checker.sock").unlink() + await adapter.locate_forge_change(request, _grant(request)) @pytest.mark.asyncio @@ -235,7 +242,7 @@ async def test_locator_socket_allows_infrastructure_failure_without_isolation(tm async with _service( tmp_path, request, _work_result(request, infrastructure=True), isolation=False ) as (adapter, _): - response = await adapter.locate_forge_change(request, _grant()) + response = await adapter.locate_forge_change(request, _grant(request)) assert response.result.outcome == "infrastructure_failed" assert response.isolation is None @@ -246,12 +253,12 @@ async def test_socket_operation_rejects_marker_mismatches_and_locator_as_work_re ordinary = _request(locate=False) async with _service(tmp_path, ordinary, _locator(ordinary)) as (adapter, received): with pytest.raises(ExternalServiceProtocolError): - await adapter.execute(request, _grant()) + await adapter.execute(request, _grant(request)) with pytest.raises(ExternalServiceProtocolError): - await adapter.locate_forge_change(ordinary, _grant()) + await adapter.locate_forge_change(ordinary, _grant(ordinary)) assert received == [] with pytest.raises(ExternalServiceProtocolError): - await adapter.execute(ordinary, _grant()) + await adapter.execute(ordinary, _grant(ordinary)) assert received[0]["operation"] == "execute" @@ -267,8 +274,7 @@ async def test_locator_validates_locked_output_schema_and_output_byte_limit(tmp_ parsed.validate_request(request) async with _service(tmp_path, request, value) as (adapter, _): with pytest.raises(ExternalServiceProtocolError): - await adapter.locate_forge_change(request, _grant()) - (tmp_path / "checker.sock").unlink() + await adapter.locate_forge_change(request, _grant(request)) def test_locator_request_requires_locked_version_phase_and_schema_declaration(): @@ -312,7 +318,7 @@ async def test_model_wrapper_locator_delegates_without_authorization_sessions_or monkeypatch.setattr("app.adapters.checkers.model_call_service", paid_calls) async with _service(tmp_path, request, _locator(request)) as (adapter, received): wrapped = ModelAwareExternalExecution(execution=adapter, sessions=sessions) - response = await wrapped.locate_forge_change(request, _grant()) + response = await wrapped.locate_forge_change(request, _grant(request)) assert response.result.change_url is None assert received[0]["model_grant"] is None sessions.assert_not_called() diff --git a/backend/tests/checkers/external/test_model_transport.py b/backend/tests/checkers/external/test_model_transport.py index d8a3e1778..edcc2f781 100644 --- a/backend/tests/checkers/external/test_model_transport.py +++ b/backend/tests/checkers/external/test_model_transport.py @@ -9,7 +9,6 @@ from app.adapters.checkers import external_checker_execution_factory from app.interfaces.external_checker_execution import ( - ExternalCheckerMaterialGrant, ExternalCheckerModelGrant, ) from workstream_external_services import ExternalServiceProtocolError @@ -19,6 +18,7 @@ make_external_checker_execution_result, ) from tests.checkers.external.support import ( + empty_external_material_grant, execution_identity, execution_material, registry_entry, @@ -73,14 +73,18 @@ async def handle(reader, writer): path = tmp_path / "checker.sock" server = await asyncio.start_unix_server(handle, path) + from tests.checkers.external.test_remote_node import remote_adapter_endpoint + try: - adapter = external_checker_execution_factory( - socket_path=path, timeout_seconds=90.0, - ).create("unix_socket") - await adapter.execute( - value, ExternalCheckerMaterialGrant("extract_" + "b" * 32, value.request_digest), - model_grant=grant, - ) + async with remote_adapter_endpoint(tmp_path, path) as endpoint: + adapter = external_checker_execution_factory( + **endpoint, timeout_seconds=90.0, + ).create("remote_tls") + await adapter.execute( + value, + empty_external_material_grant(value, suffix="b"), + model_grant=grant, + ) wire = await asyncio.wait_for(received, 1) assert wire["model_grant"] == { "grant_id": grant.grant_id, "binding_digest": value.request_digest, @@ -91,6 +95,7 @@ async def handle(reader, writer): finally: server.close() await server.wait_closed() + path.unlink(missing_ok=True) @pytest.mark.asyncio @@ -98,16 +103,27 @@ async def handle(reader, writer): async def test_wrong_phase_or_request_cannot_open_model_transport(tmp_path, monkeypatch, phase, substituted): value = request(phase) connect = AsyncMock() - monkeypatch.setattr(asyncio, "open_unix_connection", connect) + monkeypatch.setattr(asyncio, "open_connection", connect) + from tests.checkers.external.test_remote_node import _certificate_files + + certificates = _certificate_files(tmp_path) adapter = external_checker_execution_factory( - socket_path=tmp_path / "unused.sock", timeout_seconds=90.0, - ).create("unix_socket") + host="127.0.0.1", + port=1, + server_name="runner.test", + ca_path=certificates["ca"], + certificate_path=certificates["client_certificate"], + private_key_path=certificates["client_key"], + model_proxy_socket_path=None, + timeout_seconds=90.0, + ).create("remote_tls") grant = ExternalCheckerModelGrant( "model_" + "a" * 32, "sha256:" + "0" * 64 if substituted else value.request_digest, ) with pytest.raises(ExternalServiceProtocolError): await adapter.execute( - value, ExternalCheckerMaterialGrant("extract_" + "b" * 32, value.request_digest), + value, + empty_external_material_grant(value, suffix="b"), model_grant=grant, ) connect.assert_not_called() diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py index 2f90f9306..e0cdcf934 100644 --- a/backend/tests/checkers/external/test_remote_node.py +++ b/backend/tests/checkers/external/test_remote_node.py @@ -3,13 +3,16 @@ from __future__ import annotations import asyncio +from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone import hashlib import importlib.util import json from pathlib import Path +import socket import ssl import struct +from uuid import uuid4 from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization @@ -17,9 +20,6 @@ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID import pytest -from app.adapters.checkers.remote_model_bridge import RemoteModelProxyBridge - - _SPEC = importlib.util.spec_from_file_location( "workstream_remote_node", Path(__file__).resolve().parents[4] / "external_checkers/remote_node.py", @@ -96,12 +96,62 @@ def _frame(value: bytes) -> bytes: return struct.pack(">I", len(value)) + value +@asynccontextmanager +async def remote_adapter_endpoint( + tmp_path: Path, + native_socket_path: Path, + *, + model_proxy_socket_path: Path | None = None, +): + """Expose one test-native Unix service through the production TLS edge.""" + certificates = _certificate_files(tmp_path) + material_root = tmp_path / f"runner-materials-{uuid4().hex}" + material_root.mkdir(mode=0o700) + runner_proxy_root = Path("/tmp") / f"ws-rm-{uuid4().hex[:12]}" + runner_proxy_root.mkdir(mode=0o700) + runner_proxy_path = runner_proxy_root / "model.sock" + node = _REMOTE.RemoteNode( + { + "listen_host": "127.0.0.1", + "listen_port": 1, + "client_name": "app.test", + "socket_path": str(native_socket_path), + "model_proxy_socket_path": str(runner_proxy_path), + "material_root": str(material_root), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), + "session_timeout_seconds": 10, + } + ) + await node.start_model_proxy() + remote = await asyncio.start_server( + node.handle, "127.0.0.1", 0, ssl=node.ssl_context + ) + try: + yield { + "host": "127.0.0.1", + "port": remote.sockets[0].getsockname()[1], + "server_name": "runner.test", + "ca_path": certificates["ca"], + "certificate_path": certificates["client_certificate"], + "private_key_path": certificates["client_key"], + "model_proxy_socket_path": model_proxy_socket_path, + } + finally: + remote.close() + await remote.wait_closed() + await node.close() + runner_proxy_root.rmdir() + + @pytest.mark.asyncio async def test_remote_post_stages_bound_material_and_removes_session(tmp_path: Path): certificates = _certificate_files(tmp_path) material_root = tmp_path / "materials" material_root.mkdir(mode=0o700) socket_path = tmp_path / "native.sock" + runner_proxy_path = tmp_path / "runner-model.sock" grant_id = "extract_" + "a" * 32 request_digest = "sha256:" + "b" * 64 content = b"remote material\n" @@ -116,6 +166,12 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> assert path.read_bytes() == content assert path.stat().st_mode & 0o777 == 0o400 assert (root / ".external-checker-grant.json").stat().st_mode & 0o777 == 0o400 + callback_reader, callback_writer = await asyncio.open_unix_connection(runner_proxy_path) + callback_writer.write(_frame(b'{"protocol_version":"workstream.setup_model_proxy.v1"}')) + await callback_writer.drain() + assert await _read_frame(callback_reader) == b'{"callback":"ok"}' + callback_writer.close() + await callback_writer.wait_closed() observed.set() writer.write(_frame(b'{"native":"ok"}')) await writer.drain() @@ -129,7 +185,7 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> "listen_port": 1, "client_name": "app.test", "socket_path": str(socket_path), - "model_proxy_socket_path": str(tmp_path / "model-proxy.sock"), + "model_proxy_socket_path": str(runner_proxy_path), "material_root": str(material_root), "tls_certificate_path": str(certificates["server_certificate"]), "tls_private_key_path": str(certificates["server_key"]), @@ -137,6 +193,7 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> "session_timeout_seconds": 10, } ) + await node.start_model_proxy() server = await asyncio.start_server( node.handle, "127.0.0.1", 0, ssl=node.ssl_context, ) @@ -211,6 +268,22 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> ) writer.write(_frame(control) + _frame(manifest) + _frame(content) + struct.pack(">I", 0)) await writer.drain() + callback_header = json.loads(await _read_frame(reader)) + assert callback_header["operation"] == "callback_request" + assert await _read_frame(reader) == b'{"protocol_version":"workstream.setup_model_proxy.v1"}' + writer.write( + _frame(json.dumps({ + "protocol_version": _REMOTE.PROTOCOL, + "operation": "callback_response", + "channel_id": callback_header["channel_id"], + }, separators=(",", ":")).encode()) + + _frame(b'{"callback":"ok"}') + ) + await writer.drain() + assert json.loads(await _read_frame(reader)) == { + "protocol_version": _REMOTE.PROTOCOL, + "operation": "execution_result", + } assert await _read_frame(reader) == b'{"native":"ok"}' await asyncio.wait_for(observed.wait(), 1) writer.close() @@ -225,33 +298,22 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> native_server.close() await server.wait_closed() await native_server.wait_closed() + await node.close() @pytest.mark.asyncio -async def test_model_callback_uses_outbound_authenticated_bridge(tmp_path: Path): +async def test_callback_is_pinned_to_exact_active_execute_connection(tmp_path: Path): certificates = _certificate_files(tmp_path) material_root = tmp_path / "materials" material_root.mkdir(mode=0o700) native_path = tmp_path / "native.sock" - app_proxy_path = tmp_path / "app-model.sock" runner_proxy_path = tmp_path / "runner-model.sock" - - async def app_proxy(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: - request = await _read_frame(reader) - writer.write(_frame(b"app:" + request)) - await writer.drain() - writer.close() - await writer.wait_closed() - native_server = await asyncio.start_unix_server( lambda _reader, writer: writer.close(), native_path ) - app_server = await asyncio.start_unix_server(app_proxy, app_proxy_path) node = _REMOTE.RemoteNode( { - "listen_host": "127.0.0.1", - "listen_port": 1, - "client_name": "app.test", + "listen_host": "127.0.0.1", "listen_port": 1, "client_name": "app.test", "socket_path": str(native_path), "model_proxy_socket_path": str(runner_proxy_path), "material_root": str(material_root), @@ -262,38 +324,179 @@ async def app_proxy(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) } ) await node.start_model_proxy() - server = await asyncio.start_server( - node.handle, "127.0.0.1", 0, ssl=node.ssl_context, - ) - port = server.sockets[0].getsockname()[1] - bridge = RemoteModelProxyBridge( - host="127.0.0.1", - port=port, - server_name="runner.test", - ca_path=certificates["ca"], - certificate_path=certificates["client_certificate"], - private_key_path=certificates["client_key"], - socket_path=app_proxy_path, - ) + + async def stream_pair(): + first, second = socket.socketpair() + return ( + await asyncio.open_connection(sock=first), + await asyncio.open_connection(sock=second), + ) + + (a_reader, a_writer), (a_peer_reader, a_peer_writer) = await stream_pair() + (b_reader, b_writer), (b_peer_reader, b_peer_writer) = await stream_pair() + channel_a = _REMOTE.ExecutionChannel(a_reader, a_writer) + channel_b = _REMOTE.ExecutionChannel(b_reader, b_writer) + + async def answer(reader, writer, prefix): + header = json.loads(await _read_frame(reader)) + payload = await _read_frame(reader) + writer.write( + _frame(json.dumps({ + "protocol_version": _REMOTE.PROTOCOL, + "operation": "callback_response", + "channel_id": header["channel_id"], + }, separators=(",", ":")).encode()) + + _frame(prefix + payload) + ) + await writer.drain() + try: - await bridge.start() - for _ in range(100): - if node._model_bridge is not None: - break - await asyncio.sleep(0.01) - assert node._model_bridge is not None + node._active_channel = channel_a + answer_a = asyncio.create_task(answer(a_peer_reader, a_peer_writer, b"a:")) + reader, writer = await asyncio.open_unix_connection(runner_proxy_path) + writer.write(_frame(b"bound callback")) + await writer.drain() + assert await _read_frame(reader) == b"a:bound callback" + await answer_a + with pytest.raises(TimeoutError): + await asyncio.wait_for(_read_frame(b_peer_reader), 0.05) + writer.close() + await writer.wait_closed() + + a_peer_writer.close() + await a_peer_writer.wait_closed() + await asyncio.wait_for(channel_a.closed.wait(), 1) + reader, writer = await asyncio.open_unix_connection(runner_proxy_path) + writer.write(_frame(b"lost owner")) + await writer.drain() + assert await reader.read() == b"" + with pytest.raises(TimeoutError): + await asyncio.wait_for(_read_frame(b_peer_reader), 0.05) + writer.close() + await writer.wait_closed() + + node._active_channel = channel_b + answer_b = asyncio.create_task(answer(b_peer_reader, b_peer_writer, b"b:")) reader, writer = await asyncio.open_unix_connection(runner_proxy_path) - writer.write(_frame(b"bound model call")) + writer.write(_frame(b"next invocation")) await writer.drain() - assert await _read_frame(reader) == b"app:bound model call" + assert await _read_frame(reader) == b"b:next invocation" + await answer_b + writer.close() + await writer.wait_closed() + finally: + node._active_channel = None + await channel_a.close() + await channel_b.close() + for writer in (a_peer_writer, b_peer_writer): + writer.close() + await writer.wait_closed() + native_server.close() + await native_server.wait_closed() + await node.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("exit_kind", ["disconnect", "timeout"]) +async def test_proxy_exit_closes_native_connection_and_copy_tasks( + tmp_path: Path, exit_kind: str, +): + certificates = _certificate_files(tmp_path) + material_root = tmp_path / "materials" + material_root.mkdir(mode=0o700) + native_path = tmp_path / "native.sock" + native_started = asyncio.Event() + native_closed = asyncio.Event() + + async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + native_started.set() + await reader.read() + native_closed.set() writer.close() await writer.wait_closed() + + native_server = await asyncio.start_unix_server(native, native_path) + node = _REMOTE.RemoteNode( + { + "listen_host": "127.0.0.1", "listen_port": 1, "client_name": "app.test", + "socket_path": str(native_path), + "model_proxy_socket_path": str(tmp_path / "runner-model.sock"), + "material_root": str(material_root), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), + "session_timeout_seconds": 1, + } + ) + server = await asyncio.start_server(node.handle, "127.0.0.1", 0, ssl=node.ssl_context) + client_context = ssl.create_default_context( + ssl.Purpose.SERVER_AUTH, cafile=str(certificates["ca"]) + ) + client_context.minimum_version = ssl.TLSVersion.TLSv1_3 + client_context.load_cert_chain( + certificates["client_certificate"], certificates["client_key"] + ) + try: + reader, writer = await asyncio.open_connection( + "127.0.0.1", server.sockets[0].getsockname()[1], + ssl=client_context, server_hostname="runner.test", + ) + control = json.dumps({ + "protocol_version": _REMOTE.PROTOCOL, + "operation": "proxy", + "capability": _REMOTE.CHECKER_CAPABILITY, + }, separators=(",", ":")).encode() + writer.write(_frame(control)) + await writer.drain() + await asyncio.wait_for(native_started.wait(), 1) + if exit_kind == "disconnect": + writer.close() + await writer.wait_closed() + else: + assert await asyncio.wait_for(reader.read(), 2) == b"" + writer.close() + await writer.wait_closed() + await asyncio.wait_for(native_closed.wait(), 1) finally: - await bridge.close() server.close() native_server.close() - app_server.close() await server.wait_closed() await native_server.wait_closed() - await app_server.wait_closed() - await node.close() + + +@pytest.mark.parametrize("residue_name", [".incoming-" + "a" * 32, "extract_" + "b" * 32]) +def test_restart_fails_closed_until_stopped_native_residue_is_reconciled( + tmp_path: Path, residue_name: str, +): + certificates = _certificate_files(tmp_path) + material_root = tmp_path / "materials" + workspaces = material_root / "workspaces" + workspaces.mkdir(parents=True, mode=0o700) + material_root.chmod(0o700) + residue = workspaces / residue_name + residue.mkdir(mode=0o700) + retained = residue / "retained.bin" + retained.write_bytes(b"sensitive staged bytes") + retained.chmod(0o400) + native_path = tmp_path / "native.sock" + native = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + native.bind(str(native_path)) + config = { + "listen_host": "127.0.0.1", "listen_port": 1, "client_name": "app.test", + "socket_path": str(native_path), + "model_proxy_socket_path": str(tmp_path / "runner-model.sock"), + "material_root": str(material_root), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), + "session_timeout_seconds": 10, + } + with pytest.raises(ValueError, match="requires reconciliation"): + _REMOTE.RemoteNode(config) + with pytest.raises(ValueError, match="native service must be stopped"): + _REMOTE._reconcile_stale_workspaces(config) + native.close() + native_path.unlink() + assert _REMOTE._reconcile_stale_workspaces(config) == 1 + assert list(workspaces.iterdir()) == [] + _REMOTE.RemoteNode(config) diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py index 324771c66..63a1cad4f 100644 --- a/backend/tests/checkers/external/test_runtime.py +++ b/backend/tests/checkers/external/test_runtime.py @@ -972,6 +972,7 @@ def _pre_transport_processor(lease, endpoint, changed): from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor adapter = RemoteTlsExternalCheckerAdapter( **endpoint, + model_proxy_socket_path=None, timeout_seconds=0.2 if changed == "slow_decode" else 5.0, source_contracts=selected_pre_submit_source_contracts(), ) @@ -1155,7 +1156,8 @@ def open_source(self, **kwargs): adapter = RemoteTlsExternalCheckerAdapter( host="127.0.0.1", port=1, server_name="runner.test", ca_path=certificates["ca"], certificate_path=certificates["client_certificate"], - private_key_path=certificates["client_key"], timeout_seconds=5.0, + private_key_path=certificates["client_key"], model_proxy_socket_path=None, + timeout_seconds=5.0, source_contracts=selected_pre_submit_source_contracts(), ) with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="deadline_exceeded"): @@ -1206,7 +1208,8 @@ async def handle(reader, writer): adapter = RemoteTlsExternalCheckerAdapter( host="127.0.0.1", port=remote.sockets[0].getsockname()[1], server_name="runner.test", ca_path=certificates["ca"], certificate_path=certificates["client_certificate"], - private_key_path=certificates["client_key"], timeout_seconds=5.0, + private_key_path=certificates["client_key"], model_proxy_socket_path=None, + timeout_seconds=5.0, source_contracts=selected_pre_submit_source_contracts(), ) processor = SelectedPreSubmitProcessor(lease=lease, execution=adapter, source_contracts=selected_pre_submit_source_contracts()) diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index a90ba31a8..316f09e46 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -96,6 +96,7 @@ def test_checker_delivery_and_routing_preparation_partition_every_node_once() -> "tests/checkers/default/test_contract.py", "tests/checkers/default/test_execution.py", "tests/checkers/external/test_contracts.py", + "tests/checkers/external/test_remote_node.py", "tests/checkers/external/test_migration.py", "tests/checkers/external/test_postgresql.py", "tests/checkers/external/test_public_api.py", diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md index 7157761f0..963191bce 100644 --- a/deploy/hosted/README.md +++ b/deploy/hosted/README.md @@ -1,121 +1,58 @@ # Hosted Release Configuration This directory prepares the Workstream API, durable Celery worker, Beat, -fixed guide-document parser and optional trusted model proxy on one dedicated -Linux amd64 host. The single-host profile uses the native Smol systemd node for -project PRE/POST and trusted ZIP intake. Compose does not start a checker -controller or grant access to its Docker socket. PostgreSQL and Redis are -required. Use the [private backing-service overlay](SINGLE_HOST.md) or managed -services. -AWS S3, Flow identity and the optional OTLP collector retain their separate -configuration and trust boundaries. +fixed guide-document parser and optional trusted model proxy on an app-only +Linux amd64 host. PostgreSQL and Redis may use the host-local data overlay or +separately managed services. Project PRE/POST and trusted ZIP intake run only on +the separately administered, always-on remote runner. The checked-in [release environment template](release.env.example), -[Compose wrapper](compose.py), [preflight](preflight.py), native node and -[canonical Settings](../../backend/app/core/config.py) define the source -topology. An operator must still build and publish exact images, provision the -host and external services, configure private assets and credentials, run the -real S3 storage qualification, and verify the public journey for that deployment. A render, -image build or preflight alone does not establish hosted operation or a real -model call. The [capability ledger](../../docs/roadmap_status.md) and -[hosted drill report](../../docs/reports/garden-hosted-drill-2026-11-06.md) -record what has actually been exercised; neither makes this directory an -automatic installer or qualifies another host. +[Compose wrapper](compose.py), [preflight](preflight.py), and +[canonical Settings](../../backend/app/core/config.py) define the app topology. +The runner unit/config examples live under +[external_checkers/deploy](../../external_checkers/deploy). An operator must +still build and pin exact images, provision both hosts, install private +credentials, qualify storage and runner health, and verify the public journey. +A render, image build or preflight alone is not deployment evidence. ## App host without KVM -Set `WORKSTREAM_HOSTED_PROFILE=app` and pin a backend image built from a release -that includes this profile. Remove `WORKSTREAM_CHECKER_CONFIG_FILE`, -`WORKSTREAM_CHECKER_SERVICE_BINARY`, `WORKSTREAM_CHECKER_SERVICE_BINARY_SHA256`, -both `WORKSTREAM_ARTIFACT_INTAKE_*_DIGEST` values, and any trial-authority -selectors from the release environment. Use the normal hosted preflight, -migration and `compose.py ... resume` commands. The app profile -requires the same database, broker, identity, parser, and provider setup as the -single-host profile. It starts the configured setup model proxy before the -ordinary worker. API and worker use local ART scratch for their other work. - -While this profile is active, the API returns a retryable HTTP 503 for ZIP -preparation. MCP reports the upstream error as a retryable tool failure. POST -evaluation requests and reconciliation remain in PostgreSQL until checker -delivery is available. Artifact verification, guide -compilation, and ordinary OUTBOX delivery, including completed evaluation -delivery, continue. The `single-host` profile, or an unset profile, keeps the -native Smol readiness checks and processes all delivery types. Private ingress -and worker attachment for a second checker host require separate qualification. +Hosted releases set `WORKSTREAM_HOSTED_PROFILE=app`. Supply the private runner +address, port and certificate name through +`WORKSTREAM_EXTERNAL_RUNNER_{HOST,PORT,SERVER_NAME}`; supply the CA, client +certificate and client key through the corresponding `*_FILE` selectors. +Pin `WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST` and +`WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST` to the images installed on the +runner. Preflight refuses partial endpoint or TLS configuration. + +The API and worker connect directly to the runner for PRE, POST and trusted +intake. When model execution is enabled, the worker forwards bounded callback +frames between its app-local model-proxy socket and the same authenticated TLS +connection that owns the remote execution. +There is no local native checker socket, KVM device, checker binary/config or +shared API/runner material filesystem, and there is no single-host fallback. ## Trust boundary -In the single-host profile, the native node uses KVM and its delegated -cpu/memory/pids cgroup under the same numeric UID/GID `10001:10001` as the -ART grant issuer. It owns fresh VM execution, -exact leases and cleanup. Neither the node nor project images receive provider -credentials. The optional Compose model proxy alone owns those credentials; -the native node connects to its host-visible private socket and forwards only -invocation-bound capability traffic through the Smol guest transport. - -In that profile, the API and worker mount the node socket directory read-only. -Both typed capabilities use the same host endpoint with distinct closed -protocols and pinned images: - -```text -/var/lib/workstream/scratch -/var/lib/workstream/checker-runtime/checker.sock -/var/lib/workstream/model-runtime/model.sock -``` - -`WORKSTREAM_DEPLOYMENT_ROOT` defaults to `/var/lib/workstream`. An independently -owned deployment may select one canonical absolute private root; all scratch, -checker/model/parser socket paths below it are derived together, with identical -absolute source/target paths in the containers. The root must be mode `0700`, -owned by `10001:10001`, and contain no config, provider secret or executable/cache -asset. Symlink roots, ancestor aliases and data/asset overlap fail preflight. -`WORKSTREAM_CHECKER_SERVICE_BINARY` defaults to the unit's installed path and -selects one absolute artifact under `WORKSTREAM_CHECKER_SERVICE_BINARY_SHA256`. - -For an isolated proof, use a newly owned `/var/tmp/workstream-hosted-smol-*` -prefix with a private `data` subdirectory and config/assets as separate siblings. -Give UID `10001` traversal access to the owned prefix; do not rely on another -user's private home ancestry. Configure the existing scoped unit's `ExecStart` -and cgroup path for that exact binary/config and preserve its ownership. This -uses the same release topology and preflight, without shared `/etc/workstream` -or `/var/lib/workstream` mutation. No source here deploys or restarts that unit. - -These absolute paths and identities must match across native configuration, -API/worker containers and the proxy. ART material lives under the same scratch -root on host and clients; the native node independently verifies each opaque -ART grant before staging. Model proxy sockets and ART material are never assumed -to exist only inside a Docker namespace. Project guests receive guest-local -capability sockets, never the global host socket or a provider key. - -Ordered non-model PRE and approved model-enabled POST retain their existing -owners. PRE model selectors remain unsupported: PRE has no supported paid-model -lineage/grant operation, and policy validation rejects those selectors. This -configuration does not introduce PRE model authority. - -The [hosted qualification record](../../.commitrail/changes/hosted-smol-project-execution.md#live-hosted-model-continuation) -records the actual API/Celery/AWS baseline and one live OpenRouter POST through -this wiring. The model continuation preserves its original paid effect, reaches -governed acceptance and proves replay without another charge. It uses fixture -identity and a synthetic single-rubric submission; production identity and full -project grading remain separate qualifications. - -Guide parsing uses a separate private Unix socket at -`/var/lib/workstream/guide-runtime/guide.sock`. The parser uses the immutable -backend image without network or secrets. Its bootstrap starts as root with only -`KILL`, `SETGID` and `SETUID`, then drops the broker to UID 10002 and GID 10001 -before binding the socket. The broker retains those three capabilities only to -isolate and terminate parser children. Each of its two concurrent children uses -a distinct fixed identity (10003 or 10004), no supplementary groups and no -capabilities. The broker and children verify their process protections before -processing documents; startup fails if the required identity boundary is absent. -The broker owns the socket directory and socket. Only the guide worker mounts that directory as -a read-only client. API, Beat and the native node do not -receive it. The parser process validates directory and socket ownership before -binding. The health check drops to client UID/GID 10001 with no capabilities before -performing a framed protocol round trip against the fixed parser build identity. -Keep the configured capability allowlist, no-new-privileges, read-only root, -network isolation and process limits together; do not replace this profile with -a privileged container. +The runner listener requires TLS 1.3 client authentication and the configured +application DNS SAN. The app validates the runner certificate name. PRE source +and POST material cross this boundary in bounded frames. The runner validates +the canonical request/source/grant binding before creating one private local +workspace, invokes the native checker through runner-internal Unix IPC, and +removes that exact session on success, error, timeout or disconnect. + +The runner's native service owns KVM, delegated cpu/memory/pids cgroups, Smol +leases and cleanup. Project guests receive only guest-local capability sockets. +They never receive TLS keys, model-provider credentials, AWS credentials or the +runner-global Unix sockets. The optional model proxy retains provider keys on +the app host. Callback loss closes that invocation; the runner never selects a +different app replica or a runner-global callback owner. + +Only the app security group needs private TCP access to runner port 9443. +Do not publish 9443 to the internet. Install the client key as a mode-0400 +Compose secret and never place it in the release environment or command line. +Future managed execution providers must preserve the same typed +task/source/result contract; this release does not qualify a vendor adapter. ## Prepare source images @@ -143,10 +80,11 @@ OpenAI 3.x input-count and Responses dependencies for both setup SDKs and POST checkers. The proxy rejects any non-`agents` image before reading the provider credential. `manager_authored` is accepted in either worker image with the exact `none/none/none` setup tuple; `WORKSTREAM_MODEL_PROXY_ENABLED` independently -decides whether approved POST images can use the proxy. Build the native service and static guest from the same reviewed source using the -[node instructions](../../external_checkers/README.md#smol-microvm-engine). Record the -installed service digest in `WORKSTREAM_CHECKER_SERVICE_BINARY_SHA256`; the -private node config pins Smol, the guest and every cached archive/config. A local build tag is build evidence only; the release file must +decides whether approved POST images can use the proxy. Build and install the +native service, static guest, remote edge and pinned image cache on the separate +runner using the [node instructions](../../external_checkers/README.md#smol-microvm-engine). +Record their exact digests in the runner qualification receipt. A local build +tag is build evidence only; the app release file must contain the registry-resolved digest after publication. The backend build's uv package-download cache mount exists only on the builder; it is not retained in the image. Runtime image inspection uses `uv --no-cache pip check` and bounded @@ -165,8 +103,8 @@ python3 scripts/verify_hosted_release_images.py --scope native-hosted \ This scope proves both backend SDK images without requiring a checker controller OCI image. It rejects `--checker-image` and records a closed backend-only -evidence shape. Installed native service, Smol, guest and cache identities remain -the full preflight's responsibility. Backend-image proof establishes no native +evidence shape. Installed runner service, Smol, guest and cache identities remain +the runner qualification's responsibility. Backend-image proof establishes no native readiness or hosted journey result. The [release-image workflow](../../.github/workflows/release-images.yml) @@ -186,82 +124,24 @@ operation remains separate evidence. The proof builds and inspects both SDK closures and rejects either SDK appearing in the other image. An unconditional workflow cleanup verifies that no smoke container owned by that run remains after inspection or timeout. -## Prepare the host - -Install Docker for the backend containers and the pinned native Smol bundle -for Linux amd64 with `/dev/kvm`, cgroup v2 and systemd 254 or later. Use the -[existing unit](../../external_checkers/deploy/workstream-checker.service), which -runs as `10001:10001`, places its controller in a delegated subgroup and preserves -independent guardians with `KillMode=process`. Review its explicit deployment -CPU/memory/PID/storage capacity against intake, checker and sequential trial -peak demand; this configuration does not increase registered checker limits. - -Keep that storage capacity physically free on the native checker's filesystem, -not merely configured as a quota. ZIP intake seals and counts the upload first, -then reserves a data disk sized for those bytes, permitted expansion and its -qualified image/filesystem allowance, rounded up to whole GiB. Its separate -root overlay is explicitly limited to one GiB and charged as well. A healthy -socket does not prove that reservation can succeed. Subsequent -checkers require their own configured capacity. Monitor free space as well as -service health, and remove only identified obsolete build/staging assets when -needed. Preserve active images, credential state, database volumes and retained -artifact/evidence data. An intake capacity refusal is an infrastructure failure, -not a failed assessment of contributor work. - -Provision a dedicated host service account and group at UID/GID `10001:10001` -before starting the unit. Numeric file ownership alone is insufficient: systemd -must resolve this account, otherwise it can fail with `217/USER`. Inspect -`getent passwd 10001` and `getent group 10001` first. If either ID belongs to an -unrelated identity, stop and resolve that host allocation; do not modify or reuse -the unrelated account. When both IDs and the name `workstream-checker` are unused: +## Prepare the app host -```sh -sudo groupadd --gid 10001 workstream-checker -sudo useradd --system --uid 10001 --gid 10001 --no-create-home \ - --home-dir /nonexistent --shell /usr/sbin/nologin workstream-checker -``` - -Keep the account password locked and without a login or home directory. Grant no -sudo or Docker access. The unit's `SupplementaryGroups=kvm` supplies KVM access; -ensure that host group owns `/dev/kvm`. Existing dedicated service identities -must have the same UID, primary GID and restrictions. - -Create canonical private roots on durable host storage: +Install Docker for the backend containers. Provision the dedicated app runtime +account at UID/GID `10001:10001`, then create only the app-owned durable roots: ```sh sudo install -d -m 0700 -o 10001 -g 10001 /var/lib/workstream sudo install -d -m 0700 -o 10001 -g 10001 /var/lib/workstream/scratch -sudo install -d -m 0700 -o 10001 -g 10001 /var/lib/workstream/checker-runtime sudo install -d -m 0700 -o 10001 -g 10001 /var/lib/workstream/model-runtime -sudo install -d -m 0700 -o 10001 -g 10001 /var/lib/workstream/model-relays -sudo install -d -m 0700 -o 10001 -g 10001 /var/lib/workstream-checker/smol -sudo install -d -m 0700 -o 10001 -g 10001 /var/lib/workstream-checker/images sudo install -d -m 0750 -o 10002 -g 10001 /var/lib/workstream/guide-runtime ``` -Preserve the node socket parent's persistent owner/lease custody and all trial -root markers across restarts. Never clone them into another live deployment or -replace them with `/run`, tmpfs or container storage. Do not delete retained -inputs, product evidence, shared roots or unknown runtime resources during -recovery. Unknown ownership or cleanup refuses admission. - -Provision project images and the pinned trusted intake image using the existing -[Smol cache command](../../external_checkers/README.md#smol-microvm-engine). -The native `trusted_intake` configuration selects the intake image; project -registrations cannot select that privileged purpose. Its image/config pins must -match the two `WORKSTREAM_ARTIFACT_INTAKE_*_DIGEST` values. Its required -`storage_envelope` binds the archive/config and Smol/guest hashes to qualified -entry/path limits, overhead bytes and maximum data-disk size. Use the evidence -for the exact release image and native runtime; requalify changed images or -limits. The example's zero overhead/size fields deliberately fail preflight -until replaced with measured bounds. Do not copy a guessed buffer into them. -Cold boot, archive spooling, maximum projected inventory, expanded content and -cleanup must fit; an example upload alone does not qualify the envelope. -The native owner disables automatic Smol image-seed creation and reuse; do not -qualify with an extra upstream seed VM outside the node reservation. Existing -cache data is preserved. Measure startup under the same enforced environment. -Both typed clients -connect through the one mode-`0600` socket in the mode-`0700` checker directory. +Do not install KVM, Smol, a native checker unit, image cache or checker runtime +directory on this host. Qualify the runner separately using the native and edge +units under `external_checkers/deploy`. Restrict runner TCP 9443 ingress to the +app security group, install the CA/client certificate/client key as private app +secrets, and verify the certificate SAN and pinned image identities before app +activation. Copy `release.env.example` to an operator-owned non-secret environment file and replace every example identity. The file contains paths and public configuration, @@ -322,13 +202,13 @@ This principal admits private model request/response evidence; configuring the proxy and provider credentials does not provision it. The canonical journey service bootstrap includes it for both setup and checker model use. -With the proxy enabled, the native checker service reads the global -model socket from its canonical host path. Its separate writable -`/var/lib/workstream/model-relays` directory is private to the native service, owned by the runtime UID/GID with mode `0700`. -Start the proxy before the native node. The service creates an invocation relay -and the Smol transport exposes only its guest-local capability endpoint. Project -images receive neither the global socket nor provider credentials. API and Beat receive -neither model directory. +With the proxy enabled, its process owns the app-local model socket. The Celery +worker mounts that socket read-only and forwards opaque normal-model, +trial-evidence and setup-model frames only while its exact remote execute TLS +connection remains active. The native service connects only to the runner-local +model socket. The Smol transport exposes only its guest-local capability +endpoint. Project images receive neither global socket nor provider credentials. +API and Beat receive no model directory. The two provider file paths are trusted release configuration. The proxy loads only configured dedicated files as `OPENROUTER_API_KEY` or `OPENAI_API_KEY`; this is independent of the setup provider because approved POST and setup profiles may @@ -389,62 +269,31 @@ value that accommodates the selected workload; a shorter owned qualification may observe real expiry sooner, without resetting its original deadline or changing registered checker limits. -Copy `checker-service.example.json` to the configured private mode-`0400` -path. The unit reads `/etc/workstream/checker-service.json`. Replace all example -binary, guest, archive, platform-manifest and config digests with independently -verified values. The default-behavior digest must match the built source's -canonical default checker. Runtime execution uses preloaded archives and never -pulls, resolves a tag or falls back to Docker/runsc. - -For a proxy-disabled release remove both `model_proxy_socket` and -`model_relay_root`; preflight rejects partial or substituted selectors. For a -proxy-enabled release retain their exact host paths. The running service reads -its configuration from JSON, not the release environment. - -Approved POST trial selectors additionally require the optional paired -`WORKSTREAM_CHECKER_TRIAL_AUTHORITY_MANIFEST_PATH` and -`WORKSTREAM_CHECKER_TRIAL_AUTHORITY_MANIFEST_DIGEST`. They activate -`compose.trials.yml`, which mounts that exact host file read-only only into the -model proxy. Set the native JSON's `trial_authority_manifest_path` and -`trial_authority_manifest_digest` to the same host source and digest, and supply -its existing `trial_runtime` object: private relay/scratch/child-home/cache roots, -pinned builder config ID, launcher/filesystem-tool paths and digests, deployment -owner, candidate archive ceiling and exact runtime-configuration digest. Provision -the builder cache entry and approved offline cache from the qualified runtime -release. Do not substitute a project-selected profile or copy the runtime into -this deployment layer. The native runtime and backend typed manifest loader -validate the authority catalogue; preflight checks their shared byte identity -and custody. API, worker and Beat do not read this catalogue or receive its mount. - -Smol 1.31.4's longest Unix socket adds 48 filesystem bytes below its HOME. The -107-byte socket limit therefore permits a global `smol.home` of at most 59 -bytes. A trial child adds `/ws-<32 hex digits>.home` first, so -`trial_runtime.child_home_root` must be at most 18 bytes. These are filesystem -byte limits, including multibyte characters. Use a separately owned short -private directory such as `/var/tmp/t-<6 hex>` for the trial child root; retain -its runtime owner marker and exact custody. Do not shorten invocation identities -or derive this root from a long deployment prefix. Preflight rejects excess -length before a VM is created. +Runner configuration is installed and reviewed separately. It pins the native +service and edge binaries, Smol/guest digests, trusted intake and checker image +manifests/configs, PRE root and capacity profile, private material/model-relay +roots, and TLS server identity. The runner system journal and a non-secret +qualification receipt record actual health, PRE/POST execution and cleanup. +App preflight validates only the configured endpoint, TLS files and intake +digests; it does not infer runner qualification from local files. ## Validate without disclosure -The directory commands above describe the default production root. For another -owned root, create its derived children with the same identities and modes, and -replace native JSON socket/material/model paths with those exact derived paths. -Keep source/cache/config/credential files outside that data root. +The directory commands above describe the default app production root. Runner +socket/material/model paths belong only to the separately administered runner; +keep its source, cache, config and TLS files outside app-local ART scratch. Run full preflight and the Compose wrapper as the trusted root administrator or through approved `sudo`. That operator needs authority to traverse the `10001:10001`-owned `0700` deployment root, inspect private `0400` inputs and -access Docker. This also applies to a newly owned `/var/tmp` proof root. The -native node and health containers run as `10001:10001`; do not grant that runtime -identity Docker group membership or daemon access to make operator checks work. +access Docker. This also applies to a newly owned `/var/tmp` proof root. Do not +grant the application runtime Docker group membership or daemon access to make +operator checks work. Preflight never opens application secret files. The configuration-only check renders Compose and validates fixed topology, -digest identities, Flow/AWS profile and the hosted checker selectors plus -declared cache-identity shape needed by this topology. The application and -checker startup owners validate their complete settings and config schemas, +digest identities, Flow/AWS profile and the remote-runner selectors. The app +and runner startup owners validate their complete settings and config schemas, including the canonical AWS credential settings described above. This check does not inspect host ownership, Docker, cache or any external service: @@ -454,21 +303,19 @@ sudo python3 deploy/hosted/preflight.py \ --configuration-only ``` -The full preflight additionally checks secret/config metadata without reading -secret contents, validates private directories and the one node socket owner/mode, and -hashes the installed native service, Smol, guest and cached archive/config assets. -It checks delegated cpu/memory/pids controls and calls the existing typed project -execution and trusted intake health adapters from the pinned backend image with -no credentials or network. Configuration-only mode performs none of those live checks. -Wrong runtime, image/config or default behavior rejects launch: +The full preflight additionally checks app secret/config metadata without reading +secret contents and validates private app directories. Runner runtime, cache, +capacity and cleanup are established by its separate qualification and the +typed remote health/execution paths. Wrong endpoint, TLS or pinned intake +identity rejects launch: ```sh sudo python3 deploy/hosted/preflight.py --env-file /etc/workstream/release.env ``` -Preflight cannot attest the active AWS identity, absence of extra IAM -permissions, Flow token acceptance, a successful VM boot, collector delivery, -backup recoverability or a live checker result. The +App preflight cannot attest the active AWS identity, absence of extra IAM +permissions, Flow token acceptance, a successful remote VM boot, collector +delivery, backup recoverability or a live checker result. The [S3 operations guide](../../docs/operations_aws_s3_credentials.md) describes the restricted identity, bucket policy and storage qualification. Rendered configuration does not establish live cloud behavior. @@ -528,19 +375,14 @@ wrapper never retries automatically or infers readiness. No award, policy publication or external fulfillment is performed by this operation. Cold startup orders migrations before application services. `migrate` runs the -existing API image's Alembic command without application startup or checker -health checks. Ordinary API startup never applies migrations. Qualify the -configured storage credential before cutover, then start the optional model -proxy and the native node for the single-host checker topology. Run these -operator steps: +existing API image's Alembic command without application startup. Ordinary API +startup never applies migrations. Qualify the configured storage credential and +the remote runner before cutover, including mTLS health from the app network. +Then run these operator steps: ```sh sudo python3 deploy/hosted/compose.py --env-file /etc/workstream/release.env pull sudo python3 deploy/hosted/compose.py --env-file /etc/workstream/release.env migrate -sudo python3 deploy/hosted/compose.py --env-file /etc/workstream/release.env \ - up -d model-proxy -# Wait for the proxy health check, then start the reviewed native unit explicitly. -sudo systemctl start workstream-checker.service sudo python3 deploy/hosted/preflight.py --env-file /etc/workstream/release.env sudo python3 deploy/hosted/compose.py --env-file /etc/workstream/release.env \ up --detach --wait @@ -555,18 +397,17 @@ qualification separately records its actual process/binary identities. The guide parser and enabled model proxy must pass their existing health checks before the worker starts. Beat retains existing recovery schedules. API health -is a lightweight endpoint; Celery health checks its processes. Typed native -readiness verifies runtime/identity/cache-count and pinned intake/default facts; -exact image selection is independently checked during every execution. None of +is a lightweight endpoint; Celery health checks its processes. Remote health +verifies runtime/identity/cache-count and pinned intake/default facts; exact +image selection is independently checked during every execution. None of these checks replaces a public authenticated journey, storage qualification, resource qualification or restart/cleanup evidence. Each Compose service has its existing -finite restart policy; the native unit retains its own bounded systemd policy. +finite restart policy; the runner units retain their own bounded systemd policy. ### Reconcile an installed host after reboot Docker restart policies do not enforce Compose dependency health ordering at -host boot. The native node can exhaust its start attempts before the model proxy -socket is ready, and MCP can retain a stopped API's network namespace. Install +host boot, and MCP can retain a stopped API's network namespace. Install [workstream-hosted.service](workstream-hosted.service) after the initial schema, storage qualification, pinned image installation and public journey have passed. Copy the reviewed checkout to `/opt/workstream/source`, or edit both absolute source @@ -583,14 +424,13 @@ sudo systemctl status workstream-hosted.service The unit runs exactly `compose.py --env-file /etc/workstream/release.env resume` after Docker and network startup. This reconciles optional local data and identity -services, waits for the enabled model proxy, resets the native node's exhausted -start counter and starts that existing unit. It waits for canonical typed native -and intake readiness before reconciling API, workers and scheduler. MCP is held +services and waits for the enabled model proxy. It requires configured remote +runner and intake readiness before reconciling API, workers and scheduler. MCP is held out of the API health wait, then recreated against the current API namespace and -verified. An already active native node is preserved. Each attempt has management +verified. Each attempt has management deadlines; systemd retries failed reconciliation after 30 seconds and records -failures in its journal. Inspect `journalctl -u workstream-hosted.service` and -`journalctl -u workstream-checker.service` for diagnosis. +failures in its journal. Inspect `journalctl -u workstream-hosted.service` on +the app host and the two runner unit journals for diagnosis. Resume uses installed digest-pinned images with `--pull never`; registry login and network availability to the registry are unnecessary for reboot. A missing @@ -607,8 +447,8 @@ before shutting down a deployment permanently. To rerun reconciliation after an operator repair, use `systemctl restart workstream-hosted.service`. The API binds to host loopback for an environment-owned TLS reverse proxy. Do -not expose the checker socket, Docker socket, PostgreSQL, Redis or OTLP collector -as public ports. +not expose Docker, PostgreSQL, Redis or the OTLP collector as public ports. The +runner listener is private and restricted to the app security group. ## Diagnostics @@ -626,10 +466,10 @@ outage does not change product results. Configuration alone is not that proof. The wrapper's `stop` operation stops Beat and API first so they cannot produce new work, gives the prefork worker its configured 7,320-second graceful window, then drains the model proxy before stopping the parser. If the local backing-service -overlay is enabled, Redis and PostgreSQL stop last, preserving their data directories. It never stops the -native systemd node. -Keeping all socket services alive while the worker drains lets cancellation and -terminal persistence finish against their original dependencies. Guide inference +overlay is enabled, Redis and PostgreSQL stop last, preserving their data directories. +It never stops or reconfigures the separately administered runner. Keeping +the remote runner available while the worker drains lets cancellation and +terminal persistence finish against the invocation's original connection. Guide inference has a 7,260-second process backstop; the shared Redis transport uses a 7,380-second visibility timeout with prefetch disabled. The persisted guide-attempt deadline remains the ordinary, shorter @@ -642,7 +482,7 @@ sudo python3 deploy/hosted/compose.py --env-file /etc/workstream/release.env sto For an intentional worker-only interruption, the existing wrapper also accepts exactly `stop worker` followed by `start worker`. Stop preserves API, Beat, proxy, -parser and native node while allowing the configured 7,320-second worker drain; +parser and the external runner while allowing the configured 7,320-second worker drain; its CLI deadline adds 60 seconds for management. This is not a full deployment drain: producers can continue creating durable work. Start repeats the full private-input and typed native readiness checks, then reconciles only the worker @@ -664,14 +504,13 @@ do not edit its marker to make a new release start. Stop all processes mounting that pool, verify that no reservations or workspaces remain, and retain the old directory intact before provisioning a fresh private directory at the canonical path. Let the normal ART manager initialize it, recreate the affected container -and systemd mounts, and verify that API, worker, proxy and native node all see -the same new directory. +and mounts, and verify that API and worker see the same new app-local directory. If retained work remains, complete its recovery under the original configuration before changing the pool. -Before restarting or stopping the native unit, first drain producers and the -worker through the wrapper, retain the proxy until node calls settle, and -independently confirm that this node has no active owned leases, VMs or cgroups. +Before restarting or stopping a runner unit, first drain producers and the +worker through the wrapper, retain the proxy until calls settle, and independently +confirm that the runner has no active owned leases, VMs or cgroups. Preserve guardian recovery and use the exact owner-scoped inventory; never prune shared resources or stop another deployment. Exercise an interrupted job and verify the existing exact retry/reconciliation operations rather than diff --git a/deploy/hosted/compose.yml b/deploy/hosted/compose.yml index db6a51e90..34cb08da8 100644 --- a/deploy/hosted/compose.yml +++ b/deploy/hosted/compose.yml @@ -277,33 +277,12 @@ services: WORKSTREAM_DATABASE_URL_FILE: /run/secrets/database_url WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/model-runtime/model.sock WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE: /run/workstream-artifact-credentials/aws-access-key.json - WORKSTREAM_EXTERNAL_RUNNER_HOST: ${WORKSTREAM_EXTERNAL_RUNNER_HOST:?set the private runner address} - WORKSTREAM_EXTERNAL_RUNNER_PORT: ${WORKSTREAM_EXTERNAL_RUNNER_PORT:-9443} - WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME: ${WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME:?set the runner certificate name} - WORKSTREAM_EXTERNAL_RUNNER_CA_PATH: /run/secrets/external_runner_ca - WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH: /run/secrets/external_runner_certificate - WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH: /run/secrets/external_runner_private_key secrets: - source: database_url target: database_url uid: "${WORKSTREAM_RUNTIME_UID}" gid: "${WORKSTREAM_RUNTIME_GID}" mode: 0400 - - source: external_runner_ca - target: external_runner_ca - uid: "${WORKSTREAM_RUNTIME_UID}" - gid: "${WORKSTREAM_RUNTIME_GID}" - mode: 0400 - - source: external_runner_certificate - target: external_runner_certificate - uid: "${WORKSTREAM_RUNTIME_UID}" - gid: "${WORKSTREAM_RUNTIME_GID}" - mode: 0400 - - source: external_runner_private_key - target: external_runner_private_key - uid: "${WORKSTREAM_RUNTIME_UID}" - gid: "${WORKSTREAM_RUNTIME_GID}" - mode: 0400 command: [python, -m, app.workers.checker_model_proxy] volumes: - type: bind diff --git a/deploy/hosted/preflight.py b/deploy/hosted/preflight.py index 874de359e..69df06521 100644 --- a/deploy/hosted/preflight.py +++ b/deploy/hosted/preflight.py @@ -5,7 +5,6 @@ import argparse from dataclasses import dataclass -import hashlib import ipaddress from decimal import Decimal, InvalidOperation import json @@ -16,7 +15,6 @@ import stat import subprocess import sys -import time from typing import Any from uuid import UUID, uuid4 from urllib.parse import urlsplit @@ -713,278 +711,6 @@ def validate_environment(values: dict[str, str]) -> None: ) -def load_checker_config(path: Path) -> dict[str, Any]: - """Load the non-secret runner configuration as one bounded JSON object.""" - try: - if path.stat().st_size > 1024 * 1024: - raise PreflightError("checker configuration is unbounded") - value = json.loads(path.read_text(encoding="utf-8")) - except (OSError, UnicodeError, json.JSONDecodeError) as exc: - raise PreflightError("checker configuration is unavailable or invalid") from exc - if not isinstance(value, dict): - raise PreflightError("checker configuration must be an object") - return value - - -def validate_checker_config(config: dict[str, Any], values: dict[str, str]) -> None: - """Bind release selectors and cache identities to the existing runner.""" - paths = deployment_paths(values) - expected = { - "socket_path": str(paths.socket), - "material_root": str(paths.scratch), - "runtime": "smolvm", - "isolation_mode": "smol-microvm", - "operating_system": "linux", - "sandbox_uid": _positive_id(values, "WORKSTREAM_RUNTIME_UID"), - "sandbox_gid": _positive_id(values, "WORKSTREAM_RUNTIME_GID"), - } - smol = config.get("smol") - if not isinstance(smol, dict) or set(smol) != { - "binary", - "binary_sha256", - "home", - "guest_binary", - "guest_sha256", - "cgroup_root", - "maximum_parallel", - "maximum_storage_bytes", - }: - raise PreflightError("native Smol configuration is incomplete") - for key in ("binary", "guest_binary", "home", "cgroup_root"): - if not isinstance(smol[key], str) or not Path(smol[key]).is_absolute(): - raise PreflightError("native Smol path is invalid") - if len(os.fsencode(smol["home"])) > 59: - raise PreflightError("native Smol home exceeds the 59-byte socket path budget") - for key in ("binary_sha256", "guest_sha256"): - if not isinstance(smol[key], str) or not DIGEST.fullmatch(smol[key]): - raise PreflightError("native Smol binary digest is invalid") - for key in ("maximum_parallel", "maximum_storage_bytes"): - if type(smol[key]) is not int or not 0 < smol[key] <= 2**64 - 1: - raise PreflightError("native Smol capacity must be explicitly bounded") - if Path(smol["home"]) == paths.scratch or Path(smol["home"]).is_relative_to( - paths.scratch - ): - raise PreflightError("native Smol home must be separate from ART material") - protected_inputs = [ - checker_service_binary(values), - Path(values["WORKSTREAM_CHECKER_CONFIG_FILE"]), - Path(smol["binary"]), - Path(smol["guest_binary"]), - *( - Path(values[key]) - for key in (*_secret_file_keys(values), DIRECT_USER_CREDENTIAL_HOST_FILE_KEY) - ), - ] - protected_inputs.extend( - Path(image["smol"][key]) - for image in config.get("cache", []) - if isinstance(image, dict) and isinstance(image.get("smol"), dict) - for key in ("archive", "image_config") - if isinstance(image["smol"].get(key), str) - ) - if values.get(TRIAL_KEYS[0]): - protected_inputs.append(Path(values[TRIAL_KEYS[0]])) - if any( - path.resolve(strict=False).is_relative_to(paths.root) - for path in protected_inputs - ): - raise PreflightError( - "private config, credentials and assets must remain outside deployment data" - ) - model_proxy_enabled = values["WORKSTREAM_MODEL_PROXY_ENABLED"] == "true" - expected.update( - { - "model_proxy_socket": str(paths.model_socket) - if model_proxy_enabled - else None, - "model_relay_root": str(paths.model_relays) - if model_proxy_enabled - else None, - } - ) - for key, required in expected.items(): - if config.get(key) != required: - raise PreflightError( - f"checker configuration has an unsafe release value: {key}" - ) - if config.get("architecture") != "amd64" or config.get("docker_binary") is not None: - raise PreflightError( - "checker architecture is unsupported by this release profile" - ) - cache = config.get("cache") - if not isinstance(cache, list) or not cache: - raise PreflightError("checker cache must contain at least one approved image") - seen: set[str] = set() - for entry in cache: - if not isinstance(entry, dict): - raise PreflightError("checker cache entry must be an object") - digest = entry.get("platform_manifest_digest") - image_id = entry.get("config_image_id") - repository = entry.get("repository") - if not isinstance(repository, str) or not repository or "@" in repository: - raise PreflightError("checker cache repository is invalid") - if not isinstance(digest, str) or not DIGEST.fullmatch(digest): - raise PreflightError("checker cache manifest digest is invalid") - if not isinstance(image_id, str) or not DIGEST.fullmatch(image_id): - raise PreflightError("checker cache image ID is invalid") - image = entry.get("smol") - if not isinstance(image, dict) or set(image) != { - "archive", - "archive_sha256", - "image_config", - }: - raise PreflightError("checker cache lacks native Smol assets") - if not isinstance(image["archive_sha256"], str) or not DIGEST.fullmatch( - image["archive_sha256"] - ): - raise PreflightError("checker cache archive digest is invalid") - if any( - not isinstance(image[key], str) or not Path(image[key]).is_absolute() - for key in ("archive", "image_config") - ): - raise PreflightError("checker cache asset path is invalid") - if digest in seen: - raise PreflightError("checker cache manifest digest is duplicated") - seen.add(digest) - if entry.get("operating_system") != "linux": - raise PreflightError("checker cache operating system must be linux") - if entry.get("architecture") != config["architecture"]: - raise PreflightError("checker cache architecture differs from the runner") - - intake = config.get("trusted_intake") - if not isinstance(intake, dict) or set(intake) != { - "platform_manifest_digest", - "default_behavior_sha256", - "storage_envelope", - }: - raise PreflightError("native node lacks the trusted intake purpose") - selected = [ - entry - for entry in cache - if entry["platform_manifest_digest"] == values[INTAKE_DIGEST_KEYS[0]] - ] - if ( - len(selected) != 1 - or selected[0]["config_image_id"] != values[INTAKE_DIGEST_KEYS[1]] - or intake["platform_manifest_digest"] != values[INTAKE_DIGEST_KEYS[0]] - or not isinstance(intake["default_behavior_sha256"], str) - or not DIGEST.fullmatch(intake["default_behavior_sha256"]) - ): - raise PreflightError( - "trusted intake cache identity differs from release configuration" - ) - - envelope = intake.get("storage_envelope") - identities = { - "archive_sha256": selected[0]["smol"]["archive_sha256"], - "config_image_id": selected[0]["config_image_id"], - "smol_binary_sha256": smol["binary_sha256"], - "guest_sha256": smol["guest_sha256"], - } - bounds = { - "maximum_entries", - "maximum_path_bytes", - "maximum_path_depth", - "overhead_bytes", - "maximum_storage_gib", - } - if ( - not isinstance(envelope, dict) - or set(envelope) != set(identities) | bounds - or any(envelope[key] != value for key, value in identities.items()) - or any( - type(envelope[key]) is not int or not 0 < envelope[key] <= 2**64 - 1 - for key in bounds - ) - or envelope["maximum_entries"] > 100_000 - or envelope["maximum_path_depth"] > 256 - or (envelope["maximum_storage_gib"] + 1) * 1024**3 - > smol["maximum_storage_bytes"] - ): - raise PreflightError( - "trusted intake storage qualification is missing or differs" - ) - - for key, default in (("maximum_entries", 2000), ("maximum_path_bytes", 1024), - ("maximum_path_depth", 32)): - setting = "WORKSTREAM_ARTIFACT_SUBMISSION_ZIP_" + key.upper() - try: - configured = int(values.get(setting, str(default))) - except (TypeError, ValueError): - raise PreflightError("trusted intake inspection limit is invalid") from None - if not 0 < configured <= envelope[key]: - raise PreflightError("trusted intake inspection limit exceeds storage qualification") - - # Qualification must cover supported inputs, independently of transient free space. - internal_zip_bytes = 512 * 1024**2 - try: - expanded = int(values.get("WORKSTREAM_ARTIFACT_SUBMISSION_ZIP_MAXIMUM_EXPANDED_BYTES", - str(internal_zip_bytes))) - ratio = int(values.get("WORKSTREAM_ARTIFACT_SUBMISSION_ZIP_MAXIMUM_COMPRESSION_RATIO", "100")) - except (TypeError, ValueError): - raise PreflightError("trusted intake expansion limits are invalid") from None - if not 0 < expanded <= internal_zip_bytes or not 0 < ratio <= 2**64 - 1: - raise PreflightError("trusted intake expansion limits are invalid") - required_bytes = internal_zip_bytes + min(expanded, internal_zip_bytes * ratio) + envelope["overhead_bytes"] - rounded_bytes = required_bytes + 1024**3 - 1 - if rounded_bytes > 2**64 - 1 or rounded_bytes // 1024**3 > envelope["maximum_storage_gib"]: - raise PreflightError("trusted intake storage qualification cannot cover supported ZIPs") - - trial_path, trial_digest = (values.get(key) or None for key in TRIAL_KEYS) - if ( - config.get("trial_authority_manifest_path"), - config.get("trial_authority_manifest_digest"), - ) != (trial_path, trial_digest): - raise PreflightError("native trial authority differs from the model proxy") - trial = config.get("trial_runtime") - if trial_path: - path_keys = ( - "relay_root", - "scratch_root", - "child_home_root", - "offline_cache_root", - "trusted_launcher_path", - "filesystem_tool_path", - ) - digest_keys = ( - "outer_runtime_config_digest", - "builder_image_id", - "trusted_launcher_digest", - "filesystem_tool_digest", - ) - if ( - not isinstance(trial, dict) - or set(trial) - != { - *path_keys, - *digest_keys, - "deployment_owner", - "maximum_candidate_archive_bytes", - } - or any( - not isinstance(trial[key], str) or not Path(trial[key]).is_absolute() - for key in path_keys - ) - or any( - not isinstance(trial[key], str) or not DIGEST.fullmatch(trial[key]) - for key in digest_keys - ) - or not isinstance(trial["deployment_owner"], str) - or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", trial["deployment_owner"]) - or type(trial["maximum_candidate_archive_bytes"]) is not int - or not 0 < trial["maximum_candidate_archive_bytes"] <= 2**64 - 1 - or trial["builder_image_id"] - not in {entry["config_image_id"] for entry in cache} - ): - raise PreflightError("native trial runtime configuration is incomplete") - if len(os.fsencode(trial["child_home_root"])) > 18: - raise PreflightError( - "native trial child home root exceeds the 18-byte socket path budget" - ) - elif trial is not None: - raise PreflightError("native trial runtime lacks a pinned authority manifest") - - def validate_local_data_environment(values: dict[str, str]) -> None: if not any(values.get(key) for key in LOCAL_DATA_KEYS): return @@ -1102,21 +828,6 @@ def _role_secret_file_keys(role: str, values: dict[str, str]) -> tuple[str, ...] return keys -def _validate_native_socket(path: Path, uid: int, gid: int) -> None: - try: - metadata = path.lstat() - except OSError as exc: - raise PreflightError("native node socket is unavailable") from exc - if ( - not stat.S_ISSOCK(metadata.st_mode) - or metadata.st_uid != uid - or metadata.st_gid != gid - or stat.S_IMODE(metadata.st_mode) != 0o600 - or metadata.st_nlink != 1 - ): - raise PreflightError("native node socket identity is unsafe") - - def validate_private_host_inputs( values: dict[str, str], *, require_node: bool = True ) -> None: @@ -2228,218 +1939,6 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: raise PreflightError(f"secret value was interpolated into Compose: {key}") -def _verify_smol_asset(path: Path, expected: str, uid: int, deadline: float) -> None: - """Hash pinned regular assets without symlinks or writable substitutions.""" - try: - if path.resolve(strict=True) != path: - raise PreflightError("native Smol asset path is not canonical") - descriptor = os.open( - path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC - ) - with os.fdopen(descriptor, "rb") as asset: - metadata = os.fstat(asset.fileno()) - if ( - not stat.S_ISREG(metadata.st_mode) - or metadata.st_uid not in {0, uid} - or metadata.st_mode & 0o022 - ): - raise PreflightError("native Smol asset custody is unsafe") - digest = hashlib.sha256() - while True: - if time.monotonic() >= deadline: - raise PreflightError( - "native Smol asset verification deadline exceeded" - ) - chunk = asset.read(65536) - if not chunk: - break - digest.update(chunk) - current = path.lstat() - if ( - not os.path.samestat(metadata, current) - or metadata.st_size != current.st_size - or "sha256:" + digest.hexdigest() != expected - ): - raise PreflightError("native Smol asset digest or identity differs") - except PreflightError: - raise - except (OSError, RuntimeError) as exc: - raise PreflightError("native Smol asset is unavailable") from exc - - -def validate_smol_runtime(config: dict[str, Any], values: dict[str, str]) -> None: - """Check pinned native inputs, delegation and the existing typed node health.""" - paths = deployment_paths(values) - uid = _positive_id(values, "WORKSTREAM_RUNTIME_UID") - gid = _positive_id(values, "WORKSTREAM_RUNTIME_GID") - smol = config["smol"] - _private_metadata( - Path(smol["home"]), kind="directory", uid=uid, gid=gid, mode=0o700 - ) - group = Path(smol["cgroup_root"]) - try: - if ( - group.resolve(strict=True) != group - or group.stat().st_uid != uid - or not group.joinpath("controller").is_dir() - ): - raise PreflightError("native Smol cgroup delegation identity differs") - for name in ("cgroup.controllers", "cgroup.subtree_control"): - with group.joinpath(name).open("r", encoding="ascii") as control: - controllers = control.read(4097) - if len(controllers) > 4096 or not {"cpu", "memory", "pids"} <= set( - controllers.split() - ): - raise PreflightError("native Smol cgroup delegation is incomplete") - except (OSError, UnicodeError) as exc: - raise PreflightError("native Smol cgroup delegation is unavailable") from exc - deadline = time.monotonic() + 30 - _verify_smol_asset( - checker_service_binary(values), - values["WORKSTREAM_CHECKER_SERVICE_BINARY_SHA256"], - uid, - deadline, - ) - for path, digest in [ - (smol["binary"], smol["binary_sha256"]), - (smol["guest_binary"], smol["guest_sha256"]), - ]: - _verify_smol_asset(Path(path), digest, uid, deadline) - for entry in config["cache"]: - _verify_smol_asset( - Path(entry["smol"]["archive"]), - entry["smol"]["archive_sha256"], - uid, - deadline, - ) - _verify_smol_asset( - Path(entry["smol"]["image_config"]), entry["config_image_id"], uid, deadline - ) - if values.get(TRIAL_KEYS[0]): - _verify_smol_asset( - Path(values[TRIAL_KEYS[0]]), values[TRIAL_KEYS[1]], uid, deadline - ) - trial = config["trial_runtime"] - for key in ( - "relay_root", - "scratch_root", - "child_home_root", - "offline_cache_root", - ): - _private_metadata( - Path(trial[key]), kind="directory", uid=uid, gid=gid, mode=0o700 - ) - for path_key, digest_key in ( - ("trusted_launcher_path", "trusted_launcher_digest"), - ("filesystem_tool_path", "filesystem_tool_digest"), - ): - _verify_smol_asset(Path(trial[path_key]), trial[digest_key], uid, deadline) - script = ( - "import asyncio,json; from dataclasses import asdict; from pathlib import Path; " - "from app.core.config import Settings; " - "from app.adapters.checkers import configured_external_checker_execution; " - "s=Settings(external_checker_service_socket=Path(" - + repr(str(paths.socket)) - + "),artifact_scratch_root=Path(" - + repr(str(paths.scratch)) - + "),external_checker_material_root=Path(" - + repr(str(paths.scratch)) - + "),external_checker_service_timeout_seconds=5.0); " - "print(json.dumps(asdict(asyncio.run(configured_external_checker_execution(s).health()))))" - ) - health = _run_json( - [ - "docker", - "run", - "--rm", - "--pull=never", - "--network", - "none", - "--read-only", - "--cap-drop=ALL", - "--security-opt=no-new-privileges", - "--pids-limit=64", - "--memory=512m", - "--cpus=1", - "--user", - str(uid) + ":" + str(gid), - "--mount", - f"type=bind,src={paths.socket_root},dst={paths.socket_root},readonly", - "--entrypoint", - "python", - values["WORKSTREAM_BACKEND_IMAGE"], - "-c", - script, - ], - failure="native Smol project readiness failed", - environment=compose_environment(values), - ) - if ( - not isinstance(health, dict) - or health.get("runtime") != "smolvm" - or health.get("isolation_mode") != "smol-microvm" - or health.get("operating_system") != config["operating_system"] - or health.get("architecture") != config["architecture"] - or health.get("sandbox_uid") != uid - or health.get("sandbox_gid") != gid - or health.get("cached_platform_manifests") != len(config["cache"]) - ): - raise PreflightError("native Smol project readiness identity differs") - - -def validate_trusted_intake(values: dict[str, str]) -> None: - """Use the release image's typed ART adapter without mounting credentials.""" - paths = deployment_paths(values) - script = ( - "import asyncio,json; from dataclasses import asdict; from pathlib import Path; " - "from app.core.config import Settings; " - "from app.adapters.artifacts import trusted_submission_intake; " - "s=Settings(artifact_intake_service_socket=Path(" - + repr(str(paths.socket)) - + "),artifact_intake_image_digest=" - + repr(values[INTAKE_DIGEST_KEYS[0]]) - + ",artifact_intake_config_digest=" - + repr(values[INTAKE_DIGEST_KEYS[1]]) - + "); " - "print(json.dumps(asdict(asyncio.run(trusted_submission_intake(s).health()))))" - ) - health = _run_json( - [ - "docker", - "run", - "--rm", - "--pull=never", - "--network", - "none", - "--read-only", - "--cap-drop=ALL", - "--security-opt=no-new-privileges", - "--pids-limit=64", - "--memory=512m", - "--cpus=1", - "--user", - values["WORKSTREAM_RUNTIME_UID"] + ":" + values["WORKSTREAM_RUNTIME_GID"], - "--mount", - f"type=bind,src={paths.socket_root},dst={paths.socket_root},readonly", - "--entrypoint", - "python", - values["WORKSTREAM_BACKEND_IMAGE"], - "-c", - script, - ], - failure="trusted Smol intake readiness failed", - environment=compose_environment(values), - ) - if ( - not isinstance(health, dict) - or (health.get("runtime"), health.get("isolation_mode")) - != ("smolvm", "smol-microvm") - or health.get("image_digest") != values[INTAKE_DIGEST_KEYS[0]] - or health.get("config_digest") != values[INTAKE_DIGEST_KEYS[1]] - ): - raise PreflightError("trusted intake readiness identity differs") - - def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--env-file", required=True, type=Path) diff --git a/deploy/hosted/release.env.example b/deploy/hosted/release.env.example index 4eb036494..56dcdf686 100644 --- a/deploy/hosted/release.env.example +++ b/deploy/hosted/release.env.example @@ -13,11 +13,11 @@ WORKSTREAM_RUNTIME_GID=10001 WORKSTREAM_API_HOST_PORT=8000 WORKSTREAM_CELERY_WORKER_CONCURRENCY=1 -# Optional single-host PostgreSQL/Redis. Set all seven together to select the +# Optional host-local PostgreSQL/Redis. Set all seven together to select the # local-data overlay; leave blank when using environment-managed services. # Use PostgreSQL 16 bookworm and Redis 7 bookworm images with reviewed digests # and their numeric UID/GID 999. initialize-local-data.py prints private paths -# and never prints generated credentials. See SINGLE_HOST.md. +# and never prints generated credentials. See the hosted operator guide. WORKSTREAM_POSTGRES_IMAGE= WORKSTREAM_REDIS_IMAGE= WORKSTREAM_POSTGRES_DATA_DIR= diff --git a/external_checkers/deploy/runner-qualification-20261124.md b/external_checkers/deploy/runner-qualification-20261124.md new file mode 100644 index 000000000..5345bdf0e --- /dev/null +++ b/external_checkers/deploy/runner-qualification-20261124.md @@ -0,0 +1,95 @@ +# Dedicated runner qualification — 2026-11-24 + +This is the non-secret deployment receipt for the first dedicated hosted Smol +node. It records observed identities and exact digests; it does not contain TLS, +SSH or AWS credential material. + +## AWS resources + +- runner instance: `i-0936c305f8f67d835`, on-demand `m7i.large`, + `eu-north-1a`, private address `172.31.21.182` +- runner security group: `sg-06167eb0a825ed79a` +- encrypted 100 GiB gp3 volume: `vol-0cd68046697a4b662` +- app instance (unchanged): `i-000b0c090ddc142bd`, private address + `172.31.17.97`, security group `sg-015b341d9f8d39117` +- shared VPC: `vpc-049ecd21b84781a6a` + +The required private application rule is TCP 9443 on the runner security group +with source `sg-015b341d9f8d39117`. No public 9443 ingress is required. + +## Pinned runtime + +- service source: reviewed integration descendant of `99049d0c25d177500e733f8e14659f83ff0cb53e` +- qualified service binary: `sha256:d792b8f84f44ab495c3369b865f55f8d4b8901b3d14b0a3299238df20f27538f` +- guest: `sha256:ded79cf4f7d4a29a4a3571f9427ef63a86ae8ad34f9d5ef9af79a25265e2e476` +- Smol v1.31.4 binary: `sha256:b67b25f363403e19deceb6897e5a4d94be30a079f8cb751372782f17fc99003a` +- checker image/config: `sha256:526f081b8f2a86b7e7b5d1963a96fdcd179c989db3c9d64ca70ec209c945b87f` / + `sha256:8b19b951a661dfdf23808252eb74b883a11078e23c6e9ff11507be9ee2b6d07c` +- trusted intake image/config: `sha256:f77b5470b269ebce8ab2b467fcf0c52be814c2db9e5306aab090f45e7e2d8b81` / + `sha256:6a83910f3989fb657a405188d9b84b1815993be7af11bb399246a0d30100c5b0` +- PRE root: 462,365,541 bytes, + `sha256:b87e18c8713f2a80f03b0f358ef44338aaa5e851d5570573d31ee979b5cc6509` +- installed service config: + `sha256:c35de5c4f38db8c5b9d003e47d4bf9e4310f22549c6e8dde65bdd27d57ecf5a6` + +## Live receipts + +TLS 1.3 mutual authentication reported Linux amd64, Smol microVM isolation, +two cached platform manifests, and sandbox uid/gid 10001. + +The real POST returned a completed, request-bound result from the pinned image: + +- request: `sha256:43179e023a83ff620ae9b1b0c8922f42bab8880c2bf8d9a9f3a8ddcc0c926db7` +- outcome/verdict: `completed` / `failed` +- expected finding: `harnessy.proof.missing` from the deliberately empty material + +The real streamed-ZIP PRE returned a completed native receipt: + +- source: `sha256:d99e15d519bfbfd3b579336e074a05a89018be10392491437a96072babf40f79` +- request: `sha256:fb0a937904f8371031b93d9989c6accd50ab67a3960b983a24da255140611c8f` +- outcome: `completed`; selected checker: `completed` / `failed` +- isolation: `smolvm` / `smol-microvm` +- cleanup: `destroyed` +- timings in milliseconds: admission 0, preparation 3395, execution 78916, + cleanup 124, total 82437 + +After POST and PRE, the material workspace, model relay and Smol lease roots were +empty. Both `workstream-remote-node.service` and +`workstream-checker.service` remained active with one task each. + +The follow-up crash-recovery guard admits no new session when `workspaces` +contains residue. Reconciliation is a separate stopped-native operation: + +```sh +sudo systemctl stop workstream-checker.service workstream-remote-node.service +sudo -u '#10001' /usr/bin/python3 /opt/workstream/bin/workstream-remote-node \ + --config /etc/workstream/remote-node.json --reconcile-stale-workspaces +sudo systemctl start workstream-remote-node.service workstream-checker.service +``` + +The command refuses an existing native socket, a non-private or foreign-owned +root, more than one residue, unknown names, links, special files, foreign-owned +members, more than 14,000 members or more than 1 GiB plus the bounded control +envelope. It never deletes an active or uncertain grant. The focused restart +proof covers both `.incoming-*` and renamed `extract_*` residue, refusal while +the native socket exists, exact removal after confirmed stop, and clean restart. + +## Evidence and secret locations + +- this saved non-secret receipt: + `external_checkers/deploy/runner-qualification-20261124.md` +- live runner logs: system journal units `workstream-remote-node.service` and + `workstream-checker.service` +- live configs: `/etc/workstream/remote-node.json` and + `/etc/workstream/checker-service.json` +- pinned SSH host keys: + `/home/abiorh/flow/workstream_aws_setup_582/runner-20261124-known-hosts` +- staged app client TLS files: + `/home/abiorh/flow/workstream_aws_setup_582/runner-20261124-assets/tls/ca.crt`, + `app.crt`, and `app.key` + +`app.key` is private and must be installed as a mode-0400 Compose secret without +printing or copying its contents into reviews or logs. + +Successful governed acceptance and an actual provider-backed model callback are +separate integration qualifications; the transport smoke does not claim either. diff --git a/external_checkers/remote_node.py b/external_checkers/remote_node.py index 1dc65964f..74aa9b8ec 100644 --- a/external_checkers/remote_node.py +++ b/external_checkers/remote_node.py @@ -27,6 +27,7 @@ MAXIMUM_MATERIAL_BYTES = 1024 * 1024 * 1024 MAXIMUM_FILES = 4_000 _GRANT_ID = re.compile(r"extract_[0-9a-f]{32}") +_INCOMING_ID = re.compile(r"\.incoming-[0-9a-f]{32}") _SHA256 = re.compile(r"sha256:[0-9a-f]{64}") @@ -34,50 +35,6 @@ class ProtocolError(Exception): """A remote peer sent a malformed or unbound request.""" -class ModelBridge: - """Serialize runner-local callbacks over one app-authenticated TLS session.""" - - def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: - self.reader, self.writer = reader, writer - self.lock = asyncio.Lock() - self.closed = asyncio.Event() - - async def exchange(self, request: bytes) -> bytes: - async with self.lock: - if self.closed.is_set(): - raise ProtocolError("model bridge is unavailable") - channel_id = uuid.uuid4().hex - header = json.dumps( - { - "protocol_version": PROTOCOL, - "operation": "model_request", - "channel_id": channel_id, - }, - separators=(",", ":"), - ).encode() - try: - await _write_frame(self.writer, header) - await _write_frame(self.writer, request) - response_header = _decode_object( - await _read_frame(self.reader, MAXIMUM_CONTROL_BYTES) - ) - if response_header != { - "protocol_version": PROTOCOL, - "operation": "model_response", - "channel_id": channel_id, - }: - raise ProtocolError("model response header differs") - return await _read_frame(self.reader, MAXIMUM_FRAME_BYTES) - except (OSError, ssl.SSLError, asyncio.IncompleteReadError): - self.close() - raise ProtocolError("model bridge is unavailable") from None - - def close(self) -> None: - if not self.closed.is_set(): - self.closed.set() - self.writer.close() - - def _closed_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: value: dict[str, Any] = {} for key, item in pairs: @@ -122,6 +79,87 @@ async def _write_frame(writer: asyncio.StreamWriter, body: bytes) -> None: await writer.drain() +class ExecutionChannel: + """Multiplex native callback frames over the exact owning execute connection.""" + + def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + self.reader, self.writer = reader, writer + self.closed = asyncio.Event() + self._write_lock = asyncio.Lock() + self._pending: dict[str, asyncio.Future[bytes]] = {} + self._router = asyncio.create_task(self._route_responses()) + + async def callback(self, request: bytes) -> bytes: + channel_id = uuid.uuid4().hex + future = asyncio.get_running_loop().create_future() + self._pending[channel_id] = future + try: + async with self._write_lock: + if self.closed.is_set(): + raise ProtocolError("execute channel is unavailable") + await _write_frame( + self.writer, + json.dumps( + { + "protocol_version": PROTOCOL, + "operation": "callback_request", + "channel_id": channel_id, + }, + separators=(",", ":"), + ).encode(), + ) + await _write_frame(self.writer, request) + return await future + finally: + self._pending.pop(channel_id, None) + + async def result(self, response: bytes) -> None: + async with self._write_lock: + if self.closed.is_set(): + raise ProtocolError("execute channel is unavailable") + await _write_frame( + self.writer, + json.dumps( + {"protocol_version": PROTOCOL, "operation": "execution_result"}, + separators=(",", ":"), + ).encode(), + ) + await _write_frame(self.writer, response) + + async def _route_responses(self) -> None: + failure: BaseException = ProtocolError("execute channel closed") + try: + while True: + header = _decode_object(await _read_frame(self.reader, 16_384)) + if ( + set(header) != {"protocol_version", "operation", "channel_id"} + or header.get("protocol_version") != PROTOCOL + or header.get("operation") != "callback_response" + or type(header.get("channel_id")) is not str + ): + raise ProtocolError("callback response header is invalid") + future = self._pending.get(header["channel_id"]) + if future is None or future.done(): + raise ProtocolError("callback response has no owner") + future.set_result(await _read_frame(self.reader, MAXIMUM_FRAME_BYTES)) + except asyncio.CancelledError as exc: + failure = exc + raise + except (ProtocolError, OSError, ssl.SSLError, asyncio.IncompleteReadError) as exc: + failure = exc + finally: + self.closed.set() + for future in tuple(self._pending.values()): + if not future.done(): + future.set_exception(failure) + + async def close(self) -> None: + if not self._router.done(): + self._router.cancel() + await asyncio.gather(self._router, return_exceptions=True) + self.closed.set() + + def _peer_name(writer: asyncio.StreamWriter) -> set[str]: certificate = writer.get_extra_info("peercert") if type(certificate) is not dict: @@ -152,6 +190,7 @@ def _manifest_files( raise ProtocolError("material inventory is invalid") values: list[tuple[PurePosixPath, int, str, bool]] = [] roles: set[str] = set() + inventory_entries = 0 for item in materials: if type(item) is not dict or set(item) != {"material", "directories", "files"}: raise ProtocolError("material descriptor is invalid") @@ -168,6 +207,9 @@ def _manifest_files( files = item["files"] if type(directories) is not list or type(files) is not list: raise ProtocolError("material inventory is invalid") + inventory_entries += len(directories) + len(files) + if inventory_entries > MAXIMUM_FILES: + raise ProtocolError("material inventory is unbounded") seen: set[str] = set() for value in directories: path = _relative_path(value) @@ -194,8 +236,6 @@ def _manifest_files( raise ProtocolError("material file is invalid") seen.add(str(path)) values.append((PurePosixPath("materials", role, *path.parts), count, digest, executable)) - if len(values) > MAXIMUM_FILES: - raise ProtocolError("material file count is unbounded") return tuple(values) @@ -232,6 +272,56 @@ def _remove_tree(path: Path) -> None: shutil.rmtree(path) +def _reconcile_stale_workspaces(config: dict[str, Any]) -> int: + """Remove only bounded edge-owned residue while the native service is stopped.""" + socket_path = Path(config.get("socket_path", "")) + material_root = Path(config.get("material_root", "")) + workspaces = material_root / "workspaces" + if not socket_path.is_absolute() or socket_path.exists(): + raise ValueError("native service must be stopped before reconciliation") + metadata = workspaces.lstat() + if ( + not stat.S_ISDIR(metadata.st_mode) + or stat.S_ISLNK(metadata.st_mode) + or metadata.st_uid != os.getuid() + or metadata.st_mode & 0o077 + or workspaces.resolve() != workspaces + ): + raise ValueError("workspace root custody is invalid") + entries = sorted(workspaces.iterdir()) + # One exclusive execution can leave at most one renamed or incoming tree. + # More residue cannot be attributed safely to one crashed edge process. + if len(entries) > 1: + raise ValueError("workspace residue ownership is uncertain") + removed = 0 + for entry in entries: + if ( + not (_GRANT_ID.fullmatch(entry.name) or _INCOMING_ID.fullmatch(entry.name)) + or entry.is_symlink() + or not entry.is_dir() + ): + raise ValueError("workspace residue ownership is uncertain") + count, total = 0, 0 + for current, directories, files in os.walk(entry, followlinks=False): + for name in (*directories, *files): + item = Path(current, name) + observed = item.lstat() + if ( + observed.st_uid != os.getuid() + or stat.S_ISLNK(observed.st_mode) + or not (stat.S_ISDIR(observed.st_mode) or stat.S_ISREG(observed.st_mode)) + ): + raise ValueError("workspace residue ownership is uncertain") + count += 1 + if stat.S_ISREG(observed.st_mode): + total += observed.st_size + if count > MAXIMUM_FILES + 10_000 or total > MAXIMUM_MATERIAL_BYTES + MAXIMUM_CONTROL_BYTES: + raise ValueError("workspace residue is unbounded") + _remove_tree(entry) + removed += 1 + return removed + + def _write_descriptor(descriptor: int, body: bytes) -> None: view = memoryview(body) while view: @@ -276,11 +366,22 @@ def __init__(self, config: dict[str, Any]) -> None: if ( not self.material_root.is_dir() or self.material_root.is_symlink() + or metadata.st_uid != os.getuid() or metadata.st_mode & 0o077 or self.material_root.resolve() != self.material_root ): raise ValueError("remote node material root is not private") self.workspaces.mkdir(mode=0o700, exist_ok=True) + workspace_metadata = self.workspaces.lstat() + if ( + not stat.S_ISDIR(workspace_metadata.st_mode) + or stat.S_ISLNK(workspace_metadata.st_mode) + or workspace_metadata.st_uid != os.getuid() + or workspace_metadata.st_mode & 0o077 + or self.workspaces.resolve() != self.workspaces + or any(self.workspaces.iterdir()) + ): + raise ValueError("remote node workspace root requires reconciliation") context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.minimum_version = ssl.TLSVersion.TLSv1_3 context.verify_mode = ssl.CERT_REQUIRED @@ -288,7 +389,7 @@ def __init__(self, config: dict[str, Any]) -> None: context.load_verify_locations(config["tls_ca_path"]) self.ssl_context = context self._execution = asyncio.Lock() - self._model_bridge: ModelBridge | None = None + self._active_channel: ExecutionChannel | None = None self._model_server: asyncio.AbstractServer | None = None async def start_model_proxy(self) -> None: @@ -325,8 +426,6 @@ async def close(self) -> None: if self._model_server is not None: self._model_server.close() await self._model_server.wait_closed() - if self._model_bridge is not None: - self._model_bridge.close() try: metadata = self.model_proxy_socket_path.lstat() if stat.S_ISSOCK(metadata.st_mode) and metadata.st_uid == os.getuid(): @@ -340,10 +439,10 @@ async def _handle_model_proxy( try: async with asyncio.timeout(self.timeout): request = await _read_frame(reader, MAXIMUM_FRAME_BYTES) - bridge = self._model_bridge - if bridge is None: - raise ProtocolError("model bridge is unavailable") - response = await bridge.exchange(request) + channel = self._active_channel + if channel is None: + raise ProtocolError("execute callback owner is unavailable") + response = await channel.callback(request) await _write_frame(writer, response) if await reader.read(1): raise ProtocolError("model proxy request contains trailing data") @@ -372,10 +471,6 @@ async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWrite }: raise ProtocolError("proxy request is invalid") await self._proxy(reader, writer) - elif operation == "model_bridge": - if set(control) != {"protocol_version", "operation", "capability"} or capability != CHECKER_CAPABILITY: - raise ProtocolError("model bridge request is invalid") - await self._serve_model_bridge(reader, writer) elif operation == "execute": if capability != CHECKER_CAPABILITY: raise ProtocolError("execute capability differs") @@ -391,31 +486,6 @@ async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWrite except (OSError, ssl.SSLError): pass - async def _serve_model_bridge( - self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter - ) -> None: - bridge = ModelBridge(reader, writer) - previous = self._model_bridge - self._model_bridge = bridge - if previous is not None: - previous.close() - await _write_frame( - writer, - json.dumps( - { - "protocol_version": PROTOCOL, - "operation": "model_bridge", - "status": "ready", - }, - separators=(",", ":"), - ).encode(), - ) - try: - await bridge.closed.wait() - finally: - if self._model_bridge is bridge: - self._model_bridge = None - async def _proxy(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: native_reader, native_writer = await asyncio.open_unix_connection(self.socket_path) @@ -424,19 +494,23 @@ async def copy(source: asyncio.StreamReader, target: asyncio.StreamWriter) -> No target.write(chunk) await target.drain() - tasks = { - asyncio.create_task(copy(reader, native_writer)), - asyncio.create_task(copy(native_reader, writer)), - } - done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) - for task in pending: - task.cancel() - await asyncio.gather(*done, *pending, return_exceptions=True) - native_writer.close() + tasks: set[asyncio.Task[None]] = set() try: - await native_writer.wait_closed() - except OSError: - pass + tasks = { + asyncio.create_task(copy(reader, native_writer)), + asyncio.create_task(copy(native_reader, writer)), + } + await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + finally: + for task in tasks: + if not task.done(): + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + native_writer.close() + try: + await native_writer.wait_closed() + except OSError: + pass async def _execute( self, @@ -510,6 +584,8 @@ async def _stage_and_execute( target = self.workspaces / grant_id incoming = self.workspaces / f".incoming-{uuid.uuid4().hex}" native_writer: asyncio.StreamWriter | None = None + channel: ExecutionChannel | None = None + wait_tasks: set[asyncio.Task[Any]] = set() if target.exists(): raise ProtocolError("grant is already active") incoming.mkdir(mode=0o700) @@ -547,19 +623,30 @@ async def _stage_and_execute( encoded = json.dumps( request, ensure_ascii=False, allow_nan=False, separators=(",", ":") ).encode() + channel = ExecutionChannel(reader, writer) + if self._active_channel is not None: + raise ProtocolError("execute callback owner is already active") + self._active_channel = channel await _write_frame(native_writer, encoded) response_task = asyncio.create_task(_read_frame(native_reader, MAXIMUM_FRAME_BYTES)) - disconnect_task = asyncio.create_task(reader.read(1)) + disconnect_task = asyncio.create_task(channel.closed.wait()) + wait_tasks = {response_task, disconnect_task} done, _ = await asyncio.wait( - {response_task, disconnect_task}, return_when=asyncio.FIRST_COMPLETED + wait_tasks, return_when=asyncio.FIRST_COMPLETED ) if disconnect_task in done: - response_task.cancel() raise ProtocolError("remote client disconnected") - disconnect_task.cancel() response = await response_task - await _write_frame(writer, response) + await channel.result(response) finally: + for task in wait_tasks: + if not task.done(): + task.cancel() + await asyncio.gather(*wait_tasks, return_exceptions=True) + if self._active_channel is channel: + self._active_channel = None + if channel is not None: + await channel.close() if native_writer is not None: native_writer.close() try: @@ -571,10 +658,7 @@ async def _stage_and_execute( async def _main(config_path: Path) -> None: - raw = config_path.read_bytes() - if len(raw) > 64 * 1024: - raise ValueError("remote node configuration is too large") - node = RemoteNode(_decode_object(raw)) + node = RemoteNode(_load_config(config_path)) await node.start_model_proxy() try: server = await asyncio.start_server( @@ -590,8 +674,20 @@ async def _main(config_path: Path) -> None: await node.close() +def _load_config(config_path: Path) -> dict[str, Any]: + raw = config_path.read_bytes() + if len(raw) > 64 * 1024: + raise ValueError("remote node configuration is too large") + return _decode_object(raw) + + if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--reconcile-stale-workspaces", action="store_true") arguments = parser.parse_args() - asyncio.run(_main(arguments.config)) + if arguments.reconcile_stale_workspaces: + configuration = _load_config(arguments.config) + print(_reconcile_stale_workspaces(configuration)) + else: + asyncio.run(_main(arguments.config)) From c8a6cc9da9abb81438bc159d8e017087de8af29c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:19:08 +0100 Subject: [PATCH 265/513] Verify revision fence changes during public ZIP upload --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 28 ++++++ .../test_submission_predecessor_custody.py | 86 ++++++------------- 2 files changed, 56 insertions(+), 58 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8db646bd7..6409788cd 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8731,3 +8731,31 @@ cases then passed in45.39s; /tmp/submission-public-nonremediation-repair.json records schema0090 and complete database/MinIO cleanup (launcher02920f9ff with final test edits). Structure, Ruff and diff checks passed. This is controlled storage failure plus real HTTP/SQL authority proof, not live provider acceptance. + +QA closed b976a7d2d PASS WITH LOW RISKS; no lost refusal/infrastructure assertions. +Next bounded retirement migrates the upload-time superseded revision cause test +onto public raw-ZIP intake. Allowed: predecessor custody test and this record. +Preserve real checker-fence advancement during body consumption, refusal before +PRE/admission/Submission, and current-context denial. Unlike obsolete scratch +preparation, the new source upload has durable cleanup custody: assert sealed +charged source survives failed intake without acceptance/finalization. Remove +only now-unused local preparation helper/imports. No production/schema changes. +Medium workflow-test risk; isolated PostgreSQL race test, Ruff/structure and +focused QA review. Human focus: no late acceptance or false quota release. + +The upload-fence race passed in42.64s with schema0090 and full PostgreSQL/MinIO +cleanup (/tmp/submission-public-upload-fence-sized.json; launcher8fa9ae12c with +final test edits). The first request hit429 before the race because an unknown +stream length reserved the configured maximum; supplying the exact content +length exercises the intended race without weakening quota. Actual body read +advances the checker fence; fresh context refuses before any PRE reservation, +operation ends failed and its sealed source stays fully charged for cleanup. +One existing POST fixture Pydantic serialization warning was emitted. Ruff/diff +passed. Removed the now-unused local preparation helper and its dependencies. + +Runner repair a64729edc integrated as8fa9ae12c. Scoped ARCH/SEC replay passed: +callback connection ownership, proxy cancellation and known workspace residue +reconciliation findings closed. The initially suspected missing worker model +socket was retracted after checking the selected inference Compose overlay. +Agent reports112 focused tests; real provider callbacks and complete public +acceptance remain unqualified. No app deployment or restart occurred. diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 5b0fdc4e1..c7d6ccecd 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -3,8 +3,6 @@ from __future__ import annotations import asyncio -from unittest.mock import patch -from tests.trusted_intake_fixtures import LocalIntakeAdapter from dataclasses import replace from io import BytesIO @@ -14,26 +12,18 @@ from zipfile import ZipFile import pytest -from sqlalchemy import text +from sqlalchemy import select, text from sqlalchemy.exc import DBAPIError, IntegrityError -from starlette.requests import Request from app.adapters.checkers import evaluation_coordinator -from app.adapters.artifacts import get_submission_bundle_preparation_command from app.adapters.tasks import task_post_submit_outcome from app.adapters.artifacts.local import LocalStorageAdapter from app.core.identifiers import new_record_id from app.core.hashing import canonical_json_hash -from app.modules.actors.api.service_identities import ServiceIdentity from app.interfaces.artifacts import ArtifactStoreUnavailableError from app.modules.artifacts.api import ( - SubmissionBundlePreparationRejected, SubmissionBundlePreparationRequest, ) -from app.modules.artifacts.authorization import ( - PreparedArtifactInternalAuthority, - PreparedSubmissionBundlePreparationAuthorization, -) from app.modules.checkers.models import CheckerRun, SelectedPreSubmitRun from app.modules.artifacts.models import ( SubmissionBundleAdmission, @@ -74,18 +64,6 @@ async def traced(self, *args, _original=original, _operation=operation, **kwargs return calls -def _http_request(settings) -> Request: - return Request( - { - "type": "http", - "headers": [], - "app": SimpleNamespace( - state=SimpleNamespace( - settings=settings, - ) - ), - } - ) def _replacement_request(h, data: bytes, *, predecessor_id: UUID, idempotency_key: UUID): @@ -111,22 +89,6 @@ def _replacement_request(h, data: bytes, *, predecessor_id: UUID, idempotency_ke ) -async def _prepare(h, request: SubmissionBundlePreparationRequest): - http = _http_request(h.settings) - async with h.factory() as session: - internal = PreparedArtifactInternalAuthority( - session, - service_identity=ServiceIdentity.ARTIFACT_PUT_RESOLVER, - request_id=new_record_id(), - correlation_id=new_record_id(), - ) - with patch("app.adapters.artifacts.trusted_submission_intake", return_value=LocalIntakeAdapter()): - return await get_submission_bundle_preparation_command( - http, - session, - internal, - PreparedSubmissionBundlePreparationAuthorization(session, h.actor_context), - ).prepare(request) async def _fixture_revision_context(h): @@ -892,45 +854,53 @@ async def forbidden_upload(*_args, **_kwargs): await no_economic_effects(session) -async def test_source_superseded_during_zip_read_stops_before_art_effects( +async def test_source_superseded_during_zip_read_refuses_acceptance( tmp_path, isolated_database_env, monkeypatch, ): + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.test_public_submission_intake import _client + provider_writes = _trace_provider_writes(monkeypatch) async with remediation_source(tmp_path, isolated_database_env) as h: source_id = await _fixture_revision_context(h) async with h.factory.begin() as session: - current = await task_submission_context_port(session).lock_submission_context( - _context_request(h) - ) + current = await task_submission_context_port(session).lock_submission_context(_context_request(h)) assert current.checker_remediation_manifest_id == source_id before = await _snapshot(h) provider_writes.clear() opened = [] + data = revision_archive(h.data) async def superseding_bytes(): opened.append(True) await reserve(h, await next_request(h)) - yield revision_archive(h.data) + yield data - with pytest.raises( - SubmissionBundlePreparationRejected, - match="submission_bundle_preparation_context_changed", - ): - await _prepare(h, replace( - _replacement_request( - h, revision_archive(h.data), predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ), - byte_source=superseding_bytes(), - )) + async with _client(h, monkeypatch, isolated_database_env) as client: + _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + headers = _revision_upload_headers(h) | {"Content-Length": str(len(data))} + response = await client.post( + f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=headers, content=superseding_bytes()) + assert response.status_code == 404, response.text + assert response.json()["error"]["code"] == "submission_unavailable" assert opened == [True] + assert calls == [] and not errors assert await _snapshot(h) == before assert provider_writes == [] async with h.factory.begin() as session: + operation = (await session.scalars(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.idempotency_key == headers["Idempotency-Key"]))).one() + assert operation.state == "failed" and operation.acceptance_receipt is None + assert operation.finalization_event_id is None and operation.finalized_submission_id is None + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.state == "sealed" and charge.accounted_bytes == len(data) + assert operation.raw_byte_count == len(data) + assert await session.scalar(text("SELECT count(*) FROM submissions")) == 1 + await no_economic_effects(session) with pytest.raises(TaskSubmissionContextUnavailable): - await task_submission_context_port(session).lock_submission_context( - _context_request(h) - ) + await task_submission_context_port(session).lock_submission_context(_context_request(h)) async def _predecessor_fence_snapshot(h, source_id): From 092986b8a361d3692bd2728697ea1f0bbb4c68e1 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:21:30 +0100 Subject: [PATCH 266/513] Align hosted tests with the remote runner --- .../changes/flow-self-service-signup.md | 7 + deploy/hosted/preflight.py | 16 +- scripts/test_hosted_release_config.py | 1146 +---------------- 3 files changed, 65 insertions(+), 1104 deletions(-) diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index 4d7c60484..6e3fe8786 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -443,3 +443,10 @@ Smol leases empty. Focused local remote transport/intake coverage passed 85 tests. Successful-checker public acceptance and a real model-callback provider journey remain explicit integration qualifications, not claims from the transport smoke tests. + +The hosted regression profile now contains 58 app-only/remote-runner cases. It +proves that only API and worker receive runner TLS identity, while only the +worker receives the read-only app-local model callback socket. Foreground PRE +uses `execute_pre`, whose contract prohibits model, trial and build grants; +POST and setup/trial callback execution remains worker-owned. The profile +contains no app-host native checker/socket readiness fallback. diff --git a/deploy/hosted/preflight.py b/deploy/hosted/preflight.py index 69df06521..b1ef5e16d 100644 --- a/deploy/hosted/preflight.py +++ b/deploy/hosted/preflight.py @@ -67,6 +67,7 @@ "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE", *INTAKE_DIGEST_KEYS, ) +REMOTE_RUNNER_SECRET_FILE_KEYS = REMOTE_RUNNER_KEYS[3:6] REMOTE_RUNNER_ENVIRONMENT_KEYS = ( "WORKSTREAM_EXTERNAL_RUNNER_HOST", "WORKSTREAM_EXTERNAL_RUNNER_PORT", @@ -221,12 +222,7 @@ def deployment_paths(values: dict[str, str]) -> HostedPaths: "WORKSTREAM_DATABASE_URL_FILE", "WORKSTREAM_CELERY_BROKER_URL_FILE", ), - "model-proxy": ( - "WORKSTREAM_DATABASE_URL_FILE", - "WORKSTREAM_EXTERNAL_RUNNER_CA_FILE", - "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE", - "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE", - ), + "model-proxy": ("WORKSTREAM_DATABASE_URL_FILE",), } FORBIDDEN_RELEASE_KEYS = ( "WORKSTREAM_GITHUB_APP_PRIVATE_KEY", @@ -1731,6 +1727,12 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: ) required_file_keys = set(_role_secret_file_keys(role, values)) for key, (_, target) in SECRET_FILE_TARGETS.items(): + if key in REMOTE_RUNNER_SECRET_FILE_KEYS: + if key in environment: + raise PreflightError( + f"{role} contains a host-only secret selector: {key}" + ) + continue if key in required_file_keys: if environment.get(key) != target: raise PreflightError( @@ -1840,7 +1842,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: else {} ), } - if name in {"api", "worker"} or (name == "model-proxy" and model_proxy_enabled) + if name in {"api", "worker"} else {} ) if { diff --git a/scripts/test_hosted_release_config.py b/scripts/test_hosted_release_config.py index a04865732..e23e3ce10 100644 --- a/scripts/test_hosted_release_config.py +++ b/scripts/test_hosted_release_config.py @@ -2,7 +2,7 @@ from __future__ import annotations -from contextlib import redirect_stderr, redirect_stdout +from contextlib import redirect_stderr import copy import hashlib import importlib.util @@ -10,7 +10,6 @@ import json import os from pathlib import Path -import socket import subprocess import sys import tempfile @@ -22,7 +21,6 @@ PREFLIGHT_PATH = ROOT / "deploy" / "hosted" / "preflight.py" ENTRYPOINT_PATH = ROOT / "docker" / "backend" / "release-entrypoint.sh" ENV_EXAMPLE = ROOT / "deploy" / "hosted" / "release.env.example" -CHECKER_EXAMPLE = ROOT / "deploy" / "hosted" / "checker-service.example.json" SPEC = importlib.util.spec_from_file_location( "hosted_release_preflight", PREFLIGHT_PATH @@ -48,14 +46,7 @@ def setUp(self) -> None: self.runtime_uid = 10001 self.runtime_gid = 10001 self.checker_path = self.root / "checker.json" - self.checker = json.loads(CHECKER_EXAMPLE.read_text(encoding="utf-8")) - self.checker["sandbox_uid"] = self.runtime_uid - self.checker["sandbox_gid"] = self.runtime_gid - # Synthetic test qualification, never an operational sizing recommendation. - self.checker["trusted_intake"]["storage_envelope"].update( - overhead_bytes=128 * 1024**2, maximum_storage_gib=2, - ) - self.checker_path.write_text(json.dumps(self.checker), encoding="utf-8") + self.checker_path.write_text("obsolete local checker sentinel", encoding="utf-8") self.direct_user_credentials = self.root / "aws-access-key.json" self.direct_user_credentials.write_text( json.dumps( @@ -77,10 +68,6 @@ def setUp(self) -> None: "WORKSTREAM_RUNTIME_GID=10001", f"WORKSTREAM_RUNTIME_GID={self.runtime_gid}", ) - .replace( - "WORKSTREAM_CHECKER_CONFIG_FILE=/etc/workstream/checker-service.json", - f"WORKSTREAM_CHECKER_CONFIG_FILE={self.checker_path}", - ) .replace( "/etc/workstream/aws/direct-user-credentials.json", str(self.direct_user_credentials), @@ -103,8 +90,6 @@ def local_data_environment(self): def app_environment(self): values = self.environment | {preflight.HOSTED_PROFILE_KEY: "app"} - for key in (*preflight.NATIVE_REQUIRED_KEYS, "WORKSTREAM_CHECKER_SERVICE_BINARY"): - values.pop(key) self.environment_path.write_text( "\n".join(f"{key}={value}" for key, value in values.items()) + "\n", encoding="utf-8", @@ -121,8 +106,30 @@ def test_app_profile_keeps_inference_and_rejects_native_runtime_custody(self): self.assertIn("guide-document-parser", services["worker"]["depends_on"]) self.assertIn("model-proxy", services["worker"]["depends_on"]) paths = preflight.deployment_paths(values) + self.assertEqual( + services["worker"]["environment"]["WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET"], + str(paths.model_socket), + ) + self.assertEqual( + services["model-proxy"]["environment"]["WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET"], + str(paths.model_socket), + ) + self.assertNotIn( + "WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET", services["api"]["environment"] + ) + worker_model_mount = preflight._service_mounts(services["worker"])[ + str(paths.model_socket.parent) + ] + self.assertEqual(worker_model_mount["source"], str(paths.model_socket.parent)) + self.assertTrue(worker_model_mount["read_only"]) for role in ("api", "worker"): - self.assertFalse(set(preflight.NATIVE_ENVIRONMENT_KEYS) & services[role]["environment"].keys()) + self.assertFalse( + { + "WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET", + "WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET", + } + & services[role]["environment"].keys() + ) self.assertNotIn(str(paths.socket_root), preflight._service_mounts(services[role])) for role in ("api", "worker", "model-proxy"): mounts = preflight._service_mounts(services[role]) @@ -151,9 +158,9 @@ def test_app_profile_keeps_inference_and_rejects_native_runtime_custody(self): preflight._service_mounts(services[role]), ) services["worker"]["environment"]["WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET"] = str(paths.socket) - with self.assertRaisesRegex(preflight.PreflightError, "native checker environment"): + with self.assertRaisesRegex(preflight.PreflightError, "environment"): preflight.validate_compose(rendered, values) - with self.assertRaisesRegex(preflight.PreflightError, "cannot configure a native checker"): + with self.assertRaisesRegex(preflight.PreflightError, "unsupported key"): preflight.validate_environment(values | {"WORKSTREAM_CHECKER_CONFIG_FILE": str(self.checker_path)}) with self.assertRaisesRegex(preflight.PreflightError, "requires the trusted model proxy"): preflight.validate_environment(values | {"WORKSTREAM_MODEL_PROXY_ENABLED": "false"}) @@ -163,9 +170,6 @@ def test_app_profile_starts_and_resumes_without_native_readiness(self): self.checker_path.unlink() with ( patch.object(compose, "validate_private_host_inputs") as private, - patch.object(compose, "validate_smol_runtime", side_effect=AssertionError("native runtime")), - patch.object(compose, "validate_trusted_intake", side_effect=AssertionError("native intake")), - patch.object(compose, "resume_native_checker", side_effect=AssertionError("native systemd")), patch.object(compose, "run_compose", return_value=0) as run, ): result, error = self._compose_main("up", "--detach") @@ -482,13 +486,11 @@ def test_identity_startup_checks_only_issuer_inputs_and_waits(self): compose, "validate_identity_host_inputs" ) as issuer_inputs, patch.object(compose, "validate_private_host_inputs") as backend_inputs, - patch.object(compose, "load_checker_config") as checker_inputs, patch.object(compose, "run_compose", return_value=0), ): self.assertEqual(compose.main(), 0) issuer_inputs.assert_called_once_with(values) backend_inputs.assert_not_called() - checker_inputs.assert_not_called() with patch.object( preflight.subprocess, "run", @@ -598,222 +600,6 @@ def test_worker_cannot_consume_finalization_or_omit_its_queue_selection(self) -> with self.assertRaisesRegex(preflight.PreflightError, "worker delivery profile"): preflight.validate_compose(changed, self.environment) - def test_valid_configuration_and_rendered_topology(self) -> None: - self.assertEqual( - str(preflight.deployment_paths(self.environment).socket_root), - "/var/lib/workstream/checker-runtime", - ) - preflight.validate_environment(self.environment) - preflight.validate_checker_config(self.checker, self.environment) - rendered = preflight.render_compose(self.environment_path, self.environment) - preflight.validate_compose(rendered, self.environment) - self.assertEqual( - set(rendered["services"]), - { - "api", - "worker", - "beat", - "model-proxy", - "guide-document-parser", - }, - ) - self.assertNotIn("build", rendered["services"]["api"]) - services = rendered["services"] - identity = { - key: self.environment[key] for key in preflight.AWS_S3_IDENTITY_KEYS - } - for name in ( - "api", - "worker", - "beat", - "model-proxy", - "guide-document-parser", - ): - service = services[name] - self.assertEqual(service["pull_policy"], "always") - self.assertTrue(service["init"]) - self.assertEqual(service["restart"], "on-failure:5") - self.assertTrue(service["healthcheck"]["test"]) - for name in preflight.ROLE_SECRET_FILE_KEYS: - service_environment = services[name]["environment"] - self.assertEqual( - { - key: service_environment[key] - for key in preflight.AWS_S3_IDENTITY_KEYS - }, - identity, - ) - project_agent_configuration = { - key: self.environment[key] - for key in preflight.PROJECT_AGENT_CONFIGURATION_KEYS - } - for name in ( - "api", - "worker", - "beat", - "model-proxy", - ): - self.assertEqual( - { - key: services[name]["environment"][key] - for key in preflight.PROJECT_AGENT_CONFIGURATION_KEYS - }, - project_agent_configuration, - ) - api_command = " ".join(services["api"]["command"]) - worker_command = " ".join(services["worker"]["command"]) - self.assertEqual(services["api"]["command"], [ - "python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", - ]) - self.assertNotIn("--reload", api_command) - self.assertIn("--pool=prefork", worker_command) - health_commands = { - name: " ".join(services[name]["healthcheck"]["test"]) - for name in ( - "api", - "worker", - "beat", - "model-proxy", - ) - } - self.assertIn("/api/v1/health", health_commands["api"]) - self.assertIn("/tmp/celery-worker.pid", health_commands["worker"]) - self.assertIn("/tmp/celerybeat.pid", health_commands["beat"]) - self.assertIn( - "/var/lib/workstream/model-runtime/model.sock", - health_commands["model-proxy"], - ) - self.assertNotIn("checker-service", services) - for service in services.values(): - self.assertNotIn("/var/run/docker.sock", preflight._service_mounts(service)) - self.assertEqual(services["api"]["stop_grace_period"], "30s") - self.assertIn(services["worker"]["stop_grace_period"], {"7320s", "2h2m0s"}) - self.assertIn(services["model-proxy"]["stop_grace_period"], {"7320s", "2h2m0s"}) - self.assertEqual(services["beat"]["stop_grace_period"], "30s") - self.assertEqual(services["guide-document-parser"]["stop_grace_period"], "30s") - self.assertEqual(services["api"]["ports"][0]["host_ip"], "127.0.0.1") - expected_secrets = { - preflight.SECRET_FILE_TARGETS[key][0] - for key in preflight._secret_file_keys(self.environment) - } - self.assertEqual(set(rendered["secrets"]), expected_secrets) - for key in preflight._secret_file_keys(self.environment): - secret_name, _target = preflight.SECRET_FILE_TARGETS[key] - self.assertEqual( - rendered["secrets"][secret_name]["file"], - self.environment[key], - ) - for service in services.values(): - self.assertNotIn("volumes_from", service) - self.assertNotIn("configs", service) - for name in preflight.ROLE_SECRET_FILE_KEYS: - file_keys = preflight._role_secret_file_keys(name, self.environment) - self.assertEqual( - services[name]["environment"]["WORKSTREAM_RELEASE_ROLE"], name - ) - mounted = services[name]["secrets"] - expected_role_secrets = { - preflight.SECRET_FILE_TARGETS[key][0] for key in file_keys - } - self.assertEqual( - {item["source"] for item in mounted}, expected_role_secrets - ) - self.assertTrue(all(item["mode"] in (0o400, "0400") for item in mounted)) - for key in preflight.SECRET_FILE_KEYS: - if key in file_keys: - self.assertEqual( - services[name]["environment"][key], - preflight.SECRET_FILE_TARGETS[key][1], - ) - else: - self.assertNotIn(key, services[name]["environment"]) - parser = services["guide-document-parser"] - self.assertEqual(parser["image"], services["api"]["image"]) - self.assertEqual(parser["user"], "0:0") - self.assertEqual(parser["cap_drop"], ["ALL"]) - self.assertEqual(parser["cap_add"], ["KILL", "SETGID", "SETUID"]) - self.assertEqual(parser["network_mode"], "none") - self.assertNotIn("secrets", parser) - self.assertEqual( - parser["environment"], - { - "WORKSTREAM_RELEASE_ROLE": "parser", - "WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET": str( - preflight.deployment_paths(self.environment).guide_socket - ), - }, - ) - self.assertEqual(parser["mem_limit"], "536870912") - self.assertEqual(parser["memswap_limit"], "536870912") - self.assertEqual(parser["cpus"], 1) - self.assertEqual(parser["pids_limit"], 64) - self.assertFalse( - preflight._service_mounts(parser)[ - str(preflight.deployment_paths(self.environment).guide_root) - ].get("read_only", False) - ) - worker_mounts = preflight._service_mounts(services["worker"]) - self.assertTrue( - worker_mounts[str(preflight.deployment_paths(self.environment).guide_root)][ - "read_only" - ] - ) - for name in ("api", "beat"): - self.assertNotIn( - str(preflight.deployment_paths(self.environment).guide_root), - preflight._service_mounts(services[name]), - ) - for name in ("api", "worker", "model-proxy"): - mounts = preflight._service_mounts(services[name]) - self.assertEqual( - mounts[str(preflight.DIRECT_USER_CREDENTIAL_TARGET)]["source"], - str(self.direct_user_credentials), - ) - self.assertTrue( - mounts[str(preflight.DIRECT_USER_CREDENTIAL_TARGET)]["read_only"] - ) - self.assertEqual( - services[name]["environment"][preflight.DIRECT_USER_CREDENTIAL_FILE_KEY], - str(preflight.DIRECT_USER_CREDENTIAL_TARGET), - ) - beat_mounts = preflight._service_mounts(services["beat"]) - self.assertEqual(beat_mounts, {}) - self.assertNotIn( - preflight.DIRECT_USER_CREDENTIAL_FILE_KEY, - services["beat"]["environment"], - ) - self.assertNotIn( - preflight.DIRECT_USER_CREDENTIAL_FILE_KEY, - services["guide-document-parser"]["environment"], - ) - model_socket_root = str(preflight.deployment_paths(self.environment).model_root) - self.assertTrue(worker_mounts[model_socket_root]["read_only"]) - self.assertFalse( - preflight._service_mounts(services["model-proxy"])[model_socket_root].get( - "read_only", False - ) - ) - for name in ("api", "beat"): - self.assertNotIn( - model_socket_root, - preflight._service_mounts(services[name]), - ) - relay_root = str(preflight.deployment_paths(self.environment).model_relays) - for name, service in services.items(): - self.assertNotIn(relay_root, preflight._service_mounts(service)) - for role in ("api", "worker"): - self.assertEqual( - services[role]["environment"][ - "WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET" - ], - str(preflight.deployment_paths(self.environment).socket), - ) - self.assertEqual( - services[role]["environment"][ - "WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET" - ], - str(preflight.deployment_paths(self.environment).socket), - ) def test_actual_render_rejects_beat_inheriting_api_volumes(self) -> None: compose_text = preflight.COMPOSE_PATH.read_text(encoding="utf-8").replace( @@ -1012,110 +798,8 @@ def _compose_main(self, *arguments: str) -> tuple[int, str]: result = compose.main() return result, errors.getvalue() - def test_launch_rechecks_checker_selectors_after_preflight(self) -> None: - with ( - patch.object( - sys, "argv", ["preflight.py", "--env-file", str(self.environment_path)] - ), - patch.object(preflight, "validate_private_host_inputs"), - patch.object(preflight, "validate_smol_runtime"), - patch.object(preflight, "validate_trusted_intake"), - redirect_stdout(io.StringIO()), - ): - self.assertEqual(preflight.main(), 0) - for field, unsafe in (("runtime", "runc"), ("isolation_mode", "docker-dev")): - with self.subTest(field=field): - self.checker_path.write_text( - json.dumps(self.checker | {field: unsafe}), encoding="utf-8" - ) - with ( - patch.object(compose, "validate_private_host_inputs") as private, - patch.object(compose, "validate_smol_runtime") as runtime, - patch.object(compose, "run_compose") as run, - ): - result, error = self._compose_main("up") - self.assertEqual(result, 1) - self.assertIn(f"unsafe release value: {field}", error) - private.assert_not_called() - runtime.assert_not_called() - run.assert_not_called() - def test_launch_checks_host_and_runtime_before_starting(self) -> None: - for failure in (None, "private", "runtime", "intake"): - with self.subTest(failure=failure): - order = [] - - def private_check(values): - self.assertEqual(values, self.environment) - order.append("private") - if failure == "private": - raise preflight.PreflightError("private host rejected") - - def runtime_check(config, values): - self.assertEqual(config, self.checker) - self.assertEqual(values, self.environment) - order.append("runtime") - if failure == "runtime": - raise preflight.PreflightError("Docker runtime rejected") - - def intake_check(values): - self.assertEqual(values, self.environment) - order.append("intake") - if failure == "intake": - raise preflight.PreflightError("trusted intake rejected") - - def launch(path, values, arguments): - self.assertEqual(path, self.environment_path) - self.assertEqual(values, self.environment) - self.assertEqual(arguments, ["up"]) - order.append("launch") - return 0 - - with ( - patch.object( - compose, - "validate_private_host_inputs", - side_effect=private_check, - ), - patch.object( - compose, "validate_smol_runtime", side_effect=runtime_check - ), - patch.object( - compose, "validate_trusted_intake", side_effect=intake_check - ), - patch.object(compose, "run_compose", side_effect=launch) as run, - ): - result, error = self._compose_main("up") - if failure is None: - self.assertEqual((result, error), (0, "")) - self.assertEqual(order, ["private", "runtime", "intake", "launch"]) - run.assert_called_once() - else: - self.assertEqual(result, 1) - self.assertIn("rejected", error) - self.assertEqual( - order, - { - "private": ["private"], - "runtime": ["private", "runtime"], - "intake": ["private", "runtime", "intake"], - }[failure], - ) - run.assert_not_called() - def test_stop_remains_available_with_invalid_checker_configuration(self) -> None: - self.checker_path.write_text("invalid json", encoding="utf-8") - with ( - patch.object(compose, "load_checker_config") as load, - patch.object(compose, "validate_private_host_inputs") as private, - patch.object(compose, "validate_smol_runtime") as runtime, - patch.object(compose, "run_shutdown", return_value=0) as shutdown, - ): - self.assertEqual(self._compose_main("stop"), (0, "")) - load.assert_not_called() - private.assert_not_called() - runtime.assert_not_called() - shutdown.assert_called_once_with(self.environment_path, self.environment) def test_shutdown_drains_producers_worker_and_proxy_without_stopping_native_node( self, @@ -1180,55 +864,6 @@ def test_stop_rejects_caller_selected_service_order(self) -> None: "fixed shutdown sequence or exactly one worker", errors.getvalue() ) - def test_exact_worker_stop_preserves_dependencies_and_start_rechecks_native(self): - self.checker_path.write_text("invalid json", encoding="utf-8") - with ( - patch.object(compose, "load_checker_config") as load, - patch.object(compose, "run_compose", return_value=0) as run, - ): - self.assertEqual(self._compose_main("stop", "worker"), (0, "")) - load.assert_not_called() - run.assert_called_once_with( - self.environment_path, self.environment, ["stop", "worker"] - ) - self.checker_path.write_text(json.dumps(self.checker), encoding="utf-8") - for failure in (None, "private", "native", "intake"): - with ( - self.subTest(failure=failure), - patch.object( - compose, - "validate_private_host_inputs", - side_effect=preflight.PreflightError("private") - if failure == "private" - else None, - ) as private, - patch.object( - compose, - "validate_smol_runtime", - side_effect=preflight.PreflightError("native") - if failure == "native" - else None, - ) as native, - patch.object( - compose, - "validate_trusted_intake", - side_effect=preflight.PreflightError("intake") - if failure == "intake" - else None, - ) as intake, - patch.object(compose, "run_compose", return_value=0) as run, - ): - result, _ = self._compose_main("start", "worker") - self.assertEqual(result, 0 if failure is None else 1) - if failure is None: - private.assert_called_once_with(self.environment) - native.assert_called_once_with(self.checker, self.environment) - intake.assert_called_once_with(self.environment) - run.assert_called_once_with( - self.environment_path, self.environment, ["start", "worker"] - ) - else: - run.assert_not_called() def test_worker_operations_have_fixed_grace_readiness_and_management_bounds(self): cases = ( @@ -1636,179 +1271,11 @@ def test_enabled_setup_rejects_missing_selected_provider_credential(self) -> Non with self.assertRaisesRegex(preflight.PreflightError, "at least one"): preflight.validate_environment(manager) - def test_checker_config_rejects_non_hosted_or_substituted_identity(self) -> None: - cases = { - "runc": ("runtime", "runc"), - "development isolation": ("isolation_mode", "docker-dev"), - "wrong material root": ("material_root", "/tmp/material"), - "root sandbox": ("sandbox_uid", 0), - "empty cache": ("cache", []), - } - for label, (key, value) in cases.items(): - with self.subTest(label=label): - changed = copy.deepcopy(self.checker) - changed[key] = value - with self.assertRaises(preflight.PreflightError): - preflight.validate_checker_config(changed, self.environment) - changed = copy.deepcopy(self.checker) - changed["cache"][0]["config_image_id"] = "sha256:" + "A" * 64 - with self.assertRaises(preflight.PreflightError): - preflight.validate_checker_config(changed, self.environment) - - def test_intake_storage_qualification_must_match_pins_and_have_real_bounds(self): - preflight.validate_checker_config(self.checker, self.environment) - for key in ( - "archive_sha256", - "config_image_id", - "smol_binary_sha256", - "guest_sha256", - ): - with self.subTest(identity=key): - changed = copy.deepcopy(self.checker) - changed["trusted_intake"]["storage_envelope"][key] = ( - "sha256:" + "f" * 64 - ) - with self.assertRaisesRegex( - preflight.PreflightError, "storage qualification" - ): - preflight.validate_checker_config(changed, self.environment) - for key in ( - "overhead_bytes", - "maximum_storage_gib", - "maximum_entries", - "maximum_path_bytes", - "maximum_path_depth", - ): - for value in (0, True, -1, 2**64): - with self.subTest(bound=key, value=value): - changed = copy.deepcopy(self.checker) - changed["trusted_intake"]["storage_envelope"][key] = value - with self.assertRaisesRegex( - preflight.PreflightError, "storage qualification" - ): - preflight.validate_checker_config(changed, self.environment) - changed = copy.deepcopy(self.checker) - changed["smol"]["maximum_storage_bytes"] = 2 * 1024**3 - with self.assertRaisesRegex(preflight.PreflightError, "storage qualification"): - preflight.validate_checker_config(changed, self.environment) - - def test_intake_storage_qualification_covers_configured_inspection_limits(self): - for setting in ("MAXIMUM_ENTRIES", "MAXIMUM_PATH_BYTES", "MAXIMUM_PATH_DEPTH"): - values = self.environment | {"WORKSTREAM_ARTIFACT_SUBMISSION_ZIP_" + setting: "100001"} - with self.subTest(setting=setting): - with self.assertRaisesRegex(preflight.PreflightError, "exceeds storage qualification"): - preflight.validate_checker_config(self.checker, values) - - def test_intake_storage_qualification_covers_largest_supported_zip(self): - changed = copy.deepcopy(self.checker) - envelope = changed["trusted_intake"]["storage_envelope"] - envelope["maximum_storage_gib"] = 1 - with self.assertRaisesRegex(preflight.PreflightError, "cannot cover supported ZIPs"): - preflight.validate_checker_config(changed, self.environment) - envelope.update(maximum_storage_gib=2, overhead_bytes=1024**3) - preflight.validate_checker_config(changed, self.environment) - envelope["overhead_bytes"] += 1 - with self.assertRaisesRegex(preflight.PreflightError, "cannot cover supported ZIPs"): - preflight.validate_checker_config(changed, self.environment) - envelope["overhead_bytes"] = 2**64 - 1 - with self.assertRaisesRegex(preflight.PreflightError, "cannot cover supported ZIPs"): - preflight.validate_checker_config(changed, self.environment) - - def test_custom_deployment_root_preserves_paths_and_refuses_unsafe_custody( - self, - ) -> None: - root = self.root / "owned-data" - root.mkdir(mode=0o700) - values = self.environment | {"WORKSTREAM_DEPLOYMENT_ROOT": str(root)} - paths = preflight.deployment_paths(values) - config = copy.deepcopy(self.checker) - config.update( - socket_path=str(paths.socket), - material_root=str(paths.scratch), - model_proxy_socket=str(paths.model_socket), - model_relay_root=str(paths.model_relays), - ) - preflight.validate_environment(values) - preflight.validate_checker_config(config, values) - rendered = preflight.render_compose(self.environment_path, values) - preflight.validate_compose(rendered, values) - for role in ("api", "worker"): - environment = rendered["services"][role]["environment"] - self.assertEqual( - environment["WORKSTREAM_ARTIFACT_SCRATCH_ROOT"], str(paths.scratch) - ) - self.assertEqual( - environment["WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET"], - str(paths.socket), - ) - self.assertEqual( - environment["WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET"], - str(paths.socket), - ) - mounts = preflight._service_mounts(rendered["services"][role]) - self.assertEqual(mounts[str(paths.scratch)]["source"], str(paths.scratch)) - self.assertTrue(mounts[str(paths.socket_root)]["read_only"]) - proxy_mounts = preflight._service_mounts(rendered["services"]["model-proxy"]) - self.assertEqual( - proxy_mounts[str(paths.model_root)]["source"], str(paths.model_root) - ) - preflight._private_metadata( - root, kind="directory", uid=os.getuid(), gid=os.getgid(), mode=0o700 - ) - with self.assertRaisesRegex(preflight.PreflightError, "owner"): - preflight._private_metadata( - root, kind="directory", uid=os.getuid() + 1, gid=os.getgid(), mode=0o700 - ) - alias = self.root / "root-alias" - alias.symlink_to(root, target_is_directory=True) - for unsafe in ("/", str(alias), str(root / ".." / "owned-data")): - with self.subTest(root=unsafe), self.assertRaises(preflight.PreflightError): - preflight.validate_environment( - values | {"WORKSTREAM_DEPLOYMENT_ROOT": unsafe} - ) - with self.assertRaises(preflight.PreflightError): - preflight.validate_environment( - values | {"WORKSTREAM_CHECKER_SERVICE_BINARY": str(root / "service")} - ) - for field, path in ( - ("guest_binary", root / "guest"), - ("binary", root / "engine"), - ): - changed = copy.deepcopy(config) - changed["smol"][field] = str(path) - with self.assertRaisesRegex(preflight.PreflightError, "outside deployment"): - preflight.validate_checker_config(changed, values) - credential_values = values | { - "WORKSTREAM_MODEL_PROXY_OPENROUTER_API_KEY_FILE": str(root / "credential") - } - with self.assertRaisesRegex(preflight.PreflightError, "outside deployment"): - preflight.validate_checker_config(config, credential_values) - self.assertTrue(root.is_dir()) - - def test_native_socket_rejects_foreign_identity_permissions_and_links(self) -> None: - path = self.root / "native.sock" - listener = socket.socket(socket.AF_UNIX) - listener.bind(str(path)) - self.addCleanup(listener.close) - path.chmod(0o600) - with self.subTest(path=path): - preflight._validate_native_socket(path, os.getuid(), os.getgid()) - for uid, gid in ( - (os.getuid() + 1, os.getgid()), - (os.getuid(), os.getgid() + 1), - ): - with self.assertRaisesRegex(preflight.PreflightError, "identity"): - preflight._validate_native_socket(path, uid, gid) - path.chmod(0o660) - with self.assertRaises(preflight.PreflightError): - preflight._validate_native_socket(path, os.getuid(), os.getgid()) - path.chmod(0o600) - alias = self.root / "native-alias" - os.link(path, alias) - with self.assertRaises(preflight.PreflightError): - preflight._validate_native_socket(path, os.getuid(), os.getgid()) - alias.unlink() - preflight._validate_native_socket(path, os.getuid(), os.getgid()) + + + + + def test_trial_manifest_is_paired_shared_and_confined_to_the_proxy(self) -> None: manifest = self.root / "trial-authority.json" @@ -1852,334 +1319,11 @@ def test_trial_manifest_is_paired_shared_and_confined_to_the_proxy(self) -> None ] = str(preflight.TRIAL_MANIFEST_TARGET) with self.assertRaises(preflight.PreflightError): preflight.validate_compose(changed, self.environment) - native = copy.deepcopy(self.checker) - native.update( - trial_authority_manifest_path=str(manifest), - trial_authority_manifest_digest=self.environment[preflight.TRIAL_KEYS[1]], - ) - native["trial_runtime"] = { - **{ - key: str(self.root / key) - for key in ( - "relay_root", - "scratch_root", - "child_home_root", - "offline_cache_root", - "trusted_launcher_path", - "filesystem_tool_path", - ) - }, - **{ - key: "sha256:" + "f" * 64 - for key in ( - "outer_runtime_config_digest", - "trusted_launcher_digest", - "filesystem_tool_digest", - ) - }, - "builder_image_id": native["cache"][0]["config_image_id"], - "deployment_owner": "hosted-native", - "maximum_candidate_archive_bytes": 1024, - } - native["trial_runtime"]["child_home_root"] = self.enterContext( - tempfile.TemporaryDirectory(prefix="ws", dir="/tmp") - ) - preflight.validate_checker_config(native, self.environment) - for root, valid in ( - ("/" + "a" * 17, True), - ("/" + "é" * 8 + "a", True), - ("/" + "a" * 18, False), - ("/" + "é" * 9, False), - ): - changed = copy.deepcopy(native) - changed["trial_runtime"]["child_home_root"] = root - with self.subTest(child_home_root=root): - if valid: - preflight.validate_checker_config(changed, self.environment) - else: - with self.assertRaisesRegex(preflight.PreflightError, "18-byte"): - preflight.validate_checker_config(changed, self.environment) - substituted = native | {"trial_authority_manifest_digest": "sha256:" + "0" * 64} - with self.assertRaisesRegex(preflight.PreflightError, "trial authority"): - preflight.validate_checker_config(substituted, self.environment) for key in preflight.TRIAL_KEYS: changed = dict(self.environment) del changed[key] with self.assertRaises(preflight.PreflightError): preflight.validate_environment(changed) - with self.assertRaisesRegex(preflight.PreflightError, "trial authority"): - preflight.validate_checker_config(self.checker, self.environment) - - def test_smol_home_socket_budget_counts_filesystem_bytes(self): - for root, valid in ( - ("/" + "a" * 58, True), - ("/" + "é" * 29, True), - ("/" + "a" * 59, False), - ("/" + "é" * 30, False), - ): - changed = copy.deepcopy(self.checker) - changed["smol"]["home"] = root - with self.subTest(home=root): - if valid: - preflight.validate_checker_config(changed, self.environment) - else: - with self.assertRaisesRegex(preflight.PreflightError, "59-byte"): - preflight.validate_checker_config(changed, self.environment) - - def _native_inputs(self): - config = copy.deepcopy(self.checker) - values = self.environment | { - "WORKSTREAM_RUNTIME_UID": str(os.getuid()), - "WORKSTREAM_RUNTIME_GID": str(os.getgid()), - } - smol = config["smol"] - home = self.root / "native-home" - home.mkdir(mode=0o700) - group = self.root / "delegated" - group.mkdir(mode=0o700) - (group / "controller").mkdir(mode=0o700) - for key in ("cgroup.controllers", "cgroup.subtree_control"): - (group / key).write_text("cpu memory pids", encoding="ascii") - smol.update(home=str(home), cgroup_root=str(group)) - for key, digest_key in ( - ("binary", "binary_sha256"), - ("guest_binary", "guest_sha256"), - ): - path = self.root / key - raw = key.encode() - path.write_bytes(raw) - path.chmod(0o400) - smol[key] = str(path) - smol[digest_key] = "sha256:" + hashlib.sha256(raw).hexdigest() - for index, entry in enumerate(config["cache"]): - for key, digest_key in ( - ("archive", "archive_sha256"), - ("image_config", "config_image_id"), - ): - path = self.root / f"cache-{index}-{key}" - raw = f"static native custody fixture {index} {key}".encode() - path.write_bytes(raw) - path.chmod(0o400) - entry["smol"][key] = str(path) - target = entry["smol"] if key == "archive" else entry - target[digest_key] = "sha256:" + hashlib.sha256(raw).hexdigest() - values[preflight.INTAKE_DIGEST_KEYS[1]] = config["cache"][1]["config_image_id"] - service = self.root / "service-binary" - service.write_bytes(b"pinned installed native service") - service.chmod(0o400) - values["WORKSTREAM_CHECKER_SERVICE_BINARY"] = str(service) - values["WORKSTREAM_CHECKER_SERVICE_BINARY_SHA256"] = ( - "sha256:" + hashlib.sha256(service.read_bytes()).hexdigest() - ) - health = { - "runtime": "smolvm", - "isolation_mode": "smol-microvm", - "operating_system": "linux", - "architecture": "amd64", - "sandbox_uid": os.getuid(), - "sandbox_gid": os.getgid(), - "cached_platform_manifests": len(config["cache"]), - } - return config, values, service, health - - def test_native_asset_refusals_preserve_operator_diagnostics(self) -> None: - for failure, reason in ( - ("path", "path is not canonical"), - ("custody", "custody is unsafe"), - ("deadline", "verification deadline exceeded"), - ("digest", "digest or identity differs"), - ("missing", "is unavailable"), - ): - with self.subTest(failure=failure): - asset = self.root / f"asset-{failure}" - asset.write_bytes(b"pinned asset") - asset.chmod(0o400) - expected = "sha256:" + hashlib.sha256(asset.read_bytes()).hexdigest() - deadline = float("inf") - if failure == "path": - alias = self.root / "asset-alias" - alias.symlink_to(asset) - asset = alias - elif failure == "custody": - asset.chmod(0o620) - elif failure == "deadline": - deadline = 0 - elif failure == "digest": - expected = "sha256:" + "0" * 64 - else: - asset.unlink() - with self.assertRaisesRegex( - preflight.PreflightError, f"^native Smol asset {reason}$" - ): - preflight._verify_smol_asset(asset, expected, os.getuid(), deadline) - - def test_native_readiness_binds_static_assets_delegation_and_typed_health( - self, - ) -> None: - config, values, service, health = self._native_inputs() - with ( - patch.object(preflight, "_run_json", return_value=health) as run, - ): - preflight.validate_smol_runtime(config, values) - command = run.call_args.args[0] - self.assertIn("configured_external_checker_execution(s).health()", command[-1]) - self.assertIn("--network", command) - self.assertEqual(command[command.index("--network") + 1], "none") - self.assertIn("readonly", command[command.index("--mount") + 1]) - self.assertNotIn("--env", command) - self.assertNotIn("--env-file", command) - self.assertNotIn("/var/run/docker.sock", " ".join(command)) - for changed_health in ( - health | {"runtime": "runsc"}, - health | {"sandbox_uid": os.getuid() + 1}, - health | {"cached_platform_manifests": 1}, - ): - with ( - patch.object(preflight, "_run_json", return_value=changed_health), - ): - with self.assertRaisesRegex( - preflight.PreflightError, "readiness identity" - ): - preflight.validate_smol_runtime(config, values) - for mutate in ("cache", "binary", "delegation"): - changed = copy.deepcopy(config) - if mutate == "cache": - changed["cache"][0]["smol"]["archive_sha256"] = "sha256:" + "f" * 64 - elif mutate == "binary": - changed["smol"]["guest_sha256"] = "sha256:" + "f" * 64 - else: - Path(changed["smol"]["cgroup_root"]).joinpath( - "cgroup.subtree_control" - ).write_text("cpu memory", encoding="ascii") - with ( - patch.object(preflight, "_run_json") as run, - ): - with self.assertRaises(preflight.PreflightError): - preflight.validate_smol_runtime(changed, values) - run.assert_not_called() - - def test_resume_orders_dependencies_before_native_and_application(self): - values = self.local_data_environment() | self.identity_values() - events = [] - def run(path, release, arguments, **kwargs): - self.assertTrue(kwargs["cached_images"]) - events.append(arguments) - return 0 - with ( - patch.object(compose, "validate_private_host_inputs"), - patch.object(compose, "validate_local_data_host_inputs"), - patch.object(compose, "validate_identity_host_inputs"), - patch.object(compose, "validate_checker_config"), - patch.object(compose, "run_compose", side_effect=run), - patch.object(compose.subprocess, "run", side_effect=lambda command, **kw: - events.append(command) or subprocess.CompletedProcess(command, 0)), - patch.object(compose, "validate_smol_runtime", side_effect=[ - preflight.PreflightError("not ready"), None, - ]) as native, - patch.object(compose, "validate_trusted_intake") as intake, - patch.object(compose.time, "sleep") as sleep, - ): - self.assertEqual(compose.resume_release(self.environment_path, values), 0) - self.assertEqual(events[0], ["start", "local-data"]) - self.assertEqual(events[1], ["start", "identity"]) - self.assertEqual(events[2][-1], "model-proxy") - self.assertEqual(events[3], ["systemctl", "reset-failed", "workstream-checker.service"]) - self.assertEqual(events[4], ["systemctl", "start", "workstream-checker.service"]) - self.assertEqual(events[5], ["up", "--detach", "--wait", "--wait-timeout", "120"]) - self.assertEqual(native.call_count, 2) - sleep.assert_called_once_with(2) - intake.assert_called_once_with(values) - - def test_resume_without_optional_services_keeps_native_readiness_guards(self): - values = self.environment | {"WORKSTREAM_MODEL_PROXY_ENABLED": "false"} - with ( - patch.object(compose, "validate_checker_config"), - patch.object(compose, "validate_private_host_inputs") as private, - patch.object(compose, "run_compose", return_value=0) as run, - patch.object(compose.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)), - patch.object(compose, "validate_smol_runtime") as native, - patch.object(compose, "validate_trusted_intake") as intake, - ): - self.assertEqual(compose.resume_release(self.environment_path, values), 0) - self.assertEqual(private.call_count, 2) - native.assert_called_once_with(self.checker, values) - intake.assert_called_once_with(values) - run.assert_called_once_with(self.environment_path, values, - ["up", "--detach", "--wait", "--wait-timeout", "120"], cached_images=True) - - def test_resume_dependency_failure_never_starts_native_or_application(self): - with ( - patch.object(compose, "validate_private_host_inputs"), - patch.object(compose, "run_compose", return_value=17) as run, - patch.object(compose.subprocess, "run") as native, - patch.object(compose, "validate_smol_runtime") as health, - ): - self.assertEqual(compose.resume_release(self.environment_path, self.environment), 17) - self.assertEqual(run.call_count, 1) - native.assert_not_called() - health.assert_not_called() - - def test_resume_native_failure_never_releases_application(self): - for failure in ("start", "readiness"): - with ( - self.subTest(failure=failure), - patch.object(compose, "validate_private_host_inputs"), - patch.object(compose, "run_compose", return_value=0) as run, - patch.object(compose.subprocess, "run", return_value= - subprocess.CompletedProcess([], 17 if failure == "start" else 0)), - patch.object(compose, "validate_smol_runtime", - side_effect=preflight.PreflightError("unready")), - patch.object(compose.time, "monotonic", side_effect=[0, 121]), - ): - if failure == "start": - self.assertEqual(compose.resume_release(self.environment_path, self.environment), 17) - else: - with self.assertRaisesRegex(preflight.PreflightError, "unready"): - compose.resume_release(self.environment_path, self.environment) - self.assertEqual(run.call_count, 1) - self.assertEqual(run.call_args.args[2][-1], "model-proxy") - - def test_cold_start_prerequisites_never_release_application_or_require_node( - self, - ) -> None: - for arguments in (("migrate",), ("up", "-d", "model-proxy")): - with ( - self.subTest(arguments=arguments), - patch.object(compose, "validate_private_host_inputs") as private, - patch.object(compose, "validate_smol_runtime") as native, - patch.object(compose, "validate_trusted_intake") as intake, - patch.object(compose, "run_compose", return_value=0) as run, - ): - self.assertEqual(self._compose_main(*arguments), (0, "")) - private.assert_called_once_with(self.environment, require_node=False) - native.assert_not_called() - intake.assert_not_called() - run.assert_called_once_with( - self.environment_path, self.environment, list(arguments) - ) - completed = subprocess.CompletedProcess([], 0) - with patch.object(preflight.subprocess, "run", return_value=completed) as run: - self.assertEqual( - preflight.run_compose( - self.environment_path, self.environment, ["migrate"] - ), - 0, - ) - self.assertEqual( - run.call_args.args[0][-9:], - [ - "run", - "--rm", - "--no-deps", - "api", - "python", - "-m", - "alembic", - "upgrade", - "head", - ], - ) - def _points_inputs(self): token = self.root / "finance-token" token.write_text("private-finance-bearer", encoding="ascii") @@ -2293,35 +1437,7 @@ def test_points_operator_timeout_and_start_failure_clean_only_owned_container(se if not cleanup_ok: self.assertIn(name, errors.getvalue()) - def test_points_operator_preflight_requires_static_inputs_without_checker_execution(self): - _, arguments, _ = self._points_inputs() - with ( - patch.object(compose, "validate_private_host_inputs") as private, - patch.object(compose, "validate_smol_runtime") as native, - patch.object(compose, "validate_trusted_intake") as intake, - patch.object(compose, "run_compose", return_value=0) as run, - ): - self.assertEqual(self._compose_main(*arguments), (0, "")) - private.assert_called_once_with(self.environment, require_node=False) - native.assert_not_called() - intake.assert_not_called() - run.assert_called_once_with(self.environment_path, self.environment, arguments) - - def test_checker_model_paths_require_enabled_exact_proxy_topology(self) -> None: - for key in ("model_proxy_socket", "model_relay_root"): - for replacement in (None, "/tmp/substituted"): - with self.subTest(key=key, replacement=replacement): - changed = copy.deepcopy(self.checker) - changed[key] = replacement - with self.assertRaises(preflight.PreflightError): - preflight.validate_checker_config(changed, self.environment) - disabled = self.environment | {"WORKSTREAM_MODEL_PROXY_ENABLED": "false"} - with self.assertRaises(preflight.PreflightError): - preflight.validate_checker_config(self.checker, disabled) - ordinary = copy.deepcopy(self.checker) - del ordinary["model_proxy_socket"] - del ordinary["model_relay_root"] - preflight.validate_checker_config(ordinary, disabled) + def test_rendered_topology_rejects_a_second_checker_controller(self) -> None: rendered = preflight.render_compose(self.environment_path, self.environment) @@ -2345,14 +1461,13 @@ def test_rendered_topology_rejects_privilege_and_path_drift(self) -> None: "registry.example/workstream/backend@sha256:" + "9" * 64 ) cases.append(("different guide parser image", different_parser_image)) - for role in ("api", "worker"): - writable_owner = copy.deepcopy(rendered) - for mount in writable_owner["services"][role]["volumes"]: - if mount["target"] == str( - preflight.deployment_paths(self.environment).socket_root - ): - mount["read_only"] = False - cases.append((f"{role} writable checker custody", writable_owner)) + writable_model_socket = copy.deepcopy(rendered) + for mount in writable_model_socket["services"]["worker"]["volumes"]: + if mount["target"] == str( + preflight.deployment_paths(self.environment).model_socket.parent + ): + mount["read_only"] = False + cases.append(("worker writable model callback socket", writable_model_socket)) expanded_worker = copy.deepcopy(rendered) expanded_worker["services"]["worker"]["environment"]["UNREVIEWED"] = "true" cases.append(("worker environment drift", expanded_worker)) @@ -2554,150 +1669,8 @@ def test_private_metadata_rejects_empty_broad_and_linked_files(self) -> None: mode=0o400, ) - def test_private_host_inputs_check_socket_identity_without_reading_secrets( - self, - ) -> None: - scratch = self.root / "scratch" - socket_root = self.root / "checker-runtime" - model_socket_root = self.root / "model-runtime" - model_relay_root = self.root / "model-relays" - guide_socket_root = self.root / "guide-runtime" - intake_root = self.root / "checker-runtime" - intake_root.mkdir(mode=0o700) - intake_path = intake_root / "checker.sock" - intake_listener = socket.socket(socket.AF_UNIX) - intake_listener.bind(str(intake_path)) - intake_path.chmod(0o600) - self.addCleanup(intake_listener.close) - scratch.mkdir(mode=0o700) - socket_root.mkdir(mode=0o700, exist_ok=True) - model_socket_root.mkdir(mode=0o700, exist_ok=True) - model_relay_root.mkdir(mode=0o700) - guide_socket_root.mkdir(mode=0o750) - host_uid = os.getuid() - host_gid = os.getgid() - environment = dict(self.environment) - environment["WORKSTREAM_GITHUB_APP_ID"] = "123" - environment["WORKSTREAM_DEPLOYMENT_ROOT"] = str(self.root) - environment["WORKSTREAM_RUNTIME_UID"] = str(host_uid) - environment["WORKSTREAM_RUNTIME_GID"] = str(host_gid) - checker = self.root / "private-checker.json" - checker.write_text("{}", encoding="utf-8") - checker.chmod(0o400) - secret_paths = [] - environment["WORKSTREAM_CHECKER_CONFIG_FILE"] = str(checker) - for index, key in enumerate(preflight.SECRET_FILE_KEYS): - secret = self.root / f"secret-{index}" - secret.write_text(f"private-{index}", encoding="utf-8") - secret.chmod(0o400) - environment[key] = str(secret) - secret_paths.append(secret) - docker_socket = self.root / "docker.sock" - listener = socket.socket(socket.AF_UNIX) - listener.bind(str(docker_socket)) - try: - with ( - patch.object(preflight, "GUIDE_PARSER_UID", host_uid), - patch.object(preflight, "GUIDE_PARSER_GID", host_gid), - patch.object(preflight, "DOCKER_SOCKET", docker_socket), - ): - preflight.validate_private_host_inputs(environment) - model_relay_root.chmod(0o755) - with self.assertRaisesRegex(preflight.PreflightError, "wrong mode"): - preflight.validate_private_host_inputs(environment) - model_relay_root.chmod(0o700) - guide_listener = socket.socket(socket.AF_UNIX) - guide_listener.bind(str(guide_socket_root / "guide.sock")) - (guide_socket_root / "guide.sock").chmod(0o660) - try: - preflight.validate_private_host_inputs(environment) - guide_socket_alias = self.root / "guide-socket-alias" - os.link(guide_socket_root / "guide.sock", guide_socket_alias) - try: - with self.assertRaisesRegex( - preflight.PreflightError, - "unsafe retained state", - ): - preflight.validate_private_host_inputs(environment) - finally: - guide_socket_alias.unlink() - finally: - guide_listener.close() - (guide_socket_root / "guide.sock").unlink() - (guide_socket_root / "guide.sock").write_text( - "foreign", encoding="utf-8" - ) - with self.assertRaisesRegex( - preflight.PreflightError, "unsafe retained state" - ): - preflight.validate_private_host_inputs(environment) - (guide_socket_root / "guide.sock").unlink() - guide_socket_root.chmod(0o700) - with self.assertRaisesRegex(preflight.PreflightError, "wrong mode"): - preflight.validate_private_host_inputs(environment) - guide_socket_root.chmod(0o750) - scratch_secret = scratch / "project-agent-secret" - scratch_secret.write_text("private", encoding="utf-8") - scratch_secret.chmod(0o400) - scratch_alias = self.root / "scratch-alias" - scratch_alias.symlink_to(scratch, target_is_directory=True) - environment["WORKSTREAM_MODEL_PROXY_OPENROUTER_API_KEY_FILE"] = str( - scratch_alias / scratch_secret.name - ) - with ( - patch.object(preflight, "GUIDE_PARSER_UID", host_uid), - patch.object(preflight, "GUIDE_PARSER_GID", host_gid), - patch.object(preflight, "DOCKER_SOCKET", docker_socket), - self.assertRaisesRegex( - preflight.PreflightError, "outside shared roots" - ), - ): - preflight.validate_private_host_inputs(environment) - environment["WORKSTREAM_MODEL_PROXY_OPENROUTER_API_KEY_FILE"] = str( - secret_paths[-1] - ) - socket_identity = socket_root / "aws-access-key.json" - socket_identity.write_text("private", encoding="utf-8") - socket_identity.chmod(0o400) - credential_key = preflight.DIRECT_USER_CREDENTIAL_HOST_FILE_KEY - original_credential = environment[credential_key] - environment[credential_key] = str(socket_identity) - with ( - patch.object(preflight, "GUIDE_PARSER_UID", host_uid), - patch.object(preflight, "GUIDE_PARSER_GID", host_gid), - patch.object(preflight, "DOCKER_SOCKET", docker_socket), - self.assertRaisesRegex( - preflight.PreflightError, "outside shared roots" - ), - ): - preflight.validate_private_host_inputs(environment) - environment[credential_key] = original_credential - secret_alias = self.root / "project-agent-secret-direct-key-alias" - os.link(secret_paths[-1], secret_alias) - environment[credential_key] = str(secret_alias) - with ( - patch.object(preflight, "GUIDE_PARSER_UID", host_uid), - patch.object(preflight, "GUIDE_PARSER_GID", host_gid), - patch.object(preflight, "DOCKER_SOCKET", docker_socket), - self.assertRaisesRegex(preflight.PreflightError, "distinct files"), - ): - preflight.validate_private_host_inputs(environment) - environment[credential_key] = original_credential - checker_alias = self.root / "checker-direct-key-alias" - os.link(checker, checker_alias) - environment[credential_key] = str(checker_alias) - with ( - patch.object(preflight, "GUIDE_PARSER_UID", host_uid), - patch.object(preflight, "GUIDE_PARSER_GID", host_gid), - patch.object(preflight, "DOCKER_SOCKET", docker_socket), - self.assertRaisesRegex(preflight.PreflightError, "distinct files"), - ): - preflight.validate_private_host_inputs(environment) - environment[credential_key] = original_credential - finally: - listener.close() - def test_trusted_intake_requires_pinned_settings_and_readonly_mounts(self) -> None: + def test_trusted_intake_requires_pins_without_shared_runner_mounts(self) -> None: for key in preflight.INTAKE_DIGEST_KEYS: for value in (None, "latest"): changed = dict(self.environment) @@ -2712,36 +1685,15 @@ def test_trusted_intake_requires_pinned_settings_and_readonly_mounts(self) -> No preflight.validate_environment(changed) rendered = preflight.render_compose(self.environment_path, self.environment) for role in ("api", "worker"): - changed = copy.deepcopy(rendered) - for mount in changed["services"][role]["volumes"]: - if mount["target"] == str( - preflight.deployment_paths(self.environment).socket_root - ): - mount["read_only"] = False - with self.subTest(role=role), self.assertRaises(preflight.PreflightError): - preflight.validate_compose(changed, self.environment) + environment = rendered["services"][role]["environment"] + for key in preflight.INTAKE_DIGEST_KEYS: + self.assertEqual(environment[key], self.environment[key]) + self.assertNotIn("WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET", environment) + self.assertNotIn( + str(preflight.deployment_paths(self.environment).socket_root), + preflight._service_mounts(rendered["services"][role]), + ) - def test_trusted_intake_health_uses_typed_factory_without_credentials(self) -> None: - health = { - "runtime": "smolvm", - "isolation_mode": "smol-microvm", - "image_digest": self.environment[preflight.INTAKE_DIGEST_KEYS[0]], - "config_digest": self.environment[preflight.INTAKE_DIGEST_KEYS[1]], - } - with patch.object(preflight, "_run_json", return_value=health) as run: - preflight.validate_trusted_intake(self.environment) - command = run.call_args.args[0] - self.assertIn("--pull=never", command) - self.assertIn("trusted_submission_intake(s).health()", command[-1]) - self.assertEqual(command[command.index("--network") + 1], "none") - self.assertEqual(command.count("--mount"), 1) - self.assertIn("readonly", command[command.index("--mount") + 1]) - self.assertNotIn("--env-file", command) - self.assertNotIn("--env", command) - for mutation in ({"runtime": "runsc"}, {"image_digest": "sha256:" + "f" * 64}): - with patch.object(preflight, "_run_json", return_value=health | mutation): - with self.assertRaises(preflight.PreflightError): - preflight.validate_trusted_intake(self.environment) class ReleaseSecretLoaderTests(unittest.TestCase): From a0856e8fbe0cdb69e32040cf4375ebd79e3b1c6c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:26:23 +0100 Subject: [PATCH 267/513] Move predecessor rules proof to public source intake --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 30 +++++++++ backend/scripts/test_lane_catalogue.py | 1 - .../test_selected_predecessor_rules.py | 66 ------------------- backend/tests/test_ci_lane_catalogue.py | 8 +-- .../test_submission_predecessor_custody.py | 60 +++++++++++++++++ 5 files changed, 94 insertions(+), 71 deletions(-) delete mode 100644 backend/tests/artifacts/test_selected_predecessor_rules.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6409788cd..f8d2454c2 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8759,3 +8759,33 @@ reconciliation findings closed. The initially suspected missing worker model socket was retracted after checking the selected inference Compose overlay. Agent reports112 focused tests; real provider callbacks and complete public acceptance remain unqualified. No app deployment or restart occurred. + +QA closed upload-fence c8a6cc9da PASS WITH LOW RISKS. Next transfer the last +private predecessor-rule tests to current public intake. Allowed: predecessor +custody test, obsolete artifacts/test_selected_predecessor_rules.py and record. +The positive persisted PRE context must select the consumed admission's rules, +not its different policy-context hash. Four public negative cases substitute +only that read result (absent admission/run/rules or contradictory evidence), +leaving database rows/guards unchanged, and must fail before PRE/acceptance while +retaining charged source custody. Existing initial public source tests prove no +predecessor required. Then retire the old private-method harness. Medium test +migration risk; real PostgreSQL cases, Ruff/structure and scoped QA review. +The same retirement also removes that obsolete module's explicit entry from +backend/scripts/test_lane_catalogue.py; current public replacement tests retain +their existing integration lane. No lane policy or other module ownership changes. +The catalogue's independent shared-family count/digest in +tests/test_ci_lane_catalogue.py is updated solely for this one module deletion; +recursive inventory coverage passed before that expected fingerprint update. +The same inventory check exposed an earlier runner integration omission: the +project-family fingerprint lacked exactly tests/checkers/external/test_remote_node.py. +Removing only that module reproduces the previous digest. Update the expected +project count/digest for that already-owned module; no membership change. + +All four public predecessor-custody fault cases and both positive review-policy +replay cases passed in165.79s, schema0090 with complete cleanup +(/tmp/submission-public-predecessor-rules.json). Launcher wasc8a6cc9da with final +test bytes; hosted integration afterward did not alter these tests. No retained +row/guard was changed by fault injection. Structure/Ruff/diff passed. The old +private predecessor-rule harness is now replaced by this current public proof. +Hosted follow-up97750e9c8 integrated092986b8a; ARCH/SEC passed its exact delta. +Runner-only repaired service qualification is coordinated; API remains unchanged. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index dd96c738a..abf373cc4 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -51,7 +51,6 @@ class TestLane: "tests/reviews/lifecycle/test_authority_binding.py", "tests/artifacts/test_review_packet_contract.py", "tests/reviews/packet/test_storage.py", - "tests/artifacts/test_selected_predecessor_rules.py", "tests/artifacts/test_submission_intake_contracts.py", "tests/artifacts/test_submission_intake_custody.py", "tests/artifacts/test_submission_source_cleanup.py", diff --git a/backend/tests/artifacts/test_selected_predecessor_rules.py b/backend/tests/artifacts/test_selected_predecessor_rules.py deleted file mode 100644 index f54ccf404..000000000 --- a/backend/tests/artifacts/test_selected_predecessor_rules.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Predecessor rules require selected custody, never a substitute context hash.""" - -from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock - -import pytest - -from app.core.identifiers import new_record_id -from app.modules.artifacts.api import SubmissionBundlePreparationRejected -from app.modules.artifacts.submission_admission import PreparedSubmissionBundlePreparationCommand - - -def _command(admission): - return PreparedSubmissionBundlePreparationCommand( - session=SimpleNamespace(scalar=AsyncMock(return_value=admission)), - authority=SimpleNamespace(), - task_contexts=SimpleNamespace(), - project_contexts=SimpleNamespace(), - runtime_factory=Mock(), - ) - - -def _task(): - return SimpleNamespace(predecessor=SimpleNamespace(submission_id=new_record_id())) - - -@pytest.mark.asyncio -async def test_predecessor_uses_only_its_selected_rules_commitment(): - admission = SimpleNamespace( - selected_pre_submit_run_id=new_record_id(), - pre_submit_evidence_set_id=None, - selected_rules_sha256="sha256:" + "1" * 64, - locked_policy_context_hash="sha256:" + "2" * 64, - ) - command = _command(admission) - assert await command._load_predecessor_rules(_task()) == admission.selected_rules_sha256 - - -@pytest.mark.asyncio -@pytest.mark.parametrize("missing", ("admission", "run", "rules", "contradictory_evidence")) -async def test_missing_selected_predecessor_custody_rejects(missing): - admission = SimpleNamespace( - selected_pre_submit_run_id=new_record_id(), - pre_submit_evidence_set_id=None, - selected_rules_sha256="sha256:" + "1" * 64, - locked_policy_context_hash="sha256:" + "2" * 64, - ) - if missing == "admission": - admission = None - elif missing == "run": - admission.selected_pre_submit_run_id = None - elif missing == "rules": - admission.selected_rules_sha256 = None - else: - admission.pre_submit_evidence_set_id = new_record_id() - command = _command(admission) - with pytest.raises(SubmissionBundlePreparationRejected) as rejected: - await command._load_predecessor_rules(_task()) - assert str(rejected.value) == "submission_canonical_predecessor_unavailable" - - -@pytest.mark.asyncio -async def test_initial_submission_needs_no_predecessor_rules(): - command = _command(None) - assert await command._load_predecessor_rules(SimpleNamespace(predecessor=None)) is None - command._session.scalar.assert_not_called() diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 316f09e46..8a0dc080c 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -321,12 +321,12 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 279, - "42ff87480abaeb4e69c3756b83bbe053a26fb2f84db726a1018596369c7bcc30", + 278, + "0a1ac7e344208a8178f30f48b54774afaf57b54bf76e89a34debfc5867d18038", ), "project": ( - 258, - "d1c3c2852afa36476206c00129dcd8b63a10b187b0ad8634e6f894a20cd4deed", + 259, + "a39f6728caab1ab6d593ca5740cbd505e60996bbdb924195fba553aa89933178", ), "task": ( 96, diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index c7d6ccecd..5042f672e 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -237,6 +237,8 @@ async def test_real_replacement_compares_consumed_predecessor_and_replays_exactl "archive_sha256": predecessor_admission.archive_sha256, "semantic_manifest_sha256": predecessor_admission.semantic_manifest_sha256, } + assert predecessor_admission.selected_rules_sha256 != predecessor_admission.locked_policy_context_hash + assert selected.request_json["default_context"]["predecessor_rules_sha256"] == predecessor_admission.selected_rules_sha256 lineage = selected.request_json["admission_lineage"] assert lineage["predecessor_submission_id"] == str(predecessor_id) assert lineage["predecessor_submission_version"] == 1 @@ -257,6 +259,64 @@ async def test_real_replacement_compares_consumed_predecessor_and_replays_exactl assert await _replacement_history(h, source_id, predecessor_id) == immutable_before +@pytest.mark.parametrize("missing", ["admission", "run", "rules", "contradictory_evidence"]) +async def test_public_replacement_requires_consumed_predecessor_rules( + tmp_path, isolated_database_env, monkeypatch, missing, +): + from sqlalchemy.ext.asyncio import AsyncSession + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.test_public_submission_intake import _client + + async with remediation_source(tmp_path, isolated_database_env) as h: + await _fixture_revision_context(h) + data, intercepted = revision_archive(h.data), [] + before = await _snapshot(h) + original_scalar = AsyncSession.scalar + + async def incomplete_predecessor(session, statement, *args, **kwargs): + value = await original_scalar(session, statement, *args, **kwargs) + descriptions = getattr(statement, "column_descriptions", ()) + if (len(descriptions) == 1 and descriptions[0].get("expr") is SubmissionBundleAdmission + and "consumed_by_submission_id" in str(getattr(statement, "whereclause", ""))): + assert value is not None and value.consumed_by_submission_id == str(h.created.submission_id) + assert value.selected_rules_sha256 != value.locked_policy_context_hash + intercepted.append(value.id) + # Fault only the owner's read; retained database evidence stays immutable. + session.expunge(value) + if missing == "admission": + return None + setattr(value, { + "run": "selected_pre_submit_run_id", "rules": "selected_rules_sha256", + "contradictory_evidence": "pre_submit_evidence_set_id", + }[missing], new_record_id() if missing == "contradictory_evidence" else None) + return value + + async with _client(h, monkeypatch, isolated_database_env) as client: + _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + headers = _revision_upload_headers(h) + monkeypatch.setattr(AsyncSession, "scalar", incomplete_predecessor) + response = await client.post(f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=headers, content=data) + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "submission_infrastructure_unavailable" + assert intercepted == [str(h.creation_request.admission_id)] + assert calls == [] and not errors + assert await _snapshot(h) == before + async with h.factory() as session: + operation = (await session.scalars(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.idempotency_key == headers["Idempotency-Key"]))).one() + assert operation.state == "failed" and operation.acceptance_receipt is None + assert operation.finalized_submission_id is None and operation.finalization_event_id is None + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.state == "sealed" and charge.accounted_bytes == len(data) + retained = await session.get(SubmissionBundleAdmission, str(h.creation_request.admission_id)) + assert retained.selected_pre_submit_run_id is not None and retained.selected_rules_sha256 is not None + assert retained.pre_submit_evidence_set_id is None and retained.status == "consumed" + assert await session.scalar(text("SELECT count(*) FROM submissions")) == 1 + await no_economic_effects(session) + + async def test_replacement_without_routed_cause_denied_before_bytes( tmp_path, isolated_database_env, monkeypatch, ): From f9fb0a09058ec09b5cd53ae68efd394124a7c6ac Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:24:57 +0100 Subject: [PATCH 268/513] Prove remote PRE cancellation after source export --- .../changes/flow-self-service-signup.md | 6 ++- .../tests/checkers/external/test_runtime.py | 42 ++++++++++++++++--- 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index 6e3fe8786..66df4b816 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -439,8 +439,10 @@ Live evidence on instance `i-0936c305f8f67d835` proves m7i.large nested KVM, Smol health with two pinned manifests, a completed request-bound remote POST, and a completed streamed-ZIP PRE. PRE reported native Smol isolation and `cleanup=destroyed`; POST and PRE left material workspaces, model relays and -Smol leases empty. Focused local remote transport/intake coverage passed 85 -tests. Successful-checker public acceptance and a real model-callback provider +Smol leases empty. Focused local remote transport/intake coverage passed 113 +tests, including cancellation while source export is blocked and after exact +source EOF while native execution is active; both close source/transport and +leave the remote workspace empty. Successful-checker public acceptance and a real model-callback provider journey remain explicit integration qualifications, not claims from the transport smoke tests. diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py index 63a1cad4f..db7e56618 100644 --- a/backend/tests/checkers/external/test_runtime.py +++ b/backend/tests/checkers/external/test_runtime.py @@ -1165,26 +1165,56 @@ def open_source(self, **kwargs): @pytest.mark.asyncio -async def test_single_pre_cancellation_closes_source_and_transport(tmp_path): +@pytest.mark.parametrize("stage", ["source", "execution"]) +async def test_single_pre_cancellation_closes_source_and_transport(tmp_path, stage): + from dataclasses import replace from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation entered, source_closed, connection_closed = asyncio.Event(), asyncio.Event(), asyncio.Event() + payload = b"exact cancellation source" * 4000 reservation = _source_reservation() + if stage == "execution": + reservation = replace( + reservation, + source_contracts=selected_pre_submit_source_contracts(), + source=reservation.source.model_copy( + update={ + "raw_sha256": "sha256:" + hashlib.sha256(payload).hexdigest(), + "raw_byte_count": len(payload), + } + ), + ) lease = SelectedPreSubmitLeaseFacts(reservation, uuid4(), 1, reservation.pre_deadline_at) class Grant: async def open_source(self, *, lease): try: - entered.set() - await asyncio.Event().wait() - yield b"unreachable" + if stage == "source": + entered.set() + await asyncio.Event().wait() + yield b"unreachable" + else: + for offset in range(0, len(payload), 16 * 1024): + yield payload[offset:offset + 16 * 1024] finally: source_closed.set() async def handle(reader, writer): try: - await reader.read() + if stage == "execution": + request_size = struct.unpack(">I", await reader.readexactly(4))[0] + request = json.loads(await reader.readexactly(request_size)) + assert request["request_digest"] == reservation.request_digest + received = bytearray() + while True: + size = struct.unpack(">I", await reader.readexactly(4))[0] + if size == 0: + break + received.extend(await reader.readexactly(size)) + assert bytes(received) == payload + entered.set() + assert await reader.read() == b"" finally: writer.close() await writer.wait_closed() @@ -1221,6 +1251,7 @@ async def handle(reader, writer): await task await asyncio.wait_for(connection_closed.wait(), 2) assert source_closed.is_set() + assert list((materials / "workspaces").iterdir()) == [] finally: if not task.done(): task.cancel() @@ -1229,3 +1260,4 @@ async def handle(reader, writer): remote.close() await server.wait_closed() await remote.wait_closed() + await node.close() From c4873cc36b1550e3bf3e7953531bd211e4f7418e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:30:36 +0100 Subject: [PATCH 269/513] Retire superseded preparation command test harnesses --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 34 ++ backend/scripts/test_lane_catalogue.py | 2 - .../test_selected_preparation_command.py | 397 ------------------ backend/tests/test_ci_lane_catalogue.py | 9 +- .../tests/test_pre_submit_evidence_relock.py | 94 ----- .../tests/test_submission_bundle_admission.py | 310 -------------- ..._submission_bundle_preparation_recovery.py | 216 +--------- 7 files changed, 39 insertions(+), 1023 deletions(-) delete mode 100644 backend/tests/checkers/external/test_selected_preparation_command.py delete mode 100644 backend/tests/test_pre_submit_evidence_relock.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f8d2454c2..3ea39667a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8789,3 +8789,37 @@ row/guard was changed by fault injection. Structure/Ruff/diff passed. The old private predecessor-rule harness is now replaced by this current public proof. Hosted follow-up97750e9c8 integrated092986b8a; ARCH/SEC passed its exact delta. Runner-only repaired service qualification is coordinated; API remains unchanged. + +QA closed predecessor-rule transfer a0856e8fb PASS WITH LOW RISKS. Current remote +PRE cancellation source/execution cases integrated asf9fb0a090 (runner c12fd6cce, +reported113 focused passing cases). Next remove two preparation-only modules: +test_pre_submit_evidence_relock.py and external/test_selected_preparation_command.py. +Allowed files: those modules, test_lane_catalogue.py, test_ci_lane_catalogue.py, +and this record. No production or schema changes. Medium test-retirement risk. +The relock behavior is now the reviewed public upload-fence race c8a6cc9da. +Old selected-before-durable/prepared-size ordering is obsolete: current public +raw-ZIP/replay and source custody tests require sealed exact source before PRE, +then T4/T5. Current no-route/nonremediation public tests refuse bytes before +execution; foreground upload timeout/failure retains charge; expired PRE lease +refuses source/runtime opening. Source/execution cancellation closes readers, +remote transport and staged workspace; upload cancellation retains durable +cleanup custody. Current received-failure and unknown-acceptance tests preserve +recoverable outcomes. All mounted HTTP/shared ART tests remain. Verify exact +lane inventory/fingerprints, current runtime cancellation/expired-lease controls, +Ruff/diff/structure and QA deletion mapping. Remaining old SQL fixtures and +command references still prevent production writer retirement. +Extend the same test-only batch to preparation-command-only cases/fixtures in + test_submission_bundle_admission.py and test_submission_bundle_preparation_recovery.py. +Retain all mounted/public HTTP tests, public feedback fixture, shared scratch, +limits/bootstrap, and still-existing authorization-class tests. Remove old hidden +factory/endpoint/private lock-order/replay/status projection tests and obsolete +pre/post preparation archive wrappers. Their current public authority, replay, +source failure and cancellation proofs are mapped above and in the QA retirement +review; no old public endpoint or ready-admission contract remains required. +Run both retained modules in addition to focused cancellation/inventory checks. + +Retained module checks passed26/26 in19.19s. Current remote PRE cancellation +(source/execution), expired-lease and exact inventory/fingerprint/partition +checks passed6/6 in7.56s. Unused private fixture helpers/imports were removed +afterward; executable retained test bodies are unchanged. Ruff/diff passed. +No production factory or retained-data reader has been removed in this batch. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index abf373cc4..6af92ce79 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -297,7 +297,6 @@ class TestLane: "tests/test_submission_composition.py", "tests/test_artifact_bindings.py", "tests/test_artifact_bindings_db.py", - "tests/test_pre_submit_evidence_relock.py", "tests/test_artifact_operator_api.py", "tests/test_artifact_recovery.py", "tests/test_db_session.py", @@ -568,7 +567,6 @@ class TestLane: "tests/checkers/external/test_selected_intake_lifecycle.py", "tests/checkers/external/test_selected_pre_submit_coordination.py", "tests/checkers/external/test_selected_pre_submit_service.py", - "tests/checkers/external/test_selected_preparation_command.py", "tests/checkers/execution/test_execution.py", "tests/checkers/execution/test_completion_evidence.py", "tests/checkers/execution/test_coordination.py", diff --git a/backend/tests/checkers/external/test_selected_preparation_command.py b/backend/tests/checkers/external/test_selected_preparation_command.py deleted file mode 100644 index 09c4a234f..000000000 --- a/backend/tests/checkers/external/test_selected_preparation_command.py +++ /dev/null @@ -1,397 +0,0 @@ -"""The hidden contributor command selects the durable PRE owner exclusively.""" - -from tests.trusted_intake_fixtures import LocalIntakeAdapter -from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits - -from contextlib import asynccontextmanager -from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock - -import pytest - -import app.modules.artifacts.submission_admission as owner -from app.core.identifiers import new_record_id -from app.modules.artifacts.api import ( - SubmissionBundlePreparationRequest, - SubmissionBundlePreparationStatus, -) -from app.modules.artifacts.submission_admission import ( - PreparedSubmissionBundlePreparationCommand, - SubmissionBundleDurablePutResult, - SubmissionBundlePreparationRuntime, -) -from app.modules.authorization.api import ActorIdentityFacts, ActorKind -from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitCompletion -from app.modules.artifacts.api.submission_preparation import public_pre_submission_results -from tests.test_submission_bundle_preparation_recovery import _feedback_facts - - -@asynccontextmanager -async def _root(): - yield - - -def _request_case(): - actor = ActorIdentityFacts( - actor_profile_id=new_record_id(), - identity_link_id=new_record_id(), - actor_kind=ActorKind.HUMAN, - ) - task_id, assignment_id, attempt_id = (new_record_id() for _ in range(3)) - request = SubmissionBundlePreparationRequest( - actor=actor, - request_id=new_record_id(), - correlation_id=new_record_id(), - task_id=task_id, - assignment_id=assignment_id, - predecessor_submission_id=None, - idempotency_key=new_record_id(), - summary="", - contributor_attestation="", - media_type="application/zip", - byte_source=SimpleNamespace(), - ) - prepared = SimpleNamespace( - generation_id=new_record_id(), - commitment=SimpleNamespace(sha256="sha256:" + "1" * 64, byte_count=100), - inspect=AsyncMock(return_value=object()), - close=AsyncMock(), - ) - return actor, request, prepared, attempt_id - - -def _runtime_case(prepared, attempt_id): - policy = SimpleNamespace(policy_sha256="sha256:" + "a" * 64) - selected = SimpleNamespace(policy=policy, default_input=object(), change_gate=object()) - reservation = SimpleNamespace(attempt_id=attempt_id) - completion = SelectedPreSubmitCompletion( - terminal=SimpleNamespace( - outcome="completed", - execution=_feedback_facts(eligible=True), - infrastructure_failure_code=None, - ), - capability=object(), - ) - materialization = SimpleNamespace( - prepare_selected_authorization=AsyncMock(return_value=object()), - authorize_inspected=AsyncMock(), - ) - coordinator = SimpleNamespace( - read_current=AsyncMock(return_value=None), - reserve=AsyncMock(return_value=attempt_id), - ) - selected_execution = SimpleNamespace(execute=AsyncMock(return_value=completion)) - durable = SimpleNamespace( - admit_in_transaction=AsyncMock(return_value=(prepared, attempt_id, SimpleNamespace())), - publish_after_commit=AsyncMock( - return_value=SubmissionBundleDurablePutResult( - put_attempt_id=new_record_id(), - operation_identity="sha256:" + "2" * 64, - status="prepared", - replayed=False, - admission_id=None, - selected_pre_submit_run_id=attempt_id, - ) - ), - ) - runtime = SubmissionBundlePreparationRuntime( - preparation=SimpleNamespace(prepare=AsyncMock(return_value=prepared)), - intake=LocalIntakeAdapter(), archive_limits=SubmissionArchiveLimits(), - materialization=materialization, - durable_put=durable, - selected_coordinator=coordinator, - selected_execution=selected_execution, - storage_scheme="s3", - artifact_deadline_ms=120_000, - ) - return SimpleNamespace( - runtime=runtime, - policy=policy, - selected=selected, - reservation=reservation, - completion=completion, - materialization=materialization, - coordinator=coordinator, - selected_execution=selected_execution, - durable=durable, - ) - - -def _command(runtime, actor): - @asynccontextmanager - async def runtime_factory(): - yield runtime - - authority = SimpleNamespace(preflight=AsyncMock(), transaction=_root, close=Mock()) - command = PreparedSubmissionBundlePreparationCommand( - session=SimpleNamespace(begin=_root), - authority=authority, - task_contexts=SimpleNamespace(), - project_contexts=SimpleNamespace(), - runtime_factory=runtime_factory, - ) - project = SimpleNamespace( - effective_policy_id=new_record_id(), - pre_submit_policy_id=new_record_id(), - external_checker_policies=SimpleNamespace(value="{}"), - ) - command._lock_authorized_context = AsyncMock( - return_value=(SimpleNamespace(predecessor=None, checker_remediation_manifest_id=None, revision_context=None), project) - ) - command._load_predecessor = AsyncMock(return_value=None) - command._load_predecessor_rules = AsyncMock(return_value=None) - return command - - -def _patch_selected_owners(monkeypatch, case): - monkeypatch.setattr( - owner, - "LockedExternalCheckerPolicies", - SimpleNamespace( - model_validate_json=Mock(return_value=SimpleNamespace(pre_submit=case.policy)) - ), - ) - monkeypatch.setattr(owner, "build_submission_manifest", Mock(return_value=object())) - monkeypatch.setattr( - owner, "bind_selected_pre_submit_admission", Mock(return_value=case.selected) - ) - monkeypatch.setattr( - owner, - "build_selected_pre_submit_reservation", - Mock(return_value=case.reservation), - ) - monkeypatch.setattr( - owner, - "selected_pre_submit_attempt_request_digest", - Mock(return_value="sha256:" + "3" * 64), - ) - monkeypatch.setattr(owner, "selected_pre_submit_execution_budget_ms", Mock(return_value=60_000)) - - -@pytest.mark.asyncio -async def test_hidden_preparation_uses_selected_pre_before_durable_admission( - monkeypatch, -) -> None: - actor, request, prepared, attempt_id = _request_case() - case = _runtime_case(prepared, attempt_id) - command = _command(case.runtime, actor) - _patch_selected_owners(monkeypatch, case) - - result = await command.prepare(request) - - assert result.submission_bundle_preparation_status is ( - SubmissionBundlePreparationStatus.PREPARED - ) - case.runtime.preparation.prepare.assert_awaited_once_with( - request.byte_source, media_type="application/zip", maximum_bytes=524_288_000, - ) - # The admitted attempt returns its intake feedback from the executed facts. - assert result.pre_submission_results == tuple( - public_pre_submission_results(case.completion.terminal.execution) - ) - case.materialization.prepare_selected_authorization.assert_awaited_once() - case.materialization.authorize_inspected.assert_awaited_once() - case.coordinator.read_current.assert_awaited_once_with(case.reservation) - case.coordinator.reserve.assert_awaited_once_with(case.reservation) - case.selected_execution.execute.assert_awaited_once() - admitted = case.durable.admit_in_transaction.await_args.args[0] - assert admitted.selected_completion is case.completion - case.durable.publish_after_commit.assert_awaited_once_with( - prepared, - attempt_id, - case.durable.admit_in_transaction.return_value[2], - ) - - -@pytest.mark.asyncio -async def test_intake_prepares_after_sealing_with_exact_size_and_remaining_deadline(monkeypatch): - import asyncio - from dataclasses import replace - from tests.trusted_intake_fixtures import LocalIntakeSession - - actor, request, prepared, attempt_id = _request_case() - case = _runtime_case(prepared, attempt_id) - events = [] - session = LocalIntakeSession() - - async def prepare_vm(value): - assert events == ["upload_started", "upload_sealed"] - assert value.phase == "pre_submit" and value.archive_byte_count == prepared.commitment.byte_count - assert 0 < value.deadline_ms < 1990 - events.append("vm_ready") - return session - - async def upload(*args, **kwargs): - events.append("upload_started") - await asyncio.sleep(0.02) - case.coordinator.reserve.assert_not_awaited() - events.append("upload_sealed") - return prepared - - runtime = replace(case.runtime, intake=SimpleNamespace(prepare=prepare_vm), - preparation=SimpleNamespace(prepare=upload), artifact_deadline_ms=2000) - command = _command(runtime, actor) - _patch_selected_owners(monkeypatch, case) - await command.prepare(request) - assert events == ["upload_started", "upload_sealed", "vm_ready"] - prepared.close.assert_awaited_once() - assert session.closed - - -@pytest.mark.asyncio -async def test_unauthorized_upload_does_not_prepare_vm_or_consume_bytes(monkeypatch): - from dataclasses import replace - from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError - from app.modules.artifacts.api import SubmissionBundlePreparationUnavailable - - actor, request, prepared, attempt_id = _request_case() - case = _runtime_case(prepared, attempt_id) - intake = SimpleNamespace(prepare=AsyncMock()) - runtime = replace(case.runtime, intake=intake) - command = _command(runtime, actor) - command._lock_authorized_context = AsyncMock(side_effect=ArtifactAuthorityDeniedError("denied")) - _patch_selected_owners(monkeypatch, case) - with pytest.raises(SubmissionBundlePreparationUnavailable): - await command.prepare(request) - intake.prepare.assert_not_awaited() - runtime.preparation.prepare.assert_not_awaited() - case.coordinator.reserve.assert_not_awaited() - - -@pytest.mark.asyncio -async def test_upload_failure_does_not_allocate_intake_or_reserve_attempt(monkeypatch): - from dataclasses import replace - - actor, request, prepared, attempt_id = _request_case() - case = _runtime_case(prepared, attempt_id) - intake = SimpleNamespace(prepare=AsyncMock()) - runtime = replace(case.runtime, intake=intake, - preparation=SimpleNamespace(prepare=AsyncMock(side_effect=OSError("upload interrupted")))) - command = _command(runtime, actor) - _patch_selected_owners(monkeypatch, case) - with pytest.raises(OSError, match="upload interrupted"): - await command.prepare(request) - intake.prepare.assert_not_awaited() - prepared.close.assert_not_awaited() - case.coordinator.reserve.assert_not_awaited() - case.durable.admit_in_transaction.assert_not_awaited() - - -@pytest.mark.asyncio -async def test_failed_vm_preparation_closes_already_sealed_source(monkeypatch): - from dataclasses import replace - from workstream_external_services import ExternalServiceUnavailableError - from app.modules.artifacts.api import SubmissionBundlePreparationInfrastructureUnavailable - - actor, request, prepared, attempt_id = _request_case() - case = _runtime_case(prepared, attempt_id) - intake = SimpleNamespace(prepare=AsyncMock(side_effect=ExternalServiceUnavailableError())) - command = _command(replace(case.runtime, intake=intake), actor) - _patch_selected_owners(monkeypatch, case) - with pytest.raises(SubmissionBundlePreparationInfrastructureUnavailable): - await command.prepare(request) - prepared.close.assert_awaited_once() - case.coordinator.reserve.assert_not_awaited() - case.durable.admit_in_transaction.assert_not_awaited() - - -@pytest.mark.asyncio -@pytest.mark.parametrize("stage", ["upload", "boot", "inspection"]) -async def test_caller_cancellation_drains_current_stage_and_sealed_source(monkeypatch, stage): - import asyncio - from dataclasses import replace - from tests.trusted_intake_fixtures import LocalIntakeSession - - actor, request, prepared, attempt_id = _request_case() - case = _runtime_case(prepared, attempt_id) - entered, drained = asyncio.Event(), asyncio.Event() - session = LocalIntakeSession() - - async def blocked(): - entered.set() - try: - await asyncio.Event().wait() - finally: - drained.set() - - async def prepare_vm(value): - if stage == "boot": - await blocked() - return session - - async def upload(*args, **kwargs): - if stage == "upload": - await blocked() - return prepared - - async def inspect(*args, **kwargs): - await blocked() - - intake = SimpleNamespace(prepare=AsyncMock(side_effect=prepare_vm)) - prepared.inspect = AsyncMock(side_effect=inspect) - runtime = replace(case.runtime, intake=intake, preparation=SimpleNamespace(prepare=upload)) - command = _command(runtime, actor) - _patch_selected_owners(monkeypatch, case) - pending = asyncio.create_task(command.prepare(request)) - await asyncio.wait_for(entered.wait(), 2) - pending.cancel() - with pytest.raises(asyncio.CancelledError): - await asyncio.wait_for(pending, 2) - assert drained.is_set() - if stage == "upload": - intake.prepare.assert_not_awaited() - prepared.close.assert_not_awaited() - else: - prepared.close.assert_awaited_once() - assert session.closed is (stage == "inspection") - assert session.aborted is (stage == "inspection") - assert session.default_bindings == [] - case.coordinator.reserve.assert_not_awaited() - case.selected_execution.execute.assert_not_awaited() - case.durable.admit_in_transaction.assert_not_awaited() - case.durable.publish_after_commit.assert_not_awaited() - - -@pytest.mark.asyncio -async def test_slow_upload_expires_original_deadline_before_vm_allocation(monkeypatch): - import asyncio - from dataclasses import replace - from app.modules.artifacts.api import SubmissionBundlePreparationInfrastructureUnavailable - - actor, request, prepared, attempt_id = _request_case() - case = _runtime_case(prepared, attempt_id) - drained = asyncio.Event() - - async def upload(*args, **kwargs): - try: - await asyncio.Event().wait() - finally: - drained.set() - - intake = SimpleNamespace(prepare=AsyncMock()) - runtime = replace(case.runtime, intake=intake, preparation=SimpleNamespace(prepare=upload), artifact_deadline_ms=20) - command = _command(runtime, actor) - _patch_selected_owners(monkeypatch, case) - with pytest.raises(SubmissionBundlePreparationInfrastructureUnavailable): - await asyncio.wait_for(command.prepare(request), 2) - assert drained.is_set() - intake.prepare.assert_not_awaited() - case.coordinator.reserve.assert_not_awaited() - case.durable.admit_in_transaction.assert_not_awaited() - - -@pytest.mark.asyncio -async def test_unconfirmed_intake_deadline_returns_recoverable_failure(monkeypatch): - from app.modules.artifacts.preparation import ArtifactPreparationDeadlineError - from app.modules.artifacts.api import SubmissionBundlePreparationInfrastructureUnavailable - - actor, request, prepared, attempt_id = _request_case() - case = _runtime_case(prepared, attempt_id) - case.selected_execution.execute.side_effect = ArtifactPreparationDeadlineError("expired") - command = _command(case.runtime, actor) - _patch_selected_owners(monkeypatch, case) - with pytest.raises(SubmissionBundlePreparationInfrastructureUnavailable) as failure: - await command.prepare(request) - assert str(failure.value) == "pre_submission_attempt_outcome_unresolved" - case.durable.admit_in_transaction.assert_not_awaited() - case.durable.publish_after_commit.assert_not_awaited() diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 8a0dc080c..52c6052fb 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -111,7 +111,6 @@ def test_checker_delivery_and_routing_preparation_partition_every_node_once() -> "tests/checkers/external/test_selected_intake_lifecycle.py", "tests/checkers/external/test_selected_pre_submit_coordination.py", "tests/checkers/external/test_selected_pre_submit_service.py", - "tests/checkers/external/test_selected_preparation_command.py", "tests/checkers/execution/test_execution.py", "tests/checkers/execution/test_completion_evidence.py", "tests/checkers/execution/test_coordination.py", @@ -321,12 +320,12 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 278, - "0a1ac7e344208a8178f30f48b54774afaf57b54bf76e89a34debfc5867d18038", + 277, + "450b3fdb7336f81066405c487b2fa05fb2ee394dae66df917b5dbc0bb7009229", ), "project": ( - 259, - "a39f6728caab1ab6d593ca5740cbd505e60996bbdb924195fba553aa89933178", + 258, + "90240bd7c6dcb03c20bcf271ec2afbc153901f49ede40fc074ce06d6a8d3c15e", ), "task": ( 96, diff --git a/backend/tests/test_pre_submit_evidence_relock.py b/backend/tests/test_pre_submit_evidence_relock.py deleted file mode 100644 index f4043f1a4..000000000 --- a/backend/tests/test_pre_submit_evidence_relock.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Post-byte TASK drift refuses selected execution and durable admission.""" - -from contextlib import asynccontextmanager -from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock - -import pytest - -from app.core.identifiers import new_record_id -from app.modules.artifacts.api import ( - SubmissionBundlePreparationRejected, SubmissionBundlePreparationRequest, -) -from app.modules.artifacts.api.submission_archive import ( - MAXIMUM_SUBMISSION_ZIP_BYTES, SubmissionArchiveLimits, -) -from app.modules.artifacts.sources import ArtifactCommitment -from app.modules.artifacts.submission_admission import PreparedSubmissionBundlePreparationCommand -from app.modules.authorization.api import ActorIdentityFacts, ActorKind -from app.modules.tasks.api import TaskSubmissionContextUnavailable -from tests.checkers.external.test_selected_pre_submit import _policies -from tests.trusted_intake_fixtures import LocalIntakeAdapter - - -@pytest.mark.asyncio -async def test_stale_task_relock_denies_before_selected_execution_or_admission(): - actor = ActorIdentityFacts(new_record_id(), new_record_id(), ActorKind.HUMAN) - references = SimpleNamespace( - project_id=new_record_id(), guide_version="v1", - source_snapshot_id=new_record_id(), source_snapshot_hash="sha256:" + "1" * 64, - effective_policy_id=new_record_id(), effective_policy_hash="sha256:" + "2" * 64, - pre_submit_policy_id=new_record_id(), pre_submit_policy_bundle_hash="sha256:" + "3" * 64, - ) - task = SimpleNamespace(locked_project_context=references, predecessor=None, - checker_remediation_manifest_id=None) - tasks = SimpleNamespace(lock_submission_context=AsyncMock(side_effect=[ - task, TaskSubmissionContextUnavailable("task_submission_context_invalid"), - ])) - project = SimpleNamespace(external_checker_policies=SimpleNamespace( - value=_policies().model_dump_json(), - )) - projects = SimpleNamespace(lock_locked_policy_context=AsyncMock(return_value=project)) - authority = SimpleNamespace(preflight=AsyncMock(), lock_actor=AsyncMock(), - revalidate=AsyncMock(), close=Mock()) - prepared = SimpleNamespace( - commitment=ArtifactCommitment("sha256:" + "a" * 64, 1, "application/zip"), - close=AsyncMock(), - ) - coordinator = SimpleNamespace(read_current=AsyncMock(), reserve=AsyncMock()) - executor = SimpleNamespace(execute=AsyncMock()) - durable = SimpleNamespace(admit_in_transaction=AsyncMock(), publish_after_commit=AsyncMock()) - runtime = SimpleNamespace( - selected_coordinator=coordinator, selected_execution=executor, storage_scheme="s3", - intake=LocalIntakeAdapter(), archive_limits=SubmissionArchiveLimits(), - artifact_deadline_ms=60_000, - preparation=SimpleNamespace(prepare=AsyncMock(return_value=prepared)), durable_put=durable, - ) - - @asynccontextmanager - async def root(): - yield - - @asynccontextmanager - async def runtime_factory(): - yield runtime - - command = PreparedSubmissionBundlePreparationCommand( - session=SimpleNamespace(begin=root), authority=authority, - task_contexts=tasks, project_contexts=projects, runtime_factory=runtime_factory, - ) - request = SubmissionBundlePreparationRequest( - actor=actor, request_id=new_record_id(), correlation_id=new_record_id(), - task_id=new_record_id(), assignment_id=new_record_id(), predecessor_submission_id=None, - idempotency_key=new_record_id(), summary="", contributor_attestation="", - media_type="application/zip", byte_source=object(), - ) - with pytest.raises(SubmissionBundlePreparationRejected, - match="^submission_bundle_preparation_context_changed$"): - await command.prepare(request) - assert tasks.lock_submission_context.await_count == 2 - runtime.preparation.prepare.assert_awaited_once_with( - request.byte_source, media_type="application/zip", maximum_bytes=MAXIMUM_SUBMISSION_ZIP_BYTES, - ) - projects.lock_locked_policy_context.assert_awaited_once() - authority.lock_actor.assert_awaited_once() - authority.revalidate.assert_awaited_once() - coordinator.read_current.assert_not_awaited() - coordinator.reserve.assert_not_awaited() - executor.execute.assert_not_awaited() - durable.admit_in_transaction.assert_not_awaited() - durable.publish_after_commit.assert_not_awaited() - prepared.close.assert_awaited_once() - assert len(runtime.intake.sessions) == 1 - assert runtime.intake.sessions[0].events == ["close"] - authority.close.assert_called_once_with() diff --git a/backend/tests/test_submission_bundle_admission.py b/backend/tests/test_submission_bundle_admission.py index 294471867..e4d606aa2 100644 --- a/backend/tests/test_submission_bundle_admission.py +++ b/backend/tests/test_submission_bundle_admission.py @@ -2,23 +2,17 @@ from __future__ import annotations -from contextlib import asynccontextmanager from types import SimpleNamespace from unittest.mock import AsyncMock, Mock from app.core.identifiers import new_record_id import pytest -from httpx import ASGITransport, AsyncClient -from starlette.requests import Request import app.adapters.artifacts as artifact_adapters from app.core.config import Settings -from app.db.session import get_db_session from app.modules.artifacts.api import ( SubmissionBundlePreparationRejected, SubmissionBundlePreparationRequest, - SubmissionBundlePreparationResult, - SubmissionBundlePreparationUnavailable, ) from app.modules.artifacts.schemas import ( ArtifactAuthorityDeniedError, @@ -30,17 +24,8 @@ DenySubmissionBundlePreparedAuthorization, DenySubmissionBundlePreparationAuthorization, ) -from app.modules.artifacts.submission_admission import ( - SubmissionBundleDurablePutResult, -) -from app.modules.artifacts.submission_admission import ( - PreparedSubmissionBundlePreparationCommand, -) from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.authorization.prepared import PreparedAuthorizationHandle -from app.modules.artifacts.api.submission_preparation import public_pre_submission_results -from tests.artifact_store_helpers import artifact_byte_stream -from tests.test_submission_bundle_preparation_recovery import _feedback_facts from tests.artifact_store_helpers import artifact_admission_limit_settings from app.main import create_app from app.api.routes.artifact_submissions import router as submission_router @@ -73,10 +58,6 @@ def _preparation_request( ) -def _sha(character: str) -> str: - return "sha256:" + character * 64 - - @pytest.mark.asyncio async def test_artifact_adapter_preserves_public_actor_facts() -> None: actor = _actor() @@ -86,9 +67,6 @@ async def test_artifact_adapter_preserves_public_actor_facts() -> None: @pytest.mark.asyncio async def test_explicit_deny_preparation_authority_denies() -> None: - from app.modules.artifacts.submission_authorization import ( - DenySubmissionBundlePreparationAuthorization, - ) authority = DenySubmissionBundlePreparationAuthorization() request = _preparation_request(byte_source=object()) @@ -163,8 +141,6 @@ def test_artifact_adapter_maps_preparation_limits_from_settings() -> None: ) - - def test_artifact_adapter_requires_configured_scratch_root() -> None: settings = Settings() settings.artifact_scratch_root = None @@ -195,57 +171,6 @@ def test_artifact_adapter_builds_configured_local_bootstrap(tmp_path) -> None: bootstrap.close() -def test_artifact_adapter_composes_submission_command_from_owner_ports( - monkeypatch: pytest.MonkeyPatch, -) -> None: - request_id = new_record_id() - correlation_id = new_record_id() - request = Request( - { - "type": "http", - "method": "POST", - "path": "/hidden", - "headers": [], - "state": { - "request_id": str(request_id), - "correlation_id": str(correlation_id), - }, - } - ) - request.scope["app"] = SimpleNamespace( - state=SimpleNamespace( - settings=Settings(), - ) - ) - session = object() - internal_authority = object() - authority = SimpleNamespace(close=Mock()) - task_contexts = object() - project_contexts = object() - monkeypatch.setattr( - artifact_adapters, "task_submission_context_port", Mock(return_value=task_contexts) - ) - monkeypatch.setattr( - artifact_adapters, - "project_locked_policy_context_port", - Mock(return_value=project_contexts), - ) - - command = artifact_adapters.get_submission_bundle_preparation_command( - request, - session, # type: ignore[arg-type] - internal_authority, # type: ignore[arg-type] - authority, - ) - - assert command._session is session - assert command._authority is authority - assert command._task_contexts is task_contexts - assert command._project_contexts is project_contexts - artifact_adapters.task_submission_context_port.assert_called_once_with(session) - artifact_adapters.project_locked_policy_context_port.assert_called_once_with(session) - - def test_submission_is_public_binary_contract() -> None: from fastapi import FastAPI @@ -272,50 +197,6 @@ def test_submission_is_public_binary_contract() -> None: assert operation["responses"]["202"] and operation["responses"]["422"] -@pytest.mark.asyncio -async def test_app_profile_zip_preparation_is_retryable_without_reading_upload(tmp_path) -> None: - root = tmp_path / "objects" - root.mkdir(mode=0o700) - app = create_app(Settings( - _env_file=None, - **artifact_admission_limit_settings(), - environment="test", - hosted_profile="app", - artifact_store_backend="local", - artifact_local_root=root, - artifact_scratch_root=tmp_path / "scratch", - artifact_scratch_minimum_free_bytes=0, - )) - session = SimpleNamespace(rollback=AsyncMock(), begin=Mock()) - authority = SimpleNamespace(preflight=AsyncMock(), close=Mock()) - app.dependency_overrides.update({ - get_db_session: lambda: session, - artifact_adapters.get_submission_bundle_preparation_actor: _actor, - artifact_adapters.get_artifact_internal_authority: object, - artifact_adapters.get_submission_bundle_preparation_authorization: lambda: authority, - }) - - async def upload(): - pytest.fail("offline preparation consumed the uploaded body") - yield b"PK" - - async with AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as client: - response = await client.post( - f"/api/v1/tasks/{new_record_id()}/submission-bundle-preparations", - headers={ - "Content-Type": "application/zip", - "X-Task-Assignment-Id": str(new_record_id()), - "Idempotency-Key": str(new_record_id()), - }, - content=upload(), - ) - assert response.status_code == 503 - assert response.json()["error"]["code"] == "service_unavailable" - assert response.json()["error"]["retryable"] is True - authority.preflight.assert_awaited_once() - session.begin.assert_not_called() - - def test_submission_packet_headers_reject_non_ascii() -> None: validate_submission_packet_headers("plain summary", "plain attestation") with pytest.raises( @@ -325,197 +206,6 @@ def test_submission_packet_headers_reject_non_ascii() -> None: validate_submission_packet_headers("caf\N{LATIN SMALL LETTER E WITH ACUTE}", "ok") -@asynccontextmanager -async def _transaction(): - yield - - -@pytest.mark.asyncio -async def test_hidden_preparation_denies_before_reading_uploaded_bytes() -> None: - reads = 0 - - async def bytes_source(): - nonlocal reads - reads += 1 - yield b"PK\x03\x04must-not-be-read" - - def runtime_factory(): - raise AssertionError("runtime must not open before contributor preflight") - - command = PreparedSubmissionBundlePreparationCommand( - session=SimpleNamespace(), - authority=DenySubmissionBundlePreparationAuthorization(), - task_contexts=SimpleNamespace(), - project_contexts=SimpleNamespace(), - runtime_factory=runtime_factory, - ) - with pytest.raises(SubmissionBundlePreparationUnavailable): - await command.prepare( - _preparation_request( - byte_source=bytes_source(), - summary="caf\N{LATIN SMALL LETTER E WITH ACUTE}", - ) - ) - assert reads == 0 - - -@pytest.mark.asyncio -async def test_hidden_preparation_closes_authority_after_invalid_media_type() -> None: - authority = SimpleNamespace( - preflight=AsyncMock(), - close=Mock(), - ) - command = PreparedSubmissionBundlePreparationCommand( - session=SimpleNamespace(), - authority=authority, - task_contexts=SimpleNamespace(), - project_contexts=SimpleNamespace(), - runtime_factory=Mock(side_effect=AssertionError("runtime must stay closed")), - ) - with pytest.raises( - SubmissionBundlePreparationRejected, - match="submission_bundle_media_type_invalid", - ): - await command.prepare( - _preparation_request( - byte_source=artifact_byte_stream(b"{}"), media_type="application/json" - ) - ) - authority.close.assert_called_once_with() - - -@pytest.mark.asyncio -@pytest.mark.parametrize("denied_phase", ("actor", "grant")) -async def test_authority_denial_preserves_task_actor_project_grant_order(denied_phase) -> None: - events = [] - denial = ArtifactAuthorityDeniedError("submission bundle preparation is unavailable") - - def phase(name): - async def invoke(*_args, **_kwargs): - events.append(name) - if name == denied_phase: - raise denial - return object() - - return invoke - - authority = SimpleNamespace( - lock_actor=AsyncMock(side_effect=phase("actor")), - revalidate=AsyncMock(side_effect=phase("grant")), - ) - references = SimpleNamespace( - project_id=new_record_id(), guide_version="v1", - source_snapshot_id=new_record_id(), source_snapshot_hash=_sha("1"), - effective_policy_id=new_record_id(), effective_policy_hash=_sha("2"), - pre_submit_policy_id=new_record_id(), pre_submit_policy_bundle_hash=_sha("3"), - ) - task = SimpleNamespace(locked_project_context=references) - async def lock_task(*args): - events.append("task") - return task - project_contexts = SimpleNamespace(lock_locked_policy_context=AsyncMock(side_effect=phase("project"))) - command = PreparedSubmissionBundlePreparationCommand( - session=SimpleNamespace(), authority=authority, - task_contexts=SimpleNamespace(lock_submission_context=AsyncMock(side_effect=lock_task)), - project_contexts=project_contexts, runtime_factory=Mock(), - ) - with pytest.raises(ArtifactAuthorityDeniedError) as caught: - await command._lock_authorized_context(_preparation_request(byte_source=object())) - assert caught.value is denial - assert events == ( - ["task", "actor"] if denied_phase == "actor" else ["task", "actor", "project", "grant"] - ) - command._runtime_factory.assert_not_called() - - -@pytest.mark.asyncio -@pytest.mark.parametrize( - "admission_status,expected_status", - ( - ("ready", "ready"), - ("stale", "stale"), - ("consumed", "conflict"), - ), -) -async def test_selected_replay_projects_current_admission_state( - admission_status, - expected_status, -) -> None: - attempt_id = new_record_id() - admission_id = new_record_id() - row_result = SimpleNamespace( - one_or_none=lambda: ( - SimpleNamespace(id=str(new_record_id())), - SimpleNamespace(id=str(attempt_id), status="object_confirmed"), - SimpleNamespace(id=str(admission_id), status=admission_status), - ) - ) - session = SimpleNamespace(begin=_transaction, execute=AsyncMock(return_value=row_result)) - command = PreparedSubmissionBundlePreparationCommand( - session=session, - authority=SimpleNamespace(), - task_contexts=SimpleNamespace(), - project_contexts=SimpleNamespace(), - runtime_factory=Mock(), - ) - - execution = _feedback_facts(eligible=True) - result = await command._selected_replay_result(SimpleNamespace( - run_id=new_record_id(), status="completed", - terminal=SimpleNamespace(outcome="completed", execution=execution), - )) - - # Exact replay returns the retained intake feedback, not a fresh check. - assert result == SubmissionBundlePreparationResult( - put_attempt_id=attempt_id, - admission_id=admission_id if admission_status == "ready" else None, - submission_bundle_preparation_status=expected_status, - replayed=True, - pre_submission_results=tuple(public_pre_submission_results(execution)), - ) - - -@pytest.mark.parametrize( - "durable_status", - ( - "prepared", - "put_in_flight", - "object_confirmed", - "stored_pending_verification", - "observed_confirmed", - "acknowledgement_unknown", - "provider_unavailable", - "conflict", - "integrity_mismatch", - "missing", - "absent_replay_required", - "stale", - "ready", - ), -) -def test_durable_put_result_projects_every_closed_preparation_status( - durable_status: str, -) -> None: - durable = SubmissionBundleDurablePutResult( - put_attempt_id=new_record_id(), - selected_pre_submit_run_id=new_record_id(), - operation_identity=_sha("9"), - admission_id=None, - status=durable_status, - replayed=True, - ) - execution = _feedback_facts(eligible=True) - assert PreparedSubmissionBundlePreparationCommand._result(durable, execution) == ( - SubmissionBundlePreparationResult( - put_attempt_id=durable.put_attempt_id, - admission_id=None, - submission_bundle_preparation_status=durable_status, - replayed=True, - pre_submission_results=tuple(public_pre_submission_results(execution)), - ) - ) - - @pytest.mark.asyncio async def test_deny_submission_authority_fails_closed() -> None: with pytest.raises(ArtifactAuthorityDeniedError): diff --git a/backend/tests/test_submission_bundle_preparation_recovery.py b/backend/tests/test_submission_bundle_preparation_recovery.py index c7ed2076d..3761b8690 100644 --- a/backend/tests/test_submission_bundle_preparation_recovery.py +++ b/backend/tests/test_submission_bundle_preparation_recovery.py @@ -2,36 +2,22 @@ from app.adapters.artifacts import selected_pre_submit_source_contracts -from tests.trusted_intake_fixtures import LocalIntakeAdapter -from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits -from contextlib import asynccontextmanager from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock +from unittest.mock import AsyncMock from app.core.identifiers import new_record_id import pytest from httpx import ASGITransport, AsyncClient -import app.modules.artifacts.submission_admission as submission_admission from app.api.deps.authorization import get_authorization_actor_identity from app.adapters.artifacts import get_submission_intake_command from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure from app.modules.artifacts.api.submission_preparation import public_pre_submission_results from app.main import create_app from app.modules.artifacts.api import ( - SubmissionBundlePreparationRequest, SubmissionBundlePreparationCheckFailed, - SubmissionBundlePreparationRejected, -) -from app.modules.artifacts.submission_admission import ( - PreparedSubmissionBundlePreparationCommand, - SubmissionBundlePreparationRuntime, -) -from app.modules.artifacts.api.submission_archive import ( - SubmissionArchiveFailureCode, - SubmissionArchiveRejectedError, ) from app.modules.checkers.api.default_checker import ( WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, WORKSTREAM_DEFAULT_CHECK_IDS, @@ -43,7 +29,6 @@ def _actor(): return ActorIdentityFacts(new_record_id(), new_record_id(), ActorKind.HUMAN) - def _feedback_facts(*, eligible: bool = False) -> SelectedPreSubmitExecutionFacts: """Use the sole selected default result shape for sanitized HTTP feedback.""" checks = tuple({ @@ -69,7 +54,6 @@ def _feedback_facts(*, eligible: bool = False) -> SelectedPreSubmitExecutionFact ) - async def _mounted_submission_response(error=None, *, command=None, packet_text=True): app = create_app() app.dependency_overrides[get_authorization_actor_identity] = _actor @@ -159,204 +143,6 @@ async def test_mounted_submission_does_not_reclassify_unexpected_failure() -> No ) -@asynccontextmanager -async def _transaction(): - yield - - -def _post_reservation_runtime_case(): - actor = _actor() - request = SubmissionBundlePreparationRequest( - actor=actor, - request_id=new_record_id(), - correlation_id=new_record_id(), - task_id=new_record_id(), - assignment_id=new_record_id(), - predecessor_submission_id=None, - idempotency_key=new_record_id(), - summary="summary", - contributor_attestation="attestation", - media_type="application/zip", - byte_source=SimpleNamespace(), - ) - prepared = SimpleNamespace( - generation_id=new_record_id(), - commitment=SimpleNamespace(sha256="sha256:" + "1" * 64, byte_count=100), - inspect=AsyncMock(return_value=object()), - close=AsyncMock(), - ) - policy = SimpleNamespace(policy_sha256="sha256:" + "a" * 64) - selected = SimpleNamespace( - policy=policy, - default_input=object(), - change_gate=object(), - ) - reservation = SimpleNamespace(attempt_id=new_record_id()) - materialization = SimpleNamespace( - prepare_selected_authorization=AsyncMock(return_value=object()), - authorize_inspected=AsyncMock(), - ) - coordinator = SimpleNamespace( - read_current=AsyncMock(return_value=None), - reserve=AsyncMock(return_value=reservation.attempt_id), - ) - later_failure = SubmissionArchiveRejectedError( - SubmissionArchiveFailureCode.INTEGRITY_FAILURE - ) - selected_execution = SimpleNamespace( - execute=AsyncMock(side_effect=later_failure), - ) - durable_put = SimpleNamespace( - admit_in_transaction=AsyncMock(), - publish_after_commit=AsyncMock(), - ) - runtime = SubmissionBundlePreparationRuntime( - preparation=SimpleNamespace(prepare=AsyncMock(return_value=prepared)), - intake=LocalIntakeAdapter(), archive_limits=SubmissionArchiveLimits(), - materialization=materialization, - durable_put=durable_put, - selected_coordinator=coordinator, - selected_execution=selected_execution, - storage_scheme="s3", - artifact_deadline_ms=120_000, - ) - return SimpleNamespace( - request=request, - prepared=prepared, - policy=policy, - selected=selected, - reservation=reservation, - materialization=materialization, - coordinator=coordinator, - later_failure=later_failure, - selected_execution=selected_execution, - durable_put=durable_put, - runtime=runtime, - ) - - -def _post_reservation_command(case, monkeypatch): - @asynccontextmanager - async def runtime_factory(): - yield case.runtime - - authority = SimpleNamespace( - preflight=AsyncMock(), - transaction=_transaction, - close=Mock(), - ) - command = PreparedSubmissionBundlePreparationCommand( - session=SimpleNamespace(begin=_transaction), - authority=authority, - task_contexts=SimpleNamespace(), - project_contexts=SimpleNamespace(), - runtime_factory=runtime_factory, - ) - task = SimpleNamespace( - predecessor=None, - checker_remediation_manifest_id=None, - revision_context=None, - ) - project = SimpleNamespace( - effective_policy_id=new_record_id(), - pre_submit_policy_id=new_record_id(), - external_checker_policies=SimpleNamespace(value="{}"), - ) - command._lock_authorized_context = AsyncMock(return_value=(task, project)) - command._load_predecessor = AsyncMock(return_value=None) - command._load_predecessor_rules = AsyncMock(return_value=None) - monkeypatch.setattr( - submission_admission, - "LockedExternalCheckerPolicies", - SimpleNamespace( - model_validate_json=Mock( - return_value=SimpleNamespace(pre_submit=case.policy) - ) - ), - ) - monkeypatch.setattr( - submission_admission, - "build_submission_manifest", - Mock(return_value=object()), - ) - monkeypatch.setattr( - submission_admission, - "bind_selected_pre_submit_admission", - Mock(return_value=case.selected), - ) - monkeypatch.setattr( - submission_admission, - "build_selected_pre_submit_reservation", - Mock(return_value=case.reservation), - ) - monkeypatch.setattr( - submission_admission, - "selected_pre_submit_attempt_request_digest", - Mock(return_value="sha256:" + "2" * 64), - ) - monkeypatch.setattr( - submission_admission, - "selected_pre_submit_execution_budget_ms", - Mock(return_value=60_000), - ) - return command, authority - - -@pytest.mark.asyncio -@pytest.mark.parametrize("failure_stage", ["empty_sealed_archive", "inspection"]) -async def test_pre_reservation_archive_failure_is_rejected_without_reserving( - monkeypatch, failure_stage, -) -> None: - case = _post_reservation_runtime_case() - if failure_stage == "empty_sealed_archive": - from hashlib import sha256 - - case.prepared.commitment.byte_count = 0 - case.prepared.commitment.sha256 = "sha256:" + sha256(b"").hexdigest() - else: - case.prepared.inspect.side_effect = SubmissionArchiveRejectedError( - SubmissionArchiveFailureCode.MALFORMED - ) - command, authority = _post_reservation_command(case, monkeypatch) - - with pytest.raises(SubmissionBundlePreparationRejected) as failure: - await command.prepare(case.request) - - assert str(failure.value) == SubmissionArchiveFailureCode.MALFORMED.value - if failure_stage == "empty_sealed_archive": - case.prepared.inspect.assert_not_awaited() - else: - case.prepared.inspect.assert_awaited_once() - case.materialization.authorize_inspected.assert_not_awaited() - case.coordinator.reserve.assert_not_awaited() - case.selected_execution.execute.assert_not_awaited() - case.durable_put.admit_in_transaction.assert_not_awaited() - case.durable_put.publish_after_commit.assert_not_awaited() - case.prepared.close.assert_awaited_once() - authority.close.assert_called_once() - - -@pytest.mark.asyncio -async def test_post_reservation_archive_failure_remains_recoverable( - monkeypatch, -) -> None: - """A later projection failure must retain its reserved PRE recovery owner.""" - case = _post_reservation_runtime_case() - command, authority = _post_reservation_command(case, monkeypatch) - - with pytest.raises(SubmissionArchiveRejectedError) as failure: - await command.prepare(case.request) - - assert failure.value is case.later_failure - case.materialization.authorize_inspected.assert_awaited_once() - case.coordinator.reserve.assert_awaited_once_with(case.reservation) - case.selected_execution.execute.assert_awaited_once() - case.durable_put.admit_in_transaction.assert_not_awaited() - case.durable_put.publish_after_commit.assert_not_awaited() - case.prepared.close.assert_awaited_once() - authority.close.assert_called_once() - - @pytest.mark.asyncio @pytest.mark.parametrize("code,status_code,retryable", ( ("submission_operation_in_progress", 409, False), From 565704c3a02d937188d144d8151fba0b9a065999 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:37:55 +0100 Subject: [PATCH 270/513] Exercise current PRE SQL guard against superseded revision cause --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 25 ++++ .../test_submission_predecessor_custody.py | 133 ++++++++++++------ 2 files changed, 112 insertions(+), 46 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3ea39667a..3f15bc068 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8823,3 +8823,28 @@ Retained module checks passed26/26 in19.19s. Current remote PRE cancellation checks passed6/6 in7.56s. Unused private fixture helpers/imports were removed afterward; executable retained test bodies are unchanged. Ruff/diff passed. No production factory or retained-data reader has been removed in this batch. + +QA approved c4873cc36 test retirement. Next replace the old superseded-cause SQL +fixture with current public source intake, valid/superseded controls. Allowed: +predecessor custody test and this record only. During upload advance the real +checker fence; freeze only application TASK context/selected-scope reads to the +previous allowed facts so the actual selected PRE INSERT guard is exercised. +Keep all native SQL guards and writes real. Require exact23514 routed-cause +failure, no PRE execution/admission/Submission, retained sealed source charge; +positive control must insert/run PRE and accept202. Medium authority-test risk; +isolated PostgreSQL pair, Ruff/structure and focused QA/ARCH review. No production, +schema or retained-data edits. Foreign-cause SQL fixture remains next. + +The valid control passed in the first pair run. Its negative parameter and an +isolated retry failed earlier in fixture creation at the unchanged selected PRE +timestamp ordering guard, before the tested upload. Added exception-only clock +value notes (no timestamp/guard substitution); the targeted negative then passed +in31.11s with exact23514 routed-cause error, zero PRE calls and charged failed +source. Receipts: /tmp/submission-current-pre-sql-fence.json (mixed result), +/tmp/submission-current-pre-sql-fence-retry.json (fixture failure), and +/tmp/submission-pre-clock-diagnostic.json (negative pass); all cleanup complete, +schema0090. Positive and negative evidence is from separate runs, not one clean +aggregate. The intermittent fixture timing cause remains unresolved; a100000 +sample database-clock probe observed no backwards samples and does not establish +that no clock adjustment occurred. Retain diagnostic notes for recurrence. +Structure passed before exception-note-only addition; Ruff/diff checked final. diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 5042f672e..0525fcbfd 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -483,59 +483,100 @@ async def test_replacement_dispatch_sql_rejects_cause_and_receipt_substitution( ) is False, field +@pytest.mark.parametrize("advance_fence", [False, True]) async def test_sql_selected_pre_reservation_rejects_superseded_checker_cause( - tmp_path, - isolated_database_env, + tmp_path, isolated_database_env, monkeypatch, advance_fence, ): + from sqlalchemy.ext.asyncio import AsyncSession + from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from app.modules.checkers.selected_pre_submit_coordination import SelectedPreSubmitCoordinator + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.test_public_submission_intake import _client + + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitTerminalFacts + original_terminal_check = SelectedPreSubmitTerminalFacts.__post_init__ + + def diagnose_terminal_clock(terminal, source_contracts): + try: + return original_terminal_check(terminal, source_contracts) + except ValueError as exc: + exc.add_note(f"PRE clock values: queued={terminal.queued_at.isoformat()} " + f"started={terminal.started_at.isoformat()} completed={terminal.completed_at.isoformat()}") + raise + + monkeypatch.setattr(SelectedPreSubmitTerminalFacts, "__post_init__", diagnose_terminal_clock) async with remediation_source(tmp_path, isolated_database_env) as h: source_id = await _fixture_revision_context(h) - admission_id = await _verified_admission( - h.factory, - h.store, - h.namespace, - h.settings, - h.actor_context, - _replacement_request( - h, - revision_archive(h.data), - predecessor_id=h.created.submission_id, - idempotency_key=new_record_id(), - ), - ) - positive = await _queued_selected_body(h, admission_id) - assert positive["request_json"]["admission_lineage"][ - "checker_remediation_manifest_id" - ] == str(source_id) - await _insert_selected_reservation(h, positive) - rejected = await _queued_selected_body(h, admission_id) - await reserve(h, await next_request(h)) + data, frozen, sql_errors, opened = revision_archive(h.data), [], [], [] before = await _snapshot(h) + original_context = ForegroundIntakeAdmission._validate_context + original_scope = SelectedPreSubmitCoordinator._lock_source + original_flush = AsyncSession.flush + + async def stale_context(owner, *args): + if advance_fence and frozen: + return frozen[0] + value = await original_context(owner, *args) + frozen.append(value) + assert value[0].checker_remediation_manifest_id == source_id + return value + + async def stale_selected_scope(owner, facts): + if advance_fence: + assert facts.admission_lineage.checker_remediation_manifest_id == source_id + return + await original_scope(owner, facts) + + async def observed_flush(session, *args, **kwargs): + try: + return await original_flush(session, *args, **kwargs) + except IntegrityError as exc: + sql_errors.append((exc.orig.sqlstate, str(exc.orig))) + raise + + async def body(): + opened.append(True) + if advance_fence: + await reserve(h, await next_request(h)) + async with h.factory.begin() as session: + with pytest.raises(TaskSubmissionContextUnavailable): + await task_submission_context_port(session).lock_submission_context(_context_request(h)) + yield data + + async with _client(h, monkeypatch, isolated_database_env) as client: + _, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) + headers = _revision_upload_headers(h) | {"Content-Length": str(len(data))} + monkeypatch.setattr(ForegroundIntakeAdmission, "_validate_context", stale_context) + monkeypatch.setattr(SelectedPreSubmitCoordinator, "_lock_source", stale_selected_scope) + monkeypatch.setattr(AsyncSession, "flush", observed_flush) + response = await client.post(f"/api/v1/tasks/{h.request.task_id}/submissions", + headers=headers, content=body()) + assert opened == [True] and frozen + assert not errors, errors async with h.factory() as session: - current = await session.scalar( - text( - "SELECT current_run_id FROM public.checker_submission_fences WHERE submission_id=:id" - ), - {"id": h.created.submission_id}, - ) - routed = await session.scalar( - text( - "SELECT checker_run_id FROM public.task_post_submit_routing_manifests WHERE id=:id" - ), - {"id": source_id}, - ) - assert current != routed - with pytest.raises( - IntegrityError, match="selected PRE reservation routed cause is not current" - ) as denied: - await _insert_selected_reservation(h, rejected) - assert denied.value.orig.sqlstate == "23514" - assert await _snapshot(h) == before - async with h.factory() as session: - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert admission.status == "ready" - assert admission.checker_remediation_manifest_id == source_id - assert await session.scalar(text("SELECT count(*) FROM public.submissions")) == 1 + operation = (await session.scalars(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.idempotency_key == headers["Idempotency-Key"]))).one() + charge = await session.get(SubmissionSourceCharge, operation.id) + assert charge.state == "sealed" and charge.accounted_bytes == len(data) + assert operation.finalized_submission_id is None + assert await session.scalar(text("SELECT count(*) FROM submissions")) == 1 await no_economic_effects(session) + if advance_fence: + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "submission_infrastructure_unavailable" + assert len(sql_errors) == 1 and sql_errors[0][0] == "23514" + assert "selected PRE reservation routed cause is not current" in sql_errors[0][1] + assert calls == [] and await _snapshot(h) == before + assert operation.state == "failed" and operation.acceptance_receipt is None + assert operation.finalization_event_id is None + else: + assert response.status_code == 202, response.text + assert sql_errors == [] and len(calls) == 1 + assert operation.state == "finalization_pending" + selected = (await session.scalars(select(SelectedPreSubmitRun).where( + SelectedPreSubmitRun.source_operation_id == operation.id))).one() + assert selected.eligible and selected.request_json["admission_lineage"]["checker_remediation_manifest_id"] == str(source_id) async def _assert_foreign_verified_admission_rejected(local, foreign, admission_id, before): From 2bb68b49ee7ab016730e1d99212e9f8a3c0be285 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:46:54 +0100 Subject: [PATCH 271/513] Replace final legacy preparation fixture with source custody SQL proof --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 31 +++ .../tests/selected_predecessor_fixtures.py | 127 --------- .../tests/tasks/submission_lineage_support.py | 41 --- .../test_submission_predecessor_custody.py | 249 +++++++----------- 4 files changed, 127 insertions(+), 321 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3f15bc068..4aa82a980 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8848,3 +8848,34 @@ aggregate. The intermittent fixture timing cause remains unresolved; a100000 sample database-clock probe observed no backwards samples and does not establish that no clock adjustment occurred. Retain diagnostic notes for recurrence. Structure passed before exception-note-only addition; Ruff/diff checked final. + +QA/ARCH approved565704c3a within its split-run evidence limits. Final old SQL +fixture migration covers foreign cause at native PRE INSERT, immutable PRE +request, and foreign cause/run at native source-admission INSERT during real T5. +Allowed: predecessor custody test, exclusively unused predecessor/lineage fixture +helpers and this record. Use real local/foreign routed histories; mutate only new +INSERT values. Admission negative probes use transaction savepoints then valid +registration in the same T5 root; retained rows and triggers remain unchanged. +Assert exact SQLSTATE/messages, rollback counts, current source charge, one valid +consumed successor, unchanged foreign history and no economics. Medium workflow/ +authority-test risk; isolated PostgreSQL case, Ruff/structure plus QA/ARCH review. +Preserve historical verifier helper and any other shared consumers. No production +writer deletion until this final old fixture dependency is removed and reviewed. +The first new run correctly stopped at namespace validation: HTTP used parent +scratch/root instead of the local fixture's exact root. Corrected that test setup. +The next run reached all SQL probes but T5 then refused PostgreSQL subtransaction +state from the probe savepoints. Keep the real T5 root free of savepoints: first +finalize normally, then probe invalid admission INSERT copies in independent +rolled-back transactions using the actual current source-bound admission. This +preserves exact foreign provenance/lineage guard proof without weakening root +transaction enforcement. No production change or retained-row mutation. + +Final foreign-cause case passed in54.97s with full schema0090 database/MinIO +cleanup (/tmp/submission-current-foreign-sql-roots-valid.json; launcher565704c3a +with final test/helper edits). It reaches exact foreign PRE23514, immutable +request55000, and both current source-admission23514 guards, plus valid T5 and +unchanged foreign history. Prior failed setup/savepoint runs remain recorded; +one launcher typo used a shortened MinIO host and was rejected before provisioning. +Structure, Ruff and diff passed. No testcaller of the obsolete preparation +factory/command remains. Historical _verify_put_attempt and its real retained +publisher tests remain; exclusively unused old preparation helpers were removed. diff --git a/backend/tests/selected_predecessor_fixtures.py b/backend/tests/selected_predecessor_fixtures.py index c6fd48d95..7bbfdce77 100644 --- a/backend/tests/selected_predecessor_fixtures.py +++ b/backend/tests/selected_predecessor_fixtures.py @@ -2,21 +2,14 @@ from app.adapters.artifacts import selected_pre_submit_source_contracts -from dataclasses import replace from io import BytesIO from uuid import UUID -import json from zipfile import ZipFile from sqlalchemy import select, text -from app.core.identifiers import new_record_id -from app.modules.artifacts.selected_pre_submit_admission import ( - selected_pre_submit_attempt_request_digest, -) from app.modules.checkers.models import SelectedPreSubmitRun from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitReservationFacts, SelectedPreSubmitTerminalFacts, ) @@ -102,123 +95,3 @@ def _secret_archive(data: bytes) -> bytes: with ZipFile(output, "a") as archive: archive.writestr("probe.txt", b"-----BEGIN OPENSSH PRIVATE KEY-----\nprobe\n") return output.getvalue() - - -async def _assert_default_failure(h, request, failure, before, code: str) -> None: - """Allow only the exact terminal selected run while ART remains untouched.""" - assert failure.facts.eligible is False - failed = tuple( - check for check in failure.facts.workstream_default.checks if check.status == "failed" - ) - assert tuple(check.failure_code for check in failed) == (code,) - assert failure.facts.external_members == () - after = dict(await _snapshot(h)) - expected = dict(before) - expected["selected_pre_submit_runs"] += 1 - assert after == expected - async with h.factory() as session: - run = ( - await session.scalars( - select(SelectedPreSubmitRun).where( - SelectedPreSubmitRun.actor_profile_id == str(request.actor.actor_profile_id), - SelectedPreSubmitRun.idempotency_key == str(request.idempotency_key), - ) - ) - ).one() - terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(run.terminal_json, source_contracts=selected_pre_submit_source_contracts()) - reservation = terminal.lease.reservation - assert run.status == terminal.outcome == "completed" - assert run.eligible is False and terminal.execution == failure.facts - assert terminal.terminal_digest == run.terminal_digest - assert reservation.request_digest == run.request_digest - assert reservation.task_id == request.task_id - assert reservation.assignment_id == request.assignment_id - assert reservation.actor_profile_id == request.actor.actor_profile_id - assert ( - reservation.admission_lineage.predecessor_submission_id - == request.predecessor_submission_id - ) - assert ( - await session.scalar( - text(""" - SELECT public.selected_pre_submit_receipt_valid(r,'execute',false) - AND public.selected_pre_submit_receipt_valid(r,'finalize',false) - FROM public.selected_pre_submit_runs r WHERE id=:id - """), - {"id": run.id}, - ) - is True - ) - - -async def _queued_selected_body(h, admission_id, *, cause=None) -> dict: - """Build a valid fresh reservation from one actual selected admission.""" - async with h.factory() as session: - body = await session.scalar( - text(""" - SELECT to_jsonb(r) FROM public.selected_pre_submit_runs r - JOIN public.submission_bundle_admissions a ON a.selected_pre_submit_run_id=r.id - WHERE a.id=:id - """), - {"id": admission_id}, - ) - assert body is not None and body["status"] == "completed" and body["eligible"] is True - facts = SelectedPreSubmitReservationFacts.from_canonical_body(body["request_json"], source_contracts=selected_pre_submit_source_contracts()) - lineage = facts.admission_lineage - assert lineage is not None - key = new_record_id() - facts = replace( - facts, - attempt_id=new_record_id(), - idempotency_key=key, - prepared_generation_id=new_record_id(), - admission_lineage=( - replace(lineage, checker_remediation_manifest_id=UUID(str(cause))) - if cause is not None - else lineage - ), - attempt_request_digest=selected_pre_submit_attempt_request_digest( - actor_profile_id=facts.actor_profile_id, - identity_link_id=facts.identity_link_id, - task_id=facts.task_id, - assignment_id=facts.assignment_id, - predecessor_submission_id=lineage.predecessor_submission_id, - idempotency_key=key, - archive_sha256=facts.archive_sha256, - archive_byte_count=facts.archive_byte_count, - packet_sha256=lineage.packet_sha256, - ), - ) - return body | { - "id": str(facts.attempt_id), - "idempotency_key": str(key), - "prepared_generation_id": str(facts.prepared_generation_id), - "request_json": facts.canonical_body(), - "request_digest": facts.request_digest, - "status": "queued", - "lease_id": None, - "lease_generation": 0, - "lease_expires_at": None, - "execute_evidence_id": None, - "finalize_evidence_id": None, - "terminal_json": None, - "terminal_digest": None, - "eligible": None, - "started_at": None, - "completed_at": None, - } - - -async def _insert_selected_reservation(h, body) -> None: - """Exercise installed native INSERT guards without disabling any custody.""" - async with h.factory.begin() as session: - await session.execute( - text(""" - INSERT INTO public.selected_pre_submit_runs - SELECT (pg_catalog.jsonb_populate_record( - NULL::public.selected_pre_submit_runs, CAST(:body AS jsonb) - || pg_catalog.jsonb_build_object('queued_at',clock_timestamp()) - )).* - """), - {"body": json.dumps(body)}, - ) diff --git a/backend/tests/tasks/submission_lineage_support.py b/backend/tests/tasks/submission_lineage_support.py index 220bf35bb..c3aee6c49 100644 --- a/backend/tests/tasks/submission_lineage_support.py +++ b/backend/tests/tasks/submission_lineage_support.py @@ -1,22 +1,16 @@ """Shared real ART preparation and verifier fixture for TASK integration proofs.""" -from unittest.mock import patch -from tests.trusted_intake_fixtures import LocalIntakeAdapter -from types import SimpleNamespace from uuid import UUID from app.core.identifiers import new_record_id from sqlalchemy import select -from starlette.requests import Request -from app.adapters.artifacts import get_submission_bundle_preparation_command from app.adapters.tasks import task_submission_context_port from app.modules.actors.models import ActorIdentityLink, ActorProfile from app.modules.actors.api.service_identities import ServiceIdentity from app.modules.artifacts.authorization import ( PreparedArtifactInternalAuthority, - PreparedSubmissionBundlePreparationAuthorization, ) from app.modules.artifacts.models import ( ArtifactVerificationJob, @@ -58,41 +52,6 @@ async def _seed_services(factory): ) -async def _verified_admission(factory, store, namespace, settings, context, request): - """Run the real ART command and independent verifier, returning its ready admission.""" - put_attempt_id = await _prepare_put_attempt(factory, settings, context, request) - return await _verify_put_attempt( - factory, store, namespace, settings, put_attempt_id - ) - - -async def _prepare_put_attempt(factory, settings, context, request): - """Run ART authority/storage with explicit in-process intake; leave verification pending.""" - http = Request( - { - "type": "http", - "headers": [], - "app": SimpleNamespace(state=SimpleNamespace(settings=settings)), - } - ) - async with factory() as session: - put_authority = PreparedArtifactInternalAuthority( - session, - service_identity=ServiceIdentity.ARTIFACT_PUT_RESOLVER, - request_id=new_record_id(), - correlation_id=new_record_id(), - ) - with patch("app.adapters.artifacts.trusted_submission_intake", return_value=LocalIntakeAdapter()): - result = await get_submission_bundle_preparation_command( - http, - session, - put_authority, - PreparedSubmissionBundlePreparationAuthorization(session, context), - ).prepare(request) - assert result.put_attempt_id is not None - return result.put_attempt_id - - async def _verify_put_attempt(factory, store, namespace, settings, put_attempt_id): """Publish a prepared put through the real independent ART verifier.""" async with factory() as session: diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 0525fcbfd..3958cf5ed 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -21,14 +21,10 @@ from app.core.identifiers import new_record_id from app.core.hashing import canonical_json_hash from app.interfaces.artifacts import ArtifactStoreUnavailableError -from app.modules.artifacts.api import ( - SubmissionBundlePreparationRequest, -) from app.modules.checkers.models import CheckerRun, SelectedPreSubmitRun from app.modules.artifacts.models import ( SubmissionBundleAdmission, ) -from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.checkers.api.execution import CheckerExecutionUnavailable from app.modules.tasks.api.submission_context import ( TaskSubmissionContextRequest, @@ -37,7 +33,6 @@ from app.modules.tasks.models import SubmissionDispatch from app.adapters.tasks import task_submission_context_port from tests.auth_concurrency_support import wait_for_named_database_lock -from tests.artifact_store_helpers import artifact_byte_stream from tests.checkers.execution.support import live_executor, reserve from tests.post_submit_materialization_helpers import material_fixture from tests.tasks.post_submit_routing.remediation_support import ( @@ -45,9 +40,8 @@ remediation_source, ) from tests.tasks.post_submit_routing.support import next_request, revision_archive -from tests.tasks.submission_lineage_support import _verified_admission from tests.selected_predecessor_fixtures import ( - _snapshot, _secret_archive, _queued_selected_body, _insert_selected_reservation, + _snapshot, _secret_archive, ) @@ -64,33 +58,6 @@ async def traced(self, *args, _original=original, _operation=operation, **kwargs return calls - - -def _replacement_request(h, data: bytes, *, predecessor_id: UUID, idempotency_key: UUID): - return SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - h.actor_context.actor_profile_id, - h.actor_context.identity_link_id, - ActorKind.HUMAN, - ), - request_id=new_record_id(), - correlation_id=new_record_id(), - task_id=h.request.task_id, - assignment_id=h.request.assignment_id, - predecessor_submission_id=predecessor_id, - revision_preparation_id=(str(h.revision_preparation_id) - if getattr(h, "revision_preparation_id", None) else None), - revision_preparation_sha256=getattr(h, "revision_preparation_sha256", None), - idempotency_key=idempotency_key, - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, - media_type="application/zip", - byte_source=artifact_byte_stream(data), - ) - - - - async def _fixture_revision_context(h): """Commit the real routed checker failure before replacement intake.""" async with h.factory() as session, session.begin(): @@ -579,136 +546,112 @@ async def body(): assert selected.eligible and selected.request_json["admission_lineage"]["checker_remediation_manifest_id"] == str(source_id) -async def _assert_foreign_verified_admission_rejected(local, foreign, admission_id, before): - # Keep current preparation/cause binding intact, then substitute - # a real foreign verified PRE run to reach the original byte guard. - async with local.factory() as session: - foreign_run_id = await session.scalar(text(""" - SELECT a.selected_pre_submit_run_id - FROM public.submission_bundle_admissions a - JOIN public.submissions s ON s.submission_bundle_admission_id=a.id - WHERE s.id=:submission - """), {"submission": foreign.created.submission_id}) - assert foreign_run_id is not None - with pytest.raises( - IntegrityError, match="submission bundle admission verified lineage mismatch" - ) as verified_mismatch: - async with local.factory.begin() as session: - await session.execute(text(""" - INSERT INTO public.submission_bundle_admissions - SELECT (pg_catalog.jsonb_populate_record( - NULL::public.submission_bundle_admissions, to_jsonb(a) - || pg_catalog.jsonb_build_object( - 'id',CAST(:new_id AS uuid), - 'selected_pre_submit_run_id',CAST(:run AS uuid) - ) - )).* FROM public.submission_bundle_admissions a WHERE a.id=:id - """), {"new_id": new_record_id(), "run": foreign_run_id, "id": admission_id}) - assert verified_mismatch.value.orig.sqlstate == "23514" - assert await _snapshot(local) == before - - async def test_sql_selected_pre_reservation_and_admission_reject_foreign_routed_cause( - tmp_path, - isolated_database_env, + tmp_path, isolated_database_env, monkeypatch, ): + from sqlalchemy import event + from sqlalchemy.ext.asyncio import AsyncSession + from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge + from tests.retained_material_fixtures import finalize_retained_intake + from tests.tasks.submission_dispatch.test_revision_capacity import _revision_http_runtime, _revision_upload_headers + from tests.tasks.test_public_submission_intake import _client + async with remediation_source(tmp_path / "local", isolated_database_env) as local: - async with remediation_source( - tmp_path / "foreign", - isolated_database_env, - provision_services=False, - storage_settings=local.settings, - ) as foreign: + async with remediation_source(tmp_path / "foreign", isolated_database_env, + provision_services=False, storage_settings=local.settings) as foreign: local_source = await _fixture_revision_context(local) foreign_source = await _fixture_revision_context(foreign) - admission_id = await _verified_admission( - local.factory, - local.store, - local.namespace, - local.settings, - local.actor_context, - _replacement_request( - local, - revision_archive(local.data), - predecessor_id=local.created.submission_id, - idempotency_key=new_record_id(), - ), - ) - positive = await _queued_selected_body(local, admission_id) - assert positive["request_json"]["admission_lineage"][ - "checker_remediation_manifest_id" - ] == str(local_source) - await _insert_selected_reservation(local, positive) - rejected = await _queued_selected_body(local, admission_id, cause=foreign_source) + foreign_history = await _replacement_history(foreign, foreign_source, foreign.created.submission_id) + async with local.factory() as session: + foreign_run = await session.scalar(text( + "SELECT selected_pre_submit_run_id FROM submission_bundle_admissions WHERE consumed_by_submission_id=:id" + ), {"id": foreign.created.submission_id}) + assert foreign_run is not None and local_source != foreign_source + data, sql_errors = revision_archive(local.data), [] + original_flush = AsyncSession.flush + + async def observed_flush(session, *args, **kwargs): + try: + return await original_flush(session, *args, **kwargs) + except IntegrityError as exc: + sql_errors.append((exc.orig.sqlstate, str(exc.orig))) + raise + + def foreign_reservation(_mapper, _connection, row): + assert row.task_id == str(local.request.task_id) + body = row.request_json + assert body["admission_lineage"]["checker_remediation_manifest_id"] == str(local_source) + row.request_json = body | {"admission_lineage": body["admission_lineage"] | { + "checker_remediation_manifest_id": str(foreign_source)}} + row.request_digest = canonical_json_hash(row.request_json) + before = await _snapshot(local) - with pytest.raises( - IntegrityError, match="selected PRE reservation routed cause is foreign" - ) as denied: - await _insert_selected_reservation(local, rejected) - assert denied.value.orig.sqlstate == "23514" - assert await _snapshot(local) == before - with pytest.raises( - DBAPIError, match="selected PRE request custody is immutable" - ) as immutable: + async with _client(local, monkeypatch, isolated_database_env) as client: + settings, errors, calls = await _revision_http_runtime(local, client, tmp_path / "local", monkeypatch, data) + route = f"/api/v1/tasks/{local.request.task_id}/submissions" + refused_headers = _revision_upload_headers(local) + monkeypatch.setattr(AsyncSession, "flush", observed_flush) + event.listen(SelectedPreSubmitRun, "before_insert", foreign_reservation) + try: + refused = await client.post(route, headers=refused_headers, content=data) + finally: + event.remove(SelectedPreSubmitRun, "before_insert", foreign_reservation) + assert refused.status_code == 503, refused.text + assert refused.json()["error"]["code"] == "submission_infrastructure_unavailable" + assert len(sql_errors) == 1 and sql_errors[0][0] == "23514" + assert "selected PRE reservation routed cause is foreign" in sql_errors[0][1] + assert calls == [] and not errors and await _snapshot(local) == before + async with local.factory() as session: + refused_operation = (await session.scalars(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.idempotency_key == refused_headers["Idempotency-Key"]))).one() + charge = await session.get(SubmissionSourceCharge, refused_operation.id) + assert refused_operation.state == "failed" and refused_operation.acceptance_receipt is None + assert refused_operation.finalization_event_id is None + assert charge.state == "sealed" and charge.accounted_bytes == len(data) + accepted = await client.post(route, headers=_revision_upload_headers(local), content=data) + assert accepted.status_code == 202, accepted.text + assert len(calls) == 1 and not errors + operation_id = UUID(accepted.json()["operation_id"]) + async with local.factory() as session: + selected = (await session.scalars(select(SelectedPreSubmitRun).where( + SelectedPreSubmitRun.source_operation_id == str(operation_id)))).one() + substituted = selected.request_json | {"admission_lineage": selected.request_json["admission_lineage"] | { + "checker_remediation_manifest_id": str(foreign_source)}} + with pytest.raises(DBAPIError, match="selected PRE request custody is immutable") as immutable: async with local.factory.begin() as session: - await session.execute( - text(""" - UPDATE public.selected_pre_submit_runs - SET request_json=CAST(:request AS jsonb), request_digest=:digest WHERE id=:id - """), - { - "id": positive["id"], - "request": json.dumps( - positive["request_json"] - | { - "admission_lineage": rejected["request_json"][ - "admission_lineage" - ] - } - ), - "digest": canonical_json_hash( - positive["request_json"] - | { - "admission_lineage": rejected["request_json"][ - "admission_lineage" - ] - } - ), - }, - ) + await session.execute(text("UPDATE selected_pre_submit_runs SET request_json=CAST(:body AS jsonb), " + "request_digest=:digest WHERE id=:id"), {"id": selected.id, + "body": json.dumps(substituted), "digest": canonical_json_hash(substituted)}) assert immutable.value.orig.sqlstate == "55000" - assert await _snapshot(local) == before - with pytest.raises( - IntegrityError, match="revision admission context unavailable" - ) as mismatch: - async with local.factory.begin() as session: - await session.execute( - text(""" - INSERT INTO public.submission_bundle_admissions - SELECT (pg_catalog.jsonb_populate_record( - NULL::public.submission_bundle_admissions, to_jsonb(a) - || pg_catalog.jsonb_build_object( - 'id',CAST(:new_id AS uuid), - 'checker_remediation_manifest_id',CAST(:cause AS uuid) - ) - )).* FROM public.submission_bundle_admissions a WHERE a.id=:id - """), - {"new_id": new_record_id(), "cause": foreign_source, "id": admission_id}, - ) - assert mismatch.value.orig.sqlstate == "23514" - assert await _snapshot(local) == before - await _assert_foreign_verified_admission_rejected( - local, foreign, admission_id, before, - ) + + submission_id = await finalize_retained_intake(local.factory, SimpleNamespace( + operation_id=operation_id, store=local.store.wrapped, namespace=local.namespace, settings=settings)) async with local.factory() as session: - admission = await session.get(SubmissionBundleAdmission, str(admission_id)) - assert ( - admission.status == "ready" and admission.selected_pre_submit_run_id is not None - ) - assert admission.pre_submit_evidence_set_id is None + admission = (await session.scalars(select(SubmissionBundleAdmission).where( + SubmissionBundleAdmission.consumed_by_submission_id == submission_id))).one() + assert admission.status == "consumed" and admission.selected_pre_submit_run_id == selected.id assert admission.checker_remediation_manifest_id == local_source - assert await session.scalar(text("SELECT count(*) FROM public.submissions")) == 2 + assert admission.source_operation_id == str(operation_id) and admission.pre_submit_evidence_set_id is None + assert await session.scalar(text("SELECT count(*) FROM submissions")) == 3 await no_economic_effects(session) + before_invalid_insert = await _snapshot(local) + for field, replacement, message in ( + ("checker_remediation_manifest_id", foreign_source, "source admission locked lineage mismatch"), + ("selected_pre_submit_run_id", foreign_run, "source admission provenance mismatch"), + ): + with pytest.raises(IntegrityError, match=message) as denied: + async with local.factory.begin() as session: + await session.execute(text(""" + INSERT INTO submission_bundle_admissions + SELECT (jsonb_populate_record(NULL::submission_bundle_admissions, + to_jsonb(a) || jsonb_build_object('id',CAST(:new_id AS uuid), + CAST(:field AS text),CAST(:replacement AS uuid)))).* + FROM submission_bundle_admissions a WHERE a.id=:id + """), {"new_id": new_record_id(), "field": field, + "replacement": replacement, "id": admission.id}) + assert denied.value.orig.sqlstate == "23514" + assert await _snapshot(local) == before_invalid_insert + assert await _replacement_history(foreign, foreign_source, foreign.created.submission_id) == foreign_history @pytest.mark.parametrize("advance_fence", [False, True]) From f9db6febbcf28d14ad39ed4752c474e81d5c29b2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:46:44 +0100 Subject: [PATCH 272/513] Record repaired runner qualification --- .../changes/flow-self-service-signup.md | 13 +++ .../deploy/runner-qualification-20261124.md | 83 +++++++++++++++++-- 2 files changed, 89 insertions(+), 7 deletions(-) diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index 66df4b816..777ee4b41 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -452,3 +452,16 @@ worker receives the read-only app-local model callback socket. Foreground PRE uses `execute_pre`, whose contract prohibits model, trial and build grants; POST and setup/trial callback execution remains worker-owned. The profile contains no app-host native checker/socket readiness fallback. + +The repaired edge was installed on the dedicated runner without changing the +app host, network or IAM. Operator-only recovery first stopped both runner +units, preserved their exact bytes and modes, made runtime masks effective by +moving only the two verified local unit files outside systemd search paths, +and required inactive/masked state before touching the stale socket. Exact +private ownership, type, mode, link count, refusal, listener and process-owner +checks preceded removal of only that socket inode. The unchanged bounded +reconciler removed one controlled `.incoming-*` residue after normal startup +refused it. Byte-identical units were restored and remain loaded, enabled and +active; retained backup hashes match. Repaired POST and streamed-ZIP PRE both +completed with pinned Smol isolation, PRE cleanup was destroyed, and all +material, model-relay and Smol-lease roots were empty afterward. diff --git a/external_checkers/deploy/runner-qualification-20261124.md b/external_checkers/deploy/runner-qualification-20261124.md index 5345bdf0e..3e12ac3db 100644 --- a/external_checkers/deploy/runner-qualification-20261124.md +++ b/external_checkers/deploy/runner-qualification-20261124.md @@ -31,6 +31,10 @@ with source `sg-015b341d9f8d39117`. No public 9443 ingress is required. `sha256:b87e18c8713f2a80f03b0f358ef44338aaa5e851d5570573d31ee979b5cc6509` - installed service config: `sha256:c35de5c4f38db8c5b9d003e47d4bf9e4310f22549c6e8dde65bdd27d57ecf5a6` +- repaired authenticated edge from reviewed commit `a64729edc`: + `sha256:4c487d108b33f4a30bef220c95eb2b9d9483874e0a6e0ac9a5887fec1c68af6d` +- retained pre-repair rollback edge: + `/opt/workstream/bin/workstream-remote-node.rollback-20261124-7fb81d74` ## Live receipts @@ -57,22 +61,87 @@ After POST and PRE, the material workspace, model relay and Smol lease roots wer empty. Both `workstream-remote-node.service` and `workstream-checker.service` remained active with one task each. -The follow-up crash-recovery guard admits no new session when `workspaces` -contains residue. Reconciliation is a separate stopped-native operation: +The repaired edge was qualified again after the crash-recovery and +same-connection callback changes. The request-bound POST completed through the +pinned checker image with the expected deliberately-empty-material result: + +- request: `sha256:336944f608f0933300666e28e3087bf0b4b31d670ef07853f81cfd18ee97018f` +- outcome/verdict: `completed` / `failed` +- expected finding: `harnessy.proof.missing` +- isolation: `smolvm` / `smol-microvm` + +The repaired streamed-ZIP PRE also completed and destroyed its cleanup +obligation: + +- source: 261 bytes, + `sha256:0359882cbc4c194551d439d227e606f6c4d1783c5061e6474d3f8cee2f6654ea` +- request: `sha256:da14d383a6162a3019eb4af296453882e289535a3123f8a3207f133892a51a71` +- outcome/cleanup: `completed` / `destroyed` +- selected checker: `completed` / `failed`, expected + `harnessy.proof.missing` +- timings in milliseconds: admission 0, preparation 3377, execution 79922, + cleanup 123, total 83424 + +The final check found zero children in `materials/workspaces`, `model-relay` and +`smol-leases`. Both services were loaded, enabled and active. The restored unit +files matched their retained root-private backups exactly: + +- `workstream-remote-node.service`: + `sha256:6e0854001756bb359907479b5b33bd51554031de7f05209ee980c507299968d0` +- `workstream-checker.service`: + `sha256:6dc65ad632417984b1add1788b41553305f9cea879ed4c26bc29dc27e54eef8a` +- backups: `/etc/workstream/maintenance-backups/20261124-a64729edc/` + +## Stale-workspace maintenance qualification + +The crash-recovery guard admits no new session when `workspaces` contains +residue. Ordinary startup remains fail closed on any existing native socket; +connection refusal alone is not evidence that the native owner is stopped. +Reconciliation is an operator-only stopped-native procedure, not a product +startup fallback. + +The live maintenance qualification used this bounded sequence: + +1. Stop both runner units. Preserve the exact two local unit files, modes and + hashes under a unique root-private, same-filesystem backup directory. +2. Apply runtime masks. Because local unit files in `/etc/systemd/system` take + precedence over `/run` masks, atomically move only those two verified unit + files outside systemd search paths, reload, and require both effective + `LoadState=masked` and inactive state. +3. Require the exact private runtime parent (uid/gid 10001, mode 0700), exact + known checker socket (uid/gid 10001, mode 0600, one link, socket type), no + listener, no owning process and `ECONNREFUSED`. Only then unlink that one + verified inode. Do not infer this permission from `ECONNREFUSED` alone. +4. Run the unchanged bounded reconciler as uid 10001. Abort without deleting + anything on any identity, ownership, type, link-count, state or bound + mismatch. +5. Restore the byte-identical unit files and metadata, reload, remove the + runtime masks, and start the edge before the checker. Recheck hashes, loaded + state, enabled state and active state. Keep the backups. + +The observed stale checker socket was inode 303586 with uid/gid 10001, mode +0600, one link and no listener or owner. After its exact removal the clean +reconciler reported zero removals. A controlled +`.incoming-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa` directory containing one 4096-byte +regular file then proved that normal edge startup refused with `workspace root +requires reconciliation`. With both units stopped and effectively masked, the +reconciler removed exactly one owned residue; the workspace was empty before +the unit files were restored and the services restarted. + +The underlying bounded reconciliation command is: ```sh -sudo systemctl stop workstream-checker.service workstream-remote-node.service sudo -u '#10001' /usr/bin/python3 /opt/workstream/bin/workstream-remote-node \ --config /etc/workstream/remote-node.json --reconcile-stale-workspaces -sudo systemctl start workstream-remote-node.service workstream-checker.service ``` +It must only be invoked after the preceding stopped-and-masked ownership checks. The command refuses an existing native socket, a non-private or foreign-owned root, more than one residue, unknown names, links, special files, foreign-owned members, more than 14,000 members or more than 1 GiB plus the bounded control -envelope. It never deletes an active or uncertain grant. The focused restart -proof covers both `.incoming-*` and renamed `extract_*` residue, refusal while -the native socket exists, exact removal after confirmed stop, and clean restart. +envelope. It never deletes an active or uncertain grant. Focused tests cover +both `.incoming-*` and renamed `extract_*` residue, refusal while the native +socket exists, exact removal after confirmed stop, and clean restart. ## Evidence and secret locations From a65b5b1ce1a578c393bf6316c41dbe0ad86767fc Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:51:36 +0100 Subject: [PATCH 273/513] Remove unused preparation command and durable handoff factory --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 32 + backend/app/adapters/artifacts/__init__.py | 149 +--- .../modules/artifacts/submission_admission.py | 701 +----------------- .../external/test_selected_pre_submit.py | 28 +- 4 files changed, 54 insertions(+), 856 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 4aa82a980..d2d8a87d7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8879,3 +8879,35 @@ one launcher typo used a shortened MinIO host and was rejected before provisioni Structure, Ruff and diff passed. No testcaller of the obsolete preparation factory/command remains. Historical _verify_put_attempt and its real retained publisher tests remain; exclusively unused old preparation helpers were removed. + +QA/ARCH closed2bb68b49e PASS. Remove the uncalled high-level preparation writer +now: adapter get_submission_bundle_preparation_command; ART durable-put request/ +result/service, current_submission_bundle_admission_id, preparation runtime and +command. Allowed files: adapters/artifacts/__init__.py, submission_admission.py, +this record, and affected exact architecture inventory if required. Preserve +historical publisher/error byte-for-byte, packet validation still tested, and +shared ART producers/current foreground source execution. Medium architecture +risk; import app/outbox with explicit test broker, focused retained publisher +contracts, structure/import boundaries, Ruff/diff and ARCH/QA review. Remaining +old low-level ArtifactAdmissionService branch, authorization/request and old +materialization classes are the next coherent deletion, not declared retired yet. +No database migration, retained data deletion, app deployment or new fallback. +Focused publisher checks exposed pre-existing stale pure fixtures constructing +v1 fields through the live v2 type. Add test_selected_pre_submit.py to scope only +for retained publisher fixtures: decode the committed v1 completed capture with +the read-only historical decoder and use its actual terminal shape, preserving +publisher assertions and current live types. Old live materialization tests in +that module remain for the next deletion batch. App import also identified the +shared ArtifactInternalAuthority adapter export; retained it explicitly for +current project routes. No compatibility writer or historical fixture rewrite. + +High-level writer retirement verification: app/outbox imports pass with explicit +memory broker (imports only, not broker qualification);5 focused retained-publisher +cases pass9.57s after historical fixture repair; real retained publication-failure +rollback case passes82.65s, schema0090/fullcleanup +(/tmp/submission-writer-retirement-retained.json; launcherf9db6febb with final +production deletion). Publisher/error class ASTs are identical to baseline. +Structure and authorization boundaries, scoped Ruff/diff passed. Fresh origin/main +remainsd713594eb and has0 commits absent from this branch. Low-level old admission +branch/authorization/materialization remain explicitly pending; no complete +writer-retirement or full-suite qualification claim is made yet. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index 6396f09ab..d969a82b7 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -60,7 +60,6 @@ SetupModelOutputBindingPort, SetupModelUsageOwnerPort, ) -from app.modules.artifacts.api import SubmissionBundlePreparationCommand from app.modules.artifacts.api.task_import_source import TaskImportSourceCommandPort from app.modules.checkers.api.materialization import PostSubmissionMaterializationPort from app.modules.checkers.api.materialization import ( @@ -89,12 +88,7 @@ from app.modules.artifacts.api.submission_archive import ( SubmissionArchiveLimits, ) -from app.modules.artifacts.submission_authorization import ( - SubmissionBundlePreparationAuthorization, -) -from app.modules.artifacts.schemas import ( - ArtifactInternalAuthority, -) +from app.modules.artifacts.schemas import ArtifactInternalAuthority as ArtifactInternalAuthority from app.modules.artifacts.authorization import ( GuideArtifactPreparedAuthorization, PreparedArtifactInternalAuthority, @@ -430,147 +424,6 @@ def submission_admission_consumption_port( ) -def get_submission_bundle_preparation_command( - request: Request, - session: Annotated[AsyncSession, Depends(get_db_session)], - internal_authority: Annotated[ - ArtifactInternalAuthority, - Depends(get_artifact_internal_authority), - ], - authority: Annotated[ - SubmissionBundlePreparationAuthorization, - Depends(get_submission_bundle_preparation_authorization), - ], -) -> SubmissionBundlePreparationCommand: - """Compose the sole hidden contributor preparation path from closed ART ports.""" - from app.modules.artifacts.authorization import ( - PreparedPreSubmitMaterializationAuthorization, - ) - from app.modules.artifacts.service import ( - ArtifactAdmissionService, - ArtifactStorageOrchestrator, - artifact_storage_namespace_spec, - ) - from app.modules.artifacts.submission_admission import SubmissionBundleDurablePutService - from app.modules.artifacts.submission_materialization import ( - PreparedBundleMaterializationService, - ) - from app.modules.artifacts.submission_admission import ( - PreparedSubmissionBundlePreparationCommand, - SubmissionBundlePreparationRuntime, - ) - - settings = request.app.state.settings - request_id, correlation_id = (UUID(value) for value in request_ids(request)) - task_contexts = task_submission_context_port(session) - project_contexts = project_locked_policy_context_port(session) - - @asynccontextmanager - async def runtime(): - bootstrap = create_artifact_store_bootstrap(settings) - try: - manager = create_artifact_scratch_manager(settings) - except BaseException: - bootstrap.close() - raise - try: - materialization_authority = PreparedPreSubmitMaterializationAuthorization( - session, - request_id=request_id, - correlation_id=correlation_id, - ) - except BaseException: - manager.close() - bootstrap.close() - raise - try: - namespace = artifact_storage_namespace_spec(settings, bootstrap) - store = bootstrap.initialize_after_namespace_claim( - ArtifactStoreNamespaceClaim( - adapter_identity=bootstrap.identity, - namespace_identity=bootstrap.namespace_identity, - namespace_fingerprint=namespace.namespace_fingerprint, - ) - ) - preparation = ArtifactPreparationService(manager) - intake = trusted_submission_intake(settings) - archive_limits = submission_archive_limits(settings) - from app.adapters.auth import selected_pre_submit_authority - from app.adapters.checkers import selected_pre_submit_checker_execution - from app.modules.artifacts.selected_pre_submit_execution import ( - SelectedPreSubmitExecutionService, SelectedPreSubmitSourceReads, - ) - from app.adapters.checkers import selected_pre_submit_coordinator - - checker_execution = selected_pre_submit_checker_execution( - settings=settings, - ) - storage_schemes = {"local": "local", "s3_compatible": "s3"} - try: - storage_scheme = storage_schemes[settings.artifact_store_backend] - except KeyError as exc: - raise RuntimeError("unsupported artifact store backend") from exc - materialization = PreparedBundleMaterializationService( - session=session, - authorization=materialization_authority, - preparation=preparation, - checker_execution=checker_execution, - storage_scheme=storage_scheme, - archive_limits=archive_limits, - ) - admission = ArtifactAdmissionService(session, settings, namespace) - storage = ArtifactStorageOrchestrator( - session, - store, - namespace, - settings, - internal_authority, - ) - selected_coordinator = selected_pre_submit_coordinator(session) - - yield SubmissionBundlePreparationRuntime( - preparation=preparation, - intake=intake, - archive_limits=archive_limits, - materialization=materialization, - selected_coordinator=selected_coordinator, - selected_execution=SelectedPreSubmitExecutionService( - session=session, - coordinator=selected_coordinator, - authority=selected_pre_submit_authority(session), - source_reads=SelectedPreSubmitSourceReads( - session=session, sources=submission_intake_pre_source_port(session), - authority=materialization_authority, store=store, - ), - execution=checker_execution, - ), - storage_scheme=storage_scheme, - artifact_deadline_ms=int( - settings.artifact_preparation_total_deadline_seconds * 1000 - ), - durable_put=SubmissionBundleDurablePutService( - session=session, - admission=admission, - storage=storage, - authorization=authority, - task_contexts=task_contexts, - project_contexts=project_contexts, - ), - ) - finally: - materialization_authority.close() - manager.close() - bootstrap.close() - - return PreparedSubmissionBundlePreparationCommand( - session=session, - authority=authority, - task_contexts=task_contexts, - project_contexts=project_contexts, - runtime_factory=runtime, - ) - - async def cleanup_stale_artifact_scratch(settings: Settings) -> int: """Run one database-independent stale cleanup with shared construction.""" manager = create_artifact_scratch_manager(settings) diff --git a/backend/app/modules/artifacts/submission_admission.py b/backend/app/modules/artifacts/submission_admission.py index 2cf5960d9..dc80f8920 100644 --- a/backend/app/modules/artifacts/submission_admission.py +++ b/backend/app/modules/artifacts/submission_admission.py @@ -1,30 +1,18 @@ -"""Hidden evidence-bound durable put handoff for one checked submission ZIP.""" +"""Publish retained verified preparation evidence without a new preparation writer.""" from __future__ import annotations -from collections.abc import Callable -from contextlib import AbstractAsyncContextManager, AsyncExitStack -import asyncio -from dataclasses import dataclass, field, replace from uuid import UUID from app.core.hashing import canonical_json_hash -from app.interfaces.trusted_submission_intake import TrustedSubmissionIntakeAdapter -from workstream_external_services import ExternalServiceAdapterError from app.core.identifiers import new_record_id from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.modules.artifacts.api import ( - SubmissionBundlePreparationCheckFailed, SubmissionBundlePreparationRejected, - SubmissionBundlePreparationInfrastructureUnavailable, SubmissionBundlePreparationRequest, - SubmissionBundlePreparationResult, - SubmissionBundlePreparationStatus, - SubmissionBundlePreparationUnavailable, ) -from app.modules.artifacts.api.submission_preparation import public_pre_submission_results from app.modules.artifacts.models import ( ArtifactContent, ArtifactOperationReceipt, @@ -36,77 +24,14 @@ SubmissionBundleAdmission, SubmissionBundleDurableIntent, ) -from app.modules.artifacts.preparation import ArtifactPreparationService, ArtifactPreparationDeadlineError -from app.modules.artifacts.schemas import ( - ArtifactAdmissionResult, - ArtifactAuthorityDeniedError, - SubmissionBundleArtifactAdmissionRequest, -) -from app.modules.artifacts.submission_authorization import ( - SubmissionBundlePreparedAuthorization, -) -from app.modules.artifacts.service import ( - ArtifactAdmissionService, - ArtifactStorageOrchestrator, -) -from app.modules.artifacts.sources import PreparedArtifact -from app.modules.artifacts.trusted_intake import prepared_trusted_intake, TrustedArchiveInspector -from app.modules.artifacts.api.submission_archive import ( - MAXIMUM_SUBMISSION_ZIP_BYTES, - SubmissionArchiveRejectedError, - SubmissionArchiveLimits, -) -from app.modules.artifacts.submission_authorization import ( - SubmissionBundlePreparationAuthorization, -) -from app.modules.artifacts.submission_custody import SubmissionBundlePreparedCustody -from app.modules.artifacts.api.submission_manifest import ( - build_submission_manifest, -) -from app.modules.artifacts.submission_manifest import ( - SubmissionCanonicalPredecessor, -) -from app.modules.artifacts.submission_materialization import ( - PreparedBundleMaterializationRequest, - PreparedBundleMaterializationService, -) -from app.modules.artifacts.selected_pre_submit_admission import ( - bind_selected_pre_submit_admission, - build_selected_pre_submit_reservation, - selected_pre_submit_attempt_request_digest, -) -from app.modules.artifacts.selected_pre_submit_execution import ( - SelectedPreSubmitExecutionService, -) from app.modules.checkers.api.historical_selected_pre_submit import ( HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal, ) -from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitCompletion, - SelectedPreSubmitCoordinationPort, - SelectedPreSubmitCurrentFacts, - SelectedPreSubmitExecutionFacts, - SelectedPreSubmitRequestConflict, - SelectedPreSubmitUnavailable, -) -from app.modules.checkers.api.external_policy import ( - LockedExternalCheckerPolicies, - selected_pre_submit_execution_budget_ms, -) -from app.modules.checkers.api.pre_submit_material import SubmissionPacketView -from app.modules.projects.api import ( - ProjectLockedPolicyContextFacts, - ProjectLockedPolicyContextPort, - ProjectLockedPolicyContextRequest, - ProjectLockedPolicyContextUnavailable, -) -from app.modules.projects.api.policy_lineage import RevisionPolicySemantics -from app.modules.tasks.api.submission_context import require_revision_capacity, require_revision_acknowledgement +from app.modules.tasks.api.submission_context import require_revision_acknowledgement from app.modules.tasks.api import ( TaskRetainedSubmissionParentsRequest, TaskSubmissionContextFacts, TaskSubmissionContextPort, - TaskSubmissionContextRequest, TaskSubmissionContextUnavailable, ) @@ -133,164 +58,6 @@ def require_revision_preparation_acknowledgement( raise SubmissionBundlePreparationRejected(exc.code) from exc -@dataclass(frozen=True, slots=True) -class SubmissionBundleDurablePutRequest: - """Exact live custody and opaque authority for one final durable handoff.""" - - prepared_authorization: object - prepared_artifact: PreparedArtifact - replay_durable_intent_id: UUID | None = None - selected_completion: SelectedPreSubmitCompletion = field(kw_only=True) - - def __post_init__(self) -> None: - if type(self.selected_completion) is not SelectedPreSubmitCompletion: - raise ValueError("submission bundle durable PRE custody is invalid") - - -@dataclass(frozen=True, slots=True) -class SubmissionBundleDurablePutResult: - """Bounded durable operation result without provider coordinates.""" - - put_attempt_id: UUID - operation_identity: str - status: str - replayed: bool - admission_id: UUID | None - selected_pre_submit_run_id: UUID - - -class SubmissionBundleDurablePutService: - """Commit final authority and intent before invoking the generic provider path.""" - - def __init__( - self, - *, - session: AsyncSession, - admission: ArtifactAdmissionService, - storage: ArtifactStorageOrchestrator, - authorization: SubmissionBundlePreparedAuthorization, - task_contexts: TaskSubmissionContextPort, - project_contexts: ProjectLockedPolicyContextPort, - ) -> None: - self._session = session - self._admission = admission - self._storage = storage - self._authorization = authorization - self._task_contexts = task_contexts - self._project_contexts = project_contexts - - async def admit_in_transaction( - self, - request: SubmissionBundleDurablePutRequest, - ) -> tuple[PreparedArtifact, UUID, ArtifactAdmissionResult]: - """Persist intent after the preparation command locks its authorized context. - - The caller holds TASK, actor, PROJECT and grant locks in that order; - the admission reads below revalidate those already-locked owner facts. - """ - if type(request) is not SubmissionBundleDurablePutRequest: - raise TypeError("invalid submission bundle durable put request") - transaction = self._session.sync_session.get_transaction() - prepared = request.prepared_artifact - if ( - transaction is None - or not transaction.is_active - or self._session.in_nested_transaction() - or type(prepared) is not PreparedArtifact - or type(request.selected_completion) is not SelectedPreSubmitCompletion - ): - if type(prepared) is PreparedArtifact: - await prepared.close() - raise RuntimeError("submission bundle durable transaction is unavailable") - try: - custody = SubmissionBundlePreparedCustody._from_selected_pre_submit( - prepared=prepared, completion=request.selected_completion, - ) - selected_run_id = custody.selected_reservation.attempt_id - admission = await self._admission.admit( - SubmissionBundleArtifactAdmissionRequest( - pre_submit_evidence_set_id=None, - custody=custody, - replay_durable_intent_id=request.replay_durable_intent_id, - selected_pre_submit_run_id=selected_run_id, - selected_terminal_digest=( - custody.selected_terminal_digest - ), - ), - submission_prepared_authorization=self._authorization, - submission_task_contexts=self._task_contexts, - submission_project_contexts=self._project_contexts, - prepared_authorization=request.prepared_authorization, - existing_transaction=True, - ) - return prepared, selected_run_id, admission - except BaseException: - await prepared.close() - raise - - async def publish_after_commit( - self, - prepared: PreparedArtifact, - lineage_id: UUID, - admission: ArtifactAdmissionResult, - ) -> SubmissionBundleDurablePutResult: - """Hand the exact ZIP to storage only after the durable transaction ended.""" - if self._session.in_transaction(): - await prepared.close() - raise RuntimeError("submission bundle durable transaction is still active") - try: - admission_id = None - if admission.replayed: - async with self._session.begin(): - admission_id = await current_submission_bundle_admission_id( - self._session, - put_attempt_id=admission.attempt_id, - ) - if admission_id is not None: - return SubmissionBundleDurablePutResult( - put_attempt_id=admission.attempt_id, - operation_identity=admission.operation_identity, - status="ready", - replayed=True, - admission_id=admission_id, - selected_pre_submit_run_id=lineage_id, - ) - if admission.replayed and admission.status == "object_confirmed": - return SubmissionBundleDurablePutResult( - put_attempt_id=admission.attempt_id, - operation_identity=admission.operation_identity, - status="object_confirmed", - replayed=True, - admission_id=None, - selected_pre_submit_run_id=lineage_id, - ) - if admission.replayed: - status = await self._storage.resume_committed_put( - attempt_id=admission.attempt_id, - source=prepared.committed_source, - ) - else: - status = await self._storage.execute_committed_put( - attempt_id=admission.attempt_id, - source=prepared.committed_source, - ) - async with self._session.begin(): - admission_id = await current_submission_bundle_admission_id( - self._session, - put_attempt_id=admission.attempt_id, - ) - return SubmissionBundleDurablePutResult( - put_attempt_id=admission.attempt_id, - operation_identity=admission.operation_identity, - status=status, - replayed=admission.replayed, - admission_id=admission_id, - selected_pre_submit_run_id=lineage_id, - ) - finally: - await prepared.close() - - class SubmissionBundleAdmissionPublicationError(RuntimeError): """Durable verification lineage cannot publish a trusted ready admission.""" @@ -593,467 +360,3 @@ async def _write_receipt_ids( "put observation receipt lineage is invalid" ) return None, observation.id - - -async def current_submission_bundle_admission_id( - session: AsyncSession, *, put_attempt_id: UUID -) -> UUID | None: - """Return bounded current state for hidden exact request replay.""" - value = await session.scalar( - select(SubmissionBundleAdmission.id) - .join( - SubmissionBundleDurableIntent, - SubmissionBundleDurableIntent.id == SubmissionBundleAdmission.durable_intent_id, - ) - .where( - SubmissionBundleDurableIntent.put_attempt_id == str(put_attempt_id), - SubmissionBundleAdmission.status == "ready", - ) - ) - return UUID(value) if value is not None else None - - -@dataclass(frozen=True, slots=True) -class SubmissionBundlePreparationRuntime: - preparation: ArtifactPreparationService - intake: TrustedSubmissionIntakeAdapter - archive_limits: SubmissionArchiveLimits - materialization: PreparedBundleMaterializationService - durable_put: SubmissionBundleDurablePutService - selected_coordinator: SelectedPreSubmitCoordinationPort | None = None - selected_execution: SelectedPreSubmitExecutionService | None = None - storage_scheme: str | None = None - artifact_deadline_ms: int = 0 - - -class PreparedSubmissionBundlePreparationCommand: - """Keep every process-local capability within one hidden request.""" - - def __init__( - self, - *, - session: AsyncSession, - authority: SubmissionBundlePreparationAuthorization, - task_contexts: TaskSubmissionContextPort, - project_contexts: ProjectLockedPolicyContextPort, - runtime_factory: Callable[ - [], AbstractAsyncContextManager[SubmissionBundlePreparationRuntime] - ], - ) -> None: - self._session = session - self._authority = authority - self._task_contexts = task_contexts - self._project_contexts = project_contexts - self._runtime_factory = runtime_factory - - async def prepare( - self, request: SubmissionBundlePreparationRequest - ) -> SubmissionBundlePreparationResult: - if type(request) is not SubmissionBundlePreparationRequest: - raise TypeError("invalid submission bundle preparation request") - try: - await self._authority.preflight(request=request) - validate_submission_packet_headers( - request.summary, - request.contributor_attestation, - ) - if request.media_type.partition(";")[0].strip().lower() != "application/zip": - raise SubmissionBundlePreparationRejected("submission_bundle_media_type_invalid") - async with self._runtime_factory() as runtime, AsyncExitStack() as scratch_cleanup: - if ( - runtime.selected_coordinator is None - or runtime.selected_execution is None - or runtime.storage_scheme is None - ): - raise RuntimeError("selected PRE runtime is unavailable") - async with self._session.begin(): - task_context, project_context = await self._lock_authorized_context(request) - predecessor = await self._load_predecessor(task_context) - predecessor_rules_sha256 = await self._load_predecessor_rules(task_context) - remediation_manifest_id = task_context.checker_remediation_manifest_id - early_policy = LockedExternalCheckerPolicies.model_validate_json( - project_context.external_checker_policies.value - ).pre_submit - deadline = asyncio.get_running_loop().time() + runtime.artifact_deadline_ms / 1000 - try: - prepared, intake = await scratch_cleanup.enter_async_context(prepared_trusted_intake( - runtime.intake, - runtime.preparation.prepare( - request.byte_source, media_type="application/zip", - maximum_bytes=MAXIMUM_SUBMISSION_ZIP_BYTES, - ), - phase="pre_submit", policy_sha256=early_policy.policy_sha256, - limits=runtime.archive_limits, deadline=deadline, - )) - except SubmissionArchiveRejectedError as exc: - raise SubmissionBundlePreparationRejected(exc.code.value) from exc - async with self._session.begin(): - task_context, project_context = await self._lock_authorized_context(request) - if task_context.checker_remediation_manifest_id != remediation_manifest_id: - raise SubmissionBundlePreparationRejected( - "submission_bundle_preparation_context_changed" - ) - policies = LockedExternalCheckerPolicies.model_validate_json( - project_context.external_checker_policies.value - ) - if policies.pre_submit.policy_sha256 != early_policy.policy_sha256: - raise SubmissionBundlePreparationRejected("submission_bundle_preparation_context_changed") - materialization_handle = ( - await runtime.materialization.prepare_selected_authorization( - task=task_context, - project=project_context, - prepared_artifact=prepared, - external_policy=policies.pre_submit, - idempotency_key=request.idempotency_key, - ) - ) - try: - inspection = await prepared.inspect( - TrustedArchiveInspector(intake, prepared.commitment), on_cancel=intake.abort, - ) - except SubmissionArchiveRejectedError as exc: - raise SubmissionBundlePreparationRejected(exc.code.value) from exc - manifest = build_submission_manifest(inspection) - packet = SubmissionPacketView( - summary=request.summary, - contributor_attestation=request.contributor_attestation, - ) - selected = bind_selected_pre_submit_admission( - task=task_context, - project=project_context, - commitment=prepared.commitment, - manifest=manifest, - predecessor=predecessor, - predecessor_rules_sha256=predecessor_rules_sha256, - predecessor_exists=(request.predecessor_submission_id is not None), - packet=packet, - ) - attempt_id = new_record_id() - reservation = build_selected_pre_submit_reservation( - actor_profile_id=request.actor.actor_profile_id, - identity_link_id=request.actor.identity_link_id, - task=task_context, - project=project_context, - prepared_generation_id=prepared.generation_id, - attempt_id=attempt_id, - idempotency_key=request.idempotency_key, - attempt_request_digest=( - selected_pre_submit_attempt_request_digest( - actor_profile_id=request.actor.actor_profile_id, - identity_link_id=request.actor.identity_link_id, - task_id=request.task_id, - assignment_id=request.assignment_id, - predecessor_submission_id=(request.predecessor_submission_id), - idempotency_key=request.idempotency_key, - archive_sha256=prepared.commitment.sha256, - archive_byte_count=prepared.commitment.byte_count, - packet_sha256=packet.sha256, - revision_preparation_id=( - task_context.revision_context.preparation_id - if task_context.revision_context is not None else None - ), - revision_preparation_sha256=( - task_context.revision_context.preparation_sha256 - if task_context.revision_context is not None else None - ), - ) - ), - commitment=prepared.commitment, - manifest=manifest, - packet=packet, - selected=selected, - storage_scheme=runtime.storage_scheme, - execution_budget_ms=selected_pre_submit_execution_budget_ms( - selected.policy, - artifact_deadline_ms=runtime.artifact_deadline_ms, - ), - ) - materialization_request = PreparedBundleMaterializationRequest( - prepared_authorization=materialization_handle, - task_id=request.task_id, - assignment_id=request.assignment_id, - submission_artifact_policy_id=project_context.effective_policy_id, - checker_policy_id=project_context.pre_submit_policy_id, - predecessor_submission_version=( - task_context.predecessor.version - if task_context.predecessor is not None - else None - ), - checker_remediation_manifest_id=remediation_manifest_id, - prepared_artifact=prepared, - inspection=inspection, - manifest=manifest, - change_gate=selected.change_gate, - packet=packet, - external_policy=selected.policy, - default_checker_input=selected.default_input, - selected_reservation=reservation, - intake=intake, - ) - current = await runtime.selected_coordinator.read_current(reservation) - if current is None: - await runtime.materialization.authorize_inspected(materialization_request) - reserved_id = await runtime.selected_coordinator.reserve(reservation) - if reserved_id != reservation.attempt_id: - raise RuntimeError("selected PRE reservation identity changed") - if current is not None: - if current.status == "running": - try: - recovered = await runtime.selected_execution.recover_expired( - run_id=current.run_id, - reservation=current.reservation, - ) - except SelectedPreSubmitUnavailable: - pass - else: - current = SelectedPreSubmitCurrentFacts( - run_id=current.run_id, - reservation=current.reservation, - status="infrastructure_failed", - terminal=recovered.terminal, - ) - return await self._selected_replay_result(current) - completion = await runtime.selected_execution.execute( - reservation=reservation, - materialization=replace( - materialization_request, - prepared_authorization=None, - ), - ) - terminal = completion.terminal - if terminal.outcome == "infrastructure_failed": - raise SubmissionBundlePreparationInfrastructureUnavailable( - terminal.infrastructure_failure_code - or "pre_submission_checked_custody_unavailable" - ) - if terminal.execution is None: - raise SubmissionBundlePreparationInfrastructureUnavailable( - "pre_submission_checked_custody_unavailable" - ) - if not terminal.execution.eligible: - raise SubmissionBundlePreparationCheckFailed(terminal.execution) - if completion.capability is None: - raise SubmissionBundlePreparationInfrastructureUnavailable( - "pre_submission_checked_custody_unavailable" - ) - async with self._authority.transaction(): - await self._lock_authorized_context(request) - retained, _, durable = await runtime.durable_put.admit_in_transaction( - SubmissionBundleDurablePutRequest( - prepared_authorization=None, - prepared_artifact=prepared, - selected_completion=completion, - ) - ) - result = await runtime.durable_put.publish_after_commit( - retained, - reservation.attempt_id, - durable, - ) - return self._result(result, terminal.execution) - except ArtifactPreparationDeadlineError as exc: - # No terminal claim is made when intake cleanup was not confirmed. - # The existing lease recovery owner resolves an already reserved run. - raise SubmissionBundlePreparationInfrastructureUnavailable( - "pre_submission_attempt_outcome_unresolved" - ) from exc - except ExternalServiceAdapterError as exc: - raise SubmissionBundlePreparationInfrastructureUnavailable("implementation_unavailable") from exc - except SelectedPreSubmitRequestConflict as exc: - raise SubmissionBundlePreparationRejected( - "submission_bundle_preparation_request_conflict" - ) from exc - except ArtifactAuthorityDeniedError as exc: - raise SubmissionBundlePreparationUnavailable( - "submission bundle preparation is unavailable" - ) from exc - finally: - self._authority.close() - - async def _selected_replay_result( - self, current: SelectedPreSubmitCurrentFacts - ) -> SubmissionBundlePreparationResult: - """Replay exact work facts or an already durable pass without execution.""" - terminal = current.terminal - if current.status in {"queued", "running"} or terminal is None: - raise SubmissionBundlePreparationInfrastructureUnavailable( - "pre_submission_attempt_outcome_unresolved" - ) - if terminal.outcome == "infrastructure_failed": - raise SubmissionBundlePreparationInfrastructureUnavailable( - terminal.infrastructure_failure_code or "pre_submission_checked_custody_unavailable" - ) - execution = terminal.execution - if execution is None: - raise SubmissionBundlePreparationInfrastructureUnavailable( - "pre_submission_checked_custody_unavailable" - ) - if not execution.eligible: - raise SubmissionBundlePreparationCheckFailed(execution) - row = ( - await self._session.execute( - select( - SubmissionBundleDurableIntent, - ArtifactPutAttempt, - SubmissionBundleAdmission, - ) - .join( - ArtifactPutAttempt, - ArtifactPutAttempt.id == SubmissionBundleDurableIntent.put_attempt_id, - ) - .outerjoin( - SubmissionBundleAdmission, - SubmissionBundleAdmission.durable_intent_id == SubmissionBundleDurableIntent.id, - ) - .where( - SubmissionBundleDurableIntent.selected_pre_submit_run_id == str(current.run_id) - ) - ) - ).one_or_none() - if row is None: - raise SubmissionBundlePreparationInfrastructureUnavailable( - "pre_submission_checked_custody_unavailable" - ) - _, attempt, admission = row - status = attempt.status - admission_id = None - if admission is not None: - if admission.status == "ready": - status, admission_id = "ready", UUID(admission.id) - elif admission.status == "stale": - status = "stale" - else: - status = "conflict" - return SubmissionBundlePreparationResult( - put_attempt_id=UUID(attempt.id), - admission_id=admission_id, - submission_bundle_preparation_status=SubmissionBundlePreparationStatus(status), - replayed=True, - pre_submission_results=tuple(public_pre_submission_results(execution)), - ) - - async def _lock_authorized_context( - self, - request: SubmissionBundlePreparationRequest, - ) -> tuple[TaskSubmissionContextFacts, ProjectLockedPolicyContextFacts]: - """Lock TASK, actor identity, PROJECT, then the current submitter grant.""" - task, project = await self._lock_context(request) - await self._authority.revalidate( - request=request, - project_id=task.locked_project_context.project_id, - ) - try: - if task.predecessor is not None: - selected_revision = project.activation_receipt.command.revision - require_revision_capacity( - task, project_id=project.project_id, - policy_id=selected_revision.policy_id, - policy_generation=selected_revision.generation, - policy_hash=selected_revision.policy_hash, - max_revision_rounds=RevisionPolicySemantics.model_validate_json( - project.revision_policy.value, - ).max_revision_rounds, - ) - except TaskSubmissionContextUnavailable as exc: - raise SubmissionBundlePreparationRejected(exc.code) from exc - require_revision_preparation_acknowledgement(task, request) - return task, project - - async def _lock_context( - self, - request: SubmissionBundlePreparationRequest, - ) -> tuple[TaskSubmissionContextFacts, ProjectLockedPolicyContextFacts]: - """Lock actor identity between the exact TASK and PROJECT context phases.""" - try: - task_context = await self._task_contexts.lock_submission_context( - TaskSubmissionContextRequest( - task_id=request.task_id, - assignment_id=request.assignment_id, - contributor_id=request.actor.actor_profile_id, - predecessor_submission_id=request.predecessor_submission_id, - ) - ) - await self._authority.lock_actor(request=request) - references = task_context.locked_project_context - project_context = await self._project_contexts.lock_locked_policy_context( - ProjectLockedPolicyContextRequest( - project_id=references.project_id, - guide_version=references.guide_version, - source_snapshot_id=references.source_snapshot_id, - source_snapshot_hash=references.source_snapshot_hash, - effective_policy_id=references.effective_policy_id, - effective_policy_hash=references.effective_policy_hash, - pre_submit_policy_id=references.pre_submit_policy_id, - pre_submit_policy_bundle_hash=references.pre_submit_policy_bundle_hash, - ) - ) - except (TaskSubmissionContextUnavailable, ProjectLockedPolicyContextUnavailable) as exc: - raise SubmissionBundlePreparationRejected( - "submission_bundle_preparation_context_changed" - ) from exc - return task_context, project_context - - - async def _load_predecessor( - self, - task_context: TaskSubmissionContextFacts, - ) -> SubmissionCanonicalPredecessor | None: - predecessor = task_context.predecessor - if predecessor is None: - return None - admission = await self._session.scalar( - select(SubmissionBundleAdmission).where( - SubmissionBundleAdmission.consumed_by_submission_id - == str(predecessor.submission_id), - SubmissionBundleAdmission.status == "consumed", - ) - ) - if admission is None: - raise SubmissionBundlePreparationRejected( - "submission_canonical_predecessor_unavailable" - ) - return SubmissionCanonicalPredecessor( - submission_id=predecessor.submission_id, - submission_version=predecessor.version, - archive_sha256=admission.archive_sha256, - semantic_manifest_sha256=admission.semantic_manifest_sha256, - ) - - async def _load_predecessor_rules( - self, - task_context: TaskSubmissionContextFacts, - ) -> str | None: - """Require the predecessor's exact selected rules commitment.""" - predecessor = task_context.predecessor - if predecessor is None: - return None - admission = await self._session.scalar( - select(SubmissionBundleAdmission).where( - SubmissionBundleAdmission.consumed_by_submission_id - == str(predecessor.submission_id), - SubmissionBundleAdmission.status == "consumed", - ) - ) - if ( - admission is None - or admission.selected_pre_submit_run_id is None - or admission.pre_submit_evidence_set_id is not None - or admission.selected_rules_sha256 is None - ): - raise SubmissionBundlePreparationRejected( - "submission_canonical_predecessor_unavailable" - ) - return admission.selected_rules_sha256 - - @staticmethod - def _result( - result: SubmissionBundleDurablePutResult, - execution: SelectedPreSubmitExecutionFacts, - ) -> SubmissionBundlePreparationResult: - return SubmissionBundlePreparationResult( - put_attempt_id=result.put_attempt_id, - admission_id=result.admission_id, - submission_bundle_preparation_status=SubmissionBundlePreparationStatus(result.status), - replayed=result.replayed, - pre_submission_results=tuple(public_pre_submission_results(execution)), - ) diff --git a/backend/tests/checkers/external/test_selected_pre_submit.py b/backend/tests/checkers/external/test_selected_pre_submit.py index 02650f256..aa67fe4b8 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit.py +++ b/backend/tests/checkers/external/test_selected_pre_submit.py @@ -272,11 +272,21 @@ def test_revision_acknowledgement_requires_exact_current_preparation() -> None: ) +def _retained_admission_reservation(): + from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitReservation + from tests.checkers.external.test_selected_pre_submit_coordination import _retained_v1 + + selected = HistoricalSelectedPreSubmitReservation.from_canonical_body( + _retained_v1("selected_pre_v1_completed")["request"]) + lineage = selected.admission_lineage + return lineage.semantic_manifest_body, lineage.post_submit_policy_body, selected + + def _selected_admission_publisher_fixture(selected): - terminal = { - "request_digest": selected.request_digest, - "outcome": "completed", - "execution": {"eligible": True}, + from tests.checkers.external.test_selected_pre_submit_coordination import _retained_v1 + + terminal = _retained_v1("selected_pre_v1_completed")["terminal"] | { + "reservation": selected.canonical_body(), "request_digest": selected.request_digest, } attempt = SimpleNamespace( id=str(new_record_id()), @@ -781,7 +791,7 @@ async def test_selected_pre_only_requires_project_runtime_for_locked_external_im async def test_selected_pre_terminal_publishes_self_contained_ready_admission( replacement: bool, ) -> None: - manifest, post_policy, selected = _selected_admission_reservation() + manifest, post_policy, selected = _retained_admission_reservation() if replacement: selected = replace( selected, @@ -794,7 +804,7 @@ async def test_selected_pre_terminal_publishes_self_contained_ready_admission( ) lineage = selected.admission_lineage assert ( - SelectedPreSubmitAdmissionLineage.from_canonical_body(lineage.canonical_body()) == lineage + type(lineage).from_canonical_body(lineage.canonical_body()) == lineage ) session, job, verification, _ = _selected_admission_publisher_fixture(selected) task_contexts = SimpleNamespace(lock_retained_submission_parents=AsyncMock()) @@ -834,7 +844,7 @@ async def test_selected_pre_terminal_publishes_self_contained_ready_admission( @pytest.mark.asyncio async def test_selected_pre_publication_requires_exact_retained_task_identity() -> None: - _, _, selected = _selected_admission_reservation() + _, _, selected = _retained_admission_reservation() session, job, verification, intent = _selected_admission_publisher_fixture(selected) task_contexts = SimpleNamespace(lock_retained_submission_parents=AsyncMock()) publisher = SubmissionBundleAdmissionPublisher(session) @@ -863,7 +873,7 @@ async def test_selected_pre_publication_requires_exact_retained_task_identity() @pytest.mark.asyncio async def test_selected_pre_publication_requires_task_port_before_terminal_reads() -> None: - _, _, selected = _selected_admission_reservation() + _, _, selected = _retained_admission_reservation() session, job, _, _ = _selected_admission_publisher_fixture(selected) with pytest.raises(RuntimeError, match="TASK composition is unavailable"): @@ -880,7 +890,7 @@ async def test_selected_pre_publication_requires_task_port_before_terminal_reads @pytest.mark.asyncio async def test_selected_pre_task_lock_failure_propagates_before_terminal_reads() -> None: - _, _, selected = _selected_admission_reservation() + _, _, selected = _retained_admission_reservation() session, job, _, _ = _selected_admission_publisher_fixture(selected) task_contexts = SimpleNamespace( lock_retained_submission_parents=AsyncMock( From 8d8fe05a884d754373e448d657cbf14b2ec0fb48 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 13:56:33 +0100 Subject: [PATCH 274/513] Remove obsolete prepared submission artifact admission writer --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 30 ++ backend/app/modules/artifacts/schemas.py | 37 --- backend/app/modules/artifacts/service.py | 308 +----------------- .../modules/artifacts/submission_custody.py | 94 ------ .../test_selected_pre_submit_coordination.py | 24 -- backend/tests/test_artifact_architecture.py | 25 +- 6 files changed, 44 insertions(+), 474 deletions(-) delete mode 100644 backend/app/modules/artifacts/submission_custody.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d2d8a87d7..b7d684fe5 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8911,3 +8911,33 @@ Structure and authorization boundaries, scoped Ruff/diff passed. Fresh origin/ma remainsd713594eb and has0 commits absent from this branch. Low-level old admission branch/authorization/materialization remain explicitly pending; no complete writer-retirement or full-suite qualification claim is made yet. + +Next delete the now-uncalled low-level prepared-submission writer: the +SubmissionBundleArtifactAdmissionRequest schema/union arm, ArtifactAdmissionService +submission kwargs/branch/intent creation and three private submission-facts/replay +methods, and exclusive submission_custody.py. Allowed: service.py, schemas.py, +submission_custody.py, old DTO-only coordination test, exact architecture inventory, +and this record. Preserve verifier/publisher, ORM/history, shared guide/import/ +model/trial producers, current source intake and their authority guards. Remove +only the obsolete DTO-shape test; current source reservation/admission SQL proofs +replace its lineage invariant. Medium architecture/security risk; imports, +architecture/current source contract tests, shared artifact admission tests, +structure/auth boundaries and scoped ARCH/QA. No schema/data/deployment changes. +Architecture tests surfaced stale pre-cutover expectations already in the +current branch: preparation POST (now read-only), two rather than three ART +capability factories (cleanup is separate), and retired Unix transport names. +Update these exact inventories to current public raw-ZIP/read-only history and +remote-TLS constructors. Preserve aliased-constructor mutation controls and +closed composition-root counts; no relaxed wildcard or skipped assertion. + +Low-level writer deletion verification passed: shared committed put/independent +verification PostgreSQL case1/1 in32.01s, schema0090/fullcleanup +(/tmp/submission-lowlevel-retirement.json);53 architecture cases42.81s after +current inventory repair (/tmp/submission-retired-writer-architecture.log); +57 current source-first/historical decoder coordination cases13.03s +(/tmp/submission-retired-writer-coordination.log). App/outbox import, structure, +authorization boundaries and Ruff/diff passed. AST comparison confirms verifier/ +orchestrator and every surviving admission method except admit/request-boundary +are unchanged. Removed DTO/custody names are now forbidden by the existing retired +intake architecture check. Old authorization and materialization-only code still +needs cleanup; no full-suite/deployment completion claim. diff --git a/backend/app/modules/artifacts/schemas.py b/backend/app/modules/artifacts/schemas.py index 06fb2e46d..28efe29a3 100644 --- a/backend/app/modules/artifacts/schemas.py +++ b/backend/app/modules/artifacts/schemas.py @@ -52,47 +52,10 @@ class CheckerOutputArtifactAdmissionRequest: source: CommittedArtifactSource -@final -@dataclass(frozen=True, slots=True) -class SubmissionBundleArtifactAdmissionRequest: - """One passing prepared bundle selected for durable provider intent.""" - - pre_submit_evidence_set_id: UUID | None - custody: object - replay_durable_intent_id: UUID | None - selected_pre_submit_run_id: UUID | None = None - selected_terminal_digest: str | None = None - - def __post_init__(self) -> None: - if ( - self.pre_submit_evidence_set_id is not None - or self.selected_pre_submit_run_id is None - or self.selected_terminal_digest is None - or ( - self.selected_terminal_digest is not None - and ( - len(self.selected_terminal_digest) != 71 - or not self.selected_terminal_digest.startswith("sha256:") - ) - ) - ): - raise ValueError("submission bundle admission lineage is invalid") - - @property - def source(self) -> CommittedArtifactSource: - """Expose only the source sealed into process-local prepared custody.""" - from app.modules.artifacts.submission_custody import SubmissionBundlePreparedCustody - - if type(self.custody) is not SubmissionBundlePreparedCustody: - raise TypeError("submission bundle prepared custody is unavailable") - return self.custody.source - - ArtifactAdmissionRequest: TypeAlias = ( GuideArtifactAdmissionRequest | TaskImportSourceAdmissionRequest | CheckerOutputArtifactAdmissionRequest - | SubmissionBundleArtifactAdmissionRequest ) diff --git a/backend/app/modules/artifacts/service.py b/backend/app/modules/artifacts/service.py index 948d1f3a3..6759945f8 100644 --- a/backend/app/modules/artifacts/service.py +++ b/backend/app/modules/artifacts/service.py @@ -7,7 +7,7 @@ import sys from collections.abc import AsyncIterable, Awaitable, Callable from contextlib import AbstractAsyncContextManager, asynccontextmanager -from dataclasses import dataclass, replace +from dataclasses import dataclass from datetime import datetime, timedelta from uuid import UUID from app.core.identifiers import new_record_id @@ -34,12 +34,8 @@ artifact_store_namespace_material, ) from workstream_external_services import ExternalServiceAdapterIdentity -from app.modules.projects.api import ( - ProjectLockedPolicyContextPort, ProjectLockedPolicyContextRequest, - ProjectLockedPolicyContextUnavailable, -) from app.modules.tasks.api import ( - TaskSubmissionContextPort, TaskSubmissionContextRequest, TaskSubmissionContextUnavailable, + TaskSubmissionContextPort, ) from app.modules.projects.api.guide_documents import DOCUMENT_EXTENSIONS, GuideDocumentUploadTargetPort from app.modules.artifacts.guide_formats import BoundGuideFormatInspector, GuideFormatDetector, GuideFormatLimits @@ -64,7 +60,6 @@ ArtifactStorageNamespace, ArtifactVerificationJob, ArtifactVerificationReceipt, - SubmissionBundleDurableIntent, ) from app.modules.artifacts.metrics import ( ArtifactAdmissionMetrics, @@ -105,11 +100,6 @@ CheckerOutputArtifactAdmissionRequest, GuideArtifactAdmissionRequest, GuideArtifactIngestAuthorityFacts, - SubmissionBundleArtifactAdmissionRequest, - SubmissionBundleDurableIntentAuthorityFacts, -) -from app.modules.artifacts.submission_authorization import ( - SubmissionBundlePreparedAuthorization, ) from app.modules.artifacts.sources import CommittedArtifactSource, PreparedArtifact from app.modules.checkers.api.output_custody import ( @@ -2005,9 +1995,6 @@ async def admit( request: ArtifactAdmissionRequest, *, guide_prepared_authorization: GuideArtifactPreparedAuthorization | None = None, - submission_prepared_authorization: SubmissionBundlePreparedAuthorization | None = None, - submission_task_contexts: TaskSubmissionContextPort | None = None, - submission_project_contexts: ProjectLockedPolicyContextPort | None = None, checker_output_authority: CheckerOutputWriteAuthority | None = None, task_import_source_authority: TaskImportSourceAdmissionAuthority | None = None, prepared_authorization: PreparedAuthorizationHandle | None = None, @@ -2115,44 +2102,11 @@ async def admit( raise ArtifactAdmissionConflictError(str(exc)) from exc except ValueError as exc: raise ArtifactAdmissionRelationshipError(str(exc)) from exc - submission_facts: _AdmissionFacts | None = None - if type(request) is SubmissionBundleArtifactAdmissionRequest: - if ( - submission_prepared_authorization is None - or submission_task_contexts is None - or submission_project_contexts is None - or prepared_authorization is not None - ): - raise ArtifactAuthorityDeniedError( - "submission bundle durable preparation is unavailable" - ) - authority_facts, submission_facts = await self._submission_bundle_facts( - request, task_contexts=submission_task_contexts, - project_contexts=submission_project_contexts, - ) - replay_attempt = await self._submission_bundle_replay_attempt( - request, - authority_facts, - ) - if replay_attempt is not None: - authority_facts = replace( - authority_facts, - operation_identity=replay_attempt.operation_identity, - ) - prepared_authorization = await submission_prepared_authorization.prepare_final( - facts=authority_facts - ) - await submission_prepared_authorization.consume( - prepared_authorization=prepared_authorization, - facts=authority_facts, - ) - if replay_attempt is not None: - return await self._result(replay_attempt, replayed=True) namespace = await _claim_and_validate_storage_namespace( self._repo, self._namespace, ) - facts = import_facts or submission_facts or await self._derive_admission_facts(request) + facts = import_facts or await self._derive_admission_facts(request) scopes = self._derive_scopes(facts) request_digest = canonical_json_hash( { @@ -2218,14 +2172,6 @@ async def admit( counter.scope_type, counter.counted_bytes, counter.limit_bytes ) if replay is not None: - if facts.selected_pre_submit_run_id is not None: - intent = await self._repo.get_submission_bundle_intent_by_selected_run( - facts.selected_pre_submit_run_id - ) - if intent is None or intent.put_attempt_id != replay.id: - raise ArtifactAdmissionConfigurationError( - "submission bundle replay intent is incomplete" - ) linked_charge_ids = await self._repo.list_put_attempt_charge_ids(replay.id) reserved_charge_ids = tuple(sorted(charge.id for charge in charges)) if linked_charge_ids != reserved_charge_ids: @@ -2274,44 +2220,6 @@ async def admit( terminal_at=None, ) await self._repo.add_put_attempt(attempt, charges) - if facts.selected_pre_submit_run_id is not None: - selected_request = ( - request.custody.selected_reservation - if type(request) is SubmissionBundleArtifactAdmissionRequest - else None - ) - await self._repo.add_submission_bundle_intent( - SubmissionBundleDurableIntent( - id=str(new_record_id()), - pre_submit_evidence_set_id=facts.pre_submit_evidence_set_id, - selected_pre_submit_run_id=facts.selected_pre_submit_run_id, - selected_request_json=( - selected_request.canonical_body() - if selected_request is not None - else None - ), - selected_request_digest=( - selected_request.request_digest - if selected_request is not None - else None - ), - selected_terminal_json=( - request.custody.selected_terminal_body - if selected_request is not None - and type(request) - is SubmissionBundleArtifactAdmissionRequest - else None - ), - selected_terminal_digest=( - request.custody.selected_terminal_digest - if selected_request is not None - and type(request) - is SubmissionBundleArtifactAdmissionRequest - else None - ), - put_attempt_id=attempt.id, - ) - ) return await self._result(attempt, replayed=False) @staticmethod @@ -2320,7 +2228,6 @@ def _validate_request_boundary(request: ArtifactAdmissionRequest) -> None: if type(request) not in { GuideArtifactAdmissionRequest, CheckerOutputArtifactAdmissionRequest, - SubmissionBundleArtifactAdmissionRequest, TaskImportSourceAdmissionRequest, }: raise TypeError("invalid artifact admission request") @@ -2349,8 +2256,6 @@ def _validate_request_boundary(request: ArtifactAdmissionRequest) -> None: ): raise TypeError("guide artifact lineage claims are incomplete") return - if type(request) is SubmissionBundleArtifactAdmissionRequest: - return return async def _derive_admission_facts(self, request: ArtifactAdmissionRequest) -> _AdmissionFacts: @@ -2446,213 +2351,6 @@ async def _checker_output_facts( operation_identity=operation_identity, ) - async def _submission_bundle_replay_attempt( - self, - request: SubmissionBundleArtifactAdmissionRequest, - current: SubmissionBundleDurableIntentAuthorityFacts, - ) -> ArtifactPutAttempt | None: - """Reuse one committed intent when fresh checked custody exactly matches it.""" - if request.replay_durable_intent_id is None: - return None - intent = await self._repo.lock_submission_bundle_intent( - str(request.replay_durable_intent_id) - ) - if intent is None: - raise ArtifactAdmissionRelationshipError( - "submission bundle replay intent is unavailable" - ) - reservation = request.custody.selected_reservation - attempt = await self._repo.lock_put_attempt(intent.put_attempt_id) - if ( - attempt is None - or intent.selected_pre_submit_run_id != str(reservation.attempt_id) - or intent.pre_submit_evidence_set_id is not None - or intent.selected_request_json != reservation.canonical_body() - or intent.selected_request_digest != reservation.request_digest - or intent.selected_terminal_json - != request.custody.selected_terminal_body - or intent.selected_terminal_digest - != request.custody.selected_terminal_digest - or attempt.producer_request_type != "submission_bundle" - or attempt.status - not in { - "prepared", - "acknowledgement_unknown", - "absent_replay_required", - "object_confirmed", - } - or attempt.sha256 != current.archive_sha256 - or attempt.byte_count != current.archive_byte_count - or attempt.media_type != current.media_type - ): - raise ArtifactAdmissionRelationshipError( - "selected submission bundle replay intent does not match custody" - ) - return attempt - - async def _submission_bundle_facts( - self, request: SubmissionBundleArtifactAdmissionRequest, *, - task_contexts: TaskSubmissionContextPort, - project_contexts: ProjectLockedPolicyContextPort, - ) -> tuple[SubmissionBundleDurableIntentAuthorityFacts, _AdmissionFacts]: - """Revalidate the sole external PRE custody under current owner locks.""" - from app.modules.artifacts.submission_custody import SubmissionBundlePreparedCustody - - if type(request.custody) is not SubmissionBundlePreparedCustody: - raise ArtifactAuthorityDeniedError("submission bundle prepared custody is unavailable") - return await self._selected_submission_bundle_facts( - request, task_contexts=task_contexts, project_contexts=project_contexts, - ) - - async def _selected_submission_bundle_facts( - self, - request: SubmissionBundleArtifactAdmissionRequest, - *, - task_contexts: TaskSubmissionContextPort, - project_contexts: ProjectLockedPolicyContextPort, - ) -> tuple[SubmissionBundleDurableIntentAuthorityFacts, _AdmissionFacts]: - """Revalidate selected terminal custody against current TASK and PROJECT locks.""" - reservation = request.custody.selected_reservation - lineage = reservation.admission_lineage - commitment = request.source.commitment - if ( - lineage is None - or request.pre_submit_evidence_set_id is not None - or request.selected_pre_submit_run_id != reservation.attempt_id - or request.selected_terminal_digest - != request.custody.selected_terminal_digest - or reservation.prepared_generation_id - != request.custody.prepared_generation_id - or reservation.archive_sha256 != commitment.sha256 - or reservation.archive_byte_count != commitment.byte_count - or commitment.media_type != "application/zip" - or canonical_json_hash(lineage.semantic_manifest_body) - != reservation.semantic_manifest_sha256 - ): - raise ArtifactAdmissionRelationshipError( - "selected submission bundle passing evidence is unavailable" - ) - try: - task = await task_contexts.lock_submission_context( - TaskSubmissionContextRequest( - task_id=reservation.task_id, - assignment_id=reservation.assignment_id, - contributor_id=reservation.actor_profile_id, - predecessor_submission_id=lineage.predecessor_submission_id, - ) - ) - locked = await project_contexts.lock_locked_policy_context( - ProjectLockedPolicyContextRequest( - project_id=reservation.project_id, - guide_version=lineage.guide_version, - source_snapshot_id=lineage.source_snapshot_id, - source_snapshot_hash=lineage.source_snapshot_sha256, - effective_policy_id=lineage.effective_policy_id, - effective_policy_hash=lineage.effective_policy_sha256, - pre_submit_policy_id=lineage.pre_submit_policy_id, - pre_submit_policy_bundle_hash=lineage.pre_submit_policy_sha256, - ) - ) - except (TaskSubmissionContextUnavailable, ProjectLockedPolicyContextUnavailable) as exc: - raise ArtifactAdmissionRelationshipError( - "selected_pre_submit_locked_context_changed" - ) from exc - predecessor = task.predecessor - revision = task.revision_context - if ( - task.contributor_id != reservation.actor_profile_id - or task.task_id != reservation.task_id - or task.assignment_id != reservation.assignment_id - or (predecessor.submission_id if predecessor is not None else None) - != lineage.predecessor_submission_id - or (predecessor.version if predecessor is not None else None) - != lineage.predecessor_submission_version - or task.checker_remediation_manifest_id - != lineage.checker_remediation_manifest_id - or (predecessor is not None and ( - revision is None or revision.disposition != "ready" - or revision.source_submission_id != predecessor.submission_id - or revision.source_routing_manifest_id != task.checker_remediation_manifest_id - )) - or lineage.revision_preparation_id != ( - revision.preparation_id if revision is not None else None - ) - or lineage.revision_preparation_sha256 != ( - revision.preparation_sha256 if revision is not None else None - ) - or locked.project_id != reservation.project_id - or locked.guide_id != lineage.guide_id - or locked.guide_version != lineage.guide_version - or locked.source_snapshot_id != lineage.source_snapshot_id - or locked.source_snapshot_hash != lineage.source_snapshot_sha256 - or locked.effective_policy_id != lineage.effective_policy_id - or locked.effective_policy_hash != lineage.effective_policy_sha256 - or locked.pre_submit_policy_id != lineage.pre_submit_policy_id - or locked.pre_submit_policy_bundle_hash - != lineage.pre_submit_policy_sha256 - or reservation.policy_sha256 != lineage.effective_plan_sha256 - ): - raise ArtifactAdmissionRelationshipError( - "selected submission bundle locked context changed" - ) - operation_identity = canonical_json_hash( - { - "request_type": "submission_bundle", - "selected_pre_submit_run_id": str(reservation.attempt_id), - } - ) - authority_facts = SubmissionBundleDurableIntentAuthorityFacts( - actor_profile_id=reservation.actor_profile_id, - identity_link_id=reservation.identity_link_id, - project_id=reservation.project_id, - task_id=reservation.task_id, - assignment_id=reservation.assignment_id, - predecessor_submission_id=lineage.predecessor_submission_id, - predecessor_submission_version=lineage.predecessor_submission_version, - checker_remediation_manifest_id=lineage.checker_remediation_manifest_id, - pre_submit_evidence_set_id=None, - prepared_generation_id=reservation.prepared_generation_id, - guide_id=lineage.guide_id, - guide_version=lineage.guide_version, - source_snapshot_id=lineage.source_snapshot_id, - source_snapshot_sha256=lineage.source_snapshot_sha256, - effective_policy_id=lineage.effective_policy_id, - effective_policy_sha256=lineage.effective_policy_sha256, - pre_submit_policy_id=lineage.pre_submit_policy_id, - pre_submit_policy_sha256=lineage.pre_submit_policy_sha256, - effective_plan_sha256=lineage.effective_plan_sha256, - semantic_manifest_id=lineage.semantic_manifest_id, - semantic_manifest_sha256=reservation.semantic_manifest_sha256, - semantic_manifest_body=lineage.semantic_manifest_body, - packet_sha256=lineage.packet_sha256, - archive_sha256=reservation.archive_sha256, - archive_byte_count=reservation.archive_byte_count, - media_type=commitment.media_type, - storage_scheme=lineage.storage_scheme, - operation_identity=operation_identity, - replay_durable_intent_id=request.replay_durable_intent_id, - selected_pre_submit_run_id=reservation.attempt_id, - selected_terminal_digest=request.custody.selected_terminal_digest, - ) - return authority_facts, _AdmissionFacts( - request_type="submission_bundle", - producer_type="actor_profile", - producer_ref=str(reservation.actor_profile_id), - project_id=str(reservation.project_id), - guide_id=str(lineage.guide_id), - task_id=str(reservation.task_id), - guide_source_item_id=None, - guide_source_snapshot_id=str(lineage.source_snapshot_id), - checker_run_id=None, - logical_role=None, - submission_id=None, - submission_version=None, - checker_request_digest=None, - checker_request_digest_facts=None, - pre_submit_evidence_set_id=None, - operation_identity=operation_identity, - selected_pre_submit_run_id=str(reservation.attempt_id), - ) async def _require_active_human_actor(self, context: AuthorizationContext) -> None: """Revalidate and lock exact human identity state inside admission.""" diff --git a/backend/app/modules/artifacts/submission_custody.py b/backend/app/modules/artifacts/submission_custody.py deleted file mode 100644 index 2efc8f28c..000000000 --- a/backend/app/modules/artifacts/submission_custody.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Sealed process-local custody for one checked submission continuation.""" - -from __future__ import annotations - -from typing import final -from uuid import UUID - -from app.modules.artifacts.sources import CommittedArtifactSource, PreparedArtifact -from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitCompletion, - SelectedPreSubmitReservationFacts, -) - - -@final -class SubmissionBundlePreparedCustody: - """Unforgeable join of live prepared bytes and their fresh pass capability.""" - - __slots__ = ("_prepared", "_selected") - - def __init__(self, *_: object, **__: object) -> None: - raise TypeError("submission bundle custody requires live prepared work") - - - @classmethod - def _from_selected_pre_submit( - cls, - *, - prepared: PreparedArtifact, - completion: SelectedPreSubmitCompletion, - ) -> SubmissionBundlePreparedCustody: - """Seal a completed selected run to the still-live verified bytes once.""" - if ( - type(prepared) is not PreparedArtifact - or type(completion) is not SelectedPreSubmitCompletion - or completion.capability is None - or completion.terminal.outcome != "completed" - or completion.terminal.execution is None - or not completion.terminal.execution.eligible - ): - raise TypeError("submission bundle selected custody requires a passing run") - reservation = completion.terminal.lease.reservation - if ( - type(reservation) is not SelectedPreSubmitReservationFacts - or reservation.admission_lineage is None - or reservation.prepared_generation_id != prepared.generation_id - or reservation.archive_sha256 != prepared.commitment.sha256 - or reservation.archive_byte_count != prepared.commitment.byte_count - ): - raise TypeError("submission bundle selected custody differs from prepared bytes") - run_id = completion.capability.consume( - run_id=reservation.attempt_id, - terminal_digest=completion.terminal.terminal_digest, - attempt_id=reservation.attempt_id, - prepared_generation_id=reservation.prepared_generation_id, - archive_sha256=reservation.archive_sha256, - semantic_manifest_sha256=reservation.semantic_manifest_sha256, - ) - if run_id != reservation.attempt_id: - raise TypeError("submission bundle selected custody is unavailable") - custody = object.__new__(cls) - custody._prepared = prepared - custody._selected = completion.terminal - return custody - - @property - def prepared_generation_id(self) -> UUID: - return self._prepared.generation_id - - - @property - def selected_reservation(self) -> SelectedPreSubmitReservationFacts: - """Return the exact selected request only for selected-run custody.""" - if self._selected is None: - raise TypeError("selected submission custody is unavailable") - return self._selected.lease.reservation - - @property - def selected_terminal_digest(self) -> str: - """Return the terminal digest paired with the selected reservation.""" - if self._selected is None: - raise TypeError("selected submission custody is unavailable") - return self._selected.terminal_digest - - @property - def selected_terminal_body(self) -> dict[str, object]: - """Return a fresh canonical terminal body for the durable ART snapshot.""" - if self._selected is None: - raise TypeError("selected submission custody is unavailable") - return self._selected.canonical_body() - - @property - def source(self) -> CommittedArtifactSource: - return self._prepared.committed_source diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py index a8fccc14c..cce0c7e00 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py +++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py @@ -21,7 +21,6 @@ from app.core.identifiers import new_record_id from app.core.hashing import canonical_json_hash -from app.modules.artifacts.schemas import SubmissionBundleArtifactAdmissionRequest from app.modules.artifacts.submission_bindings import SubmissionAdmissionConsumptionService from app.modules.artifacts.models import ( SubmissionBundleAdmission, @@ -415,28 +414,6 @@ def test_selected_pre_request_binds_complete_later_admission_lineage() -> None: body, source_contracts=selected_pre_submit_source_contracts()) -def test_submission_artifact_request_selects_exactly_one_pre_lineage() -> None: - selected_id = new_record_id() - request = SubmissionBundleArtifactAdmissionRequest( - pre_submit_evidence_set_id=None, - custody=object(), - replay_durable_intent_id=None, - selected_pre_submit_run_id=selected_id, - selected_terminal_digest=SHA, - ) - assert request.selected_pre_submit_run_id == selected_id - with pytest.raises(ValueError, match="lineage"): - SubmissionBundleArtifactAdmissionRequest( - pre_submit_evidence_set_id=new_record_id(), - custody=object(), - replay_durable_intent_id=None, - selected_pre_submit_run_id=selected_id, - selected_terminal_digest=SHA, - ) - with pytest.raises(ValueError, match="lineage"): - replace(request, selected_terminal_digest=None) - - def test_selected_ready_admission_binds_selected_run() -> None: run_id = new_record_id() admission = SimpleNamespace( @@ -493,7 +470,6 @@ def _retained_v1(name="selected_pre_v1"): return json.loads((Path(__file__).parent / "fixtures" / f"{name}.json").read_text()) - def _retained_row(retained): """Complete indexed columns beside one independently frozen v1 record.""" terminal = retained["terminal"] diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py index f50f0d346..ad0129b25 100644 --- a/backend/tests/test_artifact_architecture.py +++ b/backend/tests/test_artifact_architecture.py @@ -76,10 +76,11 @@ "ArtifactAdmissionResult", "CheckerOutputArtifactAdmissionRequest", "GuideArtifactAdmissionRequest", - "SubmissionBundleArtifactAdmissionRequest", } RETIRED_CONTRIBUTOR_INTAKE_NAMES = { + "SubmissionBundleArtifactAdmissionRequest", + "SubmissionBundlePreparedCustody", "ArtifactUploadItem", "ArtifactUploadSession", "ContributorArtifactAdmissionRequest", @@ -174,8 +175,7 @@ def test_only_canonical_admission_backed_contributor_intake_routes_are_composed( assert not {path for path in paths if any(fragment in path for fragment in forbidden_fragments)} preparation_path = "/api/v1/tasks/{task_id}/submission-bundle-preparations" project_preparations = "/api/v1/projects/{project_id}/submission-bundle-preparations" - # Contributors read their own preparations back and Project Managers list a - # project's; only the task POST prepares. + # Retained preparations remain read-only; new ZIP intake uses task submissions. assert {path for path in paths if "submission-bundle" in path} == { preparation_path, f"{preparation_path}/{{preparation_id}}", @@ -188,11 +188,8 @@ def test_only_canonical_admission_backed_contributor_intake_routes_are_composed( if "submission-bundle" in path for method in operations if method != "parameters" - } == {"post", "get"} - assert "post" not in paths[f"{preparation_path}/{{preparation_id}}"] - preparation = paths[preparation_path]["post"] - assert preparation["security"] - assert preparation["x-workstream-action-id"] == "artifact.submission_bundle.prepare" + } == {"get"} + assert paths[preparation_path]["get"]["security"] creation_path = "/api/v1/tasks/{task_id}/submissions" assert { @@ -378,8 +375,8 @@ def _assert_concrete_adapter_composition( in { "LocalStorageAdapter", "S3CompatibleArtifactStore", - "UnixSocketExternalCheckerAdapter", - "UnixSocketTrustedIntakeAdapter", + "RemoteTlsExternalCheckerAdapter", + "RemoteTlsTrustedIntakeAdapter", "OpenAIResponsesCheckerModelProvider", "OpenRouterCheckerModelProvider", } @@ -391,8 +388,8 @@ def _assert_concrete_adapter_composition( if name in {"OTLPMetricExporter", "OTLPSpanExporter", "PeriodicExportingMetricReader"} ) assert Counter(factory_calls) == { - # Immutable storage and ephemeral trusted intake are separate capabilities. - COMPOSITION_ROOT: 2, + # Storage, trusted intake and source cleanup are separate capabilities. + COMPOSITION_ROOT: 3, CHECKER_COMPOSITION_ROOT: 2, # Inference and retained-resource cleanup are distinct typed capabilities. AGENT_COMPOSITION_ROOT: 2, @@ -427,8 +424,8 @@ def test_concrete_adapter_construction_has_one_composition_path( "from workstream_external_services import ExternalServiceAdapterFactory as factory\nfactory[object]('extra')\n", "from workstream_external_services import ExternalServiceAdapterFactory\nfactory: object = ExternalServiceAdapterFactory\nfactory[object]('extra')\n", "import workstream_external_services as external\nexternal.ExternalServiceAdapterFactory[object]('extra')\n", - "from app.adapters.artifacts.trusted_intake import UnixSocketTrustedIntakeAdapter as runtime\nruntime(configuration)\n", - "import app.adapters.artifacts.trusted_intake as intake\nintake.UnixSocketTrustedIntakeAdapter(configuration)\n", + "from app.adapters.artifacts.trusted_intake import RemoteTlsTrustedIntakeAdapter as runtime\nruntime(configuration)\n", + "import app.adapters.artifacts.trusted_intake as intake\nintake.RemoteTlsTrustedIntakeAdapter(configuration)\n", "from app.adapters.project_agents.openai_agent_sdk import OpenAIAgentSdkProjectGuideRuntime as runtime\nruntime(configuration)\n", "import app.adapters.project_agents.openai_agent_sdk as sdk\nsdk.OpenAIAgentSdkProjectGuideRuntime(configuration)\n", "from app.adapters.project_agents.omnicore_agent import OmniCoreAgentProjectGuideRuntime as runtime\nruntime(configuration)\n", From ccda218021091e9e1850023142c0fcb6c57ec3d1 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:00:58 +0100 Subject: [PATCH 275/513] Retire unused preparation authorization adapters --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 23 ++ backend/app/adapters/artifacts/__init__.py | 27 --- .../app/modules/artifacts/authorization.py | 203 +----------------- .../artifacts/submission_authorization.py | 106 --------- backend/scripts/test_lane_catalogue.py | 1 - .../submission_preparation_auth_helpers.py | 24 --- backend/tests/test_ci_lane_catalogue.py | 4 +- .../tests/test_submission_bundle_admission.py | 95 -------- .../test_submission_preparation_adapter.py | 97 --------- 9 files changed, 27 insertions(+), 553 deletions(-) delete mode 100644 backend/app/modules/artifacts/submission_authorization.py delete mode 100644 backend/tests/test_submission_preparation_adapter.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b7d684fe5..5361598ab 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8941,3 +8941,26 @@ orchestrator and every surviving admission method except admit/request-boundary are unchanged. Removed DTO/custody names are now forbidden by the existing retired intake architecture check. Old authorization and materialization-only code still needs cleanup; no full-suite/deployment completion claim. + +Next remove exclusively old preparation authorization: ART +PreparedSubmissionBundlePreparationAuthorization, its two adapter dependencies +(actor/get-authority), submission_authorization.py protocols/deny types, obsolete +adapter/deny tests and unused prepared_submitter_authority fixture. Allowed: +ART authorization.py, adapter __init__, submission_authorization.py, corresponding +test_submission_preparation_adapter.py/test_submission_bundle_admission.py, +submission_preparation_auth_helpers.py, catalogue/fingerprint and this record. +Keep install_submitter_grant and historical AUTH parsers/binding validation; +keep current source-read issuer PreparedPreSubmitMaterializationAuthorization +and current intake authority. API DTO/old materialization cleanup remains next. +Medium authorization risk; retained shared tests, current intake AUTH tests, +imports/structure/auth boundary and scoped ARCH/QA review. No schema/data/deploy. + +Authorization retirement checks passed:8 retained shared/catalogue checks22.22s +(/tmp/submission-auth-retirement-pure.log); current intake exact audit/rollback/ +single-use PostgreSQL case1/1 in5.02s, schema0090/fullcleanup +(/tmp/submission-auth-retirement.json). Imports, structure, AUTH boundary, +Ruff/diff passed. Fresh designated-provisioner IAM read still returns AccessDenied +for ListUserPolicies; no policy mutation or credential change was attempted. +Runner owner is preparing the app connection/deployment delta read-only while +root finishes remaining API/materialization retirement. Hosted qualification +still requires the prepared administrative IAM grant/policies. diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index d969a82b7..cf7b81000 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -49,7 +49,6 @@ from app.core.config import Settings from app.core.api_controls import request_ids -from app.api.deps.authorization import get_authorization_actor_identity from app.adapters.projects import project_locked_policy_context_port from app.adapters.tasks import task_submission_context_port from app.db.session import get_db_session @@ -96,7 +95,6 @@ get_guide_artifact_prepared_authorization, ) from app.modules.actors.api import ServiceIdentity -from app.modules.authorization.api import ActorIdentityFacts from app.modules.tasks.api.guide_documents import TaskGuideDocumentsPort from app.modules.projects.api.guide_reads import ProjectGuideDocumentContentPort @@ -128,16 +126,6 @@ def trusted_submission_intake(settings: Settings) -> TrustedSubmissionIntakeAdap return factory.create(PROVIDER) -async def get_submission_bundle_preparation_actor( - actor: Annotated[ - ActorIdentityFacts, - Depends(get_authorization_actor_identity), - ], -) -> ActorIdentityFacts: - """Return dependency-safe AUTH facts to the route-facing ART command.""" - return actor - - def create_artifact_store_bootstrap(settings: Settings) -> ArtifactStoreBootstrap: """Construct the selected store bootstrap through one typed factory. @@ -389,21 +377,6 @@ async def runtime(): ) -def get_submission_bundle_preparation_authorization( - session: Annotated[AsyncSession, Depends(get_db_session)], - context: Annotated[ - object, - Depends(get_artifact_authorization_context), - ], -): - """Compose the active contributor PREP adapter from canonical AUTH context.""" - from app.modules.artifacts.authorization import ( - PreparedSubmissionBundlePreparationAuthorization, - ) - - return PreparedSubmissionBundlePreparationAuthorization(session, context) - - def submission_admission_consumption_port( session: AsyncSession, *, diff --git a/backend/app/modules/artifacts/authorization.py b/backend/app/modules/artifacts/authorization.py index 9ead6ae5d..384e2cdf0 100644 --- a/backend/app/modules/artifacts/authorization.py +++ b/backend/app/modules/artifacts/authorization.py @@ -5,7 +5,7 @@ from collections.abc import AsyncIterator from contextlib import AbstractAsyncContextManager, asynccontextmanager from dataclasses import asdict -from typing import Annotated, NoReturn, Protocol +from typing import Annotated, Protocol from uuid import UUID from fastapi import Depends, Request @@ -36,7 +36,7 @@ from app.modules.artifacts.submission_bindings import SubmissionBindingAuthorityFacts from app.modules.artifacts.api import SubmissionAdmissionConsumptionError -from app.modules.authorization.catalogue import ACTION_BY_ID, ActionAvailability, ActionId +from app.modules.authorization.catalogue import ActionId from app.modules.authorization.kernel import AuthorizationService from app.modules.authorization.prepared import ( PreparedAuthorizationHandle, @@ -63,209 +63,10 @@ PreparedAuthorizationUnsupported, ServiceAuthorizationContext, AuthorizationContext, - SubmissionBundlePreparationPreflightResourceContext, - SubmissionBundlePreparationResourceContext, SubmissionBindingResourceContext, ) -class PreparedSubmissionBundlePreparationAuthorization: - """Translate ART facts into AUTH's existing request-local PREP protocol.""" - - def __init__(self, session: AsyncSession, context: AuthorizationContext) -> None: - """Compose one request-local ART-to-AUTH preparation adapter.""" - self._session = session - self._context = context - self._repository = AdminAuthorizationRepository(session) - self._authorization = AuthorizationService( - session, context, admin_repository=self._repository - ) - self._prepared = PreparedAuthorizationService( - session, context, self._authorization, self._repository - ) - self._input: PreparedAuthorizationInput | None = None - - @staticmethod - def _deny(exc: BaseException | None = None) -> NoReturn: - """Conceal every internal authorization failure from ART callers.""" - denial = ArtifactAuthorityDeniedError("submission bundle preparation is unavailable") - if exc is None: - raise denial - raise denial from exc - - @staticmethod - def _request_input(request, project_id: UUID) -> PreparedAuthorizationInput: - """Build immutable preliminary selectors from the ART request.""" - return PreparedAuthorizationInput( - idempotency_key=request.idempotency_key, - request_value={ - "scope_project_id": str(project_id), - "actor_profile_id": str(request.actor.actor_profile_id), - "identity_link_id": str(request.actor.identity_link_id), - "task_id": str(request.task_id), - "assignment_id": str(request.assignment_id), - "predecessor_submission_id": ( - str(request.predecessor_submission_id) - if request.predecessor_submission_id is not None - else None - ), - }, - ) - - def _final_input(self, facts) -> PreparedAuthorizationInput: - """Build exact final request facts for transaction-bound PREP.""" - request_value = self._final_values(facts, json=True) - return PreparedAuthorizationInput( - idempotency_key=self._input.idempotency_key, - request_value=request_value, - ) - - @staticmethod - def _final_values(facts, *, json: bool) -> dict: - values = asdict(facts) - project_id = values.pop("project_id") - values["scope_project_id"] = project_id - if json: - return { - key: str(value) if isinstance(value, UUID) else value - for key, value in values.items() - } - return values - - def _validate_actor_request(self, request) -> None: - """Reject invalid request identities before opening a database transaction.""" - action = ACTION_BY_ID[ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE] - invalid = ( - not isinstance(self._context, HumanAuthorizationContext) - or action.availability is not ActionAvailability.ACTIVE - or self._context.actor_status.value != "active" - or self._context.identity_link_status.value != "active" - or request.actor.actor_profile_id != self._context.actor_profile_id - or request.actor.identity_link_id != self._context.identity_link_id - ) - if invalid: - self._deny() - - async def preflight(self, *, request) -> None: - """Check the actor before context or byte access in a separate transaction.""" - self._validate_actor_request(request) - async with self._session.begin(): - await self.lock_actor(request=request) - - async def lock_actor(self, *, request) -> None: - """Hold current actor identity between TASK and PROJECT locks.""" - if not self._session.in_transaction() or self._session.in_nested_transaction(): - self._deny() - self._validate_actor_request(request) - locked = await self._repository.lock_request_actor( - self._context.identity_link_id, self._context.actor_profile_id - ) - if locked is None: - self._deny() - link, profile = locked - if ( - link.id != str(self._context.identity_link_id) - or link.actor_profile_id != str(self._context.actor_profile_id) - or link.status != "active" - or profile.id != str(self._context.actor_profile_id) - or profile.actor_kind != "human" - or profile.status != "active" - ): - self._deny() - - async def revalidate(self, *, request, project_id: UUID | None = None) -> None: - if project_id is None: - if self._input is None: - self._deny() - project_id = UUID(str(self._input.request_value["scope_project_id"])) - self._input = self._request_input(request, project_id) - resource = SubmissionBundlePreparationPreflightResourceContext( - resource_type="submission_bundle_preparation_preflight", - resource_id=request.assignment_id, - scope_project_id=project_id, - actor_profile_id=request.actor.actor_profile_id, - identity_link_id=request.actor.identity_link_id, - task_id=request.task_id, - assignment_id=request.assignment_id, - predecessor_submission_id=request.predecessor_submission_id, - ) - try: - await self._prepared.preflight( - ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE, - self._input, - PreparedAuthorityScope( - kind=PreparedAuthorityScopeKind.PROJECT, - project_id=project_id, - ), - resource, - ) - except (PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported) as exc: - self._deny(exc) - - @asynccontextmanager - async def transaction(self): - async with self._session.begin(): - yield - - async def prepare_final(self, *, facts): - if self._input is None: - self._deny() - final_input = self._final_input(facts) - expected = self._input.request_value - actual = final_input.request_value - for field in ( - "scope_project_id", - "actor_profile_id", - "identity_link_id", - "task_id", - "assignment_id", - "predecessor_submission_id", - ): - if actual[field] != expected[field]: - self._deny() - if final_input.idempotency_key != self._input.idempotency_key: - self._deny() - try: - handle = await self._prepared.prepare( - ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE, - final_input, - PreparedAuthorityScope( - kind=PreparedAuthorityScopeKind.PROJECT, - project_id=facts.project_id, - ), - ) - except (PreparedAuthorizationHandleInvalid, PreparedAuthorizationUnsupported) as exc: - self._deny(exc) - self._input = final_input - return handle - - async def consume(self, *, prepared_authorization: object, facts) -> None: - if self._input is None or type(prepared_authorization) is not PreparedAuthorizationHandle: - self._deny() - try: - resource = SubmissionBundlePreparationResourceContext( - resource_type="submission_bundle_preparation", - resource_id=facts.prepared_generation_id, - **self._final_values(facts, json=False), - ) - await self._prepared.consume( - prepared_authorization, - ActionId.ARTIFACT_SUBMISSION_BUNDLE_PREPARE, - self._input, - resource, - ) - except ( - AuthorizationDenied, - PreparedAuthorizationHandleInvalid, - PreparedAuthorizationUnsupported, - ValidationError, - ) as exc: - self._deny(exc) - - def close(self) -> None: - self._prepared.close() - - async def get_artifact_authorization_context( request: Request, resolved: Annotated[ResolvedActor, Depends(get_authorization_actor)], diff --git a/backend/app/modules/artifacts/submission_authorization.py b/backend/app/modules/artifacts/submission_authorization.py deleted file mode 100644 index 36b455745..000000000 --- a/backend/app/modules/artifacts/submission_authorization.py +++ /dev/null @@ -1,106 +0,0 @@ -"""Internal opaque authorization seam for submission-bundle durable intent.""" - -from __future__ import annotations - -from contextlib import AbstractAsyncContextManager -from typing import Protocol -from uuid import UUID - -from app.modules.artifacts.api import SubmissionBundlePreparationRequest -from app.modules.artifacts.schemas import ( - ArtifactAuthorityDeniedError, - SubmissionBundleDurableIntentAuthorityFacts, -) - - -class SubmissionBundlePreparedAuthorization(Protocol): - """Consume final contributor authority in the durable intent transaction.""" - - async def consume( - self, - *, - prepared_authorization: object, - facts: SubmissionBundleDurableIntentAuthorityFacts, - ) -> None: ... - - -class SubmissionBundlePreparationAuthorization(SubmissionBundlePreparedAuthorization, Protocol): - """Own preflight and final transaction-bound contributor preparation authority.""" - - async def preflight( - self, - *, - request: SubmissionBundlePreparationRequest, - ) -> None: ... - - async def lock_actor( - self, - *, - request: SubmissionBundlePreparationRequest, - ) -> None: - """Lock current actor identity in the caller's root transaction.""" - ... - - async def revalidate( - self, - *, - request: SubmissionBundlePreparationRequest, - project_id: UUID | None = None, - ) -> None: ... - - def transaction(self) -> AbstractAsyncContextManager[object]: ... - - async def prepare_final( - self, - *, - facts: SubmissionBundleDurableIntentAuthorityFacts, - ) -> object: ... - - def close(self) -> None: ... - - -class DenySubmissionBundlePreparedAuthorization: - """Keep contributor durable preparation unavailable until XINT-05A.""" - - async def prepare_final( - self, - *, - facts: SubmissionBundleDurableIntentAuthorityFacts, - ) -> object: - del facts - raise ArtifactAuthorityDeniedError("submission bundle durable preparation is unavailable") - - async def consume( - self, - *, - prepared_authorization: object, - facts: SubmissionBundleDurableIntentAuthorityFacts, - ) -> None: - del prepared_authorization, facts - raise ArtifactAuthorityDeniedError("submission bundle durable preparation is unavailable") - - -class DenySubmissionBundlePreparationAuthorization(DenySubmissionBundlePreparedAuthorization): - """Keep the complete contributor surface unavailable until XINT-05A.""" - - async def preflight(self, **values: object) -> None: - del values - raise ArtifactAuthorityDeniedError("submission bundle preparation is unavailable") - - async def lock_actor(self, **values: object) -> None: - del values - raise ArtifactAuthorityDeniedError("submission bundle preparation is unavailable") - - async def revalidate(self, **values: object) -> None: - del values - raise ArtifactAuthorityDeniedError("submission bundle preparation is unavailable") - - def transaction(self) -> AbstractAsyncContextManager[object]: - raise ArtifactAuthorityDeniedError("submission bundle preparation is unavailable") - - async def prepare_final(self, **values: object) -> object: - del values - raise ArtifactAuthorityDeniedError("submission bundle preparation is unavailable") - - def close(self) -> None: - return None diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 6af92ce79..605e83c11 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -292,7 +292,6 @@ class TestLane: "tests/test_artifact_admission_digest.py", "tests/test_submission_bundle_admission.py", "tests/test_submission_bundle_preparation_recovery.py", - "tests/test_submission_preparation_adapter.py", "tests/test_submission_preparation_authorization.py", "tests/test_submission_composition.py", "tests/test_artifact_bindings.py", diff --git a/backend/tests/submission_preparation_auth_helpers.py b/backend/tests/submission_preparation_auth_helpers.py index 2da04e427..788693263 100644 --- a/backend/tests/submission_preparation_auth_helpers.py +++ b/backend/tests/submission_preparation_auth_helpers.py @@ -5,13 +5,6 @@ from sqlalchemy import text -from app.modules.artifacts.authorization import PreparedSubmissionBundlePreparationAuthorization -from app.modules.authorization.runtime import ( - ActorKind, - ActorStatus, - HumanAuthorizationContext, - IdentityLinkStatus, -) async def install_submitter_grant(connection, params) -> None: @@ -77,20 +70,3 @@ async def table_counts(connection, tables) -> dict[str, int]: table: int(await connection.scalar(text(f"select count(*) from {table}")) or 0) for table in tables } - - -async def prepared_submitter_authority(session, request, actor_id, identity_link_id, project_id): - authority = PreparedSubmissionBundlePreparationAuthorization( - session, - HumanAuthorizationContext( - actor_profile_id=actor_id, - actor_kind=ActorKind.HUMAN, - actor_status=ActorStatus.ACTIVE, - identity_link_id=identity_link_id, - identity_link_status=IdentityLinkStatus.ACTIVE, - request_id=request.request_id, - correlation_id=request.correlation_id, - ), - ) - await authority.revalidate(request=request, project_id=project_id) - return authority diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 52c6052fb..9aa3b892a 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -320,8 +320,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 277, - "450b3fdb7336f81066405c487b2fa05fb2ee394dae66df917b5dbc0bb7009229", + 276, + "5b40d4e12032e17b09c70cc4a7484acda6994d918479a7e1e0fce955efa292a4", ), "project": ( 258, diff --git a/backend/tests/test_submission_bundle_admission.py b/backend/tests/test_submission_bundle_admission.py index e4d606aa2..47261a7f7 100644 --- a/backend/tests/test_submission_bundle_admission.py +++ b/backend/tests/test_submission_bundle_admission.py @@ -12,102 +12,16 @@ from app.core.config import Settings from app.modules.artifacts.api import ( SubmissionBundlePreparationRejected, - SubmissionBundlePreparationRequest, -) -from app.modules.artifacts.schemas import ( - ArtifactAuthorityDeniedError, ) from app.interfaces.artifacts import ( ArtifactConfigurationError, ) -from app.modules.artifacts.submission_authorization import ( - DenySubmissionBundlePreparedAuthorization, - DenySubmissionBundlePreparationAuthorization, -) -from app.modules.authorization.api import ActorIdentityFacts, ActorKind -from app.modules.authorization.prepared import PreparedAuthorizationHandle from tests.artifact_store_helpers import artifact_admission_limit_settings from app.main import create_app from app.api.routes.artifact_submissions import router as submission_router from app.modules.artifacts.submission_admission import validate_submission_packet_headers -def _actor() -> ActorIdentityFacts: - return ActorIdentityFacts( - actor_profile_id=new_record_id(), - identity_link_id=new_record_id(), - actor_kind=ActorKind.HUMAN, - ) - - -def _preparation_request( - *, byte_source, media_type: str = "application/zip", summary: str = "summary" -): - return SubmissionBundlePreparationRequest( - actor=_actor(), - request_id=new_record_id(), - correlation_id=new_record_id(), - task_id=new_record_id(), - assignment_id=new_record_id(), - predecessor_submission_id=None, - idempotency_key=new_record_id(), - summary=summary, - contributor_attestation="attestation", - media_type=media_type, - byte_source=byte_source, - ) - - -@pytest.mark.asyncio -async def test_artifact_adapter_preserves_public_actor_facts() -> None: - actor = _actor() - - assert await artifact_adapters.get_submission_bundle_preparation_actor(actor) is actor - - -@pytest.mark.asyncio -async def test_explicit_deny_preparation_authority_denies() -> None: - - authority = DenySubmissionBundlePreparationAuthorization() - request = _preparation_request(byte_source=object()) - - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.preflight(request=request) - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.lock_actor(request=request) - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.revalidate(request=request, project_id=new_record_id()) - with pytest.raises(ArtifactAuthorityDeniedError): - authority.transaction() - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.prepare_final(request=request) - authority.close() - - -@pytest.mark.asyncio -@pytest.mark.parametrize("active,nested", ((False, False), (True, True))) -async def test_actor_prelock_requires_a_root_transaction(active, nested) -> None: - from app.modules.artifacts.authorization import PreparedSubmissionBundlePreparationAuthorization - - authority = object.__new__(PreparedSubmissionBundlePreparationAuthorization) - authority._session = SimpleNamespace( - in_transaction=lambda: active, - in_nested_transaction=lambda: nested, - ) - authority._repository = SimpleNamespace(lock_request_actor=AsyncMock()) - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.lock_actor(request=object()) - authority._repository.lock_request_actor.assert_not_awaited() - - -@pytest.mark.asyncio -async def test_explicit_deny_durable_authority_denies_final_preparation() -> None: - authority = DenySubmissionBundlePreparedAuthorization() - - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.prepare_final(facts=object()) # type: ignore[arg-type] - - @pytest.mark.asyncio async def test_artifact_adapter_stale_scratch_cleanup_closes_manager( monkeypatch: pytest.MonkeyPatch, @@ -204,12 +118,3 @@ def test_submission_packet_headers_reject_non_ascii() -> None: match="submission_bundle_packet_header_encoding_invalid", ): validate_submission_packet_headers("caf\N{LATIN SMALL LETTER E WITH ACUTE}", "ok") - - -@pytest.mark.asyncio -async def test_deny_submission_authority_fails_closed() -> None: - with pytest.raises(ArtifactAuthorityDeniedError): - await DenySubmissionBundlePreparedAuthorization().consume( - prepared_authorization=object.__new__(PreparedAuthorizationHandle), - facts=object(), - ) diff --git a/backend/tests/test_submission_preparation_adapter.py b/backend/tests/test_submission_preparation_adapter.py deleted file mode 100644 index ad608ab78..000000000 --- a/backend/tests/test_submission_preparation_adapter.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Focused ART adapter proofs for AUTH submission preparation.""" - -from app.core.identifiers import new_record_id -from types import SimpleNamespace -from unittest.mock import AsyncMock - -import pytest - -from app.adapters import artifacts as artifact_adapters -from app.modules.artifacts.authorization import PreparedSubmissionBundlePreparationAuthorization -from app.modules.artifacts.schemas import ( - ArtifactAuthorityDeniedError, - SubmissionBundleDurableIntentAuthorityFacts, -) -from app.modules.authorization.runtime import PreparedAuthorizationInput - - -def _sha(value: str) -> str: - return "sha256:" + value * 64 - - -def test_artifact_adapter_composes_active_preparation_authority() -> None: - session, context = object(), object() - authority = artifact_adapters.get_submission_bundle_preparation_authorization(session, context) - assert type(authority) is PreparedSubmissionBundlePreparationAuthorization - assert authority._session is session - assert authority._context is context - - -@pytest.mark.asyncio -async def test_final_preparation_rejects_cross_request_facts() -> None: - authority = object.__new__(PreparedSubmissionBundlePreparationAuthorization) - project_id, actor_id, link_id, task_id, assignment_id = (new_record_id() for _ in range(5)) - authority._input = PreparedAuthorizationInput( - idempotency_key=new_record_id(), - request_value={ - "scope_project_id": str(project_id), - "actor_profile_id": str(actor_id), - "identity_link_id": str(link_id), - "task_id": str(task_id), - "assignment_id": str(assignment_id), - "predecessor_submission_id": None, - }, - ) - facts = SubmissionBundleDurableIntentAuthorityFacts( - actor_profile_id=actor_id, - identity_link_id=link_id, - project_id=project_id, - task_id=task_id, - assignment_id=new_record_id(), - predecessor_submission_id=None, - predecessor_submission_version=None, - pre_submit_evidence_set_id=None, - selected_pre_submit_run_id=new_record_id(), - selected_terminal_digest=_sha("9"), - prepared_generation_id=new_record_id(), - guide_id=new_record_id(), - guide_version="v1", - source_snapshot_id=new_record_id(), - source_snapshot_sha256=_sha("1"), - effective_policy_id=new_record_id(), - effective_policy_sha256=_sha("2"), - pre_submit_policy_id=new_record_id(), - pre_submit_policy_sha256=_sha("3"), - effective_plan_sha256=_sha("4"), - semantic_manifest_id=new_record_id(), - semantic_manifest_sha256=_sha("5"), - semantic_manifest_body={"schema_version": "submission_manifest.v1", "entries": []}, - packet_sha256=_sha("8"), - archive_sha256=_sha("6"), - archive_byte_count=42, - media_type="application/zip", - storage_scheme="s3", - operation_identity=_sha("7"), - replay_durable_intent_id=None, - ) - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.prepare_final(facts=facts) - - -@pytest.mark.asyncio -async def test_preflight_rejects_nonhuman_context_before_database_access() -> None: - authority = object.__new__(PreparedSubmissionBundlePreparationAuthorization) - authority._context = object() - authority._session = SimpleNamespace(begin=AsyncMock()) - - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.preflight(request=SimpleNamespace(actor=object())) - - -@pytest.mark.asyncio -async def test_final_preparation_requires_preflight_input() -> None: - authority = object.__new__(PreparedSubmissionBundlePreparationAuthorization) - authority._input = None - - with pytest.raises(ArtifactAuthorityDeniedError): - await authority.prepare_final(facts=object()) From 08066c81a7a1d6c2b58676677b5c77cd970fbd86 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:06:03 +0100 Subject: [PATCH 276/513] Record app runner deployment handoff --- .../changes/flow-self-service-signup.md | 12 +++ .../deploy/runner-qualification-20261124.md | 84 +++++++++++++++++++ 2 files changed, 96 insertions(+) diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index 777ee4b41..3cd90b391 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -465,3 +465,15 @@ refused it. Byte-identical units were restored and remain loaded, enabled and active; retained backup hashes match. Repaired POST and streamed-ZIP PRE both completed with pinned Smol isolation, PRE cleanup was destroyed, and all material, model-relay and Smol-lease roots were empty afterward. + +The app deployment handoff records the unchanged installed release and image, +the eight exact remote-runner/trusted-intake environment additions, private TLS +file custody, worker-only model callback mount, and one required private network +rule. Read-only host and control-plane inspection confirmed that the app has no +runner settings or TLS files yet and that TCP 9443 times out because the runner +group has only SSH ingress. Activation requires a new exact-head backend image, +an immutable release directory, one runner-group rule sourced from the app +group, mTLS health from the app host, offline render/private-input checks, and a +coordinated consumer-first upgrade. No app, network or IAM state changed during +the inspection; AWS source admission remains closed pending its separate IAM +qualification. diff --git a/external_checkers/deploy/runner-qualification-20261124.md b/external_checkers/deploy/runner-qualification-20261124.md index 3e12ac3db..834472ad8 100644 --- a/external_checkers/deploy/runner-qualification-20261124.md +++ b/external_checkers/deploy/runner-qualification-20261124.md @@ -143,6 +143,90 @@ envelope. It never deletes an active or uncertain grant. Focused tests cover both `.incoming-*` and renamed `extract_*` residue, refusal while the native socket exists, exact removal after confirmed stop, and clean restart. +## App deployment handoff + +The read-only app inspection found instance `i-000b0c090ddc142bd` healthy on +immutable release `/opt/workstream/releases/013ffbac2291179c03ff6d832f52efee9382322d`. +`workstream-hosted.service` and `workstream-identity-ingress.service` were +loaded, enabled and active. API and worker used the digest-pinned backend image +`094032936130.dkr.ecr.eu-north-1.amazonaws.com/workstream-backend@sha256:83744f1c16dd77e81555f613019898b1cca7d278a585749d2084de90ea3172a3`. +The app has no EC2 instance role; its existing direct S3 credential path remains +unchanged. Its observed source profile is hosted `app`, store backend +`s3_compatible`, provider `aws_s3`, credential mode `aws_access_key` and virtual +addressing. Keep those values and the existing credential mount unchanged; the +separate AWS source-admission gate remains closed pending qualification. + +The installed release predates the remote-runner wiring. Its release environment +contains no external-runner or trusted-intake keys, API and worker have no +runner TLS mounts, and `/etc/workstream/runner-tls` is absent. The worker's +existing app-local callback socket is healthy at +`/var/lib/workstream/model-runtime/model.sock` (uid/gid 10001, mode 0600, one +link); the API intentionally has no model callback socket. + +The exact non-secret release additions are: + +```dotenv +WORKSTREAM_EXTERNAL_RUNNER_HOST=172.31.21.182 +WORKSTREAM_EXTERNAL_RUNNER_PORT=9443 +WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME=runner.workstream.internal +WORKSTREAM_EXTERNAL_RUNNER_CA_FILE=/etc/workstream/runner-tls/ca.crt +WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE=/etc/workstream/runner-tls/app.crt +WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE=/etc/workstream/runner-tls/app.key +WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST=sha256:f77b5470b269ebce8ab2b467fcf0c52be814c2db9e5306aab090f45e7e2d8b81 +WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST=sha256:6a83910f3989fb657a405188d9b84b1815993be7af11bb399246a0d30100c5b0 +``` + +The three staged TLS inputs are present only in the operator-owned setup +directory. The CA is valid through 2036; the client certificate is valid +through 2029, has client-auth extended usage, chains to that CA and matches the +staged private key. Install distinct copies on the app as uid/gid 10001, mode +0400, without logging their contents. The reviewed Compose file mounts all +three as mode-0400 secrets into API and worker only. The worker also retains its +read-only app-local model socket; no runner secret or callback socket reaches +Beat, MCP, parser or model proxy. + +Both instances are in `vpc-049ecd21b84781a6a`. A live TCP probe from the app to +`172.31.21.182:9443` timed out. Control-plane readback showed that runner group +`sg-06167eb0a825ed79a` has only operator SSH ingress. The one required network +mutation is a TCP 9443 ingress rule on that runner group whose source is app +group `sg-015b341d9f8d39117` (a security-group reference, not a CIDR). No public +9443 rule and no app-group ingress change are needed. + +The bounded activation sequence is: + +1. Freeze the exact clean integrated commit and build/publish its backend image + under a new digest. The inspected candidate was `ccda21802`; deployment must + record the actual later head and image digest rather than reuse that mutable + observation. +2. Copy that exact source to a new root-owned `/opt/workstream/releases/` + directory. Preserve the current release and image for forward-repair or + supported rollback; do not modify the installed release in place. +3. Install the three TLS files with the ownership/mode above. Add only the eight + environment values listed above to a private staged release file, plus the + new release ID and backend image digest. Preserve all existing S3 direct-key + values and mounts. +4. Authorize exactly the app-group-to-runner-group TCP 9443 rule after confirming + it is still absent. Re-read the rule, verify private TCP reachability, then run + an mTLS runner-health probe from the app using the candidate backend image. + Require Linux/amd64, `smolvm`, `smol-microvm`, two cached manifests and + sandbox uid/gid 10001. +5. Run the candidate `compose.py` environment/render/private-input preflight + against the staged file before stopping any current container. Verify the + rendered environment and mode-0400 secrets appear on API and worker only, + and the model callback socket remains worker-only. +6. After the root owner coordinates a release window, use the documented + consumer-first drain and forward migration/upgrade procedure. Reconcile the + candidate release, wait for all container health checks, then verify the API + and worker both reach runner health over the private address. Only after + success should the hosted systemd unit be repointed to the new immutable + release and reconciled. + +At handoff, the SG rule, app TLS files, new backend image digest and new immutable +release were still absent. No app container, unit, environment, network or IAM +state was changed. The AWS submission-source admission gate remains separately +blocked on its IAM qualification; it must remain closed until that evidence +passes, but it does not require adding a local-native checker fallback. + ## Evidence and secret locations - this saved non-secret receipt: From f7a777a3019b0dd4acf1c2321e0fb57cbba16a51 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:15:20 +0100 Subject: [PATCH 277/513] Record app runner connection proof --- .../changes/flow-self-service-signup.md | 10 ++++ .../deploy/runner-qualification-20261124.md | 55 +++++++++++++++++-- 2 files changed, 60 insertions(+), 5 deletions(-) diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index 3cd90b391..29a5935a2 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -477,3 +477,13 @@ group, mTLS health from the app host, offline render/private-input checks, and a coordinated consumer-first upgrade. No app, network or IAM state changed during the inspection; AWS source admission remains closed pending its separate IAM qualification. + +Connection preparation then added only the runner-group TCP 9443 rule sourced +from the app security group and installed the CA/client certificate/client key +as private mode-0400 app files. An app-host TLS 1.3 exchange returned the exact +runner health identity; this is host connectivity evidence, not deployed +API/worker proof. Clean tracked source was staged under a new inactive immutable +release directory, while the active unit, environment and containers remained +unchanged. The deployed image records the `agents` SDK selection. It has no +submission execution or cleanup profile, exposing a separate fail-closed hosted +configuration gap before activation. diff --git a/external_checkers/deploy/runner-qualification-20261124.md b/external_checkers/deploy/runner-qualification-20261124.md index 834472ad8..ad38175be 100644 --- a/external_checkers/deploy/runner-qualification-20261124.md +++ b/external_checkers/deploy/runner-qualification-20261124.md @@ -82,6 +82,15 @@ obligation: - timings in milliseconds: admission 0, preparation 3377, execution 79922, cleanup 123, total 83424 +The preparation interval includes Smol machine creation, start and guest copy. +The execution interval begins at `machine exec` and includes delivery, spooling, +validation and staging of the 462,365,541-byte trusted root (459,170,607 expanded +bytes), followed by source and worker/project execution. The code has 2 ms I/O +polling but no configured fixed wait in that path; its aggregate and guest +timeout is 120 seconds. The receipt has no finer substage timings, so the trusted +root is the dominant-size code-path explanation for the 79.9-second execution, +not a separately measured attribution. + The final check found zero children in `materials/workspaces`, `model-relay` and `smol-leases`. Both services were loaded, enabled and active. The restored unit files matched their retained root-private backups exactly: @@ -155,6 +164,9 @@ unchanged. Its observed source profile is hosted `app`, store backend `s3_compatible`, provider `aws_s3`, credential mode `aws_access_key` and virtual addressing. Keep those values and the existing credential mount unchanged; the separate AWS source-admission gate remains closed pending qualification. +The installed image records SDK environment `agents`, runtime +`openai_agents_sdk`, provider `openrouter` and API `chat_completions`; a candidate +backend build must use `WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT=agents`. The installed release predates the remote-runner wiring. Its release environment contains no external-runner or trusted-intake keys, API and worker have no @@ -221,11 +233,44 @@ The bounded activation sequence is: success should the hosted systemd unit be repointed to the new immutable release and reconciled. -At handoff, the SG rule, app TLS files, new backend image digest and new immutable -release were still absent. No app container, unit, environment, network or IAM -state was changed. The AWS submission-source admission gate remains separately -blocked on its IAM qualification; it must remain closed until that evidence -passes, but it does not require adding a local-native checker fallback. +The deployed API has no submission execution or source-cleanup profile. The +candidate `Settings` values therefore remain `None`, and the hosted release +environment/Compose/preflight do not yet expose approved values. C01-C06 remain +unresolved; do not invent them or claim public source execution ready. + +## App connection preparation receipt + +After explicit coordination, the one private runner rule was created through +the isolated AWS provisioner wrapper and read back: + +- security-group rule: `sgr-0374858efbff06c93` +- runner group: `sg-06167eb0a825ed79a` +- protocol/port: TCP 9443 +- source group: `sg-015b341d9f8d39117` +- description: `Workstream app to runner mTLS` + +There is no CIDR source and no public 9443 rule. The three TLS files were copied +to `/etc/workstream/runner-tls` without printing their contents. The directory is +root-owned mode 0700; `ca.crt`, `app.crt` and `app.key` are regular, single-link, +nonempty files owned by uid/gid 10001 with mode 0400. The certificate chain and +client private-key match passed on the app host. + +A direct health exchange originating on the app host negotiated TLS 1.3 with +certificate name `runner.workstream.internal` and returned exact ready identity: +Linux/amd64, `smolvm`, `smol-microvm`, two cached manifests and sandbox uid/gid +10001. This proves app-host network, mTLS and protocol reachability only; the +deployed API and worker still use the old image and have not received runner +configuration. + +Clean tracked source commit `08066c81a7a1d6c2b58676677b5c77cd970fbd86` was +atomically staged, root-owned and non-writable by group/other at +`/opt/workstream/releases/08066c81a7a1d6c2b58676677b5c77cd970fbd86` (3,950 +files). Its Compose wrapper, Compose file and preflight hashes match the local +commit. It is only a candidate snapshot: the active unit still points to +`013ffbac2291179c03ff6d832f52efee9382322d`, no candidate backend image was built +on the live t3 app, and no environment, container, unit, IAM or source-gate state +changed. Root must freeze the eventual exact integration head and build its +`agents` image elsewhere before activation. ## Evidence and secret locations From adaa73716342643cf37850afa7ef918333cfbc66 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:22:11 +0100 Subject: [PATCH 278/513] Reconcile project test ownership fingerprint after retirement --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 27 +++++++++++++++++++ backend/tests/test_ci_lane_catalogue.py | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 5361598ab..2c4608429 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8964,3 +8964,30 @@ for ListUserPolicies; no policy mutation or credential change was attempted. Runner owner is preparing the app connection/deployment delta read-only while root finishes remaining API/materialization retirement. Hosted qualification still requires the prepared administrative IAM grant/policies. + +Hosted connection verification now proves app-host private mTLS to the separate +runner (receipt f7a777a30); API/worker activation remains unproved. Read-only +deployed inventory at 2026-11-24 13:18:50 UTC found schema +0069_remove_artifact_proof, zero contributor admissions/PRE/checker runs/formal +Submissions, and one guide object_confirmed put with one retained replica. A +second read found no workstream_tasks or checker_policies rows. Repeat under +actual cutover drain; preserve guide custody. Receipt: +/tmp/workstream-deployed-cutover-inventory-20261124.txt. Public API module8/8 +and CLI submission HTTP/public API18/18 passed with controlled PRE transport; +these are not deployed journey evidence. + +Bounded verification repair: update only the independent project ownership +fingerprint in backend/tests/test_ci_lane_catalogue.py and this record. The +runner test addition8fa9ae12c and retired preparation-command test removal +c4873cc36 left the count258 unchanged but changed the exact module mapping. +Replacing current test_remote_node.py with retired +test_selected_preparation_command.py in memory restores the old expected +f2581105 digest exactly; current mapping hashes to2d323a55. No lane ownership, +selector, count or assertion changes. Low risk; verify complete catalogue +module and diff/record checks. Human review focus: independent fixed digest +continues to reject unreviewed ownership changes. + +Independent catalogue repair verified:59 tests passed in15.63s +(/tmp/submission-catalogue-current.log); Commitrail and diff checks passed. +The warning reflects running this pure module without the asyncio plugin, +not a skipped asynchronous case. diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 9aa3b892a..cfb7574bf 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -399,7 +399,7 @@ def test_project_lane_ownership_has_an_independent_fingerprint() -> None: ) assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 258 assert hashlib.sha256(canonical.encode()).hexdigest() == ( - "f2581105d16fe388d824b0e50b017aa10f97ba7cbf5df27a8121d5591d2be96d" + "2d323a55856a88708dc247bfe2314e12fafde30f1900d3dfab06cbfd2026c335" ) From bf7836d757c7693a2236a0696a1fe6ee6c5ebc44 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:24:02 +0100 Subject: [PATCH 279/513] Prove public finalization recovers through real Redis delivery --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 59 +++++ ...est_submission_finalization_worker_loss.py | 233 ++++++++++++++++++ 2 files changed, 292 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2c4608429..3f6370565 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -8991,3 +8991,62 @@ Independent catalogue repair verified:59 tests passed in15.63s (/tmp/submission-catalogue-current.log); Commitrail and diff checks passed. The warning reflects running this pure module without the asyncio plugin, not a skipped asynchronous case. + +### Qualify finalization publication recovery through real Redis/prefork + +Allowed: the existing test_submission_finalization_worker_loss.py module and +this record. Add one bounded integration proof: signed public raw-ZIP acceptance +through real PRE/T4 owners using the existing controlled guest transport; actual +production scanner publication fails at a closed test-only TCP endpoint while +accepted custody remains intact; restore that endpoint as a transparent Redis +forwarder, run the same scanner and deliver duplicate production finalization +tasks through the exclusive non-eager prefork worker. Preserve real registry, +AUTH, outbox claim/invocation/finalization and provider observation. Observe task +completion without replacing handlers; require one durable Submission, binding +and POST event, stable receipt/replay and retained source charge. + +Risk: medium test-process/network custody. Use one isolated PostgreSQL/MinIO +launcher and a unique Redis key prefix; terminate only the owned worker process +group, drain owned proxy connections and remove only prefixed Redis keys. The +shared Redis container must remain running. No production/schema/provider changes +or new queue. Verify focused test, Ruff/structure and scoped review. This does +not qualify Beat scheduling, SIGKILL broker redelivery, native guest execution, +AWS, deployment or the complete public governed-acceptance journey. Existing +SIGKILL owner tests remain separate. User authorized parallel end-to-end proof; +all edits are isolated from the primary checkout. + +Initial isolated V1 stopped after public acceptance but before discovery: the +fixture exported local artifact configuration without environment=test, so the +unchanged Settings validator refused local production storage. Receipt +/tmp/submission-finalizer-real-broker-v1.json confirms schema0090 and complete +cleanup; it is not successful broker evidence. Match the existing fixture's test +environment explicitly and isolate/close this proof's Celery connection pools +so later tests do not inherit the temporary broker endpoint. + +Final V2 passed1 in109.24s under system Python3.12.3 with real Redis7.4.12. +/tmp/submission-finalizer-real-broker-v2.{log,json} records launcher08066c81a, +schema0090 and complete PostgreSQL/MinIO cleanup; executable test bytes were +728682ecb2092fddbf20d04d7e760964772469fc before execution and remain unchanged. The actual +scanner reports selected1/published0 during connection refusal, then +selected1/published1 after restoration. Original plus two duplicate production +tasks returned SUCCESS from the exclusive prefork child; one recorded delivery +and two unavailable duplicate deliveries leave one completed outbox attempt, +Submission, binding and POST event. Accepted receipt and one PRE invocation are +stable through public same-key replay. Source remains sealed and fully charged; +only T5 clears the task pointer. + +The test removes only its unique Redis prefix and owned worker/proxy resources. +A post-run read confirmed shared Redis still responds and no finalizer-proof-* +keys remain. One Python fork-with-threads DeprecationWarning is retained (the +existing repository real-broker prefork pattern); passing does not establish +thread-free process startup or broker-crash redelivery. Production scanner logic +is invoked directly to simulate its next scheduled pass; Beat itself is outside +this proof. The task, registry, delivery/authority and source provider are real; +only PRE guest transport uses the existing controlled fixture. + +Ruff and diff checks pass; test-structure validation exits0 +(/tmp/submission-finalizer-broker-structure.log). Commitrail gate exits0 before +this evidence append and is repeated for the final record. Original SIGKILL test +and helper ASTs are unchanged. No new module/lane registration or production edit. +This is a single focused precommit execution, not a final-head/full-suite/native +or deployed governed-outcome qualification. V1's setup failure remains above. diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py index 9996c0342..728682ecb 100644 --- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -145,3 +145,236 @@ async def test_sigkill_finalizer_recovers_exact_accepted_operation(admission_int assert not process.is_alive(), "crash worker cleanup failed" process.close() store.close() + + +def _broker_finalizer(app, hostname, completed): + """Observe real returns after the production exclusive-prefork boundary.""" + from celery.signals import task_postrun + from app.workers.outbox_topology import FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE + + def record(task_id, task, retval, state, **_kwargs): + if task.name == FINALIZATION_DELIVERY_TASK: + completed.put((task_id, state, retval, os.getpid(), task.request.is_eager, + task.request.delivery_info["routing_key"])) + + os.setsid() + task_postrun.connect(record, weak=False) + app.Worker(pool="prefork", concurrency=1, queues=[FINALIZATION_QUEUE], hostname=hostname, + loglevel="ERROR", without_gossip=True, without_mingle=True, + without_heartbeat=True).start() + + +async def _redis_forwarder(reader, writer, destination, connections): + """Restore only this test's TCP endpoint; Redis and its namespace stay real.""" + current = asyncio.current_task() + connections.add(current) + upstream, copies = None, [] + + async def copy_bytes(source, target): + while data := await source.read(64 * 1024): + target.write(data) + await target.drain() + + try: + remote, upstream = await asyncio.open_connection(*destination) + copies = [asyncio.create_task(copy_bytes(reader, upstream)), + asyncio.create_task(copy_bytes(remote, writer))] + await asyncio.wait(copies, return_when=asyncio.FIRST_COMPLETED) + finally: + for pending in copies: + pending.cancel() + await asyncio.gather(*copies, return_exceptions=True) + for stream in (writer, upstream): + if stream is not None: + stream.close() + try: + await stream.wait_closed() + except ConnectionError: + pass + connections.discard(current) + + +def _broker_settings(settings, monkeypatch): + """Give the worker the same real local namespace as the public upload.""" + import json + from app.core.config import get_settings + + for name, value in settings.model_dump(mode="json").items(): + if name.startswith("artifact_") and value is not None: + encoded = json.dumps(value) if isinstance(value, (dict, list, bool)) else str(value) + monkeypatch.setenv("WORKSTREAM_" + name.upper(), encoded) + monkeypatch.setenv("WORKSTREAM_ENVIRONMENT", "test") + monkeypatch.setenv("WORKSTREAM_HOSTED_PROFILE", "app") + get_settings.cache_clear() + + +async def _accepted_broker_facts(f, operation_id): + """Freeze accepted product/outbox custody across publication failure.""" + from app.modules.artifacts.intake.models import SubmissionSourceCharge + + async with f.factory() as session: + operation = await session.get(SubmissionIntakeOperation, operation_id) + event = await session.get(OutboxEvent, UUID(operation.finalization_event_id)) + charge = await session.get(SubmissionSourceCharge, operation_id) + pointer = await session.scalar(text( + "SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:task" + ), {"task": f.task}) + return (operation.state, operation.acceptance_receipt, operation.finalized_submission_id, + operation.continuation_generation, event.event_id, event.delivery_state, + event.attempt_count, charge.state, charge.accounted_bytes, pointer) + + +async def _assert_broker_finalized_once(f, operation_id, accepted): + """Require one durable graph after original and duplicate tasks return.""" + from app.modules.artifacts.intake.models import SubmissionSourceCharge + from app.modules.outbox.models import OutboxDeliveryAttempt + + async with f.factory() as session: + operation = await session.get(SubmissionIntakeOperation, operation_id) + event = await session.get(OutboxEvent, UUID(operation.finalization_event_id)) + charge = await session.get(SubmissionSourceCharge, operation_id) + assert operation.state == "finalized" and operation.finalized_submission_id is not None + assert operation.acceptance_receipt == accepted and operation.continuation_generation == 1 + assert event.delivery_state == "acknowledged" and event.attempt_count == 1 + attempts = (await session.scalars(select(OutboxDeliveryAttempt).where( + OutboxDeliveryAttempt.event_id == event.event_id))).all() + assert len(attempts) == 1 and attempts[0].stage == "completed" + assert charge.state == "sealed" and charge.accounted_bytes == operation.raw_byte_count > 0 + for table in ("submissions", "submission_dispatches", "checker_runs"): + assert await session.scalar(text( + f"SELECT count(*) FROM {table} WHERE task_id=:task" + ), {"task": f.task}) == 1 + assert await session.scalar(text( + "SELECT count(*) FROM artifact_bindings WHERE resource_id=:submission" + ), {"submission": operation.finalized_submission_id}) == 1 + assert await session.scalar(text( + "SELECT count(*) FROM outbox_events WHERE project_id=:project " + "AND event_type='PostSubmissionEvaluationRequested'" + ), {"project": f.project}) == 1 + assert await session.scalar(text( + "SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:task" + ), {"task": f.task}) is None + return operation.finalized_submission_id + + +async def _stop_broker_worker(process, completed): + """Stop only the owned worker group before removing this test's keys.""" + if process.pid is not None: + if process.is_alive(): + os.killpg(process.pid, signal.SIGTERM) + await asyncio.to_thread(process.join, 10) + if process.is_alive(): + os.killpg(process.pid, signal.SIGKILL) + await asyncio.to_thread(process.join, 5) + assert not process.is_alive(), "owned finalization worker survived cleanup" + process.close() + completed.close() + completed.join_thread() + + +async def test_real_broker_recovers_public_acceptance_and_deduplicates_finalization( + admission_intake, tmp_path, monkeypatch, +): + """Controlled public PRE, real outage/scanner, Redis and production prefork T5.""" + import queue + import socket + import time + from urllib.parse import urlsplit + import redis + from app.core.config import get_settings + from app.core.identifiers import new_record_id + from app.workers import outbox as worker + from app.workers.outbox_topology import FINALIZATION_QUEUE + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.test_trusted_intake import _archive + + f = admission_intake + broker = urlsplit(os.environ["WORKSTREAM_TEST_BROKER_URL"]) + assert broker.scheme == "redis" and broker.hostname and broker.port + connection = redis.Redis.from_url(broker.geturl()) + assert connection.ping() + prefix, hostname = f"finalizer-proof-{new_record_id()}:", f"finalizer-{new_record_id()}@localhost" + closed_endpoint = socket.socket() + closed_endpoint.bind(("127.0.0.1", 0)) + port = closed_endpoint.getsockname()[1] + app = worker.celery_app + monkeypatch.setattr(app, "_pool", None) + monkeypatch.setattr(app.amqp, "_producer_pool", None) + monkeypatch.setitem(app.conf, "broker_url", f"redis://127.0.0.1:{port}/{broker.path.lstrip('/')}") + monkeypatch.setitem(app.conf, "broker_transport_options", { + **app.conf.broker_transport_options, "global_keyprefix": prefix, + "socket_connect_timeout": 0.25, "socket_timeout": 5, "max_retries": 0, + }) + monkeypatch.setitem(app.conf, "task_publish_retry", False) + monkeypatch.setitem(app.conf, "task_always_eager", False) + completed = multiprocessing.get_context("fork").Queue() + process = multiprocessing.get_context("fork").Process(target=_broker_finalizer, args=(app, hostname, completed)) + proxy, connections = None, set() + try: + payload, key = _archive(), new_record_id() + client, settings, errors, calls = await configure_source_http( + f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "completed") + headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + "Idempotency-Key": str(key), "Content-Length": str(len(payload)), + } + url = f"/api/v1/tasks/{f.task}/submissions" + accepted = await client.post(url, headers=headers, content=payload) + assert accepted.status_code == 202, accepted.text + assert len(calls) == 1 and not errors, errors + operation_id = UUID(accepted.json()["operation_id"]) + for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER): + await provision_post_submit_service(f.factory, identity) + _broker_settings(settings, monkeypatch) + before = await _accepted_broker_facts(f, operation_id) + assert before[0] == "finalization_pending" and before[5:7] == ("pending", 0) + failed = await asyncio.to_thread(worker.scan_pending.run) + assert failed == {"selected": 1, "published": 0} + assert await _accepted_broker_facts(f, operation_id) == before + assert list(connection.scan_iter(match=prefix + "*")) == [] + closed_endpoint.close() + proxy = await asyncio.start_server( + lambda reader, writer: _redis_forwarder(reader, writer, (broker.hostname, broker.port), connections), + "127.0.0.1", port) + published = await asyncio.to_thread(worker.scan_pending.run) + assert published == {"selected": 1, "published": 1} + for _ in range(2): + await asyncio.to_thread(worker.finalize_submission.apply_async, args=(str(before[4]), str(f.project))) + assert connection.llen(prefix + FINALIZATION_QUEUE) == 3 + process.start() + deadline, observations = time.monotonic() + 120, [] + while len(observations) < 3 and time.monotonic() < deadline: + assert process.is_alive(), f"finalization worker exited: {process.exitcode}" + try: + observations.append(await asyncio.to_thread(completed.get, True, 0.2)) + except queue.Empty: + pass + assert len(observations) == 3, observations + assert len({item[0] for item in observations}) == 3 + assert all(item[1] == "SUCCESS" and item[3] not in {os.getpid(), process.pid} + and item[4:] == (False, FINALIZATION_QUEUE) for item in observations), observations + assert sorted(item[2]["status"] for item in observations) == [ + "delivery_recorded", "delivery_unavailable", "delivery_unavailable"] + await _assert_broker_finalized_once(f, operation_id, before[1]) + replay = await client.post(url, headers=headers, content=payload) + assert replay.status_code == 202 and replay.json() == dict(accepted.json(), replayed=True), replay.text + assert len(calls) == 1 and not errors + await _assert_broker_finalized_once(f, operation_id, before[1]) + finally: + closed_endpoint.close() + await _stop_broker_worker(process, completed) + for pool in (app.amqp._producer_pool, app._pool): + if pool is not None: + pool.force_close_all() + if proxy is not None: + proxy.close() + await proxy.wait_closed() + for pending in tuple(connections): + pending.cancel() + await asyncio.gather(*tuple(connections), return_exceptions=True) + keys = list(connection.scan_iter(match=prefix + "*")) + if keys: + connection.delete(*keys) + assert list(connection.scan_iter(match=prefix + "*")) == [] + connection.close() + get_settings.cache_clear() From 8b664ec38c975ff6673a7328f3466ef30ca26882 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:26:47 +0100 Subject: [PATCH 280/513] Retire obsolete submission preparation API and materialization --- .ci/behavior-ownership/partition.v1.json | 14 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 39 + backend/app/modules/artifacts/api/__init__.py | 14 - .../artifacts/api/submission_preparation.py | 75 -- .../modules/artifacts/submission_admission.py | 28 - .../artifacts/submission_materialization.py | 658 ---------------- backend/scripts/behavior_ownership.py | 7 +- .../architecture/test_module_boundaries.py | 2 +- .../test_selected_intake_lifecycle.py | 162 +--- .../external/test_selected_pre_submit.py | 714 +----------------- backend/tests/submission_capacity_fixtures.py | 56 -- backend/tests/test_artifact_architecture.py | 20 +- .../tests/test_submission_bundle_admission.py | 13 - ..._submission_bundle_preparation_recovery.py | 18 - 14 files changed, 87 insertions(+), 1733 deletions(-) delete mode 100644 backend/app/modules/artifacts/submission_materialization.py delete mode 100644 backend/tests/submission_capacity_fixtures.py diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json index 8302e21b5..6a43a6f76 100644 --- a/.ci/behavior-ownership/partition.v1.json +++ b/.ci/behavior-ownership/partition.v1.json @@ -756,26 +756,14 @@ "group": "artifacts", "target": "backend/app/modules/artifacts/submission_archive.py" }, - { - "group": "artifacts", - "target": "backend/app/modules/artifacts/submission_authorization.py" - }, { "group": "artifacts", "target": "backend/app/modules/artifacts/submission_bindings.py" }, - { - "group": "artifacts", - "target": "backend/app/modules/artifacts/submission_custody.py" - }, { "group": "artifacts", "target": "backend/app/modules/artifacts/submission_manifest.py" }, - { - "group": "artifacts", - "target": "backend/app/modules/artifacts/submission_materialization.py" - }, { "group": "artifacts", "target": "backend/app/modules/artifacts/task_guide_documents.py" @@ -2761,7 +2749,7 @@ "target": "backend/scripts/validate_test_lane_evidence.py" } ], - "authority_digest": "4e1cb7d1dbc23133efd77854a6c6f5c7ecaee7a75f928845c5b81ca86c20b66c", + "authority_digest": "ec63dcd5f70071cd2dcb69a2c3e127162a2b017aa3734bed14d12440c38d8bdc", "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6", "schema": "workstream.behavior-ownership-partition.v1" } diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3f6370565..1f33c12fc 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9050,3 +9050,42 @@ this evidence append and is repeated for the final record. Original SIGKILL test and helper ASTs are unchanged. No new module/lane registration or production edit. This is a single focused precommit execution, not a final-head/full-suite/native or deployed governed-outcome qualification. V1's setup failure remains above. + +Next retire the obsolete ART submission preparation writer API and its exclusive +prepared-bundle materialization module. Remove Request/Result/Command and +writer-only exceptions, header/revision wrappers and stale capacity fixtures; +retain read DTOs/status, historical AUTH/ORM readers, publisher byte behavior, +current source grants and shared scratch cleanup. Migrate revision +acknowledgement, packet-header and cleanup assertions to current owners before +removing obsolete tests. Allowed: ART API/submission admission/materialization, +their direct tests and architecture inventories, catalogue only if selection +changes, and this record. No schema/data/deployment changes. Medium API and +test-coverage risk. Verify current intake contracts, retained publisher and +historical reads, shared scratch cleanup, imports, architecture, structure, +ownership, Ruff and diff; seek scoped architecture and QA review. + +Retirement implementation removes the writer Request/Result/Command, +writer-only exceptions, obsolete header/revision wrappers, exclusive prepared +materialization module and its unused capacity fixture. The selected PRE test +module now retains current source-first revision binding, direct TASK revision +acknowledgement and four historical publisher controls; the intake lifecycle +module retains three shared scratch/cancellation cleanup tests. Current +SubmissionIntakeMetadata packet validation replaces the removed header helper +test. ART read DTO/status, historical AUTH parsers and retained publisher stay; +AST comparison confirms the publisher class, publication error, PRE feedback +projections and read DTOs are unchanged. Protected behavior ownership partition +removes exactly this module plus submission_custody.py and +submission_authorization.py, which earlier retirement commits had already +deleted but left listed in the manifest. + +Staged-tree verification: selected PRE/coordination/shared cleanup 119 passed; +current intake, admission and packet contract tests 153 passed; artifact and +module-boundary architecture 90 passed; behavior ownership tests 172 passed. +Structure and module-boundary validators, behavior partition validator, +Commitrail record check, Ruff and diff check passed. No PostgreSQL/storage or +native PRE qualification is claimed from this retirement-only verification. +An attempted whole-backend collection using the base backend virtual environment +collected 12080 cases but ended with eight unrelated optional-agent import +errors because that environment lacks `httpx2`; it is not counted as a pass. +The repository-wide Markdown-link checker also fails unchanged on two links to +the missing `deploy/hosted/SINGLE_HOST.md` in untouched documents. diff --git a/backend/app/modules/artifacts/api/__init__.py b/backend/app/modules/artifacts/api/__init__.py index bf0473ab8..2e0c2858b 100644 --- a/backend/app/modules/artifacts/api/__init__.py +++ b/backend/app/modules/artifacts/api/__init__.py @@ -1,14 +1,7 @@ """Dependency-safe public API for the ARTIFACTS business module.""" from app.modules.artifacts.api.submission_preparation import ( - SubmissionBundlePreparationCheckFailed, - SubmissionBundlePreparationCommand, - SubmissionBundlePreparationRejected, - SubmissionBundlePreparationInfrastructureUnavailable, - SubmissionBundlePreparationRequest, - SubmissionBundlePreparationResult, SubmissionBundlePreparationStatus, - SubmissionBundlePreparationUnavailable, ) from app.modules.artifacts.api.submission_admission import ( SubmissionAdmissionConsumptionError, @@ -36,14 +29,7 @@ "ReviewPacketMembershipRequest", "ReviewPacketMembershipUnavailable", "ReviewSubmissionMember", - "SubmissionBundlePreparationCheckFailed", - "SubmissionBundlePreparationCommand", - "SubmissionBundlePreparationRejected", - "SubmissionBundlePreparationInfrastructureUnavailable", - "SubmissionBundlePreparationRequest", - "SubmissionBundlePreparationResult", "SubmissionBundlePreparationStatus", - "SubmissionBundlePreparationUnavailable", "SubmissionAdmissionConsumptionError", "SubmissionAdmissionConsumptionPort", "SubmissionAdmissionConsumptionRequest", diff --git a/backend/app/modules/artifacts/api/submission_preparation.py b/backend/app/modules/artifacts/api/submission_preparation.py index bf820c876..eac5a013b 100644 --- a/backend/app/modules/artifacts/api/submission_preparation.py +++ b/backend/app/modules/artifacts/api/submission_preparation.py @@ -2,8 +2,6 @@ from __future__ import annotations -from collections.abc import AsyncIterable -from dataclasses import dataclass from enum import StrEnum from datetime import datetime from typing import TYPE_CHECKING, Any, Literal, Protocol @@ -11,36 +9,10 @@ from pydantic import AwareDatetime, BaseModel, ConfigDict, Field -from app.modules.authorization.api import ActorIdentityFacts if TYPE_CHECKING: from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts -class SubmissionBundlePreparationRejected(RuntimeError): - """Reject preparation with one stable ART-owned failure code.""" - - -class SubmissionBundlePreparationCheckFailed(SubmissionBundlePreparationRejected): - """Carry the exact bounded CHECKERS facts for one blocked preparation.""" - - def __init__( - self, - facts: SelectedPreSubmitExecutionFacts, - ) -> None: - from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts - - if type(facts) is not SelectedPreSubmitExecutionFacts: - raise TypeError("pre-submission feedback facts are invalid") - if facts.eligible is not False: - raise ValueError("blocked pre-submission facts require eligible false") - super().__init__("pre_submission_checker_failed") - self.facts = facts - - def public_results(self) -> list[dict[str, object]]: - """Return sanitized ordered work findings without execution authority.""" - return public_pre_submission_results(self.facts) - - def public_pre_submission_results( facts: SelectedPreSubmitExecutionFacts, ) -> list[dict[str, object]]: @@ -103,14 +75,6 @@ def pre_submission_finding_counts(facts: SelectedPreSubmitExecutionFacts) -> dic } -class SubmissionBundlePreparationUnavailable(RuntimeError): - """Conceal unavailable or denied preparation authority.""" - - -class SubmissionBundlePreparationInfrastructureUnavailable(RuntimeError): - """Authorized preparation cannot safely recover its execution or continuation.""" - - class SubmissionBundlePreparationStatus(StrEnum): """Closed public state vocabulary for one ART preparation operation.""" @@ -129,36 +93,6 @@ class SubmissionBundlePreparationStatus(StrEnum): READY = "ready" -@dataclass(frozen=True, slots=True) -class SubmissionBundlePreparationRequest: - """One continuous contributor ZIP request with server-owned actor facts.""" - - actor: ActorIdentityFacts - request_id: UUID - correlation_id: UUID - task_id: UUID - assignment_id: UUID - predecessor_submission_id: UUID | None - idempotency_key: UUID - summary: str - contributor_attestation: str - media_type: str - byte_source: AsyncIterable[bytes] - revision_preparation_id: str | None = None - revision_preparation_sha256: str | None = None - - -@dataclass(frozen=True, slots=True) -class SubmissionBundlePreparationResult: - """Bounded preparation result without custody or provider coordinates.""" - - put_attempt_id: UUID - admission_id: UUID | None - submission_bundle_preparation_status: SubmissionBundlePreparationStatus - replayed: bool - pre_submission_results: tuple[dict[str, object], ...] - - PreparationOutcome = Literal["pending", "passed", "failed", "infrastructure_failed"] PreparationState = Literal[ "checking", "checks_failed", "infrastructure_failed", "storing", "ready", "submitted", "stale", @@ -235,12 +169,3 @@ async def read_project( ) -> tuple[tuple[ProjectSubmissionBundlePreparation, ...], bool]: """Every contributor's preparations in one project, without findings.""" ... - - -class SubmissionBundlePreparationCommand(Protocol): - """Prepare one hidden contributor bundle through the sole ART command.""" - - async def prepare( - self, request: SubmissionBundlePreparationRequest - ) -> SubmissionBundlePreparationResult: - """Run the continuous fail-closed preparation workflow.""" diff --git a/backend/app/modules/artifacts/submission_admission.py b/backend/app/modules/artifacts/submission_admission.py index dc80f8920..05f522280 100644 --- a/backend/app/modules/artifacts/submission_admission.py +++ b/backend/app/modules/artifacts/submission_admission.py @@ -9,10 +9,6 @@ from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from app.modules.artifacts.api import ( - SubmissionBundlePreparationRejected, - SubmissionBundlePreparationRequest, -) from app.modules.artifacts.models import ( ArtifactContent, ArtifactOperationReceipt, @@ -27,37 +23,13 @@ from app.modules.checkers.api.historical_selected_pre_submit import ( HistoricalSelectedPreSubmitReservation, HistoricalSelectedPreSubmitTerminal, ) -from app.modules.tasks.api.submission_context import require_revision_acknowledgement from app.modules.tasks.api import ( TaskRetainedSubmissionParentsRequest, - TaskSubmissionContextFacts, TaskSubmissionContextPort, TaskSubmissionContextUnavailable, ) -def validate_submission_packet_headers(summary: str, attestation: str) -> None: - """Reject lossy header decoding only after contributor preflight succeeds.""" - try: - summary.encode("ascii") - attestation.encode("ascii") - except UnicodeEncodeError as exc: - raise SubmissionBundlePreparationRejected( - "submission_bundle_packet_header_encoding_invalid" - ) from exc - - -def require_revision_preparation_acknowledgement( - task: TaskSubmissionContextFacts, - request: SubmissionBundlePreparationRequest, -) -> None: - """Compare the contributor's explicit acknowledgement after fresh authority.""" - try: - require_revision_acknowledgement(task, request.revision_preparation_id, request.revision_preparation_sha256) - except TaskSubmissionContextUnavailable as exc: - raise SubmissionBundlePreparationRejected(exc.code) from exc - - class SubmissionBundleAdmissionPublicationError(RuntimeError): """Durable verification lineage cannot publish a trusted ready admission.""" diff --git a/backend/app/modules/artifacts/submission_materialization.py b/backend/app/modules/artifacts/submission_materialization.py deleted file mode 100644 index d0d588d0d..000000000 --- a/backend/app/modules/artifacts/submission_materialization.py +++ /dev/null @@ -1,658 +0,0 @@ -"""Hidden authorized materialization for one prepared contributor bundle.""" - -from __future__ import annotations - -import asyncio -from contextlib import AbstractContextManager, contextmanager -from dataclasses import asdict, dataclass, field -from pathlib import Path -from typing import Protocol, final -from uuid import UUID - -from sqlalchemy.ext.asyncio import AsyncSession - -from app.core.hashing import canonical_json_hash -from app.core.cancellation import await_cancellation_resistant -from app.interfaces.trusted_submission_intake import TrustedIntakeSession, TrustedDefaultBinding -from workstream_external_services import ExternalServiceAdapterError -from app.modules.artifacts.submission_archive import exported_submission_tree -from app.modules.checkers.api.materialization import PreSubmitMaterialView, SubmissionMaterialEntry -from app.interfaces.external_checker_execution import ( - ExternalCheckerMaterialGrant, -) -from app.modules.artifacts.schemas import ArtifactAuthorityDeniedError -from app.modules.artifacts.preparation import ( - ArtifactPreparationService, - ArtifactPreparationDeadlineError, - ExternalMaterialFile, - ExternalMaterialGrantRequest, -) -from app.modules.artifacts.sources import PreparedArtifact -from app.modules.artifacts.api.submission_archive import ( - SubmissionArchiveInspectionResult, - SubmissionArchiveLimits, -) -from app.modules.artifacts.api.submission_manifest import ( - SubmissionManifest, - build_submission_manifest, -) -from app.modules.artifacts.submission_manifest import ( - SubmissionChangeGateResult, -) -from app.modules.checkers.api.pre_submit_material import ( - ALLOWED_PRE_SUBMIT_STORAGE_SCHEMES, - SubmissionPacketView, -) -from app.modules.checkers.api.default_checker import ( - WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - WorkstreamDefaultCheckerInput, - WorkstreamDefaultCheckerResult, - workstream_default_input_body, -) -from app.modules.checkers.api.external import ( - ExternalCheckerExecutionRequest, - PreSubmitExternalCheckerIdentity, - PreSubmitExternalCheckerMaterial, -) -from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy -from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitExecutionAuthority, - SelectedPreSubmitExecutionFacts, - SelectedPreSubmitLeaseFacts, - SelectedPreSubmitReservationFacts, - SelectedPreSubmitInfrastructureUnavailable, -) -from app.modules.projects.api import ProjectLockedPolicyContextFacts -from app.modules.tasks.api import TaskSubmissionContextFacts - - -@dataclass(frozen=True, slots=True) -class PreparedBundleMaterializationRequest: - """ART-private process-local prepared bytes and exact execution facts.""" - - prepared_authorization: object - task_id: UUID - assignment_id: UUID - submission_artifact_policy_id: UUID - checker_policy_id: UUID - predecessor_submission_version: int | None - checker_remediation_manifest_id: UUID | None = field(default=None, kw_only=True) - prepared_artifact: PreparedArtifact - inspection: SubmissionArchiveInspectionResult - manifest: SubmissionManifest - change_gate: SubmissionChangeGateResult - packet: SubmissionPacketView - external_policy: LockedExternalPreSubmitPolicy - default_checker_input: WorkstreamDefaultCheckerInput - selected_reservation: SelectedPreSubmitReservationFacts - intake: TrustedIntakeSession - - -@dataclass(frozen=True, slots=True) -class PreSubmitCheckerExecutionRequest: - """Exact process-local input supplied to the composition CHECKER adapter.""" - - project_id: UUID - task_id: UUID - assignment_id: UUID - commitment: object - inspection: SubmissionArchiveInspectionResult - manifest: SubmissionManifest - change_gate: SubmissionChangeGateResult - packet: SubmissionPacketView - prepared_generation_id: UUID - storage_scheme: str - external_policy: LockedExternalPreSubmitPolicy - default_checker_input: WorkstreamDefaultCheckerInput - attempt_id: UUID - attempt_request_digest: str - - -class PreSubmitExternalGrantPort(Protocol): - """Issue one callback-scoped grant from genuine prepared ART custody.""" - - def issue( - self, - request: ExternalCheckerExecutionRequest, - workspace: Path, - ) -> AbstractContextManager[ExternalCheckerMaterialGrant]: ... - - -@dataclass(frozen=True, slots=True) -class _SelectedGrantClaim: - """Minimum genuine selected-run identity required by the ART grant issuer.""" - - attempt_id: UUID - request_digest: str - - -class _PreSubmitExternalGrantIssuer: - """Keep private prepared-artifact authority behind a typed callback port.""" - - def __init__( - self, - *, - preparation: ArtifactPreparationService, - prepared: PreparedArtifact, - request: PreparedBundleMaterializationRequest, - claim: _SelectedGrantClaim, - ) -> None: - self._preparation = preparation - self._prepared = prepared - self._request = request - self._claim = claim - - @contextmanager - def issue( - self, - request: ExternalCheckerExecutionRequest, - workspace: Path, - ): - """Bind the service grant to exact claim, manifest and prepared bytes.""" - checked = ExternalCheckerExecutionRequest.model_validate(request) - identity = checked.identity - source = self._request - project_id = source.selected_reservation.project_id - if ( - not isinstance(identity, PreSubmitExternalCheckerIdentity) - or identity.project_id != project_id - or identity.task_id != source.task_id - or identity.assignment_id != source.assignment_id - or identity.prepared_generation_id != source.prepared_artifact.generation_id - or identity.attempt_id != self._claim.attempt_id - or identity.attempt_request_digest != self._claim.request_digest - or len(checked.materials) != 1 - or not isinstance(checked.materials[0], PreSubmitExternalCheckerMaterial) - ): - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - material = checked.materials[0] - commitment = source.prepared_artifact.commitment - if ( - material.prepared_generation_id != source.prepared_artifact.generation_id - or material.attempt_id != self._claim.attempt_id - or material.attempt_request_digest != self._claim.request_digest - or material.archive_sha256 != commitment.sha256 - or material.archive_byte_count != commitment.byte_count - or material.semantic_manifest_sha256 != source.manifest.sha256 - or material.media_type != commitment.media_type - ): - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - directories = tuple( - item.normalized_path - for item in source.manifest.entries - if item.entry_type.value == "directory" - ) - files = tuple( - ExternalMaterialFile( - normalized_path=item.normalized_path, - byte_count=item.byte_count, - sha256=item.sha256 or "", - executable=bool(item.executable), - ) - for item in source.manifest.entries - if item.entry_type.value == "file" - ) - grant_request = ExternalMaterialGrantRequest( - request_digest=checked.request_digest, - prepared_generation_id=str(identity.prepared_generation_id), - attempt_id=str(identity.attempt_id), - attempt_request_digest=identity.attempt_request_digest, - archive_sha256=material.archive_sha256, - archive_byte_count=material.archive_byte_count, - semantic_manifest_sha256=material.semantic_manifest_sha256, - directories=directories, - files=files, - ) - with self._preparation.external_material_grant( - self._prepared, workspace, grant_request - ) as grant: - yield ExternalCheckerMaterialGrant( - grant_id=grant.grant_id, - binding_digest=grant.binding_digest, - source=grant, - ) - - -class _PreSubmitMaterialView: - """Keep verified reads and the opaque PRE grant inside one ART callback.""" - - def __init__(self, tree, *, grants, workspace) -> None: - self._tree, self._grants, self._workspace = tree, grants, workspace - self._closed = False - - def close(self) -> None: - self._closed = True - - def _require_open(self) -> None: - if self._closed: - raise RuntimeError("pre-submit material view is closed") - - @property - def entries(self) -> tuple[SubmissionMaterialEntry, ...]: - self._require_open() - return tuple( - SubmissionMaterialEntry( - item.normalized_path, - item.entry_type.value, - item.byte_count, - item.sha256, - item.executable, - ) - for item in self._tree.entries - ) - - def read_file(self, normalized_path: str, *, maximum_bytes: int) -> bytes: - self._require_open() - return self._tree.read_file(normalized_path, maximum_bytes=maximum_bytes) - - def external_checker_grant(self, request): - self._require_open() - return self._grants.issue(request, self._workspace) - - -class PreSubmitCheckerProcessor(Protocol): - """Async processor built by the composition-root CHECKER adapter.""" - - def abort(self) -> None: ... - - async def process( - self, material: PreSubmitMaterialView, default: WorkstreamDefaultCheckerResult, - ) -> SelectedPreSubmitExecutionFacts: ... - - -class PreSubmitCheckerExecutionFactory(Protocol): - """Build one process-local CHECKER processor without private imports in ART.""" - - def build(self, request: PreSubmitCheckerExecutionRequest) -> PreSubmitCheckerProcessor: ... - - -class _TrustedPreSubmitProcessor: - """Keep export, default, cleanup and project execution in one ART callback.""" - - def __init__(self, *, request, checker, limits, grants) -> None: - self._request, self._checker, self._limits, self._grants = request, checker, limits, grants - self._aborted = False - self._view = None - self._active = None - self.intake_cleanup_confirmed = False - - def abort(self) -> None: - self._aborted = True - self._request.intake.abort() - self._checker.abort() - if self._view is not None: - self._view.close() - if self._active is not None: - self._active.cancel() - - async def process(self, reader, workspace) -> SelectedPreSubmitExecutionFacts: - del reader # The retained ZIP is never parsed by the host projection. - request = self._request - projection = exported_submission_tree( - request.intake.export, workspace, expected=request.inspection, limits=self._limits, - ) - tree = await asyncio.to_thread(projection.__enter__) - try: - if self._aborted: - raise asyncio.CancelledError - self._view = _PreSubmitMaterialView(tree, grants=self._grants, workspace=workspace) - reservation = request.selected_reservation - binding = TrustedDefaultBinding( - attempt_id=reservation.attempt_id, - attempt_request_digest=reservation.request_digest, - policy_sha256=reservation.policy_sha256, - semantic_manifest_sha256=reservation.semantic_manifest_sha256, - default_input_sha256=reservation.default_input_sha256, - ) - self._active = asyncio.create_task(request.intake.evaluate_default(binding, request.default_checker_input)) - default = await self._active - await request.intake.close() - self.intake_cleanup_confirmed = True - if self._aborted: - raise asyncio.CancelledError - return await self._checker.process(self._view, default) - except ExternalServiceAdapterError as exc: - raise SelectedPreSubmitInfrastructureUnavailable("implementation_unavailable") from exc - finally: - self._active = None - if self._view is not None: - self._view.close() - await await_cancellation_resistant(asyncio.to_thread(projection.__exit__, None, None, None)) - - -@dataclass(frozen=True, slots=True) -class PreSubmitMaterializationPreparationFacts: - """Exact scalar facts available before any ZIP inspection.""" - - task_id: UUID - assignment_id: UUID - project_id: UUID - guide_id: UUID - guide_version: str - source_snapshot_id: UUID - source_snapshot_hash: str - submission_artifact_policy_id: UUID - submission_artifact_policy_hash: str - checker_policy_id: UUID - checker_policy_hash: str - prepared_generation_id: UUID - plan_sha256: str - catalogue_manifest_sha256: str - archive_sha256: str - archive_byte_count: int - storage_scheme: str - - -@final -@dataclass(frozen=True, slots=True) -class PreSubmitMaterializationAuthorityFacts(PreSubmitMaterializationPreparationFacts): - """Exact inspected resource facts consumed before scratch exposure.""" - - semantic_manifest_sha256: str - - @property - def preparation(self) -> PreSubmitMaterializationPreparationFacts: - """Return the exact pre-inspection projection of the final facts.""" - return PreSubmitMaterializationPreparationFacts( - task_id=self.task_id, - assignment_id=self.assignment_id, - project_id=self.project_id, - guide_id=self.guide_id, - guide_version=self.guide_version, - source_snapshot_id=self.source_snapshot_id, - source_snapshot_hash=self.source_snapshot_hash, - submission_artifact_policy_id=self.submission_artifact_policy_id, - submission_artifact_policy_hash=self.submission_artifact_policy_hash, - checker_policy_id=self.checker_policy_id, - checker_policy_hash=self.checker_policy_hash, - prepared_generation_id=self.prepared_generation_id, - plan_sha256=self.plan_sha256, - catalogue_manifest_sha256=self.catalogue_manifest_sha256, - archive_sha256=self.archive_sha256, - archive_byte_count=self.archive_byte_count, - storage_scheme=self.storage_scheme, - ) - - -class PreSubmitMaterializationAuthorization(Protocol): - """Adapter over AUTH's opaque transaction-bound prepared capability.""" - - async def prepare( - self, - *, - facts: PreSubmitMaterializationPreparationFacts, - idempotency_key: UUID, - ) -> object: - """Prepare an opaque capability before any submitted byte is inspected.""" - ... - - async def consume( - self, - *, - prepared_authorization: object, - facts: PreSubmitMaterializationAuthorityFacts, - ) -> None: - """Consume the capability against the server-computed final facts.""" - ... - - -class DenyPreSubmitMaterializationAuthorization: - """Keep production byte access unavailable until XINT-06A activation.""" - - async def prepare( - self, - *, - facts: PreSubmitMaterializationPreparationFacts, - idempotency_key: UUID, - ) -> object: - """Deny capability preparation while the production adapter is absent.""" - del facts, idempotency_key - raise ArtifactAuthorityDeniedError( - "pre-submit checker input materialization is unavailable" - ) - - async def consume( - self, - *, - prepared_authorization: object, - facts: PreSubmitMaterializationAuthorityFacts, - ) -> None: - """Deny capability consumption while the production adapter is absent.""" - del prepared_authorization, facts - raise ArtifactAuthorityDeniedError( - "pre-submit checker input materialization is unavailable" - ) - - -class PreparedBundleMaterializationService: - """Authorize, project, execute, and clean one process-local bundle.""" - - def __init__( - self, - *, - session: AsyncSession, - authorization: PreSubmitMaterializationAuthorization, - preparation: ArtifactPreparationService, - checker_execution: PreSubmitCheckerExecutionFactory, - storage_scheme: str, - archive_limits: SubmissionArchiveLimits, - ) -> None: - """Compose the bounded materializer from its AUTH and ART dependencies.""" - self._session = session - self._authorization = authorization - self._preparation = preparation - self._checker_execution = checker_execution - if storage_scheme not in ALLOWED_PRE_SUBMIT_STORAGE_SCHEMES: - raise ValueError("pre-submit materializer storage scheme is invalid") - self._storage_scheme = storage_scheme - self._archive_limits = archive_limits - - - async def materialize_selected_pre_submit( - self, - request: PreparedBundleMaterializationRequest, - *, - run_id: UUID, - lease: SelectedPreSubmitLeaseFacts, - execution_authority: SelectedPreSubmitExecutionAuthority, - ) -> SelectedPreSubmitExecutionFacts: - """Execute the committed external policy lease against genuine prepared bytes.""" - if self._session.in_transaction(): - raise RuntimeError("selected pre-submit execution requires no transaction") - checked = execution_authority.consume(run_id=run_id, lease=lease) - reservation = checked.reservation - commitment = request.prepared_artifact.commitment - if ( - run_id != reservation.attempt_id - or request.task_id != reservation.task_id - or request.assignment_id != reservation.assignment_id - or request.selected_reservation != reservation - or request.prepared_artifact.generation_id != reservation.prepared_generation_id - or request.external_policy is None - or request.external_policy.policy_sha256 != reservation.policy_sha256 - or request.default_checker_input is None - or canonical_json_hash(workstream_default_input_body(request.default_checker_input)) - != reservation.default_input_sha256 - or commitment.sha256 != reservation.archive_sha256 - or commitment.byte_count != reservation.archive_byte_count - or request.manifest.sha256 != reservation.semantic_manifest_sha256 - ): - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - processor = self._checker_execution.build( - PreSubmitCheckerExecutionRequest( - project_id=reservation.project_id, - task_id=request.task_id, - assignment_id=request.assignment_id, - commitment=commitment, - inspection=request.inspection, - manifest=request.manifest, - change_gate=request.change_gate, - packet=request.packet, - prepared_generation_id=request.prepared_artifact.generation_id, - storage_scheme=self._storage_scheme, - external_policy=request.external_policy, - default_checker_input=request.default_checker_input, - attempt_id=run_id, - attempt_request_digest=reservation.request_digest, - ) - ) - trusted_processor = _TrustedPreSubmitProcessor( - request=request, checker=processor, limits=self._archive_limits, - grants=_PreSubmitExternalGrantIssuer( - preparation=self._preparation, prepared=request.prepared_artifact, - request=request, claim=_SelectedGrantClaim(run_id, reservation.request_digest), - ), - ) - try: - result = await self._preparation._process_prepared_submission( - request.prepared_artifact, - trusted_processor, - reserved_bytes=request.manifest.total_expanded_bytes, - maximum_entries=request.manifest.entry_count + 1, - ) - except ArtifactPreparationDeadlineError as exc: - # ART has drained the callback and verified scratch cleanup. Only a - # confirmed intake close permits immediate terminal finalization. - if not trusted_processor.intake_cleanup_confirmed: - raise - raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded") from exc - if type(result) is not SelectedPreSubmitExecutionFacts: - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - return result - - async def authorize_inspected(self, request: PreparedBundleMaterializationRequest) -> None: - """Authorize inspected custody for reservation without invoking checker members.""" - await self._authorization.consume( - prepared_authorization=request.prepared_authorization, - facts=self._authority_facts(request), - ) - - - async def prepare_selected_authorization( - self, - *, - task: TaskSubmissionContextFacts, - project: ProjectLockedPolicyContextFacts, - prepared_artifact: PreparedArtifact, - external_policy: LockedExternalPreSubmitPolicy, - idempotency_key: UUID, - ) -> object: - """Prepare selected material authority before inspecting contributor bytes.""" - references = task.locked_project_context - commitment = prepared_artifact.commitment - if ( - task.task_id is None - or task.assignment_id is None - or references.project_id != project.project_id - or references.guide_version != project.guide_version - or references.source_snapshot_id != project.source_snapshot_id - or references.source_snapshot_hash != project.source_snapshot_hash - or references.effective_policy_id != project.effective_policy_id - or references.effective_policy_hash != project.effective_policy_hash - or references.pre_submit_policy_id != project.pre_submit_policy_id - or references.pre_submit_policy_bundle_hash != project.pre_submit_policy_bundle_hash - or external_policy.policy_sha256 - != canonical_json_hash( - external_policy.model_dump(mode="json", exclude={"policy_sha256"}) - ) - or external_policy.workstream_default.behavior_sha256 - != WORKSTREAM_DEFAULT_BEHAVIOR_SHA256 - ): - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - facts = PreSubmitMaterializationPreparationFacts( - task_id=task.task_id, - assignment_id=task.assignment_id, - project_id=project.project_id, - guide_id=project.guide_id, - guide_version=project.guide_version, - source_snapshot_id=project.source_snapshot_id, - source_snapshot_hash=project.source_snapshot_hash, - submission_artifact_policy_id=project.effective_policy_id, - submission_artifact_policy_hash=project.effective_policy_hash, - checker_policy_id=project.pre_submit_policy_id, - checker_policy_hash=project.pre_submit_policy_bundle_hash, - prepared_generation_id=prepared_artifact.generation_id, - plan_sha256=external_policy.policy_sha256, - catalogue_manifest_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - archive_sha256=commitment.sha256, - archive_byte_count=commitment.byte_count, - storage_scheme=self._storage_scheme, - ) - return await self._authorization.prepare( - facts=facts, - idempotency_key=idempotency_key, - ) - - def _authority_facts( - self, - request: PreparedBundleMaterializationRequest, - ) -> PreSubmitMaterializationAuthorityFacts: - """Build final authority facts from the canonical inspected manifest.""" - preparation = self._preparation_facts( - task_id=request.task_id, - assignment_id=request.assignment_id, - submission_artifact_policy_id=request.submission_artifact_policy_id, - checker_policy_id=request.checker_policy_id, - prepared_artifact=request.prepared_artifact, - external_policy=request.external_policy, - selected_reservation=request.selected_reservation, - ) - if ( - request.manifest != request.change_gate.manifest - or build_submission_manifest(request.inspection) != request.manifest - or request.prepared_artifact.commitment.sha256 != request.change_gate.archive_sha256 - or request.prepared_artifact.commitment.byte_count - != request.change_gate.archive_byte_count - ): - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - return PreSubmitMaterializationAuthorityFacts( - **asdict(preparation), - semantic_manifest_sha256=request.manifest.sha256, - ) - - def _preparation_facts( - self, - *, - task_id: UUID, - assignment_id: UUID, - submission_artifact_policy_id: UUID, - checker_policy_id: UUID, - prepared_artifact: PreparedArtifact, - external_policy: LockedExternalPreSubmitPolicy, - selected_reservation: SelectedPreSubmitReservationFacts, - ) -> PreSubmitMaterializationPreparationFacts: - """Build pre-inspection facts from locked lineage and byte commitment.""" - lineage = selected_reservation.admission_lineage - commitment = prepared_artifact.commitment - if ( - lineage is None - or external_policy is None - or task_id != selected_reservation.task_id - or assignment_id != selected_reservation.assignment_id - or prepared_artifact.generation_id != selected_reservation.prepared_generation_id - or submission_artifact_policy_id != lineage.effective_policy_id - or checker_policy_id != lineage.pre_submit_policy_id - or external_policy.policy_sha256 != selected_reservation.policy_sha256 - or commitment.sha256 != selected_reservation.archive_sha256 - or commitment.byte_count != selected_reservation.archive_byte_count - ): - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - return PreSubmitMaterializationPreparationFacts( - task_id=task_id, - assignment_id=assignment_id, - project_id=selected_reservation.project_id, - guide_id=lineage.guide_id, - guide_version=lineage.guide_version, - source_snapshot_id=lineage.source_snapshot_id, - source_snapshot_hash=lineage.source_snapshot_sha256, - submission_artifact_policy_id=submission_artifact_policy_id, - submission_artifact_policy_hash=lineage.effective_policy_sha256, - checker_policy_id=checker_policy_id, - checker_policy_hash=lineage.pre_submit_policy_sha256, - prepared_generation_id=prepared_artifact.generation_id, - plan_sha256=selected_reservation.policy_sha256, - catalogue_manifest_sha256=(selected_reservation.default_behavior_sha256), - archive_sha256=commitment.sha256, - archive_byte_count=commitment.byte_count, - storage_scheme=self._storage_scheme, - ) diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py index 071f73eb0..585a166e0 100644 --- a/backend/scripts/behavior_ownership.py +++ b/backend/scripts/behavior_ownership.py @@ -567,6 +567,11 @@ ARCH_04B_SEAM_REMOVED_TARGETS = frozenset({ "backend/app/modules/artifacts/api/submission_materialization.py", }) +SUBMISSION_PREPARATION_RETIRED_TARGETS = frozenset({ + "backend/app/modules/artifacts/submission_authorization.py", + "backend/app/modules/artifacts/submission_custody.py", + "backend/app/modules/artifacts/submission_materialization.py", +}) ARCH_04A_POST_SUBMIT_TARGETS = frozenset( { "backend/app/modules/checkers/api/post_submit.py", @@ -1181,7 +1186,7 @@ def _validate_additive_partition_transition( ] if ( trusted_targets != sorted(trusted_targets) - or removed - (NEUTRAL_GUIDE_RUNTIME_REMOVED_TARGETS | REV_04C_REMOVED_TARGETS | ARCH_04D2_REMOVED_TARGETS | ARCH_03D_REMOVED_TARGETS | TASK_CHECKER_CLEANUP_REMOVED_TARGETS | ARCH_03C2_REMOVED_TARGETS | OUTBOX_IDENTITY_REMOVED_TARGETS | V01_BASELINE_REMOVED_TARGETS | POL_03B_REMOVED_TARGETS | POL_04B_REMOVED_TARGETS | POL_05A_REMOVED_TARGETS | ARCH_03A_GUIDE_CONTEXT_REMOVED_TARGETS | ARCH_04B_SEAM_REMOVED_TARGETS | PILOT_04_RETIRED_CATALOGUE_TARGETS | FORGE_PROOF_FACTS_REMOVED_TARGETS | SHARED_ADAPTER_PACKAGE_REMOVED_TARGETS | AWS_ARTIFACT_PROOF_REMOVED_TARGETS | SUBMISSION_INTAKE_REMOVED_TARGETS) + or removed - (NEUTRAL_GUIDE_RUNTIME_REMOVED_TARGETS | REV_04C_REMOVED_TARGETS | ARCH_04D2_REMOVED_TARGETS | ARCH_03D_REMOVED_TARGETS | TASK_CHECKER_CLEANUP_REMOVED_TARGETS | ARCH_03C2_REMOVED_TARGETS | OUTBOX_IDENTITY_REMOVED_TARGETS | V01_BASELINE_REMOVED_TARGETS | POL_03B_REMOVED_TARGETS | POL_04B_REMOVED_TARGETS | POL_05A_REMOVED_TARGETS | ARCH_03A_GUIDE_CONTEXT_REMOVED_TARGETS | ARCH_04B_SEAM_REMOVED_TARGETS | SUBMISSION_PREPARATION_RETIRED_TARGETS | PILOT_04_RETIRED_CATALOGUE_TARGETS | FORGE_PROOF_FACTS_REMOVED_TARGETS | SHARED_ADAPTER_PACKAGE_REMOVED_TARGETS | AWS_ARTIFACT_PROOF_REMOVED_TARGETS | SUBMISSION_INTAKE_REMOVED_TARGETS) or [current_by_target[item["target"]] for item in retained_trusted] != retained_trusted ): diff --git a/backend/tests/architecture/test_module_boundaries.py b/backend/tests/architecture/test_module_boundaries.py index 88afd98b4..7fea151a1 100644 --- a/backend/tests/architecture/test_module_boundaries.py +++ b/backend/tests/architecture/test_module_boundaries.py @@ -328,7 +328,7 @@ def test_checker_to_art_public_import_would_close_a_cycle(tmp_path: Path) -> Non ) _write( tmp_path / "backend/app/modules/checkers/future_execution.py", - "from app.modules.artifacts.api import SubmissionBundlePreparationCommand\n", + "from app.modules.artifacts.api import SubmissionBundlePreparationStatus\n", ) _, graph, _ = boundary.scan(tmp_path, boundary.load_registry(registry_path)) assert graph["artifacts"] == {"checkers"} diff --git a/backend/tests/checkers/external/test_selected_intake_lifecycle.py b/backend/tests/checkers/external/test_selected_intake_lifecycle.py index 277cfac38..e4d2019cb 100644 --- a/backend/tests/checkers/external/test_selected_intake_lifecycle.py +++ b/backend/tests/checkers/external/test_selected_intake_lifecycle.py @@ -1,170 +1,10 @@ -"""Trusted intake cleanup gates ordered PRE execution and deadline finalization.""" +"""Shared trusted-intake scratch and cancellation cleanup proofs.""" -from contextlib import contextmanager -from datetime import UTC, datetime, timedelta from types import SimpleNamespace import pytest -from tests.trusted_intake_fixtures import assert_sealed_export - -from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter -from app.core.hashing import canonical_json_hash -from app.core.identifiers import new_record_id from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits -from app.modules.artifacts.submission_materialization import ( - PreparedBundleMaterializationService, _PreSubmitExternalGrantIssuer, _SelectedGrantClaim, -) -from app.modules.checkers.api.external_policy import LockedExternalPreSubmitPolicy -from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitInfrastructureUnavailable, SelectedPreSubmitLeaseFacts, -) -from tests.checkers.external.test_selected_pre_submit import ( - _request, _policy, _execution_context, _processor, _Execution, _GrantIssuer, -) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("cleanup_confirmed", [True, False]) -async def test_intake_cleanup_precedes_both_project_bindings(tmp_path, cleanup_confirmed): - from workstream_external_services import ExternalServiceUnavailableError - - request, _, manager, preparation = await _request(tmp_path) - first = _policy() - bindings = (first.entries[0], first.entries[0].model_copy(update={"requirement_id": "project.second_rule"})) - body = {"schema_version": "external_pre_submit_policy.v1", - "workstream_default": first.workstream_default.model_dump(mode="json"), - "entries": [binding.model_dump(mode="json") for binding in bindings]} - policy = LockedExternalPreSubmitPolicy(workstream_default=first.workstream_default, - entries=bindings, policy_sha256=canonical_json_hash(body)) - identity, material, default_input = _execution_context(request, policy) - binding = {"attempt_id": request.selected_reservation.attempt_id, - "attempt_request_digest": request.selected_reservation.request_digest} - identity, material = identity.model_copy(update=binding), material.model_copy(update=binding) - events = [] - close = request.intake.close - - async def confirm_cleanup(): - assert request.intake.events[-1] == "default" - events.append("cleanup") - if not cleanup_confirmed: - raise ExternalServiceUnavailableError() - await close() - - request.intake.close = confirm_cleanup - - class OrderedExecution(_Execution): - async def execute(self, command, grant): - assert request.intake.closed - assert events[0] == "cleanup" - events.append(command.input["requirement_id"]) - return await super().execute(command, grant) - - issuer = _PreSubmitExternalGrantIssuer( - preparation=preparation, prepared=request.prepared_artifact, request=request, - claim=_SelectedGrantClaim(request.selected_reservation.attempt_id, - request.selected_reservation.request_digest), - ) - - class RealGrants(_GrantIssuer): - @contextmanager - def issue(self, command, workspace): - self.requests.append(command) - with issuer.issue(command, workspace) as grant: - yield grant - assert_sealed_export(workspace) - - grants, execution = RealGrants(), OrderedExecution("passed") - processor = _processor(request=request, policy=policy, default_input=default_input, - identity=identity, material=material, grants=grants, execution=execution) - try: - operation = preparation._process_prepared_submission( - request.prepared_artifact, processor, reserved_bytes=request.manifest.total_expanded_bytes, - maximum_entries=request.manifest.entry_count) - if cleanup_confirmed: - result = await operation - assert result.eligible - assert [member.requirement_id for member in result.external_members] == [binding.requirement_id for binding in bindings] - assert events == ["cleanup", "project.archive_rules", "project.second_rule"] - else: - with pytest.raises(SelectedPreSubmitInfrastructureUnavailable): - await operation - assert events == ["cleanup"] - assert grants.requests == execution.requests == [] - assert list((tmp_path / "scratch" / "workspaces").iterdir()) == [] - finally: - await request.prepared_artifact.close() - await close() - manager.close() - - -@pytest.mark.asyncio -@pytest.mark.parametrize("intake_cleanup_confirmed", [False, True]) -async def test_preparation_deadline_finalizes_only_after_intake_cleanup(tmp_path, intake_cleanup_confirmed): - import asyncio - from app.modules.artifacts.preparation import ArtifactPreparationDeadlineError - from app.modules.artifacts.selected_pre_submit_execution import SelectedPreSubmitExecutionService - from tests.checkers.external.test_selected_pre_submit_service import _Session, _Authority, _Coordinator - - request, _, manager, preparation = await _request(tmp_path) - reservation = request.selected_reservation - lease = SelectedPreSubmitLeaseFacts( - reservation=reservation, lease_id=new_record_id(), lease_generation=1, - lease_expires_at=datetime.now(UTC) + timedelta(minutes=2), - ) - entered, drained = asyncio.Event(), asyncio.Event() - - async def blocked(*args): - entered.set() - try: - await asyncio.Event().wait() - finally: - drained.set() - - execution = _Execution("passed") - if intake_cleanup_confirmed: - execution.execute = blocked - else: - request.intake.evaluate_default = blocked - order = [] - session = _Session(order) - - class Coordinator(_Coordinator): - async def committed_execution(self, **values): - await super().committed_execution(**values) - return SimpleNamespace(consume=lambda **kwargs: lease) - - materialization = PreparedBundleMaterializationService( - session=session, authorization=SimpleNamespace(), preparation=preparation, - checker_execution=SelectedPreSubmitCheckerExecutionAdapter(external_execution=execution), - storage_scheme="s3", archive_limits=SubmissionArchiveLimits(), - ) - service = SelectedPreSubmitExecutionService( - session=session, coordinator=Coordinator(session, order, lease), - authority=_Authority(session, order), materialization=materialization, - ) - # Exercise ART's actual absolute-deadline cancellation and scratch drain. - preparation._active[request.prepared_artifact._binding].deadline = asyncio.get_running_loop().time() + 2 - session.in_transaction = lambda: session.active - try: - operation = service.execute(reservation=reservation, materialization=request) - if intake_cleanup_confirmed: - completion = await operation - assert completion.terminal.infrastructure_failure_code == "deadline_exceeded" - assert completion.terminal.execution is None - assert order.count("finalize") == 1 - assert request.intake.closed - else: - with pytest.raises(ArtifactPreparationDeadlineError): - await operation - assert "finalize" not in order - assert entered.is_set() and drained.is_set() - assert list((tmp_path / "scratch" / "workspaces").iterdir()) == [] - finally: - await request.intake.close() - await request.prepared_artifact.close() - manager.close() - @pytest.mark.asyncio @pytest.mark.parametrize("body_failure", ["deadline", "rejection", "cancellation", None]) diff --git a/backend/tests/checkers/external/test_selected_pre_submit.py b/backend/tests/checkers/external/test_selected_pre_submit.py index aa67fe4b8..72e9af3b0 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit.py +++ b/backend/tests/checkers/external/test_selected_pre_submit.py @@ -1,46 +1,33 @@ -"""Selected default and project PRE images share one verified ART callback.""" +"""Current selected PRE revision binding and retained admission publisher proofs.""" from __future__ import annotations -from app.adapters.artifacts import selected_pre_submit_source_contracts - -from tests.trusted_intake_fixtures import LocalIntakeSession -from app.modules.artifacts.trusted_intake import TrustedArchiveInspector -from app.modules.artifacts.submission_materialization import _TrustedPreSubmitProcessor - -from contextlib import contextmanager, nullcontext +from contextlib import nullcontext from dataclasses import replace -from datetime import UTC, datetime, timedelta -from io import BytesIO -from pathlib import Path +from datetime import UTC, datetime from types import SimpleNamespace -from typing import cast -from unittest.mock import AsyncMock, Mock, patch -import zipfile +from unittest.mock import AsyncMock, Mock + import pytest -from app.adapters.checkers import configured_external_checker_execution -from app.core.config import Settings +from app.adapters.artifacts import selected_pre_submit_source_contracts from app.core.hashing import canonical_json_hash from app.core.identifiers import new_record_id -from app.interfaces.external_checker_execution import ( - ExternalCheckerExecutionResponse, - ExternalCheckerIsolationReceipt, - ExternalCheckerMaterialGrant, +from app.modules.artifacts.selected_pre_submit_admission import ( + bind_selected_pre_submit_admission, + build_selected_pre_submit_reservation, + selected_pre_submit_attempt_request_digest, ) -from app.modules.checkers.api.default_checker import ( - WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - WorkstreamDefaultCheckerInput, - workstream_default_input_sha256, +from app.modules.artifacts.submission_admission import ( + SubmissionBundleAdmissionPublicationError, + SubmissionBundleAdmissionPublisher, ) +from app.modules.artifacts.submission_manifest import SubmissionCanonicalPredecessor from app.modules.checkers.api.external import ( PRE_SUBMIT_INPUT_SCHEMA_ID, ExternalCheckerRegistryEntry, ExternalCheckerSchema, - PreSubmitExternalCheckerIdentity, - PreSubmitExternalCheckerMaterial, external_checker_json_hash, - make_external_checker_execution_result, ) from app.modules.checkers.api.external_policy import ( LockedExternalCheckerBinding, @@ -49,127 +36,18 @@ LockedExternalPreSubmitPolicy, LockedWorkstreamDefault, ) -from app.modules.checkers.api.materialization import SubmissionMaterialEntry from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitAdmissionLineage, SelectedPreSubmitLeaseFacts, - SelectedPreSubmitInfrastructureUnavailable, SelectedPreSubmitReservationFacts, - SelectedPreSubmitTerminalFacts, ) -from app.modules.checkers.selected_pre_submit_execution import SelectedPreSubmitProcessor -from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter -from app.modules.artifacts.preparation import ( - HARD_MAXIMUM_ARTIFACT_BYTES, - ArtifactPreparationLimits, - ArtifactPreparationService, - ArtifactScratchManager, -) -from app.modules.artifacts.selected_pre_submit_admission import ( - bind_selected_pre_submit_admission, - build_selected_pre_submit_reservation, - selected_pre_submit_attempt_request_digest, -) -from app.modules.artifacts.submission_admission import ( - SubmissionBundleAdmissionPublicationError, - SubmissionBundleAdmissionPublisher, - require_revision_preparation_acknowledgement, -) -from app.modules.artifacts.api import SubmissionBundlePreparationRejected -from app.modules.artifacts.api.submission_archive import ( - SubmissionArchiveLimits, -) -from app.modules.artifacts.submission_archive import ( - SubmissionArchiveInspector, -) -from app.modules.artifacts.api.submission_manifest import ( - build_submission_manifest, -) -from app.modules.artifacts.submission_manifest import ( - SubmissionCanonicalPredecessor, - semantic_manifest_identity, - evaluate_submission_change, -) -from app.modules.artifacts.submission_materialization import ( - PreparedBundleMaterializationRequest, - PreparedBundleMaterializationService, -) -from app.modules.authorization.prepared import PreparedAuthorizationHandle -from app.modules.checkers.api.pre_submit_material import SubmissionPacketView +from app.modules.tasks.api.submission_context import require_revision_acknowledgement +from app.modules.tasks.api import TaskSubmissionContextUnavailable from tests.checkers.external.support import SHA, registry_entry - -async def _bytes(value: bytes): - yield value - - -def _archive(primary_bytes: bytes) -> bytes: - output = BytesIO() - with zipfile.ZipFile(output, "w") as archive: - for name, value in ( - ("task.toml", primary_bytes), - ("evidence/results", b"verified\n"), - ): - entry = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) - archive.writestr(entry, value) - return output.getvalue() - - def _hex_sha(character: str) -> str: return "sha256:" + character * 64 -def _selected_admission_reservation(): - manifest = {"schema_version": "submission_manifest.v1", "entries": []} - post_policy = {"schema_version": "external_post_submit_policy.v1", "entries": []} - post_policy_sha256 = canonical_json_hash(post_policy) - post_policy["policy_sha256"] = post_policy_sha256 - lineage = SelectedPreSubmitAdmissionLineage( - predecessor_submission_id=None, - predecessor_submission_version=None, - checker_remediation_manifest_id=None, - guide_id=new_record_id(), - guide_version="v2", - source_snapshot_id=new_record_id(), - source_snapshot_sha256=_hex_sha("1"), - locked_guide_sha256=_hex_sha("2"), - effective_policy_id=new_record_id(), - effective_policy_sha256=_hex_sha("3"), - pre_submit_policy_id=new_record_id(), - pre_submit_policy_sha256=_hex_sha("4"), - effective_plan_sha256=_hex_sha("5"), - rules_sha256=_hex_sha("8"), - external_checker_policies_sha256=_hex_sha("9"), - post_submit_policy_sha256=post_policy_sha256, - post_submit_policy_body=post_policy, - locked_policy_context_hash=_hex_sha("6"), - semantic_manifest_id=new_record_id(), - semantic_manifest_body=manifest, - packet_sha256=_hex_sha("7"), - storage_scheme="s3", - ) - selected = SelectedPreSubmitReservationFacts( - actor_profile_id=new_record_id(), - identity_link_id=new_record_id(), - project_id=new_record_id(), - task_id=new_record_id(), - assignment_id=new_record_id(), - attempt_id=new_record_id(), - idempotency_key=new_record_id(), - attempt_request_digest=_hex_sha("8"), - prepared_generation_id=new_record_id(), - policy_sha256=lineage.effective_plan_sha256, - default_behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - default_input_sha256=_hex_sha("9"), - archive_sha256=_hex_sha("a"), - archive_byte_count=25, - semantic_manifest_sha256=canonical_json_hash(manifest), - execution_budget_ms=120_000, - admission_lineage=lineage, - source_contracts=selected_pre_submit_source_contracts()) - return manifest, post_policy, selected - - def test_revision_acknowledgement_changes_selected_request_and_retains_old_bytes() -> None: """A new acknowledgement is frozen; old selected requests keep their digest.""" from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation @@ -251,25 +129,20 @@ def test_revision_acknowledgement_requires_exact_current_preparation() -> None: checker_remediation_manifest_id=manifest_id, revision_context=revision, ) - request = SimpleNamespace( - revision_preparation_id=str(preparation_id), - revision_preparation_sha256=_hex_sha("c"), - ) - require_revision_preparation_acknowledgement(task, request) - with pytest.raises(SubmissionBundlePreparationRejected, match="revision_context_changed"): - require_revision_preparation_acknowledgement( - task, SimpleNamespace(revision_preparation_id=str(new_record_id()), - revision_preparation_sha256=_hex_sha("c")), - ) - with pytest.raises(SubmissionBundlePreparationRejected, match="revision_acknowledgement_required"): - require_revision_preparation_acknowledgement( - task, SimpleNamespace(revision_preparation_id=None, - revision_preparation_sha256=None), - ) - with pytest.raises(SubmissionBundlePreparationRejected, match="revision_acknowledgement_invalid"): - require_revision_preparation_acknowledgement( - SimpleNamespace(predecessor=None), request, + require_revision_acknowledgement(task, str(preparation_id), _hex_sha("c")) + for acknowledged_id, acknowledged_hash, code in ( + (str(new_record_id()), _hex_sha("c"), "revision_context_changed"), + (None, None, "revision_acknowledgement_required"), + (str(preparation_id), _hex_sha("d"), "revision_context_changed"), + ): + with pytest.raises(TaskSubmissionContextUnavailable) as refused: + require_revision_acknowledgement(task, acknowledged_id, acknowledged_hash) + assert refused.value.code == code + with pytest.raises(TaskSubmissionContextUnavailable) as refused: + require_revision_acknowledgement( + SimpleNamespace(predecessor=None), str(preparation_id), _hex_sha("c") ) + assert refused.value.code == "revision_acknowledgement_invalid" def _retained_admission_reservation(): @@ -364,104 +237,6 @@ def _selected_admission_publisher_fixture(selected): return session, job, verification, intent -def _limits() -> ArtifactPreparationLimits: - return ArtifactPreparationLimits( - aggregate_reserved_bytes=2 * HARD_MAXIMUM_ARTIFACT_BYTES, - maximum_files=2, - maximum_concurrency=2, - minimum_free_bytes=0, - reservation_ttl_seconds=30, - total_deadline_seconds=10, - cleanup_margin_seconds=5, - stream_buffer_bytes=1024, - maximum_source_bytes=1024 * 1024, - maximum_workspace_entries=2_000, - ) - - -class _PreparedHandle: - pass - - -async def _request( - tmp_path: Path, - *, - primary_bytes: bytes = b"[task]\nname='proof'\n", -): - inspector = SubmissionArchiveInspector(SubmissionArchiveLimits()) - manager = ArtifactScratchManager(root=tmp_path / "scratch", limits=_limits()) - preparation = ArtifactPreparationService(manager) - prepared = await preparation.prepare( - _bytes(_archive(primary_bytes)), media_type="application/zip" - ) - intake = LocalIntakeSession(inspector) - inspection = await prepared.inspect(TrustedArchiveInspector(intake, prepared.commitment)) - manifest = build_submission_manifest(inspection) - policy = _policy() - packet = SubmissionPacketView( - summary="Completed exact project work.", contributor_attestation="rights_confirmed", - ) - _, _, seed = _selected_admission_reservation() - default_input = WorkstreamDefaultCheckerInput( - archive_sha256=prepared.commitment.sha256, - archive_byte_count=prepared.commitment.byte_count, - archive_media_type="application/zip", - semantic_manifest_sha256=manifest.sha256, - entries=tuple(SubmissionMaterialEntry( - item.normalized_path, item.entry_type.value, item.byte_count, - item.sha256, item.executable, - ) for item in manifest.entries), - predecessor=None, predecessor_exists=False, current_predecessor=None, - current_rules_sha256=seed.admission_lineage.rules_sha256, - predecessor_rules_sha256=None, packet=packet, - ) - reservation = replace( - seed, - prepared_generation_id=prepared.generation_id, - policy_sha256=policy.policy_sha256, - default_input_sha256=workstream_default_input_sha256(default_input), - archive_sha256=prepared.commitment.sha256, - archive_byte_count=prepared.commitment.byte_count, - semantic_manifest_sha256=manifest.sha256, - admission_lineage=replace( - seed.admission_lineage, - effective_plan_sha256=policy.policy_sha256, - semantic_manifest_id=semantic_manifest_identity(manifest.sha256), - semantic_manifest_body=manifest.as_dict(), packet_sha256=packet.sha256, - ), - ) - request = PreparedBundleMaterializationRequest( - prepared_authorization=cast(PreparedAuthorizationHandle, _PreparedHandle()), - task_id=reservation.task_id, assignment_id=reservation.assignment_id, - submission_artifact_policy_id=reservation.admission_lineage.effective_policy_id, - checker_policy_id=reservation.admission_lineage.pre_submit_policy_id, - predecessor_submission_version=None, checker_remediation_manifest_id=None, - prepared_artifact=prepared, inspection=inspection, manifest=manifest, - change_gate=evaluate_submission_change( - commitment=prepared.commitment, manifest=manifest, - predecessor=None, predecessor_exists=False, - ), - packet=packet, external_policy=policy, default_checker_input=default_input, - selected_reservation=reservation, intake=intake, - ) - return request, inspector, manager, preparation - - -def _processor(*, request, policy, default_input, identity, material, grants, execution): - checker = SelectedPreSubmitProcessor( - policy=policy, default_input=default_input, identity=identity, - material=material, execution=execution, - source_contracts=selected_pre_submit_source_contracts()) - request = replace(request, default_checker_input=default_input, external_policy=policy, - selected_reservation=replace(request.selected_reservation, - policy_sha256=policy.policy_sha256, - admission_lineage=replace(request.selected_reservation.admission_lineage, - effective_plan_sha256=policy.policy_sha256, packet_sha256=default_input.packet.sha256), - default_input_sha256=workstream_default_input_sha256(default_input))) - return _TrustedPreSubmitProcessor(request=request, checker=checker, - limits=SubmissionArchiveLimits(), grants=grants) - - def _open_input_schema() -> ExternalCheckerSchema: document = {"type": "object"} return ExternalCheckerSchema( @@ -548,244 +323,6 @@ def _policies() -> LockedExternalCheckerPolicies: ) -class _GrantIssuer: - def __init__(self) -> None: - self.requests = [] - - @contextmanager - def issue(self, request, _workspace): - self.requests.append(request) - yield ExternalCheckerMaterialGrant( - grant_id="extract_" + "a" * 32, - binding_digest="sha256:" + "b" * 64, - ) - - -class _Execution: - def __init__(self, verdict: str) -> None: - self.verdict = verdict - self.requests = [] - - async def execute(self, request, _grant): - self.requests.append(request) - findings = ( - () - if self.verdict == "passed" - else ( - { - "check_id": "project_rule", - "code": "project_rule_failed", - "level": "error", - "message": "Project rule failed.", - }, - ) - ) - result = make_external_checker_execution_result( - request_digest=request.request_digest, - registry_entry_id=request.registry.registry_entry_id, - registry_entry_digest=request.registry.entry_digest, - phase="pre_submit", - outcome="completed", - verdict=self.verdict, - findings=findings, - infrastructure_failure_code=None, - ) - return ExternalCheckerExecutionResponse( - result=result, - isolation=ExternalCheckerIsolationReceipt( - repository="registry.example/workstream/checker", - platform_manifest_digest=request.registry.image_digest, - platform_manifest_media_type=("application/vnd.oci.image.manifest.v1+json"), - platform_manifest_byte_count=1024, - operating_system="linux", - architecture="amd64", - config_image_id=SHA, - runtime="runsc", - isolation_mode="gvisor", - sandbox_uid=65532, - sandbox_gid=65532, - ), - ) - - -def _execution_context(request, policy): - identity = PreSubmitExternalCheckerIdentity( - project_id=request.selected_reservation.project_id, - task_id=request.task_id, - assignment_id=request.assignment_id, - prepared_generation_id=request.prepared_artifact.generation_id, - attempt_id=new_record_id(), - attempt_request_digest=SHA, - effective_plan_sha256=policy.policy_sha256, - ) - material = PreSubmitExternalCheckerMaterial( - role="submission_archive", - prepared_generation_id=identity.prepared_generation_id, - attempt_id=identity.attempt_id, - attempt_request_digest=identity.attempt_request_digest, - archive_sha256=request.prepared_artifact.commitment.sha256, - archive_byte_count=request.prepared_artifact.commitment.byte_count, - semantic_manifest_sha256=request.manifest.sha256, - media_type="application/zip", - ) - entries = tuple( - SubmissionMaterialEntry( - item.normalized_path, - item.entry_type.value, - item.byte_count, - item.sha256, - item.executable, - ) - for item in request.manifest.entries - ) - default_input = WorkstreamDefaultCheckerInput( - archive_sha256=material.archive_sha256, - archive_byte_count=material.archive_byte_count, - archive_media_type=material.media_type, - semantic_manifest_sha256=material.semantic_manifest_sha256, - entries=entries, - predecessor=None, - predecessor_exists=False, - current_predecessor=None, - current_rules_sha256=request.selected_reservation.admission_lineage.rules_sha256, - predecessor_rules_sha256=None, - packet=SubmissionPacketView(summary="", contributor_attestation=""), - ) - return identity, material, default_input - - -def _assert_terminal_round_trip(identity, policy, default_input, material, result) -> None: - now = datetime.now(UTC) - reservation = SelectedPreSubmitReservationFacts( - actor_profile_id=new_record_id(), - identity_link_id=new_record_id(), - project_id=identity.project_id, - task_id=identity.task_id, - assignment_id=identity.assignment_id, - attempt_id=identity.attempt_id, - idempotency_key=new_record_id(), - attempt_request_digest=identity.attempt_request_digest, - prepared_generation_id=identity.prepared_generation_id, - policy_sha256=policy.policy_sha256, - default_behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - default_input_sha256=workstream_default_input_sha256(default_input), - archive_sha256=material.archive_sha256, - archive_byte_count=material.archive_byte_count, - semantic_manifest_sha256=material.semantic_manifest_sha256, - execution_budget_ms=120_000, - source_contracts=selected_pre_submit_source_contracts()) - lease = SelectedPreSubmitLeaseFacts( - reservation=reservation, - lease_id=new_record_id(), - lease_generation=1, - lease_expires_at=now + timedelta(minutes=2), - ) - terminal = SelectedPreSubmitTerminalFacts( - lease=lease, - outcome="completed", - execution=result, - infrastructure_failure_code=None, - queued_at=now, - started_at=now + timedelta(milliseconds=25), - completed_at=now + timedelta(milliseconds=75), - source_contracts=selected_pre_submit_source_contracts()) - assert terminal.canonical_body()["queue_latency_ms"] == 25 - assert terminal.canonical_body()["execution_latency_ms"] == 50 - assert terminal.canonical_body()["request_digest"] == reservation.request_digest - assert terminal.terminal_digest == canonical_json_hash(terminal.canonical_body()) - assert SelectedPreSubmitTerminalFacts.from_canonical_body(terminal.canonical_body(), source_contracts=selected_pre_submit_source_contracts()) == terminal - changed_terminal = terminal.canonical_body() | {"queue_latency_ms": 26} - with pytest.raises(ValueError, match="terminal facts"): - SelectedPreSubmitTerminalFacts.from_canonical_body(changed_terminal, source_contracts=selected_pre_submit_source_contracts()) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("verdict,eligible", [("passed", True), ("failed", False)]) -async def test_selected_pre_runs_default_then_locked_external_image( - tmp_path, verdict: str, eligible: bool -) -> None: - request, inspector, manager, preparation = await _request(tmp_path) - policy = _policy() - identity, material, default_input = _execution_context(request, policy) - grants, execution = _GrantIssuer(), _Execution(verdict) - processor = _processor( - request=request, - policy=policy, - default_input=default_input, - identity=identity, - material=material, - grants=grants, - execution=execution, - ) - try: - result = await preparation._process_prepared_submission( - request.prepared_artifact, - processor, - reserved_bytes=request.manifest.total_expanded_bytes, - maximum_entries=request.manifest.entry_count, - ) - assert result.eligible is eligible - assert result.workstream_default.eligible - assert [item.code for item in result.workstream_default.warnings] == [ - "submission_summary_missing", - "submission_attestation_missing", - ] - assert len(result.external_members) == 1 - assert result.external_members[0].result.verdict == verdict - assert len(grants.requests) == len(execution.requests) == 1 - assert grants.requests[0].request_digest == execution.requests[0].request_digest - assert result.result_digest == canonical_json_hash(result.canonical_body()) - _assert_terminal_round_trip(identity, policy, default_input, material, result) - finally: - await request.prepared_artifact.close() - manager.close() - - -@pytest.mark.asyncio -@pytest.mark.parametrize("external", [False, True]) -async def test_selected_pre_only_requires_project_runtime_for_locked_external_images( - tmp_path, external: bool -) -> None: - request, inspector, manager, preparation = await _request(tmp_path) - policy = _policy() if external else _empty_policy() - identity, material, default_input = _execution_context(request, policy) - grants = _GrantIssuer() - processor = _processor( - request=request, - policy=policy, - default_input=default_input, - identity=identity, - material=material, - grants=grants, - execution=configured_external_checker_execution(Settings()), - ) - try: - if external: - with pytest.raises(SelectedPreSubmitInfrastructureUnavailable) as failure: - await preparation._process_prepared_submission( - request.prepared_artifact, - processor, - reserved_bytes=request.manifest.total_expanded_bytes, - maximum_entries=request.manifest.entry_count, - ) - assert failure.value.code == "implementation_unavailable" - assert len(grants.requests) == 1 - else: - result = await preparation._process_prepared_submission( - request.prepared_artifact, - processor, - reserved_bytes=request.manifest.total_expanded_bytes, - maximum_entries=request.manifest.entry_count, - ) - assert result.eligible is True - assert result.required_external_count == 0 - assert result.external_members == () - assert grants.requests == [] - finally: - await request.prepared_artifact.close() - manager.close() - - @pytest.mark.asyncio @pytest.mark.parametrize("replacement", [False, True]) async def test_selected_pre_terminal_publishes_self_contained_ready_admission( @@ -910,86 +447,6 @@ async def test_selected_pre_task_lock_failure_propagates_before_terminal_reads() session.add.assert_not_called() -@pytest.mark.asyncio -async def test_selected_pre_default_secret_blocker_precedes_external_image( - tmp_path, -) -> None: - request, inspector, manager, preparation = await _request( - tmp_path, - primary_bytes=b"-----BEGIN OPENSSH PRIVATE KEY-----\nencoded", - ) - policy = _policy() - identity = PreSubmitExternalCheckerIdentity( - project_id=request.selected_reservation.project_id, - task_id=request.task_id, - assignment_id=request.assignment_id, - prepared_generation_id=request.prepared_artifact.generation_id, - attempt_id=new_record_id(), - attempt_request_digest=SHA, - effective_plan_sha256=policy.policy_sha256, - ) - material = PreSubmitExternalCheckerMaterial( - role="submission_archive", - prepared_generation_id=identity.prepared_generation_id, - attempt_id=identity.attempt_id, - attempt_request_digest=identity.attempt_request_digest, - archive_sha256=request.prepared_artifact.commitment.sha256, - archive_byte_count=request.prepared_artifact.commitment.byte_count, - semantic_manifest_sha256=request.manifest.sha256, - media_type="application/zip", - ) - entries = tuple( - SubmissionMaterialEntry( - item.normalized_path, - item.entry_type.value, - item.byte_count, - item.sha256, - item.executable, - ) - for item in request.manifest.entries - ) - execution = _Execution("passed") - grants = _GrantIssuer() - processor = _processor( - request=request, - policy=policy, - default_input=WorkstreamDefaultCheckerInput( - archive_sha256=material.archive_sha256, - archive_byte_count=material.archive_byte_count, - archive_media_type=material.media_type, - semantic_manifest_sha256=material.semantic_manifest_sha256, - entries=entries, - predecessor=None, - predecessor_exists=False, - current_predecessor=None, - current_rules_sha256=request.selected_reservation.admission_lineage.rules_sha256, - predecessor_rules_sha256=None, - packet=request.packet, - ), - identity=identity, - material=material, - grants=grants, - execution=execution, - ) - try: - result = await preparation._process_prepared_submission( - request.prepared_artifact, - processor, - reserved_bytes=request.manifest.total_expanded_bytes, - maximum_entries=request.manifest.entry_count, - ) - assert result.eligible is False - assert result.workstream_default.checks[2].failure_code == ( - "high_confidence_secret_detected" - ) - assert result.external_members == () - assert grants.requests == [] - assert execution.requests == [] - finally: - await request.prepared_artifact.close() - manager.close() - - @pytest.mark.asyncio async def test_selected_admission_binds_unchanged_work_to_current_task_rules() -> None: """Bind prior content/rules before inspection, then derive unchanged input in PRE.""" @@ -1080,116 +537,3 @@ async def test_selected_admission_binds_unchanged_work_to_current_task_rules() - assert _change_failure(default_input) is None assert _change_failure(replace(default_input, predecessor_rules_sha256=default_input.current_rules_sha256)) == "submission_archive_unchanged" - - -@pytest.mark.asyncio -async def test_selected_factory_uses_request_bound_art_grant(tmp_path) -> None: - request, inspector, manager, preparation = await _request(tmp_path) - reservation = request.selected_reservation - lease = SelectedPreSubmitLeaseFacts( - reservation=reservation, lease_id=new_record_id(), lease_generation=1, - lease_expires_at=datetime.now(UTC) + timedelta(minutes=2), - ) - transaction = True - session = SimpleNamespace(in_transaction=lambda: transaction) - - class CommittedAuthority: - def __init__(self): - self.calls = 0 - - def consume(self, *, run_id, lease): - assert not transaction - assert run_id == reservation.attempt_id - assert lease == expected_lease - assert self.calls == 0 - self.calls += 1 - return lease - - from app.interfaces.trusted_submission_intake import TrustedDefaultBinding - expected_binding = TrustedDefaultBinding( - attempt_id=reservation.attempt_id, - attempt_request_digest=reservation.request_digest, - policy_sha256=reservation.policy_sha256, - semantic_manifest_sha256=reservation.semantic_manifest_sha256, - default_input_sha256=reservation.default_input_sha256, - ) - evaluate_default = request.intake.evaluate_default - - async def bound_default(binding, value): - # The fake is an assertion oracle at the committed owner seam. The - # guest itself has no independent access to the reservation database. - assert binding == expected_binding - assert execution.requests == [] - return await evaluate_default(binding, value) - - request.intake.evaluate_default = bound_default - expected_lease = lease - committed = CommittedAuthority() - execution = _Execution("passed") - authority = SimpleNamespace( - prepare=AsyncMock(return_value=object()), - consume=AsyncMock(), - ) - service = PreparedBundleMaterializationService( - session=session, - authorization=authority, - preparation=preparation, - checker_execution=SelectedPreSubmitCheckerExecutionAdapter( - external_execution=execution, - ), - storage_scheme="s3", archive_limits=SubmissionArchiveLimits(), - ) - try: - await service.authorize_inspected(request) - assert authority.consume.await_count == 1 - assert execution.requests == [] - transaction = False - # A substituted default packet must fail before byte access or grants, - # even when the committed lease is otherwise exact. - process = AsyncMock() - with patch.object(preparation, "_process_prepared_submission", process): - with pytest.raises(SelectedPreSubmitInfrastructureUnavailable) as refusal: - await service.materialize_selected_pre_submit( - replace( - request, - prepared_authorization=None, - default_checker_input=replace( - request.default_checker_input, - packet=SubmissionPacketView("Changed packet", "rights_confirmed"), - ), - ), - run_id=reservation.attempt_id, lease=lease, - execution_authority=CommittedAuthority(), - ) - assert refusal.value.code == "material_unavailable" - process.assert_not_awaited() - assert execution.requests == [] - for changed_reservation in ( - replace(reservation, attempt_id=new_record_id()), - replace(reservation, attempt_request_digest="sha256:" + "f" * 64), - ): - with pytest.raises(SelectedPreSubmitInfrastructureUnavailable) as refusal: - await service.materialize_selected_pre_submit( - replace(request, selected_reservation=changed_reservation), - run_id=reservation.attempt_id, lease=lease, - execution_authority=CommittedAuthority(), - ) - assert refusal.value.code == "material_unavailable" - process.assert_not_awaited() - assert request.intake.default_bindings == [] - assert execution.requests == [] - result = await service.materialize_selected_pre_submit( - replace(request, prepared_authorization=None), - run_id=reservation.attempt_id, lease=lease, execution_authority=committed, - ) - assert result.eligible is True - assert request.intake.default_bindings == [expected_binding] - assert committed.calls == 1 - assert len(execution.requests) == 1 - assert execution.requests[0].identity.attempt_id == reservation.attempt_id - assert execution.requests[0].materials[0].archive_sha256 == ( - request.prepared_artifact.commitment.sha256 - ) - finally: - await request.prepared_artifact.close() - manager.close() diff --git a/backend/tests/submission_capacity_fixtures.py b/backend/tests/submission_capacity_fixtures.py deleted file mode 100644 index b256c8d5c..000000000 --- a/backend/tests/submission_capacity_fixtures.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Real approved guide and started task for early evaluation-capacity checks.""" - -from contextlib import asynccontextmanager -from types import SimpleNamespace - -from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine - -from app.core.identifiers import new_record_id -from app.modules.artifacts.api import SubmissionBundlePreparationRequest -from app.modules.authorization.api import ActorIdentityFacts, ActorKind -from tests.selected_policy_fixtures import approved_selected_policy_fixture -from tests.submission_preparation_auth_helpers import install_submitter_grant -from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test -from tests.tasks.submission_lineage_support import _seed_services -from tests.test_artifact_admission import _settings, _namespace, _local_store, _context, _seed_human_actor -from tests.archive_fixtures import byte_source as _bytes, submission_archive as _archive - - -@asynccontextmanager -async def capacity_fixture(database_url, tmp_path): - engine = create_async_engine(database_url) - factory = async_sessionmaker(engine, expire_on_commit=False) - settings = _settings(tmp_path, maximum_bytes=1024 * 1024).model_copy( - update={"external_checker_service_socket": tmp_path / "checker.sock", - "external_checker_material_root": tmp_path / "scratch"} - ) - namespace = _namespace(settings) - bootstrap, store = _local_store(settings, namespace) - try: - plan, policy = await approved_selected_policy_fixture( - factory, namespace, guide_version="v1" - ) - context = _context() - await _seed_services(factory) - task_id, assignment_id = new_record_id(), new_record_id() - async with factory.begin() as session: - await _seed_human_actor(session, context) - async with engine.begin() as connection: - params = dict(task=str(task_id), assignment=str(assignment_id), - project=str(plan.lineage.project_id), actor=str(context.actor_profile_id)) - await seed_started_task_for_artifact_test(connection, params) - await install_submitter_grant(connection, params) - request = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts(context.actor_profile_id, context.identity_link_id, ActorKind.HUMAN), - request_id=context.request_id, correlation_id=context.correlation_id, - task_id=task_id, assignment_id=assignment_id, predecessor_submission_id=None, - idempotency_key=new_record_id(), summary="Completed the work with verified evidence.", - contributor_attestation="I confirm no confidential client data, credentials, or copied source material is included; rights_confirmed. " - + " ".join(policy["attestation_terms"]), media_type="application/zip", - byte_source=_bytes(_archive(evidence_path=policy["evidence_path"])), - ) - yield SimpleNamespace(factory=factory, settings=settings, namespace=namespace, store=store, - context=context, request=request, plan=plan, policy=policy) - finally: - bootstrap.close() - await engine.dispose() diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py index ad0129b25..1c5d4a15a 100644 --- a/backend/tests/test_artifact_architecture.py +++ b/backend/tests/test_artifact_architecture.py @@ -17,8 +17,8 @@ BACKEND_ROOT = Path(__file__).parents[1] APP_ROOT = BACKEND_ROOT / "app" ARTIFACT_OPERATIONS = APP_ROOT / "interfaces" / "artifact_operations.py" -SUBMISSION_PREPARATION_API = ( - APP_ROOT / "modules" / "artifacts" / "api" / "submission_preparation.py" +SUBMISSION_INTAKE_API = ( + APP_ROOT / "modules" / "artifacts" / "api" / "submission_intake.py" ) SUBMISSION_ADMISSION_API = APP_ROOT / "modules" / "artifacts" / "api" / "submission_admission.py" CHECKER_OUTPUT_CUSTODY_API = APP_ROOT / "modules" / "checkers" / "api" / "output_custody.py" @@ -820,7 +820,6 @@ def _assert_checker_custody_consumers( "app/adapters/artifacts/__init__.py", "app/modules/artifacts/post_submit_materialization.py", "app/modules/artifacts/post_submit_selection.py", - "app/modules/artifacts/submission_materialization.py", "app/modules/checkers/default_checker.py", "app/modules/checkers/execution.py", }, @@ -886,12 +885,12 @@ def test_checker_custody_inventory_rejects_unregistered_import( _assert_checker_custody_consumers(injected_inventory) -def test_submission_preparation_http_request_never_carries_prepared_authority() -> None: - tree = _tree(SUBMISSION_PREPARATION_API) +def test_submission_intake_metadata_never_carries_prepared_authority() -> None: + tree = _tree(SUBMISSION_INTAKE_API) request_class = next( node for node in tree.body - if isinstance(node, ast.ClassDef) and node.name == "SubmissionBundlePreparationRequest" + if isinstance(node, ast.ClassDef) and node.name == "SubmissionIntakeMetadata" ) fields = { node.target.id: _annotation_names(node.annotation) @@ -899,10 +898,11 @@ def test_submission_preparation_http_request_never_carries_prepared_authority() if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) } assert "prepared_authorization" not in fields - assert fields["actor"] == {"ActorIdentityFacts"} - assert fields["request_id"] == {"UUID"} - assert fields["correlation_id"] == {"UUID"} - assert fields["idempotency_key"] == {"UUID"} + assert fields["task_id"] == {"UUID"} + assert fields["assignment_id"] == {"UUID"} + assert fields["predecessor_submission_id"] == {"UUID"} + assert "actor" not in fields + assert "idempotency_key" not in fields def test_prepared_handle_never_enters_public_async_or_provider_contracts() -> None: diff --git a/backend/tests/test_submission_bundle_admission.py b/backend/tests/test_submission_bundle_admission.py index 47261a7f7..cb2e3b69a 100644 --- a/backend/tests/test_submission_bundle_admission.py +++ b/backend/tests/test_submission_bundle_admission.py @@ -10,16 +10,12 @@ import app.adapters.artifacts as artifact_adapters from app.core.config import Settings -from app.modules.artifacts.api import ( - SubmissionBundlePreparationRejected, -) from app.interfaces.artifacts import ( ArtifactConfigurationError, ) from tests.artifact_store_helpers import artifact_admission_limit_settings from app.main import create_app from app.api.routes.artifact_submissions import router as submission_router -from app.modules.artifacts.submission_admission import validate_submission_packet_headers @pytest.mark.asyncio @@ -109,12 +105,3 @@ def test_submission_is_public_binary_contract() -> None: if parameter["in"] == "header" and parameter["required"]} assert {"X-Task-Assignment-Id", "Idempotency-Key"} <= required_headers assert operation["responses"]["202"] and operation["responses"]["422"] - - -def test_submission_packet_headers_reject_non_ascii() -> None: - validate_submission_packet_headers("plain summary", "plain attestation") - with pytest.raises( - SubmissionBundlePreparationRejected, - match="submission_bundle_packet_header_encoding_invalid", - ): - validate_submission_packet_headers("caf\N{LATIN SMALL LETTER E WITH ACUTE}", "ok") diff --git a/backend/tests/test_submission_bundle_preparation_recovery.py b/backend/tests/test_submission_bundle_preparation_recovery.py index 3761b8690..ac3eeeb79 100644 --- a/backend/tests/test_submission_bundle_preparation_recovery.py +++ b/backend/tests/test_submission_bundle_preparation_recovery.py @@ -16,9 +16,6 @@ from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure from app.modules.artifacts.api.submission_preparation import public_pre_submission_results from app.main import create_app -from app.modules.artifacts.api import ( - SubmissionBundlePreparationCheckFailed, -) from app.modules.checkers.api.default_checker import ( WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, WORKSTREAM_DEFAULT_CHECK_IDS, WorkstreamDefaultCheckerResult, @@ -166,21 +163,6 @@ async def test_mounted_submission_preserves_non_feedback_error_boundaries( assert "results" not in payload["error"]["details"] -@pytest.mark.parametrize("eligible", (True, 0, None)) -def test_blocked_feedback_rejects_noncanonical_or_non_false_facts(eligible) -> None: - with pytest.raises(TypeError, match="feedback facts are invalid"): - SubmissionBundlePreparationCheckFailed(object()) # type: ignore[arg-type] - from dataclasses import fields - - original = _feedback_facts() - forged = object.__new__(SelectedPreSubmitExecutionFacts) - for field in fields(original): - object.__setattr__(forged, field.name, getattr(original, field.name)) - object.__setattr__(forged, "eligible", eligible) - with pytest.raises(ValueError, match="require eligible false"): - SubmissionBundlePreparationCheckFailed(forged) - - @pytest.mark.asyncio async def test_mounted_submission_keeps_missing_optional_packet_text_warning_only() -> None: """Missing summary and attestation reach PRE as empty warning-only values.""" From 609f59ed73b5f591da684ecb432613757acf2bab Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:34:02 +0100 Subject: [PATCH 281/513] Wire hosted submission execution profiles --- .../changes/flow-self-service-signup.md | 15 ++ deploy/hosted/README.md | 40 ++- deploy/hosted/compose.py | 6 + deploy/hosted/compose.yml | 95 +++++++ deploy/hosted/preflight.py | 255 ++++++++++++++++-- deploy/hosted/release.env.example | 11 + docs/operations_authorization_service.md | 2 +- docs/roadmap_status.md | 9 +- .../deploy/runner-qualification-20261124.md | 53 +++- scripts/test_hosted_release_config.py | 189 ++++++++++++- 10 files changed, 632 insertions(+), 43 deletions(-) diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index 29a5935a2..a505420ea 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -487,3 +487,18 @@ release directory, while the active unit, environment and containers remained unchanged. The deployed image records the `agents` SDK selection. It has no submission execution or cleanup profile, exposing a separate fail-closed hosted configuration gap before activation. + +Hosted submission activation preparation closes that configuration/wiring gap +without choosing C01-C06 values or changing the live app. Both execution and +source-cleanup profiles are now required JSON inputs and pass canonical strict +typed validation in the pinned backend image before full preflight, `up` and +reboot reconciliation. The template retains replacement sentinels rather than +invented operational numbers. Static preflight binds the cleanup profile's +upload principal to the runtime IAM ARN and requires a distinct cleanup IAM ARN, +path and private credential inode. A dedicated one-queue finalization worker +uses the runtime credential; a dedicated one-queue source-cleanup worker alone +uses the cleanup credential. The general worker retains only its existing +general/outbox queues, and Beat can no longer silently omit cleanup scheduling. +Focused hosted tests passed 61 cases; compile, Ruff, whitespace and current +hosted documentation-link checks passed. No app service, container, active +release file, database, IAM policy or source-admission gate changed. diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md index 963191bce..58404ccc5 100644 --- a/deploy/hosted/README.md +++ b/deploy/hosted/README.md @@ -1,10 +1,11 @@ # Hosted Release Configuration -This directory prepares the Workstream API, durable Celery worker, Beat, -fixed guide-document parser and optional trusted model proxy on an app-only -Linux amd64 host. PostgreSQL and Redis may use the host-local data overlay or -separately managed services. Project PRE/POST and trusted ZIP intake run only on -the separately administered, always-on remote runner. +This directory prepares the Workstream API, general Celery worker, exclusive +submission-finalization and source-cleanup workers, Beat, fixed guide-document +parser and optional trusted model proxy on an app-only Linux amd64 host. +PostgreSQL and Redis may use the host-local data overlay or separately managed +services. Project PRE/POST and trusted ZIP intake run only on the separately +administered, always-on remote runner. The checked-in [release environment template](release.env.example), [Compose wrapper](compose.py), [preflight](preflight.py), and @@ -247,8 +248,13 @@ The hosted profile uses `WORKSTREAM_ARTIFACT_S3_CREDENTIAL_MODE=aws_access_key`. Set `WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN` to the dedicated IAM user and `WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_HOST_FILE` to its private JSON credential file. Compose mounts it read-only at -`/run/workstream-artifact-credentials/aws-access-key.json` only in API, worker -and model-proxy. Beat, MCP, parser and checker guests receive no storage key. +`/run/workstream-artifact-credentials/aws-access-key.json` only in API, general +worker, exclusive finalization worker and model-proxy. Set +`WORKSTREAM_ARTIFACT_S3_CLEANUP_USER_ARN` and +`WORKSTREAM_ARTIFACT_S3_CLEANUP_USER_CREDENTIAL_HOST_FILE` to the separately +authorized deletion identity. Only the exclusive source-cleanup worker receives +that file; preflight rejects a reused ARN, path or inode. Beat, MCP, parser and +checker guests receive no storage key. Follow [S3 credential setup](../../docs/operations_aws_s3_credentials.md) for restricted policies and rotation. Qualification verifies real conditional @@ -257,6 +263,18 @@ periodic proof jobs, certificate mounts or expiring database activations. Keep operation deadlines bounded and measured against the deployment; a network failure remains a recoverable storage failure, not permission to declare success. +`WORKSTREAM_SUBMISSION_EXECUTION_PROFILE` and +`WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE` are required JSON objects. The +template intentionally contains sentinels rather than guessed values. Static +preflight rejects missing or malformed objects and requires the cleanup +profile's `upload_principal` to equal the runtime upload ARN. Full preflight, +every `up`, and reboot reconciliation then run the canonical strict profile +validators from the pinned backend image before activating services. The +general worker consumes only `celery,workstream.outbox`; finalization and source +cleanup each use a separate prefork worker with exactly one queue. Beat always +receives the required cleanup profile, so the cleanup schedule cannot disappear +because of an omitted setting. + `WORKSTREAM_ARTIFACT_PREPARATION_TOTAL_DEADLINE_SECONDS` explicitly carries the existing ART processing deadline to every backend role. The template preserves its 3,400-second default. With the unchanged ZIP inspection, @@ -304,7 +322,8 @@ sudo python3 deploy/hosted/preflight.py \ ``` The full preflight additionally checks app secret/config metadata without reading -secret contents and validates private app directories. Runner runtime, cache, +secret contents, validates private app directories, and runs the pinned image's +strict submission execution/source-cleanup profile validators. Runner runtime, cache, capacity and cleanup are established by its separate qualification and the typed remote health/execution paths. Wrong endpoint, TLS or pinned intake identity rejects launch: @@ -396,8 +415,9 @@ administrator and do not attest the running node's complete source custody; qualification separately records its actual process/binary identities. The guide parser and enabled model proxy must pass their existing health checks -before the worker starts. Beat retains existing recovery schedules. API health -is a lightweight endpoint; Celery health checks its processes. Remote health +before the general worker starts. The exclusive finalization and cleanup +workers must also become healthy, and Beat retains its recovery schedules. API +health is a lightweight endpoint; Celery health checks its processes. Remote health verifies runtime/identity/cache-count and pinned intake/default facts; exact image selection is independently checked during every execution. None of these checks replaces a public authenticated journey, storage qualification, resource diff --git a/deploy/hosted/compose.py b/deploy/hosted/compose.py index 6515857c7..3861d6945 100644 --- a/deploy/hosted/compose.py +++ b/deploy/hosted/compose.py @@ -18,6 +18,7 @@ validate_private_host_inputs, validate_identity_host_inputs, validate_local_data_host_inputs, + validate_typed_submission_profiles, ) @@ -31,6 +32,9 @@ def parse_args() -> argparse.Namespace: def resume_release(environment_path: Path, values: dict[str, str]) -> int: """Reconcile an installed release after reboot, without pulling or migrating.""" validate_private_host_inputs(values, require_node=False) + validate_typed_submission_profiles( + environment_path, values, cached_images=True + ) phases: list[list[str]] = [] if values.get("WORKSTREAM_POSTGRES_IMAGE"): phases.append(["start", "local-data"]) @@ -91,6 +95,8 @@ def main() -> int: validate_private_host_inputs(values, require_node=False) else: validate_private_host_inputs(values) + if launch: + validate_typed_submission_profiles(args.env_file, values) if args.compose_arguments and args.compose_arguments[0] == "stop": if args.compose_arguments == ["stop", "worker"]: return run_compose(args.env_file, values, args.compose_arguments) diff --git a/deploy/hosted/compose.yml b/deploy/hosted/compose.yml index 34cb08da8..e7ec5030a 100644 --- a/deploy/hosted/compose.yml +++ b/deploy/hosted/compose.yml @@ -51,6 +51,8 @@ x-backend-environment: &backend-environment WORKSTREAM_TOKEN_INTROSPECTION_MODE: ${WORKSTREAM_TOKEN_INTROSPECTION_MODE:?set the Flow introspection policy} WORKSTREAM_TOKEN_ISSUER: ${WORKSTREAM_TOKEN_ISSUER:?set the Flow issuer} WORKSTREAM_TOKEN_JWKS_URL: ${WORKSTREAM_TOKEN_JWKS_URL:?set the Flow JWKS URL} + WORKSTREAM_SUBMISSION_EXECUTION_PROFILE: ${WORKSTREAM_SUBMISSION_EXECUTION_PROFILE:?set the approved finite submission execution profile JSON} + WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE: ${WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE:?set the approved finite submission source-cleanup profile JSON} x-backend-runtime: &backend-runtime image: ${WORKSTREAM_BACKEND_IMAGE:?set a digest-qualified backend image} @@ -267,6 +269,99 @@ services: retries: 6 start_period: 30s + submission-finalization-worker: + <<: *backend-runtime + environment: + <<: *backend-environment + WORKSTREAM_RELEASE_ROLE: worker + WORKSTREAM_DATABASE_URL_FILE: /run/secrets/database_url + WORKSTREAM_CELERY_BROKER_URL_FILE: /run/secrets/celery_broker_url + WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE: /run/workstream-artifact-credentials/aws-access-key.json + secrets: + - source: database_url + target: database_url + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: celery_broker_url + target: celery_broker_url + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=submission-finalization@%h + - --queues=workstream.submission_finalization + - --pidfile=/tmp/celery-submission-finalization.pid + - --loglevel=INFO + volumes: + - type: bind + source: ${WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_HOST_FILE:?set the private AWS access-key file path} + target: /run/workstream-artifact-credentials/aws-access-key.json + read_only: true + restart: on-failure:5 + stop_grace_period: 420s + healthcheck: + test: [CMD-SHELL, "test -s /tmp/celery-submission-finalization.pid && kill -0 $$(cat /tmp/celery-submission-finalization.pid)"] + interval: 20s + timeout: 10s + retries: 6 + start_period: 30s + + submission-source-cleanup-worker: + <<: *backend-runtime + environment: + <<: *backend-environment + WORKSTREAM_RELEASE_ROLE: worker + WORKSTREAM_DATABASE_URL_FILE: /run/secrets/database_url + WORKSTREAM_CELERY_BROKER_URL_FILE: /run/secrets/celery_broker_url + WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN: ${WORKSTREAM_ARTIFACT_S3_CLEANUP_USER_ARN:?set the exact source-cleanup IAM user ARN} + WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE: /run/workstream-artifact-credentials/aws-access-key.json + secrets: + - source: database_url + target: database_url + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: celery_broker_url + target: celery_broker_url + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=submission-source-cleanup@%h + - --queues=workstream.source_cleanup + - --pidfile=/tmp/celery-submission-source-cleanup.pid + - --loglevel=INFO + volumes: + - type: bind + source: ${WORKSTREAM_ARTIFACT_S3_CLEANUP_USER_CREDENTIAL_HOST_FILE:?set the private source-cleanup AWS access-key file path} + target: /run/workstream-artifact-credentials/aws-access-key.json + read_only: true + restart: on-failure:5 + stop_grace_period: 420s + healthcheck: + test: [CMD-SHELL, "test -s /tmp/celery-submission-source-cleanup.pid && kill -0 $$(cat /tmp/celery-submission-source-cleanup.pid)"] + interval: 20s + timeout: 10s + retries: 6 + start_period: 30s + model-proxy: <<: *backend-runtime profiles: [model-proxy] diff --git a/deploy/hosted/preflight.py b/deploy/hosted/preflight.py index b1ef5e16d..983f3b6a2 100644 --- a/deploy/hosted/preflight.py +++ b/deploy/hosted/preflight.py @@ -132,6 +132,14 @@ def deployment_paths(values: dict[str, str]) -> HostedPaths: "WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_HOST_FILE" ) DIRECT_USER_CREDENTIAL_FILE_KEY = "WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE" +CLEANUP_USER_ARN_KEY = "WORKSTREAM_ARTIFACT_S3_CLEANUP_USER_ARN" +CLEANUP_USER_CREDENTIAL_HOST_FILE_KEY = ( + "WORKSTREAM_ARTIFACT_S3_CLEANUP_USER_CREDENTIAL_HOST_FILE" +) +SUBMISSION_PROFILE_KEYS = ( + "WORKSTREAM_SUBMISSION_EXECUTION_PROFILE", + "WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE", +) DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z") IMAGE_REFERENCE = re.compile(r"[^\s@]+@sha256:[0-9a-f]{64}\Z") ENVIRONMENT_KEY = re.compile(r"[A-Z][A-Z0-9_]*\Z") @@ -322,6 +330,9 @@ def deployment_paths(values: dict[str, str]) -> HostedPaths: "WORKSTREAM_ARTIFACT_S3_BUCKET", "WORKSTREAM_ARTIFACT_S3_PRIVATE_PREFIX", DIRECT_USER_CREDENTIAL_HOST_FILE_KEY, + CLEANUP_USER_ARN_KEY, + CLEANUP_USER_CREDENTIAL_HOST_FILE_KEY, + *SUBMISSION_PROFILE_KEYS, *PROJECT_AGENT_CONFIGURATION_KEYS, *AWS_S3_IDENTITY_KEYS, *TIMEOUT_KEYS, @@ -536,6 +547,20 @@ def validate_environment(values: dict[str, str]) -> None: raise PreflightError("deployment paths must be canonical absolute paths") for key in REQUIRED_RELEASE_KEYS: _required(values, key) + parsed_profiles: dict[str, dict[str, Any]] = {} + for key in SUBMISSION_PROFILE_KEYS: + raw = values[key] + if len(raw.encode("utf-8")) > 65_536: + raise PreflightError(f"submission profile is unbounded: {key}") + try: + parsed = json.loads(raw) + except json.JSONDecodeError as exc: + raise PreflightError( + f"submission profile must be a JSON object: {key}" + ) from exc + if not isinstance(parsed, dict): + raise PreflightError(f"submission profile must be a JSON object: {key}") + parsed_profiles[key] = parsed for key in ( "WORKSTREAM_BACKEND_IMAGE", "WORKSTREAM_MODEL_PROXY_IMAGE", @@ -694,17 +719,40 @@ def validate_environment(values: dict[str, str]) -> None: raise PreflightError("production observability endpoint must use HTTPS") if IAM_USER_ARN.fullmatch(values["WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN"]) is None: raise PreflightError("artifact runtime user must use an exact IAM user ARN") - credential_path = Path(values[DIRECT_USER_CREDENTIAL_HOST_FILE_KEY]) - if ( - not credential_path.is_absolute() - or credential_path != credential_path.resolve(strict=False) - or any(character.isspace() or character in ",:" for character in str(credential_path)) - or credential_path.is_relative_to(root) - or root.is_relative_to(credential_path) - ): + cleanup_arn = values[CLEANUP_USER_ARN_KEY] + if IAM_USER_ARN.fullmatch(cleanup_arn) is None: + raise PreflightError("source-cleanup user must use an exact IAM user ARN") + if cleanup_arn == values["WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN"]: + raise PreflightError("source cleanup requires a distinct IAM user") + cleanup_profile = parsed_profiles[ + "WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE" + ] + if cleanup_profile.get("upload_principal") != values[ + "WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN" + ]: raise PreflightError( - "direct IAM user credentials require one canonical private host path" + "source-cleanup profile must pin the runtime upload principal" ) + credential_paths = ( + Path(values[DIRECT_USER_CREDENTIAL_HOST_FILE_KEY]), + Path(values[CLEANUP_USER_CREDENTIAL_HOST_FILE_KEY]), + ) + for credential_path in credential_paths: + if ( + not credential_path.is_absolute() + or credential_path != credential_path.resolve(strict=False) + or any( + character.isspace() or character in ",:" + for character in str(credential_path) + ) + or credential_path.is_relative_to(root) + or root.is_relative_to(credential_path) + ): + raise PreflightError( + "direct IAM user credentials require canonical private host paths" + ) + if credential_paths[0] == credential_paths[1]: + raise PreflightError("runtime and source-cleanup credentials must be distinct") def validate_local_data_environment(values: dict[str, str]) -> None: @@ -882,6 +930,7 @@ def validate_private_host_inputs( *((Path(values[TRIAL_KEYS[0]]),) if values.get(TRIAL_KEYS[0]) else ()), *(Path(values[key]) for key in _secret_file_keys(values)), Path(values[DIRECT_USER_CREDENTIAL_HOST_FILE_KEY]), + Path(values[CLEANUP_USER_CREDENTIAL_HOST_FILE_KEY]), ] for path in private_paths: _private_metadata(path, kind="file", uid=uid, gid=gid, mode=0o400) @@ -1051,7 +1100,8 @@ def run_compose( # MCP attached to a retired API namespace after a Compose-managed update. selected_services = set(compose_arguments) & { "postgres", "redis", - "api", "mcp", "worker", "beat", "model-proxy", "identity", + "api", "mcp", "worker", "submission-finalization-worker", + "submission-source-cleanup-worker", "beat", "model-proxy", "identity", "guide-document-parser", } targets_api = not selected_services or "api" in selected_services or ( @@ -1065,8 +1115,15 @@ def run_compose( # Do not restart an existing MCP container into a discarded namespace # while waiting for API health. Release it only in the phase below. if not selected_services: - compose_arguments = [*compose_arguments, "api", "worker", "beat", - "guide-document-parser"] + compose_arguments = [ + *compose_arguments, + "api", + "worker", + "submission-finalization-worker", + "submission-source-cleanup-worker", + "beat", + "guide-document-parser", + ] if values.get("WORKSTREAM_POSTGRES_IMAGE"): compose_arguments.extend(("postgres", "redis")) if values.get("FLOW_IDENTITY_IMAGE"): @@ -1235,6 +1292,10 @@ def run_shutdown(environment_path: Path, values: dict[str, str]) -> int: phases = [ ["stop", "beat", "api"], ["stop", "--timeout", "7320", "worker"], + [ + "stop", "--timeout", "420", + "submission-finalization-worker", "submission-source-cleanup-worker", + ], ] if values.get("WORKSTREAM_MCP_IMAGE"): phases.insert(0, ["stop", "mcp"]) @@ -1266,6 +1327,65 @@ def run_shutdown(environment_path: Path, values: dict[str, str]) -> int: return 0 +TYPED_SUBMISSION_PROFILE_VALIDATION = """ +from app.adapters.artifacts import selected_pre_submit_source_contracts +from app.core.config import get_settings +from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupProfile +from app.modules.artifacts.api.submission_command import SubmissionExecutionProfile +from app.modules.checkers.api.source_contracts import source_contracts_context + +settings = get_settings() +try: + SubmissionExecutionProfile.model_validate( + settings.submission_execution_profile, + context=source_contracts_context(selected_pre_submit_source_contracts()), + ) +except Exception: + raise SystemExit(20) from None +try: + SubmissionSourceCleanupProfile.model_validate( + settings.submission_source_cleanup_profile + ) +except Exception: + raise SystemExit(21) from None +""".strip() + + +def validate_typed_submission_profiles( + environment_path: Path, values: dict[str, str], *, cached_images: bool = False +) -> None: + """Run canonical image-owned profile validators before service activation.""" + command = [ + "docker", "compose", "--env-file", str(environment_path), + *_compose_file_arguments(values), + "run", "--rm", "--no-deps", "-T", + *(("--pull", "never") if cached_images else ()), + "api", "python", "-c", TYPED_SUBMISSION_PROFILE_VALIDATION, + ] + try: + completed = subprocess.run( + command, + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=compose_environment(values), + timeout=90, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + raise PreflightError( + "image-owned submission profile validation could not complete" + ) from exc + failures = { + 20: "submission execution profile failed image-owned typed validation", + 21: "submission source-cleanup profile failed image-owned typed validation", + } + if completed.returncode: + raise PreflightError(failures.get( + completed.returncode, + "image-owned submission profile validation could not initialize", + )) + + def _service_mounts(service: dict[str, Any]) -> dict[str, dict[str, Any]]: volumes = service.get("volumes") if not isinstance(volumes, list): @@ -1443,6 +1563,8 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: expected_services = { "api", "worker", + "submission-finalization-worker", + "submission-source-cleanup-worker", "beat", "guide-document-parser", } @@ -1498,6 +1620,8 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: backend_runtime_services = { "api", "worker", + "submission-finalization-worker", + "submission-source-cleanup-worker", "beat", } if model_proxy_enabled: @@ -1512,11 +1636,13 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: backend_image = services["api"]["image"] if ( services["worker"]["image"] != backend_image + or services["submission-finalization-worker"]["image"] != backend_image + or services["submission-source-cleanup-worker"]["image"] != backend_image or services["beat"]["image"] != backend_image or services["guide-document-parser"]["image"] != backend_image ): raise PreflightError( - "API, worker, Beat and guide parser must use one exact backend image" + "API, workers, Beat and guide parser must use one exact backend image" ) if ( model_proxy_enabled @@ -1526,6 +1652,8 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: for name in ( "api", "worker", + "submission-finalization-worker", + "submission-source-cleanup-worker", "beat", "guide-document-parser", *({"model-proxy"} if model_proxy_enabled else set()), @@ -1551,6 +1679,13 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: else {} ) | direct_user_credential_mount, + "submission-finalization-worker": direct_user_credential_mount, + "submission-source-cleanup-worker": { + str(DIRECT_USER_CREDENTIAL_TARGET): ( + values[CLEANUP_USER_CREDENTIAL_HOST_FILE_KEY], + True, + ), + }, "beat": {}, "guide-document-parser": { str(paths.guide_root): (str(paths.guide_root), False), @@ -1688,6 +1823,33 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: != ["--queues=celery,workstream.outbox"] ): raise PreflightError("project guide worker delivery profile is invalid") + bounded_worker_profiles = { + "submission-finalization-worker": ( + "--queues=workstream.submission_finalization", + "--hostname=submission-finalization@%h", + "--pidfile=/tmp/celery-submission-finalization.pid", + ), + "submission-source-cleanup-worker": ( + "--queues=workstream.source_cleanup", + "--hostname=submission-source-cleanup@%h", + "--pidfile=/tmp/celery-submission-source-cleanup.pid", + ), + } + for name, required_arguments in bounded_worker_profiles.items(): + bounded_worker = services[name] + command = bounded_worker.get("command") + if ( + bounded_worker.get("stop_grace_period") not in {"420s", "7m0s"} + or not isinstance(command, list) + or "--pool=prefork" not in command + or "--concurrency=1" not in command + or any(argument not in command for argument in required_arguments) + or len( + [value for value in command if str(value).startswith(("-Q", "--queues"))] + ) + != 1 + ): + raise PreflightError(f"exclusive worker delivery profile is invalid: {name}") if model_proxy_enabled: proxy = services["model-proxy"] if ( @@ -1707,25 +1869,43 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: ): raise PreflightError("model proxy delivery profile is invalid") environments: dict[str, dict[str, Any]] = {} - active_roles = ("api", "worker", "beat") + ( + active_roles = ( + "api", + "worker", + "submission-finalization-worker", + "submission-source-cleanup-worker", + "beat", + ) + ( ("model-proxy",) if model_proxy_enabled else () ) for role in active_roles: environment = services[role].get("environment") if not isinstance(environment, dict): raise PreflightError(f"{role} release environment is unavailable") - if environment.get("WORKSTREAM_RELEASE_ROLE") != role: + expected_release_role = ( + "worker" if role.startswith("submission-") else role + ) + if environment.get("WORKSTREAM_RELEASE_ROLE") != expected_release_role: raise PreflightError(f"{role} has an unsafe release role") expected_direct_credential = ( str(DIRECT_USER_CREDENTIAL_TARGET) - if role in {"api", "worker", "model-proxy"} + if role in { + "api", "worker", "model-proxy", + "submission-finalization-worker", + "submission-source-cleanup-worker", + } else None ) if environment.get(DIRECT_USER_CREDENTIAL_FILE_KEY) != expected_direct_credential: raise PreflightError( f"{role} direct IAM user credential selector differs from its release role" ) - required_file_keys = set(_role_secret_file_keys(role, values)) + policy_role = "bounded-worker" if role.startswith("submission-") else role + required_file_keys = ( + {"WORKSTREAM_DATABASE_URL_FILE", "WORKSTREAM_CELERY_BROKER_URL_FILE"} + if policy_role == "bounded-worker" + else set(_role_secret_file_keys(policy_role, values)) + ) for key, (_, target) in SECRET_FILE_TARGETS.items(): if key in REMOTE_RUNNER_SECRET_FILE_KEYS: if key in environment: @@ -1746,7 +1926,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: if not isinstance(mounted, list): raise PreflightError(f"{role} release secrets are unavailable") expected_sources = { - SECRET_FILE_TARGETS[key][0] for key in _role_secret_file_keys(role, values) + SECRET_FILE_TARGETS[key][0] for key in required_file_keys } service_uid, service_gid = services[role]["user"].split(":", maxsplit=1) if len(mounted) != len(expected_sources) or any( @@ -1762,7 +1942,9 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: raise PreflightError(f"{role} mounted secrets differ from its release role") environments[role] = environment common_environments = [] - for environment in environments.values(): + for role, environment in environments.items(): + if role == "submission-source-cleanup-worker": + continue common_environments.append( { key: value @@ -1783,7 +1965,31 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: if any( environment != common_environments[0] for environment in common_environments[1:] ): - raise PreflightError("backend roles must share the same non-secret environment") + raise PreflightError( + "backend roles must share the same non-secret environment, including " + "WORKSTREAM_ARTIFACT_PREPARATION_TOTAL_DEADLINE_SECONDS" + ) + cleanup_environment = environments["submission-source-cleanup-worker"] + cleanup_common = { + key: value + for key, value in cleanup_environment.items() + if key not in SECRET_FILE_KEYS + and key not in { + "WORKSTREAM_RELEASE_ROLE", + DIRECT_USER_CREDENTIAL_FILE_KEY, + "WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN", + } + } + runtime_common = dict(common_environments[0]) + runtime_common.pop("WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN", None) + if cleanup_common != runtime_common: + raise PreflightError( + "source-cleanup worker must share the bounded non-secret environment" + ) + if cleanup_environment.get("WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN") != values[ + CLEANUP_USER_ARN_KEY + ]: + raise PreflightError("source-cleanup worker lacks its dedicated IAM identity") environment = environments["api"] exact = { "WORKSTREAM_AUTH_PROVIDER": "flow", @@ -1803,6 +2009,8 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: for name in ( "api", "worker", + "submission-finalization-worker", + "submission-source-cleanup-worker", "beat", *(("model-proxy",) if model_proxy_enabled else ()), ): @@ -1820,6 +2028,12 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: "rendered project agent configuration differs from release: " f"{name}.{key}" ) + for key in SUBMISSION_PROFILE_KEYS: + if str(service_environment.get(key, "")) != values[key]: + raise PreflightError( + "rendered submission profile differs from release: " + f"{name}.{key}" + ) for name, service in services.items(): environment = service.get("environment") or {} expected_remote = ( @@ -1964,6 +2178,7 @@ def main() -> int: ) return 0 validate_private_host_inputs(values) + validate_typed_submission_profiles(args.env_file, values) except PreflightError as exc: print(f"hosted release preflight failed: {exc}", file=sys.stderr) return 1 diff --git a/deploy/hosted/release.env.example b/deploy/hosted/release.env.example index 56dcdf686..8552b19a3 100644 --- a/deploy/hosted/release.env.example +++ b/deploy/hosted/release.env.example @@ -13,6 +13,12 @@ WORKSTREAM_RUNTIME_GID=10001 WORKSTREAM_API_HOST_PORT=8000 WORKSTREAM_CELERY_WORKER_CONCURRENCY=1 +# Required deployment decisions. Replace these sentinels with approved JSON; +# hosted preflight invokes the image-owned strict typed validators before any +# service is activated. The template intentionally supplies no numeric defaults. +WORKSTREAM_SUBMISSION_EXECUTION_PROFILE=REPLACE_WITH_APPROVED_SUBMISSION_EXECUTION_PROFILE_JSON +WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE=REPLACE_WITH_APPROVED_SUBMISSION_SOURCE_CLEANUP_PROFILE_JSON + # Optional host-local PostgreSQL/Redis. Set all seven together to select the # local-data overlay; leave blank when using environment-managed services. # Use PostgreSQL 16 bookworm and Redis 7 bookworm images with reviewed digests @@ -79,6 +85,11 @@ WORKSTREAM_ARTIFACT_S3_PRIVATE_PREFIX=workstream/artifacts # exactly `access_key_id` and `secret_access_key`. It is mounted only into the # API, worker and enabled model proxy. Keep it outside deployment data roots. WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_HOST_FILE=/etc/workstream/aws/direct-user-credentials.json +# The exclusive source-cleanup worker receives a distinct deletion principal +# and credential. No API, general worker, finalization worker, Beat or model +# proxy process receives this file. +WORKSTREAM_ARTIFACT_S3_CLEANUP_USER_ARN=arn:aws:iam::123456789012:user/workstream-source-cleanup +WORKSTREAM_ARTIFACT_S3_CLEANUP_USER_CREDENTIAL_HOST_FILE=/etc/workstream/aws/source-cleanup-user-credentials.json # Bind the direct key to the one dedicated IAM user and reviewed release. WORKSTREAM_RELEASE_ID=sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc diff --git a/docs/operations_authorization_service.md b/docs/operations_authorization_service.md index 90f68fd35..6dd518f9e 100644 --- a/docs/operations_authorization_service.md +++ b/docs/operations_authorization_service.md @@ -421,7 +421,7 @@ Access Administrator authority to an already admitted actor; it does not create a login account. If using the [Keycloak identity provider](../deploy/identity/README.md), initialize its administrator separately, complete browser code/PKCE login for the direct Workstream API audience, and call `GET /api/v1/actors/me` first. -A Keycloak administration token cannot authorize Workstream API calls. See the [hosted sequence](../deploy/hosted/SINGLE_HOST.md#identity-storage-and-application-activation). +A Keycloak administration token cannot authorize Workstream API calls. See the [hosted sequence](../deploy/hosted/README.md#start-and-inspect). Before execution: diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index bc48d1dbb..3a7c8cc09 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -385,10 +385,11 @@ Selected production request/completion composition and supported false-guide activation are implemented. A known pre-effect non-live REV refusal returns bounded OUTBOX retry after rollback; exhaustion dead-letters without automatic reopen. A setup-fault hold is future safety work because no current selected production result emits `task_setup_blocked`. Human review/revision, conditional fulfillment, operations and release proof remain later v0.1 work. -The [single-host installation path](../deploy/hosted/SINGLE_HOST.md) includes -private persistent PostgreSQL/Redis, fresh credential initialization and ordered -backing-service startup/shutdown alongside the existing hosted owners. Managed -databases remain supported. A [private single-host MVP drill](reports/mvp-single-host-2026-11-11.md) +The [app-host release path](../deploy/hosted/README.md#start-and-inspect) includes +optional private persistent PostgreSQL/Redis, fresh credential initialization +and ordered backing-service startup/shutdown alongside the existing hosted +owners; checker execution now uses the separate runner. Managed databases remain +supported. A historical [private single-host MVP drill](reports/mvp-single-host-2026-11-11.md) qualified the 2 vCPU/8 GiB deployment for one contributor journey: fresh identity, intake failure, verified S3 Submission, external POST failure/correction, automatic acceptance, exact contribution/10-point award and replay. Selected CLI/MCP reads diff --git a/external_checkers/deploy/runner-qualification-20261124.md b/external_checkers/deploy/runner-qualification-20261124.md index ad38175be..89c1a9ad8 100644 --- a/external_checkers/deploy/runner-qualification-20261124.md +++ b/external_checkers/deploy/runner-qualification-20261124.md @@ -233,10 +233,55 @@ The bounded activation sequence is: success should the hosted systemd unit be repointed to the new immutable release and reconciled. -The deployed API has no submission execution or source-cleanup profile. The -candidate `Settings` values therefore remain `None`, and the hosted release -environment/Compose/preflight do not yet expose approved values. C01-C06 remain -unresolved; do not invent them or claim public source execution ready. +The deployed API has no submission execution or source-cleanup profile and was +not changed. Candidate hosted configuration now requires both JSON profiles, +runs their canonical strict validators from the pinned backend image before +full preflight, `up` or reboot reconciliation, and refuses missing/malformed +values. It supplies dedicated exclusive finalization and source-cleanup workers; +the latter alone receives the distinct cleanup IAM credential. No profile value +was invented or installed. C01-C06 remain unresolved deployment decisions; do +not claim public source execution ready until approved values and the AWS source +qualification exist. + +## Hosted submission topology preparation + +The candidate app release now exposes +`WORKSTREAM_SUBMISSION_EXECUTION_PROFILE` and +`WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE` to backend Settings. The release +template contains explicit replacement sentinels, not operational defaults. +Static preflight requires bounded JSON objects, a distinct exact cleanup IAM +user ARN and credential path, and a cleanup `upload_principal` equal to the +normal runtime/upload ARN. Full preflight and activation additionally run +`SubmissionExecutionProfile` with the selected PRE source-contract context and +`SubmissionSourceCleanupProfile` inside the pinned backend image; validation +output is suppressed and the failing profile is named without disclosing its +body. + +The general worker remains limited to `celery,workstream.outbox`. A one-process +prefork worker consumes only `workstream.submission_finalization` with the +normal runtime S3 credential. A second one-process prefork worker consumes only +`workstream.source_cleanup`, substitutes the distinct cleanup IAM ARN and is +the only service mounting its credential. Beat receives the required cleanup +profile, so omission can no longer silently remove the 12-hour cleanup schedule. +The consumer-first shutdown drains the general worker and both bounded exclusive +workers before their dependencies. The app host was not activated or restarted. + +Focused hosted configuration verification passed 61 tests in 91.66 seconds. +It covers required/malformed profile refusal, upload/cleanup identity separation, +one-queue worker commands, credential confinement, fixed image-owned validation, +rendered topology, shutdown order and every prior hosted regression. Python +compilation, Ruff and whitespace checks also passed. The two remaining links to +the retired single-host guide were replaced with the current app-host release +sequence. + +Remaining approval/measurement decisions are unchanged: + +- C01: aggregate PRE hard deadline and public HTTP envelope. +- C02: default PRE/POST CPU, memory, disk, process, output and log profiles. +- C03: upload total/idle, part size and related transport bounds. +- C04: API/PRE/POST/finalization concurrency and physical capacity allocation. +- C05: retry/backoff/lease/heartbeat/stall and operator retry authority. +- C06: runtime lifetime/reaper plus cleanup batch, retry and retention envelope. ## App connection preparation receipt diff --git a/scripts/test_hosted_release_config.py b/scripts/test_hosted_release_config.py index e23e3ce10..bd2c0a574 100644 --- a/scripts/test_hosted_release_config.py +++ b/scripts/test_hosted_release_config.py @@ -58,6 +58,55 @@ def setUp(self) -> None: encoding="utf-8", ) self.direct_user_credentials.chmod(0o400) + self.cleanup_user_credentials = self.root / "cleanup-aws-access-key.json" + self.cleanup_user_credentials.write_text( + json.dumps( + { + "access_key_id": "AKIAEXAMPLE987654321", + "secret_access_key": "synthetic-cleanup-test-secret-key", + } + ), + encoding="utf-8", + ) + self.cleanup_user_credentials.chmod(0o400) + execution_profile = { + "capacity": {"maximum_total_bytes": 1_000_000}, + "runtime": { + "profile_id": "hosted-test-only", + "platform_root_sha256": "sha256:" + "3" * 64, + "cpu_millis": 2000, + "memory_bytes": 2 * 1024**3, + "temporary_disk_bytes": 4 * 1024**3, + "maximum_processes": 64, + "maximum_output_bytes": 1024 * 1024, + "maximum_log_bytes": 1024 * 1024, + "aggregate_deadline_ms": 120_000, + "archive_limits": { + "maximum_entries": 2_000, + "maximum_path_bytes": 1024, + "maximum_path_depth": 32, + "maximum_central_directory_bytes": 8 * 1024 * 1024, + "maximum_entry_bytes": 128 * 1024 * 1024, + "maximum_expanded_bytes": 512 * 1024 * 1024, + "maximum_compression_ratio": 100, + "maximum_inspection_seconds": 60.0, + }, + }, + "upload_total_seconds": 300.0, + "upload_idle_seconds": 10.0, + "foreground_lease_seconds": 60.0, + "heartbeat_seconds": 10.0, + "replay_total_seconds": 30.0, + "part_bytes": 5 * 1024**2, + } + cleanup_profile = { + "maximum_candidates": 10, + "run_seconds": 60, + "lease_seconds": 30, + "upload_principal": ( + "arn:aws:iam::123456789012:user/workstream-artifact-runtime" + ), + } environment_text = ENV_EXAMPLE.read_text(encoding="utf-8") environment_text = ( environment_text.replace( @@ -72,6 +121,18 @@ def setUp(self) -> None: "/etc/workstream/aws/direct-user-credentials.json", str(self.direct_user_credentials), ) + .replace( + "/etc/workstream/aws/source-cleanup-user-credentials.json", + str(self.cleanup_user_credentials), + ) + .replace( + "REPLACE_WITH_APPROVED_SUBMISSION_EXECUTION_PROFILE_JSON", + json.dumps(execution_profile, separators=(",", ":")), + ) + .replace( + "REPLACE_WITH_APPROVED_SUBMISSION_SOURCE_CLEANUP_PROFILE_JSON", + json.dumps(cleanup_profile, separators=(",", ":")), + ) ) self.environment_path = self.root / "release.env" self.environment_path.write_text(environment_text, encoding="utf-8") @@ -170,15 +231,125 @@ def test_app_profile_starts_and_resumes_without_native_readiness(self): self.checker_path.unlink() with ( patch.object(compose, "validate_private_host_inputs") as private, + patch.object(compose, "validate_typed_submission_profiles") as profiles, patch.object(compose, "run_compose", return_value=0) as run, ): result, error = self._compose_main("up", "--detach") self.assertEqual((result, error), (0, "")) private.assert_called_once_with(values) self.assertEqual(compose.resume_release(self.environment_path, values), 0) + self.assertEqual(profiles.call_count, 2) self.assertEqual(run.call_args_list[-2].args[2][-1], "model-proxy") self.assertEqual(run.call_args_list[-1].args[2], ["up", "--detach", "--wait", "--wait-timeout", "120"]) + def test_submission_profiles_are_required_and_bound_to_distinct_cleanup_identity(self): + preflight.validate_environment(self.environment) + for key in preflight.SUBMISSION_PROFILE_KEYS: + for value in (None, "", "not-json", "[]"): + changed = dict(self.environment) + if value is None: + changed.pop(key) + else: + changed[key] = value + with self.subTest(key=key, value=value), self.assertRaises( + preflight.PreflightError + ): + preflight.validate_environment(changed) + cleanup = json.loads( + self.environment["WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE"] + ) + cleanup["upload_principal"] = self.environment[ + preflight.CLEANUP_USER_ARN_KEY + ] + with self.assertRaisesRegex( + preflight.PreflightError, "runtime upload principal" + ): + preflight.validate_environment( + self.environment + | { + "WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE": json.dumps( + cleanup + ) + } + ) + with self.assertRaisesRegex(preflight.PreflightError, "distinct IAM user"): + preflight.validate_environment( + self.environment + | { + preflight.CLEANUP_USER_ARN_KEY: self.environment[ + "WORKSTREAM_ARTIFACT_S3_RUNTIME_USER_ARN" + ] + } + ) + + def test_exclusive_submission_workers_have_one_queue_and_separate_credentials(self): + values = self.app_environment() + rendered = preflight.render_compose(self.environment_path, values) + preflight.validate_compose(rendered, values) + services = rendered["services"] + expected = { + "submission-finalization-worker": ( + "--queues=workstream.submission_finalization", + str(self.direct_user_credentials), + ), + "submission-source-cleanup-worker": ( + "--queues=workstream.source_cleanup", + str(self.cleanup_user_credentials), + ), + } + for name, (queue, credential) in expected.items(): + service = services[name] + self.assertIn(queue, service["command"]) + self.assertEqual( + preflight._service_mounts(service)[ + str(preflight.DIRECT_USER_CREDENTIAL_TARGET) + ]["source"], + credential, + ) + self.assertEqual( + {secret["source"] for secret in service["secrets"]}, + {"database_url", "celery_broker_url"}, + ) + self.assertFalse( + set(preflight.REMOTE_RUNNER_ENVIRONMENT_KEYS) + & set(service["environment"]) + ) + for name, service in services.items(): + mounts = preflight._service_mounts(service) + if name != "submission-source-cleanup-worker": + self.assertNotIn( + str(self.cleanup_user_credentials), + {str(mount.get("source")) for mount in mounts.values()}, + ) + changed = copy.deepcopy(rendered) + changed["services"]["submission-finalization-worker"]["command"].append( + "--queues=celery" + ) + with self.assertRaisesRegex(preflight.PreflightError, "exclusive worker"): + preflight.validate_compose(changed, values) + + def test_image_owned_profile_validation_is_fixed_and_fail_closed(self): + completed = subprocess.CompletedProcess([], 0) + with patch.object(preflight.subprocess, "run", return_value=completed) as run: + preflight.validate_typed_submission_profiles( + self.environment_path, self.environment, cached_images=True + ) + command = run.call_args.args[0] + self.assertIn("--pull", command) + self.assertIn("never", command) + self.assertIn("SubmissionExecutionProfile.model_validate", command[-1]) + self.assertIn("SubmissionSourceCleanupProfile.model_validate", command[-1]) + self.assertIs(run.call_args.kwargs["stdout"], subprocess.DEVNULL) + self.assertIs(run.call_args.kwargs["stderr"], subprocess.DEVNULL) + with patch.object( + preflight.subprocess, + "run", + return_value=subprocess.CompletedProcess([], 20), + ), self.assertRaisesRegex(preflight.PreflightError, "execution profile failed"): + preflight.validate_typed_submission_profiles( + self.environment_path, self.environment + ) + def test_local_data_shutdown_preserves_dependencies_until_consumers_stop(self): values = self.local_data_environment() with patch.object(preflight.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as run: @@ -813,20 +984,30 @@ def test_shutdown_drains_producers_worker_and_proxy_without_stopping_native_node self.assertEqual(commands[0][-3:], ["stop", "beat", "api"]) self.assertEqual(commands[1][-4:], ["stop", "--timeout", "7320", "worker"]) self.assertEqual( - commands[2][-4:], + commands[2][-5:], + [ + "stop", + "--timeout", + "420", + "submission-finalization-worker", + "submission-source-cleanup-worker", + ], + ) + self.assertEqual( + commands[3][-4:], ["stop", "--timeout", "7320", "model-proxy"], ) self.assertEqual( - commands[3][-2:], + commands[4][-2:], ["stop", "guide-document-parser"], ) def test_shutdown_failure_keeps_later_dependencies_running(self) -> None: - for failed_phase in (0, 1, 2): + for failed_phase in (0, 1, 2, 3): with self.subTest(failed_phase=failed_phase): results = [ subprocess.CompletedProcess([], 17 if index == failed_phase else 0) - for index in range(4) + for index in range(5) ] with patch.object( preflight.subprocess, "run", side_effect=results From 544c228c78d496b03da52f16444628984ef83be2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:47:38 +0100 Subject: [PATCH 282/513] Record incident summary runner cache --- .../changes/flow-self-service-signup.md | 10 +++++++ .../deploy/runner-qualification-20261124.md | 28 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/.commitrail/changes/flow-self-service-signup.md b/.commitrail/changes/flow-self-service-signup.md index a505420ea..6c6429d43 100644 --- a/.commitrail/changes/flow-self-service-signup.md +++ b/.commitrail/changes/flow-self-service-signup.md @@ -502,3 +502,13 @@ general/outbox queues, and Beat can no longer silently omit cleanup scheduling. Focused hosted tests passed 61 cases; compile, Ruff, whitespace and current hosted documentation-link checks passed. No app service, container, active release file, database, IAM policy or source-admission gate changed. + +Coordinated runner-only maintenance then added the exact incident-summary image +as a third cache entry for the successful-checker public journey. Its manifest, +config and canonical USTAR are pinned in the runner receipt. The prior two-entry +config remains byte-identical in a root-private rollback backup, both existing +entries remain first and unchanged, and only the runner edge/native units were +stopped. App-origin TLS 1.3 health returned ready with three manifests; both +units are active and material/model-relay roots are empty. This installed a +test image only: it did not activate project policy or change the app, IAM, +database, release environment or AWS source gate. diff --git a/external_checkers/deploy/runner-qualification-20261124.md b/external_checkers/deploy/runner-qualification-20261124.md index 89c1a9ad8..3d10ea6c1 100644 --- a/external_checkers/deploy/runner-qualification-20261124.md +++ b/external_checkers/deploy/runner-qualification-20261124.md @@ -152,6 +152,34 @@ envelope. It never deletes an active or uncertain grant. Focused tests cover both `.incoming-*` and renamed `extract_*` residue, refusal while the native socket exists, exact removal after confirmed stop, and clean restart. +## Incident-summary qualification cache + +After the hosted profile repair was frozen and integrated, coordinated +runner-only maintenance installed one additive successful-checker image for the +governed public journey. The two existing checker/intake entries remained first +and byte-identical. The new closed cache entry is: + +- repository: `docker.io/library/workstream-incident-summary` +- platform manifest: `sha256:b4d1877fabfeacb24c6830469d1d1f057eacb64daecea7b5328f08431fc65721` +- image config: `sha256:ad76a4e619ec4a72db898650d01b789a0144c765676af2189f144c36e8db4939` +- canonical USTAR: 129,095,680 bytes, + `sha256:c71509d7bc9771a6205429267ec911407913e70a4b33b6f0376eca580fac3ff2` + +The archive/config are owned by uid/gid 10001, regular single-link files with +mode 0400. Active checker config is +`sha256:c3f8fb85ab2cc3b27ddf8da6db1e483aae9880b23918822c241d6864322a3dcd`. +The byte-identical prior two-entry config remains mode 0400 at +`/etc/workstream/maintenance-backups/20261124-incident-summary-cache/checker-service.json` +with digest +`sha256:c35de5c4f38db8c5b9d003e47d4bf9e4310f22549c6e8dde65bdd27d57ecf5a6`. + +Only the runner edge/native units stopped during the install. Both returned +active with no error-priority journal entry. An app-origin TLS 1.3 health +exchange reported ready Linux/amd64 `smolvm`/`smol-microvm`, sandbox uid/gid +10001 and three cached manifests. Material workspaces and model-relay roots were +empty afterward. Installation is cache readiness, not project policy activation +or proof of the later public acceptance journey. + ## App deployment handoff The read-only app inspection found instance `i-000b0c090ddc142bd` healthy on From 08fd205d0a7e219b3ce77f61f9fdb931a1675ae4 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 14:50:04 +0100 Subject: [PATCH 283/513] Prove Redis redelivery recovers killed finalization children --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 55 +++ ...est_submission_finalization_worker_loss.py | 401 +++++++++++++----- 2 files changed, 359 insertions(+), 97 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 1f33c12fc..55b82d738 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9089,3 +9089,58 @@ collected 12080 cases but ended with eight unrelated optional-agent import errors because that environment lacks `httpx2`; it is not counted as a pass. The repository-wide Markdown-link checker also fails unchanged on two links to the missing `deploy/hosted/SINGLE_HOST.md` in untouched documents. + +### Qualify actual broker redelivery after finalization child death + +Allowed: existing test_submission_finalization_worker_loss.py and this record. +Reuse its owned Redis endpoint/public ZIP setup and process cleanup for two +production exclusive-prefork cases. A test-only one-shot hook sends SIGKILL to +the actual Celery child immediately before source observation or after the real +T5 run commits and before handler acknowledgement. Never replace finalizer +results, registry, authority, SQL guards or provider observations. Fsync an owned +crash marker and record Celery task-prerun delivery metadata so actual broker +redelivery must preserve the task ID, set redelivered and run in a replacement +child. No manual duplicate publication may satisfy this criterion. + +Preserve the real300s ownership lease and database clock. Immediate broker +redelivery must not steal live custody. After PostgreSQL observes expiry, the +production scanner/worker must recover the uncertain invocation, respect its +actual backoff and finalize under a new claim. Require one exact retained graph, +source charge and accepted receipt, generation2 only when T5 had not committed; +committed T5 must replay its original submission without another provider read. +Existing direct SIGKILL tests remain unchanged. Risk: medium test-process/broker +proof; final isolated run covers prior outage plus both crash cases, with exact +worker/proxy/prefix cleanup and scoped review. No production, schema, remote or +shared-container changes. Beat scheduling and deployed/native execution remain +outside qualification. + +The first combined death-proof run passed3/3 in838.60s (two unchanged direct +SIGKILL cases deselected). /tmp/submission-finalizer-broker-death-v1.{log,json} +records launcheraaee53f6c, schema0090 and complete PostgreSQL/MinIO cleanup. +Executable test blob8d299d5e52a940b610b5dfc364300a3d5459c0f1 stayed unchanged during +execution; the final evidence append changes only this record. The prior +publication-outage case also passed after factoring its setup/cleanup. + +Both actual Celery child kills produced automatic Redis redelivery of the same +task ID with redelivered=True in a different prefork child. Immediate redelivery +returned unavailable while the original300s owner lease remained live. After +PostgreSQL time passed that original deadline, the production scanner and task +recorded INVOKE_OUTCOME_UNKNOWN with the real5s backoff; the next scanner pass +claimed generation2 and acknowledged. Each trace has flags +[False,True,False,False]: original, broker redelivery, owner recovery and final +claim. The before-observation case advances continuation to2; after-commit keeps +continuation1 and the exact original Submission. Both finish with one graph, +one POST event, exactly two completed outbox attempts, sealed charged source, +stable accepted receipt and no second PRE. The committed case performs only its +original provider observation; replay does not reopen source metadata. + +/tmp/submission-finalizer-broker-death-observations.json retains the fsynced +boundary/PID and real Celery delivery metadata beside the terminal receipt. All +observed child PIDs are dead afterward; test finally blocks stop their owned +worker groups, drain proxy connections and delete only the unique Redis prefixes. +The Python fork-with-threads warning remains unsuppressed for each case. This +qualifies child loss with a surviving consumer parent and broker, not parent +loss/Redis visibility-timeout reclamation, Beat scheduling, native PRE or AWS. +Ruff/structure/diff pass (structure log +/tmp/submission-finalizer-broker-death-structure.log); final Commitrail check +runs after this append. No production or lane changes, no remote mutation. diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py index 728682ecb..8d299d5e5 100644 --- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -1,5 +1,6 @@ """Actual process death retains accepted custody before and after T5 commit.""" import asyncio +from contextlib import asynccontextmanager from datetime import timedelta import multiprocessing import os @@ -224,7 +225,7 @@ async def _accepted_broker_facts(f, operation_id): event.attempt_count, charge.state, charge.accounted_bytes, pointer) -async def _assert_broker_finalized_once(f, operation_id, accepted): +async def _assert_broker_finalized_once(f, operation_id, accepted, *, attempts=1, generation=1): """Require one durable graph after original and duplicate tasks return.""" from app.modules.artifacts.intake.models import SubmissionSourceCharge from app.modules.outbox.models import OutboxDeliveryAttempt @@ -234,11 +235,11 @@ async def _assert_broker_finalized_once(f, operation_id, accepted): event = await session.get(OutboxEvent, UUID(operation.finalization_event_id)) charge = await session.get(SubmissionSourceCharge, operation_id) assert operation.state == "finalized" and operation.finalized_submission_id is not None - assert operation.acceptance_receipt == accepted and operation.continuation_generation == 1 - assert event.delivery_state == "acknowledged" and event.attempt_count == 1 - attempts = (await session.scalars(select(OutboxDeliveryAttempt).where( + assert operation.acceptance_receipt == accepted and operation.continuation_generation == generation + assert event.delivery_state == "acknowledged" and event.attempt_count == attempts + rows = (await session.scalars(select(OutboxDeliveryAttempt).where( OutboxDeliveryAttempt.event_id == event.event_id))).all() - assert len(attempts) == 1 and attempts[0].stage == "completed" + assert len(rows) == attempts and all(row.stage == "completed" for row in rows) assert charge.state == "sealed" and charge.accounted_bytes == operation.raw_byte_count > 0 for table in ("submissions", "submission_dispatches", "checker_runs"): assert await session.scalar(text( @@ -259,7 +260,7 @@ async def _assert_broker_finalized_once(f, operation_id, accepted): async def _stop_broker_worker(process, completed): """Stop only the owned worker group before removing this test's keys.""" - if process.pid is not None: + if process is not None and process.pid is not None: if process.is_alive(): os.killpg(process.pid, signal.SIGTERM) await asyncio.to_thread(process.join, 10) @@ -272,109 +273,315 @@ async def _stop_broker_worker(process, completed): completed.join_thread() -async def test_real_broker_recovers_public_acceptance_and_deduplicates_finalization( - admission_intake, tmp_path, monkeypatch, -): - """Controlled public PRE, real outage/scanner, Redis and production prefork T5.""" - import queue +async def _accept_public_broker_source(case, f, tmp_path, monkeypatch): + """Use signed HTTP and current owners; only the PRE transport is controlled.""" + from app.core.identifiers import new_record_id + from tests.artifacts.test_submission_foreground_command import configure_source_http + from tests.test_trusted_intake import _archive + + case.payload = _archive() + case.client, settings, case.errors, case.calls = await configure_source_http( + f.factory, f.access.signed.client, tmp_path, monkeypatch, case.payload, "completed") + case.headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + "Idempotency-Key": str(new_record_id()), "Content-Length": str(len(case.payload)), + } + case.url = f"/api/v1/tasks/{f.task}/submissions" + response = await case.client.post(case.url, headers=case.headers, content=case.payload) + assert response.status_code == 202, response.text + assert len(case.calls) == 1 and not case.errors, case.errors + case.accepted = response.json() + case.operation_id = UUID(case.accepted["operation_id"]) + for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER): + await provision_post_submit_service(f.factory, identity) + _broker_settings(settings, monkeypatch) + case.before = await _accepted_broker_facts(f, case.operation_id) + assert case.before[0] == "finalization_pending" and case.before[5:7] == ("pending", 0) + + +@asynccontextmanager +async def _public_broker_case(f, tmp_path, monkeypatch, *, kill_at=None): + """Own one isolated endpoint, worker group and Redis prefix for a public T4.""" import socket - import time + from types import SimpleNamespace from urllib.parse import urlsplit import redis - from app.core.config import get_settings from app.core.identifiers import new_record_id from app.workers import outbox as worker - from app.workers.outbox_topology import FINALIZATION_QUEUE - from tests.artifacts.test_submission_foreground_command import configure_source_http - from tests.test_trusted_intake import _archive - f = admission_intake broker = urlsplit(os.environ["WORKSTREAM_TEST_BROKER_URL"]) assert broker.scheme == "redis" and broker.hostname and broker.port - connection = redis.Redis.from_url(broker.geturl()) - assert connection.ping() - prefix, hostname = f"finalizer-proof-{new_record_id()}:", f"finalizer-{new_record_id()}@localhost" - closed_endpoint = socket.socket() - closed_endpoint.bind(("127.0.0.1", 0)) - port = closed_endpoint.getsockname()[1] - app = worker.celery_app - monkeypatch.setattr(app, "_pool", None) - monkeypatch.setattr(app.amqp, "_producer_pool", None) - monkeypatch.setitem(app.conf, "broker_url", f"redis://127.0.0.1:{port}/{broker.path.lstrip('/')}") - monkeypatch.setitem(app.conf, "broker_transport_options", { - **app.conf.broker_transport_options, "global_keyprefix": prefix, - "socket_connect_timeout": 0.25, "socket_timeout": 5, "max_retries": 0, - }) - monkeypatch.setitem(app.conf, "task_publish_retry", False) - monkeypatch.setitem(app.conf, "task_always_eager", False) - completed = multiprocessing.get_context("fork").Queue() - process = multiprocessing.get_context("fork").Process(target=_broker_finalizer, args=(app, hostname, completed)) - proxy, connections = None, set() + case = SimpleNamespace(connection=redis.Redis.from_url(broker.geturl(), socket_timeout=2), + prefix=f"finalizer-proof-{new_record_id()}:", hostname=f"finalizer-{new_record_id()}@localhost", + endpoint=socket.socket(), proxy=None, connections=set(), process=None, + completed=multiprocessing.get_context("fork").Queue(), app=worker.celery_app, + destination=(broker.hostname, broker.port), worker=worker, + marker=tmp_path / "broker-child-kill.json", trace=tmp_path / "broker-delivery.jsonl") try: - payload, key = _archive(), new_record_id() - client, settings, errors, calls = await configure_source_http( - f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "completed") - headers = f.access.target.headers | { - "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), - "Idempotency-Key": str(key), "Content-Length": str(len(payload)), - } - url = f"/api/v1/tasks/{f.task}/submissions" - accepted = await client.post(url, headers=headers, content=payload) - assert accepted.status_code == 202, accepted.text - assert len(calls) == 1 and not errors, errors - operation_id = UUID(accepted.json()["operation_id"]) - for identity in (ServiceIdentity.ARTIFACT_BINDING, ServiceIdentity.OUTBOX_DISPATCHER): - await provision_post_submit_service(f.factory, identity) - _broker_settings(settings, monkeypatch) - before = await _accepted_broker_facts(f, operation_id) - assert before[0] == "finalization_pending" and before[5:7] == ("pending", 0) - failed = await asyncio.to_thread(worker.scan_pending.run) + assert case.connection.ping() + case.endpoint.bind(("127.0.0.1", 0)) # No listener: real connection refusal. + case.port = case.endpoint.getsockname()[1] + monkeypatch.setattr(case.app, "_pool", None) + monkeypatch.setattr(case.app.amqp, "_producer_pool", None) + monkeypatch.setitem(case.app.conf, "broker_url", f"redis://127.0.0.1:{case.port}/{broker.path.lstrip('/')}") + monkeypatch.setitem(case.app.conf, "broker_transport_options", { + **case.app.conf.broker_transport_options, "global_keyprefix": case.prefix, + "socket_connect_timeout": 0.25, "socket_timeout": 5, "max_retries": 0, + }) + monkeypatch.setitem(case.app.conf, "task_publish_retry", False) + monkeypatch.setitem(case.app.conf, "task_always_eager", False) + await _accept_public_broker_source(case, f, tmp_path, monkeypatch) + target = _broker_finalizer if kill_at is None else _crashing_broker_finalizer + arguments = (case.app, case.hostname, case.completed) + if kill_at is not None: + arguments += (str(case.operation_id), kill_at, case.marker, case.trace) + case.process = multiprocessing.get_context("fork").Process(target=target, args=arguments) + yield case + finally: + await _close_broker_case(case) + + +async def _close_broker_case(case): + """Drain only owned processes, sockets and keys; preserve the shared Redis.""" + from app.core.config import get_settings + + case.endpoint.close() + await _stop_broker_worker(case.process, case.completed) + for pool in (case.app.amqp._producer_pool, case.app._pool): + if pool is not None: + pool.force_close_all() + if case.proxy is not None: + case.proxy.close() + await case.proxy.wait_closed() + for pending in tuple(case.connections): + pending.cancel() + await asyncio.gather(*tuple(case.connections), return_exceptions=True) + keys = list(case.connection.scan_iter(match=case.prefix + "*")) + if keys: + case.connection.delete(*keys) + assert list(case.connection.scan_iter(match=case.prefix + "*")) == [] + case.connection.close() + get_settings.cache_clear() + + +async def _restore_broker_endpoint(case): + """Make the unchanged producer endpoint forward to real Redis again.""" + case.endpoint.close() + case.proxy = await asyncio.start_server( + lambda reader, writer: _redis_forwarder(reader, writer, case.destination, case.connections), + "127.0.0.1", case.port) + + +async def _next_broker_result(case): + """Observe a real task return while the proxy event loop remains live.""" + import queue + import time + + deadline = time.monotonic() + 120 + while time.monotonic() < deadline: + assert case.process.is_alive(), f"finalization worker exited: {case.process.exitcode}" + try: + result = await asyncio.to_thread(case.completed.get, True, 0.2) + except queue.Empty: + continue + from app.workers.outbox_topology import FINALIZATION_QUEUE + assert result[1] == "SUCCESS" and result[3] not in {os.getpid(), case.process.pid}, result + assert result[4:] == (False, FINALIZATION_QUEUE), result + return result + raise AssertionError("production finalization task did not return") + + +async def _assert_public_broker_replay(case): + """Exact accepted replay never uploads again or invokes PRE again.""" + response = await case.client.post(case.url, headers=case.headers, content=case.payload) + assert response.status_code == 202, response.text + assert response.json() == dict(case.accepted, replayed=True) + assert len(case.calls) == 1 and not case.errors + + +async def test_real_broker_recovers_public_acceptance_and_deduplicates_finalization( + admission_intake, tmp_path, monkeypatch, +): + """Controlled public PRE, real outage/scanner, Redis and production prefork T5.""" + from app.workers.outbox_topology import FINALIZATION_QUEUE + + f = admission_intake + async with _public_broker_case(f, tmp_path, monkeypatch) as case: + failed = await asyncio.to_thread(case.worker.scan_pending.run) assert failed == {"selected": 1, "published": 0} - assert await _accepted_broker_facts(f, operation_id) == before - assert list(connection.scan_iter(match=prefix + "*")) == [] - closed_endpoint.close() - proxy = await asyncio.start_server( - lambda reader, writer: _redis_forwarder(reader, writer, (broker.hostname, broker.port), connections), - "127.0.0.1", port) - published = await asyncio.to_thread(worker.scan_pending.run) - assert published == {"selected": 1, "published": 1} + assert await _accepted_broker_facts(f, case.operation_id) == case.before + assert list(case.connection.scan_iter(match=case.prefix + "*")) == [] + await _restore_broker_endpoint(case) + assert await asyncio.to_thread(case.worker.scan_pending.run) == {"selected": 1, "published": 1} for _ in range(2): - await asyncio.to_thread(worker.finalize_submission.apply_async, args=(str(before[4]), str(f.project))) - assert connection.llen(prefix + FINALIZATION_QUEUE) == 3 - process.start() - deadline, observations = time.monotonic() + 120, [] - while len(observations) < 3 and time.monotonic() < deadline: - assert process.is_alive(), f"finalization worker exited: {process.exitcode}" - try: - observations.append(await asyncio.to_thread(completed.get, True, 0.2)) - except queue.Empty: - pass - assert len(observations) == 3, observations + await asyncio.to_thread(case.worker.finalize_submission.apply_async, + args=(str(case.before[4]), str(f.project))) + assert case.connection.llen(case.prefix + FINALIZATION_QUEUE) == 3 + case.process.start() + observations = [await _next_broker_result(case) for _ in range(3)] assert len({item[0] for item in observations}) == 3 - assert all(item[1] == "SUCCESS" and item[3] not in {os.getpid(), process.pid} - and item[4:] == (False, FINALIZATION_QUEUE) for item in observations), observations assert sorted(item[2]["status"] for item in observations) == [ "delivery_recorded", "delivery_unavailable", "delivery_unavailable"] - await _assert_broker_finalized_once(f, operation_id, before[1]) - replay = await client.post(url, headers=headers, content=payload) - assert replay.status_code == 202 and replay.json() == dict(accepted.json(), replayed=True), replay.text - assert len(calls) == 1 and not errors - await _assert_broker_finalized_once(f, operation_id, before[1]) + await _assert_broker_finalized_once(f, case.operation_id, case.before[1]) + await _assert_public_broker_replay(case) + await _assert_broker_finalized_once(f, case.operation_id, case.before[1]) + + +def _record_broker_trace(path, body): + """Make each observed boundary durable before its process can be killed.""" + import json + + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + try: + os.write(descriptor, (json.dumps(body) + "\n").encode()) + os.fsync(descriptor) finally: - closed_endpoint.close() - await _stop_broker_worker(process, completed) - for pool in (app.amqp._producer_pool, app._pool): - if pool is not None: - pool.force_close_all() - if proxy is not None: - proxy.close() - await proxy.wait_closed() - for pending in tuple(connections): - pending.cancel() - await asyncio.gather(*tuple(connections), return_exceptions=True) - keys = list(connection.scan_iter(match=prefix + "*")) - if keys: - connection.delete(*keys) - assert list(connection.scan_iter(match=prefix + "*")) == [] - connection.close() - get_settings.cache_clear() + os.close(descriptor) + + +def _kill_broker_child_once(marker, operation_id, boundary, result=None): + """Kill the actual child exactly once, never synthesize a finalizer result.""" + import json + + try: + descriptor = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + return + try: + os.write(descriptor, json.dumps({"pid": os.getpid(), "operation_id": operation_id, + "boundary": boundary, "submission_id": str(result.submission_id) if result else None}).encode()) + os.fsync(descriptor) + finally: + os.close(descriptor) + os.kill(os.getpid(), signal.SIGKILL) + raise AssertionError("SIGKILL unexpectedly returned") + + +def _crashing_broker_finalizer(app, hostname, completed, operation_id, kill_at, marker, trace): + """Install observation-only hooks around real production T5 and broker delivery.""" + from celery.signals import task_prerun + from app.adapters.artifacts import _WorkerSourceObservation + from app.modules.artifacts.intake.finalization import AcceptedSubmissionFinalization + from app.workers.outbox_topology import FINALIZATION_DELIVERY_TASK + + original_observe = _WorkerSourceObservation.observe_sealed_source + original_run = AcceptedSubmissionFinalization.run + + async def observe(store, source): + if str(source.location.operation_id) == operation_id: + if kill_at == "before_observation": + _kill_broker_child_once(marker, operation_id, kill_at) + _record_broker_trace(trace, {"kind": "source_observation", "pid": os.getpid()}) + return await original_observe(store, source) + + async def run(finalizer, actual_id): + result = await original_run(finalizer, actual_id) + if str(actual_id) == operation_id and kill_at == "after_commit": + _kill_broker_child_once(marker, operation_id, kill_at, result) + return result + + def record(task_id, task, args, **_kwargs): + if task.name == FINALIZATION_DELIVERY_TASK: + _record_broker_trace(trace, {"kind": "delivery", "task_id": task_id, + "event_id": args[0], "pid": os.getpid(), + "redelivered": bool(task.request.delivery_info.get("redelivered"))}) + + _WorkerSourceObservation.observe_sealed_source = observe + AcceptedSubmissionFinalization.run = run + task_prerun.connect(record, weak=False) + _broker_finalizer(app, hostname, completed) + + +async def _assert_broker_redelivery(case, f, kill_at, result): + """Require broker requeue of the same message while the owner lease stays live.""" + import json + + marker = json.loads(case.marker.read_text()) + deliveries = [json.loads(line) for line in case.trace.read_text().splitlines() + if json.loads(line)["kind"] == "delivery"] + assert marker["operation_id"] == str(case.operation_id) and marker["boundary"] == kill_at + assert len(deliveries) == 2 and deliveries[0]["task_id"] == deliveries[1]["task_id"] == result[0] + assert [item["redelivered"] for item in deliveries] == [False, True] + assert all(item["event_id"] == str(case.before[4]) for item in deliveries) + assert deliveries[0]["pid"] == marker["pid"] and deliveries[1]["pid"] == result[3] != marker["pid"] + with pytest.raises(ProcessLookupError): + os.kill(marker["pid"], 0) + assert result[2] == {"status": "delivery_unavailable"} + async with f.factory() as session: + operation = await session.get(SubmissionIntakeOperation, case.operation_id) + event = await session.get(OutboxEvent, case.before[4]) + now = await session.scalar(select(func.clock_timestamp())) + assert event.delivery_state == "claimed" and event.attempt_count == 1 + assert now < event.claim_expires_at + assert (event.claim_expires_at - event.claimed_at).total_seconds() == 300 + assert operation.continuation_generation == 1 + assert operation.state == ("finalized" if kill_at == "after_commit" else "finalization_pending") + assert operation.acceptance_receipt == case.before[1] + assert operation.finalized_submission_id == marker["submission_id"] + return max(event.claim_expires_at, operation.continuation_expires_at), marker["submission_id"] + + +async def _wait_for_broker_database_time(factory, target): + """Wait through the unchanged production lease/backoff on PostgreSQL time.""" + async with asyncio.timeout(360): + while True: + async with factory() as session: + now = await session.scalar(select(func.clock_timestamp())) + if now >= target: + return + await asyncio.sleep(min(1, (target - now).total_seconds())) + + +async def _assert_broker_recovered_unknown(case, f): + """The real worker records uncertainty before any new handler claim.""" + import json + from datetime import datetime + from app.modules.outbox.models import OutboxDeliveryAttempt + + async with f.factory() as session: + event = await session.get(OutboxEvent, case.before[4]) + attempts = (await session.scalars(select(OutboxDeliveryAttempt).where( + OutboxDeliveryAttempt.event_id == event.event_id))).all() + assert event.delivery_state == "retryable" and event.attempt_count == 1 + assert len(attempts) == 1 and attempts[0].stage == "completed" + outcome = json.loads(attempts[0].outcome_json) + assert outcome["invocation_unknown"] is True and outcome["error_code"] == "INVOKE_OUTCOME_UNKNOWN" + assert (event.next_attempt_at - datetime.fromisoformat(outcome["receipt_completed_at"])).total_seconds() == 5 + return event.next_attempt_at + + +@pytest.mark.parametrize("kill_at", ["before_observation", "after_commit"]) +async def test_real_broker_redelivers_killed_finalizer_and_recovers_owner_lease( + admission_intake, tmp_path, monkeypatch, kill_at, +): + """Actual Redis redelivery plus expired-invocation recovery preserves one T5.""" + import json + + f = admission_intake + async with _public_broker_case(f, tmp_path, monkeypatch, kill_at=kill_at) as case: + await _restore_broker_endpoint(case) + assert await asyncio.to_thread(case.worker.scan_pending.run) == {"selected": 1, "published": 1} + case.process.start() + redelivery = await _next_broker_result(case) + due, original_submission = await _assert_broker_redelivery(case, f, kill_at, redelivery) + await _wait_for_broker_database_time(f.factory, due) + assert await asyncio.to_thread(case.worker.scan_pending.run) == {"selected": 1, "published": 1} + recovered = await _next_broker_result(case) + assert recovered[2] == {"status": "delivery_recorded"} + due = await _assert_broker_recovered_unknown(case, f) + await _wait_for_broker_database_time(f.factory, due) + assert await asyncio.to_thread(case.worker.scan_pending.run) == {"selected": 1, "published": 1} + finalized = await _next_broker_result(case) + assert finalized[2] == {"status": "delivery_recorded"} + submission = await _assert_broker_finalized_once(f, case.operation_id, case.before[1], + attempts=2, generation=1 if kill_at == "after_commit" else 2) + if original_submission is not None: + assert submission == original_submission + trace = [json.loads(line) for line in case.trace.read_text().splitlines()] + deliveries = [item for item in trace if item["kind"] == "delivery"] + assert len(deliveries) == 4 and len({item["task_id"] for item in deliveries}) == 3 + assert [item["redelivered"] for item in deliveries] == [False, True, False, False] + assert len([item for item in trace if item["kind"] == "source_observation"]) == 1 + await _assert_public_broker_replay(case) + assert await _assert_broker_finalized_once(f, case.operation_id, case.before[1], + attempts=2, generation=1 if kill_at == "after_commit" else 2) == submission From c853743b689a46711c13e1d800cdd27ab8230ac2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 15:06:48 +0100 Subject: [PATCH 284/513] docs: clarify submission cleanup scope and service terminology --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 17 +++++++++++++++++ docs/operations_artifact_storage.md | 5 ++++- docs/operations_aws_s3_credentials.md | 11 ++++++----- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 55b82d738..acc4f41d3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9144,3 +9144,20 @@ loss/Redis visibility-timeout reclamation, Beat scheduling, native PRE or AWS. Ruff/structure/diff pass (structure log /tmp/submission-finalizer-broker-death-structure.log); final Commitrail check runs after this append. No production or lane changes, no remote mutation. + +### Genuine-orphan scope clarification + +Read-only ARCH/SEC assessment at08fd205d0 confirms that spec17.4 makes +managed-prefix inventory for genuinely absent operation records optional. +Earlier notes listing that scanner as required remaining work are superseded +by this clarification. D05 and A14–A17 still require durable ownership before +bytes, exact indexed cleanup, accepted/retained protection and reconciliation +of uncertain known-operation writes, including conservative charges. +Only operations-guide wording changes; no owner, deletion authority, test or +provider gate changes. No orphan discovery/deletion or backlog metric is claimed. +The persistent local checklist now excludes this optional expansion. + +The AWS credential guide also names the dedicated Celery process explicitly +and links the canonical source-key specification instead of duplicating its +versioned key example. This resolves stale-vocabulary scan false positives +without changing the scanner, IAM policy, runtime behavior or key format. diff --git a/docs/operations_artifact_storage.md b/docs/operations_artifact_storage.md index f34fd4b31..097a41ffb 100644 --- a/docs/operations_artifact_storage.md +++ b/docs/operations_artifact_storage.md @@ -193,5 +193,8 @@ saved on the existing cleanup claim before abort. A fresh authorization binds that retained set; newly discovered IDs invalidate the previous authorization. Retries check every retained handle even when discovery no longer lists it. Empty discovery cannot prove that an uncertain initiation never happened, so -that case remains charged. Genuine orphan reconciliation remains unfinished. +that case remains charged. Inventory of objects whose operation record is +genuinely absent is an optional future enhancement under submission spec §17.4; +this sweep does not discover or delete those objects. Reconciliation of uncertain +writes belonging to known operations remains required. Do not treat this schedule as proof that every abandoned byte is reclaimed. diff --git a/docs/operations_aws_s3_credentials.md b/docs/operations_aws_s3_credentials.md index 5015b0fb5..a4737e02a 100644 --- a/docs/operations_aws_s3_credentials.md +++ b/docs/operations_aws_s3_credentials.md @@ -5,7 +5,7 @@ metadata and ownership used to authorize access. Contributors, reviewers, setup agents and external checker guests do not receive the bucket credential. The hosted application uses a dedicated IAM user's access key. Source cleanup -uses a separate IAM user and private key file in its dedicated worker. This works +uses a separate IAM user and private key file in its dedicated Celery worker. This works on AWS or another hosting provider. No certificate authority, certificate renewal, three-identity verification job or expiring database activation is required. @@ -14,7 +14,7 @@ required. Create two distinct IAM users in the bucket owner’s AWS account, without console access, group membership or other attached policies: the runtime uploader/reader -and the source-cleanup worker. The generator rejects cross-account or identical +and the source-cleanup service. The generator rejects cross-account or identical principals. Generate their restricted policies and the bucket policy using the deployment's actual bucket and existing private prefix: @@ -34,7 +34,8 @@ Review existing bucket users before replacing a bucket policy. Do not change the prefix of an existing deployment: retained objects must remain readable. The runtime can read and conditionally create content-addressed artifacts and -operation-owned `submission-source/v1//bundle.zip` objects. It can +operation-owned submission source objects at the exact keys defined in the +[submission specification](spec_submission_execution.md#101-object-layout-and-access). It can read exact source versions, but cannot delete versions or abort multipart uploads. Cleanup can read, abort and delete exact versions only in the managed source prefix; it cannot write sources or access content-addressed artifact bytes. @@ -51,7 +52,7 @@ Never interpret access denial as absence. Failed and retained submission sources share the same prefix. IAM cannot tell which source is accepted: the ART owner's committed cleanup claim, retention checks and exact-version confirmation remain the deletion authority. Never -expose a general delete-by-key operation or cleanup credentials to API workers. +expose a general delete-by-key operation or cleanup credentials to API processes. Keep S3 Block Public Access enabled, bucket-owner-enforced ownership, versioning and default SSE-S3 (`AES256`) encryption enabled. This policy does @@ -76,7 +77,7 @@ Git, logs or chat. Mount the file read-only only into services performing artifact operations. Beat, MCP, the document parser and checker guests do not need it. Configure the exact IAM user ARN alongside the private file path; startup must reject an unexpected identity or an ambient credential source. -The cleanup worker uses its own credential-file and IAM-ARN settings and an +The cleanup service uses its own credential-file and IAM-ARN settings and an explicit upload-principal ARN; composition rejects identical principals. ## Verify and rotate From 814f596fc75d83c0e337e6ff3e136707a2d2efe9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 15:14:26 +0100 Subject: [PATCH 285/513] fix(mcp): refresh pending submission schema descriptions --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 39 +++++++++++++++++++ mcp_server/contracts/management_task_get.json | 5 ++- .../management_task_work_context_get.json | 5 ++- mcp_server/contracts/task_get.json | 5 ++- .../contracts/task_work_context_get.json | 5 ++- 5 files changed, 51 insertions(+), 8 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index acc4f41d3..8d533e24f 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9161,3 +9161,42 @@ The AWS credential guide also names the dedicated Celery process explicitly and links the canonical source-key specification instead of duplicating its versioned key example. This resolves stale-vocabulary scan false positives without changing the scanner, IAM policy, runtime behavior or key format. + +### Refresh pending-operation MCP schema descriptions + +Configured backend OpenAPI comparison atc853743b6 passed142 and failed2 +in150.95s. Recursive comparison isolates the entire drift to the existing +PendingSubmissionOperation description missing from task_get, +task_work_context_get, management_task_work_context_get and management_task_get +snapshots. Allowed change: those four descriptions, canonical hashes and source +SHA provenance, plus this evidence. No schema properties, routes, validation, +authorization or product behavior changes. Low-risk contract metadata refresh; +root review and existing configured drift/tamper-evidence checks verify exact +backend equality. Human review focus: only description/hash/provenance differs. +The current full MCP run remains untouched until terminal. Clean wheel startup +passed1/15.91s with isolated installed wheels and no backend import availability +(/tmp/submission-mcp-wheel-current.log); this is package independence only. + +The native journey V3 stopped before PRE because its local runtime omitted the +existing isolated guide parser, and its cleanup profile had no distinct upload +principal. Its isolated PostgreSQL/MinIO cleanup completed. Root started the +existing parser image39fda85bf137cac056f0e04b1f59bb5ce908135ffb3899f568fd518b5c3be706 +with network disabled, read-only root, bounded RAM/CPU/process/tmp resources and +only KILL/SETGID/SETUID capabilities. Parser source is unchanged since609f59ed7. +An exact local client ACL permits host UID1000 access; socket10002:10001/0660 +and parent10002:10001/0750 remain enforced. A canonical client read of a +source-bound Markdown document passed; receipts are +/tmp/submission-guide-parser-{runtime,proof}.json. This local dependency repair +is not hosted activation or public submission acceptance evidence. + +Full non-integration MCP suite completed before the snapshot edit:955passed, +6environment-selected skips,1dependency deprecation warning in3563.09s +(/tmp/submission-mcp-current.log). Separately configured OpenAPI checks exposed +the two failures above; all other configured checks passed. After the exact +four-snapshot refresh, both affected modules passed45/34.62s, including live +backend OpenAPI equality, canonical hashes and current claim HTTP validation +(/tmp/submission-mcp-snapshot-repair.log). Together with the clean-wheel check, +these exercise the six environment-selected checks. Root compared parsed JSON +before/after: only the description, canonical hash and repository SHA differ. +No integration/deployed acceptance claim. Markdown links, Commitrail and diff +checks pass. diff --git a/mcp_server/contracts/management_task_get.json b/mcp_server/contracts/management_task_get.json index ec317ef6f..f4bccdb2e 100644 --- a/mcp_server/contracts/management_task_get.json +++ b/mcp_server/contracts/management_task_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "f82719a1566923d782b112b980104e5c471483fdd5951e9686fd73556a7b7d2e", + "canonical_sha256": "571a8b2e61768f696201e5d1b214b0f15c8a2bade24f6dbbf7f4c84b72c29500", "components": { "schemas": { "ApiError": { @@ -478,6 +478,7 @@ "type": "object" }, "PendingSubmissionOperation": { + "description": "Narrow current intake identity and stage, separate from Submission history.", "properties": { "operation_id": { "format": "uuid", @@ -1023,6 +1024,6 @@ "method": "GET", "openapi_version": "3.1.0", "path": "/api/v1/projects/{project_id}/tasks/{task_id}", - "repository_sha": "f0431385573eb53353c5ffc3c6cdb6a93d206b73" + "repository_sha": "c853743b689a46711c13e1d800cdd27ab8230ac2" } } diff --git a/mcp_server/contracts/management_task_work_context_get.json b/mcp_server/contracts/management_task_work_context_get.json index f188893b5..3b611eb91 100644 --- a/mcp_server/contracts/management_task_work_context_get.json +++ b/mcp_server/contracts/management_task_work_context_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "655e95deedfcaf6fa49a2791c4023a4236c2c2067bb0ea73054f89c3d6dd5b9e", + "canonical_sha256": "08d63eb0a192e59832c2ad3199225c2e9bbfe72fd54d2cd75958cd623e34afda", "components": { "schemas": { "ApiError": { @@ -586,6 +586,7 @@ "type": "object" }, "PendingSubmissionOperation": { + "description": "Narrow current intake identity and stage, separate from Submission history.", "properties": { "operation_id": { "format": "uuid", @@ -1183,6 +1184,6 @@ "method": "GET", "openapi_version": "3.1.0", "path": "/api/v1/projects/{project_id}/tasks/{task_id}/work-context", - "repository_sha": "f0431385573eb53353c5ffc3c6cdb6a93d206b73" + "repository_sha": "c853743b689a46711c13e1d800cdd27ab8230ac2" } } diff --git a/mcp_server/contracts/task_get.json b/mcp_server/contracts/task_get.json index 73b03f6a0..0b6863f63 100644 --- a/mcp_server/contracts/task_get.json +++ b/mcp_server/contracts/task_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "2974bc5e8d6c4c78b634000fcf5d39971b61c544d4aa7096d695db4552ab23ee", + "canonical_sha256": "410f10c19f0e2277cbca604cad4a80232d2c9a9f736a446111392945e1475d74", "components": { "schemas": { "ApiError": { @@ -234,6 +234,7 @@ "type": "object" }, "PendingSubmissionOperation": { + "description": "Narrow current intake identity and stage, separate from Submission history.", "properties": { "operation_id": { "format": "uuid", @@ -655,6 +656,6 @@ "method": "GET", "openapi_version": "3.1.0", "path": "/api/v1/tasks/{task_id}", - "repository_sha": "f0431385573eb53353c5ffc3c6cdb6a93d206b73" + "repository_sha": "c853743b689a46711c13e1d800cdd27ab8230ac2" } } diff --git a/mcp_server/contracts/task_work_context_get.json b/mcp_server/contracts/task_work_context_get.json index ff2c25d24..e59472aa9 100644 --- a/mcp_server/contracts/task_work_context_get.json +++ b/mcp_server/contracts/task_work_context_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "9f69f02d8981989465c20891d3c9676c1e09d437ea99c6fbe7860cd071e1c941", + "canonical_sha256": "cb9b06d69399d48ef7672b9a32f17e96f6afbf33d80924d0f3a3a94d54fb3015", "components": { "schemas": { "ApiError": { @@ -612,6 +612,7 @@ "type": "object" }, "PendingSubmissionOperation": { + "description": "Narrow current intake identity and stage, separate from Submission history.", "properties": { "operation_id": { "format": "uuid", @@ -1274,6 +1275,6 @@ "method": "GET", "openapi_version": "3.1.0", "path": "/api/v1/tasks/{task_id}/work-context", - "repository_sha": "8b068f2b788f159b1085d47f162c39ce3323d5b6" + "repository_sha": "c853743b689a46711c13e1d800cdd27ab8230ac2" } } From 4652f39bd0c990174985bdf7ff2baa8bcff498b8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 15:23:50 +0100 Subject: [PATCH 286/513] Modernize connected CLI incident-summary submission journey --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 85 +++++ cli/README.md | 113 +++--- cli/internal/api/admin_inspection.go | 1 + .../integration/test_admin_mutations_http.py | 20 ++ cli/tests/journey/artifact_work.py | 18 +- cli/tests/journey/bootstrap.py | 57 +++- cli/tests/journey/client.py | 2 +- cli/tests/journey/public_setup.py | 152 ++++++--- cli/tests/journey/runtime.py | 306 +++++++++++++---- cli/tests/journey/source_audit.py | 190 +++++++++++ cli/tests/journey/submission_work.py | 321 +++++++++++------- cli/tests/journey/task_work.py | 52 +-- pilots/terminal_systems/mvp/registry.py | 83 +++++ 13 files changed, 1080 insertions(+), 320 deletions(-) create mode 100644 cli/tests/journey/source_audit.py create mode 100644 pilots/terminal_systems/mvp/registry.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8d533e24f..124c7523e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9200,3 +9200,88 @@ these exercise the six environment-selected checks. Root compared parsed JSON before/after: only the description, canonical hash and repository SHA differ. No integration/deployed acceptance claim. Markdown links, Commitrail and diff checks pass. + +Next bounded change: modernize the existing connected public CLI journey in +`cli/tests/journey` and its current `cli/README.md` instructions. The present +script still calls removed `task prepare` and `task submit --admission`, runs a +local native checker socket, and registers Harnessy proof declarations that +need unavailable forge facts. Replace those steps with current raw ZIP +`task submit` and `task submission-operation` reads, the deterministic +`pilots/terminal_systems/mvp` correct/incorrect/pre-missing ZIPs and matching +PRE/POST registry entries, an explicitly configured remote TLS runner, and +the existing real API/Redis/MinIO/PostgreSQL worker path. Keep public setup, +claim, retained submission, governed outcome, contribution, replay, Operator +custody and exact award checks in the same journey. Run a separate default +human-review branch through public review commands if the current contracts +support it. No mocked checker, model, authority, provider or synthetic +Submission/Review/Contribution. No production, schema, deployment or external +service changes; runner image installation is a separate owned prerequisite. + +Allowed files: existing `cli/tests/journey/*.py`, the pilot's bounded +`pilots/terminal_systems/mvp/registry.py` input generator, its +connected-journey documentation in `cli/README.md`, and this record. Required inputs are +explicit runner TLS host/port/server name/CA/client certificate/key, exact +intake image/config digests, measured submission execution and cleanup +profiles, PRE/POST registry JSON and pinned image; missing inputs fail before +API or worker start. Worker queues must include exclusive finalization and +source cleanup consumers. Preserve resource ownership/cleanup of this +isolated local drill. Risk: high integration and process custody; require +focused pure tests, static/lint/structure checks, exact real PG/MinIO/Redis +and runner execution with cleanup metadata, then scoped review. Partial setup +or source acceptance cannot be reported as full governed-acceptance proof. + +Current scope resolution: the user keeps live human review deferred. The +public default-review branch must stop at `review_pending` and prove it did +not fabricate a Review or Contribution; the main locked-false branch must +reach real automatic acceptance. No human-review API or CLI operation is +added here. + +The first isolated run failed before its first CLI call because the evidence +directory parent was not created; both isolated database and MinIO cleanup +completed. After fixing that setup defect, the second run passed public +identity, authority and Project creation. It then exposed a stale CLI-local +service-identity allowlist: the backend accepts +`workstream.artifact.source_cleanup`, but `admin service-actor provision` +rejected it as `invalid_arguments` before issuing HTTP. The bounded change +therefore also allows the exact identity in +`cli/internal/api/admin_inspection.go` and its existing admin HTTP contract +module. The rebuilt CLI passed all 25 focused admin mutation contracts, +including the new positive provisioning case and existing unknown-identity +negative. That second run also cleaned its isolated database and MinIO bucket; +neither diagnostic run reached the external checker. + +The third isolated run passed service provisioning and public Project setup, +then its guide compilation stayed queued and timed out. The real guide +compiler requires the hardened fixed-parser socket; this launcher had not +supplied one. The dedicated cleanup child also exited at startup: the +test cleanup profile's null `upload_principal` and shared upload credential +violated its separate-provider-principal guard. The root-owned local parser +now serves a source-bound Markdown read under its fixed UID/GID/socket modes. +The journey uses an independently owned local MinIO instance with a distinct +read/write cleanup IAM user, a private secret file and an explicit profile +naming the actual foreground upload principal. Only the exclusive cleanup +worker receives the second credential. Parser identity, credential separation +and all named files are checked before API startup; a worker process exiting +during startup now fails early. The third run's isolated database and bucket +were removed; it did not reach PRE or POST. These are local drill prerequisites, +not hosted credential or parser qualification. + +With those prerequisites, the fourth isolated run reached the real parser and +finished guide compilation as `compilation_invalid_terminal/unsafe_text`. +The sole offending authored prose was a slash-joined count phrase in one +POST check step. It was rewritten as plain prose; the unchanged production +untrusted-result model now validates the authored fixture before API startup. +An in-memory restoration of the slash phrase fails that preflight at the +exact check-step field. No checker runner call occurred in this fourth run; +database and bucket cleanup both completed. + +The connected drill now checks the accepted Contribution's original ZIP hash +directly. A separate read-only query in the isolated database compares each +finalized operation, sealed physical charge, source admission, replica and +content to the public operation/submission and exact uploaded ZIP; it also +counts Submission, dispatch, POST run, acceptance, Review, Contribution and +award rows for each auto-acceptance, failed-POST and review-pending Task. The +audit performs no state transitions. Its SQL graph parsed and ran against a +fresh migrated isolated database; the deliberately absent operation yielded +the expected missing-graph assertion, and that database was cleaned. A +successful live graph is still pending the next end-to-end run. diff --git a/cli/README.md b/cli/README.md index 04d6c523d..76ca014e0 100644 --- a/cli/README.md +++ b/cli/README.md @@ -2206,60 +2206,87 @@ or extra branch-protection setting is needed. `tests/journey/bootstrap.py` exercises the built CLI against a fresh migrated PostgreSQL database, real MinIO, a private Redis broker, prefork Celery workers -and the real external checker service. It creates product prerequisites through -public CLI operations. The documented local administrator bootstrap and lifecycle -deployment transition are explicit deployment prerequisites, not fixture-created -project, submission or acceptance records. +(including exclusive finalization and source-cleanup queues), and one pinned +remote TLS checker runner. It creates project, guide, task, assignment and +submission prerequisites through public CLI operations. The local administrator +bootstrap and lifecycle transition remain explicit deployment prerequisites. +The script never starts a native checker socket or silently falls back to one. -This drill currently targets a Linux Docker host whose daemon can bind-mount the -same local scratch paths. Install the backend environment, Go, Rust, Docker and -`redis-server`. Use the local PostgreSQL/MinIO prerequisites and proof-checker -publication instructions in the [local agent loop](../docs/engineering/local-agent-loop.md) -to generate `.local-agent-loop/checker-service.json`, `registry-pre.json` and -`registry-post.json`. The drill starts its own native API, worker and checker -processes; it does not use an already-running application database or broker. +Build the CLI and generate two exact registration inputs from the already +installed [incident-summary pilot](../pilots/terminal_systems/mvp/README.md): -From the repository root: +```sh +(cd cli && go build -trimpath -o /tmp/workstream-journey-cli ./cmd/workstream) +export WORKSTREAM_CLI_EXECUTABLE=/tmp/workstream-journey-cli +python pilots/terminal_systems/mvp/registry.py \ + --image-digest "$PINNED_INCIDENT_IMAGE_MANIFEST_SHA256" \ + --pre "$PRIVATE_ASSETS/registry-pre.json" \ + --post "$PRIVATE_ASSETS/registry-post.json" +``` + +The runner image must already be installed and qualified for its exact +platform manifest/config and PRE root profile. Supply a locally owned, +strictly authenticated SSH tunnel to the private runner; the API connects to +loopback but verifies the runner's TLS server name. The real hardened guide +parser must also be running at a socket owned by UID 10002/GID 10001 with its +fixed directory and socket modes. The exclusive source-cleanup worker needs +a separate MinIO access key with permission on this disposable bucket; its +private secret file must have mode 0600. The cleanup profile's +`upload_principal` names the foreground upload access key, so the worker can +reject accidental reuse of that credential. Export every input below +before running the drill. No credential or runtime profile is inferred from a +local Docker installation: ```sh -(cd cli && go build -trimpath -o ../.local-agent-loop/workstream ./cmd/workstream) -cargo build --manifest-path external_checkers/Cargo.toml --locked --release \ - -p workstream-checker-service --jobs 2 -export WORKSTREAM_CLI_EXECUTABLE="$PWD/.local-agent-loop/workstream" +export WORKSTREAM_EXTERNAL_RUNNER_HOST=127.0.0.1 +export WORKSTREAM_EXTERNAL_RUNNER_PORT="$OWNED_TUNNEL_PORT" +export WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME=runner.workstream.internal +export WORKSTREAM_EXTERNAL_RUNNER_CA_PATH="$PRIVATE_TLS/ca.crt" +export WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH="$PRIVATE_TLS/app.crt" +export WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH="$PRIVATE_TLS/app.key" +export WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST="$PINNED_INTAKE_IMAGE_SHA256" +export WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST="$PINNED_INTAKE_CONFIG_SHA256" +export WORKSTREAM_CLI_JOURNEY_CHECKER_IMAGE_DIGEST="$PINNED_INCIDENT_IMAGE_MANIFEST_SHA256" +export WORKSTREAM_CLI_JOURNEY_PRE_RUNTIME_PROFILE_FILE="$PRIVATE_ASSETS/pre-runtime-profile.json" +export WORKSTREAM_CLI_JOURNEY_EXECUTION_PROFILE_FILE="$PRIVATE_ASSETS/isolated-execution-profile.json" +export WORKSTREAM_CLI_JOURNEY_CLEANUP_PROFILE_FILE="$PRIVATE_ASSETS/isolated-cleanup-profile-journey.json" +export WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID="$OWNED_CLEANUP_ACCESS_KEY" +export WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE="$PRIVATE_ASSETS/cleanup-secret" +export WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET="$OWNED_PARSER_SOCKET" +export WORKSTREAM_CLI_JOURNEY_REGISTRY_PRE_FILE="$PRIVATE_ASSETS/registry-pre.json" +export WORKSTREAM_CLI_JOURNEY_REGISTRY_POST_FILE="$PRIVATE_ASSETS/registry-post.json" export WORKSTREAM_CLI_JOURNEY_SETUP=1 export WORKSTREAM_CLI_JOURNEY_TASKS=1 export WORKSTREAM_CLI_JOURNEY_SUBMIT=1 -# Optional private raw CLI receipts for independent review; keep outside git. export WORKSTREAM_CLI_JOURNEY_EVIDENCE="$(mktemp -d /tmp/workstream-journey-evidence.XXXXXX)" -# Supply a disposable local PostgreSQL admin URL and the local MinIO endpoint -# through WORKSTREAM_TEST_ADMIN_DATABASE_URL and WORKSTREAM_TEST_MINIO_ENDPOINT. +# Supply disposable PostgreSQL and local MinIO prerequisites through +# WORKSTREAM_TEST_ADMIN_DATABASE_URL and WORKSTREAM_TEST_MINIO_ENDPOINT. cd backend .venv/bin/python scripts/run_isolated_tests.py \ --metadata-json /tmp/workstream-cli-journey-isolation.json \ - --lane cli_full_journey --timeout-seconds 900 -- \ + --lane cli_full_journey --timeout-seconds 2400 -- \ .venv/bin/python ../cli/tests/journey/bootstrap.py ``` -Use the isolated runner's fixed local test MinIO credentials, never production -credentials. Each run owns a unique database/role and bucket/prefix. Require its -cleanup metadata as well as exit zero; neither a completed migration nor a -successful intermediate stage proves the remaining journey. Do not bypass a -failed prerequisite or substitute a synthetic checker result. -The optional evidence directory retains command arguments, exit codes and raw -stdout/stderr after checking for bearer disclosure. It contains local project -data: keep it private and do not commit it. Use a fresh directory for each run. -Setup-enabled runs also retain private runtime logs after stopping their owned -processes. These logs are diagnostic evidence, not proof that a failed stage -succeeded. To verify an explicitly reviewed checker repair before merge, set -`WORKSTREAM_CLI_JOURNEY_CHECKER_EXECUTABLE` to its built binary and record that -binary's SHA-256 and source commit; this is cross-branch integration evidence. - -The scope is manager-authored setup, an explicitly unpaid policy and the locked -no-human-review acceptance branch. The example checker validates declared proof -fields, not the truth of remote GitHub work. This is not hosted deployment, -external Flow issuer, live model inference, human review/revision or compensation -fulfillment certification. The connected proof also reads the exact submission's -artifact binding, replica and verification evidence through the Operator CLI, -and checks non-Operator concealment. The separate signed API test exercises -retry only on a genuinely exhausted verification job. A successful upload is -never used as an eligible retry fixture. +The bootstrap preflights all TLS files, profiles, parser socket, cleanup +credential separation, registry schemas and image +pins before starting its API or workers. The two isolated profiles are +explicit test envelopes for the small pilot ZIPs, not approved hosted defaults +or maximum-size qualification. Each run owns a database, role, bucket/prefix, +broker and worker process groups. Require cleanup metadata as well as exit zero; +a completed migration or intermediate stage does not prove the journey. The +private evidence directory contains raw CLI receipts and runtime logs; keep it +outside Git and do not publish tokens or arbitrary server output. + +The drill submits a PRE-rejected missing-summary ZIP without a Submission, a +correct ZIP through immutable Submission, passing POST, automatic +FinalAcceptance and one unpaid submitter ContributionRecord, and a shaped but +incorrect ZIP through failed POST and governed revision without contribution. +It then configures a second project with the default human-review policy and +observes `review_pending` without a fabricated contribution. The public review +mutation and human acceptance authority are not mounted, so this drill does not +claim a live human-review decision or acceptance. It also checks exact replay, +public retained evidence, Operator custody and non-Operator concealment. +The real checker validates only the fixed incident-summary exercise; this is +not hosted deployment, external Flow issuer, model inference, broad ZIP-size +performance qualification or compensation fulfillment certification. diff --git a/cli/internal/api/admin_inspection.go b/cli/internal/api/admin_inspection.go index 19e5aa1af..a7201919b 100644 --- a/cli/internal/api/admin_inspection.go +++ b/cli/internal/api/admin_inspection.go @@ -171,6 +171,7 @@ func validServiceIdentity(value string) bool { return oneOf(value, "workstream.artifact.verifier", "workstream.artifact.put_resolver", "workstream.artifact.scheduler", "workstream.artifact.binding", + "workstream.artifact.source_cleanup", "workstream.artifact.guide_reader", "workstream.artifact.materializer", "workstream.artifact.checker_output", "workstream.task.assignment_reconciler", "workstream.task.revision_expirer", "workstream.task.post_submit_router", diff --git a/cli/tests/integration/test_admin_mutations_http.py b/cli/tests/integration/test_admin_mutations_http.py index c24d23a85..0ec7cbe53 100644 --- a/cli/tests/integration/test_admin_mutations_http.py +++ b/cli/tests/integration/test_admin_mutations_http.py @@ -46,6 +46,26 @@ def service_receipt(): } +def test_current_source_cleanup_service_identity_reaches_public_provision( + cli, tmp_path +): + identity = "workstream.artifact.source_cleanup" + file = tmp_path / "service.json" + file.write_text(json.dumps(service_body() | {"service_identity": identity})) + with http_fixture() as (origin, response, requests): + response.update( + status=201, + body=json.dumps( + service_receipt() | {"service_identity": identity} + ).encode(), + ) + result = invoke(cli, origin, file, "service-actor", "provision") + assert result.returncode == 0 + assert json.loads(result.stdout)["service_identity"] == identity + assert len(requests) == 1 + assert requests == [("POST", "/api/v1/service-actors", "Bearer " + TOKEN)] + + def lifecycle_receipt(resource, selected, *, version=None): return { "resource_type": resource, diff --git a/cli/tests/journey/artifact_work.py b/cli/tests/journey/artifact_work.py index b2e0ef336..770222bde 100644 --- a/cli/tests/journey/artifact_work.py +++ b/cli/tests/journey/artifact_work.py @@ -29,14 +29,16 @@ def read(*arguments): # This route excludes nulls, including an exhausted page's next_cursor. if receipts.get("next_cursor") is not None: raise AssertionError("isolated custody receipts unexpectedly exceed one page") - verified = [ - item for item in receipts["items"] if item["receipt_type"] == "verification" - ] - if len(verified) != 1 or verified[0]["replica_id"] != replica["id"]: - raise AssertionError("submission replica lacks exact verification evidence") - job = read("verification-job", verified[0]["verification_job_id"]) - if job["replica_id"] != replica["id"] or job["receipt_id"] != verified[0]["id"]: - raise AssertionError("verification job differs from the retained receipt") + if ( + replica["verification_state"] != "verified" + or replica["availability_state"] != "available" + or replica["integrity_state"] != "valid" + ): + raise AssertionError("accepted source replica lacks retained verified custody") + # Source-first T5 retains the sealed source itself. It does not synthesize + # the retired put/verification job lineage for the same provider version. + if any(item["receipt_type"] == "verification" for item in receipts["items"]): + raise AssertionError("source-first binding invented old verifier lineage") read("audit-events", "artifact_binding", binding["id"]) read("admission-usage", project_id, "--task-id", task_id) read("readiness") diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py index dfb4f882a..6bcfdc15f 100644 --- a/cli/tests/journey/bootstrap.py +++ b/cli/tests/journey/bootstrap.py @@ -21,9 +21,9 @@ from client import JourneyClient from public_setup import configure_guide, publish_unpaid_terms, approve_and_activate -from runtime import durable_runtime -from task_work import claim_and_read -from submission_work import submit_and_observe +from runtime import durable_runtime, load_journey_configuration +from task_work import claim_and_read, create_claimed_task, issue_submitter +from submission_work import submit_and_observe, observe_review_pending from artifact_work import inspect_submission_custody ROOT = Path(__file__).resolve().parents[3] @@ -35,6 +35,49 @@ from urllib.parse import urlsplit # noqa: E402 +def run_default_review_branch(client, tokens, actors, registry_entries): + """Use the same public setup but leave required human review untouched.""" + project = client.call( + tokens["manager"], + "project", + "create", + "--name", + "CLI incident review branch", + "--slug", + "cli-review-" + uuid4().hex, + "--idempotency-key", + str(uuid4()), + ) + project_id = project["id"] + for name, role in ( + ("manager", "project_manager"), + ("finance", "finance_authority"), + ): + client.write_and_replay( + tokens["administrator"], + "admin", + "role-grants", + "issue", + body={ + "target_actor_profile_id": actors[name], + "role": role, + "scope_type": "project", + "scope_project_id": project_id, + "reason": "Exact-project default review branch", + }, + ) + publish_unpaid_terms(client, tokens["finance"], project_id) + guide_id = configure_guide(client, tokens, project_id, human_review_required=True) + approve_and_activate( + client, tokens["manager"], project_id, guide_id, registry_entries + ) + issue_submitter(client, tokens["manager"], actors["alice"], project_id) + task_id, assignment_id = create_claimed_task( + client, tokens, project_id, title="Human review of incident summary" + ) + observe_review_pending(client, tokens, project_id, task_id, assignment_id) + + def main(): import app @@ -77,6 +120,7 @@ def main(): directory = Path(temporary) through_setup = os.environ.get("WORKSTREAM_CLI_JOURNEY_SETUP") == "1" if through_setup: + registries = load_journey_configuration(environment) start_workers = stack.enter_context( durable_runtime(ROOT, directory, environment) ) @@ -218,6 +262,7 @@ def main(): "artifact.binding", "artifact.guide_reader", "artifact.materializer", + "artifact.source_cleanup", "project.setup", "outbox.dispatcher", "checker.pre_submit", @@ -246,7 +291,7 @@ def main(): "registry", "register", "--input", - str(ROOT / f".local-agent-loop/registry-{phase}.json"), + str(registries[phase]), "--idempotency-key", str(uuid4()), ) @@ -305,6 +350,10 @@ def main(): receipt["submission_id"], ) client.complete_stage("operator_submission_custody") + run_default_review_branch( + client, tokens, actors, registry_entries + ) + client.complete_stage("default_human_review_pending") print( json.dumps( { diff --git a/cli/tests/journey/client.py b/cli/tests/journey/client.py index 070241445..9c558ae7b 100644 --- a/cli/tests/journey/client.py +++ b/cli/tests/journey/client.py @@ -20,7 +20,7 @@ def __init__(self, executable: Path, origin: str, directory: Path): self.evidence = None if location := os.environ.get("WORKSTREAM_CLI_JOURNEY_EVIDENCE"): self.evidence = Path(location) / "cli-receipts" - self.evidence.mkdir(mode=0o700) + self.evidence.mkdir(mode=0o700, parents=True) def complete_stage(self, stage: str): self.completed_stages.append(stage) diff --git a/cli/tests/journey/public_setup.py b/cli/tests/journey/public_setup.py index 346bc3c2e..fd1313447 100644 --- a/cli/tests/journey/public_setup.py +++ b/cli/tests/journey/public_setup.py @@ -2,17 +2,14 @@ import hashlib import json +from pathlib import Path import time from uuid import uuid4 -GUIDE = b"""# Local CLI contract exercise -Submit proof.json at the ZIP root. This exercise checks the format of declared -proof claims only; it does not verify any remote work or award compensation. -Both intake and post-submission evaluation use the registered harnessy.work_proof -checker. Claims must use harnessy.work.proof.v1, a forty-digit hexadecimal commit, -GitHub HTTPS PR and CI URLs, success CI conclusion, and merged true. -""" +PILOT = Path(__file__).resolve().parents[3] / "pilots/terminal_systems/mvp" +GUIDE = (PILOT / "guide.md").read_bytes() +TASK = (PILOT / "task.md").read_text(encoding="utf-8") def poll(client, token, arguments, predicate): @@ -32,61 +29,86 @@ def poll(client, token, arguments, predicate): def authored_rules(): + """Manager-authored suggestions for the real incident-summary PRE/POST image.""" reference = {"document": "sha256:" + hashlib.sha256(GUIDE).hexdigest()} requirements = [] - for phase in ("pre_submit", "post_submit"): + for phase, check in ( + ("pre_submit", "incident_summary_layout"), + ("post_submit", "incident_summary_counts"), + ): + post = phase == "post_submit" + code = "terminal.incident_summary." + ( + "incorrect_counts" if post else "invalid_layout" + ) requirements.append( { - "suggestion_id": f"proof.{phase}", - "statement": "Validate the declared proof fields.", + "suggestion_id": f"incident.{phase}", + "statement": ( + "Verify the fixed event file and exact per-service counts." + if post + else "Require the fixed event file and a shaped summary." + ), "stage": phase, "evidence_refs": [reference], - "classification_rationale": "Static inspection can validate declared fields, without verifying remote work.", + "classification_rationale": ( + "Offline image evaluation compares the submitted output with the fixed input." + if post + else "Offline image inspection checks required root files and JSON shape." + ), "check_specification": { - "evaluation_method": "Inspect the declared proof fields in proof.json.", + "evaluation_method": "Execute the pinned offline incident-summary checker image.", "inputs": [ { - "input_id": "proof", + "input_id": "incident_files", "kind": "relative_file", - "relative_path": "proof.json", - "purpose": "Declared proof claims, without network verification.", + "relative_path": "summary.json", + "purpose": "Contributor output to inspect with the fixed events.jsonl input.", } ], - "check_steps": [ - "Require a regular proof.json of at most 65536 bytes containing a UTF-8 JSON object.", - "Require schema harnessy.work.proof.v1 and commit_sha of exactly 40 hexadecimal characters.", - "Require pr_url and ci_run_url with scheme https, authority github.com and a non-root path.", - "Require ci_conclusion success and merged equal to the JSON boolean true.", - ], + "check_steps": ( + [ + "Require root events.jsonl equal to the fixed seven incident events.", + "Require root summary.json with the services array and exact per-service total and error counts.", + ] + if post + else [ + "Require root events.jsonl with the fixed seven incident events.", + "Require root summary.json as a JSON object with a nonempty services array.", + ] + ), "pass_conditions": [ - "All declared proof fields satisfy the static predicates." + "The pinned image returns passed with no error findings." ], "failure_findings": [ { - "code": "harnessy.proof.invalid_json", + "code": code, "level": "error", - "condition": "proof.json is not a UTF-8 JSON object.", - "message": "proof.json must contain a valid JSON object.", + "condition": "The submitted files violate this phase's incident summary check.", + "message": "Correct the incident summary files and submit again.", } ], "positive_tests": [ - "A JSON object satisfying every stated field predicate passes." + "The supplied correct ZIP passes the selected phase." ], "negative_tests": [ { - "name": "invalid_json", - "scenario": "proof.json contains malformed JSON.", + "name": "incorrect_counts" if post else "missing_summary", + "scenario": ( + "The shaped summary has incorrect per-service counts." + if post + else "The summary.json root file is absent." + ), "expected_verdict": "failed", - "expected_finding_codes": ["harnessy.proof.invalid_json"], + "expected_finding_codes": [code], } ], "implementation_needs": [ - "Implement a JSON parser and the listed static field predicates." + "Use the registered incident-summary image and fixed events input." ], "inability_to_evaluate": [ { - "code": "harnessy.proof.unreadable", - "condition": "proof.json cannot be read as candidate content.", + "code": "terminal.incident_summary.unavailable", + "condition": "The pinned image or material is unavailable.", } ], }, @@ -99,21 +121,38 @@ def authored_rules(): { "severity": "info", "code": "guide.ready", - "message": "Explicit unpaid format-validation exercise.", + "message": "Fixed incident summary with pinned offline PRE and POST checks.", "evidence_refs": [reference], } ], "submission_artifact_policy": { - "maximum_file_size_bytes": 1000000, - "maximum_package_size_bytes": 5000000, - "required_artifacts": ["proof.json"], + "maximum_file_size_bytes": 1_000_000, + "maximum_package_size_bytes": 5_000_000, + "required_artifacts": ["events.jsonl"], }, "requirements": requirements, "setup_notes": [], } -def configure_guide(client, tokens, project_id): +def validate_authored_rules_template(): + """Apply the production untrusted-result schema before starting a live run.""" + from app.interfaces.project_agents import ProjectGuideCompilationResult + + body = authored_rules() + body.pop("format") + reference = { + "source_item_id": "018f0ebc-7966-7e8d-bc4d-1cae1e000001", + "document_version_id": "018f0ebc-7966-7e8d-bc4d-1cae1e000002", + "sha256": "sha256:" + hashlib.sha256(GUIDE).hexdigest(), + } + for item in (*body["findings"], *body["requirements"]): + item["evidence_refs"] = [reference] + body["agent_version"] = "v1" + ProjectGuideCompilationResult.model_validate(body) + + +def configure_guide(client, tokens, project_id, *, human_review_required=False): manager = tokens["manager"] guide = client.write_and_replay( manager, @@ -122,9 +161,9 @@ def configure_guide(client, tokens, project_id): "create", project_id, body={ - "version": "cli-exercise", - "change_summary": "Unpaid local CLI journey", - "task_examples": [{"content": "Prepare the declared proof fields."}], + "version": "incident-summary-v1", + "change_summary": "Fixed incident-summary CLI journey", + "task_examples": [{"content": TASK}], "documents": [ {"label": "Guide.md", "media_type": "text/markdown"}, {"label": "workstream-rules.json", "media_type": "text/markdown"}, @@ -132,20 +171,25 @@ def configure_guide(client, tokens, project_id): }, ) guide_id = guide["id"] - for command, body in ( - ( - "set-review-policy", - { - "human_review_required": False, - "review_preference_window_seconds": 3600, - "review_lease_duration_seconds": 1800, - }, - ), + policies = [ ( "set-revision-policy", {"max_revision_rounds": 2, "revision_deadline_hours": 48}, ), - ): + ] + if not human_review_required: + policies.insert( + 0, + ( + "set-review-policy", + { + "human_review_required": False, + "review_preference_window_seconds": 3600, + "review_lease_duration_seconds": 1800, + }, + ), + ) + for command, body in policies: client.write_and_replay( manager, "project", @@ -275,18 +319,18 @@ def approve_and_activate(client, token, project_id, guide_id, registry_entries): "target": proposal["target"], "pre_submit_attachments": [ { - "requirement_id": "project.proof_pre", + "requirement_id": "terminal.pre.incident_summary_layout", "registry_entry_id": registry_entries["pre"]["registry_entry_id"], "registry_entry_digest": registry_entries["pre"]["entry_digest"], - "configuration": {}, + "configuration": {"check": "incident_summary_layout"}, } ], "post_submit_attachments": [ { - "requirement_id": "project.proof_post", + "requirement_id": "terminal.post.incident_summary_counts", "registry_entry_id": registry_entries["post"]["registry_entry_id"], "registry_entry_digest": registry_entries["post"]["entry_digest"], - "configuration": {}, + "configuration": {"check": "incident_summary_counts"}, } ], "acknowledged_warning_hashes": [], diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index f003f91db..d3d589861 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -1,48 +1,193 @@ -"""Owned local Redis, real checker service and prefork workers for the drill.""" +"""Owned Redis and dedicated workers for the remote-runner CLI drill.""" from contextlib import contextmanager import json import os from pathlib import Path +import re import shutil +import signal import socket +import stat import subprocess import sys import time +SHA256 = re.compile(r"sha256:[0-9a-f]{64}\Z") +PILOT_CHECKS = { + "pre": ("pre_submit", "incident_summary_layout"), + "post": ("post_submit", "incident_summary_counts"), +} + + +def _required_file(environment: dict[str, str], name: str, *, limit: int) -> Path: + raw = environment.get(name) + if not raw: + raise RuntimeError(f"journey requires {name}") + path = Path(raw) + if path.is_symlink() or not path.is_file(): + raise RuntimeError(f"journey requires a regular {name}") + size = path.stat().st_size + if size <= 0 or size > limit: + raise RuntimeError(f"journey {name} has an invalid size") + return path.resolve(strict=True) + + +def _required_json(environment: dict[str, str], name: str) -> tuple[Path, dict]: + path = _required_file(environment, name, limit=1_048_576) + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (UnicodeError, ValueError) as exc: + raise RuntimeError(f"journey {name} is not JSON") from exc + if type(value) is not dict: + raise RuntimeError(f"journey {name} must be an object") + return path, value + + +def load_journey_configuration(environment: dict[str, str]) -> dict[str, Path]: + """Validate every external pin before API, worker or provider startup.""" + from jsonschema import Draft202012Validator + + from app.adapters.artifacts import selected_pre_submit_source_contracts + from app.modules.artifacts.api.submission_cleanup import ( + SubmissionSourceCleanupProfile, + ) + from app.modules.artifacts.api.submission_command import SubmissionExecutionProfile + from app.modules.checkers.api.external import ExternalCheckerRegistrySpec + from app.modules.checkers.api.source_contracts import source_contracts_context + from public_setup import validate_authored_rules_template + + host = environment.get("WORKSTREAM_EXTERNAL_RUNNER_HOST") + port = environment.get("WORKSTREAM_EXTERNAL_RUNNER_PORT") + server_name = environment.get("WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME") + if ( + host != "127.0.0.1" + or not port + or not port.isdecimal() + or not 1 <= int(port) <= 65_535 + or not server_name + ): + raise RuntimeError("journey requires an explicit loopback TLS runner tunnel") + for name in ( + "WORKSTREAM_EXTERNAL_RUNNER_CA_PATH", + "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH", + "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH", + ): + environment[name] = str(_required_file(environment, name, limit=1_048_576)) + for name in ( + "WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST", + "WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST", + "WORKSTREAM_CLI_JOURNEY_CHECKER_IMAGE_DIGEST", + ): + if SHA256.fullmatch(environment.get(name, "")) is None: + raise RuntimeError(f"journey requires exact {name}") + + _, selected_runtime = _required_json( + environment, "WORKSTREAM_CLI_JOURNEY_PRE_RUNTIME_PROFILE_FILE" + ) + _, execution = _required_json( + environment, "WORKSTREAM_CLI_JOURNEY_EXECUTION_PROFILE_FILE" + ) + _, cleanup = _required_json( + environment, "WORKSTREAM_CLI_JOURNEY_CLEANUP_PROFILE_FILE" + ) + profile = SubmissionExecutionProfile.model_validate( + execution, + context=source_contracts_context(selected_pre_submit_source_contracts()), + ) + cleanup_profile = SubmissionSourceCleanupProfile.model_validate(cleanup) + if cleanup_profile.upload_principal != "workstream-minio": + raise RuntimeError("journey cleanup profile must identify the upload principal") + cleanup_key = environment.get("WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID") + if not cleanup_key or cleanup_key == cleanup_profile.upload_principal: + raise RuntimeError("journey requires a distinct cleanup access key") + secret_path = _required_file( + environment, "WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE", limit=4096 + ) + if stat.S_IMODE(secret_path.stat().st_mode) != 0o600: + raise RuntimeError("journey cleanup secret file must be private") + parser_path = Path(environment.get("WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET", "")) + if not parser_path.is_absolute() or not parser_path.is_socket(): + raise RuntimeError("journey requires the real guide parser socket") + parser_stat = parser_path.stat() + parent_stat = parser_path.parent.stat() + if (parser_stat.st_uid, parser_stat.st_gid, stat.S_IMODE(parser_stat.st_mode)) != ( + 10_002, + 10_001, + 0o660, + ) or ( + parent_stat.st_uid, + parent_stat.st_gid, + stat.S_IMODE(parent_stat.st_mode), + ) != (10_002, 10_001, 0o750): + raise RuntimeError( + "journey guide parser custody differs from the fixed service" + ) + if profile.runtime.model_dump(mode="json") != selected_runtime: + raise RuntimeError("journey PRE runtime differs from qualified profile") + + registry_files = {} + for name, (phase, check) in PILOT_CHECKS.items(): + path, body = _required_json( + environment, f"WORKSTREAM_CLI_JOURNEY_REGISTRY_{name.upper()}_FILE" + ) + spec = ExternalCheckerRegistrySpec.model_validate(body) + if ( + spec.phase != phase + or spec.image_digest + != environment["WORKSTREAM_CLI_JOURNEY_CHECKER_IMAGE_DIGEST"] + ): + raise RuntimeError("journey checker phase or pinned image differs") + if ( + spec.resources.cpu_millis > profile.runtime.cpu_millis + or spec.resources.memory_bytes > profile.runtime.memory_bytes + or spec.resources.maximum_output_bytes + > profile.runtime.maximum_output_bytes + or spec.resources.deadline_ms > profile.runtime.aggregate_deadline_ms + ): + raise RuntimeError("journey checker exceeds qualified PRE resources") + if not Draft202012Validator(spec.configuration_schema.document).is_valid( + {"check": check} + ): + raise RuntimeError("journey registry rejects its selected check") + registry_files[name] = path + + environment.update( + WORKSTREAM_SUBMISSION_EXECUTION_PROFILE=json.dumps(execution, sort_keys=True), + WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE=json.dumps( + cleanup, sort_keys=True + ), + WORKSTREAM_EXTERNAL_CHECKER_SERVICE_TIMEOUT_SECONDS=str( + profile.runtime.aggregate_deadline_ms / 1000 + ), + ) + environment.pop("WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET", None) + validate_authored_rules_template() + return registry_files + + @contextmanager -def durable_runtime(root: Path, directory: Path, environment: dict): +def durable_runtime(root: Path, directory: Path, environment: dict[str, str]): + """Start only owned local broker/worker groups; runner lives outside this host.""" processes, logs = [], [] - def start(arguments, label): + def start(arguments: list[str], label: str, *, extra_environment=None): log = (directory / (label + ".log")).open("wb") logs.append(log) process = subprocess.Popen( arguments, cwd=root / "backend", - env=environment, + env=environment | (extra_environment or {}), stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, ) processes.append(process) return process scratch = directory / "scratch" scratch.mkdir(mode=0o700) - checker_socket = directory / "checker.sock" - configuration = json.loads( - (root / ".local-agent-loop/checker-service.json").read_text() - ) - configuration.update( - socket_path=str(checker_socket), - material_root=str(scratch), - docker_binary=str(Path(shutil.which("docker")).resolve(strict=True)), - sandbox_uid=os.getuid(), - sandbox_gid=os.getgid(), - ) - config_file = directory / "checker.json" - config_file.write_text(json.dumps(configuration)) with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) redis_port = sock.getsockname()[1] @@ -53,7 +198,6 @@ def start(arguments, label): WORKSTREAM_ARTIFACT_STORE_BACKEND="s3_compatible", WORKSTREAM_ARTIFACT_SCRATCH_ROOT=str(scratch), WORKSTREAM_EXTERNAL_CHECKER_MATERIAL_ROOT=str(scratch), - WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET=str(checker_socket), WORKSTREAM_ARTIFACT_S3_PROVIDER_PROFILE="minio", WORKSTREAM_ARTIFACT_S3_REGION="us-east-1", WORKSTREAM_ARTIFACT_S3_ENDPOINT_URL=environment[ @@ -73,10 +217,13 @@ def start(arguments, label): WORKSTREAM_ARTIFACT_ADMISSION_TASK_MAXIMUM_BYTES="67108864", WORKSTREAM_ARTIFACT_PENDING_WORK_SCAN_INTERVAL_SECONDS="2", ) + redis_binary = shutil.which("redis-server") + if redis_binary is None: + raise RuntimeError("journey requires redis-server") try: redis = start( [ - shutil.which("redis-server"), + redis_binary, "--bind", "127.0.0.1", "--port", @@ -90,76 +237,95 @@ def start(arguments, label): ], "redis", ) - checker = start( - [ - os.environ.get( - "WORKSTREAM_CLI_JOURNEY_CHECKER_EXECUTABLE", - str( - root - / "external_checkers/target/release/workstream-checker-service" - ), - ), - str(config_file), - ], - "checker", - ) deadline = time.monotonic() + 30 - while not checker_socket.exists(): - if ( - checker.poll() is not None - or redis.poll() is not None - or time.monotonic() > deadline - ): - raise RuntimeError("local checker/Redis startup failed") - time.sleep(0.1) + while True: + if redis.poll() is not None or time.monotonic() > deadline: + raise RuntimeError("owned Redis startup failed") + try: + with socket.create_connection(("127.0.0.1", redis_port), timeout=0.5): + break + except OSError: + time.sleep(0.1) def start_workers(): - # Provision their public identities before scheduling any work. - start( - [ - sys.executable, - "-m", - "celery", - "-A", - "app.workers.celery_app", - "worker", - "--pool=prefork", - "--concurrency=2", - "--hostname=cli-journey@localhost", - "--loglevel=WARNING", - ], - "worker", + required = [] + + def worker( + label: str, queues: str, concurrency: int, *, extra_environment=None + ): + required.append( + start( + [ + sys.executable, + "-m", + "celery", + "-A", + "app.workers.celery_app", + "worker", + "--pool=prefork", + f"--concurrency={concurrency}", + "--queues", + queues, + f"--hostname={label}@localhost", + "--loglevel=WARNING", + ], + label, + extra_environment=extra_environment, + ) + ) + + worker("worker", "celery,workstream.outbox", 2) + worker("finalizer", "workstream.submission_finalization", 1) + worker( + "source-cleanup", + "workstream.source_cleanup", + 1, + extra_environment={ + "WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID": environment[ + "WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID" + ], + "WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY": Path( + environment["WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE"] + ).read_text(encoding="ascii"), + }, ) - start( - [ - sys.executable, - "-m", - "celery", - "-A", - "app.workers.celery_app", + required.append( + start( + [ + sys.executable, + "-m", + "celery", + "-A", + "app.workers.celery_app", + "beat", + "--schedule", + str(directory / "beat-schedule"), + "--loglevel=WARNING", + ], "beat", - "--schedule", - str(directory / "beat-schedule"), - "--loglevel=WARNING", - ], - "beat", + ) ) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + if any(process.poll() is not None for process in required): + raise RuntimeError("required journey worker exited during startup") + time.sleep(0.2) yield start_workers finally: for process in reversed(processes): if process.poll() is None: - process.terminate() + os.killpg(process.pid, signal.SIGTERM) try: process.wait(timeout=20) except subprocess.TimeoutExpired: - process.kill() + os.killpg(process.pid, signal.SIGKILL) process.wait(timeout=10) for log in logs: log.close() if location := os.environ.get("WORKSTREAM_CLI_JOURNEY_EVIDENCE"): retained = Path(location) / "runtime-logs" - retained.mkdir(mode=0o700) + retained.mkdir(mode=0o700, parents=True) for source in directory.glob("*.log"): target = retained / source.name with target.open("xb") as destination: diff --git a/cli/tests/journey/source_audit.py b/cli/tests/journey/source_audit.py new file mode 100644 index 000000000..43a67b3db --- /dev/null +++ b/cli/tests/journey/source_audit.py @@ -0,0 +1,190 @@ +"""Read-only isolated-database postconditions for source custody hidden from public DTOs.""" + +import asyncio +from hashlib import sha256 +import os +from pathlib import Path +from urllib.parse import urlsplit + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import create_async_engine + +from app.core.hashing import canonical_json_hash + + +_COUNTS = { + "submissions": "SELECT count(*) FROM submissions WHERE task_id = CAST(:task_id AS uuid)", + "dispatches": "SELECT count(*) FROM submission_dispatches WHERE task_id = CAST(:task_id AS uuid)", + "checker_runs": "SELECT count(*) FROM checker_runs WHERE task_id = CAST(:task_id AS uuid)", + "acceptances": "SELECT count(*) FROM final_acceptances WHERE task_id = CAST(:task_id AS uuid)", + "reviews": "SELECT count(*) FROM reviews WHERE task_id = CAST(:task_id AS uuid)", + "contributions": "SELECT count(*) FROM contribution_records WHERE task_id = CAST(:task_id AS uuid)", + "awards": ( + "SELECT count(*) FROM compensation_awards AS award " + "JOIN contribution_records AS contribution " + "ON contribution.id = award.contribution_record_id " + "WHERE contribution.task_id = CAST(:task_id AS uuid)" + ), +} + + +async def _audit( + operation_id: str, + submission_id: str, + task_id: str, + digest: str, + byte_count: int, + *, + accepted: bool, +) -> None: + url = os.environ["WORKSTREAM_DATABASE_URL"] + if not urlsplit(url).path.lstrip("/").startswith("workstream_test_"): + raise RuntimeError("source audit requires the isolated test database") + engine = create_async_engine(url, pool_pre_ping=True) + try: + async with engine.connect() as connection, connection.begin(): + await connection.execute(text("SET TRANSACTION READ ONLY")) + rows = ( + ( + await connection.execute( + text(""" + SELECT o.id::text AS operation_id, o.task_id::text AS task_id, + o.state, o.finalized_submission_id::text AS submission_id, + o.raw_sha256, o.raw_byte_count, o.provider_generation, + o.sealed_upload_fence, o.namespace_id, o.namespace_fingerprint, + o.provider_profile, o.object_ref, o.accepted_source_sha256, + selected.request_json AS selected_request, + charge.state AS charge_state, charge.accounted_bytes, + admission.source_operation_id::text AS admission_source, + admission.consumed_by_submission_id::text AS admission_submission, + replica.source_operation_id::text AS replica_source, + replica.storage_namespace_id, replica.namespace_fingerprint AS replica_fingerprint, + replica.provider_profile AS replica_profile, + replica.provider_object_ref, content.sha256 AS content_sha256, + content.byte_count AS content_byte_count + FROM submission_intake_operations AS o + JOIN submission_source_charges AS charge ON charge.operation_id = o.id + JOIN selected_pre_submit_runs AS selected ON selected.id = o.selected_pre_submit_run_id + JOIN submission_bundle_admissions AS admission ON admission.id = o.finalized_admission_id + JOIN artifact_replicas AS replica ON replica.source_operation_id = o.id + JOIN artifact_contents AS content ON content.id = replica.content_id + WHERE o.id = CAST(:operation_id AS uuid) + """), + {"operation_id": operation_id}, + ) + ) + .mappings() + .all() + ) + if len(rows) != 1: + raise AssertionError( + "accepted source lacks one complete stored custody graph" + ) + row = rows[0] + expected = { + "operation_id": operation_id, + "task_id": task_id, + "state": "finalized", + "submission_id": submission_id, + "raw_sha256": digest, + "raw_byte_count": byte_count, + "charge_state": "sealed", + "accounted_bytes": byte_count, + "admission_source": operation_id, + "admission_submission": submission_id, + "replica_source": operation_id, + "storage_namespace_id": row["namespace_id"], + "replica_fingerprint": row["namespace_fingerprint"], + "replica_profile": row["provider_profile"], + "provider_object_ref": row["object_ref"], + "content_sha256": digest, + "content_byte_count": byte_count, + } + for field, value in expected.items(): + if row[field] != value: + raise AssertionError( + f"accepted source stored {field} differs from public work" + ) + if not row["provider_generation"] or row["sealed_upload_fence"] <= 0: + raise AssertionError( + "accepted source lacks an exact provider generation and fence" + ) + source = row["selected_request"].get("source") + if not isinstance(source, dict) or not isinstance( + source.get("location"), dict + ): + raise AssertionError( + "selected PRE lacks the independently stored source" + ) + if ( + { + "provider_generation": source.get("provider_generation"), + "sealed_upload_fence": source.get("sealed_upload_fence"), + "raw_sha256": source.get("raw_sha256"), + "raw_byte_count": source.get("raw_byte_count"), + } + != { + "provider_generation": row["provider_generation"], + "sealed_upload_fence": row["sealed_upload_fence"], + "raw_sha256": digest, + "raw_byte_count": byte_count, + } + or source["location"] + != { + "operation_id": operation_id, + "namespace_id": row["namespace_id"], + "namespace_fingerprint": row["namespace_fingerprint"], + "provider_profile": row["provider_profile"], + } + or row["accepted_source_sha256"] + != canonical_json_hash( + { + "schema_version": "workstream.sealed_submission_source.v1", + **source, + } + ) + ): + raise AssertionError( + "selected PRE source generation or fence differs from accepted custody" + ) + counts = { + name: await connection.scalar(text(query), {"task_id": task_id}) + for name, query in _COUNTS.items() + } + expected_counts = { + "submissions": 1, + "dispatches": 1, + "checker_runs": 1, + "acceptances": int(accepted), + "reviews": 0, + "contributions": int(accepted), + "awards": 0, + } + if counts != expected_counts: + raise AssertionError( + "isolated task effect counts differ from the governed outcome" + ) + finally: + await engine.dispose() + + +def audit_accepted_source( + operation_id: str, + submission_id: str, + task_id: str, + archive: Path, + *, + accepted: bool, +) -> None: + """Observe exact source graph and downstream counts without changing state.""" + data = archive.read_bytes() + asyncio.run( + _audit( + operation_id, + submission_id, + task_id, + "sha256:" + sha256(data).hexdigest(), + len(data), + accepted=accepted, + ) + ) diff --git a/cli/tests/journey/submission_work.py b/cli/tests/journey/submission_work.py index f89031004..ce0448c10 100644 --- a/cli/tests/journey/submission_work.py +++ b/cli/tests/journey/submission_work.py @@ -1,137 +1,209 @@ -"""Real CLI intake, durable evaluation and unpaid contribution observation.""" +"""Public raw ZIP intake, real POST routing and governed contribution evidence.""" import csv import hashlib -import json +from pathlib import Path import subprocess +import sys import time from uuid import uuid4 -from zipfile import ZipFile +from task_work import create_claimed_task +from source_audit import audit_accepted_source -def submit_and_observe( - client, tokens, actors, project_id, task_id, assignment_id, grant -): - token = tokens["alice"] - packet = ( - "--assignment", - assignment_id, - "--summary", - "Local declared-proof format exercise", - "--attestation", - "These are illustrative format claims, not verified remote work.", - ) - rejected = client.directory / "rejected.zip" - with ZipFile(rejected, "x") as bundle: - bundle.writestr("proof.json", "{}") - failure = client.call( - token, - "task", - "prepare", - task_id, - *packet, - "--file", - str(rejected), - "--idempotency-key", - str(uuid4()), - expected_exit=1, +PILOT = Path(__file__).resolve().parents[3] / "pilots/terminal_systems/mvp" +PACKET = ( + "--summary", + "Fixed incident summary", + "--attestation", + "I counted the supplied incident events and retained the input.", +) + + +def _package(client, kind): + archive = client.directory / f"{kind}.zip" + subprocess.run( + [sys.executable, str(PILOT / "package.py"), kind, str(archive)], + check=True, + capture_output=True, + text=True, + timeout=30, ) - if failure["error"]["code"] != "pre_submission_checker_failed": - raise AssertionError("invalid declared proof was not rejected by intake") - # Exact task-history resolution requires an existing Submission. The self - # collection supports an empty result and is the appropriate absence proof. - if client.call(token, "me", "submissions", "--task", task_id)["items"]: - raise AssertionError("rejected candidate created a submission") - archive = client.directory / "submission.zip" - with ZipFile(archive, "x") as bundle: - bundle.writestr( - "proof.json", - json.dumps( - { - "schema": "harnessy.work.proof.v1", - "commit_sha": "a" * 40, - "pr_url": "https://github.com/example/format-exercise/pull/1", - "ci_run_url": "https://github.com/example/format-exercise/actions/runs/1", - "ci_conclusion": "success", - "merged": True, - } - ), - ) - archive_hash = "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest() - command = ( + if archive.stat().st_size <= 0: + raise AssertionError("pilot package is empty") + return archive + + +def _command(task_id, assignment_id, archive, key): + return ( "task", - "prepare", + "submit", task_id, - *packet, + "--assignment", + assignment_id, + *PACKET, "--file", str(archive), "--idempotency-key", - str(uuid4()), + key, ) - first = client.call(token, *command) - deadline = time.monotonic() + 240 + + +def _progress(client, token, task_id, key, operation_id=None): + by_key = client.call( + token, "task", "submission-operation", task_id, "--idempotency-key", key + ) + if operation_id is not None: + by_id = client.call( + token, + "task", + "submission-operation", + task_id, + "--operation-id", + operation_id, + ) + if by_key != by_id or by_id["operation_id"] != operation_id: + raise AssertionError("key and operation reads differ") + return by_key + + +def _wait_for_stage(client, token, task_id, key, receipt, expected_stage): + deadline = time.monotonic() + 600 while time.monotonic() < deadline: - page = client.call(token, "task", "preparations", task_id) - matching = [ - item for item in page["items"] if item["archive_sha256"] == archive_hash - ] - if len(matching) > 1: - raise AssertionError("one preparation request produced duplicate runs") - if matching and matching[0]["state"] == "ready": - ready = matching[0] - break - if matching and matching[0]["state"] in { - "checks_failed", - "infrastructure_failed", - "stale", + observed = _progress(client, token, task_id, key, receipt["operation_id"]) + if observed["operationally_stalled"]: + raise AssertionError("durable submission requires explicit recovery") + if observed["processing_stage"] == expected_stage: + if ( + observed["operation_state"] != "finalized" + or not observed["submission_id"] + ): + raise AssertionError("governed outcome has no finalized Submission") + return observed + if observed["operation_state"] in { + "rejected", + "failed", + "abandoned", + "cancelled", }: - raise AssertionError("real intake failed; no substitution permitted") + raise AssertionError("accepted source failed before governed evaluation") + if observed["processing_stage"] in {"accepted", "needs_revision", "rejected"}: + raise AssertionError("submission reached a different governed outcome") time.sleep(1) - else: - raise AssertionError("real intake did not reach ready admission") + raise AssertionError("durable evaluation did not reach its governed outcome") + + +def _submit(client, token, task_id, assignment_id, archive): + key = str(uuid4()) + command = _command(task_id, assignment_id, archive, key) + receipt = client.call(token, *command) + if ( + receipt["status"] != "accepted" + or receipt["processing_stage_at_acceptance"] != "finalization_pending" + ): + raise AssertionError("source command did not return T4 acceptance") replay = client.call(token, *command) + if replay != (receipt | {"replayed": True}): + raise AssertionError("exact source replay changed accepted command snapshot") + progress = _progress(client, token, task_id, key, receipt["operation_id"]) + if progress["pre_submission_results"] != receipt["pre_submission_results"]: + raise AssertionError("accepted feedback changed during operation observation") + return key, receipt + + +def _pre_missing_has_no_submission(client, token, task_id, assignment_id): + key = str(uuid4()) + command = _command(task_id, assignment_id, _package(client, "pre-missing"), key) + failure = client.call(token, *command, expected_exit=1) + if failure["error"]["code"] != "pre_submission_checker_failed": + raise AssertionError("missing summary was not rejected by real PRE") + observed = _progress(client, token, task_id, key) if ( - replay["put_attempt_id"] != first["put_attempt_id"] - or replay["admission_id"] != ready["admission_id"] - or replay["replayed"] is not True + observed["operation_state"] != "rejected" + or observed["processing_stage"] != "rejected" + or observed["submission_id"] is not None + or observed["next_action"] != "correct_and_submit_new_key" ): - raise AssertionError("exact preparation replay changed custody") - submit = ("task", "submit", task_id, *packet, "--admission", ready["admission_id"]) - receipt = client.call(token, *submit) - if client.call(token, *submit) != receipt: - raise AssertionError("exact submission replay changed receipt") - deadline = time.monotonic() + 240 - while time.monotonic() < deadline: - outcome = client.call(token, "submission", "show", receipt["submission_id"]) - if outcome["status"] == "accepted": - break - if outcome["status"] in {"rejected", "needs_revision"}: - raise AssertionError( - "real checker did not reach the expected acceptance branch" - ) - time.sleep(1) - else: - # Capture the public failure state before the isolated runtime is torn - # down. These reads never repair/retry work or turn the timeout into a - # pass; one failed diagnostic must not hide the original failure. - for diagnostic_token, arguments in ( - (token, ("submission", "findings", receipt["submission_id"])), - ( - tokens["operator"], - ("operations", "checker", "retry-sources", project_id), - ), - ( - tokens["operator"], - ("operations", "delivery", "list", project_id), - ), - ): - try: - client.call(diagnostic_token, *arguments) - except (AssertionError, subprocess.TimeoutExpired, OSError, ValueError): - # The client retains redacted execution metadata and private - # receipts when available. Do not print arbitrary server text. - print("Evaluation diagnostic unavailable: " + arguments[1]) - raise AssertionError("durable evaluation did not reach acceptance") + raise AssertionError("rejected PRE candidate created downstream work") + if client.call(token, "me", "submissions", "--task", task_id)["items"]: + raise AssertionError("rejected PRE candidate created a Submission") + + +def _incorrect_post_has_no_acceptance(client, tokens, project_id, previous_records): + task_id, assignment_id = create_claimed_task( + client, tokens, project_id, title="Reject incorrect incident counts" + ) + archive = _package(client, "incorrect") + key, receipt = _submit(client, tokens["alice"], task_id, assignment_id, archive) + observed = _wait_for_stage( + client, tokens["alice"], task_id, key, receipt, "needs_revision" + ) + submission_id = observed["submission_id"] + outcome = client.call(tokens["alice"], "submission", "show", submission_id) + if outcome["status"] != "needs_revision": + raise AssertionError("incorrect shaped summary bypassed governed revision") + runs = client.call(tokens["alice"], "submission", "findings", submission_id) + if len(runs["items"]) != 1 or not any( + result["checker_name"] == "terminal.post.incident_summary_counts" + and result["status"] == "failed" + for result in runs["items"][0]["results"] + ): + raise AssertionError("incorrect counts lack real failed POST evidence") + records = client.call(tokens["alice"], "contributions", "--project", project_id)[ + "items" + ] + if records != previous_records or any( + item["task_id"] == task_id for item in records + ): + raise AssertionError("failed POST created acceptance, award or contribution") + audit_accepted_source( + receipt["operation_id"], submission_id, task_id, archive, accepted=False + ) + + +def observe_review_pending(client, tokens, project_id, task_id, assignment_id): + """Prove the default human-review branch stops before final acceptance.""" + archive = client.directory / "correct.zip" + if not archive.is_file(): + archive = _package(client, "correct") + key, accepted = _submit(client, tokens["alice"], task_id, assignment_id, archive) + observed = _wait_for_stage( + client, tokens["alice"], task_id, key, accepted, "review_pending" + ) + submission = client.call( + tokens["alice"], "submission", "show", observed["submission_id"] + ) + if submission["status"] != "review_pending": + raise AssertionError("default review policy did not retain pending review") + records = client.call(tokens["alice"], "contributions", "--project", project_id)[ + "items" + ] + if records: + raise AssertionError("pending human review fabricated a contribution or award") + audit_accepted_source( + accepted["operation_id"], + observed["submission_id"], + task_id, + archive, + accepted=False, + ) + return observed + + +def submit_and_observe( + client, tokens, actors, project_id, task_id, assignment_id, grant +): + token = tokens["alice"] + _pre_missing_has_no_submission(client, token, task_id, assignment_id) + archive = _package(client, "correct") + archive_hash = "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest() + key, accepted = _submit(client, token, task_id, assignment_id, archive) + observed = _wait_for_stage(client, token, task_id, key, accepted, "accepted") + receipt = { + "submission_id": observed["submission_id"], + "submission_version": int(observed["submission_version"]), + } + outcome = client.call(token, "submission", "show", receipt["submission_id"]) retained = client.call(token, "me", "submissions", "--task", task_id) if retained["next_cursor"] is not None or len(retained["items"]) != 1: raise AssertionError("submission replay did not retain exactly one attempt") @@ -139,14 +211,16 @@ def submit_and_observe( retained["items"][0]["submission_id"] != receipt["submission_id"] or outcome["id"] != receipt["submission_id"] ): - raise AssertionError("retained submission differs from accepted receipt") + raise AssertionError("retained submission differs from accepted operation") for field, value in { "task_id": task_id, "version": receipt["submission_version"], "status": "accepted", }.items(): if retained["items"][0][field] != value or outcome[field] != value: - raise AssertionError("retained submission differs from accepted receipt") + raise AssertionError("retained submission differs from accepted operation") + if retained["items"][0].get("artifact_hash") not in (None, archive_hash): + raise AssertionError("retained submission differs from submitted ZIP") runs = client.call(token, "submission", "findings", receipt["submission_id"]) if runs["next_cursor"] is not None or len(runs["items"]) != 1: raise AssertionError("expected one real post-submit checker run") @@ -161,12 +235,11 @@ def submit_and_observe( if run[field] != value: raise AssertionError("checker run does not bind the accepted attempt") if not run["completed_at"] or not any( - # Public findings name the manager-selected requirement, independently - # of the setup suggestion ID and registry capability. - result["checker_name"] == "project.proof_post" and result["status"] == "passed" + result["checker_name"] == "terminal.post.incident_summary_counts" + and result["status"] == "passed" for result in run["results"] ): - raise AssertionError("registered checker has no completed passing evidence") + raise AssertionError("registered POST checker lacks passing evidence") if ( client.call( token, @@ -198,6 +271,8 @@ def submit_and_observe( raise AssertionError("contribution differs from the exercised attempt") if not record["source_final_acceptance_id"]: raise AssertionError("accepted contribution lacks final acceptance provenance") + if record["artifact_hash"] != archive_hash: + raise AssertionError("accepted contribution does not bind the original ZIP") exported = client.call(tokens["finance"], "project", "contributions", project_id) if exported["items"] != records: raise AssertionError("authorized project export differs from own evidence") @@ -224,6 +299,14 @@ def submit_and_observe( ): if rows[0][field] != record[field]: raise AssertionError("CSV lineage differs from JSON evidence") + audit_accepted_source( + accepted["operation_id"], + receipt["submission_id"], + task_id, + archive, + accepted=True, + ) + _incorrect_post_has_no_acceptance(client, tokens, project_id, records) client.call(token, "project", "show", project_id) client.write_and_replay( tokens["manager"], diff --git a/cli/tests/journey/task_work.py b/cli/tests/journey/task_work.py index f40afeb78..78f0f5fd0 100644 --- a/cli/tests/journey/task_work.py +++ b/cli/tests/journey/task_work.py @@ -3,6 +3,8 @@ import hashlib from uuid import uuid4 +from public_setup import TASK + def replay_transition(client, token, *arguments): command = ( @@ -44,22 +46,8 @@ def issue_submitter(client, manager, actor_id, project_id): ) -def claim_and_read(client, tokens, actors, project_id): - grant = issue_submitter(client, tokens["manager"], actors["alice"], project_id) - other = client.call( - tokens["manager"], - "project", - "create", - "--name", - "Isolated other project", - "--slug", - "cli-other-" + uuid4().hex, - "--idempotency-key", - str(uuid4()), - ) - issue_submitter(client, tokens["manager"], actors["bob"], other["id"]) - if client.call(tokens["bob"], "project", "show", other["id"])["id"] != other["id"]: - raise AssertionError("foreign-project contributor setup failed") +def create_claimed_task(client, tokens, project_id, *, title: str): + """Reuse the public manager and contributor lifecycle for each real output.""" task = client.write_and_replay( tokens["manager"], "project", @@ -67,14 +55,14 @@ def claim_and_read(client, tokens, actors, project_id): "create", project_id, body={ - "title": "Validate declared proof fields", - "description": "Prepare proof.json using the locked guide format.", + "title": title, + "description": TASK, "task_type": "evaluation", "difficulty": "medium", "skill_tags": ["analysis"], "estimated_time_minutes": 10, - "acceptance_criteria": "All declared proof fields pass the registered checker.", - "rejection_criteria": "Required proof fields are missing or invalid.", + "acceptance_criteria": "The fixed incident input and exact per-service counts pass POST.", + "rejection_criteria": "Required files are missing or counts are incorrect.", }, ) task_id = task["id"] @@ -85,6 +73,28 @@ def claim_and_read(client, tokens, actors, project_id): claimed = replay_transition(client, tokens["alice"], "task", "claim", task_id) if claimed["task"]["status"] != "in_progress": raise AssertionError("claim did not immediately start work") + return task_id, claimed["assignment"]["id"] + + +def claim_and_read(client, tokens, actors, project_id): + grant = issue_submitter(client, tokens["manager"], actors["alice"], project_id) + other = client.call( + tokens["manager"], + "project", + "create", + "--name", + "Isolated other project", + "--slug", + "cli-other-" + uuid4().hex, + "--idempotency-key", + str(uuid4()), + ) + issue_submitter(client, tokens["manager"], actors["bob"], other["id"]) + if client.call(tokens["bob"], "project", "show", other["id"])["id"] != other["id"]: + raise AssertionError("foreign-project contributor setup failed") + task_id, assignment_id = create_claimed_task( + client, tokens, project_id, title="Summarize the fixed incident events" + ) documents = client.call(tokens["alice"], "task", "guide", task_id) denied = client.call(tokens["bob"], "task", "guide", task_id, expected_exit=1) if denied["error"].get("status") != 404: @@ -105,4 +115,4 @@ def claim_and_read(client, tokens, actors, project_id): raise AssertionError( "downloaded originals differ from the locked public manifest" ) - return task_id, claimed["assignment"]["id"], grant + return task_id, assignment_id, grant diff --git a/pilots/terminal_systems/mvp/registry.py b/pilots/terminal_systems/mvp/registry.py new file mode 100644 index 000000000..4fb19b809 --- /dev/null +++ b/pilots/terminal_systems/mvp/registry.py @@ -0,0 +1,83 @@ +"""Build exact PRE and POST registration inputs for the incident-summary image.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import sys + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT / "backend")) + +from app.modules.checkers.api.external import ( # noqa: E402 + ExternalCheckerRegistrySpec, + ExternalCheckerResourceLimits, + ExternalCheckerSchema, + external_checker_json_hash, +) + +CHECKS = { + "pre": ("pre_submit", "incident_summary_layout"), + "post": ("post_submit", "incident_summary_counts"), +} + + +def _schema(identifier: str, document: dict) -> ExternalCheckerSchema: + return ExternalCheckerSchema( + schema_id=identifier, + schema_version="v1", + document=document, + schema_sha256=external_checker_json_hash(document), + ) + + +def registry_spec(phase: str, image_digest: str) -> ExternalCheckerRegistrySpec: + stage, check = CHECKS[phase] + return ExternalCheckerRegistrySpec( + capability_id="terminal.incident_summary", + capability_version="v1", + phase=stage, + image_digest=image_digest, + configuration_schema=_schema( + "checker.configuration", + { + "type": "object", + "properties": {"check": {"const": check}}, + "required": ["check"], + "additionalProperties": False, + }, + ), + input_schema=_schema(f"external_checker_{stage}_input", {"type": "object"}), + output_schema=_schema("external_checker_result", {"type": "object"}), + resources=ExternalCheckerResourceLimits( + cpu_millis=500, + memory_bytes=128 * 1024 * 1024, + deadline_ms=30_000, + maximum_output_bytes=32_768, + ), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--image-digest", required=True) + parser.add_argument("--pre", type=Path, required=True) + parser.add_argument("--post", type=Path, required=True) + arguments = parser.parse_args() + if re.fullmatch(r"sha256:[0-9a-f]{64}", arguments.image_digest) is None: + parser.error("image digest must be canonical sha256") + if arguments.pre == arguments.post: + parser.error("PRE and POST registry files must differ") + for phase in CHECKS: + path = getattr(arguments, phase) + spec = registry_spec(phase, arguments.image_digest) + with path.open("x", encoding="utf-8") as stream: + path.chmod(0o600) + json.dump(spec.model_dump(mode="json"), stream, indent=2, sort_keys=True) + stream.write("\n") + + +if __name__ == "__main__": + main() From e582c7bb111efea33949301c9ba697dc1d452870 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 15:30:08 +0100 Subject: [PATCH 287/513] Move qualification callers to accepted raw ZIP submissions --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 89 +++ .../README.md | 23 +- .../public_hosted_attachment.py | 4 +- .../public_hosted_model_post.py | 31 +- .../public_probe_support.py | 49 +- .../run_public_journey_probe.py | 315 +++++---- .../run_selected_end_to_end_probe.py | 645 ------------------ scripts/test_public_hosted_attachment.py | 2 +- scripts/test_public_hosted_model_post.py | 182 ++++- 9 files changed, 490 insertions(+), 850 deletions(-) delete mode 100644 experiments/pilot04_external_checker_runtime/run_selected_end_to_end_probe.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 124c7523e..3df0e4f49 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9285,3 +9285,92 @@ audit performs no state transitions. Its SQL graph parsed and ran against a fresh migrated isolated database; the deliberately absent operation yielded the expected missing-graph assertion, and that database was cleaned. A successful live graph is still pending the next end-to-end run. + +### Retire qualification-script preparation callers + +Release image guards exposed an import of removed preparation composition from +run_selected_end_to_end_probe.py. Its only live imports are the locked registry +specification and secret-fixture builders; preserve those exact functions in +public_probe_support.py and retire the obsolete hidden-owner drill. Port the +shared current public/model qualification path from preparation/admission plus +JSON201 to raw-ZIP202, immutable acceptance replay, public operation observation +and actual dedicated T5 worker. Preserve input hashes, model/forge/paid-effect +custody, native verdict and governed-outcome assertions. No old-writer alias, +compatibility route, injected verifier/finalizer or skipped test. + +Allowed first scope: run_selected_end_to_end_probe.py, run_public_journey_probe.py, +public_probe_support.py, public_hosted_attachment.py, public_hosted_model_post.py, +their two scripts/test_public_hosted_* guard modules and this record. Require +exclusive finalization worker startup/inspection, and preserve POST fault timing +by pausing only the general worker across T4/T5 before enabling the injected POST +failure. Medium qualification-tool risk: run the36 release guards plus new +current source-flow assertions, imports, Ruff/structure/diff/record checks and +scoped review. No production, remote, IAM, paid call or deployment mutation. + +The independently separable local public_intake_trials/public_runtime_trials +remain mandatory follow-up: zero/multi PRE and VM-before-seal vectors are +superseded; transfer current resource/cancellation/deadline safety claims and +use distinct tasks for multiple accepted sources. Do not call those vectors +qualified by this guard repair. Root owns operations wording and current native +journey work; this change does not claim a complete native/model qualification. + +Common-flow repair replaces only the obsolete command, not model/forge evidence. +The two helper builders moved unchanged; the hidden-owner drill is deleted after +tracing its live imports. Current _submit sends raw ZIP once, replays its exact +key/body, observes public operation progress with all four selectors bound and +checks real finalized admission/PRE hashes and acknowledged finalization custody. +No preparation/verifier task injection remains. Model replay retains the original +revision acknowledgement instead of asking current work-context to fabricate one. +The local launcher adds an exclusive production finalization consumer and pauses +only its general consumer until the POST fault is installed after PRE/T5. It +uses explicit remote-TLS/source-profile settings and an existing canonical parser +socket; no retired Unix/proof argument or second parser launcher is introduced. +Hosted inspection now requires the already-defined finalization service. + +Initial guard replay resolved all9 import failures and exposed one remaining +obsolete stalled-verifier test (35pass/1error). Ported that safety assertion to +current stalled source finalization: only GET is allowed and no finalizer task +may be injected. All40 guards passed20.81s in +/tmp/submission-qualification-guards-v2.log (original36 plus4 current contracts). +New controls cover raw bytes/exact replay, each foreign progress selector with +a valid control, exclusive worker composition and the existing parser socket. +This is local guard/contract evidence, not native or paid execution. + +The current CLI/native journey owner confirmed upload/PRE source/execution +cancellation, original deadline expiry, launch/controller loss and POST outage +recovery are not covered by its happy/failure journey. They remain mandatory in +the following local trial-vector migration; this common-flow commit does not +silently remove or qualify them. The old selected-drill README paragraph needs +root's coordinated wording update after deletion. No remote mutation occurred. + +Final live-caller trace also found model qualification explicitly requiring an +empty PRE approval, and shared task setup calling removed start/requirements +routes. Port these within the same allowed files: one non-model baseline PRE +plus exactly one paid model POST retains all rubric/profile/budget guards; +claim must prove in_progress/started_at and read current work-context. This is +required current cardinality/lifecycle alignment, not paid execution or a +qualification shortcut. Local zero/multi resource vectors remain separate. + +Root's common-flow review required preserving the canonical supplied runner +window instead of an old hardcoded90s override. The launcher now validates the +explicit typed source profile with its owner-selected source-contract context +and refuses any request window shorter than its aggregate deadline; it does +not alter product defaults or shorten a model POST window. A new positive/short +window guard first exposed omitted validation context (40pass/1error), then the +canonical context helper was supplied. The model guide explicitly discloses its +required non-model PRE; all model POST rubric/profile/accounting guards remain. + +Final common-flow guards passed41/41 in44.464s at the frozen candidate +(/tmp/submission-qualification-guards-frozen.log). A final DTO trace corrected +task setup to public accepted_at rather than internal started_at; its focused +positive/refusal guard passed1/1 in48.466s +(/tmp/submission-qualification-claim-final.log). These are split local guard +receipts, not one42-case aggregate or actual native/paid qualification. +The bounded in-memory selector mutant removes only task_id comparison; the +named guard fails with RuntimeError-not-raised while the valid control passes +(/tmp/submission-qualification-selector-mutant.json). No source or production +file was mutated by that probe. Root requested the affected README paragraph +update; it now points at current public raw-ZIP flow and labels old drill +receipts as history, retaining the mandatory local-vector gap. +Structure and Ruff/diff pass; final record/link checks follow this append. +No remote action, deployment or paid request occurred. diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md index 318cbe1ec..aa61d0a31 100644 --- a/experiments/pilot04_external_checker_runtime/README.md +++ b/experiments/pilot04_external_checker_runtime/README.md @@ -22,18 +22,19 @@ result, isolation receipt, database finalization, and workspace cleanup. The database must be disposable and independently cleaned by the caller; the probe does not create or drop it. -`run_selected_end_to_end_probe.py` exercises PostgreSQL and MinIO through -selected PRE admission, immutable Submission/initial dispatch and production -request/completion handlers. It requires default-secret rejection and an actual -external PRE image rejection to preserve `in_progress` with no new Submission. -The latter uses `project-rejected.txt` as a fixture project rule, implemented -only inside the image. It also tests unavailable-service recovery through fresh -verified bytes and restarted completion delivery with exact replay. This hidden -owner drill does not provide public contributor upload/CLI, false-guide -activation or hosted gVisor deployment proof. Run it through the isolated-test -runner so owned database, role and MinIO cleanup are checked. +`run_public_journey_probe.py` is the current qualification entry point. Its +shared submission path sends raw ZIP bytes to the public task submission API, +retains the accepted202 receipt, and observes exact operation progress until the +exclusive finalization worker commits Submission and POST dispatch. It uses no +preparation endpoint, ready-admission JSON creation, or injected verifier task. +Model qualification keeps one non-model PRE and one model POST; model/forge +identity, accounting and governed-outcome checks remain explicit. The retired +hidden-owner selected drill and its stored receipts describe historical runs, +not current-HEAD qualification. Local cancellation/deadline/controller-loss +vectors still need their separate current-source migration; the guard repair +does not qualify those runs. -The companion `run_public_journey_probe.py` starts with public project/guide +The public journey starts with public project/guide creation, original synthetic Markdown bytes and two task examples. The public upload dispatches real Celery setup. Its explicit `guide_worker` entry point selects a recorded inference adapter through the existing typed runtime port; diff --git a/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py b/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py index 0599822cc..7e1200a6e 100644 --- a/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py +++ b/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py @@ -291,7 +291,7 @@ def inspect(self): port = urlparse(self.origin).port require(port == int(values.get('WORKSTREAM_API_HOST_PORT', '8000')), "published API port differs") environment = module.compose_environment(values) - services = ['api', 'worker', 'beat', 'guide-document-parser'] + services = ['api', 'worker', 'submission-finalization-worker', 'beat', 'guide-document-parser'] if values['WORKSTREAM_MODEL_PROXY_ENABLED'] == 'true': services.append('model-proxy') observed = {} @@ -383,7 +383,7 @@ async def register_baseline_capabilities(self, client): """Register only the two requested fixture identities under public Operator authority.""" from app.modules.checkers.api.external import ExternalCheckerRegistryEntry from experiments.pilot04_external_checker_runtime.public_probe_support import _json - from experiments.pilot04_external_checker_runtime.run_selected_end_to_end_probe import _locked_spec + from experiments.pilot04_external_checker_runtime.public_probe_support import _locked_spec images = [item for item in self.native_binding.get('node_config', {}).get('cache', []) if item['repository'] == 'workstream-test/public-journey'] diff --git a/experiments/pilot04_external_checker_runtime/public_hosted_model_post.py b/experiments/pilot04_external_checker_runtime/public_hosted_model_post.py index 931c2b80d..ba36bb748 100644 --- a/experiments/pilot04_external_checker_runtime/public_hosted_model_post.py +++ b/experiments/pilot04_external_checker_runtime/public_hosted_model_post.py @@ -273,6 +273,10 @@ async def bind_project(self, client, project_id, attachment): from experiments.pilot04_external_checker_runtime.public_probe_support import _json require('project_id' not in self.state, 'this qualification already owns one project') + baseline = attachment.approval_attachments(1)['pre_submit_attachments'] + require(len(baseline) == 1 and baseline[0]['requirement_id'] == 'project.pre_submit' + and baseline[0]['configuration'] == {}, 'model qualification requires one non-model baseline PRE') + self.pre_submit_attachment = baseline[0] self.checkpoint(phase='project_created', project_id=project_id) token = attachment.token_for_label('operator') root = f'/api/v1/operations/projects/{project_id}' @@ -304,16 +308,18 @@ def guide_bytes(self): _, statement = specification() return ('# Hosted model POST engineering qualification\n\n' 'This manager-authored guide describes only the Terminal Systems ' - f'`{CHECK}` model rubric. It does not claim setup inference, a real pilot or runtime trials.\n\n' + f'`{CHECK}` model rubric. Intake also uses the non-model engineering fixture PRE check, ' + 'which rejects project-rejected.txt without a model call. ' + 'It does not claim setup inference, a real pilot or runtime trials.\n\n' + statement + '\n').encode() def rules(self, original, count): from experiments.pilot04_external_checker_runtime.public_hosted_attachment import manager_rules - require(count == 0, 'model qualification must not propose a PRE check') - body = json.loads(manager_rules(original, 0)) + require(count == 1, 'model qualification requires exactly one baseline PRE check') + body = json.loads(manager_rules(original, 1)) spec, statement = specification() - body['requirements'] = [{'suggestion_id': 'suggested.solver_brief_and_extension_disclosure', + body['requirements'] = [item for item in body['requirements'] if item['stage'] == 'pre_submit'] + [{'suggestion_id': 'suggested.solver_brief_and_extension_disclosure', 'statement': statement, 'stage': 'post_submit', 'classification_rationale': 'The rubric evaluates the submitted task after intake.', 'evidence_refs': body['findings'][0]['evidence_refs'], 'check_specification': spec.model_dump(mode='json')}] @@ -324,7 +330,7 @@ def approval_attachments(self): """Select the exact published model image and profile as the human manager.""" from app.modules.checkers.api.external_policy import ExternalCheckerImageAttachment - require(hasattr(self, 'registry') and hasattr(self, 'profile'), + require(hasattr(self, 'registry') and hasattr(self, 'profile') and hasattr(self, 'pre_submit_attachment'), 'model image and profile must be published before approval') configuration = {'check': CHECK, **self.profile.selector.model_dump(mode='json')} # The selector DTO uses profile_* names; image configuration reserves model_profile_* names. @@ -336,7 +342,7 @@ def approval_attachments(self): 'registry_entry_digest': self.registry['entry_digest'], 'configuration': configuration, }) - return {'pre_submit_attachments': [], + return {'pre_submit_attachments': [self.pre_submit_attachment], 'post_submit_attachments': [entry.model_dump(mode='json')]} @@ -456,7 +462,7 @@ async def run_model_post(attachment, client, factory, qualification): qualification.verify_cache(attachment) await attachment.transition('live') project, contributor, manager_token, contributor_token = await _public_project( - client, factory, attachment, human_review_required=False, pre_requirements=0) + client, factory, attachment, human_review_required=False, pre_requirements=1) project_id = str(project.project_id) task, assignment = await _started_public_task(client, project_id=project_id, manager_token=manager_token, contributor_token=contributor_token, source_ref='hosted-model-engineering-proof') @@ -467,8 +473,7 @@ async def run_model_post(attachment, client, factory, qualification): attestation = 'rights_confirmed; no confidential data or credentials.' saved = await _submit(client, factory, task_id=task, assignment_id=assignment, contributor_token=contributor_token, archive=archive, summary=summary, - attestation=attestation, predecessor_id=None, - hosted=True) + attestation=attestation, predecessor_id=None) qualification.checkpoint(phase='submission_created', submission=saved) async with factory() as session: dispatch = await session.get(SubmissionDispatch, saved['submission_id']) @@ -586,11 +591,9 @@ async def observe_model_post(attachment, client, factory, qualification, *, proj event = await session.get(OutboxEvent, completion) require(event.delivery_state == 'acknowledged', 'model completion was not acknowledged') before = {str(identifier): await _outbox_snapshot(factory, identifier) for identifier in (event_id, completion)} - replay = await _json(client, 'POST', f'/api/v1/tasks/{task}/submissions', - attachment.token_for_label('contributor'), 201, - json={'assignment_id': assignment, 'admission_id': saved['admission_id'], - 'predecessor_submission_id': None, 'summary': summary, 'contributor_attestation': attestation}) - require(replay == saved, 'completed public Submission replay changed its receipt') + from experiments.pilot04_external_checker_runtime.run_public_journey_probe import _replay_source_submission + await _replay_source_submission(client, task, assignment, attachment.token_for_label('contributor'), + archive, summary, attestation, saved) duplicate_tasks = [] for identifier in (event_id, completion): duplicate = await attachment.deliver_duplicate(identifier, project_id) diff --git a/experiments/pilot04_external_checker_runtime/public_probe_support.py b/experiments/pilot04_external_checker_runtime/public_probe_support.py index ecae598f6..5258421b7 100644 --- a/experiments/pilot04_external_checker_runtime/public_probe_support.py +++ b/experiments/pilot04_external_checker_runtime/public_probe_support.py @@ -11,6 +11,10 @@ from sqlalchemy import select, text from app.core.identifiers import new_record_id +from app.modules.checkers.api.external import ( + PRE_SUBMIT_INPUT_SCHEMA_ID, ExternalCheckerRegistrySpec, ExternalCheckerSchema, external_checker_json_hash, +) +from tests.checkers.external.support import post_registry_spec, registry_spec from app.modules.authorization.api import ActorIdentityFacts, ActorKind from app.modules.actors.api.service_identities import ServiceIdentity from app.modules.actors.models import ActorIdentityLink, ActorProfile @@ -171,7 +175,7 @@ async def _wait_outbox_acknowledged(factory, event_id: UUID, project_id: UUID) - async def _started_public_task(client, *, project_id: str, manager_token: str, contributor_token: str, source_ref: str) -> tuple[str, str]: - """Use the same public task, claim and start path for both project tasks.""" + """Use public task creation and the claim which immediately starts work.""" from tests.test_tasks import complete_task_payload payload = complete_task_payload() @@ -192,14 +196,9 @@ async def _started_public_task(client, *, project_id: str, manager_token: str, 200, headers={"Idempotency-Key": str(uuid4())}, ) assignment_id = claimed["assignment"]["id"] - await _json( - client, "POST", f"/api/v1/tasks/{task_id}/start", contributor_token, - 200, headers={"Idempotency-Key": str(uuid4())}, - ) - await _json( - client, "GET", f"/api/v1/tasks/{task_id}/submission-requirements", - contributor_token, 200, - ) + _require(claimed["task"]["status"] == "in_progress" and claimed["assignment"]["accepted_at"] is not None, + "public claim did not immediately start this assignment") + await _json(client, "GET", f"/api/v1/tasks/{task_id}/work-context", contributor_token, 200) return task_id, assignment_id @@ -268,3 +267,35 @@ async def _public_project(client, factory, env, *, human_review_required, pre_re "public project submitter grant names another actor or role") return compilation, contributor, manager_token, contributor_token + + +def _locked_spec(phase: str, image: dict[str, str]) -> ExternalCheckerRegistrySpec: + source = registry_spec("pre_submit") if phase == "pre_submit" else post_registry_spec() + values = source.model_dump(mode="json") + if phase == "pre_submit": + document = {"type": "object"} + values["input_schema"] = ExternalCheckerSchema( + schema_id=PRE_SUBMIT_INPUT_SCHEMA_ID, + schema_version="v1", + document=document, + schema_sha256=external_checker_json_hash(document), + ).model_dump(mode="json") + values["image_digest"] = image["platform_manifest_digest"] + values["resources"] |= {"deadline_ms": 30_000, "maximum_output_bytes": 8_192} + return ExternalCheckerRegistrySpec.model_validate(values) + +def _secret_archive(source: bytes) -> bytes: + """Preserve the valid packet while introducing one known private key.""" + output = BytesIO() + with ZipFile(BytesIO(source)) as existing, ZipFile(output, "w") as target: + for item in existing.infolist(): + value = existing.read(item) + if item.filename == "task.toml": + value += b"\n-----BEGIN OPENSSH PRIVATE KEY-----\nencoded\n" + copy = ZipInfo(item.filename, date_time=(1980, 1, 1, 0, 0, 0)) + copy.create_system, copy.external_attr = ( + item.create_system, + item.external_attr, + ) + target.writestr(copy, value) + return output.getvalue() diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 1d34c0079..789b13b1c 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -35,7 +35,7 @@ from app.modules.actors.api.service_identities import ServiceIdentity from app.modules.actors.models import ActorIdentityLink, ActorProfile from app.modules.artifacts.models import ( - ArtifactPutAttempt, ArtifactVerificationJob, SubmissionBundleAdmission, + SubmissionBundleAdmission, ) from app.modules.checkers.models import CheckerRun, SelectedPreSubmitRun from app.modules.checkers.execution_repository import stored_result @@ -45,7 +45,7 @@ from app.modules.tasks.models import Submission, SubmissionDispatch, WorkstreamTask from app.adapters.artifacts import trusted_submission_intake from app.adapters.checkers import configured_external_checker_execution -from experiments.pilot04_external_checker_runtime.run_selected_end_to_end_probe import ( +from experiments.pilot04_external_checker_runtime.public_probe_support import ( _locked_spec, _secret_archive, ) @@ -185,6 +185,41 @@ def _start_worker(env: dict[str, str], root: Path, generation: int) -> tuple[sub return process, hostname +def _start_finalization_worker(env: dict[str, str], root: Path): + """Use the production exclusive consumer; the general worker cannot consume T5.""" + hostname = f"journey-finalization-{uuid4().hex}@localhost" + process = _process([ + sys.executable, "-m", "celery", "-A", "app.workers.celery_app", "worker", + "--pool=prefork", "--concurrency=1", "--queues=workstream.submission_finalization", + "--hostname", hostname, "--without-gossip", "--without-mingle", "--without-heartbeat", + "--loglevel=ERROR", + ], env=env, log=root / "finalization-worker.log") + return process, hostname + + +def _require_source_runtime_window(settings): + """Use canonical supplied transport bounds; never inherit an obsolete90s override.""" + from app.modules.artifacts.api.submission_command import SubmissionExecutionProfile + from app.adapters.artifacts import selected_pre_submit_source_contracts + from app.modules.checkers.api.source_contracts import source_contracts_context + + _require(settings.submission_execution_profile is not None, + "supply an explicit source execution profile before qualification") + profile = SubmissionExecutionProfile.model_validate(settings.submission_execution_profile, + context=source_contracts_context(selected_pre_submit_source_contracts())) + _require(settings.external_checker_service_timeout_seconds * 1000 >= profile.runtime.aggregate_deadline_ms, + "source profile exceeds the configured runner request timeout") + return profile + + +def _require_parser_socket(settings): + """Require an explicitly supplied existing parser; never launch a second one.""" + path = settings.guide_document_parser_socket + _require(path.is_absolute() and not path.is_symlink() and path.is_socket(), + "existing guide parser socket is unavailable; supply WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET") + return path + + def _stop_process(process: subprocess.Popen | None) -> None: if process is None or process.poll() is not None: return @@ -377,25 +412,6 @@ async def _outbox_snapshot(factory, event_id: UUID) -> tuple: ) -async def _artifact_task_state(factory, task_id: str) -> tuple[list[tuple], list[tuple]]: - """Read only this task's put and verification disposition, never artifact data.""" - async with factory() as session: - puts = (await session.execute( - select(ArtifactPutAttempt.status, ArtifactPutAttempt.terminal_result_code) - .where(ArtifactPutAttempt.task_id == task_id, - ArtifactPutAttempt.producer_request_type == "submission_bundle") - )).all() - jobs = (await session.execute( - select(ArtifactVerificationJob.id, ArtifactVerificationJob.status, - ArtifactVerificationJob.terminal_result_code) - .join(ArtifactPutAttempt, - ArtifactVerificationJob.originating_put_attempt_id == ArtifactPutAttempt.id) - .where(ArtifactPutAttempt.task_id == task_id, - ArtifactPutAttempt.producer_request_type == "submission_bundle") - )).all() - return list(puts), list(jobs) - - async def _wait_outbox_due(factory, event_id: UUID) -> None: deadline = time.monotonic() + 30 while time.monotonic() < deadline: @@ -410,114 +426,113 @@ async def _wait_outbox_due(factory, event_id: UUID) -> None: raise RuntimeError("known safe outbox retry did not become due") -async def _ready_admission(client, factory, task_id: str, assignment_id: str, - contributor_token: str, archive: bytes, summary: str, - attestation: str, predecessor_id: str | None = None, *, hosted=False) -> str: - from app.workers.artifacts import verify_object - - expected_input = _fixture_hashes(archive) - key = str(uuid4()) +async def _source_headers(client, task_id, assignment_id, token, archive, summary, attestation, + predecessor_id=None): + """Bind original ZIP metadata and the exact current public revision acknowledgement.""" headers = { - "Content-Type": "application/zip", - "X-Task-Assignment-Id": assignment_id, - "Idempotency-Key": key, - "X-Submission-Summary": summary, - "X-Contributor-Attestation": attestation, + "Content-Type": "application/zip", "Content-Length": str(len(archive)), + "X-Task-Assignment-Id": assignment_id, "Idempotency-Key": str(uuid4()), + "X-Submission-Summary": summary, "X-Contributor-Attestation": attestation, } if predecessor_id is not None: - headers["X-Predecessor-Submission-Id"] = predecessor_id - detail = await _json(client, "GET", f"/api/v1/tasks/{task_id}/work-context", contributor_token, 200) + detail = await _json(client, "GET", f"/api/v1/tasks/{task_id}/work-context", token, 200) revision = detail["revision_context"] - headers["X-Revision-Preparation-Id"] = revision["preparation_id"] - headers["X-Revision-Preparation-Sha256"] = revision["preparation_sha256"] - route = f"/api/v1/tasks/{task_id}/submission-bundle-preparations" - deadline = time.monotonic() + 180 - current_status = None - status_since = time.monotonic() - scans_before = await _scan_audit_count(factory) + _require(revision and revision["source_submission_id"] == predecessor_id, + "revision acknowledgement differs from the exact predecessor") + headers.update({"X-Predecessor-Submission-Id": predecessor_id, + "X-Revision-Preparation-Id": revision["preparation_id"], + "X-Revision-Preparation-Sha256": revision["preparation_sha256"]}) + return headers + + +async def _finalized_source_evidence(factory, accepted, progress, expected_input): + """Observe real T5 lineage and immutable bytes; never inject a worker or verifier.""" + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from app.adapters.artifacts import selected_pre_submit_source_contracts + from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitTerminalFacts + + async with factory() as session: + operation = await session.get(SubmissionIntakeOperation, accepted["operation_id"]) + _require(operation and operation.state == "finalized" + and operation.finalized_submission_id == progress["submission_id"], + "public progress differs from retained finalization") + admission = await session.get(SubmissionBundleAdmission, operation.finalized_admission_id) + selected = await session.get(SelectedPreSubmitRun, operation.selected_pre_submit_run_id) + _require(selected is not None and admission and admission.status == "consumed" + and admission.source_operation_id == operation.id + and admission.consumed_by_submission_id == progress["submission_id"] + and admission.selected_pre_submit_run_id == selected.id, + "finalized source admission differs from accepted custody") + _assert_input_hashes(admission, expected_input) + terminal = SelectedPreSubmitTerminalFacts.from_canonical_body( + selected.terminal_json, source_contracts=selected_pre_submit_source_contracts()) + _require(terminal.execution and terminal.execution.eligible + and terminal.terminal_digest == operation.selected_pre_submit_terminal_sha256 + and terminal.execution.observed_source.raw_sha256 == expected_input["archive_sha256"] + and terminal.execution.manifest_sha256 == expected_input["semantic_manifest_sha256"], + "retained PRE differs from the exact submitted ZIP") + event_id, project_id = UUID(operation.finalization_event_id), UUID(operation.project_id) + admission_id = admission.id + await _wait_outbox_acknowledged(factory, event_id, project_id) + return {"submission_id": progress["submission_id"], "submission_version": progress["submission_version"], + "evaluation_request_id": progress["evaluation_request_id"], "admission_id": admission_id} + + +async def _await_finalized_source(client, factory, task_id, assignment_id, token, context, archive): + """Read exact public operation progress until actual worker finalization closes.""" + accepted = context["acceptance_receipt"] + deadline = time.monotonic() + 300 while time.monotonic() < deadline: - result = await _json( - client, "POST", route, contributor_token, 202, - headers=headers, content=archive, - ) - status = result["submission_bundle_preparation_status"] - _require( - bool(result["pre_submission_results"]), - "admitted intake omitted its feedback", - ) - if status == "ready": - _require(result["admission_id"] is not None, "ready intake omitted admission") - if await _scan_audit_count(factory) > scans_before: - async with factory() as session: - admission = await session.get(SubmissionBundleAdmission, result["admission_id"]) - _assert_input_hashes(admission, expected_input) - selected = await session.get(SelectedPreSubmitRun, admission.selected_pre_submit_run_id) - _assert_input_hashes(selected, expected_input) - return result["admission_id"] - await asyncio.sleep(1) - continue - _require(result["admission_id"] is None, "unverified admission was public") - _require(status not in { - "conflict", "integrity_mismatch", "missing", "absent_replay_required", "stale", - }, f"artifact preparation ended {status}") - if status != current_status: - current_status = status - status_since = time.monotonic() - now = time.monotonic() - if now - status_since >= 60: - puts, jobs = await _artifact_task_state(factory, task_id) - pending = [identifier for identifier, state, _ in jobs if state == "pending"] - if not hosted and status == "object_confirmed" and len(pending) == 1: - verification = await asyncio.to_thread( - verify_object.apply_async, args=(pending[0],), - ignore_result=False, - ) - try: - await asyncio.to_thread( - verification.get, timeout=90, propagate=True, - ) - except Exception as exc: - raise RuntimeError( - "artifact verifier task failed: " - f"{type(exc).__name__}/{type(exc.__cause__).__name__}; " - f"put_states={puts}; " - f"job_states={[(state, code) for _, state, code in jobs]}" - ) from None - finally: - await asyncio.to_thread(verification.forget) - puts, jobs = await _artifact_task_state(factory, task_id) - raise RuntimeError( - f"artifact preparation remained {status} after bounded worker scans; " - f"put_states={puts}; " - f"job_states={[(state, code) for _, state, code in jobs]}" - ) + progress = await _json(client, "GET", f"/api/v1/tasks/{task_id}/submission-operations", token, 200, + params={"operation_id": accepted["operation_id"]}) + _require(progress["operation_id"] == accepted["operation_id"] + and progress["task_id"] == task_id and progress["assignment_id"] == assignment_id + and progress["idempotency_key"] == context["idempotency_key"], + "public finalization progress substituted command selectors") + _require(not progress["operationally_stalled"] + and progress["operation_state"] in {"finalization_pending", "finalized"}, + "accepted source finalization failed or stalled; stop without another command") + if progress["operation_state"] == "finalized": + _require(progress["submission_id"] and progress["submission_version"] + and progress["evaluation_request_id"], "finalized progress omitted exact Submission selectors") + return await _finalized_source_evidence(factory, accepted, progress, _fixture_hashes(archive)) await asyncio.sleep(1) - raise RuntimeError(f"artifact verification did not become ready from {current_status}") + raise RuntimeError("source finalization did not complete; no worker task was injected") + + +async def _replay_source_submission(client, task_id, assignment_id, token, archive, summary, + attestation, saved): + """Replay the original command once, including its original revision acknowledgement.""" + headers = {"Content-Type": "application/zip", "Content-Length": str(len(archive)), + "X-Task-Assignment-Id": assignment_id, "Idempotency-Key": saved["idempotency_key"], + "X-Submission-Summary": summary, "X-Contributor-Attestation": attestation} + if saved["predecessor_submission_id"] is not None: + headers["X-Predecessor-Submission-Id"] = saved["predecessor_submission_id"] + headers.update(saved["revision_acknowledgement"]) + repeated = await _json(client, "POST", f"/api/v1/tasks/{task_id}/submissions", token, 202, + headers=headers, content=archive) + _require(repeated == dict(saved["acceptance_receipt"], replayed=True), + "public accepted source replay changed its exact receipt") async def _submit(client, factory, *, task_id: str, assignment_id: str, contributor_token: str, archive: bytes, summary: str, - attestation: str, predecessor_id: str | None, before_create=None, hosted=False) -> dict: - admission_id = await _ready_admission( - client, factory, task_id, assignment_id, contributor_token, - archive, summary, attestation, predecessor_id, hosted=hosted, - ) - if before_create is not None: - await before_create() - route = f"/api/v1/tasks/{task_id}/submissions" - packet = { - "assignment_id": assignment_id, - "admission_id": admission_id, - "predecessor_submission_id": predecessor_id, - "summary": summary, - "contributor_attestation": attestation, - } - saved = await _json(client, "POST", route, contributor_token, 201, json=packet) - repeated = await _json(client, "POST", route, contributor_token, 201, json=packet) - _require(saved == repeated, "public Submission replay changed receipt") - _require(saved["admission_id"] == admission_id, - "Submission consumed another admission") - return saved + attestation: str, predecessor_id: str | None) -> dict: + headers = await _source_headers(client, task_id, assignment_id, contributor_token, archive, + summary, attestation, predecessor_id) + accepted = await _json(client, "POST", f"/api/v1/tasks/{task_id}/submissions", contributor_token, 202, + headers=headers, content=archive) + _require(accepted["task_id"] == task_id and accepted["assignment_id"] == assignment_id + and accepted["status"] == "accepted" and accepted["replayed"] is False + and accepted["pre_submission_results"], "raw ZIP command returned an invalid accepted receipt") + context = {"operation_id": accepted["operation_id"], "acceptance_receipt": accepted, + "idempotency_key": headers["Idempotency-Key"], "predecessor_submission_id": predecessor_id, + "revision_acknowledgement": {name: value for name, value in headers.items() + if name.startswith("X-Revision-")}} + await _replay_source_submission(client, task_id, assignment_id, contributor_token, archive, + summary, attestation, context) + return context | await _await_finalized_source( + client, factory, task_id, assignment_id, contributor_token, context, archive) async def _complete_post(factory, *, submission_id: str, @@ -812,7 +827,7 @@ async def _one_mode(client, factory, env, *, "material is included in this submission; rights_confirmed." ) bad = await _json( - client, "POST", f"/api/v1/tasks/{task_id}/submission-bundle-preparations", + client, "POST", f"/api/v1/tasks/{task_id}/submissions", contributor_token, 422, headers={ "Content-Type": "application/zip", @@ -844,7 +859,7 @@ async def _one_mode(client, factory, env, *, "public default PRE feedback did not identify the injected private key", ) external_bad = await _json( - client, "POST", f"/api/v1/tasks/{task_id}/submission-bundle-preparations", + client, "POST", f"/api/v1/tasks/{task_id}/submissions", contributor_token, 422, headers={ "Content-Type": "application/zip", @@ -876,13 +891,20 @@ async def fail_post_launch(): first_archive = (_with_fixture_file(archive, "post-rejected.txt") if human_review_required else archive) - saved = await _submit( - client, factory, task_id=task_id, assignment_id=assignment_id, - contributor_token=contributor_token, archive=first_archive, - summary=summary, attestation=attestation, predecessor_id=None, - before_create=fail_post_launch if not human_review_required and fault_root else None, - hosted=attachment is not None, - ) + inject_post_fault = not human_review_required and fault_root is not None + if inject_post_fault: + _require(stop_worker is not None and start_worker is not None, "POST fault requires owned worker controls") + stop_worker() + try: + saved = await _submit( + client, factory, task_id=task_id, assignment_id=assignment_id, + contributor_token=contributor_token, archive=first_archive, + summary=summary, attestation=attestation, predecessor_id=None) + if inject_post_fault: + await fail_post_launch() + finally: + if inject_post_fault: + await start_worker() submission_path = f"/api/v1/tasks/{task_id}/submissions" history = await _json(client, "GET", submission_path, contributor_token, 200) _require([item["id"] for item in history["items"]] == [saved["submission_id"]], @@ -915,8 +937,7 @@ async def fail_post_launch(): contributor_token=contributor_token, archive=replacement_archive, summary=summary, attestation=attestation, predecessor_id=first_submission_id, - hosted=attachment is not None, - ) + ) expected_inputs[saved["submission_id"]] = _fixture_hashes(replacement_archive) _require(saved["submission_version"] == 2, "public checker remediation did not create version 2") @@ -1071,7 +1092,6 @@ async def run(database_url: str, image_reference: str, node_config: Path, bucket = os.environ["WORKSTREAM_TEST_MINIO_BUCKET"] prefix = os.environ["WORKSTREAM_TEST_MINIO_PREFIX"] scratch = Path(service_config["material_root"]) - socket_path = Path(service_config["socket_path"]) intake_images = [entry for entry in service_config["cache"] if entry["platform_manifest_digest"] == service_config["trusted_intake"]["platform_manifest_digest"]] @@ -1081,14 +1101,10 @@ async def run(database_url: str, image_reference: str, node_config: Path, "artifact_s3_bucket": bucket, "artifact_scratch_root": scratch, "artifact_scratch_minimum_free_bytes": 0, - "external_checker_service_socket": socket_path, - "external_checker_material_root": scratch, - "external_checker_service_timeout_seconds": 90.0, - "artifact_intake_service_socket": socket_path, "artifact_intake_image_digest": intake_image["platform_manifest_digest"], "artifact_intake_config_digest": intake_image["config_image_id"], }) - bootstrap = create_artifact_store_bootstrap(settings, activation_guard=None) + bootstrap = create_artifact_store_bootstrap(settings) namespace = artifact_storage_namespace_spec(settings, bootstrap) bootstrap.close() os.environ["WORKSTREAM_E2E_FLOW_ISSUER"] = "https://identity.flowresearch.tech" @@ -1104,10 +1120,6 @@ async def run(database_url: str, image_reference: str, node_config: Path, "WORKSTREAM_ARTIFACT_PENDING_WORK_SCAN_INTERVAL_SECONDS": "10", "WORKSTREAM_ARTIFACT_SCRATCH_ROOT": str(scratch), "WORKSTREAM_ARTIFACT_SCRATCH_MINIMUM_FREE_BYTES": "0", - "WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET": str(socket_path), - "WORKSTREAM_EXTERNAL_CHECKER_MATERIAL_ROOT": str(scratch), - "WORKSTREAM_EXTERNAL_CHECKER_SERVICE_TIMEOUT_SECONDS": "90", - "WORKSTREAM_ARTIFACT_INTAKE_SERVICE_SOCKET": str(socket_path), "WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST": intake_image["platform_manifest_digest"], "WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST": intake_image["config_image_id"], "PYTHONPATH": os.pathsep.join(map(str, (BACKEND, BACKEND / "tests", BACKEND.parent))), @@ -1138,10 +1150,13 @@ async def run(database_url: str, image_reference: str, node_config: Path, _require(runtime_settings.artifact_pending_work_scan_interval_seconds == 10, "Beat artifact scan interval differs from isolated drill") _require(runtime_settings.artifact_scratch_root == scratch - and runtime_settings.artifact_scratch_minimum_free_bytes == 0 - and runtime_settings.external_checker_service_socket == socket_path - and runtime_settings.external_checker_material_root == scratch, - "API/worker scratch or checker service configuration differs from fixture") + and runtime_settings.artifact_scratch_minimum_free_bytes == 0, + "API/worker scratch configuration differs from fixture") + _require(runtime_settings.external_runner_host is not None + and runtime_settings.submission_execution_profile is not None, + "supply explicit remote TLS runner and source execution profile before qualification") + _require_source_runtime_window(runtime_settings) + _require_parser_socket(runtime_settings) for field in ( "artifact_store_backend", "artifact_s3_provider_profile", "artifact_s3_region", "artifact_s3_endpoint_url", "artifact_s3_bucket", "artifact_s3_private_prefix", @@ -1150,7 +1165,7 @@ async def run(database_url: str, image_reference: str, node_config: Path, ): _require(getattr(runtime_settings, field) == getattr(settings, field), "API/worker artifact provider configuration differs from fixture") - runtime_bootstrap = create_artifact_store_bootstrap(runtime_settings, activation_guard=None) + runtime_bootstrap = create_artifact_store_bootstrap(runtime_settings) try: runtime_namespace = artifact_storage_namespace_spec( runtime_settings, runtime_bootstrap @@ -1167,7 +1182,7 @@ async def run(database_url: str, image_reference: str, node_config: Path, engine = create_async_engine(database_url) factory = async_sessionmaker(engine, expire_on_commit=False) - api = worker = beat = None + api = worker = beat = finalization_worker = None worker_generation = 0 def stop_owned_worker() -> None: @@ -1212,6 +1227,8 @@ async def start_owned_worker() -> None: ], env=env, log=root / "api.log") await _wait_api(origin, api) await start_owned_worker() + finalization_worker, finalization_hostname = _start_finalization_worker(env, root) + await _wait_worker(finalization_worker, finalization_hostname) scans_before_beat = await _scan_audit_count(factory) beat = _process([ sys.executable, "-m", "celery", "-A", "app.workers.celery_app", @@ -1236,14 +1253,15 @@ async def start_owned_worker() -> None: stop_worker=stop_owned_worker, start_worker=start_owned_worker, fault_root=fault_root, operator_token=_token(env, operator)) - _require(api.poll() is None and worker.poll() is None and beat.poll() is None, + _require(api.poll() is None and worker.poll() is None and beat.poll() is None + and finalization_worker.poll() is None, "API, prefork worker, or Beat exited during public journey") return {"tree_sha": subprocess.check_output( ["git", "rev-parse", "HEAD"], text=True, cwd=BACKEND ).strip(), "runtime": "smolvm/smol-microvm", "image_digest": image["platform_manifest_digest"], "trusted_intake_image_digest": intake_health.image_digest, "trusted_intake_config_digest": intake_health.config_digest, - "public_api": True, "prefork_worker": True, "maximum_parallel": 1, + "public_api": True, "prefork_worker": True, "prefork_finalization_worker": True, "maximum_parallel": 1, "scheduled_artifact_scans": True, "public_original_guide_setup": True, "recorded_inference": True, @@ -1254,6 +1272,7 @@ async def start_owned_worker() -> None: _stop_process(beat) for schedule_file in root.glob("beat-schedule*"): schedule_file.unlink() + _stop_process(finalization_worker) _stop_process(worker) _stop_process(api) await engine.dispose() diff --git a/experiments/pilot04_external_checker_runtime/run_selected_end_to_end_probe.py b/experiments/pilot04_external_checker_runtime/run_selected_end_to_end_probe.py deleted file mode 100644 index bc22f7a03..000000000 --- a/experiments/pilot04_external_checker_runtime/run_selected_end_to_end_probe.py +++ /dev/null @@ -1,645 +0,0 @@ -"""Run selected PRE, atomic Submission and selected POST through one Rust service.""" - -from __future__ import annotations - -import argparse -import asyncio -import json -import os -from pathlib import Path -import subprocess -import tempfile -from io import BytesIO -from types import SimpleNamespace -from uuid import UUID -from unittest.mock import patch -from zipfile import ZipFile, ZipInfo - -from aiobotocore.config import AioConfig -from aiobotocore.session import AioSession -from sqlalchemy import func, select, text -from starlette.requests import Request - -from app.adapters.artifacts import ( - artifact_preparation_limits, - create_artifact_scratch_manager, - get_submission_bundle_preparation_command, -) -from app.adapters.checkers import external_checker_execution_factory -from app.adapters.outbox import production_outbox_delivery -from app.adapters.tasks import task_submission_context_port -from app.adapters.artifacts.internal_workers import shutdown_artifact_internal_runtime -from app.api.deps.authorization import compose_hidden_submission_creation_command -from app.core.identifiers import new_record_id -from app.modules.actors.api.service_identities import ServiceIdentity -from app.modules.artifacts.api import ( - SubmissionBundlePreparationCheckFailed, - SubmissionBundlePreparationInfrastructureUnavailable, - SubmissionBundlePreparationRequest, - SubmissionBundlePreparationStatus, -) -from app.modules.artifacts.models import ( - ArtifactVerificationJob, - SubmissionBundleAdmission, -) -from app.modules.artifacts.service import ArtifactStorageOrchestrator -from app.modules.artifacts.authorization import ( - PreparedArtifactInternalAuthority, - PreparedSubmissionBundlePreparationAuthorization, -) -from app.modules.authorization.api import ActorIdentityFacts, ActorKind -from app.modules.checkers.api.external import ( - PRE_SUBMIT_INPUT_SCHEMA_ID, - ExternalCheckerRegistrySpec, - ExternalCheckerSchema, - external_checker_json_hash, -) -from app.modules.checkers.models import CheckerRun, SelectedPreSubmitRun -from app.modules.tasks.api import SubmissionCreationRequest -from app.modules.tasks.models import Submission, SubmissionDispatch, WorkstreamTask -from experiments.pilot04_external_checker_runtime.run_probe import _image_identity -from tests.artifact_store_helpers import artifact_admission_limit_settings -from app.modules.checkers.execution_repository import stored_result -from tests.authorization.post_submit_routing.support import provision_router -from tests.tasks.evaluation_delivery.support import delivery_fixture, outcome -from tests.tasks.post_submit_routing.outcome_support import outcome_snapshot -from tests.checkers.external.support import post_registry_spec, registry_spec -from tests.archive_fixtures import byte_source -from tests.post_submit_materialization_helpers import material_fixture -from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test -from tests.test_s3_artifact_store import ( - MINIO_ACCESS_KEY, - MINIO_ENDPOINT, - MINIO_REGION, - MINIO_SECRET_KEY, - minio_settings, -) - - -def _locked_spec(phase: str, image: dict[str, str]) -> ExternalCheckerRegistrySpec: - source = registry_spec("pre_submit") if phase == "pre_submit" else post_registry_spec() - values = source.model_dump(mode="json") - if phase == "pre_submit": - document = {"type": "object"} - values["input_schema"] = ExternalCheckerSchema( - schema_id=PRE_SUBMIT_INPUT_SCHEMA_ID, - schema_version="v1", - document=document, - schema_sha256=external_checker_json_hash(document), - ).model_dump(mode="json") - values["image_digest"] = image["platform_manifest_digest"] - values["resources"] |= {"deadline_ms": 30_000, "maximum_output_bytes": 8_192} - return ExternalCheckerRegistrySpec.model_validate(values) - - -async def _bucket_client(): - session = AioSession() - session.set_credentials(MINIO_ACCESS_KEY, MINIO_SECRET_KEY) - return session.create_client( - "s3", - endpoint_url=MINIO_ENDPOINT, - region_name=MINIO_REGION, - config=AioConfig(s3={"addressing_style": "path"}), - ) - - -async def _delete_bucket(bucket: str) -> None: - async with await _bucket_client() as client: - values = await client.list_objects_v2(Bucket=bucket) - objects = [{"Key": item["Key"]} for item in values.get("Contents", ())] - if objects: - await client.delete_objects(Bucket=bucket, Delete={"Objects": objects}) - await client.delete_bucket(Bucket=bucket) - - -def _secret_archive(source: bytes) -> bytes: - """Preserve the valid packet while introducing one known private key.""" - output = BytesIO() - with ZipFile(BytesIO(source)) as existing, ZipFile(output, "w") as target: - for item in existing.infolist(): - value = existing.read(item) - if item.filename == "task.toml": - value += b"\n-----BEGIN OPENSSH PRIVATE KEY-----\nencoded\n" - copy = ZipInfo(item.filename, date_time=(1980, 1, 1, 0, 0, 0)) - copy.create_system, copy.external_attr = ( - item.create_system, - item.external_attr, - ) - target.writestr(copy, value) - return output.getvalue() - - -async def _prepare(fixture, settings, request): - """Enter the actual hidden PRE composition with no owner bypass.""" - http = Request( - { - "type": "http", - "headers": [], - "app": SimpleNamespace(state=SimpleNamespace(settings=settings)), - } - ) - async with fixture.factory() as session: - authority = PreparedArtifactInternalAuthority( - session, - service_identity=ServiceIdentity.ARTIFACT_PUT_RESOLVER, - request_id=new_record_id(), - correlation_id=new_record_id(), - ) - return await get_submission_bundle_preparation_command( - http, - session, - authority, - PreparedSubmissionBundlePreparationAuthorization( - session, fixture.actor_context - ), - ).prepare(request) - - -async def _prove_work_failure(fixture, settings, *, external=False) -> dict[str, object]: - """Either actual default or project-image failure prevents admission.""" - task_id, assignment_id = new_record_id(), new_record_id() - params = { - "task": str(task_id), - "assignment": str(assignment_id), - "project": str(fixture.facts.project_id), - "actor": str(fixture.actor_context.actor_profile_id), - } - async with fixture.engine.begin() as connection: - await seed_started_task_for_artifact_test(connection, params) - data = _secret_archive(fixture.data) - if external: - output = BytesIO(fixture.data) - with ZipFile(output, "a") as archive: - archive.writestr("project-rejected.txt", b"sample project rejection\n") - data = output.getvalue() - request = SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - fixture.actor_context.actor_profile_id, - fixture.actor_context.identity_link_id, - ActorKind.HUMAN, - ), - request_id=new_record_id(), - correlation_id=new_record_id(), - task_id=task_id, - assignment_id=assignment_id, - predecessor_submission_id=None, - idempotency_key=new_record_id(), - summary=fixture.creation_request.summary, - contributor_attestation=fixture.creation_request.contributor_attestation, - media_type="application/zip", - byte_source=byte_source(data), - ) - try: - await _prepare(fixture, settings, request) - except SubmissionBundlePreparationCheckFailed as error: - codes = tuple( - check.failure_code - for check in error.facts.workstream_default.checks - if check.failure_code is not None - ) - if external: - if codes or len(error.facts.external_members) != 1: - raise RuntimeError("project failure did not follow passing defaults") - result = error.facts.external_members[0].result - codes = tuple(item.code for item in result.findings) - if result.verdict != "failed" or codes != ("probe.project_rule_failed",): - raise RuntimeError("project image did not return its exact failure") - else: - raise RuntimeError("rejected input unexpectedly passed selected PRE") - async with fixture.factory() as session: - task = await session.get(WorkstreamTask, str(task_id)) - submissions = await session.scalar(select(func.count()).select_from(Submission)) - if task.status != "in_progress" or submissions != 1: - raise RuntimeError("work finding created a Submission or advanced its Task") - return { - "task_id": str(task_id), - "failure_codes": codes, - "submission_count": submissions, - } - - -def _start_service(binary: Path, config_path: Path, socket_path: Path): - """Start only the private checker service and wait for its UDS endpoint.""" - socket_path.unlink(missing_ok=True) - return subprocess.Popen( - [str(binary), str(config_path)], - stdout=subprocess.DEVNULL, - stderr=subprocess.PIPE, - text=True, - ) - - -async def _wait_service(service, socket_path: Path) -> None: - for _ in range(500): - if socket_path.exists(): - return - if service.poll() is not None: - detail = service.stderr.read().strip() if service.stderr is not None else "" - raise RuntimeError( - f"checker service exited before readiness: {detail or 'no stderr'}" - ) - await asyncio.sleep(0.02) - raise RuntimeError("checker service socket did not become ready") - - -def _stop_service(service) -> None: - if service.poll() is not None: - return - service.terminate() - try: - service.wait(timeout=5) - except subprocess.TimeoutExpired: - service.kill() - service.wait(timeout=5) - - -def _request(fixture, task_id, assignment_id, data: bytes): - return SubmissionBundlePreparationRequest( - actor=ActorIdentityFacts( - fixture.actor_context.actor_profile_id, - fixture.actor_context.identity_link_id, - ActorKind.HUMAN, - ), - request_id=new_record_id(), - correlation_id=new_record_id(), - task_id=task_id, - assignment_id=assignment_id, - predecessor_submission_id=None, - idempotency_key=new_record_id(), - summary=fixture.creation_request.summary, - contributor_attestation=fixture.creation_request.contributor_attestation, - media_type="application/zip", - byte_source=byte_source(data), - ) - - -async def _verify_prepared(fixture, settings, prepared): - """Run the independent ART verifier for one freshly uploaded preparation.""" - async with fixture.factory() as session: - job_id = await session.scalar( - select(ArtifactVerificationJob.id).where( - ArtifactVerificationJob.originating_put_attempt_id - == str(prepared.put_attempt_id) - ) - ) - if job_id is None: - raise RuntimeError("fresh preparation did not enqueue verification") - await session.rollback() - verifier = PreparedArtifactInternalAuthority( - session, - service_identity=ServiceIdentity.ARTIFACT_VERIFIER, - request_id=new_record_id(), - correlation_id=new_record_id(), - ) - outcome = await ArtifactStorageOrchestrator( - session, fixture.store, fixture.namespace, settings, verifier - ).verify_object( - UUID(job_id), - submission_task_contexts=task_submission_context_port(session), - ) - if outcome != "verified": - raise RuntimeError("fresh preparation verification did not complete") - async with fixture.factory() as session: - admission = ( - await session.scalars( - select(SubmissionBundleAdmission).where( - SubmissionBundleAdmission.put_attempt_id - == str(prepared.put_attempt_id) - ) - ) - ).one() - if admission.status != "ready": - raise RuntimeError("fresh preparation admission is not ready") - return UUID(admission.id) - - -async def _prove_infrastructure_recovery( - fixture, settings, service_holder, service_binary, config_path, socket_path -): - """Retain infrastructure failure, then require a fresh successful upload.""" - task_id, assignment_id = new_record_id(), new_record_id() - params = { - "task": str(task_id), - "assignment": str(assignment_id), - "project": str(fixture.facts.project_id), - "actor": str(fixture.actor_context.actor_profile_id), - } - async with fixture.engine.begin() as connection: - await seed_started_task_for_artifact_test(connection, params) - _stop_service(service_holder[0]) - try: - await _prepare( - fixture, settings, _request(fixture, task_id, assignment_id, fixture.data) - ) - except SubmissionBundlePreparationInfrastructureUnavailable as error: - failure_code = str(error) - else: - raise RuntimeError("unavailable checker service did not fail preparation") - async with fixture.factory() as session: - task = await session.get(WorkstreamTask, str(task_id)) - before_submissions = await session.scalar( - select(func.count()).select_from(Submission) - ) - failed = ( - ( - await session.execute( - select(SelectedPreSubmitRun) - .where(SelectedPreSubmitRun.task_id == str(task_id)) - .order_by(SelectedPreSubmitRun.queued_at) - ) - ) - .scalars() - .all() - ) - if ( - task.status != "in_progress" - or before_submissions != 1 - or len(failed) != 1 - or failed[0].status != "infrastructure_failed" - ): - raise RuntimeError("infrastructure failure changed TASK or was not retained") - service = _start_service(service_binary, config_path, socket_path) - service_holder[0] = service - await _wait_service(service, socket_path) - recovered = await _prepare( - fixture, - settings, - _request(fixture, task_id, assignment_id, fixture.data), - ) - if recovered.replayed: - raise RuntimeError( - "fresh preparation did not recover infrastructure failure: " - f"status={recovered.submission_bundle_preparation_status}, " - f"admission={recovered.admission_id}, replayed={recovered.replayed}" - ) - if ( - recovered.submission_bundle_preparation_status - == SubmissionBundlePreparationStatus.STORED_PENDING_VERIFICATION - and recovered.admission_id is None - ): - admission_id = await _verify_prepared(fixture, settings, recovered) - elif ( - recovered.submission_bundle_preparation_status - == SubmissionBundlePreparationStatus.READY - and recovered.admission_id is not None - ): - admission_id = recovered.admission_id - else: - raise RuntimeError( - "fresh preparation returned an invalid durable state: " - f"status={recovered.submission_bundle_preparation_status}, " - f"admission={recovered.admission_id}" - ) - async with fixture.factory() as session: - created = await compose_hidden_submission_creation_command( - session, - fixture.actor_context, - request_id=new_record_id(), - correlation_id=new_record_id(), - ).create( - SubmissionCreationRequest( - task_id=task_id, - assignment_id=assignment_id, - contributor_id=fixture.actor_context.actor_profile_id, - predecessor_submission_id=None, - admission_id=admission_id, - summary=fixture.creation_request.summary, - contributor_attestation=fixture.creation_request.contributor_attestation, - ) - ) - async with fixture.factory() as session: - task = await session.get(WorkstreamTask, str(task_id)) - submission_count = await session.scalar( - select(func.count()).select_from(Submission) - ) - dispatch_count = await session.scalar( - select(func.count()).select_from(SubmissionDispatch) - ) - runs = ( - ( - await session.execute( - select(SelectedPreSubmitRun.status) - .where(SelectedPreSubmitRun.task_id == str(task_id)) - .order_by(SelectedPreSubmitRun.queued_at) - ) - ) - .scalars() - .all() - ) - if ( - task.status != "evaluation_pending" - or submission_count != 2 - or dispatch_count != 2 - or tuple(runs) != ("infrastructure_failed", "completed") - ): - raise RuntimeError("fresh recovery did not commit one atomic dispatch") - return { - "failure_code": failure_code, - "retained_run_statuses": runs, - "submission_id": str(created.submission_id), - "evaluation_request_id": str(created.evaluation_request_id), - "submission_count": submission_count, - "dispatch_count": dispatch_count, - } - - -async def _production_post_delivery(fixture, settings): - """Use production handlers and a fresh worker runtime, then replay delivery.""" - # The ART arrangement is not a contributor-start authority proof. Supply - # its exact accepted-assignment prerequisite before testing routing owners. - async with fixture.factory() as session, session.begin(): - accepted = await session.execute(text( - "UPDATE public.task_assignments SET accepted_at=clock_timestamp() " - "WHERE id=:id AND accepted_at IS NULL" - ), {"id": str(fixture.request.assignment_id)}) - if accepted.rowcount != 1: - raise RuntimeError("fixture assignment acceptance was not established") - await provision_router(fixture.factory) - await delivery_fixture(fixture) - # Supply only this isolated run's configuration. Every provider, grant, - # authority, execution and routing operation remains the production owner. - with patch("app.core.config.get_settings", return_value=settings), patch( - "app.adapters.artifacts.internal_workers.get_settings", return_value=settings - ): - shutdown_artifact_internal_runtime() - try: - delivery = production_outbox_delivery(fixture.factory) - requested = await delivery.deliver( - fixture.created.evaluation_event_id, fixture.facts.project_id, - "selected-production-request", - ) - if requested is None or outcome(requested)["delivery_state"] != "acknowledged": - raise RuntimeError("production evaluation request was not acknowledged") - async with fixture.factory() as session: - run = await session.get(CheckerRun, str(fixture.created.evaluation_attempt_id)) - if run.status != "completed" or run.completion_event_id is None: - raise RuntimeError("production selected execution did not emit completion") - result = stored_result(run) - completion_id = run.completion_event_id - # Reconstruct the worker between the two durable events. No callback - # grant, lease capability or in-memory result crosses this boundary. - shutdown_artifact_internal_runtime() - delivery = production_outbox_delivery(fixture.factory) - completed = await delivery.deliver( - completion_id, fixture.facts.project_id, "selected-production-completion", - ) - if completed is None or outcome(completed)["delivery_state"] != "acknowledged": - raise RuntimeError("production completion was not acknowledged") - async with fixture.factory() as session: - before = await outcome_snapshot(session) - if await delivery.deliver( - completion_id, fixture.facts.project_id, "selected-production-replay", - ) is not None: - raise RuntimeError("production completion was delivered twice") - async with fixture.factory() as session: - if await outcome_snapshot(session) != before: - raise RuntimeError("duplicate completion changed retained owner facts") - return result - finally: - shutdown_artifact_internal_runtime() - - -async def run( - *, database_url: str, image_reference: str, service_binary: Path, root: Path -) -> dict[str, object]: - """Prove actual image execution on both sides of atomic Submission creation.""" - image = _image_identity(image_reference) - bucket = "ws-p04-e2e-" + os.urandom(8).hex() - socket_root, scratch = root / "service", root / "scratch" - socket_root.mkdir(mode=0o700) - scratch.mkdir(mode=0o700) - socket_path = socket_root / "checker.sock" - settings = minio_settings( - private_prefix="selected-flow", - ).model_copy( - update={ - **artifact_admission_limit_settings(1024 * 1024), - "artifact_s3_bucket": bucket, - "artifact_scratch_root": scratch, - "artifact_scratch_minimum_free_bytes": 0, - "external_checker_service_socket": socket_path, - "external_checker_material_root": scratch, - "external_checker_service_timeout_seconds": 90.0, - } - ) - config = { - "socket_path": str(socket_path), - "material_root": str(scratch), - "docker_binary": "/usr/bin/docker", - "runtime": "runc", - "isolation_mode": "docker-dev", - "operating_system": image["operating_system"], - "architecture": image["architecture"], - "sandbox_uid": os.getuid(), - "sandbox_gid": os.getgid(), - "cache": [image], - } - config_path = socket_root / "service.json" - config_path.write_text(json.dumps(config, separators=(",", ":"))) - scratch_owner = create_artifact_scratch_manager(settings) - scratch_owner.close() - async with await _bucket_client() as client: - await client.create_bucket(Bucket=bucket) - service = _start_service(service_binary, config_path, socket_path) - service_holder = [service] - try: - await _wait_service(service, socket_path) - adapter = external_checker_execution_factory( - socket_path=socket_path, timeout_seconds=90.0 - ).create("unix_socket") - health = await adapter.health() - async with material_fixture( - root, - database_url, - storage_settings=settings, - pre_submit_registry_spec=_locked_spec("pre_submit", image), - post_submit_registry_spec=_locked_spec("post_submit", image), - post_scratch_root=scratch, - scratch_limits=artifact_preparation_limits(settings), - ) as fixture: - result = await _production_post_delivery(fixture, settings) - async with fixture.factory() as session: - task = await session.get(WorkstreamTask, str(fixture.facts.task_id)) - submission_count = await session.scalar( - select(func.count()).select_from(Submission) - ) - run_row = await session.get(CheckerRun, str(result.attempt_id)) - if ( - submission_count != 1 - or task.status != "review_pending" - or result.outcome != "completed" - or result.execution is None - or len(result.execution.external_members) != 1 - or run_row.status != "completed" - ): - raise RuntimeError("selected flow did not retain its atomic boundaries") - member = result.execution.external_members[0] - if ( - member.result.verdict != "passed" - or member.isolation.platform_manifest_digest - != image["platform_manifest_digest"] - ): - raise RuntimeError("selected POST result or isolation differs") - workspaces = scratch / "workspaces" - workspace_cleanup = not workspaces.exists() or not any(workspaces.iterdir()) - if not workspace_cleanup: - raise RuntimeError("selected checker workspace cleanup is incomplete") - work_failure = await _prove_work_failure(fixture, settings) - external_pre_failure = await _prove_work_failure(fixture, settings, external=True) - infrastructure_recovery = await _prove_infrastructure_recovery( - fixture, - settings, - service_holder, - service_binary, - config_path, - socket_path, - ) - return { - "image": image, - "health": { - "runtime": health.runtime, - "isolation_mode": health.isolation_mode, - }, - "submission_id": str(fixture.created.submission_id), - "evaluation_request_id": str(fixture.created.evaluation_request_id), - "attempt_id": str(result.attempt_id), - "post_result_digest": result.result_digest, - "post_member_result_digest": member.result.result_digest, - "task_status": task.status, - "submission_count": submission_count, - "workspace_cleanup": workspace_cleanup, - "work_failure": work_failure, - "external_pre_failure": external_pre_failure, - "infrastructure_recovery": infrastructure_recovery, - "minio_bucket": bucket, - } - finally: - _stop_service(service_holder[0]) - await _delete_bucket(bucket) - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument( - "--database-url", default=os.environ.get("WORKSTREAM_TEST_DATABASE_URL") - ) - parser.add_argument("--image-reference", required=True) - parser.add_argument("--service-binary", required=True, type=Path) - args = parser.parse_args() - if not args.database_url: - parser.error("--database-url or WORKSTREAM_TEST_DATABASE_URL is required") - with tempfile.TemporaryDirectory(prefix="ws-pilot04-selected-e2e-") as directory: - value = asyncio.run( - run( - database_url=args.database_url, - image_reference=args.image_reference, - service_binary=args.service_binary, - root=Path(directory), - ) - ) - print(json.dumps(value, sort_keys=True, separators=(",", ":"))) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 78b7bb5f6..0e34c4174 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -308,7 +308,7 @@ def test_fresh_setup_grants_operator_then_registers_exact_supplied_baseline_capa from datetime import UTC, datetime from app.core.identifiers import new_record_id from app.modules.checkers.api.external import ExternalCheckerRegistrySpec - from experiments.pilot04_external_checker_runtime.run_selected_end_to_end_probe import _locked_spec + from experiments.pilot04_external_checker_runtime.public_probe_support import _locked_spec capabilities = {'pre_submit': {'capability_id': 'probe.hosted_pre', 'capability_version': 'v1'}, 'post_submit': {'capability_id': 'probe.hosted_post', 'capability_version': 'v1'}} diff --git a/scripts/test_public_hosted_model_post.py b/scripts/test_public_hosted_model_post.py index 73ebaf124..a6f8c699f 100644 --- a/scripts/test_public_hosted_model_post.py +++ b/scripts/test_public_hosted_model_post.py @@ -333,7 +333,10 @@ async def handler(request): response = {**body, 'entry_digest': spec.spec_digest, 'registry_entry_id': str(new_record_id())} return httpx.Response(201, json=response) - attachment = SimpleNamespace(token_for_label=lambda label: 'scoped-rs256-fixture') + baseline_pre = {'requirement_id': 'project.pre_submit', 'registry_entry_id': str(new_record_id()), + 'registry_entry_digest': 'sha256:' + 'b' * 64, 'configuration': {}} + attachment = SimpleNamespace(token_for_label=lambda label: 'scoped-rs256-fixture', + approval_attachments=lambda count: {'pre_submit_attachments': [baseline_pre]}) async def exercise(): async with httpx.AsyncClient(base_url='http://127.0.0.1:8000', transport=httpx.MockTransport(handler)) as client: @@ -353,7 +356,7 @@ async def exercise(): self.assertEqual(budget['configuration_version'], 1) self.assertEqual(qualification.state['historical_charge']['status'], 'unresolved_separate') selected = qualification.approval_attachments() - self.assertEqual(selected['pre_submit_attachments'], []) + self.assertEqual(selected['pre_submit_attachments'], [baseline_pre]) [attachment] = selected['post_submit_attachments'] self.assertEqual(attachment['requirement_id'], CHECK) self.assertEqual(attachment['registry_entry_id'], qualification.registry['registry_entry_id']) @@ -364,20 +367,21 @@ async def exercise(): self.assertEqual(configuration['model_profile_id'], str(profile_id)) self.assertEqual(configuration['model_profile_digest'], qualification.profile.profile_digest) original = qualification.guide_bytes() - rules = json.loads(qualification.rules(original, 0)) + rules = json.loads(qualification.rules(original, 1)) self.assertNotIn('pre_submit_bindings', rules) self.assertNotIn('post_submit_bindings', rules) doc = SimpleNamespace(source_item_id=new_record_id(), ingest_id=new_record_id(), sha256=digest(original)) authored = SimpleNamespace(source_item_id=new_record_id(), ingest_id=new_record_id(), sha256=digest(canonical(rules))) result = _compile_rules(SimpleNamespace(agent_version='v1', material=SimpleNamespace(documents=[doc, authored])), [(authored, rules)]) - [suggestion] = result.requirements - self.assertEqual(suggestion.stage, 'post_submit') + self.assertEqual([item.stage for item in result.requirements], ['pre_submit', 'post_submit']) + [suggestion] = [item for item in result.requirements if item.stage == 'post_submit'] self.assertNotEqual(suggestion.suggestion_id, attachment['requirement_id']) self.assertEqual([ref.sha256 for ref in suggestion.evidence_refs], [doc.sha256, authored.sha256]) self.assertEqual(suggestion.check_specification, specification()[0]) self.assertTrue(suggestion.check_specification.implementation_needs) - with self.assertRaisesRegex(RuntimeError, 'must not propose a PRE check'): - qualification.rules(original, 1) + for count in (0, 2): + with self.assertRaisesRegex(RuntimeError, 'exactly one baseline PRE'): + qualification.rules(original, count) def test_ambiguous_effect_or_outstanding_reservation_cannot_claim_model_proof(self): good = {'reserved_nanodollars': 0, 'effects': [{'state': 'completed', 'provider_response_known': True, @@ -433,26 +437,30 @@ def test_fixture_is_deterministic_and_its_disclosed_commands_are_coherent(self): subprocess.run(['sh', 'tests/run.sh'], cwd=self.root, capture_output=True, check=True, timeout=5) self.assertIn(b'no execution or trial measurement is claimed', (self.root / 'evidence/results').read_bytes()) - def test_hosted_stalled_admission_does_not_inject_a_verifier_task(self): + def test_stalled_source_finalization_does_not_inject_a_worker_task(self): from app.core.config import get_settings with patch.dict(os.environ, {'WORKSTREAM_CELERY_BROKER_URL': 'redis://127.0.0.1:6379/15'}): - # Earlier proof imports may have cached settings without a broker. get_settings.cache_clear() try: from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe - from app.workers.artifacts import verify_object - - result = {'pre_submission_results': [{}], 'submission_bundle_preparation_status': 'object_confirmed', 'admission_id': None} - ticks = iter(range(0, 1000, 31)) - with patch.object(probe, '_fixture_hashes', return_value={}), \ - patch.object(probe, '_scan_audit_count', new=AsyncMock(return_value=0)), \ - patch.object(probe, '_json', new=AsyncMock(return_value=result)), \ - patch.object(probe, '_artifact_task_state', new=AsyncMock(return_value=([], [('job', 'pending', None)]))), \ + from app.workers.outbox import finalize_submission + + task, assignment, operation, key = (str(new_record_id()) for _ in range(4)) + context = {'acceptance_receipt': {'operation_id': operation}, 'idempotency_key': key} + progress = {'operation_id': operation, 'task_id': task, 'assignment_id': assignment, + 'idempotency_key': key, 'operation_state': 'finalization_pending', + 'operationally_stalled': False} + ticks = iter(range(0, 1000, 101)) + with patch.object(probe, '_json', new=AsyncMock(return_value=progress)) as reads, \ patch.object(probe.time, 'monotonic', side_effect=lambda: next(ticks)), \ - patch.object(probe.asyncio, 'sleep', new=AsyncMock()), patch.object(verify_object, 'apply_async') as dispatch: - with self.assertRaisesRegex(RuntimeError, 'remained object_confirmed'): - asyncio.run(probe._ready_admission(None, None, 'task', 'assignment', 'token', b'zip', 'summary', 'attestation', hosted=True)) + patch.object(probe.asyncio, 'sleep', new=AsyncMock()), \ + patch.object(finalize_submission, 'apply_async') as dispatch: + with self.assertRaisesRegex(RuntimeError, 'source finalization did not complete'): + asyncio.run(probe._await_finalized_source( + None, None, task, assignment, 'token', context, b'zip')) + self.assertEqual(reads.await_count, 2) + self.assertTrue(all(call.args[1] == 'GET' for call in reads.await_args_list)) dispatch.assert_not_called() finally: get_settings.cache_clear() @@ -477,5 +485,139 @@ def test_model_stage_requires_and_uses_the_existing_hosted_attachment(self): local.assert_not_called() +class PublicSourceCommandContracts(unittest.TestCase): + def test_raw_zip_acceptance_replays_once_then_observes_finalization(self): + import httpx + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + task, assignment, operation = (str(new_record_id()) for _ in range(3)) + accepted = {'operation_id': operation, 'task_id': task, 'assignment_id': assignment, + 'status': 'accepted', 'replayed': False, 'pre_submission_results': [{}]} + posts, reads = [], [] + graph = {'submission_id': str(new_record_id()), 'submission_version': 1, + 'evaluation_request_id': str(new_record_id()), 'admission_id': str(new_record_id())} + + async def respond(request): + self.assertNotIn('submission-bundle-preparations', request.url.path) + if request.method == 'POST': + self.assertEqual(request.headers['Content-Type'], 'application/zip') + self.assertEqual(request.headers['Content-Length'], '7') + self.assertEqual(request.content, b'raw-zip') + posts.append(dict(request.headers)) + return httpx.Response(202, json=accepted | {'replayed': len(posts) > 1}) + self.assertEqual(request.method, 'GET') + self.assertEqual(dict(request.url.params), {'operation_id': operation}) + reads.append(request.url.path) + return httpx.Response(200, json={ + 'operation_id': operation, 'task_id': task, 'assignment_id': assignment, + 'idempotency_key': posts[0]['idempotency-key'], 'operationally_stalled': False, + 'operation_state': 'finalized' if len(reads) == 2 else 'finalization_pending', **graph}) + + async def exercise(): + async with httpx.AsyncClient(transport=httpx.MockTransport(respond), base_url='http://test') as client: + return await probe._submit(client, None, task_id=task, assignment_id=assignment, + contributor_token='token', archive=b'raw-zip', summary='summary', + attestation='attestation', predecessor_id=None) + + with patch.object(probe, '_finalized_source_evidence', new=AsyncMock(return_value=graph)) as retained, \ + patch.object(probe, '_fixture_hashes', return_value={'expected': 'hashes'}), \ + patch.object(probe.asyncio, 'sleep', new=AsyncMock()): + saved = asyncio.run(exercise()) + self.assertEqual(posts[0], posts[1]) + self.assertEqual(len(posts), 2) + self.assertEqual(len(reads), 2) + self.assertEqual(saved['acceptance_receipt'], accepted) + self.assertEqual(saved['submission_id'], graph['submission_id']) + retained.assert_awaited_once() + + def test_progress_selector_substitution_fails_before_retained_reads(self): + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + task, assignment, operation, key = (str(new_record_id()) for _ in range(4)) + context = {'acceptance_receipt': {'operation_id': operation}, 'idempotency_key': key} + valid = {'task_id': task, 'assignment_id': assignment, 'operation_id': operation, + 'idempotency_key': key, 'operation_state': 'finalized', 'operationally_stalled': False, + 'submission_id': str(new_record_id()), 'submission_version': 1, + 'evaluation_request_id': str(new_record_id())} + with patch.object(probe, '_fixture_hashes', return_value={}), \ + patch.object(probe, '_finalized_source_evidence', new=AsyncMock(return_value={'control': True})) as retained: + with patch.object(probe, '_json', new=AsyncMock(return_value=valid)): + self.assertEqual(asyncio.run(probe._await_finalized_source( + None, None, task, assignment, 'token', context, b'zip')), {'control': True}) + retained.reset_mock() + for field in ('task_id', 'assignment_id', 'operation_id', 'idempotency_key'): + with self.subTest(field=field), \ + patch.object(probe, '_json', new=AsyncMock(return_value=valid | {field: str(new_record_id())})): + with self.assertRaisesRegex(RuntimeError, 'substituted command selectors'): + asyncio.run(probe._await_finalized_source(None, None, task, assignment, 'token', context, b'zip')) + retained.assert_not_awaited() + + def test_public_claim_starts_work_without_retired_routes(self): + from app.modules.tasks.schemas import AssignmentResponse + from experiments.pilot04_external_checker_runtime import public_probe_support as support + + self.assertIn('accepted_at', AssignmentResponse.model_fields) + self.assertNotIn('started_at', AssignmentResponse.model_fields) + task, assignment = (str(new_record_id()) for _ in range(2)) + for accepted in ('2026-01-01T00:00:00Z', None): + replies = [{'id': task}, {}, {}, {'task': {'status': 'in_progress'}, + 'assignment': {'id': assignment, 'accepted_at': accepted}}, {}] + with self.subTest(accepted=accepted), patch.object(support, '_json', new=AsyncMock(side_effect=replies)) as requests: + call = support._started_public_task(None, project_id='project', manager_token='manager', + contributor_token='contributor', source_ref='claim-contract') + if accepted is None: + with self.assertRaisesRegex(RuntimeError, 'immediately start'): + asyncio.run(call) + else: + self.assertEqual(asyncio.run(call), (task, assignment)) + self.assertTrue(requests.await_args.args[2].endswith('/work-context')) + paths = [item.args[2] for item in requests.await_args_list] + self.assertFalse(any(path.endswith('/start') or path.endswith('/submission-requirements') for path in paths)) + + def test_finalization_worker_is_exclusive_and_uses_production_app(self): + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + with patch.object(probe, '_process', return_value='owned') as launch: + process, _ = probe._start_finalization_worker({}, Path('/private/proof')) + self.assertEqual(process, 'owned') + command = launch.call_args.args[0] + self.assertEqual(command[command.index('-A') + 1], 'app.workers.celery_app') + self.assertEqual([x for x in command if x.startswith('--queues=')], + ['--queues=workstream.submission_finalization']) + + def test_source_profile_cannot_exceed_the_supplied_runner_window(self): + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + runtime = _source_reservation().runtime_profile + profile = {'capacity': {'maximum_total_bytes': 4 * 1024**2}, + 'runtime': runtime.model_dump(mode='json'), 'upload_total_seconds': 300.0, + 'upload_idle_seconds': 10.0, 'foreground_lease_seconds': 10.0, + 'heartbeat_seconds': 1.0, 'replay_total_seconds': 30.0, 'part_bytes': 5 * 1024**2} + window = runtime.aggregate_deadline_ms / 1000 + settings = SimpleNamespace(submission_execution_profile=profile, external_checker_service_timeout_seconds=window) + self.assertEqual(probe._require_source_runtime_window(settings).runtime, runtime) + settings.external_checker_service_timeout_seconds = window - 0.1 + with self.assertRaisesRegex(RuntimeError, 'exceeds the configured runner request timeout'): + probe._require_source_runtime_window(settings) + + def test_parser_requires_an_existing_socket_without_starting_a_service(self): + import socket + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'guide.sock' + settings = SimpleNamespace(guide_document_parser_socket=path) + with self.assertRaisesRegex(RuntimeError, 'existing guide parser socket'): + probe._require_parser_socket(settings) + with socket.socket(socket.AF_UNIX) as bound: + bound.bind(str(path)) + self.assertEqual(probe._require_parser_socket(settings), path) + alias = Path(directory) / 'alias.sock' + alias.symlink_to(path) + with self.assertRaisesRegex(RuntimeError, 'existing guide parser socket'): + probe._require_parser_socket(SimpleNamespace(guide_document_parser_socket=alias)) + + if __name__ == '__main__': unittest.main() From 5c29fcf62538c7f8acd9372399bb5ac86a84e240 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 15:45:02 +0100 Subject: [PATCH 288/513] docs: reconcile submission delivery scope and remaining qualification --- .commitrail/INDEX.md | 2 +- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 40 +++--- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 25 ++++ docs/roadmap_status.md | 121 ++++++++++-------- 4 files changed, 116 insertions(+), 72 deletions(-) diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index d36498ac9..8f119a5a6 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP intake, PRE/T4/T5, unsealed cleanup and both POST review-policy branches have focused proof; admission-only TASK writer is removed. Next: separate-runner integration and live provider qualification, remaining preparation-writer retirement and orphan reconciliation, then full acceptance/configuration closure. See the overview for checked implementation versus remaining evidence. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP API/CLI/MCP, PRE/T4/T5, indexed cleanup and POST policy routing are implemented; superseded writers are retired and real Redis/Celery child recovery is proved. Next: complete native public automatic acceptance, remaining runtime/resource and AWS qualification, hosted activation and full acceptance/configuration closure. Live human review remains deferred. See the overview for checked implementation versus remaining evidence. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 526a7716d..4acd1cc4c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -25,7 +25,7 @@ limits are in [the change record](WS-SUBMIT-001-01.md). - [x] Unsealed cleanup and discovered multipart handles use durable cleanup ownership; ambiguous empty discovery retains its charge. - [x] Admission-only TASK writer removed; accepted-source finalization remains the sole Submission writer. - [x] Source-backed POST reaches both default human review and automatic acceptance with exact contribution/award lineage and replay checks. -- [x] Actual finalizer process death before source observation and after commit has separate recovery receipts; real broker qualification remains open. +- [x] Real Redis publication recovery and Celery child SIGKILL/redelivery before observation and after commit preserve one finalized graph (08fd205d0); parent-process/Beat and deployed qualification remain separate. Recent focused evidence includes atomic invalidation (`8a854f7a6`), public ZIP/T5 lineage (`168e5268f`), and policy-error translation (`d31a45773`). These and the cleanup/recovery runs recorded below are bounded results, not @@ -34,10 +34,11 @@ full-head qualification. ## Execution deployment decision The API/application server and microVM execution run on separate infrastructure. -The user reports a new t3.large EC2 application instance; this is deployment -context, not independently verified provisioning evidence. Do not require nested +The application instance is a verified t3.large; the dedicated always-on runner +is an m7i.large with native KVM. App-origin mTLS health and native transport +smoke receipts establish connectivity, not the complete deployed submission journey. Do not require nested virtualization, a Smol binary, host sockets or local KVM on the API instance. -Self-hosted microVM execution will use dedicated runner infrastructure. A paid +Self-hosted microVM execution uses dedicated runner infrastructure. A paid sandbox may implement the same qualified execution capability later. One PRE session means one isolated execution session per PRE operation, not one @@ -84,15 +85,17 @@ journey. The remaining cleanup and verification requirements below still apply. | Order | Required outcome | Concrete finishing evidence | | --- | --- | --- | -| 1 | Finish remaining uncertain/orphan reconciliation | Reconcile interrupted multipart and lost acknowledgements; retained/stalled sources survive; actual absence and settled writes release charges once; exercise worker loss/restart. | -| 2 | Retire remaining superseded preparation writers and consumers | Trace all remaining callers, preserve their distinct authority/history contracts, then delete obsolete implementation. Current T5 `create_accepted` remains. | -| 3 | Complete separate-runner integration and runtime/provider/resource qualification | Authenticated remote execution replacing the current API-side Unix-socket coupling; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | +| 1 | Qualify the connected public journey | Real PRE, durable T5, POST and automatic acceptance under locked false ReviewPolicy; exact ZIP, source generation, ContributionRecord and applicable awards; failures and replay. Preserve default review_pending guards. | +| 2 | Finish affected qualification callers | Preparation API/materialization and the admission-only TASK writer are removed. Current qualification scripts use raw ZIP acceptance and dedicated finalization; remaining runtime fault vectors must use that same flow and preserve their evidence. | +| 3 | Complete separate-runner integration and runtime/provider/resource qualification | Activate the prepared authenticated remote configuration on the app deployment; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. | | 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. | -The next integration boundary is the separate runner and live source provider, -in parallel with the remaining writer audit. Ordinary unsealed cleanup is -implemented; genuine-orphan reconciliation remains open. AWS policy and adapter +The next integration boundary is the complete public journey and live AWS source +qualification. Ordinary indexed unsealed cleanup is implemented. Spec §17.4 makes +inventory for genuinely absent operation records optional; it is not a new +scanner prerequisite. Uncertain writes of known operations remain owned and +conservatively charged until proved settled. AWS policy and adapter drill preparation are reviewed, but IAM administration access is pending and no live source qualification has run. Do not repeat completed local proofs as a substitute for connecting and testing the deployed journey. @@ -106,10 +109,10 @@ lost-abort/replay case proves conservative charge retention then one release. Remote initiation without a recorded handle now retains discovered IDs before abort and binds them to a fresh cleanup authorization. Focused PostgreSQL/MinIO checks cover growing observations and lost-abort replay. Empty ambiguous -discovery remains charged; genuine-orphan reconciliation and deployed operational -drills remain open. Actual local finalizer SIGKILL recovery has separate passing -before-observation and after-commit receipts, not a real broker crash proof. -This partial implementation does not complete order 1. +discovery remains charged; deployed cleanup qualification remains open. Real +Redis outage recovery and Celery child redelivery are proved with unchanged +production leases/backoff; these do not qualify broker-server loss or hosted +operation. ## Acceptance evidence still to close @@ -120,19 +123,20 @@ This is the final qualification queue, not a claim that all listed code is absen | --- | --- | --- | | A01–A03 | Public ZIP flow, default/project PRE and formal finalization tests | Complete API/CLI journey with required real runtime and POST evidence. | | A04–A08 | Metadata/body replay, competing custody, interruption and T4 uncertainty tests | Reconcile exact cases and execute integrated final-head failure/retry matrix. | -| A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Celery/broker-unavailable drill and final-head reconciliation. | +| A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Redis publication outage and Celery child-redelivery proofs passed; reconcile the remaining exact cases at the final head. | | A14–A18 | Cleanup lock/retention/charge owners and Local/MinIO provider tests | Production sweeps, accepted-source survival, AWS versions and uncertain multipart ownership. | | A19–A23 | Streaming/framing, safe archives, semantic identity and bounded findings code/tests | Measured permitted maxima/slow-provider memory bounds and complete safety matrix. | | A24–A30 | Source/result/fence contracts and runtime/capacity/substitution tests | Actual native isolation/failure/cleanup, multiple replicas/nodes, saturation and adapter qualification. | -| A31–A32 | Source-backed POST reaches review_pending or shared automatic FinalAcceptance with exact contribution/awards and replay checks | Complete public-API/native journey and final combined downstream tests, including human acceptance. | -| A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | Finish old-writer retirement and full current-head migration/client convergence proof. | +| A31–A32 | Source-backed POST reaches review_pending or shared automatic FinalAcceptance with exact contribution/awards and replay checks | Complete public-API/native automatic acceptance and final downstream tests. Keep default review_pending guards; live human review remains explicitly deferred by the user. | +| A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | Affected old writers are retired; finish current-head migration/client convergence and remaining qualification callers. | ## Configuration and external evidence C01–C07 remain open until individually reconciled with the specification and actual deployment evidence. Test-only leases/profiles are not approved defaults. Native Smol qualification must run on the dedicated execution infrastructure, -not the API host. The current local environment does not supply that evidence. AWS source +not the API host. Native transport smoke is recorded; complete public/runtime +qualification must be linked to its actual results. AWS source qualification remains separate from MinIO and ordinary SHA-object operation. Current main's dedicated credentials replace expiring provider activation; submission work must not reinstate the retired activation subsystem. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3df0e4f49..e54a97765 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9374,3 +9374,28 @@ update; it now points at current public raw-ZIP flow and labels old drill receipts as history, retaining the mandatory local-vector gap. Structure and Ruff/diff pass; final record/link checks follow this append. No remote action, deployment or paid request occurred. + +### Reconcile current delivery scope and capability claims + +Allowed scope: affected submission statements in roadmap_status.md, this +initiative overview/index and local one-sheet XLSX/CSV exports. The ledger still +describes the removed two-step writer, empty phase selections and unimplemented +T4/T5; replace those with current owners and distinguish implementation from +unqualified deployment. Preserve default review_pending and user-deferred live +human review, historical receipts, mandatory known-operation cleanup and all +remaining runtime/provider/resource evidence. Do not mark the initiative complete +or imply AWS/native public acceptance from component tests. Verification: compare +claims to current routes/guards and named receipts, Markdown/stale-wording checks, +and exactly one WorkStream RoadMap export sheet with current definition. + +Reconciled executive submission summary, lifecycle scoreboard, dependency map, +release gates and current initiative/index boundary against the current raw-ZIP +route, exactly-one phase guards, indexed cleanup and recorded broker/native +transport proofs. Older named hosted receipts remain historical. The initiative +stays Planned; no complete native public or AWS qualification is claimed. +Local ignored sheets/workstream_roadmap.xlsx and CSV export the25 lifecycle +scoreboard rows plus current README definition. Verified identical cell data, +exactly one sheet named WorkStream RoadMap and gitignore exclusion. Markdown +links, stale authorization/review scans and diff checks pass. Full Go CLI +suite also passed on4652f39bd (/tmp/submission-cli-go-current.log); later changes +touch qualification scripts/docs only. Latest main fetch found0missing commits. diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 3a7c8cc09..a694a3c53 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -97,7 +97,7 @@ and truthful loaded-page/evidence states, without new API or product operations. [WS-CLI-001-51](../.commitrail/initiatives/WS-CLI-001/WS-CLI-001-51.md) adds direct collection navigation and confirmed Claim through the existing public API, with caller-owned saved keys and explicit replay. Contribution -Evidence remains an explicit CLI handoff; ZIP preparation/Submission, other +Evidence remains an explicit CLI handoff; ZIP submission, other TUI mutations and management remain separate. Neither this interface nor release automation establishes hosted operation or a published binary. @@ -107,20 +107,25 @@ CLI and MCP cannot edit email. Optional issuer name seeds first admission; subse display-name edits, including clearing it, remain local. Identity and authority remain bound to issuer/subject, not email; signed email is not proof of mailbox verification. -The [single-request submission specification](spec_submission_execution.md) is -the approved target for [WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). -Its hidden owner boundaries define immutable command/source values and durable -foreground intake custody with a matching TASK pointer, source/lease fences and -per-operation physical source reservations under explicit limits. Hidden bounded -receipt and S3-compatible source capabilities cover conditional completion and -exact-version reads. Local source methods preserve one ZIP inode through sealing -and completed bytes on late abort. Private upload composition commits intent -before provider begin, handle before parts, and EOF before provider completion, -then binds the resulting source under the current fence. -Full foreground authorization/heartbeat integration, cleanup orchestration, AWS -source qualification, one-session PRE, accepted handoff, -finalization and client cutover remain planned; -the active API still uses preparation followed by admission-consuming submission. +The [single-request submission specification](spec_submission_execution.md) governs +[WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). The current +implementation exposes one raw-ZIP mutation through API, CLI and MCP, with durable +intake/source custody, bounded streaming, one-session PRE, atomic T4 acceptance +and dedicated durable T5 finalization into the existing Submission/POST owners. +Exact source generations stay protected while accepted work awaits finalization. +Indexed cleanup reconciles known operation writes and releases charges only after +confirmed settlement; genuinely absent-operation inventory is optional. + +Superseded preparation writers are removed; authorized historical reads remain. +New policies require exactly one project image per phase, separate from the +Workstream PRE default. Locked `human_review_required=false` lets passing required +POST invoke shared automatic acceptance and contribution/award creation. Default +true retains `review_pending` and its guards; live human review remains deferred. +Scoped PostgreSQL/MinIO, client and real Redis/Celery child-recovery proofs exist. +The separate runner has native transport and app-origin mTLS connectivity evidence; +complete public native acceptance, maximum/resource and failure qualification, +AWS source permissions/version cleanup, hosted activation and final A01–A35/C01–C07 +closure remain deployment/release gates. Implementation is not hosted qualification. ## Product Goal @@ -129,7 +134,7 @@ Workstream turns governed work into trusted `ContributionRecord` facts: ```text Project Guide -> governed Task --> artifact preparation and pre-submission intake checks +-> raw ZIP upload and pre-submission intake checks -> immutable Submission -> post-submission evaluation against locked requirements -> policy-governed acceptance: authorized human Review or automated decision @@ -271,10 +276,10 @@ shared Harnessy retains its minimum of one. Locked false ReviewPolicy passing POST reached shared acceptance, one submitter ContributionRecord and one earned 100 FLOW award with null Review references. [Exact hosted evidence](reports/garden-hosted-drill-2026-11-06.md). Managers discover exact activation selections through the authorized draft post-policy read; Finance publication remains separate. Task policy -lineage, public ZIP preparation and admission-backed immutable Submission creation -are implemented for initial work and exact checker remediation. Their complete -public API and Celery service journey passed its bounded local drill under -public guide inputs and recorded inference. TASK +lineage and raw-ZIP accepted-source finalization are implemented for initial work +and exact checker remediation. Earlier preparation/admission journey receipts +remain historical evidence; they do not qualify the replacement native public +submission flow. TASK now reserves and replays exact post-submit routing requests internally. Hidden AUTH binds those requests to exact source and branch consequences through canonical PREP. The hidden authorized outcome operation commits source custody @@ -310,9 +315,9 @@ Operator reconciliation classifies uncertain post-submit request/completion deliveries and appends at most one child to verify committed effects or invoke the existing owner after proving no effect. Unresolved sources and an UNKNOWN child remain held. Full hosted interruption proof remains outstanding. PILOT-04 registers -selected request and completion handlers in production composition. ARCH-02I-B -publishes ZIP preparation and the canonical admission-backed Submission POST in -OpenAPI. Current completion classification has no `task_setup_blocked` path, so +selected request and completion handlers in production composition. WS-SUBMIT-001 +publishes the raw-ZIP Submission POST and exact submission-operation progress in +OpenAPI; the superseded preparation mutation is absent. Current completion classification has no `task_setup_blocked` path, so a manager-visible setup-fault hold is future safety work rather than a first-journey prerequisite. @@ -473,8 +478,8 @@ separate. CLI contribution-evidence commands now provide self and authorized project reads, including exact server CSV downloads. Backend fixed-membership pagination and the CLI's bounded internal traversal preserve complete selections through 100,000 contributions without exposing cursor controls. -Explicit CLI ZIP preparation, admission-backed creation/replay, submission history -and contributor checker findings now consume the public APIs. PILOT-READ-1 adds +CLI raw-ZIP submission, accepted receipt replay, exact operation progress, +submission history and contributor checker findings consume the public APIs. PILOT-READ-1 adds typed attempt status, `decided_at` and finding counts to history, and per-finding `check_id`/`path`/`line` to checker results. The CLI also exposes the seven existing manager task requirements/context, @@ -500,9 +505,9 @@ task import batches and ZIP preparations with finding counts; plus the Finance list of every ContributionPolicy version. The CLI `project guide list|show|readiness|document`, `project submissions|assignments|summary|import-batches`, `project preparations` and `project contribution-policy list` commands consume -them. Preparation does -not create a Submission; readiness recovery is an explicit same-key POST replay, -not a polling GET. PILOT-08 exposes frozen revision-change summaries through +them. Historical preparation reads remain available. The current raw-ZIP command +returns accepted custody before durable finalization creates the Submission; +selector-bound GETs observe progress and exact same-key POST resolves replay. PILOT-08 exposes frozen revision-change summaries through contributor task context and requires the exact preparation acknowledgement for checker-remediation intake. CLI submission/history text distinguishes the absence of that summary in historical responses from the separate current task-context @@ -628,8 +633,9 @@ Both stages enforce quality, but answer different questions and produce different outcomes. They are not one combined checker phase. The phase is distinct from the execution method. Static inspection and other -checks that can reliably finish within 60 seconds belong before Submission -creation, even when they use durable execution and polling. Longer work, +checks intended to meet the approximately 60-second experience target belong +before Submission creation. PRE runs in the foreground with an explicitly +qualified finite aggregate envelope; 60 seconds is not an inferred hard cutoff. Longer work, repeated trials and model evaluation belong in background POST. Automation alone does not make a check POST. Recording a model evaluator's inputs and result does not promise identical judgments on rerun; it still needs an explicit @@ -637,7 +643,7 @@ implementation, runtime dependency and policy binding. | Stage | Purpose and examples | Policy and execution boundary | Outcome | | --- | --- | --- | --- | -| Pre-submission intake checks | Is this bounded package check acceptable before creating a Submission? Check static structure, required/forbidden files, evidence integrity and other work that reliably completes within 60 seconds. | The locked selected PRE policy runs the single Workstream default followed by every required digest-pinned project image on ART-verified material. PRE may use durable execution and polling, but a proposed check and selected registry deadline must remain within the 60-second boundary. | Blocking failures return correction feedback and prevent Submission creation. Passing intake does not prove the task is accepted or ready for review. | +| Pre-submission intake checks | Is this bounded package check acceptable before creating a Submission? Check static structure, required/forbidden files and evidence integrity within the qualified PRE envelope. | One PRE session runs the Workstream default followed, on success, by the single approved project image against the exact sealed source. The foreground operation has explicit admission and aggregate deadlines; POST and T5 use durable consumers. | Blocking failures return correction feedback and prevent Submission creation. Passing intake does not prove the task is accepted or ready for review. | | Post-submission evaluation | Does the submitted work meet checks that need longer execution, repeated trials or model evaluation? Evaluate the exact immutable work and evidence under the locked requirements. | The Submission-stamped external POST policy drives approved digest-pinned images through the Rust service and durable `CheckerRun` ownership after immutable Submission creation. Only supported, registered checks execute. 04F1 verifies current completed failure evidence through the same CHECKERS port. The locked project revision policy requires an explicit integer cap `N >= 0` and positive deadline hours. | Persist current evidence. The hidden authorized operation publishes exact source custody. `allow_review` branches on locked ReviewPolicy: true moves TASK to `review_pending`; false invokes shared acceptance under TASK authority. Exact current `needs_revision` with another revision remaining moves TASK to contributor remediation under either mode, with a running or setup-paused PostgreSQL window and no REV/CON effects. Failure on the final permitted attempt immediately records rejection and exhaustion, closes the assignment as `revision_exhausted`, and returns TASK to `ready` without another preparation or window. CHECKERS never writes TASK state or acceptance itself. B8 supplies completion custody; PILOT-04 registers selected request/completion production delivery. | PR #697's intended initial setup reads only assigned guide documents and task @@ -646,12 +652,12 @@ and POST check specifications, never registry matches, image choices or runtime availability. PM and engineering review the suggestions; engineering implements and registers external images. An authorized Project Manager makes explicit PRE and POST image attachment choices during policy approval. The phase lists are -independent of suggestion IDs and may intentionally be empty; the Workstream +independent of suggestion IDs and each require exactly one approved project image; the Workstream PRE default stays separate. Approval locks exact image digest and configuration. Registration after proposal does not change its hash or require another setup run. Missing implementation does not block a source-sufficient proposal. Both -phase lists must be present; explicit empty lists are valid, and suggestions impose -no image-membership requirement. Retained +phase lists must be present and contain exactly one selection; missing, empty or +multiple selections are rejected. Suggestions impose no image-membership requirement. Retained result bytes and hashes remain immutable evidence, not an alternate compiler or executor. Setup inference is not a runtime judge. The inference adapter drafts a candidate, then reviews source coverage in a fresh @@ -683,8 +689,8 @@ cannot be reused as post-submission review-gate evidence. See the | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS | | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate | | Contributor artifact preparation | **Public initial and checker-remediation entry** | One outer ZIP up to 500 MiB through the published preparation route (MCP transport: 64 MiB); scratch reservations grow before writes from counted bytes plus bounded headroom; unreadable or structurally rejected ZIPs return sanitized non-retryable 422 feedback before PRE reservation or durable effects; bounded scratch inspection; canonical manifest; shared evaluation-content capacity and exact locked-policy checks before attempts or durable intent; platform and project prechecks; unchanged-work rejection; durable put intent; verification; capacity-charged ready admission; final handoff validates the exact activated historical guide through owner ports; same-key ready replay does not repeat checker or PUT. The preparing contributor reads back their own preparations with outcome, storage state, finding counts and intake findings (PILOT-READ-2); a Project Manager lists a project's preparations with finding counts only (PILOT-READ-3). CLI preparation, read-back, creation/replay and history consume these public owners | Bounded local API/CLI journeys and hosted PRE rejection, lost-response recovery, ready admission and exact replay passed. Hosted CLI/MCP preparation, creation and replay passed in the [fresh resource-qualified journey](reports/managed-mcp-hosted-2026-11-07.md#sealed-size-resource-qualification-and-fresh-hosted-journey). Complete remaining intake negatives, isolation and interruption scenarios | -| Pre-submission intake checking | **Public selected entry with approved-guide lineage and bounded feedback** | One versioned Workstream default checker enforces safe ZIP/resource bounds, independently verified digest/manifest, high-confidence secret rejection and unchanged-work rejection. Missing summary/attestation produces warnings only. Successful preparation and its exact replay return the same bounded intake results as a blocked one (PILOT-READ-1), so nonblocking findings such as coverage gaps stay visible; CLI preparation prints them. Approved project PRE checks are immutable digest-pinned images run by the Rust service on verified read-only ART material. A supported system Operator API and explicit CLI commands register and read exact immutable external-checker entries with server-selected UUIDv7 identity, fresh authority and replay recovery. Durable selected custody takes TASK before CHECKERS; only a complete pass grants admission to the existing atomic Submission transaction. Both executable catalogues are removed. CLI preparation prints bounded contributor failure details. The same typed adapter also accepts the Smol node's fresh microVM execution receipts, with bounded concurrency and exact-lease recovery; ART uses a separate typed trusted intake capability, prepares after authorized upload/download has been sealed and counted, verifies raw guest exports and closes intake before project execution. API and Celery workers require a configured pinned Smol intake image/socket. Hosted API/Celery composition uses one native Smol endpoint for typed intake and project execution, with read-only client socket mounts and no Compose checker controller. The isolated public Smol drill proved the preceding upload-overlap implementation, zero/two PRE bindings, cancellation, bounded runtime retry/recovery and public Operator POST retry through both governed policy branches | Bounded self-hosted Smol/Celery proof and hosted selected PRE rejection/pass with AWS-verified admission passed. Complete the remaining ZIP, interruption and representative-limit matrix; production Flow certification remains separate. Registry publication alone does not activate an image or change a saved proposal. Work findings create no Submission and preserve in_progress; infrastructure failures retain recoverable outcomes. PR #697 requires explicit authorized phase attachments at approval; public REV lifecycle controls are a separate boundary. Seal-first sizing uses a required image/runtime-bound storage envelope. Pinned cold/maximum-input qualification and a separate fresh hosted CLI/MCP PRE-to-contribution journey passed; [resource evidence and limits](reports/managed-mcp-hosted-2026-11-07.md#sealed-size-resource-qualification-and-fresh-hosted-journey) distinguish VM floors, measured latency and canonical-owner fixtures from public maximum-size uploads. | -| Immutable Submission creation | **Public admission-backed entry with explicit CLI consumption** | Canonical POST derives contributor identity and consumes a ready admission for initial work or exact checker remediation; durable pre-submit reservation and same-key ready recovery without rerunning checks or PUT; TASK-owned atomic creation with exact assignment ContributionPolicyVersion, locked policy lineage and service/database checked-packet custody; fixed-service artifact binding; exact replay, authority, concurrency and rollback proof. CLI creation/replay and bounded history use these public owners | Bounded local API/CLI unpaid automated-acceptance journeys and hosted immutable Submission creation/exact replay passed. The small hosted POST-to-contribution journey and accepted-state submission replay passed; Garden v3 additionally passed real current-head POST and exact accepted-state replay with one 100 FLOW award. Broader interruption proof remains. Live human-review revision remains separate | +| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | Complete native public acceptance and remaining failure, isolation, capacity and maximum-input qualification. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. App-origin mTLS and native transport smoke are proved; hosted activation and AWS source qualification remain open. | +| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Complete the connected native public journey, AWS exact-version qualification, hosted cutover and final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. | | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. The bounded local public API/Celery drill passed both branches, prefork Celery process restart and late authority revocation | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate | | Operator uncertain-delivery CLI | **Existing public delivery routes consumed by explicit CLI commands** | WS-CLI-001-40 adds one project-bound page of finalized UNKNOWN deliveries and a deliberate reasoned, UUID-keyed reconciliation of one exact event. Fresh backend authority and classification remain decisive; a page never authorizes a later write. | Native signed PostgreSQL proof is scoped to an owner-produced source; a hosted interruption and deployed CLI remain unproven | | Review queue and lease | **Hidden persistence foundation** | Queue/admission idempotency and ReviewLease/preference persistence; complete unavailable REV action/principal catalogue and typed AUTH contracts; ART-07A1 metadata-only packet contract and REV-03B immutable normalized packet persistence with live ingest custody; REV-04A Review/finding/resolution and completed request storage | Future resolver proof; canonical admission from `allow_review`; claim/lease/packet authority; lease copies the Submission-stamped policy version with no CON lookup | @@ -1357,7 +1363,8 @@ hidden exact-cause replacement intake and 04F4 supplies the retry owner; the supported public Operator discovery/retry path now invokes it. PILOT-04 registers selected request and completion delivery in production composition; passing false-policy results use the shared atomic acceptance operation. ARCH-02I-B -publishes admission-backed initial and checker-remediation Submission entry. +supplied the earlier admission-backed entry; WS-SUBMIT-001 now exposes raw-ZIP +accepted custody and durable finalization for initial work and checker remediation. Live setup does not wait for downstream task/checker execution. The [first complete contributor milestone](../.commitrail/initiatives/WS-ARCH-001/planning/PLAN.md#first-complete-contributor-milestone) @@ -1549,10 +1556,11 @@ Delivered foundations (bounded local journey proven; no deployment claim) privacy-bounded API/Celery diagnostics (current export disabled; collector optional) digest-only API/Celery/Beat/checker release configuration (hosted proof still required) WS-EXEC-001-01 Smol node + existing typed execution adapter + exact-lease recovery - WS-EXEC-001-02 authorized upload/download overlap + trusted guest ZIP/default intake - WS-EXEC-001-02 public Smol API/Celery proof + required hosted intake configuration + historical WS-EXEC-001-02 upload-overlap receipts remain historical + WS-SUBMIT-001 raw ZIP -> sealed source -> one PRE -> atomic T4 pending custody + -> dedicated durable T5 -> immutable Submission/binding -> POST -> locked true: review_pending; locked false: shared acceptance + contribution + applicable award - -> intended hosted deployment proof with actual Flow/AWS identities remains separate + -> separate API/runner transport verified; complete native/hosted journey remains required verified guide originals -> explicit PM assistance OR provider-free uploaded rules -> unified compilation -> separate manager pre/post approvals -> existing activation guards (human review defaults true; approved false supported) @@ -1574,7 +1582,7 @@ Delivered foundations (bounded local journey proven; no deployment claim) WS-CLI-001-51 existing public claim -> explicit TUI confirmation + caller-owned key direct Ready/Mine/Submissions navigation; unknown -> explicit unchanged replay later ZIP/Submission need per-operation recovery; Evidence needs typed single-page port - task/assignment/Submission lineage + public ZIP intake/admission-backed creation + task/assignment/Submission lineage + public raw-ZIP accepted-source finalization ARCH-03D exact approved historical guide through durable intake handoff ARCH-04B hidden verified Submission input shared setup/POST model-call ART request/response custody with exact owner authority @@ -1730,13 +1738,22 @@ and award history never changes. Client scope remains distinct from product completion: the contributor TUI presents existing reads/downloads plus deliberate claim with externally saved replay keys. It does not complete human review, payment or -hosted proof. In-TUI Contribution Evidence, ZIP preparation/Submission and +hosted proof. In-TUI Contribution Evidence, ZIP submission and automatic crash recovery remain separate interface boundaries, not new backend lifecycle prerequisites. CLI binary distribution still requires protected publication and independent public-asset/install verification. v0.1 is not ready until all of the following are true: +- Qualify the current single-request submission flow, not only its historical + preparation/admission predecessors: public native PRE/T4/T5/POST and automatic + acceptance, exact retained source/contribution facts, failure/retry behavior, + maximum/slow-upload memory, isolation and capacity. Qualify AWS source IAM and + exact-version cleanup before opening its gate; activate separate-runner hosted + API/consumers with measured/approved C01–C07 settings and reconcile A01–A35. + Default review_pending remains protected; live human review is deferred from + this submission initiative. See [WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). + - Finish PR #697 proposal/attachment separation verification and reproduce the connected guide-to-contribution journey with the intended hosted identity, inference provider and infrastructure. @@ -2070,21 +2087,19 @@ The [offline gVisor build spike](engineering/pilot00-gvisor-offline-build-spike. selects a sealed-cache Kaniko builder plus a separate gVisor oracle sandbox for PILOT-04/PILOT-06. PILOT-04 now has a normalized external request/result contract, immutable authorized digest-pinned registry, selected Rust service/SDK -with a typed Unix-socket adapter and request-bound ART grant, and one versioned +with typed execution adapters and request-bound ART grants, and one versioned Workstream default checker with exactly four blocking outcomes. Both executable -catalogues are removed. Verified ZIP/default checks precede approved external PRE -images; only a complete pass permits immutable Submission creation and durable -POST dispatch. Under PR #697, setup suggestions do not select registered images; -an authorized Project Manager supplies exact phase attachments, including -intentional empty lists, and approval locks their digest/configuration identities. -Registration alone grants no project authority. Both phase lists must be present; -explicit empty lists are valid, and suggestions impose no image-membership -requirement. Production completion routes true-policy success to review_pending +catalogues are removed. The sealed-source PRE session runs default checks before +one approved external PRE image; passing T4 accepts durable custody for T5 and +POST. Setup suggestions do not select registered images. An authorized Project +Manager supplies exactly one attachment per phase, and approval locks its digest +and configuration. Registration alone grants no project authority; suggestions +impose no image-membership requirement. Production completion routes true-policy success to review_pending and false-policy success through shared atomic acceptance. Default failures prevent Submission creation; infrastructure failures retain recoverable outcomes. Local Rust/MinIO integration evidence uses runc/docker-dev, not gVisor. ARCH-02I-B -delivers public Submission entry; CLI25 consumes it through explicit preparation, -creation/replay and history/findings commands. The spike proves only the included small Linux fixture; +supplied the earlier public entry; WS-SUBMIT-001 replaces that writer with raw-ZIP +acceptance, progress and replay across API/CLI/MCP while preserving history/findings. The spike proves only the included small Linux fixture; representative task sizing, hosted hardening and macOS fallback evidence remain. From e020577874e64323b1fe0f3658fa35fbc653cdc6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:17:24 +0100 Subject: [PATCH 289/513] Recover unknown guide dispatch in public journey --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 13 ++ .../test_journey_guide_recovery.py | 127 ++++++++++++++++++ cli/tests/journey/client.py | 6 +- cli/tests/journey/public_setup.py | 59 +++++++- 4 files changed, 201 insertions(+), 4 deletions(-) create mode 100644 cli/tests/integration/test_journey_guide_recovery.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e54a97765..c509f9b3a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9286,6 +9286,7 @@ fresh migrated isolated database; the deliberately absent operation yielded the expected missing-graph assertion, and that database was cleaned. A successful live graph is still pending the next end-to-end run. + ### Retire qualification-script preparation callers Release image guards exposed an import of removed preparation composition from @@ -9399,3 +9400,15 @@ exactly one sheet named WorkStream RoadMap and gitignore exclusion. Markdown links, stale authorization/review scans and diff checks pass. Full Go CLI suite also passed on4652f39bd (/tmp/submission-cli-go-current.log); later changes touch qualification scripts/docs only. Latest main fetch found0missing commits. + +The next isolated public drill exposed a guide dispatch transport uncertainty: +the CLI's ordinary 12-second HTTP deadline returned `service_unavailable` with +`outcome_unknown=true` after the request entered the API. The journey now +reads the public setup before dispatch, observes the same setup after such an +unknown response, and replays only the identical compile command and +idempotency key within three bounded attempts. It refuses changed setup +identity, generation or source, failed setup, conclusive errors, and a receipt +that names another setup. Eight focused regressions cover the recovered and +refused cases. This is a journey caller repair; it does not extend the CLI +deadline or claim a completed PRE/POST run. The diagnostic run's isolated +database and bucket cleanup completed. diff --git a/cli/tests/integration/test_journey_guide_recovery.py b/cli/tests/integration/test_journey_guide_recovery.py new file mode 100644 index 000000000..03028577c --- /dev/null +++ b/cli/tests/integration/test_journey_guide_recovery.py @@ -0,0 +1,127 @@ +"""The CLI journey keeps one exact guide request after an unknown transport result.""" + +import importlib.util +from pathlib import Path + +import pytest + + +PATH = Path(__file__).resolve().parents[1] / "journey/public_setup.py" +SPEC = importlib.util.spec_from_file_location("journey_public_setup_recovery", PATH) +assert SPEC is not None and SPEC.loader is not None +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + +SETUP = { + "id": "setup-1", + "project_id": "project-1", + "guide_id": "guide-1", + "source_snapshot_id": "source-1", + "setup_generation": 1, + "status": "queued", +} +COMMAND = ( + "project", + "guide", + "compile-requirements", + "project-1", + "guide-1", + "--idempotency-key", + "one-fixed-key", +) +SELECTOR = ("project", "guide", "setup", "project-1", "guide-1") + + +class FakeClient: + def __init__(self, dispatch, observed=None): + self.dispatch = list(dispatch) + self.observed = observed or SETUP + self.calls = [] + + def call(self, _token, *arguments, expected_exit=0): + self.calls.append((arguments, expected_exit)) + if arguments == SELECTOR: + return dict(SETUP if len(self.calls) == 1 else self.observed) + assert arguments == COMMAND + return self.dispatch.pop(0) + + +def test_lost_guide_ack_observes_then_replays_identical_key(monkeypatch): + monkeypatch.setattr(MODULE.time, "sleep", lambda _: None) + receipt = { + "operation_id": "operation-1", + "setup_run_id": "setup-1", + "setup_generation": 1, + "status": "queued", + } + client = FakeClient( + [ + {"error": {"code": "service_unavailable", "outcome_unknown": True}}, + receipt, + ] + ) + assert ( + MODULE._request_compilation_with_unknown_recovery( + client, "token", COMMAND, SELECTOR + ) + == receipt + ) + assert client.calls == [ + (SELECTOR, 0), + (COMMAND, None), + (SELECTOR, 0), + (COMMAND, None), + ] + + +@pytest.mark.parametrize( + "changed", + [ + {"id": "other-setup"}, + {"source_snapshot_id": "other-source"}, + {"setup_generation": 2}, + {"status": "compilation_invalid_terminal"}, + ], +) +def test_lost_guide_ack_refuses_changed_or_failed_setup(monkeypatch, changed): + monkeypatch.setattr(MODULE.time, "sleep", lambda _: None) + client = FakeClient( + [{"error": {"code": "service_unavailable", "outcome_unknown": True}}], + observed=SETUP | changed, + ) + with pytest.raises(AssertionError): + MODULE._request_compilation_with_unknown_recovery( + client, "token", COMMAND, SELECTOR + ) + assert client.calls == [(SELECTOR, 0), (COMMAND, None), (SELECTOR, 0)] + + +def test_conclusive_guide_dispatch_error_never_retries(): + client = FakeClient([{"error": {"code": "not_allowed"}}]) + with pytest.raises(AssertionError, match="conclusively"): + MODULE._request_compilation_with_unknown_recovery( + client, "token", COMMAND, SELECTOR + ) + assert client.calls == [(SELECTOR, 0), (COMMAND, None)] + + +@pytest.mark.parametrize( + "substitution", + [ + {"setup_run_id": "foreign-setup"}, + {"setup_generation": 2}, + ], +) +def test_guide_dispatch_refuses_wrong_acknowledged_setup(substitution): + receipt = { + "operation_id": "operation-1", + "setup_run_id": "setup-1", + "setup_generation": 1, + "status": "queued", + } + client = FakeClient([receipt | substitution]) + with pytest.raises(AssertionError, match="acknowledgement changed setup"): + MODULE._request_compilation_with_unknown_recovery( + client, "token", COMMAND, SELECTOR + ) + assert client.calls == [(SELECTOR, 0), (COMMAND, None)] diff --git a/cli/tests/journey/client.py b/cli/tests/journey/client.py index 9c558ae7b..a8ba7d2e4 100644 --- a/cli/tests/journey/client.py +++ b/cli/tests/journey/client.py @@ -26,7 +26,7 @@ def complete_stage(self, stage: str): self.completed_stages.append(stage) print(json.dumps({"stage": stage, "result": "passed"}), flush=True) - def call(self, token: str, *arguments: str, expected_exit: int = 0): + def call(self, token: str, *arguments: str, expected_exit: int | None = 0): environment = { key: value for key, value in os.environ.items() @@ -59,7 +59,9 @@ def call(self, token: str, *arguments: str, expected_exit: int = 0): }, stream, ) - if result.returncode != expected_exit: + if result.returncode not in ( + {0, 1} if expected_exit is None else {expected_exit} + ): evidence = Path(tempfile.mkdtemp(prefix="workstream-cli-failure-")) (evidence / "stdout.json").write_text(result.stdout) (evidence / "stderr.json").write_text(result.stderr) diff --git a/cli/tests/journey/public_setup.py b/cli/tests/journey/public_setup.py index fd1313447..e2cd78195 100644 --- a/cli/tests/journey/public_setup.py +++ b/cli/tests/journey/public_setup.py @@ -274,6 +274,58 @@ def publish_unpaid_terms(client, token, project_id): return policy +def _request_compilation_with_unknown_recovery(client, token, command, setup_selector): + """Observe same-setup custody before replaying one lost dispatch response.""" + project_id, guide_id = setup_selector[-2:] + before = client.call(token, *setup_selector) + if before["project_id"] != project_id or before["guide_id"] != guide_id: + raise AssertionError("public setup identity differs before compilation") + # A short JSON client deadline may lose only the dispatch acknowledgement. + # Read the retained setup first, then replay the identical command/key. + # The original failure remains in the CLI receipt evidence. + for attempt in range(3): + candidate = client.call(token, *command, expected_exit=None) + if "error" not in candidate: + if ( + candidate["setup_run_id"] != before["id"] + or candidate["setup_generation"] != before["setup_generation"] + ): + raise AssertionError("guide dispatch acknowledgement changed setup") + requested = candidate + break + if candidate["error"] != { + "code": "service_unavailable", + "outcome_unknown": True, + }: + raise AssertionError("guide dispatch failed conclusively") + observed = client.call(token, *setup_selector) + if any( + observed[field] != before[field] + for field in ( + "id", + "project_id", + "guide_id", + "source_snapshot_id", + "setup_generation", + ) + ): + raise AssertionError("guide setup changed during unknown dispatch") + if observed["status"] in { + "failed", + "guide_blocked", + "compilation_invalid_terminal", + }: + raise AssertionError("unknown guide dispatch reached failed terminal state") + if attempt == 2: + raise AssertionError( + "guide dispatch remained outcome-unknown after observation" + ) + time.sleep(1) + else: + raise AssertionError("guide dispatch produced no acknowledged receipt") + return requested + + def approve_and_activate(client, token, project_id, guide_id, registry_entries): command = ( "project", @@ -284,7 +336,10 @@ def approve_and_activate(client, token, project_id, guide_id, registry_entries): "--idempotency-key", str(uuid4()), ) - requested = client.call(token, *command) + setup_selector = ("project", "guide", "setup", project_id, guide_id) + requested = _request_compilation_with_unknown_recovery( + client, token, command, setup_selector + ) replay = client.call(token, *command) # Dispatch status may advance while the same durable request is replayed. for field in ("operation_id", "setup_run_id", "setup_generation"): @@ -293,7 +348,7 @@ def approve_and_activate(client, token, project_id, guide_id, registry_entries): setup = poll( client, token, - ("project", "guide", "setup", project_id, guide_id), + setup_selector, lambda value: value["finalized_compilation_id"] is not None, ) if ( From 1d0469b3638c2815cbafa7fbcecdfec88f772df6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:22:27 +0100 Subject: [PATCH 290/513] test(artifacts): measure bounded public source upload --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 77 ++++ .../tests/artifacts/qualify_submission_a19.py | 397 ++++++++++++++++++ 2 files changed, 474 insertions(+) create mode 100644 backend/tests/artifacts/qualify_submission_a19.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c509f9b3a..3dcdbaf1b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9412,3 +9412,80 @@ that names another setup. Eight focused regressions cover the recovered and refused cases. This is a journey caller repair; it does not extend the CLI deadline or claim a completed PRE/POST run. The diagnostic run's isolated database and bucket cleanup completed. + +### A19 public upload resource measurement + +Intent: measure the remaining maximum-size public upload resource boundary in +one isolated local qualification, while retaining the existing contract, +deadline, and small real-MinIO tests as separate evidence. This is a test-only +probe, not a new upload path or production setting. + +Allowed files: this record and one opt-in qualification script at +`backend/tests/artifacts/qualify_submission_a19.py`. Its non-test basename keeps it outside the regular test +lane so the 500 MiB drill is never selected in ordinary CI. Prohibited changes: +production API/ART/provider +owners, deployment defaults, CLI/MCP journeys, shared service configuration, +and unscoped object deletion. Use a runner-owned temporary PostgreSQL database +and versioned MinIO namespace; launch the existing public route through the +repository's pinned Caddy configuration on loopback. Generate a valid ZIP near +the 500 MiB compressed limit incrementally without an archive-sized file or +Python buffer. The public request uses a test-only dev token mapped to the +fixture's real active identity and must traverse real T1/T2 custody and +the S3 multipart adapter; the PRE result is outside this resource probe. + +Acceptance: record raw bytes and part count, Caddy/API peak RSS and temporary +disk, and a timeline showing a held provider part prevents unbounded request +read-ahead. A slow client and a finite provider stall/failure must terminate within +the explicit measured upload envelope, with no accepted receipt, no PRE +session, and retained charged ownership until ordinary cleanup. Verify the +owned bucket/database are cleaned by the isolated runner. Risk is high for +resource use and test-harness interference; verification starts with a small +smoke, then one near-limit run, with other heavy local journeys coordinated. +Architecture/security review focus: no fixture shortcuts around the public +route or source custody, no whole-body spool, no shared namespace deletion, +and resource claims limited to measured processes/provider. +Review tracks: architecture and security inspect public-route ownership, +provider stall/custody and memory evidence; CI integrity inspects opt-in +selection and the isolated runner receipt. Human review should check that +these local measurements support A19 without implying AWS or hosted capacity. + +The first public smoke reached both provider holds. Holding the final part +until the hard upload deadline produced an outcome-unknown response because +the foreground lease also expired at that deadline; that run is diagnostic, +not a conclusive terminalization or cleanup proof. The bounded measurement +now returns a controlled provider failure after an eight-second hold, before +the hard deadline, so it can verify the committed failed state and retained +charge. Existing deadline tests remain the hard-deadline evidence. + +The finite-stall 6 MiB smoke passed through the pinned Caddy public route, +real API and isolated MinIO source. One 5 MiB part completed; holding the +final part for eight seconds then returning a provider error yielded an exact +503 `submission_infrastructure_unavailable`, a committed failed operation, +no acceptance, and the reserved 500 MiB charge. The client emitted 6,291,618 +bytes, read-ahead during the first two-second part hold was zero, API peak RSS +was 248,877,056 bytes (201,003,008 at first sample), Caddy peak RSS was +47,927,296 bytes, and API scratch peak was 143 bytes. Evidence: +`/tmp/submission-a19-smoke5.log`, `/tmp/submission-a19-smoke5.json`, and the +timeline path printed in that log. Isolated database and bucket cleanup were +confirmed. This small smoke does not establish near-limit memory behavior. + +One near-limit run then passed from the same isolated worktree at +`814f596fc75d83c0e337e6ff3e136707a2d2efe9`: a generated 496 MiB +ZIP (520,094,278 wire bytes) traversed the pinned Caddy ingress and public +API. The adapter completed 31 real 16 MiB MinIO parts; the final 582-byte +part was held for eight seconds and failed before provider I/O. The exact +response was 503 `submission_infrastructure_unavailable`; DB custody was +committed failed with no acceptance and its 500 MiB charge remained reserved. +During the two-second first-part hold, the client emitted only 7 MiB more. +Across 484 samples over 113.67 seconds, API RSS peaked at 283,742,208 bytes +(200,982,528 at the first sample); the peak before 100 MiB and after 396 MiB +was essentially flat (283,742,208 and 283,525,120 bytes). Caddy peaked at +47,251,456 bytes; API scratch peaked at 143 bytes. Caddy XDG state was +scoped to the test directory. The explicit test profile used a 300-second +upload deadline, 30-second idle deadline, 60-second foreground lease and +16 MiB parts, without changing hosted defaults. Evidence: +`/tmp/submission-a19-max.log`, `/tmp/submission-a19-max.json`, and +`/tmp/pytest-of-abiorh/pytest-6701/test_public_a19_near_limit_upl0/a19-timeline.json`. +The isolated database and versioned bucket were removed by the runner. +This is local MinIO/Caddy resource evidence for a deliberately failed upload, +not native AWS, PRE or accepted-submission qualification. diff --git a/backend/tests/artifacts/qualify_submission_a19.py b/backend/tests/artifacts/qualify_submission_a19.py new file mode 100644 index 000000000..e3dc5a8bc --- /dev/null +++ b/backend/tests/artifacts/qualify_submission_a19.py @@ -0,0 +1,397 @@ +"""Opt-in public A19 resource drill through Caddy, API, PostgreSQL and MinIO. + +Run only with the isolated database/bucket runner and a pinned Caddy binary. +The body is generated incrementally; neither the test nor the API stores it. +""" + +from __future__ import annotations + +import asyncio +import json +import os +from pathlib import Path +import queue +import socket +import subprocess +import sys +import threading +import time +import zipfile + +import httpx +import pytest +from sqlalchemy import text + +from app.core.identifiers import new_record_id +from tests.artifacts.test_submission_intake_admission import admission_intake as admission_intake +from tests.authentication.fixtures import ( + auth_database_env as auth_database_env, + clear_settings_cache as clear_settings_cache, + rsa_signing_material as rsa_signing_material, +) +from tests.authorization.admin_access.fixtures import ( + signed_access as signed_access, + admin_access as admin_access, +) +from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation +from tests.test_s3_artifact_store import minio_settings + + +MIB = 1024 * 1024 +REPOSITORY = Path(__file__).resolve().parents[3] +BACKEND = REPOSITORY / "backend" + + +def _free_port() -> int: + with socket.socket() as value: + value.bind(("127.0.0.1", 0)) + return int(value.getsockname()[1]) + + +def _rss(pid: int) -> int: + try: + for line in Path(f"/proc/{pid}/status").read_text().splitlines(): + if line.startswith("VmRSS:"): + return int(line.split()[1]) * 1024 + except FileNotFoundError: + pass + return 0 + + +def _disk_bytes(root: Path) -> int: + return sum(path.stat().st_size for path in root.rglob("*") if path.is_file()) + + +def _stop(process: subprocess.Popen, output) -> None: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + output.close() + + +async def _listen(port: int, process: subprocess.Popen, log: Path) -> None: + async with asyncio.timeout(180): + while True: + if process.poll() is not None: + raise AssertionError(f"socket owner exited: {log.read_text()[-3000:]}") + try: + reader, writer = await asyncio.open_connection("127.0.0.1", port) + except OSError: + await asyncio.sleep(0.05) + else: + writer.close() + await writer.wait_closed() + return + + +def _caddy_config(binary: Path, directory: Path, api_port: int, caddy_port: int) -> Path: + certificate, key = directory / "identity.crt", directory / "identity.key" + subprocess.run([ + "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-days", "1", "-subj", "/CN=identity.example.test", + "-addext", "subjectAltName=DNS:identity.example.test", + "-keyout", str(key), "-out", str(certificate), + ], check=True, capture_output=True, timeout=15) + environment = os.environ | { + "FLOW_IDENTITY_HOSTNAME": "identity.example.test", + "FLOW_IDENTITY_UPSTREAM_CERT": str(certificate), + "WORKSTREAM_PUBLIC_HOSTNAME": "workstream.example.test", + "WORKSTREAM_API_HOST_PORT": str(api_port), + } + adapted = subprocess.run([ + str(binary), "adapt", "--config", str(REPOSITORY / "deploy/hosted/public.Caddyfile"), + "--adapter", "caddyfile", + ], check=True, capture_output=True, text=True, env=environment, timeout=15) + configuration = json.loads(adapted.stdout) + servers = list(configuration["apps"]["http"]["servers"].values()) + server = next(item for item in servers if item["listen"] == [":443"]) + server["listen"] = [f"127.0.0.1:{caddy_port}"] + server["automatic_https"] = {"disable": True} + server.pop("tls_connection_policies", None) + configuration["apps"].pop("tls", None) + routes = [] + + def relocate(value): + if isinstance(value, dict): + if value.get("handler") == "reverse_proxy": + for upstream in value["upstreams"]: + if upstream["dial"] == f"127.0.0.1:{api_port}": + routes.append(upstream) + for item in value.values(): + relocate(item) + elif isinstance(value, list): + for item in value: + relocate(item) + + relocate(configuration) + assert len(routes) == 1 # The product API route is the only measured upstream. + target = directory / "caddy.json" + target.write_text(json.dumps(configuration)) + return target + + +class _QueueSink: + """Non-seekable ZIP output with one queued chunk, never a body-sized file.""" + + def __init__(self, chunks: queue.Queue, stopped: threading.Event): + self.chunks, self.stopped, self.position = chunks, stopped, 0 + + def write(self, data) -> int: + value = bytes(data) + while not self.stopped.is_set(): + try: + self.chunks.put(value, timeout=0.1) + self.position += len(value) + return len(value) + except queue.Full: + continue + raise OSError("A19 HTTP reader stopped") + + def tell(self) -> int: + return self.position + + def flush(self) -> None: + pass + + +async def _zip_body(content_mib: int, emitted: list[int]): + chunks: queue.Queue = queue.Queue(maxsize=1) + stopped = threading.Event() + errors = [] + block = b"A" * MIB + + def produce() -> None: + try: + with zipfile.ZipFile(_QueueSink(chunks, stopped), "w", compression=zipfile.ZIP_STORED) as archive: + sizes = (content_mib,) if content_mib < 128 else (124, 124, 124, content_mib - 372) + for number, size in enumerate(sizes): + with archive.open(f"work-{number}.bin", "w", force_zip64=True) as entry: + for _ in range(size): + entry.write(block) + except BaseException as error: + errors.append(error) + finally: + while not stopped.is_set(): + try: + chunks.put(None, timeout=0.1) + break + except queue.Full: + continue + + producer = threading.Thread(target=produce, daemon=True) + producer.start() + emitted.append(0) + try: + while True: + chunk = await asyncio.to_thread(chunks.get) + if chunk is None: + break + emitted[0] += len(chunk) + yield chunk + if content_mib == 496: + await asyncio.sleep(0.03) # Finite slow client, still below idle timeout. + assert not errors, errors + finally: + stopped.set() + await asyncio.to_thread(producer.join, 2) + assert not producer.is_alive(), "ZIP generator survived the request" + + +API_CODE = """ +import asyncio +import os +from pathlib import Path +from app.adapters.artifacts.s3_compatible import S3CompatibleArtifactStore +from app.interfaces.artifacts import ArtifactStoreUnavailableError + +original = S3CompatibleArtifactStore.upload_source_part +markers = Path(os.environ['WORKSTREAM_A19_MARKERS']) +last = int(os.environ['WORKSTREAM_A19_LAST_PART']) + +async def measured_part(self, upload, number, data): + if number == 1: + (markers / 'first').write_text(str(len(data))) + while not (markers / 'release-first').exists(): + await asyncio.sleep(0.02) + if number == last: + (markers / 'last').write_text(str(len(data))) + await asyncio.sleep(8) # Finite stalled provider; owner can terminalize before hard expiry. + raise ArtifactStoreUnavailableError('measured provider stall') + receipt = await original(self, upload, number, data) + (markers / 'completed').write_text(str(number)) + return receipt + +S3CompatibleArtifactStore.upload_source_part = measured_part +import uvicorn +uvicorn.run('app.main:app', host='127.0.0.1', port=int(os.environ['WORKSTREAM_A19_API_PORT']), + log_level='warning', lifespan='on') +""" + + +def _api_environment(fixture, prefix: str, directory: Path, part_bytes: int, markers: Path, last: int): + settings = minio_settings(private_prefix=prefix, buffer_bytes=65536) + settings = settings.model_copy(update={ + "artifact_admission_task_maximum_bytes": 1024**3, + "artifact_admission_producer_maximum_bytes": 1024**3, + "artifact_admission_project_maximum_bytes": 1024**3, + "artifact_admission_deployment_maximum_bytes": 1024**3, + }) + profile = { + "capacity": {"maximum_total_bytes": 1024**3}, + "runtime": _source_reservation().runtime_profile.model_dump(mode="json"), + "upload_total_seconds": 120.0 if last == 2 else 300.0, + "upload_idle_seconds": 30.0, + "foreground_lease_seconds": 60.0, "heartbeat_seconds": 10.0, + "replay_total_seconds": 30.0, "part_bytes": part_bytes, + } + values = { + "WORKSTREAM_ENVIRONMENT": "test", + "WORKSTREAM_AUTH_PROVIDER": "dev", + "WORKSTREAM_DATABASE_URL": os.environ["WORKSTREAM_TEST_DATABASE_URL"], + "WORKSTREAM_DEV_AUTH_TOKEN": "a19-measurement-token", + "WORKSTREAM_DEV_AUTH_SUBJECT": fixture.access.target.subject, + "WORKSTREAM_DEV_AUTH_ISSUER": fixture.access.signed.issuer, + "WORKSTREAM_API_RATE_LIMIT_KEY_SECRET": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", + "WORKSTREAM_PAGINATION_CURSOR_HMAC_SECRET": "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=", + "WORKSTREAM_SUBMISSION_EXECUTION_PROFILE": json.dumps(profile), + "WORKSTREAM_ARTIFACT_SCRATCH_ROOT": str(directory / "scratch"), + "WORKSTREAM_A19_MARKERS": str(markers), + "WORKSTREAM_A19_LAST_PART": str(last), + } + for key in ( + "artifact_store_backend", "artifact_s3_provider_profile", "artifact_s3_region", + "artifact_s3_endpoint_url", "artifact_s3_bucket", "artifact_s3_private_prefix", + "artifact_s3_addressing_style", "artifact_s3_credential_mode", + "artifact_s3_operation_total_timeout_seconds", "artifact_s3_write_timeout_seconds", + "artifact_stream_buffer_bytes", "artifact_admission_task_maximum_bytes", + "artifact_admission_producer_maximum_bytes", "artifact_admission_project_maximum_bytes", + "artifact_admission_deployment_maximum_bytes", + ): + values["WORKSTREAM_" + key.upper()] = str(getattr(settings, key)) + values["WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID"] = settings.artifact_s3_access_key_id.get_secret_value() + values["WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY"] = settings.artifact_s3_secret_access_key.get_secret_value() + return os.environ | values, profile + + +async def _wait_file(path: Path, *, timeout: float) -> None: + async with asyncio.timeout(timeout): + while not path.exists(): + await asyncio.sleep(0.05) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("admission_intake", ["minio"], indirect=True) +async def test_public_a19_near_limit_upload_stays_bounded(admission_intake, tmp_path): + """A real public request holds a provider part and expires with charged custody.""" + content_mib = int(os.environ.get("WORKSTREAM_A19_BODY_MIB", "6")) + assert content_mib in {6, 496} + binary = Path(os.environ["WORKSTREAM_TEST_CADDY"]) + assert binary.is_file() + fixture = admission_intake + source = fixture.source_store_factory() + try: + prefix = source._private_prefix + finally: + source.close() + markers = tmp_path / "markers" + markers.mkdir() + (tmp_path / "scratch").mkdir(mode=0o700) + part_bytes = (5 if content_mib == 6 else 16) * MIB + last_part = 2 if content_mib == 6 else 32 + api_port, caddy_port = _free_port(), _free_port() + environment, profile = _api_environment(fixture, prefix, tmp_path, part_bytes, markers, last_part) + environment["WORKSTREAM_A19_API_PORT"] = str(api_port) + for name, key in (("xdg-config", "XDG_CONFIG_HOME"), ("xdg-data", "XDG_DATA_HOME")): + private = tmp_path / name + private.mkdir(mode=0o700) + environment[key] = str(private) + environment["PYTHONPATH"] = os.pathsep.join((str(BACKEND), str(BACKEND / "tests"), str(REPOSITORY))) + api_log, caddy_log = tmp_path / "api.log", tmp_path / "caddy.log" + api_output = api_log.open("wb") + api = subprocess.Popen([sys.executable, "-c", API_CODE], cwd=BACKEND, + env=environment, stdout=api_output, stderr=api_output) + caddy = None + caddy_output = None + request = None + try: + await _listen(api_port, api, api_log) + config = _caddy_config(binary, tmp_path, api_port, caddy_port) + caddy_output = caddy_log.open("wb") + caddy = subprocess.Popen([str(binary), "run", "--config", str(config)], + env=environment, stdout=caddy_output, stderr=caddy_output) + await _listen(caddy_port, caddy, caddy_log) + emitted = [] + samples = [] + + async def sample() -> None: + while request is not None and not request.done(): + samples.append({"at": time.monotonic(), "api_rss": _rss(api.pid), + "caddy_rss": _rss(caddy.pid), "client_rss": _rss(os.getpid()), + "scratch_bytes": _disk_bytes(tmp_path / "scratch"), + "emitted_bytes": emitted[0] if emitted else 0}) + await asyncio.sleep(0.2) + + async with httpx.AsyncClient(timeout=None) as client: + headers = { + "Host": "workstream.example.test", "Authorization": "Bearer a19-measurement-token", + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(fixture.assignment), + "X-Submission-Summary": "Measured bounded source upload", + "X-Contributor-Attestation": "I completed the measured work", + "Idempotency-Key": str(new_record_id()), + } + request = asyncio.create_task(client.post( + f"http://127.0.0.1:{caddy_port}/api/v1/tasks/{fixture.task}/submissions", + headers=headers, content=_zip_body(content_mib, emitted))) + sampler = asyncio.create_task(sample()) + await _wait_file(markers / "first", timeout=90) + blocked_at = emitted[0] + await asyncio.sleep(2) + blocked_growth = emitted[0] - blocked_at + assert content_mib == 6 or blocked_growth < content_mib * MIB // 4 + (markers / "release-first").touch() + await _wait_file(markers / "last", timeout=240) + response = await asyncio.wait_for(request, timeout=125) + await sampler + timeline = tmp_path / "a19-timeline.json" + timeline.write_text(json.dumps(samples, separators=(",", ":"))) + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "submission_infrastructure_unavailable" + assert int((markers / "completed").read_text()) == last_part - 1 + assert emitted[0] > content_mib * MIB and emitted[0] < 500 * MIB + assert samples + assert max(row["scratch_bytes"] for row in samples) < 2 * MIB + async with fixture.factory() as session: + state = (await session.execute(text( + "SELECT o.id,o.state AS operation_state,o.failure_code,o.accepted_at," + "c.accounted_bytes,c.state AS charge_state " + "FROM submission_intake_operations o JOIN submission_source_charges c " + "ON c.operation_id=o.id WHERE o.task_id=:task" + ), {"task": fixture.task})).one() + assert state.operation_state == "failed" and state.failure_code == "submission_infrastructure_unavailable" + assert state.accepted_at is None and state.accounted_bytes == 500 * MIB + assert state.charge_state == "reserved" + result = { + "content_mib": content_mib, "raw_bytes_emitted": emitted[0], + "provider_part_bytes": part_bytes, "held_part_number": last_part, + "provider_completed_parts": last_part - 1, + "blocked_client_growth_bytes": blocked_growth, + "peak_api_rss_bytes": max(row["api_rss"] for row in samples), + "peak_caddy_rss_bytes": max(row["caddy_rss"] for row in samples), + "peak_client_rss_bytes": max(row["client_rss"] for row in samples), + "peak_api_scratch_bytes": max(row["scratch_bytes"] for row in samples), + "timeline": str(timeline), + "upload_total_seconds": profile["upload_total_seconds"], + "result": "503_provider_stall_retained_charge", + } + print("A19_MEASUREMENT=" + json.dumps(result, sort_keys=True), flush=True) + finally: + if request is not None and not request.done(): + request.cancel() + await asyncio.gather(request, return_exceptions=True) + if caddy is not None: + _stop(caddy, caddy_output) + _stop(api, api_output) From ff3d4a37256a0034aa650e0591162bc5017e5fe8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:22:51 +0100 Subject: [PATCH 291/513] Port fault qualification callers to source intake and accepted T5 --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 149 +++++++ .../README.md | 66 ++- .../guide_worker.py | 6 +- .../public_guide_setup.py | 36 +- .../public_hosted_attachment.py | 14 +- .../public_intake_trials.py | 390 ++++++++---------- .../public_runtime_trials.py | 227 ++++++---- .../run_public_journey_probe.py | 14 +- scripts/test_public_hosted_attachment.py | 259 ++++++++++-- 9 files changed, 797 insertions(+), 364 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3dcdbaf1b..6c87d06b9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9489,3 +9489,152 @@ upload deadline, 30-second idle deadline, 60-second foreground lease and The isolated database and versioned bucket were removed by the runner. This is local MinIO/Caddy resource evidence for a deliberately failed upload, not native AWS, PRE or accepted-submission qualification. + +### Port local native failure vectors to current source intake + +Allowed next scope: public_intake_trials.py, public_runtime_trials.py, +public_guide_setup.py, guide_worker.py, run_public_journey_probe.py, +public_hosted_attachment.py, scripts/test_public_hosted_attachment.py and this +record. Preserve actual native launch retries, controller death/restart, original +lease epoch/deadline, exact deletion/foreign-resource control, failure replay, +fresh recovery and authorized POST retry. Use one PRE and separate tasks for +independent accepted vectors; no zero/multi approval or VM-before-EOF claim. +Upload cancellation/timeout must retain reserved source charge and no PRE/T4/T5, +and valid source upload must allocate native processing only after EOF. + +Pause only the general worker after each fixture project's guide setup while +measuring PRE resources; the dedicated finalizer stays real. Resume and observe +queued POST execution before the next fixture so it cannot pollute PRE counts. +Read source operations/charges and public progress rather than old admission +status. Keep exact native deadline safety in its current execution-stage guard. +Remove the local worker's scripted parser override but keep explicitly recorded +inference; consume the already-supplied canonical parser service. Local policy +approval must select the exact registered one-PRE/one-POST fixture entries. + +Risk: medium qualification control code. Run affected guard contracts, omission +probes, imports, Ruff/structure/record/link/diff and scoped review. Real native +resource/controller vectors require a separately authorized qualified execution; +local contract tests cannot close them. No remote fault commands, deployment or +paid requests will be issued in this repair worktree. + +Include the affected README status paragraph in this local-vector scope so +implemented caller migration remains distinct from unexecuted native proof. + +Implementation of this bounded port: + +- public_intake_trials now sends public raw ZIP with exact declared length; + cancellation and timeout precede EOF/native allocation and require terminal + operation, no acceptance/finalization selectors, released Task pointer and + exact positive reserved charge. The source-upload timeout keeps its original + stored upload deadline. Default-secret rejection blocks the single external + image; project rejection retains its exact finding/request/native receipt. + A deliberately incomplete valid body cannot allocate a VM; after releasing + its final bytes the accepted source must finalize through public progress and + the actual dedicated T5 worker. +- public_runtime_trials uses four separate tasks for one-attempt launch + refusals, controller death and selected-image timeout. POST separately retains + automatic launch retry/exhaustion; actual aggregate native expiry is pending. It keeps exact native + create/start/exec/delete counts, shared deadline/epoch, foreign-resource + survival, failed terminal replay without another VM, and fresh-key recovery. + The pre-existing public Operator POST outage/retry function is AST unchanged. + General workers stop only after guide setup and restart before observing each + queued POST result; T5 is never patched or manually injected. +- Local approvals read exact immutable registered fixture identities inside a + root transaction, selecting exactly one PRE and POST. Stale approval uses + otherwise-valid attachments. Hosted approval rejects zero/multiple PRE input. + The local API now starts app.main:app; the old optional observer module stays + solely because its shared adapter-transparency test still consumes it. No + obsolete prepare observer or tracing environment is installed by this flow. + guide_worker retains recorded inference and production ART source receipts, + but no longer overrides the real parser. Existing canonical parser socket, + explicit TLS runner and source profile remain required. Local HTTP request + timeout derives from upload/runner envelopes, replacing the obsolete90s cap. + +Executed contract evidence: affected HostedAttachment/ModelPOST unittest suites +passed45 in224.097s (/tmp/submission-local-vectors-guards-v1.log). The subsequently +added final local registry selection/root-transaction guard passed1 in45.359s +(/tmp/submission-local-approval-guard-v1.log). These are split receipts, not an +aggregate final-head46-case run. Named current PRE and source-failure guards +use controlled typed-shaped facts to check exact selected image/default stop, +charge preservation, no accepted handoff and pointer release; they do not prove +those PostgreSQL/native boundaries end to end. The current native expiry guard +has a valid control plus early deletion, reset deadline and changed epoch +refusals. An in-memory omission of only deletion-at-original-expiry caused its +named guard to fail RuntimeError-not-raised, without editing source files +(/tmp/submission-local-native-expiry-mutant.json and .log). + +Ruff, whitespace, record and links passed; structure validation is pending at +this append. No actual native fault, remote service mutation, deployment or paid +model/forge call was performed. Required qualification remains actual connected +upload cancellation/timeout, launch retry/exhaustion, controller death/restart, +original native expiry and POST recovery on an owned node. Native PRE source and +execution cancellation are distinct remaining vectors; provider-stage upload +cancellation does not qualify them. Recorded setup inference does not certify +real model inference. This change ports affected callers, not full-system or +native/AWS qualification. + +Root review caught two protocol-shape distinctions before freeze. The actual +smol/pre/admission.rs selects the locked registry's image cache, and pre.rs +passes it to prepare_with_connection: one VM runs both trusted defaults and +optional project execution. Thus the existing image-based `project` trace flag +classifies the whole source PRE VM, not the guest project phase. Default-secret +rejection now requires exactly one native VM and zero external members, never +zero VM. create_pre explicitly has one create attempt; source launch failures +now require one failed launch, no retry and fresh-key recovery. Native automatic +2/3 launch retry/exhaustion is preserved in bounded POST cases: valid source +PRE/T4/T5 precedes fault installation while the general worker is paused, then +real POST consumes the fault. Exhaustion uses unchanged public Operator retry +and a fresh successful POST machine; no finalizer or custody patch. + +The selected-image marker timeout also differs from aggregate PRE VM expiry. +The PRE trial requires an unchanged aggregate lease plus its exact retained +failure, not deletion-after-aggregate-expiry. Actual aggregate expiry remains +unqualified. The separate pure original-expiry guard still protects that future +receipt contract; it is not invoked by or credited as the inner-timeout vector. +Controller kill observes native VM execution/controller identity, not proof of +entry into the guest project phase. + +Topology limit: public_node_faults reads the runner's lease/cgroup/Smol state +and exchanges operator-local private command/trace files. Current TLS source +execution does not supply authenticated remote fault control or evidence +transport. The requested separate app/runner deployment must not share these +paths or move KVM onto the API host. This operator-local harness is not ready to +qualify that topology; remote fault transport and actual native aggregate +expiry/source/execution cancellation are concrete remaining prerequisites. +No new production control framework or remote action was introduced. + +Final current-shape guard result: the two added PRE/POST vector composition +contracts passed2 in91.897s (/tmp/submission-current-runtime-vector-guards-v2.log). +They observe separate tasks, exactly one source PRE creation attempt, native +POST2/3 launch retries, fault installation after accepted T5 and before worker +resume, and the unchanged Operator recovery route. Their first run reported +only two mock argument-index errors, corrected in the final guard source; no +production defect or native execution was inferred. The two-case receipt is +separate from the earlier45 and local-registry1 receipts. No aggregate final-head +suite, remote transport, aggregate-expiry or actual native fault pass is claimed. +Root requested a contention hold; no further guard/probe was launched after it. + +The selected wait case is named project_wait_failure. Static tracing through +pre.rs::run_project_phase and guest::run_project shows that its inner timeout +may exit the bootstrap and become implementation_unavailable at the host, before +the aggregate VM deadline. It now requires that exact current classification, +exec-to-delete elapsed time at least the locked selected deadline, and unchanged +aggregate VM epoch/deadline. It does not label generic failure as a proven typed +inner-deadline result or aggregate expiry. A new pure guard has a valid cleanup +before aggregate expiry control plus early-selected-cleanup, reset-lease and +wrong-classification refusals; execution is pending the shared A19 memory-run +slot. Actual receiving cancellation here uses an incomplete one-byte HTTP body; +it does not claim completed remote part upload or native PRE cancellation. + +After the A19 runner and its cleanup became terminal, the held selected-wait +pure guard passed1 in30.742s (/tmp/submission-selected-wait-guard-final.log). +No new native or remote run occurred. Full structure validation exited0 +(/tmp/submission-local-vectors-structure-final.log) before the final23-line pure +guard addition; protected backend files and ledgers remain untouched. Final +Ruff, Markdown links and whitespace checks passed. Final record gate follows +this evidence append. Executed contract custody is45+1+2+1 separate guards, +not an aggregate49-case or clean-commit runtime run. The native-expiry omission +probe is controlled in-memory evidence only. Actual two-host fault transport, +aggregate VM expiry, native PRE source/execution cancellation and real native +fault execution remain mandatory open qualification, without API-side KVM or +shared runner paths. diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md index aa61d0a31..b32963be7 100644 --- a/experiments/pilot04_external_checker_runtime/README.md +++ b/experiments/pilot04_external_checker_runtime/README.md @@ -30,15 +30,18 @@ preparation endpoint, ready-admission JSON creation, or injected verifier task. Model qualification keeps one non-model PRE and one model POST; model/forge identity, accounting and governed-outcome checks remain explicit. The retired hidden-owner selected drill and its stored receipts describe historical runs, -not current-HEAD qualification. Local cancellation/deadline/controller-loss -vectors still need their separate current-source migration; the guard repair -does not qualify those runs. +not current-HEAD qualification. Local upload cancellation/timeout and native launch/deadline/controller-loss +callers now use current source intake with exact retained charges and one PRE. +Their contract tests do not qualify actual native fault execution; connected +source/execution cancellation remains a separate mandatory native vector. The public journey starts with public project/guide creation, original synthetic Markdown bytes and two task examples. The public upload dispatches real Celery setup. Its explicit `guide_worker` entry point selects a recorded inference adapter through the existing typed runtime port; -production composition has no test switch. The adapter reads the actual scoped +production composition has no test switch. The existing production parser +service must be supplied through its canonical socket setting; this worker does +not replace it. The recorded inference adapter reads the actual scoped ART document grant and checks exact bytes, normalized examples and correction feedback. Stored source commitments and the runtime-observed canonical input hash must agree. This proves integration, not model reasoning or hosted inference. @@ -55,13 +58,13 @@ inject guide, proposal, policy, Task, Submission, acceptance or award facts. Locally signed tokens do not certify the hosted Flow Identity service. The companion uses a live loopback API, -the public manager guide activation, project submitter grant, and task lifecycle, contributor ZIP -preparation and canonical Submission POST, and a real Redis-backed prefork +the public manager guide activation, project submitter grant, and task lifecycle, contributor raw-ZIP +submission acceptance and exclusive finalization, and a real Redis-backed prefork Celery worker and Beat scheduler for artifact and outbox delivery. The isolated run sets the supported artifact scan interval to 10 seconds and requires a -retained scheduler audit before public intake; no manual scanner dispatch can -make a preparation ready. After a bounded timeout, the probe may publish the -exact pending verifier for private diagnosis and then unconditionally fails. +retained scheduler audit before public intake. Accepted source progress must +close through the dedicated production finalization worker; a timeout fails +without injecting a verifier or a finalization task. OUTBOX keeps its production 60-second Beat scan. The probe only observes its ordinary first delivery and due retry through retained project-scoped worker attempts and dispatch decisions; it publishes a duplicate message only after @@ -92,8 +95,10 @@ and API/worker/Beat processes belong to one disposable local run; the isolated-t runner owns database/role/MinIO namespace cleanup. This still does not certify hosted gVisor, arbitrary checker quality, live human review, or deployment. -Run from `backend/` on a dedicated Linux x86-64 KVM host with disposable -PostgreSQL, MinIO and Redis. Provision the [Smol node](../../external_checkers/README.md#smol-microvm-engine) +The command below describes the operator-local fault harness, not a qualified +two-host deployment. Production API/workers must stay on an app-only host and +KVM on a separate Linux x86-64 runner. Remote fault transport is still missing, +as detailed below. Use disposable PostgreSQL, MinIO and Redis. Provision the [Smol node](../../external_checkers/README.md#smol-microvm-engine) with `maximum_parallel=1`, the pinned trusted intake image and this directory's project fixture image. Both are operator-provisioned cache entries; no registry or Docker socket is needed by the API/worker or running guests. Build the Rust @@ -125,8 +130,12 @@ it permits only the recorded test wrapper substitution and compares the host validation receipt. Do not generate expected binary hashes from an unverified node and call that independent build custody. -The API proof entry point records genuine intake readiness/cleanup acknowledgements; -it delegates to the production adapter and is never imported by production. +The launcher uses the production API entry point. Native allocation/deletion +traces and retained source/PRE facts supply the fault evidence. Supply the +existing parser socket through `WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET`, the +canonical remote TLS runner settings, and an explicit +`WORKSTREAM_SUBMISSION_EXECUTION_PROFILE`; no parser or runner is provisioned +by this launcher. ```sh PYTHONPATH=.:tests:.. .venv/bin/python scripts/run_isolated_tests.py \ @@ -146,11 +155,13 @@ worker and Beat; the host supervisor owns node configuration and restart. Remove only the drill's own infrastructure after verifying both cleanup receipts. Do not remove retained product evidence or use broad container/volume pruning. -The expanded cases cover authenticated upload readiness before the last byte, -disconnect cleanup, no unauthenticated allocation, default-only and two ordered -project PRE bindings, stopping at the first failed binding, bounded pre-launch -retry/exhaustion, controller loss, same-key infrastructure replay and fresh-request -recovery. POST outage uses the existing **public Operator discovery/retry routes** +The current fault callers hold an incomplete upload without native allocation, +cancel or time out provider input while retaining its reserved charge, and +exercise Workstream default rejection before the single project PRE. Native +launch retry/exhaustion, original execution deadline, controller loss, same-key +infrastructure replay and fresh-request recovery use separate tasks. These +ported callers still require actual native fault execution; unit guard results +do not qualify those resource and cancellation boundaries. POST outage uses the existing **public Operator discovery/retry routes** and observes the next durable generation before governed acceptance. The prior non-live routing retry remains a separate trial. Check the final JSON cases and `cleanup_complete`, `database_cleanup_complete` and `minio_cleanup_complete`; @@ -161,3 +172,22 @@ attempts and governed outcomes. Private logs contain diagnostic metadata, never provider credentials. The Flow signer and guide inference are explicit fixtures; this proves self-hosted execution through real API/PG/MinIO/Celery owners, not production Flow, live model quality, native AWS S3 activation or hosted deployment. + +The fault supervisor is an operator-local harness: it reads the owned node's +lease/cgroup/Smol state and exchanges private command/trace files. It currently +has no authenticated remote fault-control/trace transport. The application's +production TLS connection to a separate runner does not supply that transport. +Do not mount runner paths into the API host or move KVM to the API to make these +vectors run. For the requested two-host deployment these fault vectors remain +unqualified until an operator can address and collect exact evidence from the +owned remote node. The contract tests here issue no remote fault commands. + +Current PRE uses one selected-image VM for trusted defaults and the optional +project phase; a default blocker still allocates that VM but never invokes the +project member. PRE has one native creation attempt. Automatic launch retry and +exhaustion belong to the POST vectors, with faults installed after accepted T5 +and recovery through the existing public Operator route. The PRE selected-image +marker deadline is distinct from the aggregate VM envelope. An actual aggregate +expiry receipt with unchanged epoch/deadline and exact deletion/foreign-resource +checks is still required; a pure expiry guard or inner checker timeout does not +qualify it. diff --git a/experiments/pilot04_external_checker_runtime/guide_worker.py b/experiments/pilot04_external_checker_runtime/guide_worker.py index f3f1563c8..a5edecb6e 100644 --- a/experiments/pilot04_external_checker_runtime/guide_worker.py +++ b/experiments/pilot04_external_checker_runtime/guide_worker.py @@ -3,10 +3,8 @@ from app.workers import project_setup from app.workers.celery_app import celery_app # noqa: F401 from experiments.pilot04_external_checker_runtime.guide_runtime import create_recorded_runtime -from guide_compilation_e2e import scripted_guide_document_parser_factory # Selected explicitly by the drill's celery -A, before prefork startup. Neither -# production app nor ordinary tests import this entry point. Inference and parser -# behavior are scripted; production ART reads and PROJECTS access receipts remain active. +# production app nor ordinary tests import this entry point. Setup inference +# is recorded; production parser, ART reads and PROJECTS access receipts remain active. project_setup.create_project_guide_runtime = create_recorded_runtime -project_setup.guide_document_parser_factory = scripted_guide_document_parser_factory diff --git a/experiments/pilot04_external_checker_runtime/public_guide_setup.py b/experiments/pilot04_external_checker_runtime/public_guide_setup.py index a5667659e..75f9ecb59 100644 --- a/experiments/pilot04_external_checker_runtime/public_guide_setup.py +++ b/experiments/pilot04_external_checker_runtime/public_guide_setup.py @@ -174,8 +174,36 @@ async def _source_evidence(factory, guide, setup, package, original): "uploaded_sha256": "sha256:" + hashlib.sha256(original).hexdigest()} +async def _local_approval_attachments(factory): + """Select the exact previously published fixture identities, never empty phases.""" + from app.modules.checkers.api.external_policy import ExternalCheckerImageAttachment + from app.modules.checkers.external_registry import ExternalCheckerRegistryReader + from tests.checkers.external.support import post_registry_spec, registry_spec + + attachments = {} + async with factory() as session, session.begin(): + reader = ExternalCheckerRegistryReader(session) + entries = await reader.list_entries() + for spec in (registry_spec("pre_submit"), post_registry_spec()): + matches = [entry for entry in entries if + (entry.capability_id, entry.capability_version, entry.phase) + == (spec.capability_id, spec.capability_version, spec.phase)] + if len(matches) != 1: + raise AssertionError("exact registered local fixture image is absent or ambiguous") + entry = await reader.read_exact(matches[0].registry_entry_id, matches[0].entry_digest) + attachments[spec.phase + "_attachments"] = [ExternalCheckerImageAttachment( + requirement_id="project." + spec.phase, + registry_entry_id=entry.registry_entry_id, + registry_entry_digest=entry.entry_digest, + configuration={}, + ).model_dump(mode="json")] + return attachments + + async def public_guide_setup(client, factory, human_review_required, call, token_for, *, pre_requirements=1, attachment=None): + if pre_requirements != 1: + raise ValueError("current qualification requires exactly one PRE image") model_post = attachment.model_post if attachment else None if model_post and 'project_id' in model_post.state: raise RuntimeError('this model qualification already owns one project') @@ -228,6 +256,9 @@ async def public_guide_setup(client, factory, human_review_required, call, token compilation_root = root + f"/compilations/{setup['finalized_compilation_id']}" initial = await call(client, "GET", compilation_root + "/proposal", token, 200) initial_setup = setup + attachments = (model_post.approval_attachments() if model_post else + attachment.approval_attachments(pre_requirements) if attachment else + await _local_approval_attachments(factory)) if human_review_required and attachment is None: correction = await _correct_public_proposal(client, compilation_root, initial, token, call) setup = await wait_for_guide_read(client, root + "/setup-runs/latest", token, @@ -244,13 +275,10 @@ async def public_guide_setup(client, factory, human_review_required, call, token headers={"Idempotency-Key": str(uuid4())}, json={"target": initial["target"], "acknowledged_warning_hashes": initial["warning_hashes"], - "pre_submit_attachments": [], "post_submit_attachments": []}) + **attachments}) compilation_root = root + f"/compilations/{setup['finalized_compilation_id']}" await _finance_policy(client, factory, UUID(project["id"]), token_for, not human_review_required and attachment is None, call, attachment) - attachments = (model_post.approval_attachments() if model_post else - attachment.approval_attachments(pre_requirements) if attachment else - {"pre_submit_attachments": [], "post_submit_attachments": []}) post = await _approve_policies(client, compilation_root, token, call, attachments) context = post["activation_context"] activation = {"target": post["target"], **{field: context[field] for field in ( diff --git a/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py b/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py index 7e1200a6e..2e8f279c5 100644 --- a/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py +++ b/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py @@ -414,7 +414,7 @@ def approval_attachments(self, pre_requirements): """Select exact published fixture images as the human manager.""" from app.modules.checkers.api.external_policy import ExternalCheckerImageAttachment - require(pre_requirements in (0, 1, 2), 'unsupported hosted PRE fixture count') + require(pre_requirements == 1, 'current qualification requires exactly one PRE image') require(set(self.registered_images) == {'pre_submit', 'post_submit'}, 'baseline registry publications are incomplete') @@ -425,10 +425,7 @@ def attach(phase, requirement_id): registry_entry_digest=entry.entry_digest, configuration={}, ).model_dump(mode='json') - pre_ids = ('project.pre_submit.01', 'project.pre_submit.02') if pre_requirements == 2 else ( - ('project.pre_submit',) if pre_requirements == 1 else () - ) - return {'pre_submit_attachments': [attach('pre_submit', key) for key in pre_ids], + return {'pre_submit_attachments': [attach('pre_submit', 'project.pre_submit')], 'post_submit_attachments': [attach('post_submit', 'project.post_submit')]} async def provision_services(self, client): @@ -566,8 +563,11 @@ async def _run(attachment, database_url, broker_url, qualification): while await _scan_audit_count(factory) <= scans_before: require(time.monotonic() < deadline, 'hosted Beat did not dispatch an authorized artifact scan') await asyncio.sleep(2) - intake = await public_intake_trials(client, factory, attachment, None, attachment.node_root) - runtime = await public_runtime_trials(client, factory, attachment, attachment.node_root) + intake = await public_intake_trials(client, factory, attachment, attachment.node_root, + stop_worker=attachment.stop_worker, start_worker=attachment.start_worker) + runtime = await public_runtime_trials(client, factory, attachment, attachment.node_root, + stop_worker=attachment.stop_worker, start_worker=attachment.start_worker, + operator_token=attachment.token_for_label('operator')) human = await _one_mode(client, factory, attachment, human_review_required=True, operator_id=attachment.actors['operator'].actor_profile_id) automatic = await _one_mode(client, factory, attachment, human_review_required=False, diff --git a/experiments/pilot04_external_checker_runtime/public_intake_trials.py b/experiments/pilot04_external_checker_runtime/public_intake_trials.py index 53e15a8a4..0cd6f47c2 100644 --- a/experiments/pilot04_external_checker_runtime/public_intake_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_intake_trials.py @@ -1,18 +1,18 @@ -"""Public zero/two-binding and upload-overlap evidence on the real one-slot node.""" +"""Current public source-intake failure boundaries on the owned native node.""" import asyncio -import json from pathlib import Path import time from uuid import uuid4 from sqlalchemy import func, select +from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge from app.modules.artifacts.models import SubmissionBundleAdmission, SubmissionBundleDurableIntent from app.modules.checkers.models import SelectedPreSubmitRun -from app.modules.tasks.models import Submission +from app.modules.tasks.models import Submission, WorkstreamTask from experiments.pilot04_external_checker_runtime.public_probe_support import ( - _json, _public_project, _require, _started_public_task, _with_fixture_file, + _json, _public_project, _require, _secret_archive, _started_public_task, _with_fixture_file, ) from experiments.pilot04_external_checker_runtime.public_node_faults import assert_launches, node_command, trace_events from tests.post_submit_materialization_helpers import archive_with_modes @@ -38,243 +38,205 @@ async def _selected(factory, key): return row -def _assert_default_only_pre(row): - value = row.terminal_json["execution"] - _require(row.status == "completed" and value["eligible"] - and value["workstream_default"]["eligible"] - and value["required_external_count"] == 0 and value["external_members"] == [], - "default-only policy did not retain its exact zero-project execution") - - -def _assert_ordered_pre_and_stop(row, *, failed): - value = row.terminal_json["execution"] - members = value["external_members"] - expected = ["project.pre_submit.01"] if failed else ["project.pre_submit.01", "project.pre_submit.02"] - _require(row.status == "completed" and value["workstream_default"]["eligible"] - and value["required_external_count"] == 2 and value["eligible"] is not failed - and [member["requirement_id"] for member in members] == expected - and [member["order"] for member in members] == list(range(len(expected))) - and len({member["request_digest"] for member in members}) == len(expected), - "two-binding policy did not retain its ordered executed prefix") - for member in members: - _require(member["result"]["verdict"] == ("failed" if failed else "passed") - and member["result"]["request_digest"] == member["request_digest"] - and member["isolation"]["runtime"] == "smolvm", - "selected member lost its real isolated request/result custody") - - -def _events(path): - return [json.loads(line) for line in path.read_text().splitlines()] if path and path.exists() else [] - - -def _assert_project_invocations(row, trace, observer_start, node_root, runtime_start): - members = row.terminal_json['execution']['external_members'] - expected = [member['request_digest'] for member in members] - observed = _events(trace)[observer_start:] - starts = [event for event in observed if event['event'] == 'project_started'] - ends = [event for event in observed if event['event'] == 'project_completed'] - _require(trace is None or ([event['session'] for event in starts] == expected - and [event['session'] for event in ends] == expected), - 'project adapter invocations differ from retained ordered members') - order = [(event['event'], event['session']) for event in observed - if event['event'] in {'project_started', 'project_completed'}] - _require(trace is None or order == [(kind, digest) for digest in expected - for kind in ('project_started', 'project_completed')], - 'project checker invocations overlap or run outside canonical order') - machines = assert_launches(node_root, runtime_start, creates=len(expected), - executions=len(expected), shared_deadline=False) - executions = [event for event in trace_events(node_root)[runtime_start:] - if event['project'] and event['operation'] == 'exec'] - _require([event['name'] for event in executions] == machines, - 'project guest execution order differs from fresh allocation order') - for started, ended, executed in zip(starts, ends, executions if trace else [], strict=True): - _require(started['monotonic'] <= executed['monotonic'] <= ended['monotonic'], - 'project VM execution is outside its exact adapter request') - return machines - - -async def _wait_event(path, start, event, session=None): - deadline = time.monotonic() + 45 - while time.monotonic() < deadline: - found = [item for item in _events(path)[start:] if item["event"] == event - and (session is None or item["session"] == session)] - if found: - return found[0] - await asyncio.sleep(0.05) - raise RuntimeError("real intake adapter did not acknowledge " + event) +async def _source_operation(factory, key): + async with factory() as session: + return (await session.scalars(select(SubmissionIntakeOperation).where( + SubmissionIntakeOperation.idempotency_key == key))).one_or_none() -async def _native_event(root, start, operation, *, name=None, timeout=45): +async def _wait_source_state(factory, key, states, *, timeout=90): deadline = time.monotonic() + timeout while time.monotonic() < deadline: - matches = [event for event in trace_events(root)[start:] - if event['operation'] == operation and event['project'] is False - and (name is None or event['name'] == name)] - if matches: - _require(len(matches) == 1 and matches[0].get('lease') - and matches[0]['lease']['name'] == matches[0]['name'], - 'native preparation evidence is ambiguous or lacks a lease') - return matches[0] + operation = await _source_operation(factory, key) + if operation is not None and operation.state in states: + return operation await asyncio.sleep(.05) - raise RuntimeError('native intake did not reach ' + operation) - - -async def _prepared(trace, start, node_root, runtime_start): - if trace is not None: - return await _wait_event(trace, start, 'prepare_ready') - event = await _native_event(node_root, runtime_start, 'prepare_completed') - return {'evidence': 'native_prepare_completed', 'session': event['name'], **event} - + raise RuntimeError('source operation did not reach its exact expected state') -async def _closed(trace, start, session, node_root, runtime_start): - if trace is not None: - await _wait_event(trace, start, 'close_confirmed', session) - else: - await _native_event(node_root, runtime_start, 'delete', name=session) - -async def _cancel_upload(client, factory, route, headers, token, archive, trace, task, node_root): - start = len(_events(trace)) - key = str(uuid4()) - ready = asyncio.Event() - session_id = None - runtime_start = len(trace_events(node_root)) +async def _assert_source_failure(factory, task, key, size, *, sealed, code=None): + """Failed input remains charged without PRE admission or accepted handoff.""" + row = await _wait_source_state(factory, key, {'failed', 'cancelled', 'rejected', 'abandoned'}) + _require(row.task_id == task and row.acceptance_receipt is None + and row.finalized_submission_id is None and row.finalization_event_id is None, + 'failed source escaped into accepted custody') + if code is not None: + _require(row.failure_code == code, 'source failure changed its exact code') + async with factory() as session: + charge = await session.get(SubmissionSourceCharge, row.id) + owner = await session.get(WorkstreamTask, task) + _require(charge and charge.state == ('sealed' if sealed else 'reserved') + and charge.accounted_bytes == size > 0, + 'failed source released or changed its exact charge') + _require(owner.status == 'in_progress' and owner.active_submission_operation_id is None, + 'failed source changed Task eligibility or retained its pointer') + if not sealed: + _require(row.raw_byte_count is None and row.selected_pre_submit_run_id is None, + 'incomplete upload sealed bytes or reserved PRE') + _require(await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun).where( + SelectedPreSubmitRun.task_id == task)) == 0, 'incomplete upload created a PRE run') + await _assert_no_submission_after_intake_failure(factory, task, row.selected_pre_submit_run_id) + return row + + +async def _observe_accepted_source(client, factory, task, assignment, token, archive, key, receipt): + from experiments.pilot04_external_checker_runtime.run_public_journey_probe import _await_finalized_source + + _require(receipt['status'] == 'accepted' and receipt['replayed'] is False, + 'source trial did not retain a new accepted receipt') + context = {'acceptance_receipt': receipt, 'idempotency_key': key} + return await _await_finalized_source(client, factory, task, assignment, token, context, archive) + + +def _assert_current_pre(row, *, failure=None): + """One selected image replaces obsolete zero/multi-image approval vectors.""" + value = row.terminal_json['execution'] + _require(row.status == 'completed' and value['required_external_count'] == 1, + 'current PRE did not retain exactly one required project image') + members = value['external_members'] + if failure == 'secret': + failed = [check['failure_code'] for check in value['workstream_default']['checks'] + if check['status'] == 'failed'] + _require(not value['eligible'] and not value['workstream_default']['eligible'] + and failed == ['high_confidence_secret_detected'] and members == [], + 'default blocker reached project execution or lost exact feedback') + return + _require(value['workstream_default']['eligible'] and value['eligible'] is (failure is None) + and len(members) == 1 and members[0]['order'] == 0 + and members[0]['requirement_id'] == 'project.pre_submit', + 'one-project PRE lost its default-before-project boundary') + member = members[0] + _require(member['result']['verdict'] == ('failed' if failure else 'passed') + and member['result']['request_digest'] == member['request_digest'] + and member['isolation']['runtime'] == 'smolvm' + and member['isolation']['isolation_mode'] == 'smol-microvm', + 'selected member lost its exact native request/result custody') + if failure: + _require([f['code'] for f in member['result']['findings']] == ['probe.project_rule_failed'], + 'project PRE failure lost its exact finding') + + +async def _source_request(client, route, headers, token, key, content, expected): + return await _json(client, 'POST', route, token, expected, + headers=headers | {'Idempotency-Key': key, 'Content-Length': str(len(content))}, content=content) + + +async def _cancel_upload(client, factory, route, headers, token, archive, task, node_root): + """Cancel incomplete provider upload before any native allocation is permitted.""" + key, ready, start = str(uuid4()), asyncio.Event(), len(trace_events(node_root)) async def incomplete(): - nonlocal session_id yield archive[:1] - session_id = (await _prepared(trace, start, node_root, runtime_start))["session"] + await _wait_source_state(factory, key, {'receiving'}) + _require(len(trace_events(node_root)) == start, 'incomplete upload allocated native resources') ready.set() await asyncio.Event().wait() - pending = asyncio.create_task(client.post( - route, headers=headers | {"Authorization": "Bearer " + token, "Idempotency-Key": key}, - content=incomplete(), - )) + pending = asyncio.create_task(client.post(route, headers=headers | { + 'Authorization': 'Bearer ' + token, 'Idempotency-Key': key, 'Content-Length': str(len(archive))}, + content=incomplete())) try: - await asyncio.wait_for(ready.wait(), timeout=45) + await asyncio.wait_for(ready.wait(), timeout=90) finally: pending.cancel() await asyncio.gather(pending, return_exceptions=True) - await _closed(trace, start, session_id, node_root, runtime_start) - cleanup = await node_command(node_root, "drained") - _require(cleanup["foreign_preserved"] and not any(cleanup["resources"].values()), - "cancelled upload retained owned resources or changed the foreign control") - machines = assert_launches(node_root, runtime_start, creates=1, executions=0, project=False) - assert_launches(node_root, runtime_start, creates=0, executions=0) - async with factory() as session: - _require(await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun).where( - SelectedPreSubmitRun.idempotency_key == key)) == 0, - "incomplete upload reserved a selected checker run") - await _assert_no_submission_after_intake_failure(factory, task) - return {"case": "cancelled_upload", "session": session_id, "machines": machines, - "cleanup": cleanup, "reserved_runs": 0} + row = await _assert_source_failure(factory, task, key, len(archive), sealed=False) + assert_launches(node_root, start, creates=0, executions=0, project=False) + assert_launches(node_root, start, creates=0, executions=0) + cleanup = await node_command(node_root, 'drained') + _require(cleanup['foreign_preserved'] and not any(cleanup['resources'].values()), + 'cancelled upload changed foreign resources') + return {'case': 'cancelled_source_upload', 'operation_id': row.id, + 'failure_code': row.failure_code, 'native_allocations': 0, 'cleanup': cleanup} async def _expire_upload(client, factory, route, headers, token, archive, task, node_root): - """Hold a real HTTP body open through its original native lease deadline.""" - key, start = str(uuid4()), len(trace_events(node_root)) - observed = {} + """Retain the original upload deadline while real idle/total timing closes input.""" + key, start, observed = str(uuid4()), len(trace_events(node_root)), {} async def stalled(): yield archive[:1] - prepared = await _native_event(node_root, start, 'prepare_completed') - remaining = (prepared['lease']['expires_ms'] - time.time_ns() // 1_000_000) / 1000 - _require(0 < remaining <= 3600, 'native intake expiry exceeds bounded public proof window') - deleted = await _native_event(node_root, start, 'delete', name=prepared['name'], timeout=remaining + 45) - _require(deleted['wall_ms'] >= prepared['lease']['expires_ms'] - and deleted['lease']['epoch'] == prepared['lease']['epoch'] - and deleted['lease']['expires_ms'] == prepared['lease']['expires_ms'], - 'stalled upload did not reach its original lease expiry') - observed.update(prepared=prepared, deleted=deleted) + row = await _wait_source_state(factory, key, {'receiving'}) + observed['original_deadline'] = row.upload_deadline_at + _require(len(trace_events(node_root)) == start, 'stalled upload allocated native resources') + await _wait_source_state(factory, key, {'failed'}, timeout=3600) yield archive[1:] response = await client.post(route, headers=headers | {'Authorization': 'Bearer ' + token, - 'Idempotency-Key': key}, content=stalled()) - _require(response.status_code == 503 - and response.json()['error']['code'] == 'service_unavailable' - and response.json()['detail'] == 'pre_submission_attempt_outcome_unresolved', - 'expired upload was not reported as unresolved infrastructure') + 'Idempotency-Key': key, 'Content-Length': str(len(archive))}, content=stalled(), timeout=3660) + _require(response.status_code == 408 and response.json()['error']['code'] == 'submission_upload_timeout', + 'expired source upload did not return its exact timeout') + row = await _assert_source_failure(factory, task, key, len(archive), sealed=False, + code='submission_upload_timeout') + _require(row.upload_deadline_at == observed['original_deadline'], 'stalled upload reset its original deadline') + assert_launches(node_root, start, creates=0, executions=0, project=False) + assert_launches(node_root, start, creates=0, executions=0) + await _source_request(client, route, headers, token, key, archive, 408) + return {'case': 'source_upload_timeout', 'operation_id': row.id, 'native_allocations': 0, + 'original_deadline': row.upload_deadline_at.isoformat()} + + +async def _drain_source_trial_posts(factory, project_id, accepted, node_root): + from experiments.pilot04_external_checker_runtime.run_public_journey_probe import _complete_post + + for saved in accepted: + await _complete_post(factory, submission_id=saved['submission_id'], project_id=project_id, + recommendation='allow_review', deliver_completion=False) cleanup = await node_command(node_root, 'drained') _require(cleanup['foreign_preserved'] and not any(cleanup['resources'].values()), - 'expired upload cleanup changed foreign custody or retained resources') - machines = assert_launches(node_root, start, creates=1, executions=0, project=False) - assert_launches(node_root, start, creates=0, executions=0) - async with factory() as session: - _require(await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun).where( - SelectedPreSubmitRun.idempotency_key == key)) == 0, - 'expired incomplete upload reserved a selected checker run') - await _assert_no_submission_after_intake_failure(factory, task) - return {'case': 'stalled_upload_original_expiry', 'observed': observed, 'machines': machines, - 'http_status': response.status_code, 'reserved_runs': 0, 'cleanup': cleanup} - - -async def public_intake_trials(client, factory, env, trace: Path, node_root: Path): - evidence = [] - for count in (0, 2): - project, _, manager, contributor = await _public_project( - client, factory, env, human_review_required=True, pre_requirements=count, - ) - task, assignment = await _started_public_task( - client, project_id=str(project.project_id), manager_token=manager, - contributor_token=contributor, source_ref=f"intake-bindings-{count}", - ) - archive = archive_with_modes("evidence/results", project.project_id) - route = f"/api/v1/tasks/{task}/submission-bundle-preparations" - headers = {"Content-Type": "application/zip", "X-Task-Assignment-Id": assignment, - "X-Submission-Summary": "Completed task evidence.", - "X-Contributor-Attestation": "rights_confirmed; no confidential data or credentials."} - if count == 0: - start = len(_events(trace)) - unauth_runtime_start = len(trace_events(node_root)) - response = await client.post(route, headers=headers | {"Idempotency-Key": str(uuid4())}, content=archive) - _require(response.status_code == 401, - f"unauthenticated upload returned {response.status_code}; expected 401") - _require(len(_events(trace)) == start, "unauthenticated upload allocated an intake session") - _require(len(trace_events(node_root)) == unauth_runtime_start, - 'unauthenticated upload allocated native resources') - evidence.append(await _cancel_upload( - client, factory, route, headers, contributor, archive, trace, task, node_root, - )) - if trace is None: - evidence.append(await _expire_upload( - client, factory, route, headers, contributor, archive, task, node_root)) - # The real configured upload deadline may outlive a fixture - # token. Mint a fresh token for the next independent request. - contributor = env.token_for_label('contributor') - start = len(_events(trace)) - runtime_start = len(trace_events(node_root)) - key = str(uuid4()) - async def delayed_upload(): - yield archive[:1] - ready = await _prepared(trace, start, node_root, runtime_start) - evidence.append({"case": "upload_overlap", "ready": ready, - "upload_finished_at": time.monotonic()}) - yield archive[1:] - result = await _json(client, "POST", route, contributor, 202, - headers=headers | {"Idempotency-Key": key}, content=delayed_upload()) - session = evidence[-1]['ready']['session'] - await _closed(trace, start, session, node_root, runtime_start) + 'source-trial POST execution retained resources or changed foreign custody') + + +async def public_intake_trials(client, factory, env, node_root: Path, *, stop_worker, start_worker): + """Current one-PRE default/project failures and source-before-native boundaries.""" + project, _, manager, token = await _public_project(client, factory, env, human_review_required=True) + task, assignment = await _started_public_task(client, project_id=str(project.project_id), + manager_token=manager, contributor_token=token, source_ref='source-intake-boundaries') + archive = archive_with_modes('evidence/results', project.project_id) + route = f'/api/v1/tasks/{task}/submissions' + headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, + 'X-Submission-Summary': 'Completed task evidence.', + 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} + evidence, accepted = [], [] + stop_worker() + try: + start = len(trace_events(node_root)) + response = await client.post(route, headers=headers | {'Idempotency-Key': str(uuid4())}, content=archive) + _require(response.status_code == 401 and len(trace_events(node_root)) == start, + 'unauthenticated source upload allocated native resources') + evidence.append(await _cancel_upload(client, factory, route, headers, token, archive, task, node_root)) + evidence.append(await _expire_upload(client, factory, route, headers, token, archive, task, node_root)) + for failure, content in (('secret', _secret_archive(archive)), + ('project', _with_fixture_file(archive, 'project-rejected.txt'))): + start, key = len(trace_events(node_root)), str(uuid4()) + result = await _source_request(client, route, headers, token, key, content, 422) + _require(result['error']['code'] == 'pre_submission_checker_failed', 'work failure lost public feedback') row = await _selected(factory, key) - _assert_default_only_pre(row) - _assert_project_invocations(row, trace, start, node_root, runtime_start) - evidence.append({"case": "default_only", "run_id": row.id, - "preparation_status": result["submission_bundle_preparation_status"]}) - else: - for failed in (True, False): - runtime_start = len(trace_events(node_root)) - observer_start = len(_events(trace)) - key = str(uuid4()) - result = await _json(client, "POST", route, contributor, 422 if failed else 202, - headers=headers | {"Idempotency-Key": key}, - content=_with_fixture_file(archive, "project-rejected.txt") if failed else archive) - row = await _selected(factory, key) - _assert_ordered_pre_and_stop(row, failed=failed) - machines = _assert_project_invocations( - row, trace, observer_start, node_root, runtime_start) - if failed: - await _assert_no_submission_after_intake_failure(factory, task, row.id) - evidence.append({"case": "ordered_stop" if failed else "ordered_pass", "run_id": row.id, "machines": machines, - "request_digests": [member["request_digest"] - for member in row.terminal_json["execution"]["external_members"]]}) + _assert_current_pre(row, failure=failure) + await _assert_source_failure(factory, task, key, len(content), sealed=True, + code='pre_submission_checker_failed') + # One VM runs trusted defaults and, only if eligible, the project phase. + assert_launches(node_root, start, creates=1, executions=1) + evidence.append({'case': failure + '_rejection', 'run_id': row.id}) + start, key, released = len(trace_events(node_root)), str(uuid4()), {} + + async def delayed(): + yield archive[:1] + await _wait_source_state(factory, key, {'receiving'}) + _require(len(trace_events(node_root)) == start, 'source allocated native VM before complete body') + released['at'] = time.monotonic() + yield archive[1:] + + result = await _json(client, 'POST', route, token, 202, headers=headers | { + 'Idempotency-Key': key, 'Content-Length': str(len(archive))}, content=delayed()) + row = await _selected(factory, key) + _assert_current_pre(row) + assert_launches(node_root, start, creates=1, executions=1) + _require(all(item['monotonic'] >= released['at'] for item in trace_events(node_root)[start:] + if item['operation'] == 'create'), 'native allocation preceded complete source release') + accepted.append(await _observe_accepted_source(client, factory, task, assignment, token, archive, key, result)) + evidence.append({'case': 'complete_source_before_native', 'run_id': row.id, 'submission': accepted[-1]}) + finally: + await start_worker() + await _drain_source_trial_posts(factory, project.project_id, accepted, node_root) return evidence diff --git a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py index 85e739246..bd21543cf 100644 --- a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py @@ -1,4 +1,4 @@ -"""Real project-launch outage and authorized durable retry in the isolated public drill.""" +"""Real project-launch faults through current public source intake and durable retry.""" import json from pathlib import Path @@ -9,7 +9,8 @@ from app.modules.checkers.models import CheckerRun from app.modules.tasks.models import SubmissionDispatch from experiments.pilot04_external_checker_runtime.public_intake_trials import ( - _assert_no_submission_after_intake_failure, _selected, + _assert_current_pre, _assert_source_failure, _drain_source_trial_posts, + _observe_accepted_source, _selected, _source_request, ) from experiments.pilot04_external_checker_runtime.public_node_faults import assert_launches, node_command, trace_events from experiments.pilot04_external_checker_runtime.public_probe_support import ( @@ -19,88 +20,166 @@ from tests.post_submit_materialization_helpers import archive_with_modes -async def public_runtime_trials(client, factory, env, root: Path): - project, _, manager, contributor = await _public_project( - client, factory, env, human_review_required=True, - ) - task, assignment = await _started_public_task( - client, project_id=str(project.project_id), manager_token=manager, - contributor_token=contributor, source_ref='runtime-failure-recovery', - ) +def _require_original_runtime_expiry(created, deleted): + """Deletion must reach the original native epoch/deadline without resetting it.""" + original, final = created['lease'], deleted['lease'] + _require(deleted['wall_ms'] >= original['expires_ms'] + and final['epoch'] == original['epoch'] + and final['expires_ms'] == original['expires_ms'], + 'native execution did not reach its original lease expiry') + + +async def _runtime_fault_evidence(root, start, action, control, row): + events = [event for event in trace_events(root)[start:] if event['project']] + leases = [event['lease'] for event in events if event.get('lease')] + if action == 'project_kill': + killed = [event for event in events if event['operation'] == 'controller_kill'] + _require(len(killed) == 1 and killed[0]['controller_pid'] == control['controller_pid'], + 'controller-death trial did not record the exact kill target') + restarted = await node_command(root, 'restarted') + _require(restarted['controller_pid'] != control['controller_pid'], + 'controller-death trial retained the original controller') + _require(leases and len({lease['epoch'] for lease in leases}) == 1 + and len({lease['expires_ms'] for lease in leases}) == 1, + 'interrupted execution changed its original lease epoch/deadline') + if action == 'project_wait_failure': + created = next(event for event in events if event['operation'] == 'create') + deleted = next(event for event in events if event['operation'] == 'delete') + # The inner selected-image deadline may precede the aggregate VM expiry. + # Full aggregate expiry needs a separate native receipt, never this marker. + _require(deleted['lease']['epoch'] == created['lease']['epoch'] + and deleted['lease']['expires_ms'] == created['lease']['expires_ms'], + 'selected deadline changed its aggregate native lease') + execution = next(event for event in events if event['operation'] == 'exec') + selected_ms = row.request_json['policy']['entries'][0]['registry']['resources']['deadline_ms'] + _require(deleted['wall_ms'] >= execution['wall_ms'] + selected_ms + and row.terminal_json['infrastructure_failure_code'] == 'implementation_unavailable', + 'selected wait did not retain bounded execution and its current infrastructure failure') + return leases + + +async def _recover_failed_source(client, factory, route, headers, token, content, archive, + key, result, row, task, assignment, root, action, leases): + _require(row.status == 'infrastructure_failed' and row.terminal_json['execution'] is None, + 'runtime outage was represented as a work verdict') + await _assert_source_failure(factory, task, key, len(content), sealed=True, + code='submission_infrastructure_unavailable') + await node_command(root, 'clear') + replay_start = len(trace_events(root)) + replay = await _source_request(client, route, headers, token, key, content, 503) + _require(replay['error']['code'] == result['error']['code'], 'failure replay changed code') + assert_launches(root, replay_start, creates=0, executions=0) + assert_launches(root, replay_start, creates=0, executions=0, project=False) + repeated = await _selected(factory, key) + _require((repeated.id, repeated.terminal_digest) == (row.id, row.terminal_digest), + 'same-key replay replaced terminal failure custody') + recovery_start, fresh_key = len(trace_events(root)), str(uuid4()) + accepted = await _source_request(client, route, headers, token, fresh_key, archive, 202) + fresh = await _selected(factory, fresh_key) + _assert_current_pre(fresh) + assert_launches(root, recovery_start, creates=1, executions=1) + _require(fresh.id != row.id, 'fresh request reused terminal failed PRE') + if action == 'project_kill': + new_leases = [event['lease'] for event in trace_events(root)[recovery_start:] + if event['project'] and event.get('lease')] + _require(new_leases and all(lease['epoch'] != leases[0]['epoch'] for lease in new_leases), + 'fresh execution did not use the restarted controller epoch') + return await _observe_accepted_source(client, factory, task, assignment, token, archive, fresh_key, accepted) + + +async def public_runtime_trials(client, factory, env, root: Path, *, stop_worker, start_worker, operator_token): + """Separate tasks retain one PRE per accepted source and independent fault trials.""" + project, _, manager, token = await _public_project(client, factory, env, human_review_required=True) archive = archive_with_modes('evidence/results', project.project_id) - route = f'/api/v1/tasks/{task}/submission-bundle-preparations' - headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, - 'X-Submission-Summary': 'Completed task evidence.', - 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} - evidence = [] + evidence, accepted = [], [] + stop_worker() try: - for action, expected, creates, executions in ( - ('project_fail_once', 202, 2, 1), - ('project_fail_all', 503, 3, 0), - ('project_kill', 503, 1, 1), - ('project_deadline', 503, 1, 1), + for action, creates, executions in ( + ('project_fail_once', 1, 0), ('project_fail_all', 1, 0), + ('project_kill', 1, 1), ('project_wait_failure', 1, 1), ): - control = await node_command(root, 'clear' if action == 'project_deadline' else action) - start = len(trace_events(root)) - key = str(uuid4()) - content = _with_fixture_file(archive, 'runtime-wait.txt') if action in {'project_kill', 'project_deadline'} else archive - began = time.monotonic() - result = await _json(client, 'POST', route, contributor, expected, - headers=headers | {'Idempotency-Key': key}, content=content) + task, assignment = await _started_public_task(client, project_id=str(project.project_id), + manager_token=manager, contributor_token=token, source_ref='source-' + action) + route = f'/api/v1/tasks/{task}/submissions' + headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, + 'X-Submission-Summary': 'Completed task evidence.', + 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} + control = await node_command(root, 'clear' if action == 'project_wait_failure' else action) + start, key, began = len(trace_events(root)), str(uuid4()), time.monotonic() + content = (_with_fixture_file(archive, 'runtime-wait.txt') + if action in {'project_kill', 'project_wait_failure'} else archive) + result = await _source_request(client, route, headers, token, key, content, 503) drained = await node_command(root, 'drained') - _require(bool(drained['foreign_preserved']) and not any(drained['resources'].values()), + _require(drained['foreign_preserved'] and not any(drained['resources'].values()), 'exact cleanup or foreign preservation is absent') names = assert_launches(root, start, creates=creates, executions=executions) - if action == 'project_kill': - events = [e for e in trace_events(root)[start:] if e['project']] - killed = [e for e in events if e['operation'] == 'controller_kill'] - _require(len(killed) == 1 and killed[0]['controller_pid'] == control['controller_pid'], - 'controller-death trial did not record the exact kill target') - restarted = await node_command(root, 'restarted') - _require(restarted['controller_pid'] != control['controller_pid'], - 'controller-death trial retained the original controller') - leases = [e['lease'] for e in events if e.get('lease')] - _require(leases and len({lease['epoch'] for lease in leases}) == 1 - and len({lease['expires_ms'] for lease in leases}) == 1, - 'interrupted execution changed its original lease epoch/deadline') row = await _selected(factory, key) - if action == 'project_deadline': - events = [event for event in trace_events(root)[start:] if event['project']] - created = next(event for event in events if event['operation'] == 'create') - deleted = next(event for event in events if event['operation'] == 'delete') - _require(row.terminal_json['infrastructure_failure_code'] == 'deadline_exceeded' - and deleted['wall_ms'] >= created['lease']['expires_ms'], - 'deadline trial did not reach its original expiry with exact timeout custody') - if expected == 503: - _require(row.status == 'infrastructure_failed' and row.terminal_json['execution'] is None, - 'runtime outage was represented as a work verdict') - await _assert_no_submission_after_intake_failure(factory, task, row.id) - await node_command(root, 'clear') - replay_start = len(trace_events(root)) - replay = await _json(client, 'POST', route, contributor, 503, - headers=headers | {'Idempotency-Key': key}, content=content) - _require(replay['error']['code'] == result['error']['code'], 'failure replay changed code') - # Re-upload and trusted inspection may occur; selected project execution may not. - assert_launches(root, replay_start, creates=0, executions=0) - repeated = await _selected(factory, key) - _require((repeated.id, repeated.terminal_digest) == (row.id, row.terminal_digest), - 'same-key replay replaced terminal failure custody') - recovery_start = len(trace_events(root)) - fresh_key = str(uuid4()) - await _json(client, 'POST', route, contributor, 202, - headers=headers | {'Idempotency-Key': fresh_key}, content=archive) - fresh = await _selected(factory, fresh_key) - if action == 'project_kill': - new_leases = [e['lease'] for e in trace_events(root)[recovery_start:] - if e['project'] and e.get('lease')] - _require(new_leases and all(lease['epoch'] != leases[0]['epoch'] for lease in new_leases), - 'fresh execution did not use the restarted controller epoch') - _require(fresh.id != row.id and fresh.eligible is True, - 'fresh request did not repeat intake successfully after recovery') + leases = await _runtime_fault_evidence(root, start, action, control, row) + saved = await _recover_failed_source(client, factory, route, headers, token, content, archive, + key, result, row, task, assignment, root, action, leases) + accepted.append(saved) evidence.append({'case': action, 'run_id': row.id, 'machines': names, 'elapsed_seconds': round(time.monotonic() - began, 3), 'status': row.status, 'failure_code': row.terminal_json.get('infrastructure_failure_code'), - 'cleanup': drained}) + 'cleanup': drained, 'recovered_submission_id': saved['submission_id']}) + finally: + try: + await node_command(root, 'clear') + await node_command(root, 'drained') + finally: + await start_worker() + await _drain_source_trial_posts(factory, project.project_id, accepted, root) + evidence.extend(await _post_launch_trials(client, factory, project.project_id, manager, token, + archive, root, operator_token, stop_worker=stop_worker, start_worker=start_worker)) + return evidence + + +async def _post_launch_trials(client, factory, project_id, manager, token, archive, root, operator_token, + *, stop_worker, start_worker): + """POST retains native launch retries; PRE itself never retries a VM create.""" + from experiments.pilot04_external_checker_runtime.run_public_journey_probe import _complete_post + + evidence = [] + try: + for action, creates, executions in (('project_fail_once', 2, 1), ('project_fail_all', 3, 0)): + task, assignment = await _started_public_task(client, project_id=str(project_id), + manager_token=manager, contributor_token=token, source_ref='post-' + action) + route = f'/api/v1/tasks/{task}/submissions' + headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, + 'X-Submission-Summary': 'Completed task evidence.', + 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} + stop_worker() + try: + key = str(uuid4()) + receipt = await _source_request(client, route, headers, token, key, archive, 202) + _assert_current_pre(await _selected(factory, key)) + saved = await _observe_accepted_source(client, factory, task, assignment, token, archive, key, receipt) + start = len(trace_events(root)) + await node_command(root, action) + finally: + await start_worker() + if action == 'project_fail_once': + await _complete_post(factory, submission_id=saved['submission_id'], project_id=project_id, + recommendation='allow_review', deliver_completion=False) + names = assert_launches(root, start, creates=creates, executions=executions) + recovery = None + else: + async with factory() as session: + dispatch = await session.get(SubmissionDispatch, saved['submission_id']) + event_id = dispatch.evaluation_event_id + await _wait_outbox_acknowledged(factory, event_id, project_id) + names = assert_launches(root, start, creates=creates, executions=executions) + recovery_start = len(trace_events(root)) + successor, recovery = await retry_post_outage( + client, factory, saved['submission_id'], project_id, operator_token, root) + await _complete_post(factory, submission_id=saved['submission_id'], project_id=project_id, + recommendation='allow_review', deliver_completion=False, successor=successor) + assert_launches(root, recovery_start, creates=1, executions=1) + cleanup = await node_command(root, 'drained') + _require(cleanup['foreign_preserved'] and not any(cleanup['resources'].values()), + 'POST launch retry changed foreign resources or leaked owned resources') + evidence.append({'case': 'post_' + action, 'submission_id': saved['submission_id'], + 'machines': names, 'operator_recovery': recovery, 'cleanup': cleanup}) finally: await node_command(root, 'clear') await node_command(root, 'drained') diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 789b13b1c..9eed70bf2 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -1111,7 +1111,6 @@ async def run(database_url: str, image_reference: str, node_config: Path, env = api_environment() env.update({ "WORKSTREAM_DATABASE_URL": database_url, - "WORKSTREAM_PROBE_INTAKE_TRACE": str(root / "intake-trace.jsonl"), "WORKSTREAM_E2E_FLOW_ISSUER": "https://identity.flowresearch.tech", "WORKSTREAM_FLOW_AUTH_ISSUER": "https://identity.flowresearch.tech", "WORKSTREAM_CELERY_BROKER_URL": broker_url, @@ -1155,7 +1154,7 @@ async def run(database_url: str, image_reference: str, node_config: Path, _require(runtime_settings.external_runner_host is not None and runtime_settings.submission_execution_profile is not None, "supply explicit remote TLS runner and source execution profile before qualification") - _require_source_runtime_window(runtime_settings) + source_profile = _require_source_runtime_window(runtime_settings) _require_parser_socket(runtime_settings) for field in ( "artifact_store_backend", "artifact_s3_provider_profile", "artifact_s3_region", @@ -1221,7 +1220,7 @@ async def start_owned_worker() -> None: origin = f"http://127.0.0.1:{port}" api = _process([ sys.executable, "-m", "uvicorn", - "experiments.pilot04_external_checker_runtime.public_intake_observer:app", + "app.main:app", "--host", "127.0.0.1", "--port", str(port), "--log-level", "error", "--no-access-log", ], env=env, log=root / "api.log") @@ -1236,14 +1235,17 @@ async def start_owned_worker() -> None: "--schedule", str(root / "beat-schedule"), ], env=env, log=root / "beat.log") await _wait_beat_scan(factory, beat, scans_before_beat) - async with httpx.AsyncClient(base_url=origin, timeout=90) as client: + async with httpx.AsyncClient(base_url=origin, timeout=(source_profile.upload_total_seconds + + runtime_settings.external_checker_service_timeout_seconds)) as client: from experiments.pilot04_external_checker_runtime.public_intake_trials import public_intake_trials intake_trials = await public_intake_trials( - client, factory, env, root / "intake-trace.jsonl", root / "node-control") + client, factory, env, root / "node-control", + stop_worker=stop_owned_worker, start_worker=start_owned_worker) from experiments.pilot04_external_checker_runtime.public_runtime_trials import public_runtime_trials fault_root = root / "node-control" _require((fault_root / "supervisor-ready").exists(), "owned node supervisor is absent") - runtime_trials = await public_runtime_trials(client, factory, env, fault_root) + runtime_trials = await public_runtime_trials(client, factory, env, fault_root, + stop_worker=stop_owned_worker, start_worker=start_owned_worker, operator_token=_token(env, operator)) true = await _one_mode(client, factory, env, human_review_required=True, operator_id=operator.actor_profile_id) diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 0e34c4174..14d424064 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -359,21 +359,17 @@ async def exercise(): for spec in registered_specs: expected = _locked_spec(spec.phase, image).model_dump(mode='json') | capabilities[spec.phase] self.assertEqual(spec.model_dump(mode='json'), expected) - for count in (0, 1, 2): - selected = attachment.approval_attachments(count) - self.assertEqual(len(selected['pre_submit_attachments']), count) - self.assertEqual(len(selected['post_submit_attachments']), 1) - for phase, entries in (('pre_submit', selected['pre_submit_attachments']), - ('post_submit', selected['post_submit_attachments'])): - published = attachment.registered_images[phase] - for entry in entries: - self.assertEqual(entry['registry_entry_id'], str(published.registry_entry_id)) - self.assertEqual(entry['registry_entry_digest'], published.entry_digest) - self.assertEqual(entry['configuration'], {}) - self.assertEqual([item['requirement_id'] for item in selected['pre_submit_attachments']], - ['project.pre_submit.01', 'project.pre_submit.02'] if count == 2 else - (['project.pre_submit'] if count == 1 else [])) - self.assertEqual(selected['post_submit_attachments'][0]['requirement_id'], 'project.post_submit') + selected = attachment.approval_attachments(1) + for phase in ('pre_submit', 'post_submit'): + published = attachment.registered_images[phase] + self.assertEqual(selected[phase + '_attachments'], [{ + 'requirement_id': 'project.' + phase, + 'registry_entry_id': str(published.registry_entry_id), + 'registry_entry_digest': published.entry_digest, 'configuration': {}, + }]) + for count in (0, 2): + with self.subTest(count=count), self.assertRaisesRegex(RuntimeError, 'exactly one PRE'): + attachment.approval_attachments(count) def test_baseline_registration_refuses_unvalidated_cache_and_substituted_receipts(self): import httpx @@ -520,31 +516,220 @@ def test_hosted_cli_never_calls_local_launcher(self): probe.main() launch.assert_not_called() - def test_stalled_upload_refuses_early_cleanup_or_reset_deadline(self): - import time - from experiments.pilot04_external_checker_runtime import public_intake_trials as intake - - class StreamingClient: - async def post(self, route, *, headers, content): - async for _ in content: - pass - raise AssertionError('invalid expiry should fail before completing request') + def test_native_execution_refuses_early_cleanup_or_reset_deadline(self): + from experiments.pilot04_external_checker_runtime.public_runtime_trials import _require_original_runtime_expiry - expires = time.time_ns() // 1_000_000 + 1000 - prepared = {'operation': 'prepare_completed', 'name': 'exact-intake', 'project': False, - 'lease': {'epoch': 'original', 'expires_ms': expires}} + created = {'lease': {'epoch': 'original', 'expires_ms': 1000}} + _require_original_runtime_expiry(created, {'wall_ms': 1001, 'lease': created['lease']}) for deletion in ( - {'wall_ms': expires - 1, 'lease': prepared['lease']}, - {'wall_ms': expires + 1, 'lease': {'epoch': 'original', 'expires_ms': expires + 1000}}, - {'wall_ms': expires + 1, 'lease': {'epoch': 'restarted', 'expires_ms': expires}}, + {'wall_ms': 999, 'lease': created['lease']}, + {'wall_ms': 1001, 'lease': {'epoch': 'original', 'expires_ms': 2000}}, + {'wall_ms': 1001, 'lease': {'epoch': 'restarted', 'expires_ms': 1000}}, ): - with self.subTest(deletion=deletion), patch.object(intake, 'trace_events', return_value=[]), \ - patch.object(intake, '_native_event', new=AsyncMock(side_effect=[prepared, deletion])), \ - patch.object(intake, 'node_command', new=AsyncMock()) as cleanup: - with self.assertRaisesRegex(RuntimeError, 'original lease expiry'): - asyncio.run(intake._expire_upload(StreamingClient(), None, '/public', {}, 'token', b'zip', - 'task', Path('/owned/control'))) - cleanup.assert_not_awaited() + with self.subTest(deletion=deletion), self.assertRaisesRegex(RuntimeError, 'original lease expiry'): + _require_original_runtime_expiry(created, deletion) + + def test_selected_wait_failure_does_not_claim_aggregate_vm_expiry(self): + from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime + + lease = {'epoch': 'original', 'expires_ms': 120000} + events = [{'operation': 'create', 'project': True, 'lease': lease}, + {'operation': 'exec', 'project': True, 'wall_ms': 1000}, + {'operation': 'delete', 'project': True, 'wall_ms': 31000, 'lease': dict(lease)}] + row = SimpleNamespace(terminal_json={'infrastructure_failure_code': 'implementation_unavailable'}, + request_json={'policy': {'entries': [{'registry': {'resources': {'deadline_ms': 30000}}}]}}) + def check(): + return asyncio.run(runtime._runtime_fault_evidence(Path('/operator'), 0, 'project_wait_failure', None, row)) + with patch.object(runtime, 'trace_events', return_value=events): + check() # Cleanup before aggregate expiry is valid for this inner wait/failure vector. + for target, field, value in ((events[2], 'wall_ms', 30999), + (events[2]['lease'], 'expires_ms', 240000), + (row.terminal_json, 'infrastructure_failure_code', 'deadline_exceeded')): + original = target[field] + target[field] = value + try: + with self.subTest(field=field), self.assertRaises(RuntimeError): + check() + finally: + target[field] = original + + def test_pre_runtime_fault_vectors_use_single_vm_and_separate_tasks(self): + from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime + + operations = [] + row = SimpleNamespace(id='run', status='infrastructure_failed', terminal_json={'infrastructure_failure_code': 'failure'}) + async def source(client, route, headers, token, key, content, expected): + self.assertEqual(expected, 503) + operations.append(route) + return {'error': {'code': 'service_unavailable'}} + async def resume(): + operations.append('start') + async def accepted(*args): + return {'submission_id': 'submission-' + args[10]} + + project = SimpleNamespace(project_id=uuid4()) + with patch.object(runtime, '_public_project', new=AsyncMock(return_value=(project, None, 'manager', 'actor'))), \ + patch.object(runtime, '_started_public_task', new=AsyncMock(side_effect=[(f'task-{i}', f'assignment-{i}') for i in range(4)])), \ + patch.object(runtime, 'archive_with_modes', return_value=b'zip'), \ + patch.object(runtime, '_with_fixture_file', return_value=b'wait'), \ + patch.object(runtime, '_source_request', side_effect=source), \ + patch.object(runtime, '_selected', new=AsyncMock(return_value=row)), \ + patch.object(runtime, '_runtime_fault_evidence', new=AsyncMock(return_value=[])), \ + patch.object(runtime, '_recover_failed_source', new=AsyncMock(side_effect=accepted)), \ + patch.object(runtime, 'trace_events', return_value=[]), \ + patch.object(runtime, 'node_command', new=AsyncMock(return_value={'foreign_preserved': True, 'resources': {}})), \ + patch.object(runtime, 'assert_launches', return_value=['vm']) as launches, \ + patch.object(runtime, '_drain_source_trial_posts', new=AsyncMock()) as drain, \ + patch.object(runtime, '_post_launch_trials', new=AsyncMock(return_value=[])) as posts: + asyncio.run(runtime.public_runtime_trials(None, None, None, Path('/operator'), + stop_worker=lambda: operations.append('stop'), start_worker=resume, operator_token='operator')) + self.assertEqual(operations, ['stop'] + [f'/api/v1/tasks/task-{i}/submissions' for i in range(4)] + ['start']) + self.assertEqual([(call.kwargs['creates'], call.kwargs['executions']) for call in launches.call_args_list], + [(1, 0), (1, 0), (1, 1), (1, 1)]) + self.assertEqual(len(drain.await_args.args[2]), 4) + self.assertEqual(posts.await_args.args[7], 'operator') + + def test_post_native_retries_install_fault_after_t5_and_use_operator_recovery(self): + from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + operations = [] + async def submit(*args): + operations.append('submit') + self.assertEqual(args[6], 202) + return {'accepted': True} + async def finalized(*args): + operations.append('T5') + return {'submission_id': 'submission'} + async def node(root, action): + operations.append(action) + return {'foreign_preserved': True, 'resources': {}} + async def resume(): + operations.append('start') + async def complete(*args, **kwargs): + operations.append('POST') + async def retry(*args): + self.assertEqual(args[4], 'operator') + operations.append('operator_retry') + return object(), {'receipt_id': 'receipt'} + session = AsyncMock() + session.__aenter__.return_value = session + session.get.return_value = SimpleNamespace(evaluation_event_id='event') + with patch.object(runtime, '_started_public_task', new=AsyncMock(side_effect=[('task1', 'assignment1'), ('task2', 'assignment2')])), \ + patch.object(runtime, '_source_request', side_effect=submit), \ + patch.object(runtime, '_selected', new=AsyncMock()), patch.object(runtime, '_assert_current_pre'), \ + patch.object(runtime, '_observe_accepted_source', side_effect=finalized), \ + patch.object(runtime, 'node_command', side_effect=node), patch.object(runtime, 'trace_events', return_value=[]), \ + patch.object(runtime, 'assert_launches', return_value=['vm']) as launches, \ + patch.object(runtime, '_wait_outbox_acknowledged', new=AsyncMock()), \ + patch.object(runtime, 'retry_post_outage', side_effect=retry), \ + patch.object(probe, '_complete_post', side_effect=complete): + asyncio.run(runtime._post_launch_trials(None, lambda: session, 'project', 'manager', 'actor', b'zip', + Path('/operator'), 'operator', stop_worker=lambda: operations.append('stop'), start_worker=resume)) + self.assertEqual(operations, ['stop', 'submit', 'T5', 'project_fail_once', 'start', 'POST', 'drained', + 'stop', 'submit', 'T5', 'project_fail_all', 'start', 'operator_retry', 'POST', 'drained', 'clear', 'drained']) + self.assertEqual([(call.kwargs['creates'], call.kwargs['executions']) for call in launches.call_args_list], + [(2, 1), (3, 0), (1, 1)]) + + def test_source_pre_retains_default_stop_and_exact_one_native_member(self): + from experiments.pilot04_external_checker_runtime.public_intake_trials import _assert_current_pre + + member = {'order': 0, 'requirement_id': 'project.pre_submit', 'request_digest': 'request', + 'result': {'verdict': 'passed', 'request_digest': 'request', 'findings': []}, + 'isolation': {'runtime': 'smolvm', 'isolation_mode': 'smol-microvm'}} + execution = {'required_external_count': 1, 'eligible': True, + 'workstream_default': {'eligible': True, 'checks': []}, 'external_members': [member]} + def row(value): + return SimpleNamespace(status='completed', terminal_json={'execution': value}) + + _assert_current_pre(row(execution)) + secret = copy.deepcopy(execution) + secret.update(eligible=False, external_members=[], workstream_default={'eligible': False, + 'checks': [{'status': 'failed', 'failure_code': 'high_confidence_secret_detected'}]}) + _assert_current_pre(row(secret), failure='secret') + project = copy.deepcopy(execution) + project['eligible'] = False + project['external_members'][0]['result'].update(verdict='failed', findings=[{'code': 'probe.project_rule_failed'}]) + _assert_current_pre(row(project), failure='project') + for field, value in (('required_external_count', 0), ('external_members', []), ('eligible', False)): + invalid = copy.deepcopy(execution) + invalid[field] = value + with self.subTest(field=field), self.assertRaises(RuntimeError): + _assert_current_pre(row(invalid)) + for field, value in (('order', 1), ('requirement_id', 'foreign'), ('request_digest', 'foreign')): + invalid = copy.deepcopy(execution) + invalid['external_members'][0][field] = value + with self.subTest(field=field), self.assertRaises(RuntimeError): + _assert_current_pre(row(invalid)) + secret['external_members'] = [member] + with self.assertRaisesRegex(RuntimeError, 'default blocker'): + _assert_current_pre(row(secret), failure='secret') + + def test_local_approval_uses_exact_registry_entries_in_root_transaction(self): + from sqlalchemy.ext.asyncio import async_sessionmaker + from app.core.identifiers import new_record_id + from app.modules.checkers import external_registry as registry + from experiments.pilot04_external_checker_runtime.public_guide_setup import _local_approval_attachments + from tests.checkers.external.support import registry_spec, post_registry_spec + + entries = [SimpleNamespace(capability_id=spec.capability_id, capability_version=spec.capability_version, + phase=spec.phase, registry_entry_id=new_record_id(), entry_digest='sha256:' + digit * 64) + for spec, digit in ((registry_spec('pre_submit'), 'a'), (post_registry_spec(), 'b'))] + repository = AsyncMock() + repository.all_entries.return_value = entries + repository.by_exact_id.side_effect = lambda key: next(entry for entry in entries if entry.registry_entry_id == key) + with patch.object(registry, 'ExternalCheckerRegistryRepository', return_value=repository), \ + patch.object(registry, '_row_entry', side_effect=lambda row: row): + result = asyncio.run(_local_approval_attachments(async_sessionmaker())) + for entry in entries: + self.assertEqual(result[entry.phase + '_attachments'], [{ + 'requirement_id': 'project.' + entry.phase, + 'registry_entry_id': str(entry.registry_entry_id), + 'registry_entry_digest': entry.entry_digest, 'configuration': {}, + }]) + repository.all_entries.return_value = entries[:1] + with self.assertRaisesRegex(AssertionError, 'absent or ambiguous'): + asyncio.run(_local_approval_attachments(async_sessionmaker())) + repository.all_entries.return_value = entries + [entries[0]] + with self.assertRaisesRegex(AssertionError, 'absent or ambiguous'): + asyncio.run(_local_approval_attachments(async_sessionmaker())) + + def test_current_guide_refuses_zero_or_multiple_pre_before_setup(self): + from experiments.pilot04_external_checker_runtime.public_guide_setup import public_guide_setup + + for count in (0, 2): + with self.subTest(count=count), self.assertRaisesRegex(ValueError, 'exactly one PRE'): + asyncio.run(public_guide_setup(None, None, True, None, None, pre_requirements=count)) + + def test_source_failure_preserves_exact_charge_and_releases_only_task_pointer(self): + from experiments.pilot04_external_checker_runtime import public_intake_trials as intake + + operation = SimpleNamespace(id='source', task_id='task', acceptance_receipt=None, + finalized_submission_id=None, finalization_event_id=None, selected_pre_submit_run_id='run', + failure_code='submission_infrastructure_unavailable') + charge = SimpleNamespace(state='sealed', accounted_bytes=42) + task = SimpleNamespace(status='in_progress', active_submission_operation_id=None) + session = AsyncMock() + session.__aenter__.return_value = session + session.get.side_effect = lambda model, key: charge if key == 'source' else task + async def exercise(): + return await intake._assert_source_failure(lambda: session, 'task', 'key', 42, sealed=True, + code='submission_infrastructure_unavailable') + + with patch.object(intake, '_wait_source_state', new=AsyncMock(return_value=operation)), \ + patch.object(intake, '_assert_no_submission_after_intake_failure', new=AsyncMock()) as no_product: + self.assertIs(asyncio.run(exercise()), operation) + no_product.assert_awaited_once_with(unittest.mock.ANY, 'task', 'run') + for target, field, value in ((charge, 'accounted_bytes', 0), (charge, 'state', 'released'), + (task, 'active_submission_operation_id', 'foreign'), (task, 'status', 'ready'), + (operation, 'acceptance_receipt', {'accepted': True})): + original = getattr(target, field) + setattr(target, field, value) + try: + with self.subTest(field=field, value=value), self.assertRaises(RuntimeError): + asyncio.run(exercise()) + finally: + setattr(target, field, original) if __name__ == '__main__': From 83ee3bacb471f0b4de63fe7bd9ae45f31eeef3eb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:27:38 +0100 Subject: [PATCH 292/513] Version isolated submission source bucket before CLI journey --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 ++++ .../test_journey_bucket_versioning.py | 80 +++++++++++++++++++ cli/tests/journey/bootstrap.py | 7 +- cli/tests/journey/runtime.py | 29 +++++++ 4 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 cli/tests/integration/test_journey_bucket_versioning.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6c87d06b9..7f4a92d9f 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9638,3 +9638,17 @@ probe is controlled in-memory evidence only. Actual two-host fault transport, aggregate VM expiry, native PRE source/execution cancellation and real native fault execution remain mandatory open qualification, without API-side KVM or shared runner paths. + +A later diagnostic run passed guide activation and reached the first public +raw-ZIP submission, then failed before a source upload was begun. A bounded +exception-class/line probe located `ArtifactConfigurationError` at the +production S3 adapter's required bucket-versioning check; the public operation +reported failed infrastructure. The canonical isolation launcher creates a +fresh bucket without versioning because other test lanes configure it in +their own fixtures. The CLI journey now validates that its runner-owned bucket +and prefix match, enables versioning on only that bucket, and reads the state +back before starting the API or workers. Four focused tests cover the exact +bucket call, foreign bucket/prefix denial and failed readback. The production +versioning guard is unchanged. The diagnostic run's database and bucket +cleanup completed; it did not reach native PRE or POST. Temporary probe code +was removed before the next qualification attempt. diff --git a/cli/tests/integration/test_journey_bucket_versioning.py b/cli/tests/integration/test_journey_bucket_versioning.py new file mode 100644 index 000000000..08f502a60 --- /dev/null +++ b/cli/tests/integration/test_journey_bucket_versioning.py @@ -0,0 +1,80 @@ +"""Source uploads require versioning on the launcher-owned isolated bucket.""" + +from contextlib import asynccontextmanager +import importlib.util +from pathlib import Path + +import pytest + + +PATH = Path(__file__).resolve().parents[1] / "journey/runtime.py" +SPEC = importlib.util.spec_from_file_location("journey_runtime_bucket", PATH) +assert SPEC is not None and SPEC.loader is not None +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + +SUFFIX = "a1b2c3d4e5f6" +BUCKET = f"workstream-ci-cli-full-journey-{SUFFIX}" +ENVIRONMENT = { + "WORKSTREAM_TEST_MINIO_BUCKET": BUCKET, + "WORKSTREAM_TEST_MINIO_PREFIX": f"ci/cli_full_journey/{SUFFIX}", + "WORKSTREAM_TEST_MINIO_ENDPOINT": "http://127.0.0.1:59044", +} + + +class VersioningClient: + def __init__(self, status="Enabled"): + self.status = status + self.calls = [] + + async def put_bucket_versioning(self, **arguments): + self.calls.append(("put", arguments)) + + async def get_bucket_versioning(self, **arguments): + self.calls.append(("get", arguments)) + return {"Status": self.status} + + +def factory_for(client): + @asynccontextmanager + async def factory(endpoint): + assert endpoint == ENVIRONMENT["WORKSTREAM_TEST_MINIO_ENDPOINT"] + yield client + + return factory + + +def test_journey_enables_and_reads_back_exact_owned_source_bucket(): + client = VersioningClient() + MODULE.prepare_versioned_source_bucket( + ENVIRONMENT, client_factory=factory_for(client) + ) + assert client.calls == [ + ("put", {"Bucket": BUCKET, "VersioningConfiguration": {"Status": "Enabled"}}), + ("get", {"Bucket": BUCKET}), + ] + + +@pytest.mark.parametrize( + "change", + [ + {"WORKSTREAM_TEST_MINIO_BUCKET": "workstream-artifacts"}, + {"WORKSTREAM_TEST_MINIO_PREFIX": "ci/cli_full_journey/other"}, + ], +) +def test_journey_refuses_foreign_bucket_before_provider_call(change): + client = VersioningClient() + with pytest.raises(RuntimeError, match="runner-owned"): + MODULE.prepare_versioned_source_bucket( + ENVIRONMENT | change, client_factory=factory_for(client) + ) + assert client.calls == [] + + +def test_journey_refuses_missing_versioning_after_readback(): + client = VersioningClient(status=None) + with pytest.raises(RuntimeError, match="versioning"): + MODULE.prepare_versioned_source_bucket( + ENVIRONMENT, client_factory=factory_for(client) + ) + assert [name for name, _ in client.calls] == ["put", "get"] diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py index 6bcfdc15f..727f9e2ff 100644 --- a/cli/tests/journey/bootstrap.py +++ b/cli/tests/journey/bootstrap.py @@ -21,7 +21,11 @@ from client import JourneyClient from public_setup import configure_guide, publish_unpaid_terms, approve_and_activate -from runtime import durable_runtime, load_journey_configuration +from runtime import ( + durable_runtime, + load_journey_configuration, + prepare_versioned_source_bucket, +) from task_work import claim_and_read, create_claimed_task, issue_submitter from submission_work import submit_and_observe, observe_review_pending from artifact_work import inspect_submission_custody @@ -121,6 +125,7 @@ def main(): through_setup = os.environ.get("WORKSTREAM_CLI_JOURNEY_SETUP") == "1" if through_setup: registries = load_journey_configuration(environment) + prepare_versioned_source_bucket(environment) start_workers = stack.enter_context( durable_runtime(ROOT, directory, environment) ) diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index d3d589861..eb2fcdb8a 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -1,5 +1,6 @@ """Owned Redis and dedicated workers for the remote-runner CLI drill.""" +import asyncio from contextlib import contextmanager import json import os @@ -167,6 +168,34 @@ def load_journey_configuration(environment: dict[str, str]) -> dict[str, Path]: return registry_files +def prepare_versioned_source_bucket( + environment: dict[str, str], *, client_factory=None +): + """Enable required source versioning on this runner-owned isolated bucket.""" + bucket = environment.get("WORKSTREAM_TEST_MINIO_BUCKET", "") + prefix = environment.get("WORKSTREAM_TEST_MINIO_PREFIX", "") + match = re.fullmatch(r"workstream-ci-cli-full-journey-([a-f0-9]{12})", bucket) + if match is None or prefix != f"ci/cli_full_journey/{match.group(1)}": + raise RuntimeError("journey source bucket is not runner-owned") + if client_factory is None: + from run_isolated_tests import _minio_client + + client_factory = _minio_client + + async def enable(): + async with client_factory( + environment["WORKSTREAM_TEST_MINIO_ENDPOINT"] + ) as client: + await client.put_bucket_versioning( + Bucket=bucket, VersioningConfiguration={"Status": "Enabled"} + ) + state = await client.get_bucket_versioning(Bucket=bucket) + if state.get("Status") != "Enabled": + raise RuntimeError("journey source bucket versioning is not enabled") + + asyncio.run(enable()) + + @contextmanager def durable_runtime(root: Path, directory: Path, environment: dict[str, str]): """Start only owned local broker/worker groups; runner lives outside this host.""" From cd7dac84c6616b0139417d8683665e2c784dcc7d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:43:47 +0100 Subject: [PATCH 293/513] Align task read and retained migration assertions with source custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 32 +++++++++++++++++++ .../submission_dispatch/test_migration.py | 2 +- backend/tests/tasks/test_project_display.py | 8 +++-- backend/tests/tasks/test_task_detail.py | 7 ++-- .../tests/test_checker_evidence_migrations.py | 4 +++ backend/tests/test_tasks.py | 4 ++- 6 files changed, 50 insertions(+), 7 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 7f4a92d9f..2af925506 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9652,3 +9652,35 @@ bucket call, foreign bucket/prefix denial and failed readback. The production versioning guard is unchanged. The diagnostic run's database and bucket cleanup completed; it did not reach native PRE or POST. Temporary probe code was removed before the next qualification attempt. + +### Align retained migration and task-read test expectations + +CI at5c29 exposed stale expectations in task detail, locked policy display and +retained checker-evidence migration tests. Allowed scope: tests/tasks/test_task_detail.py, +tests/tasks/test_project_display.py, tests/test_tasks.py and +tests/test_checker_evidence_migrations.py under backend, plus this record. +Preserve exact audience fields, locked successor isolation and byte-identical +historical columns; acknowledge the explicit nullable source_operation_id added +to historical replicas and assert that it remains null. Use distinct valid +single-image policies for the successor comparison rather than empty selection. +No product, migration, authorization or data changes. Low-risk test-only repair; +verify exact failed cases through the isolated PostgreSQL runner after the live +journey releases the heavy slot, plus Ruff/diff. Root reviews against actual +DTOs/migration and named CI failures; human review focus is preservation of the +original historical/audience assertions rather than broader ignored snapshots. + +The same additive-column mismatch also affects +backend/tests/tasks/submission_dispatch/test_migration.py; include that named +retained-data test in scope, asserting source_operation_id is null alongside +its existing exact old-column preservation. + +The isolated PostgreSQL replay passed all6 database cases in the seven-case +run, including both historical migrations, both audience projections, guide +successor lock preservation and worker/manager context. The remaining pure +contract assertion expected the generic error for the new pending-operation +field; its exact field-specific message is now checked. The focused pure rerun +passed1/1 in18.57s. Combined-run log /tmp/submission-task-read-migration.log +(6pass/1initialfailure,369.60s); final pure log +/tmp/submission-task-detail-contract.log. Isolated schema0090 database cleanup +is confirmed in /tmp/submission-task-read-migration.json. Pinned Ruff0.15.22 +and diff checks pass. No production behavior or retained row changed. diff --git a/backend/tests/tasks/submission_dispatch/test_migration.py b/backend/tests/tasks/submission_dispatch/test_migration.py index 0127d4660..19212de6c 100644 --- a/backend/tests/tasks/submission_dispatch/test_migration.py +++ b/backend/tests/tasks/submission_dispatch/test_migration.py @@ -49,7 +49,7 @@ async def snapshot(): "selected_post_submit_policy_sha256", "selected_post_submit_policy_body", }, "submission_bundle_admissions": { - "checker_remediation_manifest_id", "selected_pre_submit_run_id", + "checker_remediation_manifest_id", "selected_pre_submit_run_id", "source_operation_id", "guide_id", "guide_version", "source_snapshot_id", "source_snapshot_sha256", "effective_policy_id", "effective_policy_sha256", "pre_submit_policy_id", "pre_submit_policy_sha256", "effective_plan_sha256", "selected_rules_sha256", diff --git a/backend/tests/tasks/test_project_display.py b/backend/tests/tasks/test_project_display.py index 448b716a3..c35e6470a 100644 --- a/backend/tests/tasks/test_project_display.py +++ b/backend/tests/tasks/test_project_display.py @@ -203,7 +203,7 @@ async def test_task_display_survives_guide_successor_for_contributor_and_manager set_dev_actor(monkeypatch, roles="worker", subject="worker-one") summary_key = "locked_post_submit_checker_policy_body_summary" original_summary = original_locked["management"][summary_key] - assert original_summary["required_checkers"] == [] + assert original_summary["required_checkers"] == [post_registry_spec().capability_id] requirements_url = f"/api/v1/tasks/{task['id']}/submission-requirements" first_requirements = await task_client.get(requirements_url, headers=auth_headers()) assert first_requirements.status_code == 200, first_requirements.text @@ -224,7 +224,9 @@ async def test_task_display_survives_guide_successor_for_contributor_and_manager await create_policy_bundle_for_guide( task_client, project["id"], successor.json()["id"], task_artifact_proposal().model_copy(update={"required_artifacts": ("v2-answer.md",)}), - post_submit_registry_spec=post_registry_spec(), + post_submit_registry_spec=post_registry_spec().model_copy( + update={"capability_id": "acme.successor_archive"} + ), ) await seed_active_guide_for_downstream_test( db_session.get_session_factory(), project_id=project["id"], guide_id=successor.json()["id"], @@ -241,7 +243,7 @@ async def test_task_display_survives_guide_successor_for_contributor_and_manager PostSubmitCheckerPolicy.guide_id == active.id, )) required = [entry["registry"]["capability_id"] for entry in successor_policy.policy_body["entries"]] - assert required == [post_registry_spec().capability_id] + assert required == ["acme.successor_archive"] assert required != original_summary["required_checkers"] effective = await session.scalar(select(EffectiveProjectSubmissionArtifactPolicy).where( EffectiveProjectSubmissionArtifactPolicy.guide_id == active.id, diff --git a/backend/tests/tasks/test_task_detail.py b/backend/tests/tasks/test_task_detail.py index 6fadbd59e..2f922348f 100644 --- a/backend/tests/tasks/test_task_detail.py +++ b/backend/tests/tasks/test_task_detail.py @@ -42,7 +42,7 @@ def _detail_fields(method): - return COMMON | {"last_assignment_outcome"} | ( + return COMMON | {"last_assignment_outcome", "pending_submission_operation"} | ( MANAGEMENT | {"revision_context"} if method == READS[1] else {"compensation"} ) @@ -115,7 +115,9 @@ def test_task_detail_contracts(): ) assert replace(item, last_assignment_outcome=terminal).last_assignment_outcome == terminal for field, value in asdict(item).items(): - with pytest.raises(ValueError, match="facts are invalid"): + message = ("pending submission operation is invalid" + if field == "pending_submission_operation" else "facts are invalid") + with pytest.raises(ValueError, match=message): replace(item, **{field: []}) for field in ("created_at", "updated_at", "deadline_at"): with pytest.raises(ValueError, match="facts are invalid"): @@ -273,6 +275,7 @@ async def test_task_detail_projection(task_client, method): expected |= dict(task_id=UUID(row.id), project_id=UUID(row.project_id), skill_tags=tuple(row.skill_tags)) fields = _detail_fields(method) expected["last_assignment_outcome"] = None + expected["pending_submission_operation"] = None if method == READS[1]: expected |= {name: getattr(row, name) for name in MANAGEMENT} expected["revision_context"] = None diff --git a/backend/tests/test_checker_evidence_migrations.py b/backend/tests/test_checker_evidence_migrations.py index ada3c8499..df98206de 100644 --- a/backend/tests/test_checker_evidence_migrations.py +++ b/backend/tests/test_checker_evidence_migrations.py @@ -110,6 +110,7 @@ async def _retained_rows(database_url: str) -> dict[str, str]: "checker_runs": "input_context_custody", "artifact_put_attempts": "checker_trial_evidence_id", "artifact_operation_receipts": "checker_trial_evidence_id", + "artifact_replicas": "source_operation_id", }.get(table) projection = "to_jsonb(value)" + (f" - '{excluded}'" if excluded else "") result[table] = await connection.fetchval( @@ -147,6 +148,9 @@ async def _assert_head_lineage_projection( ) == "completed" ) + assert await connection.fetchval( + "select count(*) from artifact_replicas where source_operation_id is not null" + ) == 0 assert ( await connection.fetchval( "select count(*) from checker_runs where input_context_custody is not null" diff --git a/backend/tests/test_tasks.py b/backend/tests/test_tasks.py index 367398941..9d17511fc 100644 --- a/backend/tests/test_tasks.py +++ b/backend/tests/test_tasks.py @@ -1693,7 +1693,9 @@ async def test_task_context_apis_return_worker_requirements_and_operator_provena ) assert locked_body["locked_pre_submit_checker_bundle_hash"].startswith("sha256:") assert locked_body["locked_post_submit_checker_policy_hash"].startswith("sha256:") - assert locked_body["locked_post_submit_checker_policy_body_summary"]["required_checkers"] == [] + assert locked_body["locked_post_submit_checker_policy_body_summary"]["required_checkers"] == [ + post_registry_spec().capability_id + ] async def test_ready_worker_work_context_omits_private_task_source_fields( From 9442c682951acee5fd86094c88344a9cd8dd24c2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:36:50 +0100 Subject: [PATCH 294/513] Allow public progress reads across T5 commit --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 ++++ .../test_journey_progress_identity.py | 87 +++++++++++++++++++ cli/tests/journey/submission_work.py | 30 ++++++- 3 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 cli/tests/integration/test_journey_progress_identity.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2af925506..700c45145 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9684,3 +9684,18 @@ passed1/1 in18.57s. Combined-run log /tmp/submission-task-read-migration.log /tmp/submission-task-detail-contract.log. Isolated schema0090 database cleanup is confirmed in /tmp/submission-task-read-migration.json. Pinned Ruff0.15.22 and diff checks pass. No production behavior or retained row changed. + +The first clean run with that bucket setup passed the real pre-submit +negative: the missing-summary ZIP produced `pre_submission_checker_failed`, +the public operation was rejected, and no Submission appeared. The correct +ZIP then received T4 acceptance and exact command replay. Its subsequent +public progress reads crossed the T5 commit: the key selector read +`finalization_pending`, while the operation-ID selector read +`finalized/evaluation_pending`. Both named the same durable operation. The +journey had incorrectly required the entire two responses to be equal. It now +compares immutable operation, task, assignment, key, acceptance time and PRE +feedback, refuses state regression and any changed populated Submission +identity, and permits the forward commit between separate reads. Eight focused +tests cover that observed transition and identity substitutions. The run's +isolated database and bucket were cleaned; the automatic POST outcome was not +yet observed in this run. diff --git a/cli/tests/integration/test_journey_progress_identity.py b/cli/tests/integration/test_journey_progress_identity.py new file mode 100644 index 000000000..8d4f83dfa --- /dev/null +++ b/cli/tests/integration/test_journey_progress_identity.py @@ -0,0 +1,87 @@ +"""Two public operation reads may straddle the T5 commit.""" + +import importlib.util +from pathlib import Path +import sys +from types import SimpleNamespace + +import pytest + + +PATH = Path(__file__).resolve().parents[1] / "journey/submission_work.py" +PENDING = { + "operation_id": "operation-1", + "task_id": "task-1", + "assignment_id": "assignment-1", + "idempotency_key": "key-1", + "accepted_at": "accepted-once", + "task_status_at_acceptance": "evaluation_pending", + "pre_submission_results": [{"checker_name": "pilot-pre", "status": "passed"}], + "operation_state": "finalization_pending", + "processing_stage": "finalization_pending", + "submission_id": None, + "submission_version": None, + "evaluation_request_id": None, +} +FINALIZED = PENDING | { + "operation_state": "finalized", + "processing_stage": "evaluation_pending", + "submission_id": "submission-1", + "submission_version": 1, + "evaluation_request_id": "evaluation-1", +} + + +@pytest.fixture +def progress(monkeypatch): + monkeypatch.setitem( + sys.modules, "task_work", SimpleNamespace(create_claimed_task=None) + ) + monkeypatch.setitem( + sys.modules, "source_audit", SimpleNamespace(audit_accepted_source=None) + ) + spec = importlib.util.spec_from_file_location("journey_progress_identity", PATH) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module._progress + + +class Client: + def __init__(self, by_key, by_id): + self.reads = [by_key, by_id] + self.commands = [] + + def call(self, _token, *arguments): + self.commands.append(arguments) + return self.reads.pop(0) + + +def test_key_then_id_read_may_straddle_finalization_commit(progress): + client = Client(PENDING, FINALIZED) + assert progress(client, "token", "task-1", "key-1", "operation-1") == PENDING + assert client.commands[0][-2:] == ("--idempotency-key", "key-1") + assert client.commands[1][-2:] == ("--operation-id", "operation-1") + + +@pytest.mark.parametrize( + "field,value", + [ + ("operation_id", "other-operation"), + ("task_id", "other-task"), + ("assignment_id", "other-assignment"), + ("idempotency_key", "other-key"), + ("pre_submission_results", []), + ("submission_id", "other-submission"), + ], +) +def test_key_and_id_reads_reject_identity_substitution(progress, field, value): + client = Client(FINALIZED, FINALIZED | {field: value}) + with pytest.raises(AssertionError, match="durable identity"): + progress(client, "token", "task-1", "key-1", "operation-1") + + +def test_key_and_id_reads_reject_state_regression(progress): + client = Client(FINALIZED, PENDING) + with pytest.raises(AssertionError, match="durable identity"): + progress(client, "token", "task-1", "key-1", "operation-1") diff --git a/cli/tests/journey/submission_work.py b/cli/tests/journey/submission_work.py index ce0448c10..cedabe6cb 100644 --- a/cli/tests/journey/submission_work.py +++ b/cli/tests/journey/submission_work.py @@ -62,8 +62,34 @@ def _progress(client, token, task_id, key, operation_id=None): "--operation-id", operation_id, ) - if by_key != by_id or by_id["operation_id"] != operation_id: - raise AssertionError("key and operation reads differ") + immutable = ( + "operation_id", + "task_id", + "assignment_id", + "idempotency_key", + "accepted_at", + "task_status_at_acceptance", + "pre_submission_results", + ) + if ( + by_key["operation_id"] != operation_id + or any(by_key[field] != by_id[field] for field in immutable) + or by_key["operation_state"] not in {"finalization_pending", "finalized"} + or by_id["operation_state"] not in {"finalization_pending", "finalized"} + or ( + by_key["operation_state"] == "finalized" + and by_id["operation_state"] != "finalized" + ) + or any( + by_key[field] is not None and by_key[field] != by_id[field] + for field in ( + "submission_id", + "submission_version", + "evaluation_request_id", + ) + ) + ): + raise AssertionError("key and operation reads differ in durable identity") return by_key From 61f23700259dfb7a7ea2cc39cd5b22daccb344d3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:44:44 +0100 Subject: [PATCH 295/513] test(submission): align shared fixtures with source-first PRE --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 12 + backend/scripts/test_lane_catalogue.py | 1 - .../external/test_selected_post_submit.py | 17 ++ .../test_selected_pre_submit_service.py | 225 ------------------ .../contributor_reads/test_projection.py | 25 +- backend/tests/test_ci_lane_catalogue.py | 9 +- 6 files changed, 50 insertions(+), 239 deletions(-) delete mode 100644 backend/tests/checkers/external/test_selected_pre_submit_service.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 700c45145..7f7289c77 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9699,3 +9699,15 @@ identity, and permits the forward commit between separate reads. Eight focused tests cover that observed transition and identity substitutions. The run's isolated database and bucket were cleaned; the automatic POST outcome was not yet observed in this run. + +### Repair shared current-source test constructors after the single-flow cutover + +Intent: restore the current POST grant and PRE projection test fixtures without reintroducing prepared-bundle PRE APIs. This is a test and catalogue change only; production source custody, AUTH, SQL, runtime, and CI gate policy stay unchanged. The superseded `test_selected_pre_submit_service.py` invokes a removed materialization constructor and `recover_expired` method. Its claim/commit/finalize behavior is covered by the source-backed real PostgreSQL cases in `test_submission_pre_source.py`; expired lease no-I/O and cancellation drainage are covered by `test_runtime.py`, and TASK-first expired-lease custody by `test_selected_pre_submit_coordination.py`. + +Allowed files: `backend/tests/checkers/external/test_selected_post_submit.py`, `backend/tests/contributor_reads/test_projection.py`, the obsolete PRE service test module and, if needed, those named current-source proof modules; `backend/scripts/test_lane_catalogue.py`, `backend/tests/test_ci_lane_catalogue.py`, and this record. Remove the obsolete test and its exact catalogue membership; update the independent fingerprint from the resulting catalogue. No compatibility constructor, relaxed grant source, skipped test, altered production contract, new default, or lowered test gate is allowed. + +Acceptance: POST mock execution receives an explicit typed source capability without reading project bytes; contributor projection uses structurally valid source-first PRE results and retains eligible and blocked findings and every custody-state assertion; current-source claim/finalize, expiry no-I/O, and cancellation proofs remain selected. Verify focused pure tests and catalogue/inventory contracts, then run only affected real cases when the shared resource slot is free. Risk: a fixture could become vacuous or the deleted PRE tests could leave an interruption or expiry gap. CI integrity and architecture/security reviews should compare those precise assertions. Human review focus is the evidence map for the deleted tests and the independent catalogue count/hash; this does not claim full CI or native qualification. + +Exact retained proof map: `tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read` owns real source claim, short committed AUTH roots, finalization and failure retention. `tests/checkers/external/test_runtime.py::test_single_pre_expired_lease_does_not_open_source_or_runtime` rejects source/runtime access after lease expiry, and `test_single_pre_cancellation_closes_source_and_transport` owns interruption drainage. `tests/checkers/external/test_selected_pre_submit_coordination.py::test_selected_pre_expired_lease_read_keeps_task_first_custody` owns expired-lease TASK lock order; the adjacent authority-digest test binds the distinct deadline outcome. `tests/artifacts/test_submission_intake_custody.py::test_expiry_can_only_abandon_and_cannot_resume` owns the current required operation-level fence, charge retention, and fresh-key recovery; `test_submission_intake_admission.py::test_t4_and_expiry_serialize_both_winner_orders` owns accepted handoff versus abandonment. Spec section 16 requires the operation to terminalize/fence and forbids PRE worker continuation; it does not require an orphaned selected-run row itself to gain a synthetic deadline terminal. Those are existing current-source tests, not newly executed PostgreSQL/native proof in this commit. The removed test module's synthetic `recover_expired` method did not exist on the current service, so retaining it would create false API coverage. A selected run left `running` after a crashed foreground is a retained observation, not an adopted recovery path or a claim of selected-run terminalization. + +Focused final pure execution: 111 passed and two unrelated real-PostgreSQL POST cases deselected in 14.01 seconds, exit 0. Initial run had 52 passed, two PostgreSQL setup errors because no isolated database URL was provided, and the independent project fingerprint failed before its count/hash update; it was not credited as a pass. The two deselected cases use `material_fixture` and `live_executor`, not the edited fake source-grant constructors. The current catalogue has 257 project modules with independently recomputed family and lane ownership hashes. This is affected pure test custody, not a full backend CI pass. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 605e83c11..0a9d217ac 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -565,7 +565,6 @@ class TestLane: "tests/checkers/external/test_selected_pre_submit.py", "tests/checkers/external/test_selected_intake_lifecycle.py", "tests/checkers/external/test_selected_pre_submit_coordination.py", - "tests/checkers/external/test_selected_pre_submit_service.py", "tests/checkers/execution/test_execution.py", "tests/checkers/execution/test_completion_evidence.py", "tests/checkers/execution/test_coordination.py", diff --git a/backend/tests/checkers/external/test_selected_post_submit.py b/backend/tests/checkers/external/test_selected_post_submit.py index 0f33b0912..b09160d09 100644 --- a/backend/tests/checkers/external/test_selected_post_submit.py +++ b/backend/tests/checkers/external/test_selected_post_submit.py @@ -165,6 +165,21 @@ def _request(identity, policy): ) +class _UnopenedMaterialSource: + """These processor tests observe a grant, not its ART-backed file stream.""" + + @property + def manifest(self): + raise AssertionError("mock execution must not read project material") + + @property + def files(self): + raise AssertionError("mock execution must not read project material") + + def open_file(self, _item): + raise AssertionError("mock execution must not read project material") + + class _MaterialView: def __init__(self, material, *, events=None, cleanup_failure=False) -> None: self.external_checker_material = material @@ -184,6 +199,7 @@ def external_checker_grant(self, request): yield ExternalCheckerMaterialGrant( grant_id="extract_" + "a" * 32, binding_digest="sha256:" + "b" * 64, + source=_UnopenedMaterialSource(), ) finally: if self.events is not None: @@ -687,6 +703,7 @@ def external_checker_grant(self, request): grant = ExternalCheckerMaterialGrant( grant_id="extract_" + uuid4().hex, binding_digest=request.request_digest, + source=_UnopenedMaterialSource(), ) self.grants.append(grant) yield grant diff --git a/backend/tests/checkers/external/test_selected_pre_submit_service.py b/backend/tests/checkers/external/test_selected_pre_submit_service.py deleted file mode 100644 index efd693a4c..000000000 --- a/backend/tests/checkers/external/test_selected_pre_submit_service.py +++ /dev/null @@ -1,225 +0,0 @@ -"""Selected PRE work stays outside short claim and finalization roots.""" - -from __future__ import annotations - -from app.adapters.artifacts import selected_pre_submit_source_contracts - -from contextlib import asynccontextmanager -from datetime import UTC, datetime, timedelta -from types import SimpleNamespace - -import pytest - -from app.core.identifiers import new_record_id -from app.modules.artifacts.selected_pre_submit_execution import ( - SelectedPreSubmitExecutionService, -) -from app.modules.checkers.api.default_checker import ( - WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, -) -from app.modules.checkers.api.selected_pre_submit import ( - SelectedPreSubmitAuthorityEvidence, - SelectedPreSubmitExecuteFacts, - SelectedPreSubmitFinalizeFacts, - SelectedPreSubmitInfrastructureUnavailable, - SelectedPreSubmitLeaseFacts, - SelectedPreSubmitReservationFacts, -) - - -class _Session: - def __init__(self, order: list[str]) -> None: - self.active = False - self.order = order - - @asynccontextmanager - async def begin(self): - assert not self.active - self.active = True - self.order.append("begin") - try: - yield - finally: - self.active = False - self.order.append("commit") - - -class _Prepared: - def __init__(self, order: list[str], phase: str) -> None: - self.order = order - self.phase = phase - - async def consume(self, facts): - self.order.append("consume_" + self.phase) - return SelectedPreSubmitAuthorityEvidence( - evidence_id=new_record_id(), facts_digest=facts.facts_digest - ) - - -class _Authority: - def __init__(self, session: _Session, order: list[str]) -> None: - self.session = session - self.order = order - - @asynccontextmanager - async def prepare_execution(self, _reservation): - assert self.session.active - self.order.append("prepare_execute") - yield _Prepared(self.order, "execute") - - @asynccontextmanager - async def prepare_finalization(self, _facts): - assert self.session.active - self.order.append("prepare_finalize") - yield _Prepared(self.order, "finalize") - - -class _Coordinator: - def __init__(self, session: _Session, order: list[str], lease) -> None: - self.session = session - self.order = order - self.lease = lease - - async def claim(self, *, authority, **_values): - assert self.session.active - self.order.append("claim") - await authority.consume(SelectedPreSubmitExecuteFacts(self.lease)) - return self.lease - - async def committed_execution(self, **_values): - assert not self.session.active - self.order.append("committed_execution") - return object() - - async def read_expired_lease(self, **_values): - assert self.session.active - self.order.append("read_expired_lease") - return self.lease - - async def finalize(self, *, authority, execution, infrastructure_failure_code, **_values): - assert self.session.active - self.order.append("finalize") - facts = SelectedPreSubmitFinalizeFacts( - lease=self.lease, - execution=execution, - infrastructure_failure_code=infrastructure_failure_code, - source_contracts=selected_pre_submit_source_contracts()) - await authority.consume(facts) - return SimpleNamespace(terminal=facts, capability=None) - - -class _Materialization: - def __init__(self, session: _Session, order: list[str]) -> None: - self.session = session - self.order = order - - async def materialize_selected_pre_submit(self, *_args, **_kwargs): - assert not self.session.active - self.order.append("materialize") - raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable") - - -def _reservation() -> SelectedPreSubmitReservationFacts: - return SelectedPreSubmitReservationFacts( - actor_profile_id=new_record_id(), - identity_link_id=new_record_id(), - project_id=new_record_id(), - task_id=new_record_id(), - assignment_id=new_record_id(), - attempt_id=new_record_id(), - idempotency_key=new_record_id(), - attempt_request_digest="sha256:" + "0" * 64, - prepared_generation_id=new_record_id(), - policy_sha256="sha256:" + "1" * 64, - default_behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - default_input_sha256="sha256:" + "2" * 64, - archive_sha256="sha256:" + "3" * 64, - archive_byte_count=100, - semantic_manifest_sha256="sha256:" + "4" * 64, - execution_budget_ms=60_000, - source_contracts=selected_pre_submit_source_contracts()) - - -@pytest.mark.asyncio -async def test_selected_pre_execution_commits_lease_before_work_and_finalizes_after() -> None: - order: list[str] = [] - session = _Session(order) - reservation = _reservation() - lease = SelectedPreSubmitLeaseFacts( - reservation=reservation, - lease_id=new_record_id(), - lease_generation=1, - lease_expires_at=datetime.now(UTC) + timedelta(minutes=1), - ) - service = SelectedPreSubmitExecutionService( - session=session, - coordinator=_Coordinator(session, order, lease), - authority=_Authority(session, order), - materialization=_Materialization(session, order), - ) - - completed = await service.execute( - reservation=reservation, - materialization=SimpleNamespace(), - ) - - assert completed.terminal.infrastructure_failure_code == "material_unavailable" - assert order == [ - "begin", - "prepare_execute", - "claim", - "consume_execute", - "commit", - "committed_execution", - "materialize", - "begin", - "prepare_finalize", - "finalize", - "consume_finalize", - "commit", - ] - - -@pytest.mark.asyncio -async def test_selected_pre_recovery_finalizes_expired_lease_without_material() -> None: - order: list[str] = [] - session = _Session(order) - reservation = _reservation() - lease = SelectedPreSubmitLeaseFacts( - reservation=reservation, - lease_id=new_record_id(), - lease_generation=1, - lease_expires_at=datetime.now(UTC) - timedelta(seconds=1), - ) - service = SelectedPreSubmitExecutionService( - session=session, - coordinator=_Coordinator(session, order, lease), - authority=_Authority(session, order), - materialization=_Materialization(session, order), - ) - - completed = await service.recover_expired( - run_id=reservation.attempt_id, - reservation=reservation, - ) - - assert completed.terminal.infrastructure_failure_code == "deadline_exceeded" - assert order == [ - "begin", - "read_expired_lease", - "commit", - "begin", - "prepare_finalize", - "finalize", - "consume_finalize", - "commit", - ] - - with pytest.raises( - SelectedPreSubmitInfrastructureUnavailable, - match="material_unavailable", - ): - await service.recover_expired( - run_id=new_record_id(), - reservation=reservation, - ) diff --git a/backend/tests/contributor_reads/test_projection.py b/backend/tests/contributor_reads/test_projection.py index 6953121a4..52e7af9ee 100644 --- a/backend/tests/contributor_reads/test_projection.py +++ b/backend/tests/contributor_reads/test_projection.py @@ -2,6 +2,7 @@ from app.adapters.artifacts import selected_pre_submit_source_contracts +from dataclasses import replace from datetime import UTC, datetime, timedelta from decimal import Decimal from types import SimpleNamespace @@ -17,13 +18,17 @@ from app.modules.checkers.api.default_checker import ( WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, WORKSTREAM_DEFAULT_CHECK_IDS, WorkstreamDefaultCheckerResult, ) -from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts, SelectedPreSubmitRunView +from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitRunView from app.modules.checkers.models import SelectedPreSubmitRun from app.modules.compensation.api.award_reads import ContributorAwardTotal from app.modules.compensation.awards.read_repository import ContributionAwardReadRepository from tests.submission_fixtures import route_retained_checker_remediation, seed_retained_checker_run from tests.test_tasks import set_dev_actor from .support import ME, OWNER, as_actor, get_ok, preparations_path, submitted_case +from tests.checkers.external.test_selected_pre_submit_coordination import ( + _source_completed_execution, + _source_reservation, +) def _present(view): @@ -137,18 +142,22 @@ async def totals(repository, contributor_id, project_ids): def _execution(eligible): + current = _source_completed_execution(_source_reservation()) + if eligible: + return current checks = tuple({ "check_id": check_id, - "status": "passed" if eligible or index < 2 else "failed" if index == 2 else "not_run", - "failure_code": None if eligible or index != 2 else "high_confidence_secret_detected", - "finding_count": 0 if eligible or index != 2 else 1, + "status": "passed" if index < 2 else "failed" if index == 2 else "not_run", + "failure_code": "high_confidence_secret_detected" if index == 2 else None, + "finding_count": 1 if index == 2 else 0, } for index, check_id in enumerate(WORKSTREAM_DEFAULT_CHECK_IDS)) - return SelectedPreSubmitExecutionFacts( - policy_sha256="sha256:" + "1" * 64, required_external_count=0, external_members=(), eligible=eligible, + return replace( + current, external_members=(), eligible=False, workstream_default=WorkstreamDefaultCheckerResult( - behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, eligible=eligible, checks=checks, warnings=(), + behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, eligible=False, checks=checks, warnings=(), ), - source_contracts=selected_pre_submit_source_contracts()) + source_contracts=selected_pre_submit_source_contracts(), + ) _ADMISSION, _SUBMISSION = uuid4(), uuid4() diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index cfb7574bf..21ce7a36d 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -110,7 +110,6 @@ def test_checker_delivery_and_routing_preparation_partition_every_node_once() -> "tests/checkers/external/test_selected_pre_submit.py", "tests/checkers/external/test_selected_intake_lifecycle.py", "tests/checkers/external/test_selected_pre_submit_coordination.py", - "tests/checkers/external/test_selected_pre_submit_service.py", "tests/checkers/execution/test_execution.py", "tests/checkers/execution/test_completion_evidence.py", "tests/checkers/execution/test_coordination.py", @@ -324,8 +323,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: "5b40d4e12032e17b09c70cc4a7484acda6994d918479a7e1e0fce955efa292a4", ), "project": ( - 258, - "90240bd7c6dcb03c20bcf271ec2afbc153901f49ede40fc074ce06d6a8d3c15e", + 257, + "bce3b7bb971159d065d8d7b9bd4a7ff0bb69566f515e02de8542902c0511ebe5", ), "task": ( 96, @@ -397,9 +396,9 @@ def test_project_lane_ownership_has_an_independent_fingerprint() -> None: ) + "\n" ) - assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 258 + assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 257 assert hashlib.sha256(canonical.encode()).hexdigest() == ( - "2d323a55856a88708dc247bfe2314e12fafde30f1900d3dfab06cbfd2026c335" + "2dc926ed22f4ceceaa7d9915625567921290f3588d27a76586c010475f02764e" ) From 7c3c25a8772584e2c4a2b0d082f31b53a8d58ed9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:49:04 +0100 Subject: [PATCH 296/513] Allow remote POST delivery from the app worker --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 22 +++++++++++++++++++ backend/app/adapters/outbox/__init__.py | 6 ----- .../tests/outbox/test_worker_postgresql.py | 5 ++--- .../evaluation_delivery/test_completion.py | 2 +- 4 files changed, 25 insertions(+), 10 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 7f7289c77..3be98b3b2 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9711,3 +9711,25 @@ Acceptance: POST mock execution receives an explicit typed source capability wit Exact retained proof map: `tests/artifacts/test_submission_pre_source.py::test_source_pre_execution_uses_committed_authorized_local_read` owns real source claim, short committed AUTH roots, finalization and failure retention. `tests/checkers/external/test_runtime.py::test_single_pre_expired_lease_does_not_open_source_or_runtime` rejects source/runtime access after lease expiry, and `test_single_pre_cancellation_closes_source_and_transport` owns interruption drainage. `tests/checkers/external/test_selected_pre_submit_coordination.py::test_selected_pre_expired_lease_read_keeps_task_first_custody` owns expired-lease TASK lock order; the adjacent authority-digest test binds the distinct deadline outcome. `tests/artifacts/test_submission_intake_custody.py::test_expiry_can_only_abandon_and_cannot_resume` owns the current required operation-level fence, charge retention, and fresh-key recovery; `test_submission_intake_admission.py::test_t4_and_expiry_serialize_both_winner_orders` owns accepted handoff versus abandonment. Spec section 16 requires the operation to terminalize/fence and forbids PRE worker continuation; it does not require an orphaned selected-run row itself to gain a synthetic deadline terminal. Those are existing current-source tests, not newly executed PostgreSQL/native proof in this commit. The removed test module's synthetic `recover_expired` method did not exist on the current service, so retaining it would create false API coverage. A selected run left `running` after a crashed foreground is a retained observation, not an adopted recovery path or a claim of selected-run terminalization. Focused final pure execution: 111 passed and two unrelated real-PostgreSQL POST cases deselected in 14.01 seconds, exit 0. Initial run had 52 passed, two PostgreSQL setup errors because no isolated database URL was provided, and the independent project fingerprint failed before its count/hash update; it was not credited as a pass. The two deselected cases use `material_fixture` and `live_executor`, not the edited fake source-grant constructors. The current catalogue has 257 project modules with independently recomputed family and lane ownership hashes. This is affected pure test custody, not a full backend CI pass. + +### Restore remote POST delivery in the app-only topology + +CI's production POST/reconciliation calls return no claim because the app-only +profile exclusion still removes those event types. Settings now permit only +hosted_profile=app; native execution moved to the authenticated runner, so this +old local-runtime exclusion blocks the required current path. Allowed scope: +backend/app/adapters/outbox/__init__.py, existing production delivery tests if +needed, and this record. Remove only profile-based exclusion/get_settings import; +retain exact handler registration, exclusive finalization worker filtering, +finite leases, authorization and configured remote adapter failures. No deployment, +provider default, local KVM fallback or authority changes. Medium workflow risk; +QA reviews the composition against remote wiring. Verification uses existing +production request/completion tests for both policy branches and real public +reconciliation/custody tests, plus the native journey. Human review focus: app +workers can dispatch remote POST while finalization workers remain exclusive. + +Use the actual general-worker composition (finalization_worker=False) in +the existing request→completion regression for both policy branches. The +existing finalization-worker isolation test retains pending/expired cases +under the sole supported app profile; remove its obsolete single-host variant. +These tests directly exercise the two worker groups affected by this fix. diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py index d79b02bdc..5e682d021 100644 --- a/backend/app/adapters/outbox/__init__.py +++ b/backend/app/adapters/outbox/__init__.py @@ -68,7 +68,6 @@ def production_outbox_delivery(session_factory, *, finalization_worker: bool | N evaluation_request_handler, ) from app.adapters.checkers import post_submit_delivery_reconciliation_handler - from app.core.config import get_settings from app.modules.checkers.api.delivery_reconciliation import ( POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT as RECONCILIATION_EVENT, ) @@ -189,11 +188,6 @@ def production_outbox_delivery(session_factory, *, finalization_worker: bool | N session_factory, authorization_factory=outbox_dispatch_authorization, registry=registry, options=DeliveryOptions(), event_options={key: value for key, value in event_options.items() if key in registry.keys}, - excluded_events=( - frozenset({(REQUEST_EVENT, 1), (RECONCILIATION_EVENT, 1)}).intersection(registry.keys) - if get_settings().hosted_profile == "app" - else frozenset() - ), ) diff --git a/backend/tests/outbox/test_worker_postgresql.py b/backend/tests/outbox/test_worker_postgresql.py index 5280eeb8f..18bc56fae 100644 --- a/backend/tests/outbox/test_worker_postgresql.py +++ b/backend/tests/outbox/test_worker_postgresql.py @@ -401,8 +401,7 @@ def test_delivery_task_has_independent_hard_limit(worker): @pytest.mark.parametrize("expired", [False, True]) -@pytest.mark.parametrize("profile", ["single-host", "app"]) -async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery_harness, monkeypatch, expired, profile): +async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery_harness, monkeypatch, expired): from app.adapters.outbox import production_outbox_delivery h = delivery_harness kind = "PostSubmissionEvaluationRequested" @@ -412,7 +411,7 @@ async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery assert await owner.claim(event.event_id, h.project, "post-worker") is not None async with h.factory() as session: await session.execute(text("select pg_sleep(3.05)")) - monkeypatch.setenv("WORKSTREAM_HOSTED_PROFILE", profile) + monkeypatch.setenv("WORKSTREAM_HOSTED_PROFILE", "app") get_settings.cache_clear() try: finalization = production_outbox_delivery(h.factory, finalization_worker=True) diff --git a/backend/tests/tasks/evaluation_delivery/test_completion.py b/backend/tests/tasks/evaluation_delivery/test_completion.py index 656999f89..84f04953e 100644 --- a/backend/tests/tasks/evaluation_delivery/test_completion.py +++ b/backend/tests/tasks/evaluation_delivery/test_completion.py @@ -319,7 +319,7 @@ async def test_production_registry_delivers_request_then_completion_exactly_once "worker_post_submission_materialization", lambda *, sessions: h.service, ) - delivery = production_outbox_delivery(h.factory) + delivery = production_outbox_delivery(h.factory, finalization_worker=False) assert delivery._registry.keys[-3:] == ( (REQUEST_EVENT, 1), (COMPLETION_EVENT, 1), From 5f3599d73c2ff15b51691edd35702fc8b022ecf2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:50:04 +0100 Subject: [PATCH 297/513] Qualify separate Terminal Systems POST images through TLS edge --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 76 +++++++++ .../checkers/external/test_remote_node.py | 161 +++++++++++++++--- .../scripts/qualify_terminal_systems_smol.py | 46 ++++- .../terminal_systems_smol_composition.py | 121 ++++++++----- .../tests/terminal_systems_smol_recovery.py | 6 +- .../tests/test_qualify_smol_script.py | 68 +++++++- 6 files changed, 392 insertions(+), 86 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3be98b3b2..e31509d36 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9733,3 +9733,79 @@ the existing request→completion regression for both policy branches. The existing finalization-worker isolation test retains pending/expired cases under the sole supported app profile; remove its obsolete single-host variant. These tests directly exercise the two worker groups affected by this fix. + +### Repair retained Terminal Systems Smol qualification callers + +Bounded intent over83ee3bacb: terminal_systems_smol_composition.py and recovery +reuse the production RemoteTls adapters through existing remote_adapter_endpoint, +without restoring removed Unix adapters. Extend that existing test endpoint only +with explicit finite session/material/callback socket parameters; ordinary10s +callers keep their current envelope. The native Rust service must see the edge's +runner callback socket while the adapter routes callbacks to actual application +model/trial proxies. Preserve exact ART material roots and cleanup inventories. + +Split author and runtime POST approval into independent one-image pytest cases, +with separate fixture roots, two model effects and one retained trial receipt per +case. Preserve the original combined four effects/two receipts, all17 trial-slot +outcomes, replay and full binding/economic checks in aggregate qualification +admission; recovery explicitly selects the runtime case. Update existing native +wrapper/evidence guards to require both cases, refusing missing/duplicate/skipped +branches instead of lowering the total. Allowed files: composition, recovery, +existing test_remote_node endpoint helper, native qualifier and its existing guard +module, and this record. No product code or schema changes planned. + +Use scoped imports/collection and actual loopback production-TLS helper guards, +plus native evidence-admission negatives and source checks. No live native, +service, runner configuration or deployment mutation while the connected journey +uses the remote node; local guards/collection do not qualify native composition. + +Implemented the bounded harness cutover. Both POST cases are explicit pytest +parameters, each approving exactly one registered image/configuration. Recovery +calls the same runtime-case helper directly. Each case gets an independent +composition root and short child-HOME leaf, refusing reuse; the configured child +HOME parent must therefore fit <=16 bytes so each existing native leaf bound +stays <=18. Each result requires two completed model effects with UUIDv7 request/ +response bindings, one retained trial evidence binding/content/put/verification +join and its exact receipt digest. Native qualifier admission requires both exact +JUnit case IDs and both one-image summaries; flattened totals must equal those +summaries and remain the original four model effects/two receipts. Per-case +raw summary hashes are retained alongside the aggregate, with separate authority +manifest digests rather than pretending authority is shared. + +Both adapters use the production RemoteTls implementations and canonical +selected_pre_submit_source_contracts(). The existing loopback test edge now +accepts explicit finite720s sessions and independently pinned material/callback +roots, keeping default10s behavior unchanged. Application post-scratch stays +separate from runner-materials to prevent extract-ID collisions. Rust callbacks +target the runner edge socket; the adapter routes the owning connection back to +actual application model/trial proxies in native qualification. The helper +cleans its socket root even if explicit-root validation fails. No Unix adapter +or compatibility layer was restored. + +Executed scoped evidence (modified content over83ee3bacb): exact hosted CI +collection command collected author, runtime and recovery (three nodes) in4.09s +at /tmp/submission-ts-harness-collection-v1.log, exit0; its pre-existing unknown +postgres_schema_contract mark warning is retained. Native evidence-admission +and inventory guards passed14 in0.543s at +/tmp/submission-ts-qualification-guards-v1.log. Actual loopback production-TLS +endpoint guards plus the existing model-selector control passed3 in5.31s at +/tmp/submission-ts-tls-helper-final.log. Those native peer replies and model/ +trial-labelled callback frames are controlled plumbing facts, not real Smol, +SQL model/trial custody, paid inference or deployed two-host qualification. + +The first TLS plumbing guard failed due to its fake native peer using the wrong +wire key material_grant instead of grant; a wrong-cwd edit did not apply before +the second run, which honestly repeated that fixture failure. Final bytes fixed +that field; assertions were retained. No product failure was inferred. A pure +in-memory mutant retained count2 and fatal-result checks but omitted exact JUnit +image-case identities: the named duplicate-author/missing-runtime test failed +ValueError-not-raised after its valid control, with no source mutation +(/tmp/submission-ts-case-omission-probe.json and .log). + +AST comparison confirms _provider_output, _manifest, +_runtime_configuration_digest, _assert_idle_trial_roots and +_retained_trial_summary unchanged, plus original17-slot cardinality/all11 +explicit slot assertions unchanged (/tmp/submission-ts-preservation.json). +Ruff/whitespace pass. Record/link checks follow this append. Actual native +composition/recovery remains unexecuted: no live runner, service, configuration, +deployment or paid-provider mutation occurred while the connected journey ran. diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py index e0cdcf934..dbea9f06f 100644 --- a/backend/tests/checkers/external/test_remote_node.py +++ b/backend/tests/checkers/external/test_remote_node.py @@ -102,33 +102,38 @@ async def remote_adapter_endpoint( native_socket_path: Path, *, model_proxy_socket_path: Path | None = None, + material_root: Path | None = None, + native_model_proxy_socket_path: Path | None = None, + session_timeout_seconds: float = 10.0, ): - """Expose one test-native Unix service through the production TLS edge.""" + """Expose one test-native service with explicit finite owner roots/windows.""" certificates = _certificate_files(tmp_path) - material_root = tmp_path / f"runner-materials-{uuid4().hex}" - material_root.mkdir(mode=0o700) + if material_root is None: + material_root = tmp_path / f"runner-materials-{uuid4().hex}" + material_root.mkdir(mode=0o700) runner_proxy_root = Path("/tmp") / f"ws-rm-{uuid4().hex[:12]}" runner_proxy_root.mkdir(mode=0o700) - runner_proxy_path = runner_proxy_root / "model.sock" - node = _REMOTE.RemoteNode( - { - "listen_host": "127.0.0.1", - "listen_port": 1, - "client_name": "app.test", - "socket_path": str(native_socket_path), - "model_proxy_socket_path": str(runner_proxy_path), - "material_root": str(material_root), - "tls_certificate_path": str(certificates["server_certificate"]), - "tls_private_key_path": str(certificates["server_key"]), - "tls_ca_path": str(certificates["ca"]), - "session_timeout_seconds": 10, - } - ) - await node.start_model_proxy() - remote = await asyncio.start_server( - node.handle, "127.0.0.1", 0, ssl=node.ssl_context - ) + runner_proxy_path = native_model_proxy_socket_path or runner_proxy_root / "model.sock" + node, remote = None, None try: + node = _REMOTE.RemoteNode( + { + "listen_host": "127.0.0.1", + "listen_port": 1, + "client_name": "app.test", + "socket_path": str(native_socket_path), + "model_proxy_socket_path": str(runner_proxy_path), + "material_root": str(material_root), + "tls_certificate_path": str(certificates["server_certificate"]), + "tls_private_key_path": str(certificates["server_key"]), + "tls_ca_path": str(certificates["ca"]), + "session_timeout_seconds": session_timeout_seconds, + } + ) + await node.start_model_proxy() + remote = await asyncio.start_server( + node.handle, "127.0.0.1", 0, ssl=node.ssl_context + ) yield { "host": "127.0.0.1", "port": remote.sockets[0].getsockname()[1], @@ -139,12 +144,118 @@ async def remote_adapter_endpoint( "model_proxy_socket_path": model_proxy_socket_path, } finally: - remote.close() - await remote.wait_closed() - await node.close() + if remote is not None: + remote.close() + await remote.wait_closed() + if node is not None: + await node.close() runner_proxy_root.rmdir() +@pytest.mark.asyncio +async def test_remote_adapter_endpoint_preserves_explicit_roots_and_callback_routes(tmp_path, monkeypatch): + """Actual production TLS forwards both callback frames on the owning execute.""" + import tempfile + from app.adapters.artifacts import selected_pre_submit_source_contracts + from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter + from app.interfaces.external_checker_execution import ExternalCheckerModelGrant + from app.modules.checkers.api.external import make_external_checker_execution_result + from tests.checkers.external.support import empty_external_material_grant + from tests.checkers.external.test_model_transport import request + + value = request() + result = make_external_checker_execution_result( + request_digest=value.request_digest, registry_entry_id=value.registry.registry_entry_id, + registry_entry_digest=value.registry.entry_digest, phase="post_submit", outcome="infrastructure_failed", + verdict=None, findings=(), infrastructure_failure_code="implementation_unavailable", + ) + material = tmp_path / "runner-material" + material.mkdir(mode=0o700) + captured, callbacks, failures = [], [], [] + original_node = _REMOTE.RemoteNode + def node(config): + instance = original_node(config) + captured.append(instance) + return instance + monkeypatch.setattr(_REMOTE, "RemoteNode", node) + with tempfile.TemporaryDirectory(prefix="ws-ts-tls-") as temporary: + sockets = Path(temporary) + app_proxy, native_proxy, native_socket = (sockets / name for name in ("app", "runner", "native")) + async def app(reader, writer): + try: + payload = await _read_frame(reader) + callbacks.append(payload) + writer.write(_frame(payload)) + await writer.drain() + finally: + writer.close() + await writer.wait_closed() + async def native(reader, writer): + try: + wire = json.loads(await _read_frame(reader)) + grant_id = wire["grant"]["grant_id"] + assert (material / "workspaces" / grant_id).is_dir() + assert wire["model_grant"]["grant_id"] == "model_" + "a" * 32 + for payload in (b'{"callback":"model"}', b'{"callback":"trial"}'): + callback_reader, callback_writer = await asyncio.open_unix_connection(native_proxy) + callback_writer.write(_frame(payload)) + await callback_writer.drain() + assert await _read_frame(callback_reader) == payload + callback_writer.close() + await callback_writer.wait_closed() + writer.write(_frame(json.dumps({"protocol_version": "external_checker_service.v1", + "result": result.model_dump(mode="json"), "isolation": None}).encode())) + await writer.drain() + except BaseException as error: + failures.append(error) + finally: + writer.close() + await writer.wait_closed() + native_server = await asyncio.start_unix_server(native, native_socket) + app_server = await asyncio.start_unix_server(app, app_proxy) + try: + async with remote_adapter_endpoint(tmp_path, native_socket, model_proxy_socket_path=app_proxy, + material_root=material, native_model_proxy_socket_path=native_proxy, + session_timeout_seconds=720.0) as endpoint: + assert captured[0].timeout == 720.0 + assert captured[0].material_root == material + assert captured[0].model_proxy_socket_path == native_proxy + adapter = RemoteTlsExternalCheckerAdapter(**endpoint, timeout_seconds=90.0, + source_contracts=selected_pre_submit_source_contracts()) + observed = await adapter.execute(value, empty_external_material_grant(value, suffix="c"), + model_grant=ExternalCheckerModelGrant("model_" + "a" * 32, value.request_digest)) + assert observed.result == result + assert not native_proxy.exists() + assert list((material / "workspaces").iterdir()) == [] + assert callbacks == [b'{"callback":"model"}', b'{"callback":"trial"}'] + assert failures == [] + finally: + native_server.close() + app_server.close() + await native_server.wait_closed() + await app_server.wait_closed() + + +@pytest.mark.asyncio +async def test_remote_adapter_endpoint_invalid_explicit_root_cleans_helper_socket_root(tmp_path, monkeypatch): + """Fail before native contact and leave no helper-owned directory on rejection.""" + identity = uuid4() + monkeypatch.setitem(remote_adapter_endpoint.__wrapped__.__globals__, "uuid4", lambda: identity) + material = tmp_path / "public-material" + material.mkdir(mode=0o755) + root = Path("/tmp") / f"ws-rm-{identity.hex[:12]}" + assert not root.exists() + private = tmp_path / "private-material" + private.mkdir(mode=0o700) + async with remote_adapter_endpoint(tmp_path, tmp_path / "no-native.sock", material_root=private): + assert root.is_dir() + assert not root.exists() + with pytest.raises(ValueError, match="material root is not private"): + async with remote_adapter_endpoint(tmp_path, tmp_path / "no-native.sock", material_root=material): + raise AssertionError("invalid material root entered native execution") + assert not root.exists() + + @pytest.mark.asyncio async def test_remote_post_stages_bound_material_and_removes_session(tmp_path: Path): certificates = _certificate_files(tmp_path) diff --git a/external_checkers/workstream-checker-service/scripts/qualify_terminal_systems_smol.py b/external_checkers/workstream-checker-service/scripts/qualify_terminal_systems_smol.py index cf08a424f..fea8a2473 100644 --- a/external_checkers/workstream-checker-service/scripts/qualify_terminal_systems_smol.py +++ b/external_checkers/workstream-checker-service/scripts/qualify_terminal_systems_smol.py @@ -21,6 +21,7 @@ ROOT = Path(__file__).resolve().parents[3] CASE = "test_production_service_executes_project_trial_under_smol_with_real_custody" +CASES = {"author": "author_evidence_accuracy", "runtime": "runtime_environment_and_verification_trials"} def digest(path: Path) -> str: @@ -88,8 +89,9 @@ def verify_results(junit: Path, metadata: dict, fixture: dict, head: str) -> Non document = ET.parse(junit).getroot() cases = document.findall(".//testcase") if ( - len(cases) != 1 - or cases[0].get("name") != CASE + sorted(case.get("name", "") for case in cases) != sorted( + f"{CASE}[{case}]" for case in CASES + ) or any(document.findall(f".//{tag}") for tag in ("failure", "error", "skipped")) ): raise ValueError("composition did not complete its exact required case") @@ -100,6 +102,21 @@ def verify_results(junit: Path, metadata: dict, fixture: dict, head: str) -> Non or metadata.get("minio_cleanup_complete") is not True ): raise ValueError("database/storage completion evidence is incomplete") + selected_cases = fixture.get("cases", {}) + if type(selected_cases) is not dict or set(selected_cases) != set(CASES): + raise ValueError("composition must retain both independent image cases") + for case, value in selected_cases.items(): + if (value.get("case") != case or value.get("requirement_id") != CASES[case] + or value.get("provider_mode") != "controlled" + or value.get("guide_to_contribution_proven") is not False + or value.get("replay_additional_provider_calls") != 0 + or value.get("owned_runtime_resources_removed") is not True + or len(value.get("model_effects", [])) != 2 + or len(value.get("trials", [])) != 1): + raise ValueError("one-image case custody is incomplete") + if (fixture.get("model_effects") != [effect for case in CASES for effect in selected_cases[case]["model_effects"]] + or fixture.get("trials") != [trial for case in CASES for trial in selected_cases[case]["trials"]]): + raise ValueError("aggregate custody differs from independent cases") if ( fixture.get("schema_version") != "workstream.terminal_systems_composition_evidence.v1" @@ -113,6 +130,26 @@ def verify_results(junit: Path, metadata: dict, fixture: dict, head: str) -> Non raise ValueError("runtime/custody completion evidence is incomplete") +def combine_case_results(path: Path) -> dict: + """Retain both one-image receipts without pretending their authority is shared.""" + cases = {case: read_json(path.with_name(path.stem + "-" + case + path.suffix)) for case in CASES} + common = ("schema_version", "provider_mode", "guide_to_contribution_proven", "image", + "profile", "projection", "runtime", "predecessor_material_exercised") + first = cases["author"] + if any(value.get(field) != first.get(field) for value in cases.values() for field in common): + raise ValueError("one-image runtime identities differ") + result = {field: first[field] for field in common} + result.update( + cases=cases, + authority_manifest_digests={case: value["authority_manifest_digest"] for case, value in cases.items()}, + model_effects=[effect for value in cases.values() for effect in value["model_effects"]], + trials=[trial for value in cases.values() for trial in value["trials"]], + replay_additional_provider_calls=sum(value["replay_additional_provider_calls"] for value in cases.values()), + owned_runtime_resources_removed=all(value["owned_runtime_resources_removed"] for value in cases.values()), + ) + return result + + def write_new(path: Path, value: dict) -> None: with path.open("x", encoding="utf-8") as output: json.dump(value, output, sort_keys=True, indent=2) @@ -260,7 +297,8 @@ def main() -> int: ) if digest(args.node_config) != outcome["node_config_sha256"]: raise ValueError("node config changed") - fixture_facts = read_json(fixture) + fixture_facts = combine_case_results(fixture) + write_new(fixture, fixture_facts) verify_results(junit, read_json(metadata), fixture_facts, args.expected_head) verify_runtime( fixture_facts, @@ -278,6 +316,8 @@ def main() -> int: "junit.xml", "metadata.json", "fixture-summary.json", + "fixture-summary-author.json", + "fixture-summary-runtime.json", ) }, ) diff --git a/external_checkers/workstream-checker-service/tests/terminal_systems_smol_composition.py b/external_checkers/workstream-checker-service/tests/terminal_systems_smol_composition.py index 861a3bf65..2e3b3d755 100644 --- a/external_checkers/workstream-checker-service/tests/terminal_systems_smol_composition.py +++ b/external_checkers/workstream-checker-service/tests/terminal_systems_smol_composition.py @@ -22,13 +22,14 @@ from uuid import UUID, uuid4 import zipfile +import pytest from sqlalchemy import select from smol_runtime import assert_smol_vm_inventory, smol_vm_inventory -from app.adapters.artifacts import checker_output_binding, checker_output_storage +from app.adapters.artifacts import checker_output_binding, checker_output_storage, selected_pre_submit_source_contracts from app.adapters.artifacts import post_submission_materialization -from app.adapters.artifacts.trusted_intake import UnixSocketTrustedIntakeAdapter +from app.adapters.artifacts.trusted_intake import RemoteTlsTrustedIntakeAdapter from app.adapters.auth import checker_model_service_authorization from app.adapters.checkers import ( checker_output_reservations, @@ -36,7 +37,7 @@ model_invocation_grants, model_profile_reader, ) -from app.adapters.checkers.external_service import UnixSocketExternalCheckerAdapter +from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter from app.adapters.checkers.model_execution import ModelAwareExternalExecution from app.adapters.checkers.model_proxy import CheckerModelProxy from app.adapters.checkers.model_proxy_transport import ModelProxyTransport @@ -91,6 +92,7 @@ reserve, ) from tests.checkers.external.support import post_registry_spec +from tests.checkers.external.test_remote_node import remote_adapter_endpoint from tests.checkers.external.test_trial_evidence import _owner from tests.checkers.external.test_revision_materialization import ( DiagnosticMaterialization, @@ -809,19 +811,38 @@ def _wait_for_socket( raise AssertionError("Rust service socket did not become ready") +@pytest.mark.parametrize("case", ("author", "runtime")) async def test_production_service_executes_project_trial_under_smol_with_real_custody( - tmp_path, isolated_database_env, admin_access, monkeypatch, *, recovery=None + tmp_path, isolated_database_env, admin_access, monkeypatch, case +): + """Qualify both locked one-image cases independently, never a multi-POST policy.""" + await _run_composition_case(tmp_path, isolated_database_env, admin_access, monkeypatch, case=case) + + +async def _run_composition_case( + tmp_path, isolated_database_env, admin_access, monkeypatch, *, case, recovery=None ): """Prove the exact qualification boundary; no live model provider is used.""" env = _required_environment() configured_root = Path(env["WORKSTREAM_TS_SMOL_ROOT"]) assert configured_root.is_absolute() and not configured_root.is_symlink() - root = configured_root.resolve(strict=True) - assert root == configured_root and root.stat().st_mode & 0o077 == 0 + assert case in {"author", "runtime"} + requirement_id = AUTHOR_REQUIREMENT if case == "author" else REQUIREMENT + assert configured_root.resolve(strict=True) == configured_root + assert configured_root.stat().st_mode & 0o077 == 0 + root = configured_root / case[0] + root.mkdir(mode=0o700) node, checker_image, builder_image, intake_image = _node_configuration(env) - child_home_root = Path(node["trial_runtime"]["child_home_root"]) + child_parent = Path(node["trial_runtime"]["child_home_root"]) + assert child_parent.is_absolute() and child_parent.resolve(strict=True) == child_parent + metadata = child_parent.lstat() + assert stat.S_ISDIR(metadata.st_mode) and stat.S_IMODE(metadata.st_mode) == 0o700 + assert (metadata.st_uid, metadata.st_gid) == (os.geteuid(), os.getegid()) + child_home_root = child_parent / case[0] + assert len(os.fsencode(child_home_root)) <= 18, "one-image cases require child HOME parent <=16 bytes" + child_home_root.mkdir(mode=0o700) + node["trial_runtime"]["child_home_root"] = str(child_home_root) assert child_home_root.is_absolute() and child_home_root.resolve(strict=True) == child_home_root - assert len(os.fsencode(child_home_root)) <= 18 child_root_stat = child_home_root.lstat() assert stat.S_ISDIR(child_root_stat.st_mode) assert stat.S_IMODE(child_root_stat.st_mode) == 0o700 @@ -896,14 +917,9 @@ async def attachment_cases(_factory, project_id, _registry): "model_profile_version": response.json()["spec"]["profile_version"], "model_profile_digest": response.json()["profile_digest"], } - return tuple( - PostSubmitAttachmentCase( - requirement_id=requirement_id, - configuration=shared | {"check": requirement_id}, - ) - for requirement_id in (AUTHOR_REQUIREMENT, REQUIREMENT) - if recovery is None or requirement_id == REQUIREMENT - ) + return (PostSubmitAttachmentCase( + requirement_id=requirement_id, configuration=shared | {"check": requirement_id}, + ),) post_scratch = root / "post-scratch" post_scratch.mkdir(mode=0o700) @@ -937,14 +953,12 @@ async def attachment_cases(_factory, project_id, _registry): ) as h: # Fixture creation deliberately uses its in-process intake to seed the # already-verified submission admission. The public post-submit journey - # below is recomposed with the native trusted-intake socket only after - # the authority manifest and Rust service exist. + # below uses the production TLS edge only after the authority manifest + # and native Rust service exist. await provision_post_submit_service( h.factory, ServiceIdentity.ARTIFACT_CHECKER_OUTPUT ) - expected_requirements = ( - {AUTHOR_REQUIREMENT, REQUIREMENT} if recovery is None else {REQUIREMENT} - ) + expected_requirements = {requirement_id} assert len(h.request.policy.entries) == len(expected_requirements) assert { entry.requirement_id: entry.configuration["check"] @@ -1053,7 +1067,9 @@ def trial_reservations(session, external): proxy_root = root / "private-proxy" service_root = root / "service" + runner_material_root = root / "runner-materials" for directory in ( + runner_material_root, proxy_root, service_root, root / "model-relay", @@ -1063,14 +1079,15 @@ def trial_reservations(session, external): directory.mkdir(mode=0o700, exist_ok=True) proxy_path = proxy_root / "proxy.sock" service_socket = service_root / "checker.sock" + runner_proxy_path = proxy_root / "runner.sock" service_config = json.loads(json.dumps(node)) service_config.update( socket_path=str(service_socket), - model_proxy_socket=str(proxy_path), + model_proxy_socket=str(runner_proxy_path), model_relay_root=str(root / "model-relay"), trial_authority_manifest_path=str(manifest_path), trial_authority_manifest_digest=manifest_digest, - material_root=str(post_scratch), + material_root=str(runner_material_root), docker_binary="", sandbox_uid=os.geteuid(), sandbox_gid=os.getegid(), @@ -1107,13 +1124,21 @@ def trial_reservations(session, external): before_cgroups = _directory_children(cgroup_root) service = None try: - async with ModelProxyTransport( - socket_path=proxy_path, - handler=model_proxy.handle, - trial_handler=trial_proxy.handle, - read_timeout_seconds=60.0, - write_timeout_seconds=60.0, - shutdown_timeout_seconds=30.0, + async with ( + ModelProxyTransport( + socket_path=proxy_path, + handler=model_proxy.handle, + trial_handler=trial_proxy.handle, + read_timeout_seconds=60.0, + write_timeout_seconds=60.0, + shutdown_timeout_seconds=30.0, + ), + remote_adapter_endpoint( + tmp_path, service_socket, model_proxy_socket_path=proxy_path, + material_root=runner_material_root, + native_model_proxy_socket_path=runner_proxy_path, + session_timeout_seconds=720.0, + ) as endpoint, ): service = subprocess.Popen( [str(service_binary), str(config_path)], @@ -1123,8 +1148,8 @@ def trial_reservations(session, external): text=True, ) _wait_for_socket(service_socket, service) - intake = UnixSocketTrustedIntakeAdapter( - socket_path=service_socket, + intake = RemoteTlsTrustedIntakeAdapter( + **{key: value for key, value in endpoint.items() if key != "model_proxy_socket_path"}, image_digest=intake_image["platform_manifest_digest"], config_digest=intake_image["config_image_id"], ) @@ -1156,8 +1181,9 @@ def trial_reservations(session, external): artifact_deadline_ms=120_000, ) ) - adapter = UnixSocketExternalCheckerAdapter( - socket_path=service_socket, timeout_seconds=660.0 + adapter = RemoteTlsExternalCheckerAdapter( + **endpoint, timeout_seconds=660.0, + source_contracts=selected_pre_submit_source_contracts(), ) health = await adapter.health() assert (health.runtime, health.isolation_mode) == ( @@ -1190,12 +1216,14 @@ def trial_reservations(session, external): assert _directory_children(cgroup_root) == before_cgroups return result = await executor.evaluate_post_submission(h.request) + assert _directory_children(runner_material_root / "workspaces") == set() + assert _directory_children(post_scratch / "workspaces") == set() assert result.outcome == "completed", ( result, len(creates), len(observations), ) - assert len(result.execution.external_members) == 2 + assert len(result.execution.external_members) == 1 # This qualification is an initial submission: it proves the # current-only least-material path and explicitly does not claim a # predecessor/archive revision journey. @@ -1206,17 +1234,14 @@ def trial_reservations(session, external): assert { member.requirement_id: (member.result.outcome, member.result.verdict) for member in result.execution.external_members - } == { - AUTHOR_REQUIREMENT: ("completed", "passed"), - REQUIREMENT: ("completed", "passed"), - } - assert len(creates) == 4 + } == {requirement_id: ("completed", "passed")} + assert len(creates) == 2 receipts = [item["receipt"] for item in observations if "receipt" in item] - assert len(receipts) == 2 + assert len(receipts) == 1 assert { receipt["originating_identity"]["requirement_id"] for receipt in receipts - } == {AUTHOR_REQUIREMENT, REQUIREMENT} + } == {requirement_id} for receipt in receipts: assert receipt["plan_completed"] is True assert receipt["cleanup_confirmed"] is True @@ -1261,10 +1286,10 @@ def trial_reservations(session, external): assert outcomes["interrupt_work"] == "signalled" assert outcomes["restart_work_verification"] == "succeeded" assert await executor.evaluate_post_submission(h.request) == result - assert len(creates) == 4 + assert len(creates) == 2 async with h.factory() as session: effects = tuple(await session.scalars(select(ModelUsageEffect))) - assert len(effects) == 4 + assert len(effects) == 2 assert all(item.state == "completed" for item in effects) assert all( UUID(item.request_binding_id).version == 7 for item in effects @@ -1273,7 +1298,7 @@ def trial_reservations(session, external): UUID(item.response_binding_id).version == 7 for item in effects ) retained = tuple(await session.scalars(select(CheckerTrialEvidence))) - assert len(retained) == 2 + assert len(retained) == 1 assert {item.content_sha256 for item in retained} == { external_checker_json_hash(receipt) for receipt in receipts } @@ -1318,6 +1343,7 @@ def trial_reservations(session, external): summary = { "schema_version": "workstream.terminal_systems_composition_evidence.v1", "provider_mode": "controlled", + "case": case, "requirement_id": requirement_id, "guide_to_contribution_proven": False, "image": { "digest": env["WORKSTREAM_TS_SMOL_CHECKER_DIGEST"], @@ -1355,7 +1381,7 @@ def trial_reservations(session, external): }, "model_effects": model_summary, "trials": trial_summary, - "replay_additional_provider_calls": len(creates) - 4, + "replay_additional_provider_calls": len(creates) - 2, "predecessor_material_exercised": False, "owned_runtime_resources_removed": True, } @@ -1363,7 +1389,8 @@ def trial_reservations(session, external): summary, sort_keys=True, separators=(",", ":"), allow_nan=False ).encode() assert len(encoded) <= 64 * 1024 - summary_path = Path(env["WORKSTREAM_TS_SMOL_SUMMARY_PATH"]) + base_summary = Path(env["WORKSTREAM_TS_SMOL_SUMMARY_PATH"]) + summary_path = base_summary.with_name(base_summary.stem + "-" + case + base_summary.suffix) assert summary_path.is_absolute() and root not in summary_path.parents descriptor = os.open(summary_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(descriptor, "wb") as output: diff --git a/external_checkers/workstream-checker-service/tests/terminal_systems_smol_recovery.py b/external_checkers/workstream-checker-service/tests/terminal_systems_smol_recovery.py index 6982f1144..47ce4edeb 100644 --- a/external_checkers/workstream-checker-service/tests/terminal_systems_smol_recovery.py +++ b/external_checkers/workstream-checker-service/tests/terminal_systems_smol_recovery.py @@ -8,7 +8,7 @@ from smol_recovery import NestedTrialRecovery from terminal_systems_smol_composition import ( - test_production_service_executes_project_trial_under_smol_with_real_custody as run_composition, + _run_composition_case, ) @@ -16,7 +16,7 @@ async def test_active_nested_trial_recovery( tmp_path, isolated_database_env, admin_access, monkeypatch ): recovery = NestedTrialRecovery(os.environ["WORKSTREAM_TS_SMOL_RECOVERY_CASE"]) - await run_composition( - tmp_path, isolated_database_env, admin_access, monkeypatch, recovery=recovery + await _run_composition_case( + tmp_path, isolated_database_env, admin_access, monkeypatch, case="runtime", recovery=recovery ) assert recovery.completed is True diff --git a/external_checkers/workstream-checker-service/tests/test_qualify_smol_script.py b/external_checkers/workstream-checker-service/tests/test_qualify_smol_script.py index a631d9482..bdcbeae78 100644 --- a/external_checkers/workstream-checker-service/tests/test_qualify_smol_script.py +++ b/external_checkers/workstream-checker-service/tests/test_qualify_smol_script.py @@ -100,14 +100,14 @@ def test_binary_provenance_rejects_mutation_and_symlink(self): ) def check_result( - self, *, children="", count=1, metadata_update=None, fixture_update=None + self, *, children="", count=2, metadata_update=None, fixture_update=None, case_names=None, case_update=None ): with tempfile.TemporaryDirectory() as temporary: junit = Path(temporary) / "junit.xml" - case = f'{children}' - junit.write_text( - f"{case * count}" - ) + names = case_names or [f"{qualifier.CASE}[{case}]" for case in qualifier.CASES] + names = (names * max(1, count))[:count] + cases_xml = "".join(f'{children}' for name in names) + junit.write_text(f"{cases_xml}") metadata = { "tree_sha": "a" * 40, "lane": "trial_composition", @@ -120,22 +120,74 @@ def check_result( "guide_to_contribution_proven": False, "replay_additional_provider_calls": 0, "owned_runtime_resources_removed": True, - "model_effects": [{}, {}, {}, {}], - "trials": [{}, {}], + "model_effects": [{"case": case, "index": index} for case in qualifier.CASES for index in range(2)], + "trials": [{"case": case} for case in qualifier.CASES], + "cases": {case: { + "case": case, "requirement_id": requirement, "provider_mode": "controlled", + "guide_to_contribution_proven": False, "replay_additional_provider_calls": 0, + "owned_runtime_resources_removed": True, + "model_effects": [{"case": case, "index": index} for index in range(2)], + "trials": [{"case": case}], + } for case, requirement in qualifier.CASES.items()}, } metadata.update(metadata_update or {}) fixture.update(fixture_update or {}) + if case_update: + case_update(fixture["cases"]) qualifier.verify_results(junit, metadata, fixture, "a" * 40) def test_exact_completed_case_is_required(self): self.check_result() - for count in (0, 2): + for count in (0, 1, 3): with self.subTest(count=count), self.assertRaises(ValueError): self.check_result(count=count) for child in ("", "", ""): with self.subTest(child=child), self.assertRaises(ValueError): self.check_result(children=child) + def test_duplicate_image_case_cannot_replace_missing_case(self): + self.check_result() + name = f"{qualifier.CASE}[author]" + with self.assertRaisesRegex(ValueError, "exact required case"): + self.check_result(case_names=[name, name]) + + def test_per_case_custody_cannot_be_masked_by_old_aggregate_totals(self): + self.check_result() + for case in qualifier.CASES: + for field, value in (("model_effects", []), ("trials", []), + ("requirement_id", "foreign"), ("owned_runtime_resources_removed", False), + ("replay_additional_provider_calls", 1)): + with self.subTest(case=case, field=field), self.assertRaises(ValueError): + self.check_result(case_update=lambda cases: cases[case].update({field: value})) + with self.subTest(missing=case), self.assertRaises(ValueError): + self.check_result(case_update=lambda cases: cases.pop(case)) + for field in ("model_effects", "trials"): + with self.subTest(flattened=field), self.assertRaisesRegex(ValueError, "aggregate custody"): + self.check_result(fixture_update={field: list(reversed( + [{"case": case, "index": index} for case in qualifier.CASES for index in range(2)] + if field == "model_effects" else [{"case": case} for case in qualifier.CASES]))}) + + def test_combiner_keeps_distinct_authorities_and_both_cases(self): + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / "fixture.json" + for case, requirement in qualifier.CASES.items(): + facts = {"schema_version": "workstream.terminal_systems_composition_evidence.v1", + "provider_mode": "controlled", "guide_to_contribution_proven": False, + "image": {}, "profile": {}, "projection": {}, "runtime": {}, + "predecessor_material_exercised": False, "case": case, "requirement_id": requirement, + "authority_manifest_digest": case, "model_effects": [{"case": case}] * 2, + "trials": [{"case": case}], "replay_additional_provider_calls": 0, + "owned_runtime_resources_removed": True} + path.with_name("fixture-" + case + ".json").write_text(json.dumps(facts)) + combined = qualifier.combine_case_results(path) + self.assertEqual(set(combined["cases"]), set(qualifier.CASES)) + self.assertEqual(len(combined["model_effects"]), 4) + self.assertEqual(len(combined["trials"]), 2) + self.assertEqual(combined["authority_manifest_digests"], {case: case for case in qualifier.CASES}) + path.with_name("fixture-runtime.json").unlink() + with self.assertRaises(FileNotFoundError): + qualifier.combine_case_results(path) + def test_storage_cleanup_and_exact_source_are_required(self): for changed in ( {"database_cleanup_complete": False}, From 0449ed4c9f7fbc801dc6a0f0e3e2b8e1c41ab14a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 16:53:27 +0100 Subject: [PATCH 298/513] Verify remote POST admission in the app worker --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 7 +++ .../tests/outbox/test_worker_postgresql.py | 49 ++++++++++--------- 2 files changed, 33 insertions(+), 23 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e31509d36..89d00a70d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9809,3 +9809,10 @@ explicit slot assertions unchanged (/tmp/submission-ts-preservation.json). Ruff/whitespace pass. Record/link checks follow this append. Actual native composition/recovery remains unexecuted: no live runner, service, configuration, deployment or paid-provider mutation occurred while the connected journey ran. + +QA-REMOTE-POST-001 identified the old app-hides-POST regression. Replaced +that obsolete expectation with exact general-worker pagination, POST claim +and expired uninvoked reconciliation recovery under the sole app profile. +The test preserves generation/owner/state checks and proves discovery/recovery +does not invoke synthetic payloads; real request execution stays covered by +the separate production request→completion tests. diff --git a/backend/tests/outbox/test_worker_postgresql.py b/backend/tests/outbox/test_worker_postgresql.py index 18bc56fae..ee1ea962b 100644 --- a/backend/tests/outbox/test_worker_postgresql.py +++ b/backend/tests/outbox/test_worker_postgresql.py @@ -66,15 +66,13 @@ async def test_worker_duplicate_delivery(delivery_harness, worker): ) -async def test_app_host_leaves_checker_work_for_the_full_topology(delivery_harness, monkeypatch): +async def test_app_worker_discovers_remote_post_and_recovers_expired_custody(delivery_harness, monkeypatch): h = delivery_harness checker_request = await h.append(event_type=REQUEST_EVENT) reconciliation = await h.append(event_type=POST_SUBMIT_DELIVERY_RECONCILIATION_EVENT) completion = await h.append(event_type=COMPLETION_EVENT) - full_delivery = h.build(HandlerRegistry([ - (reconciliation.event_type, 1, h.handle), - ])) - expired = await full_delivery.claim(reconciliation.event_id, h.project, "checker-worker") + owner = h.build(HandlerRegistry([(reconciliation.event_type, 1, h.handle)])) + expired = await owner.claim(reconciliation.event_id, h.project, "checker-worker") assert expired is not None async with h.factory() as session: await session.execute(text("select pg_sleep(3.05)")) @@ -82,30 +80,35 @@ async def test_app_host_leaves_checker_work_for_the_full_topology(delivery_harne monkeypatch.setenv("WORKSTREAM_HOSTED_PROFILE", "app") get_settings.cache_clear() try: - app_delivery = production_outbox_delivery(h.factory) + app_delivery = production_outbox_delivery(h.factory, finalization_worker=False) for _ in range(2): - page = await app_delivery.candidates(limit=1) - assert tuple(item.event_id for item in page.items) == (completion.event_id,) - assert page.next_after is None - for event in (checker_request, reconciliation): - assert await app_delivery.deliver(event.event_id, h.project, "app-worker") is None + page = await app_delivery.candidates(limit=2) + assert tuple(item.event_id for item in page.items) == ( + checker_request.event_id, reconciliation.event_id, + ) + assert page.next_after == reconciliation.event_id + last = await app_delivery.candidates(after=page.next_after, limit=2) + assert tuple(item.event_id for item in last.items) == (completion.event_id,) + assert last.next_after is None + request_claim = await app_delivery.claim(checker_request.event_id, h.project, "app-worker") + assert request_claim is not None assert await app_delivery.claim(completion.event_id, h.project, "app-worker") is not None + assert await app_delivery.recover(reconciliation.event_id, h.project) is not None async with h.factory() as session: - pending = await session.get(OutboxEvent, checker_request.event_id) + request = await session.get(OutboxEvent, checker_request.event_id) retained = await session.get(OutboxEvent, reconciliation.event_id) - assert (pending.delivery_state, pending.claim_generation) == ("pending", 0) + assert (request.delivery_state, request.claim_generation, request.claim_owner) == ( + "claimed", request_claim.claim_generation, "app-worker", + ) assert (retained.delivery_state, retained.claim_generation, retained.claim_owner) == ( - "claimed", expired.claim_generation, expired.claim_owner, + "retryable", expired.claim_generation, None, ) - - monkeypatch.setenv("WORKSTREAM_HOSTED_PROFILE", "single-host") - get_settings.cache_clear() - restored_delivery = production_outbox_delivery(h.factory) - restored_page = await restored_delivery.candidates(limit=2) - assert tuple(item.event_id for item in restored_page.items) == ( - checker_request.event_id, reconciliation.event_id, - ) - assert await restored_delivery.recover(reconciliation.event_id, h.project) is not None + attempt = await session.scalar(select(OutboxDeliveryAttempt).where( + OutboxDeliveryAttempt.event_id == reconciliation.event_id, + OutboxDeliveryAttempt.claim_generation == expired.claim_generation, + )) + assert attempt.stage == "completed" and attempt.invoked_at is None + assert h.handled == [] # Discovery/claim/recovery do not execute synthetic payloads. finally: get_settings.cache_clear() From 7b566e69f0eac54aaf615017db9795eb09d9146c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:10:10 +0100 Subject: [PATCH 299/513] Record remote POST regression proof and actual S3 permission gaps --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 89d00a70d..d4d08c1e9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9816,3 +9816,41 @@ and expired uninvoked reconciliation recovery under the sole app profile. The test preserves generation/owner/state checks and proves discovery/recovery does not invoke synthetic payloads; real request execution stays covered by the separate production request→completion tests. + +The clean public journey at `a51f1acd0` passed the native PRE missing-summary +rejection, accepted and replayed the correct source, and finalized T5 to one +Submission. A read-only isolated database observation showed the original +finalization event acknowledged on its first attempt, while +`PostSubmissionEvaluationRequested` remained pending, unclaimed and at zero +attempts; the POST run was queued. A second observation still found the same +pending event. This matches the profile-based exclusion removed above. The +canonical isolation runner was signalled only after those observations and +reported both database and MinIO cleanup complete. That stopped run did not +observe automatic acceptance, the incorrect POST branch or review-pending +branch. The repaired production worker composition still needs its focused +PostgreSQL replay and then a fresh full public journey. + +The repaired composition's10 scoped real-PostgreSQL cases passed at0449ed4c9 +in317.77s (/tmp/submission-remote-post-delivery.log and .json), schema0090 and +owned database cleanup confirmed. Cases cover actual general-worker POST +request→completion under both review-policy branches, committed reconciliation +without repeated effects, four substituted child/operator-cause refusals, +app-worker pagination/claim/expired-uninvoked recovery, and pending/expired POST +isolation from the finalizer group. No MinIO was provisioned by this run. +QA-REMOTE-POST-001 is resolved; scoped QA PASS at the exact clean candidate. +Independent composition control restores the old exclusion and rejects it, +while retaining finalizer-only registration/options and missing-TLS refusal. +These are local SQL/controlled execution proofs, not native/AWS qualification. + +Read-only live API credential inspection confirms mounted dedicated AWS access +keys through the canonical direct-user provider, not inline MinIO fields. +GetBucketVersioning and ListObjectVersions under the actual +workstream/artifacts/submission-source/v1 prefix return AccessDenied. The +provisioning identity can read the bucket policy and versioning: versioning is +already Enabled, while the current policy explicitly confines object access +to the old sha256 namespace and denies all deletion. Its IAM GetUser/ListUserPolicies +calls are denied; those are administration limits, not a runtime need for IAM +administration. Existing API credentials stay on the app side; no keys belong +in the microVM. Prepared source permissions must preserve retained SHA objects +and qualify the separate cleanup authority. No bucket/object/config mutation +was performed by these probes. Actual AWS source qualification remains open. From 35b636a3fe7c109a19bdaae1025f7254ad2a14ed Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:17:37 +0100 Subject: [PATCH 300/513] Scope multipart permission exception to submission sources --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 25 +++++++++++++++++++ backend/scripts/aws_direct_user_config.py | 4 ++- backend/tests/test_aws_direct_user_config.py | 6 ++++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d4d08c1e9..40ac5be6e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9854,3 +9854,28 @@ administration. Existing API credentials stay on the app side; no keys belong in the microVM. Prepared source permissions must preserve retained SHA objects and qualify the separate cleanup authority. No bucket/object/config mutation was performed by these probes. Actual AWS source qualification remains open. + +### Preserve SHA put guards while enabling source multipart uploads + +Read-only live policy comparison shows the existing SHA namespace denies every +PutObject operation without If-None-Match. Restrict the multipart API exemption +to the new submission-source bundle keys rather than broadening legacy SHA +behavior. Allowed files: backend/scripts/aws_direct_user_config.py and its +existing test_aws_direct_user_config.py, this record and regenerated local +permission handoff JSON. No live AWS mutation or credential handling change. +Medium storage-policy risk; ARCH/SEC reviewed prepared policy against the live +five-statement snapshot and found no blocker, subject to exact generator parity +and actual later AWS positive/negative qualification. Retain metadata-listing +scope limitation in the handoff; no object read/delete authority outside exact +sources is added. Verify existing focused policy tests and generated JSON equality. +AWS conditional multipart reference: +https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes-enforce.html + +All15 existing policy guards passed2.02s, including separate runtime/cleanup +rights, retained SHA protection, conditional completion/part rules and refusal +of foreign/unbounded identities (/tmp/submission-aws-policy-scope.log). +All three prepared JSON files compare exactly to canonical generator output +for the actual bucket, namespace and same-account IAM users. ARCH/SEC review +found no blocker to administrator application; metadata-list scope is explicit +in administrator-handoff.txt. Live policy application, credentials provisioning +and actual AWS source qualification remain unperformed. Pinned Ruff/diff pass. diff --git a/backend/scripts/aws_direct_user_config.py b/backend/scripts/aws_direct_user_config.py index 0c83d02c7..8f85297b7 100644 --- a/backend/scripts/aws_direct_user_config.py +++ b/backend/scripts/aws_direct_user_config.py @@ -62,7 +62,9 @@ def generate_policies(*, bucket: str, private_prefix: str, user_arn: str, cleanu {"Sid": "DenyArtifactDeletion", "Effect": "Deny", "Principal": "*", "Action": ["s3:DeleteObject", "s3:DeleteObjectVersion"], "Resource": artifacts}, {"Sid": "DenyUnconditionalPut", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", - "Resource": all_objects, "Condition": {"Null": {"s3:if-none-match": "true"}, + "Resource": artifacts, "Condition": {"Null": {"s3:if-none-match": "true"}}}, + {"Sid": "DenyUnconditionalSourceCompletion", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", + "Resource": sources, "Condition": {"Null": {"s3:if-none-match": "true"}, "Bool": {"s3:ObjectCreationOperation": "true"}}}, ]}, } diff --git a/backend/tests/test_aws_direct_user_config.py b/backend/tests/test_aws_direct_user_config.py index dc0dd5552..ca5b3e96f 100644 --- a/backend/tests/test_aws_direct_user_config.py +++ b/backend/tests/test_aws_direct_user_config.py @@ -62,7 +62,11 @@ def test_conditional_completion_is_required_without_blocking_multipart_parts(): denials = {row["Sid"]: row for row in statements} assert denials["DenyUnconditionalPut"] == { "Sid": "DenyUnconditionalPut", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", - "Resource": BUCKET + "/*", "Condition": {"Null": {"s3:if-none-match": "true"}, + "Resource": ARTIFACTS, "Condition": {"Null": {"s3:if-none-match": "true"}}, + } + assert denials["DenyUnconditionalSourceCompletion"] == { + "Sid": "DenyUnconditionalSourceCompletion", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", + "Resource": SOURCES, "Condition": {"Null": {"s3:if-none-match": "true"}, "Bool": {"s3:ObjectCreationOperation": "true"}}, } assert denials["DenyInsecureTransport"]["Condition"] == {"Bool": {"aws:SecureTransport": "false"}} From f776a33e33819e6e19f415bd8deaa4e8f14da955 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:20:45 +0100 Subject: [PATCH 301/513] Select backend default review policy in public journey --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 +++++++++ .../test_journey_guide_recovery.py | 10 ++++++ cli/tests/journey/public_setup.py | 34 ++++++++++++------- 3 files changed, 47 insertions(+), 13 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 40ac5be6e..608a41d00 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9879,3 +9879,19 @@ for the actual bucket, namespace and same-account IAM users. ARCH/SEC review found no blocker to administrator application; metadata-list scope is explicit in administrator-handoff.txt. Live policy application, credentials provisioning and actual AWS source qualification remain unperformed. Pinned Ruff/diff pass. + +The first clean run with the repaired POST dispatcher (`f14a19179`) passed +public setup, real native PRE rejection for the missing-summary ZIP, correct +ZIP T4/T5 and automatic POST acceptance, exact accepted Contribution/export, +the source/effect read-only audit, incorrect-count ZIP POST failure with no +acceptance, and Operator custody. It stopped while creating the separate +review-required project: that fixture skipped `set-review-policy` entirely, +leaving the public activation context without a selected review policy. The +backend and built CLI both require such a selection. The journey now calls +the ordinary public `set-review-policy` with only required window and lease +fields in this branch, letting the backend apply its documented default +`human_review_required=true`; the automatic branch continues to pass explicit +`false`. It checks the selected response. A focused test pins omission versus +explicit false. This is a fixture correction, not a human acceptance route. +The stopped run's isolated PostgreSQL database and MinIO bucket were cleaned; +`review_pending` remains unobserved in that run. diff --git a/cli/tests/integration/test_journey_guide_recovery.py b/cli/tests/integration/test_journey_guide_recovery.py index 03028577c..370b6e97f 100644 --- a/cli/tests/integration/test_journey_guide_recovery.py +++ b/cli/tests/integration/test_journey_guide_recovery.py @@ -125,3 +125,13 @@ def test_guide_dispatch_refuses_wrong_acknowledged_setup(substitution): client, "token", COMMAND, SELECTOR ) assert client.calls == [(SELECTOR, 0), (COMMAND, None)] + + +def test_review_required_branch_selects_backend_default_by_omission(): + required = MODULE._review_policy_input(human_review_required=True) + automatic = MODULE._review_policy_input(human_review_required=False) + assert required == { + "review_preference_window_seconds": 3600, + "review_lease_duration_seconds": 1800, + } + assert automatic == required | {"human_review_required": False} diff --git a/cli/tests/journey/public_setup.py b/cli/tests/journey/public_setup.py index e2cd78195..d4e07ca5b 100644 --- a/cli/tests/journey/public_setup.py +++ b/cli/tests/journey/public_setup.py @@ -152,6 +152,17 @@ def validate_authored_rules_template(): ProjectGuideCompilationResult.model_validate(body) +def _review_policy_input(*, human_review_required: bool) -> dict: + """Omission selects the backend's required-review default for this guide.""" + body = { + "review_preference_window_seconds": 3600, + "review_lease_duration_seconds": 1800, + } + if not human_review_required: + body["human_review_required"] = False + return body + + def configure_guide(client, tokens, project_id, *, human_review_required=False): manager = tokens["manager"] guide = client.write_and_replay( @@ -172,25 +183,17 @@ def configure_guide(client, tokens, project_id, *, human_review_required=False): ) guide_id = guide["id"] policies = [ + ( + "set-review-policy", + _review_policy_input(human_review_required=human_review_required), + ), ( "set-revision-policy", {"max_revision_rounds": 2, "revision_deadline_hours": 48}, ), ] - if not human_review_required: - policies.insert( - 0, - ( - "set-review-policy", - { - "human_review_required": False, - "review_preference_window_seconds": 3600, - "review_lease_duration_seconds": 1800, - }, - ), - ) for command, body in policies: - client.write_and_replay( + selected = client.write_and_replay( manager, "project", "guide", @@ -201,6 +204,11 @@ def configure_guide(client, tokens, project_id, *, human_review_required=False): '"no-current-policy"', body=body, ) + if ( + command == "set-review-policy" + and selected["human_review_required"] is not human_review_required + ): + raise AssertionError("selected review mode differs from authored default") for document, content in zip( guide["documents"], (GUIDE, json.dumps(authored_rules()).encode()), strict=True ): From 439de11ff9679a8b4c835fcff49aacc953238b60 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:29:47 +0100 Subject: [PATCH 302/513] Record verified AWS read permissions and remaining bucket guard --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 608a41d00..644ea2d6d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9895,3 +9895,23 @@ fields in this branch, letting the backend apply its documented default explicit false. This is a fixture correction, not a human acceptance route. The stopped run's isolated PostgreSQL database and MinIO bucket were cleaned; `review_pending` remains unobserved in that run. + + +### Existing AWS runtime permissions rechecked after administrator update + +On 2026-11-24, the running API container's canonical isolated AWS credential +provider returned HTTP 200 for GetBucketVersioning (Enabled) and +ListObjectVersions under a fresh submission-source/v1 operation prefix. The +existing API key remains in its private mount; no credential was exposed or +provided to the runner. Receipt: `/tmp/submission-aws-permission-recheck-20261124.json`. + +A separate read of the actual bucket policy still returned the old five +statements: source keys remain outside DenyOutsideArtifactNamespace's allowed +SHA namespace and DenyArtifactDeletion still covers all objects. The reviewed +source bucket guard update is therefore not yet applied. Receipt: +`source-policy-applied-read-aed80ad765474a2eb0d7b7c2999a048f.json` in the private +AWS setup directory. The separate cleanup credential file location is pending. +These two successful reads close the previous read-permission failures only; +actual multipart, exact-version, restricted cleanup and lost-acknowledgement +AWS qualification remain unproved. No service, policy or deployment was changed +by these checks. From 3f95c7cca612b8a76263a8a383fb480d40669242 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:33:47 +0100 Subject: [PATCH 303/513] Add bounded operator SSH attachment for native fault qualification --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 82 +++++ .../README.md | 42 ++- .../public_fault_files.py | 16 + .../public_node_faults.py | 208 +++++++++++- .../public_runner_faults.py | 226 +++++++++++++ scripts/test_public_hosted_attachment.py | 317 ++++++++++++++++++ 6 files changed, 871 insertions(+), 20 deletions(-) create mode 100644 experiments/pilot04_external_checker_runtime/public_runner_faults.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 644ea2d6d..29d9befd1 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9915,3 +9915,85 @@ These two successful reads close the previous read-permission failures only; actual multipart, exact-version, restricted cleanup and lost-acknowledgement AWS qualification remain unproved. No service, policy or deployment was changed by these checks. + +### Prepare attach-only operator SSH fault bridge + +Bounded intent over5f3599d73: extend existing public_node_faults/private control +owner with run-ID-bound command/query/snapshot input and bounded trace reads; +add one thin public_runner_faults operator client using the approved pinned SSH +argv pattern, never a production endpoint. Allowed files: public_node_faults.py, +public_fault_files.py, new public_runner_faults.py, existing public fixture guard +module, the experiment README and this record. No CLI journey overlap. + +Commands retain one stable ID/action and query that same ID after lost ACK; +unknown transport never means safe to resend under a new ID. Snapshots bind exact +run/custody and bounded trace prefix. Reject wrong run/custody, mutable or aliased +private files, arbitrary actions, oversized/truncated output and malformed IDs. +SSH must use -F /dev/null, explicit identity, no agent, BatchMode and strict pinned +known-host checking. Keys stay operator-side and are never read/printed or passed +to API/workers. Application TLS source execution remains unchanged. + +Supervisor preparation must be finite and handle HUP/TERM through existing +restore/foreign-resource cleanup; independent operator-owned finite lifetime is +a prerequisite for future SSH disconnect qualification. The bridge attaches to +an already prepared verified run and does not start or deploy a remote service. +No remote connection, service/configuration mutation, native fault or paid call +will run while the connected journey owns the runner. The next live vector and +caller wiring remain separately qualified; no shared runner filesystem, API-side +KVM, cross-host monotonic comparison or aggregate-expiry inference is permitted. + +Read-only tracing identified that hardcoded fixture repository selection would +block the actual pinned runner cache. Within the same bridge files, require an +explicit locked image digest at supervisor startup and in every operator +request/response, resolve exactly one cache entry and bind it into the private +run metadata. Preserve original node-binding bytes/custody; no cache population, +image replacement, app caller or production configuration change is introduced. + +Implemented the attach-only bridge in the allowed six files. Every request +requires exact run ID, canonical node-binding SHA and explicit cached image +digest before command dispatch. Cached image selection is exact/unique and no +longer depends on the retired fixture repository name. The client reuses the +approved pinned SSH argument pattern and additionally disables global host-key +fallback and automatic pin updates. It never reads key bytes, starts a remote +supervisor or forwards credentials to API/workers. Requests/results and SSH +stdout/stderr have finite byte/time limits, and a dead local SSH PID during +cleanup cannot lose the original command ID. Unknown ACKs only query that same +ID; no automatic resend/new-ID path exists. + +Snapshots bind an append-only trace prefix and include a same-run/image/custody +cleanup receipt when present. Invalid IDs/pins, mutable private modes, symlinked +or incomplete traces, oversized output, rewound traces and incomplete cleanup +are refused. Cleanup observation requires empty typed resource lists and exact +foreign cleanup flags; the caller still compares the original config hash with +its independent preparation custody. The supervisor accepts a finite <=1800s +run budget, checks it before queued commands, uses bounded command subprocesses, +and preserves existing config/foreign cleanup under controlled HUP/TERM. This +is a bounded run loop plus restoration, not a host reboot/SIGKILL guarantee. +Actual launch must use an independently finite operator-owned supervisor/unit. + +Root review identified that O_NONBLOCK does not bound flock. Repaired new trace +reads to LOCK_SH|LOCK_NB; a held writer now means unavailable observation with +no polling. The named guard runs real local reader children under a five-second +failure bound: available control, held writer returns unavailable, available +again after release. Native/service operations remain mocked in the lifecycle +guard. Final bridge class passed9 in2.347s at +/tmp/submission-runner-bridge-guards-lock.log. Earlier lifecycle fixture errors +were a missing dummy socket_path; an intermediate request fixture accidentally +included response-only cleanup metadata and was correctly rejected. Neither +was a product/native failure or reason to relax the protocol. + +A bounded in-memory omission of only the before-dispatch custody/image check +makes the named stable-command/refusal guard fail after its valid control +(/tmp/submission-runner-bridge-custody-probe.json and +/tmp/submission-runner-bridge-custody-probe-current.log). No source file, SSH or +native state was mutated by the probe. AST checks show validate_node, +write_node_config, ForeignControl, runtime, owned_resources and +runtime_control_root unchanged (/tmp/submission-runner-bridge-owner-preservation.json). +Ruff/whitespace pass; final record/link checks follow this append. + +No live SSH connection, native fault, service/configuration/deployment change or +paid request occurred. Physical node custody checks and actual foreign VM +preservation are not proved by mocked lifecycle tests. Existing filesystem-based +trial callers are not yet wired to this bridge, no two-host fault drill has run, +and independent supervisor disconnect/restoration, API/runner separation, +aggregate native expiry and source/execution cancellation remain required. diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md index b32963be7..0fded1ff7 100644 --- a/experiments/pilot04_external_checker_runtime/README.md +++ b/experiments/pilot04_external_checker_runtime/README.md @@ -107,7 +107,8 @@ configuration and checks both typed adapter identities before starting services. The public drill deliberately injects faults. Start `public_node_faults.py` on the host against **only the dedicated drill unit**, with `--node-config`, `--unit` -and `--root /node-control`, plus `--owner-manifest `. +and `--root /node-control`, plus `--owner-manifest `, +`--run-id `, `--image-digest ` and a finite `--maximum-seconds` no greater than1800. Run it with the repository root on `PYTHONPATH`. The fresh control directory must be mode `0700` with no symlink or writable ancestor; control files are mode `0600` and accessed relative to its retained directory descriptor. It installs a pinned test-only Smol wrapper, @@ -175,8 +176,9 @@ production Flow, live model quality, native AWS S3 activation or hosted deployme The fault supervisor is an operator-local harness: it reads the owned node's lease/cgroup/Smol state and exchanges private command/trace files. It currently -has no authenticated remote fault-control/trace transport. The application's -production TLS connection to a separate runner does not supply that transport. +now has an attach-only operator SSH bridge, but its actual remote fault-control +and restoration sequence is not yet qualified. The application's production TLS +connection to a separate runner does not itself supply fault transport. Do not mount runner paths into the API host or move KVM to the API to make these vectors run. For the requested two-host deployment these fault vectors remain unqualified until an operator can address and collect exact evidence from the @@ -191,3 +193,37 @@ marker deadline is distinct from the aggregate VM envelope. An actual aggregate expiry receipt with unchanged epoch/deadline and exact deletion/foreign-resource checks is still required; a pure expiry guard or inner checker timeout does not qualify it. + +`public_runner_faults.py` attaches to an already verified, independently +supervised runner run. `RunnerFaultProfile` contains explicit runner IPv4 address, +operator identity/known-hosts paths, immutable source root, remote private control +root, run UUID, independently obtained native binding SHA and exact locked image digest. +The binding SHA hashes the canonical `node-binding.json` value (`sort_keys=True`, +compact separators, ASCII JSON); it is not the pretty-printed file's byte hash. Identity files +are stat-validated and passed only to OpenSSH; their bytes never enter this code, +API/worker settings or evidence. The approved SSH pattern uses `-F /dev/null`, +explicit identity, no agent, batch mode, strict checking, only the pinned known- +host file and no automatic host-key update. JSON requests travel on stdin to the +fixed existing operator module; no application endpoint is exposed. + +`RunnerFaults.command(action, command_id=...)` permits only the six existing +fixture actions. Run ID, custody SHA and selected image digest are checked on the runner before +any command dispatch. On uncertain transport, retain the exception's original +command ID and use `query(id, action)`; an absent response means unknown, never +permission to submit a new mutation. Snapshots include the same-run cleanup receipt when present and are bounded, +run-bound append-only observations; their timestamps stay on the runner and must not be compared to +application monotonic clocks. The bridge does not start/deploy a supervisor or +install its wrapper, and it does not wire the current filesystem-based trial +loops into a two-host run automatically. + +Before a live fault, an operator must stage reviewed source and independent +binary/config custody, verify compatible private ownership/modes and exact image +selection, obtain an exclusive drained-node window, and start the supervisor +under an independent finite operator-owned process/unit. The supervisor checks +its run budget between bounded commands, refuses late commands and routes HUP/ +TERM through its existing restore/foreign-resource cleanup; cleanup ignores +repeated HUP/TERM until it finishes. This is not a host-reboot/SIGKILL guarantee. +Require the same-run cleanup receipt, original config hash, removed owned +resources and exact foreign preservation/removal after disconnect. Missing or +failed restoration stops qualification and requires owner recovery. No live SSH +or native disconnect qualification is claimed by the local bridge guard tests. diff --git a/experiments/pilot04_external_checker_runtime/public_fault_files.py b/experiments/pilot04_external_checker_runtime/public_fault_files.py index 8dd296b32..f42197594 100644 --- a/experiments/pilot04_external_checker_runtime/public_fault_files.py +++ b/experiments/pilot04_external_checker_runtime/public_fault_files.py @@ -1,5 +1,6 @@ """Private, no-follow control files for the destructive node proof only.""" +import fcntl import json import os from pathlib import Path @@ -65,6 +66,21 @@ def read(self, name): raise ValueError('control file ownership/mode/size differs') return json.loads(source.read(65537)) + def trace_bytes(self): + """Read only a complete bounded trace under the writer's advisory lock.""" + descriptor = os.open('runtime-trace.jsonl', os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + dir_fd=self.fd) + with os.fdopen(descriptor, 'rb') as source: + fcntl.flock(source, fcntl.LOCK_SH | fcntl.LOCK_NB) + info = os.fstat(source.fileno()) + if (not stat.S_ISREG(info.st_mode) or info.st_uid != self.uid or info.st_gid != self.gid + or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1 or info.st_size > 1024 * 1024): + raise ValueError('trace ownership/mode/size differs') + data = source.read(1024 * 1024 + 1) + if len(data) > 1024 * 1024 or data and not data.endswith(b'\n'): + raise ValueError('trace is oversized or incomplete') + return data + def write(self, name, value): if Path(name).name != name: raise ValueError('control file is not a basename') diff --git a/experiments/pilot04_external_checker_runtime/public_node_faults.py b/experiments/pilot04_external_checker_runtime/public_node_faults.py index 11686ff38..7cb9f05a8 100644 --- a/experiments/pilot04_external_checker_runtime/public_node_faults.py +++ b/experiments/pilot04_external_checker_runtime/public_node_faults.py @@ -4,18 +4,39 @@ import asyncio import hashlib import json +import math import os +import re from pathlib import Path import signal import stat import subprocess +import sys import time -from uuid import uuid4 +from uuid import UUID, uuid4 from experiments.pilot04_external_checker_runtime.public_fault_files import PrivateControlDirectory, private_path HOSTED_IDENTITY = (10001, 10001) +CONTROL_PROTOCOL = 'workstream.operator_fault.v1' +ACTIONS = frozenset({'project_fail_once', 'project_fail_all', 'project_kill', 'clear', 'drained', 'restarted'}) +_COMMAND_ID = re.compile(r'[0-9a-f]{32}\Z') + + +def _run_id(value): + if type(value) is not str or str(UUID(value)) != value: + raise ValueError('fault run ID differs') + return value + + +def _unique_object(pairs): + value = {} + for key, item in pairs: + if key in value: + raise ValueError('duplicate fault JSON field') + value[key] = item + return value def _operator_controls(root): @@ -113,12 +134,23 @@ def assert_launches(root, start, *, creates, executions, project=True, shared_de return made -async def node_command(root, action): - """Send only a closed fixture command to the separately owned host supervisor.""" - identifier = uuid4().hex +async def node_command(root, action, *, identifier=None): + """Send one stable closed command; an uncertain ACK never changes its ID.""" + if action not in ACTIONS: + raise ValueError('unknown fixture action') + identifier = uuid4().hex if identifier is None else identifier + if type(identifier) is not str or _COMMAND_ID.fullmatch(identifier) is None: + raise ValueError('fault command ID differs') control = _operator_controls(root) try: - control.write(identifier + '.request', {'action': action}) + request = {'action': action} + try: + retained = control.read(identifier + '.request') + except FileNotFoundError: + control.write(identifier + '.request', request) + else: + if retained != request: + raise ValueError('fault command ID/action changed') finally: control.close() response = root / (identifier + '.response') @@ -138,6 +170,103 @@ async def node_command(root, action): +def _read_run(root, expected): + """Bind all operator observations to the same private finite supervisor run.""" + _run_id(expected) + control = _operator_controls(root) + try: + run = control.read('supervisor-run.json') + finally: + control.close() + if (type(run) is not dict or run.get('protocol_version') != CONTROL_PROTOCOL + or run.get('run_id') != expected or type(run.get('deadline_monotonic')) not in {int, float} + or not math.isfinite(run['deadline_monotonic']) or run['deadline_monotonic'] <= 0 + or type(run.get('maximum_seconds')) is not int or not 1 <= run['maximum_seconds'] <= 1800 + or type(run.get('binding_sha256')) is not str + or re.fullmatch(r'sha256:[0-9a-f]{64}', run['binding_sha256']) is None + or type(run.get('image_digest')) is not str + or re.fullmatch(r'sha256:[0-9a-f]{64}', run['image_digest']) is None): + raise ValueError('fault supervisor run differs') + return run + + +def _command_observation(root, identifier, action): + if type(identifier) is not str or _COMMAND_ID.fullmatch(identifier) is None or type(action) is not str or action not in ACTIONS: + raise ValueError('fault command selector differs') + control = _operator_controls(root) + try: + try: + request = control.read(identifier + '.request') + except FileNotFoundError: + return {'state': 'unknown', 'result': None} + if request != {'action': action}: + raise ValueError('fault command ID/action changed') + try: + result = control.read(identifier + '.response') + except FileNotFoundError: + return {'state': 'unknown', 'result': None} + if type(result) is not dict or result.get('action') != action or type(result.get('ok')) is not bool: + raise ValueError('fault command response differs') + return {'state': 'completed', 'result': result} + finally: + control.close() + + +async def control_request(root, request): + """SSH-only operator entry point; no deployment or arbitrary filesystem API.""" + if type(request) is not dict or request.get('protocol_version') != CONTROL_PROTOCOL: + raise ValueError('fault control protocol differs') + operation = request.get('operation') + expected = {'protocol_version', 'run_id', 'operation', 'binding_sha256', 'image_digest'} + if operation in {'command', 'query'}: + expected |= {'command_id', 'action'} + if set(request) != expected or operation not in {'command', 'query', 'snapshot'}: + raise ValueError('fault control request differs') + run = _read_run(root, request['run_id']) + if request['binding_sha256'] != run['binding_sha256'] or request['image_digest'] != run['image_digest']: + raise ValueError('fault custody pin differs') + response = {'protocol_version': CONTROL_PROTOCOL, 'run_id': run['run_id'], + 'operation': operation, 'binding_sha256': run['binding_sha256'], 'image_digest': run['image_digest']} + if operation == 'snapshot': + runtime_root = runtime_control_root(root) + identity = HOSTED_IDENTITY if runtime_root != root else (os.getuid(), os.getgid()) + trace = PrivateControlDirectory(runtime_root, uid=identity[0], gid=identity[1]) + try: + data = trace.trace_bytes() + finally: + trace.close() + events = [json.loads(line) for line in data.splitlines()] + if len(events) > 4096 or any(type(event) is not dict for event in events): + raise ValueError('fault trace record bound differs') + control = _operator_controls(root) + try: + try: + cleanup = control.read('supervisor-cleanup.json') + except FileNotFoundError: + cleanup = None + finally: + control.close() + if cleanup is not None and (type(cleanup) is not dict + or cleanup.get('protocol_version') != CONTROL_PROTOCOL + or cleanup.get('run_id') != run['run_id'] + or cleanup.get('binding_sha256') != run['binding_sha256'] + or cleanup.get('image_digest') != run['image_digest']): + raise ValueError('fault cleanup receipt differs') + response.update(events=events, cursor=len(events), trace_sha256='sha256:' + hashlib.sha256(data).hexdigest(), + cleanup=cleanup) + return response + identifier, action = request['command_id'], request['action'] + observed = _command_observation(root, identifier, action) + if operation == 'command' and observed['state'] != 'completed': + if time.monotonic() >= run['deadline_monotonic'] or (root / 'supervisor-cleanup.json').exists(): + raise RuntimeError('fault supervisor is not available') + private_path(root / 'supervisor-ready', 0o600) + await node_command(root, action, identifier=identifier) + observed = _command_observation(root, identifier, action) + response.update(command_id=identifier, action=action, **observed) + return response + + def _config_identity(hosted_runtime): if hosted_runtime: if os.getuid() != 0: @@ -278,13 +407,22 @@ def close(self): return {'name': self.name, 'machine_absent': True, 'disk_absent': True, 'cgroup_absent': True, 'process_reaped': True} -def serve(config_path, root, unit, manifest_path, *, hosted_runtime=False): +def serve(config_path, root, unit, manifest_path, *, hosted_runtime=False, run_id, maximum_seconds, image_digest): """Inject only project-start faults on a dedicated empty node and restore on exit.""" from shutil import copyfile + _run_id(run_id) + if type(maximum_seconds) is not int or not 1 <= maximum_seconds <= 1800: + raise ValueError('fault supervisor requires a finite <=1800s budget') os.umask(0o077) original, config_identity = _read_config(config_path, hosted_runtime) config = json.loads(original) + if type(image_digest) is not str or re.fullmatch(r'sha256:[0-9a-f]{64}', image_digest) is None: + raise ValueError('fault image digest differs') + matching = [entry for entry in config['cache'] if entry['platform_manifest_digest'] == image_digest] + if len(matching) != 1: + raise ValueError('fault image cache selection is absent or ambiguous') + project = matching[0] binding = validate_node(config_path, config, unit, manifest_path, hosted_runtime=hosted_runtime) identity = HOSTED_IDENTITY if hosted_runtime else None if any(owned_resources(config, identity=identity).values()): @@ -294,6 +432,12 @@ def serve(config_path, root, unit, manifest_path, *, hosted_runtime=False): if list(root.iterdir()): raise ValueError('fault root must be fresh and empty') control.write('node-binding.json', binding) + run_deadline = time.monotonic() + maximum_seconds + binding_sha256 = 'sha256:' + hashlib.sha256(json.dumps(binding, sort_keys=True, + separators=(',', ':'), allow_nan=False).encode()).hexdigest() + control.write('supervisor-run.json', {'protocol_version': CONTROL_PROTOCOL, 'run_id': run_id, + 'maximum_seconds': maximum_seconds, 'deadline_monotonic': run_deadline, 'image_digest': image_digest, + 'binding_sha256': binding_sha256}) runtime_root = root runtime_control = control if hosted_runtime: @@ -307,7 +451,6 @@ def serve(config_path, root, unit, manifest_path, *, hosted_runtime=False): wrapper.chmod(0o700) if hosted_runtime: os.chown(wrapper, *HOSTED_IDENTITY) - project = next(c for c in config['cache'] if c['repository'] == 'workstream-test/public-journey') state = runtime_root / 'runtime-mode.json' runtime_control.write(state.name, {'failures': 0, 'kill': False}) trace = runtime_root / 'runtime-trace.jsonl' @@ -330,15 +473,19 @@ def stop(_signum, _frame): raise KeyboardInterrupt foreign = ForeignControl(config, project, identity=identity) + previous_handlers = {item: signal.getsignal(item) for item in (signal.SIGTERM, signal.SIGHUP)} signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGHUP, stop) try: foreign.start() write_node_config(config_path, json.dumps(changed).encode(), config_identity, hosted_runtime=hosted_runtime) restart() (root / 'supervisor-ready').write_text('ready') - while True: + while time.monotonic() < run_deadline: for request in sorted(root.glob('*.request')): + if time.monotonic() >= run_deadline: + break response = request.with_suffix('.response') if response.exists(): continue @@ -351,7 +498,7 @@ def stop(_signum, _frame): runtime_control.write(state.name, {'failures': failures, 'kill': action == 'project_kill'}) if action == 'project_kill': result['controller_pid'] = int(subprocess.check_output( - ['systemctl', 'show', unit, '-p', 'MainPID', '--value'], text=True)) + ['systemctl', 'show', unit, '-p', 'MainPID', '--value'], text=True, timeout=15)) elif action == 'drained': deadline = time.monotonic() + 25 while any(owned_resources(config, root, identity=identity).values()): @@ -365,7 +512,7 @@ def stop(_signum, _frame): deadline = time.monotonic() + 25 while True: pid = int(subprocess.check_output( - ['systemctl', 'show', unit, '-p', 'MainPID', '--value'], text=True)) + ['systemctl', 'show', unit, '-p', 'MainPID', '--value'], text=True, timeout=15)) # A new owned VM after restart is the health/epoch proof; the # caller compares this PID to the durably recorded kill target. if pid and Path(f'/proc/{pid}/exe').resolve() == Path(binding['executable']): @@ -383,6 +530,9 @@ def stop(_signum, _frame): except KeyboardInterrupt: pass finally: + # Repeated disconnect/termination cannot interrupt bounded restoration. + signal.signal(signal.SIGTERM, signal.SIG_IGN) + signal.signal(signal.SIGHUP, signal.SIG_IGN) try: write_node_config(config_path, original, config_identity, hosted_runtime=hosted_runtime) restart() @@ -395,23 +545,47 @@ def stop(_signum, _frame): if any(resources.values()) or config_path.read_bytes() != original: raise RuntimeError('supervisor restore or owned cleanup is incomplete') control.write('supervisor-cleanup.json', { + 'protocol_version': CONTROL_PROTOCOL, 'run_id': run_id, + 'binding_sha256': binding_sha256, 'image_digest': image_digest, 'config_sha256': 'sha256:' + hashlib.sha256(original).hexdigest(), 'resources': resources, 'foreign': foreign_cleanup, }) (root / 'supervisor-ready').unlink(missing_ok=True) finally: - if runtime_control is not control: - runtime_control.close() - control.close() + try: + if runtime_control is not control: + runtime_control.close() + control.close() + finally: + for item, previous in previous_handlers.items(): + signal.signal(item, previous) if __name__ == '__main__': parser = argparse.ArgumentParser() - parser.add_argument('--node-config', type=Path, required=True) + parser.add_argument('--node-config', type=Path) parser.add_argument('--root', type=Path, required=True) - parser.add_argument('--unit', required=True) - parser.add_argument('--owner-manifest', type=Path, required=True) + parser.add_argument('--unit') + parser.add_argument('--owner-manifest', type=Path) + parser.add_argument('--request', action='store_true', help='process one bounded SSH operator request on stdin') + parser.add_argument('--run-id') + parser.add_argument('--maximum-seconds', type=int) + parser.add_argument('--image-digest') parser.add_argument('--hosted-runtime', action='store_true', help='root operator with the fixed runtime identity 10001:10001') args = parser.parse_args() - serve(args.node_config, args.root, args.unit, args.owner_manifest, hosted_runtime=args.hosted_runtime) + if args.request: + raw = sys.stdin.buffer.read(65537) + if len(raw) > 65536: + parser.error('fault request exceeds bound') + result = asyncio.run(control_request(args.root, json.loads(raw, object_pairs_hook=_unique_object, + parse_constant=lambda _: (_ for _ in ()).throw(ValueError('JSON constant'))))) + encoded = json.dumps(result, separators=(',', ':'), allow_nan=False).encode() + if len(encoded) > 2 * 1024 * 1024: + parser.error('fault response exceeds bound') + sys.stdout.buffer.write(encoded + b'\n') + else: + if not all((args.node_config, args.unit, args.owner_manifest, args.run_id, args.maximum_seconds, args.image_digest)): + parser.error('supervisor requires node config, unit, manifest, run ID and finite budget') + serve(args.node_config, args.root, args.unit, args.owner_manifest, hosted_runtime=args.hosted_runtime, + run_id=args.run_id, maximum_seconds=args.maximum_seconds, image_digest=args.image_digest) diff --git a/experiments/pilot04_external_checker_runtime/public_runner_faults.py b/experiments/pilot04_external_checker_runtime/public_runner_faults.py new file mode 100644 index 000000000..2f8793929 --- /dev/null +++ b/experiments/pilot04_external_checker_runtime/public_runner_faults.py @@ -0,0 +1,226 @@ +"""Operator-only SSH attachment to one already verified finite runner fault run. + +No credentials enter API/worker settings. This module never deploys or starts a +remote supervisor, changes a node configuration, or retries a command after an +uncertain acknowledgement. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass +import ipaddress +import json +import os +from pathlib import Path, PurePosixPath +import re +import shlex +import stat +from uuid import UUID, uuid4 + +from experiments.pilot04_external_checker_runtime.public_node_faults import ACTIONS, CONTROL_PROTOCOL, _unique_object + +_SHA256 = re.compile(r'sha256:[0-9a-f]{64}\Z') +_COMMAND_ID = re.compile(r'[0-9a-f]{32}\Z') + + +class FaultOutcomeUnknown(RuntimeError): + """Keep the original ID so the operator observes it instead of resending.""" + + def __init__(self, command_id): + self.command_id = command_id + super().__init__('runner fault outcome unknown; query the original command ID') + + +def _private_file(path, *, secret): + if not isinstance(path, Path) or not path.is_absolute() or path.resolve(strict=True) != path: + raise ValueError('SSH pin path differs') + info = path.lstat() + modes = {0o400, 0o600} if secret else {0o400, 0o600, 0o644} + owners = {os.getuid()} if secret else {0, os.getuid()} + if (not stat.S_ISREG(info.st_mode) or info.st_uid not in owners + or stat.S_IMODE(info.st_mode) not in modes or info.st_nlink != 1 + or not 0 < info.st_size <= 1024 * 1024): + raise ValueError('SSH pin ownership/mode differs') + + +def _remote_path(value): + if (type(value) is not str or not value.startswith('/') or '\x00' in value + or len(value) > 4096 or '\n' in value or '\r' in value + or str(PurePosixPath(value)) != value or '..' in PurePosixPath(value).parts): + raise ValueError('remote fault path differs') + return value + + +@dataclass(frozen=True) +class RunnerFaultProfile: + """Explicit operator pins; callers must obtain custody independently.""" + + host: str + identity_file: Path + known_hosts_file: Path + source_root: str + control_root: str + run_id: str + binding_sha256: str + image_digest: str + + def validate(self): + """Check explicit operator pins without reading identity key bytes.""" + if (type(self.host) is not str or type(self.run_id) is not str + or str(ipaddress.IPv4Address(self.host)) != self.host or str(UUID(self.run_id)) != self.run_id): + raise ValueError('SSH runner/run identity differs') + if (type(self.binding_sha256) is not str or _SHA256.fullmatch(self.binding_sha256) is None + or type(self.image_digest) is not str or _SHA256.fullmatch(self.image_digest) is None): + raise ValueError('runner custody pin differs') + _private_file(self.identity_file, secret=True) + _private_file(self.known_hosts_file, secret=False) + _remote_path(self.source_root) + _remote_path(self.control_root) + + def command(self): + """Reuse the approved pinned transport pattern, with a fixed remote action.""" + self.validate() + remote = shlex.join(['/usr/bin/sudo', '-n', '/usr/bin/env', 'PYTHONPATH=' + self.source_root, + '/usr/bin/python3', '-m', 'experiments.pilot04_external_checker_runtime.public_node_faults', + '--root', self.control_root, '--request']) + return ['ssh', '-F', '/dev/null', '-i', str(self.identity_file), + '-o', 'IdentitiesOnly=yes', '-o', 'IdentityAgent=none', '-o', 'BatchMode=yes', + '-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + str(self.known_hosts_file), + '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'UpdateHostKeys=no', + '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3', + 'ubuntu@' + self.host, remote] + + +async def _bounded_read(stream, limit): + chunks, count = [], 0 + while True: + chunk = await stream.read(min(65536, limit + 1 - count)) + if not chunk: + return b''.join(chunks) + count += len(chunk) + if count > limit: + raise ValueError('SSH output exceeds bound') + chunks.append(chunk) + + + +class RunnerFaults: + """One SSH operator context with append-only trace observation.""" + + def __init__(self, profile: RunnerFaultProfile): + profile.validate() + self.profile, self._events, self._trace_sha256 = profile, (), None + + async def _exchange(self, request): + process, readers = None, [] + try: + encoded = json.dumps(request, separators=(',', ':'), allow_nan=False).encode() + async with asyncio.timeout(60): + process = await asyncio.create_subprocess_exec(*self.profile.command(), + stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + process.stdin.write(encoded) + await process.stdin.drain() + process.stdin.close() + readers = [asyncio.create_task(_bounded_read(process.stdout, 2 * 1024 * 1024)), + asyncio.create_task(_bounded_read(process.stderr, 16384))] + output, _ = await asyncio.gather(*readers) + if await process.wait() != 0: + raise RuntimeError('SSH fault request failed') + response = json.loads(output, object_pairs_hook=_unique_object, + parse_constant=lambda _: (_ for _ in ()).throw(ValueError('JSON constant'))) + if (type(response) is not dict or response.get('protocol_version') != CONTROL_PROTOCOL + or response.get('run_id') != self.profile.run_id + or response.get('operation') != request['operation'] + or response.get('binding_sha256') != self.profile.binding_sha256 + or response.get('image_digest') != self.profile.image_digest): + raise ValueError('fault response identity differs') + return response + except BaseException as error: + if process is not None and process.returncode is None: + try: + process.kill() # Only the owned local SSH process, never a remote controller PID. + except ProcessLookupError: + pass + try: + await asyncio.wait_for(process.wait(), timeout=5) + except TimeoutError: + pass + for reader in readers: + if not reader.done(): + reader.cancel() + await asyncio.gather(*readers, return_exceptions=True) + if request['operation'] == 'command': + raise FaultOutcomeUnknown(request['command_id']) from None + raise RuntimeError('runner fault observation unavailable') from error + + def _request(self, operation, **fields): + return {'protocol_version': CONTROL_PROTOCOL, 'run_id': self.profile.run_id, + 'operation': operation, 'binding_sha256': self.profile.binding_sha256, + 'image_digest': self.profile.image_digest, **fields} + + async def command(self, action, *, command_id=None): + """Issue once; any uncertain completion retains the original command ID.""" + identifier = uuid4().hex if command_id is None else command_id + if type(action) is not str or action not in ACTIONS or type(identifier) is not str or _COMMAND_ID.fullmatch(identifier) is None: + raise ValueError('fault command selector differs') + response = await self._exchange(self._request('command', command_id=identifier, action=action)) + observed = self._command_response(response, identifier, action) + if observed['state'] != 'completed' or observed['result']['ok'] is not True: + raise FaultOutcomeUnknown(identifier) + return observed + + async def query(self, command_id, action): + """Observe the original command without enqueuing another mutation.""" + if type(command_id) is not str or _COMMAND_ID.fullmatch(command_id) is None or type(action) is not str or action not in ACTIONS: + raise ValueError('fault command selector differs') + response = await self._exchange(self._request('query', command_id=command_id, action=action)) + return self._command_response(response, command_id, action) + + @staticmethod + def _command_response(response, identifier, action): + if (set(response) != {'protocol_version', 'run_id', 'operation', 'binding_sha256', 'image_digest', + 'command_id', 'action', 'state', 'result'} + or response['command_id'] != identifier or response['action'] != action + or response['state'] not in {'unknown', 'completed'}): + raise FaultOutcomeUnknown(identifier) + result = response['result'] + if response['state'] == 'unknown': + if result is not None: + raise FaultOutcomeUnknown(identifier) + elif type(result) is not dict or result.get('action') != action or type(result.get('ok')) is not bool: + raise FaultOutcomeUnknown(identifier) + return response + + async def snapshot(self): + """Read a bounded trace prefix and same-run cleanup observation.""" + response = await self._exchange(self._request('snapshot')) + if (set(response) != {'protocol_version', 'run_id', 'operation', 'binding_sha256', 'image_digest', + 'events', 'cursor', 'trace_sha256', 'cleanup'} + or type(response['events']) is not list or len(response['events']) > 4096 + or type(response['cursor']) is not int or response['cursor'] != len(response['events']) + or type(response['trace_sha256']) is not str or _SHA256.fullmatch(response['trace_sha256']) is None + or any(type(event) is not dict for event in response['events']) + or response['events'][:len(self._events)] != list(self._events) + or len(response['events']) == len(self._events) and self._trace_sha256 is not None + and response['trace_sha256'] != self._trace_sha256): + raise RuntimeError('runner trace changed or exceeded its bound') + cleanup = response['cleanup'] + if cleanup is not None: + if (type(cleanup) is not dict or cleanup.get('protocol_version') != CONTROL_PROTOCOL + or cleanup.get('run_id') != self.profile.run_id + or cleanup.get('binding_sha256') != self.profile.binding_sha256 + or cleanup.get('image_digest') != self.profile.image_digest + or type(cleanup.get('config_sha256')) is not str + or _SHA256.fullmatch(cleanup['config_sha256']) is None + or type(cleanup.get('resources')) is not dict + or set(cleanup['resources']) != {'disks', 'leases', 'machines', 'cgroups'} + or any(type(value) is not list or value for value in cleanup['resources'].values()) + or type(cleanup.get('foreign')) is not dict + or type(cleanup['foreign'].get('name')) is not str or not cleanup['foreign']['name'] + or any(cleanup['foreign'].get(field) is not True for field in + ('machine_absent', 'disk_absent', 'cgroup_absent', 'process_reaped'))): + raise RuntimeError('runner cleanup is incomplete or belongs to another run') + self._events = tuple(response['events']) + self._trace_sha256 = response['trace_sha256'] + return response diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 14d424064..d7eadb7dd 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -732,5 +732,322 @@ async def exercise(): setattr(target, field, original) +class RunnerFaultBridgeContracts(unittest.TestCase): + def profile(self, root): + from experiments.pilot04_external_checker_runtime.public_runner_faults import RunnerFaultProfile + key, known = root / 'identity', root / 'known-hosts' + key.write_text('dummy-private-key-never-read') + known.write_text('pinned-public-host-key-fixture') + key.chmod(0o600) + known.chmod(0o600) + return RunnerFaultProfile('13.61.148.238', key, known, '/opt/workstream/reviewed-source', + '/var/lib/workstream-operator/fault-run', str(uuid4()), 'sha256:' + 'a' * 64, 'sha256:' + 'b' * 64) + + def root(self, directory, profile): + import time + from experiments.pilot04_external_checker_runtime.public_fault_files import PrivateControlDirectory + from experiments.pilot04_external_checker_runtime.public_node_faults import CONTROL_PROTOCOL + control = PrivateControlDirectory(directory) + control.write('supervisor-run.json', {'protocol_version': CONTROL_PROTOCOL, + 'run_id': profile.run_id, 'maximum_seconds': 30, 'deadline_monotonic': time.monotonic() + 30, + 'binding_sha256': profile.binding_sha256, 'image_digest': profile.image_digest}) + (directory / 'runtime-trace.jsonl').write_bytes(b'') + (directory / 'runtime-trace.jsonl').chmod(0o600) + (directory / 'supervisor-ready').write_text('ready') + (directory / 'supervisor-ready').chmod(0o600) + return control + + def response(self, profile, operation, **fields): + if operation == 'snapshot': + fields = {'cleanup': None} | fields + from experiments.pilot04_external_checker_runtime.public_node_faults import CONTROL_PROTOCOL + return {'protocol_version': CONTROL_PROTOCOL, 'run_id': profile.run_id, + 'operation': operation, 'binding_sha256': profile.binding_sha256, + 'image_digest': profile.image_digest, **fields} + + def test_pinned_ssh_uses_fixed_module_and_never_reads_identity_bytes(self): + import shlex + with tempfile.TemporaryDirectory() as temporary: + profile = self.profile(Path(temporary)) + with patch.object(Path, 'read_bytes', side_effect=AssertionError('must not read key')), \ + patch.object(Path, 'read_text', side_effect=AssertionError('must not read key')): + command = profile.command() + self.assertEqual(command[:3], ['ssh', '-F', '/dev/null']) + self.assertEqual(command[-2], 'ubuntu@13.61.148.238') + for option in ('IdentitiesOnly=yes', 'IdentityAgent=none', 'BatchMode=yes', + 'StrictHostKeyChecking=yes', 'GlobalKnownHostsFile=/dev/null', 'UpdateHostKeys=no', + 'UserKnownHostsFile=' + str(profile.known_hosts_file)): + self.assertIn(option, command) + remote = shlex.split(command[-1]) + self.assertEqual(remote[-3:], ['--root', profile.control_root, '--request']) + self.assertIn('experiments.pilot04_external_checker_runtime.public_node_faults', remote) + profile.identity_file.chmod(0o644) + with self.assertRaisesRegex(ValueError, 'ownership/mode'): + profile.command() + + def test_runner_commands_have_stable_id_and_refuse_action_or_run_substitution(self): + from experiments.pilot04_external_checker_runtime.public_node_faults import control_request + async def exercise(): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + profile = self.profile(directory) + control = self.root(directory, profile) + request = self.response(profile, 'command', command_id='b' * 32, action='clear') + async def respond(): + while not (directory / ('b' * 32 + '.request')).exists(): + await asyncio.sleep(.001) + self.assertEqual(control.read('b' * 32 + '.request'), {'action': 'clear'}) + control.write('b' * 32 + '.response', {'action': 'clear', 'ok': True}) + try: + result, _ = await asyncio.gather(control_request(directory, request), respond()) + self.assertEqual(result['state'], 'completed') + with patch('experiments.pilot04_external_checker_runtime.public_node_faults.node_command', + new=AsyncMock(side_effect=AssertionError('duplicate mutation'))): + self.assertEqual(await control_request(directory, request), result) + for change in ({'run_id': str(uuid4())}, {'binding_sha256': 'sha256:' + 'f' * 64}, + {'image_digest': 'sha256:' + 'f' * 64}, + {'action': 'project_kill'}, {'action': 'arbitrary'}): + with self.subTest(change=change), self.assertRaises(ValueError): + await control_request(directory, request | change) + with patch('experiments.pilot04_external_checker_runtime.public_node_faults.node_command', + new=AsyncMock(side_effect=AssertionError('custody checked after dispatch'))) as dispatch: + with self.assertRaisesRegex(ValueError, 'custody pin'): + await control_request(directory, request | {'command_id': 'f' * 32, + 'binding_sha256': 'sha256:' + 'f' * 64}) + dispatch.assert_not_awaited() + self.assertFalse((directory / ('f' * 32 + '.request')).exists()) + before = {item.name for item in directory.iterdir()} + unknown = await control_request(directory, request | {'operation': 'query', 'command_id': 'c' * 32}) + self.assertEqual((unknown['state'], unknown['result']), ('unknown', None)) + self.assertEqual({item.name for item in directory.iterdir()}, before) + finally: + control.close() + asyncio.run(exercise()) + + def test_snapshot_binds_run_and_rejects_aliased_or_incomplete_trace(self): + from experiments.pilot04_external_checker_runtime.public_node_faults import control_request + async def exercise(): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + profile = self.profile(directory) + control = self.root(directory, profile) + request = self.response(profile, 'snapshot') + request.pop('cleanup') + trace = directory / 'runtime-trace.jsonl' + data = b'{"operation":"create","name":"owned"}\n' + try: + trace.write_bytes(data) + result = await control_request(directory, request) + self.assertEqual(result['cursor'], 1) + self.assertEqual(result['events'], [{'operation': 'create', 'name': 'owned'}]) + self.assertEqual(result['trace_sha256'], 'sha256:' + hashlib.sha256(data).hexdigest()) + trace.write_bytes(data[:-1]) + with self.assertRaisesRegex(ValueError, 'incomplete'): + await control_request(directory, request) + trace.write_bytes(data) + trace.chmod(0o644) + with self.assertRaisesRegex(ValueError, 'ownership/mode'): + await control_request(directory, request) + trace.chmod(0o600) + retained = directory / 'retained-trace' + trace.rename(retained) + trace.symlink_to(retained) + with self.assertRaises(OSError): + await control_request(directory, request) + finally: + control.close() + asyncio.run(exercise()) + + def test_trace_snapshot_refuses_held_writer_lock_without_waiting(self): + import fcntl + code = """import sys +from pathlib import Path +from experiments.pilot04_external_checker_runtime.public_fault_files import PrivateControlDirectory +control = PrivateControlDirectory(Path(sys.argv[1])) +try: + try: + control.trace_bytes() + except BlockingIOError: + print('unavailable') + else: + print('available') +finally: + control.close() +""" + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + trace = directory / 'runtime-trace.jsonl' + trace.write_bytes(b'{}\n') + trace.chmod(0o600) + def read(): + try: + result = subprocess.run([sys.executable, '-c', code, str(directory)], + capture_output=True, text=True, timeout=5, check=True, cwd=ROOT) + except subprocess.TimeoutExpired: + self.fail('trace snapshot blocked behind the held writer lock') + return result.stdout.strip() + self.assertEqual(read(), 'available') + with trace.open('a') as writer: + fcntl.flock(writer, fcntl.LOCK_EX | fcntl.LOCK_NB) + self.assertEqual(read(), 'unavailable') + self.assertEqual(read(), 'available') + + def test_ssh_lost_ack_is_observed_by_same_id_without_repeating_mutation(self): + from experiments.pilot04_external_checker_runtime.public_runner_faults import RunnerFaults, FaultOutcomeUnknown + async def exercise(): + with tempfile.TemporaryDirectory() as temporary: + profile = self.profile(Path(temporary)) + client = RunnerFaults(profile) + identifier = 'd' * 32 + response = self.response(profile, 'query', command_id=identifier, action='clear', + state='completed', result={'action': 'clear', 'ok': True}) + written = [] + def process(body, *, lost=False): + output, errors = asyncio.StreamReader(), asyncio.StreamReader() + output.feed_data(json.dumps(body).encode()) + output.feed_eof() + errors.feed_eof() + if lost: + output.read = AsyncMock(side_effect=TimeoutError('lost ACK after input')) + return SimpleNamespace(stdin=SimpleNamespace(write=lambda data: written.append(json.loads(data)), + drain=AsyncMock(), close=lambda: None), stdout=output, stderr=errors, + returncode=None if lost else 0, wait=AsyncMock(return_value=0), + kill=unittest.mock.Mock(side_effect=ProcessLookupError()) if lost else unittest.mock.Mock()) + with patch('asyncio.create_subprocess_exec', new=AsyncMock(side_effect=[process({}, lost=True), process(response)])) as execute: + with self.assertRaises(FaultOutcomeUnknown) as unknown: + await client.command('clear', command_id=identifier) + self.assertEqual(unknown.exception.command_id, identifier) + observed = await client.query(identifier, 'clear') + self.assertEqual(observed['state'], 'completed') + self.assertEqual(execute.await_count, 2) + self.assertEqual([item['operation'] for item in written], ['command', 'query']) + for change in ({'run_id': str(uuid4())}, {'binding_sha256': 'sha256:' + 'f' * 64}): + with patch('asyncio.create_subprocess_exec', new=AsyncMock(return_value=process(response | change))): + with self.assertRaisesRegex(RuntimeError, 'observation unavailable'): + await client.query(identifier, 'clear') + self.assertEqual(sum(item['operation'] == 'command' for item in written), 1) + self.assertTrue(all(item['command_id'] == identifier for item in written)) + asyncio.run(exercise()) + + def test_remote_snapshot_cannot_rewind_or_rebind_existing_prefix(self): + from experiments.pilot04_external_checker_runtime.public_runner_faults import RunnerFaults + async def exercise(): + with tempfile.TemporaryDirectory() as temporary: + profile = self.profile(Path(temporary)) + client = RunnerFaults(profile) + first = self.response(profile, 'snapshot', events=[{'name': 'exact'}], cursor=1, + trace_sha256='sha256:' + 'b' * 64) + with patch.object(client, '_exchange', new=AsyncMock(return_value=first)): + await client.snapshot() + for changed in (dict(first, events=[], cursor=0), + dict(first, events=[{'name': 'foreign'}]), dict(first, trace_sha256='sha256:' + 'c' * 64)): + with self.subTest(changed=changed), patch.object(client, '_exchange', new=AsyncMock(return_value=changed)): + with self.assertRaisesRegex(RuntimeError, 'trace changed'): + await client.snapshot() + asyncio.run(exercise()) + + def test_same_run_cleanup_receipt_requires_exact_absence_and_foreign_cleanup(self): + from experiments.pilot04_external_checker_runtime.public_runner_faults import RunnerFaults + async def exercise(): + with tempfile.TemporaryDirectory() as temporary: + profile = self.profile(Path(temporary)) + client = RunnerFaults(profile) + cleanup = self.response(profile, 'snapshot') + cleanup.pop('operation') + cleanup.pop('cleanup') + cleanup.update(config_sha256='sha256:' + 'c' * 64, + resources={'disks': [], 'leases': [], 'machines': [], 'cgroups': []}, + foreign={'name': 'exact-foreign', 'machine_absent': True, 'disk_absent': True, + 'cgroup_absent': True, 'process_reaped': True}) + reply = self.response(profile, 'snapshot', events=[], cursor=0, + trace_sha256='sha256:' + 'd' * 64, cleanup=cleanup) + with patch.object(client, '_exchange', new=AsyncMock(return_value=reply)): + self.assertEqual((await client.snapshot())['cleanup'], cleanup) + for change in ({'run_id': str(uuid4())}, {'image_digest': 'sha256:' + 'f' * 64}, + {'resources': dict(cleanup['resources'], leases=None)}, + {'resources': dict(cleanup['resources'], machines=['owned-remains'])}, + {'foreign': dict(cleanup['foreign'], process_reaped=False)}): + invalid = reply | {'cleanup': cleanup | change} + with self.subTest(change=change), patch.object(client, '_exchange', new=AsyncMock(return_value=invalid)): + with self.assertRaisesRegex(RuntimeError, 'cleanup is incomplete'): + await client.snapshot() + asyncio.run(exercise()) + + def test_finite_supervisor_and_hup_restore_only_owned_config(self): + from experiments.pilot04_external_checker_runtime import public_node_faults as owner + import signal + for hup in (False, True): + with self.subTest(hup=hup), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + config = root / 'node.json' + original = json.dumps({'socket_path': '/unused/native.sock', 'smol': {'binary': '/unused/smol', 'binary_sha256': 'sha256:' + 'a' * 64}, + 'cache': [{'repository': 'independent-real-registry', 'platform_manifest_digest': 'sha256:' + 'b' * 64, 'smol': {'archive': '/unused/image'}}]}).encode() + config.write_bytes(original) + config.chmod(0o600) + states, handlers, clock = [], {}, [0.0] + def monotonic(): + clock[0] += .1 + return clock[0] + def sleep(_seconds): + if hup: + handlers[signal.SIGHUP](signal.SIGHUP, None) + class Foreign: + created = False + process = None + def __init__(self, *args, **kwargs): + pass + def start(self): + self.created, self.process = True, object() + states.append('foreign_started') + self.check() + def check(self): + states.append('foreign_preserved') + def close(self): + self_test.assertEqual(handlers[signal.SIGTERM], signal.SIG_IGN) + self_test.assertEqual(handlers[signal.SIGHUP], signal.SIG_IGN) + states.append('foreign_removed') + return {'name': 'foreign-fixture', 'machine_absent': True, 'disk_absent': True, + 'cgroup_absent': True, 'process_reaped': True} + self_test = self + control_root = root / 'control' + with patch.object(owner, 'validate_node', return_value={'verified': True}), \ + patch.object(owner, 'owned_resources', return_value={'machines': [], 'disks': [], 'leases': [], 'cgroups': []}), \ + patch.object(owner, 'ForeignControl', Foreign), \ + patch.object(owner.subprocess, 'run') as restart, \ + patch.object(owner.time, 'monotonic', side_effect=monotonic), \ + patch.object(owner.time, 'sleep', side_effect=sleep), \ + patch.object(owner.signal, 'getsignal', return_value=signal.SIG_DFL), \ + patch.object(owner.signal, 'signal', side_effect=lambda item, handler: handlers.update({item: handler})): + owner.serve(config, control_root, 'owned-unit', root / 'not-read-manifest', + run_id=str(uuid4()), maximum_seconds=1, image_digest='sha256:' + 'b' * 64) + self.assertEqual(config.read_bytes(), original) + self.assertEqual(restart.call_count, 2) + self.assertTrue(all(call.args[0] == ['sudo', 'systemctl', 'restart', 'owned-unit'] + for call in restart.call_args_list)) + receipt = json.loads((control_root / 'supervisor-cleanup.json').read_text()) + self.assertEqual(receipt['config_sha256'], 'sha256:' + hashlib.sha256(original).hexdigest()) + self.assertTrue(receipt['foreign']['machine_absent']) + self.assertEqual(receipt['image_digest'], 'sha256:' + 'b' * 64) + self.assertEqual(receipt['protocol_version'], owner.CONTROL_PROTOCOL) + self.assertFalse((control_root / 'supervisor-ready').exists()) + self.assertEqual(states, ['foreign_started', 'foreign_preserved', 'foreign_preserved', 'foreign_removed']) + self.assertEqual(handlers[signal.SIGTERM], signal.SIG_DFL) + self.assertEqual(handlers[signal.SIGHUP], signal.SIG_DFL) + + def test_bounded_ssh_reader_refuses_oversized_output(self): + from experiments.pilot04_external_checker_runtime.public_runner_faults import _bounded_read + async def exercise(): + stream = asyncio.StreamReader() + stream.feed_data(b'1234') + stream.feed_eof() + self.assertEqual(await _bounded_read(stream, 4), b'1234') + stream = asyncio.StreamReader() + stream.feed_data(b'12345') + stream.feed_eof() + with self.assertRaisesRegex(ValueError, 'output exceeds'): + await _bounded_read(stream, 4) + asyncio.run(exercise()) + + if __name__ == '__main__': unittest.main() From e0dca7221e5d4fd673b7a4dfe4787bd387a66451 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:47:07 +0100 Subject: [PATCH 304/513] Provide private scratch for AWS source qualification --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ scripts/qualify_submission_source.py | 10 ++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 29d9befd1..9ff501e58 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -9997,3 +9997,18 @@ preservation are not proved by mocked lifecycle tests. Existing filesystem-based trial callers are not yet wired to this bridge, no two-host fault drill has run, and independent supervisor disconnect/restoration, API/runner separation, aggregate native expiry and source/execution cancellation remain required. + + +### AWS source qualification scratch prerequisite + +The first live attempt at439de11ff verified both exact IAM users but stopped +before source intent creation or provider writes: enabled storage Settings +requires artifact_scratch_root, which the drill omitted. Journal +live-620b55b065974b6f9e99db3dc8948560.jsonl contains only started and ValidationError. +The bounded repair supplies an owned temporary scratch directory to the two +existing production adapter constructors and removes it on exit. Only the +qualification script and this evidence record change; no product validation, +credential policy, source ownership, retention or cleanup rule changes. +Verification uses the real AWS drill after the prerequisite repair. The bucket +policy now exactly matches the reviewed guard; the cleanup credential is +installed on the API host with0400 ownership10001 and its exact IAM ARN verified. diff --git a/scripts/qualify_submission_source.py b/scripts/qualify_submission_source.py index 80d083327..269845708 100644 --- a/scripts/qualify_submission_source.py +++ b/scripts/qualify_submission_source.py @@ -13,6 +13,7 @@ import os from pathlib import Path import subprocess +import tempfile from botocore.exceptions import ClientError from app.adapters.artifacts import create_artifact_store_bootstrap @@ -33,7 +34,7 @@ CLEANUP = "arn:aws:iam::094032936130:user/workstream-source-cleanup" -def store_for(key_file, principal): +def store_for(key_file, principal, *, scratch_root): limits = {f"artifact_admission_{scope}_maximum_bytes": 6 * 1024**2 for scope in ("task", "producer", "project", "deployment")} settings = Settings(environment="production", artifact_store_backend="s3_compatible", @@ -41,6 +42,7 @@ def store_for(key_file, principal): artifact_s3_bucket=BUCKET, artifact_s3_private_prefix=PREFIX, artifact_s3_credential_mode="aws_access_key", artifact_s3_runtime_user_arn=principal, artifact_s3_direct_user_credential_file=key_file, + artifact_scratch_root=scratch_root, artifact_stream_buffer_bytes=65536, artifact_s3_operation_total_timeout_seconds=60, **limits) bootstrap = create_artifact_store_bootstrap(settings) @@ -226,7 +228,7 @@ def main(): os.environ.pop(key) fd = os.open(args.report, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) runtime = cleanup_store = None - with os.fdopen(fd, "w") as output: + with os.fdopen(fd, "w") as output, tempfile.TemporaryDirectory(prefix="workstream-source-qualification-") as scratch: def emit(event, **facts): output.write(json.dumps({"event": event, "at": datetime.now(UTC).isoformat(), **facts}) + "\n") output.flush() @@ -235,8 +237,8 @@ def emit(event, **facts): head = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() emit("started", commit=head, bucket=BUCKET, prefix=PREFIX, runtime=RUNTIME, cleanup=CLEANUP, script_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()) - runtime = store_for(args.runtime_key_file.resolve(), RUNTIME) - cleanup_store = store_for(args.cleanup_key_file.resolve(), CLEANUP) + runtime = store_for(args.runtime_key_file.resolve(), RUNTIME, scratch_root=Path(scratch)) + cleanup_store = store_for(args.cleanup_key_file.resolve(), CLEANUP, scratch_root=Path(scratch)) asyncio.run(asyncio.wait_for(qualify(runtime, cleanup_store, emit), timeout=900)) emit("completed", result="passed") print("AWS source adapter qualification passed; see private report") From 1089e1ccd42db2b36e4daa0c9b1854033ff481e1 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:57:02 +0100 Subject: [PATCH 305/513] Report safe failure locations in AWS source drill --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 12 ++++++++++++ scripts/qualify_submission_source.py | 6 +++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 9ff501e58..d5990f8d9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10012,3 +10012,15 @@ credential policy, source ownership, retention or cleanup rule changes. Verification uses the real AWS drill after the prerequisite repair. The bucket policy now exactly matches the reviewed guard; the cleanup credential is installed on the API host with0400 ownership10001 and its exact IAM ARN verified. + + +The workstation correctly rejects ambient ~/.aws files; the failed second +attempt's two exact keys were independently confirmed to have no versions or +multipart uploads. A clean isolated container using the production dependencies, +read-only current source and two private selected keys reached real multipart +upload, conditional completion and exact source readback, then AssertionError +before the permission/cleanup checkpoint. Its journal is +live-d0dad07781b744538b4a46b1fce9802c.jsonl; synthetic targets remain explicitly +owned for reconciliation. The drill now records traceback locations (no locals +or SDK messages) and its own static AssertionError text to diagnose the exact +failure. This is diagnostic-only; no acceptance assertion is removed or widened. diff --git a/scripts/qualify_submission_source.py b/scripts/qualify_submission_source.py index 269845708..5ee56f4aa 100644 --- a/scripts/qualify_submission_source.py +++ b/scripts/qualify_submission_source.py @@ -14,6 +14,7 @@ from pathlib import Path import subprocess import tempfile +import traceback from botocore.exceptions import ClientError from app.adapters.artifacts import create_artifact_store_bootstrap @@ -243,7 +244,10 @@ def emit(event, **facts): emit("completed", result="passed") print("AWS source adapter qualification passed; see private report") except BaseException as error: - emit("failed", error_type=type(error).__name__) + emit("failed", error_type=type(error).__name__, + assertion=str(error) if type(error) is AssertionError else None, + frames=[{"file": Path(frame.filename).name, "line": frame.lineno, + "function": frame.name} for frame in traceback.extract_tb(error.__traceback__)]) print("AWS source adapter qualification failed; retain journal and owned targets") raise SystemExit(1) from None finally: From 074cade5e36f944033803225df78488b0dd0bf83 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:01:52 +0100 Subject: [PATCH 306/513] Use existing retained artifact for AWS cleanup denial proof --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 ++++++++++++++ docs/operations_aws_s3_credentials.md | 10 ++++++++-- scripts/qualify_submission_source.py | 16 +++++++++++++--- 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d5990f8d9..afc77cca9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10024,3 +10024,17 @@ live-d0dad07781b744538b4a46b1fce9802c.jsonl; synthetic targets remain explicitly owned for reconciliation. The drill now records traceback locations (no locals or SDK messages) and its own static AssertionError text to diagnose the exact failure. This is diagnostic-only; no acceptance assertion is removed or widened. + + +### Conclusive retained-artifact permission control + +The diagnostic replay isolated the failure to the cleanup GET of an invented +all-zero SHA key. AWS returned NoSuchKey/404, not a conclusive permission denial. +ARCH/SEC reviewed a narrow correction: require an operator-selected existing +canonical SHA key, prove its existence with runtime HEAD, then require cleanup +HEAD to fail with403/AccessDenied. HEAD exercises GetObject permission without +reading retained user bytes. Run this control before synthetic source creation. +Keep all source multipart/overwrite/deletion/abort and lost-ack checks unchanged; +never accept404 as permission-denial proof and never create an undeletable SHA +fixture. Allowed changes are the operator drill, its operations instructions and +this record. Real AWS replay provides verification; no product policy changes. diff --git a/docs/operations_aws_s3_credentials.md b/docs/operations_aws_s3_credentials.md index a4737e02a..f1e20509e 100644 --- a/docs/operations_aws_s3_credentials.md +++ b/docs/operations_aws_s3_credentials.md @@ -96,8 +96,14 @@ time-limited permission record required by ordinary storage operations. The reviewed pilot drill is [qualify_submission_source.py](../scripts/qualify_submission_source.py). It is deliberately pinned to the current pilot bucket, prefix and two principal ARNs; it is not a generic cleanup command. Run from the repository root with -`PYTHONPATH=backend`, explicit `--runtime-key-file`, `--cleanup-key-file` and a -new private `--report` JSONL path. Both key files must have mode `0400`. +`PYTHONPATH=backend`, explicit `--runtime-key-file`, `--cleanup-key-file`, +`--retained-artifact-key` and a new private `--report` JSONL path. Select an +existing current SHA artifact key for the runtime HEAD existence control and +cleanup HEAD denial check; neither check reads its body. A nonexistent key's +404 is not evidence of denied read permission. Both key files must have mode `0400`. +Use an isolated runtime without ambient AWS configuration or credential files; +the production adapter rejects those files even when SDK environment variables +are cleared. The drill supplies its own private temporary scratch directory. It creates only new synthetic operation keys, journals each target before provider I/O, and cleans only their exact handles/versions. A failed run retains its journal and uncertain targets for reconciliation. It does not test product diff --git a/scripts/qualify_submission_source.py b/scripts/qualify_submission_source.py index 5ee56f4aa..488bfa075 100644 --- a/scripts/qualify_submission_source.py +++ b/scripts/qualify_submission_source.py @@ -12,6 +12,7 @@ import json import os from pathlib import Path +import re import subprocess import tempfile import traceback @@ -98,9 +99,15 @@ async def denied(store, operation, **kwargs): raise AssertionError("restricted operation unexpectedly permitted") -async def qualify(runtime, cleanup_store, emit): +async def qualify(runtime, cleanup_store, emit, *, retained_artifact_key): cleanup = S3SubmissionSourceCleanup(cleanup_store) owned = set() + # A missing key is not a permission-denial control. HEAD checks the same + # GetObject permission without retrieving retained user bytes. + async with runtime._client() as client: + await client.head_object(Bucket=BUCKET, Key=retained_artifact_key) + await denied(cleanup_store, "head_object", Key=retained_artifact_key) + emit("passed", check="existing_retained_artifact_cleanup_read_denied") def intent(): location = SubmissionSourceLocation(operation_id=new_record_id(), namespace_id="primary", @@ -162,7 +169,6 @@ async def remove_owned(source, upload): await cleanup_store.request_source_abort(competitor.upload) assert await cleanup_store.source_upload_parts_absent(competitor.upload) await denied(cleanup_store, "put_object", Key=key, Body=b"forbidden", IfNoneMatch="*") - await denied(cleanup_store, "get_object", Key=PREFIX + "/sha256/00/" + "0" * 62) emit("passed", check="conditional_versioned_multipart_and_separate_principals") async with lose_ack(cleanup_store, "delete_object", emit) as delete_effect: try: @@ -220,7 +226,10 @@ def main(): parser.add_argument("--runtime-key-file", required=True, type=Path) parser.add_argument("--cleanup-key-file", required=True, type=Path) parser.add_argument("--report", required=True, type=Path) + parser.add_argument("--retained-artifact-key", required=True) args = parser.parse_args() + if re.fullmatch(re.escape(PREFIX) + r"/sha256/[0-9a-f]{2}/[0-9a-f]{62}", args.retained_artifact_key) is None: + parser.error("retained artifact key must be an existing canonical SHA key") if not __debug__: parser.error("qualification requires Python assertions enabled; do not use -O") # Never load the invalid default AWS profile or ambient credentials. @@ -240,7 +249,8 @@ def emit(event, **facts): script_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()) runtime = store_for(args.runtime_key_file.resolve(), RUNTIME, scratch_root=Path(scratch)) cleanup_store = store_for(args.cleanup_key_file.resolve(), CLEANUP, scratch_root=Path(scratch)) - asyncio.run(asyncio.wait_for(qualify(runtime, cleanup_store, emit), timeout=900)) + asyncio.run(asyncio.wait_for(qualify(runtime, cleanup_store, emit, + retained_artifact_key=args.retained_artifact_key), timeout=900)) emit("completed", result="passed") print("AWS source adapter qualification passed; see private report") except BaseException as error: From d0f0c021e349b6939368cb9b351db1bb84f16b45 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:55:06 +0100 Subject: [PATCH 307/513] fix(submission): keep preparation reads historical --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 12 +++ .../app/api/deps/project_preparation_reads.py | 2 +- backend/app/api/routes/contributor_reads.py | 4 +- .../api/routes/project_preparation_reads.py | 4 +- .../checkers/selected_pre_submit_reads.py | 10 +- .../tests/contributor_reads/test_authority.py | 18 ++-- .../contributor_reads/test_consistency.py | 15 ++- .../contributor_reads/test_projection.py | 22 +++-- backend/tests/contributor_reads/test_scale.py | 92 ++++++++++++++++--- .../migrations/test_source_pre_cutover.py | 44 ++++++++- .../project_reads/test_preparations_reads.py | 57 +++--------- .../tests/project_reads/test_work_scale.py | 14 ++- 12 files changed, 205 insertions(+), 89 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index afc77cca9..a6cd44852 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10038,3 +10038,15 @@ Keep all source multipart/overwrite/deletion/abort and lost-ack checks unchanged never accept404 as permission-denial proof and never create an undeletable SHA fixture. Allowed changes are the operator drill, its operations instructions and this record. Real AWS replay provides verification; no product policy changes. + +### Keep historical preparation reads separate from current source progress + +Intent: the retained preparation GET must show pre-cutover v1 history only. The current source-v2 PRE run has a separate operation-progress API. Reading it through the historical ART projection currently reports `passed/storing` after real T5 because that projection joins only pre-cutover durable intents and admissions; reporting this false intermediate state is a read defect. The CHECKERS run reader has only ART preparation-read consumers, so restrict its contributor and project selectors to v1 rows with null `source_operation_id`. Do not alter current source execution, operation progress, retained decoding, or authorization. The existing authorized task/project route still gates the historical reader. + +Allowed files: `backend/app/modules/checkers/selected_pre_submit_reads.py`, affected contributor/project preparation tests and scale fixture, `backend/tests/migrations/test_source_pre_cutover.py` for a genuine captured consumed-history projection after upgrade, contributor/project preparation GET route and dependency docstrings, their generated MCP description snapshots after canonical refresh, and this record. Prohibited: schema/trigger relaxation, fabricated accepted source state, separate current-progress implementation on the old route, new public route, removed tests or smaller performance dataset, bypassed foreign keys, or changed AUTH selectors. Acceptance: current v2 is omitted on both historical routes while its operation remains visible through the already tested current progress API; the unchanged checksum-bound captured v1 consumed snapshot projects its exact submitted admission and findings; corrupt completed retained facts still fail closed; 10,000 tasks, 20,000 submissions and 30 preparation-history rows keep the read budget test. Build scale-only rows from canonical retained v1 values with row identities and digests matched by the retained decoder, retaining FK enforcement. Risk: filtering by schema label alone could expose a forged v1 body on a source row, and synthetic benchmark rows could bypass decoder/ownership semantics. Architecture/security and CI integrity review should inspect both predicates, archived custody, page sizes and actor filtering. Human review focus is the archived v1 proof and the scale fixture's exact row integrity. Execute pure checks first; defer PostgreSQL setup until the shared native journey slot is free. + +The implementation filters the historical reader by `source_operation_id IS NULL`; its existing closed decoder then requires the indexed request/terminal values to match. Actual archived v1 `consumed` rows are read after a real upgrade in the existing migration test, including contributor and project projections and a foreign-actor empty result. The performance fixture remains synthetic bulk restore: it borrows the one real run's execute/finalize audit foreign-key references solely to satisfy the closed table shape, while deriving each v1 request/terminal body and digest from the retained canonical decoder. It does not prove those 30 or 10,000 benchmark runs were independently authorized or executed. The exact old public cursor filter/limit denial assertions moved to the project scale test so dropping the current-source rows does not discard them. Pure retained-decoder/projection tests passed 17/17; all 40 affected test nodes collected; Ruff and whitespace checks passed. PostgreSQL route, archive and scale execution is pending the shared slot, so no implementation pass is yet claimed here. + +The first isolated PostgreSQL pass at schema 0090 ran six selected cases: four passed, including the current-source public selector controls and contributor scale. The archived consumed-history case stopped before the added read assertions because its older 0083-to-current function-set equality now spans the merged main and later cleanup migrations. The test now compares exact function definitions only across 0083-to-0084, where the admission guard is the intended sole change, then separately requires all captured rows to survive through current schema before reading archived history. Project scale reached the historical preparation page within its unchanged one-second budget (0.707 and 0.499 seconds), but an unrelated submission continuation took 1.008 seconds and failed the same inherited budget. No budget was widened or performance result credited. The first runner's database cleanup completed; the two affected cases await a focused replay. + +Focused replay at schema 0090 passed the archived consumed-v1 read after the corrected exact migration comparison. The project scale case remained red on the unchanged one-second gate: submissions filtered took 1.905 seconds, assignments 1.316 seconds, and preparation pages 1.889/1.129 seconds under the shared host's load. Those broad overruns do not isolate a preparation-query regression, and this commit does not claim the scale gate passed. The two-case run had one pass and one failure in 462.90 seconds, with full isolated database cleanup. A later controlled performance measurement remains necessary before crediting the one-second project scale requirement. diff --git a/backend/app/api/deps/project_preparation_reads.py b/backend/app/api/deps/project_preparation_reads.py index 75d2a3e96..2010dabdb 100644 --- a/backend/app/api/deps/project_preparation_reads.py +++ b/backend/app/api/deps/project_preparation_reads.py @@ -16,7 +16,7 @@ class ProjectPreparationReads: - """C8: a project's ZIP preparations across contributors, newest first, with finding counts only.""" + """C8: historical project ZIP preparations, newest first, with counts only.""" def __init__(self, runner: ProjectManagementReadRunner, preparations: SubmissionBundlePreparationReadPort): """Compose the read runner with the ART preparation projection.""" diff --git a/backend/app/api/routes/contributor_reads.py b/backend/app/api/routes/contributor_reads.py index 8a9ccf35c..a0ba83229 100644 --- a/backend/app/api/routes/contributor_reads.py +++ b/backend/app/api/routes/contributor_reads.py @@ -82,7 +82,7 @@ async def read_my_summary(reads: Reads, project_id: UUID | None = None) -> Contr async def list_my_preparations( task_id: UUID, reads: Reads, limit: PageLimit = 25, cursor: PageCursor = None, ) -> SubmissionBundlePreparationPage: - """Your ZIP preparations for one task you hold or held, newest first.""" + """Your historical ZIP preparations for one task, newest first.""" return await reads.preparations(task_id=task_id, limit=limit, cursor=cursor) @@ -94,5 +94,5 @@ async def list_my_preparations( async def read_my_preparation( task_id: UUID, preparation_id: UUID, reads: Reads, ) -> SubmissionBundlePreparationDetail: - """One of your preparations with every intake finding; others are not found.""" + """One historical preparation with its intake findings; others are not found.""" return await reads.preparation(task_id=task_id, preparation_id=preparation_id) diff --git a/backend/app/api/routes/project_preparation_reads.py b/backend/app/api/routes/project_preparation_reads.py index f71277a3e..f2b4cddc3 100644 --- a/backend/app/api/routes/project_preparation_reads.py +++ b/backend/app/api/routes/project_preparation_reads.py @@ -1,4 +1,4 @@ -"""A Project Manager reads a project's ZIP preparations across contributors.""" +"""A Project Manager reads historical ZIP preparations across contributors.""" from typing import Annotated from uuid import UUID @@ -27,7 +27,7 @@ async def list_project_preparations( limit: Annotated[int, Query(ge=1, le=100)] = 50, cursor: Annotated[str | None, Query(min_length=1, max_length=512)] = None, ) -> ProjectSubmissionBundlePreparationPage: - """Every contributor's ZIP preparations, newest first, with finding counts and no findings or files. + """Historical ZIP preparations, newest first, with counts and no findings or files. ``outcome=failed`` lists completed intake checks that blocked the ZIP. """ diff --git a/backend/app/modules/checkers/selected_pre_submit_reads.py b/backend/app/modules/checkers/selected_pre_submit_reads.py index 1f244ad97..428e91db4 100644 --- a/backend/app/modules/checkers/selected_pre_submit_reads.py +++ b/backend/app/modules/checkers/selected_pre_submit_reads.py @@ -72,7 +72,7 @@ def _view(row: SelectedPreSubmitRun, *, source_contracts: SelectedPreSubmitSourc class SelectedPreSubmitRunReader: - """Fixed columns and revalidated terminal bodies, newest first by ``(queued_at, id)``.""" + """Retained preparation history, newest first by ``(queued_at, id)``.""" def __init__(self, session: AsyncSession, *, source_contracts: SelectedPreSubmitSourceContracts) -> None: """Read in the caller's response transaction.""" @@ -90,10 +90,13 @@ async def _page(self, statement, limit, before): return tuple(_view(row, source_contracts=self._source_contracts) for row in rows[:limit]), len(rows) > limit async def read_contributor_runs(self, *, actor_profile_id, task_id, run_id, limit, before): - """One contributor's runs for one task, optionally one exact run.""" + """One contributor's retained v1 runs; source-v2 uses operation progress.""" run = SelectedPreSubmitRun + # A v1 body on a source-linked row is excluded; _view validates the + # remaining body's schema and indexed identity before disclosure. statement = select(run).where( run.actor_profile_id == str(actor_profile_id), run.task_id == str(task_id), + run.source_operation_id.is_(None), ) if run_id is not None: statement = statement.where(run.id == str(run_id)) @@ -103,9 +106,10 @@ async def read_project_runs( self, *, project_id: UUID, statuses: tuple[SelectedPreSubmitRunStatus, ...] | None, eligible: bool | None, limit: int, before, ): - """Every contributor's runs in one project, filtered by stored status and eligibility.""" + """Retained v1 runs in one project, filtered by stored outcome facts.""" run = SelectedPreSubmitRun statement = select(run).where(run.project_id == str(project_id)) + statement = statement.where(run.source_operation_id.is_(None)) if statuses is not None: statement = statement.where(run.status.in_(statuses)) if eligible is not None: diff --git a/backend/tests/contributor_reads/test_authority.py b/backend/tests/contributor_reads/test_authority.py index b842477ed..d8b04e2e0 100644 --- a/backend/tests/contributor_reads/test_authority.py +++ b/backend/tests/contributor_reads/test_authority.py @@ -19,7 +19,7 @@ async def _preparation(task): async with db_session.get_session_factory()() as session: - return await session.scalar(select(SelectedPreSubmitRun.id).where(SelectedPreSubmitRun.task_id == task)) + return await session.scalar(select(SelectedPreSubmitRun).where(SelectedPreSubmitRun.task_id == task)) async def test_another_contributor_never_receives_the_owners_records(task_client, monkeypatch): @@ -32,7 +32,7 @@ async def test_another_contributor_never_receives_the_owners_records(task_client summary = await get_ok(task_client, f"{ME}/summary", project_id=project) assert summary["assignments"] == {"active": 0, "closed": 0} and not any(summary["submissions"].values()) assert await status_of(task_client, preparations_path(task)) == 404 - assert await status_of(task_client, f"{preparations_path(task)}/{preparation}") == 404 + assert await status_of(task_client, f"{preparations_path(task)}/{preparation.id}") == 404 async def test_project_filter_without_a_submitter_grant_is_not_found(task_client, monkeypatch): @@ -70,7 +70,7 @@ async def test_revoked_submitter_loses_every_own_work_read(task_client, monkeypa assert (await get_ok(task_client, f"{ME}/{name}"))["items"] == [] assert await status_of(task_client, f"{ME}/{name}", project_id=project) == 404 assert await status_of(task_client, preparations_path(task)) == 404 - assert await status_of(task_client, f"{preparations_path(task)}/{preparation}") == 404 + assert await status_of(task_client, f"{preparations_path(task)}/{preparation.id}") == 404 assert (await get_ok(task_client, f"{ME}/projects"))["items"] == [] @@ -81,11 +81,17 @@ async def test_preparation_of_another_contributor_is_not_found(task_client, monk foreign = await _preparation(foreign_task) set_dev_actor(monkeypatch, roles="", subject=OWNER) assert await status_of(task_client, preparations_path(foreign_task)) == 404 - assert await status_of(task_client, f"{preparations_path(foreign_task)}/{foreign}") == 404 - assert await status_of(task_client, f"{preparations_path(own_task)}/{foreign}") == 404 + assert await status_of(task_client, f"{preparations_path(foreign_task)}/{foreign.id}") == 404 + assert await status_of(task_client, f"{preparations_path(own_task)}/{foreign.id}") == 404 assert await status_of(task_client, f"{preparations_path(own_task)}/{new_record_id()}") == 404 set_dev_actor(monkeypatch, roles="", subject=OTHER) - assert (await get_ok(task_client, f"{preparations_path(foreign_task)}/{foreign}"))["preparation_id"] == foreign + assert await status_of(task_client, f"{preparations_path(foreign_task)}/{foreign.id}") == 404 + assert foreign.source_operation_id is not None + progress = await get_ok( + task_client, f"/api/v1/tasks/{foreign_task}/submission-operations", + operation_id=foreign.source_operation_id, + ) + assert progress["operation_id"] == foreign.source_operation_id async def test_each_read_commits_its_exact_decision_and_denials(task_client, monkeypatch): diff --git a/backend/tests/contributor_reads/test_consistency.py b/backend/tests/contributor_reads/test_consistency.py index 10d1fd416..c4f92d587 100644 --- a/backend/tests/contributor_reads/test_consistency.py +++ b/backend/tests/contributor_reads/test_consistency.py @@ -1,9 +1,11 @@ """Each contributor read is one REPEATABLE READ snapshot; integrity gaps are retryable 503s.""" -import dataclasses +from datetime import UTC, datetime from sqlalchemy import text +from app.core.identifiers import new_record_id +from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitRunView from app.modules.checkers.selected_pre_submit_reads import SelectedPreSubmitRunReader from app.modules.tasks.contributor_reads import ContributorWorkReader from app.modules.tasks.repository import TaskRepository @@ -55,11 +57,14 @@ async def no_terms(repository, project_id, version_ids): async def test_completed_preparation_without_execution_facts_is_unavailable(task_client, monkeypatch): _project, task, _submission = await submitted_case(task_client, monkeypatch) - original = SelectedPreSubmitRunReader.read_contributor_runs - async def without_execution(reader, **kwargs): - views, more = await original(reader, **kwargs) - return tuple(dataclasses.replace(view, status="completed", terminal=None) for view in views), more + now = datetime.now(UTC) + return (SelectedPreSubmitRunView( + run_id=new_record_id(), actor_profile_id=kwargs["actor_profile_id"], + task_id=kwargs["task_id"], assignment_id=new_record_id(), status="completed", + archive_sha256="sha256:" + "a" * 64, archive_byte_count=1, + queued_at=now, completed_at=now, terminal=None, + ),), False monkeypatch.setattr(SelectedPreSubmitRunReader, "read_contributor_runs", without_execution) await as_actor(task_client, monkeypatch, OWNER) diff --git a/backend/tests/contributor_reads/test_projection.py b/backend/tests/contributor_reads/test_projection.py index 52e7af9ee..a3b10027a 100644 --- a/backend/tests/contributor_reads/test_projection.py +++ b/backend/tests/contributor_reads/test_projection.py @@ -23,7 +23,7 @@ from app.modules.compensation.api.award_reads import ContributorAwardTotal from app.modules.compensation.awards.read_repository import ContributionAwardReadRepository from tests.submission_fixtures import route_retained_checker_remediation, seed_retained_checker_run -from tests.test_tasks import set_dev_actor +from tests.test_tasks import auth_headers, set_dev_actor from .support import ME, OWNER, as_actor, get_ok, preparations_path, submitted_case from tests.checkers.external.test_selected_pre_submit_coordination import ( _source_completed_execution, @@ -97,19 +97,21 @@ async def test_incremental_submission_read_sees_findings_committed_before_routin assert after["updated_at"] >= since -async def test_preparation_reads_return_own_submitted_preparation(task_client, monkeypatch): +async def test_current_source_run_uses_operation_progress_not_historical_preparation(task_client, monkeypatch): _project, task, submission = await submitted_case(task_client, monkeypatch) async with db_session.get_session_factory()() as session: run = await session.scalar(select(SelectedPreSubmitRun).where(SelectedPreSubmitRun.task_id == task)) + assert run is not None and run.source_operation_id is not None await as_actor(task_client, monkeypatch, OWNER) - [summary] = (await get_ok(task_client, preparations_path(task)))["items"] - assert summary["preparation_id"] == run.id and "findings" not in summary - assert (summary["outcome"], summary["state"], summary["submission_id"]) == ("passed", "submitted", submission) - assert summary["archive_sha256"] == run.archive_sha256 - assert summary["archive_byte_count"] == run.archive_byte_count - detail = await get_ok(task_client, f"{preparations_path(task)}/{run.id}") - assert detail | {"findings": None} == summary | {"findings": None} - assert {item["source"] for item in detail["findings"]} >= {"workstream_default"} + assert (await get_ok(task_client, preparations_path(task)))["items"] == [] + hidden = await task_client.get( + f"{preparations_path(task)}/{run.id}", headers=auth_headers(), + ) + assert hidden.status_code == 404 + current = await get_ok(task_client, f"/api/v1/tasks/{task}/submission-operations", + operation_id=run.source_operation_id) + assert current["operation_state"] == "finalized" + assert current["submission_id"] == submission async def test_summary_counts_own_work(task_client, monkeypatch): diff --git a/backend/tests/contributor_reads/test_scale.py b/backend/tests/contributor_reads/test_scale.py index ebc0a21be..2f3f630ca 100644 --- a/backend/tests/contributor_reads/test_scale.py +++ b/backend/tests/contributor_reads/test_scale.py @@ -3,11 +3,18 @@ import json import secrets import time +from dataclasses import replace from datetime import timedelta +from uuid import UUID import asyncpg from app.core.identifiers import new_record_id +from app.modules.checkers.api.historical_selected_pre_submit import ( + HistoricalSelectedPreSubmitReservation, + HistoricalSelectedPreSubmitTerminal, +) +from tests.checkers.external.test_selected_pre_submit_coordination import _retained_v1 from tests.test_tasks import set_dev_actor from .support import ME, MANAGER, OWNER, get_ok, preparations_path, submitted_case @@ -33,8 +40,79 @@ async def _clone(connection, table, template, varying, constant=None): ) +async def _retained_preparation_clones(connection, template, start, *, preparations): + """Scale-only canonical v1 history; borrow real audit FKs, never claim owner issuance.""" + captured = _retained_v1("selected_pre_v1_completed") + request = HistoricalSelectedPreSubmitReservation.from_canonical_body(captured["request"]) + terminal = HistoricalSelectedPreSubmitTerminal.from_canonical_body(captured["terminal"]) + owner = await connection.fetchrow( + "SELECT actor_profile_id, identity_link_id, project_id, task_id, assignment_id " + "FROM public.selected_pre_submit_runs WHERE id=$1", template, + ) + assert owner is not None + identifiers = { + "actor_profile_id": UUID(str(owner["actor_profile_id"])), + "identity_link_id": UUID(str(owner["identity_link_id"])), + "project_id": UUID(str(owner["project_id"])), + "task_id": UUID(str(owner["task_id"])), + "assignment_id": UUID(str(owner["assignment_id"])), + } + runs = [new_record_id() for _ in range(preparations)] + constant = { + "source_operation_id": "NULL", "status": "'completed'", "eligible": "TRUE", + "lease_generation": "1", "policy_sha256": f"'{request.policy_sha256}'", + "default_behavior_sha256": f"'{request.default_behavior_sha256}'", + "default_input_sha256": f"'{request.default_input_sha256}'", + "archive_sha256": f"'{request.archive_sha256}'", + "archive_byte_count": str(request.archive_byte_count), + "semantic_manifest_sha256": f"'{request.semantic_manifest_sha256}'", + "execution_budget_ms": str(request.execution_budget_ms), + } + for offset in range(0, preparations, 500): + batch = runs[offset:offset + 500] + values = {name: [] for name in ( + "id", "idempotency_key", "prepared_generation_id", "request_json", + "request_digest", "terminal_json", "terminal_digest", "lease_id", + "queued_at", "started_at", "completed_at", "lease_expires_at", + )} + for index, run_id in enumerate(batch, start=offset): + queued_at = start - timedelta(seconds=preparations - index) + started_at, completed_at = queued_at + timedelta(milliseconds=10), queued_at + timedelta(milliseconds=20) + current = replace( + request, **identifiers, attempt_id=run_id, idempotency_key=new_record_id(), + prepared_generation_id=new_record_id(), admission_lineage=None, + attempt_request_digest="sha256:" + secrets.token_hex(32), + ) + lease = replace( + terminal.lease, reservation=current, lease_id=new_record_id(), + lease_expires_at=queued_at + timedelta(seconds=60), + ) + completed = replace( + terminal, lease=lease, queued_at=queued_at, started_at=started_at, + completed_at=completed_at, + ) + for name, value in ( + ("id", run_id), ("idempotency_key", current.idempotency_key), + ("prepared_generation_id", current.prepared_generation_id), + ("request_json", json.dumps(current.canonical_body())), + ("request_digest", current.request_digest), + ("terminal_json", json.dumps(completed.canonical_body())), + ("terminal_digest", completed.terminal_digest), + ("lease_id", lease.lease_id), ("queued_at", queued_at), + ("started_at", started_at), ("completed_at", completed_at), + ("lease_expires_at", lease.lease_expires_at), + ): + values[name].append(value) + await _clone(connection, "selected_pre_submit_runs", template, { + name: ("jsonb" if name.endswith("_json") else "timestamptz" if name.endswith("_at") + else "text" if name.endswith("_digest") else "uuid", entries) + for name, entries in values.items() + }, constant) + return runs + + async def _seed(database_url, task, submission, *, preparations=PREPARATIONS): - """Clone the real claimed task, assignment, attempt and ``preparations`` runs under bulk restore.""" + """Bulk-restore 10k tasks, 20k submissions and canonical v1 read-history rows.""" connection = await asyncpg.connect(database_url.replace("+asyncpg", "")) try: start = await connection.fetchval("SELECT updated_at FROM public.workstream_tasks WHERE id=$1", task) @@ -64,15 +142,7 @@ async def _seed(database_url, task, submission, *, preparations=PREPARATIONS): "submission_bundle_admission_id", "artifact_binding_id", "artifact_content_id", "supersedes_submission_id", ), "NULL")}) - runs = [new_record_id() for _ in range(preparations)] - await _clone(connection, "selected_pre_submit_runs", run, { - "id": ("uuid", runs), "idempotency_key": ("uuid", [new_record_id() for _ in runs]), - "request_digest": ("text", ["sha256:" + secrets.token_hex(32) for _ in runs]), - "queued_at": ("timestamptz", [start + timedelta(seconds=index + 1) for index in range(preparations)]), - }, {"status": "'queued'", "lease_generation": "0", **dict.fromkeys(( - "terminal_json", "terminal_digest", "eligible", "lease_id", "lease_expires_at", "started_at", - "completed_at", "execute_evidence_id", "finalize_evidence_id", - ), "NULL")}) + runs = await _retained_preparation_clones(connection, run, start, preparations=preparations) # Settle deferred foreign keys (including the nullable intake pointer) # before ALTER TABLE; none are disabled during this fixture restore. await connection.execute("SET CONSTRAINTS ALL IMMEDIATE") @@ -120,7 +190,7 @@ async def test_pages_and_summary_meet_budget_at_scale(task_client, monkeypatch, walked += [item["preparation_id"] for item in step["items"]] if (cursor := step["next_cursor"]) is None: break - assert walked[:PREPARATIONS] == [str(run) for run in reversed(runs)] and len(set(walked)) == PREPARATIONS + 1 + assert walked == [str(run) for run in reversed(runs)] summary = await get_ok(task_client, f"{ME}/summary") assert summary["assignments"]["active"] == TASKS + 1 assert sum(summary["submissions"].values()) == TASKS * SUBMISSIONS_PER_TASK + 1 diff --git a/backend/tests/migrations/test_source_pre_cutover.py b/backend/tests/migrations/test_source_pre_cutover.py index f7efc42d4..8a5f0c5a8 100644 --- a/backend/tests/migrations/test_source_pre_cutover.py +++ b/backend/tests/migrations/test_source_pre_cutover.py @@ -5,6 +5,7 @@ import hashlib import json from pathlib import Path +from uuid import UUID import asyncpg import pytest @@ -194,7 +195,7 @@ async def _upgrade_admission_guard_behind_writer(url): try: async with writer.transaction(): await writer.execute('LOCK TABLE public.submission_bundle_admissions IN ROW EXCLUSIVE MODE') - migration = asyncio.create_task(asyncio.to_thread(command.upgrade, _config(), current_schema_revision())) + migration = asyncio.create_task(asyncio.to_thread(command.upgrade, _config(), '0084_submission_source_binding')) async def wait_for_lock(): while True: @@ -235,17 +236,52 @@ async def test_source_binding_cutover_preserves_history_and_closes_old_consumpti if state == 'ready': await _upgrade_admission_guard_behind_writer(isolated_database_env) else: - await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + await asyncio.to_thread(command.upgrade, _config(), '0084_submission_source_binding') after, new_functions = await _retained_rows_and_functions(isolated_database_env, snapshot['tables']) - await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) - assert await _retained_rows_and_functions(isolated_database_env, snapshot['tables']) == (after, new_functions) assert after == before assert set(old_functions) == set(new_functions) assert {k for k in old_functions if old_functions[k] != new_functions[k]} == {'guard_submission_bundle_admission_lineage()'} + await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) + current_rows, _ = await _retained_rows_and_functions(isolated_database_env, snapshot['tables']) + assert current_rows == after if state == 'ready': await _refuse_old_consumption_and_allow_stale( isolated_database_env, snapshots['consumed']['tables']['submission_bundle_admissions'][0], ) + else: + from app.adapters.artifacts import submission_bundle_preparation_reader + from app.core.identifiers import new_record_id + + run = snapshot['tables']['selected_pre_submit_runs'][0] + admission = snapshot['tables']['submission_bundle_admissions'][0] + async with db_session.get_session_factory()() as session: + reader = submission_bundle_preparation_reader(session) + (detail,), more = await reader.read( + actor_profile_id=UUID(run['actor_profile_id']), task_id=UUID(run['task_id']), + preparation_id=UUID(run['id']), limit=2, before=None, + ) + (project_item,), project_more = await reader.read_project( + project_id=UUID(run['project_id']), outcome='passed', limit=2, before=None, + ) + foreign, foreign_more = await reader.read( + actor_profile_id=new_record_id(), task_id=UUID(run['task_id']), + preparation_id=UUID(run['id']), limit=2, before=None, + ) + assert not more and not project_more + assert foreign == () and not foreign_more + assert detail.preparation_id == UUID(run['id']) + assert (detail.outcome, detail.state, detail.submission_id) == ( + 'passed', 'submitted', UUID(admission['consumed_by_submission_id']), + ) + assert detail.archive_sha256 == run['archive_sha256'] + assert detail.archive_byte_count == run['archive_byte_count'] + assert detail.findings and {item['source'] for item in detail.findings} >= {'workstream_default'} + assert project_item.preparation_id == detail.preparation_id + assert project_item.actor_profile_id == UUID(run['actor_profile_id']) + assert (project_item.outcome, project_item.state, project_item.submission_id) == ( + detail.outcome, detail.state, detail.submission_id, + ) + assert 'findings' not in project_item.model_dump() finally: await _drop_test_database_schema(isolated_database_env) await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) diff --git a/backend/tests/project_reads/test_preparations_reads.py b/backend/tests/project_reads/test_preparations_reads.py index 81f12387e..ec846ff98 100644 --- a/backend/tests/project_reads/test_preparations_reads.py +++ b/backend/tests/project_reads/test_preparations_reads.py @@ -10,7 +10,7 @@ from app.modules.tasks.models import AuditEvent from tests.submission_fixtures import seed_retained_submission from tests.test_tasks import ( - actor_id, auth_headers, complete_submission_payload, create_active_project, create_started_task, set_dev_actor, + auth_headers, complete_submission_payload, create_active_project, create_started_task, set_dev_actor, ) from .support import ( AUDITOR, EXACT_MANAGER, FINANCE, OPERATOR, OWNER, as_admin, as_manager, get_ok, project_path, submitted_case, @@ -18,14 +18,6 @@ OTHER = "worker-two" ACTION = "project.submission_bundle_preparation.list" -# The summary fields plus the contributor; no findings, packet or file content. -FIELDS = { - "preparation_id", "task_id", "assignment_id", "outcome", "state", "storage_status", - "infrastructure_failure_code", "archive_sha256", "archive_byte_count", "finding_counts", "admission_id", - "submission_id", "created_at", "completed_at", "actor_profile_id", -} - - def _path(project): return project_path(project, "/submission-bundle-preparations") @@ -38,7 +30,7 @@ async def _runs(project): async def _two_contributors(client, monkeypatch): - """worker-one's and worker-two's submitted preparations in one project.""" + """Two contributors' current source runs must stay outside retained history.""" project, task, submission = await submitted_case(client, monkeypatch) other_task = (await create_started_task(client, project, monkeypatch, subject=OTHER))["id"] await seed_retained_submission(other_task, complete_submission_payload("sha256:other")) @@ -51,60 +43,39 @@ async def _concealed(client, path, **params): return response.json()["error"]["code"] -async def test_manager_reads_counts_and_contributor_without_findings(task_client, monkeypatch): - project, task, submission = await submitted_case(task_client, monkeypatch) +async def test_manager_and_contributor_preparation_reads_omit_current_source(task_client, monkeypatch): + project, task, _submission = await submitted_case(task_client, monkeypatch) [run] = await _runs(project) + assert run.source_operation_id is not None as_manager(monkeypatch) page = await get_ok(task_client, _path(project)) - assert page["next_cursor"] is None - [item] = page["items"] - assert set(item) == FIELDS - assert (item["preparation_id"], item["task_id"], item["submission_id"]) == (run.id, task, submission) - assert UUID(item["actor_profile_id"]) == UUID(str(await actor_id(OWNER))) - assert (item["outcome"], item["state"]) == ("passed", "submitted") - assert set(item["finding_counts"]) == {"blocking", "warning", "coverage_incomplete"} - # The same projection the contributor reads for their own preparation. + assert page == {"items": [], "next_cursor": None} set_dev_actor(monkeypatch, roles="", subject=OWNER) - [own] = (await get_ok(task_client, f"/api/v1/tasks/{task}/submission-bundle-preparations"))["items"] - assert own == {key: value for key, value in item.items() if key != "actor_profile_id"} + assert (await get_ok(task_client, f"/api/v1/tasks/{task}/submission-bundle-preparations"))["items"] == [] -async def test_outcome_filter_selects_the_stored_outcome(task_client, monkeypatch): +async def test_outcome_filters_do_not_adopt_current_source_run(task_client, monkeypatch): project, _task, _submission = await submitted_case(task_client, monkeypatch) as_manager(monkeypatch) - assert len((await get_ok(task_client, _path(project), outcome="passed"))["items"]) == 1 - for outcome in ("pending", "failed", "infrastructure_failed"): + for outcome in ("passed", "pending", "failed", "infrastructure_failed"): assert (await get_ok(task_client, _path(project), outcome=outcome))["items"] == [], outcome invalid = await task_client.get(_path(project), params={"outcome": "checks_failed"}, headers=auth_headers()) assert invalid.status_code == 422 -async def test_pages_are_newest_first_without_gaps_or_duplicates(task_client, monkeypatch): +async def test_two_contributors_current_sources_do_not_enter_historical_pages(task_client, monkeypatch): project, _task, _submission = await _two_contributors(task_client, monkeypatch) - expected = [run.id for run in await _runs(project)] - assert len(expected) == 2 + runs = await _runs(project) + assert len(runs) == 2 and all(run.source_operation_id is not None for run in runs) as_manager(monkeypatch) first = await get_ok(task_client, _path(project), limit=1) - assert first["next_cursor"] is not None - second = await get_ok(task_client, _path(project), limit=1, cursor=first["next_cursor"]) - assert second["next_cursor"] is None - assert [item["preparation_id"] for item in first["items"] + second["items"]] == expected - assert {item["actor_profile_id"] for item in first["items"] + second["items"]} == { - str(await actor_id(OWNER)), str(await actor_id(OTHER)), - } - # A cursor is bound to its exact filters and limit. - for params in ({"limit": 2}, {"limit": 1, "outcome": "passed"}): - response = await task_client.get( - _path(project), params=params | {"cursor": first["next_cursor"]}, headers=auth_headers(), - ) - assert response.status_code == 422, params - assert response.json()["error"]["code"] == "project_read_cursor_invalid" + assert first == {"items": [], "next_cursor": None} async def test_system_and_exact_managers_are_admitted(task_client, monkeypatch): project, _task, _submission = await submitted_case(task_client, monkeypatch) await as_admin(task_client, monkeypatch, EXACT_MANAGER, "project_manager", project=project) - assert len((await get_ok(task_client, _path(project)))["items"]) == 1 + assert (await get_ok(task_client, _path(project)))["items"] == [] async def test_contributor_and_other_admin_roles_are_concealed(task_client, monkeypatch): diff --git a/backend/tests/project_reads/test_work_scale.py b/backend/tests/project_reads/test_work_scale.py index c60e2bc5e..3352314d0 100644 --- a/backend/tests/project_reads/test_work_scale.py +++ b/backend/tests/project_reads/test_work_scale.py @@ -1,13 +1,15 @@ """Project work pages and the summary stay within budget on 10,000 tasks and 20,000 submissions. -The preparation list is timed over 10,000 seeded runs, so its project/queued -index carries the page and the ``failed`` filter scans every pending run. The +The preparation list is timed over 10,000 retained-history benchmark rows, so +its project/queued index carries the page and the ``failed`` filter scans +completed passing runs. The guide list (C1) and the contribution policy list (D1) are low-cardinality per project and are not timed here. """ import json +from tests.test_tasks import auth_headers from tests.contributor_reads.test_scale import ( BUDGET_SECONDS, SUBMISSIONS_PER_TASK, @@ -47,6 +49,14 @@ async def test_project_pages_and_summary_meet_budget_at_scale( # A seeding miss must fail: the timed page is full, and no seeded or real run failed. assert len(pages["preparations"]["items"]) == 100 and pages["preparations"]["next_cursor"] assert pages["preparations_failed"] == {"items": [], "next_cursor": None} + for params in ({"limit": 2}, {"limit": 100, "outcome": "passed"}): + invalid = await task_client.get( + project_path(project, "/submission-bundle-preparations"), + params=params | {"cursor": pages["preparations"]["next_cursor"]}, + headers=auth_headers(), + ) + assert invalid.status_code == 422, params + assert invalid.json()["error"]["code"] == "project_read_cursor_invalid" summary = await get_ok(task_client, project_path(project, "/summary")) assert sum(summary["tasks"].values()) == TASKS + 1 assert summary["assignments"]["active"] == TASKS + 1 From 1b410efc78ae299d63f52e3540262ba8092a1e0d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:06:25 +0100 Subject: [PATCH 308/513] Record complete live AWS source and cleanup qualification --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a6cd44852..a8e60b0b8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10050,3 +10050,31 @@ The implementation filters the historical reader by `source_operation_id IS NULL The first isolated PostgreSQL pass at schema 0090 ran six selected cases: four passed, including the current-source public selector controls and contributor scale. The archived consumed-history case stopped before the added read assertions because its older 0083-to-current function-set equality now spans the merged main and later cleanup migrations. The test now compares exact function definitions only across 0083-to-0084, where the admission guard is the intended sole change, then separately requires all captured rows to survive through current schema before reading archived history. Project scale reached the historical preparation page within its unchanged one-second budget (0.707 and 0.499 seconds), but an unrelated submission continuation took 1.008 seconds and failed the same inherited budget. No budget was widened or performance result credited. The first runner's database cleanup completed; the two affected cases await a focused replay. Focused replay at schema 0090 passed the archived consumed-v1 read after the corrected exact migration comparison. The project scale case remained red on the unchanged one-second gate: submissions filtered took 1.905 seconds, assignments 1.316 seconds, and preparation pages 1.889/1.129 seconds under the shared host's load. Those broad overruns do not isolate a preparation-query regression, and this commit does not claim the scale gate passed. The two-case run had one pass and one failure in 462.90 seconds, with full isolated database cleanup. A later controlled performance measurement remains necessary before crediting the one-second project scale requirement. + + +### Live AWS source qualification passed + +At clean script candidate074cade5e, the pilot bucket and both independently +STS-verified runtime/cleanup IAM users passed the complete operator source drill. +Private journal: aws-source-qualification-20261124/live-612605b1732644d189ad0c5257328c5c.jsonl. +Actual checks: runtime HEAD confirms an existing retained artifact and cleanup +HEAD is403; two-part conditional source completion and pinned-version byte/hash +readback; conflicting overwrite refusal; runtime DeleteObjectVersion/Abort +refusal; cleanup Put refusal; cleanup abort and exact NoSuchUpload; lost delete +ACK reconciliation while an independent equal-byte retained source survives; +lost begin ACK exact-handle discovery/abort; lost complete ACK exact-version +recovery and substituted hash refusal. Four new owned operation keys were used: +three completed sources removed with confirmed absence, one unsealed multipart +handle discovered and aborted with confirmed absence. Final event completed/passed. +No user artifact body was read by the retained-object permission control. + +The two earlier synthetic runs each had two source keys. Exact recorded versions +and upload handles were reconciled with the cleanup principal, and independent +exact-key listings confirmed no versions, delete markers or multipart uploads. +Their adjacent .cleanup.json receipts are retained. No product SQL rows, current +API/worker configuration or existing retained keys were mutated. Temporary local +credential files and isolated drill container were removed on process exit. +This qualifies the actual native AWS source adapter/policies for this pilot; +it does not prove deployed worker wiring, public hosted journey or C01–C07 limits. +The hard-coded native-AWS admission exclusion can now be replaced with the +qualified profile, followed by its focused T1 test and actual hosted activation. From b23b9be281cc4ec5428bdc50f097a4c4c35a7c16 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 17:58:19 +0100 Subject: [PATCH 309/513] Wire first public PRE launch fault to pinned remote observations --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 74 +++++++++ .../README.md | 5 + .../REMOTE_PRE_LAUNCH.md | 140 ++++++++++++++++++ .../public_node_faults.py | 8 +- .../public_runtime_trials.py | 103 ++++++++++++- scripts/test_public_hosted_attachment.py | 93 ++++++++++++ 6 files changed, 421 insertions(+), 2 deletions(-) create mode 100644 experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a8e60b0b8..b7a61f8d7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10078,3 +10078,77 @@ This qualifies the actual native AWS source adapter/policies for this pilot; it does not prove deployed worker wiring, public hosted journey or C01–C07 limits. The hard-coded native-AWS admission exclusion can now be replaced with the qualified profile, followed by its focused T1 test and actual hosted activation. + +### Wire the first remote PRE launch-failure trial + +Intent: connect only the existing first project_fail_once public PRE vector to +RunnerFaults. Allowed files are the existing runtime trial, native trace assertion +owner, fixture guard module, this record and experiment documentation. The caller +must supply an already approved/claimed current task, exact assignment/actor and +actual locked-image-compatible ZIP. Reuse real public raw-ZIP intake, SQL custody +reads and durable OUTBOX T5; do not create another setup or product fault endpoint. + +Acceptance: one failed operation with sealed exact charge/no accepted handoff, +one native create/start/delete and no exec, same-key replay with unchanged terminal +custody and no new remote trace events, then a fresh key accepted202 and real T5. +Use acknowledged remote snapshots/cursors only; never compare local and runner +monotonic values. Unknown SSH command/transport stops the trial without resend or +fresh submission. Preserve actual lease and exact foreign-resource assertions. + +Risk: operator qualification code mutates an owned runner only when explicitly +launched later. Prepare pinned runner-only source staging/start/restore commands +for owner review. No SSH, service/configuration mutation, native run or paid call +is authorized during the current V14 runner window. Verification here is focused +caller/trace guard testing, static gates and root review, not live qualification. +No roadmap capability is completed by this wiring. Other runtime vectors, +remote disconnect restoration and original aggregate expiry remain unqualified. + +Implemented the isolated first-vector caller in public_runtime_trials. It accepts +only a fresh existing task plus its exact assignment/token/compatible ZIP and the +reviewed RunnerFaults profile; it does not repeat project setup or select a new +image. The general POST consumer must be paused by its existing launcher owner, +with the exclusive production finalizer still running. Existing local trial loops +and CLI bootstrap are unchanged; the latter exposes worker startup only and is +not silently treated as a fault launcher. + +The caller records acknowledged remote cursor snapshots around failure, replay +and recovery, binds the persisted failed/fresh PRE to the exact profile image, +requires the known infrastructure failure, sealed exact positive charge and one +failed operation, then unchanged terminal replay with no trace growth. Only after +conclusive failure and acknowledged clear does it submit a fresh key and delegate +to existing real OUTBOX T5 observation. It rechecks failed custody after replay +and requires exactly the failed and accepted operation IDs afterward. Unknown +command ACKs propagate with the retained ID and no fresh source submission. + +Extracted the existing native launch/lease/deletion assertions into a pure trace +assertion used unchanged by both filesystem and snapshot callers. AST comparison +confirmed all original assertion statements unchanged after the input filter. +The new guard valid control delegates the existing T5 observer and preserves exact +503/503/202 selectors; independent missing-delete, replay-allocation and wrong-image +controls fail their intended exact messages. An uncertain command retains its ID +and prevents submission. These are mocked HTTP/SQL/SSH caller guards, not live +fault/provider evidence. Final2guards passed33.404s at +/tmp/submission-remote-pre-caller-v2.log (initial2passed78.049s before final +replay-custody recheck and precise negative-message assertions). + +REMOTE_PRE_LAUNCH.md contains the runner-only reviewed source bundle/staging, +independent manifest fields, exact current image/unit/config candidates, finite +systemd supervisor and TERM restoration commands. The saved setup config has old +cache pins and is explicitly insufficient current custody. No owner manifest or +live source staging root was invented, and no permissions/cache are changed to +fit a test. Missing independent custody blocks the live run. Roadmap scope is +unchanged: this prepares qualification, not a new delivered product capability. +No SSH connection, runner/app service mutation, native VM, paid request or live +fault occurred. Actual remote launch failure/restoration remain unqualified. + +Root required explicit worker lifecycle ownership before live scheduling. The +entry now requires the existing isolated fixture stop_worker/start_worker +callbacks and restores that general worker in finally, including partial pause +failure and unknown fault-command outcome. It never stops arbitrary deployed +services. The final3caller guards passed26.830s at +/tmp/submission-remote-pre-caller-final.log with these exact executable bytes; +valid/negative vector controls and the owned-worker restoration paths ran. +Structure validation exited0 (/tmp/submission-remote-pre-structure.log); after the +small callback/test addition, a bounded AST check confirmed all added functions +remain below120lines and the guard module remains below1200 without ledger edits. +Ruff, links and whitespace pass. Commitrail is checked against the bridge base. diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md index 0fded1ff7..0e75aaf17 100644 --- a/experiments/pilot04_external_checker_runtime/README.md +++ b/experiments/pilot04_external_checker_runtime/README.md @@ -227,3 +227,8 @@ Require the same-run cleanup receipt, original config hash, removed owned resources and exact foreign preservation/removal after disconnect. Missing or failed restoration stops qualification and requires owner recovery. No live SSH or native disconnect qualification is claimed by the local bridge guard tests. + +The first PRE launch-failure caller can now attach to `RunnerFaults` with an +already approved/claimed current task and its real ZIP. See the bounded +[runner staging and restore recipe](REMOTE_PRE_LAUNCH.md). Other trial loops +remain operator-local; caller guards do not qualify an actual remote fault. diff --git a/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md b/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md new file mode 100644 index 000000000..8fc7265d2 --- /dev/null +++ b/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md @@ -0,0 +1,140 @@ +# First remote PRE launch-failure drill + +This is a preparation/review recipe, not an executed receipt. Do not run it while +another journey owns the runner. It changes only the dedicated runner after an +exclusive drained-node window is granted. The API host remains separate and +receives no KVM access, runner filesystem mount or SSH key. + +The bounded caller is `public_runtime_trials.public_pre_launch_failure`. Supply +an already publicly approved/claimed task, its assignment and contributor token, +the actual compatible incident-summary ZIP bytes and a `RunnerFaults` instance. +Supply only the isolated fixture launcher's existing owned stop_worker/start_worker +callbacks. The trial pauses that general POST worker and restores it in finally +on success, refusal or unknown outcome; keep the production finalizer running. +Never supply callbacks that stop arbitrary deployed application services. The caller uses public POST/GET and +read-only SQL custody checks; it never injects a T5 task or returns fake results. +From the existing isolated application harness, call it inside the owned HTTP +client/session-factory scope, after creating a fresh task via the same public +setup and packaging the actual `correct` pilot ZIP: + +```python +from experiments.pilot04_external_checker_runtime.public_runner_faults import RunnerFaults +from experiments.pilot04_external_checker_runtime.public_runtime_trials import public_pre_launch_failure + +result = await public_pre_launch_failure( + client, factory, task=task_id, assignment=assignment_id, token=contributor_token, + archive=correct_archive.read_bytes(), runner=RunnerFaults(reviewed_runner_profile), + stop_worker=stop_owned_general_worker, start_worker=start_owned_general_worker, +) +``` + +The HTTP timeout remains derived from the existing explicit source execution +profile. Do not use the old operator-local HostedAttachment inspection path, +which assumes local Smol files. Keep the result and tokens in private operator +evidence; never emit token values into the result or logs. +It checks one failed source, exact sealed charge, no accepted handoff, one native +create/start/delete without exec, exact same-key failure replay with no new trace, +then fresh-key202 and real durable T5. Other fault vectors are not selected. + +## Runner preparation for review + +Known transport pins are runner `13.61.148.238`, user `ubuntu`, identity +`/home/abiorh/flow/workstream_aws_setup_582/ec2-pilot-ssh-key` and known-hosts +`/home/abiorh/flow/workstream_aws_setup_582/runner-20261124-known-hosts`. Never read +or print the identity bytes. Every SSH/SCP command must use the bridge's approved +`-F /dev/null`, explicit identity, `IdentitiesOnly=yes`, `IdentityAgent=none`, +`BatchMode=yes`, `StrictHostKeyChecking=yes`, explicit known-hosts, +`GlobalKnownHostsFile=/dev/null`, `UpdateHostKeys=no`, finite connect/keepalive +options. Do not substitute the application-host SSH destination. + +Known unit/config candidates are `workstream-checker.service` and +`/etc/workstream/checker-service.json`. Reconfirm them read-only from the live +unit before selecting a manifest. The intended incident PRE platform digest is +`sha256:b4d1877fabfeacb24c6830469d1d1f057eacb64daecea7b5328f08431fc65721`. +The saved runner setup config contains older cache entries and is not current +custody. Do not modify its cache, permissions or pins to make a check pass. + +After owner review, choose one reviewed commit (`REVIEWED_COMMIT`, full hex), one +new canonical run UUID (`RUN_ID`), and the following fresh runner-only paths: + +- Source: `/opt/workstream/operator-fault-source/$REVIEWED_COMMIT`. +- Control: `/var/lib/workstream-operator/pre-launch-$RUN_ID` (created by supervisor). +- Independent custody: `/var/lib/workstream-operator/pre-launch-$RUN_ID-custody.json`. +- Finite operator unit: `workstream-operator-pre-launch-$RUN_ID.service`. + +The only executable files used by the supervisor are the reviewed +`public_node_faults.py`, `public_fault_files.py` and `public_runtime_wrapper.py`, +under their existing package paths. Stage the exact committed repository rather +than rewriting its Git identity. Prepare locally (no remote side effects): + +```sh +test "$(git rev-parse HEAD)" = "$REVIEWED_COMMIT" +git bundle create /tmp/workstream-operator-fault.bundle HEAD +sha256sum /tmp/workstream-operator-fault.bundle +git show "$REVIEWED_COMMIT":experiments/pilot04_external_checker_runtime/public_runtime_wrapper.py | sha256sum +``` + +Transfer that bundle through the same pinned SSH transport to an exclusive +operator staging directory. Check the independently recorded bundle hash there. +Only after that check, these are the proposed runner commands (variables must be +validated canonical values, not arbitrary shell input): + +```sh +sudo -n install -d -m 0755 /opt/workstream/operator-fault-source +sudo -n git clone --no-checkout /absolute/operator-staging/workstream-operator-fault.bundle "/opt/workstream/operator-fault-source/$REVIEWED_COMMIT" +sudo -n git -C "/opt/workstream/operator-fault-source/$REVIEWED_COMMIT" checkout --detach "$REVIEWED_COMMIT" +sudo -n git -C "/opt/workstream/operator-fault-source/$REVIEWED_COMMIT" status --porcelain +sudo -n install -d -m 0700 /var/lib/workstream-operator +``` + +Before any config write, compare the actual unit MainPID/ControlGroup, process +executable/argv, UID/GID10001, private config0400, private runtime parent0700, +owner file0600, single slot, exact image cache entry and original config bytes +against independent deployment custody. Hash service, Smol, guest and the +reviewed wrapper against their independently approved artifacts. The root-owned +0600 manifest must contain exactly the fields required by existing `validate_node`: +`unit`, `config`, `socket`, `executable`, `owner`, `config_sha256`, `node_config`, +`service_sha256`, `smol_sha256`, `guest_sha256`, `wrapper_sha256`, `source_tree`. +`source_tree` is the reviewed staged Git commit; `wrapper_sha256` is independently +checked above. This recipe does not synthesize a trusted manifest from whatever +files happen to be present. A missing/mismatched custody value blocks the drill. + +Once the manifest is independently reviewed and staged, start only this runner +supervisor, under a distinct finite root-owned unit: + +```sh +sudo -n systemd-run --unit="workstream-operator-pre-launch-$RUN_ID" --property=Type=exec --property=RuntimeMaxSec=1200 --property=TimeoutStopSec=90 --property=KillSignal=SIGTERM --property=KillMode=process --property=SendSIGKILL=no /usr/bin/env "PYTHONPATH=/opt/workstream/operator-fault-source/$REVIEWED_COMMIT" /usr/bin/python3 -m experiments.pilot04_external_checker_runtime.public_node_faults --node-config /etc/workstream/checker-service.json --unit workstream-checker.service --root "/var/lib/workstream-operator/pre-launch-$RUN_ID" --owner-manifest "/var/lib/workstream-operator/pre-launch-$RUN_ID-custody.json" --hosted-runtime --run-id "$RUN_ID" --maximum-seconds 900 --image-digest sha256:b4d1877fabfeacb24c6830469d1d1f057eacb64daecea7b5328f08431fc65721 +``` + +The supervisor validates custody, a drained node and exact cached image before +creating its foreign control, installing the wrapper and restarting the existing +checker unit. Read its private `node-binding.json` and compare its canonical JSON +SHA with the independent expected value. Set `RunnerFaultProfile` to that reviewed +SHA, exact run/source/control/image and pinned transport. A ready marker alone is +not custody. Snapshot cursors, not wall/monotonic comparisons across hosts, delimit +request/replay/recovery traces. Uncertain command ACKs preserve their original ID +and stop the trial; use read-only query of that ID before any later operator action. + +## Restore and retain evidence + +After the caller returns or fails, stop only the operator supervisor unit: + +```sh +sudo -n systemctl stop --no-block "workstream-operator-pre-launch-$RUN_ID.service" +``` + +TERM invokes the existing exact-inode configuration restore, checker restart, +foreign-preservation check and exact foreign cleanup. The unit intentionally does +not SIGKILL cleanup after a local SSH disconnect or stop deadline. This is not a +host-reboot/SIGKILL recovery guarantee. Observe the same run's cleanup receipt via +`RunnerFaults.snapshot()` and require its config hash equals the independently +recorded original config hash, all four owned resource lists empty, and all four +foreign-removal flags true. Independently recheck the original checker config +bytes and unit health. Preserve manifest, commands, caller result, bounded traces, +unit journal and cleanup receipt before removing only the fresh staged source and +run directories. Do not manually copy a saved config over an unverified live inode. +Missing/failed restoration blocks further trials and requires owner recovery. + +No commands above have been run by the local caller guards. Source staging, +independent custody, actual runner fault execution, API/runner separation during +the drill and restoration remain live qualification prerequisites. diff --git a/experiments/pilot04_external_checker_runtime/public_node_faults.py b/experiments/pilot04_external_checker_runtime/public_node_faults.py index 7cb9f05a8..5a7661f98 100644 --- a/experiments/pilot04_external_checker_runtime/public_node_faults.py +++ b/experiments/pilot04_external_checker_runtime/public_node_faults.py @@ -102,7 +102,13 @@ def trace_events(root): def assert_launches(root, start, *, creates, executions, project=True, shared_deadline=True): - events = [event for event in trace_events(root)[start:] if event['project'] is project] + return assert_trace_launches(trace_events(root)[start:], creates=creates, executions=executions, + project=project, shared_deadline=shared_deadline) + + +def assert_trace_launches(records, *, creates, executions, project=True, shared_deadline=True): + """Check the same native custody sequence from a local or remote snapshot.""" + events = [event for event in records if event['project'] is project] made = [event['name'] for event in events if event['operation'] == 'create'] _trace_require(len(made) == creates and len(set(made)) == creates, 'runtime retry did not allocate the expected fresh machines') diff --git a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py index bd21543cf..3f99309ec 100644 --- a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py @@ -5,6 +5,9 @@ import time from uuid import uuid4 +from sqlalchemy import select + +from app.modules.artifacts.intake.models import SubmissionIntakeOperation from app.modules.checkers.api.execution import CheckerRetryPublicResult from app.modules.checkers.models import CheckerRun from app.modules.tasks.models import SubmissionDispatch @@ -12,11 +15,14 @@ _assert_current_pre, _assert_source_failure, _drain_source_trial_posts, _observe_accepted_source, _selected, _source_request, ) -from experiments.pilot04_external_checker_runtime.public_node_faults import assert_launches, node_command, trace_events +from experiments.pilot04_external_checker_runtime.public_node_faults import ( + assert_launches, assert_trace_launches, node_command, trace_events, +) from experiments.pilot04_external_checker_runtime.public_probe_support import ( _assert_task_has_no_effects, _json, _public_project, _require, _started_public_task, _wait_outbox_acknowledged, _with_fixture_file, ) +from experiments.pilot04_external_checker_runtime.public_runner_faults import RunnerFaults from tests.post_submit_materialization_helpers import archive_with_modes @@ -87,6 +93,101 @@ async def _recover_failed_source(client, factory, route, headers, token, content return await _observe_accepted_source(client, factory, task, assignment, token, archive, fresh_key, accepted) +async def _trial_operation_ids(factory, task): + async with factory() as session: + return set(await session.scalars(select(SubmissionIntakeOperation.id).where( + SubmissionIntakeOperation.task_id == task))) + + +async def _runner_drained(runner): + observed = await runner.command('drained') + result = observed['result'] + _require(type(result.get('foreign_preserved')) is str and bool(result['foreign_preserved']) + and type(result.get('resources')) is dict + and set(result['resources']) == {'disks', 'leases', 'machines', 'cgroups'} + and all(type(value) is list and not value for value in result['resources'].values()), + 'remote cleanup or exact foreign preservation is absent') + return observed + + +async def public_pre_launch_failure(client, factory, *, task, assignment, token, archive, + runner: RunnerFaults, stop_worker, start_worker): + """Pause/restore only the isolated fixture's owned general POST consumer.""" + try: + stop_worker() + return await _remote_pre_launch_failure(client, factory, task=task, assignment=assignment, + token=token, archive=archive, runner=runner) + finally: + await start_worker() + + +async def _remote_pre_launch_failure(client, factory, *, task, assignment, token, archive, runner): + """One remote launch fault on an already approved/claimed current public task. + + The actual locked-image-compatible ZIP is supplied by the caller. The general + POST worker must be paused for this exclusive trace window; the production + finalization worker remains live. Unknown command outcome propagates without + replaying that command or submitting a fresh candidate. + """ + _require(not await _trial_operation_ids(factory, task), 'launch trial task already has intake custody') + route = f'/api/v1/tasks/{task}/submissions' + headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, + 'X-Submission-Summary': 'Completed task evidence.', + 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} + installed = await runner.command('project_fail_once') + before = await runner.snapshot() + key = str(uuid4()) + failure = await _source_request(client, route, headers, token, key, archive, 503) + _require(failure['error']['code'] == 'submission_infrastructure_unavailable', + 'remote launch failure was not a known infrastructure refusal') + failed_cleanup = await _runner_drained(runner) + failed_trace = await runner.snapshot() + records = failed_trace['events'][before['cursor']:] + machines = assert_trace_launches(records, creates=1, executions=0) + assert_trace_launches(records, creates=0, executions=0, project=False) + row = await _selected(factory, key) + _require(row.status == 'infrastructure_failed' and row.terminal_json['execution'] is None + and row.terminal_json['infrastructure_failure_code'] == 'implementation_unavailable' + and row.request_json['policy']['entries'][0]['registry']['image_digest'] == runner.profile.image_digest, + 'remote failed PRE lost exact selected image or terminal infrastructure custody') + operation = await _assert_source_failure(factory, task, key, len(archive), sealed=True, + code='submission_infrastructure_unavailable') + _require(operation.selected_pre_submit_run_id == row.id + and await _trial_operation_ids(factory, task) == {operation.id}, + 'launch failure created another operation or changed its exact PRE') + await runner.command('clear') + replay = await _source_request(client, route, headers, token, key, archive, 503) + repeated = await _selected(factory, key) + replay_trace = await runner.snapshot() + _require(replay == failure and (repeated.id, repeated.terminal_digest) == (row.id, row.terminal_digest) + and replay_trace['cursor'] == failed_trace['cursor'] + and await _trial_operation_ids(factory, task) == {operation.id}, + 'same-key failure replay changed custody or allocated a native machine') + await _assert_source_failure(factory, task, key, len(archive), sealed=True, + code='submission_infrastructure_unavailable') + fresh_key = str(uuid4()) + receipt = await _source_request(client, route, headers, token, fresh_key, archive, 202) + fresh = await _selected(factory, fresh_key) + _assert_current_pre(fresh) + _require(fresh.id != row.id and fresh.request_json['policy']['entries'][0]['registry']['image_digest'] + == runner.profile.image_digest, 'recovery changed the exact selected image or reused failed PRE') + recovered_cleanup = await _runner_drained(runner) + recovered_trace = await runner.snapshot() + records = recovered_trace['events'][replay_trace['cursor']:] + assert_trace_launches(records, creates=1, executions=1) + assert_trace_launches(records, creates=0, executions=0, project=False) + saved = await _observe_accepted_source(client, factory, task, assignment, token, archive, fresh_key, receipt) + _require(await _trial_operation_ids(factory, task) == {operation.id, receipt['operation_id']}, + 'fresh-key recovery created extra operations') + return {'case': 'remote_pre_launch_failure', 'run_id': runner.profile.run_id, + 'command': installed, 'failed_operation_id': operation.id, 'failed_pre_id': row.id, + 'failure_key': key, 'recovery_key': fresh_key, 'recovery_receipt': receipt, + 'failed_machines': machines, 'recovered_submission': saved, + 'trace_before': before, 'trace_failed': failed_trace, + 'trace_replay': replay_trace, 'trace_recovered': recovered_trace, + 'failed_cleanup': failed_cleanup, 'recovered_cleanup': recovered_cleanup} + + async def public_runtime_trials(client, factory, env, root: Path, *, stop_worker, start_worker, operator_token): """Separate tasks retain one PRE per accepted source and independent fault trials.""" project, _, manager, token = await _public_project(client, factory, env, human_review_required=True) diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index d7eadb7dd..6ce05b79e 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -1049,5 +1049,98 @@ async def exercise(): asyncio.run(exercise()) +class RemotePreLaunchContracts(unittest.TestCase): + def exercise(self, *, omit_delete=False, replay_allocates=False, wrong_image=False, unknown=False): + from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime + from experiments.pilot04_external_checker_runtime.public_runner_faults import FaultOutcomeUnknown + + image = 'sha256:' + 'b' * 64 + def events(name, operations): + lease = {'name': name, 'epoch': 'epoch', 'expires_ms': 100, 'lifetime_ms': 10} + return [{'operation': operation, 'name': name, 'project': True, 'lease': lease} + for operation in operations] + failed = events('failed-vm', ['create', 'start'] + ([] if omit_delete else ['delete'])) + replay = failed + (events('unexpected', ['create']) if replay_allocates else []) + recovered = replay + events('recovered-vm', ['create', 'start', 'exec', 'delete']) + traces = [{'cursor': len(records), 'events': records} + for records in ([], failed, replay, recovered)] + cleanup = {'result': {'foreign_preserved': 'foreign-vm', + 'resources': {name: [] for name in ('disks', 'leases', 'machines', 'cgroups')}}} + commands, worker_events = [], [] + async def resume(): + worker_events.append('start') + class Runner: + profile = SimpleNamespace(image_digest=image, run_id='run') + async def command(self, action): + commands.append(action) + if unknown: + raise FaultOutcomeUnknown('c' * 32) + return cleanup if action == 'drained' else {'command_id': 'c' * 32} + async def snapshot(self): + return traces.pop(0) + registry = {'image_digest': 'sha256:' + 'a' * 64 if wrong_image else image} + request = {'policy': {'entries': [{'registry': registry}]}} + failed_row = SimpleNamespace(id='failed-pre', terminal_digest='digest', request_json=request, + status='infrastructure_failed', terminal_json={'execution': None, + 'infrastructure_failure_code': 'implementation_unavailable'}) + fresh_row = SimpleNamespace(id='fresh-pre', request_json=request) + operation = SimpleNamespace(id='failed-operation', selected_pre_submit_run_id='failed-pre') + failure = {'error': {'code': 'submission_infrastructure_unavailable'}} + receipt = {'operation_id': 'fresh-operation', 'status': 'accepted', 'replayed': False} + source = AsyncMock(side_effect=[failure, failure, receipt]) + accepted = AsyncMock(return_value={'submission_id': 'submission'}) + with patch.object(runtime, '_trial_operation_ids', new=AsyncMock(side_effect=[set(), + {'failed-operation'}, {'failed-operation'}, {'failed-operation', 'fresh-operation'}])), \ + patch.object(runtime, '_source_request', new=source), \ + patch.object(runtime, '_selected', new=AsyncMock(side_effect=[failed_row, failed_row, fresh_row])), \ + patch.object(runtime, '_assert_source_failure', new=AsyncMock(return_value=operation)) as failed_custody, \ + patch.object(runtime, '_assert_current_pre') as current_pre, \ + patch.object(runtime, '_observe_accepted_source', new=accepted): + try: + result = asyncio.run(runtime.public_pre_launch_failure(None, None, task='task', assignment='assignment', + token='private-token', archive=b'actual-zip', runner=Runner(), + stop_worker=lambda: worker_events.append('stop'), start_worker=resume)) + finally: + self.assertEqual(worker_events, ['stop', 'start']) + self.assertEqual([call.args[-1] for call in source.await_args_list], [503, 503, 202]) + self.assertEqual(source.await_args_list[0].args[4], source.await_args_list[1].args[4]) + self.assertNotEqual(source.await_args_list[0].args[4], source.await_args_list[2].args[4]) + self.assertEqual(failed_custody.await_args.kwargs, {'sealed': True, 'code': 'submission_infrastructure_unavailable'}) + self.assertEqual(current_pre.call_args.args, (fresh_row,)) + self.assertEqual(accepted.await_args.args[2:7], ('task', 'assignment', 'private-token', b'actual-zip', + source.await_args_list[2].args[4])) + self.assertEqual(commands, ['project_fail_once', 'drained', 'clear', 'drained']) + self.assertEqual(result['failed_operation_id'], 'failed-operation') + self.assertEqual(result['recovered_submission'], {'submission_id': 'submission'}) + return result + + def test_remote_first_pre_preserves_known_failure_replay_and_real_t5_observer(self): + self.exercise() + for fault, message in (('omit_delete', 'lacks deletion'), + ('replay_allocates', 'same-key failure replay changed custody'), + ('wrong_image', 'failed PRE lost exact selected image')): + with self.subTest(fault=fault), self.assertRaisesRegex(RuntimeError, message): + self.exercise(**{fault: True}) + + def test_partial_owned_worker_pause_failure_still_restores_worker(self): + from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime + def failed_pause(): + raise RuntimeError('owned pause failed') + resume = AsyncMock() + with patch.object(runtime, '_remote_pre_launch_failure', new=AsyncMock()) as vector: + with self.assertRaisesRegex(RuntimeError, 'owned pause failed'): + asyncio.run(runtime.public_pre_launch_failure(None, None, task='task', assignment='assignment', + token='private-token', archive=b'actual-zip', runner=None, + stop_worker=failed_pause, start_worker=resume)) + resume.assert_awaited_once_with() + vector.assert_not_awaited() + + def test_unknown_fault_command_stops_before_any_public_submission(self): + from experiments.pilot04_external_checker_runtime.public_runner_faults import FaultOutcomeUnknown + with self.assertRaises(FaultOutcomeUnknown) as error: + self.exercise(unknown=True) + self.assertEqual(error.exception.command_id, 'c' * 32) + + if __name__ == '__main__': unittest.main() From 919cb0b925ae21ff99e484ccf7f18c32a040cbff Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:19:17 +0100 Subject: [PATCH 310/513] Record connected native journey and refresh historical read contracts --- .commitrail/INDEX.md | 2 +- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 39 +++++++++++-------- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 31 +++++++++++++++ docs/roadmap_status.md | 19 +++++---- mcp_server/contracts/preparation_get.json | 6 +-- mcp_server/contracts/preparations_list.json | 6 +-- .../contracts/project_preparations_list.json | 6 +-- 7 files changed, 74 insertions(+), 35 deletions(-) diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md index 8f119a5a6..7ae33d27e 100644 --- a/.commitrail/INDEX.md +++ b/.commitrail/INDEX.md @@ -6,7 +6,7 @@ for current product capability. | Initiative | Durable disposition | Next usable boundary | |---|---|---| -| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP API/CLI/MCP, PRE/T4/T5, indexed cleanup and POST policy routing are implemented; superseded writers are retired and real Redis/Celery child recovery is proved. Next: complete native public automatic acceptance, remaining runtime/resource and AWS qualification, hosted activation and full acceptance/configuration closure. Live human review remains deferred. See the overview for checked implementation versus remaining evidence. | +| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP API/CLI/MCP, PRE/T4/T5, indexed cleanup and POST policy routing are implemented; superseded writers are retired and real Redis/Celery child recovery is proved. The local API/separate AWS runner journey and live AWS source cleanup are proved. Next: qualified AWS admission activation, remaining runtime/resource qualification, hosted activation and full acceptance/configuration closure. Live human review remains deferred. See the overview for checked implementation versus remaining evidence. | | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. | | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. | | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. | diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 4acd1cc4c..fc072b434 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -36,7 +36,9 @@ full-head qualification. The API/application server and microVM execution run on separate infrastructure. The application instance is a verified t3.large; the dedicated always-on runner is an m7i.large with native KVM. App-origin mTLS health and native transport -smoke receipts establish connectivity, not the complete deployed submission journey. Do not require nested +smoke receipts establish connectivity. V14 also proves the connected local API +and real remote runner through automatic acceptance, rejection and default +review_pending; it does not prove the deployed API/worker release. Do not require nested virtualization, a Smol binary, host sockets or local KVM on the API instance. Self-hosted microVM execution uses dedicated runner infrastructure. A paid sandbox may implement the same qualified execution capability later. @@ -85,20 +87,23 @@ journey. The remaining cleanup and verification requirements below still apply. | Order | Required outcome | Concrete finishing evidence | | --- | --- | --- | -| 1 | Qualify the connected public journey | Real PRE, durable T5, POST and automatic acceptance under locked false ReviewPolicy; exact ZIP, source generation, ContributionRecord and applicable awards; failures and replay. Preserve default review_pending guards. | +| 1 | Reproduce the connected proof on the deployed API | V14 passes real PRE/T5/POST, automatic acceptance, exact ZIP/Contribution export, rejection, replay and default review_pending with a local API and separate AWS runner. The actual deployed API/consumers remain to activate and prove. | | 2 | Finish affected qualification callers | Preparation API/materialization and the admission-only TASK writer are removed. Current qualification scripts use raw ZIP acceptance and dedicated finalization; remaining runtime fault vectors must use that same flow and preserve their evidence. | | 3 | Complete separate-runner integration and runtime/provider/resource qualification | Activate the prepared authenticated remote configuration on the app deployment; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. | | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. | | 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. | -The next integration boundary is the complete public journey and live AWS source -qualification. Ordinary indexed unsealed cleanup is implemented. Spec §17.4 makes -inventory for genuinely absent operation records optional; it is not a new -scanner prerequisite. Uncertain writes of known operations remain owned and -conservatively charged until proved settled. AWS policy and adapter -drill preparation are reviewed, but IAM administration access is pending and no -live source qualification has run. Do not repeat completed local proofs as a -substitute for connecting and testing the deployed journey. +The connected public journey passed at 85ce76e17 (V14): 573 CLI invocations, +real PRE/T4/T5/POST, exact source and Contribution/export custody, PRE/POST +rejection and default review_pending; owned database/bucket cleanup passed. +Live AWS source qualification passed at 074cade5e with the actual restricted +runtime/cleanup identities, pinned versions, lost acknowledgements and exact +cleanup. Neither result claims a deployed API journey. The next boundary is +qualified AWS admission activation, separate-runner hosted cutover and remaining +native fault/isolation/capacity and final full-head qualification. Ordinary +indexed unsealed cleanup is implemented; optional absent-operation inventory is +not a new prerequisite. Known uncertain writes stay owned and charged until +settled. Do not repeat completed local proofs instead of closing these gaps. The current unsealed change extends that same cleanup owner: Local incomplete uploads can be reclaimed, and an observed late completion is retained until a @@ -121,13 +126,13 @@ This is the final qualification queue, not a claim that all listed code is absen | IDs | Existing implementation/focused evidence | Required closure | | --- | --- | --- | -| A01–A03 | Public ZIP flow, default/project PRE and formal finalization tests | Complete API/CLI journey with required real runtime and POST evidence. | +| A01–A03 | V14 connected public API/CLI journey with real separate-runner PRE and POST, T4/T5 and exact source checks | Reconcile each requirement and reproduce on the deployed release. | | A04–A08 | Metadata/body replay, competing custody, interruption and T4 uncertainty tests | Reconcile exact cases and execute integrated final-head failure/retry matrix. | | A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Redis publication outage and Celery child-redelivery proofs passed; reconcile the remaining exact cases at the final head. | -| A14–A18 | Cleanup lock/retention/charge owners and Local/MinIO provider tests | Production sweeps, accepted-source survival, AWS versions and uncertain multipart ownership. | -| A19–A23 | Streaming/framing, safe archives, semantic identity and bounded findings code/tests | Measured permitted maxima/slow-provider memory bounds and complete safety matrix. | +| A14–A18 | Cleanup lock/retention/charge owners, Local/MinIO tests and live AWS exact-version/lost-ack cleanup with retained-source survival | Production worker sweeps and exact acceptance-case reconciliation. | +| A19–A23 | Streaming/framing, safe archives, semantic identity and findings tests; local A19 496 MiB slow-provider memory/backpressure drill | Full permitted maxima and safety matrix, native/deployment scope where required. | | A24–A30 | Source/result/fence contracts and runtime/capacity/substitution tests | Actual native isolation/failure/cleanup, multiple replicas/nodes, saturation and adapter qualification. | -| A31–A32 | Source-backed POST reaches review_pending or shared automatic FinalAcceptance with exact contribution/awards and replay checks | Complete public-API/native automatic acceptance and final downstream tests. Keep default review_pending guards; live human review remains explicitly deferred by the user. | +| A31–A32 | V14 proves real POST automatic acceptance, exact Contribution/export and default review_pending; focused tests cover applicable awards/replay | Deployed release and final downstream tests. Keep default review_pending guards; live human review remains explicitly deferred by the user. | | A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | Affected old writers are retired; finish current-head migration/client convergence and remaining qualification callers. | ## Configuration and external evidence @@ -135,9 +140,9 @@ This is the final qualification queue, not a claim that all listed code is absen C01–C07 remain open until individually reconciled with the specification and actual deployment evidence. Test-only leases/profiles are not approved defaults. Native Smol qualification must run on the dedicated execution infrastructure, -not the API host. Native transport smoke is recorded; complete public/runtime -qualification must be linked to its actual results. AWS source -qualification remains separate from MinIO and ordinary SHA-object operation. +not the API host. V14 records connected public native proof; remaining runtime +faults/capacity and deployed API proof need their own receipts. Live AWS source +qualification passed separately from MinIO and ordinary SHA-object operation. Current main's dedicated credentials replace expiring provider activation; submission work must not reinstate the retired activation subsystem. Request only concrete missing access or decisions after the corresponding drill diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b7a61f8d7..e21cd231d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10152,3 +10152,34 @@ Structure validation exited0 (/tmp/submission-remote-pre-structure.log); after t small callback/test addition, a bounded AST check confirmed all added functions remain below120lines and the guard module remains below1200 without ledger edits. Ruff, links and whitespace pass. Commitrail is checked against the bridge base. + +### Complete connected native journey and current read contracts + +V14 passed all six stages and 573 CLI invocations at clean85ce76e17, schema 0090. +Public PRE rejection leaves no Submission; correct input reaches one passing +registered POST, FinalAcceptance, Submission and Contribution with exact original +ZIP hash in Contribution/CSV export, no Review and no awards for this policy. +Incorrect input passes PRE then reaches failed POST/needs_revision without +acceptance effects. Default-required review reaches review_pending with zero +Review/Contribution/FinalAcceptance. Read-only source/effect audits and Operator +custody checks passed. Metadata confirms owned database and MinIO cleanup; +journey-owned provider container/secret were removed. Evidence: +`/tmp/submission-public-journey-live-v14.log` and matching.json; private timing +snapshot `/tmp/submission-public-journey-v14-pre-intervals.json`. + +Topology was disposable local API/PostgreSQL/MinIO/Redis and the real dedicated +AWS Smol runner, not the deployed API release. DB-recorded PRE intervals were +86.422219, 85.504909, 83.267697, 80.466899 seconds under the test 120-second / 2 CPU / +2 GiB / 8 GiB / 64-process profile. These are not HTTP or execution-only timings. +The approximately 60-second target is not met; C01 hard-limit approval was +requested with these measurements and remains pending. Do not fabricate defaults. + +Historical preparation route descriptions were refreshed in exactly three MCP +snapshots using current exported OpenAPI and the canonical fragment/hash helpers; +only descriptions, hashes and source provenance changed. No schema or permission +changed. Five focused configured checks passed 1.35s, including both current +OpenAPI comparisons (`/tmp/submission-historical-mcp-contracts-final.log`). +The initial selector command selected two nodes from the wrong module and ran +no tests; corrected selection uses the existing task-execution contract module. +Roadmap, initiative overview/index and local sheet exports are reconciled to +these scoped results while keeping hosted activation and final qualification open. diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index a694a3c53..89433eba5 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -122,10 +122,12 @@ Workstream PRE default. Locked `human_review_required=false` lets passing requir POST invoke shared automatic acceptance and contribution/award creation. Default true retains `review_pending` and its guards; live human review remains deferred. Scoped PostgreSQL/MinIO, client and real Redis/Celery child-recovery proofs exist. -The separate runner has native transport and app-origin mTLS connectivity evidence; -complete public native acceptance, maximum/resource and failure qualification, -AWS source permissions/version cleanup, hosted activation and final A01–A35/C01–C07 -closure remain deployment/release gates. Implementation is not hosted qualification. +The connected local API/separate AWS runner journey proves automatic acceptance, +PRE and POST rejection, exact source/contribution custody and default review_pending. +Live AWS versioned-source permissions, cleanup and lost-acknowledgement recovery +are qualified. Remaining native faults, isolation/capacity/maxima, deployed API +activation and A01–A35/C01–C07 closure remain release gates. Local journey evidence +does not establish hosted API deployment. ## Product Goal @@ -689,7 +691,7 @@ cannot be reused as post-submission review-gate evidence. See the | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS | | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate | | Contributor artifact preparation | **Public initial and checker-remediation entry** | One outer ZIP up to 500 MiB through the published preparation route (MCP transport: 64 MiB); scratch reservations grow before writes from counted bytes plus bounded headroom; unreadable or structurally rejected ZIPs return sanitized non-retryable 422 feedback before PRE reservation or durable effects; bounded scratch inspection; canonical manifest; shared evaluation-content capacity and exact locked-policy checks before attempts or durable intent; platform and project prechecks; unchanged-work rejection; durable put intent; verification; capacity-charged ready admission; final handoff validates the exact activated historical guide through owner ports; same-key ready replay does not repeat checker or PUT. The preparing contributor reads back their own preparations with outcome, storage state, finding counts and intake findings (PILOT-READ-2); a Project Manager lists a project's preparations with finding counts only (PILOT-READ-3). CLI preparation, read-back, creation/replay and history consume these public owners | Bounded local API/CLI journeys and hosted PRE rejection, lost-response recovery, ready admission and exact replay passed. Hosted CLI/MCP preparation, creation and replay passed in the [fresh resource-qualified journey](reports/managed-mcp-hosted-2026-11-07.md#sealed-size-resource-qualification-and-fresh-hosted-journey). Complete remaining intake negatives, isolation and interruption scenarios | -| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | Complete native public acceptance and remaining failure, isolation, capacity and maximum-input qualification. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. App-origin mTLS and native transport smoke are proved; hosted activation and AWS source qualification remain open. | +| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. Remaining gates are native fault, isolation, capacity and maximum-input qualification, qualified AWS admission activation and deployed API/consumer cutover. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. | | Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Complete the connected native public journey, AWS exact-version qualification, hosted cutover and final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. | | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. The bounded local public API/Celery drill passed both branches, prefork Celery process restart and late authority revocation | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate | | Operator uncertain-delivery CLI | **Existing public delivery routes consumed by explicit CLI commands** | WS-CLI-001-40 adds one project-bound page of finalized UNKNOWN deliveries and a deliberate reasoned, UUID-keyed reconciliation of one exact event. Fresh backend authority and classification remain decisive; a page never authorizes a later write. | Native signed PostgreSQL proof is scoped to an owner-produced source; a hosted interruption and deployed CLI remain unproven | @@ -1748,9 +1750,10 @@ v0.1 is not ready until all of the following are true: - Qualify the current single-request submission flow, not only its historical preparation/admission predecessors: public native PRE/T4/T5/POST and automatic acceptance, exact retained source/contribution facts, failure/retry behavior, - maximum/slow-upload memory, isolation and capacity. Qualify AWS source IAM and - exact-version cleanup before opening its gate; activate separate-runner hosted - API/consumers with measured/approved C01–C07 settings and reconcile A01–A35. + maximum/slow-upload memory, isolation and capacity. The connected local API / + separate AWS runner journey and live AWS source IAM/exact-version cleanup pass; + activate qualified AWS admission and the hosted API/consumers with + measured/approved C01–C07 settings and reconcile A01–A35. Default review_pending remains protected; live human review is deferred from this submission initiative. See [WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). diff --git a/mcp_server/contracts/preparation_get.json b/mcp_server/contracts/preparation_get.json index e56a3de86..b9185917d 100644 --- a/mcp_server/contracts/preparation_get.json +++ b/mcp_server/contracts/preparation_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "e7f1bb9a59affbbe855b6948fb3b9a20e2f5fddf54f3acbd38a0debc5ffe6084", + "canonical_sha256": "178620e9596db912a29be5b288b5b86a25b7234971f9772a234b9f9ed805b230", "components": { "schemas": { "ApiError": { @@ -264,7 +264,7 @@ } }, "operation": { - "description": "One of your preparations with every intake finding; others are not found.", + "description": "One historical preparation with its intake findings; others are not found.", "operationId": "read_my_preparation_api_v1_tasks__task_id__submission_bundle_preparations__preparation_id__get", "parameters": [ { @@ -541,6 +541,6 @@ "method": "GET", "openapi_version": "3.1.0", "path": "/api/v1/tasks/{task_id}/submission-bundle-preparations/{preparation_id}", - "repository_sha": "f0431385573eb53353c5ffc3c6cdb6a93d206b73" + "repository_sha": "b23b9be281cc4ec5428bdc50f097a4c4c35a7c16" } } diff --git a/mcp_server/contracts/preparations_list.json b/mcp_server/contracts/preparations_list.json index 760612d1b..149e68cb0 100644 --- a/mcp_server/contracts/preparations_list.json +++ b/mcp_server/contracts/preparations_list.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "d755e495999adc90b97aa50c0df632892cb902d6124be68ed5957fe3ba40a01b", + "canonical_sha256": "bef46520f920b5e058caf45475eb0a3012661f8cdd53f4ee11e5db7f40e27cba", "components": { "schemas": { "ApiError": { @@ -284,7 +284,7 @@ } }, "operation": { - "description": "Your ZIP preparations for one task you hold or held, newest first.", + "description": "Your historical ZIP preparations for one task, newest first.", "operationId": "list_my_preparations_api_v1_tasks__task_id__submission_bundle_preparations_get", "parameters": [ { @@ -581,6 +581,6 @@ "method": "GET", "openapi_version": "3.1.0", "path": "/api/v1/tasks/{task_id}/submission-bundle-preparations", - "repository_sha": "f0431385573eb53353c5ffc3c6cdb6a93d206b73" + "repository_sha": "b23b9be281cc4ec5428bdc50f097a4c4c35a7c16" } } diff --git a/mcp_server/contracts/project_preparations_list.json b/mcp_server/contracts/project_preparations_list.json index a9f6b3798..5276b5184 100644 --- a/mcp_server/contracts/project_preparations_list.json +++ b/mcp_server/contracts/project_preparations_list.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "f435dfbfcd335f00948ed84edc949d65802052d096620f4ddd8f6593c6880eef", + "canonical_sha256": "4edab7436e7c5903d8263cf3b9c20d5dd105feb04d19eecd7649634ca76efada", "components": { "schemas": { "ApiError": { @@ -291,7 +291,7 @@ } }, "operation": { - "description": "Every contributor's ZIP preparations, newest first, with finding counts and no findings or files.\n\n``outcome=failed`` lists completed intake checks that blocked the ZIP.", + "description": "Historical ZIP preparations, newest first, with counts and no findings or files.\n\n``outcome=failed`` lists completed intake checks that blocked the ZIP.", "operationId": "list_project_preparations_api_v1_projects__project_id__submission_bundle_preparations_get", "parameters": [ { @@ -609,6 +609,6 @@ "method": "GET", "openapi_version": "3.1.0", "path": "/api/v1/projects/{project_id}/submission-bundle-preparations", - "repository_sha": "bb39ac10aed24e3484f3155706f7a8902ef97694" + "repository_sha": "b23b9be281cc4ec5428bdc50f097a4c4c35a7c16" } } From bc4c37acdfdd8f7b395b220f678476f636ed1876 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:24:52 +0100 Subject: [PATCH 311/513] feat(submission): admit qualified AWS source custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 10 ++ backend/alembic/env.py | 3 +- .../versions/0091_qualified_aws_source.py | 34 +++++ .../artifacts/intake/foreground_admission.py | 2 +- .../selected_pre_submit_admission.py | 2 +- .../test_submission_intake_admission.py | 133 ++++++++++++++++-- .../artifacts/test_submission_pre_source.py | 2 +- backend/tests/conftest.py | 2 +- backend/tests/test_alembic.py | 46 +++++- 9 files changed, 219 insertions(+), 15 deletions(-) create mode 100644 backend/alembic/versions/0091_qualified_aws_source.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e21cd231d..4288da989 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10183,3 +10183,13 @@ The initial selector command selected two nodes from the wrong module and ran no tests; corrected selection uses the existing task-execution contract module. Roadmap, initiative overview/index and local sheet exports are reconciled to these scoped results while keeping hosted activation and final qualification open. + +### Admit the qualified AWS source profile into T1 and source PRE + +Intent: the actual pilot AWS source drill passed with conditional multipart completion, exact version reads, retained-version survival, scoped deletion and abort, denied runtime deletion, and lost begin/complete/delete acknowledgement recovery. The provider identity `aws-s3-v1` can now enter the same source-first T1 and PRE custody as qualified local/MinIO; this is an explicit profile addition, not a dynamic proof registry or an AWS runtime default. The live drill used the dedicated runtime and cleanup IAM users and a private fsynced journal; it did not execute a public T1/PRE transaction or native guest. The administrator-applied policies and pilot bucket are deployment evidence, not a new database authority source. + +Allowed files: `backend/app/modules/artifacts/intake/foreground_admission.py`, `backend/app/modules/artifacts/selected_pre_submit_admission.py`, a new narrow `backend/alembic/versions/0091_qualified_aws_source.py`, Alembic current-head and expected-schema fingerprint fixtures, `backend/tests/artifacts/test_submission_intake_admission.py`, `backend/tests/artifacts/test_submission_pre_source.py`, exact migration graph tests if needed, and this record. The migration must replace only the existing selected PRE source-profile/scheme predicate, with predecessor-shape checks and no historical row rewrite. Preserve all locked source, packet, policy, fence, deadline, and task checks. + +Acceptance: a real PostgreSQL T1 under a pinned AWS namespace commits one receiving operation, reserved source charge, exact TASK pointer and AUTH allow before any provider/body I/O; replay returns the same operation. A database-only sealed AWS source (explicitly not a provider qualification) builds `storage_scheme=s3` and passes the current SQL source guard, while a rehashed foreign profile/scheme is refused. An unknown profile cannot form the canonical namespace identity, and the PRE builder continues to refuse an unknown source profile. Verify the exact 0090-to-0091 SQL function delta, current schema fingerprint, focused positive/negative cases and retained existing local/MinIO controls. No broad SDK, native VM, public flow, config default, or cleanup authority change. Risk: admitting T1 without both PRE builder and SQL guard would leave a committed unusable operation; broadening the SQL predicate or accepting a forged scheme would weaken source custody. Human review focus is the three coordinated gates, immutable function delta, AWS namespace binding, and the separate limits of the live adapter versus database-only tests. PostgreSQL execution waits until the shared V14 journey releases its isolated test slot. + +After V14 released the shared PostgreSQL slot, the first focused five-case run at schema 0091 passed four cases: AWS T1 exact receiving operation, reserved charge, TASK pointer, AUTH allow and same-key replay; existing local admission/source control; and an actual 0090-to-0091 full-function comparison that found only the two expected profile/scheme edits. The fifth case stopped at a test-only strict UUID decoder call before its SQL assertion. The fixture was corrected to decode the persisted JSON through the model's JSON validator; the single affected PostgreSQL replay then passed, including the AWS `s3` source guard positive and rehashed foreign profile/scheme refusals. Receipts: `/tmp/submission-qualified-aws-admission-v2.log/.json` (4 passed, 1 test-fixture failure, 241.84 seconds) and `/tmp/submission-qualified-aws-pre-source-v3.log/.json` (1 passed, 41.18 seconds). Both isolated databases report cleanup complete and Alembic 0091. The measured current public-schema fingerprint is `7ad79f8771b732cbabdc956cdffae50905b757990b1e5336f44990054967f31b`; Ruff, whitespace and Commitrail checks pass. These tests exercise database custody with a synthetic provider generation; the separate actual AWS adapter drill is the provider evidence. No public AWS submission or native guest journey is claimed by this change. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 33d187861..71055fd12 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0090_merge_direct_storage" +_CURRENT_HEAD_REVISION = "0091_qualified_aws_source" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -145,6 +145,7 @@ def do_run_migrations(connection: Connection) -> None: ("0088_unsealed_source_cleanup",), ("0089_observed_upload_cleanup",), ("0069_remove_artifact_proof",), + ("0090_merge_direct_storage",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0091_qualified_aws_source.py b/backend/alembic/versions/0091_qualified_aws_source.py new file mode 100644 index 000000000..a295d2b3f --- /dev/null +++ b/backend/alembic/versions/0091_qualified_aws_source.py @@ -0,0 +1,34 @@ +"""Admit the qualified AWS source profile to the existing selected PRE guard.""" + +from alembic import op +from sqlalchemy import text + +revision = "0091_qualified_aws_source" +down_revision = "0090_merge_direct_storage" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Change only the profile/scheme predicate; retain every other source fence.""" + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.selected_pre_submit_runs IN ACCESS EXCLUSIVE MODE") + definition = op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_functiondef(" + "'public.require_selected_pre_source(public.selected_pre_submit_runs)'::regprocedure)" + )).scalar_one() + replacements = ( + ("o.provider_profile NOT IN ('local-v2','minio-v1')", + "o.provider_profile NOT IN ('local-v2','minio-v1','aws-s3-v1')"), + ("WHEN 'minio-v1' THEN 's3' END", + "WHEN 'minio-v1' THEN 's3' WHEN 'aws-s3-v1' THEN 's3' END"), + ) + for old, new in replacements: + if definition.count(old) != 1: + raise RuntimeError("qualified AWS source predecessor shape changed") + definition = definition.replace(old, new) + op.execute(definition) + + +def downgrade() -> None: + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py index 07b579e4c..5752d6045 100644 --- a/backend/app/modules/artifacts/intake/foreground_admission.py +++ b/backend/app/modules/artifacts/intake/foreground_admission.py @@ -202,7 +202,7 @@ async def _validate_context(self, session, metadata, actor_id): namespace = await session.get(ArtifactStorageNamespace, "primary") if namespace is None or any(getattr(namespace, name) != value for name, value in asdict(self._namespace).items()): raise IntakeCustodyConflict("intake_namespace_unavailable") - if namespace.provider_profile not in {"local-v2", "minio-v1"}: + if namespace.provider_profile not in {"local-v2", "minio-v1", "aws-s3-v1"}: raise IntakeCustodyConflict("intake_source_provider_unqualified") return task, project diff --git a/backend/app/modules/artifacts/selected_pre_submit_admission.py b/backend/app/modules/artifacts/selected_pre_submit_admission.py index c966d7300..3a00fed6a 100644 --- a/backend/app/modules/artifacts/selected_pre_submit_admission.py +++ b/backend/app/modules/artifacts/selected_pre_submit_admission.py @@ -136,7 +136,7 @@ def build_selected_pre_submit_reservation( or selected.rules_sha256 != expected_rules or selected.default_context.current_rules_sha256 != expected_rules): raise ValueError("selected PRE policy context differs") - storage_scheme = {"local-v2": "local", "minio-v1": "s3"}.get( + storage_scheme = {"local-v2": "local", "minio-v1": "s3", "aws-s3-v1": "s3"}.get( source.source.location.provider_profile ) if storage_scheme is None: diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py index 19c73e8ac..ffc0aea0d 100644 --- a/backend/tests/artifacts/test_submission_intake_admission.py +++ b/backend/tests/artifacts/test_submission_intake_admission.py @@ -78,7 +78,7 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques from workstream_external_services import ExternalServiceAdapterIdentity from app.modules.artifacts.service import ArtifactStorageNamespaceSpec identity = ArtifactStoreNamespaceIdentity("aws-s3-v1", ( - ("addressing_style", "virtual"), ("bucket", "intake-refusal-fixture"), + ("addressing_style", "virtual"), ("bucket", "aws-admission-fixture"), ("private_prefix", "workstream/artifacts"), ("region", "us-east-1"), )) descriptor, fingerprint = artifact_store_namespace_material( @@ -442,17 +442,132 @@ async def body(): @pytest.mark.parametrize("admission_intake", ["aws"], indirect=True) -async def test_t1_unqualified_aws_source_refuses_before_reservation(admission_intake): - from sqlalchemy import func, select +async def test_t1_qualified_aws_reserves_exact_source_custody(admission_intake): + from sqlalchemy import select + from app.modules.artifacts.intake.foreground_admission import IntakeReservationOwner, IntakeReplay from app.modules.artifacts.intake.models import SubmissionSourceCharge - from app.modules.tasks.models import WorkstreamTask + from app.modules.tasks.models import AuditEvent, WorkstreamTask f = admission_intake - with pytest.raises(IntakeCustodyConflict, match="intake_source_provider_unqualified"): - await admit_new(f) + assert f.source_store_factory is None # T1 has no provider or body capability. + key = new_record_id() + owner = await admit_new(f, key=key) + assert isinstance(owner, IntakeReservationOwner) async with f.factory() as session: - assert await session.scalar(select(func.count()).select_from(SubmissionIntakeOperation)) == 0 - assert await session.scalar(select(func.count()).select_from(SubmissionSourceCharge)) == 0 - assert (await session.get(WorkstreamTask, str(f.task))).active_submission_operation_id is None + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + charge = await session.get(SubmissionSourceCharge, row.id) + task = await session.get(WorkstreamTask, str(f.task)) + assert row.provider_profile == "aws-s3-v1" + assert row.namespace_id == "primary" and row.namespace_fingerprint == f.namespace.namespace_fingerprint + assert row.state == "receiving" and row.raw_sha256 is None + assert row.idempotency_key == str(key) and row.identity_link_id == str(f.actor.identity_link_id) + assert charge.accounted_bytes == 1024 and charge.state == "reserved" + assert task.active_submission_operation_id == row.id + events = list(await session.scalars(select(AuditEvent).where( + AuditEvent.action_id == "submission.intake.reserve", AuditEvent.resource_id == row.id, + ))) + assert len(events) == 1 and events[0].after_facts["allowed"] is True + replay = await admit_new(f, key=key) + assert isinstance(replay, IntakeReplay) and replay.operation_id == owner.operation_id + + +def test_unknown_source_profile_has_no_namespace_identity(): + from app.interfaces.artifacts import ArtifactStoreNamespaceIdentity + with pytest.raises(ValueError, match="artifact provider profile is unsupported"): + ArtifactStoreNamespaceIdentity("unqualified-v1", ()) + + +@pytest.mark.parametrize("admission_intake", ["aws"], indirect=True) +async def test_qualified_aws_pre_source_matches_locked_sql(admission_intake): + """A database-only source binds the qualified profile; provider I/O is separate proof.""" + import json + from datetime import UTC, datetime + from uuid import UUID + + from sqlalchemy import text + from sqlalchemy.exc import DBAPIError + + from app.adapters.artifacts import submission_intake_pre_source_port + from app.adapters.projects import project_locked_policy_context_port + from app.core.hashing import canonical_json_hash + from app.modules.artifacts.selected_pre_submit_admission import ( + bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, + ) + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest + from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + f = admission_intake + owner = await admit_new(f) + await record_intake_eof(f, owner, b"aws-profile-source") + async with f.factory.begin() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + deadline = datetime.now(UTC) + timedelta(minutes=2) + source = await repository(session).seal( + owner.operation_id, owner.lease_id, owner.generation, + provider_generation="opaque-aws-version", pre_deadline_at=deadline, + lease_expires_at=deadline, + ) + async with f.factory.begin() as session: + task = await task_submission_context_port(session).lock_submission_context( + TaskSubmissionContextRequest( + task_id=f.task, assignment_id=f.assignment, + contributor_id=f.actor.actor_profile_id, predecessor_submission_id=None, + ), + ) + references = task.locked_project_context + project = await project_locked_policy_context_port(session).lock_locked_policy_context( + ProjectLockedPolicyContextRequest(**{ + name: getattr(references, name) for name in ( + "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", + "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", + "pre_submit_policy_bundle_hash", + ) + }), + ) + guarded = await submission_intake_pre_source_port(session).lock_pre_source( + source=source, lease_id=owner.lease_id, generation=owner.generation, + ) + metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + selected = bind_selected_pre_submit_admission( + task=task, project=project, predecessor=None, predecessor_rules_sha256=None, + predecessor_exists=False, + packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + ) + request = build_selected_pre_submit_reservation( + source=guarded, metadata=metadata, task=task, project=project, + attempt_id=new_record_id(), idempotency_key=UUID(row.idempotency_key), + selected=selected, runtime_profile=_source_reservation().runtime_profile, + ) + assert request.admission_lineage.storage_scheme == "s3" + body = request.canonical_body() + value = { + "source_operation_id": str(owner.operation_id), "task_id": str(f.task), + "project_id": row.project_id, "assignment_id": str(f.assignment), + "actor_profile_id": row.actor_profile_id, "identity_link_id": row.identity_link_id, + "idempotency_key": row.idempotency_key, "request_json": body, + "request_digest": canonical_json_hash(body), + "archive_sha256": source.raw_sha256, "archive_byte_count": source.raw_byte_count, + "policy_sha256": request.policy_sha256, + } + statement = text("""SELECT public.require_selected_pre_source( + jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)))""") + async with f.factory.begin() as session: + await session.execute(statement, {"value": json.dumps(value)}) + for changed in ("storage_scheme", "provider_profile"): + forged = json.loads(json.dumps(body)) + if changed == "storage_scheme": + forged["admission_lineage"]["storage_scheme"] = "local" + else: + forged["source"]["location"]["provider_profile"] = "minio-v1" + forged["source_sha256"] = canonical_json_hash({ + "schema_version": "workstream.sealed_submission_source.v1", **forged["source"], + }) + with pytest.raises(DBAPIError, match="selected PRE source descriptor mismatch"): + async with f.factory.begin() as session: + await session.execute(statement, {"value": json.dumps(value | { + "request_json": forged, "request_digest": canonical_json_hash(forged), + })}) async def test_t1_replay_reauthorizes_after_body_read(admission_intake): diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py index a4e528449..5c72eaa68 100644 --- a/backend/tests/artifacts/test_submission_pre_source.py +++ b/backend/tests/artifacts/test_submission_pre_source.py @@ -42,7 +42,7 @@ def _assert_pre_reservation_rejects_substitution(build_values, guarded, metadata build_selected_pre_submit_reservation(**(build_values | replacement)) from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakePreSourceFacts unsupported_source = SealedSubmissionSource.model_validate(guarded.source.model_copy(update={ - "location": guarded.source.location.model_copy(update={"provider_profile": "aws-s3-v1"}), + "location": guarded.source.location.model_copy(update={"provider_profile": "unqualified-v1"}), })) unsupported_facts = SubmissionIntakePreSourceFacts.model_validate( guarded.model_copy(update={"source": unsupported_source}) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 27c753ad6..47aff9242 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "1ab3f95836accf52887d6e006d0f37ddfd60bf1269bd945255a46c529ac384a2" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "7ad79f8771b732cbabdc956cdffae50905b757990b1e5336f44990054967f31b" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 52b788580..292d6a283 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -430,6 +430,7 @@ def test_v01_graph_has_one_root_and_head() -> None: assert [revision.revision for revision in revisions] == [ HEAD_REVISION, + "0090_merge_direct_storage", "0089_observed_upload_cleanup", "0088_unsealed_source_cleanup", "0087_source_cleanup_candidates", @@ -521,13 +522,56 @@ def test_v01_graph_has_one_root_and_head() -> None: "0002_task_queue_authority", BASELINE_REVISION, ] - assert script.get_revision(HEAD_REVISION).down_revision == ( + assert script.get_revision("0090_merge_direct_storage").down_revision == ( "0089_observed_upload_cleanup", "0069_remove_artifact_proof", ) + assert script.get_revision(HEAD_REVISION).down_revision == "0090_merge_direct_storage" assert revisions[-1].down_revision is None assert script.get_heads() == [HEAD_REVISION] +async def test_qualified_aws_source_upgrade_only_changes_pre_profile_predicate( + isolated_database_env, migration_lock, +) -> None: + """Compare the complete SQL guard across 0090 to 0091; retain other custody.""" + from app.db import session as db_session + from tests.conftest import _drop_test_database_schema + + signature = "public.require_selected_pre_source(public.selected_pre_submit_runs)" + url = isolated_database_env.replace("+asyncpg", "") + + async def definition(): + connection = await asyncpg.connect(url) + try: + return await connection.fetchval( + "SELECT pg_catalog.pg_get_functiondef(CAST($1 AS regprocedure))", signature, + ) + finally: + await connection.close() + + with migration_lock(): + await db_session.dispose_engine() + await _drop_test_database_schema(isolated_database_env) + try: + await asyncio.to_thread(command.upgrade, _alembic_config(), "0090_merge_direct_storage") + before = await definition() + assert before.count("o.provider_profile NOT IN ('local-v2','minio-v1')") == 1 + assert before.count("WHEN 'minio-v1' THEN 's3' END") == 1 + await asyncio.to_thread(command.upgrade, _alembic_config(), HEAD_REVISION) + after = await definition() + expected = before.replace( + "o.provider_profile NOT IN ('local-v2','minio-v1')", + "o.provider_profile NOT IN ('local-v2','minio-v1','aws-s3-v1')", + ).replace( + "WHEN 'minio-v1' THEN 's3' END", + "WHEN 'minio-v1' THEN 's3' WHEN 'aws-s3-v1' THEN 's3' END", + ) + assert expected != before and after == expected + finally: + await _drop_test_database_schema(isolated_database_env) + await asyncio.to_thread(command.upgrade, _alembic_config(), HEAD_REVISION) + + async def test_guide_read_upgrade_targets_public_audit_with_shadow_search_path( isolated_database_env, migration_lock, From 0cebf84f6ee85ca8ccfa281d508dc4f1974e32b7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:41:06 +0100 Subject: [PATCH 312/513] Record AWS admission review and exact project scale verification --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 4288da989..5adca4fa7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10193,3 +10193,49 @@ Allowed files: `backend/app/modules/artifacts/intake/foreground_admission.py`, ` Acceptance: a real PostgreSQL T1 under a pinned AWS namespace commits one receiving operation, reserved source charge, exact TASK pointer and AUTH allow before any provider/body I/O; replay returns the same operation. A database-only sealed AWS source (explicitly not a provider qualification) builds `storage_scheme=s3` and passes the current SQL source guard, while a rehashed foreign profile/scheme is refused. An unknown profile cannot form the canonical namespace identity, and the PRE builder continues to refuse an unknown source profile. Verify the exact 0090-to-0091 SQL function delta, current schema fingerprint, focused positive/negative cases and retained existing local/MinIO controls. No broad SDK, native VM, public flow, config default, or cleanup authority change. Risk: admitting T1 without both PRE builder and SQL guard would leave a committed unusable operation; broadening the SQL predicate or accepting a forged scheme would weaken source custody. Human review focus is the three coordinated gates, immutable function delta, AWS namespace binding, and the separate limits of the live adapter versus database-only tests. PostgreSQL execution waits until the shared V14 journey releases its isolated test slot. After V14 released the shared PostgreSQL slot, the first focused five-case run at schema 0091 passed four cases: AWS T1 exact receiving operation, reserved charge, TASK pointer, AUTH allow and same-key replay; existing local admission/source control; and an actual 0090-to-0091 full-function comparison that found only the two expected profile/scheme edits. The fifth case stopped at a test-only strict UUID decoder call before its SQL assertion. The fixture was corrected to decode the persisted JSON through the model's JSON validator; the single affected PostgreSQL replay then passed, including the AWS `s3` source guard positive and rehashed foreign profile/scheme refusals. Receipts: `/tmp/submission-qualified-aws-admission-v2.log/.json` (4 passed, 1 test-fixture failure, 241.84 seconds) and `/tmp/submission-qualified-aws-pre-source-v3.log/.json` (1 passed, 41.18 seconds). Both isolated databases report cleanup complete and Alembic 0091. The measured current public-schema fingerprint is `7ad79f8771b732cbabdc956cdffae50905b757990b1e5336f44990054967f31b`; Ruff, whitespace and Commitrail checks pass. These tests exercise database custody with a synthetic provider generation; the separate actual AWS adapter drill is the provider evidence. No public AWS submission or native guest journey is claimed by this change. + + +Independent QA scoped review passed for bc4c37acd versus919cb0b92. Runtime AST +comparison preserved every existing source/packet/policy/lease/deadline/namespace +and AUTH predicate after removing only the additive AWS profile entries. The +unknown-profile fail-open control was detected; migration control changed exactly +two predicates and rejected absent/duplicated predecessor fragments. Author18750 +and integratedbc4 executable paths match the shared five successful PostgreSQL +cases across two runs; these are not claimed as full-head executions. Actual AWS +adapter qualification was independently checked through the safe journal envelope +and exact074 script hash. Evidence `/tmp/submission-aws-gates-qa-probe.json`. +No deployed AWS public journey or full-CI pass is claimed. + + +### Contributor scale control and interrupted-fixture process cleanup + +The contributor scale node passed at clean bc4c37acd / schema0091 in30.76s, +with complete isolated database cleanup. Slowest-of-three request measurements: +assignments0.209s/continued0.305s, submissions0.202s/continued0.232s, +summary0.223s, preparations0.165s, project tasks0.243s; all below the existing1s +budget. The agent initially mislabeled this as the project scale test; root +checked the printed endpoint set against both test owners and rejected that +scope claim. Project scale remains pending its exact named node. Evidence +`/tmp/submission-project-scale-quiet.log` and matching.json; +host samples `/tmp/submission-project-scale-quiet-host.txt`. No threshold widened. + +Before this measurement, root identified still-running private Celery groups +from the terminated V11/V13 fixtures by exact process group, executable/cwd, +stdio paths and database names matching their terminal metadata. Root sent TERM +only to those two owned groups and verified all members exited. This occurred +during the scale runner's startup and was recorded in the host context; no test +restart occurred. The earlier database/bucket cleanup receipts remain true, but +they did not establish process teardown. The existing journey runtime teardown +is being repaired and tested before the next fault drill. PRE intervals from V14 +remain actual observed stages under that host context, not quiet-host benchmarks. + +Reviewed b23b9be28 fault source and the independently compared root-private +custody manifest were staged on the dedicated runner with exact bundle/file hash +checks. Source is clean at the pinned commit. This is staging only; no fault +supervisor or service restart occurred. Archive nlink2 was resolved as the +existing immutable native-cache hardlink with exact bytes and0400 owner10001; +post-V14 leases/workspaces were empty. Local proposal/transfer evidence remains +in `/tmp/submission-runner-b23b9be28-stage.log` and associated comparison files. + + +The corrected exact project node `tests/project_reads/test_work_scale.py::test_project_pages_and_summary_meet_budget_at_scale` passed at bc4c37acd, schema0091, in47.62s. The actual `project read timings` output includes filtered submissions, import batches and10,000 preparation history rows; slowest endpoint0.414s against the unchanged1s budget. `/tmp/submission-project-work-scale-v1.log` and `.json` show one pass and full isolated database cleanup. This closes the focused project performance replay; the earlier contributor control is not its evidence. From 80090efdfd5767151e8d3c478b0702c5b6a3ae21 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:34:25 +0100 Subject: [PATCH 313/513] Add focused public PRE launch fault fixture and owned worker cleanup --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 34 ++++ .../test_journey_worker_cleanup.py | 62 ++++++++ cli/tests/journey/bootstrap.py | 31 +++- cli/tests/journey/pre_launch_fault.py | 150 ++++++++++++++++++ cli/tests/journey/runtime.py | 142 +++++++++++++---- 5 files changed, 387 insertions(+), 32 deletions(-) create mode 100644 cli/tests/integration/test_journey_worker_cleanup.py create mode 100644 cli/tests/journey/pre_launch_fault.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 5adca4fa7..77f04ac2e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10239,3 +10239,37 @@ in `/tmp/submission-runner-b23b9be28-stage.log` and associated comparison files. The corrected exact project node `tests/project_reads/test_work_scale.py::test_project_pages_and_summary_meet_budget_at_scale` passed at bc4c37acd, schema0091, in47.62s. The actual `project read timings` output includes filtered submissions, import batches and10,000 preparation history rows; slowest endpoint0.414s against the unchanged1s budget. `/tmp/submission-project-work-scale-v1.log` and `.json` show one pass and full isolated database cleanup. This closes the focused project performance replay; the earlier contributor control is not its evidence. + +### Focused remote PRE launch-failure fixture + +Intent: run only the existing `public_pre_launch_failure` vector after the +connected CLI journey's public guide, task creation and claim. This bounded +fixture may change `cli/tests/journey/bootstrap.py`, `runtime.py`, add its +single adapter module and focused cleanup tests, plus this record. It must +reuse the actual incident-summary ZIP, isolated database and bucket, exact +runner profile and owned general-worker callbacks. The dedicated finalizer +remains live. No product route, provider policy, runner configuration or +human-review behavior changes are allowed. The lead owns reviewed runner +staging, supervisor start and restoration; this fixture cannot perform them. + +Acceptance is a real public 503 with one failed source/PRE and no accepted +handoff, one remote create/start/delete without execution, unchanged same-key +failure replay without new allocation, then fresh-key 202 and durable T5. +The runner cleanup receipt must bind the original config and show no owned +resources after the supervisor stops. Unknown remote command outcomes retain +their original ID and stop the sequence. Verification uses a private isolated +launcher and focused process-group regression; the complete V14 journey is not +repeated. Risk is high because the fault supervisor temporarily changes the +owned remote runner and interrupted local workers must be reaped. + +The fixture now selects this one branch only after existing public setup. A +private runner profile is validated before local API startup, with exact image +pin and no credentials in output. It pauses only the fixture-owned general +worker and restores it in `finally`; the finalizer continues T5. A new exact +process-group shutdown helper observes every live group member rather than +waiting solely for the Celery leader. Cancellation sends TERM to all owned +separate sessions and kills survivors within the isolation runner's two-second +grace. Real leader plus TERM-resistant child controls passed both normal and +cancellation paths (2 cases); an in-memory predecessor leader-only stop failed +the regression. Focused bucket/cleanup checks: 6 passed; Ruff and diff check +passed. These are fixture checks, not a live runner-fault result. diff --git a/cli/tests/integration/test_journey_worker_cleanup.py b/cli/tests/integration/test_journey_worker_cleanup.py new file mode 100644 index 000000000..c52c484bb --- /dev/null +++ b/cli/tests/integration/test_journey_worker_cleanup.py @@ -0,0 +1,62 @@ +"""The journey must reap its own separate worker sessions on exit and cancellation.""" + +import importlib.util +import os +from pathlib import Path +import select +import signal +import subprocess +import sys + +import pytest + + +PATH = Path(__file__).resolve().parents[1] / "journey/runtime.py" +SPEC = importlib.util.spec_from_file_location("journey_runtime_cleanup", PATH) +assert SPEC is not None and SPEC.loader is not None +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +@pytest.mark.parametrize("cancelled", [False, True]) +def test_owned_worker_group_reaps_leader_and_term_resistant_child(tmp_path, cancelled): + """A leader exit alone cannot leave its same-group prefork child alive.""" + ready = tmp_path / "child-ready" + child_code = ( + "import signal,sys,time; from pathlib import Path; " + "signal.signal(signal.SIGTERM, signal.SIG_IGN); " + "Path(sys.argv[1]).write_text('ready'); time.sleep(360)" + ) + leader_code = ( + "import signal,subprocess,sys,time; from pathlib import Path; " + "signal.signal(signal.SIGTERM, signal.SIG_IGN if sys.argv[2]=='1' " + "else lambda *_: sys.exit(0)); " + "child=subprocess.Popen([sys.executable,'-c',sys.argv[3],sys.argv[1]]); " + "ready=Path(sys.argv[1]); " + "[time.sleep(.01) for _ in range(500) if not ready.exists()]; " + "print(child.pid,flush=True); time.sleep(360)" + ) + leader = subprocess.Popen( + [sys.executable, "-c", leader_code, str(ready), str(int(cancelled)), child_code], + start_new_session=True, + stdout=subprocess.PIPE, + text=True, + ) + try: + assert leader.stdout is not None + assert select.select([leader.stdout], [], [], 5)[0] + child = int(leader.stdout.readline().strip()) + assert ready.is_file() + assert MODULE._live_group_members(leader.pid) == {leader.pid, child} + if cancelled: + MODULE._interrupt_owned_groups([leader]) + else: + MODULE._stop_owned_group(leader, graceful_seconds=0.2, force_seconds=3) + leader.wait(timeout=5) + assert not MODULE._live_group_members(leader.pid) + finally: + if MODULE._live_group_members(leader.pid): + os.killpg(leader.pid, signal.SIGKILL) + leader.wait(timeout=5) + if leader.stdout is not None: + leader.stdout.close() diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py index 727f9e2ff..379f6c1f5 100644 --- a/cli/tests/journey/bootstrap.py +++ b/cli/tests/journey/bootstrap.py @@ -32,6 +32,7 @@ ROOT = Path(__file__).resolve().parents[3] BACKEND = ROOT / "backend" +sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(BACKEND)) sys.path.insert(0, str(BACKEND / "scripts")) from local_flow_tokens import issue_flow_token # noqa: E402 @@ -123,6 +124,19 @@ def main(): ): directory = Path(temporary) through_setup = os.environ.get("WORKSTREAM_CLI_JOURNEY_SETUP") == "1" + fault_mode = os.environ.get("WORKSTREAM_CLI_JOURNEY_PRE_LAUNCH_FAULT") == "1" + if fault_mode and ( + not through_setup + or os.environ.get("WORKSTREAM_CLI_JOURNEY_TASKS") != "1" + or os.environ.get("WORKSTREAM_CLI_JOURNEY_SUBMIT") == "1" + or not os.environ.get("WORKSTREAM_CLI_JOURNEY_EVIDENCE") + ): + raise RuntimeError("PRE launch fault requires the isolated setup and task path") + fault_profile = None + if fault_mode: + from pre_launch_fault import load_fault_profile + + fault_profile = load_fault_profile(environment) if through_setup: registries = load_journey_configuration(environment) prepare_versioned_source_bucket(environment) @@ -301,7 +315,7 @@ def main(): str(uuid4()), ) project_id = project["id"] - start_workers() + worker_controls = start_workers() publish_unpaid_terms(client, tokens["finance"], project_id) guide_id = configure_guide(client, tokens, project_id) approve_and_activate( @@ -334,7 +348,20 @@ def main(): client, tokens, actors, project_id ) client.complete_stage("task_claim_and_guide") - if os.environ.get("WORKSTREAM_CLI_JOURNEY_SUBMIT") == "1": + if fault_mode: + from pre_launch_fault import run_pre_launch_fault + + run_pre_launch_fault( + client, + origin, + environment, + task_id, + assignment_id, + tokens["alice"], + worker_controls, + fault_profile, + ) + elif os.environ.get("WORKSTREAM_CLI_JOURNEY_SUBMIT") == "1": receipt = submit_and_observe( client, tokens, diff --git a/cli/tests/journey/pre_launch_fault.py b/cli/tests/journey/pre_launch_fault.py new file mode 100644 index 000000000..4b3f76f92 --- /dev/null +++ b/cli/tests/journey/pre_launch_fault.py @@ -0,0 +1,150 @@ +"""Run one remote PRE launch fault through the existing public journey fixture.""" + +import asyncio +import json +import os +from pathlib import Path +import stat +import sys +from urllib.parse import urlsplit + +import httpx +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from experiments.pilot04_external_checker_runtime.public_runner_faults import ( + RunnerFaultProfile, + RunnerFaults, +) +from submission_work import _package + + +PROFILE_FIELDS = frozenset( + { + "host", + "identity_file", + "known_hosts_file", + "source_root", + "control_root", + "run_id", + "binding_sha256", + "image_digest", + } +) + + +def load_fault_profile(environment: dict[str, str]) -> RunnerFaultProfile: + """Require an independently prepared, private runner pin before fixture startup.""" + raw = environment.get("WORKSTREAM_CLI_JOURNEY_FAULT_PROFILE_FILE", "") + path = Path(raw) + if ( + not path.is_absolute() + or path.is_symlink() + or not path.is_file() + or stat.S_IMODE(path.stat().st_mode) != 0o600 + or not 0 < path.stat().st_size <= 16_384 + ): + raise RuntimeError("journey requires a private fault profile") + + def unique_pairs(pairs): + value = {} + for key, item in pairs: + if key in value: + raise ValueError("duplicate fault profile field") + value[key] = item + return value + + body = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_pairs) + if type(body) is not dict or set(body) != PROFILE_FIELDS: + raise RuntimeError("fault profile fields differ") + profile = RunnerFaultProfile( + **(body | { + "identity_file": Path(body["identity_file"]), + "known_hosts_file": Path(body["known_hosts_file"]), + }) + ) + profile.validate() + if profile.image_digest != environment.get("WORKSTREAM_CLI_JOURNEY_CHECKER_IMAGE_DIGEST"): + raise RuntimeError("fault profile image differs from approved guide") + return profile + + +async def _run( + origin: str, + environment: dict[str, str], + task: str, + assignment: str, + token: str, + archive: bytes, + profile: RunnerFaultProfile, + stop_worker, + start_worker, +): + root = Path(__file__).resolve().parents[3] + sys.path.insert(0, str(root / "backend" / "tests")) + sys.path.insert(0, str(root / "backend" / "scripts")) + from experiments.pilot04_external_checker_runtime.public_runtime_trials import ( + public_pre_launch_failure, + ) + + database_url = environment["WORKSTREAM_DATABASE_URL"] + if not urlsplit(database_url).path.lstrip("/").startswith("workstream_test_"): + raise RuntimeError("fault trial requires an isolated database") + execution = json.loads( + Path(environment["WORKSTREAM_CLI_JOURNEY_EXECUTION_PROFILE_FILE"]).read_text( + encoding="utf-8" + ) + ) + timeout = ( + execution["upload_total_seconds"] + + execution["runtime"]["aggregate_deadline_ms"] / 1000 + ) + engine = create_async_engine(database_url) + factory = async_sessionmaker(engine, expire_on_commit=False) + try: + async with httpx.AsyncClient(base_url=origin, timeout=timeout, trust_env=False) as client: + return await public_pre_launch_failure( + client, + factory, + task=task, + assignment=assignment, + token=token, + archive=archive, + runner=RunnerFaults(profile), + stop_worker=stop_worker, + start_worker=start_worker, + ) + finally: + await engine.dispose() + + +def run_pre_launch_fault( + client, + origin: str, + environment: dict[str, str], + task: str, + assignment: str, + token: str, + controls, + profile: RunnerFaultProfile, +) -> None: + """Keep remote evidence private; report only the bounded case completion.""" + archive = _package(client, "correct").read_bytes() + result = asyncio.run( + _run( + origin, + environment, + task, + assignment, + token, + archive, + profile, + *controls, + ) + ) + evidence = Path(os.environ["WORKSTREAM_CLI_JOURNEY_EVIDENCE"]) + evidence.mkdir(mode=0o700, parents=True, exist_ok=True) + path = evidence / "remote-pre-launch-fault.json" + with path.open("x", encoding="utf-8") as stream: + path.chmod(0o600) + json.dump(result, stream, default=str, sort_keys=True) + client.complete_stage("remote_pre_launch_failure") diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index eb2fcdb8a..f72ab09c5 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -22,6 +22,63 @@ } +def _live_group_members(group_id: int) -> set[int]: + """Observe live members of one process group created by this fixture.""" + members = set() + for entry in Path("/proc").iterdir(): + if not entry.name.isdecimal(): + continue + try: + fields = (entry / "stat").read_text().rsplit(") ", 1)[1].split() + if int(fields[2]) == group_id and fields[0] not in {"Z", "X"}: + members.add(int(entry.name)) + except (IndexError, OSError, ValueError): + continue + return members + + +def _stop_owned_group( + process: subprocess.Popen, *, graceful_seconds: float = 20, force_seconds: float = 10 +) -> None: + """Stop and reap every live member of this start_new_session process group.""" + group_id = process.pid + if process.poll() is None and os.getpgid(group_id) != group_id: + raise RuntimeError("owned process is not its own group leader") + + def wait_until_empty(seconds: float) -> bool: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + process.poll() + if not _live_group_members(group_id): + return True + time.sleep(0.1) + process.poll() + return not _live_group_members(group_id) + + if _live_group_members(group_id): + os.killpg(group_id, signal.SIGTERM) + if not wait_until_empty(graceful_seconds): + os.killpg(group_id, signal.SIGKILL) + if not wait_until_empty(force_seconds): + raise RuntimeError("owned process group retained live members") + process.wait(timeout=1) + + +def _interrupt_owned_groups(processes: list[subprocess.Popen]) -> None: + """Fan out cancellation before the isolation runner's two-second KILL grace.""" + for process in reversed(processes): + if _live_group_members(process.pid): + os.killpg(process.pid, signal.SIGTERM) + deadline = time.monotonic() + 1 + while time.monotonic() < deadline and any( + _live_group_members(process.pid) for process in processes + ): + time.sleep(0.05) + for process in reversed(processes): + if _live_group_members(process.pid): + os.killpg(process.pid, signal.SIGKILL) + + def _required_file(environment: dict[str, str], name: str, *, limit: int) -> Path: raw = environment.get(name) if not raw: @@ -201,6 +258,13 @@ def durable_runtime(root: Path, directory: Path, environment: dict[str, str]): """Start only owned local broker/worker groups; runner lives outside this host.""" processes, logs = [], [] + def interrupt_owned(_signum, _frame): + # The isolation runner gives its child only two seconds after TERM. + # These workers are separate sessions, so the runner's process-group + # signal does not reach them without this exact-owned fanout. + _interrupt_owned_groups(processes) + raise KeyboardInterrupt + def start(arguments: list[str], label: str, *, extra_environment=None): log = (directory / (label + ".log")).open("wb") logs.append(log) @@ -249,6 +313,7 @@ def start(arguments: list[str], label: str, *, extra_environment=None): redis_binary = shutil.which("redis-server") if redis_binary is None: raise RuntimeError("journey requires redis-server") + previous_sigterm = signal.signal(signal.SIGTERM, interrupt_owned) try: redis = start( [ @@ -282,28 +347,28 @@ def start_workers(): def worker( label: str, queues: str, concurrency: int, *, extra_environment=None ): - required.append( - start( - [ - sys.executable, - "-m", - "celery", - "-A", - "app.workers.celery_app", - "worker", - "--pool=prefork", - f"--concurrency={concurrency}", - "--queues", - queues, - f"--hostname={label}@localhost", - "--loglevel=WARNING", - ], - label, - extra_environment=extra_environment, - ) + process = start( + [ + sys.executable, + "-m", + "celery", + "-A", + "app.workers.celery_app", + "worker", + "--pool=prefork", + f"--concurrency={concurrency}", + "--queues", + queues, + f"--hostname={label}@localhost", + "--loglevel=WARNING", + ], + label, + extra_environment=extra_environment, ) + required.append(process) + return process - worker("worker", "celery,workstream.outbox", 2) + general_worker = worker("worker", "celery,workstream.outbox", 2) worker("finalizer", "workstream.submission_finalization", 1) worker( "source-cleanup", @@ -340,18 +405,35 @@ def worker( raise RuntimeError("required journey worker exited during startup") time.sleep(0.2) + def stop_general_worker(): + if general_worker.poll() is not None: + raise RuntimeError("owned general worker already exited") + _stop_owned_group(general_worker) + + async def start_general_worker(): + nonlocal general_worker + if general_worker.poll() is None: + raise RuntimeError("owned general worker was not stopped") + general_worker = worker( + "worker-restarted", "celery,workstream.outbox", 2 + ) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + if general_worker.poll() is not None: + raise RuntimeError("owned general worker restart exited") + await asyncio.sleep(0.2) + + return stop_general_worker, start_general_worker + yield start_workers finally: - for process in reversed(processes): - if process.poll() is None: - os.killpg(process.pid, signal.SIGTERM) - try: - process.wait(timeout=20) - except subprocess.TimeoutExpired: - os.killpg(process.pid, signal.SIGKILL) - process.wait(timeout=10) - for log in logs: - log.close() + try: + for process in reversed(processes): + _stop_owned_group(process) + finally: + signal.signal(signal.SIGTERM, previous_sigterm) + for log in logs: + log.close() if location := os.environ.get("WORKSTREAM_CLI_JOURNEY_EVIDENCE"): retained = Path(location) / "runtime-logs" retained.mkdir(mode=0o700, parents=True) From 3b3c33783203f68737563bc36bfef37479f3481a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:37:38 +0100 Subject: [PATCH 314/513] Drain all owned journey worker groups on shutdown --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 +++ .../test_journey_worker_cleanup.py | 35 ++++++++++ cli/tests/journey/runtime.py | 68 ++++++++++++++----- 3 files changed, 93 insertions(+), 18 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 77f04ac2e..92af8d2a8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10273,3 +10273,11 @@ grace. Real leader plus TERM-resistant child controls passed both normal and cancellation paths (2 cases); an in-memory predecessor leader-only stop failed the regression. Focused bucket/cleanup checks: 6 passed; Ruff and diff check passed. These are fixture checks, not a live runner-fault result. + +Root review found three teardown edges before integration. Exact group signals +now accept a group exiting between observation and `killpg`; shutdown attempts +every owned group and retains its first failure through log capture; a stopped +general worker is removed from the active ownership list before restart so a +stale process-group ID is never signalled later. Added focused race and +attempt-all controls. Eight local fixture checks pass, including the two real +process-group cases; the remote supervisor is still unstarted. diff --git a/cli/tests/integration/test_journey_worker_cleanup.py b/cli/tests/integration/test_journey_worker_cleanup.py index c52c484bb..181635d16 100644 --- a/cli/tests/integration/test_journey_worker_cleanup.py +++ b/cli/tests/integration/test_journey_worker_cleanup.py @@ -60,3 +60,38 @@ def test_owned_worker_group_reaps_leader_and_term_resistant_child(tmp_path, canc leader.wait(timeout=5) if leader.stdout is not None: leader.stdout.close() + + +def test_group_exit_between_snapshot_and_signal_is_already_drained(monkeypatch): + class Exited: + pid = 424242 + + def poll(self): + return 0 + + def wait(self, *, timeout): + return 0 + + observations = iter(({Exited.pid}, set(), set())) + monkeypatch.setattr(MODULE, "_live_group_members", lambda _: next(observations)) + monkeypatch.setattr( + MODULE.os, + "killpg", + lambda *_: (_ for _ in ()).throw(ProcessLookupError()), + ) + MODULE._stop_owned_group(Exited(), graceful_seconds=0, force_seconds=0) + + +def test_failed_group_does_not_skip_other_owned_group(monkeypatch): + first, second = object(), object() + expected = RuntimeError("first group refused to drain") + observed = [] + + def stop(process): + observed.append(process) + if process is second: + raise expected + + monkeypatch.setattr(MODULE, "_stop_owned_group", stop) + assert MODULE._stop_owned_groups([first, second]) is expected + assert observed == [second, first] diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index f72ab09c5..9860b4724 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -42,8 +42,12 @@ def _stop_owned_group( ) -> None: """Stop and reap every live member of this start_new_session process group.""" group_id = process.pid - if process.poll() is None and os.getpgid(group_id) != group_id: - raise RuntimeError("owned process is not its own group leader") + if process.poll() is None: + try: + if os.getpgid(group_id) != group_id: + raise RuntimeError("owned process is not its own group leader") + except ProcessLookupError: + pass def wait_until_empty(seconds: float) -> bool: deadline = time.monotonic() + seconds @@ -56,9 +60,15 @@ def wait_until_empty(seconds: float) -> bool: return not _live_group_members(group_id) if _live_group_members(group_id): - os.killpg(group_id, signal.SIGTERM) + try: + os.killpg(group_id, signal.SIGTERM) + except ProcessLookupError: + pass if not wait_until_empty(graceful_seconds): - os.killpg(group_id, signal.SIGKILL) + try: + os.killpg(group_id, signal.SIGKILL) + except ProcessLookupError: + pass if not wait_until_empty(force_seconds): raise RuntimeError("owned process group retained live members") process.wait(timeout=1) @@ -68,7 +78,10 @@ def _interrupt_owned_groups(processes: list[subprocess.Popen]) -> None: """Fan out cancellation before the isolation runner's two-second KILL grace.""" for process in reversed(processes): if _live_group_members(process.pid): - os.killpg(process.pid, signal.SIGTERM) + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass deadline = time.monotonic() + 1 while time.monotonic() < deadline and any( _live_group_members(process.pid) for process in processes @@ -76,7 +89,22 @@ def _interrupt_owned_groups(processes: list[subprocess.Popen]) -> None: time.sleep(0.05) for process in reversed(processes): if _live_group_members(process.pid): - os.killpg(process.pid, signal.SIGKILL) + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def _stop_owned_groups(processes: list[subprocess.Popen]) -> BaseException | None: + """Attempt every owned group even when an earlier group refuses to drain.""" + first_error = None + for process in reversed(processes): + try: + _stop_owned_group(process) + except BaseException as exc: + if first_error is None: + first_error = exc + return first_error def _required_file(environment: dict[str, str], name: str, *, limit: int) -> Path: @@ -409,6 +437,7 @@ def stop_general_worker(): if general_worker.poll() is not None: raise RuntimeError("owned general worker already exited") _stop_owned_group(general_worker) + processes.remove(general_worker) async def start_general_worker(): nonlocal general_worker @@ -427,19 +456,22 @@ async def start_general_worker(): yield start_workers finally: + shutdown_error = _stop_owned_groups(processes) try: - for process in reversed(processes): - _stop_owned_group(process) - finally: signal.signal(signal.SIGTERM, previous_sigterm) for log in logs: log.close() - if location := os.environ.get("WORKSTREAM_CLI_JOURNEY_EVIDENCE"): - retained = Path(location) / "runtime-logs" - retained.mkdir(mode=0o700, parents=True) - for source in directory.glob("*.log"): - target = retained / source.name - with target.open("xb") as destination: - target.chmod(0o600) - with source.open("rb") as incoming: - shutil.copyfileobj(incoming, destination) + if location := os.environ.get("WORKSTREAM_CLI_JOURNEY_EVIDENCE"): + retained = Path(location) / "runtime-logs" + retained.mkdir(mode=0o700, parents=True) + for source in directory.glob("*.log"): + target = retained / source.name + with target.open("xb") as destination: + target.chmod(0o600) + with source.open("rb") as incoming: + shutil.copyfileobj(incoming, destination) + except BaseException as exc: + if shutdown_error is None: + shutdown_error = exc + if shutdown_error is not None: + raise shutdown_error From 5c3be023d86a5f0cd3424d924ebb8fe1e3532171 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:40:22 +0100 Subject: [PATCH 315/513] Validate hosted runner config under root-owned ancestry --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 49 ++++++++++++++++++ .../REMOTE_PRE_LAUNCH.md | 3 +- .../public_node_faults.py | 26 ++++++++-- scripts/test_public_hosted_attachment.py | 51 +++++++++++++++++++ 4 files changed, 124 insertions(+), 5 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 92af8d2a8..f0fb64961 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10281,3 +10281,52 @@ general worker is removed from the active ownership list before restart so a stale process-group ID is never signalled later. Added focused race and attempt-all controls. Eight local fixture checks pass, including the two real process-group cases; the remote supervisor is still unstarted. + +### Validate hosted config custody under its root-owned directory + +Intent: actual read-only staged validate_node failed before any supervisor start +because the shared private-control path check required the config parent to be +owned by runtime UID10001/mode0700. The approved hosted configuration is instead +UID/GID10001/mode0400 under root-owned nonwritable /etc/workstream. Repair only +that configuration-file validation; never chmod/move the deployed config to fit +the operator fixture. Allowed files are public_node_faults.py, the existing +public fixture guard module, its affected experiment docs and this record. + +Acceptance: root-owned nonwritable hosted config ancestry is allowed while its +file stays exact UID/GID10001,0400,regular,single-link,canonical and inode-bound. +Writable or foreign-owned ancestry, symlink aliases, wrong file mode/owner and +extra links refuse. Keep local config and every private control/runtime directory +on their existing strict private checks. Add a discriminating root-parent control +and denials, retain the same-fd read and exact-inode write checks, then run focused +guards/static gates. Local tests may model root ownership because the host user +has no sudo; actual runner read-only validation follows reviewed incremental +source staging. No runner file writes, restart or supervisor start in this task. + +Read-only parent audit confirmed /etc/workstream, /etc and / are UID/GID0 mode0755; +config inode303569 remains UID/GID10001 mode0400 with one link. Evidence is +/tmp/submission-runner-config-parents.json. No runner permissions, files or +services changed. The config-only helper now accepts that root-owned ancestry +without group/other write, retaining the existing runtime-private0700 hosted +layout and local config branch through unchanged private_path checks. Mutable +private controls were not generalized. + +Final bridge class passed10 in0.494s at +/tmp/submission-runner-config-parent-final.log. The new named guard uses modeled +root/runtime stat identities with a real FD read and a real foreign-inode denial; +local sudo is unavailable, so it is not a physical root-ownership drill. It +includes both valid config-anchor layouts plus writable/foreign ancestry, +file UID/GID/mode/link, symlink, canonical-alias and inode denials; root0755 is +still refused as a mutable private control directory. The same named guard +fails against the pre-repair read at the actual private-anchor error and kills +an in-memory omission of the new ancestry checks: +/tmp/submission-runner-config-parent-probe-final.json and matching.log. The first +probe replay reached its existing O_EXCL evidence filename; the unique final +artifact rerun completed. No source was mutated by either probe. + +AST/byte comparison confirms validate_node, ForeignControl, native resource +custody, private_path/PrivateControlDirectory and all same-FD/exact-inode I/O +checks unchanged. New helper/test stay below120lines, and the guard module is +1197lines without ledger changes. Ruff, local links and whitespace pass; +Commitrail is checked against bc4c37acd. Actual hosted validate_node remains a +separate read-only check after review and incremental source staging. No +supervisor start or native fault proof is claimed here; roadmap scope unchanged. diff --git a/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md b/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md index 8fc7265d2..ee9fbed3b 100644 --- a/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md +++ b/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md @@ -88,7 +88,8 @@ sudo -n install -d -m 0700 /var/lib/workstream-operator ``` Before any config write, compare the actual unit MainPID/ControlGroup, process -executable/argv, UID/GID10001, private config0400, private runtime parent0700, +executable/argv, UID/GID10001, runtime-owned config0400 under root-owned ancestry without +group/other write (or the existing runtime-private0700 anchor), private runtime parent0700, owner file0600, single slot, exact image cache entry and original config bytes against independent deployment custody. Hash service, Smol, guest and the reviewed wrapper against their independently approved artifacts. The root-owned diff --git a/experiments/pilot04_external_checker_runtime/public_node_faults.py b/experiments/pilot04_external_checker_runtime/public_node_faults.py index 5a7661f98..52c902a69 100644 --- a/experiments/pilot04_external_checker_runtime/public_node_faults.py +++ b/experiments/pilot04_external_checker_runtime/public_node_faults.py @@ -281,9 +281,28 @@ def _config_identity(hosted_runtime): return os.getuid(), os.getgid(), 0o600 -def _read_config(config_path, hosted_runtime): +def _validate_config_path(config_path, hosted_runtime): + """Validate config custody separately from private mutable control files.""" uid, gid, mode = _config_identity(hosted_runtime) - private_path(config_path, mode, uid=uid, gid=gid) + if not hosted_runtime or Path(config_path).parent.lstat().st_uid != 0: + private_path(config_path, mode, uid=uid, gid=gid) + return uid, gid, mode + path = Path(config_path) + if not path.is_absolute() or path.resolve() != path: + raise ValueError('hosted config path is not absolute and canonical') + info = path.lstat() + if (not stat.S_ISREG(info.st_mode) or (info.st_uid, info.st_gid) != (uid, gid) + or stat.S_IMODE(info.st_mode) != mode or info.st_nlink != 1): + raise ValueError('hosted config file ownership/mode/link differs') + for parent in path.parents: + info = parent.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError('hosted config ancestor ownership/mode differs') + return uid, gid, mode + + +def _read_config(config_path, hosted_runtime): + _validate_config_path(config_path, hosted_runtime) before = config_path.lstat() descriptor = os.open(config_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) with os.fdopen(descriptor, 'rb') as source: @@ -299,8 +318,7 @@ def write_node_config(config_path, data, identity, *, hosted_runtime=False): """Write only the validated existing inode, preserving its owner and mode.""" if len(data) > 1024 * 1024: raise ValueError('node config exceeds bound') - uid, gid, mode = _config_identity(hosted_runtime) - private_path(config_path, mode, uid=uid, gid=gid) + uid, gid, mode = _validate_config_path(config_path, hosted_runtime) descriptor = os.open(config_path, os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) with os.fdopen(descriptor, 'wb') as target: info = os.fstat(target.fileno()) diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 6ce05b79e..4dbb6668c 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -1034,6 +1034,57 @@ def close(self): self.assertEqual(handlers[signal.SIGTERM], signal.SIG_DFL) self.assertEqual(handlers[signal.SIGHUP], signal.SIG_DFL) + def test_hosted_config_root_parent_keeps_file_and_control_custody(self): + import os + import stat + from experiments.pilot04_external_checker_runtime import public_node_faults as owner + from experiments.pilot04_external_checker_runtime.public_fault_files import PrivateControlDirectory + config = Path('/etc/workstream/checker-service.json') + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / 'actual-fd' + source.write_bytes(b'{"owned":true}') + actual = source.stat() + def info(mode, uid, gid, links=1): + return os.stat_result((mode, actual.st_ino, actual.st_dev, links, uid, gid, + actual.st_size, 0, 0, 0)) + baseline = {path: info(stat.S_IFDIR | 0o755, 0, 0) for path in config.parents} + baseline[config] = info(stat.S_IFREG | 0o400, 10001, 10001) + observed = dict(baseline) + original_open, opened, resolved = os.open, source, config + def read(): + with patch.object(owner.os, 'getuid', return_value=0), \ + patch.object(Path, 'lstat', side_effect=lambda path: observed[path], autospec=True), \ + patch.object(Path, 'resolve', autospec=True, side_effect=lambda path: resolved), \ + patch.object(owner.os, 'open', side_effect=lambda *args: original_open(opened, os.O_RDONLY)): + return owner._read_config(config, True) + self.assertEqual(read(), (b'{"owned":true}', (actual.st_dev, actual.st_ino))) + observed[config.parent] = info(stat.S_IFDIR | 0o700, 10001, 10001) + self.assertEqual(read()[0], b'{"owned":true}') + observed = dict(baseline) + changes = [(config.parent, info(stat.S_IFDIR | mode, 0, 0)) for mode in (0o775, 0o777, 0o1777)] + changes += [(config.parent, info(stat.S_IFDIR | 0o755, uid, 0)) for uid in (1000, 10001)] + changes += [(Path('/etc'), info(stat.S_IFDIR | 0o755, 10001, 0)), + (config, info(stat.S_IFREG | 0o600, 10001, 10001)), + (config, info(stat.S_IFREG | 0o400, 0, 10001)), + (config, info(stat.S_IFREG | 0o400, 10001, 0)), + (config, info(stat.S_IFREG | 0o400, 10001, 10001, 2)), + (config, info(stat.S_IFLNK | 0o400, 10001, 10001))] + for path, value in changes: + observed = dict(baseline) | {path: value} + with self.subTest(path=path, mode=value.st_mode), self.assertRaises(ValueError): + read() + observed, resolved = dict(baseline), source + with self.assertRaisesRegex(ValueError, 'canonical'): + read() + resolved, opened = config, Path(directory) / 'other-fd' + opened.write_bytes(b'foreign inode') + with self.assertRaisesRegex(ValueError, 'identity/size'): + read() + with patch.object(Path, 'lstat', side_effect=lambda path: baseline[path], autospec=True), \ + patch.object(Path, 'resolve', autospec=True, side_effect=lambda path: path): + with self.assertRaises(ValueError): + PrivateControlDirectory(config.parent, uid=0, gid=0) + def test_bounded_ssh_reader_refuses_oversized_output(self): from experiments.pilot04_external_checker_runtime.public_runner_faults import _bounded_read async def exercise(): From 877c06c8111094e98041df84752185aae124296f Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:42:36 +0100 Subject: [PATCH 316/513] Record combined runner fault fixture verification --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f0fb64961..f45173562 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10330,3 +10330,5 @@ checks unchanged. New helper/test stay below120lines, and the guard module is Commitrail is checked against bc4c37acd. Actual hosted validate_node remains a separate read-only check after review and incremental source staging. No supervisor start or native fault proof is claimed here; roadmap scope unchanged. + +Integrated runner config validation and focused PRE fixture at5c3be023d: combined worker-group cleanup and hosted-attachment suite passed41 tests plus73 subtests in26.57s. Ruff passed all six affected Python paths, whitespace passed and Commitrail passed. This verifies the combined local test tooling, not execution of the remote fault. Staging/read-only validation of the new runner-pinned source remains the next deployment action. From f26f201f5b9df954e93dbb29300e701e92011e0e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:45:35 +0100 Subject: [PATCH 317/513] Update busy-node refusal fixture for finite runner supervisor --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 6 ++++++ scripts/test_public_smol_proof.py | 7 +++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f45173562..81018f177 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10332,3 +10332,9 @@ separate read-only check after review and incremental source staging. No supervisor start or native fault proof is claimed here; roadmap scope unchanged. Integrated runner config validation and focused PRE fixture at5c3be023d: combined worker-group cleanup and hosted-attachment suite passed41 tests plus73 subtests in26.57s. Ruff passed all six affected Python paths, whitespace passed and Commitrail passed. This verifies the combined local test tooling, not execution of the remote fault. Staging/read-only validation of the new runner-pinned source remains the next deployment action. + +### Repair busy-node fixture for the finite runner supervisor + +Intent: release-image CI at877c06c81 found the existing busy-node control still calls serve without required run_id, maximum_seconds and image_digest, failing before its refusal assertion. Bounded change: scripts/test_public_smol_proof.py and this record only; supply explicit finite test pins and a matching cache entry so the existing busy-resource refusal is reached. No production changes, weakened assertions or skipped checks. Low-risk fixture repair; verify the complete existing script suite, including optimized Python refusal, and Ruff. Root reviews exact diff; human review focus is preserving no-control/no-config mutation for all four resource classes. + +Fixture repair verification: all13 scripts.test_public_smol_proof unittest cases passed in3.026s, including the optimized-Python subprocess and all four busy-resource subcases. Ruff and whitespace checks passed. Exact review confirms only matching test config and the three required bounded supervisor arguments changed; all refusal and no-mutation assertions remain. diff --git a/scripts/test_public_smol_proof.py b/scripts/test_public_smol_proof.py index 59e0466f8..1729fac66 100644 --- a/scripts/test_public_smol_proof.py +++ b/scripts/test_public_smol_proof.py @@ -264,7 +264,8 @@ def test_foreign_fixture_cleanup_is_exact_and_requires_disk_absence(self): def test_busy_node_refused_before_control_or_config_mutation(self): config_path = self.root / 'service.json' - original = b'{"test": "untouched"}' + image_digest = 'sha256:' + 'a' * 64 + original = json.dumps({'cache': [{'platform_manifest_digest': image_digest}]}).encode() config_path.write_bytes(original) config_path.chmod(0o600) control_root = self.root / 'control' @@ -275,7 +276,9 @@ def test_busy_node_refused_before_control_or_config_mutation(self): patch.object(faults, 'ForeignControl') as foreign, \ patch.object(subprocess, 'run') as commands: with self.assertRaisesRegex(RuntimeError, 'node must be drained'): - faults.serve(config_path, control_root, 'owned.service', self.root / 'manifest') + faults.serve(config_path, control_root, 'owned.service', self.root / 'manifest', + run_id='2f662dee-328c-4df5-8b8e-e9f934360654', + maximum_seconds=30, image_digest=image_digest) controls.assert_not_called() foreign.assert_not_called() commands.assert_not_called() From 35e1d50ea973bced00cdc0f79dd6ba6519db9f5d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:49:50 +0100 Subject: [PATCH 318/513] Format focused PRE journey fixtures with pinned Ruff --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 4 ++++ .../test_journey_worker_cleanup.py | 9 ++++++++- cli/tests/journey/bootstrap.py | 4 +++- cli/tests/journey/pre_launch_fault.py | 19 +++++++++++++------ cli/tests/journey/runtime.py | 5 ++++- 5 files changed, 32 insertions(+), 9 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 81018f177..1ec78bf9d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10338,3 +10338,7 @@ Integrated runner config validation and focused PRE fixture at5c3be023d: combine Intent: release-image CI at877c06c81 found the existing busy-node control still calls serve without required run_id, maximum_seconds and image_digest, failing before its refusal assertion. Bounded change: scripts/test_public_smol_proof.py and this record only; supply explicit finite test pins and a matching cache entry so the existing busy-resource refusal is reached. No production changes, weakened assertions or skipped checks. Low-risk fixture repair; verify the complete existing script suite, including optimized Python refusal, and Ruff. Root reviews exact diff; human review focus is preserving no-control/no-config mutation for all four resource classes. Fixture repair verification: all13 scripts.test_public_smol_proof unittest cases passed in3.026s, including the optimized-Python subprocess and all four busy-resource subcases. Ruff and whitespace checks passed. Exact review confirms only matching test config and the three required bounded supervisor arguments changed; all refusal and no-mutation assertions remain. + +Actual runner source61dbcdd55 passed read-only validate_node on the hosted node; `/tmp/submission-runner-61dbcdd55-validation.json` binds exact source, unchanged original config and PID8263. The root then started the finite supervisor run3a85b8a2-eafa-4b33-a13c-86c05844c62e once; systemd acknowledged invocation493fafa63a0147d5ae3d89796b8c1f63, and a separate observation confirmed PID11525 active/running with supervisor-ready present. Focused public failure/replay/recovery drill pre1 is using integrated5c3be023d, with source0091 and the matching private profile. This entry records launch only, not a passing fault result or completed restoration. + +CLI contract CI stopped at the existing formatter check for the four new/edited journey fixture files (lint passed). Apply pinned Ruff formatting only to those four paths; preserve ASTs and all assertions, then run whole cli/tests lint/format checks. This is formatting repair of the same bounded fixture, with no runtime change. diff --git a/cli/tests/integration/test_journey_worker_cleanup.py b/cli/tests/integration/test_journey_worker_cleanup.py index 181635d16..fbdf4aa79 100644 --- a/cli/tests/integration/test_journey_worker_cleanup.py +++ b/cli/tests/integration/test_journey_worker_cleanup.py @@ -37,7 +37,14 @@ def test_owned_worker_group_reaps_leader_and_term_resistant_child(tmp_path, canc "print(child.pid,flush=True); time.sleep(360)" ) leader = subprocess.Popen( - [sys.executable, "-c", leader_code, str(ready), str(int(cancelled)), child_code], + [ + sys.executable, + "-c", + leader_code, + str(ready), + str(int(cancelled)), + child_code, + ], start_new_session=True, stdout=subprocess.PIPE, text=True, diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py index 379f6c1f5..c896058d5 100644 --- a/cli/tests/journey/bootstrap.py +++ b/cli/tests/journey/bootstrap.py @@ -131,7 +131,9 @@ def main(): or os.environ.get("WORKSTREAM_CLI_JOURNEY_SUBMIT") == "1" or not os.environ.get("WORKSTREAM_CLI_JOURNEY_EVIDENCE") ): - raise RuntimeError("PRE launch fault requires the isolated setup and task path") + raise RuntimeError( + "PRE launch fault requires the isolated setup and task path" + ) fault_profile = None if fault_mode: from pre_launch_fault import load_fault_profile diff --git a/cli/tests/journey/pre_launch_fault.py b/cli/tests/journey/pre_launch_fault.py index 4b3f76f92..503830cdf 100644 --- a/cli/tests/journey/pre_launch_fault.py +++ b/cli/tests/journey/pre_launch_fault.py @@ -57,13 +57,18 @@ def unique_pairs(pairs): if type(body) is not dict or set(body) != PROFILE_FIELDS: raise RuntimeError("fault profile fields differ") profile = RunnerFaultProfile( - **(body | { - "identity_file": Path(body["identity_file"]), - "known_hosts_file": Path(body["known_hosts_file"]), - }) + **( + body + | { + "identity_file": Path(body["identity_file"]), + "known_hosts_file": Path(body["known_hosts_file"]), + } + ) ) profile.validate() - if profile.image_digest != environment.get("WORKSTREAM_CLI_JOURNEY_CHECKER_IMAGE_DIGEST"): + if profile.image_digest != environment.get( + "WORKSTREAM_CLI_JOURNEY_CHECKER_IMAGE_DIGEST" + ): raise RuntimeError("fault profile image differs from approved guide") return profile @@ -101,7 +106,9 @@ async def _run( engine = create_async_engine(database_url) factory = async_sessionmaker(engine, expire_on_commit=False) try: - async with httpx.AsyncClient(base_url=origin, timeout=timeout, trust_env=False) as client: + async with httpx.AsyncClient( + base_url=origin, timeout=timeout, trust_env=False + ) as client: return await public_pre_launch_failure( client, factory, diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index 9860b4724..76b2546d5 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -38,7 +38,10 @@ def _live_group_members(group_id: int) -> set[int]: def _stop_owned_group( - process: subprocess.Popen, *, graceful_seconds: float = 20, force_seconds: float = 10 + process: subprocess.Popen, + *, + graceful_seconds: float = 20, + force_seconds: float = 10, ) -> None: """Stop and reap every live member of this start_new_session process group.""" group_id = process.pid From d67eddfd6f9c1de352dc6760768a28786251f686 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:52:42 +0100 Subject: [PATCH 319/513] Record remote PRE fault refusal and verified runner restoration --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 1ec78bf9d..976070e2e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10342,3 +10342,7 @@ Fixture repair verification: all13 scripts.test_public_smol_proof unittest cases Actual runner source61dbcdd55 passed read-only validate_node on the hosted node; `/tmp/submission-runner-61dbcdd55-validation.json` binds exact source, unchanged original config and PID8263. The root then started the finite supervisor run3a85b8a2-eafa-4b33-a13c-86c05844c62e once; systemd acknowledged invocation493fafa63a0147d5ae3d89796b8c1f63, and a separate observation confirmed PID11525 active/running with supervisor-ready present. Focused public failure/replay/recovery drill pre1 is using integrated5c3be023d, with source0091 and the matching private profile. This entry records launch only, not a passing fault result or completed restoration. CLI contract CI stopped at the existing formatter check for the four new/edited journey fixture files (lint passed). Apply pinned Ruff formatting only to those four paths; preserve ASTs and all assertions, then run whole cli/tests lint/format checks. This is formatting repair of the same bounded fixture, with no runtime change. + +Focused remote pre1 finished exit1: public setup and claimed task succeeded; the failure submission returned expected503, then native trace launch-count assertion failed before replay/recovery. This is not a passing fault qualification. Isolated metadata confirms schema0091 and database/MinIO cleanup complete. Root sent TERM once to the exact finite supervisor; same-run restoration receipt `/tmp/submission-runner-pre1-restoration.json` confirms original config SHA c3f8fb85ab2cc3b27ddf8da6db1e483aae9880b23918822c241d6864322a3dcd, empty disks/leases/machines/cgroups, and exact foreign test machine/disk/cgroup/process removal. Trace diagnosis precedes any rerun. + +Post-restoration independent SSH verified checker PID11966 active/running and exact original config hash. Read-only snapshot has zero trace events, so pre1 did not reach the intended native launch fault. Root reproduced a concrete harness path defect: `/var/lib/workstream-operator` is root:root0700, while its runtime child is10001:10001/0700; `sudo -u '#10001' test -x` on the wrapper fails. Runtime-only files must live beneath an accessible service-owned anchor; operator controls must remain private. Do not relax launch-count assertions or shared parent permissions. From d1d5d38e7f12ba23c1c9d1677a16661df88fcbd1 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:56:16 +0100 Subject: [PATCH 320/513] Record complete release configuration repair verification --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 976070e2e..d388ccc25 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10346,3 +10346,5 @@ CLI contract CI stopped at the existing formatter check for the four new/edited Focused remote pre1 finished exit1: public setup and claimed task succeeded; the failure submission returned expected503, then native trace launch-count assertion failed before replay/recovery. This is not a passing fault qualification. Isolated metadata confirms schema0091 and database/MinIO cleanup complete. Root sent TERM once to the exact finite supervisor; same-run restoration receipt `/tmp/submission-runner-pre1-restoration.json` confirms original config SHA c3f8fb85ab2cc3b27ddf8da6db1e483aae9880b23918822c241d6864322a3dcd, empty disks/leases/machines/cgroups, and exact foreign test machine/disk/cgroup/process removal. Trace diagnosis precedes any rerun. Post-restoration independent SSH verified checker PID11966 active/running and exact original config hash. Read-only snapshot has zero trace events, so pre1 did not reach the intended native launch fault. Root reproduced a concrete harness path defect: `/var/lib/workstream-operator` is root:root0700, while its runtime child is10001:10001/0700; `sudo -u '#10001' test -x` on the wrapper fails. Runtime-only files must live beneath an accessible service-owned anchor; operator controls must remain private. Do not relax launch-count assertions or shared parent permissions. + +The exact six-module release configuration unittest command that failed in CI was rerun atd67eddfd6 after the busy-node fixture repair:119 tests passed in49.978s (`/tmp/submission-release-config-repair.log`). Whole cli/tests lint and all105 formatting checks also pass; AST comparison confirmed the four formatted files preserve behavior. These local repairs do not claim the final CI or native fault qualification passed. From 366ec6ddc7ffde8c01865416dfabc8d0bc49d60c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 18:56:31 +0100 Subject: [PATCH 321/513] Keep AWS source tests within the unchanged structural gate --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 46 ++++++ backend/scripts/test_lane_catalogue.py | 1 + .../artifacts/test_submission_aws_source.py | 145 ++++++++++++++++++ .../test_submission_intake_admission.py | 129 ---------------- backend/tests/test_ci_lane_catalogue.py | 4 +- 5 files changed, 194 insertions(+), 131 deletions(-) create mode 100644 backend/tests/artifacts/test_submission_aws_source.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d388ccc25..53e841886 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10348,3 +10348,49 @@ Focused remote pre1 finished exit1: public setup and claimed task succeeded; the Post-restoration independent SSH verified checker PID11966 active/running and exact original config hash. Read-only snapshot has zero trace events, so pre1 did not reach the intended native launch fault. Root reproduced a concrete harness path defect: `/var/lib/workstream-operator` is root:root0700, while its runtime child is10001:10001/0700; `sudo -u '#10001' test -x` on the wrapper fails. Runtime-only files must live beneath an accessible service-owned anchor; operator controls must remain private. Do not relax launch-count assertions or shared parent permissions. The exact six-module release configuration unittest command that failed in CI was rerun atd67eddfd6 after the busy-node fixture repair:119 tests passed in49.978s (`/tmp/submission-release-config-repair.log`). Whole cli/tests lint and all105 formatting checks also pass; AST comparison confirmed the four formatted files preserve behavior. These local repairs do not claim the final CI or native fault qualification passed. + +### Restore the structural gate by relocating AWS source tests + +Intent: hosted auth preflight877c06c81 passed92boundary guards, then correctly +failed structural_debt_mismatch. Exact inventory comparison found only one new +item: backend/tests/artifacts/test_submission_intake_admission.py at1249lines +against hard1200; all33 frozen entries and policy digest remain identical. +Do not regenerate or relax the debt ledger. The added AWS profile contract tests +belong in a small cohesive artifact module using their unchanged shared fixture. + +Allowed files: the original admission test module, new +backend/tests/artifacts/test_submission_aws_source.py, existing test lane catalogue +and independent family fingerprint test, and this record. Relocate the three AWS +profile tests byte/AST-identically, retain their signed AUTH/namespace fixture +closure and real-SQL assertions, and assign the new module to the same shared +family without moving/deleting existing modules. No production, workflow, policy, +ledger, skip, threshold or runtime deadline changes. Verification: exact inventory +parity, complete structural validation, old/new test and fixture identity checks, +focused collection and catalogue negatives. Reuse prior executed PG proof only +for identical test bodies/context; do not claim a fresh PG or deployed AWS run. + +Implemented the relocation without changing policy or ledger: original admission +module is1120lines and new AWS source module145. All three decorated function ASTs +and exact function source segments match877c06c81, and every remaining original +module AST is unchanged (/tmp/submission-structural-877-preservation.py). The new +module imports the identical signed AUTH/admission fixtures and helpers; focused +collection passed39nodes in7.33s, including all three relocated nodes, complete +fixture closure and exact identity of13fixture/global bindings +(/tmp/submission-structural-877-collection.log/.json). Collection executes no +PostgreSQL setup. Existing PG component proof remains pre-relocation custody; +no new transaction/provider/native execution is claimed. + +Full unchanged structural validation exits0 at +/tmp/submission-structural-877-after.log. Its exact repository guard passes on +current source and rejects the original1249line source restored only in memory +with structural_debt_mismatch. Omitting only the new AWS module makes the exact +independent family test fail; no source files were mutated by these probes +(/tmp/submission-structural-877-discriminator.log/.json). The shared family adds +exactly one module, retaining all previous modules/order and lane topology; +removing only that addition reproduces the prior276-module fingerprint. The +new277-module fingerprint is7d5683912037886633519322314c8fdc3c89855dc2408b2ffc629c842e3ad8fc. +All59catalogue tests pass7.54s (/tmp/submission-structural-877-catalogue.log), with +only the documented plugin-disabled asyncio-mode warning. Ruff, whitespace and +Markdown links pass. No workflow, debt baseline, limits, assertion-map, skip or +product capability changed; roadmap scope is unchanged. Hosted lane reruns remain +root-owned rather than inferred from these local checks. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 0a9d217ac..07471c74d 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -60,6 +60,7 @@ class TestLane: "tests/artifacts/test_source_cleanup_topology.py", "tests/artifacts/test_submission_pre_source.py", "tests/artifacts/test_submission_intake_admission.py", + "tests/artifacts/test_submission_aws_source.py", "tests/artifacts/test_submission_intake_progress.py", "tests/artifacts/test_submission_finalization_worker_loss.py", "tests/artifacts/test_submission_foreground_command.py", diff --git a/backend/tests/artifacts/test_submission_aws_source.py b/backend/tests/artifacts/test_submission_aws_source.py new file mode 100644 index 000000000..29ccbacc3 --- /dev/null +++ b/backend/tests/artifacts/test_submission_aws_source.py @@ -0,0 +1,145 @@ +"""Qualified AWS profile joins the existing T1 and selected PRE source custody.""" +from datetime import timedelta + +import pytest + +from app.adapters.tasks import task_submission_context_port +from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata +from app.modules.artifacts.intake.models import SubmissionIntakeOperation +from tests.artifacts.test_submission_intake_custody import repository +from tests.artifacts.test_submission_intake_admission import ( + admission_intake as admission_intake, admin_access as admin_access, admit_new, + auth_database_env as auth_database_env, clear_settings_cache as clear_settings_cache, + rsa_signing_material as rsa_signing_material, signed_access as signed_access, + record_intake_eof, +) + + +@pytest.mark.parametrize("admission_intake", ["aws"], indirect=True) +async def test_t1_qualified_aws_reserves_exact_source_custody(admission_intake): + from sqlalchemy import select + from app.modules.artifacts.intake.foreground_admission import IntakeReservationOwner, IntakeReplay + from app.modules.artifacts.intake.models import SubmissionSourceCharge + from app.modules.tasks.models import AuditEvent, WorkstreamTask + f = admission_intake + assert f.source_store_factory is None # T1 has no provider or body capability. + key = new_record_id() + owner = await admit_new(f, key=key) + assert isinstance(owner, IntakeReservationOwner) + async with f.factory() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + charge = await session.get(SubmissionSourceCharge, row.id) + task = await session.get(WorkstreamTask, str(f.task)) + assert row.provider_profile == "aws-s3-v1" + assert row.namespace_id == "primary" and row.namespace_fingerprint == f.namespace.namespace_fingerprint + assert row.state == "receiving" and row.raw_sha256 is None + assert row.idempotency_key == str(key) and row.identity_link_id == str(f.actor.identity_link_id) + assert charge.accounted_bytes == 1024 and charge.state == "reserved" + assert task.active_submission_operation_id == row.id + events = list(await session.scalars(select(AuditEvent).where( + AuditEvent.action_id == "submission.intake.reserve", AuditEvent.resource_id == row.id, + ))) + assert len(events) == 1 and events[0].after_facts["allowed"] is True + replay = await admit_new(f, key=key) + assert isinstance(replay, IntakeReplay) and replay.operation_id == owner.operation_id + + +def test_unknown_source_profile_has_no_namespace_identity(): + from app.interfaces.artifacts import ArtifactStoreNamespaceIdentity + with pytest.raises(ValueError, match="artifact provider profile is unsupported"): + ArtifactStoreNamespaceIdentity("unqualified-v1", ()) + + +@pytest.mark.parametrize("admission_intake", ["aws"], indirect=True) +async def test_qualified_aws_pre_source_matches_locked_sql(admission_intake): + """A database-only source binds the qualified profile; provider I/O is separate proof.""" + import json + from datetime import UTC, datetime + from uuid import UUID + + from sqlalchemy import text + from sqlalchemy.exc import DBAPIError + + from app.adapters.artifacts import submission_intake_pre_source_port + from app.adapters.projects import project_locked_policy_context_port + from app.core.hashing import canonical_json_hash + from app.modules.artifacts.selected_pre_submit_admission import ( + bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, + ) + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest + from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + + f = admission_intake + owner = await admit_new(f) + await record_intake_eof(f, owner, b"aws-profile-source") + async with f.factory.begin() as session: + row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) + deadline = datetime.now(UTC) + timedelta(minutes=2) + source = await repository(session).seal( + owner.operation_id, owner.lease_id, owner.generation, + provider_generation="opaque-aws-version", pre_deadline_at=deadline, + lease_expires_at=deadline, + ) + async with f.factory.begin() as session: + task = await task_submission_context_port(session).lock_submission_context( + TaskSubmissionContextRequest( + task_id=f.task, assignment_id=f.assignment, + contributor_id=f.actor.actor_profile_id, predecessor_submission_id=None, + ), + ) + references = task.locked_project_context + project = await project_locked_policy_context_port(session).lock_locked_policy_context( + ProjectLockedPolicyContextRequest(**{ + name: getattr(references, name) for name in ( + "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", + "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", + "pre_submit_policy_bundle_hash", + ) + }), + ) + guarded = await submission_intake_pre_source_port(session).lock_pre_source( + source=source, lease_id=owner.lease_id, generation=owner.generation, + ) + metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + selected = bind_selected_pre_submit_admission( + task=task, project=project, predecessor=None, predecessor_rules_sha256=None, + predecessor_exists=False, + packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + ) + request = build_selected_pre_submit_reservation( + source=guarded, metadata=metadata, task=task, project=project, + attempt_id=new_record_id(), idempotency_key=UUID(row.idempotency_key), + selected=selected, runtime_profile=_source_reservation().runtime_profile, + ) + assert request.admission_lineage.storage_scheme == "s3" + body = request.canonical_body() + value = { + "source_operation_id": str(owner.operation_id), "task_id": str(f.task), + "project_id": row.project_id, "assignment_id": str(f.assignment), + "actor_profile_id": row.actor_profile_id, "identity_link_id": row.identity_link_id, + "idempotency_key": row.idempotency_key, "request_json": body, + "request_digest": canonical_json_hash(body), + "archive_sha256": source.raw_sha256, "archive_byte_count": source.raw_byte_count, + "policy_sha256": request.policy_sha256, + } + statement = text("""SELECT public.require_selected_pre_source( + jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)))""") + async with f.factory.begin() as session: + await session.execute(statement, {"value": json.dumps(value)}) + for changed in ("storage_scheme", "provider_profile"): + forged = json.loads(json.dumps(body)) + if changed == "storage_scheme": + forged["admission_lineage"]["storage_scheme"] = "local" + else: + forged["source"]["location"]["provider_profile"] = "minio-v1" + forged["source_sha256"] = canonical_json_hash({ + "schema_version": "workstream.sealed_submission_source.v1", **forged["source"], + }) + with pytest.raises(DBAPIError, match="selected PRE source descriptor mismatch"): + async with f.factory.begin() as session: + await session.execute(statement, {"value": json.dumps(value | { + "request_json": forged, "request_digest": canonical_json_hash(forged), + })}) diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py index ffc0aea0d..4a3939436 100644 --- a/backend/tests/artifacts/test_submission_intake_admission.py +++ b/backend/tests/artifacts/test_submission_intake_admission.py @@ -441,133 +441,8 @@ async def body(): assert (await session.get(SubmissionSourceCharge, row.id)).accounted_bytes == 1024 -@pytest.mark.parametrize("admission_intake", ["aws"], indirect=True) -async def test_t1_qualified_aws_reserves_exact_source_custody(admission_intake): - from sqlalchemy import select - from app.modules.artifacts.intake.foreground_admission import IntakeReservationOwner, IntakeReplay - from app.modules.artifacts.intake.models import SubmissionSourceCharge - from app.modules.tasks.models import AuditEvent, WorkstreamTask - f = admission_intake - assert f.source_store_factory is None # T1 has no provider or body capability. - key = new_record_id() - owner = await admit_new(f, key=key) - assert isinstance(owner, IntakeReservationOwner) - async with f.factory() as session: - row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) - charge = await session.get(SubmissionSourceCharge, row.id) - task = await session.get(WorkstreamTask, str(f.task)) - assert row.provider_profile == "aws-s3-v1" - assert row.namespace_id == "primary" and row.namespace_fingerprint == f.namespace.namespace_fingerprint - assert row.state == "receiving" and row.raw_sha256 is None - assert row.idempotency_key == str(key) and row.identity_link_id == str(f.actor.identity_link_id) - assert charge.accounted_bytes == 1024 and charge.state == "reserved" - assert task.active_submission_operation_id == row.id - events = list(await session.scalars(select(AuditEvent).where( - AuditEvent.action_id == "submission.intake.reserve", AuditEvent.resource_id == row.id, - ))) - assert len(events) == 1 and events[0].after_facts["allowed"] is True - replay = await admit_new(f, key=key) - assert isinstance(replay, IntakeReplay) and replay.operation_id == owner.operation_id - - -def test_unknown_source_profile_has_no_namespace_identity(): - from app.interfaces.artifacts import ArtifactStoreNamespaceIdentity - with pytest.raises(ValueError, match="artifact provider profile is unsupported"): - ArtifactStoreNamespaceIdentity("unqualified-v1", ()) - - -@pytest.mark.parametrize("admission_intake", ["aws"], indirect=True) -async def test_qualified_aws_pre_source_matches_locked_sql(admission_intake): - """A database-only source binds the qualified profile; provider I/O is separate proof.""" - import json - from datetime import UTC, datetime - from uuid import UUID - - from sqlalchemy import text - from sqlalchemy.exc import DBAPIError - from app.adapters.artifacts import submission_intake_pre_source_port - from app.adapters.projects import project_locked_policy_context_port - from app.core.hashing import canonical_json_hash - from app.modules.artifacts.selected_pre_submit_admission import ( - bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, - ) - from app.modules.checkers.api.pre_submit_material import SubmissionPacketView - from app.modules.projects.api.locked_policy import ProjectLockedPolicyContextRequest - from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest - from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation - f = admission_intake - owner = await admit_new(f) - await record_intake_eof(f, owner, b"aws-profile-source") - async with f.factory.begin() as session: - row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) - deadline = datetime.now(UTC) + timedelta(minutes=2) - source = await repository(session).seal( - owner.operation_id, owner.lease_id, owner.generation, - provider_generation="opaque-aws-version", pre_deadline_at=deadline, - lease_expires_at=deadline, - ) - async with f.factory.begin() as session: - task = await task_submission_context_port(session).lock_submission_context( - TaskSubmissionContextRequest( - task_id=f.task, assignment_id=f.assignment, - contributor_id=f.actor.actor_profile_id, predecessor_submission_id=None, - ), - ) - references = task.locked_project_context - project = await project_locked_policy_context_port(session).lock_locked_policy_context( - ProjectLockedPolicyContextRequest(**{ - name: getattr(references, name) for name in ( - "project_id", "guide_version", "source_snapshot_id", "source_snapshot_hash", - "effective_policy_id", "effective_policy_hash", "pre_submit_policy_id", - "pre_submit_policy_bundle_hash", - ) - }), - ) - guarded = await submission_intake_pre_source_port(session).lock_pre_source( - source=source, lease_id=owner.lease_id, generation=owner.generation, - ) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) - selected = bind_selected_pre_submit_admission( - task=task, project=project, predecessor=None, predecessor_rules_sha256=None, - predecessor_exists=False, - packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), - ) - request = build_selected_pre_submit_reservation( - source=guarded, metadata=metadata, task=task, project=project, - attempt_id=new_record_id(), idempotency_key=UUID(row.idempotency_key), - selected=selected, runtime_profile=_source_reservation().runtime_profile, - ) - assert request.admission_lineage.storage_scheme == "s3" - body = request.canonical_body() - value = { - "source_operation_id": str(owner.operation_id), "task_id": str(f.task), - "project_id": row.project_id, "assignment_id": str(f.assignment), - "actor_profile_id": row.actor_profile_id, "identity_link_id": row.identity_link_id, - "idempotency_key": row.idempotency_key, "request_json": body, - "request_digest": canonical_json_hash(body), - "archive_sha256": source.raw_sha256, "archive_byte_count": source.raw_byte_count, - "policy_sha256": request.policy_sha256, - } - statement = text("""SELECT public.require_selected_pre_source( - jsonb_populate_record(NULL::public.selected_pre_submit_runs, CAST(:value AS jsonb)))""") - async with f.factory.begin() as session: - await session.execute(statement, {"value": json.dumps(value)}) - for changed in ("storage_scheme", "provider_profile"): - forged = json.loads(json.dumps(body)) - if changed == "storage_scheme": - forged["admission_lineage"]["storage_scheme"] = "local" - else: - forged["source"]["location"]["provider_profile"] = "minio-v1" - forged["source_sha256"] = canonical_json_hash({ - "schema_version": "workstream.sealed_submission_source.v1", **forged["source"], - }) - with pytest.raises(DBAPIError, match="selected PRE source descriptor mismatch"): - async with f.factory.begin() as session: - await session.execute(statement, {"value": json.dumps(value | { - "request_json": forged, "request_digest": canonical_json_hash(forged), - })}) async def test_t1_replay_reauthorizes_after_body_read(admission_intake): @@ -602,8 +477,6 @@ async def body(): - - async def test_t4_accepts_exact_source_and_replays_one_receipt(admission_intake, tmp_path): """T1/upload/PRE through the real atomic T4 owner; no formal Submission yet.""" from sqlalchemy import text @@ -654,7 +527,6 @@ async def repeated_body(): - @pytest.mark.parametrize("boundary", ["outbox", "task"]) async def test_t4_rolls_back_all_participants_and_can_retry(admission_intake, tmp_path, boundary): from sqlalchemy import text @@ -946,7 +818,6 @@ async def commit(self): - async def test_operator_recovers_same_accepted_finalization_once(recovery_intake, tmp_path): import asyncio from sqlalchemy import select, func diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 21ce7a36d..968dabc53 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -319,8 +319,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 276, - "5b40d4e12032e17b09c70cc4a7484acda6994d918479a7e1e0fce955efa292a4", + 277, + "7d5683912037886633519322314c8fdc3c89855dc2408b2ffc629c842e3ad8fc", ), "project": ( 257, From 9e8ab8130a73a1c86566908c09f8528bc2ed645d Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:02:43 +0100 Subject: [PATCH 322/513] Preflight hosted fault wrapper through traversable sibling --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 +++++++ .../REMOTE_PRE_LAUNCH.md | 4 +- .../public_node_faults.py | 17 +++++++ scripts/test_public_smol_proof.py | 45 +++++++++++++++++++ 4 files changed, 80 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 53e841886..4c221a6db 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10394,3 +10394,19 @@ only the documented plugin-disabled asyncio-mode warning. Ruff, whitespace and Markdown links pass. No workflow, debt baseline, limits, assertion-map, skip or product capability changed; roadmap scope is unchanged. Hosted lane reruns remain root-owned rather than inferred from these local checks. + +The smallest repair leaves the existing exact sibling resolver and root-private +controls unchanged. A fresh control root `/var/lib/workstream-pre-launch-$RUN_ID` +is root-owned0700 directly under the existing root-owned0755 `/var/lib` parent; +the supervisor-created sibling runtime remains checker-owned0700 and UID10001 +can traverse the parent. The independent custody manifest stays inside the +existing root-private `/var/lib/workstream-operator` directory. No parent mode, +service configuration or production binary is changed to make the fixture pass. +Before config rewrite, the supervisor now runs the reviewed wrapper `--version` +as UID/GID10001 with empty supplemental groups and requires the real pinned +Smol response, proving path traversal, wrapper settings read and original-binary +exec. A portable real-subprocess old-parent denial/new-sibling success test and +the unchanged exact sibling-binding control pass. Pinned read-only runner checks +also showed UID10001 can traverse `/var/lib` and execute original Smol. The new +run path and preflight remain to be staged and exercised; pre1 is still failed +evidence, not an injected-launch proof. diff --git a/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md b/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md index ee9fbed3b..7cb0adf19 100644 --- a/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md +++ b/experiments/pilot04_external_checker_runtime/REMOTE_PRE_LAUNCH.md @@ -58,7 +58,7 @@ After owner review, choose one reviewed commit (`REVIEWED_COMMIT`, full hex), on new canonical run UUID (`RUN_ID`), and the following fresh runner-only paths: - Source: `/opt/workstream/operator-fault-source/$REVIEWED_COMMIT`. -- Control: `/var/lib/workstream-operator/pre-launch-$RUN_ID` (created by supervisor). +- Control: `/var/lib/workstream-pre-launch-$RUN_ID` (root-owned `0700`, created by supervisor). Its existing sibling runtime is checker-owned `0700` under the already traversable, root-owned `/var/lib` `0755` parent. - Independent custody: `/var/lib/workstream-operator/pre-launch-$RUN_ID-custody.json`. - Finite operator unit: `workstream-operator-pre-launch-$RUN_ID.service`. @@ -104,7 +104,7 @@ Once the manifest is independently reviewed and staged, start only this runner supervisor, under a distinct finite root-owned unit: ```sh -sudo -n systemd-run --unit="workstream-operator-pre-launch-$RUN_ID" --property=Type=exec --property=RuntimeMaxSec=1200 --property=TimeoutStopSec=90 --property=KillSignal=SIGTERM --property=KillMode=process --property=SendSIGKILL=no /usr/bin/env "PYTHONPATH=/opt/workstream/operator-fault-source/$REVIEWED_COMMIT" /usr/bin/python3 -m experiments.pilot04_external_checker_runtime.public_node_faults --node-config /etc/workstream/checker-service.json --unit workstream-checker.service --root "/var/lib/workstream-operator/pre-launch-$RUN_ID" --owner-manifest "/var/lib/workstream-operator/pre-launch-$RUN_ID-custody.json" --hosted-runtime --run-id "$RUN_ID" --maximum-seconds 900 --image-digest sha256:b4d1877fabfeacb24c6830469d1d1f057eacb64daecea7b5328f08431fc65721 +sudo -n systemd-run --unit="workstream-operator-pre-launch-$RUN_ID" --property=Type=exec --property=RuntimeMaxSec=1200 --property=TimeoutStopSec=90 --property=KillSignal=SIGTERM --property=KillMode=process --property=SendSIGKILL=no /usr/bin/env "PYTHONPATH=/opt/workstream/operator-fault-source/$REVIEWED_COMMIT" /usr/bin/python3 -m experiments.pilot04_external_checker_runtime.public_node_faults --node-config /etc/workstream/checker-service.json --unit workstream-checker.service --root "/var/lib/workstream-pre-launch-$RUN_ID" --owner-manifest "/var/lib/workstream-operator/pre-launch-$RUN_ID-custody.json" --hosted-runtime --run-id "$RUN_ID" --maximum-seconds 900 --image-digest sha256:b4d1877fabfeacb24c6830469d1d1f057eacb64daecea7b5328f08431fc65721 ``` The supervisor validates custody, a drained node and exact cached image before diff --git a/experiments/pilot04_external_checker_runtime/public_node_faults.py b/experiments/pilot04_external_checker_runtime/public_node_faults.py index 52c902a69..f108e9b9e 100644 --- a/experiments/pilot04_external_checker_runtime/public_node_faults.py +++ b/experiments/pilot04_external_checker_runtime/public_node_faults.py @@ -69,6 +69,21 @@ def _runtime_user(identity): return {'user': identity[0], 'group': identity[1], 'extra_groups': []} +def _check_hosted_wrapper_execution(wrapper, home): + """Prove checker-UID traversal, settings read and real binary exec before rewrite.""" + probe = subprocess.run( + [str(wrapper), "--version"], + check=True, + capture_output=True, + text=True, + timeout=5, + env={"HOME": home, "PATH": "/usr/bin:/bin"}, + **_runtime_user(HOSTED_IDENTITY), + ) + if not probe.stdout.startswith("smolvm ") or probe.stderr: + raise ValueError("hosted runtime wrapper execution differs") + + def runtime(config, *args, identity=None): smol = config['smol'] return json.loads(subprocess.check_output( @@ -486,6 +501,8 @@ def serve(config_path, root, unit, manifest_path, *, hosted_runtime=False, run_i 'mode': str(state), 'trace': str(trace), 'unit': unit, 'socket': config['socket_path'], }) + if hosted_runtime: + _check_hosted_wrapper_execution(wrapper, config['smol']['home']) changed = json.loads(original) changed['smol']['binary'] = str(wrapper) changed['smol']['binary_sha256'] = 'sha256:' + hashlib.sha256(wrapper.read_bytes()).hexdigest() diff --git a/scripts/test_public_smol_proof.py b/scripts/test_public_smol_proof.py index 1729fac66..a53d27039 100644 --- a/scripts/test_public_smol_proof.py +++ b/scripts/test_public_smol_proof.py @@ -205,6 +205,51 @@ def validate(path, mode, **kwargs): self.assertEqual(os.getuid(), original_getuid()) self.assertEqual(os.getgid(), original_getgid()) + def test_hosted_wrapper_exec_requires_traversable_sibling_parent(self): + """A real user process must read wrapper settings and exec through ancestry.""" + source = ( + ROOT + / "experiments/pilot04_external_checker_runtime/public_runtime_wrapper.py" + ) + binary = self.root / "smol-version" + binary.write_text('#!/bin/sh\nprintf "smolvm 1.31.4\\n"\n') + binary.chmod(0o700) + + def prepare(parent): + runtime = parent / "workstream-pre-launch-fault-runtime" + runtime.mkdir(mode=0o700) + wrapper = runtime / "runtime-wrapper" + wrapper.write_bytes(source.read_bytes()) + wrapper.chmod(0o700) + wrapper.with_suffix(".json").write_text( + json.dumps( + { + "binary": str(binary), + "project_archive": "/unused", + "mode": "/unused", + "trace": "/unused", + "unit": "unused", + "socket": "/unused", + } + ) + ) + return wrapper + + old_parent = self.root / "operator-private" + old_parent.mkdir(mode=0o700) + new_wrapper = prepare(self.root) + old_wrapper = prepare(old_parent) + with patch.object(faults, "_runtime_user", return_value={}): + self.assertIsNone( + faults._check_hosted_wrapper_execution(new_wrapper, str(self.root)) + ) + old_parent.chmod(0o000) + try: + with self.assertRaises((OSError, subprocess.CalledProcessError)): + faults._check_hosted_wrapper_execution(old_wrapper, str(self.root)) + finally: + old_parent.chmod(0o700) + def test_launch_trace_rejects_extra_execution_and_reset_deadline(self): trace = self.root / 'runtime-trace.jsonl' lease = {'epoch': 'original', 'expires_ms': 1000} From 527e7ab5ab17af9a3ff0d2129434be81c3ecdee3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:05:57 +0100 Subject: [PATCH 323/513] Match active-guide assertion to required selected POST policy --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 4 ++++ backend/tests/test_projects.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 4c221a6db..092287509 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10410,3 +10410,7 @@ the unchanged exact sibling-binding control pass. Pinned read-only runner checks also showed UID10001 can traverse `/var/lib` and execute original Smol. The new run path and preflight remain to be staged and exercised; pre1 is still failed evidence, not an injected-launch proof. + +### Active-guide exact selected POST assertion + +Cloud project_lifecycle_g at merge5bc9a104 (PR877c06c81) ran525 cases:524 passed, one active-guide test expected an empty required POST list although its approved canonical bundle now selects acme.safe_archive under mandatory single-image cardinality. Isolated schema0091 database/MinIO cleanup completed. Bounded low-risk fixture correction: backend/tests/test_projects.py plus this record; require the exact selected POST checker supplied by the approved canonical bundle, retaining every other response/authority assertion. No production/cardinality/fixture mutation. Root review; one real PostgreSQL case after native pre2 releases the shared slot. Do not credit that replay before execution. diff --git a/backend/tests/test_projects.py b/backend/tests/test_projects.py index 7dcdbee6b..be4574c97 100644 --- a/backend/tests/test_projects.py +++ b/backend/tests/test_projects.py @@ -5160,7 +5160,7 @@ async def test_active_guide_retrieval_returns_exact_policy_bundle(project_client assert active.json()["guide"]["effective_at"] is not None assert activation["guide"]["approved_by"] == guide["created_by"] assert datetime.fromisoformat(activation["guide"]["effective_at"]) == datetime.fromisoformat(active.json()["guide"]["effective_at"]) - assert active.json()["post_submit_checker_policy"]["required_checkers"] == [] + assert active.json()["post_submit_checker_policy"]["required_checkers"] == ["acme.safe_archive"] assert ( active.json()["guide_source_snapshot"]["bundle_hash"] == (bundle["source_snapshot"]["bundle_hash"]) From 989c6d0b65fc4f7d2f0c1723e87503c4fb891311 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:13:44 +0100 Subject: [PATCH 324/513] Record exact PRE fault configuration identity refusal --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 092287509..22837c350 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10414,3 +10414,9 @@ evidence, not an injected-launch proof. ### Active-guide exact selected POST assertion Cloud project_lifecycle_g at merge5bc9a104 (PR877c06c81) ran525 cases:524 passed, one active-guide test expected an empty required POST list although its approved canonical bundle now selects acme.safe_archive under mandatory single-image cardinality. Isolated schema0091 database/MinIO cleanup completed. Bounded low-risk fixture correction: backend/tests/test_projects.py plus this record; require the exact selected POST checker supplied by the approved canonical bundle, retaining every other response/authority assertion. No production/cardinality/fixture mutation. Root review; one real PostgreSQL case after native pre2 releases the shared slot. Do not credit that replay before execution. + +### Second native fault run and exact PRE refusal diagnosis + +Pre2 at integrated9e8ab8130 used direct /var/lib private sibling roots; actual checker UID wrapper --version preflight passed and supervisor PID13136 reached ready. Its public request returned503 before native creation; exact trace has zero events. Isolated database/MinIO cleanup completed. Root restored the exact supervisor18e8adc0-48ae-406e-8f7e-edcb80e345bc once. `/tmp/submission-runner-pre2-restoration.json` confirms original config hash, empty owned machine/lease/disk/cgroup sets and foreign fixture removal. This is not passing failure/recovery evidence. + +Read-only service journal at18:10:44 reports `PRE request rejected: PRE configured identity differs` (`/tmp/submission-pre2-runner-journal.log`). Rust PRE admission compares its configured Smol digest with runtime.binary_sha256. The temporary fault harness replaces the runtime digest with the verified wrapper digest but leaves the PRE copy at the original executable. Repair the temporary config pins consistently, retain the production identity guard, and restore exact original bytes. The earlier traversal defect was real but was not the sole pre-launch blocker. A discriminating config-consistency check and focused review must precede another native attempt. From a3d6178dc91303cfe8cc1deb4573adeb9dfd8a87 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:19:20 +0100 Subject: [PATCH 325/513] Retire superseded revision-fence probe with retained race coverage --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 4 +++ .../accepted_revision_probes.py | 25 ------------------- backend/tests/test_tasks.py | 25 ------------------- 3 files changed, 4 insertions(+), 50 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 22837c350..676d423a9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10420,3 +10420,7 @@ Cloud project_lifecycle_g at merge5bc9a104 (PR877c06c81) ran525 cases:524 passed Pre2 at integrated9e8ab8130 used direct /var/lib private sibling roots; actual checker UID wrapper --version preflight passed and supervisor PID13136 reached ready. Its public request returned503 before native creation; exact trace has zero events. Isolated database/MinIO cleanup completed. Root restored the exact supervisor18e8adc0-48ae-406e-8f7e-edcb80e345bc once. `/tmp/submission-runner-pre2-restoration.json` confirms original config hash, empty owned machine/lease/disk/cgroup sets and foreign fixture removal. This is not passing failure/recovery evidence. Read-only service journal at18:10:44 reports `PRE request rejected: PRE configured identity differs` (`/tmp/submission-pre2-runner-journal.log`). Rust PRE admission compares its configured Smol digest with runtime.binary_sha256. The temporary fault harness replaces the runtime digest with the verified wrapper digest but leaves the PRE copy at the original executable. Repair the temporary config pins consistently, retain the production identity guard, and restore exact original bytes. The earlier traversal defect was real but was not the sole pre-launch blocker. A discriminating config-consistency check and focused review must precede another native attempt. + +### Retire impossible duplicate revision-fence probe + +TASK E cloud failure occurs because the obsolete test reserves a new checker generation after T4 has already staged finalization_pending. The current TASK owner correctly refuses it. Scoped ARCH/SEC review identifies two existing stronger real-PostgreSQL tests in test_submission_predecessor_custody.py: test_dispatch_commit_requires_current_predecessor_checker_fence advances the fence before T4 and verifies real deferred23514/rollback plus positiveT5; test_replacement_holds_task_custody_against_successor_generation verifies acceptedT4 denies a waiting successor while retaining predecessor fence. Retire only the impossible duplicate test in test_tasks.py and its sole-use stale_fence_before_acceptance_commit helper; no replacement behavior or product change. Preserve both named current tests and replay them after the shared slot is free. Refresh only mechanically affected shrinking structural debt metadata with reviewed diff; no gate/policy change. Human review focus is that both distinct race orderings remain covered by real owners and SQL. diff --git a/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py b/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py index fb816f18e..e95202949 100644 --- a/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py +++ b/backend/tests/tasks/submission_dispatch/accepted_revision_probes.py @@ -75,31 +75,6 @@ async def add(repository, submission): assert len(observed) == 1 -@contextmanager -def stale_fence_before_acceptance_commit(): - """Reserve a legitimate successor after T4 staging, before deferred SQL checks.""" - from app.adapters.checkers import evaluation_coordinator - from app.modules.artifacts.intake.foreground_admission import ForegroundIntakeAdmission - from tests.checkers.execution.storage_fixture import storage_request - - original = ForegroundIntakeAdmission._accept_new - observed = [] - - async def accept(admission, session, authority, repository, row, owner, - request, terminal_digest, checkers, outbox): - receipt = await original(admission, session, authority, repository, row, owner, - request, terminal_digest, checkers, outbox) - predecessor = row.accepted_context["predecessor_submission_id"] - assert predecessor is not None and row.state == "finalization_pending" - successor = await storage_request(session, predecessor, generation=2) - reserved = await evaluation_coordinator(session).reserve_current_evaluation(successor) - assert reserved.request_id == successor.evaluation_request_id - observed.append(row.id) - return receipt - - with patch.object(ForegroundIntakeAdmission, "_accept_new", accept): - yield observed - assert len(observed) == 1 async def revision_target_snapshot(factory, task_id): diff --git a/backend/tests/test_tasks.py b/backend/tests/test_tasks.py index 9d17511fc..a206ce333 100644 --- a/backend/tests/test_tasks.py +++ b/backend/tests/test_tasks.py @@ -2537,31 +2537,6 @@ async def test_retained_submission_versions_are_readable_without_exposing_packet assert denied.status_code == 404 -async def test_revision_acceptance_rejects_checker_fence_changed_before_commit(task_client, monkeypatch): - from app.modules.artifacts.intake.repository import IntakeCustodyConflict - from tests.tasks.submission_dispatch.accepted_revision_probes import stale_fence_before_acceptance_commit - - project = await create_active_project(task_client, post_submit_registry_spec=post_registry_spec()) - task = await create_started_task(task_client, project["id"], monkeypatch) - first = await seed_retained_submission(task["id"], complete_submission_payload()) - await route_retained_checker_remediation(first) - set_dev_actor(monkeypatch, roles="worker", subject="worker-one") - with stale_fence_before_acceptance_commit(): - with pytest.raises(IntakeCustodyConflict) as error: - await seed_retained_submission(task["id"], complete_submission_payload(), predecessor_id=first) - assert "revision acceptance is no longer eligible" in str(error.value.__cause__) - async with db_session.get_session_factory()() as session: - assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": task["id"]}) == 1 - assert await session.scalar(text("SELECT count(*) FROM submission_bundle_admissions WHERE task_id=:id"), {"id": task["id"]}) == 1 - row = (await session.execute(text(""" - SELECT state, acceptance_receipt, finalization_event_id FROM submission_intake_operations - WHERE task_id=:id AND command_metadata->>'predecessor_submission_id' IS NOT NULL - """), {"id": task["id"]})).one() - assert row.state == "failed" and row.acceptance_receipt is None and row.finalization_event_id is None - assert await session.scalar(text(""" - SELECT count(*) FROM outbox_events - WHERE event_type='SubmissionFinalizationRequested' AND payload->>'task_id'=:id - """), {"id": task["id"]}) == 1 async def test_retained_submission_history_preserves_locked_guide_after_activation( From b423cc2b88850304e3897eef236ece5ac2a0ab48 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:20:01 +0100 Subject: [PATCH 326/513] test(checkers): provision trial custody services and control reconciliation execution --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 31 +++++++++++++++++++ .../test_delivery_reconciliation_public.py | 11 +++++-- .../external/test_trial_artifact_custody.py | 4 +++ .../external/test_trial_model_custody.py | 2 ++ 4 files changed, 46 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 676d423a9..2f243e715 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10424,3 +10424,34 @@ Read-only service journal at18:10:44 reports `PRE request rejected: PRE configur ### Retire impossible duplicate revision-fence probe TASK E cloud failure occurs because the obsolete test reserves a new checker generation after T4 has already staged finalization_pending. The current TASK owner correctly refuses it. Scoped ARCH/SEC review identifies two existing stronger real-PostgreSQL tests in test_submission_predecessor_custody.py: test_dispatch_commit_requires_current_predecessor_checker_fence advances the fence before T4 and verifies real deferred23514/rollback plus positiveT5; test_replacement_holds_task_custody_against_successor_generation verifies acceptedT4 denies a waiting successor while retaining predecessor fence. Retire only the impossible duplicate test in test_tasks.py and its sole-use stale_fence_before_acceptance_commit helper; no replacement behavior or product change. Preserve both named current tests and replay them after the shared slot is free. Refresh only mechanically affected shrinking structural debt metadata with reviewed diff; no gate/policy change. Human review focus is that both distinct race orderings remain covered by real owners and SQL. + +### Cloud project lifecycle C fixture repair + +The cloud `project_lifecycle_c` lane at the integrated submission head reported +four failures. Three trial custody journeys reach ART materialization without +the `ARTIFACT_PUT_RESOLVER` and `ARTIFACT_VERIFIER` fixed service actors used +by the existing checker-output storage owner, so authorization stops before +trial publication. The public operator reconciliation request test +creates its child production handler with the default remote checker adapter +while its fixture has no runner endpoint, so acknowledged delivery records an +`infrastructure_failed` checker run. This bounded change may adjust only the +three trial setup calls and that operator test's selected execution factory. +It must retain the real ART, CHECKERS, AUTH, OUTBOX and SQL owner operations, +the trial/model behavior, and the public operator reconciliation authority. +The selected POST adapter may be controlled only for the child delivery, as +the existing `delivery_fixture` controls the original request. No production, +schema, runtime profile, or test expectation may be relaxed. Focused +PostgreSQL cases were deferred until the concurrent native PRE proof released +the local heavy test slot. The first isolated four-case replay reached the +next missing `ARTIFACT_VERIFIER` identity in all three trial cases, while the +operator child completed; its PostgreSQL and MinIO cleanup both completed +(`/tmp/submission-project-lifecycle-c-fixture.log/.json`). After provisioning +the exact two identities composed by `checker_output_storage`, the two trial +publication race variants, trial byte custody and trial/model receipt custody +all passed (4 in 107.48 seconds, schema 0091, PostgreSQL and MinIO cleanup +true; `/tmp/submission-project-lifecycle-trials-v2.log/.json`). These are +isolated worktree receipts whose metadata names the pre-commit base, not a +claim of exact committed-head execution. They retain the real publication, +verification, binding, model proxy and selected POST owner paths; no native +runner qualification follows from the controlled selected response in the +operator reconciliation case. diff --git a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py index 509f67c50..b27781421 100644 --- a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py +++ b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py @@ -34,6 +34,7 @@ live_acceptance_lifecycle as live_acceptance_lifecycle, ) from tests.tasks.evaluation_delivery.support import delivery_fixture, invoked, outcome, state +from tests.checkers.execution.support import ControlledSelectedExecution from tests.tasks.post_submit_routing.outcome_support import ( apply_outcome, authorized_routing_source, @@ -413,8 +414,8 @@ async def test_public_operator_retries_proven_no_effect_request_once( settings = h.settings.model_copy( update={ - "external_checker_service_socket": None, - "external_checker_material_root": None, + "external_runner_host": None, + "external_runner_port": None, } ) monkeypatch.setattr("app.core.config.get_settings", lambda: settings) @@ -423,11 +424,17 @@ async def test_public_operator_retries_proven_no_effect_request_once( "worker_post_submission_materialization", lambda *, sessions: h.service, ) + selected = ControlledSelectedExecution() + monkeypatch.setattr( + "app.adapters.checkers.configured_post_submit_external_execution", + lambda settings, *, sessions: selected, + ) child_id = UUID(result["successor"]["event_id"]) delivered = await production_outbox_delivery(h.factory).deliver( child_id, h.request.project_id, "reconcile-request" ) assert outcome(delivered)["delivery_state"] == "acknowledged" + assert len(selected.requests) == 1 completed = await state(h) assert completed["run"]["status"] == "completed" assert completed["events"] == 1 diff --git a/backend/tests/checkers/external/test_trial_artifact_custody.py b/backend/tests/checkers/external/test_trial_artifact_custody.py index c6d6b38c8..69f20df05 100644 --- a/backend/tests/checkers/external/test_trial_artifact_custody.py +++ b/backend/tests/checkers/external/test_trial_artifact_custody.py @@ -163,6 +163,8 @@ async def test_trial_bytes_use_real_art_custody_and_recover_exact_original( ) as h: catalog = catalog_for(h.request) await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_CHECKER_OUTPUT) + await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_PUT_RESOLVER) + await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_VERIFIER) await reserve(h) h.service = DiagnosticMaterialization(h.service) adapter = PublishingExecution(h, catalog, projected) @@ -332,6 +334,8 @@ async def test_competing_trial_publication_observes_pin_commit_or_complete_rollb ) as h: catalog = catalog_for(h.request) await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_CHECKER_OUTPUT) + await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_PUT_RESOLVER) + await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_VERIFIER) await reserve(h) h.service = DiagnosticMaterialization(h.service) adapter = CompetingPublication(h, catalog, projected, rollback) diff --git a/backend/tests/checkers/external/test_trial_model_custody.py b/backend/tests/checkers/external/test_trial_model_custody.py index 1356f0e03..81fc9bf7a 100644 --- a/backend/tests/checkers/external/test_trial_model_custody.py +++ b/backend/tests/checkers/external/test_trial_model_custody.py @@ -231,6 +231,8 @@ async def parameters(_factory, project_id, registry): ) as h: catalog = catalog_for(h.request) await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_CHECKER_OUTPUT) + await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_PUT_RESOLVER) + await provision_post_submit_service(h.factory, ServiceIdentity.ARTIFACT_VERIFIER) h.service = DiagnosticMaterialization(h.service) creates = [] stages: list[tuple[str, float]] = [] From 478916fe60d9dcbd8c01e70e64ca9e0bf2a429e6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:18:20 +0100 Subject: [PATCH 327/513] Bind selected POST materialization evidence to the locked member --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 +++++++++++++++++++ .../external/test_selected_post_submit.py | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 2f243e715..a61556c67 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10455,3 +10455,27 @@ claim of exact committed-head execution. They retain the real publication, verification, binding, model proxy and selected POST owner paths; no native runner qualification follows from the controlled selected response in the operator reconciliation case. + +### Match the selected POST materialization oracle to current approval + +Intent: project_lifecycle_d artifact14949234050 from the same PR run records +1failure/480passes, schema0091 and complete cleanup. Only + test_selected_post_materializes_actual_submission_and_replays fails: the current +material fixture has one required registered POST, while the oracle expects no +external members. Correct that assertion only in test_selected_post_submit.py +and this record. Require the exact one-member order/requirement, pinned locked +registry ID/digest and completed/passed phase, preserving original result identity, +replay equality and exactly-one provider read assertions. No production, fixture, +policy, timer or file-line growth. Pure exact-oracle discrimination and static +gates now; root owns B/D/G PostgreSQL batch after C/F and native ownership finish. + +The replacement binds exactly order0/project.post_evidence to the locked request's +registry ID/digest and post_submit/completed/passed result. The old empty oracle +fails on the real registry_entry fixture; the new assertion accepts that control +and rejects9member-count/order/identity/result substitutions +(/tmp/submission-project-d-oracle-probe.log/.json). Every other AST and all1084 +file lines are unchanged; replay equality and provider read count remain intact. +Ruff/diff/Commitrail pass. The combined structural check separately exposes the +B/G edits' stale frozen test_projects file hash; this D module introduces no +structural change. That debt must shrink through honest behavior relocation, +not a hash-only rebaseline. Actual D PostgreSQL replay remains root-batched. diff --git a/backend/tests/checkers/external/test_selected_post_submit.py b/backend/tests/checkers/external/test_selected_post_submit.py index b09160d09..03aa8e4c8 100644 --- a/backend/tests/checkers/external/test_selected_post_submit.py +++ b/backend/tests/checkers/external/test_selected_post_submit.py @@ -339,7 +339,7 @@ async def test_selected_post_materializes_actual_submission_and_replays( assert result.outcome == "completed" assert result.attempt_id == reservation.attempt_id assert result.execution is not None - assert result.execution.external_members == () + assert [(m.order, m.requirement_id, m.registry_entry_id, m.registry_entry_digest, m.result.phase, m.result.outcome, m.result.verdict) for m in result.execution.external_members] == [(0, "project.post_evidence", h.request.policy.entries[0].registry.registry_entry_id, h.request.policy.entries[0].registry.entry_digest, "post_submit", "completed", "passed")] assert await executor.evaluate_post_submission(h.request) == result assert len(h.store.opens) == 1 From 78d0c71ddd17c69db8684e3686f93ea364253ad4 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:22:34 +0100 Subject: [PATCH 328/513] Verify retained public revision race and rollback coverage --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a61556c67..caa5149bc 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10479,3 +10479,5 @@ Ruff/diff/Commitrail pass. The combined structural check separately exposes the B/G edits' stale frozen test_projects file hash; this D module introduces no structural change. That debt must shrink through honest behavior relocation, not a hash-only rebaseline. Actual D PostgreSQL replay remains root-batched. + +Retained revision-race replay passed all3 cases in96.24s at a3d6178dc, schema0091: both variants of test_dispatch_commit_requires_current_predecessor_checker_fence plus test_replacement_holds_task_custody_against_successor_generation. `/tmp/submission-retained-revision-races.log` and `.json` confirm complete isolated database cleanup. This verifies the preserved stronger SQL/race coverage after retiring the impossible duplicate. No constraints, product guards or time budgets changed. From 2d0f494444bd05f7412c00ae242653b723698722 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:19:21 +0100 Subject: [PATCH 329/513] Bind temporary PRE fault binary pin and retain first response --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 29 ++++++++++++ cli/tests/journey/pre_launch_fault.py | 12 ++++- .../public_node_faults.py | 26 +++++++++-- .../public_runtime_trials.py | 17 +++++-- scripts/test_public_hosted_attachment.py | 45 +++++++++++++++++-- scripts/test_public_smol_proof.py | 26 ++++++++++- 6 files changed, 142 insertions(+), 13 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index caa5149bc..a8ea00caf 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10481,3 +10481,32 @@ structural change. That debt must shrink through honest behavior relocation, not a hash-only rebaseline. Actual D PostgreSQL replay remains root-batched. Retained revision-race replay passed all3 cases in96.24s at a3d6178dc, schema0091: both variants of test_dispatch_commit_requires_current_predecessor_checker_fence plus test_replacement_holds_task_custody_against_successor_generation. `/tmp/submission-retained-revision-races.log` and `.json` confirm complete isolated database cleanup. This verifies the preserved stronger SQL/race coverage after retiring the impossible duplicate. No constraints, product guards or time budgets changed. + +The next isolated pre2 trial used clean `9e8ab8130a73a1c86566908c09f8528bc2ed645d` +and the staged `18e8adc0-48ae-406e-8f7e-edcb80e345bc` supervisor. The real +checker-UID wrapper preflight and public guide/task claim passed, but the public +request returned infrastructure 503 before any native create. The unchanged +launch-count assertion failed; the read-only runner snapshot recorded zero +runtime events and drained owned resources. The isolated database and MinIO +bucket cleaned successfully. The runner journal identified the exact refusal: +PRE configured binary identity differed because the temporary fault config +changed `smol.binary_sha256` to the wrapper digest but retained the original +`pre.smol_binary_sha256`. This is failed fixture evidence, not the required +injected native launch proof. + +The narrow fixture repair requires an existing PRE binary pin to match the +original Smol pin, then sets both temporary pins to the exact wrapper digest. +That original-pin check runs before creating fault controls or foreign node +resources, and a negative fixture confirms rejection leaves both absent. +The original config bytes remain available for the existing restore. A config +without PRE retains its older POST-only fault path. A focused test checks both +new pins, old-pin mismatch refusal, unchanged unrelated fields and the legacy +path. The next attempt also stores the first public failure and selected PRE +terminal in a private local receipt before the native count assertion, so an +early refusal cannot disappear with isolated database cleanup. The evidence +directory is made owner-private before this write. The existing busy-node +fixture now includes a valid Smol pin so it still reaches the busy-resource +guard. Focused supervisor and hosted attachment tests pass +`54 passed, 77 subtests passed`; changed-file Ruff +and `git diff --check` pass. A real third trial and supervisor restoration are +still required before any native launch-failure qualification claim. diff --git a/cli/tests/journey/pre_launch_fault.py b/cli/tests/journey/pre_launch_fault.py index 503830cdf..cb61b9e1d 100644 --- a/cli/tests/journey/pre_launch_fault.py +++ b/cli/tests/journey/pre_launch_fault.py @@ -83,6 +83,7 @@ async def _run( profile: RunnerFaultProfile, stop_worker, start_worker, + first_response_path: Path, ): root = Path(__file__).resolve().parents[3] sys.path.insert(0, str(root / "backend" / "tests")) @@ -119,6 +120,7 @@ async def _run( runner=RunnerFaults(profile), stop_worker=stop_worker, start_worker=start_worker, + first_response_path=first_response_path, ) finally: await engine.dispose() @@ -136,6 +138,13 @@ def run_pre_launch_fault( ) -> None: """Keep remote evidence private; report only the bounded case completion.""" archive = _package(client, "correct").read_bytes() + evidence = Path(os.environ["WORKSTREAM_CLI_JOURNEY_EVIDENCE"]) + if not evidence.is_absolute() or evidence.is_symlink(): + raise RuntimeError("fault evidence directory differs") + evidence.mkdir(mode=0o700, parents=True, exist_ok=True) + if not stat.S_ISDIR(evidence.lstat().st_mode) or evidence.stat().st_uid != os.getuid(): + raise RuntimeError("fault evidence directory owner differs") + evidence.chmod(0o700) result = asyncio.run( _run( origin, @@ -146,10 +155,9 @@ def run_pre_launch_fault( archive, profile, *controls, + evidence / "remote-pre-launch-first-response.json", ) ) - evidence = Path(os.environ["WORKSTREAM_CLI_JOURNEY_EVIDENCE"]) - evidence.mkdir(mode=0o700, parents=True, exist_ok=True) path = evidence / "remote-pre-launch-fault.json" with path.open("x", encoding="utf-8") as stream: path.chmod(0o600) diff --git a/experiments/pilot04_external_checker_runtime/public_node_faults.py b/experiments/pilot04_external_checker_runtime/public_node_faults.py index f108e9b9e..87e69a6a6 100644 --- a/experiments/pilot04_external_checker_runtime/public_node_faults.py +++ b/experiments/pilot04_external_checker_runtime/public_node_faults.py @@ -84,6 +84,27 @@ def _check_hosted_wrapper_execution(wrapper, home): raise ValueError("hosted runtime wrapper execution differs") +def _require_pre_runtime_binary_pins(config): + smol, pre = config.get('smol'), config.get('pre') + if (type(smol) is not dict or (pre is not None and + (type(pre) is not dict or type(smol.get('binary_sha256')) is not str + or pre.get('smol_binary_sha256') != smol['binary_sha256']))): + raise ValueError('PRE and runtime binary pins differ before fault setup') + + +def _bound_wrapper_config(original, wrapper): + """Keep the temporary PRE pin aligned with the verified wrapper binary.""" + changed = json.loads(original) + _require_pre_runtime_binary_pins(changed) + smol, pre = changed['smol'], changed.get('pre') + digest = 'sha256:' + hashlib.sha256(wrapper.read_bytes()).hexdigest() + smol['binary'] = str(wrapper) + smol['binary_sha256'] = digest + if pre is not None: + pre['smol_binary_sha256'] = digest + return changed + + def runtime(config, *args, identity=None): smol = config['smol'] return json.loads(subprocess.check_output( @@ -463,6 +484,7 @@ def serve(config_path, root, unit, manifest_path, *, hosted_runtime=False, run_i raise ValueError('fault image cache selection is absent or ambiguous') project = matching[0] binding = validate_node(config_path, config, unit, manifest_path, hosted_runtime=hosted_runtime) + _require_pre_runtime_binary_pins(config) identity = HOSTED_IDENTITY if hosted_runtime else None if any(owned_resources(config, identity=identity).values()): raise RuntimeError('node must be drained') @@ -503,9 +525,7 @@ def serve(config_path, root, unit, manifest_path, *, hosted_runtime=False, run_i }) if hosted_runtime: _check_hosted_wrapper_execution(wrapper, config['smol']['home']) - changed = json.loads(original) - changed['smol']['binary'] = str(wrapper) - changed['smol']['binary_sha256'] = 'sha256:' + hashlib.sha256(wrapper.read_bytes()).hexdigest() + changed = _bound_wrapper_config(original, wrapper) def restart(): subprocess.run(['sudo', 'systemctl', 'restart', unit], check=True, timeout=30) diff --git a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py index 3f99309ec..96eccc9f7 100644 --- a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py @@ -111,17 +111,19 @@ async def _runner_drained(runner): async def public_pre_launch_failure(client, factory, *, task, assignment, token, archive, - runner: RunnerFaults, stop_worker, start_worker): + runner: RunnerFaults, stop_worker, start_worker, + first_response_path: Path | None = None): """Pause/restore only the isolated fixture's owned general POST consumer.""" try: stop_worker() return await _remote_pre_launch_failure(client, factory, task=task, assignment=assignment, - token=token, archive=archive, runner=runner) + token=token, archive=archive, runner=runner, first_response_path=first_response_path) finally: await start_worker() -async def _remote_pre_launch_failure(client, factory, *, task, assignment, token, archive, runner): +async def _remote_pre_launch_failure(client, factory, *, task, assignment, token, archive, runner, + first_response_path=None): """One remote launch fault on an already approved/claimed current public task. The actual locked-image-compatible ZIP is supplied by the caller. The general @@ -143,9 +145,16 @@ async def _remote_pre_launch_failure(client, factory, *, task, assignment, token failed_cleanup = await _runner_drained(runner) failed_trace = await runner.snapshot() records = failed_trace['events'][before['cursor']:] + row = await _selected(factory, key) + if first_response_path is not None: + with first_response_path.open('x', encoding='utf-8') as stream: + first_response_path.chmod(0o600) + json.dump({'public_failure': failure, 'selected_pre': {'id': str(row.id), + 'status': row.status, 'terminal_digest': row.terminal_digest, + 'terminal': row.terminal_json}, 'runtime_event_count': len(records)}, + stream, default=str, sort_keys=True) machines = assert_trace_launches(records, creates=1, executions=0) assert_trace_launches(records, creates=0, executions=0, project=False) - row = await _selected(factory, key) _require(row.status == 'infrastructure_failed' and row.terminal_json['execution'] is None and row.terminal_json['infrastructure_failure_code'] == 'implementation_unavailable' and row.request_json['policy']['entries'][0]['registry']['image_digest'] == runner.profile.image_digest, diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 4dbb6668c..51db5453a 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -973,6 +973,28 @@ async def exercise(): await client.snapshot() asyncio.run(exercise()) + def test_mismatched_pre_pin_refuses_before_fault_setup(self): + from experiments.pilot04_external_checker_runtime import public_node_faults as owner + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + config = directory / 'node.json' + original = json.dumps({'smol': {'binary_sha256': 'sha256:' + 'a' * 64}, + 'pre': {'smol_binary_sha256': 'sha256:' + 'b' * 64}, + 'cache': [{'platform_manifest_digest': 'sha256:' + 'c' * 64}]}).encode() + config.write_bytes(original) + control_root = directory / 'control' + with patch.object(owner, 'validate_node', return_value={'verified': True}), \ + patch.object(owner, 'owned_resources') as resources, \ + patch.object(owner, 'ForeignControl') as foreign: + with self.assertRaisesRegex(ValueError, 'pins differ before fault setup'): + owner.serve(config, control_root, 'owned-unit', directory / 'manifest', + run_id=str(uuid4()), maximum_seconds=1, + image_digest='sha256:' + 'c' * 64) + self.assertFalse(control_root.exists()) + self.assertEqual(config.read_bytes(), original) + resources.assert_not_called() + foreign.assert_not_called() + def test_finite_supervisor_and_hup_restore_only_owned_config(self): from experiments.pilot04_external_checker_runtime import public_node_faults as owner import signal @@ -1101,7 +1123,8 @@ async def exercise(): class RemotePreLaunchContracts(unittest.TestCase): - def exercise(self, *, omit_delete=False, replay_allocates=False, wrong_image=False, unknown=False): + def exercise(self, *, omit_delete=False, replay_allocates=False, wrong_image=False, + unknown=False, missing_create=False, first_response_path=None): from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime from experiments.pilot04_external_checker_runtime.public_runner_faults import FaultOutcomeUnknown @@ -1110,7 +1133,8 @@ def events(name, operations): lease = {'name': name, 'epoch': 'epoch', 'expires_ms': 100, 'lifetime_ms': 10} return [{'operation': operation, 'name': name, 'project': True, 'lease': lease} for operation in operations] - failed = events('failed-vm', ['create', 'start'] + ([] if omit_delete else ['delete'])) + failed = ([] if missing_create else events('failed-vm', + ['create', 'start'] + ([] if omit_delete else ['delete']))) replay = failed + (events('unexpected', ['create']) if replay_allocates else []) recovered = replay + events('recovered-vm', ['create', 'start', 'exec', 'delete']) traces = [{'cursor': len(records), 'events': records} @@ -1150,7 +1174,8 @@ async def snapshot(self): try: result = asyncio.run(runtime.public_pre_launch_failure(None, None, task='task', assignment='assignment', token='private-token', archive=b'actual-zip', runner=Runner(), - stop_worker=lambda: worker_events.append('stop'), start_worker=resume)) + stop_worker=lambda: worker_events.append('stop'), start_worker=resume, + first_response_path=first_response_path)) finally: self.assertEqual(worker_events, ['stop', 'start']) self.assertEqual([call.args[-1] for call in source.await_args_list], [503, 503, 202]) @@ -1173,6 +1198,20 @@ def test_remote_first_pre_preserves_known_failure_replay_and_real_t5_observer(se with self.subTest(fault=fault), self.assertRaisesRegex(RuntimeError, message): self.exercise(**{fault: True}) + def test_first_response_is_retained_before_native_count_refusal(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'first-response.json' + with self.assertRaisesRegex(RuntimeError, 'expected fresh machines'): + self.exercise(missing_create=True, first_response_path=path) + body = json.loads(path.read_text()) + self.assertEqual(body['public_failure']['error']['code'], + 'submission_infrastructure_unavailable') + self.assertEqual(body['selected_pre']['status'], 'infrastructure_failed') + self.assertEqual(body['selected_pre']['terminal']['infrastructure_failure_code'], + 'implementation_unavailable') + self.assertEqual(body['runtime_event_count'], 0) + self.assertEqual(path.stat().st_mode & 0o777, 0o600) + def test_partial_owned_worker_pause_failure_still_restores_worker(self): from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime def failed_pause(): diff --git a/scripts/test_public_smol_proof.py b/scripts/test_public_smol_proof.py index a53d27039..f4276f002 100644 --- a/scripts/test_public_smol_proof.py +++ b/scripts/test_public_smol_proof.py @@ -250,6 +250,29 @@ def prepare(parent): finally: old_parent.chmod(0o700) + def test_fault_wrapper_rebinds_exact_runtime_and_pre_binary_pins(self): + wrapper = self.root / 'runtime-wrapper' + wrapper.write_bytes(b'qualified temporary wrapper') + old_digest = 'sha256:' + 'a' * 64 + original = {'smol': {'binary': '/qualified/smolvm', 'binary_sha256': old_digest}, + 'pre': {'smol_binary_sha256': old_digest, 'platform_root_sha256': 'root-pin'}, + 'unrelated': {'retained': True}} + encoded = json.dumps(original).encode() + changed = faults._bound_wrapper_config(encoded, wrapper) + self.assertEqual(changed['smol']['binary'], str(wrapper)) + self.assertEqual(changed['smol']['binary_sha256'], digest(wrapper)) + self.assertEqual(changed['pre']['smol_binary_sha256'], digest(wrapper)) + self.assertEqual(changed['pre']['platform_root_sha256'], 'root-pin') + self.assertEqual(changed['unrelated'], original['unrelated']) + self.assertEqual(json.loads(encoded), original) + original['pre']['smol_binary_sha256'] = 'sha256:' + 'b' * 64 + with self.assertRaisesRegex(ValueError, 'pins differ'): + faults._bound_wrapper_config(json.dumps(original).encode(), wrapper) + del original['pre'] + legacy = faults._bound_wrapper_config(json.dumps(original).encode(), wrapper) + self.assertNotIn('pre', legacy) + self.assertEqual(legacy['smol']['binary_sha256'], digest(wrapper)) + def test_launch_trace_rejects_extra_execution_and_reset_deadline(self): trace = self.root / 'runtime-trace.jsonl' lease = {'epoch': 'original', 'expires_ms': 1000} @@ -310,7 +333,8 @@ def test_foreign_fixture_cleanup_is_exact_and_requires_disk_absence(self): def test_busy_node_refused_before_control_or_config_mutation(self): config_path = self.root / 'service.json' image_digest = 'sha256:' + 'a' * 64 - original = json.dumps({'cache': [{'platform_manifest_digest': image_digest}]}).encode() + original = json.dumps({'smol': {'binary_sha256': 'sha256:' + 'b' * 64}, + 'cache': [{'platform_manifest_digest': image_digest}]}).encode() config_path.write_bytes(original) config_path.chmod(0o600) control_root = self.root / 'control' From 9c489adbed12387fc4cc9b5101ab4176094abceb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:24:04 +0100 Subject: [PATCH 330/513] Format private fault evidence capture with pinned Ruff --- cli/tests/journey/pre_launch_fault.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cli/tests/journey/pre_launch_fault.py b/cli/tests/journey/pre_launch_fault.py index cb61b9e1d..63b630981 100644 --- a/cli/tests/journey/pre_launch_fault.py +++ b/cli/tests/journey/pre_launch_fault.py @@ -142,7 +142,10 @@ def run_pre_launch_fault( if not evidence.is_absolute() or evidence.is_symlink(): raise RuntimeError("fault evidence directory differs") evidence.mkdir(mode=0o700, parents=True, exist_ok=True) - if not stat.S_ISDIR(evidence.lstat().st_mode) or evidence.stat().st_uid != os.getuid(): + if ( + not stat.S_ISDIR(evidence.lstat().st_mode) + or evidence.stat().st_uid != os.getuid() + ): raise RuntimeError("fault evidence directory owner differs") evidence.chmod(0o700) result = asyncio.run( From c897ad192a17b828057bcc69721ad8b478799cc4 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:28:47 +0100 Subject: [PATCH 331/513] Extract selected policy read tests and shrink frozen file debt --- .ci/auth-boundaries/TEST_STRUCTURE_DEBT.json | 14 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 52 +++++ backend/scripts/test_lane_catalogue.py | 1 + .../projects/test_policy_read_postgresql.py | 197 ++++++++++++++++++ backend/tests/test_ci_lane_catalogue.py | 8 +- backend/tests/test_projects.py | 171 --------------- 6 files changed, 261 insertions(+), 182 deletions(-) create mode 100644 backend/tests/projects/test_policy_read_postgresql.py diff --git a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json index eb771f148..b6410468e 100644 --- a/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json +++ b/.ci/auth-boundaries/TEST_STRUCTURE_DEBT.json @@ -98,11 +98,11 @@ }, { "capability": "oversized_authorization_structure", - "content_sha256": "33093fc291a24d0322197f3b42dac903af4c6ffe87ee1c658a8844c9691ee9df", - "end_line": 5492, + "content_sha256": "0f9b01add64fbdccf9ee33414ab65c04d28990a90d21331c7b63c43cdcab438f", + "end_line": 5321, "hard_limit": 1200, "kind": "test_file", - "observed_lines": 5492, + "observed_lines": 5321, "path": "backend/tests/test_projects.py", "qualified_symbol": null, "removal_chunk": "WS-AUTH-003-CLOSE", @@ -363,26 +363,26 @@ { "capability": "oversized_authorization_structure", "content_sha256": "e723bd10cd20ba716fb75edda2a5b0c21a78dfce771efd55154834063c08b4b4", - "end_line": 2215, + "end_line": 2214, "hard_limit": 120, "kind": "test_function", "observed_lines": 128, "path": "backend/tests/test_projects.py", "qualified_symbol": "test_guide_mutation_service_executes_all_three_authorized_happy_paths", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 2088 + "start_line": 2087 }, { "capability": "oversized_authorization_structure", "content_sha256": "a801cae6e9f200073a42b7a2cb94edd614480899288fbe78783ea78fffe859c7", - "end_line": 1039, + "end_line": 1038, "hard_limit": 120, "kind": "test_function", "observed_lines": 137, "path": "backend/tests/test_projects.py", "qualified_symbol": "test_project_role_grant_repository_filters_and_uses_strict_keyset", "removal_chunk": "WS-AUTH-003-CLOSE", - "start_line": 903 + "start_line": 902 }, { "capability": "oversized_authorization_structure", diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a8ea00caf..e1063ad70 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10510,3 +10510,55 @@ guard. Focused supervisor and hosted attachment tests pass `54 passed, 77 subtests passed`; changed-file Ruff and `git diff --check` pass. A real third trial and supervisor restoration are still required before any native launch-failure qualification claim. + +### Shrink policy-read file debt while correcting B/G selected-policy oracles + +Intent: B/G exact one-checker oracle repairs touch frozen test_projects.py file +debt. Equal line count still changes its frozen hash, so a hash-only refresh is +invalid. Move both whole primary tests into a cohesive PostgreSQL policy-read +module, preserving every body/assertion except the reviewed B/G empty-checker +corrections. Reuse existing API client/settings/grant fixtures; no decomposition, +new resolver, compatibility alias or production change. Allowed files are the +legacy test module, new project policy-read test module, exact catalogue and +independent family fingerprint, measured debt ledger and this record. Remove +only imports made unused by the move. Update only the genuinely shrunk FILE debt +and any unchanged-function span shifts caused by removed imports; preserve every +limit, scope, debt owner/removal chunk, policy, validator and assertion map. + +Acceptance: exact decorated/body preservation, identical fixture/global closure, +same total collected tests, exact project-family addition with no module moves, +full unchanged structural validation and adversarial stale/unshrunk checks. +Root owns actual B/D/G PostgreSQL replay after the native/C/F jobs; no duplicate +heavy database run. This combined closure supersedes standalone B94bfd3d48; +G527e7ab5a remains the reviewed current POST policy oracle. + +Both complete tests now live in tests/projects/test_policy_read_postgresql.py +(197lines), with exact decorated/body identity to the reviewed B94/G527 fixes. +The retained legacy module differs only by whole-node removal and its now-unused +validator import; it shrinks5492->5321. Actual inventory changes exactly the FILE +digest/span/count plus two unchanged-function start/end offsets of-1 from that +import removal. Their hashes, sizes, limits, owners and removal chunks are intact; +all other debt entries are untouched. No policy, validator or map changed. + +Focused collection passed248nodes in11.21s, equal to the original CI canonical +project-node count. New paths are test_policy_read_postgresql.py:: + test_submission_artifact_policy_approval_persists_effective_policy_hash and + test_active_guide_retrieval_returns_exact_policy_bundle. Exact19fixture/global +bindings and complete fixture dependency closure were checked without PG setup +(/tmp/submission-policy-read-collection.log/.json); full-body/source comparison is +/tmp/submission-policy-read-preservation.py. New project-family membership is an +exact+1; removing that one module reproduces both prior family and lane-ownership +fingerprints. Existing modules/assignments are unchanged. The initial catalogue +run correctly rejected its unrefreshed independent ownership count; the exact +addition refresh then passed all59tests in2.45s +(/tmp/submission-policy-read-catalogue-final.log). + +Unchanged full structural validation exits0 +(/tmp/submission-policy-read-structure.log). A valid shrink passes the existing +transition check, while simulated hash-only unshrunk metadata fails with +structural_debt_changed_without_shrink. Both exact independent family/ownership +tests reject omission of the new module (/tmp/submission-policy-read-guard-probe +.log/.json). Ruff, whitespace and links pass; Commitrail checked against527. +This is whole-node relocation and real debt reduction; prior PG proof is retained +as inspected custody, with current-path B/D/G replay owned by root. No runtime, +provider, public capability or roadmap completion claim changes. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 07471c74d..42b42caea 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -498,6 +498,7 @@ class TestLane: "tests/projects/test_locked_policy_custody.py", "tests/projects/test_locked_policy_concurrency.py", "tests/projects/test_policy_read_composition.py", + "tests/projects/test_policy_read_postgresql.py", "tests/projects/test_active_guide_read_composition.py", "tests/projects/test_diagnostic_read_composition.py", "tests/projects/test_diagnostic_read_rejections.py", diff --git a/backend/tests/projects/test_policy_read_postgresql.py b/backend/tests/projects/test_policy_read_postgresql.py new file mode 100644 index 000000000..4caeeefbf --- /dev/null +++ b/backend/tests/projects/test_policy_read_postgresql.py @@ -0,0 +1,197 @@ +"""Persisted approval and public policy reads retain exact selected checker custody.""" +from __future__ import annotations + +from datetime import datetime + +from httpx import AsyncClient +from sqlalchemy import select + +from app.db import session as db_session +from app.modules.checkers.api.external_policy import validate_stored_external_pre_policy +from app.modules.projects.models import PreSubmitCheckerPolicy, SubmissionArtifactPolicy +from projects.client_fixtures import ( + auth_headers, + clear_project_settings_cache_after_test as clear_project_settings_cache_after_test, + project_client as project_client, + project_database_env as project_database_env, +) +from projects.guide_fixtures import ( + complete_guide_payload, create_guide, create_project, read_guide_source_snapshot, +) +from projects.policy_bundle_fixtures import create_approved_policy_bundle +from projects.submission_policy_fixtures import approve_submission_artifact_policy, create_sufficiency_report +from tests.projects.guide_activation.read_fixtures import activate_approved_guide + + +async def test_submission_artifact_policy_approval_persists_effective_policy_hash( + project_client: AsyncClient, +) -> None: + project = await create_project(project_client) + guide = await create_guide(project_client, project["id"], complete_guide_payload()) + snapshot = await read_guide_source_snapshot(project["id"], guide["id"]) + report = await create_sufficiency_report(project_client, project["id"], guide["id"], snapshot["id"]) + from projects.unified_policy_fixtures import create_unified_submission_policy + policy = await create_unified_submission_policy(report["id"], snapshot["id"]) + + effective = await approve_submission_artifact_policy( + project_client, + project["id"], + guide["id"], + policy["id"], + ) + + assert policy["lifecycle_status"] == "draft" + assert policy["policy_hash"].startswith("sha256:") + assert effective["source_snapshot_id"] == snapshot["id"] + assert effective["source_snapshot_hash"] == snapshot["bundle_hash"] + assert effective["submission_artifact_policy_hash"] == policy["policy_hash"] + assert effective["effective_policy_hash"].startswith("sha256:") + assert effective["effective_policy"]["artifact_hash_algorithm"] == "sha256" + + async with db_session.get_session_factory()() as session: + persisted_policy = await session.get(SubmissionArtifactPolicy, policy["id"]) + pre_submit_checker_policy = await session.scalar( + select(PreSubmitCheckerPolicy).where( + PreSubmitCheckerPolicy.effective_policy_id == effective["id"] + ) + ) + + assert persisted_policy is not None + assert persisted_policy.lifecycle_status == "approved" + assert persisted_policy.approved_by_role == "project_manager" + assert persisted_policy.approved_by_actor == persisted_policy.approved_by_actor_profile_id + assert persisted_policy.approved_by_actor != policy["created_by"] + assert persisted_policy.approved_at is not None + assert persisted_policy.derivation_source == "unified_compilation" + assert len(persisted_policy.source_material_refs) == len(snapshot["items"]) + assert all( + ref.startswith("guide-document:") and "#sha256:" in ref + for ref in persisted_policy.source_material_refs + ) + assert pre_submit_checker_policy.lifecycle_status == "compiled" + assert pre_submit_checker_policy.effective_policy_hash == effective["effective_policy_hash"] + assert pre_submit_checker_policy.compiler_version == "external_checker_policy.v1" + locked_pre_policy = validate_stored_external_pre_policy( + pre_submit_checker_policy.compiled_bundle + ) + assert locked_pre_policy.policy_sha256 == pre_submit_checker_policy.compiled_bundle_hash + assert [(e.requirement_id, e.stage, e.registry.capability_id, e.registry.capability_version, e.registry.image_digest, e.configuration) for e in locked_pre_policy.entries] == [("project.archive_rules", "pre_submit", "acme.safe_archive", "v1.2.3", "sha256:" + "a" * 64, {})] + + +async def test_active_guide_retrieval_returns_exact_policy_bundle(project_client: AsyncClient) -> None: + project = await create_project(project_client) + guide = await create_guide(project_client, project["id"], complete_guide_payload()) + bundle = await create_approved_policy_bundle(project_client, project["id"], guide["id"]) + + activation = await activate_approved_guide( + db_session.get_session_factory(), + project_id=project["id"], + guide_id=guide["id"], + ) + active = await project_client.get( + f"/api/v1/projects/{project['id']}/active-guide", + headers=auth_headers(), + ) + effective_read = await project_client.get( + f"/api/v1/projects/{project['id']}/guides/{guide['id']}/" + "effective-submission-artifact-policy", + headers=auth_headers(), + ) + checker_read = await project_client.get( + f"/api/v1/projects/{project['id']}/guides/{guide['id']}/pre-submit-checker-policy", + headers=auth_headers(), + ) + + assert active.status_code == 200, active.text + assert effective_read.status_code == 200, effective_read.text + assert checker_read.status_code == 200, checker_read.text + assert set(effective_read.json()) == { + "id", + "project_id", + "guide_id", + "guide_version", + "source_snapshot_id", + "source_snapshot_hash", + "submission_artifact_policy_id", + "submission_artifact_policy_hash", + "lifecycle_status", + "merge_algorithm_version", + "effective_policy", + "effective_policy_hash", + "created_by", + "created_at", + "supersedes_effective_policy_id", + "superseded_at", + } + assert set(checker_read.json()) == { + "id", + "project_id", + "guide_id", + "guide_version", + "source_snapshot_id", + "source_snapshot_hash", + "effective_policy_id", + "effective_policy_hash", + "lifecycle_status", + "compiler_version", + "compiled_bundle_hash", + "checker_names", + "created_by", + "created_at", + "supersedes_pre_submit_checker_policy_id", + "superseded_at", + } + assert set(active.json()) == { + "guide", + "guide_source_snapshot", + "guide_sufficiency_report", + "submission_artifact_policy", + "effective_submission_artifact_policy", + "pre_submit_checker_policy", + "post_submit_checker_policy", + "review_policy", + "revision_policy", + } + assert effective_read.json()["id"] == bundle["effective_policy"]["id"] + assert checker_read.json()["effective_policy_id"] == bundle["effective_policy"]["id"] + assert "compiled_bundle" not in checker_read.json() + assert "checker_configs" not in checker_read.json() + assert active.json()["guide"]["status"] == "active" + assert active.json()["guide"]["version"] == "v1" + assert active.json()["guide"]["approved_by"] == guide["created_by"] + assert active.json()["guide"]["effective_at"] is not None + assert activation["guide"]["approved_by"] == guide["created_by"] + assert datetime.fromisoformat(activation["guide"]["effective_at"]) == datetime.fromisoformat(active.json()["guide"]["effective_at"]) + assert active.json()["post_submit_checker_policy"]["required_checkers"] == ["acme.safe_archive"] + assert ( + active.json()["guide_source_snapshot"]["bundle_hash"] + == (bundle["source_snapshot"]["bundle_hash"]) + ) + assert active.json()["guide_sufficiency_report"]["status"] == "passed" + assert active.json()["submission_artifact_policy"]["lifecycle_status"] == "approved" + assert ( + active.json()["effective_submission_artifact_policy"]["effective_policy_hash"] + == (bundle["effective_policy"]["effective_policy_hash"]) + ) + assert active.json()["pre_submit_checker_policy"]["lifecycle_status"] == "compiled" + assert ( + active.json()["pre_submit_checker_policy"]["effective_policy_id"] + == (bundle["effective_policy"]["id"]) + ) + assert ( + active.json()["pre_submit_checker_policy"]["compiled_bundle_hash"] + == (bundle["pre_submit_checker_policy"]["compiled_bundle_hash"]) + ) + assert "compiled_bundle" not in active.json()["pre_submit_checker_policy"] + assert "payment_policy" not in active.json() + assert "review_policy" in active.json() + assert ( + active.json()["pre_submit_checker_policy"]["checker_names"] + == (bundle["pre_submit_checker_policy"]["checker_names"]) + ) + assert ( + active.json()["pre_submit_checker_policy"]["checker_configs"] + == (bundle["pre_submit_checker_policy"]["checker_configs"]) + ) + assert active.json()["revision_policy"]["max_revision_rounds"] == 7 + assert "auto_reject_after_limit" not in active.json()["revision_policy"] diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 968dabc53..b1e3e13fa 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -323,8 +323,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: "7d5683912037886633519322314c8fdc3c89855dc2408b2ffc629c842e3ad8fc", ), "project": ( - 257, - "bce3b7bb971159d065d8d7b9bd4a7ff0bb69566f515e02de8542902c0511ebe5", + 258, + "39504157bb06c4da278a8682230d5e76ce820d7ce3c88cd59af08f8693f293c6", ), "task": ( 96, @@ -396,9 +396,9 @@ def test_project_lane_ownership_has_an_independent_fingerprint() -> None: ) + "\n" ) - assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 257 + assert len(catalogue.PROJECT_PARTITIONED_MODULES) == 258 assert hashlib.sha256(canonical.encode()).hexdigest() == ( - "2dc926ed22f4ceceaa7d9915625567921290f3588d27a76586c010475f02764e" + "c19e85ce7e623252d6de97f6707225b92a88514dc11ef36fd16e51d5531b9020" ) diff --git a/backend/tests/test_projects.py b/backend/tests/test_projects.py index be4574c97..45c94ef7a 100644 --- a/backend/tests/test_projects.py +++ b/backend/tests/test_projects.py @@ -33,7 +33,6 @@ from app.core.config import get_settings from app.core.hashing import canonical_json_hash from app.core.identifiers import new_record_id -from app.modules.checkers.api.external_policy import validate_stored_external_pre_policy from app.db import session as db_session from app.db.base import Base from app.main import create_app @@ -3629,59 +3628,6 @@ async def test_submission_artifact_policy_removed_agent_route_performs_no_runtim assert policies == [] -async def test_submission_artifact_policy_approval_persists_effective_policy_hash( - project_client: AsyncClient, -) -> None: - project = await create_project(project_client) - guide = await create_guide(project_client, project["id"], complete_guide_payload()) - snapshot = await read_guide_source_snapshot(project["id"], guide["id"]) - report = await create_sufficiency_report(project_client, project["id"], guide["id"], snapshot["id"]) - from projects.unified_policy_fixtures import create_unified_submission_policy - policy = await create_unified_submission_policy(report["id"], snapshot["id"]) - - effective = await approve_submission_artifact_policy( - project_client, - project["id"], - guide["id"], - policy["id"], - ) - - assert policy["lifecycle_status"] == "draft" - assert policy["policy_hash"].startswith("sha256:") - assert effective["source_snapshot_id"] == snapshot["id"] - assert effective["source_snapshot_hash"] == snapshot["bundle_hash"] - assert effective["submission_artifact_policy_hash"] == policy["policy_hash"] - assert effective["effective_policy_hash"].startswith("sha256:") - assert effective["effective_policy"]["artifact_hash_algorithm"] == "sha256" - - async with db_session.get_session_factory()() as session: - persisted_policy = await session.get(SubmissionArtifactPolicy, policy["id"]) - pre_submit_checker_policy = await session.scalar( - select(PreSubmitCheckerPolicy).where( - PreSubmitCheckerPolicy.effective_policy_id == effective["id"] - ) - ) - - assert persisted_policy is not None - assert persisted_policy.lifecycle_status == "approved" - assert persisted_policy.approved_by_role == "project_manager" - assert persisted_policy.approved_by_actor == persisted_policy.approved_by_actor_profile_id - assert persisted_policy.approved_by_actor != policy["created_by"] - assert persisted_policy.approved_at is not None - assert persisted_policy.derivation_source == "unified_compilation" - assert len(persisted_policy.source_material_refs) == len(snapshot["items"]) - assert all( - ref.startswith("guide-document:") and "#sha256:" in ref - for ref in persisted_policy.source_material_refs - ) - assert pre_submit_checker_policy.lifecycle_status == "compiled" - assert pre_submit_checker_policy.effective_policy_hash == effective["effective_policy_hash"] - assert pre_submit_checker_policy.compiler_version == "external_checker_policy.v1" - locked_pre_policy = validate_stored_external_pre_policy( - pre_submit_checker_policy.compiled_bundle - ) - assert locked_pre_policy.policy_sha256 == pre_submit_checker_policy.compiled_bundle_hash - assert locked_pre_policy.entries == () async def test_approved_submission_artifact_policy_cannot_be_updated( @@ -5076,123 +5022,6 @@ async def test_active_guide_read_revalidates_policy_context( assert response.json()["guide"]["id"] == guide["id"] -async def test_active_guide_retrieval_returns_exact_policy_bundle(project_client: AsyncClient) -> None: - project = await create_project(project_client) - guide = await create_guide(project_client, project["id"], complete_guide_payload()) - bundle = await create_approved_policy_bundle(project_client, project["id"], guide["id"]) - - activation = await activate_approved_guide( - db_session.get_session_factory(), - project_id=project["id"], - guide_id=guide["id"], - ) - active = await project_client.get( - f"/api/v1/projects/{project['id']}/active-guide", - headers=auth_headers(), - ) - effective_read = await project_client.get( - f"/api/v1/projects/{project['id']}/guides/{guide['id']}/" - "effective-submission-artifact-policy", - headers=auth_headers(), - ) - checker_read = await project_client.get( - f"/api/v1/projects/{project['id']}/guides/{guide['id']}/pre-submit-checker-policy", - headers=auth_headers(), - ) - - assert active.status_code == 200, active.text - assert effective_read.status_code == 200, effective_read.text - assert checker_read.status_code == 200, checker_read.text - assert set(effective_read.json()) == { - "id", - "project_id", - "guide_id", - "guide_version", - "source_snapshot_id", - "source_snapshot_hash", - "submission_artifact_policy_id", - "submission_artifact_policy_hash", - "lifecycle_status", - "merge_algorithm_version", - "effective_policy", - "effective_policy_hash", - "created_by", - "created_at", - "supersedes_effective_policy_id", - "superseded_at", - } - assert set(checker_read.json()) == { - "id", - "project_id", - "guide_id", - "guide_version", - "source_snapshot_id", - "source_snapshot_hash", - "effective_policy_id", - "effective_policy_hash", - "lifecycle_status", - "compiler_version", - "compiled_bundle_hash", - "checker_names", - "created_by", - "created_at", - "supersedes_pre_submit_checker_policy_id", - "superseded_at", - } - assert set(active.json()) == { - "guide", - "guide_source_snapshot", - "guide_sufficiency_report", - "submission_artifact_policy", - "effective_submission_artifact_policy", - "pre_submit_checker_policy", - "post_submit_checker_policy", - "review_policy", - "revision_policy", - } - assert effective_read.json()["id"] == bundle["effective_policy"]["id"] - assert checker_read.json()["effective_policy_id"] == bundle["effective_policy"]["id"] - assert "compiled_bundle" not in checker_read.json() - assert "checker_configs" not in checker_read.json() - assert active.json()["guide"]["status"] == "active" - assert active.json()["guide"]["version"] == "v1" - assert active.json()["guide"]["approved_by"] == guide["created_by"] - assert active.json()["guide"]["effective_at"] is not None - assert activation["guide"]["approved_by"] == guide["created_by"] - assert datetime.fromisoformat(activation["guide"]["effective_at"]) == datetime.fromisoformat(active.json()["guide"]["effective_at"]) - assert active.json()["post_submit_checker_policy"]["required_checkers"] == ["acme.safe_archive"] - assert ( - active.json()["guide_source_snapshot"]["bundle_hash"] - == (bundle["source_snapshot"]["bundle_hash"]) - ) - assert active.json()["guide_sufficiency_report"]["status"] == "passed" - assert active.json()["submission_artifact_policy"]["lifecycle_status"] == "approved" - assert ( - active.json()["effective_submission_artifact_policy"]["effective_policy_hash"] - == (bundle["effective_policy"]["effective_policy_hash"]) - ) - assert active.json()["pre_submit_checker_policy"]["lifecycle_status"] == "compiled" - assert ( - active.json()["pre_submit_checker_policy"]["effective_policy_id"] - == (bundle["effective_policy"]["id"]) - ) - assert ( - active.json()["pre_submit_checker_policy"]["compiled_bundle_hash"] - == (bundle["pre_submit_checker_policy"]["compiled_bundle_hash"]) - ) - assert "compiled_bundle" not in active.json()["pre_submit_checker_policy"] - assert "payment_policy" not in active.json() - assert "review_policy" in active.json() - assert ( - active.json()["pre_submit_checker_policy"]["checker_names"] - == (bundle["pre_submit_checker_policy"]["checker_names"]) - ) - assert ( - active.json()["pre_submit_checker_policy"]["checker_configs"] - == (bundle["pre_submit_checker_policy"]["checker_configs"]) - ) - assert active.json()["revision_policy"]["max_revision_rounds"] == 7 - assert "auto_reject_after_limit" not in active.json()["revision_policy"] async def test_draft_guide_edit_and_active_guide_edit_block(project_client: AsyncClient) -> None: From 300241e625f57375f37b4a465ea3e9d93bdaca47 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:35:26 +0100 Subject: [PATCH 332/513] Record native launch failure evidence and failed-source assertion diagnosis --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e1063ad70..fd6f2716d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10562,3 +10562,7 @@ tests reject omission of the new module (/tmp/submission-policy-read-guard-probe This is whole-node relocation and real debt reduction; prior PG proof is retained as inspected custody, with current-path B/D/G replay owned by root. No runtime, provider, public capability or roadmap completion claim changes. + +Pre3 at9c489adbe reached the intended native launch fault: first-response receipt reports3trace events (create/start/delete), exact infrastructure_failed/implementation_unavailable PRE, expected public503, and failed-source assertions passed (sealed physical charge, no acceptance/Submission, task eligible). It then stopped before replay/recovery on an incorrect fixture expectation that failed intake carries acceptance-only selected_pre_submit_run_id. Production stage_acceptance alone fills that field; the real failed binding is SelectedPreSubmitRun.source_operation_id with its unique FK. Correct the fixture to require the failed operation pointerNULL, the exact reverse binding, and the same singleton operation set; do not change production custody. + +The run is not a passing full fault/recovery result. Isolated DB/MinIO cleanup completed; root restored exact run09ebccf4-d1d2-49c3-8804-32d647e43d17 once. `/tmp/submission-runner-pre3-restoration.json` confirms original config hash, all four owned resource lists empty, and exact foreign fixture removal. The first response remains private in `/tmp/submission-pre-launch-evidence-pre3/remote-pre-launch-first-response.json`. Next attempt can reuse unchanged staged9c supervisor source with fresh run identity; only the local caller assertion changes. From 9d691a84de0f9a2e1255b43861a038003c3a07c9 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:37:21 +0100 Subject: [PATCH 333/513] Bind failed PRE to source operation in native fault trial --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 +++++++++++++++++++ .../public_runtime_trials.py | 8 +++++-- scripts/test_public_hosted_attachment.py | 18 +++++++++----- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index fd6f2716d..929c151b0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10566,3 +10566,27 @@ provider, public capability or roadmap completion claim changes. Pre3 at9c489adbe reached the intended native launch fault: first-response receipt reports3trace events (create/start/delete), exact infrastructure_failed/implementation_unavailable PRE, expected public503, and failed-source assertions passed (sealed physical charge, no acceptance/Submission, task eligible). It then stopped before replay/recovery on an incorrect fixture expectation that failed intake carries acceptance-only selected_pre_submit_run_id. Production stage_acceptance alone fills that field; the real failed binding is SelectedPreSubmitRun.source_operation_id with its unique FK. Correct the fixture to require the failed operation pointerNULL, the exact reverse binding, and the same singleton operation set; do not change production custody. The run is not a passing full fault/recovery result. Isolated DB/MinIO cleanup completed; root restored exact run09ebccf4-d1d2-49c3-8804-32d647e43d17 once. `/tmp/submission-runner-pre3-restoration.json` confirms original config hash, all four owned resource lists empty, and exact foreign fixture removal. The first response remains private in `/tmp/submission-pre-launch-evidence-pre3/remote-pre-launch-first-response.json`. Next attempt can reuse unchanged staged9c supervisor source with fresh run identity; only the local caller assertion changes. + +The third isolated run used clean `9c489adbed12387fc4cc9b5101ab4176094abceb` +with one finite supervisor and the corrected temporary PRE/Smol binary pins. +Public guide activation and task claim passed. The first public submission +returned the expected infrastructure 503 and retained a finalized failed PRE +terminal with `implementation_unavailable`. The private first-response receipt +and independent runner snapshot show exactly one project machine create, start +and delete, no exec, and drained owned resources. The run then failed a later +trial assertion before replay/recovery: it expected a failed intake operation's +`selected_pre_submit_run_id` to equal that PRE. That field belongs only to an +accepted operation and must be NULL on failure. Isolated database and MinIO +cleanup both completed; the operator restored the original checker config and +empty resources. This is real first-failure native evidence, not the full +same-key/fresh-key recovery qualification. + +The trial now requires the failed operation's acceptance pointer to be NULL +and binds the exact failed PRE through its durable `source_operation_id`, +canonical request and terminal source location operation ID, and the singleton +task operation set. Fresh recovery also requires its PRE source-operation ID to +equal the public accepted receipt operation. Controlled tests model the real +NULL field and reject a foreign source binding; the entire affected hosted +attachment module passes `39 passed, 74 subtests passed`. The retained native +trace-count assertion remains unchanged. A fourth connected run is still +required to prove same-key replay, fresh-key accepted T5 and full cleanup. diff --git a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py index 96eccc9f7..9f88e168e 100644 --- a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py @@ -161,7 +161,10 @@ async def _remote_pre_launch_failure(client, factory, *, task, assignment, token 'remote failed PRE lost exact selected image or terminal infrastructure custody') operation = await _assert_source_failure(factory, task, key, len(archive), sealed=True, code='submission_infrastructure_unavailable') - _require(operation.selected_pre_submit_run_id == row.id + _require(operation.selected_pre_submit_run_id is None + and row.task_id == task and row.source_operation_id == operation.id + and row.request_json['source']['location']['operation_id'] == operation.id + and row.terminal_json['reservation']['source']['location']['operation_id'] == operation.id and await _trial_operation_ids(factory, task) == {operation.id}, 'launch failure created another operation or changed its exact PRE') await runner.command('clear') @@ -178,7 +181,8 @@ async def _remote_pre_launch_failure(client, factory, *, task, assignment, token receipt = await _source_request(client, route, headers, token, fresh_key, archive, 202) fresh = await _selected(factory, fresh_key) _assert_current_pre(fresh) - _require(fresh.id != row.id and fresh.request_json['policy']['entries'][0]['registry']['image_digest'] + _require(fresh.id != row.id and fresh.source_operation_id == receipt['operation_id'] + and fresh.request_json['policy']['entries'][0]['registry']['image_digest'] == runner.profile.image_digest, 'recovery changed the exact selected image or reused failed PRE') recovered_cleanup = await _runner_drained(runner) recovered_trace = await runner.snapshot() diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 51db5453a..488c598f1 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -1124,7 +1124,8 @@ async def exercise(): class RemotePreLaunchContracts(unittest.TestCase): def exercise(self, *, omit_delete=False, replay_allocates=False, wrong_image=False, - unknown=False, missing_create=False, first_response_path=None): + unknown=False, missing_create=False, wrong_source=False, + first_response_path=None): from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime from experiments.pilot04_external_checker_runtime.public_runner_faults import FaultOutcomeUnknown @@ -1154,12 +1155,16 @@ async def command(self, action): async def snapshot(self): return traces.pop(0) registry = {'image_digest': 'sha256:' + 'a' * 64 if wrong_image else image} - request = {'policy': {'entries': [{'registry': registry}]}} + source_id = 'foreign-operation' if wrong_source else 'failed-operation' + request = {'policy': {'entries': [{'registry': registry}]}, + 'source': {'location': {'operation_id': source_id}}} failed_row = SimpleNamespace(id='failed-pre', terminal_digest='digest', request_json=request, + task_id='task', source_operation_id='failed-operation', status='infrastructure_failed', terminal_json={'execution': None, - 'infrastructure_failure_code': 'implementation_unavailable'}) - fresh_row = SimpleNamespace(id='fresh-pre', request_json=request) - operation = SimpleNamespace(id='failed-operation', selected_pre_submit_run_id='failed-pre') + 'infrastructure_failure_code': 'implementation_unavailable', + 'reservation': {'source': {'location': {'operation_id': 'failed-operation'}}}}) + fresh_row = SimpleNamespace(id='fresh-pre', source_operation_id='fresh-operation', request_json=request) + operation = SimpleNamespace(id='failed-operation', selected_pre_submit_run_id=None) failure = {'error': {'code': 'submission_infrastructure_unavailable'}} receipt = {'operation_id': 'fresh-operation', 'status': 'accepted', 'replayed': False} source = AsyncMock(side_effect=[failure, failure, receipt]) @@ -1194,7 +1199,8 @@ def test_remote_first_pre_preserves_known_failure_replay_and_real_t5_observer(se self.exercise() for fault, message in (('omit_delete', 'lacks deletion'), ('replay_allocates', 'same-key failure replay changed custody'), - ('wrong_image', 'failed PRE lost exact selected image')): + ('wrong_image', 'failed PRE lost exact selected image'), + ('wrong_source', 'changed its exact PRE')): with self.subTest(fault=fault), self.assertRaisesRegex(RuntimeError, message): self.exercise(**{fault: True}) From 4b6c42807b7ce25a57573b10d06839dcbb958b92 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:38:17 +0100 Subject: [PATCH 334/513] Record focused PostgreSQL policy and POST repair passes --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 929c151b0..553af5c9e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10590,3 +10590,5 @@ NULL field and reject a foreign source binding; the entire affected hosted attachment module passes `39 passed, 74 subtests passed`. The retained native trace-count assertion remains unchanged. A fourth connected run is still required to prove same-key replay, fresh-key accepted T5 and full cleanup. + +Integrated B/D/G repair replay atc897ad192 passed all3 exact PostgreSQL cases in89.42s, schema0091, complete isolated database cleanup (`/tmp/submission-policy-and-post-repairs.log` and `.json`). These cover persisted required PRE selection, public active-guide POST selection, and selected POST materialization/replay with the exact locked member. The unchanged structural validator and Commitrail check passed on integrated source before this replay. From c38144a5395289a89788753699878ed20750a157 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:40:53 +0100 Subject: [PATCH 335/513] ci: split shared lane capacity and retain early failures --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 78 ++++++++++++++++++ .github/workflows/backend.yml | 4 +- backend/scripts/run_test_lanes.py | 13 ++- backend/scripts/test_lane_catalogue.py | 6 ++ .../scripts/validate_test_lane_evidence.py | 2 +- backend/tests/test_ci_lane_catalogue.py | 12 ++- backend/tests/test_ci_test_lanes.py | 79 ++++++++++++++++++- .../tests/test_merge_test_lane_evidence.py | 4 +- backend/tests/test_test_lane_evidence.py | 12 ++- docs/operations_backend_testing.md | 12 ++- 10 files changed, 205 insertions(+), 17 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 553af5c9e..290ab8b90 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10592,3 +10592,81 @@ trace-count assertion remains unchanged. A fourth connected run is still required to prove same-key replay, fresh-key accepted T5 and full cleanup. Integrated B/D/G repair replay atc897ad192 passed all3 exact PostgreSQL cases in89.42s, schema0091, complete isolated database cleanup (`/tmp/submission-policy-and-post-repairs.log` and `.json`). These cover persisted required PRE selection, public active-guide POST selection, and selected POST materialization/replay with the exact locked member. The unchanged structural validator and Commitrail check passed on integrated source before this replay. + +### Shared CI capacity and immediate failure diagnostics (2026-11-24) + +Intent: three shared-foundation jobs from run45451579222 exhausted the unchanged +1500-second budget. The exact receipts retain A1301/2319, B881/2184 and C1394/2214 +completed nodes, no skips/deselections, and successful cleanup. Buffered progress +dots cannot identify failed node IDs soundly; no inferred failure mapping is used. + +Allowed scope: existing shared-family shard tuple, independent exact inventory +controls and hosted aggregation/validator counts, existing lane report hook and +focused runner tests, affected operations guide, this record. Increase only shared a..c to a..i using the +existing node hash; preserve every family member, project/task assignment, +timeout, status, isolation, coverage, interruption and exact-once custody gate. +No product change, skip, new evidence schema, framework or budget increase. +Immediate failed reports must print node/phase and bounded existing traceback, +redact configured secrets, and flush before a subsequent hang or interruption. + +Acceptance: historical6717-node shared inventory has exactly one new owner per +node; other5679 ownerships unchanged; independent family fingerprints unchanged. +Actual subprocess regression must retain a failure before final pytest summary +when a later node is interrupted. Missing shards/duplicates still fail existing +evidence controls. Existing1500-second budget and hosted status dependency remain +unchanged. Root selected9 shared shards for headroom beyond the smallest8 +(799..868nodes versus slowest observed881 completions); node counts do not prove +timing. CI-integrity/QA review and fresh hosted replay remain required. Risk is +CI selection/diagnostic custody; human focus is complete inventory and unchanged +blocking gates. Roadmap capability claims are unaffected. + +The historical12396-node canonical manifest is preserved byte-for-byte per row +except shared lane selection. Shared6717 redistributes to a..i counts +809/751/767/738/688/738/772/745/709; all5679 other nodes keep their exact owners. +All shared/project/task module tuples, old lane definitions and independent +family membership fingerprints are unchanged. Six new shared shards are the +only added lanes. Hosted coverage/aggregation and independent validator now +require exactly23 distinct complete lanes rather than17; workflow changes only +those two exact-count checks. Existing1500-second budgets and blocking status +logic are untouched. /tmp/submission-shared-capacity-preservation.json records +the original manifest digest and exact counts; this is inspected redistribution, +not fresh hosted runtime qualification. + +Existing report hook now flushes failed node/phase plus at most65536characters +of redacted existing traceback, with explicit truncation. No report file/schema +or new collection behavior. Ordinary/admin output owners still apply their +existing outer redaction and buffering; child report bytes survive timeout +before pytest can print its final summary. Actual subprocess proof creates +setup/call/teardown failures then a hanging node, uses the production isolated +process timeout path, and requires all three exact reports without final summary. +It removes all four outer custody-path environments and checks unchanged parent +sentinels, preventing synthetic nodes from polluting hosted lane evidence. + +First narrow red run exposed missing reports; two5-second branches did not +reach the hang under load, so those are harness failures, not discriminator +proof. The consolidated20-second test reaches every failure phase in one child. +First full focused run252pass/1fail caught the unchanged17-row timing fixture; +its exact23-row sum now includes all new lanes and retains missing/extra/invalid +timing refusal. Final five-module pure suite passed273 in50.75s +(/tmp/submission-shared-capacity-tests-v2.log), including new-i missing/foreign +bundle, latest-failed/no-fallback, partial/duplicate/skip custody controls. +The final parent-custody test-only tightening was separately replayed successfully +(/tmp/submission-lane-custody-regression.log). No database run was started. + +An isolated omission mutant reached the hanging node and actual timeout124, +then failed specifically because exact setup report bytes were absent; no final +summary existed (/tmp/submission-lane-report-omission-mutant-v2.log). Initial +mutant setup lacked app/HEAD prerequisites and is excluded from behavioral proof. +Configured-secret redaction, finite output, passed-report silence and unchanged +skip recording are tested directly. Full unchanged structural validation exited0 +(/tmp/submission-shared-capacity-structure.log) before the final test-only child +custody assertion addition; no policy, debt ledger or runtime assertion changed. +Ruff and whitespace pass. CI-integrity review and fresh hosted completion remain +required; this change neither identifies old buffered failure IDs nor claims +all current tests pass or the full submission goal is complete. + +The affected operations guide now names nine shared shards and immediate bounded +failure diagnostics. Its bucket wording follows current isolation owner: shared +lanes create/probe/remove their distinct buckets; only omnicore_sdk retains the +fixed workstream-artifacts traffic-proof bucket. Historical17-lane receipts in +reports/roadmap remain historical and unchanged. diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml index 20c5363f4..098556949 100644 --- a/.github/workflows/backend.yml +++ b/.github/workflows/backend.yml @@ -652,7 +652,7 @@ jobs: set -euo pipefail shopt -s nullglob coverage_files=(.ci/test-lanes/run/.coverage.*) - test "${#coverage_files[@]}" -eq 17 + test "${#coverage_files[@]}" -eq 23 for source in "${coverage_files[@]}"; do destination="$(basename "${source}")" test -f "${source}" @@ -731,7 +731,7 @@ jobs: raise SystemExit("hosted evidence head drift") lanes = summary.get("lanes") - if not isinstance(lanes, list) or len(lanes) != 17: + if not isinstance(lanes, list) or len(lanes) != 23: raise SystemExit("invalid hosted lane inventory") collected: list[str] = [] completed: list[str] = [] diff --git a/backend/scripts/run_test_lanes.py b/backend/scripts/run_test_lanes.py index 72a10f4c8..2d185cc39 100644 --- a/backend/scripts/run_test_lanes.py +++ b/backend/scripts/run_test_lanes.py @@ -68,6 +68,7 @@ HEARTBEAT_SECONDS = 60.0 CLEANUP_GRACE_SECONDS = 10.0 POLL_SECONDS = 0.05 +FAILED_REPORT_MAX_CHARS = 65536 SHA_RE = re.compile(r"[0-9a-f]{40}") LANE_RE = re.compile(r"[a-z][a-z0-9_]*") INTERRUPTED = False @@ -144,10 +145,20 @@ def pytest_runtest_logfinish(nodeid: str, location: tuple[str, int | None, str]) def pytest_runtest_logreport(report: Any) -> None: - """Record every skip observed during setup, call, or teardown.""" + """Record skips and retain failures before timeout can erase the summary.""" destination = os.environ.get(SKIPPED_ENV) if destination and report.skipped: _append_node(destination, report.nodeid) + if report.failed: + rendered = f"\nLANE FAILURE {report.nodeid} [{report.when}]\n{report.longreprtext}\n" + for name in TRACEBACK_SECRET_ENVS: + value = os.environ.get(name) + if value: + rendered = rendered.replace(value, f"[REDACTED_{name}]") + if len(rendered) > FAILED_REPORT_MAX_CHARS: + rendered = rendered[:FAILED_REPORT_MAX_CHARS] + "\n[TRACEBACK TRUNCATED]\n" + sys.stderr.write(rendered) + sys.stderr.flush() def pytest_deselected(items: list[Any]) -> None: diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 42b42caea..4a1f32a1d 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -8,6 +8,12 @@ "shared_foundations_a", "shared_foundations_b", "shared_foundations_c", + "shared_foundations_d", + "shared_foundations_e", + "shared_foundations_f", + "shared_foundations_g", + "shared_foundations_h", + "shared_foundations_i", ) PARTITIONED_PROJECT_LANES = ( "project_lifecycle_a", diff --git a/backend/scripts/validate_test_lane_evidence.py b/backend/scripts/validate_test_lane_evidence.py index b2e967042..9bee46efb 100644 --- a/backend/scripts/validate_test_lane_evidence.py +++ b/backend/scripts/validate_test_lane_evidence.py @@ -24,7 +24,7 @@ from scripts.record_id_collection import RecordIdCollection # noqa: E402 SCHEMA_VERSION = 1 -LANE_COUNT = 17 +LANE_COUNT = 23 SHA_RE = re.compile(r"^[0-9a-f]{40}$") DIGEST_RE = re.compile(r"^[0-9a-f]{64}$") LANE_RE = re.compile(r"^[a-z][a-z0-9_]*$") diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index b1e3e13fa..0fcb8de61 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -24,7 +24,7 @@ def test_committed_lanes_cover_recursive_inventory_exactly_once() -> None: runner.validate_lane_inventory(discovered) assigned = [module for lane in LANES for module in lane.modules] - assert len(LANES) == 17 + assert len(LANES) == 23 assert all(lane.requires_postgres for lane in LANES) assert Counter(assigned)[catalogue.SCHEMA_MODULE] == 1 assert all( @@ -198,6 +198,12 @@ def test_expanded_lane_families_keep_exact_semantic_owners() -> None: "shared_foundations_a", "shared_foundations_b", "shared_foundations_c", + "shared_foundations_d", + "shared_foundations_e", + "shared_foundations_f", + "shared_foundations_g", + "shared_foundations_h", + "shared_foundations_i", ), catalogue.SHARED_FOUNDATION_MODULES, ), @@ -814,8 +820,8 @@ def test_workflow_lane_inventory_matches_catalogue() -> None: assert source.count("path: backend/.ci/download\n merge-multiple: false") == 1 assert '--expected-head "${GITHUB_SHA}"' in source assert '--run-attempt "${GITHUB_RUN_ATTEMPT}"' in source - assert 'test "${#coverage_files[@]}" -eq 17' in source - assert "len(lanes) != 17" in source + assert 'test "${#coverage_files[@]}" -eq 23' in source + assert "len(lanes) != 23" in source assert 'Path(".ci/download"), expected_head, int(os.environ["GITHUB_RUN_ATTEMPT"])' in source assert 'timing_path = bundle / "job-start-epoch.txt"' in source assert ( diff --git a/backend/tests/test_ci_test_lanes.py b/backend/tests/test_ci_test_lanes.py index 54bf92bd8..bafc28b5e 100644 --- a/backend/tests/test_ci_test_lanes.py +++ b/backend/tests/test_ci_test_lanes.py @@ -331,11 +331,17 @@ def test_timing_summary_is_derived_from_exact_declared_lanes() -> None: 0.125, 0.375, 0.25, + 0.25, + 0.25, + 0.25, + 0.25, + 0.25, + 0.25, ) lanes = [{"elapsed_seconds": value} for value in elapsed] assert runner._timing_summary(lanes) == { - "aggregate_runner_seconds": 15.0, + "aggregate_runner_seconds": 16.5, "slowest_lane_seconds": 3.75, } with pytest.raises(LaneError, match="invalid_lane_timing_inventory"): @@ -501,3 +507,74 @@ def fail_second_launch(*args, **kwargs): summary = json.loads(summary_path.read_text(encoding="utf-8")) assert len(summary["lanes"]) == 4 assert all(row["execution_exit_code"] != 0 for row in summary["lanes"]) + + +def test_failed_report_survives_later_node_timeout( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Actual timed-out pytest retains all failure phases without final summary.""" + from scripts import run_isolated_tests as isolated + + marker = tmp_path / "waiting" + module = tmp_path / "test_failure_then_wait.py" + module.write_text( + "import time\nfrom pathlib import Path\nimport pytest\n" + "@pytest.fixture\ndef setup_failure():\n" + " raise AssertionError('lane-setup-fault')\n" + "@pytest.fixture\ndef teardown_failure():\n yield\n" + " raise AssertionError('lane-teardown-fault')\n" + "def test_00_setup(setup_failure): pass\n" + "def test_01_call(): raise AssertionError('lane-call-fault')\n" + "def test_02_teardown(teardown_failure): pass\n" + "def test_03_waits():\n" + f" Path({str(marker)!r}).touch()\n time.sleep(60)\n", + encoding="utf-8", + ) + evidence = {} + for name in (runner.COLLECTED_ENV, runner.COMPLETED_ENV, + runner.SKIPPED_ENV, runner.DESELECTED_ENV): + path = tmp_path / name + path.write_bytes(b"parent-custody\n") + monkeypatch.setenv(name, str(path)) + evidence[name] = path + env = os.environ.copy() + for name in evidence: + env.pop(name) + env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1" + env["PYTHONPATH"] = str(runner.ROOT) + command = [sys.executable, "-m", "pytest", "-q", "--noconftest", + "-c", "/dev/null", "-p", "scripts.run_test_lanes", str(module)] + code, stdout, stderr = isolated._run(command, env, timeout=20) + + assert code == 124 + assert marker.exists(), (stdout, stderr) + assert all(path.read_bytes() == b"parent-custody\n" for path in evidence.values()) + assert b"short test summary info" not in stdout + stderr + for index, phase in enumerate(("setup", "call", "teardown")): + assert f"::test_0{index}_{phase} [{phase}]".encode() in stderr + assert f"AssertionError: lane-{phase}-fault".encode() in stderr + + +def test_failed_report_redacts_secrets_bounds_output_and_preserves_skips( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path, +) -> None: + destination = tmp_path / "skipped.jsonl" + destination.touch() + monkeypatch.setenv(runner.SKIPPED_ENV, str(destination)) + for index, name in enumerate(runner.TRACEBACK_SECRET_ENVS): + monkeypatch.setenv(name, f"private-lane-value-{index}") + secrets = [os.environ[name] for name in runner.TRACEBACK_SECRET_ENVS] + report = types.SimpleNamespace(nodeid="test_exact", when="call", skipped=False, + failed=True, longreprtext=" ".join(secrets) + "x" * 100000) + runner.pytest_runtest_logreport(report) + output = capsys.readouterr().err + assert all(secret not in output for secret in secrets) + assert all(f"[REDACTED_{name}]" in output for name in runner.TRACEBACK_SECRET_ENVS) + assert output.startswith("\nLANE FAILURE test_exact [call]\n") + assert output.endswith("\n[TRACEBACK TRUNCATED]\n") + assert len(output) == runner.FAILED_REPORT_MAX_CHARS + len("\n[TRACEBACK TRUNCATED]\n") + for failed, skipped in ((False, False), (False, True)): + report.failed, report.skipped = failed, skipped + runner.pytest_runtest_logreport(report) + assert capsys.readouterr().err == "" + assert destination.read_text().splitlines() == ['"test_exact"'] diff --git a/backend/tests/test_merge_test_lane_evidence.py b/backend/tests/test_merge_test_lane_evidence.py index 6448030bc..f1c8e2cab 100644 --- a/backend/tests/test_merge_test_lane_evidence.py +++ b/backend/tests/test_merge_test_lane_evidence.py @@ -110,7 +110,7 @@ def test_merge_bundles_emits_complete_run_summary(tmp_path: Path) -> None: assert len(list((tmp_path / "merged").glob(".coverage.*"))) == len(LANES) -@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) +@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) @pytest.mark.parametrize("damage", ["missing", "foreign"]) def test_merge_bundles_rejects_missing_or_foreign_lane(tmp_path: Path, lane_name: str, damage: str) -> None: source = tmp_path / "source" @@ -217,7 +217,7 @@ def test_partial_retry_selects_numeric_latest_before_validation(tmp_path: Path) ("coverage", "invalid_lane_bundle_file"), ("head", "invalid_lane_bundle_summary"), ]) -@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) +@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) def test_latest_invalid_attempt_never_falls_back(tmp_path: Path, damage: str, error: str, lane_name: str) -> None: source = tmp_path / "source" _bundles(source) diff --git a/backend/tests/test_test_lane_evidence.py b/backend/tests/test_test_lane_evidence.py index a119ad3bc..e1f072047 100644 --- a/backend/tests/test_test_lane_evidence.py +++ b/backend/tests/test_test_lane_evidence.py @@ -24,6 +24,12 @@ "shared_foundations_a", "shared_foundations_b", "shared_foundations_c", + "shared_foundations_d", + "shared_foundations_e", + "shared_foundations_f", + "shared_foundations_g", + "shared_foundations_h", + "shared_foundations_i", "schema_contracts", "project_lifecycle_a", "project_lifecycle_b", @@ -42,7 +48,7 @@ def test_validator_requires_exact_expanded_lane_and_shared_s3_custody() -> None: - assert validator.LANE_COUNT == len(LANES) == 17 + assert validator.LANE_COUNT == len(LANES) == 23 assert validator.SHARED_S3_LANES == {"omnicore_sdk"} @@ -219,7 +225,7 @@ def test_rejects_wrong_head_and_noncanonical_manifest(tmp_path: Path) -> None: ), ], ) -@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) +@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) def test_rejects_node_custody_failures(tmp_path: Path, mutation, message: str, lane_name: str) -> None: metadata, summary_path, summary = _bundle(tmp_path) lane = next(row for row in summary["lanes"] if row["name"] == lane_name) @@ -244,7 +250,7 @@ def test_rejects_node_custody_failures(tmp_path: Path, mutation, message: str, l ("interrupted", True, "lane_interrupted"), ], ) -@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) +@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) def test_rejects_failed_or_partial_lane( tmp_path: Path, field: str, value: object, message: str, lane_name: str ) -> None: diff --git a/docs/operations_backend_testing.md b/docs/operations_backend_testing.md index 441bf096d..9941b8cd8 100644 --- a/docs/operations_backend_testing.md +++ b/docs/operations_backend_testing.md @@ -202,12 +202,16 @@ The lane logs retain all setup/call/teardown phase durations, including phases below five milliseconds, for performance diagnosis. This output is bounded by the selected test inventory and remains diagnostic only: it cannot select tests or override completeness, cleanup or the execution deadline. +Failed setup/call/teardown reports also flush the exact node and phase with a +redacted traceback capped at 65,536 characters before pytest's final summary. +The isolated runner retains those bytes if a later test times out; its existing +outer output buffering and redaction remain in place. Measure final-report overhead alongside test execution when comparing allocations. The five `task_lifecycle_a` through `task_lifecycle_e` lanes use the same deterministic partition mechanism for the remaining TASK and checker nodes. The single `schema_contracts` lane owns all baseline/PostgreSQL schema, reset and isolated-runner contracts, together with database-backed migration, storage, and custody proofs. The -`shared_foundations_a`, `shared_foundations_b`, and `shared_foundations_c` lanes deterministically +nine `shared_foundations_a` through `shared_foundations_i` lanes deterministically partition exact node IDs from the remaining authorization, artifact, API, and infrastructure modules. This includes the database-independent repository inspections in `test_artifact_architecture.py`, `architecture/test_module_boundaries.py`, and @@ -249,9 +253,9 @@ validates complete execution. There is no duplicate standalone inventory pass in each matrix job. Each lane receives a distinct runner-created database and role plus a distinct MinIO prefix custody record. -All three shared-foundation jobs run in separate MinIO containers, use the actual -`workstream-artifacts` test bucket, and receive distinct run prefixes; other -lanes create, probe, and remove distinct buckets. +All nine shared-foundation jobs run in separate MinIO containers and create, +probe, and remove distinct buckets with distinct run prefixes. Only `omnicore_sdk` +uses the fixed `workstream-artifacts` bucket for its existing S3 traffic proof. The isolated-runner self-tests remain in the canonical manifest as the explicit `admin_runner_self_test` execution kind. The lane orchestrator runs only those nodes directly with the admin URL while stripping application database URLs; From df766fe63b043cae686586373421ba153c735ac7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:52:00 +0100 Subject: [PATCH 336/513] Compare stable public replay errors in native fault trial --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 +++++++++++++ .../public_runtime_trials.py | 34 ++++++++++++++++--- scripts/test_public_hosted_attachment.py | 17 +++++++--- 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 290ab8b90..67b3b67ca 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10670,3 +10670,27 @@ failure diagnostics. Its bucket wording follows current isolation owner: shared lanes create/probe/remove their distinct buckets; only omnicore_sdk retains the fixed workstream-artifacts traffic-proof bucket. Historical17-lane receipts in reports/roadmap remain historical and unchanged. + +The fourth isolated public fault run used clean +`4b6c42807b7ce25a57573b10d06839dcbb958b92` and one fresh finite +supervisor. Guide/task setup passed; the first public submission returned the +expected infrastructure 503, with a finalized failed PRE and exact native +create/start/delete. The failed source-to-PRE custody assertion now passed. +The same-key replay returned infrastructure 503, but the trial stopped at a +compound equality assertion comparing the entire first and replay error +bodies. That comparison included request-scoped `error.correlation_id`, which +the API creates for each HTTP request. The independent post-terminal trace +still has only the original three events, so replay did not allocate another +native machine. The other equality terms were not individually observed by +this failed assertion. Isolated database and MinIO cleanup completed; the +operator restored the original config and verified all owned resource lists +empty with the exact foreign control removed. + +The trial now compares the five closed public error fields while validating +both correlation IDs as canonical UUID strings, and checks selected PRE ID +and digest, native trace cursor and singleton source operation separately. +The fake public replay uses distinct valid correlation IDs; changed stable +message and malformed correlation cases fail. The entire affected hosted +attachment module passes `39 passed, 76 subtests passed`; Ruff lint and diff +checks pass. A fifth connected run is still needed for same-key custody, +fresh-key accepted T5 and complete end-to-end cleanup proof. diff --git a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py index 9f88e168e..4e0bd0118 100644 --- a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py @@ -3,7 +3,7 @@ import json from pathlib import Path import time -from uuid import uuid4 +from uuid import UUID, uuid4 from sqlalchemy import select @@ -99,6 +99,27 @@ async def _trial_operation_ids(factory, task): SubmissionIntakeOperation.task_id == task))) +def _same_public_failure(first, replay): + """Compare durable error fields while validating request-scoped IDs.""" + def stable(value): + if type(value) is not dict or set(value) != {'error'}: + return None + error = value['error'] + expected = {'code', 'message', 'details', 'correlation_id', 'retryable'} + if type(error) is not dict or set(error) != expected: + return None + correlation = error['correlation_id'] + try: + if type(correlation) is not str or str(UUID(correlation)) != correlation: + return None + except ValueError: + return None + return {key: item for key, item in error.items() if key != 'correlation_id'} + + left, right = stable(first), stable(replay) + return left is not None and left == right + + async def _runner_drained(runner): observed = await runner.command('drained') result = observed['result'] @@ -171,10 +192,13 @@ async def _remote_pre_launch_failure(client, factory, *, task, assignment, token replay = await _source_request(client, route, headers, token, key, archive, 503) repeated = await _selected(factory, key) replay_trace = await runner.snapshot() - _require(replay == failure and (repeated.id, repeated.terminal_digest) == (row.id, row.terminal_digest) - and replay_trace['cursor'] == failed_trace['cursor'] - and await _trial_operation_ids(factory, task) == {operation.id}, - 'same-key failure replay changed custody or allocated a native machine') + _require(_same_public_failure(failure, replay), 'same-key public failure fields changed') + _require((repeated.id, repeated.terminal_digest) == (row.id, row.terminal_digest), + 'same-key selected PRE identity or digest changed') + _require(replay_trace['cursor'] == failed_trace['cursor'], + 'same-key replay allocated a native machine') + _require(await _trial_operation_ids(factory, task) == {operation.id}, + 'same-key replay created another source operation') await _assert_source_failure(factory, task, key, len(archive), sealed=True, code='submission_infrastructure_unavailable') fresh_key = str(uuid4()) diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 488c598f1..e52cc1739 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -1125,6 +1125,7 @@ async def exercise(): class RemotePreLaunchContracts(unittest.TestCase): def exercise(self, *, omit_delete=False, replay_allocates=False, wrong_image=False, unknown=False, missing_create=False, wrong_source=False, + wrong_replay_field=False, bad_replay_correlation=False, first_response_path=None): from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime from experiments.pilot04_external_checker_runtime.public_runner_faults import FaultOutcomeUnknown @@ -1165,9 +1166,15 @@ async def snapshot(self): 'reservation': {'source': {'location': {'operation_id': 'failed-operation'}}}}) fresh_row = SimpleNamespace(id='fresh-pre', source_operation_id='fresh-operation', request_json=request) operation = SimpleNamespace(id='failed-operation', selected_pre_submit_run_id=None) - failure = {'error': {'code': 'submission_infrastructure_unavailable'}} + failure = {'error': {'code': 'submission_infrastructure_unavailable', + 'message': 'submission_infrastructure_unavailable', 'details': {}, + 'correlation_id': str(uuid4()), 'retryable': True}} + replay_error = {'error': failure['error'] | { + 'correlation_id': 'invalid' if bad_replay_correlation else str(uuid4()), + 'message': 'changed' if wrong_replay_field else failure['error']['message'], + }} receipt = {'operation_id': 'fresh-operation', 'status': 'accepted', 'replayed': False} - source = AsyncMock(side_effect=[failure, failure, receipt]) + source = AsyncMock(side_effect=[failure, replay_error, receipt]) accepted = AsyncMock(return_value={'submission_id': 'submission'}) with patch.object(runtime, '_trial_operation_ids', new=AsyncMock(side_effect=[set(), {'failed-operation'}, {'failed-operation'}, {'failed-operation', 'fresh-operation'}])), \ @@ -1198,9 +1205,11 @@ async def snapshot(self): def test_remote_first_pre_preserves_known_failure_replay_and_real_t5_observer(self): self.exercise() for fault, message in (('omit_delete', 'lacks deletion'), - ('replay_allocates', 'same-key failure replay changed custody'), + ('replay_allocates', 'same-key replay allocated a native machine'), ('wrong_image', 'failed PRE lost exact selected image'), - ('wrong_source', 'changed its exact PRE')): + ('wrong_source', 'changed its exact PRE'), + ('wrong_replay_field', 'same-key public failure fields changed'), + ('bad_replay_correlation', 'same-key public failure fields changed')): with self.subTest(fault=fault), self.assertRaisesRegex(RuntimeError, message): self.exercise(**{fault: True}) From 65a176a69b9994597d47ca8c8257a4133314e874 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 19:57:48 +0100 Subject: [PATCH 337/513] Correct documented backend lane count after shard split --- docs/operations_backend_testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/operations_backend_testing.md b/docs/operations_backend_testing.md index 9941b8cd8..7e21de63a 100644 --- a/docs/operations_backend_testing.md +++ b/docs/operations_backend_testing.md @@ -273,7 +273,7 @@ SHA, lane and numeric run attempt, containing its manifest, lane evidence, isolation record, and coverage data. On complete runs, the `full-suite` job runs with a fail-closed dependency guard, downloads available diagnostic bundles, then rejects any failed, cancelled, or skipped matrix result before -fan-in. Fan-in selects the highest numeric attempt available for each of the sixteen declared +fan-in. Fan-in selects the highest numeric attempt available for each of the 23 declared lanes from separately downloaded artifact directories. It rejects malformed, foreign or future attempt names and never falls back from an incomplete or corrupt latest bundle to an older passing one. For the selected bundles it From cceaae90c0fc185dda7c14e921b5332d5e5c5c15 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 20:06:38 +0100 Subject: [PATCH 338/513] Bind native PRE proof to locked selection --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 25 +++++++++++ .../public_intake_trials.py | 12 +++++- .../public_runtime_trials.py | 34 +++++++++++++++ scripts/test_public_hosted_attachment.py | 41 ++++++++++++++++--- 4 files changed, 105 insertions(+), 7 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 67b3b67ca..6e18ad2ab 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10694,3 +10694,28 @@ message and malformed correlation cases fail. The entire affected hosted attachment module passes `39 passed, 76 subtests passed`; Ruff lint and diff checks pass. A fifth connected run is still needed for same-key custody, fresh-key accepted T5 and complete end-to-end cleanup proof. + +The fifth isolated run used clean `df766fe63b043cae686586373421ba153c735ac7`. +The initial public 503 and exact failed PRE/source binding passed. The same-key +public 503 preserved stable error fields, selected PRE ID/digest, the singleton +source operation and the native trace cursor. A fresh key then returned public +202 and a second native VM ran through project execution: the independent +snapshot has two create/start/delete sequences, one `prepare_completed` and +one `exec`. The trial stopped before accepted T5 because its shared PRE helper +expected the synthetic `project.pre_submit` requirement, while this locked +incident-summary policy selects `terminal.pre.incident_summary_layout`. The +fresh result was not retained before isolated DB teardown, so the precise +failed helper conjunct is inferred from code and requires replay. Database and +MinIO cleanup completed; the operator restoration receipt confirms original +checker config, empty owned resources and exact foreign process removal. + +The helper now derives its expected requirement, registry ID/digest and native +image digest from the independently locked selected request policy. It still +requires eligible defaults, one ordered project member, the expected verdict, +request digest and Smol isolation. A private 0600 diagnostic stores only fresh +selection, policy and outcome identifiers before that assertion, so a future +failure is observable without retaining source bytes or credentials. An +incident-summary requirement positive and foreign selection/image negatives +pass; the full affected hosted attachment module passes +`40 passed, 78 subtests passed`, with Ruff lint and diff checks. A sixth +connected run must still prove fresh-key T5 and final cleanup. diff --git a/experiments/pilot04_external_checker_runtime/public_intake_trials.py b/experiments/pilot04_external_checker_runtime/public_intake_trials.py index 0cd6f47c2..d33b24243 100644 --- a/experiments/pilot04_external_checker_runtime/public_intake_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_intake_trials.py @@ -101,12 +101,20 @@ def _assert_current_pre(row, *, failure=None): and failed == ['high_confidence_secret_detected'] and members == [], 'default blocker reached project execution or lost exact feedback') return + entries = row.request_json['policy']['entries'] + _require(len(entries) == 1 and entries[0]['stage'] == 'pre_submit', + 'current PRE lost its exact locked project selection') + selected = entries[0] + registry = selected['registry'] _require(value['workstream_default']['eligible'] and value['eligible'] is (failure is None) and len(members) == 1 and members[0]['order'] == 0 - and members[0]['requirement_id'] == 'project.pre_submit', + and members[0]['requirement_id'] == selected['requirement_id'], 'one-project PRE lost its default-before-project boundary') member = members[0] - _require(member['result']['verdict'] == ('failed' if failure else 'passed') + _require(member['registry_entry_id'] == registry['registry_entry_id'] + and member['registry_entry_digest'] == registry['entry_digest'] + and member['isolation']['platform_manifest_digest'] == registry['image_digest'] + and member['result']['verdict'] == ('failed' if failure else 'passed') and member['result']['request_digest'] == member['request_digest'] and member['isolation']['runtime'] == 'smolvm' and member['isolation']['isolation_mode'] == 'smol-microvm', diff --git a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py index 4e0bd0118..21308ca88 100644 --- a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py @@ -120,6 +120,38 @@ def stable(value): return left is not None and left == right +def _retain_fresh_pre(path, row, receipt): + """Keep bounded selection and outcome facts before the recovery assertion.""" + entries = row.request_json.get('policy', {}).get('entries', []) + execution = row.terminal_json.get('execution') or {} + members = execution.get('external_members', []) + observation = { + 'receipt': {key: receipt.get(key) for key in ('operation_id', 'status', 'replayed')}, + 'selected': {'id': str(row.id), 'status': row.status, + 'source_operation_id': row.source_operation_id, + 'terminal_digest': row.terminal_digest}, + 'policy': [{'requirement_id': entry.get('requirement_id'), 'stage': entry.get('stage'), + 'registry_entry_id': entry.get('registry', {}).get('registry_entry_id'), + 'registry_entry_digest': entry.get('registry', {}).get('entry_digest'), + 'image_digest': entry.get('registry', {}).get('image_digest')} + for entry in entries], + 'execution': {'eligible': execution.get('eligible'), + 'required_external_count': execution.get('required_external_count'), + 'default_eligible': execution.get('workstream_default', {}).get('eligible'), + 'members': [{'order': member.get('order'), + 'requirement_id': member.get('requirement_id'), + 'registry_entry_id': member.get('registry_entry_id'), + 'registry_entry_digest': member.get('registry_entry_digest'), + 'verdict': member.get('result', {}).get('verdict'), + 'runtime': member.get('isolation', {}).get('runtime'), + 'platform_manifest_digest': member.get('isolation', {}).get('platform_manifest_digest')} + for member in members]}, + } + with path.open('x', encoding='utf-8') as stream: + path.chmod(0o600) + json.dump(observation, stream, sort_keys=True) + + async def _runner_drained(runner): observed = await runner.command('drained') result = observed['result'] @@ -204,6 +236,8 @@ async def _remote_pre_launch_failure(client, factory, *, task, assignment, token fresh_key = str(uuid4()) receipt = await _source_request(client, route, headers, token, fresh_key, archive, 202) fresh = await _selected(factory, fresh_key) + if first_response_path is not None: + _retain_fresh_pre(first_response_path.with_name('remote-pre-launch-fresh-pre.json'), fresh, receipt) _assert_current_pre(fresh) _require(fresh.id != row.id and fresh.source_operation_id == receipt['operation_id'] and fresh.request_json['policy']['entries'][0]['registry']['image_digest'] diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index e52cc1739..164cbac47 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -634,13 +634,20 @@ async def retry(*args): def test_source_pre_retains_default_stop_and_exact_one_native_member(self): from experiments.pilot04_external_checker_runtime.public_intake_trials import _assert_current_pre - member = {'order': 0, 'requirement_id': 'project.pre_submit', 'request_digest': 'request', + requirement = 'terminal.pre.incident_summary_layout' + registry = {'registry_entry_id': 'locked-entry', 'entry_digest': 'locked-digest', + 'image_digest': 'sha256:' + 'a' * 64} + member = {'order': 0, 'requirement_id': requirement, 'registry_entry_id': 'locked-entry', + 'registry_entry_digest': 'locked-digest', 'request_digest': 'request', 'result': {'verdict': 'passed', 'request_digest': 'request', 'findings': []}, - 'isolation': {'runtime': 'smolvm', 'isolation_mode': 'smol-microvm'}} + 'isolation': {'runtime': 'smolvm', 'isolation_mode': 'smol-microvm', + 'platform_manifest_digest': registry['image_digest']}} execution = {'required_external_count': 1, 'eligible': True, 'workstream_default': {'eligible': True, 'checks': []}, 'external_members': [member]} def row(value): - return SimpleNamespace(status='completed', terminal_json={'execution': value}) + return SimpleNamespace(status='completed', terminal_json={'execution': value}, + request_json={'policy': {'entries': [{'stage': 'pre_submit', + 'requirement_id': requirement, 'registry': registry}]}}) _assert_current_pre(row(execution)) secret = copy.deepcopy(execution) @@ -656,11 +663,21 @@ def row(value): invalid[field] = value with self.subTest(field=field), self.assertRaises(RuntimeError): _assert_current_pre(row(invalid)) - for field, value in (('order', 1), ('requirement_id', 'foreign'), ('request_digest', 'foreign')): + for field, value in (('order', 1), ('requirement_id', 'foreign'), + ('registry_entry_id', 'foreign'), ('registry_entry_digest', 'foreign'), + ('request_digest', 'foreign')): invalid = copy.deepcopy(execution) invalid['external_members'][0][field] = value with self.subTest(field=field), self.assertRaises(RuntimeError): _assert_current_pre(row(invalid)) + invalid = copy.deepcopy(execution) + invalid['external_members'][0]['isolation']['platform_manifest_digest'] = 'sha256:' + 'b' * 64 + with self.assertRaisesRegex(RuntimeError, 'exact native request/result custody'): + _assert_current_pre(row(invalid)) + selected = row(execution) + selected.request_json['policy']['entries'][0]['requirement_id'] = 'foreign' + with self.assertRaisesRegex(RuntimeError, 'default-before-project boundary'): + _assert_current_pre(selected) secret['external_members'] = [member] with self.assertRaisesRegex(RuntimeError, 'default blocker'): _assert_current_pre(row(secret), failure='secret') @@ -1164,7 +1181,10 @@ async def snapshot(self): status='infrastructure_failed', terminal_json={'execution': None, 'infrastructure_failure_code': 'implementation_unavailable', 'reservation': {'source': {'location': {'operation_id': 'failed-operation'}}}}) - fresh_row = SimpleNamespace(id='fresh-pre', source_operation_id='fresh-operation', request_json=request) + fresh_row = SimpleNamespace(id='fresh-pre', source_operation_id='fresh-operation', request_json=request, + status='completed', terminal_digest='fresh-digest', terminal_json={'execution': { + 'eligible': True, 'required_external_count': 1, + 'workstream_default': {'eligible': True}, 'external_members': []}}) operation = SimpleNamespace(id='failed-operation', selected_pre_submit_run_id=None) failure = {'error': {'code': 'submission_infrastructure_unavailable', 'message': 'submission_infrastructure_unavailable', 'details': {}, @@ -1227,6 +1247,17 @@ def test_first_response_is_retained_before_native_count_refusal(self): self.assertEqual(body['runtime_event_count'], 0) self.assertEqual(path.stat().st_mode & 0o777, 0o600) + def test_fresh_pre_selection_is_retained_before_recovery_assertions(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'first-response.json' + self.exercise(first_response_path=path) + fresh = path.with_name('remote-pre-launch-fresh-pre.json') + body = json.loads(fresh.read_text()) + self.assertEqual(body['receipt']['operation_id'], 'fresh-operation') + self.assertEqual(body['selected']['source_operation_id'], 'fresh-operation') + self.assertTrue(body['execution']['eligible']) + self.assertEqual(fresh.stat().st_mode & 0o777, 0o600) + def test_partial_owned_worker_pause_failure_still_restores_worker(self): from experiments.pilot04_external_checker_runtime import public_runtime_trials as runtime def failed_pause(): From bd9765804e26cad7163d7ad1e91d4cb6a9644d4c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 20:20:45 +0100 Subject: [PATCH 339/513] Reconcile identifier tests with referenced intake identities --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 32 +++++++++++++++++++ backend/tests/test_identifier_schema.py | 13 +++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 6e18ad2ab..172f17b87 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10719,3 +10719,35 @@ incident-summary requirement positive and foreign selection/image negatives pass; the full affected hosted attachment module passes `40 passed, 78 subtests passed`, with Ruff lint and diff checks. A sixth connected run must still prove fresh-key T5 and final cleanup. + + +### Identifier metadata contract reconciliation + +Intent: repair the two exact identifier-metadata failures from shared shard H +without changing persisted identities or owner-local Python representations. +Allowed files: `backend/tests/test_identifier_schema.py` and this record. +No product/model/migration changes or removal of UUIDv7 guards are authorized +by this bounded change. Cleanup claims reuse the intake operation foreign key +as their primary key; they do not generate a second identity. The sole current +foreign-key representation difference is intake.finalization_event_id (string) +to outbox.event_id (UUID), both native PostgreSQL UUID. AGENTS.md explicitly +preserves owner-local string/UUID boundaries. +Acceptance: classify the exact cleanup-claim natural key and compare relational +PostgreSQL UUID types, retaining every generated-key version/variant assertion. +Verification: complete identifier metadata module, current metadata inventory, +diff check and scoped architecture review; existing real T4/T5 proofs cover the +unchanged runtime conversion boundary. Risk is test-contract interpretation; +review focuses on preserving native types and distinguishing generated from +referenced identities. No new deployment or full-suite claim follows. + +Scoped ARCH review independently confirmed the cleanup key is already classified +in `backend/scripts/identifier_inventory.py`, migration 0073 uses native UUID, +and the acceptance owner deliberately stores `str(outbox.append(...).event_id)`. +Apply only the exact ART-to-OUTBOX representation exception and assert its +False/True Python mapping plus identical PostgreSQL UUID types; retain generic +representation equality for every other relationship. + +Verification: all five identifier metadata tests passed in 0.61 seconds; pinned +Ruff and diff checks passed. ARCH inspected the final exact exception and found +no further scoped issue. Metadata inventory confirms this is the sole current +representation difference and cleanup claims the sole omitted referenced key. diff --git a/backend/tests/test_identifier_schema.py b/backend/tests/test_identifier_schema.py index 63f682390..2a6e43ef5 100644 --- a/backend/tests/test_identifier_schema.py +++ b/backend/tests/test_identifier_schema.py @@ -11,6 +11,7 @@ NATURAL_PRIMARY_KEYS = { "submission_source_capacity_profiles": ("namespace_id",), "submission_source_charges": ("operation_id",), + "submission_source_cleanup_claims": ("operation_id",), "submission_source_upload_receipts": ("operation_id",), "submission_dispatches": ("submission_id",), "submission_binding_receipts": ("admission_id",), @@ -60,7 +61,17 @@ def test_every_relational_uuid_reference_uses_the_same_native_type(): continue local = reference.parent.type assert isinstance(local, Uuid) and local.native_uuid, str(reference) - assert local.as_uuid == reference.column.type.as_uuid, str(reference) + boundary = (table.name, reference.parent.name, + reference.column.table.name, reference.column.name) + if boundary == ("submission_intake_operations", "finalization_event_id", + "outbox_events", "event_id"): + # ART retains string selectors; OUTBOX owns UUID objects. Their + # persisted relation is the same native PostgreSQL UUID type. + assert local.as_uuid is False and reference.column.type.as_uuid is True + assert str(local.compile(dialect=postgresql.dialect())) == "UUID" + assert str(reference.column.type.compile(dialect=postgresql.dialect())) == "UUID" + else: + assert local.as_uuid == reference.column.type.as_uuid, str(reference) checked += 1 assert checked > 0 From de768dc11d37685573081db98450546a3878337f Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 20:23:23 +0100 Subject: [PATCH 340/513] test: align current intake authority fixtures and public contracts --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 98 +++++++++++++++++++ ...est_submission_finalization_worker_loss.py | 5 +- .../test_admin_reads_postgresql.py | 2 +- .../test_grant_reads_postgresql.py | 2 +- .../pre_submit/test_contracts.py | 25 +---- .../setup_finalization/test_catalogue.py | 4 + .../setup_finalization/test_structure.py | 18 +++- .../task_authority/test_public_surface.py | 3 +- .../task_authority/test_task_commands.py | 2 +- docs/spec_authorization_service.md | 2 + 10 files changed, 132 insertions(+), 29 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 172f17b87..072a22ae0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10751,3 +10751,101 @@ Verification: all five identifier metadata tests passed in 0.61 seconds; pinned Ruff and diff checks passed. ARCH inspected the final exact exception and found no further scoped issue. Metadata inventory confirms this is the sole current representation difference and cleanup claims the sole omitted referenced key. + +### First fresh shared-lane CI fixture corrections (2026-11-24) + +Intent: run45465160851 for PRhead65a176a69 executes mergeac81fefb7987569ba15414bb8130bf1433a52a1a. +Its shared_foundations_i artifact14953584341 reports3failed/706passed in410.89s, +709/709 completed, zero skips/deselections, schema0091 and complete DB/MinIO +cleanup. New immediate failure blocks expose exact causes. Allowed scope only +the broker finalizer fixture, exact active-action test inventory, client packet +refusal oracle, and this record. No production/config defaults, authorization +policy, timeout, skip, selection or completeness gate changes. + +The real broker helper imports the production Celery app before configuring its +explicit test broker; cold CI has no production broker setting. Bind the existing +required WORKSTREAM_TEST_BROKER_URL before import, clear settings cache, retain +real isolated endpoint/prefix/prefork worker and all outage/duplicate assertions. +Exact catalogue expectation must include the four activated source cleanup, +accepted finalization, PM operation-read and gate-repair actions. The empty JSON +packet reaches current ART input refusal submission_packet_invalid, while full +and forged old packets retain invalid_request; preserve status, complete state +snapshot and foreign/concealment assertions. + +Acceptance: focused exact catalogue check and actual four PG cases (real broker +plus all three packet variants), cold broker configuration with no ambient +production URL, no public/runtime change, Ruff/structure/record/diff checks. Risk +is test-fixture/contract custody; QA/CI review checks meaningful exact refusal +and retained durable graph assertions. Human focus is unchanged production +guards and exact approved inventory. Full CI remains running; no full-head or +provider/native completion claim. Roadmap capability claims unchanged. + +Scope extension from the next exact CI failure: shared_d completed1failed/739passed +in523.97s. Its pre_submit/test_contracts.py shared reservation still constructs +retired prepared fields before reaching decision/audit/parser assertions. Port +only that fixture to the existing current _source_reservation and supply required +source contracts to dataclass replacement; all assertions and substitutions stay. +No production compatibility or new source fixture. Exercise the complete pure +contract module so failures in other shards from the same cause are covered. + +The full pure PRE contract module also requires explicit invocation_receipt=None +for its existing no-runtime infrastructure finalization; no synthetic provider +receipt is introduced. All parser/digest/phase/audit assertions remain. Next +shared_f failure is exact admin permission surface94 versus current95. Extend +allowed scope to that one cardinality oracle after canonical catalogue inspection; +retain HTTP200, exact total/items equality and every role/grant isolation check. + +Fresh A/E reports confirm the same packet refusal for all three JSON variants; +use exact submission_packet_invalid throughout, retaining all no-mutation and +concealment assertions. A second admin permission oracle has the same94->95 +canonical correction. Extend scoped files to that existing parameter value. +ART custody documentation test needs only the two current action/permission +rows missing from spec_authorization_service.md; both independent custody +tables and their historical counts already pass and remain unchanged. + +The setup-finalization reachability test fails on unrelated accepted-submission +worker topology symbols sharing the word finalization, not an authority path. +Extend only that test file: allow exact topology constant/module/process-role +symbols on exact outbox/celery_app/outbox_topology paths. Preserve the generic +rejection of every other finalization import/call, exact project_setup authority +exception, and no direct finalize invocation. Extend existing four aliased setup +authority mutations across all four affected worker paths; no whole-file bypass. + +Shared_g exposes a second PRE test from the same repaired fixture and an obsolete +public201 assertion. Extend only task_authority/test_public_surface.py: require +current202 and exact sole application/zip content; preserve authentication/action +metadata, forbidden self-activation/start routes, required body and all claim +key/UUID/closed-DTO limits. No mounted route or schema change. + +Final scoped evidence: exact pure batch33passed in41.60s +(/tmp/submission-fresh-ci-pure-batch-v2.log): current PRE source/phase/digest/audit +contracts, exact active action inventory, both ART custody documents, exact +worker-path topology exceptions with sixteen aliased authority mutants, and +public202/soleZIP schema. The initial pure fixture replay exposed missing required +invocation_receipt; explicitNone fixed the no-runtime branch. No original +assertion was removed. Canonical permission IDs are exactly95. + +Cold composition probe removes ambient production broker configuration. Omitting +only before-import binding reproduces exact CeleryConfigurationError; final +fixture reaches the public acceptance boundary then intentionally stops, cleaning +its owned endpoint/queue/Redis connection (/tmp/submission-cold-broker-before-v2 +.log and -after-v2.log). An initial standalone probe missed pytest's test import +path and is excluded from behavior proof. This proves import configuration, not +new worker/broker recovery behavior; existing integration remains required and +is coordinated with the separate scanner isolation repair. No expensive child +death cases were repeated. + +Five actual PG cases passed102.36s: all three client packet JSON refusals, admin +permission catalogue, and auditor permission read. Each retains its snapshot, +identity, confidentiality, audit and exact total/item assertions. Receipt +/tmp/submission-fresh-ci-packet-admin.json records launcher65a176a69 with final +modified test bytes, schema0091 and all database/MinIO cleanup true; this is +precommit execution, not clean-commit or complete-head qualification. + +Full unchanged structural validator exits0 +(/tmp/submission-fresh-ci-structure.log); Ruff and whitespace pass. No production +file, policy, ledger, provider guard, workflow or test budget changed. The two +identifier-schema failures from shared_h are separately routed to root/ARCH and +are not claimed fixed here. Remaining lanes are still being observed. Historical +shared receipts prove completed tests/cleanup and newly retained failure details; +they do not turn failing CI green or qualify the full submission goal. diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py index 8d299d5e5..888b8b16e 100644 --- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -307,10 +307,13 @@ async def _public_broker_case(f, tmp_path, monkeypatch, *, kill_at=None): from urllib.parse import urlsplit import redis from app.core.identifiers import new_record_id - from app.workers import outbox as worker + from app.core.config import get_settings broker = urlsplit(os.environ["WORKSTREAM_TEST_BROKER_URL"]) assert broker.scheme == "redis" and broker.hostname and broker.port + monkeypatch.setenv("WORKSTREAM_CELERY_BROKER_URL", broker.geturl()) + get_settings.cache_clear() + from app.workers import outbox as worker case = SimpleNamespace(connection=redis.Redis.from_url(broker.geturl(), socket_timeout=2), prefix=f"finalizer-proof-{new_record_id()}:", hostname=f"finalizer-{new_record_id()}@localhost", endpoint=socket.socket(), proxy=None, connections=set(), process=None, diff --git a/backend/tests/authorization/admin_access/test_admin_reads_postgresql.py b/backend/tests/authorization/admin_access/test_admin_reads_postgresql.py index 32a3a838a..d8ad8b3ca 100644 --- a/backend/tests/authorization/admin_access/test_admin_reads_postgresql.py +++ b/backend/tests/authorization/admin_access/test_admin_reads_postgresql.py @@ -183,7 +183,7 @@ async def test_missing_admin_target_has_concealed_response_and_no_success_effect assert await authority_snapshot() == before -@pytest.mark.parametrize("surface,total", [("permissions", 94), ("admin-role-definitions", 5)]) +@pytest.mark.parametrize("surface,total", [("permissions", 95), ("admin-role-definitions", 5)]) async def test_admin_catalogue_read_returns_public_definitions( admin_access: AdminAccess, surface: str, diff --git a/backend/tests/authorization/admin_access/test_grant_reads_postgresql.py b/backend/tests/authorization/admin_access/test_grant_reads_postgresql.py index 63e26171e..21f2bfc3a 100644 --- a/backend/tests/authorization/admin_access/test_grant_reads_postgresql.py +++ b/backend/tests/authorization/admin_access/test_grant_reads_postgresql.py @@ -92,7 +92,7 @@ async def test_system_auditor_has_exact_read_surface( assert response.status_code == 200, response.text body = response.json() if surface in {"permissions", "definitions"}: - assert body["total"] == len(body["items"]) == (94 if surface == "permissions" else 5) + assert body["total"] == len(body["items"]) == (95 if surface == "permissions" else 5) elif surface in {"list", "history"}: expected = {grant_id, access.bootstrap_grant_id} if surface == "list" else {grant_id} assert body["total"] == len(expected) diff --git a/backend/tests/authorization/pre_submit/test_contracts.py b/backend/tests/authorization/pre_submit/test_contracts.py index 23e0e1f1d..062846000 100644 --- a/backend/tests/authorization/pre_submit/test_contracts.py +++ b/backend/tests/authorization/pre_submit/test_contracts.py @@ -32,9 +32,6 @@ from app.modules.authorization.domain.action_groups import CONTEXT_DIGEST_ACTIONS from app.modules.authorization.domain.resource_digest import authorization_resource_digest from app.modules.authorization.runtime import PreparedAuthorizationHandleInvalid -from app.modules.checkers.api.default_checker import ( - WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, -) from app.modules.checkers.api.selected_pre_submit import ( SelectedPreSubmitExecuteFacts, SelectedPreSubmitFinalizeFacts, @@ -44,24 +41,8 @@ def _reservation() -> SelectedPreSubmitReservationFacts: - return SelectedPreSubmitReservationFacts( - actor_profile_id=new_record_id(), - identity_link_id=new_record_id(), - project_id=new_record_id(), - task_id=new_record_id(), - assignment_id=new_record_id(), - attempt_id=new_record_id(), - idempotency_key=new_record_id(), - attempt_request_digest="sha256:" + "0" * 64, - prepared_generation_id=new_record_id(), - policy_sha256="sha256:" + "1" * 64, - default_behavior_sha256=WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, - default_input_sha256="sha256:" + "2" * 64, - archive_sha256="sha256:" + "3" * 64, - archive_byte_count=100, - semantic_manifest_sha256="sha256:" + "4" * 64, - execution_budget_ms=60_000, - source_contracts=selected_pre_submit_source_contracts()) + from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation + return _source_reservation() def _execute() -> SelectedPreSubmitExecuteFacts: @@ -149,6 +130,7 @@ def test_selected_pre_finalize_and_prepare_parser_are_closed() -> None: final = SelectedPreSubmitFinalizeFacts( lease=execute.lease, execution=None, + invocation_receipt=None, infrastructure_failure_code="deadline_exceeded", source_contracts=selected_pre_submit_source_contracts()) resource = pre_submit_resource(FINALIZE, final) @@ -170,6 +152,7 @@ def test_selected_pre_finalize_and_prepare_parser_are_closed() -> None: changed = replace( execute.lease.reservation, attempt_id=new_record_id(), + source_contracts=selected_pre_submit_source_contracts(), ) assert not pre_submit_prepare_matches( FINALIZE, pre_submit_prepare_values(changed), resource diff --git a/backend/tests/authorization/setup_finalization/test_catalogue.py b/backend/tests/authorization/setup_finalization/test_catalogue.py index 2e8c0b752..7c3913019 100644 --- a/backend/tests/authorization/setup_finalization/test_catalogue.py +++ b/backend/tests/authorization/setup_finalization/test_catalogue.py @@ -45,6 +45,10 @@ ActionId.PROJECT_MODEL_CALL_RECOVERY_CHILD_AUTHORIZE, ActionId.ARTIFACT_CHECKER_OUTPUT_WRITE, ActionId.ARTIFACT_CHECKER_OUTPUT_BINDING_CREATE, + ActionId.ARTIFACT_SOURCE_CLEANUP, + ActionId.ARTIFACT_SUBMISSION_FINALIZE, + ActionId.PROJECT_TASK_SUBMISSION_OPERATION_READ, + ActionId.OPERATIONS_SUBMISSION_GATE_REPAIR, ActionId.PROJECT_TASK_IMPORT, ActionId.PROJECT_TASK_IMPORT_BATCH_READ, ActionId.CONTRIBUTION_READ_SELF, ActionId.CONTRIBUTION_READ_PROJECT, diff --git a/backend/tests/authorization/setup_finalization/test_structure.py b/backend/tests/authorization/setup_finalization/test_structure.py index 60f31daec..10ed81e58 100644 --- a/backend/tests/authorization/setup_finalization/test_structure.py +++ b/backend/tests/authorization/setup_finalization/test_structure.py @@ -20,7 +20,18 @@ def assert_no_live_finalization(paths): if path == ROOT / "app/workers/project_setup.py": assert "setup_finalization_authorization" in imports imports.remove("setup_finalization_authorization") - assert not any("finalization" in name.lower() for name in imports | calls) + topology = { + ROOT / "app/workers/outbox.py": {"FINALIZATION_HARD_LIMIT_SECONDS"}, + ROOT / "app/workers/celery_app.py": { + "FINALIZATION_DELIVERY_TASK", "FINALIZATION_QUEUE", "is_finalization_worker_process", + }, + ROOT / "app/workers/outbox_topology.py": { + "SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS", + "app.modules.artifacts.api.submission_finalization", + }, + } + assert not any("finalization" in name.lower() + for name in (imports | calls) - topology.get(path, set())) assert "finalize" not in calls @@ -117,11 +128,12 @@ def test_finalization_partition_additions_are_exact_and_fail_closed(): "from app.adapters.auth import setup_finalization_authorization\nordinary: object = setup_finalization_authorization\nordinary(session)\n", ], ) -def test_exact_worker_cannot_call_aliased_finalization_factory(tmp_path, monkeypatch, source): +@pytest.mark.parametrize("worker", ["project_setup", "outbox", "celery_app", "outbox_topology"]) +def test_exact_worker_cannot_call_aliased_finalization_factory(tmp_path, monkeypatch, source, worker): import sys monkeypatch.setattr(sys.modules[__name__], "ROOT", tmp_path) - path = tmp_path / "app/workers/project_setup.py" + path = tmp_path / f"app/workers/{worker}.py" path.parent.mkdir(parents=True) path.write_text(source) with pytest.raises(AssertionError): diff --git a/backend/tests/authorization/task_authority/test_public_surface.py b/backend/tests/authorization/task_authority/test_public_surface.py index fad2366a7..e889faf5e 100644 --- a/backend/tests/authorization/task_authority/test_public_surface.py +++ b/backend/tests/authorization/task_authority/test_public_surface.py @@ -14,8 +14,9 @@ def test_task_public_surface_has_no_self_activation_and_one_admission_creation() creation = submissions["post"] assert creation["security"] assert creation["x-workstream-action-id"] == "submission.create" - assert "201" in creation["responses"] + assert "202" in creation["responses"] assert creation["requestBody"]["required"] is True + assert set(creation["requestBody"]["content"]) == {"application/zip"} for path, method, action in ( ("/api/v1/tasks/{task_id}/claim", "post", "task.claim"), ("/api/v1/tasks/{task_id}/work-context", "get", "task.work_context.read"), diff --git a/backend/tests/authorization/task_authority/test_task_commands.py b/backend/tests/authorization/task_authority/test_task_commands.py index a48ab7e1a..d861357d2 100644 --- a/backend/tests/authorization/task_authority/test_task_commands.py +++ b/backend/tests/authorization/task_authority/test_task_commands.py @@ -48,7 +48,7 @@ async def test_client_owned_packet_cannot_mutate_an_authorized_assignment( f"/api/v1/tasks/{task['id']}/submissions", headers=auth_headers(), json=payload, ) assert response.status_code == 422, response.text - assert response.json()["error"]["code"] == "invalid_request" + assert response.json()["error"]["code"] == "submission_packet_invalid" assert await _read_task_contributor_race_snapshot(task_database_env, task["id"]) == before retained_read = await task_client.get( f"/api/v1/tasks/{task['id']}/submissions", headers=auth_headers(), diff --git a/docs/spec_authorization_service.md b/docs/spec_authorization_service.md index 5d3411bd1..eab27e4ca 100644 --- a/docs/spec_authorization_service.md +++ b/docs/spec_authorization_service.md @@ -696,6 +696,8 @@ remain planned and unavailable, and add no migration. | `artifact.guide_source.read` | `artifact.guide_source.read` | fixed guide-reader service | exact committed document version and fenced compilation attempt | `03` | | `artifact.submission_bundle.prepare` | `submission.create` | assigned contributor | exact task/admission context | `04C2` | | `artifact.submission.binding.create` | `artifact.binding.create` | fixed binding service | submission | `05` | +| `artifact.submission.finalize` | `artifact.binding.create` | fixed binding service | exact accepted source operation, acceptance receipt and current continuation lease; source-bound consumed admission | `WS-AUTH-001-ART-05` | +| `artifact.submission_source.cleanup` | `artifact.submission_source.cleanup` | fixed cleanup service | exact namespace, operation, retained charge and cleanup generation with provider-bound authorization | `WS-AUTH-001-ART-02D-INTERNAL` | | `artifact.checker_output.binding.create` | `artifact.binding.create` | fixed binding service | exact setup or POST paid model-call attempt, private request/response slot and verified content | `06B`, model runtime | | `artifact.verification.execute` | `artifact.verification.execute` | fixed verifier service | verification job | `02D` | | `artifact.pending_work.scan` | `artifact.pending_work.scan` | fixed scheduler service | system pending-work scope | `02D` | From 8afcf88c8da888d099bba7a4e848e84060390c11 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Tue, 24 Nov 2026 20:25:56 +0100 Subject: [PATCH 341/513] Record dedicated worker requirement and publication gap --- .commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index fc072b434..ef3ca6781 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -34,6 +34,12 @@ full-head qualification. ## Execution deployment decision The API/application server and microVM execution run on separate infrastructure. +Celery workload queues must also have dedicated workers: no worker consumes a +mixed queue list, and no catch-all worker handles unrelated workloads. Outbox +publication must remain available while POST execution is stopped or saturated; +it must not share the POST or submission-finalization consumer. The PRE6 drill +accepted a fresh source but exposed publication waiting behind the paused general +worker, so dedicated scanner delivery and the corresponding T5 proof remain open. The application instance is a verified t3.large; the dedicated always-on runner is an m7i.large with native KVM. App-origin mTLS health and native transport smoke receipts establish connectivity. V14 also proves the connected local API From 3334fa5660c56f2f2a9bc88de0867c92e39d031e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 07:24:46 +0100 Subject: [PATCH 342/513] test: prove managed PRE through public source finalization --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 72 +++++++ backend/scripts/test_lane_catalogue.py | 1 + .../test_submission_foreground_command.py | 5 +- .../test_submission_managed_execution.py | 180 ++++++++++++++++++ backend/tests/test_ci_lane_catalogue.py | 4 +- 5 files changed, 258 insertions(+), 4 deletions(-) create mode 100644 backend/tests/artifacts/test_submission_managed_execution.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 072a22ae0..f0371f7d0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10849,3 +10849,75 @@ identifier-schema failures from shared_h are separately routed to root/ARCH and are not claimed fixed here. Remaining lanes are still being observed. Historical shared receipts prove completed tests/cleanup and newly retained failure details; they do not turn failing CI green or qualify the full submission goal. + + +### A30 completed managed-style adapter substitution (2026-11-24) + +Intent: pure managed PRE receipt/processor failure tests do not prove completed +source-bound facts survive real public intake, SQL terminal custody, T4 and T5. +SQL0072 already validates managed runtime/deployment/provider-cleanup facts with +exact source/request/lease/profile/config binding; no provider/schema change is +needed. The guest PreSubmitWorker constructor intentionally accepts native +isolation only, so do not relabel a native result or weaken that worker. + +Allowed files exactly five: new tests/artifacts/test_submission_managed_execution.py; +existing tests/artifacts/test_submission_foreground_command.py test-only optional +typed external_execution injection; scripts/test_lane_catalogue.py exact shared +module addition; tests/test_ci_lane_catalogue.py independent shared fingerprint; +and this record. Reuse canonical inspector/manifest/default-input/derived-request +functions used by the trusted worker and its material reader, exact live source +grant drain/close, managed evidence from construction onward, existing signed +HTTP fixture and production OUTBOX/T5 helper. No product adapter, provider +registration, model, migration, native worker branch or compatibility path. + +Acceptance: public rawZIP202 with one managed PRE, exact persisted source/result +and public feedback binding; matched managed deployment/config/provider cleanup +receipt with no native binary/guest/journal/UID/path fields; no Submission at T4; +real T5 consumes exact source admission and creates one graph; replay before and +after T5 preserves accepted receipt without another PRE. Exact source bytes/hash +and canonical manifest/default semantics remain real. Existing default runtime +helper behavior unchanged. One focused PG case plus exact lane/structure/Ruff +checks; bounded forged managed deployment or source/result must be rejected. +Risk is test-adapter/SQL custody composition; QA/security review inspects those +bindings. Human focus is proof limits: controlled managed-style computation, not +a deployed managed provider, native isolation, full public journey or goal-ready +qualification. Current CI failure repair is already frozen25f81de8d; new work is +separate and does not alter its executed evidence. + +Evidence frozen on2026-11-26 from the executed2026-11-24 candidate, before the +separate submitter-journey delta. The single managed public case passed27.51s +(/tmp/submission-managed-public-v1.log). Its JSON receipt records launcher +25f81de8da24a3edcb2a9fbbb475b25906e720ea, schema0091 and complete database/MinIO +cleanup. Actual modified test bytes were present for that execution; this is +precommit evidence, not a clean-commit, current full-head or later-contract run. +No runtime was restarted after the pause. The saved structure session79926 +returned exit0; /tmp/submission-managed-structure.log is intentionally empty on +success, and no missing live-session outcome was inferred. + +The managed adapter uses the exact canonical archive inspector, semantic manifest, +default derivation/evaluator and project request constructors used by the trusted +worker. It constructs managed isolation/deployment and provider cleanup receipt +from outset, checks exact source bytes/hash, closes the actual grant and removes +its owned private temporary processing tree. The public test compares persisted +terminal/digest/receipt and every feedback result, rejects independently forged +managed deployment and source observations, proves T4 has no Submission, then +consumes the exact source admission through production OUTBOX/T5 owners. Exact +one Submission/dispatch/checker run/binding/POST event and stable pre/post-T5 +accepted-key replay remain asserted. + +The T5 helper invokes the real OUTBOX delivery and finalization owners; it is not +a live broker-consumer proof. Existing broker/child-loss qualification remains +separate. Existing [managed receipt and processor controls](../../../backend/tests/checkers/external/test_pre_invocation.py) +retain test_completed_worker_is_bound_to_provider_receipt, wrong selected factory, +wrong runtime family, received failure/cancellation and malformed/bounded receipt +refusal. This controlled provider fixture does not register a paid or deployed +managed provider, prove provider cleanup in a remote environment, or qualify +native isolation. No SQL/provider authorization check was relaxed. + +All59 catalogue tests passed4.68s (/tmp/submission-managed-catalogue.log). Exact +shared membership is277->278; removing only the managed module reproduces the +previous fingerprint. An isolated omission of that module is rejected by the +existing independent family guard. No existing module or lane owner moved. +Ruff/whitespace checks and unchanged structure passed. Root inspected the bounded +draft with no scoped code blocker; final clean content binding follows this +evidence-only append. Full goal/hosted CI qualification remains outside scope. diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 4a1f32a1d..57095557e 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -70,6 +70,7 @@ class TestLane: "tests/artifacts/test_submission_intake_progress.py", "tests/artifacts/test_submission_finalization_worker_loss.py", "tests/artifacts/test_submission_foreground_command.py", + "tests/artifacts/test_submission_managed_execution.py", "tests/authorization/post_submit/test_atomicity.py", "tests/authorization/post_submit/test_concurrency.py", "tests/authorization/post_submit/test_live_authority.py", diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py index 96751781c..e08a87e46 100644 --- a/backend/tests/artifacts/test_submission_foreground_command.py +++ b/backend/tests/artifacts/test_submission_foreground_command.py @@ -16,7 +16,7 @@ ) -async def configure_source_http(factory, client, tmp_path, monkeypatch, payload, outcome, *, project_findings=()): +async def configure_source_http(factory, client, tmp_path, monkeypatch, payload, outcome, *, project_findings=(), external_execution=None): """Bind signed HTTP to real intake owners and the controlled guest transport.""" from app.adapters import artifacts as composition from app.adapters.checkers import SelectedPreSubmitCheckerExecutionAdapter @@ -27,7 +27,8 @@ async def configure_source_http(factory, client, tmp_path, monkeypatch, payload, from tests.test_artifact_admission import _settings runtime_root = tmp_path / f"source-http-{new_record_id()}" runtime_root.mkdir() - runtime, errors = _source_runtime(payload, runtime_root, outcome, project_findings=project_findings) + runtime, errors = (_source_runtime(payload, runtime_root, outcome, project_findings=project_findings) + if external_execution is None else (external_execution, [])) calls, original = [], runtime.execute_pre async def execute(lease, grant): calls.append(lease.reservation.attempt_id) diff --git a/backend/tests/artifacts/test_submission_managed_execution.py b/backend/tests/artifacts/test_submission_managed_execution.py new file mode 100644 index 000000000..948ba0aab --- /dev/null +++ b/backend/tests/artifacts/test_submission_managed_execution.py @@ -0,0 +1,180 @@ +"""Controlled managed PRE through real public source custody, T4 and OUTBOX T5.""" + +from contextlib import aclosing +import hashlib +import json +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from uuid import UUID + +import pytest +from sqlalchemy import text +from workstream_external_services import ExternalServiceAdapterIdentity + +from app.adapters.artifacts import selected_pre_submit_source_contracts +from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_manifest import build_submission_manifest +from app.modules.artifacts.api.submission_preparation import public_pre_submission_results +from app.modules.artifacts.submission_archive import SubmissionArchiveInspector +from app.modules.checkers.api.default_checker import workstream_default_input_sha256 +from app.modules.checkers.api.external import make_external_checker_execution_result +from app.modules.checkers.api.selected_pre_submit import ( + ExternalPreSubmitManagedIsolationFacts, ExternalPreSubmitMemberFacts, + SelectedPreSubmitExecutionFacts, SelectedPreSubmitInvocationResult, + SelectedPreSubmitTerminalFacts, derive_selected_pre_submit_default_input, + derive_selected_pre_submit_input, +) +from app.modules.checkers.default_checker import evaluate_verified_archive +from tests.artifacts.test_submission_foreground_command import ( + admission_intake as admission_intake, admin_access as admin_access, + signed_access as signed_access, rsa_signing_material as rsa_signing_material, + auth_database_env as auth_database_env, clear_settings_cache as clear_settings_cache, + configure_source_http, +) +from tests.checkers.external.test_pre_invocation import receipt_body +from tests.retained_material_fixtures import finalize_retained_intake +from tests.test_artifact_admission import _local_store +from tests.test_trusted_intake import _archive, _WORKER + + +class ManagedExecution: + """Test-only provider uses canonical worker rules, never native observations.""" + + identity = ExternalServiceAdapterIdentity("external_checker_execution", "managed_test") + pre_runtime_provider = "managed" + + def __init__(self, payload, root): + self.payload, self.root = payload, root + self.calls, self.closed, self.cleaned = 0, False, False + + async def execute_pre(self, lease, grant): + self.calls += 1 + async with aclosing(grant.open_source(lease=lease)) as source: + data = b"".join([chunk async for chunk in source]) + self.closed = True + assert data == self.payload + assert len(data) == lease.reservation.source.raw_byte_count + assert "sha256:" + hashlib.sha256(data).hexdigest() == lease.reservation.source.raw_sha256 + with TemporaryDirectory(dir=self.root) as directory: + archive, workspace = Path(directory) / "source.zip", Path(directory) / "tree" + archive.write_bytes(data) + workspace.mkdir(mode=0o700) + inspector = SubmissionArchiveInspector(lease.reservation.runtime_profile.archive_limits) + with archive.open("rb") as stream: + inspection = inspector.inspect(stream) + manifest = build_submission_manifest(inspection) + args = dict(manifest_body=manifest.as_dict(), manifest_sha256=manifest.sha256, + source_contracts=selected_pre_submit_source_contracts()) + value = derive_selected_pre_submit_default_input(lease, **args) + with inspector._projected_tree(stream, workspace, expected=inspection) as tree: + default = evaluate_verified_archive(value, _WORKER._Material(tree)) + assert default.eligible + _, request = derive_selected_pre_submit_input(lease, **args) + selected = lease.reservation.policy.entries[0] + result = make_external_checker_execution_result( + request_digest=request.request_digest, registry_entry_id=selected.registry.registry_entry_id, + registry_entry_digest=selected.registry.entry_digest, phase="pre_submit", + outcome="completed", verdict="passed", findings=(), infrastructure_failure_code=None, + ) + body = receipt_body(lease, managed=True) + member = ExternalPreSubmitMemberFacts( + order=0, requirement_id=selected.requirement_id, + registry_entry_id=selected.registry.registry_entry_id, + registry_entry_digest=selected.registry.entry_digest, + request_digest=request.request_digest, result=result, + isolation=ExternalPreSubmitManagedIsolationFacts( + provider="managed", platform_manifest_digest=selected.registry.image_digest, + config_image_id=body["invocation"]["config_image_id"], + deployment_sha256=body["runtime"]["deployment_sha256"], + ), + ) + facts = SelectedPreSubmitExecutionFacts( + request_digest=lease.reservation.request_digest, lease_id=lease.lease_id, + lease_generation=lease.lease_generation, observed_source=lease.reservation.source, + manifest_body=manifest.as_dict(), manifest_sha256=manifest.sha256, + default_input_sha256=workstream_default_input_sha256(value), + policy_sha256=lease.reservation.policy_sha256, workstream_default=default, + required_external_count=1, external_members=(member,), eligible=True, + source_contracts=selected_pre_submit_source_contracts(), + ) + self.cleaned = not Path(directory).exists() + self.result = SelectedPreSubmitInvocationResult.from_canonical_body( + body | {"execution": facts.canonical_body()}, + source_contracts=selected_pre_submit_source_contracts(), + ) + self.lease = lease + return self.result + + +async def test_managed_completion_preserves_public_source_acceptance_and_finalization( + admission_intake, tmp_path, monkeypatch, +): + f, payload, key = admission_intake, _archive(), new_record_id() + runtime = ManagedExecution(payload, tmp_path) + client, settings, errors, calls = await configure_source_http( + f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "completed", + external_execution=runtime, + ) + url = f"/api/v1/tasks/{f.task}/submissions" + headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + "Idempotency-Key": str(key), "Content-Length": str(len(payload)), + } + first = await client.post(url, headers=headers, content=payload) + assert not errors, errors + assert first.status_code == 202, first.text + accepted, operation_id = first.json(), UUID(first.json()["operation_id"]) + assert runtime.calls == len(calls) == 1 and runtime.closed and runtime.cleaned + receipt = runtime.result.receipt.canonical_body() + assert receipt["runtime"]["provider"] == "managed" + assert set(receipt["runtime"]) == {"provider", "version", "deployment_sha256", "profile"} + assert set(receipt["cleanup"]) == {"obligation_id", "provider_receipt_sha256", "disposition"} + assert receipt["cleanup"]["disposition"] == "destroyed" + assert set(runtime.result.execution.external_members[0].isolation.__dataclass_fields__) == { + "provider", "platform_manifest_digest", "config_image_id", "deployment_sha256", + } + async with f.factory() as session: + row = (await session.execute(text("SELECT source_operation_id, terminal_json, terminal_digest " + "FROM selected_pre_submit_runs WHERE id=:id"), {"id": calls[0]})).one() + terminal = SelectedPreSubmitTerminalFacts.from_canonical_body( + row.terminal_json, source_contracts=selected_pre_submit_source_contracts(), + ) + assert row.source_operation_id == operation_id + assert terminal.terminal_digest == row.terminal_digest + assert terminal.execution == runtime.result.execution + assert terminal.invocation_receipt == runtime.result.receipt + assert public_pre_submission_results(terminal.execution) == accepted["pre_submission_results"] + assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": f.task}) == 0 + for changed in ("deployment", "source"): + forged = json.loads(json.dumps(runtime.result.canonical_body())) + if changed == "deployment": + forged["execution"]["external_members"][0]["isolation"]["deployment_sha256"] = "sha256:" + "f" * 64 + else: + forged["invocation"]["source_sha256"] = "sha256:" + "f" * 64 + with pytest.raises(ValueError): + SelectedPreSubmitInvocationResult.from_canonical_body( + forged, source_contracts=selected_pre_submit_source_contracts(), + ).validate_lease(runtime.lease, source_contracts=selected_pre_submit_source_contracts()) + before = await client.post(url, headers=headers, content=payload) + assert before.status_code == 202 and before.json() == dict(accepted, replayed=True), before.text + bootstrap, store = _local_store(settings, f.namespace) + try: + submission_id = await finalize_retained_intake(f.factory, SimpleNamespace( + operation_id=operation_id, settings=settings, store=store, namespace=f.namespace, + )) + finally: + bootstrap.close() + after = await client.post(url, headers=headers, content=payload) + assert after.status_code == 202 and after.json() == dict(accepted, replayed=True), after.text + assert runtime.calls == len(calls) == 1 + async with f.factory() as session: + admission = (await session.execute(text("SELECT status, source_operation_id FROM " + "submission_bundle_admissions WHERE consumed_by_submission_id=:id"), {"id": submission_id})).one() + assert (admission.status, admission.source_operation_id) == ("consumed", operation_id) + for table in ("submissions", "submission_dispatches", "checker_runs"): + assert await session.scalar(text(f"SELECT count(*) FROM {table} WHERE task_id=:id"), {"id": f.task}) == 1 + assert await session.scalar(text("SELECT count(*) FROM artifact_bindings WHERE resource_id=:id"), + {"id": submission_id}) == 1 + assert await session.scalar(text("SELECT count(*) FROM outbox_events WHERE project_id=:id " + "AND event_type='PostSubmissionEvaluationRequested'"), {"id": f.project}) == 1 diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 0fcb8de61..287b0d664 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -325,8 +325,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None: """A catalogue-internal move across semantic families must fail this contract.""" expected = { "shared": ( - 277, - "7d5683912037886633519322314c8fdc3c89855dc2408b2ffc629c842e3ad8fc", + 278, + "ea3aaefe0250b88bfd4592ed63312000476b0a8a6da9622c59ddc3422788f5b6", ), "project": ( 258, From db4f0a92cb0221fb56842a1110f0b69220210d5e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 07:44:59 +0100 Subject: [PATCH 343/513] Isolate Celery workloads and outbox publication --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 53 +++++++ backend/app/workers/celery_app.py | 73 +++++++--- backend/app/workers/outbox.py | 11 +- backend/app/workers/outbox_topology.py | 38 ++++- backend/app/workers/project_setup_topology.py | 4 +- .../app/workers/source_cleanup_topology.py | 35 ++++- ...est_submission_finalization_worker_loss.py | 107 +++++++++++++- .../tests/outbox/test_delivery_topology.py | 116 ++++++++++++++- .../tests/outbox/test_recovery_postgresql.py | 1 + .../tests/outbox/test_worker_postgresql.py | 1 + cli/tests/journey/runtime.py | 36 ++--- deploy/hosted/README.md | 7 +- deploy/hosted/compose.inference.yml | 11 ++ deploy/hosted/compose.yml | 95 ++++++++++++- deploy/hosted/preflight.py | 133 ++++++++++++------ docker-compose.agent-loop.yml | 13 ++ docker-compose.yml | 105 +++++++++++++- docs/engineering/developer-setup.md | 8 +- scripts/test_hosted_release_config.py | 52 ++++++- scripts/test_local_guide_runtime.py | 12 +- 20 files changed, 793 insertions(+), 118 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f0371f7d0..28d3831c2 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10921,3 +10921,56 @@ existing independent family guard. No existing module or lane owner moved. Ruff/whitespace checks and unchanged structure passed. Root inspected the bounded draft with no scoped code blocker; final clean content binding follows this evidence-only append. Full goal/hosted CI qualification remains outside scope. + +### Dedicated worker queues and durable outbox publication + +PRE6 proved the public native launch failure, same-key failed replay, and fresh +accepted PRE source, then timed out before T5. A read-only isolated database +observation found the accepted operation still `finalization_pending` and its +`SubmissionFinalizationRequested` event `pending` with zero delivery attempts. +The general worker had been stopped for the trial; Beat scheduled the outbox +scan on its default `celery` queue, which that same worker consumed. Hosted +general workers also shared guide work and POST effects at concurrency one, +so a long effect could delay publication. The PRE6 isolated database/MinIO +cleanup and runner restoration completed; this is a partial diagnostic, not +a completed public journey. + +The bounded repair assigns all fifteen registered application tasks to seven +fixed workload queues: guide compilation, project control, artifact work, +outbox scanning, generic POST effects, submission finalization, and source +cleanup. Each queue has one dedicated prefork service in hosted and local +composition and the public journey launcher. Outbox scanning uses its own +DB-and-broker hosted worker and a sixty-second hard limit for each one-hundred +candidate page. Existing sixty-second Beat scheduling reselects still-pending +events after a failed or killed publication; generic effects remain on the +outbox delivery queue and finalization remains exclusive. A closed route map +refuses unknown task names; the worker start and task boundary refuse mixed +queues or delivery to a foreign role before owner work. The model proxy socket +follows POST delivery to its new worker. No provider, authorization, schema, +public contract, or native runner behavior changes are in this repair. Existing +cloned local/hosted worker mounts retain their prior permissions; queue +isolation is a scheduling and execution claim, not a new least-privilege claim. +The hosted scanner receives only database and broker secrets; the local opt-in +scanner still inherits the local MinIO root environment. Retained OpenAI guide +runtime cleanup remains governed by its existing provider-mode credential +availability and is not qualified by moving it to project control. + +Allowed files are the existing Celery worker topology/task files, the hosted +and local Compose/preflight and inference overlays, the public journey worker +launcher, affected topology/broker/Compose tests, and their immediate docs. +The risk is high because publication can stall accepted operations; architecture, +security, QA/test-delta and CI topology review apply. Acceptance requires an +independent exact task-route inventory, wrong-queue task refusal, actual Redis +prefork scan-to-finalizer delivery with no general consumer, hosted/local +singleton queue checks, and cleanup of owned test resources. This proof does +not qualify native fault recovery or the complete public journey by itself. +The focused real Redis/prefork test passed with one scanner and one finalizer, +no general consumer, an actual foreign registered-task rejection before DB +effects, exact T5 finalization and public replay; its isolated PostgreSQL and +MinIO resources cleaned (`/tmp/workstream-queue-scanner-real2.log` and `.json`). +The first run exposed Celery's requirement for a declared sender default even +with explicit routes; the corrected closed fallback router still refuses an +unknown task. The launch receipt names the base commit because the working tree +held this patch, so it is scope-compatible dirty-tree evidence, not clean-head +qualification. Focused topology, rendered hosted/local configuration, Ruff, +structure, Commitrail and changed Markdown links are checked separately. diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py index f01bb42ea..a19f9c5a3 100644 --- a/backend/app/workers/celery_app.py +++ b/backend/app/workers/celery_app.py @@ -3,10 +3,12 @@ from __future__ import annotations from celery import Celery +from celery.exceptions import QueueNotFound from kombu import Queue from app.workers.outbox_topology import ( - OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE, FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE, - is_finalization_worker_process, + OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE, OUTBOX_SCAN_TASK, OUTBOX_SCAN_QUEUE, + FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE, is_finalization_worker_process, + is_outbox_scan_worker_process, ) from app.workers.source_cleanup_topology import ( SOURCE_CLEANUP_QUEUE, SOURCE_CLEANUP_TASK, SOURCE_CLEANUP_SCHEDULE, @@ -18,6 +20,7 @@ from app.workers.project_setup_topology import ( CELERY_VISIBILITY_TIMEOUT_SECONDS, PROJECT_GUIDE_CONSUMER_MARKER, + PROJECT_GUIDE_QUEUE, ) from celery.signals import beat_init, worker_process_init, worker_process_shutdown, worker_shutdown @@ -46,17 +49,24 @@ GUIDE_SETUP_CONTINUATION_TASK = "workstream.artifacts.continue_guide_setup" GUIDE_SETUP_CONTINUATION_SCAN_TASK = "workstream.artifacts.scan_guide_setup_continuations" GUIDE_SETUP_CONTINUATION_SCAN_SCHEDULE = "guide-setup-continuation-scan" +PROJECT_CONTROL_QUEUE = "workstream.project_control" +ARTIFACT_WORK_QUEUE = "workstream.artifacts" +PROJECT_GUIDE_COMPILATION_TASK = "workstream.project_setup.compile_project_guide" +POST_POLICY_DERIVATION_TASK = "workstream.project_setup.derive_post_policy" +POST_POLICY_SCAN_TASK = "workstream.project_setup.scan_post_policy_approvals" +RETAINED_REVISION_SCAN_TASK = "workstream.tasks.scan_retained_revisions" +GUIDE_RUNTIME_CLEANUP_TASK = "workstream.project_setup.cleanup_runtime_resources" OBSERVED_TASK_NAMES = frozenset( { OUTBOX_DELIVERY_TASK, FINALIZATION_DELIVERY_TASK, SOURCE_CLEANUP_TASK, - "workstream.outbox.scan_pending", - "workstream.tasks.scan_retained_revisions", - "workstream.project_setup.derive_post_policy", - "workstream.project_setup.scan_post_policy_approvals", - "workstream.project_setup.compile_project_guide", - "workstream.project_setup.cleanup_runtime_resources", + OUTBOX_SCAN_TASK, + RETAINED_REVISION_SCAN_TASK, + POST_POLICY_DERIVATION_TASK, + POST_POLICY_SCAN_TASK, + PROJECT_GUIDE_COMPILATION_TASK, + GUIDE_RUNTIME_CLEANUP_TASK, ARTIFACT_SCRATCH_CLEANUP_TASK, ARTIFACT_PUT_RESOLUTION_TASK, ARTIFACT_VERIFICATION_TASK, @@ -65,6 +75,28 @@ GUIDE_SETUP_CONTINUATION_SCAN_TASK, } ) +WORKSTREAM_TASK_ROUTES = { + PROJECT_GUIDE_COMPILATION_TASK: {"queue": PROJECT_GUIDE_QUEUE}, + POST_POLICY_DERIVATION_TASK: {"queue": PROJECT_CONTROL_QUEUE}, + POST_POLICY_SCAN_TASK: {"queue": PROJECT_CONTROL_QUEUE}, + RETAINED_REVISION_SCAN_TASK: {"queue": PROJECT_CONTROL_QUEUE}, + GUIDE_RUNTIME_CLEANUP_TASK: {"queue": PROJECT_CONTROL_QUEUE}, + ARTIFACT_SCRATCH_CLEANUP_TASK: {"queue": ARTIFACT_WORK_QUEUE}, + ARTIFACT_PUT_RESOLUTION_TASK: {"queue": ARTIFACT_WORK_QUEUE}, + ARTIFACT_VERIFICATION_TASK: {"queue": ARTIFACT_WORK_QUEUE}, + ARTIFACT_PENDING_WORK_SCAN_TASK: {"queue": ARTIFACT_WORK_QUEUE}, + GUIDE_SETUP_CONTINUATION_TASK: {"queue": ARTIFACT_WORK_QUEUE}, + GUIDE_SETUP_CONTINUATION_SCAN_TASK: {"queue": ARTIFACT_WORK_QUEUE}, + OUTBOX_SCAN_TASK: {"queue": OUTBOX_SCAN_QUEUE}, + OUTBOX_DELIVERY_TASK: {"queue": OUTBOX_QUEUE}, + FINALIZATION_DELIVERY_TASK: {"queue": FINALIZATION_QUEUE}, + SOURCE_CLEANUP_TASK: {"queue": SOURCE_CLEANUP_QUEUE}, +} + + +def _reject_unrouted_task(name, _args, _kwargs, _options, *, task=None): + """Refuse a publisher that bypasses the closed Workstream task inventory.""" + raise QueueNotFound(f"unrouted Workstream task: {name}") @worker_process_init.connect @@ -73,9 +105,9 @@ def initialize_artifact_runtime_for_process(**_kwargs: object) -> None: if is_source_cleanup_worker_process(): # Parent validated cleanup startup; each sweep rechecks current authority. return - if is_finalization_worker_process(): - # Finalized replay needs retained SQL facts only. Unfinished finalization - # leases/initializes the same provider through _WorkerSourceObservation. + if is_finalization_worker_process() or is_outbox_scan_worker_process(): + # Scanning uses SQL and broker only. Finalized replay uses retained SQL; + # unfinished finalization initializes its provider on actual observation. return run_async_task(initialize_artifact_internal_runtime) @@ -144,10 +176,13 @@ def create_celery_app() -> Celery: ], ) celery_app.conf.update( - task_queues=(Queue("celery"), Queue(OUTBOX_QUEUE), Queue(FINALIZATION_QUEUE), Queue(SOURCE_CLEANUP_QUEUE)), - task_routes={SOURCE_CLEANUP_TASK: {"queue": SOURCE_CLEANUP_QUEUE}, - OUTBOX_DELIVERY_TASK: {"queue": OUTBOX_QUEUE}, - FINALIZATION_DELIVERY_TASK: {"queue": FINALIZATION_QUEUE}}, + task_queues=tuple(Queue(name) for name in ( + PROJECT_GUIDE_QUEUE, PROJECT_CONTROL_QUEUE, ARTIFACT_WORK_QUEUE, + OUTBOX_SCAN_QUEUE, OUTBOX_QUEUE, FINALIZATION_QUEUE, SOURCE_CLEANUP_QUEUE, + )), + task_default_queue=PROJECT_GUIDE_QUEUE, + task_create_missing_queues=False, + task_routes=(WORKSTREAM_TASK_ROUTES, _reject_unrouted_task), accept_content=["json"], result_serializer="json", task_always_eager=settings.celery_task_always_eager, @@ -169,17 +204,17 @@ def create_celery_app() -> Celery: "task": SOURCE_CLEANUP_TASK, "schedule": SUBMISSION_SOURCE_SWEEP_SECONDS, }} if settings.submission_source_cleanup_profile is not None else {}), "outbox-delivery-recovery": { - "task": "workstream.outbox.scan_pending", "schedule": 60.0, + "task": OUTBOX_SCAN_TASK, "schedule": 60.0, }, "retained-revision-recovery": { - "task": "workstream.tasks.scan_retained_revisions", "schedule": 60.0, + "task": RETAINED_REVISION_SCAN_TASK, "schedule": 60.0, }, "post-policy-approval-recovery": { - "task": "workstream.project_setup.scan_post_policy_approvals", + "task": POST_POLICY_SCAN_TASK, "schedule": 60.0, }, "guide-runtime-resource-cleanup": { - "task": "workstream.project_setup.cleanup_runtime_resources", + "task": GUIDE_RUNTIME_CLEANUP_TASK, "schedule": settings.artifact_pending_work_scan_interval_seconds, }, ARTIFACT_SCRATCH_CLEANUP_SCHEDULE: { diff --git a/backend/app/workers/outbox.py b/backend/app/workers/outbox.py index 6a712d932..aa816b787 100644 --- a/backend/app/workers/outbox.py +++ b/backend/app/workers/outbox.py @@ -10,7 +10,8 @@ from app.workers.async_runner import run_async_task from app.workers.celery_app import celery_app from app.workers.outbox_topology import ( - require_outbox_worker, OUTBOX_HARD_LIMIT_SECONDS, FINALIZATION_HARD_LIMIT_SECONDS, + require_outbox_worker, require_outbox_scan_worker, OUTBOX_HARD_LIMIT_SECONDS, + OUTBOX_SCAN_TASK, OUTBOX_SCAN_HARD_LIMIT_SECONDS, FINALIZATION_HARD_LIMIT_SECONDS, ) logger = get_task_logger(__name__) @@ -73,9 +74,15 @@ async def _deliver(event_id, project_id, task_id, finalization=False): await engine.dispose() -@celery_app.task(name="workstream.outbox.scan_pending", bind=True) +@celery_app.task(name=OUTBOX_SCAN_TASK, bind=True, time_limit=OUTBOX_SCAN_HARD_LIMIT_SECONDS) def scan_pending(self, after=None): """One stable page continues despite a failed publication; periodic scans repair gaps.""" + require_outbox_scan_worker(self) + return _scan_pending(self, after) + + +def _scan_pending(self, after=None): + """Publish one bounded page; the next periodic scan repairs interrupted pages.""" try: cursor = _uuid(after) if after is not None else None except (TypeError, ValueError): diff --git a/backend/app/workers/outbox_topology.py b/backend/app/workers/outbox_topology.py index 0f74ad444..1c579f5cb 100644 --- a/backend/app/workers/outbox_topology.py +++ b/backend/app/workers/outbox_topology.py @@ -15,24 +15,30 @@ ) OUTBOX_QUEUE = "workstream.outbox" OUTBOX_DELIVERY_TASK = "workstream.outbox.deliver_event" +OUTBOX_SCAN_QUEUE = "workstream.outbox_scan" +OUTBOX_SCAN_TASK = "workstream.outbox.scan_pending" +OUTBOX_SCAN_HARD_LIMIT_SECONDS = 60 FINALIZATION_QUEUE = "workstream.submission_finalization" FINALIZATION_DELIVERY_TASK = "workstream.outbox.finalize_submission" FINALIZATION_HARD_LIMIT_SECONDS = SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS + OUTBOX_PROCESS_SHUTDOWN_MARGIN_SECONDS _validated_parent: int | None = None _validated_finalization = False +_validated_scan = False @worker_init.connect def validate_outbox_worker(sender, **_kwargs): """Validate the actual selected queues and pool before the worker starts.""" - global _validated_parent, _validated_finalization + global _validated_parent, _validated_finalization, _validated_scan _validated_parent = None queues = set(sender.app.amqp.queues.consume_from) _validated_finalization = FINALIZATION_QUEUE in queues - if _validated_finalization and queues != {FINALIZATION_QUEUE}: - raise WorkerShutdown("submission finalization requires an exclusive worker queue") - if OUTBOX_QUEUE not in queues and not _validated_finalization: + _validated_scan = OUTBOX_SCAN_QUEUE in queues + selected = queues & {OUTBOX_QUEUE, OUTBOX_SCAN_QUEUE, FINALIZATION_QUEUE} + if not selected: return + if queues != selected or len(selected) != 1: + raise WorkerShutdown("OUTBOX workers require an exclusive worker queue") pool = sender.pool_cls if isinstance(pool, str): pool = get_implementation(pool) @@ -47,13 +53,35 @@ def is_finalization_worker_process() -> bool: and os.getppid() == _validated_parent) +def is_outbox_scan_worker_process() -> bool: + """Identify only a child of the validated exclusive scanner consumer.""" + return (_validated_scan and _validated_parent is not None + and os.getppid() == _validated_parent) + + +def require_outbox_scan_worker(task) -> None: + """Reject direct scans and broker attempts to extend the per-page bound.""" + if ( + not is_outbox_scan_worker_process() or task.app.conf.task_always_eager + or task.request.is_eager or task.request.called_directly + ): + raise RuntimeError("OUTBOX scan requires a validated prefork worker") + message_limit = (task.request.timelimit or (None, None))[0] + if ( + type(task.time_limit) is not int or task.time_limit != OUTBOX_SCAN_HARD_LIMIT_SECONDS + or message_limit is not None + and (type(message_limit) is not int or message_limit != OUTBOX_SCAN_HARD_LIMIT_SECONDS) + ): + raise RuntimeError("OUTBOX scan requires a bounded hard time limit") + + def require_outbox_worker(task, *, finalization=False): """Reject direct/eager delivery and consumers not validated for this queue.""" if ( _validated_parent is None or os.getppid() != _validated_parent or task.app.conf.task_always_eager or task.request.is_eager or task.request.called_directly - or finalization != _validated_finalization + or finalization != _validated_finalization or _validated_scan ): raise RuntimeError("OUTBOX delivery requires a validated prefork worker") message_limit = (task.request.timelimit or (None, None))[0] diff --git a/backend/app/workers/project_setup_topology.py b/backend/app/workers/project_setup_topology.py index 060122638..2b82468c0 100644 --- a/backend/app/workers/project_setup_topology.py +++ b/backend/app/workers/project_setup_topology.py @@ -14,7 +14,7 @@ PROJECT_GUIDE_HARD_LIMIT_SECONDS = 7_260 PROJECT_GUIDE_DRAIN_SECONDS = 7_320 CELERY_VISIBILITY_TIMEOUT_SECONDS = 7_380 -PROJECT_GUIDE_QUEUE = "celery" +PROJECT_GUIDE_QUEUE = "workstream.project_setup" PROJECT_GUIDE_CONSUMER_MARKER = "workstream_project_guide_consumer" _validated_parent: int | None = None @@ -51,6 +51,8 @@ def validate_project_setup_worker(sender, **_kwargs: object) -> None: ): return _validated_parent = None + if set(sender.app.amqp.queues.consume_from) != {PROJECT_GUIDE_QUEUE}: + raise WorkerShutdown("project guide compilation requires an exclusive worker queue") pool = sender.pool_cls if isinstance(pool, str): pool = get_implementation(pool) diff --git a/backend/app/workers/source_cleanup_topology.py b/backend/app/workers/source_cleanup_topology.py index 1ec634367..36da0a55e 100644 --- a/backend/app/workers/source_cleanup_topology.py +++ b/backend/app/workers/source_cleanup_topology.py @@ -18,6 +18,31 @@ SOURCE_CLEANUP_TASK = "workstream.artifacts.sweep_submission_sources" SOURCE_CLEANUP_SCHEDULE = "submission-source-cleanup" _validated_parent = None +_selected_queue_parent = None +_selected_queue = None + + +@worker_init.connect +def validate_workstream_queue_selection(sender, **_kwargs): + """Require one declared queue for every Workstream application worker.""" + global _selected_queue_parent, _selected_queue + from app.workers.project_setup_topology import PROJECT_GUIDE_CONSUMER_MARKER + + if getattr(sender.app.conf, PROJECT_GUIDE_CONSUMER_MARKER, False) is not True: + return + _selected_queue_parent = None + _selected_queue = None + queues = set(sender.app.amqp.queues.consume_from) + declared = {queue.name for queue in sender.app.conf.task_queues} + if len(queues) != 1 or not queues <= declared: + raise WorkerShutdown("Workstream workers require one declared queue") + pool = sender.pool_cls + if isinstance(pool, str): + pool = get_implementation(pool) + if pool is not TaskPool or sender.app.conf.task_always_eager: + raise WorkerShutdown("Workstream workers require non-eager prefork delivery") + _selected_queue = next(iter(queues)) + _selected_queue_parent = os.getpid() @worker_init.connect @@ -60,9 +85,17 @@ def require_source_cleanup_worker(task): class WorkerTaskBoundary(Task): - """Keep foreign registered tasks away from a cleanup child's credentials.""" + """Reject foreign task names on each dedicated worker before owner I/O.""" def before_start(self, task_id, args, kwargs): if is_source_cleanup_worker_process() and self.name != SOURCE_CLEANUP_TASK: raise RuntimeError("dedicated source cleanup worker rejects foreign tasks") + if _selected_queue_parent is not None and os.getppid() == _selected_queue_parent: + from app.workers.celery_app import WORKSTREAM_TASK_ROUTES + + route = WORKSTREAM_TASK_ROUTES.get(self.name) + expected = route.get("queue") if isinstance(route, dict) else None + received = self.request.delivery_info.get("routing_key") + if expected != _selected_queue or received != _selected_queue: + raise RuntimeError("dedicated worker rejects a foreign task") return super().before_start(task_id, args, kwargs) diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py index 888b8b16e..d44210534 100644 --- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -165,6 +165,24 @@ def record(task_id, task, retval, state, **_kwargs): without_heartbeat=True).start() +def _broker_scanner(app, hostname, completed): + """Run the production scan task with its own real prefork consumer.""" + from celery.signals import task_postrun + from app.workers.outbox_topology import OUTBOX_DELIVERY_TASK, OUTBOX_SCAN_QUEUE, OUTBOX_SCAN_TASK + + def record(task_id, task, retval, state, **_kwargs): + if task.name in {OUTBOX_SCAN_TASK, OUTBOX_DELIVERY_TASK}: + completed.put((task_id, task.name, state, str(retval) if state == "FAILURE" else retval, + os.getpid(), task.request.is_eager, + task.request.delivery_info["routing_key"])) + + os.setsid() + task_postrun.connect(record, weak=False) + app.Worker(pool="prefork", concurrency=1, queues=[OUTBOX_SCAN_QUEUE], hostname=hostname, + loglevel="ERROR", without_gossip=True, without_mingle=True, + without_heartbeat=True).start() + + async def _redis_forwarder(reader, writer, destination, connections): """Restore only this test's TCP endpoint; Redis and its namespace stay real.""" current = asyncio.current_task() @@ -316,8 +334,9 @@ async def _public_broker_case(f, tmp_path, monkeypatch, *, kill_at=None): from app.workers import outbox as worker case = SimpleNamespace(connection=redis.Redis.from_url(broker.geturl(), socket_timeout=2), prefix=f"finalizer-proof-{new_record_id()}:", hostname=f"finalizer-{new_record_id()}@localhost", - endpoint=socket.socket(), proxy=None, connections=set(), process=None, - completed=multiprocessing.get_context("fork").Queue(), app=worker.celery_app, + endpoint=socket.socket(), proxy=None, connections=set(), process=None, scan_process=None, + completed=multiprocessing.get_context("fork").Queue(), + scan_completed=multiprocessing.get_context("fork").Queue(), app=worker.celery_app, destination=(broker.hostname, broker.port), worker=worker, marker=tmp_path / "broker-child-kill.json", trace=tmp_path / "broker-delivery.jsonl") try: @@ -349,6 +368,7 @@ async def _close_broker_case(case): from app.core.config import get_settings case.endpoint.close() + await _stop_broker_worker(case.scan_process, case.scan_completed) await _stop_broker_worker(case.process, case.completed) for pool in (case.app.amqp._producer_pool, case.app._pool): if pool is not None: @@ -394,6 +414,79 @@ async def _next_broker_result(case): raise AssertionError("production finalization task did not return") +async def _next_scan_result(case): + """Observe real scanner completion in a child of its exclusive worker.""" + import queue + import time + from app.workers.outbox_topology import OUTBOX_SCAN_QUEUE + + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + assert case.scan_process.is_alive(), f"scan worker exited: {case.scan_process.exitcode}" + try: + result = await asyncio.to_thread(case.scan_completed.get, True, 0.2) + except queue.Empty: + continue + assert result[1:3] == ("workstream.outbox.scan_pending", "SUCCESS") + assert result[4] not in {os.getpid(), case.scan_process.pid} + assert result[5:] == (False, OUTBOX_SCAN_QUEUE) + return result + raise AssertionError("dedicated scan worker did not publish finalization") + + +async def _next_scan_foreign_result(case): + """Observe a substituted broker delivery rejected before owner I/O.""" + import queue + import time + from app.workers.outbox_topology import OUTBOX_SCAN_QUEUE + + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + assert case.scan_process.is_alive(), f"scan worker exited: {case.scan_process.exitcode}" + try: + result = await asyncio.to_thread(case.scan_completed.get, True, 0.2) + except queue.Empty: + continue + assert result[4] not in {os.getpid(), case.scan_process.pid} + assert result[5:] == (False, OUTBOX_SCAN_QUEUE) + return result + raise AssertionError("foreign task did not reach dedicated scan worker") + + +async def test_dedicated_scanner_publishes_finalization_without_general_consumer( + admission_intake, tmp_path, monkeypatch, +): + """Pending public acceptance reaches T5 through only scan and finalizer queues.""" + from app.core.identifiers import new_record_id + from app.workers.outbox_topology import OUTBOX_DELIVERY_TASK, OUTBOX_SCAN_QUEUE + + f = admission_intake + async with _public_broker_case(f, tmp_path, monkeypatch) as case: + await _restore_broker_endpoint(case) + case.scan_process = multiprocessing.get_context("fork").Process( + target=_broker_scanner, + args=(case.app, f"outbox-scan-{new_record_id()}@localhost", case.scan_completed), + ) + case.scan_process.start() + case.process.start() + await asyncio.to_thread(case.worker.deliver_event.apply_async, + args=(str(case.before[4]), str(f.project)), queue=OUTBOX_SCAN_QUEUE, + task_id=str(new_record_id())) + foreign = await _next_scan_foreign_result(case) + assert foreign[1:3] == (OUTBOX_DELIVERY_TASK, "FAILURE") + assert foreign[3] == "dedicated worker rejects a foreign task" + assert await _accepted_broker_facts(f, case.operation_id) == case.before + await asyncio.to_thread(case.worker.scan_pending.apply_async, + task_id=str(new_record_id())) + scan = await _next_scan_result(case) + assert scan[3] == {"selected": 1, "published": 1} + finalization = await _next_broker_result(case) + assert finalization[2] == {"status": "delivery_recorded"} + await _assert_broker_finalized_once(f, case.operation_id, case.before[1]) + await _assert_public_broker_replay(case) + await _assert_broker_finalized_once(f, case.operation_id, case.before[1]) + + async def _assert_public_broker_replay(case): """Exact accepted replay never uploads again or invokes PRE again.""" response = await case.client.post(case.url, headers=case.headers, content=case.payload) @@ -410,12 +503,12 @@ async def test_real_broker_recovers_public_acceptance_and_deduplicates_finalizat f = admission_intake async with _public_broker_case(f, tmp_path, monkeypatch) as case: - failed = await asyncio.to_thread(case.worker.scan_pending.run) + failed = await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) assert failed == {"selected": 1, "published": 0} assert await _accepted_broker_facts(f, case.operation_id) == case.before assert list(case.connection.scan_iter(match=case.prefix + "*")) == [] await _restore_broker_endpoint(case) - assert await asyncio.to_thread(case.worker.scan_pending.run) == {"selected": 1, "published": 1} + assert await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) == {"selected": 1, "published": 1} for _ in range(2): await asyncio.to_thread(case.worker.finalize_submission.apply_async, args=(str(case.before[4]), str(f.project))) @@ -563,17 +656,17 @@ async def test_real_broker_redelivers_killed_finalizer_and_recovers_owner_lease( f = admission_intake async with _public_broker_case(f, tmp_path, monkeypatch, kill_at=kill_at) as case: await _restore_broker_endpoint(case) - assert await asyncio.to_thread(case.worker.scan_pending.run) == {"selected": 1, "published": 1} + assert await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) == {"selected": 1, "published": 1} case.process.start() redelivery = await _next_broker_result(case) due, original_submission = await _assert_broker_redelivery(case, f, kill_at, redelivery) await _wait_for_broker_database_time(f.factory, due) - assert await asyncio.to_thread(case.worker.scan_pending.run) == {"selected": 1, "published": 1} + assert await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) == {"selected": 1, "published": 1} recovered = await _next_broker_result(case) assert recovered[2] == {"status": "delivery_recorded"} due = await _assert_broker_recovered_unknown(case, f) await _wait_for_broker_database_time(f.factory, due) - assert await asyncio.to_thread(case.worker.scan_pending.run) == {"selected": 1, "published": 1} + assert await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) == {"selected": 1, "published": 1} finalized = await _next_broker_result(case) assert finalized[2] == {"status": "delivery_recorded"} submission = await _assert_broker_finalized_once(f, case.operation_id, case.before[1], diff --git a/backend/tests/outbox/test_delivery_topology.py b/backend/tests/outbox/test_delivery_topology.py index 6548a9f42..c0d134372 100644 --- a/backend/tests/outbox/test_delivery_topology.py +++ b/backend/tests/outbox/test_delivery_topology.py @@ -6,7 +6,7 @@ import pytest from celery.concurrency.prefork import TaskPool from celery.concurrency.solo import TaskPool as SoloPool -from celery.exceptions import WorkerShutdown +from celery.exceptions import QueueNotFound, WorkerShutdown from app.workers import outbox_topology as topology @@ -25,6 +25,7 @@ def restore_process_state(monkeypatch): original_join_guard = task_join_will_block() monkeypatch.setattr(topology, "_validated_parent", None) monkeypatch.setattr(topology, "_validated_finalization", False) + monkeypatch.setattr(topology, "_validated_scan", False) try: yield finally: @@ -100,7 +101,11 @@ def test_delivery_routes_to_dedicated_queue(monkeypatch): try: route = app.amqp.router.route({}, topology.OUTBOX_DELIVERY_TASK) assert route["queue"].name == topology.OUTBOX_QUEUE - assert app.amqp.router.route({}, "workstream.project_setup.compile")["queue"].name == "celery" + from app.workers.celery_app import PROJECT_GUIDE_COMPILATION_TASK + from app.workers.project_setup_topology import PROJECT_GUIDE_QUEUE + assert app.amqp.router.route({}, PROJECT_GUIDE_COMPILATION_TASK)["queue"].name == PROJECT_GUIDE_QUEUE + with pytest.raises(QueueNotFound): + app.amqp.router.route({}, "workstream.unregistered") finally: app.close() get_settings.cache_clear() @@ -138,7 +143,7 @@ def test_actual_worker_startup_rejects_invalid_delivery_topology(monkeypatch, po get_settings.cache_clear() -def test_actual_other_queue_worker_allows_solo(monkeypatch): +def test_actual_unregistered_queue_worker_is_refused(monkeypatch): from app.core.config import get_settings monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true") get_settings.cache_clear() @@ -146,7 +151,8 @@ def test_actual_other_queue_worker_allows_solo(monkeypatch): app = create_celery_app() app.conf.task_always_eager = False try: - app.Worker(pool="solo", queues=["workstream.unrelated"]) + with pytest.raises(Exception, match="isn't|missing"): + app.Worker(pool="solo", queues=["workstream.unrelated"]) assert topology._validated_parent is None finally: app.close() @@ -179,6 +185,11 @@ def test_finalization_task_routes_to_reserved_queue(monkeypatch): app = create_celery_app() try: assert app.amqp.router.route({}, topology.FINALIZATION_DELIVERY_TASK)["queue"].name == topology.FINALIZATION_QUEUE + assert app.amqp.router.route({}, topology.OUTBOX_SCAN_TASK)["queue"].name == topology.OUTBOX_SCAN_QUEUE + assert app.tasks[topology.OUTBOX_SCAN_TASK].time_limit == topology.OUTBOX_SCAN_HARD_LIMIT_SECONDS + assert app.conf.beat_schedule["outbox-delivery-recovery"] == { + "task": topology.OUTBOX_SCAN_TASK, "schedule": 60.0, + } app.conf.task_always_eager = False with pytest.raises(WorkerShutdown, match="exclusive worker queue"): app.Worker(pool="prefork", queues=[topology.FINALIZATION_QUEUE, topology.OUTBOX_QUEUE]) @@ -187,6 +198,102 @@ def test_finalization_task_routes_to_reserved_queue(monkeypatch): get_settings.cache_clear() +def test_every_registered_workstream_task_has_one_explicit_queue(monkeypatch): + """Independent task inventory rejects an accidental default or mixed role.""" + from app.core.config import get_settings + from app.workers.celery_app import WORKSTREAM_TASK_ROUTES, create_celery_app + + monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true") + get_settings.cache_clear() + app = create_celery_app() + expected = { + "workstream.project_setup.compile_project_guide": "workstream.project_setup", + "workstream.project_setup.derive_post_policy": "workstream.project_control", + "workstream.project_setup.scan_post_policy_approvals": "workstream.project_control", + "workstream.project_setup.cleanup_runtime_resources": "workstream.project_control", + "workstream.tasks.scan_retained_revisions": "workstream.project_control", + "workstream.artifacts.cleanup_stale_scratch": "workstream.artifacts", + "workstream.artifacts.resolve_put_attempt": "workstream.artifacts", + "workstream.artifacts.verify_object": "workstream.artifacts", + "workstream.artifacts.scan_pending_work": "workstream.artifacts", + "workstream.artifacts.continue_guide_setup": "workstream.artifacts", + "workstream.artifacts.scan_guide_setup_continuations": "workstream.artifacts", + "workstream.outbox.scan_pending": "workstream.outbox_scan", + "workstream.outbox.deliver_event": "workstream.outbox", + "workstream.outbox.finalize_submission": "workstream.submission_finalization", + "workstream.artifacts.sweep_submission_sources": "workstream.source_cleanup", + } + try: + app.loader.import_default_modules() + assert {name for name in app.tasks if name.startswith("workstream.")} == set(expected) + assert app.conf.task_routes[0] is WORKSTREAM_TASK_ROUTES + assert {name: route["queue"] for name, route in WORKSTREAM_TASK_ROUTES.items()} == expected + assert {queue.name for queue in app.conf.task_queues} == set(expected.values()) + assert app.conf.task_create_missing_queues is False + for scheduled in app.conf.beat_schedule.values(): + assert scheduled["task"] in expected + for name, queue in expected.items(): + assert app.amqp.router.route({}, name)["queue"].name == queue + finally: + app.close() + get_settings.cache_clear() + + +@pytest.mark.parametrize("queues", [ + (topology.OUTBOX_SCAN_QUEUE, topology.OUTBOX_QUEUE), + (topology.OUTBOX_SCAN_QUEUE, topology.FINALIZATION_QUEUE), + (topology.OUTBOX_SCAN_QUEUE, "celery"), +]) +def test_scan_worker_refuses_shared_queues(queues): + with pytest.raises(WorkerShutdown, match="exclusive worker queue"): + topology.validate_outbox_worker(worker(queues=queues)) + + +def test_scan_entry_requires_dedicated_prefork_and_sixty_second_limit(monkeypatch): + configured = worker(queues=(topology.OUTBOX_SCAN_QUEUE,)) + topology.validate_outbox_worker(configured) + task = SimpleNamespace(app=configured.app, time_limit=topology.OUTBOX_SCAN_HARD_LIMIT_SECONDS, + request=SimpleNamespace(is_eager=False, called_directly=False, timelimit=None)) + with pytest.raises(RuntimeError, match="validated prefork"): + topology.require_outbox_scan_worker(task) + monkeypatch.setattr(topology.os, "getppid", os.getpid) + topology.require_outbox_scan_worker(task) + with pytest.raises(RuntimeError, match="bounded hard time limit"): + topology.require_outbox_scan_worker(SimpleNamespace(app=configured.app, time_limit=61, + request=task.request)) + with pytest.raises(RuntimeError, match="validated prefork"): + topology.require_outbox_worker(task) + + +@pytest.mark.parametrize("selected,name,routing_key", [ + ("workstream.outbox_scan", "workstream.outbox.deliver_event", "workstream.outbox_scan"), + ("workstream.project_control", "workstream.artifacts.verify_object", "workstream.project_control"), + ("workstream.artifacts", "workstream.artifacts.verify_object", "workstream.project_control"), +]) +def test_dedicated_worker_rejects_foreign_registered_delivery_before_owner_io( + monkeypatch, selected, name, routing_key, +): + from app.core.config import get_settings + from app.workers import source_cleanup_topology as boundary + from app.workers.celery_app import create_celery_app + + monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true") + get_settings.cache_clear() + app = create_celery_app() + monkeypatch.setattr(boundary, "_selected_queue_parent", os.getpid()) + monkeypatch.setattr(boundary, "_selected_queue", selected) + monkeypatch.setattr(boundary, "_validated_parent", None) + monkeypatch.setattr(boundary.os, "getppid", os.getpid) + fake = SimpleNamespace(name=name, app=app, + request=SimpleNamespace(delivery_info={"routing_key": routing_key})) + try: + with pytest.raises(RuntimeError, match="dedicated worker rejects a foreign task"): + boundary.WorkerTaskBoundary.before_start(fake, "task-id", (), {}) + finally: + app.close() + get_settings.cache_clear() + + def test_scan_routes_each_event_group_without_acknowledging(monkeypatch): from app.core.config import get_settings from app.core.identifiers import new_record_id @@ -200,6 +307,7 @@ async def candidates(_after): return DeliveryCandidatePage(items=items, next_after=None) published = [] monkeypatch.setattr(outbox, "_candidates", candidates) + monkeypatch.setattr(outbox, "require_outbox_scan_worker", lambda _task: None) monkeypatch.setattr(outbox.deliver_event, "apply_async", lambda **kwargs: published.append(("post", kwargs))) monkeypatch.setattr(outbox.finalize_submission, "apply_async", lambda **kwargs: published.append(("final", kwargs))) try: diff --git a/backend/tests/outbox/test_recovery_postgresql.py b/backend/tests/outbox/test_recovery_postgresql.py index 196a2d810..7331e1650 100644 --- a/backend/tests/outbox/test_recovery_postgresql.py +++ b/backend/tests/outbox/test_recovery_postgresql.py @@ -76,6 +76,7 @@ def _configure_recovery_worker(h, monkeypatch: pytest.MonkeyPatch): from app.workers import outbox as worker monkeypatch.setattr(worker, "require_outbox_worker", lambda _task, **_kwargs: None) + monkeypatch.setattr(worker, "require_outbox_scan_worker", lambda _task: None) monkeypatch.setattr(worker, "get_database_url", lambda: h.factory.kw["bind"].url) worker_factories = [] diff --git a/backend/tests/outbox/test_worker_postgresql.py b/backend/tests/outbox/test_worker_postgresql.py index ee1ea962b..08634abf3 100644 --- a/backend/tests/outbox/test_worker_postgresql.py +++ b/backend/tests/outbox/test_worker_postgresql.py @@ -25,6 +25,7 @@ def worker(delivery_harness, monkeypatch): # Shared SQL/timeout proofs isolate topology, covered by the real broker drill. monkeypatch.setattr(worker, "require_outbox_worker", lambda _task, **_kwargs: None) + monkeypatch.setattr(worker, "require_outbox_scan_worker", lambda _task: None) monkeypatch.setattr(worker, "get_database_url", lambda: h.factory.kw["bind"].url) monkeypatch.setattr( worker, diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index 76b2546d5..8f8d245b1 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -399,7 +399,11 @@ def worker( required.append(process) return process - general_worker = worker("worker", "celery,workstream.outbox", 2) + worker("guide", "workstream.project_setup", 1) + worker("project-control", "workstream.project_control", 1) + worker("artifacts", "workstream.artifacts", 1) + worker("outbox-scan", "workstream.outbox_scan", 1) + effect_worker = worker("outbox", "workstream.outbox", 1) worker("finalizer", "workstream.submission_finalization", 1) worker( "source-cleanup", @@ -436,26 +440,24 @@ def worker( raise RuntimeError("required journey worker exited during startup") time.sleep(0.2) - def stop_general_worker(): - if general_worker.poll() is not None: - raise RuntimeError("owned general worker already exited") - _stop_owned_group(general_worker) - processes.remove(general_worker) - - async def start_general_worker(): - nonlocal general_worker - if general_worker.poll() is None: - raise RuntimeError("owned general worker was not stopped") - general_worker = worker( - "worker-restarted", "celery,workstream.outbox", 2 - ) + def stop_effect_worker(): + if effect_worker.poll() is not None: + raise RuntimeError("owned POST delivery worker already exited") + _stop_owned_group(effect_worker) + processes.remove(effect_worker) + + async def start_effect_worker(): + nonlocal effect_worker + if effect_worker.poll() is None: + raise RuntimeError("owned POST delivery worker was not stopped") + effect_worker = worker("outbox-restarted", "workstream.outbox", 1) deadline = time.monotonic() + 15 while time.monotonic() < deadline: - if general_worker.poll() is not None: - raise RuntimeError("owned general worker restart exited") + if effect_worker.poll() is not None: + raise RuntimeError("owned POST delivery worker restart exited") await asyncio.sleep(0.2) - return stop_general_worker, start_general_worker + return stop_effect_worker, start_effect_worker yield start_workers finally: diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md index 58404ccc5..14c3d6d88 100644 --- a/deploy/hosted/README.md +++ b/deploy/hosted/README.md @@ -270,8 +270,9 @@ preflight rejects missing or malformed objects and requires the cleanup profile's `upload_principal` to equal the runtime upload ARN. Full preflight, every `up`, and reboot reconciliation then run the canonical strict profile validators from the pinned backend image before activating services. The -general worker consumes only `celery,workstream.outbox`; finalization and source -cleanup each use a separate prefork worker with exactly one queue. Beat always +guide compilation, project control, artifact work, outbox scanning, POST delivery, +submission finalization, and source cleanup each have one dedicated prefork +worker consuming exactly one named queue. Beat always receives the required cleanup profile, so the cleanup schedule cannot disappear because of an omitted setting. @@ -415,7 +416,7 @@ administrator and do not attest the running node's complete source custody; qualification separately records its actual process/binary identities. The guide parser and enabled model proxy must pass their existing health checks -before the general worker starts. The exclusive finalization and cleanup +before the guide worker starts. The exclusive finalization and cleanup workers must also become healthy, and Beat retains its recovery schedules. API health is a lightweight endpoint; Celery health checks its processes. Remote health verifies runtime/identity/cache-count and pinned intake/default facts; exact diff --git a/deploy/hosted/compose.inference.yml b/deploy/hosted/compose.inference.yml index 8321a8485..0b5860a20 100644 --- a/deploy/hosted/compose.inference.yml +++ b/deploy/hosted/compose.inference.yml @@ -10,3 +10,14 @@ services: depends_on: model-proxy: condition: service_healthy + outbox-worker: + environment: + WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/model-runtime/model.sock + volumes: + - type: bind + source: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/model-runtime + target: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/model-runtime + read_only: true + depends_on: + model-proxy: + condition: service_healthy diff --git a/deploy/hosted/compose.yml b/deploy/hosted/compose.yml index e7ec5030a..b38f4b797 100644 --- a/deploy/hosted/compose.yml +++ b/deploy/hosted/compose.yml @@ -187,7 +187,7 @@ services: retries: 6 start_period: 30s - worker: + worker: &project-guide-worker <<: *backend-runtime environment: <<: *backend-environment @@ -240,7 +240,7 @@ services: - --pool=prefork - --concurrency=${WORKSTREAM_CELERY_WORKER_CONCURRENCY:-1} - --hostname=worker@%h - - --queues=celery,workstream.outbox + - --queues=workstream.project_setup - --pidfile=/tmp/celery-worker.pid - --loglevel=INFO volumes: @@ -269,6 +269,97 @@ services: retries: 6 start_period: 30s + project-control-worker: + <<: *project-guide-worker + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=project-control@%h + - --queues=workstream.project_control + - --pidfile=/tmp/celery-worker.pid + - --loglevel=INFO + + artifact-worker: + <<: *project-guide-worker + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=artifacts@%h + - --queues=workstream.artifacts + - --pidfile=/tmp/celery-worker.pid + - --loglevel=INFO + + outbox-worker: + <<: *project-guide-worker + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=outbox@%h + - --queues=workstream.outbox + - --pidfile=/tmp/celery-worker.pid + - --loglevel=INFO + + outbox-scan-worker: + <<: *backend-runtime + environment: + <<: *backend-environment + WORKSTREAM_RELEASE_ROLE: worker + WORKSTREAM_DATABASE_URL_FILE: /run/secrets/database_url + WORKSTREAM_CELERY_BROKER_URL_FILE: /run/secrets/celery_broker_url + secrets: + - source: database_url + target: database_url + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + - source: celery_broker_url + target: celery_broker_url + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=outbox-scan@%h + - --queues=workstream.outbox_scan + - --pidfile=/tmp/celery-outbox-scan.pid + - --loglevel=INFO + depends_on: + api: + condition: service_healthy + restart: on-failure:5 + stop_grace_period: 120s + healthcheck: + test: [CMD-SHELL, "test -s /tmp/celery-outbox-scan.pid && kill -0 $$(cat /tmp/celery-outbox-scan.pid)"] + interval: 20s + timeout: 10s + retries: 6 + start_period: 30s + submission-finalization-worker: <<: *backend-runtime environment: diff --git a/deploy/hosted/preflight.py b/deploy/hosted/preflight.py index 983f3b6a2..84b026705 100644 --- a/deploy/hosted/preflight.py +++ b/deploy/hosted/preflight.py @@ -1100,13 +1100,18 @@ def run_compose( # MCP attached to a retired API namespace after a Compose-managed update. selected_services = set(compose_arguments) & { "postgres", "redis", - "api", "mcp", "worker", "submission-finalization-worker", + "api", "mcp", "worker", "project-control-worker", "artifact-worker", + "outbox-scan-worker", "outbox-worker", "submission-finalization-worker", "submission-source-cleanup-worker", "beat", "model-proxy", "identity", "guide-document-parser", } targets_api = not selected_services or "api" in selected_services or ( "--no-deps" not in compose_arguments - and bool(selected_services & {"mcp", "worker", "beat"}) + and bool(selected_services & { + "mcp", "beat", "worker", "project-control-worker", "artifact-worker", + "outbox-scan-worker", "outbox-worker", "submission-finalization-worker", + "submission-source-cleanup-worker", + }) ) couple_mcp = bool(values.get("WORKSTREAM_MCP_IMAGE")) and ( compose_arguments[0] == "up" and targets_api @@ -1119,6 +1124,10 @@ def run_compose( *compose_arguments, "api", "worker", + "project-control-worker", + "artifact-worker", + "outbox-scan-worker", + "outbox-worker", "submission-finalization-worker", "submission-source-cleanup-worker", "beat", @@ -1291,11 +1300,13 @@ def run_shutdown(environment_path: Path, values: dict[str, str]) -> int: """Stop producers, drain the worker, then stop its isolated dependencies.""" phases = [ ["stop", "beat", "api"], - ["stop", "--timeout", "7320", "worker"], + ["stop", "--timeout", "7320", "worker", "project-control-worker", + "artifact-worker", "outbox-worker"], [ "stop", "--timeout", "420", "submission-finalization-worker", "submission-source-cleanup-worker", ], + ["stop", "--timeout", "120", "outbox-scan-worker"], ] if values.get("WORKSTREAM_MCP_IMAGE"): phases.insert(0, ["stop", "mcp"]) @@ -1560,11 +1571,17 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: """Check the rendered release process and privilege topology.""" paths = deployment_paths(values) services = rendered.get("services") + standard_workers = { + "worker", "project-control-worker", "artifact-worker", "outbox-worker", + } + bounded_workers = { + "outbox-scan-worker", "submission-finalization-worker", + "submission-source-cleanup-worker", + } + all_workers = standard_workers | bounded_workers expected_services = { "api", - "worker", - "submission-finalization-worker", - "submission-source-cleanup-worker", + *all_workers, "beat", "guide-document-parser", } @@ -1619,9 +1636,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: ) backend_runtime_services = { "api", - "worker", - "submission-finalization-worker", - "submission-source-cleanup-worker", + *all_workers, "beat", } if model_proxy_enabled: @@ -1634,13 +1649,9 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: if services["guide-document-parser"]["user"] != "0:0": raise PreflightError("guide parser has the wrong bootstrap identity") backend_image = services["api"]["image"] - if ( - services["worker"]["image"] != backend_image - or services["submission-finalization-worker"]["image"] != backend_image - or services["submission-source-cleanup-worker"]["image"] != backend_image - or services["beat"]["image"] != backend_image - or services["guide-document-parser"]["image"] != backend_image - ): + if any(services[name]["image"] != backend_image for name in ( + *all_workers, "beat", "guide-document-parser", + )): raise PreflightError( "API, workers, Beat and guide parser must use one exact backend image" ) @@ -1651,9 +1662,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: raise PreflightError("model proxy must use the exact agents backend image") for name in ( "api", - "worker", - "submission-finalization-worker", - "submission-source-cleanup-worker", + *all_workers, "beat", "guide-document-parser", *({"model-proxy"} if model_proxy_enabled else set()), @@ -1669,16 +1678,26 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: shared_backend_mounts = { str(paths.scratch): (str(paths.scratch), False), } + cloned_worker_mounts = ( + shared_backend_mounts + | {str(paths.guide_root): (str(paths.guide_root), True)} + | direct_user_credential_mount + ) expected_mounts = { "api": shared_backend_mounts | direct_user_credential_mount, - "worker": shared_backend_mounts - | {str(paths.guide_root): (str(paths.guide_root), True)} + "worker": cloned_worker_mounts | ( {str(paths.model_root): (str(paths.model_root), True)} if model_proxy_enabled else {} - ) - | direct_user_credential_mount, + ), + "project-control-worker": cloned_worker_mounts, + "artifact-worker": cloned_worker_mounts, + "outbox-worker": cloned_worker_mounts | ( + {str(paths.model_root): (str(paths.model_root), True)} + if model_proxy_enabled else {} + ), + "outbox-scan-worker": {}, "submission-finalization-worker": direct_user_credential_mount, "submission-source-cleanup-worker": { str(DIRECT_USER_CREDENTIAL_TARGET): ( @@ -1812,6 +1831,12 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: "required": True, }: raise PreflightError("worker must wait for a healthy model proxy") + if model_proxy_enabled and ( + services["outbox-worker"].get("depends_on") or {} + ).get("model-proxy") != { + "condition": "service_healthy", "required": True, + }: + raise PreflightError("outbox worker must wait for a healthy model proxy") worker = services["worker"] worker_command = worker.get("command") if ( @@ -1820,10 +1845,30 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: or "--pool=prefork" not in worker_command or [value for value in worker_command if str(value).startswith(("-Q", "--queues"))] - != ["--queues=celery,workstream.outbox"] + != ["--queues=workstream.project_setup"] ): raise PreflightError("project guide worker delivery profile is invalid") bounded_worker_profiles = { + "project-control-worker": ( + "--queues=workstream.project_control", + "--hostname=project-control@%h", + "--pidfile=/tmp/celery-worker.pid", + ), + "artifact-worker": ( + "--queues=workstream.artifacts", + "--hostname=artifacts@%h", + "--pidfile=/tmp/celery-worker.pid", + ), + "outbox-worker": ( + "--queues=workstream.outbox", + "--hostname=outbox@%h", + "--pidfile=/tmp/celery-worker.pid", + ), + "outbox-scan-worker": ( + "--queues=workstream.outbox_scan", + "--hostname=outbox-scan@%h", + "--pidfile=/tmp/celery-outbox-scan.pid", + ), "submission-finalization-worker": ( "--queues=workstream.submission_finalization", "--hostname=submission-finalization@%h", @@ -1839,7 +1884,12 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: bounded_worker = services[name] command = bounded_worker.get("command") if ( - bounded_worker.get("stop_grace_period") not in {"420s", "7m0s"} + bounded_worker.get("stop_grace_period") not in ( + {"120s", "2m0s"} if name == "outbox-scan-worker" else + {"7320s", "2h2m0s"} if name in { + "project-control-worker", "artifact-worker", "outbox-worker", + } else {"420s", "7m0s"} + ) or not isinstance(command, list) or "--pool=prefork" not in command or "--concurrency=1" not in command @@ -1871,9 +1921,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: environments: dict[str, dict[str, Any]] = {} active_roles = ( "api", - "worker", - "submission-finalization-worker", - "submission-source-cleanup-worker", + *sorted(all_workers), "beat", ) + ( ("model-proxy",) if model_proxy_enabled else () @@ -1882,28 +1930,27 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: environment = services[role].get("environment") if not isinstance(environment, dict): raise PreflightError(f"{role} release environment is unavailable") - expected_release_role = ( - "worker" if role.startswith("submission-") else role - ) + expected_release_role = "worker" if role in all_workers else role if environment.get("WORKSTREAM_RELEASE_ROLE") != expected_release_role: raise PreflightError(f"{role} has an unsafe release role") expected_direct_credential = ( str(DIRECT_USER_CREDENTIAL_TARGET) - if role in { - "api", "worker", "model-proxy", - "submission-finalization-worker", - "submission-source-cleanup-worker", - } + if role in {"api", "model-proxy", *standard_workers, + "submission-finalization-worker", "submission-source-cleanup-worker"} else None ) if environment.get(DIRECT_USER_CREDENTIAL_FILE_KEY) != expected_direct_credential: raise PreflightError( f"{role} direct IAM user credential selector differs from its release role" ) - policy_role = "bounded-worker" if role.startswith("submission-") else role + policy_role = "bounded-worker" if role in bounded_workers else ( + "worker" if role in standard_workers else role + ) required_file_keys = ( {"WORKSTREAM_DATABASE_URL_FILE", "WORKSTREAM_CELERY_BROKER_URL_FILE"} if policy_role == "bounded-worker" + else set(ROLE_SECRET_FILE_KEYS["worker"]) + if role in standard_workers - {"worker"} else set(_role_secret_file_keys(policy_role, values)) ) for key, (_, target) in SECRET_FILE_TARGETS.items(): @@ -2008,9 +2055,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: raise PreflightError(f"rendered release environment is unsafe: {key}") for name in ( "api", - "worker", - "submission-finalization-worker", - "submission-source-cleanup-worker", + *sorted(all_workers), "beat", *(("model-proxy",) if model_proxy_enabled else ()), ): @@ -2052,11 +2097,11 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: ), **( {key: values[key] for key in INTAKE_DIGEST_KEYS} - if name in {"api", "worker"} + if name in {"api", *standard_workers} else {} ), } - if name in {"api", "worker"} + if name in {"api", *standard_workers} else {} ) if { @@ -2088,6 +2133,10 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: "WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET" ) != str(paths.model_socket): raise PreflightError("worker lacks the fixed model proxy socket") + if model_proxy_enabled and environments["outbox-worker"].get( + "WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET" + ) != str(paths.model_socket): + raise PreflightError("outbox worker lacks the fixed model proxy socket") if model_proxy_enabled and environments["model-proxy"].get( "WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET" ) != str(paths.model_socket): diff --git a/docker-compose.agent-loop.yml b/docker-compose.agent-loop.yml index d68a1376e..6a8289db2 100644 --- a/docker-compose.agent-loop.yml +++ b/docker-compose.agent-loop.yml @@ -41,6 +41,19 @@ services: - checker_material:/var/lib/docker/volumes/${COMPOSE_PROJECT_NAME}-checker-material/_data - checker_socket:/run/ws-checker:ro - checker_model_proxy:/run/ws-model-proxy:ro + outbox-worker: + environment: + WORKSTREAM_ARTIFACT_SCRATCH_ROOT: /var/lib/docker/volumes/${COMPOSE_PROJECT_NAME}-checker-material/_data + WORKSTREAM_EXTERNAL_CHECKER_MATERIAL_ROOT: /var/lib/docker/volumes/${COMPOSE_PROJECT_NAME}-checker-material/_data + WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET: /run/ws-checker/checker.sock + WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET: /run/ws-model-proxy/model-proxy.sock + volumes: + - checker_material:/var/lib/docker/volumes/${COMPOSE_PROJECT_NAME}-checker-material/_data + - checker_socket:/run/ws-checker:ro + - checker_model_proxy:/run/ws-model-proxy:ro + depends_on: + checker-volumes-init: + condition: service_completed_successfully beat: *agent-loop-backend model-proxy: diff --git a/docker-compose.yml b/docker-compose.yml index 1db420c87..775206034 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -80,7 +80,7 @@ services: retries: 20 start_period: 15s - worker: &general-worker + worker: &guide-worker <<: *backend-runtime group_add: ["10001"] environment: &worker-environment @@ -100,7 +100,7 @@ services: - --pool=prefork - --concurrency=${WORKSTREAM_CELERY_WORKER_CONCURRENCY:-2} - --hostname=worker@%h - - --queues=celery,workstream.outbox + - --queues=workstream.project_setup - --pidfile=/tmp/celery-worker.pid - --loglevel=INFO depends_on: @@ -121,8 +121,86 @@ services: retries: 12 start_period: 20s + project-control-worker: + <<: *guide-worker + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=project-control@%h + - --queues=workstream.project_control + - --pidfile=/tmp/celery-worker.pid + - --loglevel=INFO + + artifact-worker: + <<: *guide-worker + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=artifacts@%h + - --queues=workstream.artifacts + - --pidfile=/tmp/celery-worker.pid + - --loglevel=INFO + + outbox-scan-worker: + <<: *backend-runtime + environment: + <<: *backend-environment + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=outbox-scan@%h + - --queues=workstream.outbox_scan + - --pidfile=/tmp/celery-worker.pid + - --loglevel=INFO + depends_on: + backend: + condition: service_healthy + redis: + condition: service_healthy + stop_grace_period: 120s + healthcheck: + test: [CMD-SHELL, "test -s /tmp/celery-worker.pid && kill -0 $$(cat /tmp/celery-worker.pid)"] + interval: 10s + timeout: 8s + retries: 12 + start_period: 20s + + outbox-worker: + <<: *guide-worker + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=outbox@%h + - --queues=workstream.outbox + - --pidfile=/tmp/celery-worker.pid + - --loglevel=INFO + submission-finalizer: - <<: *general-worker + <<: *guide-worker profiles: ["submission-intake"] environment: <<: *worker-environment @@ -137,6 +215,27 @@ services: exec python -m celery -A app.workers.celery_app worker --pool=prefork --concurrency="$$n" --queues=workstream.submission_finalization --hostname=submission-finalizer@%h --pidfile=/tmp/celery-worker.pid --loglevel=INFO stop_grace_period: 420s + submission-source-cleanup-worker: + <<: *guide-worker + profiles: ["submission-intake"] + environment: + <<: *worker-environment + WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE: ${WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE:-} + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=source-cleanup@%h + - --queues=workstream.source_cleanup + - --pidfile=/tmp/celery-worker.pid + - --loglevel=INFO + stop_grace_period: 420s + model-proxy: <<: *backend-runtime profiles: ["model-proxy"] diff --git a/docs/engineering/developer-setup.md b/docs/engineering/developer-setup.md index 7a8ec787c..a6aecc2c2 100644 --- a/docs/engineering/developer-setup.md +++ b/docs/engineering/developer-setup.md @@ -149,10 +149,10 @@ uploaded rules compilation at the same prefix's `requirements/compile` suffix. Both require a UUID `Idempotency-Key` and no body; manager review and separate approvals remain required. See the [local pilot](local-pilot.md#declare-and-upload-a-real-guide-document). -The single-request submission implementation has an opt-in `submission-intake` -Celery worker profile in local Compose. Its `submission-finalizer` service -consumes only `workstream.submission_finalization`; the general Celery worker consumes -`celery,workstream.outbox`. Set `WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY` +The local Compose workers each consume one queue: project guide compilation, +project control, artifact work, outbox scanning, POST delivery, submission +finalization, and source cleanup. The submission finalizer and source cleanup +services use the opt-in `submission-intake` profile. Set `WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY` to an approved positive integer before enabling the profile. Missing or invalid values stop that consumer before Celery starts. No concurrency default or native runtime qualification is implied. Hosted consumer provisioning, public submission diff --git a/scripts/test_hosted_release_config.py b/scripts/test_hosted_release_config.py index bd2c0a574..f1127022c 100644 --- a/scripts/test_hosted_release_config.py +++ b/scripts/test_hosted_release_config.py @@ -166,6 +166,8 @@ def test_app_profile_keeps_inference_and_rejects_native_runtime_custody(self): self.assertIn("model-proxy", services) self.assertIn("guide-document-parser", services["worker"]["depends_on"]) self.assertIn("model-proxy", services["worker"]["depends_on"]) + self.assertEqual(services["outbox-worker"]["depends_on"]["model-proxy"], + {"condition": "service_healthy", "required": True}) paths = preflight.deployment_paths(values) self.assertEqual( services["worker"]["environment"]["WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET"], @@ -183,6 +185,16 @@ def test_app_profile_keeps_inference_and_rejects_native_runtime_custody(self): ] self.assertEqual(worker_model_mount["source"], str(paths.model_socket.parent)) self.assertTrue(worker_model_mount["read_only"]) + self.assertEqual( + services["outbox-worker"]["environment"]["WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET"], + str(paths.model_socket), + ) + self.assertTrue(preflight._service_mounts(services["outbox-worker"])[ + str(paths.model_socket.parent)]["read_only"]) + changed = copy.deepcopy(rendered) + del changed["services"]["outbox-worker"]["depends_on"]["model-proxy"] + with self.assertRaisesRegex(preflight.PreflightError, "outbox worker must wait"): + preflight.validate_compose(changed, values) for role in ("api", "worker"): self.assertFalse( { @@ -356,7 +368,8 @@ def test_local_data_shutdown_preserves_dependencies_until_consumers_stop(self): self.assertEqual(preflight.run_shutdown(self.environment_path, values), 0) commands = [call.args[0] for call in run.call_args_list] self.assertEqual(commands[-1][-5:], ["stop", "--timeout", "60", "redis", "postgres"]) - self.assertTrue(any(command[-4:] == ["stop", "--timeout", "7320", "worker"] for command in commands[:-1])) + self.assertTrue(any(command[-7:] == ["stop", "--timeout", "7320", "worker", + "project-control-worker", "artifact-worker", "outbox-worker"] for command in commands[:-1])) with patch.object(preflight.subprocess, "run", side_effect=[ subprocess.CompletedProcess([], 0), subprocess.CompletedProcess([], 17), ]) as run: @@ -485,6 +498,26 @@ def run(command, **kwargs): with self.assertRaisesRegex(preflight.PreflightError, "different API namespace"): preflight.validate_running_mcp_namespace(["docker", "compose"], values) + def test_targeted_worker_up_keeps_mcp_coupled_to_api_dependency(self): + values = self.mcp_environment() + for service in ("project-control-worker", "artifact-worker", "outbox-scan-worker", + "outbox-worker", "submission-finalization-worker", + "submission-source-cleanup-worker"): + calls = [] + def run(command, **_kwargs): + calls.append(command) + return subprocess.CompletedProcess(command, 0) + with self.subTest(service=service), patch.object( + preflight.subprocess, "run", side_effect=run + ), patch.object(preflight, "validate_running_mcp_namespace"): + self.assertEqual(preflight.run_compose( + self.environment_path, values, ["up", "--detach", service] + ), 0) + self.assertEqual(calls[0][-2:], ["stop", "mcp"]) + self.assertIn(service, calls[1]) + self.assertIn("--force-recreate", calls[2]) + self.assertEqual(calls[2][-1], "mcp") + def test_full_launch_waits_for_api_before_starting_stale_mcp(self): values = self.mcp_environment() calls = [] @@ -761,11 +794,11 @@ def tearDown(self) -> None: def test_worker_cannot_consume_finalization_or_omit_its_queue_selection(self) -> None: rendered = preflight.render_compose(self.environment_path, self.environment) for selection in (None, "--queues=celery", "-Qworkstream.submission_finalization", - "--queues=celery,workstream.outbox,workstream.submission_finalization"): + "--queues=workstream.project_setup,workstream.outbox"): with self.subTest(selection=selection): changed = copy.deepcopy(rendered) command = changed["services"]["worker"]["command"] - command.remove("--queues=celery,workstream.outbox") + command.remove("--queues=workstream.project_setup") if selection: command.append(selection) with self.assertRaisesRegex(preflight.PreflightError, "worker delivery profile"): @@ -982,7 +1015,8 @@ def test_shutdown_drains_producers_worker_and_proxy_without_stopping_native_node ) commands = [call.args[0] for call in run.call_args_list] self.assertEqual(commands[0][-3:], ["stop", "beat", "api"]) - self.assertEqual(commands[1][-4:], ["stop", "--timeout", "7320", "worker"]) + self.assertEqual(commands[1][-7:], ["stop", "--timeout", "7320", "worker", + "project-control-worker", "artifact-worker", "outbox-worker"]) self.assertEqual( commands[2][-5:], [ @@ -995,19 +1029,23 @@ def test_shutdown_drains_producers_worker_and_proxy_without_stopping_native_node ) self.assertEqual( commands[3][-4:], + ["stop", "--timeout", "120", "outbox-scan-worker"], + ) + self.assertEqual( + commands[4][-4:], ["stop", "--timeout", "7320", "model-proxy"], ) self.assertEqual( - commands[4][-2:], + commands[5][-2:], ["stop", "guide-document-parser"], ) def test_shutdown_failure_keeps_later_dependencies_running(self) -> None: - for failed_phase in (0, 1, 2, 3): + for failed_phase in (0, 1, 2, 3, 4): with self.subTest(failed_phase=failed_phase): results = [ subprocess.CompletedProcess([], 17 if index == failed_phase else 0) - for index in range(5) + for index in range(6) ] with patch.object( preflight.subprocess, "run", side_effect=results diff --git a/scripts/test_local_guide_runtime.py b/scripts/test_local_guide_runtime.py index e77d6da9e..224afde89 100644 --- a/scripts/test_local_guide_runtime.py +++ b/scripts/test_local_guide_runtime.py @@ -64,6 +64,16 @@ def setUp(self): self.compose = yaml.safe_load((ROOT / "docker-compose.yml").read_text()) self.services = self.compose["services"] + def test_agent_loop_post_worker_receives_model_and_checker_sockets(self): + overlay = yaml.safe_load((ROOT / "docker-compose.agent-loop.yml").read_text()) + worker = overlay["services"]["outbox-worker"] + self.assertEqual(worker["environment"]["WORKSTREAM_CHECKER_MODEL_PROXY_SOCKET"], + "/run/ws-model-proxy/model-proxy.sock") + self.assertEqual(worker["environment"]["WORKSTREAM_EXTERNAL_CHECKER_SERVICE_SOCKET"], + "/run/ws-checker/checker.sock") + self.assertIn("checker_model_proxy:/run/ws-model-proxy:ro", worker["volumes"]) + self.assertIn("checker_socket:/run/ws-checker:ro", worker["volumes"]) + def test_parser_has_no_secrets_network_or_source_mount(self): parser = self.services["guide-document-parser"] self.assertEqual(parser["network_mode"], "none") @@ -106,7 +116,7 @@ def test_worker_receives_readonly_parser_socket(self): def test_finalization_consumer_requires_explicit_positive_capacity(self): service = self.services["submission-finalizer"] self.assertEqual(service["profiles"], ["submission-intake"]) - self.assertIn("--queues=celery,workstream.outbox", self.services["worker"]["command"]) + self.assertIn("--queues=workstream.project_setup", self.services["worker"]["command"]) # Compose turns escaped dollars into shell variables at container launch. script = service["command"][2].replace("$$", "$") with tempfile.TemporaryDirectory() as directory: From f40071744430dc7f26edb679e6b72af7e345ba80 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 07:48:10 +0100 Subject: [PATCH 344/513] Record schema timeout evidence and combined journey boundaries --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 28d3831c2..9a0b04306 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10974,3 +10974,27 @@ unknown task. The launch receipt names the base commit because the working tree held this patch, so it is scope-compatible dirty-tree evidence, not clean-head qualification. Focused topology, rendered hosted/local configuration, Ruff, structure, Commitrail and changed Markdown links are checked separately. + + +### Remaining full-suite schema execution boundary + +Backend run 45465160851 at PR head 65a176a69 completed with all project/task +lanes passing. The nine shared shards executed all 6717 assigned nodes with +no skips/deselections; their concrete contract/fixture failures are addressed +by the reviewed local repairs. This is not a final-head CI pass. +The schema lane exhausted its unchanged 1500-second budget: artifact 14957896305 +records 237 of 584 nodes complete, including all 56 isolated-runner admin cases +and 65 of 70 Alembic cases, without a reported assertion failure. Root's bounded +remaining-five-case probe at 3334fa566 also reached its 180-second bound after +three completed cases; this is incomplete execution, not a pass or proof of a +specific hanging test. Its receipt confirms schema 0091 and complete owned +database/MinIO cleanup. Private evidence: `/tmp/submission-schema-65a.zip`, +`/tmp/submission-schema-tail-65a.log`, `/tmp/submission-schema-tail-65a.json`. +Full schema execution still needs bounded capacity diagnosis/partition and a +complete run; do not skip cases or treat the timeout as an assertion repair. + +Queue isolation is integrated at db4f0a92c after scoped ARCH review and real +scanner/finalizer proof. The native public-journey caller still needs its owned +worker lifecycle updated before the combined live drill. The submitter handoff +core remains in a separate reviewed candidate pending historical-upgrade and +public read tests. All changes remain in PR 708; PR 709 is not our workstream. From 4d423427ad2225face8e1954185cacb5b3270198 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 07:50:10 +0100 Subject: [PATCH 345/513] Track submitter journey additions within PR 708 --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index ef3ca6781..35f5be797 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -31,6 +31,26 @@ Recent focused evidence includes atomic invalidation (`8a854f7a6`), public ZIP/T5 lineage (`168e5268f`), and policy-error translation (`d31a45773`). These and the cleanup/recovery runs recorded below are bounded results, not full-head qualification. +## Submitter experience reconciliation in PR 708 + +The user-provided `workstream_submission_pr_708_addition.md` supplements the +execution specification and supersedes conflicting public-input/guide-access +requirements. All implementation belongs in this PR; PR 709 is not part of this +work. Existing reward owners remain authoritative. + +- [ ] Four required submission inputs and optional feedback; backend-selected revision context and exact actor-scoped replay. +- [ ] Forward migration preserves historical accepted commands and refuses unsafe old in-flight work before mutation. +- [ ] Approved project and governing task guides are readable/downloadable before claim under exact contributor authority. +- [ ] Exact task/assignment status exposes current safe feedback, processing activity, revision terms and accepted evidence without internal-ID discovery. +- [ ] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits. +- [ ] Combined public contributor journey proves correction, revision, replay, history and applicable existing awards on the integrated code. + +Dedicated queue/consumer implementation and its real isolated scanner-to-T5 +regression are integrated; native caller conversion and deployed qualification +remain required. The managed-style adapter substitution passed through public +ZIP acceptance, retained source custody, real T5 owner delivery and replay; +it does not establish a deployed managed provider or broker-consumer proof. + ## Execution deployment decision The API/application server and microVM execution run on separate infrastructure. @@ -39,7 +59,8 @@ mixed queue list, and no catch-all worker handles unrelated workloads. Outbox publication must remain available while POST execution is stopped or saturated; it must not share the POST or submission-finalization consumer. The PRE6 drill accepted a fresh source but exposed publication waiting behind the paused general -worker, so dedicated scanner delivery and the corresponding T5 proof remain open. +worker. Dedicated scanner delivery now has a real Redis/prefork T5 proof; +combined native and deployed confirmation remain open. The application instance is a verified t3.large; the dedicated always-on runner is an m7i.large with native KVM. App-origin mTLS health and native transport smoke receipts establish connectivity. V14 also proves the connected local API From 125bdd82342a3e586701392ba437f8bd944a8ce7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 07:58:32 +0100 Subject: [PATCH 346/513] ci: partition schema contracts without widening execution budgets --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 85 +++++++++++++++++++ .github/workflows/backend.yml | 8 +- backend/scripts/test_lane_catalogue.py | 61 +++++++------ .../scripts/validate_test_lane_evidence.py | 2 +- backend/tests/test_ci_lane_catalogue.py | 80 ++++++++++++----- backend/tests/test_ci_scope_selection.py | 2 +- backend/tests/test_ci_test_lanes.py | 12 +-- .../tests/test_merge_test_lane_evidence.py | 4 +- backend/tests/test_test_lane_evidence.py | 12 +-- docs/operations_backend_testing.md | 17 ++-- 10 files changed, 207 insertions(+), 76 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 9a0b04306..0b9ca1b87 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -10998,3 +10998,88 @@ scanner/finalizer proof. The native public-journey caller still needs its owned worker lifecycle updated before the combined live drill. The submitter handoff core remains in a separate reviewed candidate pending historical-upgrade and public read tests. All changes remain in PR 708; PR 709 is not our workstream. + + +### Bounded schema lane capacity partition (2026-11-26) + +Intent: Backend45465160851 schema artifact14957896305 has584canonical nodes +(528ordinary,56admin),237completed (181ordinary,56admin), zero skip/deselection +and1502.273seconds before unchanged1500-second interruption.65/70Alembic cases +completed. Root remaining-five-case probe also reached180seconds after three +completions with completecleanup; sortedmetadata/progress does not identify a +hanging node. No assertion repair or skipped case follows from these timeouts. + +Scope exactly ten paths: existing test_lane_catalogue.py, independent +validate_test_lane_evidence.py, Backendworkflow, test_ci_lane_catalogue.py, +test_ci_scope_selection.py, test_ci_test_lanes.py, test_test_lane_evidence.py, +test_merge_test_lane_evidence.py, operations_backend_testing.md and this record. +Use the existing hash to partition the entire current schema family across +schema_contracts_a, schema_contracts_b and schema_contracts_c. Preserve all module +membership, current A30 inventory, otherfamily ownership, every node and runtime +kind. Admin runner self-tests still execute in separate admin units; ordinary +children retain isolated credential/database custody. All three schema jobs and +the aggregate remain disk-backed. Total required lanes23->25 with exact distinct +coverage/fan-in/validator inventory. Keep1500seconds, all blocking gates and all +cleanup/skip/deselection/duplicate/partial-execution checks unchanged. + +Existinghash on the historical584nodes gives191/207/186total,175/178/175ordinary, +16/29/11admin and29/26/15Alembic across three shards. Two shards leave259/269 +ordinary and35/35Alembic; three is the smallest placing every ordinary group +below the181observed ordinary completions, with expensive Alembic groups reduced +from70to atmost29. Counts guide capacity, not timingqualification or a diagnosis +of an individual slow/hanging case. Existingnodehash and runtime are unchanged. + +Acceptance: exact old-to-new canonical row preservation except schema owner, +no foreignfamily changes, deterministic/order-independent and head-independent +one-owner partition, unchangedadmin classification/credentials, all3disk-backed +workflow selection, missing/duplicate/new-shard evidence rejection and existing +purelane suites. Risk is CI capacity/custody; root+ARCH review exact gates and +admin isolation before push. No heavy PostgreSQL run, cancellation, rerun, product +change, newframework, timeoutincrease or PR709 work. Fresh hosted completion +remains required. Runtime roadmap capabilities do not change. + +Candidate uses consistent schema_contracts_a/b/c names; the ambiguous old +unsuffixed lane is retired from active callers. The existing schema module tuple +is moved unchanged into SCHEMA_CONTRACT_MODULES, registered as one more existing +partition group. No new runner or hash path. All three schema jobs explicitly +select disk storage both in PostgreSQL container options and the independent +mount/write-settings expectation. Exact hosted fan-in/coverage and independent +validator require25lanes. Every1500-second execution budget is unchanged. + +The saved12423-node manifest comparison preserves all node IDs, module names and +execution kinds; only584schema owner fields change, with11839other owners +unchanged (/tmp/submission-schema-capacity-preservation.json). The current A30 +shared module membership/fingerprint and all other family definitions are +unchanged. This historical redistribution is not a current full collection or +actual execution result. + +Focused existing five-module CI suite passed335tests in100.20s +(/tmp/submission-schema-capacity-pure-v1.log), including deterministic reversed +input/head independence, every schema module partitioned once, ordinary/admin +kind preservation, exact three-shard scope selection, strict25-row timings and +fan-in/independent custody failures on all three schema names. Existing missing, +foreign, partial/duplicate/skipped and latest-invalid/no-fallback controls remain +blocking. Tests still require separate ordinary coverage even when admin coverage +is empty. The plugin-disabled pure run has its existing asyncio_mode warning; +no async or database test was silently skipped. + +An isolated source-only workflow probe kills omission of one schema disk member, +reversal of the storage guard expectation, and an increased execution budget. No +shared file was mutated by these probes. The regular pure suite also checks exact +three-name membership in both disk rules and unchanged45-minute job allowance. +Ruff and whitespace pass; full unchanged structural validation is recorded at +completion separately. No PostgreSQL, native runner, deployment, CI rerun, +cancellation or push was started. Hosted timing/completeness must still be +qualified on the combined candidate; no individual timeout/hang is declared fixed. + +Final unchanged structural validator exits0 +(/tmp/submission-schema-capacity-structure.log). Source binding confirms the +old schema module tuple is identical, every non-schema lane definition is +unchanged, A30 membership remains present, and run_test_lanes.py has no diff +(/tmp/submission-schema-capacity-source-binding.json). Pure tests executed these +modified candidate files over clean basef40071744 before commit; subsequent +changes were documentation/evidence only. This is bounded precommit verification, +not a clean-head hosted run. Ruff, links, Commitrail and whitespace pass. Root +inspected the scoped diff with no blocker; independent ARCH review and combined +25-lane hosted completion remain pending. No schema test was executed or skipped +locally for this partition change, and no other workstream/PR was touched. diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml index 098556949..d43af32c8 100644 --- a/.github/workflows/backend.yml +++ b/.github/workflows/backend.yml @@ -340,7 +340,7 @@ jobs: ports: - 5433:5432 options: >- - ${{ matrix.lane != 'schema_contracts' && '--tmpfs /var/lib/postgresql/data:rw,nosuid,nodev,noexec,size=2147483648' || '' }} + ${{ !contains(fromJSON('["schema_contracts_a","schema_contracts_b","schema_contracts_c"]'), matrix.lane) && '--tmpfs /var/lib/postgresql/data:rw,nosuid,nodev,noexec,size=2147483648' || '' }} --health-cmd "pg_isready -U workstream -d workstream_test" --health-interval 5s --health-timeout 5s @@ -415,7 +415,7 @@ jobs: - name: Verify PostgreSQL CI storage and write settings env: POSTGRES_CONTAINER: ${{ job.services.postgres.id }} - EXPECTED_PG_STORAGE: ${{ matrix.lane == 'schema_contracts' && 'disk' || 'tmpfs' }} + EXPECTED_PG_STORAGE: ${{ contains(fromJSON('["schema_contracts_a","schema_contracts_b","schema_contracts_c"]'), matrix.lane) && 'disk' || 'tmpfs' }} shell: bash run: | set -euo pipefail @@ -652,7 +652,7 @@ jobs: set -euo pipefail shopt -s nullglob coverage_files=(.ci/test-lanes/run/.coverage.*) - test "${#coverage_files[@]}" -eq 23 + test "${#coverage_files[@]}" -eq 25 for source in "${coverage_files[@]}"; do destination="$(basename "${source}")" test -f "${source}" @@ -731,7 +731,7 @@ jobs: raise SystemExit("hosted evidence head drift") lanes = summary.get("lanes") - if not isinstance(lanes, list) or len(lanes) != 23: + if not isinstance(lanes, list) or len(lanes) != 25: raise SystemExit("invalid hosted lane inventory") collected: list[str] = [] completed: list[str] = [] diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 57095557e..8a4e48a18 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -4,6 +4,11 @@ ADMIN_RUNNER_MODULE = "tests/test_isolated_database_runner.py" SCHEMA_MODULE = "tests/test_alembic.py" +PARTITIONED_SCHEMA_LANES = ( + "schema_contracts_a", + "schema_contracts_b", + "schema_contracts_c", +) PARTITIONED_SHARED_LANES = ( "shared_foundations_a", "shared_foundations_b", @@ -775,10 +780,37 @@ class TestLane: ), } +SCHEMA_CONTRACT_MODULES = ( + SCHEMA_MODULE, + "tests/test_checker_evidence_migrations.py", + "tests/migrations/test_project_catalogue_read.py", + "tests/migrations/test_guide_check_specification.py", + "tests/migrations/test_contribution_read_audit.py", + "tests/migrations/test_contribution_export_snapshots.py", + "tests/reviews/lifecycle/test_contracts.py", + "tests/reviews/lifecycle/test_storage.py", + "tests/reviews/lifecycle/test_transition_storage.py", + "tests/reviews/lifecycle/test_fence.py", + "tests/reviews/lifecycle/test_migration.py", + "tests/reviews/acceptance/test_contracts.py", + "tests/reviews/acceptance/test_storage.py", + "tests/reviews/acceptance/test_migration.py", + "tests/test_database_reset.py", + "tests/test_ci_lane_catalogue.py", + "tests/test_ci_scope_selection.py", + "tests/test_ci_test_lanes.py", + "tests/test_test_lane_evidence.py", + "tests/test_merge_test_lane_evidence.py", + *TASK_ROUTING_REQUEST_MODULES, + *OBSERVABILITY_MODULES, + ADMIN_RUNNER_MODULE, +) + PARTITION_GROUPS = ( (PARTITIONED_SHARED_LANES, SHARED_FOUNDATION_MODULES), (PARTITIONED_PROJECT_LANES, PROJECT_PARTITIONED_MODULES), (PARTITIONED_TASK_LANES, TASK_MODULES), + (PARTITIONED_SCHEMA_LANES, SCHEMA_CONTRACT_MODULES), ) PARTITION_LANES_BY_MODULE = { module: PROJECT_MODULE_LANE_OVERRIDES.get(module, names) @@ -788,34 +820,7 @@ class TestLane: LANES = ( *(TestLane(name, SHARED_FOUNDATION_MODULES) for name in PARTITIONED_SHARED_LANES), - TestLane( - "schema_contracts", - ( - SCHEMA_MODULE, - "tests/test_checker_evidence_migrations.py", - "tests/migrations/test_project_catalogue_read.py", - "tests/migrations/test_guide_check_specification.py", - "tests/migrations/test_contribution_read_audit.py", - "tests/migrations/test_contribution_export_snapshots.py", - "tests/reviews/lifecycle/test_contracts.py", - "tests/reviews/lifecycle/test_storage.py", - "tests/reviews/lifecycle/test_transition_storage.py", - "tests/reviews/lifecycle/test_fence.py", - "tests/reviews/lifecycle/test_migration.py", - "tests/reviews/acceptance/test_contracts.py", - "tests/reviews/acceptance/test_storage.py", - "tests/reviews/acceptance/test_migration.py", - "tests/test_database_reset.py", - "tests/test_ci_lane_catalogue.py", - "tests/test_ci_scope_selection.py", - "tests/test_ci_test_lanes.py", - "tests/test_test_lane_evidence.py", - "tests/test_merge_test_lane_evidence.py", - *TASK_ROUTING_REQUEST_MODULES, - *OBSERVABILITY_MODULES, - ADMIN_RUNNER_MODULE, - ), - ), + *(TestLane(name, SCHEMA_CONTRACT_MODULES) for name in PARTITIONED_SCHEMA_LANES), *( TestLane( name, diff --git a/backend/scripts/validate_test_lane_evidence.py b/backend/scripts/validate_test_lane_evidence.py index 9bee46efb..0a1bc911d 100644 --- a/backend/scripts/validate_test_lane_evidence.py +++ b/backend/scripts/validate_test_lane_evidence.py @@ -24,7 +24,7 @@ from scripts.record_id_collection import RecordIdCollection # noqa: E402 SCHEMA_VERSION = 1 -LANE_COUNT = 23 +LANE_COUNT = 25 SHA_RE = re.compile(r"^[0-9a-f]{40}$") DIGEST_RE = re.compile(r"^[0-9a-f]{64}$") LANE_RE = re.compile(r"^[a-z][a-z0-9_]*$") diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py index 287b0d664..05174e28c 100644 --- a/backend/tests/test_ci_lane_catalogue.py +++ b/backend/tests/test_ci_lane_catalogue.py @@ -24,9 +24,9 @@ def test_committed_lanes_cover_recursive_inventory_exactly_once() -> None: runner.validate_lane_inventory(discovered) assigned = [module for lane in LANES for module in lane.modules] - assert len(LANES) == 23 + assert len(LANES) == 25 assert all(lane.requires_postgres for lane in LANES) - assert Counter(assigned)[catalogue.SCHEMA_MODULE] == 1 + assert Counter(assigned)[catalogue.SCHEMA_MODULE] == 3 assert all( count == ( @@ -38,7 +38,7 @@ def test_committed_lanes_cover_recursive_inventory_exactly_once() -> None: ) assert set(assigned) == set(discovered) assert runner.ADMIN_RUNNER_MODULE in next( - lane.modules for lane in LANES if lane.name == "schema_contracts" + lane.modules for lane in LANES if lane.name == "schema_contracts_a" ) @@ -48,7 +48,7 @@ def test_architecture_inspections_share_capacity_without_losing_nodes() -> None: "tests/architecture/test_module_boundaries.py", "tests/architecture/test_test_structure_boundary.py", } - schema = next(lane for lane in LANES if lane.name == "schema_contracts") + schema = next(lane for lane in LANES if lane.name == "schema_contracts_a") assert modules.isdisjoint(schema.modules) for module in modules: assert catalogue.PARTITION_LANES_BY_MODULE[module] == catalogue.PARTITIONED_SHARED_LANES @@ -229,6 +229,10 @@ def test_expanded_lane_families_keep_exact_semantic_owners() -> None: ), catalogue.TASK_MODULES, ), + ( + ("schema_contracts_a", "schema_contracts_b", "schema_contracts_c"), + catalogue.SCHEMA_CONTRACT_MODULES, + ), ) assert catalogue.PARTITION_GROUPS == tuple( (lane_names, modules) for lane_names, modules in expected_families @@ -253,7 +257,10 @@ def test_expanded_lane_families_keep_exact_semantic_owners() -> None: } partitioned_modules = set().union(*(set(modules) for _, modules in expected_families)) assert set(catalogue.STATIC_FOUNDATION_MODULES) <= set(catalogue.SHARED_FOUNDATION_MODULES) - assert schema_static_contracts.isdisjoint(partitioned_modules) + assert schema_static_contracts <= set(catalogue.SCHEMA_CONTRACT_MODULES) + assert schema_static_contracts.isdisjoint( + partitioned_modules - set(catalogue.SCHEMA_CONTRACT_MODULES) + ) assert { "tests/test_alembic.py", "tests/test_checker_evidence_migrations.py", @@ -273,7 +280,7 @@ def test_expanded_lane_families_keep_exact_semantic_owners() -> None: runner.ADMIN_RUNNER_MODULE, } | schema_static_contracts | set(catalogue.OBSERVABILITY_MODULES) | set( catalogue.TASK_ROUTING_REQUEST_MODULES - ) == modules_by_lane["schema_contracts"] + ) == modules_by_lane["schema_contracts_a"] def test_post_submit_and_packet_custody_share_foundations_without_losing_nodes() -> None: @@ -568,20 +575,35 @@ def test_manifest_classifies_only_runner_self_tests_as_admin_kind() -> None: admin: runner.ADMIN_KIND, ordinary: runner.ORDINARY_KIND, } - assert next(row for row in rows if row["nodeid"] == admin)["lane"] == "schema_contracts" - - -def test_schema_nodes_share_one_lane() -> None: - nodes = [f"{catalogue.SCHEMA_MODULE}::test_migration_{index}" for index in range(100)] - rows = runner.build_manifest("a" * 40, nodes)["nodes"] - assert {row["lane"] for row in rows} == {"schema_contracts"} - assert [row["nodeid"] for row in rows] == sorted(nodes) + assert next(row for row in rows if row["nodeid"] == admin)["lane"] == ( + "schema_contracts_a", "schema_contracts_b", "schema_contracts_c" + )[hashlib.sha256(admin.encode()).digest()[0] % 3] + + +def test_schema_nodes_partition_once_with_admin_kind_and_order_independence() -> None: + names = ("schema_contracts_a", "schema_contracts_b", "schema_contracts_c") + nodes = [f"{module}::test_schema[{index}]" + for module in catalogue.SCHEMA_CONTRACT_MODULES for index in range(64)] + first = runner.build_manifest("a" * 40, nodes)["nodes"] + reversed_rows = runner.build_manifest("b" * 40, list(reversed(nodes)))["nodes"] + assert first == reversed_rows + assert Counter(row["nodeid"] for row in first) == Counter(nodes) + assert {row["lane"] for row in first} == set(names) + for row in first: + assert row["lane"] == names[hashlib.sha256(row["nodeid"].encode()).digest()[0] % 3] + assert row["execution_kind"] == ( + runner.ADMIN_KIND if row["module"] == runner.ADMIN_RUNNER_MODULE else runner.ORDINARY_KIND + ) + for name in names: + partition = [row for row in first if row["lane"] == name] + assert {row["execution_kind"] for row in partition} == {runner.ADMIN_KIND, runner.ORDINARY_KIND} + assert any(row["module"] == catalogue.SCHEMA_MODULE for row in partition) @pytest.mark.parametrize( ("names", "modules"), catalogue.PARTITION_GROUPS, - ids=("shared", "project", "task"), + ids=("shared", "project", "task", "schema"), ) def test_owner_nodes_partition_deterministically(names, modules) -> None: module = modules[0] @@ -634,7 +656,7 @@ def test_manifest_has_no_exclusion_escape_hatch() -> None: assert manifest["nodes"] == [ { "execution_kind": runner.ADMIN_KIND, - "lane": "schema_contracts", + "lane": "schema_contracts_a", "module": runner.ADMIN_RUNNER_MODULE, "nodeid": admin, } @@ -757,7 +779,7 @@ def test_partition_rejects_inexact_ordered_owners( changed = { "missing": owners[:-1], "duplicate": (*owners[:-1], owners[0]), - "foreign": (*owners[:-1], "schema_contracts"), + "foreign": (*owners[:-1], "schema_contracts_a"), }[mutation] monkeypatch.setitem(runner.PARTITION_LANES_BY_MODULE, module, changed) @@ -820,8 +842,8 @@ def test_workflow_lane_inventory_matches_catalogue() -> None: assert source.count("path: backend/.ci/download\n merge-multiple: false") == 1 assert '--expected-head "${GITHUB_SHA}"' in source assert '--run-attempt "${GITHUB_RUN_ATTEMPT}"' in source - assert 'test "${#coverage_files[@]}" -eq 23' in source - assert "len(lanes) != 23" in source + assert 'test "${#coverage_files[@]}" -eq 25' in source + assert "len(lanes) != 25" in source assert 'Path(".ci/download"), expected_head, int(os.environ["GITHUB_RUN_ATTEMPT"])' in source assert 'timing_path = bundle / "job-start-epoch.txt"' in source assert ( @@ -957,9 +979,10 @@ def test_routing_request_proofs_use_schema_lane_with_measured_headroom(): assert set(catalogue.TASK_ROUTING_REQUEST_MODULES) == expected for lane in LANES: assert set(lane.modules) & expected == ( - expected if lane.name == "schema_contracts" else set() + expected if lane.name in catalogue.PARTITIONED_SCHEMA_LANES else set() ) - assert not expected & set(catalogue.PARTITION_LANES_BY_MODULE) + assert all(catalogue.PARTITION_LANES_BY_MODULE[module] == catalogue.PARTITIONED_SCHEMA_LANES + for module in expected) def test_observability_proofs_use_schema_lane_with_measured_headroom(): @@ -971,9 +994,10 @@ def test_observability_proofs_use_schema_lane_with_measured_headroom(): assert set(catalogue.OBSERVABILITY_MODULES) == expected for lane in LANES: assert set(lane.modules) & expected == ( - expected if lane.name == "schema_contracts" else set() + expected if lane.name in catalogue.PARTITIONED_SCHEMA_LANES else set() ) - assert not expected & set(catalogue.PARTITION_LANES_BY_MODULE) + assert all(catalogue.PARTITION_LANES_BY_MODULE[module] == catalogue.PARTITIONED_SCHEMA_LANES + for module in expected) def test_routing_authorization_proofs_use_the_project_partition(): @@ -1017,3 +1041,13 @@ def test_evaluation_custody_proofs_use_project_lane_headroom(): catalogue.PARTITION_LANES_BY_MODULE[path] == catalogue.PARTITIONED_PROJECT_LANES for path in expected ) + + +def test_workflow_schema_shards_keep_exact_disk_storage_and_budget() -> None: + source = (runner.ROOT.parent / ".github/workflows/backend.yml").read_text() + member = "contains(fromJSON('[\"schema_contracts_a\",\"schema_contracts_b\",\"schema_contracts_c\"]'), matrix.lane)" + assert source.count(member) == 2 + assert ("${{ !" + member + " && '--tmpfs /var/lib/postgresql/data:rw,nosuid,nodev,noexec,size=2147483648' || '' }}") in source + assert ("EXPECTED_PG_STORAGE: ${{ " + member + " && 'disk' || 'tmpfs' }}") in source + assert source.count("--timeout-seconds 1500") == 2 + assert "timeout-minutes: 45" in source diff --git a/backend/tests/test_ci_scope_selection.py b/backend/tests/test_ci_scope_selection.py index 737ef3d61..689fdc648 100644 --- a/backend/tests/test_ci_scope_selection.py +++ b/backend/tests/test_ci_scope_selection.py @@ -102,7 +102,7 @@ def test_external_checker_change_requires_full_unmapped_consumer_proof() -> None @pytest.mark.parametrize( ("path", "expected"), [ - ("backend/tests/test_observability.py", ("schema_contracts",)), + ("backend/tests/test_observability.py", ("schema_contracts_a", "schema_contracts_b", "schema_contracts_c")), ( "backend/tests/projects/guide_activation/test_contracts.py", ( diff --git a/backend/tests/test_ci_test_lanes.py b/backend/tests/test_ci_test_lanes.py index bafc28b5e..caf16a0a4 100644 --- a/backend/tests/test_ci_test_lanes.py +++ b/backend/tests/test_ci_test_lanes.py @@ -134,7 +134,7 @@ def test_admin_runner_environment_retains_only_admin_database_url( monkeypatch.setenv( "WORKSTREAM_TEST_DATABASE_URL", "postgresql+asyncpg://test:secret@localhost/test" ) - lane = next(lane for lane in LANES if lane.name == "schema_contracts") + lane = next(lane for lane in LANES if lane.name == "schema_contracts_a") env = runner.admin_runner_environment(lane, tmp_path, tmp_path / ".coverage", "admin") @@ -171,10 +171,10 @@ def test_admin_wrapper_redacts_admin_url_before_persisted_output() -> None: def test_finalize_lane_requires_ordinary_coverage_but_allows_empty_admin_coverage( tmp_path: Path, ) -> None: - lane = next(lane for lane in LANES if lane.name == "schema_contracts") + lane = next(lane for lane in LANES if lane.name == "schema_contracts_a") isolation = tmp_path / f"{lane.name}.database.json" isolation.write_text("{}\n", encoding="utf-8") - ordinary_coverage = tmp_path / ".coverage.unit.schema_contracts" + ordinary_coverage = tmp_path / ".coverage.unit.schema_contracts_a" ordinary_coverage.write_bytes(b"ordinary coverage") units = [ { @@ -193,7 +193,7 @@ def test_finalize_lane_requires_ordinary_coverage_but_allows_empty_admin_coverag "collection_exit_code": 0, "collected_nodes": [f"{runner.ADMIN_RUNNER_MODULE}::test_one"], "completed_nodes": [f"{runner.ADMIN_RUNNER_MODULE}::test_one"], - "coverage_path": tmp_path / ".coverage.unit.schema_contracts.admin", + "coverage_path": tmp_path / ".coverage.unit.schema_contracts_a.admin", "deselected_nodes": [], "elapsed_seconds": 2.0, "execution_kind": runner.ADMIN_KIND, @@ -337,11 +337,13 @@ def test_timing_summary_is_derived_from_exact_declared_lanes() -> None: 0.25, 0.25, 0.25, + 0.25, + 0.25, ) lanes = [{"elapsed_seconds": value} for value in elapsed] assert runner._timing_summary(lanes) == { - "aggregate_runner_seconds": 16.5, + "aggregate_runner_seconds": 17.0, "slowest_lane_seconds": 3.75, } with pytest.raises(LaneError, match="invalid_lane_timing_inventory"): diff --git a/backend/tests/test_merge_test_lane_evidence.py b/backend/tests/test_merge_test_lane_evidence.py index f1c8e2cab..7302c6770 100644 --- a/backend/tests/test_merge_test_lane_evidence.py +++ b/backend/tests/test_merge_test_lane_evidence.py @@ -110,7 +110,7 @@ def test_merge_bundles_emits_complete_run_summary(tmp_path: Path) -> None: assert len(list((tmp_path / "merged").glob(".coverage.*"))) == len(LANES) -@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) +@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "schema_contracts_a", "schema_contracts_b", "schema_contracts_c", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) @pytest.mark.parametrize("damage", ["missing", "foreign"]) def test_merge_bundles_rejects_missing_or_foreign_lane(tmp_path: Path, lane_name: str, damage: str) -> None: source = tmp_path / "source" @@ -217,7 +217,7 @@ def test_partial_retry_selects_numeric_latest_before_validation(tmp_path: Path) ("coverage", "invalid_lane_bundle_file"), ("head", "invalid_lane_bundle_summary"), ]) -@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) +@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "schema_contracts_a", "schema_contracts_b", "schema_contracts_c", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) def test_latest_invalid_attempt_never_falls_back(tmp_path: Path, damage: str, error: str, lane_name: str) -> None: source = tmp_path / "source" _bundles(source) diff --git a/backend/tests/test_test_lane_evidence.py b/backend/tests/test_test_lane_evidence.py index e1f072047..69d65d6d9 100644 --- a/backend/tests/test_test_lane_evidence.py +++ b/backend/tests/test_test_lane_evidence.py @@ -30,7 +30,9 @@ "shared_foundations_g", "shared_foundations_h", "shared_foundations_i", - "schema_contracts", + "schema_contracts_a", + "schema_contracts_b", + "schema_contracts_c", "project_lifecycle_a", "project_lifecycle_b", "project_lifecycle_c", @@ -48,7 +50,7 @@ def test_validator_requires_exact_expanded_lane_and_shared_s3_custody() -> None: - assert validator.LANE_COUNT == len(LANES) == 23 + assert validator.LANE_COUNT == len(LANES) == 25 assert validator.SHARED_S3_LANES == {"omnicore_sdk"} @@ -73,7 +75,7 @@ def _bundle(tmp_path: Path, mode: str = "run") -> tuple[Path, Path, dict]: nodes.append( { "execution_kind": "admin_runner_self_test", - "lane": "schema_contracts", + "lane": "schema_contracts_a", "module": "tests/test_isolated_database_runner.py", "nodeid": "tests/test_isolated_database_runner.py::test_admin_custody", } @@ -225,7 +227,7 @@ def test_rejects_wrong_head_and_noncanonical_manifest(tmp_path: Path) -> None: ), ], ) -@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) +@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "schema_contracts_a", "schema_contracts_b", "schema_contracts_c", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) def test_rejects_node_custody_failures(tmp_path: Path, mutation, message: str, lane_name: str) -> None: metadata, summary_path, summary = _bundle(tmp_path) lane = next(row for row in summary["lanes"] if row["name"] == lane_name) @@ -250,7 +252,7 @@ def test_rejects_node_custody_failures(tmp_path: Path, mutation, message: str, l ("interrupted", True, "lane_interrupted"), ], ) -@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) +@pytest.mark.parametrize("lane_name", ["shared_foundations_a", "shared_foundations_i", "schema_contracts_a", "schema_contracts_b", "schema_contracts_c", "project_lifecycle_d", "project_lifecycle_e", "task_lifecycle_d"]) def test_rejects_failed_or_partial_lane( tmp_path: Path, field: str, value: object, message: str, lane_name: str ) -> None: diff --git a/docs/operations_backend_testing.md b/docs/operations_backend_testing.md index 7e21de63a..a67cc59ff 100644 --- a/docs/operations_backend_testing.md +++ b/docs/operations_backend_testing.md @@ -172,7 +172,7 @@ Assertion-map validation analyzes each exact historical revision/module once per invocation, then checks every referenced node and assertion against that analysis. It does not cache current source or reuse analysis across validation calls. -The fifteen ordinary lanes use private, 2 GiB RAM-backed PostgreSQL data directories +Non-schema lane jobs use private, 2 GiB RAM-backed PostgreSQL data directories to reduce ephemeral reset I/O. A runtime guard verifies the mount, capacity, data directory and enabled `fsync`, `full_page_writes` and `synchronous_commit` before tests. Real SQL, transaction, lock, isolation, and full hosted behavior @@ -183,7 +183,7 @@ replacement use `postgres_schema_contract` to rebuild it. The contribution storage function-replacement and trigger-removal controls explicitly roll back their transaction-local DDL and retain canonical teardown verification. No assertions or storage tests are omitted. -The schema-contract lane and aggregate job retain disk-backed databases. +All three schema-contract shards and the aggregate job retain disk-backed databases. This is not a production configuration or proof of host-power-loss durability: [Docker tmpfs data disappears when the container stops](https://docs.docker.com/engine/storage/tmpfs/). An exhausted mount fails the job; it does not silently change storage or skip tests. @@ -208,16 +208,19 @@ The isolated runner retains those bytes if a later test times out; its existing outer output buffering and redaction remain in place. Measure final-report overhead alongside test execution when comparing allocations. The five `task_lifecycle_a` through `task_lifecycle_e` lanes use the same -deterministic partition mechanism for the remaining TASK and checker nodes. The single `schema_contracts` lane owns all baseline/PostgreSQL schema, reset and -isolated-runner contracts, together with database-backed migration, storage, and -custody proofs. The +deterministic partition mechanism for the remaining TASK and checker nodes. +The three `schema_contracts_a`, `schema_contracts_b`, and `schema_contracts_c` lanes +partition baseline/PostgreSQL schema, reset and isolated-runner contracts, together +with database-backed migration, storage and custody proofs, using that same +exact-node hash. Admin runner tests retain their separate execution kind and +credential custody within each shard; ordinary tests remain isolated. The nine `shared_foundations_a` through `shared_foundations_i` lanes deterministically partition exact node IDs from the remaining authorization, artifact, API, and infrastructure modules. This includes the database-independent repository inspections in `test_artifact_architecture.py`, `architecture/test_module_boundaries.py`, and `architecture/test_test_structure_boundary.py`, together with the static authorization boundary, identifier inventory and record-ID collection checks; schema, reset and -isolated-runner contracts stay in `schema_contracts`. Every collected test node, including each Alembic and +isolated-runner contracts stay in that schema family. Every collected test node, including each Alembic and shared-foundation node, belongs to exactly one lane. An explicit per-module owner tuple may order its eligible lanes for measured distribution. The manifest builder rejects missing, duplicate, or foreign lane @@ -273,7 +276,7 @@ SHA, lane and numeric run attempt, containing its manifest, lane evidence, isolation record, and coverage data. On complete runs, the `full-suite` job runs with a fail-closed dependency guard, downloads available diagnostic bundles, then rejects any failed, cancelled, or skipped matrix result before -fan-in. Fan-in selects the highest numeric attempt available for each of the 23 declared +fan-in. Fan-in selects the highest numeric attempt available for each of the 25 declared lanes from separately downloaded artifact directories. It rejects malformed, foreign or future attempt names and never falls back from an incomplete or corrupt latest bundle to an older passing one. For the selected bundles it From 236f2bab5e135b0cf6328b82fad0096a2f8c2639 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:00:49 +0100 Subject: [PATCH 347/513] Route native public journey workers to dedicated queues --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 25 +++ .../README.md | 9 +- .../run_public_journey_probe.py | 179 +++++++++++++----- scripts/test_public_hosted_attachment.py | 96 ++++++++++ 4 files changed, 263 insertions(+), 46 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0b9ca1b87..344a377ef 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11083,3 +11083,28 @@ not a clean-head hosted run. Ruff, links, Commitrail and whitespace pass. Root inspected the scoped diff with no blocker; independent ARCH review and combined 25-lane hosted completion remain pending. No schema test was executed or skipped locally for this partition change, and no other workstream/PR was touched. + +The existing native public journey launcher also needs this topology. Its +former guide worker selected both `celery` and `workstream.outbox`, which the +singleton guard now rejects. The launcher starts one owned prefork process +for each of the seven exact workload queues, using recorded guide composition +only for project setup and the production app for the other roles. Fault +callbacks pause and restart only POST/outbox delivery; the scanner and T5 +finalizer remain live so accepted-source publication can continue. Every +source-cleanup child receives the separately supplied private deletion +credential and explicit bounded profile; the upload/API credential remains +with the other workers. The profile must identify that upload principal, and +the deletion key must differ. Every +started process is registered before readiness is awaited, and final cleanup +attempts every owned process group even after a prior stop failure. A real +exited-leader/remaining-child regression checks that group cleanup does not +leave a worker behind. Focused command tests pin the complete role/queue/app +map. This is caller closure for a future combined native journey; no new +native trial or deployed worker qualification is claimed by these tests. +The affected hosted-attachment test module passed all 44 cases and 87 subtests; +the focused four-case worker custody subset passed separately. Replacing the +group stop in memory with the previous leader-only return made the real +exited-leader child regression fail, and its `finally` removed that owned +child. Ruff, whitespace and changed Markdown links passed. The two Python +files predate this change with Ruff-format differences, so the edit did not +claim a file-wide format pass. diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md index 0e75aaf17..21eddc342 100644 --- a/experiments/pilot04_external_checker_runtime/README.md +++ b/experiments/pilot04_external_checker_runtime/README.md @@ -136,7 +136,12 @@ traces and retained source/PRE facts supply the fault evidence. Supply the existing parser socket through `WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET`, the canonical remote TLS runner settings, and an explicit `WORKSTREAM_SUBMISSION_EXECUTION_PROFILE`; no parser or runner is provisioned -by this launcher. +by this launcher. The seven dedicated workers also require an explicit +`WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE` whose `upload_principal` matches +the isolated upload key, plus the existing journey fixture's distinct +`WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID` and private mode-0600 +`WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE`. Only the cleanup child receives +that separate credential. ```sh PYTHONPATH=.:tests:.. .venv/bin/python scripts/run_isolated_tests.py \ @@ -152,7 +157,7 @@ PYTHONPATH=.:tests:.. .venv/bin/python scripts/run_isolated_tests.py \ Use a new metadata path, work directory and private broker for each run. The isolated runner owns database/role/bucket/prefix cleanup. The probe stops its API, -worker and Beat; the host supervisor owns node configuration and restart. Remove +seven dedicated workers and Beat; the host supervisor owns node configuration and restart. Remove only the drill's own infrastructure after verifying both cleanup receipts. Do not remove retained product evidence or use broad container/volume pruning. diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 9eed70bf2..93e9d28a3 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -17,6 +17,7 @@ import os from pathlib import Path import signal +import stat import subprocess import sys import tempfile @@ -171,30 +172,58 @@ def _process(command: list[str], *, env: dict[str, str], log: Path) -> subproces ) -def _start_worker(env: dict[str, str], root: Path, generation: int) -> tuple[subprocess.Popen, str]: - """Start one owned prefork worker with a distinct broker identity and log.""" - hostname = f"first-journey-{uuid4().hex}@localhost" +WORKER_ROLES = ( + ("guide", "workstream.project_setup"), + ("project-control", "workstream.project_control"), + ("artifacts", "workstream.artifacts"), + ("outbox-scan", "workstream.outbox_scan"), + ("outbox", "workstream.outbox"), + ("finalization", "workstream.submission_finalization"), + ("source-cleanup", "workstream.source_cleanup"), +) + + +def _start_worker(env: dict[str, str], root: Path, role: str, queue: str, + generation: int = 1) -> tuple[subprocess.Popen, str]: + """Start one owned prefork worker for exactly one registered workload queue.""" + hostname = f"first-journey-{role}-{uuid4().hex}@localhost" + celery_app = ("experiments.pilot04_external_checker_runtime.guide_worker" + if role == "guide" else "app.workers.celery_app") process = _process([ - sys.executable, "-m", "celery", "-A", - "experiments.pilot04_external_checker_runtime.guide_worker", + sys.executable, "-m", "celery", "-A", celery_app, "worker", "--pool=prefork", "--concurrency=1", - "--queues=celery,workstream.outbox", "--hostname", hostname, + f"--queues={queue}", "--hostname", hostname, "--without-gossip", "--without-mingle", "--without-heartbeat", "--loglevel=ERROR", - ], env=env, log=root / ("worker.log" if generation == 1 else f"worker-{generation}.log")) + ], env=env, log=root / f"{role}-worker-{generation}.log") return process, hostname -def _start_finalization_worker(env: dict[str, str], root: Path): - """Use the production exclusive consumer; the general worker cannot consume T5.""" - hostname = f"journey-finalization-{uuid4().hex}@localhost" - process = _process([ - sys.executable, "-m", "celery", "-A", "app.workers.celery_app", "worker", - "--pool=prefork", "--concurrency=1", "--queues=workstream.submission_finalization", - "--hostname", hostname, "--without-gossip", "--without-mingle", "--without-heartbeat", - "--loglevel=ERROR", - ], env=env, log=root / "finalization-worker.log") - return process, hostname +def _source_cleanup_environment(env: dict[str, str], settings) -> dict[str, str]: + """Give only the deletion worker its explicitly supplied separate principal.""" + from app.modules.artifacts.api.submission_cleanup import SubmissionSourceCleanupProfile + + profile = SubmissionSourceCleanupProfile.model_validate( + settings.submission_source_cleanup_profile + ) + upload_key = settings.artifact_s3_access_key_id + _require(upload_key is not None + and profile.upload_principal == upload_key.get_secret_value(), + "source cleanup profile does not identify the upload principal") + cleanup_key = env.get("WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID") + _require(bool(cleanup_key) and cleanup_key != profile.upload_principal, + "source cleanup requires a distinct provider principal") + secret_name = env.get("WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE") + secret_file = Path(secret_name) if secret_name else None + _require(secret_file is not None and secret_file.is_absolute() + and not secret_file.is_symlink() and secret_file.is_file() + and stat.S_IMODE(secret_file.stat().st_mode) == 0o600 + and 0 < secret_file.stat().st_size <= 4096, + "source cleanup requires a private credential file") + cleanup_env = dict(env) + cleanup_env["WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID"] = cleanup_key + cleanup_env["WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY"] = secret_file.read_text(encoding="ascii") + return cleanup_env def _require_source_runtime_window(settings): @@ -220,15 +249,56 @@ def _require_parser_socket(settings): return path +def _live_group_members(group_id: int) -> set[int]: + """Find live members of only this fixture's start_new_session group.""" + members = set() + for entry in Path("/proc").iterdir(): + if not entry.name.isdecimal(): + continue + try: + fields = (entry / "stat").read_text().rsplit(") ", 1)[1].split() + if int(fields[2]) == group_id and fields[0] not in {"Z", "X"}: + members.add(int(entry.name)) + except (IndexError, OSError, ValueError): + continue + return members + + def _stop_process(process: subprocess.Popen | None) -> None: - if process is None or process.poll() is not None: + """Reap a whole owned worker group even if its leader already exited.""" + if process is None: return - os.killpg(process.pid, signal.SIGTERM) - try: - process.wait(timeout=10) - except subprocess.TimeoutExpired: - os.killpg(process.pid, signal.SIGKILL) - process.wait(timeout=5) + group_id = process.pid + if _live_group_members(group_id): + try: + os.killpg(group_id, signal.SIGTERM) + except ProcessLookupError: + pass + deadline = time.monotonic() + 10 + while _live_group_members(group_id) and time.monotonic() < deadline: + time.sleep(0.1) + if _live_group_members(group_id): + try: + os.killpg(group_id, signal.SIGKILL) + except ProcessLookupError: + pass + deadline = time.monotonic() + 5 + while _live_group_members(group_id) and time.monotonic() < deadline: + time.sleep(0.1) + _require(not _live_group_members(group_id), "owned worker retained live children") + process.wait(timeout=1) + + +def _stop_owned_processes(processes: tuple[subprocess.Popen | None, ...]) -> None: + """Attempt every owned group even when one group fails to stop.""" + failures = [] + for process in processes: + try: + _stop_process(process) + except Exception as error: + failures.append(error) + if failures: + raise RuntimeError("owned journey worker cleanup failed") from failures[0] async def _wait_api(origin: str, process: subprocess.Popen) -> None: @@ -1155,6 +1225,11 @@ async def run(database_url: str, image_reference: str, node_config: Path, and runtime_settings.submission_execution_profile is not None, "supply explicit remote TLS runner and source execution profile before qualification") source_profile = _require_source_runtime_window(runtime_settings) + _require(runtime_settings.submission_source_cleanup_profile is not None, + "supply explicit source cleanup profile for the dedicated worker") + cleanup_env = _source_cleanup_environment(env, runtime_settings) + env.pop("WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID", None) + env.pop("WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE", None) _require_parser_socket(runtime_settings) for field in ( "artifact_store_backend", "artifact_s3_provider_profile", "artifact_s3_region", @@ -1181,23 +1256,27 @@ async def run(database_url: str, image_reference: str, node_config: Path, engine = create_async_engine(database_url) factory = async_sessionmaker(engine, expire_on_commit=False) - api = worker = beat = finalization_worker = None + api = worker = beat = None + workers: list[subprocess.Popen] = [] worker_generation = 0 def stop_owned_worker() -> None: _require(worker is not None and worker.poll() is None, - "prefork worker was not running before restart") + "POST effect worker was not running before restart") _stop_process(worker) - _require(worker.poll() is not None, "old prefork worker did not exit") + _require(worker.poll() is not None, "old POST effect worker did not exit") + workers.remove(worker) async def start_owned_worker() -> None: nonlocal worker, worker_generation _require(worker is None or worker.poll() is not None, - "prefork worker was not stopped before restart") + "POST effect worker was not stopped before restart") previous_pid = worker.pid if worker is not None else None worker_generation += 1 - worker, hostname = _start_worker(env, root, worker_generation) - _require(worker.pid != previous_pid, "restart reused the old worker process") + worker, hostname = _start_worker(env, root, "outbox", "workstream.outbox", + worker_generation) + workers.append(worker) + _require(worker.pid != previous_pid, "restart reused the old POST worker process") await _wait_worker(worker, hostname) try: @@ -1225,9 +1304,15 @@ async def start_owned_worker() -> None: "--log-level", "error", "--no-access-log", ], env=env, log=root / "api.log") await _wait_api(origin, api) - await start_owned_worker() - finalization_worker, finalization_hostname = _start_finalization_worker(env, root) - await _wait_worker(finalization_worker, finalization_hostname) + for role, queue in WORKER_ROLES: + process, hostname = _start_worker( + cleanup_env if role == "source-cleanup" else env, root, role, queue + ) + workers.append(process) + await _wait_worker(process, hostname) + if role == "outbox": + worker = process + worker_generation = 1 scans_before_beat = await _scan_audit_count(factory) beat = _process([ sys.executable, "-m", "celery", "-A", "app.workers.celery_app", @@ -1255,15 +1340,16 @@ async def start_owned_worker() -> None: stop_worker=stop_owned_worker, start_worker=start_owned_worker, fault_root=fault_root, operator_token=_token(env, operator)) - _require(api.poll() is None and worker.poll() is None and beat.poll() is None - and finalization_worker.poll() is None, - "API, prefork worker, or Beat exited during public journey") + _require(api.poll() is None and beat.poll() is None + and all(process.poll() is None for process in workers), + "API, dedicated prefork worker, or Beat exited during public journey") return {"tree_sha": subprocess.check_output( ["git", "rev-parse", "HEAD"], text=True, cwd=BACKEND ).strip(), "runtime": "smolvm/smol-microvm", "image_digest": image["platform_manifest_digest"], "trusted_intake_image_digest": intake_health.image_digest, "trusted_intake_config_digest": intake_health.config_digest, - "public_api": True, "prefork_worker": True, "prefork_finalization_worker": True, "maximum_parallel": 1, + "public_api": True, "prefork_worker": True, "prefork_finalization_worker": True, + "dedicated_worker_queues": [queue for _, queue in WORKER_ROLES], "maximum_parallel": 1, "scheduled_artifact_scans": True, "public_original_guide_setup": True, "recorded_inference": True, @@ -1271,13 +1357,18 @@ async def start_owned_worker() -> None: 'source_tree', 'config_sha256', 'service_sha256', 'smol_sha256', 'guest_sha256', 'wrapper_sha256')}, "runtime_trials": runtime_trials, "intake_trials": intake_trials, "human": true, "automatic": false} finally: - _stop_process(beat) - for schedule_file in root.glob("beat-schedule*"): - schedule_file.unlink() - _stop_process(finalization_worker) - _stop_process(worker) - _stop_process(api) - await engine.dispose() + cleanup_error = None + try: + _stop_owned_processes((beat, *reversed(workers), api)) + except RuntimeError as error: + cleanup_error = error + try: + for schedule_file in root.glob("beat-schedule*"): + schedule_file.unlink() + finally: + await engine.dispose() + if cleanup_error is not None: + raise cleanup_error def main() -> int: diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 164cbac47..26dea17c7 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -4,6 +4,7 @@ import asyncio import hashlib import json +import os from itertools import count as sequence from pathlib import Path import shutil @@ -11,6 +12,7 @@ import sys import tempfile import threading +import time import unittest from unittest.mock import AsyncMock, patch from types import SimpleNamespace @@ -25,6 +27,100 @@ ) +class PublicJourneyWorkerCustody(unittest.TestCase): + def test_cleanup_child_alone_receives_a_private_distinct_principal(self): + from pydantic import SecretStr + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'cleanup.secret' + path.write_text('deletion-secret', encoding='ascii') + path.chmod(0o600) + original = { + 'WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID': 'upload-key', + 'WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY': 'upload-secret', + 'WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID': 'cleanup-key', + 'WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE': str(path), + } + settings = SimpleNamespace(artifact_s3_access_key_id=SecretStr('upload-key'), + submission_source_cleanup_profile={'maximum_candidates': 10, + 'run_seconds': 60, 'lease_seconds': 30, 'upload_principal': 'upload-key'}) + child = probe._source_cleanup_environment(original, settings) + self.assertEqual(original['WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID'], 'upload-key') + self.assertEqual(child['WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID'], 'cleanup-key') + self.assertEqual(child['WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY'], 'deletion-secret') + self.assertEqual(set(child) ^ set(original), set()) + for change in ( + {'WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID': 'upload-key'}, + {'WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE': str(path.parent / 'missing')}, + ): + with self.subTest(change=change), self.assertRaises(RuntimeError): + probe._source_cleanup_environment(dict(original, **change), settings) + path.chmod(0o644) + with self.assertRaisesRegex(RuntimeError, 'private credential file'): + probe._source_cleanup_environment(original, settings) + + def test_every_workload_starts_one_dedicated_queue_with_the_right_app(self): + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + expected = ( + ('guide', 'workstream.project_setup'), + ('project-control', 'workstream.project_control'), + ('artifacts', 'workstream.artifacts'), + ('outbox-scan', 'workstream.outbox_scan'), + ('outbox', 'workstream.outbox'), + ('finalization', 'workstream.submission_finalization'), + ('source-cleanup', 'workstream.source_cleanup'), + ) + self.assertEqual(probe.WORKER_ROLES, expected) + with patch.object(probe, '_process', return_value=object()) as launch: + for role, queue in expected: + with self.subTest(role=role): + launch.reset_mock() + probe._start_worker({}, Path('/owned'), role, queue) + command = launch.call_args.args[0] + self.assertEqual([part for part in command if part.startswith('--queues=')], + [f'--queues={queue}']) + self.assertEqual(command[command.index('-A') + 1], + 'experiments.pilot04_external_checker_runtime.guide_worker' + if role == 'guide' else 'app.workers.celery_app') + self.assertIn('--pool=prefork', command) + self.assertIn('--concurrency=1', command) + self.assertIn(f'{role}-worker-1.log', str(launch.call_args.kwargs['log'])) + + def test_stopping_an_exited_leader_reaps_its_owned_child_group(self): + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + launcher = subprocess.Popen([ + sys.executable, '-c', + "import subprocess,sys; child=subprocess.Popen([sys.executable,'-c'," + "'import time;time.sleep(60)'],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL," + "stderr=subprocess.DEVNULL); print(child.pid,flush=True)", + ], stdout=subprocess.PIPE, text=True, start_new_session=True) + assert launcher.stdout is not None + child_pid = int(launcher.stdout.readline()) + launcher.wait(timeout=5) + deadline = time.monotonic() + 2 + while child_pid not in probe._live_group_members(launcher.pid) and time.monotonic() < deadline: + time.sleep(.01) + self.assertIn(child_pid, probe._live_group_members(launcher.pid)) + try: + probe._stop_process(launcher) + self.assertFalse(probe._live_group_members(launcher.pid)) + finally: + if probe._live_group_members(launcher.pid): + os.killpg(launcher.pid, 9) + + def test_partial_startup_still_attempts_every_owned_group_cleanup(self): + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + owned = (object(), object(), object()) + with patch.object(probe, '_stop_process', side_effect=[RuntimeError('first'), None, None]) as stop: + with self.assertRaisesRegex(RuntimeError, 'owned journey worker cleanup failed'): + probe._stop_owned_processes(owned) + self.assertEqual([call.args[0] for call in stop.call_args_list], list(owned)) + + class HostedDuplicateEvents(unittest.TestCase): def observe(self, event_change=None, *, already_enabled=False, restore_reply=None): from celery import Celery From 76f952aeef3ff72949a55ff25d8b1992099bf631 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 07:35:46 +0100 Subject: [PATCH 348/513] Select submission revision context on the server and retain optional feedback --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 28 +++ .../versions/0092_submission_feedback.py | 176 ++++++++++++++++++ backend/app/adapters/artifacts/__init__.py | 3 +- .../app/api/routes/artifact_submissions.py | 32 +++- backend/app/api/submission_intake.py | 27 ++- .../artifacts/api/submission_intake.py | 41 ++-- .../modules/artifacts/intake/finalization.py | 3 +- .../artifacts/intake/foreground_admission.py | 61 ++++-- .../app/modules/artifacts/intake/progress.py | 18 +- .../modules/artifacts/intake/repository.py | 16 +- .../selected_pre_submit_admission.py | 8 +- .../modules/checkers/api/default_checker.py | 3 +- .../checkers/api/pre_submit_material.py | 19 +- .../checkers/api/selected_pre_submit.py | 3 +- .../app/modules/checkers/default_checker.py | 2 + .../app/modules/tasks/api/intake_custody.py | 5 +- .../modules/tasks/api/submission_command.py | 5 +- .../modules/tasks/api/submission_context.py | 35 +--- backend/app/modules/tasks/intake_custody.py | 3 + backend/app/modules/tasks/models.py | 11 +- backend/app/modules/tasks/repository.py | 4 +- backend/app/modules/tasks/schemas.py | 25 --- backend/app/modules/tasks/service.py | 28 --- .../modules/tasks/submission_composition.py | 7 +- .../app/modules/tasks/submission_dispatch.py | 8 +- .../tests/artifacts/qualify_submission_a19.py | 3 +- .../artifacts/test_submission_aws_source.py | 5 +- .../test_submission_intake_admission.py | 4 +- .../test_submission_intake_contracts.py | 67 +++---- .../test_submission_intake_custody.py | 5 +- .../artifacts/test_submission_pre_source.py | 12 +- .../test_checker_retry_history_replay.py | 6 +- .../external/test_selected_pre_submit.py | 49 +---- backend/tests/migration_revision_fixtures.py | 13 +- .../post_submit_materialization_helpers.py | 6 +- backend/tests/retained_material_fixtures.py | 5 +- backend/tests/reviews/decision/support.py | 6 +- backend/tests/tasks/invalidation_support.py | 4 - .../tasks/post_submit_routing/support.py | 18 +- .../test_evaluation_revision.py | 6 +- .../test_predecessor_receipt.py | 6 +- .../test_replacement_creation.py | 13 +- .../test_revision_capacity.py | 36 ++-- .../test_revision_exhaustion.py | 7 +- .../test_revision_exhaustion_recovery.py | 4 +- .../tasks/test_public_submission_intake.py | 67 ++----- .../tests/tasks/test_submission_lineage.py | 84 ++++----- .../tasks/test_submission_requirements.py | 11 +- backend/tests/test_api_controls.py | 47 ++--- ..._submission_bundle_preparation_recovery.py | 3 +- .../test_submission_predecessor_custody.py | 12 +- backend/tests/test_tasks.py | 8 +- 52 files changed, 531 insertions(+), 547 deletions(-) create mode 100644 backend/alembic/versions/0092_submission_feedback.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 344a377ef..c53037226 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11108,3 +11108,31 @@ exited-leader child regression fail, and its `finally` removed that owned child. Ruff, whitespace and changed Markdown links passed. The two Python files predate this change with Ruff-format differences, so the edit did not claim a file-wide format pass. +## Submitter journey reconciliation + +The public ZIP command takes task, assignment, file and caller idempotency key, +with optional exact project feedback. TASK chooses and retains the current +predecessor and revision preparation under lock. Recheck that selection before +PRE and acceptance. T5 consumes accepted evidence. Preserve historical packets +and hashes and keep optional project feedback outside checker eligibility. + +Allowed files for the contract stage are ART's intake API, repository, +foreground admission, progress, registration and finalization, its selected PRE +binding and HTTP route and error adapter. TASK may update its submission context, +intake custody, creation, dispatch, requirements and models. CHECKERS may extend +the packet evidence decoder where required for exact old and new custody. A +forward Alembic migration may update the native guards and add feedback storage. +Directly affected contracts, owner tests, public API fixtures, CLI and MCP inputs +and docs are in scope. The guide and exact assignment read stage extends the +current PROJECTS, ART, AUTH, TASK, CHECKERS and contribution read compositions and +their client contracts and tests. Preserve the T4 status transition and existing +authorization, source custody, terminal outcome and AWARD ownership. Exclude +queue topology, Finance fulfillment, review implementation and email. + +Risk class L0. Architecture, security, QA and test delta review the immutable +inputs, native guards, authorization and replay. Documentation and product +operations review the contributor journey and retained transport limits. Human +review should verify revised selection, closed-assignment isolation and the +difference between a granted award and fulfilled payment. Verification uses +real PostgreSQL and source storage in focused integration cases, plus the +connected CLI/MCP journey against the combined candidate. diff --git a/backend/alembic/versions/0092_submission_feedback.py b/backend/alembic/versions/0092_submission_feedback.py new file mode 100644 index 000000000..61857ba3f --- /dev/null +++ b/backend/alembic/versions/0092_submission_feedback.py @@ -0,0 +1,176 @@ +"""Store optional feedback and server-selected intake lineage without rewriting history.""" + +from alembic import op +from sqlalchemy import text + +revision = "0092_submission_feedback" +down_revision = "0091_qualified_aws_source" +branch_labels = None +depends_on = None + + +def _definition(signature): + return op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))" + ), {"signature": signature}).scalar_one() + + +def _replace(definition, before, after, *, expected=1): + if definition.count(before) != expected: + raise RuntimeError("submission feedback predecessor guard changed") + return definition.replace(before, after) + + +def _intake_guard(): + definition = _definition("public.guard_submission_intake_mutation()") + start = definition.index(" IF NOT (m ?& ARRAY") + end = definition.index(" THEN", definition.index("!~ '^sha256:[0-9a-f]{64}$'", start)) + definition = definition[:start] + """ IF NOT (m ?& ARRAY['task_id','assignment_id','feedback','predecessor_submission_id', + 'revision_preparation_id','revision_preparation_sha256']) + OR m - ARRAY['task_id','assignment_id','feedback','predecessor_submission_id', + 'revision_preparation_id','revision_preparation_sha256'] <> '{}'::jsonb + OR m->>'task_id' IS DISTINCT FROM NEW.task_id::text + OR m->>'assignment_id' IS DISTINCT FROM NEW.assignment_id::text + OR jsonb_typeof(m->'feedback') NOT IN ('string','null') + OR octet_length(m->>'feedback')>4096 + OR (m->>'feedback') COLLATE "C" ~ '[^ -~]' + OR btrim(m->>'feedback') IS DISTINCT FROM m->>'feedback' + OR (NEW.eligible_task_status='needs_revision')<>(m->>'predecessor_submission_id' IS NOT NULL) + OR (NEW.eligible_task_status='needs_revision')<>(m->>'revision_preparation_id' IS NOT NULL) + OR ((m->>'revision_preparation_id' IS NULL)<>(m->>'revision_preparation_sha256' IS NULL)) + OR (m->>'revision_preparation_sha256' IS NOT NULL AND + m->>'revision_preparation_sha256' !~ '^sha256:[0-9a-f]{64}$')""" + definition[end:] + definition = _replace( + definition, + "m || jsonb_build_object('schema_version','workstream.submission_intake_metadata.v1')", + "(m - ARRAY['predecessor_submission_id','revision_preparation_id','revision_preparation_sha256'])" + " || jsonb_build_object('schema_version','workstream.submission_intake_metadata.v2')", + ) + op.execute(definition) + + +def _pre_guard(): + definition = _definition("public.require_selected_pre_source(public.selected_pre_submit_runs)") + definition = _replace( + definition, + "jsonb_build_object(\n 'summary',o.command_metadata->>'summary',\n" + " 'contributor_attestation',o.command_metadata->>'contributor_attestation')", + "public.submission_operation_checker_packet(o.command_metadata)", + ) + definition = _replace( + definition, + "jsonb_build_object('summary',o.command_metadata->>'summary',\n" + " 'contributor_attestation',o.command_metadata->>'contributor_attestation')", + "public.submission_operation_checker_packet(o.command_metadata)", + ) + definition = _replace( + definition, + " OR request->'admission_lineage'->>'rules_sha256' IS DISTINCT FROM", + " OR request->'admission_lineage'->>'predecessor_submission_id' IS DISTINCT FROM\n" + " o.command_metadata->>'predecessor_submission_id'\n" + " OR (o.command_metadata ? 'feedback' AND (\n" + " request->'admission_lineage'->>'revision_preparation_id' IS DISTINCT FROM\n" + " o.command_metadata->>'revision_preparation_id' OR\n" + " request->'admission_lineage'->>'revision_preparation_sha256' IS DISTINCT FROM\n" + " o.command_metadata->>'revision_preparation_sha256'))\n" + " OR request->'admission_lineage'->>'rules_sha256' IS DISTINCT FROM", + ) + op.execute(definition) + + +def _submission_guards(): + packet = _definition("public.validate_submission_packet_custody()") + packet = _replace(packet, " expected_packet text;", " expected_packet text;\n metadata jsonb;") + packet = _replace( + packet, + " SELECT coalesce(evidence.packet_sha256,admission.packet_sha256)\n INTO expected_packet", + " SELECT coalesce(evidence.packet_sha256,admission.packet_sha256),operation.command_metadata\n" + " INTO expected_packet,metadata", + ) + packet = _replace( + packet, + " WHERE admission.id = stored.submission_bundle_admission_id;", + " LEFT JOIN public.submission_intake_operations operation ON operation.id=admission.source_operation_id\n" + " WHERE admission.id = stored.submission_bundle_admission_id;\n" + " IF stored.feedback IS DISTINCT FROM metadata->>'feedback' OR (metadata ? 'feedback' " + "AND (stored.summary IS NOT NULL OR stored.worker_attestation IS NOT NULL)) THEN\n" + " RAISE EXCEPTION 'submission feedback differs from the accepted command' USING ERRCODE='23514';\n" + " END IF;", + ) + packet = _replace( + packet, + "pg_catalog.jsonb_build_object(\n" + " 'summary', stored.summary, 'contributor_attestation', stored.worker_attestation\n" + " )", + "CASE WHEN stored.summary IS NULL THEN '{}'::jsonb ELSE pg_catalog.jsonb_build_object(\n" + " 'summary', stored.summary, 'contributor_attestation', stored.worker_attestation\n" + " ) END", + ) + op.execute(packet) + dispatch = _definition("public.submission_dispatch_valid(public.submission_dispatches)") + dispatch = _replace( + dispatch, + "'predecessor_submission_id',s.supersedes_submission_id,'summary',s.summary," + "'contributor_attestation',s.worker_attestation)))", + "'predecessor_submission_id',s.supersedes_submission_id) || CASE WHEN s.summary IS NULL\n" + " THEN pg_catalog.jsonb_build_object('feedback',s.feedback)\n" + " ELSE pg_catalog.jsonb_build_object('summary',s.summary," + "'contributor_attestation',s.worker_attestation) END))", + ) + op.execute(dispatch) + + +def upgrade() -> None: + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.submission_intake_operations, public.selected_pre_submit_runs," + " public.submissions, public.submission_dispatches IN ACCESS EXCLUSIVE MODE") + op.execute(""" + ALTER TABLE public.submissions + ADD COLUMN feedback text, + ALTER COLUMN summary DROP NOT NULL, + ALTER COLUMN worker_attestation DROP NOT NULL, + ADD CONSTRAINT ck_submissions_feedback_shape CHECK ( + (summary IS NULL)=(worker_attestation IS NULL) + AND (feedback IS NULL OR (summary IS NULL AND octet_length(feedback)<=4096 + AND feedback COLLATE "C" !~ '[^ -~]' AND btrim(feedback)=feedback)) + ); + + CREATE FUNCTION public.guard_submission_feedback() + RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ + BEGIN + IF NEW.feedback IS DISTINCT FROM OLD.feedback + OR NEW.summary IS DISTINCT FROM OLD.summary + OR NEW.worker_attestation IS DISTINCT FROM OLD.worker_attestation THEN + RAISE EXCEPTION 'submission input is immutable' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END $$; + + CREATE TRIGGER submission_feedback_immutable + BEFORE UPDATE OF feedback,summary,worker_attestation ON public.submissions + FOR EACH ROW EXECUTE FUNCTION public.guard_submission_feedback(); + + CREATE FUNCTION public.submission_operation_checker_packet(metadata jsonb) + RETURNS jsonb LANGUAGE sql IMMUTABLE STRICT SET search_path=pg_catalog,public,pg_temp AS $$ + SELECT CASE WHEN metadata ? 'feedback' THEN '{}'::jsonb + ELSE jsonb_build_object('summary',metadata->>'summary', + 'contributor_attestation',metadata->>'contributor_attestation') END + $$; + """) + _intake_guard() + _pre_guard() + acceptance = _definition("public.require_submission_acceptance_current(public.submission_intake_operations)") + op.execute(_replace( + acceptance, + " IF o.eligible_task_status='in_progress' THEN", + " IF o.command_metadata ? 'feedback' AND NOT EXISTS (\n" + " SELECT 1 FROM public.workstream_tasks t WHERE t.id=o.task_id\n" + " AND public.submission_intake_task_snapshot(t)=o.locked_task_context\n" + " ) THEN RAISE EXCEPTION 'accepted task context changed' USING ERRCODE='23514'; END IF;\n" + " IF o.eligible_task_status='in_progress' THEN", + )) + _submission_guards() + + +def downgrade() -> None: + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py index cf7b81000..a0b4107d6 100644 --- a/backend/app/adapters/artifacts/__init__.py +++ b/backend/app/adapters/artifacts/__init__.py @@ -972,8 +972,7 @@ def _submission_public_failure(exc: Exception) -> SubmissionIntakeFailure: code = "submission_operation_in_progress" elif exc.code in { "task_submission_predecessor_changed", "revision_limit_reached", "revision_deadline_expired", - "revision_context_blocked", "revision_context_changed", "revision_acknowledgement_required", - "revision_acknowledgement_invalid", + "revision_context_blocked", "revision_context_changed", }: code = exc.code else: diff --git a/backend/app/api/routes/artifact_submissions.py b/backend/app/api/routes/artifact_submissions.py index 6d9bcc2e3..c8c1a3928 100644 --- a/backend/app/api/routes/artifact_submissions.py +++ b/backend/app/api/routes/artifact_submissions.py @@ -23,15 +23,31 @@ for name, required, schema in ( ("Idempotency-Key", True, {"type": "string", "format": "uuid"}), ("X-Task-Assignment-Id", True, {"type": "string", "format": "uuid"}), - ("X-Submission-Summary", False, {"type": "string", "maxLength": 65536}), - ("X-Contributor-Attestation", False, {"type": "string", "maxLength": 65536}), - ("X-Predecessor-Submission-Id", False, {"type": "string", "format": "uuid"}), - ("X-Revision-Preparation-Id", False, {"type": "string", "format": "uuid"}), - ("X-Revision-Preparation-Sha256", False, {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}), + ("X-Submission-Feedback", False, {"type": "string", "maxLength": 4096, + "description": "Optional project feedback. Printable ASCII without leading or trailing whitespace."}), ) ] +_FAILURE_MESSAGES = { + "submission_unavailable": "Submission unavailable", + "submission_packet_invalid": "The submitted ZIP or request was invalid", + "submission_archive_limit_exceeded": "The ZIP exceeds the permitted archive limits", + "submission_upload_timeout": "The ZIP upload timed out", + "submission_capacity_exceeded": "Submission processing is at capacity. Try again later.", + "submission_infrastructure_unavailable": "Submission processing is temporarily unavailable", + "submission_outcome_unknown": "Check the original submission operation or retry with the same idempotency key", + "submission_operation_in_progress": "This assignment already has a submission in progress", + "submission_idempotency_conflict": "This idempotency key was used with different submission inputs", + "pre_submission_checker_failed": "The ZIP did not pass the pre-submission checks", + "revision_deadline_expired": "Your assignment expired. Reclaim the task if it is still available.", + "revision_limit_reached": "Your assignment has reached its revision limit", + "revision_context_blocked": "This assignment is waiting for its revision requirements", + "revision_context_changed": "The revision requirements or terms changed. Read your assignment before submitting again.", + "task_submission_predecessor_changed": "The assignment's current revision changed. Read your assignment before submitting again.", +} + + def _failure_status(code: str) -> int: if code == "submission_unavailable": return 404 @@ -41,7 +57,7 @@ def _failure_status(code: str) -> int: return 408 if code == "submission_capacity_exceeded": return 429 - if code in {"submission_packet_invalid", "pre_submission_checker_failed", "revision_acknowledgement_invalid"}: + if code in {"submission_packet_invalid", "pre_submission_checker_failed"}: return 422 if code in {"submission_infrastructure_unavailable", "submission_outcome_unknown"}: return 503 @@ -88,9 +104,7 @@ async def submit_source( details = {"status": "failed", "eligible_to_submit": False, "results": exc.pre_submission_results or []} return error_response( request, status_code=_failure_status(exc.code), code=exc.code, - message=("Your assignment expired. Reclaim the task if it is still available." - if exc.code == "revision_deadline_expired" else - "Submission unavailable" if exc.code == "submission_unavailable" else exc.code), + message=_FAILURE_MESSAGES.get(exc.code, "Submission could not be completed"), details=details, retryable=exc.code in {"submission_capacity_exceeded", "submission_infrastructure_unavailable", "submission_outcome_unknown"}, ) return SubmissionAcceptedResponse.model_validate(receipt) diff --git a/backend/app/api/submission_intake.py b/backend/app/api/submission_intake.py index 2e2f919e4..3920e0b75 100644 --- a/backend/app/api/submission_intake.py +++ b/backend/app/api/submission_intake.py @@ -9,7 +9,9 @@ from app.core.api_controls import StructuredHTTPException from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES -from app.modules.artifacts.api.submission_intake import MAXIMUM_INGRESS_CHUNK_BYTES, SubmissionIntakeMetadata +from app.modules.artifacts.api.submission_intake import ( + MAXIMUM_INGRESS_CHUNK_BYTES, MAXIMUM_SUBMISSION_FEEDBACK_BYTES, SubmissionIntakeMetadata, +) @dataclass(frozen=True, slots=True) @@ -20,9 +22,7 @@ class SubmissionIntakeHeaders: _PACKET_HEADERS = ( - "x-task-assignment-id", "idempotency-key", "x-submission-summary", - "x-contributor-attestation", "x-predecessor-submission-id", - "x-revision-preparation-id", "x-revision-preparation-sha256", + "x-task-assignment-id", "idempotency-key", "x-submission-feedback", "content-type", "content-encoding", "content-length", "transfer-encoding", ) @@ -59,19 +59,18 @@ def submission_intake_headers(request: Request, task_id: UUID) -> SubmissionInta if declared == 0: _reject("submission_packet_invalid", 422, "Submission ZIP must be nonempty") try: - predecessor = headers.get("x-predecessor-submission-id") - revision = headers.get("x-revision-preparation-id") + assignment_id = UUID(headers["x-task-assignment-id"]) + key = UUID(headers["idempotency-key"]) + except ValueError: + _reject("submission_packet_invalid", 422, "Task assignment and idempotency key must be UUIDs") + try: metadata = SubmissionIntakeMetadata( - task_id=task_id, assignment_id=UUID(headers["x-task-assignment-id"]), - predecessor_submission_id=UUID(predecessor) if predecessor is not None else None, - summary=headers.get("x-submission-summary", ""), - contributor_attestation=headers.get("x-contributor-attestation", ""), - revision_preparation_id=UUID(revision) if revision is not None else None, - revision_preparation_sha256=headers.get("x-revision-preparation-sha256"), + task_id=task_id, assignment_id=assignment_id, feedback=headers.get("x-submission-feedback"), ) - key = UUID(headers["idempotency-key"]) except ValueError: - _reject("submission_packet_invalid", 422, "Submission packet is invalid") + _reject("submission_packet_invalid", 422, + f"Feedback accepts up to {MAXIMUM_SUBMISSION_FEEDBACK_BYTES} printable ASCII bytes " + "without leading or trailing whitespace") return SubmissionIntakeHeaders(metadata, key, declared) diff --git a/backend/app/modules/artifacts/api/submission_intake.py b/backend/app/modules/artifacts/api/submission_intake.py index 7a96d5da7..84bd49cd3 100644 --- a/backend/app/modules/artifacts/api/submission_intake.py +++ b/backend/app/modules/artifacts/api/submission_intake.py @@ -41,43 +41,30 @@ class _IntakeValue(BaseModel): ) -class SubmissionIntakeMetadata(_IntakeValue): - """Exact original command; actor/key namespace and locked policy are separate. +MAXIMUM_SUBMISSION_FEEDBACK_BYTES = 4096 - These selectors are validated structurally only. TASK still checks current - assignment, actual predecessor and the required revision acknowledgement. - Empty summary/attestation retain existing nonblocking warning semantics. - """ + +class SubmissionIntakeMetadata(_IntakeValue): + """Caller inputs only. TASK selects predecessor and revision context.""" task_id: UUID assignment_id: UUID - predecessor_submission_id: UUID | None = None - summary: str = Field(default="", max_length=64 * 1024) - contributor_attestation: str = Field(default="", max_length=64 * 1024) - revision_preparation_id: UUID | None = None - revision_preparation_sha256: Sha256 | None = None + feedback: str | None = Field(default=None, max_length=MAXIMUM_SUBMISSION_FEEDBACK_BYTES) - @field_validator("summary", "contributor_attestation") + @field_validator("feedback") @classmethod - def packet_text(cls, value: str) -> str: - """Reject unsupported header text rather than silently rewriting it.""" - if value != value.strip() or any(not 32 <= ord(char) <= 126 for char in value): - raise ValueError("submission packet must be printable ASCII without edge whitespace") + def feedback_text(cls, value: str | None) -> str | None: + """Reject unsupported header text without modifying the supplied value.""" + if value is not None and ( + value != value.strip() or any(not 32 <= ord(char) <= 126 for char in value) + ): + raise ValueError("feedback must be printable ASCII without leading or trailing whitespace") return value - @model_validator(mode="after") - def revision_pair(self) -> Self: - """Require complete acknowledgement selectors and a revision predecessor.""" - if (self.revision_preparation_id is None) != (self.revision_preparation_sha256 is None): - raise ValueError("revision acknowledgement requires both selectors") - if self.predecessor_submission_id is None and self.revision_preparation_id is not None: - raise ValueError("initial submission cannot acknowledge a revision") - return self - def metadata_sha256(self) -> str: - """Hash exact metadata using one versioned, domain-separated schema.""" + """Hash the caller's inputs independently of the server's selection.""" return canonical_json_hash({ - "schema_version": "workstream.submission_intake_metadata.v1", + "schema_version": "workstream.submission_intake_metadata.v2", **self.model_dump(mode="json"), }) diff --git a/backend/app/modules/artifacts/intake/finalization.py b/backend/app/modules/artifacts/intake/finalization.py index ab55ee20d..411de0441 100644 --- a/backend/app/modules/artifacts/intake/finalization.py +++ b/backend/app/modules/artifacts/intake/finalization.py @@ -167,7 +167,8 @@ async def _finalize(self, operation_id: UUID, claim: AcceptedContinuation, obser admission_id=admission_id, task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), contributor_id=UUID(row.actor_profile_id), predecessor_submission_id=UUID(metadata["predecessor_submission_id"]) if metadata["predecessor_submission_id"] else None, - summary=metadata["summary"], contributor_attestation=metadata["contributor_attestation"], + summary=metadata.get("summary"), contributor_attestation=metadata.get("contributor_attestation"), + feedback=metadata.get("feedback"), ), authority_facts=continuation_facts(row, claim.lease_id, claim.generation), finalization_authority=authority, snapshot_sha256=row.locked_context_sha256, eligible_status=row.eligible_task_status, diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py index 5752d6045..805a9613b 100644 --- a/backend/app/modules/artifacts/intake/foreground_admission.py +++ b/backend/app/modules/artifacts/intake/foreground_admission.py @@ -4,8 +4,6 @@ key or uncertain commit resolves the stored operation through current read authority and cannot acquire a replacement lease or start a second upload. """ -import json - from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager from dataclasses import asdict, dataclass @@ -43,7 +41,7 @@ from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort from app.modules.tasks.api.submission_context import ( TaskSubmissionContextPort, TaskSubmissionContextRequest, - require_revision_acknowledgement, require_revision_capacity, + TaskSubmissionContextUnavailable, require_revision_capacity, ) @@ -183,7 +181,7 @@ async def _reserve(self, metadata, actor_id, identity_link_id, key, declared): async def _validate_context(self, session, metadata, actor_id): """Require canonical lineage, selected phases and the exact qualified namespace.""" task = await self._contexts(session).lock_submission_context(TaskSubmissionContextRequest( - metadata.task_id, metadata.assignment_id, actor_id, metadata.predecessor_submission_id, + metadata.task_id, metadata.assignment_id, actor_id, select_predecessor=True, )) references = asdict(task.locked_project_context) references.pop("locked_contribution_policy_version_id") @@ -195,7 +193,6 @@ async def _validate_context(self, session, metadata, actor_id): policy_generation=revision.generation, policy_hash=revision.policy_hash, max_revision_rounds=RevisionPolicySemantics.model_validate_json(project.revision_policy.value).max_revision_rounds, ) - require_revision_acknowledgement(task, metadata.revision_preparation_id, metadata.revision_preparation_sha256) policies = LockedExternalCheckerPolicies.model_validate_json(project.external_checker_policies.value) if len(policies.pre_submit.entries) != 1 or len(policies.post_submit.entries) != 1: raise IntakeCustodyConflict("intake_requires_one_pre_and_post_checker") @@ -206,6 +203,29 @@ async def _validate_context(self, session, metadata, actor_id): raise IntakeCustodyConflict("intake_source_provider_unqualified") return task, project + @staticmethod + async def _require_reserved_context(session, row, task): + snapshot = await session.scalar(text( + "SELECT public.submission_intake_task_snapshot(t) " + "FROM public.workstream_tasks t WHERE id=:id" + ), {"id": task.task_id}) + preparation = task.revision_context + selection = row.command_metadata + if ( + task.status != row.eligible_task_status + or snapshot != row.locked_task_context + or selection["predecessor_submission_id"] != ( + str(task.predecessor.submission_id) if task.predecessor else None + ) + or selection["revision_preparation_id"] != ( + str(preparation.preparation_id) if preparation else None + ) + or selection["revision_preparation_sha256"] != ( + preparation.preparation_sha256 if preparation else None + ) + ): + raise TaskSubmissionContextUnavailable("revision_context_changed") + async def reserve_pre( self, owner: IntakeReservationOwner, source: SealedSubmissionSource, *, runtime_profile: SelectedPreSubmitRuntimeProfile, @@ -228,8 +248,12 @@ async def reserve_pre( UUID(row.actor_profile_id), UUID(row.identity_link_id), UUID(row.idempotency_key), row.metadata_sha256, )) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + metadata = SubmissionIntakeMetadata( + task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), + feedback=row.command_metadata["feedback"], + ) task, project = await self._validate_context(session, metadata, UUID(row.actor_profile_id)) + await self._require_reserved_context(session, row, task) custody = await repository.lock_pre_source( source=source, lease_id=owner.lease_id, generation=owner.generation) predecessor, predecessor_rules = None, None @@ -253,7 +277,7 @@ async def reserve_pre( task=task, project=project, predecessor=predecessor, predecessor_rules_sha256=predecessor_rules, predecessor_exists=task.predecessor is not None, - packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + packet=SubmissionPacketView(), ) reservation = build_selected_pre_submit_reservation( source=custody, metadata=metadata, task=task, project=project, @@ -328,7 +352,7 @@ async def assignment_release_failure( await authority.authorize_read(IntakeOperationReadFacts( UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id))) if (row.actor_profile_id != str(actor_id) or row.idempotency_key != str(idempotency_key) - or row.metadata_sha256 != metadata.metadata_sha256()): + or not self._matches_public_command(row, metadata)): raise IntakeCustodyConflict("submission_idempotency_conflict") released = (row.state in {"cancelled", "abandoned"} and row.failure_code in {"revision_deadline_expired", "submission_unavailable"} @@ -367,8 +391,12 @@ async def _accept_new(self, session, authority, repository, row, owner, await authority.preflight(IntakeReservationPreflightFacts( UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.assignment_id), UUID(row.actor_profile_id), UUID(row.identity_link_id), UUID(row.idempotency_key), row.metadata_sha256)) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + metadata = SubmissionIntakeMetadata( + task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), + feedback=row.command_metadata["feedback"], + ) task, project = await self._validate_context(session, metadata, UUID(row.actor_profile_id)) + await self._require_reserved_context(session, row, task) lineage = request.admission_lineage predecessor = task.predecessor if (task.status != row.eligible_task_status @@ -399,6 +427,17 @@ async def _accept_new(self, session, authority, repository, row, owner, await self._tasks(session).accept(UUID(row.task_id), UUID(row.id), row.eligible_task_status) return dict(row.acceptance_receipt) + @staticmethod + def _matches_public_command(row, metadata): + if (str(metadata.task_id), str(metadata.assignment_id)) != (row.task_id, row.assignment_id): + return False + if "feedback" in row.command_metadata: + return row.metadata_sha256 == metadata.metadata_sha256() + # Retired text cannot be presented on the public wire. Operation reads + # still recover every historical command, even when it carried text. + return (metadata.feedback is None and row.command_metadata["summary"] == "" + and row.command_metadata["contributor_attestation"] == "") + async def _read(self, metadata, actor_id, key, *, expected_operation_id=None): """Authorize the stored operation before comparing metadata or returning its state.""" async with self._root() as (session, authority): @@ -410,7 +449,7 @@ async def _read(self, metadata, actor_id, key, *, expected_operation_id=None): await authority.authorize_read(IntakeOperationReadFacts( UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id), )) - if row.metadata_sha256 != metadata.metadata_sha256(): + if not self._matches_public_command(row, metadata): raise IntakeCustodyConflict("submission_idempotency_conflict") if expected_operation_id is not None and UUID(row.id) != expected_operation_id: raise IntakeCustodyConflict("submission_idempotency_conflict") @@ -432,7 +471,7 @@ async def replay_failure( await authority.authorize_read(IntakeOperationReadFacts( UUID(row.id), UUID(row.project_id), UUID(row.task_id), UUID(row.actor_profile_id))) if (row.actor_profile_id != str(actor_id) or row.idempotency_key != str(idempotency_key) - or row.metadata_sha256 != metadata.metadata_sha256()): + or not self._matches_public_command(row, metadata)): raise IntakeCustodyConflict("submission_idempotency_conflict") if row.state in {"finalization_pending", "finalized"}: return await self._accepted_receipt(session, authority, row) diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py index 5b5ff5fe9..a9580fbe1 100644 --- a/backend/app/modules/artifacts/intake/progress.py +++ b/backend/app/modules/artifacts/intake/progress.py @@ -105,10 +105,8 @@ def __init__(self, session, *, tasks, authority, history, evaluations, prechecks self._projects, self._events, self._deliveries = projects, events, deliveries async def read(self, task_id, selector, *, actor_id): - import json from sqlalchemy import text from app.modules.artifacts.api.submission_command import SubmissionOperationResponse - from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata from app.modules.artifacts.intake.repository import SubmissionIntakeRepository from app.modules.authorization.api.submission_intake import IntakeAuthorityDenied, IntakeOperationReadFacts from app.modules.tasks.api.submission_context import TaskSubmissionContextRequest @@ -130,13 +128,10 @@ async def read(self, task_id, selector, *, actor_id): raise IntakeAuthorityDenied("submission intake is unavailable") access = await self._authority.authorize_operation_read(IntakeOperationReadFacts( UUID(row.id), UUID(row.project_id), task_id, UUID(row.actor_profile_id))) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) - if (metadata.task_id != task_id or metadata.assignment_id != UUID(row.assignment_id) - or metadata.metadata_sha256() != row.metadata_sha256): - raise IntakeCustodyConflict("submission_operation_metadata_inconsistent") current = await self._tasks.read_operation_context( - TaskSubmissionContextRequest(task_id, UUID(row.assignment_id), UUID(row.actor_profile_id), - metadata.predecessor_submission_id), + TaskSubmissionContextRequest( + task_id, UUID(row.assignment_id), UUID(row.actor_profile_id), select_predecessor=True, + ), project_id=UUID(row.project_id), reader_id=actor_id, management=access.management, own_submitter=access.own_submitter, ) @@ -178,7 +173,7 @@ async def read(self, task_id, selector, *, actor_id): "evaluation_running" if evaluation.live_worker_lease else "evaluation_pending") elif row.state in {"rejected", "failed", "abandoned", "cancelled"}: action = "inspect_governed_outcome" - if row.state != "cancelled" and await self._permits_new_intake(current.candidate, metadata): + if row.state != "cancelled" and await self._permits_new_intake(current.candidate): action = "correct_and_submit_new_key" if row.state == "rejected" else "retry_new_key_after_terminal" code = row.failure_code if code is not None and code not in { @@ -213,14 +208,14 @@ async def _feedback(self, row, repository): raise IntakeCustodyConflict("submission_operation_pre_inconsistent") return public_pre_submission_results(terminal.execution) - async def _permits_new_intake(self, candidate, metadata): + async def _permits_new_intake(self, candidate): from dataclasses import asdict from app.modules.projects.api.locked_policy import ( ProjectLockedPolicyContextRequest, ProjectLockedPolicyContextUnavailable, ) from app.modules.projects.api.policy_lineage import RevisionPolicySemantics from app.modules.tasks.api.submission_context import ( - TaskSubmissionContextUnavailable, require_revision_acknowledgement, require_revision_capacity, + TaskSubmissionContextUnavailable, require_revision_capacity, ) if candidate is None: return False @@ -233,7 +228,6 @@ async def _permits_new_intake(self, candidate, metadata): require_revision_capacity(candidate, project_id=project.project_id, policy_id=revision.policy_id, policy_generation=revision.generation, policy_hash=revision.policy_hash, max_revision_rounds=RevisionPolicySemantics.model_validate_json(project.revision_policy.value).max_revision_rounds) - require_revision_acknowledgement(candidate, metadata.revision_preparation_id, metadata.revision_preparation_sha256) except (ProjectLockedPolicyContextUnavailable, TaskSubmissionContextUnavailable): return False return True diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py index 63a97dc84..f44eec60d 100644 --- a/backend/app/modules/artifacts/intake/repository.py +++ b/backend/app/modules/artifacts/intake/repository.py @@ -61,7 +61,7 @@ async def reserve( if not isinstance(operation_id, UUID) or operation_id.version != 7: raise ValueError("intake operation requires a generated UUIDv7") snapshot = await self._tasks.claim(TaskSubmissionContextRequest( - metadata.task_id, metadata.assignment_id, actor_id, metadata.predecessor_submission_id, + metadata.task_id, metadata.assignment_id, actor_id, select_predecessor=True, ), operation_id) namespace = await self._session.get(ArtifactStorageNamespace, "primary") if namespace is None: @@ -72,11 +72,17 @@ async def reserve( provider_profile=namespace.provider_profile, ) context = json.loads(snapshot.context_json) + command_metadata = metadata.model_dump(mode="json") + command_metadata.update( + predecessor_submission_id=str(snapshot.predecessor_submission_id) if snapshot.predecessor_submission_id else None, + revision_preparation_id=str(snapshot.revision_preparation_id) if snapshot.revision_preparation_id else None, + revision_preparation_sha256=snapshot.revision_preparation_sha256, + ) row = SubmissionIntakeOperation( id=str(operation_id), project_id=str(snapshot.project_id), task_id=str(metadata.task_id), assignment_id=str(metadata.assignment_id), actor_profile_id=str(actor_id), identity_link_id=str(identity_link_id), - idempotency_key=str(idempotency_key), command_metadata=metadata.model_dump(mode="json"), + idempotency_key=str(idempotency_key), command_metadata=command_metadata, metadata_sha256=metadata.metadata_sha256(), locked_task_context=context, locked_context_sha256=canonical_json_hash(context), eligible_task_status=snapshot.eligible_status, namespace_id=location.namespace_id, namespace_fingerprint=location.namespace_fingerprint, @@ -272,12 +278,11 @@ async def expire_revision(self, operation_id: UUID, target: TaskRevisionExpiryTa """ target = TaskRevisionExpiryTarget.model_validate(target) row = await self._lock(operation_id) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) if (row.state not in {"receiving", "pre_checking"} or row.eligible_task_status != "needs_revision" or (row.project_id, row.task_id, row.assignment_id, row.actor_profile_id) != ( str(target.project_id), str(target.task_id), str(target.assignment_id), str(target.contributor_id)) - or metadata.predecessor_submission_id != target.source_submission_id): + or row.command_metadata["predecessor_submission_id"] != str(target.source_submission_id)): raise IntakeCustodyConflict("revision_intake_expiry_mismatch") await self._tasks.require_active(target.task_id, operation_id) now = await self._session.scalar(select(func.clock_timestamp())) @@ -288,12 +293,11 @@ async def cancel_assignment(self, operation_id: UUID, target: AssignmentInvalida """End exact initial intake inside the authorized TASK invalidation root.""" target = AssignmentInvalidationTarget.model_validate(target) row = await self._lock(operation_id) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) if (row.state not in {"receiving", "pre_checking"} or row.eligible_task_status != "in_progress" or (row.project_id, row.task_id, row.assignment_id, row.actor_profile_id) != ( str(target.project_id), str(target.task_id), str(target.assignment_id), str(target.contributor_id)) - or metadata.predecessor_submission_id is not None): + or row.command_metadata["predecessor_submission_id"] is not None): raise IntakeCustodyConflict("assignment_intake_cancellation_mismatch") await self._tasks.require_active(target.task_id, operation_id) now = await self._session.scalar(select(func.clock_timestamp())) diff --git a/backend/app/modules/artifacts/selected_pre_submit_admission.py b/backend/app/modules/artifacts/selected_pre_submit_admission.py index 3a00fed6a..36acdf27c 100644 --- a/backend/app/modules/artifacts/selected_pre_submit_admission.py +++ b/backend/app/modules/artifacts/selected_pre_submit_admission.py @@ -98,7 +98,7 @@ def build_selected_pre_submit_reservation( values are comparisons only; this builder grants neither reads nor execution. """ references = task.locked_project_context - packet = SubmissionPacketView(metadata.summary, metadata.contributor_attestation) + packet = SubmissionPacketView() if ( type(source) is not SubmissionIntakePreSourceFacts or source.task_id != task.task_id or source.assignment_id != task.assignment_id @@ -106,12 +106,6 @@ def build_selected_pre_submit_reservation( or source.project_id != project.project_id or metadata.task_id != task.task_id or metadata.assignment_id != task.assignment_id or metadata.metadata_sha256() != source.metadata_sha256 - or metadata.predecessor_submission_id != ( - task.predecessor.submission_id if task.predecessor else None) - or metadata.revision_preparation_id != ( - task.revision_context.preparation_id if task.revision_context else None) - or metadata.revision_preparation_sha256 != ( - task.revision_context.preparation_sha256 if task.revision_context else None) or references.project_id != project.project_id or references.guide_version != project.guide_version or references.source_snapshot_id != project.source_snapshot_id diff --git a/backend/app/modules/checkers/api/default_checker.py b/backend/app/modules/checkers/api/default_checker.py index 12d215aa6..912dfc87e 100644 --- a/backend/app/modules/checkers/api/default_checker.py +++ b/backend/app/modules/checkers/api/default_checker.py @@ -168,8 +168,7 @@ def predecessor_body(value: WorkstreamDefaultPredecessor | None): "current_predecessor": predecessor_body(self.current_predecessor), "current_rules_sha256": self.current_rules_sha256, "predecessor_rules_sha256": self.predecessor_rules_sha256, - "packet": {"summary": self.packet.summary, - "contributor_attestation": self.packet.contributor_attestation}, + "packet": self.packet.canonical_body(), } @classmethod diff --git a/backend/app/modules/checkers/api/pre_submit_material.py b/backend/app/modules/checkers/api/pre_submit_material.py index fc189cdb3..8bf8f2589 100644 --- a/backend/app/modules/checkers/api/pre_submit_material.py +++ b/backend/app/modules/checkers/api/pre_submit_material.py @@ -14,23 +14,26 @@ class SubmissionPacketView: """Bounded optional text accompanying server-owned verified ZIP facts.""" - summary: str - contributor_attestation: str + summary: str | None = None + contributor_attestation: str | None = None def __post_init__(self) -> None: + if self.summary is None and self.contributor_attestation is None: + return for value in (self.summary, self.contributor_attestation): if type(value) is not str or len(value.encode("utf-8")) > 64 * 1024: raise ValueError("submission packet text is invalid") + def canonical_body(self) -> dict[str, str]: + """Read retired text only from retained checker evidence.""" + if self.summary is None or self.contributor_attestation is None: + return {} + return {"summary": self.summary, "contributor_attestation": self.contributor_attestation} + @property def sha256(self) -> str: """Commit to the same exact text at preparation and Submission creation.""" - return canonical_json_hash( - { - "summary": self.summary, - "contributor_attestation": self.contributor_attestation, - } - ) + return canonical_json_hash(self.canonical_body()) __all__ = ("ALLOWED_PRE_SUBMIT_STORAGE_SCHEMES", "SubmissionPacketView") diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py index 5246b2419..3e83e1c96 100644 --- a/backend/app/modules/checkers/api/selected_pre_submit.py +++ b/backend/app/modules/checkers/api/selected_pre_submit.py @@ -751,8 +751,7 @@ def derive_selected_pre_submit_input( "archive_sha256": source.raw_sha256, "archive_byte_count": source.raw_byte_count, "semantic_manifest_sha256": manifest_sha256, "manifest": [asdict(entry) for entry in value.entries], - "packet": {"summary": value.packet.summary, - "contributor_attestation": value.packet.contributor_attestation}, + "packet": value.packet.canonical_body(), } request = make_external_checker_execution_request( registry=selected.registry, identity=identity, configuration=selected.configuration, diff --git a/backend/app/modules/checkers/default_checker.py b/backend/app/modules/checkers/default_checker.py index 848effd22..bd1b24602 100644 --- a/backend/app/modules/checkers/default_checker.py +++ b/backend/app/modules/checkers/default_checker.py @@ -231,6 +231,8 @@ def _is_sha256(value: object) -> bool: def _warnings(packet: SubmissionPacketView) -> tuple[WorkstreamDefaultWarning, ...]: """Return stable warning-only absence signals in canonical order.""" + if packet.summary is None or packet.contributor_attestation is None: + return () values = [] if not packet.summary.strip(): values.append(WorkstreamDefaultWarning(code="submission_summary_missing")) diff --git a/backend/app/modules/tasks/api/intake_custody.py b/backend/app/modules/tasks/api/intake_custody.py index db88bce11..14235bdac 100644 --- a/backend/app/modules/tasks/api/intake_custody.py +++ b/backend/app/modules/tasks/api/intake_custody.py @@ -15,6 +15,9 @@ class IntakeTaskSnapshot: project_id: UUID eligible_status: str context_json: str + predecessor_submission_id: UUID | None + revision_preparation_id: UUID | None + revision_preparation_sha256: str | None @dataclass(frozen=True, slots=True) @@ -52,5 +55,5 @@ async def read_operation_context( self, request: TaskSubmissionContextRequest, *, project_id: UUID, reader_id: UUID, management: bool, own_submitter: bool, ) -> IntakeTaskReadContext: - """After AUTH, read visibility and a candidate needing locked policy/ack checks.""" + """After AUTH, read visibility and a candidate needing locked policy checks.""" ... diff --git a/backend/app/modules/tasks/api/submission_command.py b/backend/app/modules/tasks/api/submission_command.py index f142d107d..0be4692dc 100644 --- a/backend/app/modules/tasks/api/submission_command.py +++ b/backend/app/modules/tasks/api/submission_command.py @@ -39,8 +39,9 @@ class SubmissionCreationRequest: assignment_id: UUID contributor_id: UUID predecessor_submission_id: UUID | None - summary: str - contributor_attestation: str + summary: str | None = None + contributor_attestation: str | None = None + feedback: str | None = None @dataclass(frozen=True, slots=True) diff --git a/backend/app/modules/tasks/api/submission_context.py b/backend/app/modules/tasks/api/submission_context.py index d60e9d667..f45100a94 100644 --- a/backend/app/modules/tasks/api/submission_context.py +++ b/backend/app/modules/tasks/api/submission_context.py @@ -2,7 +2,6 @@ from __future__ import annotations -import re from dataclasses import dataclass from typing import Literal, Protocol, get_args from uuid import UUID @@ -16,8 +15,6 @@ TaskSubmissionContextFailure = Literal[ "task_submission_context_invalid", "task_submission_operation_in_progress", - "revision_acknowledgement_required", - "revision_acknowledgement_invalid", "task_submission_predecessor_changed", "revision_limit_reached", "revision_deadline_expired", @@ -44,7 +41,8 @@ class TaskSubmissionContextRequest: task_id: UUID assignment_id: UUID contributor_id: UUID - predecessor_submission_id: UUID | None + predecessor_submission_id: UUID | None = None + select_predecessor: bool = False @dataclass(frozen=True, slots=True) @@ -202,32 +200,3 @@ def require_revision_capacity( # A global Submission version is not an assignment's revision allowance. if task.predecessor.revision_round > max_revision_rounds: raise TaskSubmissionContextUnavailable("revision_limit_reached") - - - -def require_revision_acknowledgement( - task: TaskSubmissionContextFacts, preparation_id: UUID | str | None, preparation_sha256: str | None, -) -> None: - """Compare an explicit packet acknowledgement with canonical locked revision facts.""" - if task.predecessor is None: - if preparation_id is not None or preparation_sha256 is not None: - raise TaskSubmissionContextUnavailable("revision_acknowledgement_invalid") - return - context = task.revision_context - if context is None: - raise TaskSubmissionContextUnavailable("revision_context_changed") - if preparation_id is None and preparation_sha256 is None: - raise TaskSubmissionContextUnavailable("revision_acknowledgement_required") - if not isinstance(preparation_id, (UUID, str)) or not isinstance(preparation_sha256, str): - raise TaskSubmissionContextUnavailable("revision_acknowledgement_invalid") - try: - acknowledged_id = UUID(preparation_id) if isinstance(preparation_id, str) else preparation_id - except ValueError as exc: - raise TaskSubmissionContextUnavailable("revision_acknowledgement_invalid") from exc - if re.fullmatch(r"sha256:[0-9a-f]{64}", preparation_sha256) is None: - raise TaskSubmissionContextUnavailable("revision_acknowledgement_invalid") - if (context.source_submission_id != task.predecessor.submission_id - or context.source_routing_manifest_id != task.checker_remediation_manifest_id - or acknowledged_id != context.preparation_id - or preparation_sha256 != context.preparation_sha256): - raise TaskSubmissionContextUnavailable("revision_context_changed") diff --git a/backend/app/modules/tasks/intake_custody.py b/backend/app/modules/tasks/intake_custody.py index 991b3d350..d863435aa 100644 --- a/backend/app/modules/tasks/intake_custody.py +++ b/backend/app/modules/tasks/intake_custody.py @@ -46,6 +46,9 @@ async def claim(self, request: TaskSubmissionContextRequest, operation_id: UUID) return IntakeTaskSnapshot( context.locked_project_context.project_id, context.status, json.dumps(snapshot, sort_keys=True, separators=(",", ":")), + context.predecessor.submission_id if context.predecessor else None, + context.revision_context.preparation_id if context.revision_context else None, + context.revision_context.preparation_sha256 if context.revision_context else None, ) async def require_active(self, task_id: UUID, operation_id: UUID) -> UUID: diff --git a/backend/app/modules/tasks/models.py b/backend/app/modules/tasks/models.py index f2d97dcf6..20fd6e5b7 100644 --- a/backend/app/modules/tasks/models.py +++ b/backend/app/modules/tasks/models.py @@ -437,6 +437,12 @@ class Submission(Base): "status_reason='checker_coverage_incomplete')", name="status_reason", ), + CheckConstraint( + '(summary IS NULL)=(worker_attestation IS NULL) AND ' + " (feedback IS NULL OR (summary IS NULL AND octet_length(feedback)<=4096 " + "AND feedback COLLATE \"C\" !~ '[^ -~]' AND btrim(feedback)=feedback))", + name="feedback_shape", + ), Index("ix_submissions_contributor_updated", "contributor_id", "updated_at", "id"), ForeignKeyConstraint( ["task_assignment_id", "task_id", "contributor_id"], @@ -574,11 +580,12 @@ class Submission(Base): DateTime(timezone=True), nullable=False, server_default=func.now(), server_onupdate=FetchedValue(), ) - summary: Mapped[str] = mapped_column(Text, nullable=False) + summary: Mapped[str | None] = mapped_column(Text) + feedback: Mapped[str | None] = mapped_column(Text) package_uri: Mapped[str | None] = mapped_column(String(1000)) package_hash: Mapped[str | None] = mapped_column(String(128)) artifact_hash_manifest: Mapped[list[dict]] = mapped_column(JSON, nullable=False, default=list) - worker_attestation: Mapped[str] = mapped_column(Text, nullable=False) + worker_attestation: Mapped[str | None] = mapped_column(Text) locked_guide_version: Mapped[str] = mapped_column(String(50), nullable=False) locked_post_submit_checker_policy_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), nullable=False) locked_post_submit_checker_policy_version: Mapped[str] = mapped_column( diff --git a/backend/app/modules/tasks/repository.py b/backend/app/modules/tasks/repository.py index c42fd6acc..85497459d 100644 --- a/backend/app/modules/tasks/repository.py +++ b/backend/app/modules/tasks/repository.py @@ -722,7 +722,7 @@ async def select_submission_context( """Lock TASK rows and select one owner-qualified remediation source. Args: - request: Exact task, assignment, contributor, and predecessor selectors. + request: Exact task, assignment and contributor. Internal callers may verify a retained predecessor. Returns: Provisional TASK facts and selected immutable routing source. The @@ -779,7 +779,7 @@ async def select_submission_context( if request.predecessor_submission_id is not None else None ) - if latest_id != requested_predecessor_id: + if not request.select_predecessor and latest_id != requested_predecessor_id: raise TaskSubmissionContextUnavailable("task_submission_predecessor_changed") if ( (task.status == "in_progress" and latest_assignment_submission is not None) diff --git a/backend/app/modules/tasks/schemas.py b/backend/app/modules/tasks/schemas.py index 584f2404e..bbe47c6d8 100644 --- a/backend/app/modules/tasks/schemas.py +++ b/backend/app/modules/tasks/schemas.py @@ -135,29 +135,6 @@ def meaningful_reason(self): return self -class AdmissionBackedSubmissionCreate(BaseModel): - """Contributor packet and selectors for the canonical ready-admission POST.""" - - model_config = ConfigDict(extra="forbid") - - admission_id: UUID - assignment_id: UUID - predecessor_submission_id: UUID | None = None - summary: str | None = None - contributor_attestation: str | None = None - - -class AdmissionBackedSubmissionResponse(BaseModel): - """Stable Workstream result without provider or scratch coordinates.""" - - model_config = ConfigDict(extra="forbid") - - submission_id: UUID - submission_version: int - admission_id: UUID - evaluation_request_id: UUID - - class TaskResponse(BaseModel): """Response schema for task records.""" @@ -367,11 +344,9 @@ class _TaskSubmissionRequirements(BaseModel): guide_version: str = Field(pattern=r"\S") policy_schema_version: str | None merge_algorithm_version: str | None - required_packet_fields: tuple[str, ...] required_artifacts: tuple[RequiredArtifactRequirement, ...] required_evidence: tuple[RequiredEvidenceRequirement, ...] forbidden_artifacts: tuple[ForbiddenArtifactRequirement, ...] - attestation_terms: tuple[str, ...] manifest_required: bool artifact_hash_required: bool artifact_hash_algorithm: Literal["sha256"] diff --git a/backend/app/modules/tasks/service.py b/backend/app/modules/tasks/service.py index c53a1012f..3eda8c0b6 100644 --- a/backend/app/modules/tasks/service.py +++ b/backend/app/modules/tasks/service.py @@ -44,12 +44,6 @@ TaskResponse, ) -SUBMISSION_CREATE_REQUIRED_PACKET_FIELDS = ( - "summary", - "package_hash", - "artifact_hash_manifest", - "worker_attestation", -) LOCKED_CONTEXT_REQUIRED_FIELDS = ( "locked_guide_version", "locked_post_submit_checker_policy_id", @@ -330,7 +324,6 @@ def _submission_requirement_values( policy, "merge_algorithm_version", ), - required_packet_fields=tuple(self._required_packet_fields(policy)), required_artifacts=tuple( RequiredArtifactRequirement( key=self._policy_rule_text(rule, "key", "required_artifacts"), @@ -396,7 +389,6 @@ def _submission_requirement_values( ) for rule in forbidden_artifacts ), - attestation_terms=tuple(self._policy_string_list(policy, "attestation_terms")), manifest_required=self._policy_bool(policy, "manifest_required"), artifact_hash_required=self._policy_bool(policy, "artifact_hash_required"), artifact_hash_algorithm="sha256", @@ -515,26 +507,6 @@ def _optional_policy_non_negative_int( ) return value - def _required_packet_fields(self, policy: dict[str, Any]) -> list[str]: - """Return exact submission packet fields required by API and policy.""" - required_fields: list[str] = [] - policy_fields = policy.get("required_packet_fields", []) - if not isinstance(policy_fields, list): - raise TaskLockedContextInvalid( - "task locked effective project submission artifact policy is invalid", - {"field": "effective_policy.required_packet_fields"}, - ) - for field in (*SUBMISSION_CREATE_REQUIRED_PACKET_FIELDS, *policy_fields): - if not isinstance(field, str) or not field.strip(): - raise TaskLockedContextInvalid( - "task locked effective project submission artifact policy is invalid", - {"field": "effective_policy.required_packet_fields"}, - ) - normalized = field.strip() - if normalized not in required_fields: - required_fields.append(normalized) - return required_fields - def _policy_rule_text(self, rule: object, key: str, collection: str) -> str: """Return a required text field from a locked policy rule or fail closed.""" if not isinstance(rule, dict): diff --git a/backend/app/modules/tasks/submission_composition.py b/backend/app/modules/tasks/submission_composition.py index 20d341ba0..24533cc4f 100644 --- a/backend/app/modules/tasks/submission_composition.py +++ b/backend/app/modules/tasks/submission_composition.py @@ -38,8 +38,9 @@ def build_submission( task: Any, contributor_id: str, version: int, - summary: str, - worker_attestation: str, + summary: str | None = None, + worker_attestation: str | None = None, + feedback: str | None = None, supersedes_submission_id: str | None, contribution_policy_version_id: UUID, task_assignment_id: str, @@ -58,6 +59,7 @@ def build_submission( version=version, status="submitted", summary=summary, + feedback=feedback, package_uri=package_uri, package_hash=package_hash, artifact_hash_manifest=artifact_hash_manifest or [], @@ -160,6 +162,7 @@ async def _create_bound_submission( task_assignment_id=str(context.assignment_id), contributor_id=str(request.contributor_id), version=version, summary=request.summary, worker_attestation=request.contributor_attestation, + feedback=request.feedback, supersedes_submission_id=(str(context.predecessor.submission_id) if context.predecessor else None), ) diff --git a/backend/app/modules/tasks/submission_dispatch.py b/backend/app/modules/tasks/submission_dispatch.py index 9c149b4fa..20d0889f0 100644 --- a/backend/app/modules/tasks/submission_dispatch.py +++ b/backend/app/modules/tasks/submission_dispatch.py @@ -11,10 +11,16 @@ def creation_request_digest(request: SubmissionCreationRequest) -> str: """Bind all caller facts; admission remains the replay namespace.""" + body = asdict(request) + if request.summary is None and request.contributor_attestation is None: + body.pop("summary") + body.pop("contributor_attestation") + else: + body.pop("feedback") return canonical_json_hash({ "domain": "workstream.submission.creation", "request": {key: str(value) if isinstance(value, UUID) else value - for key, value in asdict(request).items()}, + for key, value in body.items()}, }) diff --git a/backend/tests/artifacts/qualify_submission_a19.py b/backend/tests/artifacts/qualify_submission_a19.py index e3dc5a8bc..e5a3d91fd 100644 --- a/backend/tests/artifacts/qualify_submission_a19.py +++ b/backend/tests/artifacts/qualify_submission_a19.py @@ -339,8 +339,7 @@ async def sample() -> None: headers = { "Host": "workstream.example.test", "Authorization": "Bearer a19-measurement-token", "Content-Type": "application/zip", "X-Task-Assignment-Id": str(fixture.assignment), - "X-Submission-Summary": "Measured bounded source upload", - "X-Contributor-Attestation": "I completed the measured work", + "X-Submission-Feedback": "Measured bounded source upload", "Idempotency-Key": str(new_record_id()), } request = asyncio.create_task(client.post( diff --git a/backend/tests/artifacts/test_submission_aws_source.py b/backend/tests/artifacts/test_submission_aws_source.py index 29ccbacc3..4844e774d 100644 --- a/backend/tests/artifacts/test_submission_aws_source.py +++ b/backend/tests/artifacts/test_submission_aws_source.py @@ -103,11 +103,12 @@ async def test_qualified_aws_pre_source_matches_locked_sql(admission_intake): guarded = await submission_intake_pre_source_port(session).lock_pre_source( source=source, lease_id=owner.lease_id, generation=owner.generation, ) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + metadata = SubmissionIntakeMetadata(task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), + feedback=row.command_metadata["feedback"]) selected = bind_selected_pre_submit_admission( task=task, project=project, predecessor=None, predecessor_rules_sha256=None, predecessor_exists=False, - packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + packet=SubmissionPacketView(), ) request = build_selected_pre_submit_reservation( source=guarded, metadata=metadata, task=task, project=project, diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py index 4a3939436..f529e0d6b 100644 --- a/backend/tests/artifacts/test_submission_intake_admission.py +++ b/backend/tests/artifacts/test_submission_intake_admission.py @@ -1044,7 +1044,6 @@ async def lose_ack(envelope): async def test_authorized_progress_reports_exact_exhaustion_without_reopening_intake( admission_intake, tmp_path, monkeypatch, effect_committed, ): - import json from uuid import UUID from sqlalchemy import select, func from app.adapters.artifacts import submission_finalization_handler @@ -1070,7 +1069,8 @@ async def test_authorized_progress_reports_exact_exhaustion_without_reopening_in async with f.factory() as session: row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) key, event_id = UUID(row.idempotency_key), UUID(row.finalization_event_id) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + metadata = SubmissionIntakeMetadata(task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), + feedback=row.command_metadata["feedback"]) async def read(): return await f.admission._read(metadata, f.actor.actor_profile_id, key) initial = await read() diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py index 23e929493..b7f44d41f 100644 --- a/backend/tests/artifacts/test_submission_intake_contracts.py +++ b/backend/tests/artifacts/test_submission_intake_contracts.py @@ -77,58 +77,43 @@ def source(**updates): }) -def test_metadata_canonical_fixture_and_round_trip_preserve_exact_packet(): - value = metadata(summary="A B", contributor_attestation="I did this.") - # Independent literal fixture fixes field names, nulls and domain separation. +def test_metadata_canonical_fixture_and_round_trip_preserve_exact_feedback(): + value = metadata(feedback="A B") canonical = ( '{"assignment_id":"019a0000-0000-7000-8000-000000000004",' - '"contributor_attestation":"I did this.","predecessor_submission_id":null,' - '"revision_preparation_id":null,"revision_preparation_sha256":null,' - '"schema_version":"workstream.submission_intake_metadata.v1",' - '"summary":"A B","task_id":"019a0000-0000-7000-8000-000000000003"}' + '"feedback":"A B","schema_version":"workstream.submission_intake_metadata.v2",' + '"task_id":"019a0000-0000-7000-8000-000000000003"}' ) assert value.metadata_sha256() == "sha256:" + hashlib.sha256(canonical.encode()).hexdigest() - restored = SubmissionIntakeMetadata.model_validate_json(value.model_dump_json()) - assert restored == value - assert restored.summary == "A B" - assert metadata().summary == metadata().contributor_attestation == "" - assert metadata(summary="x" * 65536).summary == "x" * 65536 - - -@pytest.mark.parametrize("field", ["task_id", "assignment_id", "predecessor_submission_id", - "summary", "contributor_attestation", - "revision_preparation_id", "revision_preparation_sha256"]) -def test_every_metadata_selector_participates_in_replay_identity(field): - original = metadata(predecessor_submission_id=PREDECESSOR, - revision_preparation_id=REVISION, revision_preparation_sha256=SHA) - replacement = ( - uuid4() if field.endswith("_id") else - "sha256:" + "b" * 64 if field.endswith("_sha256") else "changed" - ) + assert SubmissionIntakeMetadata.model_validate_json(value.model_dump_json()) == value + assert value.feedback == "A B" + assert metadata().feedback is None + assert metadata(feedback="x" * 4096).feedback == "x" * 4096 + + +@pytest.mark.parametrize("field,replacement", [ + ("task_id", uuid4()), ("assignment_id", uuid4()), ("feedback", ""), ("feedback", "changed"), +]) +def test_every_metadata_selector_participates_in_replay_identity(field, replacement): + original = metadata() changed = SubmissionIntakeMetadata.model_validate({**original.model_dump(), field: replacement}) assert changed.metadata_sha256() != original.metadata_sha256() -@pytest.mark.parametrize("text", [" leading", "trailing ", "line\nbreak", "tab\tvalue", - "café", "\x7f", "x" * 65537]) -@pytest.mark.parametrize("field", ["summary", "contributor_attestation"]) -def test_packet_rejects_unrepresentable_headers_without_normalization(field, text): +@pytest.mark.parametrize("value", [" leading", "trailing ", "line\nbreak", "tab\tvalue", + "café", "\x7f", "x" * 4097]) +def test_feedback_rejects_unrepresentable_headers_without_normalization(value): with pytest.raises(ValidationError): - metadata(**{field: text}) + metadata(feedback=value) -@pytest.mark.parametrize("updates", [ - {"revision_preparation_id": REVISION}, - {"revision_preparation_sha256": SHA}, - {"revision_preparation_id": REVISION, "revision_preparation_sha256": SHA}, - {"predecessor_submission_id": PREDECESSOR, "revision_preparation_id": REVISION}, - {"predecessor_submission_id": PREDECESSOR, "revision_preparation_sha256": SHA}, +@pytest.mark.parametrize("removed_input,value", [ + ("predecessor_submission_id", PREDECESSOR), ("revision_preparation_id", REVISION), + ("revision_preparation_sha256", SHA), ("summary", "text"), ("contributor_attestation", "text"), ]) -def test_revision_acknowledgement_cannot_be_partial_or_initial(updates): - with pytest.raises(ValidationError): - metadata(**updates) - # Whether a revision requires acknowledgement is still a TASK policy check. - assert metadata(predecessor_submission_id=PREDECESSOR).revision_preparation_id is None +def test_submit_metadata_rejects_retired_inputs(removed_input, value): + with pytest.raises(ValidationError, match="extra_forbidden"): + metadata(**{removed_input: value}) def test_source_address_is_operation_bound_and_opaque_generation_round_trips(): @@ -197,7 +182,7 @@ def test_frozen_values_revalidate_nested_instances_and_reject_unknown_command_fi metadata(bearer_token="secret") with pytest.raises(ValidationError): SubmissionIntakeMetadata.model_validate_json(json.dumps({ - "task_id": str(TASK), "assignment_id": str(ASSIGNMENT), "summary": 1, + "task_id": str(TASK), "assignment_id": str(ASSIGNMENT), "feedback": 1, })) diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py index 48c50daa5..7bbfbde5b 100644 --- a/backend/tests/artifacts/test_submission_intake_custody.py +++ b/backend/tests/artifacts/test_submission_intake_custody.py @@ -428,7 +428,7 @@ async def test_sql_insert_cannot_substitute_bound_parents(intake, field, constra project=values["project_id"], actor=str(intake.actor.actor_profile_id), )) metadata = SubmissionIntakeMetadata(task_id=intake.task, assignment_id=UUID(values[field])) - values["command_metadata"] = metadata.model_dump(mode="json") + values["command_metadata"] = {**values["command_metadata"], **metadata.model_dump(mode="json")} values["metadata_sha256"] = metadata.metadata_sha256() with pytest.raises(DBAPIError, match=constraint): async with intake.factory.begin() as session: @@ -457,7 +457,8 @@ async def test_sql_rejects_malformed_command_selectors_even_with_matching_digest metadata = {**values["command_metadata"], **selectors} candidate = {**values, "command_metadata": metadata, "metadata_sha256": canonical_json_hash({ - "schema_version": "workstream.submission_intake_metadata.v1", **metadata, + "schema_version": "workstream.submission_intake_metadata.v2", + **{field: metadata[field] for field in ("task_id", "assignment_id", "feedback")}, })} with pytest.raises(DBAPIError, match="invalid intake metadata"): async with intake.factory.begin() as session: diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py index 5c72eaa68..ad34af5b6 100644 --- a/backend/tests/artifacts/test_submission_pre_source.py +++ b/backend/tests/artifacts/test_submission_pre_source.py @@ -29,7 +29,7 @@ def _assert_pre_reservation_rejects_substitution(build_values, guarded, metadata from app.modules.checkers.api.pre_submit_material import SubmissionPacketView from app.modules.artifacts.selected_pre_submit_admission import build_selected_pre_submit_reservation substitutions = ( - {"metadata": metadata.model_copy(update={"summary": "substituted"})}, + {"metadata": metadata.model_copy(update={"feedback": "substituted"})}, {"source": guarded.model_copy(update={"actor_profile_id": new_record_id()})}, {"source": guarded.model_copy(update={"metadata_sha256": "sha256:" + "f" * 64})}, {"selected": replace(selected, rules_sha256="sha256:" + "f" * 64)}, @@ -209,11 +209,12 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed): guarded = await submission_intake_pre_source_port(session).lock_pre_source( source=source, lease_id=lease, generation=1, ) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + metadata = SubmissionIntakeMetadata(task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), + feedback=row.command_metadata["feedback"]) selected = bind_selected_pre_submit_admission( task=task, project=project, predecessor=None, predecessor_rules_sha256=None, predecessor_exists=False, - packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + packet=SubmissionPacketView(), ) build_values = dict( source=guarded, metadata=metadata, task=task, project=project, @@ -499,7 +500,8 @@ async def upload_bytes(): async with intake.factory.begin() as session: row = await reserve(intake, session, with_upload=False) operation, foreground_lease = UUID(row.id), UUID(row.lease_id) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + metadata = SubmissionIntakeMetadata(task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), + feedback=row.command_metadata["feedback"]) key = UUID(row.idempotency_key) source = await foreground_upload(intake, store).receive( operation, foreground_lease, 1, upload_bytes(), **foreground_limits(), @@ -577,7 +579,7 @@ async def test_source_pre_execution_uses_committed_authorized_local_read(intake, ) selected = bind_selected_pre_submit_admission( task=task, project=project, predecessor=None, predecessor_rules_sha256=None, - predecessor_exists=False, packet=SubmissionPacketView(metadata.summary, metadata.contributor_attestation), + predecessor_exists=False, packet=SubmissionPacketView(), ) request = build_selected_pre_submit_reservation( source=custody, metadata=metadata, task=task, project=project, diff --git a/backend/tests/checkers/execution/test_checker_retry_history_replay.py b/backend/tests/checkers/execution/test_checker_retry_history_replay.py index e0c7018e5..51fd896d1 100644 --- a/backend/tests/checkers/execution/test_checker_retry_history_replay.py +++ b/backend/tests/checkers/execution/test_checker_retry_history_replay.py @@ -88,11 +88,7 @@ async def test_retry_replays_after_real_later_submission_without_reopening_old_s h.revision_preparation_sha256 = current.revision_context.preparation_sha256 metadata = SubmissionIntakeMetadata( task_id=h.request.task_id, assignment_id=h.request.assignment_id, - predecessor_submission_id=h.created.submission_id, - revision_preparation_id=current.revision_context.preparation_id, - revision_preparation_sha256=current.revision_context.preparation_sha256, - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, + feedback=h.creation_request.summary, ) later = await create_source_submission( h.factory, h.actor_context, h.store.wrapped, h.namespace, h.settings, diff --git a/backend/tests/checkers/external/test_selected_pre_submit.py b/backend/tests/checkers/external/test_selected_pre_submit.py index 72e9af3b0..a0e830f26 100644 --- a/backend/tests/checkers/external/test_selected_pre_submit.py +++ b/backend/tests/checkers/external/test_selected_pre_submit.py @@ -40,16 +40,15 @@ SelectedPreSubmitLeaseFacts, SelectedPreSubmitReservationFacts, ) -from app.modules.tasks.api.submission_context import require_revision_acknowledgement -from app.modules.tasks.api import TaskSubmissionContextUnavailable +from app.modules.checkers.api.pre_submit_material import SubmissionPacketView from tests.checkers.external.support import SHA, registry_entry def _hex_sha(character: str) -> str: return "sha256:" + character * 64 -def test_revision_acknowledgement_changes_selected_request_and_retains_old_bytes() -> None: - """A new acknowledgement is frozen; old selected requests keep their digest.""" +def test_selected_revision_context_changes_request_and_retains_old_bytes() -> None: + """A selected revision context is frozen; old selected requests keep their digest.""" from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation from app.modules.checkers.api.default_checker import WorkstreamDefaultPredecessor @@ -113,38 +112,6 @@ def test_revision_acknowledgement_changes_selected_request_and_retains_old_bytes revision_preparation_sha256=_hex_sha("b")) -def test_revision_acknowledgement_requires_exact_current_preparation() -> None: - """The explicit pair is required for revisions and forbidden on initial intake.""" - predecessor_id, manifest_id, preparation_id = ( - new_record_id(), new_record_id(), new_record_id() - ) - revision = SimpleNamespace( - preparation_id=preparation_id, - preparation_sha256=_hex_sha("c"), - source_submission_id=predecessor_id, - source_routing_manifest_id=manifest_id, - ) - task = SimpleNamespace( - predecessor=SimpleNamespace(submission_id=predecessor_id), - checker_remediation_manifest_id=manifest_id, - revision_context=revision, - ) - require_revision_acknowledgement(task, str(preparation_id), _hex_sha("c")) - for acknowledged_id, acknowledged_hash, code in ( - (str(new_record_id()), _hex_sha("c"), "revision_context_changed"), - (None, None, "revision_acknowledgement_required"), - (str(preparation_id), _hex_sha("d"), "revision_context_changed"), - ): - with pytest.raises(TaskSubmissionContextUnavailable) as refused: - require_revision_acknowledgement(task, acknowledged_id, acknowledged_hash) - assert refused.value.code == code - with pytest.raises(TaskSubmissionContextUnavailable) as refused: - require_revision_acknowledgement( - SimpleNamespace(predecessor=None), str(preparation_id), _hex_sha("c") - ) - assert refused.value.code == "revision_acknowledgement_invalid" - - def _retained_admission_reservation(): from app.modules.checkers.api.historical_selected_pre_submit import HistoricalSelectedPreSubmitReservation from tests.checkers.external.test_selected_pre_submit_coordination import _retained_v1 @@ -483,14 +450,8 @@ async def test_selected_admission_binds_unchanged_work_to_current_task_rules() - ) project = SimpleNamespace(**vars(references), guide_id=lineage.guide_id, external_checker_policies=SimpleNamespace(value=policies.model_dump_json())) - packet = original.default_context.packet - metadata = SubmissionIntakeMetadata( - task_id=task.task_id, assignment_id=task.assignment_id, - predecessor_submission_id=predecessor.submission_id, - summary=packet.summary, contributor_attestation=packet.contributor_attestation, - revision_preparation_id=task.revision_context.preparation_id, - revision_preparation_sha256=task.revision_context.preparation_sha256, - ) + packet = SubmissionPacketView() + metadata = SubmissionIntakeMetadata(task_id=task.task_id, assignment_id=task.assignment_id) source = _source_guard(original).lock_pre_source.return_value.model_copy(update={ "metadata_sha256": metadata.metadata_sha256(), }) diff --git a/backend/tests/migration_revision_fixtures.py b/backend/tests/migration_revision_fixtures.py index 5e34c05d5..56871924f 100644 --- a/backend/tests/migration_revision_fixtures.py +++ b/backend/tests/migration_revision_fixtures.py @@ -31,7 +31,6 @@ from app.modules.tasks.api import SubmissionCreationRequest from app.modules.tasks.api.transition_audit import TaskPolicyLineage from app.modules.tasks.models import Submission, WorkstreamTask -from app.modules.tasks.schemas import AdmissionBackedSubmissionResponse from tests.historical_submission_fixtures import ( _restore_validated_snapshot_rows, ) @@ -202,13 +201,11 @@ def archived_bootstrap(_settings): request=SelectedPostSubmissionEvaluationRequest.model_validate_json( json.dumps(seed["request"]) ), - created=AdmissionBackedSubmissionResponse.model_validate_json( - json.dumps( - { - name: seed["created"][name] - for name in AdmissionBackedSubmissionResponse.model_fields - } - ) + created=SimpleNamespace( + submission_id=UUID(seed["created"]["submission_id"]), + submission_version=seed["created"]["submission_version"], + admission_id=UUID(seed["created"]["admission_id"]), + evaluation_request_id=UUID(seed["created"]["evaluation_request_id"]), ), actor_context=HumanAuthorizationContext.model_validate_json( json.dumps(seed["actor_context"]) diff --git a/backend/tests/post_submit_materialization_helpers.py b/backend/tests/post_submit_materialization_helpers.py index e75c258c2..3dca26f88 100644 --- a/backend/tests/post_submit_materialization_helpers.py +++ b/backend/tests/post_submit_materialization_helpers.py @@ -227,9 +227,7 @@ async def _create_material_submission( data = archive_with_modes(policy["evidence_path"], plan.lineage.project_id) metadata = SubmissionIntakeMetadata( task_id=task_id, assignment_id=assignment_id, - summary="Completed the required project work and included evidence.", - contributor_attestation="I confirm no confidential client data, credentials, or copied source material is included in this submission; rights_confirmed. " - + " ".join(policy["attestation_terms"]), + feedback="Completed the required project work and included evidence.", ) created = await create_source_submission(factory, context, store, namespace, settings, metadata, data, submit_source=submit_source) @@ -237,7 +235,7 @@ async def _create_material_submission( creation_request = SubmissionCreationRequest( task_id=task_id, assignment_id=assignment_id, contributor_id=context.actor_profile_id, predecessor_submission_id=None, admission_id=admission_id, - summary=metadata.summary, contributor_attestation=metadata.contributor_attestation, + feedback=metadata.feedback, ) return context, task_id, data, admission_id, creation_request, created diff --git a/backend/tests/retained_material_fixtures.py b/backend/tests/retained_material_fixtures.py index 8326953e1..bb794e455 100644 --- a/backend/tests/retained_material_fixtures.py +++ b/backend/tests/retained_material_fixtures.py @@ -185,10 +185,7 @@ def _submission_source(task, assignment, link, packet, predecessor_id, policy, r context = _context(actor_profile_id=UUID(task.assigned_to), identity_link_id=UUID(link.id)) metadata = SubmissionIntakeMetadata( task_id=UUID(task.id), assignment_id=UUID(assignment.id), - predecessor_submission_id=UUID(predecessor_id) if predecessor_id else None, - summary=packet.summary, contributor_attestation=packet.worker_attestation, - revision_preparation_id=revision_context.preparation_id if revision_context else None, - revision_preparation_sha256=revision_context.preparation_sha256 if revision_context else None, + feedback=packet.summary, ) return context, metadata, content.getvalue() diff --git a/backend/tests/reviews/decision/support.py b/backend/tests/reviews/decision/support.py index 468122a3c..cf4893b1b 100644 --- a/backend/tests/reviews/decision/support.py +++ b/backend/tests/reviews/decision/support.py @@ -281,11 +281,7 @@ async def _admit_successor(h): metadata = SubmissionIntakeMetadata( task_id=h.request.task_id, assignment_id=h.request.assignment_id, - predecessor_submission_id=h.request.submission_id, - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, - revision_preparation_id=revision.preparation_id, - revision_preparation_sha256=revision.preparation_sha256, + feedback=h.creation_request.summary, ) created = await create_source_submission( h.factory, context, h.store.wrapped, h.namespace, h.settings, metadata, revised_data, diff --git a/backend/tests/tasks/invalidation_support.py b/backend/tests/tasks/invalidation_support.py index 8afb9a27e..fb553ccd7 100644 --- a/backend/tests/tasks/invalidation_support.py +++ b/backend/tests/tasks/invalidation_support.py @@ -293,7 +293,6 @@ async def submission_packet(s): """Build raw bytes and headers for the claimed task without preparing old custody.""" from app.modules.projects.models import EffectiveProjectSubmissionArtifactPolicy from tests.archive_fixtures import submission_archive - from tests.test_tasks import complete_submission_payload async with s.sessions() as session: task = await session.get(WorkstreamTask, s.task["id"]) @@ -304,7 +303,4 @@ async def submission_packet(s): assert [item["key"] for item in body["required_evidence"]] == ["required-evidence-001"] return submission_archive(path="answer.md", evidence_path="evidence/required-evidence-001"), { "Content-Type": "application/zip", "X-Task-Assignment-Id": s.assignment["id"], - "X-Submission-Summary": "Completed the required project work and included evidence.", - "X-Contributor-Attestation": complete_submission_payload()["worker_attestation"] - + " " + " ".join(body["attestation_terms"]), } diff --git a/backend/tests/tasks/post_submit_routing/support.py b/backend/tests/tasks/post_submit_routing/support.py index d113c18e8..78607b75a 100644 --- a/backend/tests/tasks/post_submit_routing/support.py +++ b/backend/tests/tasks/post_submit_routing/support.py @@ -7,7 +7,6 @@ from sqlalchemy import select, text from app.adapters.checkers import evaluation_coordinator -from app.adapters.tasks import task_submission_context_port from app.core.identifiers import new_record_id from app.modules.actors.models import ActorIdentityLink from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata @@ -15,7 +14,6 @@ from app.modules.projects.models import ( ReviewPolicy, ) -from app.modules.tasks.api import TaskSubmissionContextRequest from app.modules.tasks.api.post_submit_routing import TaskPostSubmitManifestFacts from app.modules.tasks.api.transition_audit import TaskPolicyLineage from app.modules.tasks.models import Submission, SubmissionDispatch, TaskAssignment, WorkstreamTask @@ -241,21 +239,9 @@ async def completed_source( async def _create_submission(h, context, task_id, assignment_id, predecessor_id=None): """Admit the ZIP and create exact Submission lineage through owner services.""" - async with h.factory() as session, session.begin(): - current = await task_submission_context_port(session).lock_submission_context( - TaskSubmissionContextRequest( - task_id=task_id, assignment_id=assignment_id, - contributor_id=context.actor_profile_id, - predecessor_submission_id=predecessor_id, - ) - ) - revision = current.revision_context metadata = SubmissionIntakeMetadata( - task_id=task_id, assignment_id=assignment_id, predecessor_submission_id=predecessor_id, - revision_preparation_id=revision.preparation_id if revision else None, - revision_preparation_sha256=revision.preparation_sha256 if revision else None, - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, + task_id=task_id, assignment_id=assignment_id, + feedback=h.creation_request.feedback, ) return await create_source_submission( h.factory, context, h.store.wrapped, h.namespace, h.settings, metadata, h.data, diff --git a/backend/tests/tasks/submission_dispatch/test_evaluation_revision.py b/backend/tests/tasks/submission_dispatch/test_evaluation_revision.py index 5f76adc0d..3200fef65 100644 --- a/backend/tests/tasks/submission_dispatch/test_evaluation_revision.py +++ b/backend/tests/tasks/submission_dispatch/test_evaluation_revision.py @@ -67,11 +67,7 @@ async def test_exact_consumed_preparation_and_source_are_read_without_mutation( SubmissionIntakeMetadata( task_id=h.request.task_id, assignment_id=h.request.assignment_id, - predecessor_submission_id=h.created.submission_id, - revision_preparation_id=h.revision_preparation_id, - revision_preparation_sha256=h.revision_preparation_sha256, - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, + feedback=h.creation_request.summary, ), revision_archive(h.data), ) diff --git a/backend/tests/tasks/submission_dispatch/test_predecessor_receipt.py b/backend/tests/tasks/submission_dispatch/test_predecessor_receipt.py index e0b063336..7ab9bab80 100644 --- a/backend/tests/tasks/submission_dispatch/test_predecessor_receipt.py +++ b/backend/tests/tasks/submission_dispatch/test_predecessor_receipt.py @@ -35,11 +35,7 @@ async def test_deferred_dispatch_checks_accepted_successor_cause( assert local_source != foreign_source metadata = SubmissionIntakeMetadata( task_id=local.request.task_id, assignment_id=local.request.assignment_id, - predecessor_submission_id=local.created.submission_id, - revision_preparation_id=UUID(str(local.revision_preparation_id)), - revision_preparation_sha256=local.revision_preparation_sha256, - summary=local.creation_request.summary, - contributor_attestation=local.creation_request.contributor_attestation, + feedback=local.creation_request.summary, ) accepted, staged, checked = [], [], [] original_create, original_commit = TaskSubmissionCreationService.create_accepted, AsyncSession.commit diff --git a/backend/tests/tasks/submission_dispatch/test_replacement_creation.py b/backend/tests/tasks/submission_dispatch/test_replacement_creation.py index 27496c214..c9e5ac358 100644 --- a/backend/tests/tasks/submission_dispatch/test_replacement_creation.py +++ b/backend/tests/tasks/submission_dispatch/test_replacement_creation.py @@ -25,7 +25,6 @@ def _revision_command(h, root, data): """Build current foreground owners with exact routed revision acknowledgement.""" - from uuid import UUID from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata from tests.artifacts.test_submission_pre_source import _source_runtime from tests.retained_material_fixtures import _foreground @@ -34,11 +33,7 @@ def _revision_command(h, root, data): command = _foreground(h.factory, h.actor_context, h.namespace, h.store.wrapped, runtime) metadata = SubmissionIntakeMetadata( task_id=h.request.task_id, assignment_id=h.request.assignment_id, - predecessor_submission_id=h.created.submission_id, - revision_preparation_id=UUID(str(h.revision_preparation_id)), - revision_preparation_sha256=h.revision_preparation_sha256, - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, + feedback=h.creation_request.summary, ) return command, metadata, errors @@ -261,11 +256,7 @@ async def test_late_outbox_insert_failure_rolls_back_and_accepted_retry_succeeds command = _foreground(h.factory, h.actor_context, h.namespace, h.store.wrapped, runtime) metadata = SubmissionIntakeMetadata( task_id=h.request.task_id, assignment_id=h.request.assignment_id, - predecessor_submission_id=h.created.submission_id, - revision_preparation_id=UUID(str(h.revision_preparation_id)), - revision_preparation_sha256=h.revision_preparation_sha256, - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, + feedback=h.creation_request.summary, ) receipt = await _submit_current_source(h.factory, h.actor_context, command, metadata, data) assert receipt["status"] == "accepted" and not errors, errors diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index 9ba199f26..cfdc458d8 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -87,16 +87,11 @@ async def _fail_current_submission(h, *, findings=None, route=True, terminal=Fal def _revision_upload_headers(h): - """Build the current raw-ZIP command with its exact revision acknowledgement.""" + """Use the same minimal ZIP command for a revision.""" return { "Content-Type": "application/zip", "X-Task-Assignment-Id": str(h.request.assignment_id), "Idempotency-Key": str(new_record_id()), - "X-Predecessor-Submission-Id": str(h.created.submission_id), - "X-Revision-Preparation-Id": str(h.revision_preparation_id), - "X-Revision-Preparation-Sha256": h.revision_preparation_sha256, - "X-Submission-Summary": h.creation_request.summary, - "X-Contributor-Attestation": h.creation_request.contributor_attestation, } @@ -174,14 +169,12 @@ async def test_two_revisions_then_public_and_sql_refusal( assert receipt.source_submission_id == str(h.created.submission_id) before = await _creation_snapshot(h) - # The exhausted assignment cannot submit a new ZIP, including with - # its preceding preparation acknowledgement. No pending window exists. + # The exhausted assignment cannot start another upload. async with h.factory() as session: intake_ids = set(await session.scalars(select(SubmissionIntakeOperation.id))) assert len(intake_ids) == 3 denied = await client.post(route, headers=saved_headers | { "Idempotency-Key": str(new_record_id()), - "X-Predecessor-Submission-Id": str(h.created.submission_id), }, content=b"not a zip") assert denied.status_code == 404, denied.text assert denied.json()["error"]["code"] == "submission_unavailable" @@ -347,7 +340,7 @@ def test_revision_projection_preserves_deadline_and_distinguishes_policy_changes assert project_revision(row, row.deadline_at).disposition == "revision_limit_reached" -async def test_rebase_keeps_history_and_requires_exact_acknowledgement( +async def test_rebase_retains_original_attempt_and_selects_current_terms( tmp_path, isolated_database_env, monkeypatch, ): """A real v2 activation rebases only the next attempt and preserves v1 evidence.""" @@ -402,8 +395,7 @@ async def test_rebase_keeps_history_and_requires_exact_acknowledgement( replayed_initial = await client.post(route, headers={ "Content-Type": "application/zip", "Idempotency-Key": initial.idempotency_key, "X-Task-Assignment-Id": initial.assignment_id, - "X-Submission-Summary": initial.command_metadata["summary"], - "X-Contributor-Attestation": initial.command_metadata["contributor_attestation"], + "X-Submission-Feedback": initial.command_metadata["feedback"], }, content=h.data) assert replayed_initial.status_code == 202, replayed_initial.text assert replayed_initial.json() == dict(initial.acceptance_receipt, replayed=True) @@ -411,10 +403,10 @@ async def test_rebase_keeps_history_and_requires_exact_acknowledgement( before = await _creation_snapshot(h) headers = _revision_upload_headers(h) refused = await client.post(route, headers=headers | { - "X-Revision-Preparation-Id": str(new_record_id()), + "X-Task-Assignment-Id": str(new_record_id()), }, content=b"not a zip") - assert refused.status_code == 409, refused.text - assert refused.json()["error"]["code"] == "revision_context_changed" + assert refused.status_code == 404, refused.text + assert refused.json()["error"]["code"] == "submission_unavailable" assert await _creation_snapshot(h) == before and calls == [] created = await client.post(route, headers=headers, content=data) assert created.status_code == 202, created.text @@ -426,6 +418,13 @@ async def test_rebase_keeps_history_and_requires_exact_acknowledgement( dispatch = await session.get(SubmissionDispatch, submission_id) assert dispatch.submission_version == 2 assert dispatch.checker_remediation_manifest_id == source_id + selected = await session.get(SubmissionIntakeOperation, created.json()["operation_id"]) + assert selected.command_metadata["predecessor_submission_id"] == str(h.created.submission_id) + assert selected.command_metadata["revision_preparation_id"] == str(h.revision_preparation_id) + assert selected.command_metadata["revision_preparation_sha256"] == h.revision_preparation_sha256 + submission = await session.get(Submission, submission_id) + assert str(submission.contribution_policy_version_id) == str(assignment.submitter_contribution_policy_version_id) + async with h.factory() as session: assert await session.scalar(text( "SELECT to_jsonb(s)-ARRAY['attempt_status','status_reason','decided_at','updated_at'] FROM public.submissions s WHERE id=:id" @@ -608,13 +607,8 @@ async def test_expired_retained_failure_recovers_without_a_new_window( f"/api/v1/tasks/{h.request.task_id}/submissions", headers={ "Content-Type": "application/zip", - "X-Submission-Summary": h.creation_request.summary, - "X-Contributor-Attestation": h.creation_request.contributor_attestation, "X-Task-Assignment-Id": str(h.request.assignment_id), - "X-Predecessor-Submission-Id": str(h.created.submission_id), "Idempotency-Key": str(new_record_id()), - "X-Revision-Preparation-Id": receipt["preparation_id"], - "X-Revision-Preparation-Sha256": receipt["preparation_sha256"], }, content=b"not a zip", ) assert denied.status_code == 409, denied.text @@ -708,8 +702,6 @@ async def test_expiry_allows_new_assignment_initial_at_next_global_version( "Content-Type": "application/zip", "Idempotency-Key": str(new_record_id()), "X-Task-Assignment-Id": str(new_assignment_id), - "X-Submission-Summary": h.creation_request.summary, - "X-Contributor-Attestation": h.creation_request.contributor_attestation, } route = f"/api/v1/tasks/{h.request.task_id}/submissions" created = await client.post(route, headers=headers, content=h.data) diff --git a/backend/tests/tasks/submission_dispatch/test_revision_exhaustion.py b/backend/tests/tasks/submission_dispatch/test_revision_exhaustion.py index f500e55b6..14361ed95 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_exhaustion.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_exhaustion.py @@ -162,9 +162,7 @@ async def _submit_initial_after_reclaim(h, client): assert claim.json()["task"]["status"] == "in_progress" h.data = revision_archive(h.data) headers = {"Content-Type": "application/zip", "X-Task-Assignment-Id": str(assignment), - "Idempotency-Key": str(new_record_id()), - "X-Submission-Summary": h.creation_request.summary, - "X-Contributor-Attestation": h.creation_request.contributor_attestation} + "Idempotency-Key": str(new_record_id())} async def submit_http(factory, context, command, metadata, data): async def submit(configured, received_metadata, chunks, **arguments): @@ -183,8 +181,7 @@ async def submit(configured, received_metadata, chunks, **arguments): h.factory, h.actor_context, h.store.wrapped, h.namespace, h.settings, SubmissionIntakeMetadata( task_id=h.request.task_id, assignment_id=assignment, - summary=h.creation_request.summary, - contributor_attestation=h.creation_request.contributor_attestation, + feedback=h.creation_request.summary, ), h.data, submit_source=submit_http, ) diff --git a/backend/tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py b/backend/tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py index 55610e7e9..773da80fb 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_exhaustion_recovery.py @@ -163,9 +163,7 @@ async def fail_after_append(owner, *args, **kwargs): await _assert_upgraded_incompatible_revision_blocked( h, tmp_path, isolated_database_env, monkeypatch, headers={"Content-Type": "application/zip", "Idempotency-Key": str(new_record_id()), - "X-Task-Assignment-Id": str(assignment), - "X-Submission-Summary": h.creation_request.summary, - "X-Contributor-Attestation": h.creation_request.contributor_attestation}) + "X-Task-Assignment-Id": str(assignment)}) async with h.factory() as session: assert await session.scalar(text( "SELECT public.task_revision_exhaustion_complete(:id)" diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index 6922ffec3..a9f9f67ad 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -185,29 +185,10 @@ async def test_public_malformed_zip_preserves_task_and_retains_cleanup_custody( assert valid.json()["status"] == "accepted" and valid.json()["replayed"] is False -def test_optional_public_text_keeps_metadata_and_retained_packet_bounds(): - """Empty ASCII headers normalize; retained packets keep their UTF-8 bound.""" - from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata - - base = {"task_id": new_record_id(), "assignment_id": new_record_id()} - omitted = SubmissionIntakeMetadata(**base) - empty = SubmissionIntakeMetadata(**base, summary="", contributor_attestation="") - assert omitted.summary == omitted.contributor_attestation == "" - assert omitted.metadata_sha256() == empty.metadata_sha256() - assert SubmissionIntakeMetadata(**base, summary="x" * 65536).summary == "x" * 65536 - with pytest.raises(ValueError): - SubmissionIntakeMetadata(**base, summary="x" * 65537) - with pytest.raises(ValueError, match="printable ASCII"): - SubmissionIntakeMetadata(**base, summary="é") - assert SubmissionPacketView("é" * 32768, "").sha256 - with pytest.raises(ValueError, match="submission packet text is invalid"): - SubmissionPacketView("é" * 32769, "") - - -async def test_public_optional_packet_text_survives_acceptance_finalization_and_replay( +async def test_public_minimal_submission_survives_acceptance_finalization_and_replay( admission_intake, tmp_path, monkeypatch, ): - """Omitted and empty headers retain warning-only packet facts through T5.""" + """The four-input command emits no text warnings and retains its replay identity.""" from uuid import UUID from sqlalchemy import text from tests.artifacts.test_submission_foreground_command import configure_source_http @@ -231,11 +212,10 @@ async def test_public_optional_packet_text_survives_acceptance_finalization_and_ assert receipt["status"] == "accepted" and receipt["replayed"] is False warnings = [item["warning_code"] for item in receipt["pre_submission_results"] if item["source"] == "workstream_default" and item["status"] == "warning"] - assert warnings == ["submission_summary_missing", "submission_attestation_missing"] - empty_headers = headers | {"X-Submission-Summary": "", "X-Contributor-Attestation": ""} - replay = await client.post(route, headers=empty_headers, content=payload) + assert warnings == [] + replay = await client.post(route, headers=headers, content=payload) assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text - changed = await client.post(route, headers=headers | {"X-Submission-Summary": "now supplied"}, + changed = await client.post(route, headers=headers | {"X-Submission-Feedback": "now supplied"}, content=payload) assert changed.status_code == 409, changed.text assert changed.json()["error"]["code"] == "submission_idempotency_conflict" @@ -251,16 +231,16 @@ async def test_public_optional_packet_text_survives_acceptance_finalization_and_ )) finally: bootstrap.close() - replay = await client.post(route, headers=empty_headers, content=payload) + replay = await client.post(route, headers=headers, content=payload) assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text assert len(calls) == 1 and not errors, errors async with f.factory() as session: stored = await session.get(Submission, submission_id) - assert stored.summary == stored.worker_attestation == "" + assert stored.summary is stored.worker_attestation is stored.feedback is None assert await session.scalar(select(func.count()).select_from(Submission)) == 1 admission = (await session.scalars(select(SubmissionBundleAdmission))).one() assert admission.status == "consumed" - assert admission.packet_sha256 == SubmissionPacketView("", "").sha256 + assert admission.packet_sha256 == SubmissionPacketView().sha256 assert await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun)) == 1 assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 1 @@ -360,8 +340,7 @@ async def test_public_initial_submission_replays_and_recovers_accepted_upload( route = f"/api/v1/tasks/{f.task}/submissions" headers = f.access.target.headers | { "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), - "Idempotency-Key": str(new_record_id()), "X-Submission-Summary": "Completed work", - "X-Contributor-Attestation": "I completed this work", + "Idempotency-Key": str(new_record_id()), "X-Submission-Feedback": "Completed work", } duplicate = await client.post(route, headers=list(headers.items()) + [ ("Idempotency-Key", headers["Idempotency-Key"]), @@ -374,11 +353,11 @@ async def test_public_initial_submission_replays_and_recovers_accepted_upload( denied_actor = await client.post(route, headers=headers | foreign.headers, content=payload) assert denied_actor.status_code == 404, denied_actor.text assert denied_actor.json()["error"]["code"] == "submission_unavailable" - denied_predecessor = await client.post(route, headers=headers | { - "X-Predecessor-Submission-Id": str(new_record_id()), + denied_assignment = await client.post(route, headers=headers | { + "X-Task-Assignment-Id": str(new_record_id()), }, content=payload) - assert denied_predecessor.status_code == 409, denied_predecessor.text - assert denied_predecessor.json()["error"]["code"] == "task_submission_predecessor_changed" + assert denied_assignment.status_code == 404, denied_assignment.text + assert denied_assignment.json()["error"]["code"] == "submission_unavailable" denied_uri = await client.post(route, headers=headers | {"Content-Type": "application/json"}, json={"package_uri": "s3://caller-controlled/bundle.zip"}) assert denied_uri.status_code == 415, denied_uri.text @@ -403,7 +382,7 @@ async def no_new_upload(*args, **kwargs): replay_patch.setattr(LocalStorageAdapter, "complete_source_upload", no_new_upload) replay = await client.post(route, headers=headers, content=payload) assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text - changed = await client.post(route, headers=headers | {"X-Submission-Summary": "changed"}, + changed = await client.post(route, headers=headers | {"X-Submission-Feedback": "changed"}, content=payload) assert changed.status_code == 409, changed.text assert changed.json()["error"]["code"] == "submission_idempotency_conflict" @@ -441,8 +420,8 @@ async def no_new_upload(*args, **kwargs): assert await session.scalar(select(func.count()).select_from(Submission)) == 1 stored = await session.get(Submission, submission_id) assert stored.version == 1 - assert stored.summary == headers["X-Submission-Summary"] - assert stored.worker_attestation == headers["X-Contributor-Attestation"] + assert stored.feedback == headers["X-Submission-Feedback"] + assert stored.summary is stored.worker_attestation is None assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun)) == 1 assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 1 @@ -468,11 +447,6 @@ async def test_public_checker_remediation_uses_exact_predecessor( "Content-Type": "application/zip", "X-Task-Assignment-Id": str(h.request.assignment_id), "Idempotency-Key": str(new_record_id()), - "X-Predecessor-Submission-Id": str(h.created.submission_id), - "X-Revision-Preparation-Id": str(h.revision_preparation_id), - "X-Revision-Preparation-Sha256": h.revision_preparation_sha256, - "X-Submission-Summary": h.creation_request.summary, - "X-Contributor-Attestation": h.creation_request.contributor_attestation, } async with _client(h, monkeypatch, isolated_database_env) as client: client, settings, errors, calls = await configure_source_http( @@ -485,13 +459,6 @@ async def test_public_checker_remediation_uses_exact_predecessor( "capacity": {"maximum_total_bytes": 16 * 1024**2}, }}) monkeypatch.setattr(client._transport.app.state, "settings", settings) - denied = await client.post(route, headers=headers | { - "X-Predecessor-Submission-Id": str(new_record_id()), - }, content=payload) - assert denied.status_code == 409, denied.text - assert denied.json()["error"]["code"] == "task_submission_predecessor_changed" - assert calls == [] - created = await client.post(route, headers=headers, content=payload) assert not errors, "\n".join(errors) async with h.factory() as session: @@ -548,7 +515,7 @@ async def test_confirmed_intake_deadline_persists_terminal_failure_and_replays( headers = f.access.target.headers | { "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), "Idempotency-Key": str(new_record_id()), - "X-Submission-Summary": "Completed work", "X-Contributor-Attestation": "I completed this work", + "X-Submission-Feedback": "Completed work", } first = await client.post(route, headers=headers, content=payload) assert first.status_code == 503, first.text diff --git a/backend/tests/tasks/test_submission_lineage.py b/backend/tests/tasks/test_submission_lineage.py index 529eaf824..48617577e 100644 --- a/backend/tests/tasks/test_submission_lineage.py +++ b/backend/tests/tasks/test_submission_lineage.py @@ -333,48 +333,31 @@ def _lineage_finalizer(h, settings, operation_id): async def _assert_t5_packet_refusals(h, finalizer, operation_id, claim, observation, monkeypatch): - from app.modules.artifacts.authorization import PreparedSubmissionFinalizationAuthorization from app.modules.tasks.submission_composition import TaskSubmissionCreationService before = await _t5_lineage_snapshot(h) create = TaskSubmissionCreationService.create_accepted - for field in ("admission_id", "summary", "contributor_attestation"): - reached = [] - async def substitute_request(service, request, **kwargs): - reached.append(field) - value = new_record_id() if field == "admission_id" else getattr(request, field) + " Changed." - return await create(service, replace(request, **{field: value}), **kwargs) - with monkeypatch.context() as patch: - patch.setattr(TaskSubmissionCreationService, "create_accepted", substitute_request) - with pytest.raises(SubmissionAdmissionConsumptionError) as denied: - await finalizer._finalize(operation_id, claim, observation) - assert denied.value.code == "submission_bundle_admission_unavailable" - assert reached == [field] - assert await _t5_lineage_snapshot(h) == before - - consume = PreparedSubmissionFinalizationAuthorization.consume - for column in ("summary", "worker_attestation"): - reached = [] - async def substitute_packet(authority, *, prepared_authorization, facts): - decision = await consume(authority, prepared_authorization=prepared_authorization, facts=facts) - assert facts.phase == "commit" - changed = await authority._session.scalar(text( - f"UPDATE public.submissions SET {column}={column} || ' Changed.' " - "WHERE id=:id RETURNING id"), {"id": facts.submission_id}) - assert str(changed) == str(facts.submission_id) - reached.append(column) - await authority._session.execute(text("SET CONSTRAINTS submission_packet_custody IMMEDIATE")) - return decision - with monkeypatch.context() as patch: - patch.setattr(PreparedSubmissionFinalizationAuthorization, "consume", substitute_packet) - with pytest.raises(IntegrityError, match="submission packet differs from checked evidence") as denied: - await finalizer._finalize(operation_id, claim, observation) - assert denied.value.orig.sqlstate == "23514" - assert reached == [column] - assert await _t5_lineage_snapshot(h) == before - - -async def test_public_zip_and_t5_copy_exact_assignment_and_checked_packet( + async def substitute_admission(service, request, **kwargs): + return await create(service, replace(request, admission_id=new_record_id()), **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(TaskSubmissionCreationService, "create_accepted", substitute_admission) + with pytest.raises(SubmissionAdmissionConsumptionError) as denied: + await finalizer._finalize(operation_id, claim, observation) + assert denied.value.code == "submission_bundle_admission_unavailable" + assert await _t5_lineage_snapshot(h) == before + + async def substitute_feedback(service, request, **kwargs): + return await create(service, replace(request, feedback=request.feedback + " Changed."), **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(TaskSubmissionCreationService, "create_accepted", substitute_feedback) + with pytest.raises(IntegrityError, match="submission feedback differs from the accepted command"): + await finalizer._finalize(operation_id, claim, observation) + assert await _t5_lineage_snapshot(h) == before + + +async def test_public_zip_and_t5_copy_exact_assignment_and_feedback( isolated_database_env, tmp_path, monkeypatch, ): from app.modules.artifacts.intake.models import SubmissionIntakeOperation @@ -383,14 +366,10 @@ async def test_public_zip_and_t5_copy_exact_assignment_and_checked_packet( from tests.tasks.test_public_submission_intake import _client async with _submission_task(isolated_database_env, tmp_path) as h: - h.creation = SimpleNamespace( - summary=r'Completed the "required" project work in folder \results with evidence.', - contributor_attestation="I confirm no confidential client data, credentials, or copied source material " - "is included in this submission; rights_confirmed. " + " ".join(h.policy["attestation_terms"])) + h.creation = SimpleNamespace(feedback=r'Completed the "required" project work in folder \results with evidence.') headers = { "Content-Type": "application/zip", "Idempotency-Key": str(new_record_id()), - "X-Task-Assignment-Id": str(h.assignment_id), "X-Submission-Summary": h.creation.summary, - "X-Contributor-Attestation": h.creation.contributor_attestation, + "X-Task-Assignment-Id": str(h.assignment_id), "X-Submission-Feedback": h.creation.feedback, } async with _client(h, monkeypatch, isolated_database_env) as client: _, settings, errors, calls = await configure_source_http( @@ -401,12 +380,13 @@ async def test_public_zip_and_t5_copy_exact_assignment_and_checked_packet( assert len(calls) == 1 and errors == [], errors operation_id = UUID(accepted.json()["operation_id"]) before = await _t5_lineage_snapshot(h) - for name in ("X-Submission-Summary", "X-Contributor-Attestation"): - changed = await client.post(route, headers=headers | {name: headers[name] + " Changed."}, - content=h.archive_bytes) - assert changed.status_code == 409, changed.text - assert changed.json()["error"]["code"] == "submission_idempotency_conflict" - assert await _t5_lineage_snapshot(h) == before + changed = await client.post( + route, headers=headers | {"X-Submission-Feedback": h.creation.feedback + " Changed."}, + content=h.archive_bytes, + ) + assert changed.status_code == 409, changed.text + assert changed.json()["error"]["code"] == "submission_idempotency_conflict" + assert await _t5_lineage_snapshot(h) == before async with h.factory() as session: assert await session.scalar(select(func.count()).select_from(Submission)) == 0 finalizer = _lineage_finalizer(h, settings, operation_id) @@ -471,8 +451,8 @@ async def _assert_bound_packet_immutable(h, created): await session.execute(text(statement), {"id": admission_id, "foreign": new_record_id()}) async with factory() as session: retained = await session.get(Submission, str(created.submission_id)) - assert retained.summary == creation.summary - assert retained.worker_attestation == creation.contributor_attestation + assert retained.feedback == creation.feedback + assert retained.summary is retained.worker_attestation is None assert retained.submission_bundle_admission_id == str(admission_id) assert retained.artifact_binding_id == str(created.artifact_binding_id) assert retained.artifact_content_id == str(created.artifact_content_id) diff --git a/backend/tests/tasks/test_submission_requirements.py b/backend/tests/tasks/test_submission_requirements.py index 203a19015..562e72b36 100644 --- a/backend/tests/tasks/test_submission_requirements.py +++ b/backend/tests/tasks/test_submission_requirements.py @@ -37,8 +37,8 @@ ) FIELDS = { "task_id", "project_id", "guide_version", "policy_schema_version", "merge_algorithm_version", - "required_packet_fields", "required_artifacts", "required_evidence", "forbidden_artifacts", - "attestation_terms", "manifest_required", "artifact_hash_required", "artifact_hash_algorithm", + "required_artifacts", "required_evidence", "forbidden_artifacts", + "manifest_required", "artifact_hash_required", "artifact_hash_algorithm", "allowed_storage_schemes", "storage_reference_rules", "maximum_file_size_bytes", "maximum_package_size_bytes", "maximum_archive_entries", "maximum_archive_size_bytes", "packaging", } @@ -58,8 +58,8 @@ def test_requirement_contracts(): fragments_allowed=False, path_traversal_allowed=False) packaging = SubmissionPackagingRequirements(package_required=True, allowed_package_formats=("zip",)) values = dict(task_id=new_record_id(), project_id=new_record_id(), guide_version="guide", policy_schema_version=None, - merge_algorithm_version=None, required_packet_fields=("summary",), required_artifacts=(artifact,), - required_evidence=(evidence,), forbidden_artifacts=(forbidden,), attestation_terms=("original",), + merge_algorithm_version=None, required_artifacts=(artifact,), + required_evidence=(evidence,), forbidden_artifacts=(forbidden,), manifest_required=True, artifact_hash_required=True, artifact_hash_algorithm="sha256", allowed_storage_schemes=("s3",), storage_reference_rules=storage, maximum_file_size_bytes=None, maximum_package_size_bytes=None, maximum_archive_entries=None, maximum_archive_size_bytes=None, @@ -69,7 +69,7 @@ def test_requirement_contracts(): assert type(result) is cls and set(result.model_dump()) == FIELDS assert result.model_dump(mode="json")["packaging"]["allowed_package_formats"] == ["zip"] for field, invalid in (("task_id", "bad"), ("project_id", str(new_record_id())), ("guide_version", " "), - ("required_artifacts", [artifact]), ("attestation_terms", ["mutable"])): + ("required_artifacts", [artifact])): with pytest.raises(ValidationError): cls(**{**values, field: invalid}) with pytest.raises(ValidationError, match="extra_forbidden"): @@ -175,7 +175,6 @@ async def test_requirement_scope_and_assignment_visibility(task_client, monkeypa expected = {key: value for key, value in policy.items() if key in FIELDS and value is not None} expected.update(task_id=ready["id"], project_id=project["id"], guide_version=stored.locked_guide_version, policy_schema_version=policy["schema_version"], - required_packet_fields=["summary", "package_hash", "artifact_hash_manifest", "worker_attestation"], storage_reference_rules=dict(allowed_storage_schemes=policy["allowed_storage_schemes"], allowed_uri_prefixes=[f"{scheme}://" for scheme in policy["allowed_storage_schemes"]], credentials_allowed=False, query_strings_allowed=False, fragments_allowed=False, diff --git a/backend/tests/test_api_controls.py b/backend/tests/test_api_controls.py index 58b1e2829..dc8e6153a 100644 --- a/backend/tests/test_api_controls.py +++ b/backend/tests/test_api_controls.py @@ -925,19 +925,17 @@ async def unread_body(): ) -def test_raw_submission_headers_preserve_packet_without_consuming_body(): +def test_raw_submission_headers_preserve_feedback_without_consuming_body(): from uuid import UUID from app.api.submission_intake import submission_intake_headers task = UUID("019a0000-0000-7000-8000-000000000003") parsed = submission_intake_headers(_raw_submission_request([ - (b"x-submission-summary", b"Exact spacing"), - (b"x-contributor-attestation", b"x" * 65536), + (b"x-submission-feedback", b"Exact spacing"), (b"transfer-encoding", b"chunked"), ]), task) assert parsed.metadata.task_id == task - assert parsed.metadata.summary == "Exact spacing" - assert parsed.metadata.contributor_attestation == "x" * 65536 + assert parsed.metadata.feedback == "Exact spacing" assert parsed.declared_raw_bytes is None @@ -949,9 +947,7 @@ def test_raw_submission_rejects_every_duplicate_packet_or_framing_header(): # Deliberately independent of the parser's list: additions cannot silently # remove a required ambiguity check from this contract proof. names = ( - b"idempotency-key", b"x-task-assignment-id", b"x-submission-summary", - b"x-contributor-attestation", b"x-predecessor-submission-id", - b"x-revision-preparation-id", b"x-revision-preparation-sha256", + b"idempotency-key", b"x-task-assignment-id", b"x-submission-feedback", b"content-type", b"content-encoding", b"content-length", b"transfer-encoding", ) for name in names: @@ -961,23 +957,16 @@ def test_raw_submission_rejects_every_duplicate_packet_or_framing_header(): assert (caught.value.status_code, caught.value.error_code) == (422, "submission_packet_invalid") -def test_raw_submission_headers_preserve_revision_and_declared_limit(): +def test_raw_submission_headers_preserve_declared_limit_without_optional_feedback(): from app.api.submission_intake import submission_intake_headers from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES - predecessor, revision = uuid4(), uuid4() parsed = submission_intake_headers(_raw_submission_request([ (b"content-length", str(MAXIMUM_SUBMISSION_ZIP_BYTES).encode()), (b"content-encoding", b"identity"), - (b"x-predecessor-submission-id", str(predecessor).encode()), - (b"x-revision-preparation-id", str(revision).encode()), - (b"x-revision-preparation-sha256", b"sha256:" + b"a" * 64), ]), uuid4()) assert parsed.declared_raw_bytes == MAXIMUM_SUBMISSION_ZIP_BYTES - assert parsed.metadata.predecessor_submission_id == predecessor - assert parsed.metadata.revision_preparation_id == revision - assert parsed.metadata.revision_preparation_sha256 == "sha256:" + "a" * 64 - assert parsed.metadata.summary == parsed.metadata.contributor_attestation == "" + assert parsed.metadata.feedback is None @pytest.mark.parametrize("extra,omit,status,code", [ @@ -990,10 +979,9 @@ def test_raw_submission_headers_preserve_revision_and_declared_limit(): ([(b"content-length", b"+12")], [], 422, "submission_packet_invalid"), ([(b"content-length", b"0")], [], 422, "submission_packet_invalid"), ([(b"content-length", b"524288001")], [], 413, "submission_archive_limit_exceeded"), - ([(b"x-submission-summary", b" trimmed ")], [], 422, "submission_packet_invalid"), - ([(b"x-contributor-attestation", b"\xff")], [], 422, "submission_packet_invalid"), - ([(b"x-submission-summary", b"x" * 65537)], [], 422, "submission_packet_invalid"), - ([(b"x-revision-preparation-sha256", b"sha256:" + b"a" * 64)], [], 422, "submission_packet_invalid"), + ([(b"x-submission-feedback", b" trimmed ")], [], 422, "submission_packet_invalid"), + ([(b"x-submission-feedback", b"\xff")], [], 422, "submission_packet_invalid"), + ([(b"x-submission-feedback", b"x" * 4097)], [], 422, "submission_packet_invalid"), ]) def test_raw_submission_invalid_headers_refuse_before_body(extra, omit, status, code): from uuid import UUID @@ -1010,11 +998,7 @@ def _casefold_packet_headers(): (b'content-type', b'application/zip'), (b'idempotency-key', b'019a0000-0000-7000-8000-000000000001'), (b'x-task-assignment-id', b'019a0000-0000-7000-8000-000000000002'), - (b'x-submission-summary', b'Exact text'), - (b'x-contributor-attestation', b'My work'), - (b'x-predecessor-submission-id', b'019a0000-0000-7000-8000-000000000003'), - (b'x-revision-preparation-id', b'019a0000-0000-7000-8000-000000000004'), - (b'x-revision-preparation-sha256', b'sha256:' + b'a' * 64), + (b'x-submission-feedback', b'Exact text'), (b'content-encoding', b'identity'), (b'content-length', b'1'), ] @@ -1054,8 +1038,8 @@ async def body(): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as client: response = await client.post(f"/api/v1/tasks/{uuid4()}/submissions", content=body(), headers=[ ("Content-Type", "application/zip"), ("Idempotency-Key", str(uuid4())), - ("X-Task-Assignment-Id", str(uuid4())), ("X-Submission-Summary", "one"), - ("x-submission-summary", "two"), + ("X-Task-Assignment-Id", str(uuid4())), ("X-Submission-Feedback", "one"), + ("x-submission-feedback", "two"), ]) assert response.status_code == 422, response.text assert response.json()["error"]["code"] == "submission_packet_invalid" @@ -1070,9 +1054,8 @@ async def forbidden_read(): @pytest.mark.parametrize('header', [ b'content-type', b'idempotency-key', b'x-task-assignment-id', - b'x-submission-summary', b'x-contributor-attestation', - b'x-predecessor-submission-id', b'x-revision-preparation-id', - b'x-revision-preparation-sha256', b'content-encoding', b'content-length', + b'x-submission-feedback', + b'content-encoding', b'content-length', b'transfer-encoding', ]) def test_raw_submission_mixed_case_duplicates_reject_valid_packet(header): @@ -1086,7 +1069,7 @@ def test_raw_submission_mixed_case_duplicates_reject_valid_packet(header): task = UUID(int=3) # Valid control prevents an unrelated packet/framing error from satisfying # the duplicate refusal assertion. - assert submission_intake_headers(_casefold_request(headers), task).metadata.summary == 'Exact text' + assert submission_intake_headers(_casefold_request(headers), task).metadata.feedback == 'Exact text' value = next(value for name, value in headers if name == header) with pytest.raises(StructuredHTTPException) as caught: submission_intake_headers(_casefold_request(headers + [(header.upper(), value)]), task) diff --git a/backend/tests/test_submission_bundle_preparation_recovery.py b/backend/tests/test_submission_bundle_preparation_recovery.py index ac3eeeb79..5e5e63ce5 100644 --- a/backend/tests/test_submission_bundle_preparation_recovery.py +++ b/backend/tests/test_submission_bundle_preparation_recovery.py @@ -63,8 +63,7 @@ async def _mounted_submission_response(error=None, *, command=None, packet_text= "Idempotency-Key": str(key), } if packet_text: - headers.update({"X-Submission-Summary": "summary", - "X-Contributor-Attestation": "attestation"}) + headers["X-Submission-Feedback"] = "feedback" async with AsyncClient( transport=ASGITransport(app=app), base_url="http://testserver" ) as client: diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index 3958cf5ed..e841ea886 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -303,7 +303,6 @@ async def test_replacement_without_routed_cause_denied_before_bytes( headers = { 'Content-Type': 'application/zip', 'Idempotency-Key': str(new_record_id()), 'X-Task-Assignment-Id': str(h.request.assignment_id), - 'X-Predecessor-Submission-Id': str(h.created.submission_id), } async with h.factory() as session: before_operations = await session.scalar(text('SELECT count(*) FROM submission_intake_operations')) @@ -390,11 +389,11 @@ async def test_blocked_replacement_precheck_preserves_revision_state( route = f"/api/v1/tasks/{h.request.task_id}/submissions" _, errors, calls = await _revision_http_runtime( h, client, tmp_path, monkeypatch, data, outcome="rejected") - headers = _revision_upload_headers(h) | {'X-Contributor-Attestation': ''} + headers = _revision_upload_headers(h) response = await client.post(route, headers=headers, content=data) results = await assert_public_revision_rejection( h, response, UUID(headers['Idempotency-Key']), data, before, 'high_confidence_secret_detected') - assert [r['warning_code'] for r in results if r['status'] == 'warning'] == ['submission_attestation_missing'] + assert [r['warning_code'] for r in results if r['status'] == 'warning'] == [] assert len(calls) == 1 and not errors, errors assert provider_writes == [] assert await _replacement_history(h, source_id, h.created.submission_id) == retained @@ -804,10 +803,10 @@ async def forbidden_upload(*_args, **_kwargs): guard.setattr(ForegroundSourceUpload, "receive", forbidden_upload) refused = await client.post( f"/api/v1/tasks/{local.request.task_id}/submissions", - headers=headers | {"X-Predecessor-Submission-Id": str(foreign.created.submission_id)}, + headers=headers | {"X-Task-Assignment-Id": str(foreign.request.assignment_id)}, content=_forbidden_bytes()) - assert refused.status_code == 409, refused.text - assert refused.json()["error"]["code"] == "task_submission_predecessor_changed" + assert refused.status_code == 404, refused.text + assert refused.json()["error"]["code"] == "submission_unavailable" assert await _snapshot(local) == baseline and writes == [] and calls == [] async with local.factory() as session: assert await session.scalar(text("SELECT count(*) FROM public.submission_intake_operations")) == intake_before @@ -886,7 +885,6 @@ async def forbidden_upload(*_args, **_kwargs): headers={ "Content-Type": "application/zip", "Idempotency-Key": str(new_record_id()), "X-Task-Assignment-Id": str(h.request.assignment_id), - "X-Predecessor-Submission-Id": str(h.created.submission_id), }, content=_forbidden_bytes()) assert refused.status_code == 404, refused.text assert refused.json()["error"]["code"] == "submission_unavailable" diff --git a/backend/tests/test_tasks.py b/backend/tests/test_tasks.py index a206ce333..29157084c 100644 --- a/backend/tests/test_tasks.py +++ b/backend/tests/test_tasks.py @@ -1637,12 +1637,8 @@ async def test_task_context_apis_return_worker_requirements_and_operator_provena assert requirements.status_code == 200, requirements.text requirements_body = requirements.json() assert requirements_body["guide_version"] == "v1" - assert requirements_body["required_packet_fields"] == [ - "summary", - "package_hash", - "artifact_hash_manifest", - "worker_attestation", - ] + assert "required_packet_fields" not in requirements_body + assert "attestation_terms" not in requirements_body assert requirements_body["required_artifacts"] == [ { "key": "required-artifact-001", From edd2a23203a518561522746eeb5ade4dd8307d12 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 07:59:28 +0100 Subject: [PATCH 349/513] Expose approved guide originals and exact contributor assignment evidence --- .../versions/0092_submission_feedback.py | 20 +- .../app/adapters/contributions/__init__.py | 8 + backend/app/api/deps/contributor_reads.py | 183 +++++++++++++++++- backend/app/api/routes/contributor_reads.py | 53 ++++- backend/app/api/routes/project_guide_reads.py | 5 + .../artifacts/api/submission_command.py | 65 ++++++- .../app/modules/artifacts/intake/models.py | 1 + .../app/modules/artifacts/intake/progress.py | 92 ++++++--- .../modules/artifacts/task_guide_documents.py | 3 +- .../authorization/api/contributor_reads.py | 1 + .../app/modules/authorization/catalogue.py | 6 +- .../app/modules/authorization/domain/audit.py | 4 + .../authorization/domain/contributor_reads.py | 6 + .../authorization/domain/task_authority.py | 2 +- backend/app/modules/checkers/api/external.py | 5 +- backend/app/modules/checkers/api/history.py | 4 + backend/app/modules/checkers/history.py | 20 +- .../app/modules/contributions/api/records.py | 17 ++ .../contributions/records/read_repository.py | 32 +++ .../app/modules/projects/api/guide_reads.py | 33 ++++ backend/app/modules/projects/guide_reads.py | 43 +++- .../modules/tasks/api/contributor_reads.py | 14 ++ .../app/modules/tasks/api/guide_documents.py | 22 +-- .../modules/tasks/api/submission_history.py | 5 +- .../app/modules/tasks/authorized_commands.py | 2 +- .../app/modules/tasks/contributor_reads.py | 34 +++- backend/app/modules/tasks/schemas.py | 2 +- .../tests/authorization/catalogue_fixtures.py | 4 + backend/tests/authorization/test_catalogue.py | 2 +- backend/tests/conftest.py | 2 +- backend/tests/tasks/test_guide_documents.py | 51 ++++- .../tasks/test_public_submission_intake.py | 16 ++ backend/tests/test_api_controls.py | 20 +- 33 files changed, 704 insertions(+), 73 deletions(-) diff --git a/backend/alembic/versions/0092_submission_feedback.py b/backend/alembic/versions/0092_submission_feedback.py index 61857ba3f..8f6a3355c 100644 --- a/backend/alembic/versions/0092_submission_feedback.py +++ b/backend/alembic/versions/0092_submission_feedback.py @@ -124,6 +124,15 @@ def upgrade() -> None: op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") op.execute("LOCK TABLE public.submission_intake_operations, public.selected_pre_submit_runs," " public.submissions, public.submission_dispatches IN ACCESS EXCLUSIVE MODE") + op.execute(""" + DO $$ + BEGIN + IF EXISTS (SELECT 1 FROM public.submission_intake_operations + WHERE state IN ('receiving', 'pre_checking')) THEN + RAISE EXCEPTION 'wait for active submission uploads and PRE checks to end before upgrading'; + END IF; + END $$; + """) op.execute(""" ALTER TABLE public.submissions ADD COLUMN feedback text, @@ -134,7 +143,8 @@ def upgrade() -> None: AND (feedback IS NULL OR (summary IS NULL AND octet_length(feedback)<=4096 AND feedback COLLATE "C" !~ '[^ -~]' AND btrim(feedback)=feedback)) ); - + """) + op.execute(""" CREATE FUNCTION public.guard_submission_feedback() RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$ BEGIN @@ -145,11 +155,13 @@ def upgrade() -> None: END IF; RETURN NEW; END $$; - + """) + op.execute(""" CREATE TRIGGER submission_feedback_immutable BEFORE UPDATE OF feedback,summary,worker_attestation ON public.submissions FOR EACH ROW EXECUTE FUNCTION public.guard_submission_feedback(); - + """) + op.execute(""" CREATE FUNCTION public.submission_operation_checker_packet(metadata jsonb) RETURNS jsonb LANGUAGE sql IMMUTABLE STRICT SET search_path=pg_catalog,public,pg_temp AS $$ SELECT CASE WHEN metadata ? 'feedback' THEN '{}'::jsonb @@ -157,6 +169,8 @@ def upgrade() -> None: 'contributor_attestation',metadata->>'contributor_attestation') END $$; """) + op.execute("CREATE INDEX ix_submission_intake_assignment_activity " + "ON public.submission_intake_operations (assignment_id,created_at,id)") _intake_guard() _pre_guard() acceptance = _definition("public.require_submission_acceptance_current(public.submission_intake_operations)") diff --git a/backend/app/adapters/contributions/__init__.py b/backend/app/adapters/contributions/__init__.py index 20555ff4f..9063c18ea 100644 --- a/backend/app/adapters/contributions/__init__.py +++ b/backend/app/adapters/contributions/__init__.py @@ -4,6 +4,7 @@ from app.modules.contributions.api.policies import ContributionPolicyVersionListPort from app.modules.contributions.api.published_selection import PublishedContributionPolicyPort from app.modules.contributions.api.records import ( + AcceptedAssignmentEvidencePort, ContributionExportPort, ContributionReadAuthorizationPort, ContributionExportResponse, ) @@ -124,3 +125,10 @@ def contribution_export_csv(projection: ContributionExportResponse) -> bytes: from app.modules.contributions.records.csv import contribution_csv return contribution_csv(projection) + + +def accepted_assignment_evidence_reader(session: AsyncSession) -> AcceptedAssignmentEvidencePort: + from app.adapters.compensation import contribution_award_read_port + from app.modules.contributions.records.read_repository import AcceptedAssignmentEvidenceReader + + return AcceptedAssignmentEvidenceReader(session, contribution_award_read_port(session)) diff --git a/backend/app/api/deps/contributor_reads.py b/backend/app/api/deps/contributor_reads.py index 8cedf6d62..839a2535b 100644 --- a/backend/app/api/deps/contributor_reads.py +++ b/backend/app/api/deps/contributor_reads.py @@ -1,5 +1,6 @@ """Compose the caller's own grant and work reads with canonical AUTH in one read transaction.""" +from contextlib import AsyncExitStack, asynccontextmanager from datetime import UTC, datetime from typing import Annotated from uuid import UUID @@ -15,6 +16,9 @@ from app.api.deps.snapshot_reads import run_snapshot_read, start_read_snapshot from app.core.api_controls import StructuredHTTPException from app.db.session import get_db_session +from app.modules.artifacts.api.submission_command import ( + AssignmentIntakeAttempt, AssignmentIntakeQuery, AssignmentIntakeReadPort, AssignmentIntakeUnavailable, +) from app.modules.artifacts.api.submission_preparation import ( SubmissionBundlePreparationDetail, SubmissionBundlePreparationPage, SubmissionBundlePreparationReadPort, SubmissionBundlePreparationSummary, @@ -24,11 +28,19 @@ ActorProjectRoles, ContributorReadAuthorizationPort, ContributorReadCursorInvalid, ContributorReadPosition, ContributorReadRequest, ContributorReadUnavailable, ) +from app.modules.checkers.api.execution import CheckerExecutionUnavailable +from app.modules.checkers.api.history import CheckerHistoryReadPort, ContributorCheckerResult from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitUnavailable +from app.modules.contributions.api.records import AcceptedAssignmentEvidence, AcceptedAssignmentEvidencePort from app.modules.compensation.api.award_reads import ContributorAwardTotal, ContributorAwardTotalsPort +from app.modules.projects.api.guide_documents import GuideDocumentUnavailable +from app.modules.projects.api.guide_reads import ( + ApprovedContributorGuide, ProjectGuideDocumentContentPort, ProjectGuideReadPort, ProjectGuideReadUnavailable, +) from app.modules.projects.api.project_summaries import ProjectStatus, ProjectSummaryFacts, ProjectSummaryReadPort from app.modules.tasks.api.contributor_reads import ( - AssignmentState, ContributorAssignmentCounts, ContributorAssignmentPage, ContributorAssignmentQuery, + AssignmentState, ContributorAssignment, ContributorAssignmentCounts, ContributorAssignmentPage, + ContributorAssignmentQuery, TaskStatus, ContributorSubmissionCounts, ContributorSubmissionPage, ContributorSubmissionQuery, ContributorWorkCounts, ContributorWorkReadPort, ) @@ -140,6 +152,21 @@ def _id(value: UUID | None) -> str | None: return None if value is None else str(value) +class ExactContributorAssignment(BaseModel): + """Current status, retained intake and governed evidence for one owned claim.""" + + model_config = _FROZEN + assignment: ContributorAssignment + current_status: TaskStatus | Literal["closed", "rejected"] + status_reason: str | None + next_action: Literal["submit", "awaiting_intake", "awaiting_evaluation", "revise", "wait_for_processing", "none"] + intake: AssignmentIntakeAttempt | None + feedback_submission_id: UUID | None + post_submission_results: tuple[ContributorCheckerResult, ...] = Field(max_length=100) + next_cursor: str | None + accepted_evidence: AcceptedAssignmentEvidence | None + + class ContributorReadOperation: """Authorize first, project only the caller's rows, validate, then commit evidence.""" @@ -147,18 +174,25 @@ def __init__( self, session: AsyncSession, actor_id: UUID, authority: ContributorReadAuthorizationPort, *, work: ContributorWorkReadPort, preparations: SubmissionBundlePreparationReadPort, projects: ProjectSummaryReadPort, awards: ContributorAwardTotalsPort, + guides: ProjectGuideReadPort, guide_documents: ProjectGuideDocumentContentPort, + intake: AssignmentIntakeReadPort, checker_history: CheckerHistoryReadPort, + accepted_evidence: AcceptedAssignmentEvidencePort, ) -> None: """Compose the AUTH decision port and the owner read ports for one request.""" self._session, self._actor_id, self._authority = session, actor_id, authority self._work, self._preparations = work, preparations self._projects, self._awards = projects, awards + self._guides, self._guide_documents = guides, guide_documents + self._intake, self._checker_history, self._accepted_evidence = intake, checker_history, accepted_evidence async def _run(self, request: ContributorReadRequest, read, *, in_snapshot: bool = False): """One bounded read: AUTH denials propagate to the decision owner for restaging.""" return await run_snapshot_read( self._session, lambda: self._authority.authorize(request), read, cursor_invalid=ContributorReadCursorInvalid, invalid_cursor=_cursor_invalid, - faults=(ContributorReadUnavailable, SelectedPreSubmitUnavailable, SQLAlchemyError, ValueError), + faults=(ContributorReadUnavailable, SelectedPreSubmitUnavailable, SQLAlchemyError, + ProjectGuideReadUnavailable, GuideDocumentUnavailable, AssignmentIntakeUnavailable, + CheckerExecutionUnavailable, ValueError), unavailable=_unavailable, in_snapshot=in_snapshot, ) @@ -189,6 +223,140 @@ async def read(grant): return await self._run(request, read) + async def approved_guide(self, project_id: UUID) -> ApprovedContributorGuide: + request = self._request( + "project.contributor_guide.read", {}, resource_id=project_id, project_id=project_id, + ) + + async def read(_grant): + selected = await self._guides.read_approved_contributor_guide(project_id) + if selected is None: + await self._session.commit() + raise _missing() + return selected.guide + + return await self._run(request, read) + + @asynccontextmanager + async def approved_guide_document(self, project_id: UUID, guide_id: UUID, document_id: UUID): + request = self._request( + "project.contributor_guide.read", {"guide_id": str(guide_id), "document_id": str(document_id)}, + resource_id=project_id, project_id=project_id, + ) + async with AsyncExitStack() as stack: + verified = None + + async def read(_grant): + selected = await self._guides.read_approved_contributor_guide(project_id) + if selected is not None and selected.guide.guide_id == guide_id: + for original, document in zip(selected.originals, selected.guide.documents, strict=True): + if document.document_id == document_id: + nonlocal verified + verified = await stack.enter_async_context(self._guide_documents.open(project_id, original)) + return document + await self._session.commit() + raise _missing() + + await self._run(request, read) + yield verified + + async def assignment(self, task_id: UUID, assignment_id: UUID, *, limit: int, cursor: str | None): + """Resolve only an exact owned assignment before project read authorization.""" + try: + await start_read_snapshot(self._session) + project_id = await self._work.resolve_own_assignment_project(task_id, assignment_id, self._actor_id) + except SQLAlchemyError as exc: + await self._session.rollback() + raise _unavailable() from exc + if project_id is None: + await self._session.rollback() + raise _missing() + request = self._request( + "task.assignment.read", {"task_id": str(task_id), "limit": limit}, + resource_id=assignment_id, project_id=project_id, cursor=cursor, + ) + + async def read(grant): + selected = await self._work.read_own_assignment(project_id, task_id, assignment_id, self._actor_id) + if selected is None: + await self._session.commit() + raise _missing() + assignment = selected.assignment + intake = await self._intake.read_assignment_attempt(AssignmentIntakeQuery( + project_id, task_id, assignment_id, self._actor_id, selected.active_operation_id, + )) + latest = assignment.latest_submission + history = None if latest is None else await self._checker_history.read_current_attempt( + submission_id=latest.submission_id, task_id=task_id, + ) + results, after = self._assignment_feedback(history, grant.position, limit, request) + status, reason, action = self._assignment_status(assignment, intake, history) + evidence = None + if status == "accepted" and latest is not None and latest.status == "accepted": + evidence = await self._accepted_evidence.read_accepted_assignment( + project_id=project_id, task_id=task_id, assignment_id=assignment_id, + contributor_id=self._actor_id, submission_id=latest.submission_id, + ) + if evidence is None: + raise ValueError("accepted assignment evidence is unavailable") + return ExactContributorAssignment( + assignment=assignment, current_status=status, status_reason=reason, next_action=action, + intake=intake, feedback_submission_id=history.submission_id if history is not None else None, + post_submission_results=results, next_cursor=after, accepted_evidence=evidence, + ) + + return await self._run(request, read, in_snapshot=True) + + def _assignment_feedback(self, history, position, limit, request): + if history is None: + if position is not None: + raise ContributorReadCursorInvalid("assignment feedback changed") + return (), None + stamp = history.completed_at or history.created_at + start = 0 + if position is not None: + if stamp != position.timestamp: + raise ContributorReadCursorInvalid("assignment feedback changed") + for index, finding in enumerate(history.results): + if finding.id == position.record_id: + start = index + 1 + break + else: + raise ContributorReadCursorInvalid("assignment feedback changed") + page = tuple(history.results[start:start + limit]) + more = start + limit < len(history.results) + return page, self._next(request, more, stamp, page[-1].id if page else None) + + @staticmethod + def _assignment_status(assignment, intake, history): + latest = assignment.latest_submission + if assignment.state == "closed": + if assignment.assignment_status == "revision_expired": + return "rejected", "revision_deadline_expired", "none" + if assignment.assignment_status == "revision_exhausted": + return "rejected", "revision_limit_reached", "none" + if assignment.assignment_status == "authority_revoked": + return "closed", "authority_revoked", "none" + if latest is not None and latest.status in {"accepted", "rejected"}: + return latest.status, latest.status_reason, "none" + return "closed", assignment.assignment_status, "none" + + status = assignment.task_status + if status is None: + raise ValueError("active assignment is missing its task state") + if intake is not None and intake.stage in {"receiving", "pre_checking"}: + return status, "submission_in_progress", "awaiting_intake" + if (intake is not None and intake.operationally_stalled + or status == "evaluation_pending" and history is not None and history.status == "infrastructure_failed"): + return status, "processing_unavailable", "wait_for_processing" + if status in {"submitted", "evaluation_pending", "review_pending"}: + return status, None, "awaiting_evaluation" + reason = intake.failure_code if intake is not None else None + if reason is None and status == "needs_revision" and assignment.revision is not None: + reason = (latest.status_reason if latest is not None else None) if assignment.revision.disposition == "ready" else assignment.revision.disposition + action = "submit" if assignment.next_action == "prepare_submission" else assignment.next_action + return status, reason, action + async def assignments(self, *, project_id, state: AssignmentState | None, updated_since, limit, cursor): request = self._request("actor.assignment.list", { "limit": limit, "order": "activity_at_id_asc", "state": state, @@ -299,10 +467,14 @@ async def get_contributor_reads( authority: Annotated[object, Depends(get_authorization_service)], ) -> ContributorReadOperation: """Build the contributor read operation from request-scoped owner adapters.""" - from app.adapters.artifacts import submission_bundle_preparation_reader + from app.adapters.artifacts import ( + project_guide_documents_port, submission_bundle_preparation_reader, submission_operation_read_service, + ) from app.adapters.auth import contributor_read_authorization + from app.adapters.checkers import checker_history_repository from app.adapters.compensation import contributor_award_totals_port - from app.adapters.projects import project_summary_reader + from app.adapters.contributions import accepted_assignment_evidence_reader + from app.adapters.projects import project_guide_reader, project_summary_reader from app.adapters.tasks import contributor_work_reader return ContributorReadOperation( @@ -310,4 +482,7 @@ async def get_contributor_reads( contributor_read_authorization(authority, session, request.app.state.settings.pagination_cursor_hmac_secret), work=contributor_work_reader(session), preparations=submission_bundle_preparation_reader(session), projects=project_summary_reader(session), awards=contributor_award_totals_port(session), + guides=project_guide_reader(session), guide_documents=project_guide_documents_port(session, request.app.state.settings), + intake=submission_operation_read_service(session, None), checker_history=checker_history_repository(session), + accepted_evidence=accepted_assignment_evidence_reader(session), ) diff --git a/backend/app/api/routes/contributor_reads.py b/backend/app/api/routes/contributor_reads.py index a0ba83229..bdf4973c6 100644 --- a/backend/app/api/routes/contributor_reads.py +++ b/backend/app/api/routes/contributor_reads.py @@ -1,19 +1,23 @@ """The caller's own projects, claims, attempts, intake preparations and totals.""" +from collections.abc import AsyncIterator from typing import Annotated from uuid import UUID from fastapi import APIRouter, Depends, Query +from fastapi.responses import StreamingResponse from pydantic import AwareDatetime from app.api.deps.authorization import enforce_human_authorization_read from app.api.deps.contributor_reads import ( - ActorProjectPage, ContributorReadOperation, ContributorWorkSummary, get_contributor_reads, + ActorProjectPage, ContributorReadOperation, ContributorWorkSummary, ExactContributorAssignment, get_contributor_reads, ) +from app.api.routes.project_guide_reads import _ORIGINAL_TYPES, guide_original_response from app.core.api_controls import ApiErrorResponse from app.modules.artifacts.api.submission_preparation import ( SubmissionBundlePreparationDetail, SubmissionBundlePreparationPage, ) +from app.modules.projects.api.guide_reads import ApprovedContributorGuide, VerifiedGuideDocumentRead from app.modules.tasks.api.contributor_reads import ( AssignmentState, ContributorAssignmentPage, ContributorSubmissionPage, ) @@ -49,6 +53,18 @@ async def list_my_assignments( ) +@router.get( + "/tasks/{task_id}/assignments/{assignment_id}", response_model=ExactContributorAssignment, + tags=["tasks"], responses=_ERRORS, + openapi_extra={"x-workstream-action-id": "task.assignment.read"}, +) +async def read_my_assignment( + task_id: UUID, assignment_id: UUID, reads: Reads, limit: PageLimit = 25, cursor: PageCursor = None, +) -> ExactContributorAssignment: + """Read your assignment status, feedback and earned evidence by task and assignment.""" + return await reads.assignment(task_id, assignment_id, limit=limit, cursor=cursor) + + @router.get( "/actors/me/submissions", response_model=ContributorSubmissionPage, tags=["actors"], responses=_ERRORS, openapi_extra={"x-workstream-action-id": "actor.submission.list"}, @@ -96,3 +112,38 @@ async def read_my_preparation( ) -> SubmissionBundlePreparationDetail: """One historical preparation with its intake findings; others are not found.""" return await reads.preparation(task_id=task_id, preparation_id=preparation_id) + + +@router.get( + "/projects/{project_id}/contributor-guide", response_model=ApprovedContributorGuide, + tags=["projects"], responses=_ERRORS, + openapi_extra={"x-workstream-action-id": "project.contributor_guide.read"}, +) +async def read_approved_contributor_guide(project_id: UUID, reads: Reads) -> ApprovedContributorGuide: + """Read the project's active approved contributor guide before claiming a task.""" + return await reads.approved_guide(project_id) + + +async def verified_contributor_guide_document( + project_id: UUID, guide_id: UUID, document_id: UUID, reads: Reads, +) -> AsyncIterator[VerifiedGuideDocumentRead]: + async with reads.approved_guide_document(project_id, guide_id, document_id) as read: + yield read + + +@router.get( + "/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content", + response_class=StreamingResponse, tags=["projects"], + openapi_extra={"x-workstream-action-id": "project.contributor_guide.read"}, + responses={ + 200: {"description": "Exact verified uploaded original", "content": { + media_type: {"schema": {"type": "string", "format": "binary"}} for media_type in _ORIGINAL_TYPES + }}, + **_ERRORS, + }, +) +async def read_contributor_guide_document( + read: Annotated[VerifiedGuideDocumentRead, Depends(verified_contributor_guide_document)], +) -> StreamingResponse: + """Download one exact original of the active approved guide.""" + return guide_original_response(read) diff --git a/backend/app/api/routes/project_guide_reads.py b/backend/app/api/routes/project_guide_reads.py index 0ebb7d859..73c01d9f7 100644 --- a/backend/app/api/routes/project_guide_reads.py +++ b/backend/app/api/routes/project_guide_reads.py @@ -88,6 +88,11 @@ async def read_guide_document_content( read: Annotated[VerifiedGuideDocumentRead, Depends(verified_guide_document)], ) -> StreamingResponse: """Serve one uploaded guide original after its bytes are verified against committed custody.""" + return guide_original_response(read) + + +def guide_original_response(read: VerifiedGuideDocumentRead) -> StreamingResponse: + """Use one verified-original response contract for both project audiences.""" return StreamingResponse(read.stream, media_type=read.media_type, headers={ "Content-Length": str(read.byte_count), "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff", diff --git a/backend/app/modules/artifacts/api/submission_command.py b/backend/app/modules/artifacts/api/submission_command.py index f60d71829..091f84d19 100644 --- a/backend/app/modules/artifacts/api/submission_command.py +++ b/backend/app/modules/artifacts/api/submission_command.py @@ -1,11 +1,16 @@ """Public single-request submission command and explicit deployment contract.""" from collections.abc import AsyncIterator +from dataclasses import dataclass from typing import Annotated, Literal, Protocol, Self from uuid import UUID from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits +from app.modules.checkers.api.default_checker import ( + WorkstreamDefaultCheck, WorkstreamDefaultWarningCode, +) +from app.modules.checkers.api.external import ExternalCheckerFinding, Identifier, Sha256 from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitRuntimeProfile from app.modules.tasks.api.management_queue import TaskStatus @@ -44,6 +49,33 @@ def bounded_envelopes(self) -> Self: return self +class DefaultIntakeCheck(WorkstreamDefaultCheck): + source: Literal["workstream_default"] + + +class DefaultIntakeWarning(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + source: Literal["workstream_default"] + status: Literal["warning"] + warning_code: WorkstreamDefaultWarningCode + + +class ProjectIntakeCheck(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + source: Literal["project_external_checker"] + requirement_id: Identifier + registry_entry_id: UUID + registry_entry_digest: Sha256 + status: Literal["passed", "failed"] + findings: list[ExternalCheckerFinding] = Field(max_length=256) + + +PreSubmissionResult = DefaultIntakeCheck | DefaultIntakeWarning | ProjectIntakeCheck +PreSubmissionResults = Annotated[list[PreSubmissionResult], Field(max_length=7)] + + class SubmissionAcceptedResponse(BaseModel): """Stable T4 snapshot; Submission/evaluation IDs do not exist until T5.""" @@ -56,7 +88,7 @@ class SubmissionAcceptedResponse(BaseModel): task_status_at_acceptance: Literal["evaluation_pending"] processing_stage_at_acceptance: Literal["finalization_pending"] replayed: bool - pre_submission_results: list[dict[str, object]] + pre_submission_results: PreSubmissionResults class SubmissionIntakeCommand(Protocol): @@ -70,6 +102,35 @@ async def submit( ... +class AssignmentIntakeUnavailable(RuntimeError): + """Exact owned custody could not be projected.""" + + +class AssignmentIntakeAttempt(BaseModel): + """Retained intake activity and its safe feedback for one assignment.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + operation_id: UUID + stage: str + failure_code: str | None + submission_id: UUID | None + pre_submission_results: PreSubmissionResults + operationally_stalled: bool + + +@dataclass(frozen=True, slots=True) +class AssignmentIntakeQuery: + project_id: UUID + task_id: UUID + assignment_id: UUID + contributor_id: UUID + active_operation_id: UUID | None + + +class AssignmentIntakeReadPort(Protocol): + async def read_assignment_attempt(self, query: AssignmentIntakeQuery) -> AssignmentIntakeAttempt | None: ... + + class SubmissionOperationSelector(BaseModel): """Two selectors for one read; key scope is supplied by authenticated context.""" @@ -108,7 +169,7 @@ class SubmissionOperationResponse(BaseModel): submission_id: UUID | None submission_version: Annotated[int, Field(strict=True, gt=0)] | None evaluation_request_id: UUID | None - pre_submission_results: list[dict[str, object]] + pre_submission_results: PreSubmissionResults failure_code: str | None operationally_stalled: bool next_action: Literal[ diff --git a/backend/app/modules/artifacts/intake/models.py b/backend/app/modules/artifacts/intake/models.py index 3817ca29e..2fa87e8ee 100644 --- a/backend/app/modules/artifacts/intake/models.py +++ b/backend/app/modules/artifacts/intake/models.py @@ -60,6 +60,7 @@ class SubmissionIntakeOperation(Base): Index("ix_submission_intake_cleanup_candidates", "terminal_at", "id", postgresql_where=text("state in ('rejected','failed','abandoned','cancelled') " "and accepted_at is null")), + Index("ix_submission_intake_assignment_activity", "assignment_id", "created_at", "id"), Index("ix_submission_intake_expiry", "lease_expires_at", "id", postgresql_where=text("state in ('receiving','pre_checking')")), ) diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py index a9580fbe1..48c5cc1b9 100644 --- a/backend/app/modules/artifacts/intake/progress.py +++ b/backend/app/modules/artifacts/intake/progress.py @@ -142,8 +142,40 @@ async def read(self, task_id, selector, *, actor_id): results = row.acceptance_receipt["pre_submission_results"] else: results = await self._feedback(row, repository) - stage, action, stalled = row.state, "wait", False + action = "wait" + stage, stalled, submission_id, version, request_id = await self._attempt_progress(row) + if row.state in {"rejected", "failed", "abandoned", "cancelled"}: + action = "inspect_governed_outcome" + if row.state != "cancelled" and await self._permits_new_intake(current.candidate): + action = "correct_and_submit_new_key" if row.state == "rejected" else "retry_new_key_after_terminal" + elif row.state == "finalized" and stage not in {"evaluation_pending", "evaluation_running", "operationally_stalled"}: + action = "inspect_governed_outcome" + return SubmissionOperationResponse( + operation_id=UUID(row.id), task_id=task_id, assignment_id=UUID(row.assignment_id), + idempotency_key=UUID(row.idempotency_key), operation_state=row.state, + processing_stage=stage, accepted_at=row.accepted_at, + task_status_at_acceptance="evaluation_pending" if accepted else None, + current_task_status=current.current_task_status, submission_id=submission_id, + submission_version=version, evaluation_request_id=request_id, + pre_submission_results=results, failure_code=self._public_failure(row.failure_code), operationally_stalled=stalled, next_action=action, + ) + + @staticmethod + def _public_failure(code): + if code is not None and code not in { + "submission_packet_invalid", "submission_archive_limit_exceeded", "submission_upload_timeout", + "submission_infrastructure_unavailable", "pre_submission_checker_failed", + "submission_foreground_expired", "submission_operation_cancelled", "revision_deadline_expired", + "submission_unavailable", "revision_context_changed", "revision_context_blocked", + "revision_limit_reached", "task_submission_predecessor_changed", + }: + code = "submission_operation_terminal" + return code + + async def _attempt_progress(self, row): + stage, stalled = row.state, False submission_id = version = request_id = None + task_id = UUID(row.task_id) if row.state == "finalization_pending": progress = await finalization_progress(row, self._events, self._deliveries) stalled = progress.operationally_stalled @@ -163,7 +195,7 @@ async def read(self, task_id, selector, *, actor_id): submission_id, version = outcome.submission_id, outcome.submission_version request_id = evaluation.current.request.evaluation_request_id if outcome.status != "evaluation_pending": - stage, action = outcome.status, "inspect_governed_outcome" + stage = outcome.status else: event_id = evaluation.completion_event_id or evaluation.retry_event_id or outcome.evaluation_event_id event = OutboxAppendInput.model_validate_json(evaluation.delivery_event_json or outcome.evaluation_event_json) @@ -171,27 +203,43 @@ async def read(self, task_id, selector, *, actor_id): stalled = evaluation.status == "infrastructure_failed" or delivery.state == "dead_letter" stage = ("operationally_stalled" if stalled else "evaluation_running" if evaluation.live_worker_lease else "evaluation_pending") - elif row.state in {"rejected", "failed", "abandoned", "cancelled"}: - action = "inspect_governed_outcome" - if row.state != "cancelled" and await self._permits_new_intake(current.candidate): - action = "correct_and_submit_new_key" if row.state == "rejected" else "retry_new_key_after_terminal" - code = row.failure_code - if code is not None and code not in { - "submission_packet_invalid", "submission_archive_limit_exceeded", "submission_upload_timeout", - "submission_infrastructure_unavailable", "pre_submission_checker_failed", - "submission_foreground_expired", "submission_operation_cancelled", "revision_deadline_expired", - "submission_unavailable", - }: - code = "submission_operation_terminal" - return SubmissionOperationResponse( - operation_id=UUID(row.id), task_id=task_id, assignment_id=UUID(row.assignment_id), - idempotency_key=UUID(row.idempotency_key), operation_state=row.state, - processing_stage=stage, accepted_at=row.accepted_at, - task_status_at_acceptance="evaluation_pending" if accepted else None, - current_task_status=current.current_task_status, submission_id=submission_id, - submission_version=version, evaluation_request_id=request_id, - pre_submission_results=results, failure_code=code, operationally_stalled=stalled, next_action=action, + return stage, stalled, submission_id, version, request_id + + async def read_assignment_attempt(self, query): + """Read one assignment-scoped operation and the original PRE projection.""" + from sqlalchemy import select, text + from app.modules.artifacts.api.submission_command import AssignmentIntakeAttempt, AssignmentIntakeUnavailable + from app.modules.artifacts.intake.models import SubmissionIntakeOperation + from app.modules.artifacts.intake.repository import SubmissionIntakeRepository + + model = SubmissionIntakeOperation + statement = select(model).where( + model.project_id == str(query.project_id), model.task_id == str(query.task_id), + model.assignment_id == str(query.assignment_id), model.actor_profile_id == str(query.contributor_id), ) + if query.active_operation_id is not None: + statement = statement.where(model.id == str(query.active_operation_id)) + row = await self._session.scalar(statement.order_by(model.created_at.desc(), model.id.desc()).limit(1)) + if row is None: + if query.active_operation_id is not None: + raise AssignmentIntakeUnavailable("assignment operation unavailable") + return None + try: + if row.accepted_at is not None: + await self._session.execute(text("SELECT public.require_submission_acceptance(o) " + "FROM public.submission_intake_operations o WHERE id=:id"), {"id": UUID(row.id)}) + results = row.acceptance_receipt["pre_submission_results"] + else: + repository = SubmissionIntakeRepository(self._session, self._tasks) + results = await self._feedback(row, repository) + stage, stalled, submission_id, _, _ = await self._attempt_progress(row) + return AssignmentIntakeAttempt( + operation_id=UUID(row.id), stage=stage, failure_code=self._public_failure(row.failure_code), + submission_id=submission_id, pre_submission_results=results, + operationally_stalled=stalled or row.failure_code == "submission_infrastructure_unavailable", + ) + except IntakeCustodyConflict as exc: + raise AssignmentIntakeUnavailable("assignment operation unavailable") from exc async def _feedback(self, row, repository): from app.modules.artifacts.api.submission_preparation import public_pre_submission_results diff --git a/backend/app/modules/artifacts/task_guide_documents.py b/backend/app/modules/artifacts/task_guide_documents.py index 522f84ded..7f5a1901e 100644 --- a/backend/app/modules/artifacts/task_guide_documents.py +++ b/backend/app/modules/artifacts/task_guide_documents.py @@ -22,9 +22,8 @@ ProjectGuideDocumentScopePort, GuideDocumentVersion, ) -from app.modules.projects.api.guide_reads import VerifiedGuideDocumentRead +from app.modules.projects.api.guide_reads import ContributorGuideDocument, VerifiedGuideDocumentRead from app.modules.tasks.api.guide_documents import ( - ContributorGuideDocument, TaskGuideDocumentNotFound, TaskGuideUnavailable, VerifiedTaskGuideRead, diff --git a/backend/app/modules/authorization/api/contributor_reads.py b/backend/app/modules/authorization/api/contributor_reads.py index 1b6b07114..6205c0f8e 100644 --- a/backend/app/modules/authorization/api/contributor_reads.py +++ b/backend/app/modules/authorization/api/contributor_reads.py @@ -7,6 +7,7 @@ ContributorReadAction = Literal[ "actor.project.list", "actor.assignment.list", "actor.submission.list", + "task.assignment.read", "project.contributor_guide.read", "actor.work_summary.read", "task.submission_bundle_preparation.list", "task.submission_bundle_preparation.read", "task.submission_operation.read", ] diff --git a/backend/app/modules/authorization/catalogue.py b/backend/app/modules/authorization/catalogue.py index a64d1e3b3..1e034ed3d 100644 --- a/backend/app/modules/authorization/catalogue.py +++ b/backend/app/modules/authorization/catalogue.py @@ -304,6 +304,8 @@ class ActionId(StrEnum): CONTRIBUTION_READ_PROJECT = "contribution.read_project" ACTOR_PROJECT_LIST = "actor.project.list" ACTOR_ASSIGNMENT_LIST = "actor.assignment.list" + TASK_ASSIGNMENT_READ = "task.assignment.read" + PROJECT_CONTRIBUTOR_GUIDE_READ = "project.contributor_guide.read" ACTOR_SUBMISSION_LIST = "actor.submission.list" ACTOR_WORK_SUMMARY_READ = "actor.work_summary.read" TASK_SUBMISSION_BUNDLE_PREPARATION_LIST = "task.submission_bundle_preparation.list" @@ -327,6 +329,8 @@ class ActionId(StrEnum): CONTRIBUTOR_WORK_READ_ACTIONS = frozenset( { ActionId.ACTOR_ASSIGNMENT_LIST, + ActionId.TASK_ASSIGNMENT_READ, + ActionId.PROJECT_CONTRIBUTOR_GUIDE_READ, ActionId.ACTOR_SUBMISSION_LIST, ActionId.ACTOR_WORK_SUMMARY_READ, ActionId.TASK_SUBMISSION_BUNDLE_PREPARATION_LIST, @@ -573,7 +577,7 @@ def _active( def _require_catalogue_counts() -> None: """Keep the closed action inventory and permission boundary exact.""" - if len(PERMISSION_IDS) != 95 or len(ACTION_IDS) != 195: + if len(PERMISSION_IDS) != 95 or len(ACTION_IDS) != 197: raise RuntimeError("authorization catalogue count mismatch") if len(HISTORICAL_PERMISSION_IDS) != 49 or len(NEW_PERMISSION_IDS) != 46: raise RuntimeError("authorization permission boundary mismatch") diff --git a/backend/app/modules/authorization/domain/audit.py b/backend/app/modules/authorization/domain/audit.py index e1214477f..8eae3954d 100644 --- a/backend/app/modules/authorization/domain/audit.py +++ b/backend/app/modules/authorization/domain/audit.py @@ -68,6 +68,8 @@ "actor_project_collection", "project_catalogue", "actor_assignment_collection", + "task_assignment_read", + "project_contributor_guide", "actor_submission_collection", "actor_work_summary", "task_submission_bundle_preparation_collection", @@ -170,6 +172,8 @@ "actor_project_collection", "project_catalogue", "actor_assignment_collection", + "task_assignment_read", + "project_contributor_guide", "actor_submission_collection", "actor_work_summary", "task_submission_bundle_preparation_collection", diff --git a/backend/app/modules/authorization/domain/contributor_reads.py b/backend/app/modules/authorization/domain/contributor_reads.py index 00e4db32b..eb71f06b7 100644 --- a/backend/app/modules/authorization/domain/contributor_reads.py +++ b/backend/app/modules/authorization/domain/contributor_reads.py @@ -32,12 +32,15 @@ def exact_actor(self): ContributorWorkResourceType = Literal[ "actor_assignment_collection", "actor_submission_collection", "actor_work_summary", "task_submission_bundle_preparation_collection", "submission_bundle_preparation_read", + "task_assignment_read", "project_contributor_guide", ] _ACTOR_WIDE = frozenset({ "actor_assignment_collection", "actor_submission_collection", "actor_work_summary", }) WORK_RESOURCE_BY_ACTION = { ActionId.ACTOR_ASSIGNMENT_LIST: "actor_assignment_collection", + ActionId.TASK_ASSIGNMENT_READ: "task_assignment_read", + ActionId.PROJECT_CONTRIBUTOR_GUIDE_READ: "project_contributor_guide", ActionId.ACTOR_SUBMISSION_LIST: "actor_submission_collection", ActionId.ACTOR_WORK_SUMMARY_READ: "actor_work_summary", ActionId.TASK_SUBMISSION_BUNDLE_PREPARATION_LIST: "task_submission_bundle_preparation_collection", @@ -61,6 +64,9 @@ def exact_scope(self): if self.resource_type in _ACTOR_WIDE: if self.resource_id != self.actor_profile_id: raise ValueError("contributor work read differs from caller") + elif self.resource_type == "project_contributor_guide": + if self.scope_project_id != self.resource_id: + raise ValueError("contributor guide requires its exact project") elif self.scope_project_id is None: raise ValueError("task work read requires its project") return self diff --git a/backend/app/modules/authorization/domain/task_authority.py b/backend/app/modules/authorization/domain/task_authority.py index 323668fb3..15834a844 100644 --- a/backend/app/modules/authorization/domain/task_authority.py +++ b/backend/app/modules/authorization/domain/task_authority.py @@ -200,7 +200,7 @@ def task_resource_guard(action: ActionId, resource: TaskAuthorityResourceContext if action in TASK_CONTRIBUTOR_READ_ACTIONS: return unassigned_ready or own_assignment if action is ActionId.TASK_GUIDE_READ: - return own_assignment + return unassigned_ready or own_assignment return action in TASK_MANAGER_READ_ACTIONS | TASK_LOCKED_CONTEXT_READ_ACTIONS | {ActionId.AUDIT_TASK_EVIDENCE_READ} diff --git a/backend/app/modules/checkers/api/external.py b/backend/app/modules/checkers/api/external.py index abb5a7efb..c0d6bd3ba 100644 --- a/backend/app/modules/checkers/api/external.py +++ b/backend/app/modules/checkers/api/external.py @@ -530,7 +530,10 @@ class ExternalCheckerFinding(ExternalCheckerValue): check_id: Identifier code: Identifier level: ExternalCheckerFindingLevel - message: Annotated[StrictStr, Field(min_length=1, max_length=4096)] + message: Annotated[StrictStr, Field( + min_length=1, max_length=4096, + description="Contributor-visible diagnosis, including useful correction guidance when available.", + )] path: Annotated[StrictStr, Field(min_length=1, max_length=1000)] | None = None line: Annotated[StrictInt, Field(ge=1, le=10_000_000)] | None = None diff --git a/backend/app/modules/checkers/api/history.py b/backend/app/modules/checkers/api/history.py index 288c82d4e..686e494a3 100644 --- a/backend/app/modules/checkers/api/history.py +++ b/backend/app/modules/checkers/api/history.py @@ -79,6 +79,10 @@ class ManagementCheckerHistoryPage(BaseModel): class CheckerHistoryReadPort(Protocol): """CHECKERS reads only within the already authorized immutable TASK parent.""" + async def read_current_attempt( + self, *, submission_id: UUID, task_id: UUID, + ) -> ContributorCheckerHistory | None: ... + async def read( self, *, submission_id: UUID, task_id: UUID, manager: bool, run_id: UUID | None = None, limit: int = 25, diff --git a/backend/app/modules/checkers/history.py b/backend/app/modules/checkers/history.py index 9bdcf6579..7963eb7ab 100644 --- a/backend/app/modules/checkers/history.py +++ b/backend/app/modules/checkers/history.py @@ -2,7 +2,8 @@ from uuid import UUID -from sqlalchemy import func, select, tuple_ +from sqlalchemy import cast, func, select, tuple_ +from sqlalchemy.dialects.postgresql import JSONB from app.modules.checkers.models import ( CheckerResult, CheckerResultFinding, CheckerRun, CheckerSubmissionFence, @@ -26,6 +27,16 @@ class CheckerHistoryRepository: def __init__(self, session): self._session = session + async def read_current_attempt(self, *, submission_id, task_id): + """Resolve the sole fence, then use the existing contributor projection.""" + run_id = await self._session.scalar(select(CheckerSubmissionFence.current_run_id).where( + CheckerSubmissionFence.submission_id == str(submission_id), + )) + if run_id is None: + return None + items, _ = await self.read(submission_id=submission_id, task_id=task_id, manager=False, run_id=run_id) + return items[0] if items else None + async def read(self, *, submission_id, task_id, manager, run_id=None, limit=25, after=None): schema = ManagementCheckerHistory if manager else ContributorCheckerHistory current = select(CheckerSubmissionFence.submission_id).where( @@ -59,12 +70,15 @@ async def _results(self, run_ids, *, submission_id, task_id, manager): if not run_ids: return {} result_schema = ManagementCheckerResult if manager else ContributorCheckerResult + finding_body = cast(CheckerRun.result_json, JSONB)["execution"]["external_members"][ + CheckerResult.member_order]["result"]["findings"][CheckerResultFinding.finding_order] statement = select( CheckerResult.checker_run_id, CheckerResult.id.label("member_id"), CheckerResult.checker_name, CheckerResult.status.label("member_status"), CheckerResult.severity.label("member_severity"), CheckerResult.failure_category, CheckerResultFinding.id.label("finding_id"), CheckerResultFinding.check_id, CheckerResultFinding.path, CheckerResultFinding.line, CheckerResultFinding.level, + finding_body["message"].as_string().label("finding_message"), ).join( CheckerRun, CheckerRun.id == CheckerResult.checker_run_id, ).outerjoin( @@ -89,6 +103,10 @@ async def _results(self, run_ids, *, submission_id, task_id, manager): else: status, severity = _FINDING_STATUS[row["level"]] message, fix = RESULT_STATUS_MESSAGES[status] + if row["finding_message"] is not None: + # The retained checker message contains the approved diagnosis + # and any correction guidance. Preserve it verbatim. + message, fix = row["finding_message"], None visible = row["failure_category"] != "task_configuration" item = { "id": row["finding_id"] or row["member_id"], diff --git a/backend/app/modules/contributions/api/records.py b/backend/app/modules/contributions/api/records.py index 05a96c504..5e43082a0 100644 --- a/backend/app/modules/contributions/api/records.py +++ b/backend/app/modules/contributions/api/records.py @@ -90,6 +90,23 @@ def validate_exact_quantity(self) -> Self: return self +class AcceptedAssignmentEvidence(BaseModel): + """The accepted artifact and earned awards of the contributor's exact assignment.""" + + model_config = _STRICT + contribution_id: UUID + submission_id: UUID + artifact_hash: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") + awards: tuple[ContributionAwardView, ...] = Field(max_length=2) + + +class AcceptedAssignmentEvidencePort(Protocol): + async def read_accepted_assignment( + self, *, project_id: UUID, task_id: UUID, assignment_id: UUID, + contributor_id: UUID, submission_id: UUID, + ) -> AcceptedAssignmentEvidence | None: ... + + class ContributionRecordView(BaseModel): """One recognized record with every applicable award and honest source times.""" diff --git a/backend/app/modules/contributions/records/read_repository.py b/backend/app/modules/contributions/records/read_repository.py index 6130b82fd..a4ca17895 100644 --- a/backend/app/modules/contributions/records/read_repository.py +++ b/backend/app/modules/contributions/records/read_repository.py @@ -10,7 +10,9 @@ from app.core.identifiers import new_record_id from app.db.errors import integrity_constraint_name +from app.modules.compensation.api.award_reads import ContributionAwardReadPort from app.modules.contributions.api.records import ( + AcceptedAssignmentEvidence, ContributionAwardView, MAX_EXPORT_MEMBERS, ContributionExportAtCapacity, ContributionExportTooLarge, ContributionExportUnavailable, ContributionReadRequest, InvalidContributionCursor, ) @@ -235,3 +237,33 @@ def _facts(row, version, mode, definitions) -> ContributionReadFacts: recorded_at=row.created_at, policy_version_number=version, compensation_mode=mode, award_definitions=definitions, ) + + +class AcceptedAssignmentEvidenceReader: + """Read exact accepted evidence under the caller's own-assignment authority.""" + + def __init__(self, session: AsyncSession, awards: ContributionAwardReadPort) -> None: + self._session, self._awards = session, awards + + async def read_accepted_assignment( + self, *, project_id: UUID, task_id: UUID, assignment_id: UUID, + contributor_id: UUID, submission_id: UUID, + ) -> AcceptedAssignmentEvidence | None: + record = await self._session.scalar(select(ContributionRecord).where( + ContributionRecord.project_id == str(project_id), + ContributionRecord.task_id == str(task_id), + ContributionRecord.source_task_assignment_id == str(assignment_id), + ContributionRecord.contributor_id == str(contributor_id), + ContributionRecord.submission_id == str(submission_id), + ContributionRecord.contribution_type == "accepted_submission", + )) + if record is None: + return None + awards = await self._awards.read_contribution_awards((record.id,)) + return AcceptedAssignmentEvidence( + contribution_id=record.id, submission_id=submission_id, artifact_hash=record.artifact_hash, + awards=tuple(ContributionAwardView( + award_id=award.id, award_definition_id=award.award_definition_id, + instrument=award.instrument_type, unit=award.unit_code, quantity=format(award.quantity, "f"), + ) for award in awards), + ) diff --git a/backend/app/modules/projects/api/guide_reads.py b/backend/app/modules/projects/api/guide_reads.py index 3f3844c4c..a14328103 100644 --- a/backend/app/modules/projects/api/guide_reads.py +++ b/backend/app/modules/projects/api/guide_reads.py @@ -142,6 +142,35 @@ class GuideDocumentSelection: original: LabeledGuideOriginal | None +class ContributorGuideDocument(BaseModel): + """Public original identity and authorized download reference.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + document_id: UUID + label: str + order: int = Field(ge=0) + media_type: GuideDocumentMediaType + sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") + byte_count: int = Field(gt=0) + read_reference: str + + +class ApprovedContributorGuide(BaseModel): + """The active guide's version and original documents for Submitters.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + project_id: UUID + guide_id: UUID + version: str + documents: tuple[ContributorGuideDocument, ...] = Field(max_length=100) + + +@dataclass(frozen=True, slots=True) +class ApprovedContributorGuideOriginals: + guide: ApprovedContributorGuide + originals: tuple[LabeledGuideOriginal, ...] + + class ProjectGuideReadUnavailable(RuntimeError): """Stored guide facts failed an integrity check; never includes content.""" @@ -149,6 +178,10 @@ class ProjectGuideReadUnavailable(RuntimeError): class ProjectGuideReadPort(Protocol): """Read a project's guides inside the caller's authorized read transaction.""" + async def read_approved_contributor_guide( + self, project_id: UUID, + ) -> ApprovedContributorGuideOriginals | None: ... + async def list_guides( self, project_id: UUID, *, status: GuideStatus | None, after: tuple[datetime, UUID] | None, limit: int, diff --git a/backend/app/modules/projects/guide_reads.py b/backend/app/modules/projects/guide_reads.py index 46a95aa9b..685e2d34f 100644 --- a/backend/app/modules/projects/guide_reads.py +++ b/backend/app/modules/projects/guide_reads.py @@ -6,8 +6,13 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.core.hashing import canonical_json_hash -from app.modules.projects.api.guide_documents import LabeledGuideOriginal, ProjectGuideDocumentSource +from app.modules.projects.api.guide_documents import ( + GuideDocumentUnavailable, LabeledGuideOriginal, LockedGuideOriginalsRequest, ProjectGuideDocumentSource, +) +from app.modules.projects.guide_activation.custody import load_guide_activation +from app.modules.projects.guide_compilation.document_scope import SqlAlchemyProjectGuideDocumentScope from app.modules.projects.api.guide_reads import ( + ApprovedContributorGuide, ContributorGuideDocument, ApprovedContributorGuideOriginals, GuideDocumentSelection, GuideReviewPolicyValues, GuideRevisionPolicyValues, @@ -27,7 +32,7 @@ GuideSourceSnapshotItem, ProjectGuide, ) -from app.modules.projects.repository import ProjectRepository +from app.modules.projects.repository import ProjectRepository, ProjectRepositoryIntegrityError from app.modules.projects.schemas import ReviewPolicyResponse, RevisionPolicyResponse @@ -38,6 +43,40 @@ def __init__(self, session: AsyncSession) -> None: """Read through the caller's session and snapshot.""" self._session = session + async def read_approved_contributor_guide(self, project_id: UUID) -> ApprovedContributorGuideOriginals | None: + """Select the active approved snapshot even when the ready queue is empty.""" + try: + guide = await ProjectRepository(self._session).get_active_guide(str(project_id)) + if guide is None or guide.activation_operation_id is None: + return None + activation = await load_guide_activation(self._session, guide) + proposal = activation.command.target.proposal + originals = await SqlAlchemyProjectGuideDocumentScope(self._session).lock_task_originals( + LockedGuideOriginalsRequest( + project_id=project_id, guide_id=UUID(guide.id), guide_version=guide.version, + source_snapshot_id=proposal.source_snapshot_id, + source_snapshot_hash=proposal.source_snapshot_hash, + ) + ) + except (ProjectRepositoryIntegrityError, GuideDocumentUnavailable, ValueError) as exc: + raise ProjectGuideReadUnavailable("approved guide originals unavailable") from exc + documents = tuple( + ContributorGuideDocument( + document_id=item.source.source_item_id, label=item.label, + order=item.source.item_order, media_type=item.source.media_type, + sha256=item.source.sha256, byte_count=item.source.byte_count, + read_reference=(f"/api/v1/projects/{project_id}/contributor-guide/{guide.id}/documents/" + f"{item.source.source_item_id}/content"), + ) + for item in originals + ) + return ApprovedContributorGuideOriginals( + ApprovedContributorGuide( + project_id=project_id, guide_id=UUID(guide.id), version=guide.version, documents=documents, + ), + originals, + ) + async def list_guides(self, project_id, *, status, after, limit): """Page the project's guides by ``(created_at, id)``, optionally by stored status.""" statement = select( diff --git a/backend/app/modules/tasks/api/contributor_reads.py b/backend/app/modules/tasks/api/contributor_reads.py index 84c26897d..f882abc79 100644 --- a/backend/app/modules/tasks/api/contributor_reads.py +++ b/backend/app/modules/tasks/api/contributor_reads.py @@ -61,6 +61,12 @@ class ContributorAssignment(BaseModel): )) +@dataclass(frozen=True, slots=True) +class OwnAssignmentSelection: + assignment: ContributorAssignment + active_operation_id: UUID | None + + class ContributorAssignmentPage(BaseModel): model_config = _FROZEN items: tuple[ContributorAssignment, ...] @@ -140,6 +146,14 @@ class ContributorSubmissionQuery: class ContributorWorkReadPort(Protocol): """Read-only TASK projections; the caller owns authority and the transaction.""" + async def resolve_own_assignment_project( + self, task_id: UUID, assignment_id: UUID, contributor_id: UUID, + ) -> UUID | None: ... + + async def read_own_assignment( + self, project_id: UUID, task_id: UUID, assignment_id: UUID, contributor_id: UUID, + ) -> OwnAssignmentSelection | None: ... + async def read_assignments( self, query: ContributorAssignmentQuery, ) -> tuple[tuple[ContributorAssignment, ...], bool]: ... diff --git a/backend/app/modules/tasks/api/guide_documents.py b/backend/app/modules/tasks/api/guide_documents.py index e77b2e52e..da6a89612 100644 --- a/backend/app/modules/tasks/api/guide_documents.py +++ b/backend/app/modules/tasks/api/guide_documents.py @@ -3,10 +3,10 @@ from collections.abc import AsyncIterator from contextlib import AbstractAsyncContextManager from dataclasses import dataclass -from typing import Literal, Protocol +from typing import Protocol from uuid import UUID -from pydantic import BaseModel, ConfigDict, Field +from app.modules.projects.api.guide_reads import ContributorGuideDocument @dataclass(frozen=True, slots=True) @@ -20,24 +20,6 @@ class TaskGuideSelection: source_snapshot_hash: str -class ContributorGuideDocument(BaseModel): - """Public original identity and task-scoped authorized read reference.""" - - model_config = ConfigDict(extra="forbid", frozen=True, strict=True) - document_id: UUID - order: int = Field(ge=0) - label: str - media_type: Literal[ - "application/pdf", - "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - "application/vnd.openxmlformats-officedocument.presentationml.presentation", - "text/markdown", - ] - byte_count: int = Field(gt=0) - sha256: str = Field(pattern=r"^sha256:[0-9a-f]{64}$") - read_reference: str - - @dataclass(frozen=True, slots=True) class VerifiedTaskGuideRead: """Fully verified immutable bytes, valid only within the owning context.""" diff --git a/backend/app/modules/tasks/api/submission_history.py b/backend/app/modules/tasks/api/submission_history.py index 00a0b5b22..bee89a092 100644 --- a/backend/app/modules/tasks/api/submission_history.py +++ b/backend/app/modules/tasks/api/submission_history.py @@ -2,7 +2,7 @@ from dataclasses import dataclass from datetime import datetime -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, Field from sqlalchemy import Subquery from typing import Literal, Protocol from uuid import UUID @@ -91,7 +91,8 @@ class ContributorSubmissionHistory(BaseModel): version: int status: SubmissionAttemptStatus status_reason: SubmissionStatusReason | None - summary: str + summary: str | None = Field(description="Retained summary on submissions recorded before project feedback.") + feedback: str | None submitted_at: datetime decided_at: datetime | None finding_counts: SubmissionFindingCounts diff --git a/backend/app/modules/tasks/authorized_commands.py b/backend/app/modules/tasks/authorized_commands.py index 5969c4bdd..89b7747af 100644 --- a/backend/app/modules/tasks/authorized_commands.py +++ b/backend/app/modules/tasks/authorized_commands.py @@ -962,7 +962,7 @@ async def contributor_work_context(self, task_id: UUID) -> ContributorTaskWorkCo revision_context=(await read_contributor_revision(self._session, task, assignment)) if own_assignment else None, guide_documents=(await self._guide_documents.list(task_id, self._guide_request(task, context))) - if own_assignment else (), + if own_assignment or actions else (), ) return response diff --git a/backend/app/modules/tasks/contributor_reads.py b/backend/app/modules/tasks/contributor_reads.py index 02128cdfa..05536c96d 100644 --- a/backend/app/modules/tasks/contributor_reads.py +++ b/backend/app/modules/tasks/contributor_reads.py @@ -16,7 +16,7 @@ AssignmentState, ContributorAssignment, ContributorAssignmentCounts, ContributorAssignmentQuery, ContributorLatestSubmission, ContributorSubmission, ContributorSubmissionCounts, ContributorSubmissionQuery, ContributorWorkCounts, NextAction, - RevisionDisposition, + OwnAssignmentSelection, RevisionDisposition, ) from app.modules.tasks.api.submission_history import ( SubmissionAttemptStatus, SubmissionFindingCounts, SubmissionFindingCountsPort, @@ -239,6 +239,38 @@ def __init__( self._tasks = TaskRepository(session, compensation_terms=compensation_terms) self._finding_counts = finding_counts + @staticmethod + def _own_assignment_scope(task_id, assignment_id, contributor_id): + return ( + TaskAssignment.task_id == str(task_id), + TaskAssignment.id == str(assignment_id), + TaskAssignment.contributor_id == str(contributor_id), + ) + + async def resolve_own_assignment_project(self, task_id, assignment_id, contributor_id) -> UUID | None: + project = await self._session.scalar(select(TaskAssignment.project_id).where( + *self._own_assignment_scope(task_id, assignment_id, contributor_id), + )) + return UUID(project) if project is not None else None + + async def read_own_assignment( + self, project_id, task_id, assignment_id, contributor_id, + ) -> OwnAssignmentSelection | None: + rows, _ = await read_assignment_page(self._session, self._tasks, ( + *self._own_assignment_scope(task_id, assignment_id, contributor_id), + TaskAssignment.project_id == str(project_id), + ), state=None, updated_since=None, after=None, limit=1) + if not rows: + return None + _, assignment = rows[0] + operation = None + if assignment.state == "active": + operation = await self._session.scalar(select(WorkstreamTask.active_submission_operation_id).where( + WorkstreamTask.id == str(task_id), WorkstreamTask.project_id == str(project_id), + WorkstreamTask.assigned_to == str(contributor_id), + )) + return OwnAssignmentSelection(assignment, UUID(operation) if operation is not None else None) + async def read_assignments(self, query: ContributorAssignmentQuery): if not query.project_ids: return (), False diff --git a/backend/app/modules/tasks/schemas.py b/backend/app/modules/tasks/schemas.py index bbe47c6d8..af1c9e96e 100644 --- a/backend/app/modules/tasks/schemas.py +++ b/backend/app/modules/tasks/schemas.py @@ -15,7 +15,7 @@ from app.modules.projects.api.guide_activation_context import GuidePolicySelection from app.modules.projects.api.locked_policy import GuideDisplayFacts, ProjectDisplayFacts from app.modules.tasks.api.task_detail import ContributorTaskDetail, ManagementTaskDetail -from app.modules.tasks.api.guide_documents import ContributorGuideDocument +from app.modules.projects.api.guide_reads import ContributorGuideDocument class ContributorTaskLifecycle(BaseModel): diff --git a/backend/tests/authorization/catalogue_fixtures.py b/backend/tests/authorization/catalogue_fixtures.py index d9d0bac74..59cf088cc 100644 --- a/backend/tests/authorization/catalogue_fixtures.py +++ b/backend/tests/authorization/catalogue_fixtures.py @@ -306,6 +306,8 @@ **dict.fromkeys( ( "actor.assignment.list", + "task.assignment.read", + "project.contributor_guide.read", "actor.submission.list", "actor.work_summary.read", "task.submission_bundle_preparation.list", @@ -616,6 +618,8 @@ "contribution.read_project", "actor.project.list", "actor.assignment.list", + "task.assignment.read", + "project.contributor_guide.read", "actor.submission.list", "actor.work_summary.read", "task.submission_bundle_preparation.list", diff --git a/backend/tests/authorization/test_catalogue.py b/backend/tests/authorization/test_catalogue.py index 434b47a29..5ef8c5b59 100644 --- a/backend/tests/authorization/test_catalogue.py +++ b/backend/tests/authorization/test_catalogue.py @@ -39,7 +39,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() -> assert {item.value for item in HISTORICAL_PERMISSION_IDS} == historical_permissions assert {item.value for item in NEW_PERMISSION_IDS} == new_permissions assert {item.value for item in PERMISSION_IDS} == historical_permissions | new_permissions - assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 195 + assert len(ACTION_IDS) == len(ACTION_DEFINITIONS) == len(ACTION_BY_ID) == 197 assert set(ACTION_BY_ID) == ACTION_IDS assert {definition.owner for definition in ACTION_DEFINITIONS} == set(ActionOwner) assert { diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 47aff9242..1fe5d0660 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "7ad79f8771b732cbabdc956cdffae50905b757990b1e5336f44990054967f31b" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "acd8db80e9b59a12af629042a8f452a2c40bd31f7ed203a71d3f48ee04db9e52" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/tasks/test_guide_documents.py b/backend/tests/tasks/test_guide_documents.py index f73a25a50..50ae92c35 100644 --- a/backend/tests/tasks/test_guide_documents.py +++ b/backend/tests/tasks/test_guide_documents.py @@ -5,7 +5,7 @@ from uuid import UUID, uuid4 import pytest -from sqlalchemy import select +from sqlalchemy import func, select from app.core.config import get_settings from app.core.identifiers import new_record_id @@ -23,7 +23,7 @@ auth_headers, set_dev_actor, admit_and_grant_project_submitter, - create_active_project, + create_active_project, create_ready_task, ) from app.adapters.tasks import task_commands from app.adapters.audit import task_transition_audit @@ -87,6 +87,49 @@ async def test_assigned_originals_are_ordered_and_verified(task_client, guide_wo )[index] +async def test_approved_guide_and_ready_task_originals_are_available_without_claim( + task_client, guide_world, monkeypatch, +): + from app.modules.tasks.models import TaskAssignment + + world, project = guide_world, guide_world.project["id"] + set_dev_actor(monkeypatch, roles="project_manager", subject="project-manager-subject") + contributor = await admit_and_grant_project_submitter(task_client, monkeypatch, project, "guide-reader") + project_path = f"/api/v1/projects/{project}/contributor-guide" + empty = await task_client.get(f"/api/v1/projects/{project}/tasks/ready", headers=auth_headers()) + assert empty.status_code == 200 and empty.json()["items"] == [] + approved = await task_client.get(project_path, headers=auth_headers()) + assert approved.status_code == 200, approved.text + original = approved.json() + assert (original["guide_id"], original["version"]) == (world.guide["id"], "v1") + assert set(original) == {"project_id", "guide_id", "version", "documents"} + read = await task_client.get(original["documents"][0]["read_reference"], headers=auth_headers()) + assert read.status_code == 200 and read.content == world.originals[0] + + set_dev_actor(monkeypatch, roles="project_manager", subject="project-manager-subject") + task = await create_ready_task(task_client, project) + newer, newer_bytes = await activate_uploaded_guide(task_client, project, monkeypatch, version="v2") + set_dev_actor(monkeypatch, roles="viewer", subject="guide-reader") + active = await task_client.get(project_path, headers=auth_headers()) + assert active.status_code == 200 and active.json()["guide_id"] == newer["id"] + refreshed = await task_client.get(active.json()["documents"][0]["read_reference"], headers=auth_headers()) + assert refreshed.status_code == 200 and refreshed.content == newer_bytes[0] + obsolete_project_read = await task_client.get(original["documents"][0]["read_reference"], headers=auth_headers()) + assert obsolete_project_read.status_code == 404 + task_context = await task_client.get(f"/api/v1/tasks/{task['id']}/work-context", headers=auth_headers()) + assert task_context.status_code == 200, task_context.text + context = task_context.json() + assert not context["lifecycle"]["assigned_to_current_actor"] + assert context["guide"]["id"] == world.guide["id"] + exact = await task_client.get(context["guide_documents"][0]["read_reference"], headers=auth_headers()) + assert exact.status_code == 200 and exact.content == world.originals[0] + async with db_session.get_session_factory()() as session: + count = await session.scalar(select(func.count()).select_from(TaskAssignment).where( + TaskAssignment.contributor_id == contributor["actor_profile_id"], + )) + assert count == 0 + + async def test_unassigned_and_foreign_actors_are_concealed(task_client, guide_world, monkeypatch): world = guide_world for subject in ("pilot13-bob", "pilot13-foreign"): @@ -99,6 +142,10 @@ async def test_unassigned_and_foreign_actors_are_concealed(task_client, guide_wo await admit_and_grant_project_submitter(task_client, monkeypatch, project_id, subject) denied = await task_client.get(content_path(world), headers=auth_headers()) assert denied.status_code == 404, denied.text + guide = await task_client.get( + f"/api/v1/projects/{world.project['id']}/contributor-guide", headers=auth_headers(), + ) + assert guide.status_code == (200 if subject == "pilot13-bob" else 404), guide.text context = await task_client.get( f"/api/v1/tasks/{world.task['id']}/work-context", headers=auth_headers() ) diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index a9f9f67ad..4203db5d0 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -210,6 +210,16 @@ async def test_public_minimal_submission_survives_acceptance_finalization_and_re assert first.status_code == 202, first.text receipt = first.json() assert receipt["status"] == "accepted" and receipt["replayed"] is False + status_path = f"/api/v1/tasks/{f.task}/assignments/{f.assignment}" + pending = await client.get(status_path, headers=f.access.target.headers) + assert pending.status_code == 200, pending.text + assert pending.json()["current_status"] == "evaluation_pending" + assert pending.json()["next_action"] == "awaiting_evaluation" + assert pending.json()["assignment"]["latest_submission"] is None + assert pending.json()["intake"]["pre_submission_results"] == receipt["pre_submission_results"] + assert (await client.get( + f"/api/v1/tasks/{f.task}/assignments/{new_record_id()}", headers=f.access.target.headers, + )).status_code == 404 warnings = [item["warning_code"] for item in receipt["pre_submission_results"] if item["source"] == "workstream_default" and item["status"] == "warning"] assert warnings == [] @@ -231,6 +241,10 @@ async def test_public_minimal_submission_survives_acceptance_finalization_and_re )) finally: bootstrap.close() + finalized = await client.get(status_path, headers=f.access.target.headers) + assert finalized.status_code == 200, finalized.text + assert finalized.json()["assignment"]["latest_submission"]["submission_id"] == str(submission_id) + assert finalized.json()["current_status"] == "evaluation_pending" replay = await client.post(route, headers=headers, content=payload) assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text assert len(calls) == 1 and not errors, errors @@ -406,6 +420,8 @@ async def no_new_upload(*args, **kwargs): history = await client.get(route, headers=f.access.target.headers) assert history.status_code == 200, history.text assert [item["id"] for item in history.json()["items"]] == [str(submission_id)] + assert history.json()["items"][0]["feedback"] == headers["X-Submission-Feedback"] + assert history.json()["items"][0]["summary"] is None async with f.factory.begin() as session: profile = await session.get(ActorProfile, str(f.actor.actor_profile_id)) profile.status = "suspended" diff --git a/backend/tests/test_api_controls.py b/backend/tests/test_api_controls.py index dc8e6153a..9a28f4a9e 100644 --- a/backend/tests/test_api_controls.py +++ b/backend/tests/test_api_controls.py @@ -523,6 +523,10 @@ def test_openapi_documents_request_error_and_response_context() -> None: contributor_reads = { "GET /api/v1/actors/me/projects": "actor.project.list", "GET /api/v1/actors/me/assignments": "actor.assignment.list", + "GET /api/v1/tasks/{task_id}/assignments/{assignment_id}": "task.assignment.read", + "GET /api/v1/projects/{project_id}/contributor-guide": "project.contributor_guide.read", + "GET /api/v1/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content": + "project.contributor_guide.read", "GET /api/v1/actors/me/submissions": "actor.submission.list", "GET /api/v1/actors/me/summary": "actor.work_summary.read", f"GET {preparations}": "task.submission_bundle_preparation.list", @@ -664,13 +668,18 @@ def test_openapi_documents_request_error_and_response_context() -> None: operation = schema["paths"][path][method.lower()] assert operation["x-workstream-action-id"] == action assert operation["security"] - assert len(route_inventory) == 134 - retained_routes = sorted(set(route_inventory) - proposal_routes - post_policy_routes - queue_routes - new_manager_reads - guide_read - contribution_reads.keys() - public_entry_actions.keys() - registry_actions.keys() - recovery_actions.keys() - model_actions.keys()) - retained_protected = sorted(set(protected_inventory) - proposal_routes - post_policy_routes - queue_routes - new_manager_reads - guide_read - contribution_reads.keys() - public_entry_actions.keys() - registry_actions.keys() - recovery_actions.keys() - model_actions.keys()) + assert len(route_inventory) == 137 + contributor_journey_routes = { + "GET /api/v1/tasks/{task_id}/assignments/{assignment_id}", + "GET /api/v1/projects/{project_id}/contributor-guide", + "GET /api/v1/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content", + } + retained_routes = sorted(set(route_inventory) - proposal_routes - post_policy_routes - queue_routes - new_manager_reads - guide_read - contribution_reads.keys() - public_entry_actions.keys() - registry_actions.keys() - recovery_actions.keys() - model_actions.keys() - contributor_journey_routes) + retained_protected = sorted(set(protected_inventory) - proposal_routes - post_policy_routes - queue_routes - new_manager_reads - guide_read - contribution_reads.keys() - public_entry_actions.keys() - registry_actions.keys() - recovery_actions.keys() - model_actions.keys() - contributor_journey_routes) assert sha256("\n".join(retained_routes).encode()).hexdigest() == ( "9a495b21b504f27997a26c233e7dc4b814133038a063376b760147118bd44b7e" ) - assert len(protected_inventory) == 132 + assert len(protected_inventory) == 135 assert sha256("\n".join(retained_protected).encode()).hexdigest() == ( "8aa0828260680a7bccdb055ebb3f21fcd06d4e37a808b4a0a37dcbf77ffa0732" ) @@ -1017,6 +1026,9 @@ def test_submission_mutation_is_one_raw_zip_acceptance_contract(): assert "post" not in app.openapi()["paths"].get("/api/v1/tasks/{task_id}/submission-bundle-preparations", {}) operation = app.openapi()["paths"][path]["post"] assert operation["x-workstream-action-id"] == "submission.create" + assert {value["name"] for value in operation["parameters"] if value["in"] == "header"} == { + "X-Task-Assignment-Id", "Idempotency-Key", "X-Submission-Feedback", "X-Request-ID", "X-Correlation-ID", + } assert set(operation["requestBody"]["content"]) == {"application/zip"} assert "202" in operation["responses"] and "201" not in operation["responses"] receipt = app.openapi()["components"]["schemas"]["SubmissionAcceptedResponse"] From 182770ead8c40e2788f260e53d9612e6c8052446 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:01:07 +0100 Subject: [PATCH 350/513] Unify CLI and MCP submitter commands and document the guide and status journey --- README.md | 6 + cli/README.md | 83 +- cli/internal/api/contributor_reads.go | 79 + cli/internal/api/manager_history.go | 4 +- cli/internal/api/submission.go | 79 +- cli/internal/api/submission_reads.go | 28 +- cli/internal/api/submission_test.go | 2 +- cli/internal/api/task_context.go | 12 +- cli/internal/api/task_guide.go | 63 +- cli/internal/command/guide_reads.go | 38 + cli/internal/command/submission.go | 86 +- cli/internal/command/task_context.go | 4 +- cli/internal/command/task_guide.go | 24 +- cli/internal/tui/details.go | 23 +- cli/internal/tui/details_layout_test.go | 15 +- cli/internal/tui/model_test.go | 3 +- cli/internal/tui/render_evidence_test.go | 5 +- .../test_manager_task_evidence_public_api.py | 4 +- cli/tests/integration/test_submission_http.py | 78 +- .../integration/test_submission_public_api.py | 13 +- .../integration/test_task_context_http.py | 8 +- cli/tests/integration/test_task_guide_http.py | 37 +- .../integration/test_task_guide_public_api.py | 18 +- docs/operations_revision_replay.md | 15 +- docs/roadmap_status.md | 15 +- docs/spec_submission_execution.md | 27 +- mcp_server/README.md | 37 +- .../contracts/authorization_context_get.json | 4 +- .../contracts/management_submission_get.json | 26 +- ...ment_task_submission_requirements_get.json | 18 +- .../management_task_submissions_list.json | 26 +- ...roject_contributor_guide_document_get.json | 375 ++++ .../project_contributor_guide_get.json | 427 +++++ mcp_server/contracts/submission_create.json | 274 ++- mcp_server/contracts/submission_get.json | 26 +- .../contracts/submission_operation_get.json | 233 ++- mcp_server/contracts/task_assignment_get.json | 1637 +++++++++++++++++ .../task_submission_requirements_get.json | 18 +- .../contracts/task_submissions_list.json | 26 +- .../contracts/task_work_context_get.json | 8 +- mcp_server/pyproject.toml | 3 + mcp_server/tests/test_task_execution.py | 47 +- .../test_task_execution_contract_drift.py | 2 +- mcp_server/workstream_mcp/errors.py | 6 + mcp_server/workstream_mcp/http_gateway.py | 79 +- mcp_server/workstream_mcp/schemas.py | 46 +- .../workstream_mcp/tools/task_execution.py | 45 +- 47 files changed, 3635 insertions(+), 497 deletions(-) create mode 100644 mcp_server/contracts/project_contributor_guide_document_get.json create mode 100644 mcp_server/contracts/project_contributor_guide_get.json create mode 100644 mcp_server/contracts/task_assignment_get.json diff --git a/README.md b/README.md index 94c4acae1..bdbb13d96 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,12 @@ authorized task audit context and evidence, and export contribution records. It sends your Flow token, from `WORKSTREAM_TOKEN`, with each request. +An eligible Submitter can read the project's approved guide before claiming work. +The CLI uses the same ZIP command for initial work and revisions. Run +`workstream task status TASK_ID --assignment ASSIGNMENT_ID` to read current +status, feedback and accepted evidence. The MCP exposes the same task and +assignment read. [Contributor CLI guide](cli/README.md#submit-and-inspect-contributor-work). + ## Repository layout | Folder | Contents | diff --git a/cli/README.md b/cli/README.md index 76ca014e0..c73bce10c 100644 --- a/cli/README.md +++ b/cli/README.md @@ -1112,16 +1112,13 @@ delivery, worker completion, live setup inference or deployed Flow behavior. ```sh workstream task submit TASK_ID --assignment ASSIGNMENT_ID --file work.zip \ - --idempotency-key CALLER_UUID --summary 'Completed work' --attestation 'My attestation' -# Inspect once using the returned operation ID, or your original caller key. -workstream task submission-operation TASK_ID --operation-id OPERATION_ID -workstream task submission-operation TASK_ID --idempotency-key CALLER_UUID -# For a checker-requested revision, inspect the current task context first. -workstream task context TASK_ID --output json + --idempotency-key CALLER_UUID +workstream task status TASK_ID --assignment ASSIGNMENT_ID +# After correcting work, use the same command and a new key. workstream task submit TASK_ID --assignment ASSIGNMENT_ID --file revision.zip \ - --predecessor SOURCE_SUBMISSION_ID --revision-preparation-id PREPARATION_ID \ - --revision-preparation-sha256 "$PREPARATION_SHA256" \ - --idempotency-key REVISION_KEY --summary 'Revised work' + --idempotency-key REVISION_KEY --feedback 'Updated the examples.' +# For exact request recovery, use the operation ID or the original key. +workstream task submission-operation TASK_ID --idempotency-key CALLER_UUID workstream task submissions TASK_ID --limit 25 workstream submission show SUBMISSION_ID workstream submission findings SUBMISSION_ID --limit 25 @@ -1141,26 +1138,24 @@ ID. Nullable Submission/evaluation IDs remain null before finalization. The operation's processing stage, PRE feedback and next-action advice come from the server; current task status is contextual and may differ from a historical outcome. -Submit accepts optional `--summary`, `--attestation` and `--predecessor`. -Revisions require the exact `revision_context.preparation_id` and -`revision_context.preparation_sha256` from authorized task context as -`--revision-preparation-id` and `--revision-preparation-sha256`. Both flags are -forbidden for initial submission. These acknowledge the governed revision context; -they do not request a separate bundle preparation. A fresh server check rejects a -stale pair after a rebase, deadline or source change. The CLI never chooses a -replacement automatically. - -Packet text uses headers: printable ASCII only, at most 64KiB per field, without -leading/trailing whitespace. Unsupported text is rejected before dispatch, not -rewritten. Omitted or empty text is supported, with warning-only defaults where -applicable. The API owns policy, predecessor/currentness and authorization checks. +Use `task status` with the task and assignment IDs to see current work status, +the relevant intake and evaluation feedback, revision deadline and terms, and +accepted contribution evidence. A status read is available throughout ordinary +revisions and afterwards in the assignment history. The backend selects the +current predecessor and revision terms under lock. It refuses an attempt if +eligibility or the selected terms change while intake is in progress. + +Optional `--feedback` is project feedback. The header accepts up to 4096 printable +ASCII bytes without leading or trailing whitespace. Workstream preserves the +exact supplied text. Feedback can be omitted on every submission and has no +effect on intake or earning. Before confirming upload success, the CLI rechecks file size, modification time and SHA-256; a changed source reports an uncertain outcome. A lost or malformed write response exits 1 with `outcome_unknown: true`, empty stdout and a text-mode recovery hint. Inspect progress with the original actor -and key. Any explicit replay must preserve task, assignment, key, ZIP bytes, -packet and revision acknowledgement. Do not create a new key while the outcome +and key. Any explicit replay must preserve task, assignment, key, ZIP bytes +and optional feedback. Do not create a new key while the outcome is unknown. Every read or replay requires fresh server authority. Blocked pre-submission intake prints the validated contributor findings in error @@ -1809,44 +1804,38 @@ not an empty successful result. Context returns contributor instructions, project/guide display facts, exact review/revision policy identities and contribution-policy version, plus the -server's current assignment/action hints and `guide_documents`. An active own -assignment receives the exact locked originals' IDs, order, labels, media types, -sizes, SHA-256 commitments and task-scoped read references; ready unassigned -browsing receives an empty document list. Task examples are never included. +server's current assignment/action hints and `guide_documents`. Ready unassigned tasks and active own assignments expose their exact locked +originals' IDs, order, labels, media types, sizes, SHA-256 commitments and +task-scoped read references. Task examples are never included. For a task awaiting revision, the optional `revision_context` gives the current preparation ID and digest, source Submission, deadline, eligibility disposition -and bounded change summary. It may be absent or null on other tasks. Use its -exact preparation pair for a revision ZIP submission; the read does not reserve -or authorize later intake. +and bounded change summary. It may be absent or null on other tasks. Use the shown deadline and terms to plan the next submission. Hints are observations, not authority or a claimability guarantee. The CLI never recomputes them or automatically executes a hinted action. Claim independently authorizes each request. -Requirements expose the task's locked guide and intake rules: packet fields, -artifact/evidence requirements, forbidden patterns, attestation, hash/manifest +Requirements expose the task's locked guide and intake rules, including +artifact and evidence requirements, forbidden patterns, hash and manifest requirements, storage-reference restrictions, size/entry limits and packaging. They are not a current-guide lookup, a checker verdict or permission to upload. These reads do not invoke `task submit`. Described paths and storage references are displayed only, never read, downloaded or executed. -### Read the assigned guide +### Read an approved guide ```sh -workstream task guide TASK_ID --output json -mkdir guide-documents -workstream task guide TASK_ID --download guide-documents +workstream project guide approved PROJECT_ID --output json +mkdir project-guide task-guide +workstream project guide approved PROJECT_ID --download project-guide +workstream task guide TASK_ID --download task-guide ``` -This requires an active assignment and current exact-project Submitter authority. -Each download reauthorizes independently; neither a cached list nor a read -reference grants access. Workstream reads the task's locked snapshot, not the -latest guide or drafts. A successor activation alone never changes its documents. -Checker-requested revision preparation can atomically rebase the complete task -and assignment context for the next attempt. Inspect `task context` for its -frozen change summary and acknowledge the exact preparation pair when running -`task submit`; this guide download does not initiate a rebase. Covered-manager -repair is a separate backend operation with no CLI command. Genuine human -Review revision integration remains #554 work. +A current exact-project Submitter grant allows reading the active approved +project guide even when no tasks are ready. The task guide shows the exact +version that governs an eligible ready task or your active assignment, including +a retained version superseded by a new project guide. Each download checks +authority independently and verifies the original. Guide reads never claim tasks +or change revision terms. Use `task status` to see the current terms during revision. The API verifies the complete original against retained ART size/SHA-256 before responding. Missing, corrupt or wrong-namespace originals fail with diff --git a/cli/internal/api/contributor_reads.go b/cli/internal/api/contributor_reads.go index 456d8c06b..37c5b45c8 100644 --- a/cli/internal/api/contributor_reads.go +++ b/cli/internal/api/contributor_reads.go @@ -72,6 +72,34 @@ type ContributorAssignment struct { UpdatedAt string `json:"updated_at"` } +type AssignmentIntake struct { + OperationID string `json:"operation_id"` + Stage string `json:"stage"` + FailureCode *string `json:"failure_code"` + Submission *string `json:"submission_id"` + Feedback []json.RawMessage `json:"pre_submission_results"` + Stalled bool `json:"operationally_stalled"` +} + +type AcceptedAssignmentEvidence struct { + ContributionID string `json:"contribution_id"` + SubmissionID string `json:"submission_id"` + ArtifactHash string `json:"artifact_hash"` + Awards []ContributionAward `json:"awards"` +} + +type AssignmentStatus struct { + Assignment ContributorAssignment `json:"assignment"` + CurrentStatus string `json:"current_status"` + StatusReason *string `json:"status_reason"` + NextAction string `json:"next_action"` + Intake *AssignmentIntake `json:"intake"` + PostFindings []ContributorFinding `json:"post_submission_results"` + FeedbackSubmissionID *string `json:"feedback_submission_id"` + NextCursor *string `json:"next_cursor"` + AcceptedEvidence *AcceptedAssignmentEvidence `json:"accepted_evidence"` +} + type ContributorAssignmentPage struct { Items []ContributorAssignment `json:"items"` Cursor *string `json:"next_cursor"` @@ -310,6 +338,57 @@ func decodeContributorAssignment(raw json.RawMessage) (ContributorAssignment, bo return value, value.Revision == nil || validateRevisionContext(fields["revision"], value.Revision) == nil } +// TaskAssignment reads current status and bounded intake and evaluation feedback for an owned claim. +func (c *Client) TaskAssignment(ctx context.Context, task, assignment string, limit int, cursor *string) (Result[AssignmentStatus], error) { + var result Result[AssignmentStatus] + if !submissionSelector(task) || !submissionSelector(assignment) || + limit < 1 || limit > 100 || (cursor != nil && !validTaskCursor(*cursor)) { + return result, errors.New("task status requires task and assignment UUIDs and a valid feedback page") + } + query := url.Values{"limit": {strconv.Itoa(limit)}} + if cursor != nil { + query.Set("cursor", *cursor) + } + path := "/api/v1/tasks/" + canonicalUUID(task) + "/assignments/" + canonicalUUID(assignment) + raw, err := c.request(ctx, http.MethodGet, path, query.Encode(), nil) + if err != nil { + return result, err + } + var value AssignmentStatus + fields, err := contextObject(raw, &value, []string{"assignment", "current_status", "next_action", "post_submission_results"}, nil) + if err != nil || !requiredNullable(fields, "status_reason", "intake", "feedback_submission_id", "next_cursor", "accepted_evidence") || + !c.safeMutationResponse(raw) || !validOptionalID(value.FeedbackSubmissionID) || + !oneOf(value.CurrentStatus, append(append([]string{}, taskStatuses...), "closed", "rejected")...) || + !oneOf(value.NextAction, "submit", "awaiting_intake", "awaiting_evaluation", "revise", "wait_for_processing", "none") || + len(value.PostFindings) > limit || !validateContributorFindings(fields["post_submission_results"], value.PostFindings) || + (value.NextCursor != nil && (!validTaskCursor(*value.NextCursor) || len(value.PostFindings) == 0)) { + return result, &Failure{Code: "invalid_api_response"} + } + row, ok := decodeContributorAssignment(fields["assignment"]) + if !ok || !sameUUID(row.TaskID, task) || !sameUUID(row.AssignmentID, assignment) || + (value.FeedbackSubmissionID != nil && (row.LatestSubmission == nil || + !sameUUID(*value.FeedbackSubmissionID, row.LatestSubmission.SubmissionID))) { + return result, &Failure{Code: "invalid_api_response"} + } + value.Assignment = row + if intake := value.Intake; intake != nil { + part, err := contextObject(fields["intake"], intake, []string{"operation_id", "stage", "pre_submission_results", "operationally_stalled"}, nil) + if err != nil || !requiredNullable(part, "failure_code", "submission_id") || !validUUID(intake.OperationID) || + !validOptionalID(intake.Submission) || intake.Feedback == nil || !validPreSubmissionResults(intake.Feedback, false) { + return result, &Failure{Code: "invalid_api_response"} + } + } + if accepted := value.AcceptedEvidence; accepted != nil { + if _, err := contextObject(fields["accepted_evidence"], accepted, []string{"contribution_id", "submission_id", "artifact_hash", "awards"}, nil); err != nil || + value.CurrentStatus != "accepted" || !validUUID(accepted.ContributionID) || + row.LatestSubmission == nil || !sameUUID(accepted.SubmissionID, row.LatestSubmission.SubmissionID) || + !contextPolicyDigest.MatchString(accepted.ArtifactHash) || accepted.Awards == nil { + return result, &Failure{Code: "invalid_api_response"} + } + } + return Result[AssignmentStatus]{Raw: raw, Value: value}, nil +} + // MyAssignments lists the caller's claims in projects where it holds a Submitter grant. func (c *Client) MyAssignments(ctx context.Context, q PageQuery) (Result[ContributorAssignmentPage], error) { var result Result[ContributorAssignmentPage] diff --git a/cli/internal/api/manager_history.go b/cli/internal/api/manager_history.go index abd452f48..4549a25f5 100644 --- a/cli/internal/api/manager_history.go +++ b/cli/internal/api/manager_history.go @@ -63,10 +63,10 @@ func validOptionalHash(value *string) bool { func decodeManagementSubmission(raw json.RawMessage, task, submission string) (ManagementSubmission, error) { var value ManagementSubmission bad := &Failure{Code: "invalid_api_response"} - baseRequired := []string{"id", "task_id", "version", "status", "summary", "submitted_at", "finding_counts", "evidence_items"} + baseRequired := []string{"id", "task_id", "version", "status", "submitted_at", "finding_counts", "evidence_items"} required := append(append([]string{}, baseRequired...), managementSubmissionFields[:13]...) fields, err := contextObject(raw, &value, required, nil) - if err != nil || !requiredNullable(fields, "status_reason", "decided_at", "locked_at", "supersedes_submission_id") || + if err != nil || !requiredNullable(fields, "status_reason", "decided_at", "locked_at", "supersedes_submission_id", "summary", "feedback") || !requiredNullable(fields, "locked_guide_source_snapshot_id", "locked_guide_source_snapshot_hash", "locked_effective_project_submission_artifact_policy_id", "locked_effective_project_submission_artifact_policy_hash", "locked_pre_submit_checker_policy_id", "locked_pre_submit_checker_bundle_hash") { diff --git a/cli/internal/api/submission.go b/cli/internal/api/submission.go index 217643c1f..5a7678e52 100644 --- a/cli/internal/api/submission.go +++ b/cli/internal/api/submission.go @@ -9,7 +9,6 @@ import ( "net/http" "net/url" "os" - "regexp" "strings" "time" ) @@ -18,22 +17,13 @@ import ( // Project limits may enforce a smaller allowance. const MaxSubmissionZipBytes = 500 * 1024 * 1024 -// SubmissionPacket is the exact metadata for one source submission. -// ART's current public header boundary requires ASCII; no client normalization. -type SubmissionPacket struct { - Assignment string `json:"assignment_id"` - Predecessor *string `json:"predecessor_submission_id,omitempty"` - Summary *string `json:"summary,omitempty"` - Attestation *string `json:"contributor_attestation,omitempty"` +// SubmissionInput carries the contributor's exact assignment and optional project feedback. +type SubmissionInput struct { + Assignment string + Feedback *string } -// RevisionAcknowledgement binds the current governed revision context. -type RevisionAcknowledgement struct { - PreparationID string - PreparationSHA256 string -} - -var revisionPreparationDigest = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) +const MaxSubmissionFeedbackBytes = 4096 type SubmissionReceipt struct { OperationID string `json:"operation_id"` @@ -49,22 +39,20 @@ type SubmissionReceipt struct { func submissionSelector(value string) bool { return len(value) <= 100 && validUUID(value) } -func (p SubmissionPacket) validate(task string) error { - if !submissionSelector(task) || !submissionSelector(p.Assignment) || - (p.Predecessor != nil && !submissionSelector(*p.Predecessor)) { - return errors.New("task, assignment and predecessor must be UUIDs") +func (p SubmissionInput) validate(task string) error { + if !submissionSelector(task) || !submissionSelector(p.Assignment) { + return errors.New("task and assignment must be UUIDs") } - for _, text := range []*string{p.Summary, p.Attestation} { - if text == nil { - continue - } - if len(*text) > 64*1024 || strings.TrimSpace(*text) != *text { - return errors.New("packet text must fit 64KiB without header-edge whitespace") - } - for _, value := range []byte(*text) { - if value < 32 || value > 126 { - return errors.New("packet text must be printable ASCII for the public submission API") - } + if p.Feedback == nil { + return nil + } + text := *p.Feedback + if len(text) > MaxSubmissionFeedbackBytes || strings.TrimSpace(text) != text { + return errors.New("feedback accepts at most 4096 bytes without leading or trailing whitespace") + } + for _, value := range []byte(text) { + if value < 32 || value > 126 { + return errors.New("feedback must be printable ASCII") } } return nil @@ -73,28 +61,20 @@ func (p SubmissionPacket) validate(task string) error { func submissionFailure(err error) error { var failure *Failure if errors.As(err, &failure) && failure.OutcomeUnknown { - failure.RecoveryHint = "Observe the submission operation using the same actor and idempotency key, or explicitly replay the same task, assignment, ZIP bytes, packet and revision acknowledgement; do not create a new key while the outcome is unknown" + failure.RecoveryHint = "Observe the submission operation using the same actor and idempotency key, or explicitly replay the same task, assignment, ZIP bytes and feedback; do not create a new key while the outcome is unknown" } return err } // SubmitSubmission streams one regular ZIP once and returns its committed acceptance snapshot. -func (c *Client) SubmitSubmission(ctx context.Context, task, key string, packet SubmissionPacket, acknowledgement *RevisionAcknowledgement, source *os.File) (Result[SubmissionReceipt], error) { +func (c *Client) SubmitSubmission(ctx context.Context, task, key string, input SubmissionInput, source *os.File) (Result[SubmissionReceipt], error) { var result Result[SubmissionReceipt] - if err := packet.validate(task); err != nil { + if err := input.validate(task); err != nil { return result, err } if !submissionSelector(key) || source == nil { return result, errors.New("submission requires a caller UUID key and a regular ZIP file") } - if packet.Predecessor == nil { - if acknowledgement != nil { - return result, errors.New("initial submission cannot acknowledge a revision") - } - } else if acknowledgement == nil || !submissionSelector(acknowledgement.PreparationID) || - !revisionPreparationDigest.MatchString(acknowledgement.PreparationSHA256) { - return result, errors.New("revision preparation requires its exact preparation ID and sha256 digest") - } initial, err := source.Stat() if err != nil || !initial.Mode().IsRegular() || initial.Size() <= 0 || initial.Size() > MaxSubmissionZipBytes { return result, errors.New("ZIP must be a nonempty regular file of at most 500MiB") @@ -103,18 +83,9 @@ func (c *Client) SubmitSubmission(ctx context.Context, task, key string, packet if err != nil { return result, err } - headers := http.Header{"X-Task-Assignment-Id": {packet.Assignment}} - for name, value := range map[string]*string{ - "X-Submission-Summary": packet.Summary, "X-Contributor-Attestation": packet.Attestation, - "X-Predecessor-Submission-Id": packet.Predecessor, - } { - if value != nil { - headers.Set(name, *value) - } - } - if acknowledgement != nil { - headers.Set("X-Revision-Preparation-Id", acknowledgement.PreparationID) - headers.Set("X-Revision-Preparation-Sha256", acknowledgement.PreparationSHA256) + headers := http.Header{"X-Task-Assignment-Id": {input.Assignment}} + if input.Feedback != nil { + headers.Set("X-Submission-Feedback", *input.Feedback) } response, err := c.openBodyRequest(ctx, c.guideHTTP, http.MethodPost, "/api/v1/tasks/"+url.PathEscape(task)+"/submissions", "", @@ -150,7 +121,7 @@ func (c *Client) SubmitSubmission(ctx context.Context, task, key string, packet _, decodeErr := contextObject(raw, &value, []string{"operation_id", "task_id", "assignment_id", "status", "accepted_at", "task_status_at_acceptance", "processing_stage_at_acceptance", "replayed", "pre_submission_results"}, nil) _, acceptedErr := time.Parse(time.RFC3339Nano, value.AcceptedAt) if typeErr != nil || kind != "application/json" || decodeErr != nil || acceptedErr != nil || - !validUUID(value.OperationID) || !sameUUID(value.TaskID, task) || !sameUUID(value.AssignmentID, packet.Assignment) || + !validUUID(value.OperationID) || !sameUUID(value.TaskID, task) || !sameUUID(value.AssignmentID, input.Assignment) || value.Status != "accepted" || value.TaskStatus != "evaluation_pending" || value.ProcessingStage != "finalization_pending" || !c.safeMutationResponse(raw) || value.Feedback == nil || !validPreSubmissionResults(value.Feedback, true) || (response.Header.Get("Content-Encoding") != "" && response.Header.Get("Content-Encoding") != "identity") { diff --git a/cli/internal/api/submission_reads.go b/cli/internal/api/submission_reads.go index 0903c56a9..efa8075f3 100644 --- a/cli/internal/api/submission_reads.go +++ b/cli/internal/api/submission_reads.go @@ -46,7 +46,8 @@ type SubmissionHistory struct { Version *big.Int `json:"version"` Status string `json:"status"` StatusReason *string `json:"status_reason"` - Summary string `json:"summary"` + Summary *string `json:"summary"` + Feedback *string `json:"feedback"` SubmittedAt string `json:"submitted_at"` DecidedAt *string `json:"decided_at"` FindingCounts SubmissionFindingCounts `json:"finding_counts"` @@ -97,8 +98,8 @@ type SubmissionFindingsResult struct { func decodeSubmission(raw json.RawMessage, task, submission string) (SubmissionHistory, error) { var value SubmissionHistory bad := &Failure{Code: "invalid_api_response"} - fields, err := contextObject(raw, &value, []string{"id", "task_id", "version", "status", "summary", "submitted_at", "finding_counts", "evidence_items"}, nil) - if err != nil || !requiredNullable(fields, "status_reason", "decided_at", "locked_at", "supersedes_submission_id") || + fields, err := contextObject(raw, &value, []string{"id", "task_id", "version", "status", "submitted_at", "finding_counts", "evidence_items"}, nil) + if err != nil || !requiredNullable(fields, "status_reason", "decided_at", "locked_at", "supersedes_submission_id", "summary", "feedback") || !validUUID(value.ID) || !validUUID(value.Task) || (task != "" && !sameUUID(value.Task, task)) || (submission != "" && !sameUUID(value.ID, submission)) || value.Version == nil || value.Version.Sign() <= 0 || !validSubmissionOutcome(value) || !validFindingCounts(fields["finding_counts"], &value.FindingCounts) || @@ -225,33 +226,40 @@ func decodeSubmissionChecker(raw json.RawMessage, submission, run string) (Submi default: return value, bad } - var items []json.RawMessage - if json.Unmarshal(fields["results"], &items) != nil { + if !validateContributorFindings(fields["results"], value.Results) { return value, bad } + return value, nil +} + +func validateContributorFindings(raw json.RawMessage, findings []ContributorFinding) bool { + var items []json.RawMessage + if json.Unmarshal(raw, &items) != nil || items == nil || len(items) != len(findings) { + return false + } seen := map[[16]byte]bool{} for i, item := range items { - f := &value.Results[i] + f := &findings[i] fields, err := contextObject(item, f, []string{"id", "checker_name", "status", "severity"}, nil) id, ok := uuidIdentity(f.ID) if err != nil || !requiredNullable(fields, "check_id", "path", "line", "worker_message", "worker_suggested_fix") || !ok || seen[id] || f.Checker == "" || (f.CheckID != nil && *f.CheckID == "") || (f.Path != nil && *f.Path == "") || (f.Line != nil && (f.Path == nil || *f.Line < 1)) { - return value, bad + return false } switch f.Status { case "passed", "warning", "failed", "coverage_incomplete": default: - return value, bad + return false } switch f.Severity { case "info", "low", "medium", "high", "critical", "error": default: - return value, bad + return false } seen[id] = true } - return value, nil + return true } func (c *Client) SubmissionFindings(ctx context.Context, submission, run string, limit int, cursor *string) (Result[SubmissionFindingsResult], error) { diff --git a/cli/internal/api/submission_test.go b/cli/internal/api/submission_test.go index dd40add9a..fcc62bf6d 100644 --- a/cli/internal/api/submission_test.go +++ b/cli/internal/api/submission_test.go @@ -31,7 +31,7 @@ func TestSubmitSubmissionRejectsOversizedCompressedZipBeforeHTTP(t *testing.T) { t.Fatal(err) } _, err = client.SubmitSubmission(context.Background(), testTask, testRun, - SubmissionPacket{Assignment: testSubmission}, nil, file) + SubmissionInput{Assignment: testSubmission}, file) if err == nil || err.Error() != "ZIP must be a nonempty regular file of at most 500MiB" { t.Fatalf("expected local compressed ZIP limit rejection, got %v", err) } diff --git a/cli/internal/api/task_context.go b/cli/internal/api/task_context.go index c23665199..0408bb7a2 100644 --- a/cli/internal/api/task_context.go +++ b/cli/internal/api/task_context.go @@ -58,11 +58,9 @@ type SubmissionRequirements struct { GuideVersion string `json:"guide_version"` PolicySchemaVersion *string `json:"policy_schema_version"` MergeAlgorithmVersion *string `json:"merge_algorithm_version"` - RequiredPacketFields []string `json:"required_packet_fields"` RequiredArtifacts []ArtifactRequirement `json:"required_artifacts"` RequiredEvidence []EvidenceRequirement `json:"required_evidence"` ForbiddenArtifacts []ForbiddenArtifact `json:"forbidden_artifacts"` - AttestationTerms []string `json:"attestation_terms"` ManifestRequired bool `json:"manifest_required"` ArtifactHashRequired bool `json:"artifact_hash_required"` ArtifactHashAlgorithm string `json:"artifact_hash_algorithm"` @@ -174,7 +172,9 @@ func (c *Client) WorkContext(ctx context.Context, selector string) (Result[WorkC return result, &Failure{Code: "invalid_api_response"} } } - if err := validateGuideDocuments(fields["guide_documents"], value.GuideDocuments, value.Task.TaskID, value.Lifecycle.AssignedToCurrentActor); err != nil { + if err := validateGuideDocuments(fields["guide_documents"], value.GuideDocuments, func(documentID string) string { + return guideDocumentPath(value.Task.TaskID, documentID) + }); err != nil { return result, &Failure{Code: "invalid_api_response"} } if rawRevision, present := fields["revision_context"]; present { @@ -206,10 +206,10 @@ func decodeSubmissionRequirements(raw json.RawMessage, task, project string) (Su var value SubmissionRequirements bad := &Failure{Code: "invalid_api_response"} fields, err := contextObject(raw, &value, []string{ - "task_id", "project_id", "guide_version", "required_packet_fields", "required_artifacts", "required_evidence", - "forbidden_artifacts", "attestation_terms", "manifest_required", "artifact_hash_required", "artifact_hash_algorithm", + "task_id", "project_id", "guide_version", "required_artifacts", "required_evidence", + "forbidden_artifacts", "manifest_required", "artifact_hash_required", "artifact_hash_algorithm", "allowed_storage_schemes", "storage_reference_rules", "packaging", - }, []string{"required_packet_fields", "attestation_terms", "allowed_storage_schemes"}) + }, []string{"allowed_storage_schemes"}) if err != nil || !sameUUID(value.TaskID, task) || !validUUID(value.ProjectID) || (project != "" && !sameUUID(value.ProjectID, project)) || strings.TrimSpace(value.GuideVersion) == "" || value.ArtifactHashAlgorithm != "sha256" { diff --git a/cli/internal/api/task_guide.go b/cli/internal/api/task_guide.go index 440412899..76ce0d7af 100644 --- a/cli/internal/api/task_guide.go +++ b/cli/internal/api/task_guide.go @@ -53,9 +53,9 @@ func (d TaskGuideDocument) Extension() string { } } -func validateGuideDocuments(raw json.RawMessage, documents []TaskGuideDocument, taskID string, assigned bool) error { +func validateGuideDocuments(raw json.RawMessage, documents []TaskGuideDocument, readPath func(string) string) error { var entries []json.RawMessage - if jsonv2.Unmarshal(raw, &entries) != nil || entries == nil || len(entries) != len(documents) || (!assigned && len(entries) != 0) { + if jsonv2.Unmarshal(raw, &entries) != nil || entries == nil || len(entries) != len(documents) { return errors.New("invalid guide documents") } seen := make(map[string]bool) @@ -65,7 +65,7 @@ func validateGuideDocuments(raw json.RawMessage, documents []TaskGuideDocument, if _, err := contextObject(entry, &d, []string{"document_id", "order", "label", "media_type", "byte_count", "sha256", "read_reference"}, nil); err != nil || !validUUID(d.DocumentID) || seen[canonicalUUID(d.DocumentID)] || d.Order <= previous || strings.TrimSpace(d.Label) == "" || d.Extension() == "" || d.ByteCount <= 0 || d.ByteCount > MaxGuideDocumentBytes || - !contextPolicyDigest.MatchString(d.SHA256) || d.ReadReference != guideDocumentPath(taskID, d.DocumentID) { + !contextPolicyDigest.MatchString(d.SHA256) || d.ReadReference != readPath(d.DocumentID) { return errors.New("invalid guide document") } seen[canonicalUUID(d.DocumentID)] = true @@ -77,12 +77,19 @@ func validateGuideDocuments(raw json.RawMessage, documents []TaskGuideDocument, // DownloadGuideDocument always constructs the same-origin path itself. The // caller writes privately and publishes only after this verifies all bytes. func (c *Client) DownloadGuideDocument(ctx context.Context, taskID string, document TaskGuideDocument, target io.Writer) error { - if !validUUID(taskID) || !validUUID(document.DocumentID) || document.Extension() == "" || + if !validUUID(taskID) { + return &Failure{Code: "invalid_api_response"} + } + return c.downloadVerifiedGuideDocument(ctx, guideDocumentPath(taskID, document.DocumentID), document, target) +} + +func (c *Client) downloadVerifiedGuideDocument(ctx context.Context, path string, document TaskGuideDocument, target io.Writer) error { + if !validUUID(document.DocumentID) || document.Extension() == "" || document.ByteCount <= 0 || document.ByteCount > MaxGuideDocumentBytes || !contextPolicyDigest.MatchString(document.SHA256) || - document.ReadReference != guideDocumentPath(taskID, document.DocumentID) { + document.ReadReference != path { return &Failure{Code: "invalid_api_response"} } - response, err := c.openRequest(ctx, c.guideHTTP, http.MethodGet, guideDocumentPath(taskID, document.DocumentID), "", nil, "", document.MediaType) + response, err := c.openRequest(ctx, c.guideHTTP, http.MethodGet, path, "", nil, "", document.MediaType) if err != nil { return err } @@ -109,3 +116,47 @@ func (c *Client) DownloadGuideDocument(ctx context.Context, taskID string, docum } return nil } + +// ApprovedContributorGuide is the active approved project guide's original manifest. +type ApprovedContributorGuide struct { + ProjectID string `json:"project_id"` + GuideID string `json:"guide_id"` + Version string `json:"version"` + Documents []TaskGuideDocument `json:"documents"` +} + +func contributorGuidePath(projectID string) string { + return "/api/v1/projects/" + canonicalUUID(projectID) + "/contributor-guide" +} + +func projectGuideDocumentPath(projectID, guideID, documentID string) string { + return contributorGuidePath(projectID) + "/" + canonicalUUID(guideID) + "/documents/" + canonicalUUID(documentID) + "/content" +} + +func (c *Client) ContributorGuide(ctx context.Context, projectID string) (Result[ApprovedContributorGuide], error) { + var result Result[ApprovedContributorGuide] + if !validUUID(projectID) { + return result, errors.New("project ID must be a UUID") + } + raw, err := c.request(ctx, http.MethodGet, contributorGuidePath(projectID), "", nil) + if err != nil { + return result, err + } + var guide ApprovedContributorGuide + fields, err := contextObject(raw, &guide, []string{"project_id", "guide_id", "version", "documents"}, nil) + if err != nil || !sameUUID(guide.ProjectID, projectID) || !validUUID(guide.GuideID) || + strings.TrimSpace(guide.Version) == "" || !c.safeMutationResponse(raw) || + validateGuideDocuments(fields["documents"], guide.Documents, func(documentID string) string { + return projectGuideDocumentPath(projectID, guide.GuideID, documentID) + }) != nil { + return result, &Failure{Code: "invalid_api_response"} + } + return Result[ApprovedContributorGuide]{Raw: raw, Value: guide}, nil +} + +func (c *Client) DownloadContributorGuideDocument(ctx context.Context, projectID, guideID string, document TaskGuideDocument, target io.Writer) error { + if !validUUID(projectID) || !validUUID(guideID) { + return &Failure{Code: "invalid_api_response"} + } + return c.downloadVerifiedGuideDocument(ctx, projectGuideDocumentPath(projectID, guideID, document.DocumentID), document, target) +} diff --git a/cli/internal/command/guide_reads.go b/cli/internal/command/guide_reads.go index bcb784d73..103a6b58f 100644 --- a/cli/internal/command/guide_reads.go +++ b/cli/internal/command/guide_reads.go @@ -13,6 +13,44 @@ import ( // addGuideReads adds the Project Manager's read-only guide commands. func addGuideReads(guide *cobra.Command, client func() (*api.Client, error), output *string, stdout io.Writer) { + var approvedDirectory string + approved := &cobra.Command{ + Use: "approved PROJECT_ID", Short: "Read or download the active approved contributor guide", Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + apiClient, err := client() + if err != nil { + return err + } + result, err := apiClient.ContributorGuide(cmd.Context(), args[0]) + if err != nil { + return err + } + current := result.Value + if approvedDirectory != "" { + root, err := download.OpenRoot(approvedDirectory) + if err != nil { + return err + } + defer root.Close() + for _, document := range current.Documents { + if err := downloadGuide(root, document, func(target io.Writer) error { + return apiClient.DownloadContributorGuideDocument(cmd.Context(), current.ProjectID, current.GuideID, document, target) + }); err != nil { + return err + } + } + } + if *output == "json" { + return writeSafeJSON(stdout, result.Raw) + } + return writeTaskContextFields(stdout, []contextField{ + {"Guide version", current.Version}, {"Guide documents", current.Documents}, + }) + }, + } + approved.Flags().StringVar(&approvedDirectory, "download", "", "Download verified originals to an existing directory") + guide.AddCommand(approved) + var page pageFlags list := &cobra.Command{ Use: "list PROJECT_ID", Short: "List the project's guide versions and their stored status", Args: cobra.ExactArgs(1), diff --git a/cli/internal/command/submission.go b/cli/internal/command/submission.go index 47c400c67..9a5f6e2e5 100644 --- a/cli/internal/command/submission.go +++ b/cli/internal/command/submission.go @@ -11,41 +11,16 @@ import ( func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client, error), output *string, stdout io.Writer) { { - var assignment, predecessor, summary, attestation, path, key string - var revisionPreparationID, revisionPreparationSHA256 string - name, description := "submit", "Upload one ZIP for initial checks and durable evaluation acceptance" - cmd := &cobra.Command{Use: name + " TASK_ID", Short: description, Args: cobra.ExactArgs(1)} + var assignment, feedback, path, key string + cmd := &cobra.Command{Use: "submit TASK_ID", Short: "Submit one ZIP for initial work or revision", Args: cobra.ExactArgs(1)} cmd.Flags().StringVar(&assignment, "assignment", "", "Required active task-assignment UUID") - cmd.Flags().StringVar(&predecessor, "predecessor", "", "Predecessor Submission UUID when required by the task") - cmd.Flags().StringVar(&summary, "summary", "", "Exact printable ASCII packet summary; preserve for same-key replay") - cmd.Flags().StringVar(&attestation, "attestation", "", "Exact printable ASCII contributor attestation") + cmd.Flags().StringVar(&feedback, "feedback", "", "Optional project feedback, up to 4096 printable ASCII bytes without leading or trailing whitespace") cmd.Flags().StringVar(&path, "file", "", "Required regular ZIP; keep unchanged for explicit replay") cmd.Flags().StringVar(&key, "idempotency-key", "", "Required caller-owned UUID; never retried automatically") - cmd.Flags().StringVar(&revisionPreparationID, "revision-preparation-id", "", "Exact preparation UUID from task context; required with --predecessor") - cmd.Flags().StringVar(&revisionPreparationSHA256, "revision-preparation-sha256", "", "Exact preparation digest from task context; required with --predecessor") cmd.RunE = func(cmd *cobra.Command, args []string) error { - var acknowledgement *api.RevisionAcknowledgement - { - hasID := cmd.Flags().Changed("revision-preparation-id") - hasSHA := cmd.Flags().Changed("revision-preparation-sha256") - if cmd.Flags().Changed("predecessor") != (hasID && hasSHA) || hasID != hasSHA { - return commandError{"invalid_arguments", "revision preparation ID and sha256 are both required with --predecessor and forbidden for initial submission"} - } - if hasID { - acknowledgement = &api.RevisionAcknowledgement{ - PreparationID: revisionPreparationID, PreparationSHA256: revisionPreparationSHA256, - } - } - } - packet := api.SubmissionPacket{Assignment: assignment} - if cmd.Flags().Changed("predecessor") { - packet.Predecessor = &predecessor - } - if cmd.Flags().Changed("summary") { - packet.Summary = &summary - } - if cmd.Flags().Changed("attestation") { - packet.Attestation = &attestation + input := api.SubmissionInput{Assignment: assignment} + if cmd.Flags().Changed("feedback") { + input.Feedback = &feedback } c, err := client() if err != nil { @@ -61,7 +36,7 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client return bad } defer file.Close() - result, err := c.SubmitSubmission(cmd.Context(), args[0], key, packet, acknowledgement, file) + result, err := c.SubmitSubmission(cmd.Context(), args[0], key, input, file) if err != nil { return err } @@ -80,12 +55,57 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client return err } } - _, err = fmt.Fprintln(stdout, "Initial checks passed. Evaluation is pending; use the operation ID or the same idempotency key to observe progress.") + _, err = fmt.Fprintln(stdout, "Initial checks passed. Evaluation is pending. Use workstream task status with this task and assignment to see the outcome.") return err } task.AddCommand(cmd) } + { + var assignment string + var page pageFlags + status := &cobra.Command{Use: "status TASK_ID", Short: "Read your assignment status and feedback", Args: cobra.ExactArgs(1)} + status.Flags().StringVar(&assignment, "assignment", "", "Required task-assignment UUID") + page.bind(status, 25) + status.RunE = func(cmd *cobra.Command, args []string) error { + if !api.ValidUUID(assignment) { + return commandError{"invalid_arguments", "--assignment must be a UUID"} + } + transport, err := client() + if err != nil { + return err + } + query := page.query(cmd) + result, err := transport.TaskAssignment(cmd.Context(), args[0], assignment, query.Limit, query.Cursor) + if err != nil || *output == "json" { + return jsonOrError(stdout, result.Raw, err) + } + value := result.Value + fields := []contextField{ + {"Assignment", value.Assignment.AssignmentID}, {"Status", value.CurrentStatus}, + {"Reason", optional(value.StatusReason)}, {"Next action", value.NextAction}, + {"Terms", value.Assignment.Compensation}, {"Revision", value.Assignment.Revision}, + {"Latest submitted attempt", value.Assignment.LatestSubmission}, + } + if value.Intake != nil { + fields = append(fields, contextField{"Intake stage", value.Intake.Stage}, + contextField{"Intake feedback", api.IntakeFeedbackLines(value.Intake.Feedback)}) + } + if len(value.PostFindings) != 0 { + fields = append(fields, contextField{"Feedback for submission", optional(value.FeedbackSubmissionID)}, + contextField{"Evaluation findings", value.PostFindings}) + } + if value.AcceptedEvidence != nil { + fields = append(fields, contextField{"Accepted evidence", value.AcceptedEvidence}) + } + if value.NextCursor != nil { + fields = append(fields, contextField{"Next feedback cursor", *value.NextCursor}) + } + return writeTaskContextFields(stdout, fields) + } + task.AddCommand(status) + } + { var operation, key string progress := &cobra.Command{Use: "submission-operation TASK_ID", Short: "Inspect one submission operation without resubmitting", Args: cobra.ExactArgs(1)} diff --git a/cli/internal/command/task_context.go b/cli/internal/command/task_context.go index e4fd1fdbc..f5d135bf2 100644 --- a/cli/internal/command/task_context.go +++ b/cli/internal/command/task_context.go @@ -56,9 +56,9 @@ func addTaskContextReads(task *cobra.Command, client func() (*api.Client, error) return writeTaskContextFields(stdout, []contextField{ {"Task", value.TaskID}, {"Project", value.ProjectID}, {"Guide version", value.GuideVersion}, {"Policy schema version", value.PolicySchemaVersion}, {"Merge algorithm version", value.MergeAlgorithmVersion}, - {"Required packet fields", value.RequiredPacketFields}, {"Required artifacts", value.RequiredArtifacts}, + {"Required artifacts", value.RequiredArtifacts}, {"Required evidence", value.RequiredEvidence}, {"Forbidden artifacts", value.ForbiddenArtifacts}, - {"Attestation terms", value.AttestationTerms}, {"Manifest required", value.ManifestRequired}, + {"Manifest required", value.ManifestRequired}, {"Artifact hash required", value.ArtifactHashRequired}, {"Artifact hash algorithm", value.ArtifactHashAlgorithm}, {"Allowed storage schemes", value.AllowedStorageSchemes}, {"Storage reference rules", value.StorageReferenceRules}, {"Maximum file size bytes", value.MaximumFileSizeBytes}, {"Maximum package size bytes", value.MaximumPackageSizeBytes}, diff --git a/cli/internal/command/task_guide.go b/cli/internal/command/task_guide.go index f0f03a331..4f8f7207c 100644 --- a/cli/internal/command/task_guide.go +++ b/cli/internal/command/task_guide.go @@ -12,7 +12,7 @@ import ( func addTaskGuide(task *cobra.Command, client func() (*api.Client, error), output *string, stdout io.Writer) { var directory string cmd := &cobra.Command{ - Use: "guide TASK_ID", Short: "List or download the assigned task's locked guide originals", Args: cobra.ExactArgs(1), + Use: "guide TASK_ID", Short: "Read or download the task's exact guide before or after claiming", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { apiClient, err := client() if err != nil { @@ -22,9 +22,6 @@ func addTaskGuide(task *cobra.Command, client func() (*api.Client, error), outpu if err != nil { return err } - if !result.Value.Lifecycle.AssignedToCurrentActor { - return &api.Failure{Code: "task_assignment_required"} - } if directory != "" { root, err := download.OpenRoot(directory) if err != nil { @@ -32,33 +29,40 @@ func addTaskGuide(task *cobra.Command, client func() (*api.Client, error), outpu } defer root.Close() for _, document := range result.Value.GuideDocuments { - if err := downloadGuide(cmd, apiClient, root, result.Value.Task.TaskID, document); err != nil { + if err := downloadGuide(root, document, func(target io.Writer) error { + return apiClient.DownloadGuideDocument(cmd.Context(), result.Value.Task.TaskID, document, target) + }); err != nil { return err } } } if *output == "json" { - body, err := json.Marshal(result.Value.GuideDocuments) + body, err := json.Marshal(api.ApprovedContributorGuide{ + ProjectID: result.Value.Project.ID, GuideID: result.Value.Guide.ID, + Version: result.Value.Guide.Version, Documents: result.Value.GuideDocuments, + }) if err != nil { return err } - return writeJSON(stdout, body) + return writeSafeJSON(stdout, body) } - return writeTaskContextFields(stdout, []contextField{{"Guide documents", result.Value.GuideDocuments}}) + return writeTaskContextFields(stdout, []contextField{ + {"Guide version", result.Value.Guide.Version}, {"Guide documents", result.Value.GuideDocuments}, + }) }, } cmd.Flags().StringVar(&directory, "download", "", "Download verified originals into an existing directory (never overwrite)") task.AddCommand(cmd) } -func downloadGuide(cmd *cobra.Command, client *api.Client, root *download.Root, taskID string, document api.TaskGuideDocument) error { +func downloadGuide(root *download.Root, document api.TaskGuideDocument, write func(io.Writer) error) error { name := document.Filename() stage, err := root.Stage(name) if err != nil { return err } defer stage.Abort() - if err := client.DownloadGuideDocument(cmd.Context(), taskID, document, stage); err != nil { + if err := write(stage); err != nil { return err } if err := stage.Seal(); err != nil { diff --git a/cli/internal/tui/details.go b/cli/internal/tui/details.go index 3dd484c71..12b0ce591 100644 --- a/cli/internal/tui/details.go +++ b/cli/internal/tui/details.go @@ -201,14 +201,6 @@ func (m *Model) contextText() string { func (m *Model) intakeText() string { v := m.intake d := detailWriter{m: m} - d.heading("Required packet fields") - if len(v.RequiredPacketFields) == 0 { - d.note("None listed.") - } else { - for _, field := range v.RequiredPacketFields { - d.line("Field", field) - } - } d.heading("Required artifacts") if len(v.RequiredArtifacts) == 0 { d.note("None listed.") @@ -241,13 +233,6 @@ func (m *Model) intakeText() string { d.optionalProse("Suggested fix", a.WorkerFacingFix) d.optional("Severity", a.Severity) } - d.heading("Attestations") - if len(v.AttestationTerms) == 0 { - d.note("None listed.") - } - for _, term := range v.AttestationTerms { - d.line("Attestation term", term) - } d.heading("Package and storage constraints") d.line("Manifest required", fmt.Sprint(v.ManifestRequired)) d.line("Artifact hash required", fmt.Sprint(v.ArtifactHashRequired)) @@ -345,11 +330,9 @@ func (m *Model) guideText() string { func (m *Model) submissionText() string { v := m.submission d := detailWriter{m: m} - title := v.Summary - if strings.TrimSpace(title) == "" { - title = "Submission" - } - d.heading(m.prose(title)) + d.heading("Submission") + d.optionalProse("Historical summary", v.Summary) + d.optionalProse("Project feedback", v.Feedback) d.heading("Stored outcome") d.line("Stored outcome", v.Status) d.optional("Reason", v.StatusReason) diff --git a/cli/internal/tui/details_layout_test.go b/cli/internal/tui/details_layout_test.go index 414ba277f..5464d126a 100644 --- a/cli/internal/tui/details_layout_test.go +++ b/cli/internal/tui/details_layout_test.go @@ -154,18 +154,17 @@ func TestIntakeDisplaysConstraintsWithoutValidationClaim(t *testing.T) { desc, reason, fix := "Expected artifact", "Secrets forbidden", "Remove credentials" value := api.SubmissionRequirements{ TaskID: taskID, ProjectID: projectID, GuideVersion: "locked-v1", - RequiredPacketFields: []string{"summary"}, - RequiredArtifacts: []api.ArtifactRequirement{{Key: "source", Path: "src/**", Required: true, HashRequired: true, Description: &desc}}, - RequiredEvidence: []api.EvidenceRequirement{{Key: "test", Label: "Tests", Required: true, HashRequired: false}}, - ForbiddenArtifacts: []api.ForbiddenArtifact{{Pattern: "*.key", Reason: &reason, WorkerFacingFix: &fix}}, - AttestationTerms: []string{"original work"}, ManifestRequired: true, ArtifactHashRequired: true, + RequiredArtifacts: []api.ArtifactRequirement{{Key: "source", Path: "src/**", Required: true, HashRequired: true, Description: &desc}}, + RequiredEvidence: []api.EvidenceRequirement{{Key: "test", Label: "Tests", Required: true, HashRequired: false}}, + ForbiddenArtifacts: []api.ForbiddenArtifact{{Pattern: "*.key", Reason: &reason, WorkerFacingFix: &fix}}, + ManifestRequired: true, ArtifactHashRequired: true, ArtifactHashAlgorithm: "sha256", AllowedStorageSchemes: []string{"s3"}, StorageReferenceRules: api.StorageReferenceRules{AllowedURIPrefixes: []string{"s3://bucket/"}}, MaximumFileSizeBytes: big.NewInt(4294967297), Packaging: api.PackagingRequirements{PackageRequired: true, AllowedPackageFormats: []string{"zip"}}, } m := &Model{intake: &value, section: 2, noColor: true} rendered := m.detailText() - orderOf(t, rendered, "Required packet fields", "Field: summary", "Required artifacts", "Artifact: source", "Required evidence", "Evidence: test", "Forbidden artifacts", "Forbidden pattern: *.key", "Attestations", "Attestation term: original work", "Package and storage constraints", "Maximum file bytes: 4294967297", "References") + orderOf(t, rendered, "Required artifacts", "Artifact: source", "Required evidence", "Evidence: test", "Forbidden artifacts", "Forbidden pattern: *.key", "Package and storage constraints", "Maximum file bytes: 4294967297", "References") for _, want := range []string{"Hash required: true", "Path (text only): src/**", "Reason\nSecrets forbidden", "Suggested fix\nRemove credentials", "Package required: true", "Allowed package formats: zip", "Policy schema version"} { if want == "Policy schema version" { if strings.Contains(rendered, want) { @@ -180,8 +179,8 @@ func TestIntakeDisplaysConstraintsWithoutValidationClaim(t *testing.T) { } func TestSubmissionAndFindingsSeparateOutcomeFromEvidence(t *testing.T) { - reason := "coverage_incomplete" - submission := api.SubmissionHistory{ID: submissionID, Task: taskID, Status: "needs_revision", StatusReason: &reason, Summary: "My full summary", Version: big.NewInt(12), FindingCounts: api.SubmissionFindingCounts{Blocking: big.NewInt(2), Warning: big.NewInt(1)}, Evidence: []api.SubmissionEvidence{{ID: actorID, Type: "artifact", Label: "source", Size: big.NewInt(9007199254740993)}}} + reason, summary := "coverage_incomplete", "My full summary" + submission := api.SubmissionHistory{ID: submissionID, Task: taskID, Status: "needs_revision", StatusReason: &reason, Summary: &summary, Version: big.NewInt(12), FindingCounts: api.SubmissionFindingCounts{Blocking: big.NewInt(2), Warning: big.NewInt(1)}, Evidence: []api.SubmissionEvidence{{ID: actorID, Type: "artifact", Label: "source", Size: big.NewInt(9007199254740993)}}} m := &Model{submission: &submission, tab: submissions, noColor: true} rendered := m.detailText() orderOf(t, rendered, "My full summary", "Stored outcome: needs_revision", "Reason: coverage_incomplete", "Blocking findings: 2", "Version: 12", "Evidence label: source", "Size: 9007199254740993", "References", "Submission: "+submissionID) diff --git a/cli/internal/tui/model_test.go b/cli/internal/tui/model_test.go index 1534a82b8..8f1a1b5d2 100644 --- a/cli/internal/tui/model_test.go +++ b/cli/internal/tui/model_test.go @@ -92,7 +92,8 @@ func (f *fakeClient) SubmissionRequirements(ctx context.Context, id string) (api } func (f *fakeClient) Submission(context.Context, string) (api.Result[api.SubmissionHistory], error) { f.calls = append(f.calls, "submission") - return api.Result[api.SubmissionHistory]{Value: api.SubmissionHistory{ID: submissionID, Task: taskID, Status: "review_pending", Summary: "Stored summary"}}, nil + summary := "Stored summary" + return api.Result[api.SubmissionHistory]{Value: api.SubmissionHistory{ID: submissionID, Task: taskID, Status: "review_pending", Summary: &summary}}, nil } func (f *fakeClient) SubmissionFindings(ctx context.Context, submission, run string, limit int, cursor *string) (api.Result[api.SubmissionFindingsResult], error) { f.calls = append(f.calls, "findings") diff --git a/cli/internal/tui/render_evidence_test.go b/cli/internal/tui/render_evidence_test.go index 9d4efcc2c..832cb15a4 100644 --- a/cli/internal/tui/render_evidence_test.go +++ b/cli/internal/tui/render_evidence_test.go @@ -67,10 +67,8 @@ func renderFixture(t *testing.T, screen string) (*Model, *fakeClient) { m.section = 2 description := "One row per conclusion, with source section, page and evidence strength." m.intake = &api.SubmissionRequirements{TaskID: taskID, ProjectID: projectID, GuideVersion: "research-guide", - RequiredPacketFields: []string{"summary", "attestation"}, RequiredArtifacts: []api.ArtifactRequirement{{Key: "matrix", Path: "evidence-matrix.csv", Required: true, HashRequired: true, Description: &description}, {Key: "methodology", Path: "methodology.md", Required: true, HashRequired: true}}, RequiredEvidence: []api.EvidenceRequirement{{Key: "sources", Label: "Source citation index", Required: true, HashRequired: true}}, - AttestationTerms: []string{"I have distinguished supplied evidence from my own interpretation."}, MaximumPackageSizeBytes: big.NewInt(10485760), Packaging: api.PackagingRequirements{PackageRequired: true, AllowedPackageFormats: []string{"zip"}}} return m, f } @@ -81,7 +79,8 @@ func renderFixture(t *testing.T, screen string) (*Model, *fakeClient) { return m, f } m.tab, m.section = submissions, 0 - m.submission = &api.SubmissionHistory{ID: submissionID, Task: taskID, Version: big.NewInt(1), Status: "review_pending", Summary: "Evidence matrix and methodology for the coastal flood warning study", SubmittedAt: "2026-10-26T13:58:02Z", FindingCounts: api.SubmissionFindingCounts{Blocking: big.NewInt(0), Warning: big.NewInt(1), CoverageIncomplete: big.NewInt(0)}, Evidence: []api.SubmissionEvidence{{ID: findingID, Type: "document", Label: "Methodology and citation matrix", Size: big.NewInt(18520)}}} + summary := "Evidence matrix and methodology for the coastal flood warning study" + m.submission = &api.SubmissionHistory{ID: submissionID, Task: taskID, Version: big.NewInt(1), Status: "review_pending", Summary: &summary, SubmittedAt: "2026-10-26T13:58:02Z", FindingCounts: api.SubmissionFindingCounts{Blocking: big.NewInt(0), Warning: big.NewInt(1), CoverageIncomplete: big.NewInt(0)}, Evidence: []api.SubmissionEvidence{{ID: findingID, Type: "document", Label: "Methodology and citation matrix", Size: big.NewInt(18520)}}} if screen == "submission" { return m, f } diff --git a/cli/tests/integration/test_manager_task_evidence_public_api.py b/cli/tests/integration/test_manager_task_evidence_public_api.py index 31ce57c25..1b275532b 100644 --- a/cli/tests/integration/test_manager_task_evidence_public_api.py +++ b/cli/tests/integration/test_manager_task_evidence_public_api.py @@ -124,10 +124,8 @@ async def call(*args, status=200): str(archive), "--idempotency-key", str(uuid4()), - "--summary", + "--feedback", "Completed the required project work and included evidence.", - "--attestation", - " ".join(h.policy["attestation_terms"]), ) assert receipt["status"] == "accepted" and receipt["replayed"] is False assert len(runtime_calls) == 1 and not runtime_errors, runtime_errors diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py index 0cb52b8ed..071bfcf97 100644 --- a/cli/tests/integration/test_submission_http.py +++ b/cli/tests/integration/test_submission_http.py @@ -14,15 +14,14 @@ OPERATION = "018f0ebc-7966-7e8d-bc4d-1cae1e000013" SUBMISSION = "018f0ebc-7966-7e8d-bc4d-1cae1e000015" RUN = "018f0ebc-7966-7e8d-bc4d-1cae1e000016" -REVISION_PREPARATION = "018f0ebc-7966-7e8d-bc4d-1cae1e000017" -REVISION_DIGEST = "sha256:" + "a" * 64 HISTORY = { "id": SUBMISSION, "task_id": TASK, "version": 1, "status": "evaluation_pending", "status_reason": None, - "summary": "Work complete", + "summary": None, + "feedback": "Work complete", "submitted_at": "2026-10-14T10:00:00Z", "decided_at": None, "finding_counts": {"blocking": 0, "warning": 0, "coverage_incomplete": 0}, @@ -81,11 +80,6 @@ def submit_args(path): "failure_code": None, "finding_count": 0, }, - { - "source": "workstream_default", - "status": "warning", - "warning_code": "submission_summary_missing", - }, { "source": "project_external_checker", "requirement_id": "quality", @@ -124,22 +118,22 @@ def respond(response, value, status=200): response.update(status=status, body=json.dumps(value, ensure_ascii=False).encode()) -def test_explicit_submit_replay_preserves_packet_and_bytes(cli, tmp_path): +def test_explicit_submit_replay_preserves_feedback_and_bytes(cli, tmp_path): path = tmp_path / "submission.zip" path.write_bytes(b"PK\x03\x04exact-archive") - packet = ("--summary", "Completed work", "--attestation", "") + feedback = ("--feedback", "Completed work") with http_fixture() as (origin, response, requests): for replayed in (False, True): respond(response, acceptance(replayed), 202) - result = cli(origin, TOKEN, *submit_args(path), *packet) + result = cli(origin, TOKEN, *submit_args(path), *feedback) assert result.returncode == 0, result.stderr assert json.loads(result.stdout) == acceptance(replayed) assert len(requests) == 2 # Only caller-requested replay. assert response["raw_commands"] == [path.read_bytes()] * 2 for headers in response["request_headers"]: assert headers["X-Task-Assignment-Id"] == ASSIGNMENT - assert headers["X-Submission-Summary"] == "Completed work" - assert headers["X-Contributor-Attestation"] == "" + assert headers["X-Submission-Feedback"] == "Completed work" + assert "X-Contributor-Attestation" not in headers assert headers["Idempotency-Key"] == KEY assert headers["Content-Type"] == "application/zip" assert ( @@ -159,7 +153,6 @@ def test_accepted_submission_shows_nonblocking_intake_feedback(cli, tmp_path): receipt_line = result.stdout.splitlines()[0] assert receipt_line.startswith("Submission accepted for evaluation") assert "pre_submission_results" not in receipt_line - assert "Intake feedback: warning submission_summary_missing" in result.stdout assert ( "Intake feedback: coverage_incomplete coverage.files results/vendor.bin: " "One file was not evaluated." in result.stdout @@ -172,9 +165,9 @@ def test_accepted_submission_shows_nonblocking_intake_feedback(cli, tmp_path): "finding_count": 1, } error_finding = copy.deepcopy(INTAKE_FEEDBACK) - error_finding[2]["findings"][0]["level"] = "error" + error_finding[-1]["findings"][0]["level"] = "error" failed_member = copy.deepcopy(INTAKE_FEEDBACK) - failed_member[2]["status"] = "failed" + failed_member[-1]["status"] = "failed" missing = acceptance() missing.pop("pre_submission_results") for invalid in ( @@ -191,58 +184,27 @@ def test_accepted_submission_shows_nonblocking_intake_feedback(cli, tmp_path): assert len(requests) == 6 -def test_revision_submit_requires_and_replays_exact_acknowledgement_headers( - cli, tmp_path -): +def test_submit_uses_the_same_inputs_for_revision(cli, tmp_path): path = tmp_path / "revision.zip" path.write_bytes(b"PK\x03\x04revision") - pair = ( - "--revision-preparation-id", - REVISION_PREPARATION, - "--revision-preparation-sha256", - REVISION_DIGEST, - ) with http_fixture() as (origin, response, requests): - for args in ( - ("--predecessor", SUBMISSION), - pair, - ( - "--predecessor", - SUBMISSION, - "--revision-preparation-id", - REVISION_PREPARATION, - ), - ( - "--predecessor", - SUBMISSION, - "--revision-preparation-sha256", - REVISION_DIGEST, - ), - ("--predecessor", SUBMISSION, *pair[:-1], "sha256:" + "A" * 64), - ): - assert_failure( - cli(origin, TOKEN, *submit_args(path), *args), "invalid_arguments", 2 - ) + for flag in ("--predecessor", "--revision-preparation-id", "--revision-preparation-sha256", + "--summary", "--attestation"): + assert_failure(cli(origin, TOKEN, *submit_args(path), flag, SUBMISSION), "invalid_arguments", 2) assert requests == [] respond(response, acceptance(), 202) - for _ in range(2): - result = cli( - origin, TOKEN, *submit_args(path), "--predecessor", SUBMISSION, *pair - ) - assert result.returncode == 0, result.stderr - assert len(requests) == 2 - for headers in response["request_headers"]: - assert headers["X-Predecessor-Submission-Id"] == SUBMISSION - assert headers["X-Revision-Preparation-Id"] == REVISION_PREPARATION - assert headers["X-Revision-Preparation-Sha256"] == REVISION_DIGEST + result = cli(origin, TOKEN, *submit_args(path)) + assert result.returncode == 0, result.stderr + assert len(requests) == 1 + assert "X-Submission-Feedback" not in response["request_headers"][0] -def test_submit_rejects_untransportable_packet_before_request(cli, tmp_path): +def test_submit_rejects_untransportable_feedback_before_request(cli, tmp_path): path = tmp_path / "submission.zip" path.write_bytes(b"zip") with http_fixture() as (origin, _, requests): - for summary in ("é", "line\nbreak", " leading", "trailing ", "x" * 65537): - result = cli(origin, TOKEN, *submit_args(path), "--summary", summary) + for feedback in ("é", "line\nbreak", " leading", "trailing ", "x" * 4097): + result = cli(origin, TOKEN, *submit_args(path), "--feedback", feedback) assert_failure(result, "invalid_arguments", 2) assert requests == [] diff --git a/cli/tests/integration/test_submission_public_api.py b/cli/tests/integration/test_submission_public_api.py index e3276f597..26ef7e062 100644 --- a/cli/tests/integration/test_submission_public_api.py +++ b/cli/tests/integration/test_submission_public_api.py @@ -223,7 +223,7 @@ async def _inspect(call, f, receipt, payload): detail = await call("submission", "show", submission_id) assert detail == history["items"][0] assert ( - detail["summary"] + detail["feedback"] == "Completed the required project work and included evidence." ) [run] = (await call("submission", "findings", submission_id))["items"] @@ -357,7 +357,7 @@ async def test_cli_public_submission_progress_replay_history_and_suspension( str(archive), "--idempotency-key", key, - "--summary", + "--feedback", "Completed the required project work and included evidence.", ) async with socket_api(app) as origin: @@ -395,8 +395,14 @@ async def call(*args, denied=None, token=None): ) assert await call(*submit) == dict(receipt, replayed=True) changed = list(submit) - changed[changed.index("--summary") + 1] += " changed" + changed[changed.index("--feedback") + 1] += " changed" await call(*changed, denied=409) + status_args = ("task", "status", str(f.task), "--assignment", str(f.assignment)) + status = await call(*status_args) + assert status["current_status"] == "evaluation_pending" + assert status["next_action"] == "awaiting_evaluation" + assert status["assignment"]["latest_submission"] is None + assert status["intake"]["pre_submission_results"] == receipt["pre_submission_results"] by_key = await call( "task", "submission-operation", str(f.task), "--idempotency-key", key ) @@ -427,6 +433,7 @@ async def call(*args, denied=None, token=None): commands = ( submit, ("submission", "show", submission_id), + status_args, ("submission", "findings", submission_id), ("task", "submissions", str(f.task)), ( diff --git a/cli/tests/integration/test_task_context_http.py b/cli/tests/integration/test_task_context_http.py index 973e9d312..bc58e2135 100644 --- a/cli/tests/integration/test_task_context_http.py +++ b/cli/tests/integration/test_task_context_http.py @@ -83,7 +83,6 @@ "guide_version": "guide-1", "policy_schema_version": "artifact-policy", "merge_algorithm_version": None, - "required_packet_fields": ["summary", "worker_attestation"], "required_artifacts": [ { "key": "answer", @@ -110,7 +109,6 @@ "severity": "error", } ], - "attestation_terms": ["This is my work."], "manifest_required": False, "artifact_hash_required": True, "artifact_hash_algorithm": "sha256", @@ -249,8 +247,6 @@ def test_context_reads_preserve_wire_complete_output_and_optional_fields(cli): "required_artifacts", "required_evidence", "forbidden_artifacts", - "required_packet_fields", - "attestation_terms", "allowed_storage_schemes", ): requirements[key] = [] @@ -496,8 +492,6 @@ def test_requirements_reject_missing_null_or_substituted_facts(cli): ): cases.append(REQUIREMENTS | {key: wrong}) for key in ( - "required_packet_fields", - "attestation_terms", "allowed_storage_schemes", ): cases.append(REQUIREMENTS | {key: [None]}) @@ -587,7 +581,7 @@ def test_context_reads_use_current_failure_bounds_without_partial_output(cli): # content succeeds; excess still fails without partial output. oversized["project"]["name"] = "x" * (2 * 1024 * 1024) else: - oversized["attestation_terms"] = ["x" * 65536] + oversized["required_artifacts"][0]["path"] = "x" * 65536 response["body"] = json.dumps(oversized).encode() assert_failure( cli(origin, TOKEN, "task", command, TASK, "-o", "json"), diff --git a/cli/tests/integration/test_task_guide_http.py b/cli/tests/integration/test_task_guide_http.py index e16731d16..4c1f46caf 100644 --- a/cli/tests/integration/test_task_guide_http.py +++ b/cli/tests/integration/test_task_guide_http.py @@ -98,7 +98,7 @@ def log_message(self, *_): def test_assigned_guide_list_and_verified_private_download(cli, tmp_path): with guide_http() as (origin, state, requests): listed = cli(origin, TOKEN, "task", "guide", TASK, "-o", "json") - assert listed.returncode == 0 and json.loads(listed.stdout) == [DOCUMENT], ( + assert listed.returncode == 0 and json.loads(listed.stdout)["documents"] == [DOCUMENT], ( listed.stderr ) terminal = cli(origin, TOKEN, "task", "guide", TASK) @@ -243,7 +243,7 @@ def test_full_document_list_uses_bounded_context_not_small_page_limit(cli): assert len(json.dumps(state["context"]).encode()) > 64 * 1024 result = cli(origin, TOKEN, "task", "guide", TASK, "-o", "json") assert result.returncode == 0, result.stderr - assert json.loads(result.stdout) == documents and len(requests) == 1 + assert json.loads(result.stdout)["documents"] == documents and len(requests) == 1 @pytest.mark.parametrize("damage", ("hash", "short", "long", "content_type")) @@ -325,34 +325,25 @@ def test_canonical_duplicate_document_ids_are_rejected(cli): assert len(requests) == 1 -def test_assignment_and_symlink_targets_fail_without_download(cli, tmp_path): +def test_ready_guide_can_download_before_claim_and_refuses_symlink(cli, tmp_path): with guide_http() as (origin, state, requests): - state["context"]["lifecycle"]["assigned_to_current_actor"] = False - state["context"]["guide_documents"] = [] - denied = cli( - origin, - TOKEN, - "task", - "guide", - TASK, - "--download", - str(tmp_path), - "-o", - "json", - ) - assert ( - denied.returncode != 0 - and json.loads(denied.stderr)["error"]["code"] == "task_assignment_required" + state["context"]["task"]["status"] = "ready" + state["context"]["lifecycle"] = {"assigned_to_current_actor": False, "next_actions": ["claim"]} + first_directory = tmp_path / "valid" + first_directory.mkdir() + result = cli( + origin, TOKEN, "task", "guide", TASK, "--download", str(first_directory), "-o", "json", ) - assert len(requests) == 1 - state["context"]["lifecycle"]["assigned_to_current_actor"] = True - state["context"]["guide_documents"] = [deepcopy(DOCUMENT)] + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout)["documents"] == [DOCUMENT] + assert (first_directory / f"{ACTOR}.pdf").read_bytes() == ORIGINAL + assert len(requests) == 2 outside = tmp_path / "outside" outside.write_bytes(b"UNTOUCHED") (tmp_path / f"{ACTOR}.pdf").symlink_to(outside) denied = cli(origin, TOKEN, "task", "guide", TASK, "--download", str(tmp_path)) assert denied.returncode != 0 and outside.read_bytes() == b"UNTOUCHED" - assert len(requests) == 2 + assert len(requests) == 3 @pytest.mark.parametrize("status", (401, 404, 302, 503)) diff --git a/cli/tests/integration/test_task_guide_public_api.py b/cli/tests/integration/test_task_guide_public_api.py index 8d6975e35..12abf210c 100644 --- a/cli/tests/integration/test_task_guide_public_api.py +++ b/cli/tests/integration/test_task_guide_public_api.py @@ -276,7 +276,9 @@ async def test_installed_cli_reads_and_downloads_real_assigned_originals( "json", ) assert result.returncode == 0, result.stderr - documents = json.loads(result.stdout) + manifest = json.loads(result.stdout) + assert manifest["version"] == "v1" + documents = manifest["documents"] assert len(documents) == len(guide_world.originals) == 2 for document, original, extension in zip( documents, guide_world.originals, ("md", "pdf"), strict=True @@ -288,6 +290,20 @@ async def test_installed_cli_reads_and_downloads_real_assigned_originals( "task_examples" not in result.stdout and "PRIVATE SETUP EXAMPLE" not in result.stdout ) + project_guides = tmp_path / "project-guide" + project_guides.mkdir() + approved = await asyncio.to_thread( + cli, origin, "task-token", "project", "guide", "approved", + guide_world.project["id"], "--download", str(project_guides), "-o", "json", + ) + assert approved.returncode == 0, approved.stderr + approved_manifest = json.loads(approved.stdout) + assert approved_manifest["guide_id"] == manifest["guide_id"] + for document, original, extension in zip( + approved_manifest["documents"], guide_world.originals, ("md", "pdf"), strict=True, + ): + assert (project_guides / f"{document['document_id']}.{extension}").read_bytes() == original + set_dev_actor( monkeypatch, roles="project_manager", subject="project-manager-subject" ) diff --git a/docs/operations_revision_replay.md b/docs/operations_revision_replay.md index fc86d6c8f..859e69d41 100644 --- a/docs/operations_revision_replay.md +++ b/docs/operations_revision_replay.md @@ -70,14 +70,13 @@ ReviewFinding response or resolution. ## Resubmission And Checks -A human-Review Submission N+1 acknowledges the exact preparation head/digest, -links its immediate predecessor, and stamps the complete frozen context. A -checker-remediation Submission N+1 binds the exact final needs-revision CheckerRun -and its preparation, without a ReviewFinding response. Public ZIP preparation -requires `X-Revision-Preparation-Id` and `X-Revision-Preparation-Sha256`; the ready -admission retains that acknowledgement for final creation. Initial intake omits -both. Both paths rerun the normal finalization and checker -spine. Only a current successful `allow_review` may create a new queue entry. +The contributor uses the ordinary raw-ZIP submission command on the same task +and assignment with a new idempotency key. TASK selects the immediate +predecessor and governing revision context and rechecks eligibility before PRE +and intake acceptance. For checker remediation, the selected context binds +the predecessor's exact current needs-revision CheckerRun. Accepted custody +retains those facts for finalization and evaluation. Only a current successful +`allow_review` may create a new review queue entry. Human Review return initially prefers the reviewer who requested revision. The distinct corrected checker path enters open routing. Expiry, diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 89433eba5..228bbf28b 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -685,7 +685,7 @@ cannot be reused as post-submission review-gate evidence. See the | Project Guide source custody | **Live foundation** | Guide creation declares documents and task examples; public document upload; immutable internal metadata snapshots; draft guide and review/revision policy writes with fresh-authorized exact replay of original receipts; exact run-scoped setup reads and assigned-task locked-original reads; S3-backed originals and isolated agent document inspection; exact document generation through separate manager approvals and public exact-authorized CP07 activation; Project Manager guide list, guide detail, activation readiness dry run and verified original read-back (PILOT-READ-3); the CLI exposes existing administrative active-chain and retained sufficiency/artifact-policy reads, keyed human sufficiency writes, and separate manual artifact-policy draft create/update with backend-owned policy decisions | Hosted original upload/read-back, task examples and Celery inference are proven. The current guide has independent human attachments, separate approvals and activation; earlier guide approvals remain retained history. Complete reader/isolation and contribution-journey scenarios; manual drafts are not compiled activation proposals and deployed CLI remains separate | | Unified Project Guide compilation | **Live setup and manager proposal operations** | Upload commits custody only; an explicit exact-project PM request selects assistance (`/setup`) or provider-free uploaded manager rules (`/requirements/compile`) and dispatches one immutable attempt through Celery; complete result and crash/recovery custody; distinct pre/post proposals; typed per-requirement classification and checker specifications; deterministic sufficiency and submission-artifact-policy projections; immutable authorized setup finalization; public exact manager review, pre-submit approval and manual correction dispatch; automatic deterministic post-policy derivation, public complete policy read, separate approval and shared correction custody. Neutral read/search tools support statically registered OpenAI Agents SDK and OmniCoreAgent adapters in mutually exclusive inference images, while provider-free `manager_authored` compiles a manager-uploaded rules document with no inference or provider resources ([runtime initiative](../.commitrail/initiatives/WS-AGENT-001/OVERVIEW.md), [manager-authored record](../.commitrail/changes/manager-authored-guide-runtime.md)). Inference attempts snapshot an exact immutable model profile and use the shared project-funded proxy; fixed document-tool limits must fit that profile and provider credentials remain outside the setup process. PR #697 supplies a source-sufficient proposal even without registered implementations; retained prior results keep exact hashes and reads and cannot execute through a compatibility path. Exact Omni SDK, mutually exclusive release-image, parser-isolation and real-MinIO proofs pass. Both inference adapters pass the same original-guide public API, durable Celery, real-parser and MinIO path; the Omni run stopped at a warning-ready manager draft with no bindings, approval or activation. The Terminal Systems handoff has project-owned PRE and POST implementations. POST uses the shared bounded model session, isolated trial capability and approved revision material. PR #697 removes registry, image and runtime choices from model input and output; human-selected phase attachments are validated at approval. Initial setup receives assigned guide documents and task examples only, apart from trusted system instructions. Explicit corrections additionally receive the PM's bounded written feedback, without prior proposals or image selections. Project semantics remain outside the generic Rust service. The [checker implementation](../pilots/terminal_systems/checkers/README.md) separates rule, service-image, storage and trial qualification. | Historical source-only setup and explicit PM correction are live-proven. Hosted Garden uploads prove no implicit request or model effects; explicit provider-free compilation/replay, separate approvals/activation, task claim and real PRE failure/replay are proven without a Submission. Optional inference-request deployment and committed-request recovery remain separate; the live Garden v3 drill separately verified the open PR current head and trusted CI under an explicit zero-GitHub-approval configuration, then accepted one Submission with an earned 100 FLOW award. Earlier guides and tasks retain their original locks. Controlled composition alone establishes no live GitHub or review fact. [Garden evidence](reports/garden-hosted-drill-2026-11-06.md). Guide 28 suggestions were independently mapped by the manager to one external PRE and POST image; separate approvals/activation led to the small task's accepted v2 and public contribution. Earlier guide 25/26 evidence remains retained. [Current checkpoint](reports/terminal-systems-hosted-drill-2026-10-27.md). | | Contribution policy administration | **Public Finance policy workflow; binding administration internal** | Internal Finance Authority adapter-binding lifecycle; public ContributionPolicy discovery/read/create/update/publish/retire with exact Finance Authority and recoverable draft selectors, and a Finance list of every version (PILOT-READ-3); immutable operation and event history; internal exact selected-version validation; CP07 binding with live exact-project manager authority of the selected published version to the active guide generation | The bounded local drill and hosted unpaid-policy publication/read-back passed. Remaining policy branches and complete contribution effects need qualification; publication alone creates no contribution | -| Task readiness and claim | **Foundation with grant-backed manager and contributor commands** | Task records, assignments and locked work context; guide-bound ContributionPolicyVersion locked before `READY` and copied to TaskAssignment; detached project/guide display; public project-scoped ready, management and operational queues with distinct current grant authority and signed bounded live pagination, with typed task status and manager filters by status, assignee, native import batch and update time (PILOT-READ-2); contributor cross-project own-assignment, attempt and summary reads under current Submitter grants (PILOT-READ-2); Project Manager project-wide attempt, claim, summary and import-batch reads (PILOT-READ-3); public contributor/management detail with exact project and assignment authority; separate current live work-context projections with exact receipt-selected review/revision/ContributionPolicy identities and no obsolete economic fields; explicit management/operational/audit locked-context projections using one historical resolver, with separate public manager, system-Operator and Audit Authority access; immutable contributor/management requirements using one historical translator, with public exact Contributor and Manager authority; the CLI exposes the three exact manager requirements/context reads separately from contributor commands (WS-CLI-001-27); bounded public Audit Authority lifecycle evidence with atomic project/task scoping and exact transition references; separate CLI audit commands consume those two existing Audit Authority GETs with explicit continuation; public manager create/screen/release use exact covered Project Manager authority, atomic audit and replay; claim/contributor context use exact-project Submitter grants; assigned context lists documents only and distinct `task.guide.read` verifies locked originals before delivery; separate manager context; durable claim retry receipts with fresh authority and exact assignment checks; hidden exact-assignment invalidation with committed cause verification, delivery fencing, exact fixed-service authority and decision-bound immutable release evidence; atomic authority-loss publication and registered prefork delivery; PILOT-14 exposes both locked contribution types in ready rows and Contributor detail for active exact-project Submitters or Reviewers as unpaid or exact instrument/unit/quantity awards, without Finance binding facts; claim remain Submitter-only | The bounded local journey passed; hosted import, screening, release, immediate claim and exact Claim replay passed for queue recovery. Complete the remaining authority/recovery matrix and contribution journey | +| Task readiness and claim | **Foundation with grant-backed manager and contributor commands** | Task records, assignments and locked work context; guide-bound ContributionPolicyVersion locked before `READY` and copied to TaskAssignment; detached project/guide display; public project-scoped ready, management and operational queues with distinct current grant authority and signed bounded live pagination, with typed task status and manager filters by status, assignee, native import batch and update time (PILOT-READ-2); contributor cross-project own-assignment, attempt and summary reads under current Submitter grants (PILOT-READ-2); Project Manager project-wide attempt, claim, summary and import-batch reads (PILOT-READ-3); public contributor/management detail with exact project and assignment authority; separate current live work-context projections with exact receipt-selected review/revision/ContributionPolicy identities and no obsolete economic fields; explicit management/operational/audit locked-context projections using one historical resolver, with separate public manager, system-Operator and Audit Authority access; immutable contributor/management requirements using one historical translator, with public exact Contributor and Manager authority; the CLI exposes the three exact manager requirements/context reads separately from contributor commands (WS-CLI-001-27); bounded public Audit Authority lifecycle evidence with atomic project/task scoping and exact transition references; separate CLI audit commands consume those two existing Audit Authority GETs with explicit continuation; public manager create/screen/release use exact covered Project Manager authority, atomic audit and replay; claim/contributor context use exact-project Submitter grants; ready and own-assignment context list exact locked originals and `task.guide.read` verifies each download before delivery; separate manager context; durable claim retry receipts with fresh authority and exact assignment checks; hidden exact-assignment invalidation with committed cause verification, delivery fencing, exact fixed-service authority and decision-bound immutable release evidence; atomic authority-loss publication and registered prefork delivery; PILOT-14 exposes both locked contribution types in ready rows and Contributor detail for active exact-project Submitters or Reviewers as unpaid or exact instrument/unit/quantity awards, without Finance binding facts; claim remain Submitter-only | The bounded local journey passed; hosted import, screening, release, immediate claim and exact Claim replay passed for queue recovery. Complete the remaining authority/recovery matrix and contribution journey | | Operator task CLI | **Existing public task operations consumed by the CLI** | The Operator CLI provides separate status-only project pages and exact-project locked-reference reads. Backend Operator authority, assignment consistency, locked lineage and audit remain decisive. Claim starts contributor work atomically; there is no Operator start command. | Native public-API proof is bounded to existing fixtures; hosted/deployed operation, other Operator workflows and published binary remain separate | | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent | | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS | @@ -704,6 +704,13 @@ cannot be reused as post-submission review-gate evidence. See the | Runtime diagnostics | **Implemented foundation; release configuration prepared** | Closed structured logging, explicit API/Celery tracing, bounded metrics, safe correlation and optional typed OTLP export; hosted composition accepts only an optional HTTPS collector origin and keeps exporter outage outside product correctness | Restrict broker publishers and secure log access, encryption and finite deletion; prove actual-service privacy/correlation. Recorded hosted configuration disables export. If an approved collector is enabled, qualify its access, egress, retention and outage behavior; absence is not an outage pass and optional collector deployment is not a first-journey prerequisite | | Frontend and pilot | **Small hosted backend journey proven; operational release checks remain** | The [incident-summary pilot](../pilots/terminal_systems/mvp/README.md) exercised real source-only setup, separate human-selected PRE/POST approvals, guide activation, task creation and immediate claim, PRE rejection without a Submission, verified S3 intake, POST failure and a genuine corrected v2. Passing POST reached shared FinalAcceptance and one submitter ContributionRecord. Contributor/manager exports agree on exact artifact, assignment and locked policy; unpaid policy creates no awards or fabricated review. The [Garden hosted drill](reports/garden-hosted-drill-2026-11-06.md) separately passed an open-PR current-head check through accepted Submission and one 100 FLOW earned award with no Review. | Ordinary final-data database restore and same-Submission infrastructure retry to acceptance passed. Complete final-head verification; keep broader ART/UNKNOWN interruption and isolation limits explicit. Earlier complex benchmark/model failures remain retained and do not block this small project; their grading quality is not certified. Live human review, paid fulfillment and frontend remain deferred. Garden positive-approval and live POST-negative branches remain separate. [Current drill evidence](reports/terminal-systems-hosted-drill-2026-10-27.md). | +The PR #708 contributor reconciliation adds an exact own-assignment status +and feedback read, preclaim approved project and task guide originals, and the +same minimal ZIP command for initial work and revisions. Backend-selected terms +are retained through finalization and can be read before resubmission. +Existing contribution evidence shows earned awards. Hosted qualification and +the separately reviewed sized-award fields remain outside this exposure claim. + ## What Has Been Completed ### Security and platform foundations @@ -1103,9 +1110,9 @@ cannot be reused as post-submission review-gate evidence. See the adds a separate verified-source download through public custody. Evidence export works independently of task origin; neither command family creates a dependency on the other. [PILOT-13 assigned-guide access](../.commitrail/changes/pilot13-assigned-task-guide-documents.md) - lists exact locked originals in assigned contributor context and streams - authorized, fully verified ART bytes. `task guide` lists or safely downloads - them; setup examples remain private. Successor activation does not move a + established locked task originals and verified ART delivery. PR #708 extends + the same reads to ready tasks and adds preclaim approved project originals. + The CLI lists or downloads these guides for eligible Submitters. Successor activation does not move a task's locks; a committed fixable failure prepares the next context and a contributor-visible change summary. Live human decision composition remains later work. Built-binary HTTP diff --git a/docs/spec_submission_execution.md b/docs/spec_submission_execution.md index 6cc28f35c..bbbbc1359 100644 --- a/docs/spec_submission_execution.md +++ b/docs/spec_submission_execution.md @@ -103,7 +103,7 @@ It also tightens project policy cardinality and removes provider-host assumption Preserve: - Flow Identity authentication and Workstream's own authorization decisions. -- Task assignments, locked guides and policy lineage, exact predecessor and revision acknowledgement rules. +- Task assignments, locked guides and policy lineage, server-selected predecessor and governed revision rules. - Canonical manifest representation and existing Workstream default-check semantics. - Existing ART ownership, namespace/readiness checks and verification for other artifact producers. - Existing CHECKERS terminal-result ownership, policy evaluation and governed lifecycle routing. @@ -234,10 +234,7 @@ The old public `POST /tasks/{task_id}/submission-bundle-preparations` and the pu | `Content-Type` | `application/zip`. Reject other media types. | | `Content-Encoding` | Absent or `identity`. Do not transparently transform/compress/decompress the submitted body. | | `Content-Length` | If supplied, valid and within the permitted raw limit; verify actual EOF count equals it. If absent, reserve the permitted maximum and enforce the count while streaming. Reject ambiguous or contradictory framing at the HTTP edge. | -| `X-Submission-Summary` | Optional; omitted means empty string. Preserve current printable-ASCII header semantics, at most 64 KiB, without leading/trailing header whitespace. | -| `X-Contributor-Attestation` | Same encoding/size rules as summary. Omission preserves existing warning behavior. | -| `X-Predecessor-Submission-Id` | Exactly the current predecessor when submitting a governed revision; absent for the initial submission. No client-selected replacement of the predecessor. | -| `X-Revision-Preparation-Id` and `X-Revision-Preparation-Sha256` | Both present or both absent. Required and validated where the existing governed revision contract requires acknowledgement. | +| `X-Submission-Feedback` | Optional project feedback, up to 4096 printable ASCII bytes without leading or trailing whitespace. Preserve the exact supplied text. Eligibility and earning do not depend on feedback. | | Body | Nonempty original ZIP; actual bytes are authoritative. No multipart/form-data parser or base64 transformation at the backend submit boundary. | Reject duplicate occurrences of every selector/packet header rather than accepting one framework-selected value. Treat text exactly as validated; do not trim, normalize or rewrite a packet while hashing it. Clients and edge/header limits must support the published packet limits consistently. A larger Unicode/multipart packet redesign is not part of this change. @@ -281,10 +278,10 @@ Use the existing structured error envelope, correlation/request IDs, sanitizatio | 409 | `submission_operation_in_progress` | Another active operation owns this task, or this exact key is still in an unfinished foreground phase. Return its ID only if authorized. | | 409 | `submission_idempotency_conflict` | Same actor/key with different metadata or a verified different raw body. | | 409 | `submission_operation_terminal` | A pre-seal operation ended without a complete input identity; it cannot be resumed or reused. A new key is required once its task guard is released. | -| 409 | Existing revision/context codes | Preserve revision limit/deadline, predecessor, acknowledgement-context and locked-rule conflict semantics. | +| 409 | Existing revision/context codes | Preserve revision limit/deadline, predecessor, selected-context and locked-rule conflict semantics. | | 413 | `submission_archive_limit_exceeded` | Declared or actual raw ZIP exceeds the permitted ceiling. Stop upload; retain cleanup ownership. | | 415 | `submission_media_type_unsupported` | Unsupported content type or content encoding. | -| 422 | `submission_packet_invalid` | Invalid selectors, packet or revision acknowledgement syntax; preserve more specific existing revision codes. | +| 422 | `submission_packet_invalid` | Invalid task/assignment selectors, feedback or ZIP framing. | | 422 | `pre_submission_checker_failed` | Validated platform/project QC rejection. Include bounded actionable PRE results; `eligible_to_submit=false`; no new Submission. | | 408 | `submission_upload_timeout` | The client upload breached its explicit idle/total upload limit before handoff. No accepted work is implied. | | 429 | `submission_capacity_exceeded` | Admission or quota/rate bound prevents this request from proceeding. Include a finite retry hint where one is known. | @@ -344,7 +341,7 @@ Derive `processing_stage` from this operation's own PRE, Submission, evaluation For a terminal operation, “TASK currently permits new intake” means this reader has current contributor submit authority for this operation's task and original still-active assignment, with compatible current predecessor/revision context and no active-operation guard. Management-only readers and contributors whose assignments have closed receive `inspect_governed_outcome`. Do not recommend a submission merely because the task is eligible for somebody else. -No next-action value bypasses current revision acknowledgement or authorization. Derive it through the TASK read owner, not client guesswork. Preserve existing historical-read concealment: permission to read an old operation does not reveal the reassigned task's current status. A missing/corrupt finalized association is an operational integrity error, not permission to infer progress from another Submission. +No next-action value bypasses current revision eligibility or authorization. Derive it through the TASK read owner, not client guesswork. Preserve existing historical-read concealment: permission to read an old operation does not reveal the reassigned task's current status. A missing/corrupt finalized association is an operational integrity error, not permission to infer progress from another Submission. Extend existing task/work-context reads with its active/pending operation and stage. While a new revision awaits finalization, show the predecessor as historical and the new operation as pending; do not present the previous Submission as the newly submitted work. @@ -354,7 +351,7 @@ Extend existing task/work-context reads with its active/pending operation and st The idempotency namespace is `(actor_profile_id, idempotency_key)`. Store the original identity-link provenance and packet. Token strings and expiry timestamps are not request identity. -Metadata identity includes task, assignment, predecessor, summary, attestation, and revision acknowledgement. Raw identity adds server-observed ZIP SHA-256 and byte count. Canonical hashing uses existing Workstream encoding/domain-separation conventions; there is one explicit schema for this request body, covered by fixtures. +Metadata identity includes task, assignment and exact optional feedback. The server-selected predecessor and revision context are frozen separately. Raw identity adds server-observed ZIP SHA-256 and byte count. Canonical hashing uses existing Workstream encoding/domain-separation conventions; there is one explicit schema for this request body, covered by fixtures. The operation's accepted context is separately pinned. A later replay uses that original context and result; it must not reinterpret the same key using newly selected project rules. @@ -427,7 +424,7 @@ Extend the ART owner with one cohesive `SubmissionIntakeOperation` record. Reuse | Group | Required durable fields/facts | | --- | --- | | Identity | Workstream-generated UUIDv7 operation ID; task/project/assignment/actor/identity-link; caller idempotency key; request/correlation IDs | -| Original command | Exact packet and metadata digest; predecessor; revision acknowledgement; original eligible task status; locked guide/rules/PRE/POST/default identities and resource profile | +| Original command | Exact feedback and metadata digest; server-selected predecessor and revision context; original eligible task status; locked guide/rules/PRE/POST/default identities and resource profile | | Ownership | State; task active pointer relationship; foreground lease ID, generation, expiry; absolute deadlines; created/updated/terminal timestamps | | Source | Provider/namespace identity; generated object key; upload maximum/reservation; provider upload handle where used; immutable completion intent; raw SHA/count at EOF; sealed provider generation; completion/observation times | | PRE | Selected run ID; immutable execution-request digest; validated terminal digest; platform input/manifest/default evidence; selected project result and bounded public projection | @@ -489,7 +486,7 @@ Within one short transaction: 1. Resolve fresh authorization and lock the task. 2. Resolve idempotency or validate new-operation eligibility. -3. Validate active assignment, predecessor/revision acknowledgement, locked policy cardinality and configured provider/profile readiness. +3. Validate the active assignment, select the predecessor and revision context, and verify locked policy cardinality and provider/profile readiness. 4. Reserve upload capacity under existing required quota scopes. 5. Create the operation, generated object key, lease/fence, deadlines and immutable command/context snapshot. 6. Install the task's active-operation pointer. @@ -683,7 +680,7 @@ Keep `workstream.default`, its versioned behavior identity and the following che | `high_confidence_secrets_absent` | Preserve existing approved signature/decision behavior. Public findings expose bounded categories/counts, not detected secret values. | | `submission_changed_for_current_rules` | Under unchanged canonical rules, reject the same raw archive or semantic manifest as the actual predecessor. Preserve the existing changed-rules exception. | -Preserve current summary/attestation warning semantics. Do not silently turn omissions into blocking requirements or alter secret detection as part of moving execution. +Optional project feedback stays outside checker inputs. New attempts have no text-absence warnings. Preserve the canonical text, hashes and warning evidence of retained attempts. Canonical predecessor/rules facts come from Workstream owners, not the uploaded ZIP. The trusted session receives their frozen, authenticated request snapshot. T4 revalidates that snapshot against live task truth before accepting the result. @@ -869,7 +866,7 @@ POST outcomes continue through existing rules: | --- | --- | | Required checks pass; human review required | Enter the existing review-pending path. A passing checker cannot bypass required human review. | | Required checks pass; human review not required | Invoke the existing authorized shared final-acceptance operation. | -| Governed fixable failure | Follow existing needs-revision policy, findings, rebase/acknowledgement and attempt-limit behavior. | +| Governed fixable failure | Follow existing needs-revision policy, findings, server-selected rebase and attempt-limit behavior. | | Governed rejection / exhausted attempts | Follow the existing terminal outcome policy. | | Runtime/provider/infrastructure failure | Retry/hold under existing infrastructure rules; do not consume a contributor revision as though QC failed. | @@ -1193,7 +1190,7 @@ The CLI's submit action uploads once, waits for inline PRE outcome, prints the d Keep local file-source stability checks where needed, safe JSON/terminal output, explicit unknown-outcome recovery and exact input/key replay. Add operation status inspection without implicitly resubmitting or polling an unbounded loop. -Preserve governed **revision preparation/acknowledgement** actions where the existing revision workflow requires them. Removing the old bundle-preparation action does not remove that separate revision rule. +Preserve governed revision preparation and recovery as internal selection and manager operations. Contributors resubmit through the same raw-ZIP command. MCP is an adapter to the same backend action. Its current 64 MiB transfer bound and 120-second timeout are narrower than the backend archive ceiling; update documentation and effective timeout validation honestly. Do not silently raise a base64 JSON/tool transport to 500 MiB or create a second backend upload flow. A larger MCP transport redesign needs an explicit scoped decision; it is not necessary to implement the single backend submission contract. @@ -1268,7 +1265,7 @@ Tests must prove real boundaries. Mocking a method name does not prove bounded m | A32 | Automatic acceptance and human acceptance | Existing atomic FinalAcceptance/ContributionRecord/award facts; no fabricated Review. | | A33 | Migration with retained SHA artifacts and old admissions | Historical evidence remains readable; unsubmitted ready admissions not auto-submitted; no bulk object rewrite/delete. | | A34 | Policy cardinality and setup selection | Missing/multiple PRE or POST selection rejected everywhere; only authorized approved exact images used. | -| A35 | Foreground/client edge and API schema convergence | One mutation across CLI/MCP/backend; removed bundle-preparation path absent from active contract; revision acknowledgement preserved. | +| A35 | Foreground/client edge and API schema convergence | One mutation across CLI/MCP/backend; removed bundle-preparation path absent from active contract; governed revision selection owned by the server. | ### 23.2 Performance and provider evidence diff --git a/mcp_server/README.md b/mcp_server/README.md index 4fe3d751d..889c18605 100644 --- a/mcp_server/README.md +++ b/mcp_server/README.md @@ -238,19 +238,30 @@ Task execution uses separate contributor and manager read tools so the adapter never chooses an authority path on the caller's behalf. Screen, release and claim require typed UUID idempotency keys. Claim atomically assigns and starts a ready task through one request, returning `in_progress` and the started assignment. -Submission creation accepts a bounded Base64 ZIP, decodes it once and forwards the -caller's typed assignment/key and optional submission or revision fields as the -fixed backend headers. The raw-ZIP POST returns a `202` acceptance snapshot with -an operation ID; formal Submission creation and evaluation continue durably. -Use `workstream_submission_operation_get` with `task_id` and exactly one of -`operation_id` or `idempotency_key` for one authorized progress read. Keys are -actor-scoped; management reads can select an operation ID. The tool preserves -nullable fields, PRE feedback and server next-action advice without resubmitting -or polling. Current task status is context, not the historical operation outcome. -Revision preparation ID and digest are both required with a predecessor and -forbidden for initial submission. Workstream owns ZIP validation, pre-submit checks, replay and all task -state changes. A checker rejection is a normal safe tool failure; an unverified -mutation success remains uncertain and is never retried automatically. +Use `workstream_project_contributor_guide_get` to read the approved project guide +before claiming a task. Use its version and document IDs with +`workstream_project_contributor_guide_document_get` to retrieve verified originals. +The contributor task context exposes the locked guide of an eligible ready task +or an active assignment. `workstream_task_guide_document_content_get` retrieves +that task's exact original even if a newer project guide is active. + +`workstream_submission_create` takes `task_id`, `assignment_id`, `zip_base64` +and a caller-supplied UUID `idempotency_key` for both initial work and revisions. +MCP accepts up to 64 MiB of raw ZIP bytes. The CLI ceiling is 500 MiB and project +limits apply to both clients. The optional `feedback` field accepts up to 4096 +printable ASCII bytes without leading or trailing whitespace. Workstream retains +the exact text as project feedback. Workstream selects revision context and terms +internally. + +A raw-ZIP `202` means Workstream admitted the attempt for durable evaluation. +Both successful and rejected tool responses include applicable contributor-safe +PRE findings. Read `workstream_task_assignment_get` with `task_id` and +`assignment_id` for current status, feedback, revision terms and accepted +evidence. Continue larger feedback sets with the returned cursor. +Use `workstream_submission_operation_get` with `task_id` and the operation ID +or original key to recover the precise request outcome. A write with an +uncertain outcome is never retried automatically. Preserve the original task, +assignment, ZIP, feedback and key when explicitly replaying that request. ## Deployment Boundary diff --git a/mcp_server/contracts/authorization_context_get.json b/mcp_server/contracts/authorization_context_get.json index 8e5925c00..82f6c99c4 100644 --- a/mcp_server/contracts/authorization_context_get.json +++ b/mcp_server/contracts/authorization_context_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "e8809457e0535252680c1da3d7a95876261005706b1c597228d8436fc93ef210", + "canonical_sha256": "0318de3e2f9da1577bc922f6bf3570a7ad9f0cb8c441244cdb146c839be6a3dc", "components": { "schemas": { "ActionId": { @@ -186,6 +186,8 @@ "contribution.read_project", "actor.project.list", "actor.assignment.list", + "task.assignment.read", + "project.contributor_guide.read", "actor.submission.list", "actor.work_summary.read", "task.submission_bundle_preparation.list", diff --git a/mcp_server/contracts/management_submission_get.json b/mcp_server/contracts/management_submission_get.json index 0d5475d7b..11855e2f8 100644 --- a/mcp_server/contracts/management_submission_get.json +++ b/mcp_server/contracts/management_submission_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "03c62a94d529600b620173834aa5b75b820b3d09242bd88f3f8a337bfc7825df", + "canonical_sha256": "039cd4bc8efc5da6ebab106346a946de7676ea98d6523b7940b1db56ca060138", "components": { "schemas": { "ApiError": { @@ -113,6 +113,17 @@ "title": "Evidence Items", "type": "array" }, + "feedback": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Feedback" + }, "finding_counts": { "$ref": "#/components/schemas/SubmissionFindingCounts" }, @@ -278,8 +289,16 @@ "type": "string" }, "summary": { - "title": "Summary", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Retained summary on submissions recorded before project feedback.", + "title": "Summary" }, "supersedes_submission_id": { "anyOf": [ @@ -315,6 +334,7 @@ "status", "status_reason", "summary", + "feedback", "submitted_at", "decided_at", "finding_counts", diff --git a/mcp_server/contracts/management_task_submission_requirements_get.json b/mcp_server/contracts/management_task_submission_requirements_get.json index 33c8575cb..95640670a 100644 --- a/mcp_server/contracts/management_task_submission_requirements_get.json +++ b/mcp_server/contracts/management_task_submission_requirements_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "de6a65accd7708dc34045b6a1404830d6ebf506e06e39e3db7d4bb0fd820b71e", + "canonical_sha256": "ee6e14f52238f2544b70c408dd4bfb4b0b6f8dc5ea20e287c88593df63b52850", "components": { "schemas": { "ApiError": { @@ -148,13 +148,6 @@ "title": "Artifact Hash Required", "type": "boolean" }, - "attestation_terms": { - "items": { - "type": "string" - }, - "title": "Attestation Terms", - "type": "array" - }, "forbidden_artifacts": { "items": { "$ref": "#/components/schemas/ForbiddenArtifactRequirement" @@ -259,13 +252,6 @@ "title": "Required Evidence", "type": "array" }, - "required_packet_fields": { - "items": { - "type": "string" - }, - "title": "Required Packet Fields", - "type": "array" - }, "storage_reference_rules": { "$ref": "#/components/schemas/StorageReferenceRules" }, @@ -281,11 +267,9 @@ "guide_version", "policy_schema_version", "merge_algorithm_version", - "required_packet_fields", "required_artifacts", "required_evidence", "forbidden_artifacts", - "attestation_terms", "manifest_required", "artifact_hash_required", "artifact_hash_algorithm", diff --git a/mcp_server/contracts/management_task_submissions_list.json b/mcp_server/contracts/management_task_submissions_list.json index 40d932244..ec00e393f 100644 --- a/mcp_server/contracts/management_task_submissions_list.json +++ b/mcp_server/contracts/management_task_submissions_list.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "248a92cb3e505363559db0865b39df7c18e528007c13344f2e20c867abc68aad", + "canonical_sha256": "fd402a470bcd4cceb6ae5d207279828894759eba80f747d1c8abc41589d34590", "components": { "schemas": { "ApiError": { @@ -113,6 +113,17 @@ "title": "Evidence Items", "type": "array" }, + "feedback": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Feedback" + }, "finding_counts": { "$ref": "#/components/schemas/SubmissionFindingCounts" }, @@ -278,8 +289,16 @@ "type": "string" }, "summary": { - "title": "Summary", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Retained summary on submissions recorded before project feedback.", + "title": "Summary" }, "supersedes_submission_id": { "anyOf": [ @@ -315,6 +334,7 @@ "status", "status_reason", "summary", + "feedback", "submitted_at", "decided_at", "finding_counts", diff --git a/mcp_server/contracts/project_contributor_guide_document_get.json b/mcp_server/contracts/project_contributor_guide_document_get.json new file mode 100644 index 000000000..e3b13ef0f --- /dev/null +++ b/mcp_server/contracts/project_contributor_guide_document_get.json @@ -0,0 +1,375 @@ +{ + "canonical_sha256": "4ca4bad1faeffef7036f12f659077011fdd78fc9ea772c23f376850f423e22a2", + "components": { + "schemas": { + "ApiError": { + "additionalProperties": false, + "description": "Canonical machine-readable API error.", + "properties": { + "code": { + "title": "Code", + "type": "string" + }, + "correlation_id": { + "title": "Correlation Id", + "type": "string" + }, + "details": { + "additionalProperties": true, + "title": "Details", + "type": "object" + }, + "message": { + "title": "Message", + "type": "string" + }, + "retryable": { + "title": "Retryable", + "type": "boolean" + } + }, + "required": [ + "code", + "message", + "details", + "correlation_id", + "retryable" + ], + "title": "ApiError", + "type": "object" + }, + "ApiErrorResponse": { + "additionalProperties": false, + "description": "Canonical error plus additive legacy compatibility fields.", + "properties": { + "detail": { + "anyOf": [ + {}, + { + "type": "null" + } + ], + "title": "Detail" + }, + "error": { + "$ref": "#/components/schemas/ApiError" + } + }, + "required": [ + "error" + ], + "title": "ApiErrorResponse", + "type": "object" + } + } + }, + "operation": { + "description": "Download one exact original of the active approved guide.", + "operationId": "read_contributor_guide_document_api_v1_projects__project_id__contributor_guide__guide_id__documents__document_id__content_get", + "parameters": [ + { + "in": "path", + "name": "project_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Project Id", + "type": "string" + } + }, + { + "in": "path", + "name": "guide_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Guide Id", + "type": "string" + } + }, + { + "in": "path", + "name": "document_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Document Id", + "type": "string" + } + }, + { + "in": "header", + "name": "X-Request-ID", + "required": false, + "schema": { + "format": "uuid", + "maxLength": 36, + "minLength": 36, + "type": "string" + } + }, + { + "in": "header", + "name": "X-Correlation-ID", + "required": false, + "schema": { + "format": "uuid", + "maxLength": 36, + "minLength": 36, + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/pdf": { + "schema": { + "format": "binary", + "type": "string" + } + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "schema": { + "format": "binary", + "type": "string" + } + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "schema": { + "format": "binary", + "type": "string" + } + }, + "text/markdown": { + "schema": { + "format": "binary", + "type": "string" + } + } + }, + "description": "Exact verified uploaded original", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Invalid request.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Authentication failed.", + "headers": { + "WWW-Authenticate": { + "schema": { + "type": "string" + } + }, + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Permission denied.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Not Found", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Unprocessable Entity", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Internal server error.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Service Unavailable", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + } + }, + "security": [ + { + "HTTPBearer": [] + } + ], + "summary": "Read Contributor Guide Document", + "tags": [ + "projects" + ], + "x-workstream-action-id": "project.contributor_guide.read" + }, + "schema_version": 1, + "source": { + "method": "GET", + "openapi_version": "3.1.0", + "path": "/api/v1/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content", + "repository_sha": "c853743b689a46711c13e1d800cdd27ab8230ac2" + } +} diff --git a/mcp_server/contracts/project_contributor_guide_get.json b/mcp_server/contracts/project_contributor_guide_get.json new file mode 100644 index 000000000..cb0d3517e --- /dev/null +++ b/mcp_server/contracts/project_contributor_guide_get.json @@ -0,0 +1,427 @@ +{ + "canonical_sha256": "035ed707c1387ece4a2ede5fe03078f28c9f15cd0b542af8fe8438eb178b3844", + "components": { + "schemas": { + "ApiError": { + "additionalProperties": false, + "description": "Canonical machine-readable API error.", + "properties": { + "code": { + "title": "Code", + "type": "string" + }, + "correlation_id": { + "title": "Correlation Id", + "type": "string" + }, + "details": { + "additionalProperties": true, + "title": "Details", + "type": "object" + }, + "message": { + "title": "Message", + "type": "string" + }, + "retryable": { + "title": "Retryable", + "type": "boolean" + } + }, + "required": [ + "code", + "message", + "details", + "correlation_id", + "retryable" + ], + "title": "ApiError", + "type": "object" + }, + "ApiErrorResponse": { + "additionalProperties": false, + "description": "Canonical error plus additive legacy compatibility fields.", + "properties": { + "detail": { + "anyOf": [ + {}, + { + "type": "null" + } + ], + "title": "Detail" + }, + "error": { + "$ref": "#/components/schemas/ApiError" + } + }, + "required": [ + "error" + ], + "title": "ApiErrorResponse", + "type": "object" + }, + "ApprovedContributorGuide": { + "additionalProperties": false, + "description": "The active guide's version and original documents for Submitters.", + "properties": { + "documents": { + "items": { + "$ref": "#/components/schemas/ContributorGuideDocument" + }, + "maxItems": 100, + "title": "Documents", + "type": "array" + }, + "guide_id": { + "format": "uuid", + "title": "Guide Id", + "type": "string" + }, + "project_id": { + "format": "uuid", + "title": "Project Id", + "type": "string" + }, + "version": { + "title": "Version", + "type": "string" + } + }, + "required": [ + "project_id", + "guide_id", + "version", + "documents" + ], + "title": "ApprovedContributorGuide", + "type": "object" + }, + "ContributorGuideDocument": { + "additionalProperties": false, + "description": "Public original identity and authorized download reference.", + "properties": { + "byte_count": { + "exclusiveMinimum": 0.0, + "title": "Byte Count", + "type": "integer" + }, + "document_id": { + "format": "uuid", + "title": "Document Id", + "type": "string" + }, + "label": { + "title": "Label", + "type": "string" + }, + "media_type": { + "enum": [ + "application/pdf", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "text/markdown" + ], + "title": "Media Type", + "type": "string" + }, + "order": { + "minimum": 0.0, + "title": "Order", + "type": "integer" + }, + "read_reference": { + "title": "Read Reference", + "type": "string" + }, + "sha256": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Sha256", + "type": "string" + } + }, + "required": [ + "document_id", + "label", + "order", + "media_type", + "sha256", + "byte_count", + "read_reference" + ], + "title": "ContributorGuideDocument", + "type": "object" + } + } + }, + "operation": { + "description": "Read the project's active approved contributor guide before claiming a task.", + "operationId": "read_approved_contributor_guide_api_v1_projects__project_id__contributor_guide_get", + "parameters": [ + { + "in": "path", + "name": "project_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Project Id", + "type": "string" + } + }, + { + "in": "header", + "name": "X-Request-ID", + "required": false, + "schema": { + "format": "uuid", + "maxLength": 36, + "minLength": 36, + "type": "string" + } + }, + { + "in": "header", + "name": "X-Correlation-ID", + "required": false, + "schema": { + "format": "uuid", + "maxLength": 36, + "minLength": 36, + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApprovedContributorGuide" + } + } + }, + "description": "Successful Response", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Invalid request.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Authentication failed.", + "headers": { + "WWW-Authenticate": { + "schema": { + "type": "string" + } + }, + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Permission denied.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Not Found", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Unprocessable Entity", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Internal server error.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Service Unavailable", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + } + }, + "security": [ + { + "HTTPBearer": [] + } + ], + "summary": "Read Approved Contributor Guide", + "tags": [ + "projects" + ], + "x-workstream-action-id": "project.contributor_guide.read" + }, + "schema_version": 1, + "source": { + "method": "GET", + "openapi_version": "3.1.0", + "path": "/api/v1/projects/{project_id}/contributor-guide", + "repository_sha": "c853743b689a46711c13e1d800cdd27ab8230ac2" + } +} diff --git a/mcp_server/contracts/submission_create.json b/mcp_server/contracts/submission_create.json index 0b9b4da40..88a018f03 100644 --- a/mcp_server/contracts/submission_create.json +++ b/mcp_server/contracts/submission_create.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "024903204b1e82816bd0b9f9cdfcf3b5336e91d967840a6d411b4bc13aa91d75", + "canonical_sha256": "4b308da1c69b44193386ba0513cd9f41de2b33016c0a898bce65512e58861f63", "components": { "schemas": { "ApiError": { @@ -61,6 +61,223 @@ "title": "ApiErrorResponse", "type": "object" }, + "DefaultIntakeCheck": { + "additionalProperties": false, + "properties": { + "check_id": { + "enum": [ + "archive_safe", + "received_identity_exact", + "high_confidence_secrets_absent", + "submission_changed_for_current_rules" + ], + "title": "Check Id", + "type": "string" + }, + "failure_code": { + "anyOf": [ + { + "enum": [ + "submission_archive_malformed", + "submission_archive_limit_exceeded", + "submission_archive_unsafe_entry", + "submission_archive_collision", + "submission_archive_encrypted", + "high_confidence_secret_detected", + "submission_archive_unchanged", + "submission_manifest_unchanged" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Failure Code" + }, + "finding_count": { + "minimum": 0.0, + "title": "Finding Count", + "type": "integer" + }, + "source": { + "const": "workstream_default", + "title": "Source", + "type": "string" + }, + "status": { + "enum": [ + "passed", + "failed", + "not_run" + ], + "title": "Status", + "type": "string" + } + }, + "required": [ + "check_id", + "status", + "finding_count", + "source" + ], + "title": "DefaultIntakeCheck", + "type": "object" + }, + "DefaultIntakeWarning": { + "additionalProperties": false, + "properties": { + "source": { + "const": "workstream_default", + "title": "Source", + "type": "string" + }, + "status": { + "const": "warning", + "title": "Status", + "type": "string" + }, + "warning_code": { + "enum": [ + "submission_summary_missing", + "submission_attestation_missing" + ], + "title": "Warning Code", + "type": "string" + } + }, + "required": [ + "source", + "status", + "warning_code" + ], + "title": "DefaultIntakeWarning", + "type": "object" + }, + "ExternalCheckerFinding": { + "additionalProperties": false, + "description": "Sanitized work result; policy later decides whether failure blocks.\n\n``coverage_incomplete`` reports work the checker could not evaluate. It never\nfails the verdict or costs a revision round; locked ReviewPolicy routing sends\nit to a reviewer or back to the contributor.", + "properties": { + "check_id": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Check Id", + "type": "string" + }, + "code": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Code", + "type": "string" + }, + "level": { + "enum": [ + "info", + "warning", + "error", + "coverage_incomplete" + ], + "title": "Level", + "type": "string" + }, + "line": { + "anyOf": [ + { + "maximum": 10000000.0, + "minimum": 1.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Line" + }, + "message": { + "description": "Contributor-visible diagnosis, including useful correction guidance when available.", + "maxLength": 4096, + "minLength": 1, + "title": "Message", + "type": "string" + }, + "path": { + "anyOf": [ + { + "maxLength": 1000, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Path" + } + }, + "required": [ + "check_id", + "code", + "level", + "message" + ], + "title": "ExternalCheckerFinding", + "type": "object" + }, + "ProjectIntakeCheck": { + "additionalProperties": false, + "properties": { + "findings": { + "items": { + "$ref": "#/components/schemas/ExternalCheckerFinding" + }, + "maxItems": 256, + "title": "Findings", + "type": "array" + }, + "registry_entry_digest": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Registry Entry Digest", + "type": "string" + }, + "registry_entry_id": { + "format": "uuid", + "title": "Registry Entry Id", + "type": "string" + }, + "requirement_id": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Requirement Id", + "type": "string" + }, + "source": { + "const": "project_external_checker", + "title": "Source", + "type": "string" + }, + "status": { + "enum": [ + "passed", + "failed" + ], + "title": "Status", + "type": "string" + } + }, + "required": [ + "source", + "requirement_id", + "registry_entry_id", + "registry_entry_digest", + "status", + "findings" + ], + "title": "ProjectIntakeCheck", + "type": "object" + }, "SubmissionAcceptedResponse": { "additionalProperties": false, "description": "Stable T4 snapshot; Submission/evaluation IDs do not exist until T5.", @@ -82,9 +299,19 @@ }, "pre_submission_results": { "items": { - "additionalProperties": true, - "type": "object" + "anyOf": [ + { + "$ref": "#/components/schemas/DefaultIntakeCheck" + }, + { + "$ref": "#/components/schemas/DefaultIntakeWarning" + }, + { + "$ref": "#/components/schemas/ProjectIntakeCheck" + } + ] }, + "maxItems": 7, "title": "Pre Submission Results", "type": "array" }, @@ -163,46 +390,11 @@ }, { "in": "header", - "name": "X-Submission-Summary", - "required": false, - "schema": { - "maxLength": 65536, - "type": "string" - } - }, - { - "in": "header", - "name": "X-Contributor-Attestation", - "required": false, - "schema": { - "maxLength": 65536, - "type": "string" - } - }, - { - "in": "header", - "name": "X-Predecessor-Submission-Id", - "required": false, - "schema": { - "format": "uuid", - "type": "string" - } - }, - { - "in": "header", - "name": "X-Revision-Preparation-Id", - "required": false, - "schema": { - "format": "uuid", - "type": "string" - } - }, - { - "in": "header", - "name": "X-Revision-Preparation-Sha256", + "name": "X-Submission-Feedback", "required": false, "schema": { - "pattern": "^sha256:[0-9a-f]{64}$", + "description": "Optional project feedback. Printable ASCII without leading or trailing whitespace.", + "maxLength": 4096, "type": "string" } }, diff --git a/mcp_server/contracts/submission_get.json b/mcp_server/contracts/submission_get.json index 7aff736f1..b5260d196 100644 --- a/mcp_server/contracts/submission_get.json +++ b/mcp_server/contracts/submission_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "d28322650102cdce43c723c1c00df21974b1cf0c60ebbdf637101dd770598928", + "canonical_sha256": "6ce108cfe03d5881218cbcf85f8c681ae87ab912ff3a9f68a34259bcf24d0877", "components": { "schemas": { "ApiError": { @@ -84,6 +84,17 @@ "title": "Evidence Items", "type": "array" }, + "feedback": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Feedback" + }, "finding_counts": { "$ref": "#/components/schemas/SubmissionFindingCounts" }, @@ -137,8 +148,16 @@ "type": "string" }, "summary": { - "title": "Summary", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Retained summary on submissions recorded before project feedback.", + "title": "Summary" }, "supersedes_submission_id": { "anyOf": [ @@ -169,6 +188,7 @@ "status", "status_reason", "summary", + "feedback", "submitted_at", "decided_at", "finding_counts", diff --git a/mcp_server/contracts/submission_operation_get.json b/mcp_server/contracts/submission_operation_get.json index 3d91e9d72..110c53a43 100644 --- a/mcp_server/contracts/submission_operation_get.json +++ b/mcp_server/contracts/submission_operation_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "d952c167bfdd1a6e434c2549bbe7fd86b27dce9e4653afa72cdd5f66e740aeef", + "canonical_sha256": "e9cf7c4c35d072287b24a985a6ffb0de246e82adad1ab6f1a78abf66c42dd01c", "components": { "schemas": { "ApiError": { @@ -61,6 +61,223 @@ "title": "ApiErrorResponse", "type": "object" }, + "DefaultIntakeCheck": { + "additionalProperties": false, + "properties": { + "check_id": { + "enum": [ + "archive_safe", + "received_identity_exact", + "high_confidence_secrets_absent", + "submission_changed_for_current_rules" + ], + "title": "Check Id", + "type": "string" + }, + "failure_code": { + "anyOf": [ + { + "enum": [ + "submission_archive_malformed", + "submission_archive_limit_exceeded", + "submission_archive_unsafe_entry", + "submission_archive_collision", + "submission_archive_encrypted", + "high_confidence_secret_detected", + "submission_archive_unchanged", + "submission_manifest_unchanged" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Failure Code" + }, + "finding_count": { + "minimum": 0.0, + "title": "Finding Count", + "type": "integer" + }, + "source": { + "const": "workstream_default", + "title": "Source", + "type": "string" + }, + "status": { + "enum": [ + "passed", + "failed", + "not_run" + ], + "title": "Status", + "type": "string" + } + }, + "required": [ + "check_id", + "status", + "finding_count", + "source" + ], + "title": "DefaultIntakeCheck", + "type": "object" + }, + "DefaultIntakeWarning": { + "additionalProperties": false, + "properties": { + "source": { + "const": "workstream_default", + "title": "Source", + "type": "string" + }, + "status": { + "const": "warning", + "title": "Status", + "type": "string" + }, + "warning_code": { + "enum": [ + "submission_summary_missing", + "submission_attestation_missing" + ], + "title": "Warning Code", + "type": "string" + } + }, + "required": [ + "source", + "status", + "warning_code" + ], + "title": "DefaultIntakeWarning", + "type": "object" + }, + "ExternalCheckerFinding": { + "additionalProperties": false, + "description": "Sanitized work result; policy later decides whether failure blocks.\n\n``coverage_incomplete`` reports work the checker could not evaluate. It never\nfails the verdict or costs a revision round; locked ReviewPolicy routing sends\nit to a reviewer or back to the contributor.", + "properties": { + "check_id": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Check Id", + "type": "string" + }, + "code": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Code", + "type": "string" + }, + "level": { + "enum": [ + "info", + "warning", + "error", + "coverage_incomplete" + ], + "title": "Level", + "type": "string" + }, + "line": { + "anyOf": [ + { + "maximum": 10000000.0, + "minimum": 1.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Line" + }, + "message": { + "description": "Contributor-visible diagnosis, including useful correction guidance when available.", + "maxLength": 4096, + "minLength": 1, + "title": "Message", + "type": "string" + }, + "path": { + "anyOf": [ + { + "maxLength": 1000, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Path" + } + }, + "required": [ + "check_id", + "code", + "level", + "message" + ], + "title": "ExternalCheckerFinding", + "type": "object" + }, + "ProjectIntakeCheck": { + "additionalProperties": false, + "properties": { + "findings": { + "items": { + "$ref": "#/components/schemas/ExternalCheckerFinding" + }, + "maxItems": 256, + "title": "Findings", + "type": "array" + }, + "registry_entry_digest": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Registry Entry Digest", + "type": "string" + }, + "registry_entry_id": { + "format": "uuid", + "title": "Registry Entry Id", + "type": "string" + }, + "requirement_id": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Requirement Id", + "type": "string" + }, + "source": { + "const": "project_external_checker", + "title": "Source", + "type": "string" + }, + "status": { + "enum": [ + "passed", + "failed" + ], + "title": "Status", + "type": "string" + } + }, + "required": [ + "source", + "requirement_id", + "registry_entry_id", + "registry_entry_digest", + "status", + "findings" + ], + "title": "ProjectIntakeCheck", + "type": "object" + }, "SubmissionOperationResponse": { "additionalProperties": false, "description": "Authorized operation projection; nullable fields are required on the wire.", @@ -167,9 +384,19 @@ }, "pre_submission_results": { "items": { - "additionalProperties": true, - "type": "object" + "anyOf": [ + { + "$ref": "#/components/schemas/DefaultIntakeCheck" + }, + { + "$ref": "#/components/schemas/DefaultIntakeWarning" + }, + { + "$ref": "#/components/schemas/ProjectIntakeCheck" + } + ] }, + "maxItems": 7, "title": "Pre Submission Results", "type": "array" }, diff --git a/mcp_server/contracts/task_assignment_get.json b/mcp_server/contracts/task_assignment_get.json new file mode 100644 index 000000000..817dfca63 --- /dev/null +++ b/mcp_server/contracts/task_assignment_get.json @@ -0,0 +1,1637 @@ +{ + "canonical_sha256": "520b366d4593eca5073cecba771d8321bd467750c85fe46eb8cbb5477b939a82", + "components": { + "schemas": { + "AcceptedAssignmentEvidence": { + "additionalProperties": false, + "description": "The accepted artifact and earned awards of the contributor's exact assignment.", + "properties": { + "artifact_hash": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Artifact Hash", + "type": "string" + }, + "awards": { + "items": { + "$ref": "#/components/schemas/ContributionAwardView" + }, + "maxItems": 2, + "title": "Awards", + "type": "array" + }, + "contribution_id": { + "format": "uuid", + "title": "Contribution Id", + "type": "string" + }, + "submission_id": { + "format": "uuid", + "title": "Submission Id", + "type": "string" + } + }, + "required": [ + "contribution_id", + "submission_id", + "artifact_hash", + "awards" + ], + "title": "AcceptedAssignmentEvidence", + "type": "object" + }, + "ApiError": { + "additionalProperties": false, + "description": "Canonical machine-readable API error.", + "properties": { + "code": { + "title": "Code", + "type": "string" + }, + "correlation_id": { + "title": "Correlation Id", + "type": "string" + }, + "details": { + "additionalProperties": true, + "title": "Details", + "type": "object" + }, + "message": { + "title": "Message", + "type": "string" + }, + "retryable": { + "title": "Retryable", + "type": "boolean" + } + }, + "required": [ + "code", + "message", + "details", + "correlation_id", + "retryable" + ], + "title": "ApiError", + "type": "object" + }, + "ApiErrorResponse": { + "additionalProperties": false, + "description": "Canonical error plus additive legacy compatibility fields.", + "properties": { + "detail": { + "anyOf": [ + {}, + { + "type": "null" + } + ], + "title": "Detail" + }, + "error": { + "$ref": "#/components/schemas/ApiError" + } + }, + "required": [ + "error" + ], + "title": "ApiErrorResponse", + "type": "object" + }, + "AssignmentIntakeAttempt": { + "additionalProperties": false, + "description": "Retained intake activity and its safe feedback for one assignment.", + "properties": { + "failure_code": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Failure Code" + }, + "operation_id": { + "format": "uuid", + "title": "Operation Id", + "type": "string" + }, + "operationally_stalled": { + "title": "Operationally Stalled", + "type": "boolean" + }, + "pre_submission_results": { + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/DefaultIntakeCheck" + }, + { + "$ref": "#/components/schemas/DefaultIntakeWarning" + }, + { + "$ref": "#/components/schemas/ProjectIntakeCheck" + } + ] + }, + "maxItems": 7, + "title": "Pre Submission Results", + "type": "array" + }, + "stage": { + "title": "Stage", + "type": "string" + }, + "submission_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Submission Id" + } + }, + "required": [ + "operation_id", + "stage", + "failure_code", + "submission_id", + "pre_submission_results", + "operationally_stalled" + ], + "title": "AssignmentIntakeAttempt", + "type": "object" + }, + "ContributionAwardView": { + "additionalProperties": false, + "description": "Earned immutable terms, without any fulfillment or payment assertion.", + "properties": { + "award_definition_id": { + "format": "uuid", + "title": "Award Definition Id", + "type": "string" + }, + "award_id": { + "format": "uuid", + "title": "Award Id", + "type": "string" + }, + "instrument": { + "enum": [ + "money", + "project_points" + ], + "title": "Instrument", + "type": "string" + }, + "quantity": { + "maxLength": 40, + "pattern": "^[0-9]+(?:\\.[0-9]+)?$", + "title": "Quantity", + "type": "string" + }, + "unit": { + "title": "Unit", + "type": "string" + } + }, + "required": [ + "award_id", + "award_definition_id", + "instrument", + "unit", + "quantity" + ], + "title": "ContributionAwardView", + "type": "object" + }, + "ContributorAssignment": { + "additionalProperties": false, + "description": "One own claim. A closed one projects only the contributor's own facts.", + "properties": { + "assignment_id": { + "format": "uuid", + "title": "Assignment Id", + "type": "string" + }, + "assignment_status": { + "enum": [ + "active", + "completed", + "revision_expired", + "revision_exhausted", + "authority_revoked" + ], + "title": "Assignment Status", + "type": "string" + }, + "claimed_at": { + "format": "date-time", + "title": "Claimed At", + "type": "string" + }, + "compensation": { + "$ref": "#/components/schemas/TaskCompensationTerms" + }, + "latest_submission": { + "anyOf": [ + { + "$ref": "#/components/schemas/ContributorLatestSubmission" + }, + { + "type": "null" + } + ] + }, + "locked_guide_version": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Locked Guide Version" + }, + "next_action": { + "enum": [ + "prepare_submission", + "awaiting_evaluation", + "revise", + "none" + ], + "title": "Next Action", + "type": "string" + }, + "project_id": { + "format": "uuid", + "title": "Project Id", + "type": "string" + }, + "released_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Released At" + }, + "revision": { + "anyOf": [ + { + "$ref": "#/components/schemas/ContributorRevisionContext" + }, + { + "type": "null" + } + ] + }, + "started_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Started At" + }, + "state": { + "enum": [ + "active", + "closed" + ], + "title": "State", + "type": "string" + }, + "task_id": { + "format": "uuid", + "title": "Task Id", + "type": "string" + }, + "task_status": { + "anyOf": [ + { + "enum": [ + "draft", + "screening", + "ready", + "in_progress", + "submitted", + "evaluation_pending", + "review_pending", + "needs_revision", + "accepted" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Task Status" + }, + "title": { + "title": "Title", + "type": "string" + }, + "updated_at": { + "description": "Activity time: the latest own assignment, submission or revision stamp, plus the task stamp while active. Orders the list and drives updated_since.", + "format": "date-time", + "title": "Updated At", + "type": "string" + } + }, + "required": [ + "assignment_id", + "project_id", + "task_id", + "title", + "state", + "assignment_status", + "task_status", + "claimed_at", + "started_at", + "released_at", + "locked_guide_version", + "compensation", + "latest_submission", + "revision", + "next_action", + "updated_at" + ], + "title": "ContributorAssignment", + "type": "object" + }, + "ContributorCheckerResult": { + "additionalProperties": false, + "description": "One stored finding, or one member that reported no findings.", + "properties": { + "check_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Check Id" + }, + "checker_name": { + "title": "Checker Name", + "type": "string" + }, + "id": { + "format": "uuid", + "title": "Id", + "type": "string" + }, + "line": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Line" + }, + "path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Path" + }, + "severity": { + "enum": [ + "info", + "low", + "medium", + "high", + "critical", + "error" + ], + "title": "Severity", + "type": "string" + }, + "status": { + "enum": [ + "passed", + "warning", + "failed", + "coverage_incomplete" + ], + "title": "Status", + "type": "string" + }, + "worker_message": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Worker Message" + }, + "worker_suggested_fix": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Worker Suggested Fix" + } + }, + "required": [ + "id", + "checker_name", + "check_id", + "path", + "line", + "status", + "severity", + "worker_message", + "worker_suggested_fix" + ], + "title": "ContributorCheckerResult", + "type": "object" + }, + "ContributorLatestSubmission": { + "additionalProperties": false, + "description": "The newest own attempt on this assignment.", + "properties": { + "decided_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Decided At" + }, + "status": { + "enum": [ + "evaluation_pending", + "review_pending", + "accepted", + "needs_revision", + "rejected" + ], + "title": "Status", + "type": "string" + }, + "status_reason": { + "anyOf": [ + { + "enum": [ + "revision_deadline_expired", + "revision_limit_reached", + "checker_coverage_incomplete" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Status Reason" + }, + "submission_id": { + "format": "uuid", + "title": "Submission Id", + "type": "string" + }, + "submitted_at": { + "format": "date-time", + "title": "Submitted At", + "type": "string" + }, + "version": { + "exclusiveMinimum": 0.0, + "title": "Version", + "type": "integer" + } + }, + "required": [ + "submission_id", + "version", + "status", + "status_reason", + "submitted_at", + "decided_at" + ], + "title": "ContributorLatestSubmission", + "type": "object" + }, + "ContributorRevisionContext": { + "additionalProperties": false, + "description": "Frozen preparation plus an eligibility projection evaluated at database time.", + "properties": { + "changes": { + "items": { + "$ref": "#/components/schemas/RevisionContextChange" + }, + "maxItems": 8, + "title": "Changes", + "type": "array" + }, + "clock_state": { + "enum": [ + "running", + "paused" + ], + "title": "Clock State", + "type": "string" + }, + "deadline_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Deadline At" + }, + "direction": { + "anyOf": [ + { + "enum": [ + "kept", + "forward", + "backward" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Direction" + }, + "disposition": { + "enum": [ + "ready", + "context_blocked", + "revision_limit_reached", + "revision_deadline_expired" + ], + "title": "Disposition", + "type": "string" + }, + "max_revision_rounds": { + "minimum": 0.0, + "title": "Max Revision Rounds", + "type": "integer" + }, + "next_revision_round": { + "minimum": 0.0, + "title": "Next Revision Round", + "type": "integer" + }, + "outcome": { + "enum": [ + "kept", + "rebased", + "blocked" + ], + "title": "Outcome", + "type": "string" + }, + "predecessor_preparation_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Predecessor Preparation Id" + }, + "preparation_id": { + "format": "uuid", + "title": "Preparation Id", + "type": "string" + }, + "preparation_sha256": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Preparation Sha256", + "type": "string" + }, + "prior": { + "$ref": "#/components/schemas/RevisionContextSnapshot" + }, + "remaining_microseconds": { + "anyOf": [ + { + "minimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Remaining Microseconds" + }, + "requested_at": { + "format": "date-time", + "title": "Requested At", + "type": "string" + }, + "sequence": { + "exclusiveMinimum": 0.0, + "title": "Sequence", + "type": "integer" + }, + "source_routing_manifest_id": { + "format": "uuid", + "title": "Source Routing Manifest Id", + "type": "string" + }, + "source_submission_id": { + "format": "uuid", + "title": "Source Submission Id", + "type": "string" + }, + "target": { + "anyOf": [ + { + "$ref": "#/components/schemas/RevisionContextSnapshot" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "preparation_id", + "preparation_sha256", + "predecessor_preparation_id", + "source_submission_id", + "source_routing_manifest_id", + "sequence", + "next_revision_round", + "max_revision_rounds", + "requested_at", + "deadline_at", + "clock_state", + "remaining_microseconds", + "outcome", + "disposition", + "direction", + "prior", + "target", + "changes" + ], + "title": "ContributorRevisionContext", + "type": "object" + }, + "DefaultIntakeCheck": { + "additionalProperties": false, + "properties": { + "check_id": { + "enum": [ + "archive_safe", + "received_identity_exact", + "high_confidence_secrets_absent", + "submission_changed_for_current_rules" + ], + "title": "Check Id", + "type": "string" + }, + "failure_code": { + "anyOf": [ + { + "enum": [ + "submission_archive_malformed", + "submission_archive_limit_exceeded", + "submission_archive_unsafe_entry", + "submission_archive_collision", + "submission_archive_encrypted", + "high_confidence_secret_detected", + "submission_archive_unchanged", + "submission_manifest_unchanged" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Failure Code" + }, + "finding_count": { + "minimum": 0.0, + "title": "Finding Count", + "type": "integer" + }, + "source": { + "const": "workstream_default", + "title": "Source", + "type": "string" + }, + "status": { + "enum": [ + "passed", + "failed", + "not_run" + ], + "title": "Status", + "type": "string" + } + }, + "required": [ + "check_id", + "status", + "finding_count", + "source" + ], + "title": "DefaultIntakeCheck", + "type": "object" + }, + "DefaultIntakeWarning": { + "additionalProperties": false, + "properties": { + "source": { + "const": "workstream_default", + "title": "Source", + "type": "string" + }, + "status": { + "const": "warning", + "title": "Status", + "type": "string" + }, + "warning_code": { + "enum": [ + "submission_summary_missing", + "submission_attestation_missing" + ], + "title": "Warning Code", + "type": "string" + } + }, + "required": [ + "source", + "status", + "warning_code" + ], + "title": "DefaultIntakeWarning", + "type": "object" + }, + "ExactContributorAssignment": { + "additionalProperties": false, + "description": "Current status, retained intake and governed evidence for one owned claim.", + "properties": { + "accepted_evidence": { + "anyOf": [ + { + "$ref": "#/components/schemas/AcceptedAssignmentEvidence" + }, + { + "type": "null" + } + ] + }, + "assignment": { + "$ref": "#/components/schemas/ContributorAssignment" + }, + "current_status": { + "anyOf": [ + { + "enum": [ + "draft", + "screening", + "ready", + "in_progress", + "submitted", + "evaluation_pending", + "review_pending", + "needs_revision", + "accepted" + ], + "type": "string" + }, + { + "enum": [ + "closed", + "rejected" + ], + "type": "string" + } + ], + "title": "Current Status" + }, + "feedback_submission_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Feedback Submission Id" + }, + "intake": { + "anyOf": [ + { + "$ref": "#/components/schemas/AssignmentIntakeAttempt" + }, + { + "type": "null" + } + ] + }, + "next_action": { + "enum": [ + "submit", + "awaiting_intake", + "awaiting_evaluation", + "revise", + "wait_for_processing", + "none" + ], + "title": "Next Action", + "type": "string" + }, + "next_cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Next Cursor" + }, + "post_submission_results": { + "items": { + "$ref": "#/components/schemas/ContributorCheckerResult" + }, + "maxItems": 100, + "title": "Post Submission Results", + "type": "array" + }, + "status_reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Status Reason" + } + }, + "required": [ + "assignment", + "current_status", + "status_reason", + "next_action", + "intake", + "feedback_submission_id", + "post_submission_results", + "next_cursor", + "accepted_evidence" + ], + "title": "ExactContributorAssignment", + "type": "object" + }, + "ExternalCheckerFinding": { + "additionalProperties": false, + "description": "Sanitized work result; policy later decides whether failure blocks.\n\n``coverage_incomplete`` reports work the checker could not evaluate. It never\nfails the verdict or costs a revision round; locked ReviewPolicy routing sends\nit to a reviewer or back to the contributor.", + "properties": { + "check_id": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Check Id", + "type": "string" + }, + "code": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Code", + "type": "string" + }, + "level": { + "enum": [ + "info", + "warning", + "error", + "coverage_incomplete" + ], + "title": "Level", + "type": "string" + }, + "line": { + "anyOf": [ + { + "maximum": 10000000.0, + "minimum": 1.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Line" + }, + "message": { + "description": "Contributor-visible diagnosis, including useful correction guidance when available.", + "maxLength": 4096, + "minLength": 1, + "title": "Message", + "type": "string" + }, + "path": { + "anyOf": [ + { + "maxLength": 1000, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Path" + } + }, + "required": [ + "check_id", + "code", + "level", + "message" + ], + "title": "ExternalCheckerFinding", + "type": "object" + }, + "ProjectIntakeCheck": { + "additionalProperties": false, + "properties": { + "findings": { + "items": { + "$ref": "#/components/schemas/ExternalCheckerFinding" + }, + "maxItems": 256, + "title": "Findings", + "type": "array" + }, + "registry_entry_digest": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Registry Entry Digest", + "type": "string" + }, + "registry_entry_id": { + "format": "uuid", + "title": "Registry Entry Id", + "type": "string" + }, + "requirement_id": { + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-z][a-z0-9_.-]*$", + "title": "Requirement Id", + "type": "string" + }, + "source": { + "const": "project_external_checker", + "title": "Source", + "type": "string" + }, + "status": { + "enum": [ + "passed", + "failed" + ], + "title": "Status", + "type": "string" + } + }, + "required": [ + "source", + "requirement_id", + "registry_entry_id", + "registry_entry_digest", + "status", + "findings" + ], + "title": "ProjectIntakeCheck", + "type": "object" + }, + "RevisionContextChange": { + "additionalProperties": false, + "description": "One bounded policy identity change, without provider or finance internals.", + "properties": { + "after": { + "maxLength": 200, + "minLength": 1, + "title": "After", + "type": "string" + }, + "before": { + "maxLength": 200, + "minLength": 1, + "title": "Before", + "type": "string" + }, + "component": { + "enum": [ + "guide", + "source", + "artifact", + "pre_submit", + "post_submit", + "review", + "revision", + "contribution" + ], + "title": "Component", + "type": "string" + } + }, + "required": [ + "component", + "before", + "after" + ], + "title": "RevisionContextChange", + "type": "object" + }, + "RevisionContextSnapshot": { + "additionalProperties": false, + "description": "One complete activated context, independent of the task's mutable locks.", + "properties": { + "activated_at": { + "format": "date-time", + "title": "Activated At", + "type": "string" + }, + "activation_generation": { + "exclusiveMinimum": 0.0, + "title": "Activation Generation", + "type": "integer" + }, + "activation_operation_id": { + "format": "uuid", + "title": "Activation Operation Id", + "type": "string" + }, + "guide_id": { + "format": "uuid", + "title": "Guide Id", + "type": "string" + }, + "lineage": { + "$ref": "#/components/schemas/TaskPolicyLineage" + } + }, + "required": [ + "guide_id", + "activation_operation_id", + "activation_generation", + "activated_at", + "lineage" + ], + "title": "RevisionContextSnapshot", + "type": "object" + }, + "TaskCompensationAward": { + "description": "One contributor-safe exact award value in a TASK response.", + "properties": { + "instrument": { + "enum": [ + "money", + "project_points" + ], + "title": "Instrument", + "type": "string" + }, + "quantity": { + "title": "Quantity", + "type": "string" + }, + "unit": { + "title": "Unit", + "type": "string" + } + }, + "required": [ + "instrument", + "unit", + "quantity" + ], + "title": "TaskCompensationAward", + "type": "object" + }, + "TaskCompensationTerms": { + "description": "The two complete locked contribution rules disclosed by TASK.", + "properties": { + "accepted_submission": { + "anyOf": [ + { + "const": "unpaid", + "type": "string" + }, + { + "items": { + "$ref": "#/components/schemas/TaskCompensationAward" + }, + "type": "array" + } + ], + "title": "Accepted Submission" + }, + "completed_review": { + "anyOf": [ + { + "const": "unpaid", + "type": "string" + }, + { + "items": { + "$ref": "#/components/schemas/TaskCompensationAward" + }, + "type": "array" + } + ], + "title": "Completed Review" + }, + "contribution_policy_version_id": { + "format": "uuid", + "title": "Contribution Policy Version Id", + "type": "string" + } + }, + "required": [ + "contribution_policy_version_id", + "accepted_submission", + "completed_review" + ], + "title": "TaskCompensationTerms", + "type": "object" + }, + "TaskPolicyLineage": { + "additionalProperties": false, + "description": "Complete bounded policy identities; no policy body or arbitrary metadata.", + "properties": { + "locked_contribution_policy_version_id": { + "format": "uuid", + "title": "Locked Contribution Policy Version Id", + "type": "string" + }, + "locked_effective_project_submission_artifact_policy_hash": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Locked Effective Project Submission Artifact Policy Hash", + "type": "string" + }, + "locked_effective_project_submission_artifact_policy_id": { + "format": "uuid", + "title": "Locked Effective Project Submission Artifact Policy Id", + "type": "string" + }, + "locked_guide_source_snapshot_hash": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Locked Guide Source Snapshot Hash", + "type": "string" + }, + "locked_guide_source_snapshot_id": { + "format": "uuid", + "title": "Locked Guide Source Snapshot Id", + "type": "string" + }, + "locked_guide_version": { + "pattern": "\\S", + "title": "Locked Guide Version", + "type": "string" + }, + "locked_post_submit_checker_policy_hash": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Locked Post Submit Checker Policy Hash", + "type": "string" + }, + "locked_post_submit_checker_policy_id": { + "format": "uuid", + "title": "Locked Post Submit Checker Policy Id", + "type": "string" + }, + "locked_post_submit_checker_policy_version": { + "pattern": "\\S", + "title": "Locked Post Submit Checker Policy Version", + "type": "string" + }, + "locked_pre_submit_checker_bundle_hash": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Locked Pre Submit Checker Bundle Hash", + "type": "string" + }, + "locked_pre_submit_checker_policy_id": { + "format": "uuid", + "title": "Locked Pre Submit Checker Policy Id", + "type": "string" + }, + "locked_review_policy_generation": { + "exclusiveMinimum": 0.0, + "title": "Locked Review Policy Generation", + "type": "integer" + }, + "locked_review_policy_hash": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Locked Review Policy Hash", + "type": "string" + }, + "locked_review_policy_id": { + "format": "uuid", + "title": "Locked Review Policy Id", + "type": "string" + }, + "locked_revision_policy_generation": { + "exclusiveMinimum": 0.0, + "title": "Locked Revision Policy Generation", + "type": "integer" + }, + "locked_revision_policy_hash": { + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Locked Revision Policy Hash", + "type": "string" + }, + "locked_revision_policy_id": { + "format": "uuid", + "title": "Locked Revision Policy Id", + "type": "string" + } + }, + "required": [ + "locked_guide_version", + "locked_guide_source_snapshot_id", + "locked_guide_source_snapshot_hash", + "locked_effective_project_submission_artifact_policy_id", + "locked_effective_project_submission_artifact_policy_hash", + "locked_pre_submit_checker_policy_id", + "locked_pre_submit_checker_bundle_hash", + "locked_post_submit_checker_policy_id", + "locked_post_submit_checker_policy_version", + "locked_post_submit_checker_policy_hash", + "locked_review_policy_id", + "locked_review_policy_generation", + "locked_review_policy_hash", + "locked_revision_policy_id", + "locked_revision_policy_generation", + "locked_revision_policy_hash", + "locked_contribution_policy_version_id" + ], + "title": "TaskPolicyLineage", + "type": "object" + } + } + }, + "operation": { + "description": "Read your assignment status, feedback and earned evidence by task and assignment.", + "operationId": "read_my_assignment_api_v1_tasks__task_id__assignments__assignment_id__get", + "parameters": [ + { + "in": "path", + "name": "task_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Task Id", + "type": "string" + } + }, + { + "in": "path", + "name": "assignment_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Assignment Id", + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 25, + "maximum": 100, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "anyOf": [ + { + "maxLength": 512, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Cursor" + } + }, + { + "in": "header", + "name": "X-Request-ID", + "required": false, + "schema": { + "format": "uuid", + "maxLength": 36, + "minLength": 36, + "type": "string" + } + }, + { + "in": "header", + "name": "X-Correlation-ID", + "required": false, + "schema": { + "format": "uuid", + "maxLength": 36, + "minLength": 36, + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ExactContributorAssignment" + } + } + }, + "description": "Successful Response", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Invalid request.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Authentication failed.", + "headers": { + "WWW-Authenticate": { + "schema": { + "type": "string" + } + }, + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Permission denied.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Not Found", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Unprocessable Entity", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Internal server error.", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiErrorResponse" + } + } + }, + "description": "Service Unavailable", + "headers": { + "X-Correlation-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + "X-Request-ID": { + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + } + } + }, + "security": [ + { + "HTTPBearer": [] + } + ], + "summary": "Read My Assignment", + "tags": [ + "tasks" + ], + "x-workstream-action-id": "task.assignment.read" + }, + "schema_version": 1, + "source": { + "method": "GET", + "openapi_version": "3.1.0", + "path": "/api/v1/tasks/{task_id}/assignments/{assignment_id}", + "repository_sha": "c853743b689a46711c13e1d800cdd27ab8230ac2" + } +} diff --git a/mcp_server/contracts/task_submission_requirements_get.json b/mcp_server/contracts/task_submission_requirements_get.json index 4b5166906..bb3d61d39 100644 --- a/mcp_server/contracts/task_submission_requirements_get.json +++ b/mcp_server/contracts/task_submission_requirements_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "f32cf9d7a67d83912ee450e660c039fbfafc07a7d2c9d76f3fb10c0ee6c75472", + "canonical_sha256": "3f4054acf5398d06408b84dedf3058e4a6e320cacbe4e36b211bc803aee73f4d", "components": { "schemas": { "ApiError": { @@ -81,13 +81,6 @@ "title": "Artifact Hash Required", "type": "boolean" }, - "attestation_terms": { - "items": { - "type": "string" - }, - "title": "Attestation Terms", - "type": "array" - }, "forbidden_artifacts": { "items": { "$ref": "#/components/schemas/ForbiddenArtifactRequirement" @@ -192,13 +185,6 @@ "title": "Required Evidence", "type": "array" }, - "required_packet_fields": { - "items": { - "type": "string" - }, - "title": "Required Packet Fields", - "type": "array" - }, "storage_reference_rules": { "$ref": "#/components/schemas/StorageReferenceRules" }, @@ -214,11 +200,9 @@ "guide_version", "policy_schema_version", "merge_algorithm_version", - "required_packet_fields", "required_artifacts", "required_evidence", "forbidden_artifacts", - "attestation_terms", "manifest_required", "artifact_hash_required", "artifact_hash_algorithm", diff --git a/mcp_server/contracts/task_submissions_list.json b/mcp_server/contracts/task_submissions_list.json index e7314a8a6..18851e4aa 100644 --- a/mcp_server/contracts/task_submissions_list.json +++ b/mcp_server/contracts/task_submissions_list.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "ccf372fb280d1b99174a4ca5f6c14e8939d9eb8ad49d2dc110e23d1b2af1686d", + "canonical_sha256": "ebfec0559441fb4a618f315bc5b96bc5f9e3f3d7b3da27b1dca51adaeec2b66c", "components": { "schemas": { "ApiError": { @@ -84,6 +84,17 @@ "title": "Evidence Items", "type": "array" }, + "feedback": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Feedback" + }, "finding_counts": { "$ref": "#/components/schemas/SubmissionFindingCounts" }, @@ -137,8 +148,16 @@ "type": "string" }, "summary": { - "title": "Summary", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Retained summary on submissions recorded before project feedback.", + "title": "Summary" }, "supersedes_submission_id": { "anyOf": [ @@ -169,6 +188,7 @@ "status", "status_reason", "summary", + "feedback", "submitted_at", "decided_at", "finding_counts", diff --git a/mcp_server/contracts/task_work_context_get.json b/mcp_server/contracts/task_work_context_get.json index e59472aa9..87da77797 100644 --- a/mcp_server/contracts/task_work_context_get.json +++ b/mcp_server/contracts/task_work_context_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "cb9b06d69399d48ef7672b9a32f17e96f6afbf33d80924d0f3a3a94d54fb3015", + "canonical_sha256": "a8c5b3cc4f2092bda5225aa0e46d343b433bc57b33119b0dc5d2197dab7781ea", "components": { "schemas": { "ApiError": { @@ -63,7 +63,7 @@ }, "ContributorGuideDocument": { "additionalProperties": false, - "description": "Public original identity and task-scoped authorized read reference.", + "description": "Public original identity and authorized download reference.", "properties": { "byte_count": { "exclusiveMinimum": 0.0, @@ -106,11 +106,11 @@ }, "required": [ "document_id", - "order", "label", + "order", "media_type", - "byte_count", "sha256", + "byte_count", "read_reference" ], "title": "ContributorGuideDocument", diff --git a/mcp_server/pyproject.toml b/mcp_server/pyproject.toml index 28bcb6c74..4e5456533 100644 --- a/mcp_server/pyproject.toml +++ b/mcp_server/pyproject.toml @@ -136,6 +136,9 @@ packages = ["workstream_mcp"] "contracts/task_release.json" = "workstream_mcp/contracts/task_release.json" "contracts/task_claim.json" = "workstream_mcp/contracts/task_claim.json" "contracts/task_work_context_get.json" = "workstream_mcp/contracts/task_work_context_get.json" +"contracts/task_assignment_get.json" = "workstream_mcp/contracts/task_assignment_get.json" +"contracts/project_contributor_guide_get.json" = "workstream_mcp/contracts/project_contributor_guide_get.json" +"contracts/project_contributor_guide_document_get.json" = "workstream_mcp/contracts/project_contributor_guide_document_get.json" "contracts/task_guide_document_content_get.json" = "workstream_mcp/contracts/task_guide_document_content_get.json" "contracts/submission_operation_get.json" = "workstream_mcp/contracts/submission_operation_get.json" "contracts/submission_create.json" = "workstream_mcp/contracts/submission_create.json" diff --git a/mcp_server/tests/test_task_execution.py b/mcp_server/tests/test_task_execution.py index 3e30f0c3d..ab502581f 100644 --- a/mcp_server/tests/test_task_execution.py +++ b/mcp_server/tests/test_task_execution.py @@ -34,8 +34,7 @@ def _arguments(name: str) -> dict[str, Any]: "assignment_id": ASSIGNMENT_ID, "zip_base64": base64.b64encode(b"PK\x03\x04fixture").decode(), "idempotency_key": KEY, - "summary": "ready", - "contributor_attestation": "reviewed", + "feedback": "ready for review", }, "preparations_list": {"task_id": TASK_ID, "limit": 25, "cursor": "opaque"}, "preparation_get": {"task_id": TASK_ID, "preparation_id": PREPARATION_ID}, @@ -45,6 +44,11 @@ def _arguments(name: str) -> dict[str, Any]: "task_release": {"task_id": TASK_ID, "idempotency_key": KEY}, "task_claim": {"task_id": TASK_ID, "idempotency_key": KEY}, "task_work_context_get": {"task_id": TASK_ID}, + "task_assignment_get": {"task_id": TASK_ID, "assignment_id": ASSIGNMENT_ID}, + "project_contributor_guide_get": {"project_id": PROJECT_ID}, + "project_contributor_guide_document_get": { + "project_id": PROJECT_ID, "guide_id": PREPARATION_ID, "document_id": DOCUMENT_ID, + }, "task_guide_document_content_get": { "task_id": TASK_ID, "document_id": DOCUMENT_ID, @@ -88,7 +92,11 @@ def _bound_response(name: str) -> dict[str, Any]: } if name == "task_work_context_get": return {"task": {"task_id": TASK_ID}} - if name == "task_guide_document_content_get": + if name == "task_assignment_get": + return {"assignment": {"task_id": TASK_ID, "assignment_id": ASSIGNMENT_ID}} + if name == "project_contributor_guide_get": + return {"project_id": PROJECT_ID} + if name in {"task_guide_document_content_get", "project_contributor_guide_document_get"}: return { "media_type": "text/markdown", "content_base64": "eA==", @@ -160,7 +168,8 @@ def test_task_execution_catalogue_is_exact_closed_and_does_not_dispatch( @pytest.mark.parametrize( "name", - [name for name in TASK_EXECUTION_CONTRACT_NAMES if name != "task_guide_document_content_get"], + [name for name in TASK_EXECUTION_CONTRACT_NAMES + if name not in {"task_guide_document_content_get", "project_contributor_guide_document_get"}], ) @pytest.mark.asyncio async def test_every_json_operation_forwards_only_its_fixed_request( @@ -299,8 +308,8 @@ def test_submission_upload_decodes_once_and_forwards_only_reviewed_headers( assert request.headers["content-type"] == "application/zip" assert request.headers["idempotency-key"] == KEY assert request.headers["x-task-assignment-id"] == ASSIGNMENT_ID - assert request.headers["x-submission-summary"] == "ready" - assert request.headers["x-contributor-attestation"] == "reviewed" + assert request.headers["x-submission-feedback"] == "ready for review" + assert "x-submission-summary" not in request.headers def test_submission_bundle_contract_fits_inside_mcp_ingress() -> None: @@ -313,12 +322,12 @@ def test_submission_bundle_contract_fits_inside_mcp_ingress() -> None: ) -@pytest.mark.parametrize("field", ["summary", "contributor_attestation"]) -def test_submission_header_text_rejects_trailing_newline_before_dispatch( - adapter: Adapter, field: str +@pytest.mark.parametrize("text", ["ready\n", " edge", "café", "x" * 4097]) +def test_submission_feedback_rejects_non_wire_text( + adapter: Adapter, text: str, ) -> None: client, received, _ = adapter - arguments = {**_arguments("submission_create"), field: "ready\n"} + arguments = {**_arguments("submission_create"), "feedback": text} response = client.post( "/mcp", headers={ @@ -342,7 +351,7 @@ def test_submission_header_text_rejects_trailing_newline_before_dispatch( assert received == [] -def test_incomplete_revision_preparation_selector_never_dispatches(adapter: Adapter) -> None: +def test_retired_revision_selector_never_dispatches(adapter: Adapter) -> None: client, received, _ = adapter arguments = { **_arguments("submission_create"), @@ -377,7 +386,12 @@ def test_pre_submit_checker_failure_is_a_safe_tool_outcome(adapter: Adapter) -> "error": { "code": "pre_submission_checker_failed", "message": "Pre-submission checks failed", - "details": {"eligible_to_submit": False}, + "details": { + "eligible_to_submit": False, "status": "failed", "results": [{ + "source": "workstream_default", "check_id": "archive_safe", "status": "failed", + "failure_code": "submission_archive_malformed", "finding_count": 1, + }], + }, "correlation_id": KEY, "retryable": False, } @@ -402,6 +416,7 @@ def test_pre_submit_checker_failure_is_a_safe_tool_outcome(adapter: Adapter) -> assert result["isError"] is True assert result["structuredContent"]["status"] == 422 assert result["structuredContent"]["code"] == "pre_submission_checker_failed" + assert result["structuredContent"]["details"] == upstream["json"]["error"]["details"] assert len(received) == 1 @@ -459,17 +474,15 @@ def test_submission_acceptance_refuses_substitution_and_invalid_snapshots( {"revision_preparation_id": PREPARATION_ID, "revision_preparation_sha256": "sha256:" + "a" * 64}, ]) -def test_submission_revision_requires_predecessor_and_both_acknowledgements( +def test_submission_has_no_revision_acknowledgement_inputs( fields: dict[str, Any], ) -> None: validator = Draft202012Validator( TASK_EXECUTION_INPUT_SCHEMAS["submission_create"], format_checker=FormatChecker() ) assert not validator.is_valid(_arguments("submission_create") | fields) - assert validator.is_valid(_arguments("submission_create") | { - "predecessor_submission_id": SUBMISSION_ID, - "revision_preparation_id": PREPARATION_ID, - "revision_preparation_sha256": "sha256:" + "a" * 64, + assert validator.is_valid({ + key: value for key, value in _arguments("submission_create").items() if key != "feedback" }) diff --git a/mcp_server/tests/test_task_execution_contract_drift.py b/mcp_server/tests/test_task_execution_contract_drift.py index 3dfeab72e..823179ca8 100644 --- a/mcp_server/tests/test_task_execution_contract_drift.py +++ b/mcp_server/tests/test_task_execution_contract_drift.py @@ -69,7 +69,7 @@ def test_task_execution_contract_is_tamper_evident_and_matches_fixed_route( def test_exact_task_execution_contract_set_is_reviewed() -> None: - assert len(TASK_EXECUTION_CONTRACT_NAMES) == 17 + assert len(TASK_EXECUTION_CONTRACT_NAMES) == 20 assert set(TASK_EXECUTION_CONTRACT_NAMES) == set(TASK_EXECUTION_OPERATIONS) diff --git a/mcp_server/workstream_mcp/errors.py b/mcp_server/workstream_mcp/errors.py index 234d03115..475563e09 100644 --- a/mcp_server/workstream_mcp/errors.py +++ b/mcp_server/workstream_mcp/errors.py @@ -14,6 +14,8 @@ class SafeFailure: code: str | None = None correlation_id: str | None = None retryable: bool = False + message: str | None = None + details: dict[str, Any] | None = None def payload(self) -> dict[str, Any]: value: dict[str, Any] = {"error": self.error, "retryable": self.retryable} @@ -23,6 +25,10 @@ def payload(self) -> dict[str, Any]: value["code"] = self.code if self.correlation_id is not None: value["correlation_id"] = self.correlation_id + if self.message is not None: + value["message"] = self.message + if self.details is not None: + value["details"] = self.details return value def result(self) -> CallToolResult: diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py index 2e398d8fc..6cc43a1d6 100644 --- a/mcp_server/workstream_mcp/http_gateway.py +++ b/mcp_server/workstream_mcp/http_gateway.py @@ -5,7 +5,7 @@ import hashlib import json import re -from dataclasses import dataclass +from dataclasses import dataclass, replace from typing import Any, cast from urllib.parse import quote from uuid import UUID, uuid4 @@ -40,6 +40,15 @@ re.ASCII, ) _CORRELATION_HEADERS = ("x-request-id", "x-correlation-id") +_SUBMISSION_ERROR_CODES = frozenset({ + "submission_unavailable", "submission_packet_invalid", "submission_media_type_unsupported", + "submission_archive_limit_exceeded", "submission_upload_timeout", + "submission_capacity_exceeded", + "submission_operation_in_progress", "submission_operation_terminal", + "submission_idempotency_conflict", + "pre_submission_checker_failed", "revision_deadline_expired", "revision_limit_reached", + "revision_context_blocked", "revision_context_changed", "task_submission_predecessor_changed", +}) _PUBLIC_ERROR_CODES = frozenset( { "actor_deactivated", @@ -383,6 +392,15 @@ "task_release": ("POST", "/api/v1/tasks/{task_id}/release", 200), "task_claim": ("POST", "/api/v1/tasks/{task_id}/claim", 200), "task_work_context_get": ("GET", "/api/v1/tasks/{task_id}/work-context", 200), + "task_assignment_get": ("GET", "/api/v1/tasks/{task_id}/assignments/{assignment_id}", 200), + "project_contributor_guide_get": ( + "GET", "/api/v1/projects/{project_id}/contributor-guide", 200, + ), + "project_contributor_guide_document_get": ( + "GET", + "/api/v1/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content", + 200, + ), "task_guide_document_content_get": ( "GET", "/api/v1/tasks/{task_id}/guide/documents/{document_id}/content", @@ -1485,7 +1503,7 @@ async def task_execution_operation( if not isinstance(value, str): # guarded by the tool schema return self._invalid_read_response(correlation_id) path = path.replace(f"{{{selector}}}", quote(value, safe="")) - if name == "task_guide_document_content_get": + if name in {"task_guide_document_content_get", "project_contributor_guide_document_get"}: return await self._request_binary(path, bearer, correlation_id) excluded = { @@ -1494,11 +1512,7 @@ async def task_execution_operation( "zip_base64", "assignment_id", "idempotency_key", - "summary", - "contributor_attestation", - "predecessor_submission_id", - "revision_preparation_id", - "revision_preparation_sha256", + "feedback", } if name == "submission_operation_get": excluded.remove("idempotency_key") @@ -1512,16 +1526,9 @@ async def task_execution_operation( if upload is None: return GatewayResult(failure=SafeFailure("invalid_tool_input", status=400)) extra_headers = {"X-Task-Assignment-Id": arguments["assignment_id"]} - for argument, header in ( - ("summary", "X-Submission-Summary"), - ("contributor_attestation", "X-Contributor-Attestation"), - ("predecessor_submission_id", "X-Predecessor-Submission-Id"), - ("revision_preparation_id", "X-Revision-Preparation-Id"), - ("revision_preparation_sha256", "X-Revision-Preparation-Sha256"), - ): - value = arguments.get(argument) - if isinstance(value, str): - extra_headers[header] = value + feedback = arguments.get("feedback") + if isinstance(feedback, str): + extra_headers["X-Submission-Feedback"] = feedback mutation = name in _TASK_EXECUTION_MUTATIONS outcome = await self._request( @@ -1543,6 +1550,7 @@ async def task_execution_operation( else None ), extra_headers=extra_headers, + submission_upload=name == "submission_create", ) if outcome.failure is not None: return outcome @@ -1564,6 +1572,13 @@ def _task_execution_response_matches( project_id = arguments.get("project_id") if name in {"submission_get", "management_submission_get"}: return cls._same_uuid(data.get("id"), arguments["submission_id"]) + if name == "project_contributor_guide_get": + return cls._same_uuid(data.get("project_id"), project_id) + if name == "task_assignment_get": + assignment = data.get("assignment") + return isinstance(assignment, dict) and cls._fields_match( + assignment, {"task_id": task_id, "assignment_id": arguments["assignment_id"]}, + ) if not isinstance(task_id, str): return False if project_id is not None and not isinstance(project_id, str): @@ -2177,6 +2192,7 @@ async def _request( array_envelope: bool = False, operation_timeout_seconds: float | None = None, extra_headers: dict[str, str] | None = None, + submission_upload: bool = False, ) -> GatewayResult: request_id = correlation_id or str(uuid4()) operation_timeout = operation_timeout_seconds or self._settings.total_timeout_seconds @@ -2214,6 +2230,8 @@ async def _request( correlation_id = self._correlation_id(response, request_id) if response.status_code != expected_status: failure = self._api_failure(response.status_code, body, correlation_id) + if submission_upload and 400 <= response.status_code < 500: + failure = self._submission_failure(failure, body, output_validator) # Proxy errors and unexpected successes cannot prove rollback. if mutation and ( response.status_code < 400 or response.status_code >= 500 @@ -2375,6 +2393,33 @@ def _correlation_id(response: httpx.Response, fallback: str) -> str: return str(value) return fallback + @staticmethod + def _submission_failure( + failure: SafeFailure, body: bytes, validator: Draft202012Validator, + ) -> SafeFailure: + """Expose only the contributor-safe error fields of the raw ZIP route.""" + try: + decoded = json.loads(body) + error = decoded["error"] + if not isinstance(error, dict) or error.get("code") not in _SUBMISSION_ERROR_CODES: + return failure + code, details = error["code"], error.get("details") + message = error.get("message") + if not isinstance(message, str) or len(message) > 512 or not message.isprintable(): + message = None + if code == "pre_submission_checker_failed" and failure.status == 422: + result_schema = validator.schema["properties"]["pre_submission_results"] + if (not isinstance(details, dict) + or details.keys() != {"status", "eligible_to_submit", "results"} + or details["status"] != "failed" + or details["eligible_to_submit"] is not False): + return failure + validator.evolve(schema=result_schema).validate(details["results"]) + return replace(failure, code=code, message=message, details=details) + return replace(failure, code=code, message=message) + except (KeyError, TypeError, ValueError, RecursionError, ValidationError): + return failure + @staticmethod def _api_failure(status: int, body: bytes, correlation_id: str) -> SafeFailure: code = None diff --git a/mcp_server/workstream_mcp/schemas.py b/mcp_server/workstream_mcp/schemas.py index 15d8200bd..bd1c1e7c1 100644 --- a/mcp_server/workstream_mcp/schemas.py +++ b/mcp_server/workstream_mcp/schemas.py @@ -840,10 +840,10 @@ def _lifecycle_input(resource_key: str) -> dict[str, Any]: }, "additionalProperties": False, } -_ASCII_PACKET_TEXT = { +_SUBMISSION_FEEDBACK_TEXT = { "type": "string", "maxLength": 4_096, - "pattern": r"^[\u0020-\u007e]*$(?![\s\S])", + "pattern": r"^(?:[!-~](?:[ -~]*[!-~])?)?$(?![\s\S])", } _SHA256_INPUT = { "type": "string", @@ -903,6 +903,26 @@ def _task_transition_input() -> dict[str, Any]: "required": ["task_id"], "additionalProperties": False, }, + "task_assignment_get": { + "type": "object", + "properties": {"assignment_id": _UUID_INPUT, **_TASK_PAGE_PROPERTIES}, + "required": ["task_id", "assignment_id"], + "additionalProperties": False, + }, + "project_contributor_guide_get": { + "type": "object", + "properties": {"project_id": _UUID_INPUT}, + "required": ["project_id"], + "additionalProperties": False, + }, + "project_contributor_guide_document_get": { + "type": "object", + "properties": { + "project_id": _UUID_INPUT, "guide_id": _UUID_INPUT, "document_id": _UUID_INPUT, + }, + "required": ["project_id", "guide_id", "document_id"], + "additionalProperties": False, + }, "task_guide_document_content_get": { "type": "object", "properties": {"task_id": _UUID_INPUT, "document_id": _UUID_INPUT}, @@ -932,27 +952,9 @@ def _task_transition_input() -> dict[str, Any]: "pattern": r"^[A-Za-z0-9+/]*={0,2}$", }, "idempotency_key": _IDEMPOTENCY_KEY_INPUT, - "summary": _ASCII_PACKET_TEXT, - "contributor_attestation": _ASCII_PACKET_TEXT, - "predecessor_submission_id": _UUID_INPUT, - "revision_preparation_id": _UUID_INPUT, - "revision_preparation_sha256": _SHA256_INPUT, + "feedback": _SUBMISSION_FEEDBACK_TEXT, }, "required": ["task_id", "assignment_id", "zip_base64", "idempotency_key"], - "allOf": [ - { - "if": {"required": ["predecessor_submission_id"]}, - "then": {"required": ["revision_preparation_id", "revision_preparation_sha256"]}, - }, - { - "if": {"required": ["revision_preparation_id"]}, - "then": {"required": ["revision_preparation_sha256", "predecessor_submission_id"]}, - }, - { - "if": {"required": ["revision_preparation_sha256"]}, - "then": {"required": ["revision_preparation_id", "predecessor_submission_id"]}, - }, - ], "additionalProperties": False, }, "task_submissions_list": { @@ -1498,7 +1500,7 @@ def task_execution_output_schema(name: str) -> dict[str, Any]: """Load one reviewed task/submission response or the bounded binary projection.""" if name not in TASK_EXECUTION_INPUT_SCHEMAS: raise ContractError("unknown task execution contract") - if name == "task_guide_document_content_get": + if name in {"task_guide_document_content_get", "project_contributor_guide_document_get"}: return GUIDE_DOCUMENT_CONTENT_OUTPUT_SCHEMA return _contract_output_schema(name) diff --git a/mcp_server/workstream_mcp/tools/task_execution.py b/mcp_server/workstream_mcp/tools/task_execution.py index e405faf51..3e66cca03 100644 --- a/mcp_server/workstream_mcp/tools/task_execution.py +++ b/mcp_server/workstream_mcp/tools/task_execution.py @@ -14,9 +14,9 @@ ) from mcp.types import CallToolResult, ContentBlock, TextContent, Tool, ToolAnnotations -from workstream_mcp.errors import adapter_failure +from workstream_mcp.errors import SafeFailure, adapter_failure from workstream_mcp.http_gateway import WorkstreamGateway -from workstream_mcp.limits import SUBMISSION_BUNDLE_MAX_BYTES +from workstream_mcp.limits import SUBMISSION_BUNDLE_MAX_BASE64_CHARS, SUBMISSION_BUNDLE_MAX_BYTES from workstream_mcp.schemas import ( TASK_EXECUTION_INPUT_SCHEMAS, task_execution_output_schema, @@ -31,12 +31,24 @@ "task_release": "Release one screened task to the contributor queue.", "task_claim": "Claim and start one ready task atomically.", "task_work_context_get": "Read the current contributor work context for one task.", - "task_guide_document_content_get": "Read one assigned guide document as bounded bytes.", + "task_assignment_get": "Read your exact assignment status, feedback and earned evidence.", + "project_contributor_guide_get": ( + "Read the project's approved guide before claiming a task." + ), + "project_contributor_guide_document_get": ( + "Read one approved project guide original as bounded bytes." + ), + "task_guide_document_content_get": ( + "Read one ready or assigned task's locked guide original as bounded bytes." + ), "submission_operation_get": ( "Read one authorized submission operation by operation ID or your idempotency key; " "never resubmits." ), - "submission_create": "Upload one ZIP for initial checks and durable evaluation acceptance.", + "submission_create": ( + "Submit one base64 ZIP for initial work or revision. The MCP limit is 64 MiB " + "of raw ZIP bytes. A project can set a lower limit." + ), "task_submissions_list": "List the current contributor's submissions for one task.", "submission_get": "Read one submission visible to the current contributor.", "management_task_submissions_list": "List submissions for one managed project task.", @@ -94,11 +106,19 @@ def _decode_bundle(arguments: dict[str, Any]) -> bytes | None: content = base64.b64decode(encoded, validate=True) except (ValueError, binascii.Error): return None - if not content or len(content) > SUBMISSION_BUNDLE_MAX_BYTES: + if not content: return None return content +def _oversize_bundle() -> CallToolResult: + return SafeFailure( + "submission_archive_limit_exceeded", status=413, + message=("MCP accepts ZIPs up to 64 MiB of raw bytes. The CLI accepts up to 500 MiB. " + "Project limits also apply."), + ).result() + + async def invoke( gateway: WorkstreamGateway, tool_name: str, @@ -109,6 +129,10 @@ async def invoke( if tool_name not in TOOL_NAMES: return adapter_failure("unknown_tool", status=404) name = tool_name.removeprefix("workstream_") + if name == "submission_create": + encoded = arguments.get("zip_base64") + if isinstance(encoded, str) and len(encoded) > SUBMISSION_BUNDLE_MAX_BASE64_CHARS: + return _oversize_bundle() try: _INPUT_VALIDATORS[name].validate(arguments) except ValidationError: @@ -118,7 +142,11 @@ async def invoke( if name == "submission_create": upload = _decode_bundle(arguments) if upload is None: - return adapter_failure("invalid_tool_input", status=400) + return SafeFailure( + "invalid_tool_input", status=400, message="ZIP input must be nonempty base64", + ).result() + if len(upload) > SUBMISSION_BUNDLE_MAX_BYTES: + return _oversize_bundle() outcome = await gateway.task_execution_operation( name, bearer, @@ -127,7 +155,10 @@ async def invoke( upload=upload, ) if outcome.failure is not None: - return outcome.failure.result() + result = outcome.failure.result() + if outcome.failure.details is not None: + result.content.insert(0, TextContent(type="text", text=_UNTRUSTED_DATA_NOTICE)) + return result data = outcome.data or {} content: list[ContentBlock] = [ TextContent(type="text", text=json.dumps(data, separators=(",", ":"))) From 9efd2c017fd28941164af382ab5d72d788ad8abe Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:04:50 +0100 Subject: [PATCH 351/513] Reconcile contributor capability and action inventories --- backend/tests/authorization/test_catalogue.py | 2 +- docs/roadmap_status.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/backend/tests/authorization/test_catalogue.py b/backend/tests/authorization/test_catalogue.py index 5ef8c5b59..4e41939b7 100644 --- a/backend/tests/authorization/test_catalogue.py +++ b/backend/tests/authorization/test_catalogue.py @@ -118,7 +118,7 @@ def test_closed_permission_and_action_catalogue_is_exact_and_non_executable() -> } assert all(not owner.value.startswith("WS-REV-") for owner in ActionOwner) assert Counter(definition.availability for definition in ACTION_DEFINITIONS) == { - ActionAvailability.ACTIVE: 171, + ActionAvailability.ACTIVE: 173, ActionAvailability.PLANNED: 24, } assert ( diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 228bbf28b..b49eb1b71 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -685,14 +685,14 @@ cannot be reused as post-submission review-gate evidence. See the | Project Guide source custody | **Live foundation** | Guide creation declares documents and task examples; public document upload; immutable internal metadata snapshots; draft guide and review/revision policy writes with fresh-authorized exact replay of original receipts; exact run-scoped setup reads and assigned-task locked-original reads; S3-backed originals and isolated agent document inspection; exact document generation through separate manager approvals and public exact-authorized CP07 activation; Project Manager guide list, guide detail, activation readiness dry run and verified original read-back (PILOT-READ-3); the CLI exposes existing administrative active-chain and retained sufficiency/artifact-policy reads, keyed human sufficiency writes, and separate manual artifact-policy draft create/update with backend-owned policy decisions | Hosted original upload/read-back, task examples and Celery inference are proven. The current guide has independent human attachments, separate approvals and activation; earlier guide approvals remain retained history. Complete reader/isolation and contribution-journey scenarios; manual drafts are not compiled activation proposals and deployed CLI remains separate | | Unified Project Guide compilation | **Live setup and manager proposal operations** | Upload commits custody only; an explicit exact-project PM request selects assistance (`/setup`) or provider-free uploaded manager rules (`/requirements/compile`) and dispatches one immutable attempt through Celery; complete result and crash/recovery custody; distinct pre/post proposals; typed per-requirement classification and checker specifications; deterministic sufficiency and submission-artifact-policy projections; immutable authorized setup finalization; public exact manager review, pre-submit approval and manual correction dispatch; automatic deterministic post-policy derivation, public complete policy read, separate approval and shared correction custody. Neutral read/search tools support statically registered OpenAI Agents SDK and OmniCoreAgent adapters in mutually exclusive inference images, while provider-free `manager_authored` compiles a manager-uploaded rules document with no inference or provider resources ([runtime initiative](../.commitrail/initiatives/WS-AGENT-001/OVERVIEW.md), [manager-authored record](../.commitrail/changes/manager-authored-guide-runtime.md)). Inference attempts snapshot an exact immutable model profile and use the shared project-funded proxy; fixed document-tool limits must fit that profile and provider credentials remain outside the setup process. PR #697 supplies a source-sufficient proposal even without registered implementations; retained prior results keep exact hashes and reads and cannot execute through a compatibility path. Exact Omni SDK, mutually exclusive release-image, parser-isolation and real-MinIO proofs pass. Both inference adapters pass the same original-guide public API, durable Celery, real-parser and MinIO path; the Omni run stopped at a warning-ready manager draft with no bindings, approval or activation. The Terminal Systems handoff has project-owned PRE and POST implementations. POST uses the shared bounded model session, isolated trial capability and approved revision material. PR #697 removes registry, image and runtime choices from model input and output; human-selected phase attachments are validated at approval. Initial setup receives assigned guide documents and task examples only, apart from trusted system instructions. Explicit corrections additionally receive the PM's bounded written feedback, without prior proposals or image selections. Project semantics remain outside the generic Rust service. The [checker implementation](../pilots/terminal_systems/checkers/README.md) separates rule, service-image, storage and trial qualification. | Historical source-only setup and explicit PM correction are live-proven. Hosted Garden uploads prove no implicit request or model effects; explicit provider-free compilation/replay, separate approvals/activation, task claim and real PRE failure/replay are proven without a Submission. Optional inference-request deployment and committed-request recovery remain separate; the live Garden v3 drill separately verified the open PR current head and trusted CI under an explicit zero-GitHub-approval configuration, then accepted one Submission with an earned 100 FLOW award. Earlier guides and tasks retain their original locks. Controlled composition alone establishes no live GitHub or review fact. [Garden evidence](reports/garden-hosted-drill-2026-11-06.md). Guide 28 suggestions were independently mapped by the manager to one external PRE and POST image; separate approvals/activation led to the small task's accepted v2 and public contribution. Earlier guide 25/26 evidence remains retained. [Current checkpoint](reports/terminal-systems-hosted-drill-2026-10-27.md). | | Contribution policy administration | **Public Finance policy workflow; binding administration internal** | Internal Finance Authority adapter-binding lifecycle; public ContributionPolicy discovery/read/create/update/publish/retire with exact Finance Authority and recoverable draft selectors, and a Finance list of every version (PILOT-READ-3); immutable operation and event history; internal exact selected-version validation; CP07 binding with live exact-project manager authority of the selected published version to the active guide generation | The bounded local drill and hosted unpaid-policy publication/read-back passed. Remaining policy branches and complete contribution effects need qualification; publication alone creates no contribution | -| Task readiness and claim | **Foundation with grant-backed manager and contributor commands** | Task records, assignments and locked work context; guide-bound ContributionPolicyVersion locked before `READY` and copied to TaskAssignment; detached project/guide display; public project-scoped ready, management and operational queues with distinct current grant authority and signed bounded live pagination, with typed task status and manager filters by status, assignee, native import batch and update time (PILOT-READ-2); contributor cross-project own-assignment, attempt and summary reads under current Submitter grants (PILOT-READ-2); Project Manager project-wide attempt, claim, summary and import-batch reads (PILOT-READ-3); public contributor/management detail with exact project and assignment authority; separate current live work-context projections with exact receipt-selected review/revision/ContributionPolicy identities and no obsolete economic fields; explicit management/operational/audit locked-context projections using one historical resolver, with separate public manager, system-Operator and Audit Authority access; immutable contributor/management requirements using one historical translator, with public exact Contributor and Manager authority; the CLI exposes the three exact manager requirements/context reads separately from contributor commands (WS-CLI-001-27); bounded public Audit Authority lifecycle evidence with atomic project/task scoping and exact transition references; separate CLI audit commands consume those two existing Audit Authority GETs with explicit continuation; public manager create/screen/release use exact covered Project Manager authority, atomic audit and replay; claim/contributor context use exact-project Submitter grants; ready and own-assignment context list exact locked originals and `task.guide.read` verifies each download before delivery; separate manager context; durable claim retry receipts with fresh authority and exact assignment checks; hidden exact-assignment invalidation with committed cause verification, delivery fencing, exact fixed-service authority and decision-bound immutable release evidence; atomic authority-loss publication and registered prefork delivery; PILOT-14 exposes both locked contribution types in ready rows and Contributor detail for active exact-project Submitters or Reviewers as unpaid or exact instrument/unit/quantity awards, without Finance binding facts; claim remain Submitter-only | The bounded local journey passed; hosted import, screening, release, immediate claim and exact Claim replay passed for queue recovery. Complete the remaining authority/recovery matrix and contribution journey | +| Task readiness and claim | **Foundation with grant-backed manager and contributor commands** | Task records, assignments and locked work context; guide-bound ContributionPolicyVersion locked before `READY` and copied to TaskAssignment; detached project/guide display; public project-scoped ready, management and operational queues with distinct current grant authority and signed bounded live pagination, with typed task status and manager filters by status, assignee, native import batch and update time (PILOT-READ-2); contributor cross-project own-assignment, attempt and summary reads under current Submitter grants (PILOT-READ-2); Project Manager project-wide attempt, claim, summary and import-batch reads (PILOT-READ-3); public contributor/management detail with exact project and assignment authority; PR #708 adds approved project originals before claim and an exact own-assignment status, feedback and evidence read; separate current live work-context projections with exact receipt-selected review/revision/ContributionPolicy identities and no obsolete economic fields; explicit management/operational/audit locked-context projections using one historical resolver, with separate public manager, system-Operator and Audit Authority access; immutable contributor/management requirements using one historical translator, with public exact Contributor and Manager authority; the CLI exposes the three exact manager requirements/context reads separately from contributor commands (WS-CLI-001-27); bounded public Audit Authority lifecycle evidence with atomic project/task scoping and exact transition references; separate CLI audit commands consume those two existing Audit Authority GETs with explicit continuation; public manager create/screen/release use exact covered Project Manager authority, atomic audit and replay; claim/contributor context use exact-project Submitter grants; ready and own-assignment context list exact locked originals and `task.guide.read` verifies each download before delivery; separate manager context; durable claim retry receipts with fresh authority and exact assignment checks; hidden exact-assignment invalidation with committed cause verification, delivery fencing, exact fixed-service authority and decision-bound immutable release evidence; atomic authority-loss publication and registered prefork delivery; PILOT-14 exposes both locked contribution types in ready rows and Contributor detail for active exact-project Submitters or Reviewers as unpaid or exact instrument/unit/quantity awards, without Finance binding facts; claim remain Submitter-only | The bounded local journey passed; hosted import, screening, release, immediate claim and exact Claim replay passed for queue recovery. Complete the remaining authority/recovery matrix and contribution journey | | Operator task CLI | **Existing public task operations consumed by the CLI** | The Operator CLI provides separate status-only project pages and exact-project locked-reference reads. Backend Operator authority, assignment consistency, locked lineage and audit remain decisive. Claim starts contributor work atomically; there is no Operator start command. | Native public-API proof is bounded to existing fixtures; hosted/deployed operation, other Operator workflows and published binary remain separate | | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent | | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS | | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate | -| Contributor artifact preparation | **Public initial and checker-remediation entry** | One outer ZIP up to 500 MiB through the published preparation route (MCP transport: 64 MiB); scratch reservations grow before writes from counted bytes plus bounded headroom; unreadable or structurally rejected ZIPs return sanitized non-retryable 422 feedback before PRE reservation or durable effects; bounded scratch inspection; canonical manifest; shared evaluation-content capacity and exact locked-policy checks before attempts or durable intent; platform and project prechecks; unchanged-work rejection; durable put intent; verification; capacity-charged ready admission; final handoff validates the exact activated historical guide through owner ports; same-key ready replay does not repeat checker or PUT. The preparing contributor reads back their own preparations with outcome, storage state, finding counts and intake findings (PILOT-READ-2); a Project Manager lists a project's preparations with finding counts only (PILOT-READ-3). CLI preparation, read-back, creation/replay and history consume these public owners | Bounded local API/CLI journeys and hosted PRE rejection, lost-response recovery, ready admission and exact replay passed. Hosted CLI/MCP preparation, creation and replay passed in the [fresh resource-qualified journey](reports/managed-mcp-hosted-2026-11-07.md#sealed-size-resource-qualification-and-fresh-hosted-journey). Complete remaining intake negatives, isolation and interruption scenarios | +| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | Qualify the combined CLI/MCP submitter journey against the updated trusted intake image and dedicated workers. Preserve rejection, correction, replay and closed-assignment evidence. | | Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. Remaining gates are native fault, isolation, capacity and maximum-input qualification, qualified AWS admission activation and deployed API/consumer cutover. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. | -| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Complete the connected native public journey, AWS exact-version qualification, hosted cutover and final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. | +| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Complete the connected native public journey, AWS exact-version qualification, hosted cutover and final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. | | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. The bounded local public API/Celery drill passed both branches, prefork Celery process restart and late authority revocation | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate | | Operator uncertain-delivery CLI | **Existing public delivery routes consumed by explicit CLI commands** | WS-CLI-001-40 adds one project-bound page of finalized UNKNOWN deliveries and a deliberate reasoned, UUID-keyed reconciliation of one exact event. Fresh backend authority and classification remain decisive; a page never authorizes a later write. | Native signed PostgreSQL proof is scoped to an owner-produced source; a hosted interruption and deployed CLI remain unproven | | Review queue and lease | **Hidden persistence foundation** | Queue/admission idempotency and ReviewLease/preference persistence; complete unavailable REV action/principal catalogue and typed AUTH contracts; ART-07A1 metadata-only packet contract and REV-03B immutable normalized packet persistence with live ingest custody; REV-04A Review/finding/resolution and completed request storage | Future resolver proof; canonical admission from `allow_review`; claim/lease/packet authority; lease copies the Submission-stamped policy version with no CON lookup | From bf28fd6a43f5c5e366c1706ee27637616bb47936 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:09:46 +0100 Subject: [PATCH 352/513] Run the native contributor probe through the simplified ZIP and assignment reads --- .../artifacts/intake/foreground_admission.py | 3 +- .../artifacts/intake/foreground_command.py | 7 ++ .../test_revision_capacity.py | 14 ++- backend/tests/tasks/test_guide_documents.py | 14 +++ .../tasks/test_public_submission_intake.py | 8 ++ .../integration/test_task_context_http.py | 2 - .../public_hosted_model_post.py | 12 +-- .../public_intake_trials.py | 3 +- .../public_probe_support.py | 20 +++- .../public_runtime_trials.py | 9 +- .../run_public_journey_probe.py | 97 +++++++++---------- scripts/test_public_hosted_model_post.py | 7 +- 12 files changed, 121 insertions(+), 75 deletions(-) diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py index 805a9613b..2b6e6f427 100644 --- a/backend/app/modules/artifacts/intake/foreground_admission.py +++ b/backend/app/modules/artifacts/intake/foreground_admission.py @@ -495,7 +495,8 @@ async def replay_failure( code = row.failure_code if row.failure_code in { "submission_packet_invalid", "submission_archive_limit_exceeded", "submission_upload_timeout", "submission_infrastructure_unavailable", "revision_deadline_expired", - "submission_unavailable", + "submission_unavailable", "revision_limit_reached", "revision_context_changed", + "revision_context_blocked", "task_submission_predecessor_changed", } else "submission_operation_terminal" failure = SubmissionIntakeFailure(code) # Commit the current read authorization before returning QC feedback. diff --git a/backend/app/modules/artifacts/intake/foreground_command.py b/backend/app/modules/artifacts/intake/foreground_command.py index 1e218403f..6fa10f181 100644 --- a/backend/app/modules/artifacts/intake/foreground_command.py +++ b/backend/app/modules/artifacts/intake/foreground_command.py @@ -27,6 +27,7 @@ SelectedPreSubmitReservationFacts, SelectedPreSubmitRuntimeProfile, ) from app.modules.outbox.api import OutboxAppendPort +from app.modules.tasks.api.submission_context import TaskSubmissionContextUnavailable logger = logging.getLogger(__name__) @@ -110,6 +111,12 @@ async def run(_operation_id, _lease_id, _generation): code = exc.code if code == "pre_submission_checker_failed": state = "rejected" + elif isinstance(exc, TaskSubmissionContextUnavailable): + code = exc.code if exc.code in { + "revision_context_changed", "revision_context_blocked", + "revision_deadline_expired", "revision_limit_reached", + "task_submission_predecessor_changed", + } else "submission_unavailable" elif isinstance(exc, ArtifactLimitExceededError): code = "submission_archive_limit_exceeded" elif isinstance(exc, ArtifactInputMismatchError): diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index cfdc458d8..641ddabd2 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -351,11 +351,12 @@ async def test_rebase_retains_original_attempt_and_selects_current_terms( from app.modules.tasks.revision.models import TaskRevisionPreparation from tests.tasks.post_submit_routing.support import activate_successor_guide - async with remediation_source(tmp_path, isolated_database_env) as h: + async with remediation_source(tmp_path, isolated_database_env, contribution_awards=("money",)) as h: async with h.factory() as session: original = await session.scalar(text( "SELECT to_jsonb(s)-ARRAY['attempt_status','status_reason','decided_at','updated_at'] FROM public.submissions s WHERE id=:id" ), {"id": h.created.submission_id}) + old_policy_id = original["contribution_policy_version_id"] retained_run = await session.scalar(text( "SELECT to_jsonb(r) FROM public.checker_runs r WHERE id=:id" ), {"id": h.result.attempt_id}) @@ -386,6 +387,14 @@ async def test_rebase_retains_original_attempt_and_selects_current_terms( assert view["preparation_id"] == str(h.revision_preparation_id) assert view["outcome"] == "rebased" and view["disposition"] == "ready" assert "contribution" in {change["component"] for change in view["changes"]} + status = await client.get(f"/api/v1/tasks/{h.request.task_id}/assignments/{h.request.assignment_id}") + assert status.status_code == 200, status.text + context = status.json() + assert context["current_status"] == "needs_revision" and context["next_action"] == "revise" + assert context["assignment"]["compensation"]["accepted_submission"] == "unpaid" + assert context["feedback_submission_id"] == str(h.created.submission_id) + assert any(finding["worker_message"] and finding["status"] == "failed" + for finding in context["post_submission_results"]) data = revision_archive(h.data) settings, errors, calls = await _revision_http_runtime(h, client, tmp_path, monkeypatch, data) route = f"/api/v1/tasks/{h.request.task_id}/submissions" @@ -424,6 +433,7 @@ async def test_rebase_retains_original_attempt_and_selects_current_terms( assert selected.command_metadata["revision_preparation_sha256"] == h.revision_preparation_sha256 submission = await session.get(Submission, submission_id) assert str(submission.contribution_policy_version_id) == str(assignment.submitter_contribution_policy_version_id) + assert str(submission.contribution_policy_version_id) != old_policy_id async with h.factory() as session: assert await session.scalar(text( @@ -454,7 +464,7 @@ async def test_pm_recovers_retained_source_and_repairs_without_resetting_window( from app.modules.tasks.revision.models import TaskRevisionPreparation from tests.tasks.post_submit_routing.support import activate_successor_guide - async with remediation_source(tmp_path, isolated_database_env) as h: + async with remediation_source(tmp_path, isolated_database_env, contribution_awards=("money",)) as h: source_id = await _fixture_revision_context(h) async with h.factory() as session: original = await session.get(TaskRevisionPreparation, h.revision_preparation_id) diff --git a/backend/tests/tasks/test_guide_documents.py b/backend/tests/tasks/test_guide_documents.py index 50ae92c35..ceb64b4be 100644 --- a/backend/tests/tasks/test_guide_documents.py +++ b/backend/tests/tasks/test_guide_documents.py @@ -110,6 +110,20 @@ async def test_approved_guide_and_ready_task_originals_are_available_without_cla task = await create_ready_task(task_client, project) newer, newer_bytes = await activate_uploaded_guide(task_client, project, monkeypatch, version="v2") set_dev_actor(monkeypatch, roles="viewer", subject="guide-reader") + set_dev_actor(monkeypatch, roles="project_manager", subject="project-manager-subject") + created = await task_client.post( + f"/api/v1/projects/{project}/guides", headers=auth_headers(), + json={"version": "unapproved", "task_examples": [{"content": "Unapproved notes."}], + "documents": [{"label": "draft.md", "media_type": "text/markdown"}]}, + ) + assert created.status_code == 201, created.text + draft = created.json() + set_dev_actor(monkeypatch, roles="viewer", subject="guide-reader") + draft_path = f"{project_path}/{draft['id']}/documents/{draft['documents'][0]['document_id']}/content" + assert (await task_client.get(draft_path, headers=auth_headers())).status_code == 404 + assert (await task_client.get( + f"/api/v1/projects/{project}/guides/{draft['id']}", headers=auth_headers(), + )).status_code == 404 active = await task_client.get(project_path, headers=auth_headers()) assert active.status_code == 200 and active.json()["guide_id"] == newer["id"] refreshed = await task_client.get(active.json()["documents"][0]["read_reference"], headers=auth_headers()) diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index 4203db5d0..cd781e47b 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -153,6 +153,14 @@ async def test_public_malformed_zip_preserves_task_and_retains_cleanup_custody( assert any(item["source"] == "workstream_default" and item.get("failure_code") == "submission_archive_malformed" for item in results) assert not any(item["source"] == "project_external_checker" for item in results) + status = await client.get( + f"/api/v1/tasks/{f.task}/assignments/{f.assignment}", headers=f.access.target.headers, + ) + assert status.status_code == 200, status.text + assignment = status.json() + assert assignment["current_status"] == "in_progress" and assignment["next_action"] == "submit" + assert assignment["assignment"]["latest_submission"] is None + assert assignment["intake"]["pre_submission_results"] == results assert len(calls) == 1 and not errors, errors assert all(value not in response.text for value in ( "/tmp/", "s3://", "not-a-readable-zip", "BadZipFile", diff --git a/cli/tests/integration/test_task_context_http.py b/cli/tests/integration/test_task_context_http.py index bc58e2135..5256fec8f 100644 --- a/cli/tests/integration/test_task_context_http.py +++ b/cli/tests/integration/test_task_context_http.py @@ -143,11 +143,9 @@ "Guide version", "Policy schema version", "Merge algorithm version", - "Required packet fields", "Required artifacts", "Required evidence", "Forbidden artifacts", - "Attestation terms", "Manifest required", "Artifact hash required", "Artifact hash algorithm", diff --git a/experiments/pilot04_external_checker_runtime/public_hosted_model_post.py b/experiments/pilot04_external_checker_runtime/public_hosted_model_post.py index ba36bb748..d1eb0a647 100644 --- a/experiments/pilot04_external_checker_runtime/public_hosted_model_post.py +++ b/experiments/pilot04_external_checker_runtime/public_hosted_model_post.py @@ -469,11 +469,8 @@ async def run_model_post(attachment, client, factory, qualification): archive = fixture_archive() qualification.checkpoint(phase='task_started', task_id=task, assignment_id=assignment, archive_sha256=digest(archive), guide_setup=project.evidence) - summary = 'Synthetic model-only hosted qualification.' - attestation = 'rights_confirmed; no confidential data or credentials.' saved = await _submit(client, factory, task_id=task, assignment_id=assignment, - contributor_token=contributor_token, archive=archive, summary=summary, - attestation=attestation, predecessor_id=None) + contributor_token=contributor_token, archive=archive) qualification.checkpoint(phase='submission_created', submission=saved) async with factory() as session: dispatch = await session.get(SubmissionDispatch, saved['submission_id']) @@ -481,13 +478,12 @@ async def run_model_post(attachment, client, factory, qualification): event_id, run_id = dispatch.evaluation_event_id, dispatch.evaluation_attempt_id return await observe_model_post( attachment, client, factory, qualification, project=project, contributor=contributor, - task=task, assignment=assignment, archive=archive, summary=summary, - attestation=attestation, saved=saved, event_id=event_id, run_id=run_id, + task=task, assignment=assignment, archive=archive, saved=saved, event_id=event_id, run_id=run_id, ) async def observe_model_post(attachment, client, factory, qualification, *, project, - contributor, task, assignment, archive, summary, attestation, + contributor, task, assignment, archive, saved, event_id, run_id): """Qualify one exact public dispatch; this never creates or retries a run.""" import asyncio @@ -593,7 +589,7 @@ async def observe_model_post(attachment, client, factory, qualification, *, proj before = {str(identifier): await _outbox_snapshot(factory, identifier) for identifier in (event_id, completion)} from experiments.pilot04_external_checker_runtime.run_public_journey_probe import _replay_source_submission await _replay_source_submission(client, task, assignment, attachment.token_for_label('contributor'), - archive, summary, attestation, saved) + archive, saved) duplicate_tasks = [] for identifier in (event_id, completion): duplicate = await attachment.deliver_duplicate(identifier, project_id) diff --git a/experiments/pilot04_external_checker_runtime/public_intake_trials.py b/experiments/pilot04_external_checker_runtime/public_intake_trials.py index d33b24243..bbda44517 100644 --- a/experiments/pilot04_external_checker_runtime/public_intake_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_intake_trials.py @@ -203,8 +203,7 @@ async def public_intake_trials(client, factory, env, node_root: Path, *, stop_wo archive = archive_with_modes('evidence/results', project.project_id) route = f'/api/v1/tasks/{task}/submissions' headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, - 'X-Submission-Summary': 'Completed task evidence.', - 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} + } evidence, accepted = [], [] stop_worker() try: diff --git a/experiments/pilot04_external_checker_runtime/public_probe_support.py b/experiments/pilot04_external_checker_runtime/public_probe_support.py index 5258421b7..f3b5c1052 100644 --- a/experiments/pilot04_external_checker_runtime/public_probe_support.py +++ b/experiments/pilot04_external_checker_runtime/public_probe_support.py @@ -1,6 +1,7 @@ """Shared public drill operations; production API and durable owners retain authority.""" import asyncio +import hashlib from datetime import UTC, datetime from io import BytesIO from uuid import UUID, uuid4 @@ -174,7 +175,7 @@ async def _wait_outbox_acknowledged(factory, event_id: UUID, project_id: UUID) - async def _started_public_task(client, *, project_id: str, manager_token: str, - contributor_token: str, source_ref: str) -> tuple[str, str]: + contributor_token: str, source_ref: str, approved_guide: dict | None = None) -> tuple[str, str]: """Use public task creation and the claim which immediately starts work.""" from tests.test_tasks import complete_task_payload @@ -191,6 +192,23 @@ async def _started_public_task(client, *, project_id: str, manager_token: str, manager_token, 200, headers={"Idempotency-Key": str(uuid4())}, json={"reason": "Public first journey"}, ) + if approved_guide is not None: + locked = await _json(client, "GET", f"/api/v1/tasks/{task_id}/work-context", contributor_token, 200) + _require(not locked["lifecycle"]["assigned_to_current_actor"] + and locked["guide"]["id"] == approved_guide["guide_id"] + and [item["sha256"] for item in locked["guide_documents"]] + == [item["sha256"] for item in approved_guide["documents"]], + "the ready task did not disclose its exact originals before claim") + for guide_document, task_document in zip(approved_guide["documents"], locked["guide_documents"], strict=True): + project_guide = f"/api/v1/projects/{project_id}/contributor-guide/{approved_guide['guide_id']}" + task_guide = f"/api/v1/tasks/{task_id}/guide" + for prefix, document in ((project_guide, guide_document), (task_guide, task_document)): + path = f"{prefix}/documents/{UUID(document['document_id'])}/content" + _require(document["read_reference"] == path, "guide manifest returned a different download path") + response = await client.get(path, headers={"Authorization": f"Bearer {contributor_token}"}) + _require(response.status_code == 200 + and "sha256:" + hashlib.sha256(response.content).hexdigest() == document["sha256"], + "approved guide download did not match the retained original") claimed = await _json( client, "POST", f"/api/v1/tasks/{task_id}/claim", contributor_token, 200, headers={"Idempotency-Key": str(uuid4())}, diff --git a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py index 21308ca88..0538b6dd3 100644 --- a/experiments/pilot04_external_checker_runtime/public_runtime_trials.py +++ b/experiments/pilot04_external_checker_runtime/public_runtime_trials.py @@ -187,8 +187,7 @@ async def _remote_pre_launch_failure(client, factory, *, task, assignment, token _require(not await _trial_operation_ids(factory, task), 'launch trial task already has intake custody') route = f'/api/v1/tasks/{task}/submissions' headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, - 'X-Submission-Summary': 'Completed task evidence.', - 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} + } installed = await runner.command('project_fail_once') before = await runner.snapshot() key = str(uuid4()) @@ -274,8 +273,7 @@ async def public_runtime_trials(client, factory, env, root: Path, *, stop_worker manager_token=manager, contributor_token=token, source_ref='source-' + action) route = f'/api/v1/tasks/{task}/submissions' headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, - 'X-Submission-Summary': 'Completed task evidence.', - 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} + } control = await node_command(root, 'clear' if action == 'project_wait_failure' else action) start, key, began = len(trace_events(root)), str(uuid4()), time.monotonic() content = (_with_fixture_file(archive, 'runtime-wait.txt') @@ -318,8 +316,7 @@ async def _post_launch_trials(client, factory, project_id, manager, token, archi manager_token=manager, contributor_token=token, source_ref='post-' + action) route = f'/api/v1/tasks/{task}/submissions' headers = {'Content-Type': 'application/zip', 'X-Task-Assignment-Id': assignment, - 'X-Submission-Summary': 'Completed task evidence.', - 'X-Contributor-Attestation': 'rights_confirmed; no confidential data or credentials.'} + } stop_worker() try: key = str(uuid4()) diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 93e9d28a3..3a9ce4662 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -496,22 +496,14 @@ async def _wait_outbox_due(factory, event_id: UUID) -> None: raise RuntimeError("known safe outbox retry did not become due") -async def _source_headers(client, task_id, assignment_id, token, archive, summary, attestation, - predecessor_id=None): - """Bind original ZIP metadata and the exact current public revision acknowledgement.""" +def _source_headers(assignment_id, archive, key, feedback=None): + """Build the exact initial or revision wire inputs.""" headers = { "Content-Type": "application/zip", "Content-Length": str(len(archive)), - "X-Task-Assignment-Id": assignment_id, "Idempotency-Key": str(uuid4()), - "X-Submission-Summary": summary, "X-Contributor-Attestation": attestation, + "X-Task-Assignment-Id": assignment_id, "Idempotency-Key": key, } - if predecessor_id is not None: - detail = await _json(client, "GET", f"/api/v1/tasks/{task_id}/work-context", token, 200) - revision = detail["revision_context"] - _require(revision and revision["source_submission_id"] == predecessor_id, - "revision acknowledgement differs from the exact predecessor") - headers.update({"X-Predecessor-Submission-Id": predecessor_id, - "X-Revision-Preparation-Id": revision["preparation_id"], - "X-Revision-Preparation-Sha256": revision["preparation_sha256"]}) + if feedback is not None: + headers["X-Submission-Feedback"] = feedback return headers @@ -570,15 +562,9 @@ async def _await_finalized_source(client, factory, task_id, assignment_id, token raise RuntimeError("source finalization did not complete; no worker task was injected") -async def _replay_source_submission(client, task_id, assignment_id, token, archive, summary, - attestation, saved): - """Replay the original command once, including its original revision acknowledgement.""" - headers = {"Content-Type": "application/zip", "Content-Length": str(len(archive)), - "X-Task-Assignment-Id": assignment_id, "Idempotency-Key": saved["idempotency_key"], - "X-Submission-Summary": summary, "X-Contributor-Attestation": attestation} - if saved["predecessor_submission_id"] is not None: - headers["X-Predecessor-Submission-Id"] = saved["predecessor_submission_id"] - headers.update(saved["revision_acknowledgement"]) +async def _replay_source_submission(client, task_id, assignment_id, token, archive, saved): + """Replay the original command and let ART recover its frozen selection.""" + headers = _source_headers(assignment_id, archive, saved["idempotency_key"], saved["feedback"]) repeated = await _json(client, "POST", f"/api/v1/tasks/{task_id}/submissions", token, 202, headers=headers, content=archive) _require(repeated == dict(saved["acceptance_receipt"], replayed=True), @@ -586,21 +572,16 @@ async def _replay_source_submission(client, task_id, assignment_id, token, archi async def _submit(client, factory, *, task_id: str, assignment_id: str, - contributor_token: str, archive: bytes, summary: str, - attestation: str, predecessor_id: str | None) -> dict: - headers = await _source_headers(client, task_id, assignment_id, contributor_token, archive, - summary, attestation, predecessor_id) + contributor_token: str, archive: bytes, feedback: str | None = None) -> dict: + headers = _source_headers(assignment_id, archive, str(uuid4()), feedback) accepted = await _json(client, "POST", f"/api/v1/tasks/{task_id}/submissions", contributor_token, 202, headers=headers, content=archive) _require(accepted["task_id"] == task_id and accepted["assignment_id"] == assignment_id and accepted["status"] == "accepted" and accepted["replayed"] is False and accepted["pre_submission_results"], "raw ZIP command returned an invalid accepted receipt") context = {"operation_id": accepted["operation_id"], "acceptance_receipt": accepted, - "idempotency_key": headers["Idempotency-Key"], "predecessor_submission_id": predecessor_id, - "revision_acknowledgement": {name: value for name, value in headers.items() - if name.startswith("X-Revision-")}} - await _replay_source_submission(client, task_id, assignment_id, contributor_token, archive, - summary, attestation, context) + "idempotency_key": headers["Idempotency-Key"], "feedback": feedback} + await _replay_source_submission(client, task_id, assignment_id, contributor_token, archive, context) return context | await _await_finalized_source( client, factory, task_id, assignment_id, contributor_token, context, archive) @@ -787,7 +768,7 @@ async def _assert_outcome(factory, *, guide_source, project_id: UUID, task_id: s async def _late_revocation_trial(client, factory, env, *, project_id: UUID, accepted_task_id: str, manager_token: str, contributor_token: str, operator_id: UUID, - archive: bytes, summary: str, attestation: str, + archive: bytes, stop_worker: Callable[[], None], start_worker: Callable[[], Awaitable[None]]) -> dict: """Revoke routing authority after real POST I/O and a known non-live retry.""" @@ -810,7 +791,6 @@ async def _late_revocation_trial(client, factory, env, *, project_id: UUID, client, factory, task_id=task_id, assignment_id=assignment_id, contributor_token=contributor_token, archive=_with_fixture_file(archive, "late-revocation-trial.txt"), - summary=summary, attestation=attestation, predecessor_id=None, ) attempt_id, completion_id = await _complete_post( factory, submission_id=saved["submission_id"], project_id=project_id, @@ -885,17 +865,17 @@ async def _one_mode(client, factory, env, *, client, factory, env, human_review_required=human_review_required, ) project_id = str(compilation.project_id) + approved_guide = await _json( + client, "GET", f"/api/v1/projects/{project_id}/contributor-guide", contributor_token, 200, + ) + _require(approved_guide["guide_id"] == str(compilation.guide_id) + and approved_guide["documents"], "preclaim project guide does not match the approved originals") task_id, assignment_id = await _started_public_task( client, project_id=project_id, manager_token=manager_token, - contributor_token=contributor_token, source_ref="local-ticket-1", + contributor_token=contributor_token, source_ref="local-ticket-1", approved_guide=approved_guide, ) archive = archive_with_modes("evidence/results", compilation.project_id) - summary = "Completed the governed task with required evidence." - attestation = ( - "I confirm no confidential client data, credentials, or copied source " - "material is included in this submission; rights_confirmed." - ) bad = await _json( client, "POST", f"/api/v1/tasks/{task_id}/submissions", contributor_token, 422, @@ -903,8 +883,6 @@ async def _one_mode(client, factory, env, *, "Content-Type": "application/zip", "X-Task-Assignment-Id": assignment_id, "Idempotency-Key": str(uuid4()), - "X-Submission-Summary": summary, - "X-Contributor-Attestation": attestation, }, content=_secret_archive(archive), ) @@ -935,8 +913,6 @@ async def _one_mode(client, factory, env, *, "Content-Type": "application/zip", "X-Task-Assignment-Id": assignment_id, "Idempotency-Key": str(uuid4()), - "X-Submission-Summary": summary, - "X-Contributor-Attestation": attestation, }, content=_with_fixture_file(archive, "project-rejected.txt"), ) @@ -950,6 +926,13 @@ async def _one_mode(client, factory, env, *, and all(item.get("failure_code") is None for item in results if item["source"] == "workstream_default"), "public external PRE rejection did not preserve passing defaults") + status_path = f"/api/v1/tasks/{task_id}/assignments/{assignment_id}" + rejected = await _json(client, "GET", status_path, contributor_token, 200) + _require(rejected["current_status"] == "in_progress" + and rejected["assignment"]["latest_submission"] is None + and rejected["next_action"] == "submit" + and rejected["intake"]["pre_submission_results"] == results, + "the exact assignment lost its rejected ZIP feedback") async with factory() as session: _require(await session.scalar(select(func.count()).select_from(Submission).where( Submission.task_id == task_id @@ -968,8 +951,7 @@ async def fail_post_launch(): try: saved = await _submit( client, factory, task_id=task_id, assignment_id=assignment_id, - contributor_token=contributor_token, archive=first_archive, - summary=summary, attestation=attestation, predecessor_id=None) + contributor_token=contributor_token, archive=first_archive) if inject_post_fault: await fail_post_launch() finally: @@ -1001,13 +983,19 @@ async def fail_post_launch(): task_id=task_id, submission_id=first_submission_id, attempt_id=first_attempt_id, ) + revision = await _json(client, "GET", status_path, contributor_token, 200) + _require(revision["current_status"] == "needs_revision" + and revision["next_action"] == "revise" + and revision["feedback_submission_id"] == first_submission_id + and any(finding["worker_message"] and finding["status"] == "failed" + for finding in revision["post_submission_results"]), + "the exact assignment lost its governed revision feedback") replacement_archive = revision_archive(archive) saved = await _submit( client, factory, task_id=task_id, assignment_id=assignment_id, contributor_token=contributor_token, - archive=replacement_archive, summary=summary, - attestation=attestation, predecessor_id=first_submission_id, - ) + archive=replacement_archive, + ) expected_inputs[saved["submission_id"]] = _fixture_hashes(replacement_archive) _require(saved["submission_version"] == 2, "public checker remediation did not create version 2") @@ -1062,6 +1050,17 @@ async def fail_post_launch(): and [(award["instrument"], award["unit"], Decimal(award["quantity"])) for award in item["awards"]] == ([("project_points", "PTS", Decimal("7"))] if awards else []), "public contribution source or award set differs") + final_status = await _json(client, "GET", status_path, contributor_token, 200) + if human_review_required: + _require(final_status["current_status"] == "review_pending" and final_status["accepted_evidence"] is None, + "the exact assignment changed required human-review custody") + else: + evidence = final_status["accepted_evidence"] + _require(final_status["current_status"] == "accepted" and evidence + and evidence["submission_id"] == saved["submission_id"] + and evidence["artifact_hash"] == expected_inputs[saved["submission_id"]]["archive_sha256"] + and len(evidence["awards"]) == len(awards), + "the exact assignment differs from accepted artifact and award evidence") # Arm hosted task events before duplicate publication. The local fixture # has a result backend; neither path changes the production worker. before_delivery = await _outbox_snapshot(factory, completion_id) @@ -1098,7 +1097,7 @@ async def fail_post_launch(): client, factory, env, project_id=compilation.project_id, accepted_task_id=task_id, manager_token=manager_token, contributor_token=contributor_token, operator_id=operator_id, - archive=archive, summary=summary, attestation=attestation, + archive=archive, stop_worker=stop_worker, start_worker=start_worker, ) return { diff --git a/scripts/test_public_hosted_model_post.py b/scripts/test_public_hosted_model_post.py index a6f8c699f..1210f2f5f 100644 --- a/scripts/test_public_hosted_model_post.py +++ b/scripts/test_public_hosted_model_post.py @@ -162,7 +162,7 @@ def test_observation_refuses_a_run_from_another_project_task_or_submission(self) asyncio.run(observe_model_post( None, None, Mock(return_value=session), None, project=SimpleNamespace(project_id=project), contributor=None, - task=task, assignment=None, archive=b'', summary=None, attestation=None, + task=task, assignment=None, archive=b'', saved={'submission_id': submission}, event_id=new_record_id(), run_id=new_record_id(), )) request.assert_not_called() @@ -190,7 +190,7 @@ def test_observation_checks_real_policy_budget_with_float_settings(self): asyncio.run(observe_model_post( attachment, None, Mock(return_value=session), None, project=SimpleNamespace(project_id=project), contributor=None, - task=task, assignment=None, archive=b'', summary=None, attestation=None, + task=task, assignment=None, archive=b'', saved={'submission_id': submission}, event_id=new_record_id(), run_id=new_record_id(), )) @@ -516,8 +516,7 @@ async def respond(request): async def exercise(): async with httpx.AsyncClient(transport=httpx.MockTransport(respond), base_url='http://test') as client: return await probe._submit(client, None, task_id=task, assignment_id=assignment, - contributor_token='token', archive=b'raw-zip', summary='summary', - attestation='attestation', predecessor_id=None) + contributor_token='token', archive=b'raw-zip') with patch.object(probe, '_finalized_source_evidence', new=AsyncMock(return_value=graph)) as retained, \ patch.object(probe, '_fixture_hashes', return_value={'expected': 'hashes'}), \ From 24f06624909f45e3851f6ff97a61e91d988f14cb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:10:44 +0100 Subject: [PATCH 353/513] Keep native caller contract checks on the dedicated worker launcher --- scripts/test_public_hosted_model_post.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/test_public_hosted_model_post.py b/scripts/test_public_hosted_model_post.py index 1210f2f5f..67551efe9 100644 --- a/scripts/test_public_hosted_model_post.py +++ b/scripts/test_public_hosted_model_post.py @@ -577,7 +577,9 @@ def test_finalization_worker_is_exclusive_and_uses_production_app(self): from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe with patch.object(probe, '_process', return_value='owned') as launch: - process, _ = probe._start_finalization_worker({}, Path('/private/proof')) + process, _ = probe._start_worker( + {}, Path('/private/proof'), 'finalizer', 'workstream.submission_finalization', + ) self.assertEqual(process, 'owned') command = launch.call_args.args[0] self.assertEqual(command[command.index('-A') + 1], 'app.workers.celery_app') From a38dee4d15b9c9c2f106096d3e616ca158dbfb96 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:17:57 +0100 Subject: [PATCH 354/513] Persist contributor read authority and retain the historical upgrade drill --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 7 +- .../versions/0092_submission_feedback.py | 18 ++ .../test_submission_feedback_upgrade.py | 192 ++++++++++++++++++ backend/tests/test_alembic.py | 5 +- 4 files changed, 217 insertions(+), 5 deletions(-) create mode 100644 backend/tests/artifacts/test_submission_feedback_upgrade.py diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 35f5be797..908eb5fb2 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -45,9 +45,10 @@ work. Existing reward owners remain authoritative. - [ ] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits. - [ ] Combined public contributor journey proves correction, revision, replay, history and applicable existing awards on the integrated code. -Dedicated queue/consumer implementation and its real isolated scanner-to-T5 -regression are integrated; native caller conversion and deployed qualification -remain required. The managed-style adapter substitution passed through public +The submission, guide, assignment status, and CLI/MCP changes are implemented. +The dedicated queue topology, isolated scanner-to-T5 regression and native +caller conversion are integrated. Combined native execution and deployed +qualification remain open. The managed-style adapter substitution passed through public ZIP acceptance, retained source custody, real T5 owner delivery and replay; it does not establish a deployed managed provider or broker-consumer proof. diff --git a/backend/alembic/versions/0092_submission_feedback.py b/backend/alembic/versions/0092_submission_feedback.py index 8f6a3355c..c4864ef3f 100644 --- a/backend/alembic/versions/0092_submission_feedback.py +++ b/backend/alembic/versions/0092_submission_feedback.py @@ -21,6 +21,23 @@ def _replace(definition, before, after, *, expected=1): return definition.replace(before, after) +def _contributor_read_audit(): + name = "ck_audit_events_authorization_action_evidence" + definition = op.get_bind().execute(text( + "SELECT pg_catalog.pg_get_constraintdef(oid) FROM pg_catalog.pg_constraint " + "WHERE conrelid='public.audit_events'::regclass AND conname=:name" + ), {"name": name}).scalar_one() + anchor = ("(((action_id)::text = 'actor.assignment.list'::text) AND " + "((permission_id)::text = 'submission.read_own'::text))") + addition = "".join( + f" OR (((action_id)::text = '{action}'::text) AND ((permission_id)::text = 'submission.read_own'::text))" + for action in ("task.assignment.read", "project.contributor_guide.read") + ) + updated = _replace(definition, anchor, anchor + addition, expected=2) + op.execute(f"ALTER TABLE public.audit_events DROP CONSTRAINT {name}") + op.execute(f"ALTER TABLE public.audit_events ADD CONSTRAINT {name} {updated}") + + def _intake_guard(): definition = _definition("public.guard_submission_intake_mutation()") start = definition.index(" IF NOT (m ?& ARRAY") @@ -184,6 +201,7 @@ def upgrade() -> None: " IF o.eligible_task_status='in_progress' THEN", )) _submission_guards() + _contributor_read_audit() def downgrade() -> None: diff --git a/backend/tests/artifacts/test_submission_feedback_upgrade.py b/backend/tests/artifacts/test_submission_feedback_upgrade.py new file mode 100644 index 000000000..0d9d73e6b --- /dev/null +++ b/backend/tests/artifacts/test_submission_feedback_upgrade.py @@ -0,0 +1,192 @@ +"""Proof of the live 0091 writer handing its accepted command to the 0092 reader. + +Run this test from a 0091 checkout with the 0092 candidate backend path supplied +in WORKSTREAM_SUBMISSION_FEEDBACK_CANDIDATE. The candidate process uses the same +isolated PostgreSQL database and private local source as the predecessor. +""" + +import asyncio +import base64 +from dataclasses import asdict +from datetime import timedelta +import json +import os +from pathlib import Path +import subprocess +import sys +from types import SimpleNamespace +from uuid import UUID + +import pytest +from sqlalchemy import text +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.core.identifiers import new_record_id +from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionSourceCapacityLimits +from app.modules.artifacts.intake.repository import IntakeCustodyConflict +from app.modules.artifacts.service import ArtifactStorageNamespaceSpec +from app.modules.authorization.runtime import HumanAuthorizationContext +from tests.artifacts.test_submission_foreground_command import configure_source_http +from tests.artifacts.test_submission_intake_admission import ( + admin_access as admin_access, + admission_intake as admission_intake, + admit_new, + auth_database_env as auth_database_env, + clear_settings_cache as clear_settings_cache, + intake_admission, + rsa_signing_material as rsa_signing_material, + signed_access as signed_access, +) +from tests.retained_material_fixtures import finalize_retained_intake +from tests.test_artifact_admission import _local_store, _settings +from tests.test_trusted_intake import _archive + +_PREDECESSOR = "0091_qualified_aws_source" +_CANDIDATE = "0092_submission_feedback" +_CANDIDATE_ENV = "WORKSTREAM_SUBMISSION_FEEDBACK_CANDIDATE" +_FROZEN = text(""" + SELECT o.command_metadata,o.metadata_sha256,o.accepted_context_sha256,o.acceptance_receipt_sha256, + r.request_digest,r.terminal_digest,r.request_json->'default_context'->'packet' AS packet + FROM submission_intake_operations o + JOIN selected_pre_submit_runs r ON r.id=o.selected_pre_submit_run_id WHERE o.id=:id +""") +_AUDIT_CONSTRAINT = text(""" + SELECT pg_catalog.pg_get_constraintdef(oid) FROM pg_catalog.pg_constraint + WHERE conrelid='public.audit_events'::regclass AND conname='ck_audit_events_authorization_action_evidence' +""") +_ROW_IDENTITY = text(""" + SELECT ctid::text,xmin::text FROM submission_intake_operations WHERE id=:id +""") + + +def _candidate_command(candidate, args): + env = os.environ | {"PYTHONPATH": os.pathsep.join((str(candidate), str(candidate / "tests")))} + return subprocess.run([sys.executable, *args], cwd=candidate, env=env, + capture_output=True, text=True, check=False) + + +@pytest.mark.postgres_schema_contract +@pytest.mark.skipif(not os.environ.get(_CANDIDATE_ENV), reason="requires the predecessor and candidate checkouts") +async def test_feedback_upgrade_preserves_accepted_operation(admission_intake, tmp_path, monkeypatch): # noqa: F811 + candidate = Path(os.environ[_CANDIDATE_ENV]).resolve(strict=True) + f = admission_intake + async with f.factory() as session: + assert await session.scalar(text("SELECT version_num FROM alembic_version")) == _PREDECESSOR + route = f"/api/v1/tasks/{f.task}/submissions" + headers = f.access.target.headers | { + "Content-Type": "application/zip", "X-Task-Assignment-Id": str(f.assignment), + } + malformed = _archive("../escape") + client, _, errors, rejected_calls = await configure_source_http( + f.factory, f.access.signed.client, tmp_path, monkeypatch, malformed, "rejected", + ) + nonempty_key = str(new_record_id()) + rejected = await client.post(route, headers=headers | { + "Idempotency-Key": nonempty_key, "X-Submission-Summary": "Original retained text", + }, content=malformed) + assert rejected.status_code == 422 and len(rejected_calls) == 1 and not errors, rejected.text + + f.admission._capacity = SubmissionSourceCapacityLimits(maximum_total_bytes=4 * 1024**2) + receiving = await admit_new(f) + upgrade = ["-m", "alembic", "upgrade", _CANDIDATE] + refused = await asyncio.to_thread(_candidate_command, candidate, upgrade) + assert refused.returncode != 0 + assert "wait for active submission uploads and PRE checks to end" in refused.stderr, refused.stderr + async with f.factory() as session: + assert await session.scalar(text("SELECT version_num FROM alembic_version")) == _PREDECESSOR + assert await session.scalar(text(""" + SELECT count(*) FROM information_schema.columns + WHERE table_schema='public' AND table_name='submissions' AND column_name='feedback' + """)) == 0 + assert await f.admission.finish(receiving, state="failed", failure_code="submission_upload_timeout") + + payload = _archive() + client, _, errors, calls = await configure_source_http( + f.factory, client, tmp_path, monkeypatch, payload, "completed", + ) + key = str(new_record_id()) + accepted = await client.post(route, headers=headers | {"Idempotency-Key": key}, content=payload) + assert accepted.status_code == 202 and len(calls) == 1 and not errors, accepted.text + receipt = accepted.json() + operation = UUID(receipt["operation_id"]) + async with f.factory() as session: + frozen = (await session.execute(_FROZEN, {"id": operation})).mappings().one() + assert frozen["packet"] == {"summary": "", "contributor_attestation": ""} + row_identity = (await session.execute(_ROW_IDENTITY, {"id": operation})).one() + constraint = await session.scalar(_AUDIT_CONSTRAINT) + seed = tmp_path / "upgrade-seed.json" + seed.write_text(json.dumps({ + "actor": f.actor.model_dump(mode="json"), "task": str(f.task), "assignment": str(f.assignment), + "key": key, "nonempty_key": nonempty_key, "receipt": receipt, "namespace": asdict(f.namespace), + "frozen": dict(frozen), "data": base64.b64encode(payload).decode(), "directory": str(tmp_path), + "row_identity": list(row_identity), "audit_constraint": constraint, + })) + migrated = await asyncio.to_thread(_candidate_command, candidate, upgrade) + assert migrated.returncode == 0, migrated.stderr + checked = await asyncio.to_thread(_candidate_command, candidate, [str(Path(__file__).resolve()), str(seed)]) + assert checked.returncode == 0, checked.stderr + assert f"{_CANDIDATE}: accepted receipt, packet digest and one finalization verified" in checked.stdout + + +async def _verify_candidate(seed_path): + from app.modules.checkers.api.pre_submit_material import SubmissionPacketView + + seed = json.loads(seed_path.read_text()) + context = HumanAuthorizationContext.model_validate_json(json.dumps(seed["actor"])) + settings = _settings(Path(seed["directory"])) + namespace = ArtifactStorageNamespaceSpec(**seed["namespace"]) + engine = create_async_engine(os.environ["WORKSTREAM_DATABASE_URL"]) + factory = async_sessionmaker(engine, expire_on_commit=False) + bootstrap, store = _local_store(settings, namespace) + operation = UUID(seed["receipt"]["operation_id"]) + try: + async with factory() as session: + assert await session.scalar(text("SELECT version_num FROM alembic_version")) == _CANDIDATE + assert list((await session.execute(_ROW_IDENTITY, {"id": operation})).one()) == seed["row_identity"] + constraint = await session.scalar(_AUDIT_CONSTRAINT) + for action in ("task.assignment.read", "project.contributor_guide.read"): + added = (f" OR (((action_id)::text = '{action}'::text) AND " + "((permission_id)::text = 'submission.read_own'::text))") + assert constraint.count(added) == 2 + constraint = constraint.replace(added, "") + assert constraint == seed["audit_constraint"] + metadata = SubmissionIntakeMetadata(task_id=UUID(seed["task"]), assignment_id=UUID(seed["assignment"])) + admission = intake_admission(factory, context, namespace) + + async def body(): + yield base64.b64decode(seed["data"]) + + replay = await admission.replay( + metadata, body(), actor_id=context.actor_profile_id, idempotency_key=UUID(seed["key"]), + declared_raw_bytes=None, idle_timeout_seconds=1, replay_duration=timedelta(seconds=30), + ) + assert replay.acceptance_receipt == dict(seed["receipt"], replayed=True) + with pytest.raises(IntakeCustodyConflict, match="^submission_idempotency_conflict$"): + await admission.admit( + metadata, actor_id=context.actor_profile_id, identity_link_id=context.identity_link_id, + idempotency_key=UUID(seed["nonempty_key"]), declared_raw_bytes=None, + ) + submission_id = await finalize_retained_intake(factory, SimpleNamespace( + operation_id=operation, store=store, settings=settings, namespace=namespace, + )) + async with factory() as session: + frozen = (await session.execute(_FROZEN, {"id": operation})).mappings().one() + assert dict(frozen) == seed["frozen"] + stored = (await session.execute(text(""" + SELECT s.summary,s.worker_attestation,s.feedback, + public.submission_dispatch_valid(d),a.packet_sha256 + FROM submissions s JOIN submission_dispatches d ON d.submission_id=s.id + JOIN submission_bundle_admissions a ON a.id=s.submission_bundle_admission_id + WHERE s.id=:id + """), {"id": UUID(submission_id)})).one() + assert stored == ("", "", None, True, SubmissionPacketView("", "").sha256) + assert await session.scalar(text("SELECT count(*) FROM selected_pre_submit_runs")) == 2 + assert await session.scalar(text("SELECT count(*) FROM submissions")) == 1 + print(f"{_CANDIDATE}: accepted receipt, packet digest and one finalization verified") + finally: + bootstrap.close() + await engine.dispose() + + +if __name__ == "__main__": + asyncio.run(_verify_candidate(Path(sys.argv[1]))) diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 292d6a283..c18f04db5 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -430,6 +430,7 @@ def test_v01_graph_has_one_root_and_head() -> None: assert [revision.revision for revision in revisions] == [ HEAD_REVISION, + "0091_qualified_aws_source", "0090_merge_direct_storage", "0089_observed_upload_cleanup", "0088_unsealed_source_cleanup", @@ -525,7 +526,7 @@ def test_v01_graph_has_one_root_and_head() -> None: assert script.get_revision("0090_merge_direct_storage").down_revision == ( "0089_observed_upload_cleanup", "0069_remove_artifact_proof", ) - assert script.get_revision(HEAD_REVISION).down_revision == "0090_merge_direct_storage" + assert script.get_revision(HEAD_REVISION).down_revision == "0091_qualified_aws_source" assert revisions[-1].down_revision is None assert script.get_heads() == [HEAD_REVISION] @@ -557,7 +558,7 @@ async def definition(): before = await definition() assert before.count("o.provider_profile NOT IN ('local-v2','minio-v1')") == 1 assert before.count("WHEN 'minio-v1' THEN 's3' END") == 1 - await asyncio.to_thread(command.upgrade, _alembic_config(), HEAD_REVISION) + await asyncio.to_thread(command.upgrade, _alembic_config(), "0091_qualified_aws_source") after = await definition() expected = before.replace( "o.provider_profile NOT IN ('local-v2','minio-v1')", From ea75e5f337ecd81d2cd705f5301af6fa95e29beb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:18:46 +0100 Subject: [PATCH 355/513] Keep the two-checkout upgrade drill opt-in outside the full test suite --- .../submission_feedback_upgrade_drill.py} | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) rename backend/{tests/artifacts/test_submission_feedback_upgrade.py => scripts/submission_feedback_upgrade_drill.py} (96%) diff --git a/backend/tests/artifacts/test_submission_feedback_upgrade.py b/backend/scripts/submission_feedback_upgrade_drill.py similarity index 96% rename from backend/tests/artifacts/test_submission_feedback_upgrade.py rename to backend/scripts/submission_feedback_upgrade_drill.py index 0d9d73e6b..99a3a0142 100644 --- a/backend/tests/artifacts/test_submission_feedback_upgrade.py +++ b/backend/scripts/submission_feedback_upgrade_drill.py @@ -1,8 +1,8 @@ """Proof of the live 0091 writer handing its accepted command to the 0092 reader. -Run this test from a 0091 checkout with the 0092 candidate backend path supplied -in WORKSTREAM_SUBMISSION_FEEDBACK_CANDIDATE. The candidate process uses the same -isolated PostgreSQL database and private local source as the predecessor. +Invoke with pytest by explicitly naming this file. Use a 0091 checkout with the +0092 candidate backend path in WORKSTREAM_SUBMISSION_FEEDBACK_CANDIDATE. The +candidate uses the same isolated PostgreSQL database and private local source. """ import asyncio @@ -66,7 +66,6 @@ def _candidate_command(candidate, args): @pytest.mark.postgres_schema_contract -@pytest.mark.skipif(not os.environ.get(_CANDIDATE_ENV), reason="requires the predecessor and candidate checkouts") async def test_feedback_upgrade_preserves_accepted_operation(admission_intake, tmp_path, monkeypatch): # noqa: F811 candidate = Path(os.environ[_CANDIDATE_ENV]).resolve(strict=True) f = admission_intake From eb5f93de4b120f016c8343f77df4a5ed9d67fc90 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:19:11 +0100 Subject: [PATCH 356/513] Pin the owned PostgreSQL fingerprint for the exact read audit constraint --- backend/tests/conftest.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 1fe5d0660..2447172a9 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "acd8db80e9b59a12af629042a8f452a2c40bd31f7ed203a71d3f48ee04db9e52" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "03192dcee654b3e4322b2ed1bbbb7b45293008a156df7bbe750c1de2a26b6b7e" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", From a7fe4ec429921ab103637adf948339d71339fc5a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:21:34 +0100 Subject: [PATCH 357/513] Keep the upgrade drill with opt-in submission qualifications --- .../submission_feedback_upgrade_drill.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {backend/scripts => experiments/pilot04_external_checker_runtime}/submission_feedback_upgrade_drill.py (100%) diff --git a/backend/scripts/submission_feedback_upgrade_drill.py b/experiments/pilot04_external_checker_runtime/submission_feedback_upgrade_drill.py similarity index 100% rename from backend/scripts/submission_feedback_upgrade_drill.py rename to experiments/pilot04_external_checker_runtime/submission_feedback_upgrade_drill.py From 5fb60bef793306560fd77ea7f8c0bd64bd7fb788 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:24:56 +0100 Subject: [PATCH 358/513] Verify the exact contributor audit action and permission pairs in PostgreSQL --- .../tests/migrations/test_task_queue_authority.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/backend/tests/migrations/test_task_queue_authority.py b/backend/tests/migrations/test_task_queue_authority.py index 6b20fe527..7b4c0fce9 100644 --- a/backend/tests/migrations/test_task_queue_authority.py +++ b/backend/tests/migrations/test_task_queue_authority.py @@ -87,3 +87,17 @@ async def probe(): asyncio.run(probe()) else: asyncio.run(probe()) + + +async def test_contributor_read_audit_permission_pairs_are_closed(isolated_database_env): + """The head allows both exact pairs and rejects a substituted permission.""" + connection = await asyncpg.connect(isolated_database_env.replace("+asyncpg", "")) + try: + for action in ("task.assignment.read", "project.contributor_guide.read"): + for allowed in (False, True): + assert await insert(connection, action, "submission.read_own", allowed=allowed) + with pytest.raises(asyncpg.CheckViolationError) as failure: + await insert(connection, action, "project.read", allowed=allowed) + assert failure.value.constraint_name == CONSTRAINT + finally: + await connection.close() From 124695d5e71589a53cef34d52fff5d4c1bb95bf6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:33:39 +0100 Subject: [PATCH 359/513] Exercise the built CLI and installed MCP in the existing native contributor journey --- .../guide_compilation/proposals/pg_support.py | 5 +- .../README.md | 13 +- .../public_guide_setup.py | 12 +- .../public_probe_support.py | 12 +- .../public_submission_clients.py | 136 ++++++++++++++++++ .../run_public_journey_probe.py | 127 ++++++++++------ mcp_server/tests/integration/oauth_fixture.py | 46 +++++- .../tests/integration/test_profile_flow.py | 34 +---- 8 files changed, 294 insertions(+), 91 deletions(-) create mode 100644 experiments/pilot04_external_checker_runtime/public_submission_clients.py diff --git a/backend/tests/projects/guide_compilation/proposals/pg_support.py b/backend/tests/projects/guide_compilation/proposals/pg_support.py index 62a8f53d7..60935c6c5 100644 --- a/backend/tests/projects/guide_compilation/proposals/pg_support.py +++ b/backend/tests/projects/guide_compilation/proposals/pg_support.py @@ -370,7 +370,8 @@ async def no_model_session(_state, _context): async def seed_review_actor( - factory, project_id, *, actor=None, role="project_manager", scope="project" + factory, project_id, *, actor=None, role="project_manager", scope="project", + issuer="https://identity.flowresearch.tech", ): """Seed stored grant variants; request/approval authority guards remain enabled.""" from datetime import UTC, datetime @@ -394,7 +395,7 @@ async def seed_review_actor( ActorIdentityLink( id=str(actor.identity_link_id), actor_profile_id=str(actor.actor_profile_id), - issuer="https://identity.flowresearch.tech", + issuer=issuer, subject=str(actor.actor_profile_id), subject_kind="human", status="active", diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md index 21eddc342..00207e02c 100644 --- a/experiments/pilot04_external_checker_runtime/README.md +++ b/experiments/pilot04_external_checker_runtime/README.md @@ -143,6 +143,15 @@ the isolated upload key, plus the existing journey fixture's distinct `WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE`. Only the cleanup child receives that separate credential. +For the connected contributor proof, build the CLI and install the current +MCP wheel into its own environment. Pass both executable paths. The probe +uses the existing local HTTPS issuer and token-exchange fixture, and both +clients address the same public API while the dedicated workers process +submissions. The clean run receipt includes `connected_submitter_clients` +after guide download, PRE rejection, cross-client replay, POST revision, +resubmission, and final assignment reads complete. Hosted Flow Identity and +deployed service qualification remain separate. + ```sh PYTHONPATH=.:tests:.. .venv/bin/python scripts/run_isolated_tests.py \ --metadata-json /tmp/guide-journey-cleanup.json --timeout-seconds 1500 \ @@ -152,7 +161,9 @@ PYTHONPATH=.:tests:.. .venv/bin/python scripts/run_isolated_tests.py \ --node-config /absolute/private-node/service.json \ --expected-custody /absolute/private-node/custody.json \ --broker-url redis://127.0.0.1:/0 \ - --work-dir /absolute/private-guide-journey + --work-dir /absolute/private-guide-journey \ + --cli-executable /absolute/bin/workstream \ + --mcp-executable /absolute/mcp-wheel/bin/workstream-mcp ``` Use a new metadata path, work directory and private broker for each run. The diff --git a/experiments/pilot04_external_checker_runtime/public_guide_setup.py b/experiments/pilot04_external_checker_runtime/public_guide_setup.py index 75f9ecb59..5c9632cc1 100644 --- a/experiments/pilot04_external_checker_runtime/public_guide_setup.py +++ b/experiments/pilot04_external_checker_runtime/public_guide_setup.py @@ -46,14 +46,14 @@ async def _public_policy_settings(client, root, token, human_review_required, ca headers={**headers, "Idempotency-Key": str(uuid4())}, json=body) -async def _finance_policy(client, factory, project_id, token_for, compensated, call, attachment=None): +async def _finance_policy(client, factory, project_id, token_for, compensated, call, attachment, issuer): if attachment: await attachment.grant(client, 'finance', 'finance_authority', project_id) finance = attachment.actors['finance'] if compensated: raise AssertionError('hosted runtime fixture requires unpaid policy') else: - finance, _ = await seed_review_actor(factory, project_id, role="finance_authority") + finance, _ = await seed_review_actor(factory, project_id, role="finance_authority", issuer=issuer) token = token_for(finance) definitions = [] if compensated: @@ -201,7 +201,7 @@ async def _local_approval_attachments(factory): async def public_guide_setup(client, factory, human_review_required, call, token_for, *, - pre_requirements=1, attachment=None): + pre_requirements=1, attachment=None, issuer="https://identity.flowresearch.tech"): if pre_requirements != 1: raise ValueError("current qualification requires exactly one PRE image") model_post = attachment.model_post if attachment else None @@ -211,7 +211,7 @@ async def public_guide_setup(client, factory, human_review_required, call, token if attachment: manager = attachment.actors['manager'] else: - manager, _ = await seed_review_actor(factory, None, scope="system") + manager, _ = await seed_review_actor(factory, None, scope="system", issuer=issuer) token = token_for(manager) project = await call(client, "POST", "/api/v1/projects", token, 201, headers={"Idempotency-Key": str(uuid4())}, @@ -223,7 +223,7 @@ async def public_guide_setup(client, factory, human_review_required, call, token else: await seed_review_actor(factory, UUID(project["id"]), actor=manager) from guide_compilation_e2e import publish_scripted_model_profile - operator, _ = await seed_review_actor(factory, None, role="operator", scope="system") + operator, _ = await seed_review_actor(factory, None, role="operator", scope="system", issuer=issuer) profile = await publish_scripted_model_profile(client, token_for(operator), project["id"]) if (profile["spec"]["project_id"] != project["id"] or profile["spec"]["profile_version"] != 1): @@ -278,7 +278,7 @@ async def public_guide_setup(client, factory, human_review_required, call, token **attachments}) compilation_root = root + f"/compilations/{setup['finalized_compilation_id']}" await _finance_policy(client, factory, UUID(project["id"]), token_for, - not human_review_required and attachment is None, call, attachment) + not human_review_required and attachment is None, call, attachment, issuer) post = await _approve_policies(client, compilation_root, token, call, attachments) context = post["activation_context"] activation = {"target": post["target"], **{field: context[field] for field in ( diff --git a/experiments/pilot04_external_checker_runtime/public_probe_support.py b/experiments/pilot04_external_checker_runtime/public_probe_support.py index f3b5c1052..f5434cc50 100644 --- a/experiments/pilot04_external_checker_runtime/public_probe_support.py +++ b/experiments/pilot04_external_checker_runtime/public_probe_support.py @@ -50,9 +50,12 @@ def _assert_input_hashes(row, expected): def _token(env: dict[str, str], actor) -> str: from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment + from experiments.pilot04_external_checker_runtime.public_submission_clients import ConnectedEnvironment if isinstance(env, HostedAttachment): return env.token(actor) + if isinstance(env, ConnectedEnvironment): + return env.identity.issue(str(actor.actor_profile_id), api_lifetime_seconds=1800).api issuer, audience, secret = flow_settings(env) return issue_flow_token( str(actor.actor_profile_id), [], issuer=issuer, audience=audience, secret=secret @@ -84,7 +87,7 @@ async def _json(client: httpx.AsyncClient, method: str, path: str, token: str, return response.json() -async def _seed_contributor(factory) -> ActorIdentityFacts: +async def _seed_contributor(factory, issuer) -> ActorIdentityFacts: """Create a Flow-linked human without an administrator role grant.""" actor = ActorIdentityFacts(new_record_id(), new_record_id(), ActorKind.HUMAN) async with factory() as session, session.begin(): @@ -95,7 +98,7 @@ async def _seed_contributor(factory) -> ActorIdentityFacts: await session.flush() session.add(ActorIdentityLink( id=str(actor.identity_link_id), actor_profile_id=str(actor.actor_profile_id), - issuer="https://identity.flowresearch.tech", + issuer=issuer, subject=str(actor.actor_profile_id), subject_kind="human", status="active", linked_by="public-probe-fixture", last_verified_at=datetime.now(UTC), @@ -223,15 +226,16 @@ async def _started_public_task(client, *, project_id: str, manager_token: str, async def _public_project(client, factory, env, *, human_review_required, pre_requirements=1): """Public guide activation and submitter grant shared by every runtime trial.""" from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment + from experiments.pilot04_external_checker_runtime.public_submission_clients import seeded_issuer attachment = env if isinstance(env, HostedAttachment) else None compilation = await public_guide_setup( client, factory, human_review_required, _json, lambda actor: _token(env, actor), - pre_requirements=pre_requirements, attachment=attachment, + pre_requirements=pre_requirements, attachment=attachment, issuer=seeded_issuer(env), ) manager = compilation.manager guide_id = str(compilation.guide_id) - contributor = attachment.actors['contributor'] if attachment else await _seed_contributor(factory) + contributor = attachment.actors['contributor'] if attachment else await _seed_contributor(factory, seeded_issuer(env)) manager_token, contributor_token = _token(env, manager), _token(env, contributor) project_id = str(compilation.project_id) diff --git a/experiments/pilot04_external_checker_runtime/public_submission_clients.py b/experiments/pilot04_external_checker_runtime/public_submission_clients.py new file mode 100644 index 000000000..c9c55736b --- /dev/null +++ b/experiments/pilot04_external_checker_runtime/public_submission_clients.py @@ -0,0 +1,136 @@ +"""Connect the built CLI and installed MCP to the existing owned native journey.""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import os +from pathlib import Path +import sys +from uuid import uuid4 + +import httpx + +from cli.tests.journey.client import JourneyClient + +_MCP_FIXTURES = Path(__file__).resolve().parents[2] / "mcp_server" / "tests" / "integration" +sys.path.insert(0, str(_MCP_FIXTURES)) +try: + from oauth_fixture import IdentityFixture, call_mcp +finally: + sys.path.remove(str(_MCP_FIXTURES)) + + +class ConnectedEnvironment(dict[str, str]): + """Pass normal process settings and expose the isolated issuer to fixture callers.""" + + def __init__(self, env, identity): + super().__init__(env) + self.identity = identity + + +def seeded_issuer(env): + """Use the same canonical issuer for stored links and signed proof tokens.""" + return env.identity.issuer if isinstance(env, ConnectedEnvironment) else "https://identity.flowresearch.tech" + + +class ContributorClients: + def __init__(self, cli_executable: Path, mcp_executable: Path, scratch: Path): + self.cli_executable = cli_executable.resolve(strict=True) + self.mcp_executable = mcp_executable.resolve(strict=True) + self.scratch = scratch + scratch.mkdir(mode=0o700, parents=True) + self.identity = IdentityFixture() + self.mcp_env = { + key: value for key, value in os.environ.items() if key in {"PATH", "LANG", "LC_ALL"} + } + self.cli = None + self.mcp_origin = None + + def setup_authority(self, env): + """Use the existing signed issuer and exchange without adapting product auth.""" + authority = ConnectedEnvironment(env, self.identity) + python_path = authority["PYTHONPATH"] + self.identity.configure_processes(authority, self.mcp_env) + authority["PYTHONPATH"] = os.pathsep.join((authority["PYTHONPATH"], python_path)) + # Preserve standard roots for the native runner and storage connections. + # The fixture adds its own trust only to the HTTPS identity clients. + return authority + + def configure_processes(self, origin, port): + self.cli = JourneyClient(self.cli_executable, origin, self.scratch) + self.mcp_origin = f"http://127.0.0.1:{port}" + self.mcp_env.update( + WORKSTREAM_API_URL=origin, + WORKSTREAM_MCP_HOST="127.0.0.1", + WORKSTREAM_MCP_PORT=str(port), + WORKSTREAM_MCP_READ_TIMEOUT_SECONDS="120", + WORKSTREAM_MCP_TOTAL_TIMEOUT_SECONDS="180", + ) + + async def wait_ready(self, process): + path = self.mcp_origin + "/.well-known/oauth-protected-resource/mcp" + async with asyncio.timeout(60), httpx.AsyncClient(timeout=2, trust_env=False) as client: + while process.poll() is None: + try: + response = await client.get(path) + if response.status_code == 200 and response.json()["authorization_servers"] == [self.identity.issuer]: + return + except httpx.TransportError: + pass + await asyncio.sleep(0.25) + raise RuntimeError("installed MCP exited before readiness") + + async def mcp(self, contributor, name, arguments, *, failed=False): + token = self.identity.issue(str(contributor.actor_profile_id)) + data, error = await call_mcp(self.mcp_origin, token, name="workstream_" + name, + arguments=arguments, http_deadline_seconds=185) + if error is not failed: + raise AssertionError(f"MCP {name} had unexpected success or failure") + return data + + async def guide(self, contributor, token, project, expected): + destination = self.scratch / project + destination.mkdir(mode=0o700) + cli = await asyncio.to_thread(self.cli.call, token, "project", "guide", "approved", project, + "--download", str(destination)) + mcp = await self.mcp(contributor, "project_contributor_guide_get", {"project_id": project}) + if cli != expected or mcp != expected: + raise AssertionError("CLI or MCP approved guide manifest differs from the public read") + downloaded = sorted("sha256:" + hashlib.sha256(path.read_bytes()).hexdigest() + for path in destination.iterdir()) + if downloaded != sorted(document["sha256"] for document in expected["documents"]): + raise AssertionError("CLI did not download the approved original bytes") + for document in expected["documents"]: + read = await self.mcp(contributor, "project_contributor_guide_document_get", { + "project_id": project, "guide_id": expected["guide_id"], "document_id": document["document_id"], + }) + content = base64.b64decode(read["content_base64"], validate=True) + if "sha256:" + hashlib.sha256(content).hexdigest() != document["sha256"]: + raise AssertionError("MCP did not download the approved original bytes") + + async def submit(self, contributor, token, task, assignment, key, archive, *, client, failed=False): + if client == "mcp": + result = await self.mcp(contributor, "submission_create", { + "task_id": task, "assignment_id": assignment, "idempotency_key": key, + "zip_base64": base64.b64encode(archive).decode("ascii"), + }, failed=failed) + return {"error": result} if failed else result + path = self.scratch / f"{uuid4()}.zip" + with path.open("xb") as stream: + path.chmod(0o600) + stream.write(archive) + try: + return await asyncio.to_thread( + self.cli.call, token, "task", "submit", task, "--assignment", assignment, + "--file", str(path), "--idempotency-key", key, expected_exit=1 if failed else 0, + ) + finally: + path.unlink() + + async def status(self, contributor, token, task, assignment, expected): + cli = await asyncio.to_thread(self.cli.call, token, "task", "status", task, "--assignment", assignment) + mcp = await self.mcp(contributor, "task_assignment_get", {"task_id": task, "assignment_id": assignment}) + if cli != expected or mcp != expected: + raise AssertionError("CLI or MCP exact assignment status differs from the governed public response") diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 3a9ce4662..808309091 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -9,7 +9,7 @@ import argparse import asyncio from collections.abc import Awaitable, Callable -from contextlib import nullcontext +from contextlib import ExitStack, nullcontext from decimal import Decimal import hashlib import hmac @@ -73,6 +73,9 @@ _require, _started_public_task, _token, _wait_outbox_acknowledged, _with_fixture_file, _GOVERNED_TABLES, _fixture_hashes, _assert_input_hashes, ) +from experiments.pilot04_external_checker_runtime.public_submission_clients import ( # noqa: E402 + ContributorClients, seeded_issuer, +) def _settings_digests(settings, nonce: bytes) -> dict[str, str]: @@ -572,16 +575,24 @@ async def _replay_source_submission(client, task_id, assignment_id, token, archi async def _submit(client, factory, *, task_id: str, assignment_id: str, - contributor_token: str, archive: bytes, feedback: str | None = None) -> dict: + contributor_token: str, archive: bytes, feedback: str | None = None, + submit_zip=None, replay_zip=None) -> dict: headers = _source_headers(assignment_id, archive, str(uuid4()), feedback) - accepted = await _json(client, "POST", f"/api/v1/tasks/{task_id}/submissions", contributor_token, 202, - headers=headers, content=archive) + if submit_zip is None: + accepted = await _json(client, "POST", f"/api/v1/tasks/{task_id}/submissions", contributor_token, 202, + headers=headers, content=archive) + else: + accepted = await submit_zip(archive, headers["Idempotency-Key"]) _require(accepted["task_id"] == task_id and accepted["assignment_id"] == assignment_id and accepted["status"] == "accepted" and accepted["replayed"] is False and accepted["pre_submission_results"], "raw ZIP command returned an invalid accepted receipt") context = {"operation_id": accepted["operation_id"], "acceptance_receipt": accepted, "idempotency_key": headers["Idempotency-Key"], "feedback": feedback} - await _replay_source_submission(client, task_id, assignment_id, contributor_token, archive, context) + if replay_zip is None: + await _replay_source_submission(client, task_id, assignment_id, contributor_token, archive, context) + else: + replayed = await replay_zip(archive, context["idempotency_key"]) + _require(replayed == dict(accepted, replayed=True), "connected submission replay changed its receipt") return context | await _await_finalized_source( client, factory, task_id, assignment_id, contributor_token, context, archive) @@ -807,7 +818,7 @@ async def _late_revocation_trial(client, factory, env, *, project_id: UUID, "late completion advanced before the worker stopped") administrator, _ = await seed_review_actor( - factory, None, role="access_administrator", scope="system" + factory, None, role="access_administrator", scope="system", issuer=seeded_issuer(env), ) async with factory() as session: router_link = await session.scalar( @@ -854,7 +865,8 @@ async def _late_revocation_trial(client, factory, env, *, project_id: UUID, async def _one_mode(client, factory, env, *, human_review_required: bool, operator_id: UUID | None, stop_worker: Callable[[], None] | None = None, - start_worker: Callable[[], Awaitable[None]] | None = None, fault_root=None, operator_token=None) -> dict: + start_worker: Callable[[], Awaitable[None]] | None = None, fault_root=None, + operator_token=None, clients: ContributorClients | None = None) -> dict: from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment attachment = env if isinstance(env, HostedAttachment) else None @@ -870,22 +882,24 @@ async def _one_mode(client, factory, env, *, ) _require(approved_guide["guide_id"] == str(compilation.guide_id) and approved_guide["documents"], "preclaim project guide does not match the approved originals") + if clients is not None: + await clients.guide(contributor, contributor_token, project_id, approved_guide) task_id, assignment_id = await _started_public_task( client, project_id=project_id, manager_token=manager_token, contributor_token=contributor_token, source_ref="local-ticket-1", approved_guide=approved_guide, ) + async def submit_zip(archive, key, *, using, failed=False): + if clients is None: + return await _json( + client, "POST", f"/api/v1/tasks/{task_id}/submissions", contributor_token, 422 if failed else 202, + headers=_source_headers(assignment_id, archive, key), content=archive, + ) + return await clients.submit(contributor, contributor_token, task_id, assignment_id, + key, archive, client=using, failed=failed) + archive = archive_with_modes("evidence/results", compilation.project_id) - bad = await _json( - client, "POST", f"/api/v1/tasks/{task_id}/submissions", - contributor_token, 422, - headers={ - "Content-Type": "application/zip", - "X-Task-Assignment-Id": assignment_id, - "Idempotency-Key": str(uuid4()), - }, - content=_secret_archive(archive), - ) + bad = await submit_zip(_secret_archive(archive), str(uuid4()), using="cli", failed=True) _require(bad["error"]["code"] == "pre_submission_checker_failed", "public intake did not return checker feedback") default_details = bad["error"]["details"] @@ -906,16 +920,8 @@ async def _one_mode(client, factory, env, *, ], "public default PRE feedback did not identify the injected private key", ) - external_bad = await _json( - client, "POST", f"/api/v1/tasks/{task_id}/submissions", - contributor_token, 422, - headers={ - "Content-Type": "application/zip", - "X-Task-Assignment-Id": assignment_id, - "Idempotency-Key": str(uuid4()), - }, - content=_with_fixture_file(archive, "project-rejected.txt"), - ) + external_bad = await submit_zip(_with_fixture_file(archive, "project-rejected.txt"), str(uuid4()), + using="mcp", failed=True) results = external_bad["error"]["details"]["results"] external = [item for item in results if item["source"] == "project_external_checker"] @@ -928,6 +934,8 @@ async def _one_mode(client, factory, env, *, "public external PRE rejection did not preserve passing defaults") status_path = f"/api/v1/tasks/{task_id}/assignments/{assignment_id}" rejected = await _json(client, "GET", status_path, contributor_token, 200) + if clients is not None: + await clients.status(contributor, contributor_token, task_id, assignment_id, rejected) _require(rejected["current_status"] == "in_progress" and rejected["assignment"]["latest_submission"] is None and rejected["next_action"] == "submit" @@ -951,7 +959,10 @@ async def fail_post_launch(): try: saved = await _submit( client, factory, task_id=task_id, assignment_id=assignment_id, - contributor_token=contributor_token, archive=first_archive) + contributor_token=contributor_token, archive=first_archive, + submit_zip=lambda archive, key: submit_zip(archive, key, using="cli" if human_review_required else "mcp"), + replay_zip=lambda archive, key: submit_zip(archive, key, using="mcp" if human_review_required else "cli"), + ) if inject_post_fault: await fail_post_launch() finally: @@ -984,6 +995,8 @@ async def fail_post_launch(): attempt_id=first_attempt_id, ) revision = await _json(client, "GET", status_path, contributor_token, 200) + if clients is not None: + await clients.status(contributor, contributor_token, task_id, assignment_id, revision) _require(revision["current_status"] == "needs_revision" and revision["next_action"] == "revise" and revision["feedback_submission_id"] == first_submission_id @@ -995,6 +1008,8 @@ async def fail_post_launch(): client, factory, task_id=task_id, assignment_id=assignment_id, contributor_token=contributor_token, archive=replacement_archive, + submit_zip=lambda archive, key: submit_zip(archive, key, using="mcp"), + replay_zip=lambda archive, key: submit_zip(archive, key, using="cli"), ) expected_inputs[saved["submission_id"]] = _fixture_hashes(replacement_archive) _require(saved["submission_version"] == 2, @@ -1051,6 +1066,8 @@ async def fail_post_launch(): for award in item["awards"]] == ([("project_points", "PTS", Decimal("7"))] if awards else []), "public contribution source or award set differs") final_status = await _json(client, "GET", status_path, contributor_token, 200) + if clients is not None: + await clients.status(contributor, contributor_token, task_id, assignment_id, final_status) if human_review_required: _require(final_status["current_status"] == "review_pending" and final_status["accepted_evidence"] is None, "the exact assignment changed required human-review custody") @@ -1132,7 +1149,8 @@ async def _pre_runs(factory, task_id: str) -> list[str]: async def run(database_url: str, image_reference: str, node_config: Path, - broker_url: str, root: Path, expected_custody: Path) -> dict: + broker_url: str, root: Path, expected_custody: Path, + clients: ContributorClients | None = None) -> dict: root.mkdir(parents=True, mode=0o700, exist_ok=True) custody = json.loads(expected_custody.read_text()) _require(custody['source_tree'] == subprocess.check_output( @@ -1194,6 +1212,10 @@ async def run(database_url: str, image_reference: str, node_config: Path, }) configure_scripted_model_session_environment(env) env.pop("OPENAI_API_KEY", None) + if clients is not None: + env = clients.setup_authority(env) + os.environ.pop("WORKSTREAM_FLOW_AUTH_LOCAL_HMAC_SECRET", None) + os.environ.pop("WORKSTREAM_E2E_FLOW_SECRET", None) # Infrastructure prerequisites and broker publication use the same # isolated database and provider settings as the API and worker children. for key, value in env.items(): @@ -1202,13 +1224,20 @@ async def run(database_url: str, image_reference: str, node_config: Path, os.environ.pop("OPENAI_API_KEY", None) get_settings.cache_clear() runtime_settings = get_settings() - issuer, audience, flow_secret = flow_settings(env) _require(runtime_settings.database_url == database_url, "API/worker database differs from isolated fixture") - _require(runtime_settings.flow_auth_issuer == issuer - and runtime_settings.flow_auth_audience == audience - and runtime_settings.flow_auth_local_hmac_secret == flow_secret, - "API Flow verifier differs from local test signer") + if clients is None: + issuer, audience, flow_secret = flow_settings(env) + _require(runtime_settings.flow_auth_issuer == issuer + and runtime_settings.flow_auth_audience == audience + and runtime_settings.flow_auth_local_hmac_secret == flow_secret, + "API Flow verifier differs from local test signer") + else: + _require(runtime_settings.token_issuer == clients.identity.issuer + and runtime_settings.token_audience == "workstream-api" + and runtime_settings.token_algorithms == "RS256" + and runtime_settings.flow_auth_local_hmac_secret is None, + "API Flow verifier differs from the connected issuer fixture") _require(runtime_settings.api_rate_limit_key_secret is not None and runtime_settings.pagination_cursor_hmac_secret is not None, "API rate/cursor signing configuration is absent") @@ -1255,7 +1284,7 @@ async def run(database_url: str, image_reference: str, node_config: Path, engine = create_async_engine(database_url) factory = async_sessionmaker(engine, expire_on_commit=False) - api = worker = beat = None + api = worker = beat = mcp = None workers: list[subprocess.Popen] = [] worker_generation = 0 @@ -1285,7 +1314,7 @@ async def start_owned_worker() -> None: await _provision_runtime_services(factory) for phase in ("pre_submit", "post_submit"): await _register_external_checker_fixture(factory, _locked_spec(phase, image)) - operator, _ = await seed_review_actor(factory, None, role="operator", scope="system") + operator, _ = await seed_review_actor(factory, None, role="operator", scope="system", issuer=seeded_issuer(env)) from tests.reviews.lifecycle.transition_support import command_for, transition await transition(await command_for(operator.actor_profile_id, "shadow")) @@ -1303,6 +1332,10 @@ async def start_owned_worker() -> None: "--log-level", "error", "--no-access-log", ], env=env, log=root / "api.log") await _wait_api(origin, api) + if clients is not None: + clients.configure_processes(origin, find_free_port()) + mcp = _process([str(clients.mcp_executable)], env=clients.mcp_env, log=root / "mcp.log") + await clients.wait_ready(mcp) for role, queue in WORKER_ROLES: process, hostname = _start_worker( cleanup_env if role == "source-cleanup" else env, root, role, queue @@ -1332,16 +1365,17 @@ async def start_owned_worker() -> None: stop_worker=stop_owned_worker, start_worker=start_owned_worker, operator_token=_token(env, operator)) true = await _one_mode(client, factory, env, human_review_required=True, - operator_id=operator.actor_profile_id) + operator_id=operator.actor_profile_id, clients=clients) false = await _one_mode(client, factory, env, human_review_required=False, operator_id=operator.actor_profile_id, stop_worker=stop_owned_worker, start_worker=start_owned_worker, fault_root=fault_root, - operator_token=_token(env, operator)) + operator_token=_token(env, operator), clients=clients) _require(api.poll() is None and beat.poll() is None and all(process.poll() is None for process in workers), "API, dedicated prefork worker, or Beat exited during public journey") + _require(mcp is None or mcp.poll() is None, "installed MCP exited during public journey") return {"tree_sha": subprocess.check_output( ["git", "rev-parse", "HEAD"], text=True, cwd=BACKEND ).strip(), "runtime": "smolvm/smol-microvm", "image_digest": image["platform_manifest_digest"], @@ -1351,6 +1385,7 @@ async def start_owned_worker() -> None: "dedicated_worker_queues": [queue for _, queue in WORKER_ROLES], "maximum_parallel": 1, "scheduled_artifact_scans": True, "public_original_guide_setup": True, + "connected_submitter_clients": ["cli", "mcp"] if clients is not None else [], "recorded_inference": True, "custody": {key: custody[key] for key in ( 'source_tree', 'config_sha256', 'service_sha256', 'smol_sha256', 'guest_sha256', 'wrapper_sha256')}, @@ -1358,7 +1393,7 @@ async def start_owned_worker() -> None: finally: cleanup_error = None try: - _stop_owned_processes((beat, *reversed(workers), api)) + _stop_owned_processes((mcp, beat, *reversed(workers), api)) except RuntimeError as error: cleanup_error = error try: @@ -1379,6 +1414,8 @@ def main() -> int: parser.add_argument("--expected-custody", type=Path) parser.add_argument("--work-dir", type=Path, help="Unique private directory retaining API and worker diagnostics") + parser.add_argument("--cli-executable", type=Path, help="Built CLI for connected submitter verification") + parser.add_argument("--mcp-executable", type=Path, help="Installed MCP for connected submitter verification") parser.add_argument('--hosted-attachment', type=Path, help='Private attachment manifest for an existing hosted API/worker/Beat') parser.add_argument('--hosted-model-post', type=Path, @@ -1388,9 +1425,11 @@ def main() -> int: parser.error("isolated --database-url or WORKSTREAM_TEST_DATABASE_URL is required") if args.hosted_model_post and not args.hosted_attachment: parser.error('model POST qualification requires explicit hosted attachment') + if bool(args.cli_executable) != bool(args.mcp_executable): + parser.error("connected submitter verification requires both client executables") if args.hosted_attachment: if (not args.broker_url or args.image_reference or args.node_config - or args.work_dir or args.expected_custody): + or args.work_dir or args.expected_custody or args.cli_executable or args.mcp_executable): parser.error('hosted attachment requires broker URL and excludes local launch arguments') from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment, run as attach attachment = HostedAttachment.read(args.hosted_attachment) @@ -1402,10 +1441,14 @@ def main() -> int: parser.error("full drill requires image, node config, and broker URL") workspace = (nullcontext(args.work_dir) if args.work_dir else tempfile.TemporaryDirectory(prefix="ws-pilot04-public-")) - with workspace as directory: + with workspace as directory, ExitStack() as cleanup: + clients = None + if args.cli_executable: + clients = ContributorClients(args.cli_executable, args.mcp_executable, Path(directory) / "submitter-clients") + cleanup.callback(clients.identity.close) value = asyncio.run(run( args.database_url, args.image_reference, args.node_config, - args.broker_url, Path(directory), args.expected_custody, + args.broker_url, Path(directory), args.expected_custody, clients, )) print(json.dumps(value, sort_keys=True, separators=(",", ":"))) return 0 diff --git a/mcp_server/tests/integration/oauth_fixture.py b/mcp_server/tests/integration/oauth_fixture.py index 24e4cf663..d17120021 100644 --- a/mcp_server/tests/integration/oauth_fixture.py +++ b/mcp_server/tests/integration/oauth_fixture.py @@ -19,9 +19,11 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from threading import Thread +from typing import Any from urllib.parse import parse_qs from uuid import uuid4 +import certifi import jwt from cryptography.hazmat.primitives.serialization import load_pem_private_key @@ -160,12 +162,15 @@ def do_POST(self): # noqa: N802 - HTTP handler interface # Install an isolated test CA at the process boundary, not a permissive # verifier or product configuration switch. TLS/signature checks remain # enabled. No backend source is added to the installed MCP's sys.path. + trusted_certificates = trust / "certificates.pem" + trusted_certificates.write_bytes(Path(certifi.where()).read_bytes() + b"\n" + + (self.root / "cert.pem").read_bytes()) (trust / "sitecustomize.py").write_text( - "import certifi\ncertifi.where = lambda: " + repr(str(self.root / "cert.pem")) + "\n", + "import certifi\ncertifi.where = lambda: " + repr(str(trusted_certificates)) + "\n", ) self.trust = str(trust) - def issue(self, subject: str) -> IdentityTokens: + def issue(self, subject: str, *, api_lifetime_seconds: int = 300) -> IdentityTokens: now = int(time.time()) claims = { "iss": self.issuer, @@ -182,7 +187,7 @@ def issue(self, subject: str) -> IdentityTokens: } return IdentityTokens( jwt.encode( - {**claims, "aud": "workstream-api"}, + {**claims, "aud": "workstream-api", "exp": now + api_lifetime_seconds}, self.key, algorithm="RS256", headers={"kid": "fixture"}, @@ -220,3 +225,38 @@ def close(self): self.server.server_close() self.thread.join(timeout=5) self.temporary.cleanup() + + +async def call_mcp( + mcp_url: str, + token: IdentityTokens, + *, + name: str = "workstream_profile_get", + arguments: dict[str, Any] | None = None, + http_deadline_seconds: float = 20, +) -> tuple[dict[str, Any], bool]: + """Call the installed adapter using the public streamable HTTP session.""" + import httpx2 as httpx + from mcp import Client + from mcp.client.streamable_http import streamable_http_client + + async with httpx.AsyncClient( + headers={"Authorization": f"Bearer {token.mcp}"}, + follow_redirects=False, + trust_env=False, + timeout=http_deadline_seconds, + ) as http_client: + transport = streamable_http_client(mcp_url + "/mcp", http_client=http_client) + async with Client(server=transport, mode="2026-07-28") as client: + assert client.protocol_version == "2026-07-28" + result = await client.call_tool(name, arguments or {}) + dump = result.model_dump() + if "structuredContent" in dump and dump["structuredContent"] is not None: + content = dump["structuredContent"] + elif "structured_content" in dump and dump["structured_content"] is not None: + content = dump["structured_content"] + else: + content = json.loads(dump["content"][0]["text"]) + + is_error = dump.get("isError", dump.get("is_error", False)) + return content, bool(is_error) diff --git a/mcp_server/tests/integration/test_profile_flow.py b/mcp_server/tests/integration/test_profile_flow.py index edb24d815..488373a2a 100644 --- a/mcp_server/tests/integration/test_profile_flow.py +++ b/mcp_server/tests/integration/test_profile_flow.py @@ -14,8 +14,7 @@ import httpx2 as httpx import pytest from integration.oauth_fixture import IdentityFixture, IdentityTokens -from mcp import Client -from mcp.client.streamable_http import streamable_http_client +from integration.oauth_fixture import call_mcp as _call from workstream_mcp.tools.profile import normalize_update_input @@ -78,37 +77,6 @@ async def _ready(url: str, process: subprocess.Popen[str]) -> None: raise AssertionError("subprocess readiness timeout") -async def _call( - mcp_url: str, - token: IdentityTokens, - *, - name: str = "workstream_profile_get", - arguments: dict[str, Any] | None = None, -) -> tuple[dict[str, Any], bool]: - async with httpx.AsyncClient( - headers={"Authorization": f"Bearer {token.mcp}"}, - follow_redirects=False, - trust_env=False, - timeout=20, - ) as http_client: - transport = streamable_http_client(mcp_url + "/mcp", http_client=http_client) - async with Client(server=transport, mode="2026-07-28") as client: - assert client.protocol_version == "2026-07-28" - result = await client.call_tool(name, arguments or {}) - dump = result.model_dump() - if "structuredContent" in dump and dump["structuredContent"] is not None: - content = dump["structuredContent"] - elif "structured_content" in dump and dump["structured_content"] is not None: - content = dump["structured_content"] - else: - import json - - content = json.loads(dump["content"][0]["text"]) - - is_error = dump.get("isError", dump.get("is_error", False)) - return content, bool(is_error) - - def _bootstrap_access_administrator(actor_id: str, environment: dict[str, str]) -> None: """Run the documented local trust-root command; never seed authority by SQL.""" completed = subprocess.run( # noqa: S603 - fixed repository command and generated UUID From 46858a75dd9c1d283cc0f9da8d5b5735f2bfeb20 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:35:52 +0100 Subject: [PATCH 360/513] Record contributor qualification evidence and current runner custody --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index c53037226..11b1e306b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11136,3 +11136,40 @@ review should verify revised selection, closed-assignment isolation and the difference between a granted award and fulfilled payment. Verification uses real PostgreSQL and source storage in focused integration cases, plus the connected CLI/MCP journey against the combined candidate. + +The earlier two-source PostgreSQL drill started from `3334fa566` on Alembic +`0091_qualified_aws_source` and advanced to the `9efd2c017` implementation of +`0092_submission_feedback`. It refused upgrade while a receiving operation +was live. After it settled, the approved old attempt replayed its original +receipt, retained the two historical packet fields and digests, and finalized +once using existing OUTBOX/T5 owners. A separate nonempty legacy command +conflicted with the new minimal replay. The isolated database cleanup receipt +was complete. The reproducible two-checkout drill now lives with the +[submission qualification experiments](../../../experiments/pilot04_external_checker_runtime/submission_feedback_upgrade_drill.py). +Run its test explicitly from a detached `0091` checkout with +`WORKSTREAM_SUBMISSION_FEEDBACK_CANDIDATE` identifying the candidate backend, +using the owned isolated PostgreSQL runner. It also checks the exact audit +constraint delta and row identity across the migration. +The expanded drill passed in 248.27 seconds using the predecessor +`3334fa566` and the `0092` schema from `a38dee4d1` and `eb5f93de4`, with +owned database cleanup complete. + +At `eb5f93de4`, the combined isolated PostgreSQL/MinIO run reached eight +passing case markers for new intake, retained rejection, guide access and +concealment, revised terms, the managed adapter, migration graph and the +connected CLI. Its child reached the 540-second cap before a terminal pytest +summary and exited 124. The isolated database and MinIO cleanup receipts both +completed. The separate built-CLI HTTP suite passed 52 cases. The +precommit caller check for the `124695d5e` code passed 69 cases and 100 +subtests in 68.03 seconds. The installed MCP wheel and built CLI are available to the +native proof. The probe records a connected-client receipt only when both are +used with the same API and worker processes and the governed checkpoints pass. + +The November 26 infrastructure recheck verified the same running native +runner instance at `56.228.13.174` using its pinned original SSH host key via +`HostKeyAlias`. The configuration digest prefix `c3f8fb85`, executable, +cache and root pins were unchanged. Both runner services were active with +98.1 GB free. The existing API release still used image prefix `83744f1c16dd`, +reported healthy and had 93.2 GB free. This was a read-only recheck of the running +infrastructure. Combined candidate execution and deployment qualification +remain open. From 498706713c0ca9d5b73dd42b685931295eaec347 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:41:44 +0100 Subject: [PATCH 361/513] Clarify Celery consumer terminology in contributor documentation --- docs/engineering/developer-setup.md | 2 +- docs/roadmap_status.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/engineering/developer-setup.md b/docs/engineering/developer-setup.md index a6aecc2c2..8d59fcef9 100644 --- a/docs/engineering/developer-setup.md +++ b/docs/engineering/developer-setup.md @@ -149,7 +149,7 @@ uploaded rules compilation at the same prefix's `requirements/compile` suffix. Both require a UUID `Idempotency-Key` and no body; manager review and separate approvals remain required. See the [local pilot](local-pilot.md#declare-and-upload-a-real-guide-document). -The local Compose workers each consume one queue: project guide compilation, +The local Compose Celery workers each consume one queue: project guide compilation, project control, artifact work, outbox scanning, POST delivery, submission finalization, and source cleanup. The submission finalizer and source cleanup services use the opt-in `submission-intake` profile. Set `WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY` diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index b49eb1b71..1ac71e9d4 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -690,7 +690,7 @@ cannot be reused as post-submission review-gate evidence. See the | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent | | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS | | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate | -| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | Qualify the combined CLI/MCP submitter journey against the updated trusted intake image and dedicated workers. Preserve rejection, correction, replay and closed-assignment evidence. | +| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | Qualify the combined CLI/MCP submitter journey against the updated trusted intake image and dedicated Celery workers. Preserve rejection, correction, replay and closed-assignment evidence. | | Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. Remaining gates are native fault, isolation, capacity and maximum-input qualification, qualified AWS admission activation and deployed API/consumer cutover. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. | | Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Complete the connected native public journey, AWS exact-version qualification, hosted cutover and final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. | | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. The bounded local public API/Celery drill passed both branches, prefork Celery process restart and late authority revocation | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate | From b597dfc428eb9b16a3a8cf904bc8308ff5f78743 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:43:46 +0100 Subject: [PATCH 362/513] Require typed selectors for MCP contributor response matching --- mcp_server/workstream_mcp/http_gateway.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py index 6cc43a1d6..e99316e76 100644 --- a/mcp_server/workstream_mcp/http_gateway.py +++ b/mcp_server/workstream_mcp/http_gateway.py @@ -1573,14 +1573,21 @@ def _task_execution_response_matches( if name in {"submission_get", "management_submission_get"}: return cls._same_uuid(data.get("id"), arguments["submission_id"]) if name == "project_contributor_guide_get": - return cls._same_uuid(data.get("project_id"), project_id) - if name == "task_assignment_get": - assignment = data.get("assignment") - return isinstance(assignment, dict) and cls._fields_match( - assignment, {"task_id": task_id, "assignment_id": arguments["assignment_id"]}, + return isinstance(project_id, str) and cls._same_uuid( + data.get("project_id"), project_id, ) if not isinstance(task_id, str): return False + if name == "task_assignment_get": + assignment = data.get("assignment") + assignment_id = arguments.get("assignment_id") + return ( + isinstance(assignment, dict) + and isinstance(assignment_id, str) + and cls._fields_match( + assignment, {"task_id": task_id, "assignment_id": assignment_id}, + ) + ) if project_id is not None and not isinstance(project_id, str): return False if name == "submission_operation_get": From 82113cf0037d43b2ff23313efa9046c8208412d3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:46:13 +0100 Subject: [PATCH 363/513] Keep the separate-runner CLI journey on the minimal submission command --- cli/README.md | 2 +- cli/tests/journey/submission_work.py | 7 ------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/cli/README.md b/cli/README.md index c73bce10c..82e092f63 100644 --- a/cli/README.md +++ b/cli/README.md @@ -234,7 +234,7 @@ the [terminal presentation contract](../docs/design/cli-terminal-experience.md). | `workstream operations task list PROJECT_ID [--limit N] [--cursor TOKEN]` | `GET /api/v1/operations/projects/PROJECT_ID/tasks` | | `workstream operations task locked-context PROJECT_ID TASK_ID` | `GET /api/v1/operations/projects/PROJECT_ID/tasks/TASK_ID/locked-context` | | `workstream task context TASK_ID` | `GET /api/v1/tasks/TASK_ID/work-context` | -| `workstream task guide TASK_ID [--download DIR]` | Work context, then assigned-task `GET /api/v1/tasks/TASK_ID/guide/documents/DOCUMENT_ID/content` for downloads | +| `workstream task guide TASK_ID [--download DIR]` | Work context and verified governing originals before or after claim | | `workstream task requirements TASK_ID` | `GET /api/v1/tasks/TASK_ID/submission-requirements` | | `workstream operations artifact bindings RESOURCE_TYPE RESOURCE_ID` | `GET /api/v1/operator/artifacts/bindings` | | `workstream operations artifact replicas CONTENT_ID` | `GET /api/v1/operator/artifacts/contents/CONTENT_ID/replicas` | diff --git a/cli/tests/journey/submission_work.py b/cli/tests/journey/submission_work.py index cedabe6cb..8a6f7274d 100644 --- a/cli/tests/journey/submission_work.py +++ b/cli/tests/journey/submission_work.py @@ -12,12 +12,6 @@ from source_audit import audit_accepted_source PILOT = Path(__file__).resolve().parents[3] / "pilots/terminal_systems/mvp" -PACKET = ( - "--summary", - "Fixed incident summary", - "--attestation", - "I counted the supplied incident events and retained the input.", -) def _package(client, kind): @@ -41,7 +35,6 @@ def _command(task_id, assignment_id, archive, key): task_id, "--assignment", assignment_id, - *PACKET, "--file", str(archive), "--idempotency-key", From 8bf03b231aab90dff2c9bc7637c222d2214ff4d0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:49:54 +0100 Subject: [PATCH 364/513] Run the paired contributor proof against an independently staged runner --- .../README.md | 11 ++- .../run_public_journey_probe.py | 82 +++++++++++++------ scripts/test_public_hosted_attachment.py | 25 ++++++ 3 files changed, 90 insertions(+), 28 deletions(-) diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md index 00207e02c..98d6e9a1f 100644 --- a/experiments/pilot04_external_checker_runtime/README.md +++ b/experiments/pilot04_external_checker_runtime/README.md @@ -150,7 +150,15 @@ clients address the same public API while the dedicated workers process submissions. The clean run receipt includes `connected_submitter_clients` after guide download, PRE rejection, cross-client replay, POST revision, resubmission, and final assignment reads complete. Hosted Flow Identity and -deployed service qualification remain separate. +deployed service qualification remain separate. Use `--separate-runner` for +the local API and independently staged remote Smol topology. Pass an exact +byte copy of the remote baseline service JSON and the reviewed custody file +with `node_config`, `config_sha256`, `service_sha256`, `smol_sha256`, +`guest_sha256`, and the qualification checkout's `source_tree`. The node must +already serve the pinned project checker and trusted intake images over the +configured mTLS route. The client host keeps its own artifact scratch. +This mode records null intake and runtime fault trials. The existing remote +PRE fault bridge covers its independently supervised fault stage. ```sh PYTHONPATH=.:tests:.. .venv/bin/python scripts/run_isolated_tests.py \ @@ -162,6 +170,7 @@ PYTHONPATH=.:tests:.. .venv/bin/python scripts/run_isolated_tests.py \ --expected-custody /absolute/private-node/custody.json \ --broker-url redis://127.0.0.1:/0 \ --work-dir /absolute/private-guide-journey \ + --separate-runner \ --cli-executable /absolute/bin/workstream \ --mcp-executable /absolute/mcp-wheel/bin/workstream-mcp ``` diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 808309091..6fc64ec91 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -866,7 +866,8 @@ async def _one_mode(client, factory, env, *, human_review_required: bool, operator_id: UUID | None, stop_worker: Callable[[], None] | None = None, start_worker: Callable[[], Awaitable[None]] | None = None, fault_root=None, - operator_token=None, clients: ContributorClients | None = None) -> dict: + operator_token=None, clients: ContributorClients | None = None, + exercise_faults: bool = True) -> dict: from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment attachment = env if isinstance(env, HostedAttachment) else None @@ -985,7 +986,7 @@ async def fail_post_launch(): project_id=compilation.project_id, recommendation="needs_revision" if human_review_required else "allow_review", finding_code="probe.post_rule_failed" if human_review_required else None, - deliver_completion=human_review_required, successor=successor, + deliver_completion=human_review_required or not exercise_faults, successor=successor, ) attempt_id = first_attempt_id if human_review_required: @@ -1022,7 +1023,7 @@ async def fail_post_launch(): factory, submission_id=saved["submission_id"], project_id=compilation.project_id, recommendation="allow_review", ) - else: + elif exercise_faults: await _wait_known_retry( factory, completion_id, compilation.project_id, task_id, first_submission_id, @@ -1109,7 +1110,7 @@ async def fail_post_launch(): ) _require(again == outcome, "duplicate completion changed governed outcome") late_revocation = None - if not human_review_required and attachment is None: + if exercise_faults and not human_review_required and attachment is None: late_revocation = await _late_revocation_trial( client, factory, env, project_id=compilation.project_id, accepted_task_id=task_id, manager_token=manager_token, @@ -1148,14 +1149,18 @@ async def _pre_runs(factory, task_id: str) -> list[str]: ).order_by(SelectedPreSubmitRun.queued_at))) -async def run(database_url: str, image_reference: str, node_config: Path, - broker_url: str, root: Path, expected_custody: Path, - clients: ContributorClients | None = None) -> dict: - root.mkdir(parents=True, mode=0o700, exist_ok=True) - custody = json.loads(expected_custody.read_text()) +def _read_runner_configuration(node_config: Path, root: Path, custody: dict, *, separate_runner: bool) -> dict: + """Bind a copied baseline config or the exact locally supervised wrapper.""" _require(custody['source_tree'] == subprocess.check_output( ['git', 'rev-parse', 'HEAD'], cwd=BACKEND, text=True).strip(), 'custody source differs') - service_config = json.loads(node_config.read_text()) + raw = node_config.read_bytes() + service_config = json.loads(raw) + if separate_runner: + _require(service_config == custody['node_config'] + and 'sha256:' + hashlib.sha256(raw).hexdigest() == custody['config_sha256'] + and service_config['smol']['binary_sha256'] == custody['smol_sha256'], + 'separate runner configuration differs from reviewed custody') + return service_config _require(service_config["smol"].get("maximum_parallel") == 1, "public proof requires a one-slot node") original_config = json.loads(json.dumps(service_config)) @@ -1169,6 +1174,16 @@ async def run(database_url: str, image_reference: str, node_config: Path, _require(original_config == custody['node_config'], 'node configuration differs from expected custody') _require(json.loads((root / 'node-control/node-binding.json').read_text()) == custody, 'host binary/config validation receipt differs from expected custody') + return service_config + + +async def run(database_url: str, image_reference: str, node_config: Path, + broker_url: str, root: Path, expected_custody: Path, + clients: ContributorClients | None = None, *, separate_runner: bool = False) -> dict: + root.mkdir(parents=True, mode=0o700, exist_ok=True) + _require(not separate_runner or clients is not None, 'separate runner proof needs both clients') + custody = json.loads(expected_custody.read_text()) + service_config = _read_runner_configuration(node_config, root, custody, separate_runner=separate_runner) _require((service_config["runtime"], service_config["isolation_mode"]) == ("smolvm", "smol-microvm"), "public drill requires the provisioned Smol node") repository, digest = image_reference.rsplit("@", 1) @@ -1178,7 +1193,7 @@ async def run(database_url: str, image_reference: str, node_config: Path, image = images[0] bucket = os.environ["WORKSTREAM_TEST_MINIO_BUCKET"] prefix = os.environ["WORKSTREAM_TEST_MINIO_PREFIX"] - scratch = Path(service_config["material_root"]) + scratch = root / "artifact-scratch" if separate_runner else Path(service_config["material_root"]) intake_images = [entry for entry in service_config["cache"] if entry["platform_manifest_digest"] == service_config["trusted_intake"]["platform_manifest_digest"]] @@ -1317,6 +1332,8 @@ async def start_owned_worker() -> None: operator, _ = await seed_review_actor(factory, None, role="operator", scope="system", issuer=seeded_issuer(env)) from tests.reviews.lifecycle.transition_support import command_for, transition await transition(await command_for(operator.actor_profile_id, "shadow")) + if separate_runner: + await transition(await command_for(operator.actor_profile_id, "live")) intake_health = await trusted_submission_intake(runtime_settings).health() execution_health = await configured_external_checker_execution(runtime_settings).health() @@ -1353,25 +1370,28 @@ async def start_owned_worker() -> None: ], env=env, log=root / "beat.log") await _wait_beat_scan(factory, beat, scans_before_beat) async with httpx.AsyncClient(base_url=origin, timeout=(source_profile.upload_total_seconds - + runtime_settings.external_checker_service_timeout_seconds)) as client: - from experiments.pilot04_external_checker_runtime.public_intake_trials import public_intake_trials - intake_trials = await public_intake_trials( - client, factory, env, root / "node-control", - stop_worker=stop_owned_worker, start_worker=start_owned_worker) - from experiments.pilot04_external_checker_runtime.public_runtime_trials import public_runtime_trials - fault_root = root / "node-control" - _require((fault_root / "supervisor-ready").exists(), "owned node supervisor is absent") - runtime_trials = await public_runtime_trials(client, factory, env, fault_root, - stop_worker=stop_owned_worker, start_worker=start_owned_worker, operator_token=_token(env, operator)) + + runtime_settings.external_checker_service_timeout_seconds), trust_env=False) as client: + fault_root = None if separate_runner else root / "node-control" + intake_trials = runtime_trials = None + if fault_root is not None: + from experiments.pilot04_external_checker_runtime.public_intake_trials import public_intake_trials + from experiments.pilot04_external_checker_runtime.public_runtime_trials import public_runtime_trials + intake_trials = await public_intake_trials( + client, factory, env, fault_root, stop_worker=stop_owned_worker, start_worker=start_owned_worker) + _require((fault_root / "supervisor-ready").exists(), "owned node supervisor is absent") + runtime_trials = await public_runtime_trials(client, factory, env, fault_root, + stop_worker=stop_owned_worker, start_worker=start_owned_worker, operator_token=_token(env, operator)) true = await _one_mode(client, factory, env, human_review_required=True, - operator_id=operator.actor_profile_id, clients=clients) + operator_id=operator.actor_profile_id, clients=clients, + exercise_faults=not separate_runner) false = await _one_mode(client, factory, env, human_review_required=False, operator_id=operator.actor_profile_id, stop_worker=stop_owned_worker, start_worker=start_owned_worker, fault_root=fault_root, - operator_token=_token(env, operator), clients=clients) + operator_token=_token(env, operator), clients=clients, + exercise_faults=not separate_runner) _require(api.poll() is None and beat.poll() is None and all(process.poll() is None for process in workers), "API, dedicated prefork worker, or Beat exited during public journey") @@ -1382,13 +1402,16 @@ async def start_owned_worker() -> None: "trusted_intake_image_digest": intake_health.image_digest, "trusted_intake_config_digest": intake_health.config_digest, "public_api": True, "prefork_worker": True, "prefork_finalization_worker": True, - "dedicated_worker_queues": [queue for _, queue in WORKER_ROLES], "maximum_parallel": 1, + "dedicated_worker_queues": [queue for _, queue in WORKER_ROLES], + "maximum_parallel": service_config["smol"]["maximum_parallel"], + "separate_runner": separate_runner, "scheduled_artifact_scans": True, "public_original_guide_setup": True, "connected_submitter_clients": ["cli", "mcp"] if clients is not None else [], "recorded_inference": True, "custody": {key: custody[key] for key in ( - 'source_tree', 'config_sha256', 'service_sha256', 'smol_sha256', 'guest_sha256', 'wrapper_sha256')}, + 'source_tree', 'config_sha256', 'service_sha256', 'smol_sha256', 'guest_sha256', + ) + (() if separate_runner else ('wrapper_sha256',))}, "runtime_trials": runtime_trials, "intake_trials": intake_trials, "human": true, "automatic": false} finally: cleanup_error = None @@ -1416,6 +1439,8 @@ def main() -> int: help="Unique private directory retaining API and worker diagnostics") parser.add_argument("--cli-executable", type=Path, help="Built CLI for connected submitter verification") parser.add_argument("--mcp-executable", type=Path, help="Installed MCP for connected submitter verification") + parser.add_argument("--separate-runner", action="store_true", + help="Use baseline remote runner custody without local host fault controls") parser.add_argument('--hosted-attachment', type=Path, help='Private attachment manifest for an existing hosted API/worker/Beat') parser.add_argument('--hosted-model-post', type=Path, @@ -1427,9 +1452,12 @@ def main() -> int: parser.error('model POST qualification requires explicit hosted attachment') if bool(args.cli_executable) != bool(args.mcp_executable): parser.error("connected submitter verification requires both client executables") + if args.separate_runner and not args.cli_executable: + parser.error("the separate runner proof requires both client executables") if args.hosted_attachment: if (not args.broker_url or args.image_reference or args.node_config - or args.work_dir or args.expected_custody or args.cli_executable or args.mcp_executable): + or args.work_dir or args.expected_custody or args.cli_executable or args.mcp_executable + or args.separate_runner): parser.error('hosted attachment requires broker URL and excludes local launch arguments') from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment, run as attach attachment = HostedAttachment.read(args.hosted_attachment) @@ -1448,7 +1476,7 @@ def main() -> int: cleanup.callback(clients.identity.close) value = asyncio.run(run( args.database_url, args.image_reference, args.node_config, - args.broker_url, Path(directory), args.expected_custody, clients, + args.broker_url, Path(directory), args.expected_custody, clients, separate_runner=args.separate_runner, )) print(json.dumps(value, sort_keys=True, separators=(",", ":"))) return 0 diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 26dea17c7..e414fb0d8 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -28,6 +28,31 @@ class PublicJourneyWorkerCustody(unittest.TestCase): + def test_separate_runner_uses_exact_baseline_config_without_local_fault_files(self): + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + source, binary = 'b' * 40, 'sha256:' + 'c' * 64 + configuration = {"smol": {"binary": "/runner/smolvm", "binary_sha256": binary}} + encoded = json.dumps(configuration).encode() + custody = { + 'source_tree': source, + 'node_config': configuration, + 'config_sha256': 'sha256:' + hashlib.sha256(encoded).hexdigest(), + 'smol_sha256': binary, + } + with tempfile.TemporaryDirectory() as directory, patch.object( + probe.subprocess, 'check_output', return_value=source + '\n', + ): + root = Path(directory) + config = root / 'runner.json' + config.write_bytes(encoded) + self.assertEqual(probe._read_runner_configuration(config, root, custody, separate_runner=True), + configuration) + self.assertFalse((root / 'node-control').exists()) + config.write_bytes(encoded + b'\n') + with self.assertRaisesRegex(RuntimeError, 'separate runner configuration differs'): + probe._read_runner_configuration(config, root, custody, separate_runner=True) + def test_cleanup_child_alone_receives_a_private_distinct_principal(self): from pydantic import SecretStr from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe From 57c939a30e38cc543870c1ee0babeac64921ee4e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:50:31 +0100 Subject: [PATCH 365/513] Check the live runner cache before starting the public proof --- .../run_public_journey_probe.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 6fc64ec91..2213ce4a7 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -1340,6 +1340,8 @@ async def start_owned_worker() -> None: _require((execution_health.runtime, execution_health.isolation_mode) == (intake_health.runtime, intake_health.isolation_mode) == ("smolvm", "smol-microvm"), "typed capability health identities disagree") + _require(image["platform_manifest_digest"] in execution_health.cached_platform_manifests, + "live execution cache lacks the reviewed project checker manifest") port = find_free_port() origin = f"http://127.0.0.1:{port}" api = _process([ From 001a295d447ec5077ccac0b639a93112d46b1b76 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 08:59:05 +0100 Subject: [PATCH 366/513] =?UTF-8?q?Reap=20the=20native=20journey=E2=80=99s?= =?UTF-8?q?=20owned=20processes=20on=20runner=20termination?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 9 +- .../run_public_journey_probe.py | 89 +++++++++++-------- scripts/test_public_hosted_attachment.py | 66 ++++++++++++++ 3 files changed, 125 insertions(+), 39 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 908eb5fb2..d5bc61c48 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -38,14 +38,15 @@ execution specification and supersedes conflicting public-input/guide-access requirements. All implementation belongs in this PR; PR 709 is not part of this work. Existing reward owners remain authoritative. -- [ ] Four required submission inputs and optional feedback; backend-selected revision context and exact actor-scoped replay. -- [ ] Forward migration preserves historical accepted commands and refuses unsafe old in-flight work before mutation. +- [x] Four required submission inputs and optional feedback; backend-selected revision context and exact actor-scoped replay. +- [x] Forward migration preserves historical accepted commands and refuses unsafe old in-flight work before mutation. - [ ] Approved project and governing task guides are readable/downloadable before claim under exact contributor authority. - [ ] Exact task/assignment status exposes current safe feedback, processing activity, revision terms and accepted evidence without internal-ID discovery. -- [ ] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits. +- [x] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits. - [ ] Combined public contributor journey proves correction, revision, replay, history and applicable existing awards on the integrated code. -The submission, guide, assignment status, and CLI/MCP changes are implemented. +The checked items have focused contract and PostgreSQL proof. The guide and +assignment status changes are implemented and await the connected native proof. The dedicated queue topology, isolated scanner-to-T5 regression and native caller conversion are integrated. Combined native execution and deployed qualification remain open. The managed-style adapter substitution passed through public diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 2213ce4a7..c852ada28 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -9,7 +9,7 @@ import argparse import asyncio from collections.abc import Awaitable, Callable -from contextlib import ExitStack, nullcontext +from contextlib import ExitStack, contextmanager, nullcontext from decimal import Decimal import hashlib import hmac @@ -46,10 +46,6 @@ from app.modules.tasks.models import Submission, SubmissionDispatch, WorkstreamTask from app.adapters.artifacts import trusted_submission_intake from app.adapters.checkers import configured_external_checker_execution -from experiments.pilot04_external_checker_runtime.public_probe_support import ( - _locked_spec, - _secret_archive, -) from tests.authorization.post_submit_routing.support import provision_router from tests.post_submit_materialization_helpers import ( archive_with_modes, @@ -71,11 +67,12 @@ from experiments.pilot04_external_checker_runtime.public_probe_support import ( # noqa: E402 _assert_outbox_worker_custody, _assert_task_has_no_effects, _json, _public_project, _require, _started_public_task, _token, _wait_outbox_acknowledged, - _with_fixture_file, _GOVERNED_TABLES, _fixture_hashes, _assert_input_hashes, + _with_fixture_file, _GOVERNED_TABLES, _fixture_hashes, _assert_input_hashes, _locked_spec, _secret_archive, ) from experiments.pilot04_external_checker_runtime.public_submission_clients import ( # noqa: E402 ContributorClients, seeded_issuer, ) +from cli.tests.journey.runtime import _interrupt_owned_groups, _live_group_members # noqa: E402 def _settings_digests(settings, nonce: bytes) -> dict[str, str]: @@ -187,12 +184,12 @@ def _process(command: list[str], *, env: dict[str, str], log: Path) -> subproces def _start_worker(env: dict[str, str], root: Path, role: str, queue: str, - generation: int = 1) -> tuple[subprocess.Popen, str]: + generation: int = 1, *, launch=None) -> tuple[subprocess.Popen, str]: """Start one owned prefork worker for exactly one registered workload queue.""" hostname = f"first-journey-{role}-{uuid4().hex}@localhost" celery_app = ("experiments.pilot04_external_checker_runtime.guide_worker" if role == "guide" else "app.workers.celery_app") - process = _process([ + process = (launch or _process)([ sys.executable, "-m", "celery", "-A", celery_app, "worker", "--pool=prefork", "--concurrency=1", f"--queues={queue}", "--hostname", hostname, @@ -252,19 +249,40 @@ def _require_parser_socket(settings): return path -def _live_group_members(group_id: int) -> set[int]: - """Find live members of only this fixture's start_new_session group.""" - members = set() - for entry in Path("/proc").iterdir(): - if not entry.name.isdecimal(): - continue +@contextmanager +def _owned_process_interrupts(processes: list[subprocess.Popen]): + """Reach the owned sessions before the isolation runner's short KILL grace.""" + launching = interrupted = False + + def stop_interrupted(): + _interrupt_owned_groups(processes) + raise KeyboardInterrupt + + def interrupt(_signum, _frame): + nonlocal interrupted + if interrupted: + return + interrupted = True + if not launching: + stop_interrupted() + + def start(command, *, env, log): + nonlocal launching + launching = True try: - fields = (entry / "stat").read_text().rsplit(") ", 1)[1].split() - if int(fields[2]) == group_id and fields[0] not in {"Z", "X"}: - members.add(int(entry.name)) - except (IndexError, OSError, ValueError): - continue - return members + process = _process(command, env=env, log=log) + processes.append(process) + finally: + launching = False + if interrupted: + stop_interrupted() + return process + + with ExitStack() as restore: + for signum in (signal.SIGTERM, signal.SIGINT): + previous = signal.signal(signum, interrupt) + restore.callback(signal.signal, signum, previous) + yield start def _stop_process(process: subprocess.Popen | None) -> None: @@ -1301,6 +1319,8 @@ async def run(database_url: str, image_reference: str, node_config: Path, factory = async_sessionmaker(engine, expire_on_commit=False) api = worker = beat = mcp = None workers: list[subprocess.Popen] = [] + processes: list[subprocess.Popen] = [] + signals = ExitStack() worker_generation = 0 def stop_owned_worker() -> None: @@ -1309,6 +1329,7 @@ def stop_owned_worker() -> None: _stop_process(worker) _require(worker.poll() is not None, "old POST effect worker did not exit") workers.remove(worker) + processes.remove(worker) async def start_owned_worker() -> None: nonlocal worker, worker_generation @@ -1317,12 +1338,13 @@ async def start_owned_worker() -> None: previous_pid = worker.pid if worker is not None else None worker_generation += 1 worker, hostname = _start_worker(env, root, "outbox", "workstream.outbox", - worker_generation) + worker_generation, launch=launch) workers.append(worker) _require(worker.pid != previous_pid, "restart reused the old POST worker process") await _wait_worker(worker, hostname) try: + launch = signals.enter_context(_owned_process_interrupts(processes)) await provision_material_services(factory, artifacts=True, checker=True) await provision_router(factory) await provision_reconciler(factory) @@ -1344,7 +1366,7 @@ async def start_owned_worker() -> None: "live execution cache lacks the reviewed project checker manifest") port = find_free_port() origin = f"http://127.0.0.1:{port}" - api = _process([ + api = launch([ sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(port), @@ -1353,11 +1375,11 @@ async def start_owned_worker() -> None: await _wait_api(origin, api) if clients is not None: clients.configure_processes(origin, find_free_port()) - mcp = _process([str(clients.mcp_executable)], env=clients.mcp_env, log=root / "mcp.log") + mcp = launch([str(clients.mcp_executable)], env=clients.mcp_env, log=root / "mcp.log") await clients.wait_ready(mcp) for role, queue in WORKER_ROLES: process, hostname = _start_worker( - cleanup_env if role == "source-cleanup" else env, root, role, queue + cleanup_env if role == "source-cleanup" else env, root, role, queue, launch=launch, ) workers.append(process) await _wait_worker(process, hostname) @@ -1365,7 +1387,7 @@ async def start_owned_worker() -> None: worker = process worker_generation = 1 scans_before_beat = await _scan_audit_count(factory) - beat = _process([ + beat = launch([ sys.executable, "-m", "celery", "-A", "app.workers.celery_app", "beat", "--loglevel=ERROR", "--schedule", str(root / "beat-schedule"), @@ -1416,18 +1438,15 @@ async def start_owned_worker() -> None: ) + (() if separate_runner else ('wrapper_sha256',))}, "runtime_trials": runtime_trials, "intake_trials": intake_trials, "human": true, "automatic": false} finally: - cleanup_error = None try: - _stop_owned_processes((mcp, beat, *reversed(workers), api)) - except RuntimeError as error: - cleanup_error = error - try: - for schedule_file in root.glob("beat-schedule*"): - schedule_file.unlink() + _stop_owned_processes(tuple(reversed(processes))) finally: - await engine.dispose() - if cleanup_error is not None: - raise cleanup_error + try: + for schedule_file in root.glob("beat-schedule*"): + schedule_file.unlink() + finally: + signals.close() + await engine.dispose() def main() -> int: diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index e414fb0d8..f6633f697 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -8,6 +8,7 @@ from itertools import count as sequence from pathlib import Path import shutil +import signal import subprocess import sys import tempfile @@ -136,6 +137,71 @@ def test_stopping_an_exited_leader_reaps_its_owned_child_group(self): if probe._live_group_members(launcher.pid): os.killpg(launcher.pid, 9) + def test_term_reaches_owned_sessions_before_runner_kill_grace(self): + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + child = "import os,signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);print(os.getpid(),flush=True);time.sleep(60)" + leader = f"import subprocess,sys;subprocess.Popen([sys.executable,'-c',{child!r}])" + fixture = """ +import os, signal, sys, time +from pathlib import Path +from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + +root, leader, child = Path(sys.argv[1]), sys.argv[2], sys.argv[3] +previous = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT)} +processes = [] +try: + with probe._owned_process_interrupts(processes) as start: + orphaned = start([sys.executable, '-c', leader], env=os.environ, log=root / 'orphaned.log') + orphaned.wait(timeout=5) + running = start([sys.executable, '-c', child], env=os.environ, log=root / 'running.log') + deadline = time.monotonic() + 5 + while not all(path.stat().st_size for path in root.glob('*.log')): + assert time.monotonic() < deadline + time.sleep(0.01) + receipt = root / 'groups' + receipt.write_text(f'{orphaned.pid} {running.pid}') + receipt.rename(root / 'ready') + signal.pause() +except KeyboardInterrupt: + assert all(signal.getsignal(s) == handler for s, handler in previous.items()) + for process in processes: + process.wait(timeout=1) + print('restored', flush=True) +""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + ready = root / 'ready' + env = os.environ.copy() + env['PYTHONPATH'] = os.pathsep.join(str(ROOT / path) for path in ('backend', 'backend/tests', '.')) + with subprocess.Popen([sys.executable, '-c', fixture, directory, leader, child], + env=env, stdout=subprocess.PIPE, text=True, + start_new_session=True) as supervisor: + groups = [] + try: + deadline = time.monotonic() + 45 + while not ready.exists() and supervisor.poll() is None and time.monotonic() < deadline: + time.sleep(.02) + self.assertTrue(ready.exists(), 'signal fixture did not reach owned process readiness') + groups = [int(value) for value in ready.read_text().split()] + self.assertEqual(len(groups), 2) + self.assertTrue(all(probe._live_group_members(group) for group in groups)) + os.killpg(supervisor.pid, signal.SIGTERM) + output, _ = supervisor.communicate(timeout=2) + self.assertEqual(supervisor.returncode, 0) + self.assertEqual(output.strip(), 'restored') + self.assertTrue(all(not probe._live_group_members(group) for group in groups)) + finally: + if supervisor.poll() is None: + supervisor.terminate() + try: + supervisor.wait(timeout=2) + except subprocess.TimeoutExpired: + supervisor.kill() + for group in groups: + if probe._live_group_members(group): + os.killpg(group, 9) + def test_partial_startup_still_attempts_every_owned_group_cleanup(self): from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe From 8f6b35f3df93615529a78194f13b3b5a087dffd0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:01:55 +0100 Subject: [PATCH 367/513] Scan owned process groups together within the runner kill grace --- cli/tests/journey/runtime.py | 39 +++++++++++++++--------- scripts/test_public_hosted_attachment.py | 8 +++-- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index 8f8d245b1..038b29814 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -22,19 +22,25 @@ } -def _live_group_members(group_id: int) -> set[int]: - """Observe live members of one process group created by this fixture.""" - members = set() +def _live_groups(group_ids: set[int]) -> dict[int, set[int]]: + """Observe the fixture's live groups in one process-table scan.""" + groups: dict[int, set[int]] = {} for entry in Path("/proc").iterdir(): if not entry.name.isdecimal(): continue try: fields = (entry / "stat").read_text().rsplit(") ", 1)[1].split() - if int(fields[2]) == group_id and fields[0] not in {"Z", "X"}: - members.add(int(entry.name)) + group = int(fields[2]) + if group in group_ids and fields[0] not in {"Z", "X"}: + groups.setdefault(group, set()).add(int(entry.name)) except (IndexError, OSError, ValueError): continue - return members + return groups + + +def _live_group_members(group_id: int) -> set[int]: + """Observe live members of one process group created by this fixture.""" + return _live_groups({group_id}).get(group_id, set()) def _stop_owned_group( @@ -79,21 +85,24 @@ def wait_until_empty(seconds: float) -> bool: def _interrupt_owned_groups(processes: list[subprocess.Popen]) -> None: """Fan out cancellation before the isolation runner's two-second KILL grace.""" - for process in reversed(processes): - if _live_group_members(process.pid): + owned = [process.pid for process in reversed(processes)] + if not owned: + return + active = _live_groups(set(owned)) + for group in owned: + if group in active: try: - os.killpg(process.pid, signal.SIGTERM) + os.killpg(group, signal.SIGTERM) except ProcessLookupError: pass deadline = time.monotonic() + 1 - while time.monotonic() < deadline and any( - _live_group_members(process.pid) for process in processes - ): + while active and time.monotonic() < deadline: time.sleep(0.05) - for process in reversed(processes): - if _live_group_members(process.pid): + active = _live_groups(set(active)) + for group in owned: + if group in active: try: - os.killpg(process.pid, signal.SIGKILL) + os.killpg(group, signal.SIGKILL) except ProcessLookupError: pass diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index f6633f697..585929156 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -139,6 +139,7 @@ def test_stopping_an_exited_leader_reaps_its_owned_child_group(self): def test_term_reaches_owned_sessions_before_runner_kill_grace(self): from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + from cli.tests.journey.runtime import _live_groups child = "import os,signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);print(os.getpid(),flush=True);time.sleep(60)" leader = f"import subprocess,sys;subprocess.Popen([sys.executable,'-c',{child!r}])" @@ -187,10 +188,13 @@ def test_term_reaches_owned_sessions_before_runner_kill_grace(self): self.assertEqual(len(groups), 2) self.assertTrue(all(probe._live_group_members(group) for group in groups)) os.killpg(supervisor.pid, signal.SIGTERM) - output, _ = supervisor.communicate(timeout=2) + deadline = time.monotonic() + 2 + while time.monotonic() < deadline and _live_groups(set(groups)): + time.sleep(.01) + self.assertFalse(_live_groups(set(groups)), 'owned descendants survived the isolation runner grace') + output, _ = supervisor.communicate(timeout=3) self.assertEqual(supervisor.returncode, 0) self.assertEqual(output.strip(), 'restored') - self.assertTrue(all(not probe._live_group_members(group) for group in groups)) finally: if supervisor.poll() is None: supervisor.terminate() From 1d28b567d70e5f7f1afd1be4b5e258238e9b6370 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:06:40 +0100 Subject: [PATCH 368/513] Admit installed 0092 head through migration preflight --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ backend/alembic/env.py | 2 +- backend/tests/test_alembic.py | 9 +++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 11b1e306b..9501a2cba 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11173,3 +11173,12 @@ cache and root pins were unchanged. Both runner services were active with reported healthy and had 93.2 GB free. This was a read-only recheck of the running infrastructure. Combined candidate execution and deployment qualification remain open. + +### Installed 0092 migration preflight correction + +CI's historical-schema lanes exposed a real migration preflight omission: +`alembic/env.py` admitted installed `0091` but refused the new installed `0092` +head before any migration could run. The closed list now names `0092`; its +earlier installed revisions and fresh-database guard remain intact. A current +database no-op upgrade regression checks the revision and public snapshot before +and after. This correction changes no migration body or retained rows. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 71055fd12..a6b8a8620 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0091_qualified_aws_source" +_CURRENT_HEAD_REVISION = "0092_submission_feedback" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index c18f04db5..2a4ee6409 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -118,6 +118,15 @@ async def _execute(database_url: str, statement: str, *arguments: object) -> Non await connection.close() +def test_current_installed_head_admits_noop_upgrade(isolated_database_env, migration_lock): + """An already-upgraded database remains a supported installed starting point.""" + before = asyncio.run(_database_snapshot(isolated_database_env)) + assert before["versions"] == [HEAD_REVISION] + with migration_lock(): + command.upgrade(_alembic_config(), "head") + assert asyncio.run(_database_snapshot(isolated_database_env)) == before + + @asynccontextmanager async def _historical_artifact_lineage_projection(database_url: str): """Expose null-only current ART lineage after restoring exact historical rows.""" From 71ba11f3b0f20f8e519524bd0b6c35055842a604 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:09:27 +0100 Subject: [PATCH 369/513] test: preserve exact public guide dependency and CLI formatting --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 53 +++++++++++++++ .../architecture/test_module_boundaries.py | 67 ++++++++++++++++--- cli/tests/integration/test_submission_http.py | 15 ++++- .../integration/test_submission_public_api.py | 5 +- .../integration/test_task_context_http.py | 4 +- cli/tests/integration/test_task_guide_http.py | 25 +++++-- .../integration/test_task_guide_public_api.py | 22 ++++-- 7 files changed, 163 insertions(+), 28 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 9501a2cba..1dce371aa 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11182,3 +11182,56 @@ head before any migration could run. The closed list now names `0092`; its earlier installed revisions and fresh-database guard remain intact. A current database no-op upgrade regression checks the revision and public snapshot before and after. This correction changes no migration body or retained rows. + +###0092 caller integration: exact TASK peer DTO and CLI formatting (2026-11-26) + +Intent: Backend45776768469 for pushed46858a75d (merge6e2761218) exposes +preflight TASK-self-only syntax assertion and CLI formatting failures before +contract execution. Canonical public API validation already accepts TASK's +intended reuse of PROJECTS ContributorGuideDocument from guide_reads; root +confirmed that single immutable public owner edge avoids duplicate schemas. + +Allowed exactly seven files: tests/architecture/test_module_boundaries.py, +cli/tests/integration/test_submission_http.py, test_submission_public_api.py, +test_task_context_http.py, test_task_guide_http.py, test_task_guide_public_api.py, +and this record. Change only exact TASK guide_documents.py peer-symbol exception +while preserving canonical public/private/mutability checks and rejection of +private/unrelated foreign imports. Add valid-first negative controls at that +exact path/symbol boundary. Format only the five named CLI files; verify AST +identity before/after and run unchanged CLI Ruff lint/format gates. + +Risk is architecture/CI assertion custody, not product behavior. Independent +ARCH review applies after freeze. No production source, registry, policy, debt +ledger, test budget, skip or broad foreign-API allowance. No PG/native run or +CI restart/cancel/push. Grouped historical0092 fixtures and public-contract +failures are separate bounded followups; do not weaken guards to clear them. +The existing draftPR708 remains the sole workstream; PR709 is untouched. + +The exact peer exception applies only to TASK api/guide_documents.py importing +ContributorGuideDocument without aliases from PROJECTS api/guide_reads. The +canonical public API validator, frozen/closed model checks, nonempty import scan +and all other TASK-self-only dependencies remain enforced. Six valid-first +mutations reject private imports, another peer schema, mixed allowed/foreign +symbols, wildcard, bare module import and the allowed symbol relocated to another +TASK API file. The wildcard probe initially expected AssertionError, but the +unchanged canonical parser correctly raised its earlier wildcard_import error; +the oracle now asserts that exact existing rejection rather than weakening it. + +Focused TASK/peer/private-reexport cases passed8 in4.97s before the final +nonempty-scan preservation tightening; final targeted replay records completion +separately. CLI Ruff0.15.22 lint and all105file format checks pass. The exactfive +formatted files have identical before/after ASTs +(/tmp/pr708-cli-format-preservation.json), so no assertions/fixture behavior changed. +No database or client runtime was rerun for formatting. Full structural validation +is being checked unchanged; independent ARCH review remains required. This +clears only these named early gates, not the other0092 callers or full CI. + +Final narrow replay passed8 in1.45s +(/tmp/pr708-peer-boundary-repair-final.log); full unchanged structural validator +exits0 (/tmp/pr708-0092-gate-structure.log). Ruff, changed links, Commitrail and +whitespace pass. Exactly seven scoped files; all product/registry/policy/debt +files unchanged. The six attack controls first pass the intended actual edge, +so their refusals cannot be satisfied by a globally broken import checker. +This is precommit source verification over57c939a30, not hosted or public journey +qualification. Root supplied architecture disposition; independent ARCH review +of the frozen exception remains pending. diff --git a/backend/tests/architecture/test_module_boundaries.py b/backend/tests/architecture/test_module_boundaries.py index 7fea151a1..d1af6a784 100644 --- a/backend/tests/architecture/test_module_boundaries.py +++ b/backend/tests/architecture/test_module_boundaries.py @@ -2,6 +2,7 @@ from __future__ import annotations +import ast import json from pathlib import Path @@ -238,21 +239,65 @@ def test_public_api_private_reexport_fails_closed(tmp_path: Path) -> None: ) +def _assert_task_public_dependencies(root: Path) -> None: + api_files = list((root / "backend/app/modules/tasks/api").rglob("*.py")) + assert api_files + peer_path = root / "backend/app/modules/tasks/api/guide_documents.py" + peer_module = "app.modules.projects.api.guide_reads" + observed_imports: set[str] = set() + for path in api_files: + imports = boundary.exact_source_imports(path, root) + observed_imports.update(imports) + allowed = set() + if path == peer_path and peer_module in imports: + nodes = [node for node in ast.walk(ast.parse(path.read_text())) + if isinstance(node, ast.ImportFrom) and node.module == peer_module] + assert len(nodes) == 1 and nodes[0].level == 0 + assert [(alias.name, alias.asname) for alias in nodes[0].names] == [ + ("ContributorGuideDocument", None) + ] + allowed.add(peer_module) + assert all(not target.startswith("app.modules.") + or target.startswith("app.modules.tasks.api") + or target in allowed for target in imports) + assert observed_imports + + def test_tasks_public_api_has_no_private_or_mutable_dependency() -> None: - """TASK facts remain dependency-safe immutable public contracts.""" + """TASK reuses only the exact frozen PROJECTS guide-document contract.""" boundary._validate_public_apis( # noqa: SLF001 - architecture proof ROOT, boundary.load_registry(REGISTRY) ) - api_files = list((ROOT / "backend/app/modules/tasks/api").rglob("*.py")) - assert api_files - imports: set[str] = set() - for path in api_files: - imports.update(boundary.exact_source_imports(path, ROOT)) - assert imports - assert all( - not target.startswith("app.modules.") or target.startswith("app.modules.tasks.api") - for target in imports - ) + from app.modules.projects.api.guide_reads import ContributorGuideDocument + + assert ContributorGuideDocument.model_config["frozen"] is True + assert ContributorGuideDocument.model_config["extra"] == "forbid" + _assert_task_public_dependencies(ROOT) + + +@pytest.mark.parametrize(("filename", "source"), [ + ("guide_documents.py", "from app.modules.projects.repository import ProjectRepository\n"), + ("guide_documents.py", "from app.modules.projects.api.guide_reads import ProjectGuideRecord\n"), + ("guide_documents.py", "from app.modules.projects.api.guide_reads import ContributorGuideDocument, ProjectGuideRecord\n"), + ("guide_documents.py", "from app.modules.projects.api.guide_reads import *\n"), + ("guide_documents.py", "import app.modules.projects.api.guide_reads\n"), + ("another.py", "from app.modules.projects.api.guide_reads import ContributorGuideDocument\n"), +]) +def test_task_peer_guide_dependency_refuses_private_foreign_or_relocated_import( + tmp_path: Path, filename: str, source: str, +) -> None: + """Each attack first passes the one real peer-edge control.""" + api = tmp_path / "backend/app/modules/tasks/api" + _write(api / "guide_documents.py", + "from app.modules.projects.api.guide_reads import ContributorGuideDocument\n") + _assert_task_public_dependencies(tmp_path) + _write(api / filename, source) + if source.endswith("import *\n"): + with pytest.raises(AuthorizationBoundaryError, match="^wildcard_import$"): + _assert_task_public_dependencies(tmp_path) + else: + with pytest.raises(AssertionError): + _assert_task_public_dependencies(tmp_path) def test_projects_public_api_has_no_private_or_mutable_dependency() -> None: diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py index 071bfcf97..6297a3c72 100644 --- a/cli/tests/integration/test_submission_http.py +++ b/cli/tests/integration/test_submission_http.py @@ -188,9 +188,18 @@ def test_submit_uses_the_same_inputs_for_revision(cli, tmp_path): path = tmp_path / "revision.zip" path.write_bytes(b"PK\x03\x04revision") with http_fixture() as (origin, response, requests): - for flag in ("--predecessor", "--revision-preparation-id", "--revision-preparation-sha256", - "--summary", "--attestation"): - assert_failure(cli(origin, TOKEN, *submit_args(path), flag, SUBMISSION), "invalid_arguments", 2) + for flag in ( + "--predecessor", + "--revision-preparation-id", + "--revision-preparation-sha256", + "--summary", + "--attestation", + ): + assert_failure( + cli(origin, TOKEN, *submit_args(path), flag, SUBMISSION), + "invalid_arguments", + 2, + ) assert requests == [] respond(response, acceptance(), 202) result = cli(origin, TOKEN, *submit_args(path)) diff --git a/cli/tests/integration/test_submission_public_api.py b/cli/tests/integration/test_submission_public_api.py index 26ef7e062..af7df66ce 100644 --- a/cli/tests/integration/test_submission_public_api.py +++ b/cli/tests/integration/test_submission_public_api.py @@ -402,7 +402,10 @@ async def call(*args, denied=None, token=None): assert status["current_status"] == "evaluation_pending" assert status["next_action"] == "awaiting_evaluation" assert status["assignment"]["latest_submission"] is None - assert status["intake"]["pre_submission_results"] == receipt["pre_submission_results"] + assert ( + status["intake"]["pre_submission_results"] + == receipt["pre_submission_results"] + ) by_key = await call( "task", "submission-operation", str(f.task), "--idempotency-key", key ) diff --git a/cli/tests/integration/test_task_context_http.py b/cli/tests/integration/test_task_context_http.py index 5256fec8f..d3c55dbab 100644 --- a/cli/tests/integration/test_task_context_http.py +++ b/cli/tests/integration/test_task_context_http.py @@ -489,9 +489,7 @@ def test_requirements_reject_missing_null_or_substituted_facts(cli): ("policy_schema_version", {}), ): cases.append(REQUIREMENTS | {key: wrong}) - for key in ( - "allowed_storage_schemes", - ): + for key in ("allowed_storage_schemes",): cases.append(REQUIREMENTS | {key: [None]}) for key, required in ( ("required_artifacts", ("key", "path", "hash_required", "required")), diff --git a/cli/tests/integration/test_task_guide_http.py b/cli/tests/integration/test_task_guide_http.py index 4c1f46caf..d98232f4b 100644 --- a/cli/tests/integration/test_task_guide_http.py +++ b/cli/tests/integration/test_task_guide_http.py @@ -98,9 +98,9 @@ def log_message(self, *_): def test_assigned_guide_list_and_verified_private_download(cli, tmp_path): with guide_http() as (origin, state, requests): listed = cli(origin, TOKEN, "task", "guide", TASK, "-o", "json") - assert listed.returncode == 0 and json.loads(listed.stdout)["documents"] == [DOCUMENT], ( - listed.stderr - ) + assert listed.returncode == 0 and json.loads(listed.stdout)["documents"] == [ + DOCUMENT + ], listed.stderr terminal = cli(origin, TOKEN, "task", "guide", TASK) assert ( terminal.returncode == 0 @@ -243,7 +243,9 @@ def test_full_document_list_uses_bounded_context_not_small_page_limit(cli): assert len(json.dumps(state["context"]).encode()) > 64 * 1024 result = cli(origin, TOKEN, "task", "guide", TASK, "-o", "json") assert result.returncode == 0, result.stderr - assert json.loads(result.stdout)["documents"] == documents and len(requests) == 1 + assert ( + json.loads(result.stdout)["documents"] == documents and len(requests) == 1 + ) @pytest.mark.parametrize("damage", ("hash", "short", "long", "content_type")) @@ -328,11 +330,22 @@ def test_canonical_duplicate_document_ids_are_rejected(cli): def test_ready_guide_can_download_before_claim_and_refuses_symlink(cli, tmp_path): with guide_http() as (origin, state, requests): state["context"]["task"]["status"] = "ready" - state["context"]["lifecycle"] = {"assigned_to_current_actor": False, "next_actions": ["claim"]} + state["context"]["lifecycle"] = { + "assigned_to_current_actor": False, + "next_actions": ["claim"], + } first_directory = tmp_path / "valid" first_directory.mkdir() result = cli( - origin, TOKEN, "task", "guide", TASK, "--download", str(first_directory), "-o", "json", + origin, + TOKEN, + "task", + "guide", + TASK, + "--download", + str(first_directory), + "-o", + "json", ) assert result.returncode == 0, result.stderr assert json.loads(result.stdout)["documents"] == [DOCUMENT] diff --git a/cli/tests/integration/test_task_guide_public_api.py b/cli/tests/integration/test_task_guide_public_api.py index 12abf210c..d04057459 100644 --- a/cli/tests/integration/test_task_guide_public_api.py +++ b/cli/tests/integration/test_task_guide_public_api.py @@ -293,16 +293,30 @@ async def test_installed_cli_reads_and_downloads_real_assigned_originals( project_guides = tmp_path / "project-guide" project_guides.mkdir() approved = await asyncio.to_thread( - cli, origin, "task-token", "project", "guide", "approved", - guide_world.project["id"], "--download", str(project_guides), "-o", "json", + cli, + origin, + "task-token", + "project", + "guide", + "approved", + guide_world.project["id"], + "--download", + str(project_guides), + "-o", + "json", ) assert approved.returncode == 0, approved.stderr approved_manifest = json.loads(approved.stdout) assert approved_manifest["guide_id"] == manifest["guide_id"] for document, original, extension in zip( - approved_manifest["documents"], guide_world.originals, ("md", "pdf"), strict=True, + approved_manifest["documents"], + guide_world.originals, + ("md", "pdf"), + strict=True, ): - assert (project_guides / f"{document['document_id']}.{extension}").read_bytes() == original + assert ( + project_guides / f"{document['document_id']}.{extension}" + ).read_bytes() == original set_dev_actor( monkeypatch, roles="project_manager", subject="project-manager-subject" From c027c2c213529ce472f5e29d2ff5c366b3057a1e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:22:26 +0100 Subject: [PATCH 370/513] test: align minimal submission callers and exact feedback projections --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 76 +++++++++++++++++++ .../artifacts/intake_recovery_support.py | 3 +- ...est_submission_finalization_worker_loss.py | 13 +++- .../setup_finalization/test_catalogue.py | 2 + .../submission_history/test_absence.py | 2 +- .../task_authority/test_task_commands.py | 17 ++++- .../tests/checkers/execution/test_storage.py | 4 +- .../tests/outbox/test_delivery_topology.py | 3 +- backend/tests/test_api_rate_controls.py | 3 + backend/tests/test_artifact_architecture.py | 3 +- ..._submission_bundle_preparation_recovery.py | 10 +-- backend/tests/test_tasks.py | 10 --- 12 files changed, 122 insertions(+), 24 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 1dce371aa..fbfdd2a2a 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11235,3 +11235,79 @@ so their refusals cannot be satisfied by a globally broken import checker. This is precommit source verification over57c939a30, not hosted or public journey qualification. Root supplied architecture disposition; independent ARCH review of the frozen exception remains pending. + + +###0092 current caller and projection alignment (2026-11-26) + +Intent: group the current-contract CI failures from45776768469 by owner, after +the separate exact peer-edge/CLI format repair. Allowed twelve files: this +record; artifacts/intake_recovery_support.py; test_submission_bundle_preparation_recovery.py; +test_artifact_architecture.py; authorization/task_authority/test_task_commands.py; +authorization/setup_finalization/test_catalogue.py; test_api_rate_controls.py; +checkers/execution/test_storage.py; authorization/submission_history/test_absence.py; +test_tasks.py; outbox/test_delivery_topology.py; and +artifacts/test_submission_finalization_worker_loss.py. No production source, +sharedconftest, historicalrestore/schema fixture, policy, skip, budget or new +compatibility alias. ARCH separately owns genuine retained private-attestation +witness and all historical schema/snapshot failures; preserve their assertions. + +Reconstruct current recovery input from exact stored task/assignment/feedback, +not the enriched server command record as a caller DTO. Require exactly three +current input fields and retire only the two obsolete removed helper parameters +for required summary/attestation. Existing closed/bounded current coverage is +test_metadata_canonical_fixture_and_round_trip_preserve_exact_feedback, +test_feedback_rejects_unrepresentable_headers_without_normalization, +test_submit_metadata_rejects_retired_inputs and +test_frozen_values_revalidate_nested_instances_and_reject_unknown_command_fields +in test_submission_intake_contracts.py. All other malformed locked-policy cases +remain. Apply ledger change only if actual structural inventory demands it; no +blind baseline update. + +Preserve mounted exact ordered/privacy-safe feedback and retained warning +projection, while optional current input is feedback, not removed summary or +attestation. Add exact new feedback history field, the approved two action IDs +and three read-rate routes; keep independent exact inventories and mutation +controls. Required guide documents now compare exact locked snapshot IDs, +fixture byte hash/count/media/order and task-bound read references; never just +nonempty. Stored checker finding message is verbatim with no invented fix. + +Cold dedicated-worker negative fixture must bind its existing explicit eager +setting before importing Celery. After actual T5 commit, broker rescan legitimately +sees one original finalizer lease plus one pending POST. Require that exact extra +uninvoked POST and exacttwo counts only for after_commit; before_observation +stays exactone. Keep authority/lease/source/redelivery/graph/cleanup assertions. +Risk is fixture/projection/custody proof. QA/CI/ARCH review exact test preservation +and stale-producer retirement; root coordinates one focused PG/broker run after +native slotrelease. No new service or end-to-end completion claim; all work stays +in PR708, never709. + +Focused current-contract pure cases passed42 in49.97s +(/tmp/pr708-0092-current-contract-pure-v1.log), including mounted exact feedback +and privacy bounds, current metadata canonical/bounded/retired-field guards, +exact activated action/rate/history schema and twelve remaining malformed locked +policy cases. The separate cold dedicated-worker test passed3 in17.05s +(/tmp/pr708-0092-cold-worker-boundary.log); explicit eager configuration now +precedes import, with no production default changed. Its plugin-disabled warning +is unchanged and no async test was skipped. + +Guide-hint oracle binds exactly two locked originals (guide.pdf/rubric.pdf), +snapshot item IDs, canonical fixture hash/count, order/media and task-bound read +references. Finding history expects the actual retained diagnosis and no invented +fix; fallback messages remain tested elsewhere. Retained optional packet warning +projection remains a mounted-command response test, not a claim that new minimal +input produces deprecated summary/attestation warnings. Only feedback is optional +current input. All private path/storage fields remain forbidden. + +Full unchanged structural validator exits0 +(/tmp/pr708-0092-current-contract-structure.log). The two obsolete parameters +shrink test_tasks.py by ten lines; no ledger entry for that file requires refresh, +and no policy/debt file changed. Ruff and whitespace pass. Exactly twelve scoped +files; privacy test and seed helpers, historical migrations and conftest untouched. + +Runtime evidence remains pending: the current accepted-recovery helper consumers, +real guide-hint/source metadata and stored finding history, and the changed +after_commit Redis/worker rescan assertions have not been executed on this +candidate. Root explicitly holds heavy PG/broker work while native journey has +priority. No source/provider/authorization owner was mocked or changed to make +their future run pass. This clean source checkpoint is for review and later +focused execution, not a complete QA/CI/deployed-journey verdict. diff --git a/backend/tests/artifacts/intake_recovery_support.py b/backend/tests/artifacts/intake_recovery_support.py index 5b5e46cd8..11d0f17ea 100644 --- a/backend/tests/artifacts/intake_recovery_support.py +++ b/backend/tests/artifacts/intake_recovery_support.py @@ -38,7 +38,8 @@ async def recovery_intake(admission_intake, tmp_path): async with f.factory() as session: row = await session.get(SubmissionIntakeOperation, str(owner.operation_id)) event_id = UUID(row.finalization_event_id) - metadata = SubmissionIntakeMetadata.model_validate_json(json.dumps(row.command_metadata)) + metadata = SubmissionIntakeMetadata(task_id=UUID(row.task_id), assignment_id=UUID(row.assignment_id), + feedback=row.command_metadata["feedback"]) intake_key = UUID(row.idempotency_key) async def lost(_envelope): raise RuntimeError("lost original finalizer") diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py index d44210534..e44290bd5 100644 --- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py +++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py @@ -614,6 +614,14 @@ async def _assert_broker_redelivery(case, f, kill_at, result): assert operation.state == ("finalized" if kill_at == "after_commit" else "finalization_pending") assert operation.acceptance_receipt == case.before[1] assert operation.finalized_submission_id == marker["submission_id"] + posts = list(await session.scalars(select(OutboxEvent).where( + OutboxEvent.project_id == f.project, + OutboxEvent.event_type == "PostSubmissionEvaluationRequested", + ))) + assert len(posts) == (1 if kill_at == "after_commit" else 0) + for post in posts: + assert post.delivery_state == "pending" and post.attempt_count == 0 + assert post.payload["submission_id"] == marker["submission_id"] return max(event.claim_expires_at, operation.continuation_expires_at), marker["submission_id"] @@ -660,13 +668,14 @@ async def test_real_broker_redelivers_killed_finalizer_and_recovers_owner_lease( case.process.start() redelivery = await _next_broker_result(case) due, original_submission = await _assert_broker_redelivery(case, f, kill_at, redelivery) + expected_scan = 2 if kill_at == "after_commit" else 1 await _wait_for_broker_database_time(f.factory, due) - assert await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) == {"selected": 1, "published": 1} + assert await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) == {"selected": expected_scan, "published": expected_scan} recovered = await _next_broker_result(case) assert recovered[2] == {"status": "delivery_recorded"} due = await _assert_broker_recovered_unknown(case, f) await _wait_for_broker_database_time(f.factory, due) - assert await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) == {"selected": 1, "published": 1} + assert await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending) == {"selected": expected_scan, "published": expected_scan} finalized = await _next_broker_result(case) assert finalized[2] == {"status": "delivery_recorded"} submission = await _assert_broker_finalized_once(f, case.operation_id, case.before[1], diff --git a/backend/tests/authorization/setup_finalization/test_catalogue.py b/backend/tests/authorization/setup_finalization/test_catalogue.py index 7c3913019..79e06a6e2 100644 --- a/backend/tests/authorization/setup_finalization/test_catalogue.py +++ b/backend/tests/authorization/setup_finalization/test_catalogue.py @@ -137,6 +137,8 @@ ActionId.PROJECT_EFFECTIVE_SUBMISSION_ARTIFACT_POLICY_READ, ActionId.PROJECT_PRE_SUBMIT_CHECKER_POLICY_READ, ActionId.PROJECT_ACTIVE_GUIDE_READ, + ActionId.PROJECT_CONTRIBUTOR_GUIDE_READ, + ActionId.TASK_ASSIGNMENT_READ, ActionId.ARTIFACT_GUIDE_SOURCE_INGEST, ActionId.ARTIFACT_TASK_IMPORT_SOURCE_DECLARE, ActionId.ARTIFACT_TASK_IMPORT_SOURCE_UPLOAD, diff --git a/backend/tests/authorization/submission_history/test_absence.py b/backend/tests/authorization/submission_history/test_absence.py index 02290d7e8..0aff3c970 100644 --- a/backend/tests/authorization/submission_history/test_absence.py +++ b/backend/tests/authorization/submission_history/test_absence.py @@ -29,7 +29,7 @@ def test_removed_mutation_and_worker_surface(): assert set(AuthVerificationResult.model_fields) == {"token"} -SUBMISSION_FIELDS = set("id task_id version status status_reason summary submitted_at decided_at finding_counts locked_at supersedes_submission_id evidence_items".split()) +SUBMISSION_FIELDS = set("id task_id version status status_reason summary feedback submitted_at decided_at finding_counts locked_at supersedes_submission_id evidence_items".split()) MANAGER_SUBMISSION_FIELDS = SUBMISSION_FIELDS | set("""contributor_id task_assignment_id contribution_policy_version_id locked_guide_version locked_post_submit_checker_policy_id locked_post_submit_checker_policy_version locked_post_submit_checker_policy_hash locked_review_policy_id locked_review_policy_generation locked_review_policy_hash diff --git a/backend/tests/authorization/task_authority/test_task_commands.py b/backend/tests/authorization/task_authority/test_task_commands.py index d861357d2..e574c5534 100644 --- a/backend/tests/authorization/task_authority/test_task_commands.py +++ b/backend/tests/authorization/task_authority/test_task_commands.py @@ -1,6 +1,7 @@ """Real task HTTP transitions; identity tokens do not grant project authority.""" from uuid import uuid4 +import hashlib import pytest from sqlalchemy import func, select @@ -10,6 +11,7 @@ from app.modules.actors.models import ActorIdentityLink, ActorProfile, LegacyWorkflowEligibility from app.modules.actors.service import ActorService, IdentityLinkRevoked from app.modules.authorization.models import ProjectRoleGrant +from app.modules.projects.models import GuideSourceSnapshotItem from app.modules.authorization.runtime import AuthorizationEvidenceUnavailable from app.modules.authorization.task_authorization import PreparedTaskAuthorization from app.modules.tasks.api import TaskAuthorityDenied @@ -28,6 +30,7 @@ auth_headers, set_dev_actor, ) +from tests.projects.guide_compilation.helpers import SOURCE_BYTES from tests.authorization.task_authority.test_lifecycle_races import ( _read_task_contributor_race_snapshot, ) @@ -100,6 +103,10 @@ async def test_project_grant_drives_claim_and_current_action_hints(task_client, async with db_session.get_session_factory()() as session: untouched = await session.get(WorkstreamTask, task_id) assert untouched.status == "ready" and untouched.assigned_to is None + locked_documents = list(await session.scalars(select(GuideSourceSnapshotItem).where( + GuideSourceSnapshotItem.source_snapshot_id == untouched.locked_guide_source_snapshot_id, + GuideSourceSnapshotItem.source_kind == "document", + ).order_by(GuideSourceSnapshotItem.item_order))) assert ( await session.scalar(select(TaskAssignment).where(TaskAssignment.task_id == task_id)) is None @@ -115,7 +122,15 @@ async def test_project_grant_drives_claim_and_current_action_hints(task_client, context = await task_client.get(f"/api/v1/tasks/{task_id}/work-context", headers=auth_headers()) assert context.status_code == 200, context.text assert context.json()["lifecycle"] == {"assigned_to_current_actor": False, "next_actions": ["claim"]} - assert context.json()["guide_documents"] == [] + assert [(item.source_label, item.item_order) for item in locked_documents] == [ + ("guide.pdf", 0), ("rubric.pdf", 1), + ] + assert context.json()["guide_documents"] == [{ + "document_id": str(item.id), "label": item.source_label, "order": item.item_order, + "media_type": "application/pdf", "sha256": "sha256:" + hashlib.sha256(SOURCE_BYTES).hexdigest(), + "byte_count": len(SOURCE_BYTES), + "read_reference": f"/api/v1/tasks/{task_id}/guide/documents/{item.id}/content", + } for item in locked_documents] claimed = await task_client.post(f"/api/v1/tasks/{task_id}/claim", headers=auth_headers()) assert claimed.status_code == 200, claimed.text assert claimed.json()["assignment"]["contributor_id"] == actor_id diff --git a/backend/tests/checkers/execution/test_storage.py b/backend/tests/checkers/execution/test_storage.py index b0117cd35..eac3e5151 100644 --- a/backend/tests/checkers/execution/test_storage.py +++ b/backend/tests/checkers/execution/test_storage.py @@ -40,8 +40,8 @@ async def test_failed_external_image_history_uses_normalized_result_status( member, = rows[0].results assert member.checker_name == h.request.policy.entries[0].requirement_id assert member.status == "failed" and member.severity == "error" - assert member.worker_message == "Project check failed." - assert member.worker_suggested_fix == "Review the project guide and check findings." + assert member.worker_message == "Post evidence failed." + assert member.worker_suggested_fix is None if manager: assert member.blocks_review is True assert member.message == member.worker_message diff --git a/backend/tests/outbox/test_delivery_topology.py b/backend/tests/outbox/test_delivery_topology.py index c0d134372..16fc7aa20 100644 --- a/backend/tests/outbox/test_delivery_topology.py +++ b/backend/tests/outbox/test_delivery_topology.py @@ -275,10 +275,11 @@ def test_dedicated_worker_rejects_foreign_registered_delivery_before_owner_io( ): from app.core.config import get_settings from app.workers import source_cleanup_topology as boundary - from app.workers.celery_app import create_celery_app monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true") get_settings.cache_clear() + from app.workers.celery_app import create_celery_app + app = create_celery_app() monkeypatch.setattr(boundary, "_selected_queue_parent", os.getpid()) monkeypatch.setattr(boundary, "_selected_queue", selected) diff --git a/backend/tests/test_api_rate_controls.py b/backend/tests/test_api_rate_controls.py index 02a446615..cec3660d8 100644 --- a/backend/tests/test_api_rate_controls.py +++ b/backend/tests/test_api_rate_controls.py @@ -1012,6 +1012,9 @@ async def unavailable() -> None: # PILOT-READ-3 Project Manager and Finance project reads. ("GET", "/projects/{project_id}/assignments"), ("GET", "/projects/{project_id}/contribution-policies"), + ("GET", "/projects/{project_id}/contributor-guide"), + ("GET", "/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content"), + ("GET", "/tasks/{task_id}/assignments/{assignment_id}"), ("GET", "/projects/{project_id}/guides"), ("GET", "/projects/{project_id}/guides/{guide_id}"), ("GET", "/projects/{project_id}/guides/{guide_id}/activation-readiness"), diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py index 1c5d4a15a..0c4a6b2f9 100644 --- a/backend/tests/test_artifact_architecture.py +++ b/backend/tests/test_artifact_architecture.py @@ -900,7 +900,8 @@ def test_submission_intake_metadata_never_carries_prepared_authority() -> None: assert "prepared_authorization" not in fields assert fields["task_id"] == {"UUID"} assert fields["assignment_id"] == {"UUID"} - assert fields["predecessor_submission_id"] == {"UUID"} + assert set(fields) == {"task_id", "assignment_id", "feedback"} + assert fields["feedback"] == {"str"} assert "actor" not in fields assert "idempotency_key" not in fields diff --git a/backend/tests/test_submission_bundle_preparation_recovery.py b/backend/tests/test_submission_bundle_preparation_recovery.py index 5e5e63ce5..828c1c9bd 100644 --- a/backend/tests/test_submission_bundle_preparation_recovery.py +++ b/backend/tests/test_submission_bundle_preparation_recovery.py @@ -86,7 +86,7 @@ async def test_mounted_submission_returns_exact_ordered_bounded_feedback() -> No payload = response.json() assert set(payload) == {"error"} assert payload["error"]["code"] == "pre_submission_checker_failed" - assert payload["error"]["message"] == "pre_submission_checker_failed" + assert payload["error"]["message"] == "The ZIP did not pass the pre-submission checks" assert payload["error"]["retryable"] is False assert payload["error"]["details"] == { "status": "failed", @@ -163,8 +163,8 @@ async def test_mounted_submission_preserves_non_feedback_error_boundaries( @pytest.mark.asyncio -async def test_mounted_submission_keeps_missing_optional_packet_text_warning_only() -> None: - """Missing summary and attestation reach PRE as empty warning-only values.""" +async def test_mounted_submission_keeps_feedback_optional_and_projects_retained_warnings() -> None: + """Current optional feedback preserves returned retained warning facts.""" from datetime import UTC, datetime async def accept(metadata, chunks, **kwargs): @@ -180,8 +180,8 @@ async def accept(metadata, chunks, **kwargs): response = await _mounted_submission_response(command=command, packet_text=False) assert response.status_code == 202 submitted = command.submit.await_args.args[0] - assert submitted.summary == "" - assert submitted.contributor_attestation == "" + assert submitted.feedback is None + assert set(type(submitted).model_fields) == {"task_id", "assignment_id", "feedback"} warnings = [item["warning_code"] for item in response.json()["pre_submission_results"] if item["status"] == "warning"] assert warnings == ["submission_summary_missing", "submission_attestation_missing"] diff --git a/backend/tests/test_tasks.py b/backend/tests/test_tasks.py index 29157084c..88a77cd0b 100644 --- a/backend/tests/test_tasks.py +++ b/backend/tests/test_tasks.py @@ -390,16 +390,6 @@ async def test_task_repository_delegates_audit_persistence() -> None: ("_policy_object", ({"rules": []}, "rules"), "effective_policy.rules"), ("_optional_policy_text", ({"note": ""}, "note"), "effective_policy.note"), ("_optional_policy_non_negative_int", ({"limit": -1}, "limit"), "effective_policy.limit"), - ( - "_required_packet_fields", - ({"required_packet_fields": "summary"},), - "effective_policy.required_packet_fields", - ), - ( - "_required_packet_fields", - ({"required_packet_fields": [""]},), - "effective_policy.required_packet_fields", - ), ("_policy_rule_text", ([], "path", "files"), "effective_policy.files"), ( "_policy_rule_text", From d8046ea232de7a15a165eb87403f7f87a3ba7599 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:31:43 +0100 Subject: [PATCH 371/513] Compare native cache readiness with the typed manifest count --- .../run_public_journey_probe.py | 19 ++++++++++++++----- scripts/test_public_hosted_attachment.py | 13 +++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index c852ada28..0334b0af4 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -46,6 +46,8 @@ from app.modules.tasks.models import Submission, SubmissionDispatch, WorkstreamTask from app.adapters.artifacts import trusted_submission_intake from app.adapters.checkers import configured_external_checker_execution +from app.interfaces.external_checker_execution import ExternalCheckerServiceHealth +from app.interfaces.trusted_submission_intake import TrustedIntakeIdentity from tests.authorization.post_submit_routing.support import provision_router from tests.post_submit_materialization_helpers import ( archive_with_modes, @@ -1195,6 +1197,17 @@ def _read_runner_configuration(node_config: Path, root: Path, custody: dict, *, return service_config +def _require_runner_health(execution: ExternalCheckerServiceHealth, intake: TrustedIntakeIdentity, + expected_cache_count: int) -> None: + """Compare authenticated readiness with the independently verified runner configuration.""" + _require((execution.runtime, execution.isolation_mode) + == (intake.runtime, intake.isolation_mode) + == ("smolvm", "smol-microvm"), "typed capability health identities disagree") + # Health reports a count. The reviewed configuration binds the exact project manifest. + _require(execution.cached_platform_manifests == expected_cache_count, + "live execution cache count differs from reviewed runner configuration") + + async def run(database_url: str, image_reference: str, node_config: Path, broker_url: str, root: Path, expected_custody: Path, clients: ContributorClients | None = None, *, separate_runner: bool = False) -> dict: @@ -1359,11 +1372,7 @@ async def start_owned_worker() -> None: intake_health = await trusted_submission_intake(runtime_settings).health() execution_health = await configured_external_checker_execution(runtime_settings).health() - _require((execution_health.runtime, execution_health.isolation_mode) - == (intake_health.runtime, intake_health.isolation_mode) - == ("smolvm", "smol-microvm"), "typed capability health identities disagree") - _require(image["platform_manifest_digest"] in execution_health.cached_platform_manifests, - "live execution cache lacks the reviewed project checker manifest") + _require_runner_health(execution_health, intake_health, len(service_config["cache"])) port = find_free_port() origin = f"http://127.0.0.1:{port}" api = launch([ diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 585929156..48446114d 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -29,6 +29,19 @@ class PublicJourneyWorkerCustody(unittest.TestCase): + def test_runner_health_reports_reviewed_cache_size_as_a_count(self): + from app.interfaces.external_checker_execution import ExternalCheckerServiceHealth + from app.interfaces.trusted_submission_intake import TrustedIntakeIdentity + from app.modules.checkers.api.default_checker import WORKSTREAM_DEFAULT_BEHAVIOR_SHA256 + from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe + + intake = TrustedIntakeIdentity('sha256:' + '1' * 64, 'sha256:' + '2' * 64, + WORKSTREAM_DEFAULT_BEHAVIOR_SHA256, 'smolvm', 'smol-microvm', 1000, 2 ** 30) + execution = ExternalCheckerServiceHealth('linux', 'amd64', 'smolvm', 'smol-microvm', 3, 10001, 10001) + probe._require_runner_health(execution, intake, 3) + with self.assertRaisesRegex(RuntimeError, 'live execution cache count differs'): + probe._require_runner_health(execution, intake, 2) + def test_separate_runner_uses_exact_baseline_config_without_local_fault_files(self): from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe From e273b576226758858bb21ec8231992518318a7c6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:15:14 +0100 Subject: [PATCH 372/513] test(submission): preserve retained history across feedback migration --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 13 ++++ .../submission_history/test_migration.py | 71 +++++++++++++++++++ .../submission_history/test_privacy.py | 6 +- backend/tests/migration_revision_fixtures.py | 1 + .../migrations/test_source_pre_cutover.py | 14 +++- .../test_unsealed_source_cleanup_migration.py | 69 +++++++++++------- .../submission_dispatch/test_migration.py | 2 +- 7 files changed, 143 insertions(+), 33 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index fbfdd2a2a..0f5b06a2e 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11311,3 +11311,16 @@ candidate. Root explicitly holds heavy PG/broker work while native journey has priority. No source/provider/authorization owner was mocked or changed to make their future run pass. This clean source checkpoint is for review and later focused execution, not a complete QA/CI/deployed-journey verdict. + +### Retained 0092 history fixture correction + +The historical migration probes keep their predecessor schemas and rows intact. +Where current test owners construct an older cleanup or revision source, a +null-only `submissions.feedback` read projection is removed before the real +upgrade; the migration snapshots then require the actual 0092 column to be +null and preserve every preceding field. The current HTTP history privacy +fixture uses its still-stored private package URI as the nonleak witness. A +separate checksum-bound 0024 archive exercises the genuine old private +attestation after upgrade through the current fixed history projection. +These fixture changes do not relax runtime custody, authorization, or SQL +guards. Focused PostgreSQL replay and final evidence remain pending. diff --git a/backend/tests/authorization/submission_history/test_migration.py b/backend/tests/authorization/submission_history/test_migration.py index 1d96e5132..311646925 100644 --- a/backend/tests/authorization/submission_history/test_migration.py +++ b/backend/tests/authorization/submission_history/test_migration.py @@ -67,6 +67,77 @@ async def probe(before): asyncio.run(probe(before)) +async def test_archived_private_attestation_stays_out_of_history_projection( + tmp_path, isolated_database_env, migration_lock, +): + """Read a genuine old packet after upgrade without selecting its private text.""" + from uuid import UUID + + from sqlalchemy import event, text + from sqlalchemy.engine import Engine + + from app.adapters.tasks import submission_history_repository + from app.db import session as db_session + from tests.historical_submission_fixtures import historical_material_fixture + from tests.migration_fixtures import current_schema_revision + + url = isolated_database_env.replace("+asyncpg", "") + with migration_lock(): + await db_session.dispose_engine() + connection = await asyncpg.connect(url) + try: + await connection.execute("DROP SCHEMA public CASCADE; CREATE SCHEMA public") + finally: + await connection.close() + await asyncio.to_thread(command.upgrade, config(), "0024_require_second_review_false") + async with historical_material_fixture(tmp_path, isolated_database_env) as h: + async with h.factory() as session: + old = (await session.execute(text(""" + SELECT to_jsonb(s) AS packet,t.project_id,s.contributor_id + FROM public.submissions s + JOIN public.workstream_tasks t ON t.id=s.task_id + WHERE s.id=:id + """), {"id": h.created["submission_id"]})).one() + packet = old.packet + private_attestation = packet["worker_attestation"] + assert private_attestation and packet["summary"] + await asyncio.to_thread(command.upgrade, config(), current_schema_revision()) + captured = [] + + def capture(_connection, _cursor, _statement, _parameters, context, _many): + compiled = getattr(context, "compiled", None) + selected = getattr(getattr(compiled, "statement", None), "selected_columns", ()) + captured.extend(selected or ()) + + event.listen(Engine, "before_cursor_execute", capture) + try: + async with h.factory() as session: + current = await session.scalar(text( + "SELECT to_jsonb(s) FROM public.submissions s WHERE s.id=:id" + ), {"id": h.created["submission_id"]}) + assert current.pop("feedback") is None + assert {key: current[key] for key in packet} == packet + reader = submission_history_repository(session) + target = await reader.resolve_submission( + UUID(h.created["submission_id"]), + project_id=UUID(str(old.project_id)), + contributor_id=UUID(str(old.contributor_id)), + ) + assert target is not None + rows, more = await reader.read( + target, manager=False, + submission_id=UUID(h.created["submission_id"]), + ) + assert len(rows) == 1 and not more + assert private_attestation not in rows[0].model_dump_json() + owned = [column for column in captured + if getattr(getattr(column, "table", None), "name", None) == "submissions"] + assert owned + assert "worker_attestation" not in {column.name for column in owned} + finally: + event.remove(Engine, "before_cursor_execute", capture) + + # The superseded checker-column migration probes are replaced by the actual # predecessor refusal in checkers/execution/test_migration.py. The new execution # owner cannot invent request/lease evidence for retained old runs. Authority diff --git a/backend/tests/authorization/submission_history/test_privacy.py b/backend/tests/authorization/submission_history/test_privacy.py index ec6f6869a..2e9825d83 100644 --- a/backend/tests/authorization/submission_history/test_privacy.py +++ b/backend/tests/authorization/submission_history/test_privacy.py @@ -26,8 +26,8 @@ async def test_fixed_projection_and_selected_columns(task_client, monkeypatch, s submission = await seed_retained_submission(task["id"], complete_submission_payload()) run = await seed_retained_checker_run(submission, state=state, verdict=verdict) async with db_session.get_session_factory()() as session: - private_attestation = (await session.get(Submission, submission)).worker_attestation - assert private_attestation + private_package_uri = (await session.get(Submission, submission)).package_uri + assert private_package_uri captured = [] def capture(conn, cursor, statement, parameters, context, executemany): compiled = getattr(context, "compiled", None) @@ -42,7 +42,7 @@ def capture(conn, cursor, statement, parameters, context, executemany): captured.clear() response = await task_client.get(path, headers=auth_headers()) assert response.status_code == 200, response.text - assert private_attestation not in response.text + assert private_package_uri not in response.text value = response.json() item = value["items"][0] if action.endswith("list") else value checker = "checker" in action diff --git a/backend/tests/migration_revision_fixtures.py b/backend/tests/migration_revision_fixtures.py index 56871924f..5eb38543c 100644 --- a/backend/tests/migration_revision_fixtures.py +++ b/backend/tests/migration_revision_fixtures.py @@ -44,6 +44,7 @@ _REVISION_ARCHIVE_SCHEMA = "workstream.historical_revision_rows.v1" _REVISION_ARCHIVE_SOURCE = "6fa9a9b557fa3ae22c16af67bca25dc868f67b38" _OWNER_READ_PROJECTION_COLUMNS = ( + ("submissions", "feedback", "text"), ("workstream_tasks", "active_submission_operation_id", "uuid"), ("actor_identity_links", "email_observed_issued_at", "bigint"), ("project_guide_compilation_attempts", "result_schema_version", "varchar(100)"), diff --git a/backend/tests/migrations/test_source_pre_cutover.py b/backend/tests/migrations/test_source_pre_cutover.py index 8a5f0c5a8..863cd35f9 100644 --- a/backend/tests/migrations/test_source_pre_cutover.py +++ b/backend/tests/migrations/test_source_pre_cutover.py @@ -139,15 +139,21 @@ def _admission_archive(): return snapshots -async def _retained_rows_and_functions(url, tables): +async def _retained_rows_and_functions(url, tables, *, current_feedback=False): """Compare all captured nonempty tables and all public function definitions.""" connection = await asyncpg.connect(url.replace('+asyncpg', '')) try: rows = {} for table in tables: if table != 'alembic_version': + value = 'to_jsonb(r)' + if current_feedback and table == 'submissions': + assert await connection.fetchval( + 'SELECT count(*) FROM public.submissions WHERE feedback IS NOT NULL' + ) == 0 + value += "-'feedback'" rows[table] = await connection.fetchval( - f'SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY to_jsonb(r)::text),\'[]\')::text FROM public."{table}" r' + f'SELECT coalesce(jsonb_agg({value} ORDER BY ({value})::text),\'[]\')::text FROM public."{table}" r' ) functions = dict(await connection.fetch("""SELECT p.oid::regprocedure::text, pg_get_functiondef(p.oid) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace @@ -242,7 +248,9 @@ async def test_source_binding_cutover_preserves_history_and_closes_old_consumpti assert set(old_functions) == set(new_functions) assert {k for k in old_functions if old_functions[k] != new_functions[k]} == {'guard_submission_bundle_admission_lineage()'} await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) - current_rows, _ = await _retained_rows_and_functions(isolated_database_env, snapshot['tables']) + current_rows, _ = await _retained_rows_and_functions( + isolated_database_env, snapshot['tables'], current_feedback=True, + ) assert current_rows == after if state == 'ready': await _refuse_old_consumption_and_allow_stale( diff --git a/backend/tests/migrations/test_unsealed_source_cleanup_migration.py b/backend/tests/migrations/test_unsealed_source_cleanup_migration.py index 41df7678c..925d89143 100644 --- a/backend/tests/migrations/test_unsealed_source_cleanup_migration.py +++ b/backend/tests/migrations/test_unsealed_source_cleanup_migration.py @@ -1,5 +1,6 @@ """Upgrade real predecessor cleanup claims without rewriting their authority.""" import asyncio +from contextlib import asynccontextmanager from datetime import timedelta from uuid import UUID @@ -22,6 +23,21 @@ pytestmark = pytest.mark.postgres_schema_contract +@asynccontextmanager +async def predecessor_submission_read_projection(intake): + """Allow current fixture reads, then restore the exact predecessor schema.""" + async with intake.engine.begin() as connection: + await connection.execute(text("ALTER TABLE public.submissions ADD COLUMN feedback text")) + try: + yield + finally: + async with intake.engine.begin() as connection: + assert await connection.scalar(text( + "SELECT count(*) FROM public.submissions WHERE feedback IS NOT NULL" + )) == 0 + await connection.execute(text("ALTER TABLE public.submissions DROP COLUMN feedback")) + + @pytest.fixture(autouse=True, params=["0087_source_cleanup_candidates", "0088_unsealed_source_cleanup"]) async def predecessor_schema(isolated_database_env, migration_lock, request): """Build the actual predecessor before the ordinary intake fixture runs.""" @@ -57,33 +73,34 @@ async def retained_rows(factory, *, new_columns=()): async def test_upgrade_preserves_sealed_claims_charges_and_audit_decisions(intake, predecessor_schema): - await provision_post_submit_service(intake.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP) claims = [] - for confirmed in (False, True): - operation = await terminal_source(intake) - await age_fixture(intake, operation) - claim_id = new_record_id() - async with intake.factory.begin() as session: - row = await session.get(SubmissionIntakeOperation, str(operation)) - source = repository(session)._sealed_source(row).model_dump_json() - decision = await cleanup_decision(session, operation, claim_id) - # Use actual 0087 SQL guards and real authority decisions. The new - # Python cleanup owner cannot run against this predecessor schema. - await session.execute(text("INSERT INTO submission_source_cleanup_claims " - "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at,claim_decision_id) " - "VALUES (:id,:claim,1,CAST(:source AS jsonb),statement_timestamp()," - "statement_timestamp()+interval '5 minutes',:decision)"), - {"id": operation, "claim": claim_id, "source": source, "decision": decision}) - if confirmed: - confirmation = await cleanup_decision(session, operation, claim_id, phase="confirm") - await session.execute(text("UPDATE submission_source_cleanup_claims " - "SET confirmed_at=clock_timestamp(),confirmation_decision_id=:decision WHERE operation_id=:id"), - {"id": operation, "decision": confirmation}) - await session.execute(text("UPDATE submission_source_charges SET state='released',accounted_bytes=0 " - "WHERE operation_id=:id"), {"id": operation}) - claims.append((operation, claim_id, confirmed, None)) - if predecessor_schema == "0088_unsealed_source_cleanup": - claims.append(await observed_version_claim(intake)) + async with predecessor_submission_read_projection(intake): + await provision_post_submit_service(intake.factory, ServiceIdentity.ARTIFACT_SOURCE_CLEANUP) + for confirmed in (False, True): + operation = await terminal_source(intake) + await age_fixture(intake, operation) + claim_id = new_record_id() + async with intake.factory.begin() as session: + row = await session.get(SubmissionIntakeOperation, str(operation)) + source = repository(session)._sealed_source(row).model_dump_json() + decision = await cleanup_decision(session, operation, claim_id) + # Use actual 0087 SQL guards and real authority decisions. The new + # Python cleanup owner cannot run against this predecessor schema. + await session.execute(text("INSERT INTO submission_source_cleanup_claims " + "(operation_id,claim_id,generation,source,claimed_at,lease_expires_at,claim_decision_id) " + "VALUES (:id,:claim,1,CAST(:source AS jsonb),statement_timestamp()," + "statement_timestamp()+interval '5 minutes',:decision)"), + {"id": operation, "claim": claim_id, "source": source, "decision": decision}) + if confirmed: + confirmation = await cleanup_decision(session, operation, claim_id, phase="confirm") + await session.execute(text("UPDATE submission_source_cleanup_claims " + "SET confirmed_at=clock_timestamp(),confirmation_decision_id=:decision WHERE operation_id=:id"), + {"id": operation, "decision": confirmation}) + await session.execute(text("UPDATE submission_source_charges SET state='released',accounted_bytes=0 " + "WHERE operation_id=:id"), {"id": operation}) + claims.append((operation, claim_id, confirmed, None)) + if predecessor_schema == "0088_unsealed_source_cleanup": + claims.append(await observed_version_claim(intake)) before = await retained_rows(intake.factory) await intake.engine.dispose() await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) diff --git a/backend/tests/tasks/submission_dispatch/test_migration.py b/backend/tests/tasks/submission_dispatch/test_migration.py index 19212de6c..0320254f1 100644 --- a/backend/tests/tasks/submission_dispatch/test_migration.py +++ b/backend/tests/tasks/submission_dispatch/test_migration.py @@ -42,7 +42,7 @@ async def snapshot(): "outbox_events": {"not_before_at"}, "submissions": { "selected_post_submit_policy_sha256", "selected_post_submit_policy_body", - "attempt_status", "status_reason", "decided_at", "updated_at", + "attempt_status", "status_reason", "decided_at", "updated_at", "feedback", }, "task_assignments": {"started_at", "updated_at"}, "checker_runs": { From 8a3a2dbec51a0fe00c6b12fe93ef6ceff60f9bf6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:23:07 +0100 Subject: [PATCH 373/513] test(submission): bind predecessor fixtures to historical packet shape --- .../submission_history/test_privacy.py | 8 ++++++- .../test_unsealed_source_cleanup_migration.py | 23 +++++++++++++++++-- .../tasks/test_payment_policy_migration.py | 1 + 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/backend/tests/authorization/submission_history/test_privacy.py b/backend/tests/authorization/submission_history/test_privacy.py index 2e9825d83..f1285ad67 100644 --- a/backend/tests/authorization/submission_history/test_privacy.py +++ b/backend/tests/authorization/submission_history/test_privacy.py @@ -101,7 +101,7 @@ async def forbidden(*args, **kwargs): @pytest.mark.parametrize("manager", [False, True]) async def test_nested_values_match_exact_stored_parents(task_client, monkeypatch, manager): from app.modules.tasks.models import EvidenceItem - from app.modules.checkers.models import CheckerResult, CheckerResultFinding + from app.modules.checkers.models import CheckerResult, CheckerResultFinding, CheckerRun from app.modules.checkers.execution_results import RESULT_STATUS_MESSAGES project = await create_active_project(task_client, post_submit_registry_spec=post_registry_spec()) task = await create_started_task(task_client, project["id"], monkeypatch) @@ -117,6 +117,7 @@ async def test_nested_values_match_exact_stored_parents(task_client, monkeypatch async with db_session.get_session_factory()() as session: evidence = list(await session.scalars(select(EvidenceItem).order_by(EvidenceItem.id))) rows = list(await session.scalars(select(CheckerResult).order_by(CheckerResult.member_order))) + runs = {str(item.id): item for item in await session.scalars(select(CheckerRun))} findings = {} for finding in await session.scalars(select(CheckerResultFinding).order_by( CheckerResultFinding.finding_order, @@ -142,6 +143,11 @@ async def test_nested_values_match_exact_stored_parents(task_client, monkeypatch else level_status[finding.level] ) message, fix = RESULT_STATUS_MESSAGES[status] + if finding is not None: + retained = runs[str(row.checker_run_id)].result_json["execution"]["external_members"] + text = retained[row.member_order]["result"]["findings"][finding.finding_order]["message"] + if text is not None: + message, fix = text, None entry = { "id": row.id if finding is None else finding.id, "checker_name": row.checker_name, diff --git a/backend/tests/migrations/test_unsealed_source_cleanup_migration.py b/backend/tests/migrations/test_unsealed_source_cleanup_migration.py index 925d89143..d23797fbe 100644 --- a/backend/tests/migrations/test_unsealed_source_cleanup_migration.py +++ b/backend/tests/migrations/test_unsealed_source_cleanup_migration.py @@ -6,8 +6,9 @@ import pytest from alembic import command -from sqlalchemy import text +from sqlalchemy import event, text +from app.core.hashing import canonical_json_hash from app.core.identifiers import new_record_id from app.db import session as db_session from app.modules.actors.api import ServiceIdentity @@ -25,12 +26,30 @@ @asynccontextmanager async def predecessor_submission_read_projection(intake): - """Allow current fixture reads, then restore the exact predecessor schema.""" + """Construct old v1 commands, then restore the exact predecessor schema.""" + def bind_old_metadata(_mapper, _connection, row): + assert row.command_metadata["feedback"] is None + metadata = { + "task_id": row.task_id, + "assignment_id": row.assignment_id, + "predecessor_submission_id": None, + "summary": "", + "contributor_attestation": "", + "revision_preparation_id": None, + "revision_preparation_sha256": None, + } + row.command_metadata = metadata + row.metadata_sha256 = canonical_json_hash({ + "schema_version": "workstream.submission_intake_metadata.v1", **metadata, + }) + async with intake.engine.begin() as connection: await connection.execute(text("ALTER TABLE public.submissions ADD COLUMN feedback text")) + event.listen(SubmissionIntakeOperation, "before_insert", bind_old_metadata) try: yield finally: + event.remove(SubmissionIntakeOperation, "before_insert", bind_old_metadata) async with intake.engine.begin() as connection: assert await connection.scalar(text( "SELECT count(*) FROM public.submissions WHERE feedback IS NOT NULL" diff --git a/backend/tests/tasks/test_payment_policy_migration.py b/backend/tests/tasks/test_payment_policy_migration.py index d14baea4f..dba5da9fa 100644 --- a/backend/tests/tasks/test_payment_policy_migration.py +++ b/backend/tests/tasks/test_payment_policy_migration.py @@ -135,6 +135,7 @@ async def test_payment_cleanup_refuses_each_retained_fact_then_preserves_current "submissions": { "selected_post_submit_policy_sha256": None, "selected_post_submit_policy_body": None, + "feedback": None, "attempt_status": "evaluation_pending", "status_reason": None, "decided_at": None, "updated_at": "submitted_at", }, From 8cb6c3e09f8fd7ec4bbf4a409e19d835f0252ae7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:33:49 +0100 Subject: [PATCH 374/513] docs(submission): record focused retained migration replay --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0f5b06a2e..ea8ed3688 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11323,4 +11323,10 @@ fixture uses its still-stored private package URI as the nonleak witness. A separate checksum-bound 0024 archive exercises the genuine old private attestation after upgrade through the current fixed history projection. These fixture changes do not relax runtime custody, authorization, or SQL -guards. Focused PostgreSQL replay and final evidence remain pending. +guards. The checksum-bound archived private-attestation projection passed in +the first two-case replay; that run also exposed a predecessor 0088 INSERT +using the new command metadata. A scoped fixture binder now writes the exact +historical v1 metadata body and digest before the old guarded INSERT. The +isolated 0088 replay passed in 131.62 seconds with schema 0092 and complete +database cleanup (`/tmp/submission-0092-0088-v1.log` and `.json`). Other +historical lane cases remain pending and are not represented by this receipt. From d2ebba471da65711cf536f66ab2879648685ae6e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:34:32 +0100 Subject: [PATCH 375/513] test: align diagnostic worker and current predecessor selectors --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 44 +++++++++++++++++++ backend/tests/test_celery_observability.py | 32 +++++++++----- .../test_submission_predecessor_custody.py | 13 ++++-- 3 files changed, 75 insertions(+), 14 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index ea8ed3688..b85170fd7 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11330,3 +11330,47 @@ historical v1 metadata body and digest before the old guarded INSERT. The isolated 0088 replay passed in 131.62 seconds with schema 0092 and complete database cleanup (`/tmp/submission-0092-0088-v1.log` and `.json`). Other historical lane cases remain pending and are not represented by this receipt. + +### Remaining current CI observability and fence fixtures (2026-11-26) + +Intent: repair only the observed real-prefork diagnostics startup fixture and the +current predecessor-fence fault injection, and diagnose the OTLP timeout log +assertion independently. Scope is tests/test_celery_observability.py, +tests/test_submission_predecessor_custody.py, a possible focused OTLP test repair +only after causal evidence, and this record. Production queue declarations, +WorkerTaskBoundary, source custody, SQL guards, exporter deadlines and logging +ownership remain unchanged. No historical/privacy fixture overlap. + +The Redis diagnostics probe must consume one declared dedicated queue using its +real registered identity with only a temporary synthetic probe body, restoring +the original task exactly; it qualifies diagnostics, not the scanner owner. The +stale-fence probe must accept only the two independently validated TASK selector +forms (public current predecessor selection and explicit CHECKERS lineage), then +retain real post-fence application refusal and staged T4/deferred SQL rejection. +All original correlation, context reset, failure/retry, privacy, source charge, +rollback and valid-control assertions remain required. No PG/broker/native run +while the parent-owned native/historical fixture slot is reserved. A permitted +lightweight local HTTP OTLP run is diagnostic evidence only. + +Static-ready checkpoint: only the two named tests and this record changed. The +diagnostics test uses the existing scanner task/queue with the production task +base and closed route intact; its synthetic body proves diagnostics only. Original +registration identity is asserted on restoration and startup failure includes a +bounded tail of its private worker log. The fence test proves both reader forms +return the same exact genuine context before advancing the fence and requires +both genuine readers to refuse afterward; only those two selectors are frozen. +All staged-T4, exact23514, no-mutation, charge and positive T5 assertions remain. + +The unchanged OTLP status/refusal/timeout matrix passed3 in7.10s with the system +Python3.12.3 interpreter and explicit asyncio plugin, no conftest/PG/broker/native +(/tmp/pr708-otlp-failure-baseline.log). This does not resolve the original CI +timeout case's empty log set: even its synchronous Celery labels were absent. No +logger ownership, deadline, expected event or exporter behavior was changed on +that evidence. OTLP's full-lane failure remains an unresolved qualification limit. + +Ruff and whitespace pass; the unchanged full structure validator exits0 +(/tmp/pr708-observability-fence-structure.log). Both test files already fail Ruff +format-check at the base, so this bounded fixture patch does not reformat those +whole modules. Native execution has priority; the repaired real Redis/prefork +probe and both PostgreSQL fence parameters have not run on this candidate. No +production behavior change or aggregate runtime-pass claim. diff --git a/backend/tests/test_celery_observability.py b/backend/tests/test_celery_observability.py index d1cd09eb5..15806fa18 100644 --- a/backend/tests/test_celery_observability.py +++ b/backend/tests/test_celery_observability.py @@ -447,25 +447,32 @@ async def test_real_celery_prefork_correlates_api_and_resets_sequential_task_con ) -> None: """Exercise actual Redis publication, worker parent, and one prefork child.""" from app.core.config import get_settings + from app.workers.outbox_topology import OUTBOX_SCAN_QUEUE, OUTBOX_SCAN_TASK + from app.workers.source_cleanup_topology import WorkerTaskBoundary broker = os.environ["WORKSTREAM_TEST_BROKER_URL"] connection = redis.Redis.from_url(broker) assert connection.ping() prefix = f"workstream-observability-{uuid4()}:" - queue_name = f"workstream-observability-{uuid4()}" + queue_name, task_name = OUTBOX_SCAN_QUEUE, OUTBOX_SCAN_TASK observations = multiprocessing.get_context("fork").Queue() monkeypatch.setenv("WORKSTREAM_CELERY_BROKER_URL", broker) monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "false") monkeypatch.setenv("WORKSTREAM_ARTIFACT_STORE_BACKEND", "disabled") get_settings.cache_clear() - from app.workers.celery_app import celery_app + from app.workers.celery_app import WORKSTREAM_TASK_ROUTES, celery_app - prior_task = celery_app.tasks.pop(KNOWN_TASK, None) + celery_app.loader.import_default_modules() + assert WORKSTREAM_TASK_ROUTES[task_name] == {"queue": queue_name} + assert queue_name in {declared.name for declared in celery_app.conf.task_queues} + + prior_task = celery_app.tasks.pop(task_name) + assert isinstance(prior_task, WorkerTaskBoundary) def restore_task_registration() -> None: - celery_app.tasks.pop(KNOWN_TASK, None) - if prior_task is not None: - celery_app.tasks.register(prior_task) + celery_app.tasks.pop(task_name, None) + celery_app.tasks.register(prior_task) + assert celery_app.tasks[task_name] is prior_task request.addfinalizer(restore_task_registration) @@ -476,7 +483,7 @@ def adapter_builder(): configure_celery_observability( _settings(), - frozenset({KNOWN_TASK}), + frozenset({task_name}), adapter_builder, ) @@ -493,7 +500,7 @@ def runtime_factory(settings, *, service_name, task_names, export_adapter): monkeypatch.setattr(diagnostics, "ObservabilityRuntime", runtime_factory) assert diagnostics._WORKER_RUNTIME is None - @celery_app.task(bind=True, name=KNOWN_TASK) + @celery_app.task(bind=True, name=task_name) def probe_task(self, mode: str): if mode == "failure": raise RuntimeError("credential=worker-failure-secret") @@ -505,6 +512,8 @@ def probe_task(self, mode: str): ) return {"status": "ok"} + assert isinstance(probe_task, WorkerTaskBoundary) + def capture_after_task(task_id=None, state=None, **_kwargs): runtime = diagnostics._WORKER_RUNTIME assert runtime is not None @@ -551,7 +560,10 @@ def capture_after_task(task_id=None, state=None, **_kwargs): try: deadline = time.monotonic() + 45 while time.monotonic() < deadline: - assert process.is_alive(), f"worker startup failed: {process.exitcode}" + assert process.is_alive(), ( + f"worker startup failed: {process.exitcode}; " + + log_path.read_text(encoding="utf-8")[-8192:] + ) if celery_app.control.ping(destination=[hostname], timeout=0.2): break await asyncio.sleep(0.1) @@ -662,7 +674,7 @@ async def dispatch() -> dict[str, str]: assert task_metrics assert all( set(attributes) == {"messaging.destination.name", "workstream.outcome"} - and attributes["messaging.destination.name"] == KNOWN_TASK + and attributes["messaging.destination.name"] == task_name for _, attributes in task_metrics ) finally: diff --git a/backend/tests/test_submission_predecessor_custody.py b/backend/tests/test_submission_predecessor_custody.py index e841ea886..cac062fb6 100644 --- a/backend/tests/test_submission_predecessor_custody.py +++ b/backend/tests/test_submission_predecessor_custody.py @@ -669,13 +669,17 @@ async def test_dispatch_commit_requires_current_predecessor_checker_fence( async with remediation_source(tmp_path, isolated_database_env) as h: source_id = await _fixture_revision_context(h) + explicit_request = _context_request(h) + selected_request = replace(explicit_request, predecessor_submission_id=None, select_predecessor=True) async with h.factory.begin() as session: - frozen = await task_submission_context_port(session).lock_submission_context(_context_request(h)) + contexts = task_submission_context_port(session) + frozen = await contexts.lock_submission_context(explicit_request) + assert await contexts.lock_submission_context(selected_request) == frozen assert frozen.checker_remediation_manifest_id == source_id class FrozenTaskContextPort: async def lock_submission_context(self, selected): - assert selected == _context_request(h) + assert selected in (explicit_request, selected_request) return frozen operations, snapshots, staged, commit_errors = [], [], [], [] @@ -687,8 +691,9 @@ async def accept_after_fence_change(admission, owner, *args, **kwargs): if advance_fence: await reserve(h, await next_request(h)) async with h.factory.begin() as session: - with pytest.raises(TaskSubmissionContextUnavailable): - await task_submission_context_port(session).lock_submission_context(_context_request(h)) + for selected in (explicit_request, selected_request): + with pytest.raises(TaskSubmissionContextUnavailable): + await task_submission_context_port(session).lock_submission_context(selected) # Freeze only the TASK context reader. All writers and SQL guards remain real. monkeypatch.setattr(admission, "_contexts", lambda _session: FrozenTaskContextPort()) monkeypatch.setattr( From 565cc143aae01349a9b4a0ccd306faeec61eee07 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:35:33 +0100 Subject: [PATCH 376/513] Verify the 135-tool MCP catalogue in the hosted transport proof --- docs/roadmap_status.md | 2 +- mcp_server/README.md | 4 +- .../test_task_operation_contract_drift.py | 2 +- scripts/test_hosted_mcp_container.py | 46 +++++++++++++++---- 4 files changed, 42 insertions(+), 12 deletions(-) diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 1ac71e9d4..3292ec8f6 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -410,7 +410,7 @@ preparation returns retryable unavailability, POST requests and reconciliation remain in PostgreSQL, and ordinary Celery delivery continues. Assembled split-host checker operation remains unqualified. The operator app-only host is deployed; public identity login, API profile access, browser OAuth/PKCE and the MCP profile tool passed after migration. -The [independent MCP package](../mcp_server/README.md) implements 132 +The [independent MCP package](../mcp_server/README.md) implements 135 self-service, administrative access, actor/identity-lifecycle, project-shell, project-participation, guide-metadata, draft-policy, contributor-workspace, contribution-evidence, contribution-policy, complete guide-lifecycle, diff --git a/mcp_server/README.md b/mcp_server/README.md index 889c18605..18b73d7b5 100644 --- a/mcp_server/README.md +++ b/mcp_server/README.md @@ -1,6 +1,6 @@ # Workstream MCP Adapter -An independently installed adapter exposing 132 tools under the caller's authority: +An independently installed adapter exposing 135 tools under the caller's authority. - `workstream_profile_get` calls `GET /api/v1/actors/me`. - `workstream_profile_update` calls the unkeyed `PATCH /api/v1/actors/me`. @@ -286,7 +286,7 @@ retries. A mutation transport failure, upstream 5xx response, or unexpected success/redirect response is reported as non-retryable uncertain execution. Connections may be pooled, but caller credentials and results are not shared or cached. Response validation is -pinned to the 132 selected public contracts in `contracts/`; upstream drift +pinned to the 135 selected public contracts in `contracts/`; upstream drift must be reviewed, not silently accepted. There is no fallback service or backend-private import. diff --git a/mcp_server/tests/test_task_operation_contract_drift.py b/mcp_server/tests/test_task_operation_contract_drift.py index 569cd7fa1..4f7fd67e4 100644 --- a/mcp_server/tests/test_task_operation_contract_drift.py +++ b/mcp_server/tests/test_task_operation_contract_drift.py @@ -113,7 +113,7 @@ def test_task_operation_contracts_match_backend_openapi_when_configured() -> Non assert progress["security"] assert progress["x-workstream-action-id"] == "task.submission_operation.read" assert progress["x-workstream-management-action-id"] == "project.task.submission_operation.read" - assert len(all_operations - health_operations) == 132 + assert len(all_operations - health_operations) == 135 for name, (method, path, _) in TASK_OPERATIONS.items(): snapshot = json.loads((CONTRACTS / f"{name}.json").read_text(encoding="utf-8")) assert snapshot["source"]["openapi_version"] == openapi["openapi"] diff --git a/scripts/test_hosted_mcp_container.py b/scripts/test_hosted_mcp_container.py index 59ea292c1..876386619 100644 --- a/scripts/test_hosted_mcp_container.py +++ b/scripts/test_hosted_mcp_container.py @@ -20,6 +20,7 @@ ROOT = Path(__file__).resolve().parents[1] +REVIEWED_TOOL_COUNT = 135 API_FIXTURE = r''' from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json @@ -245,18 +246,46 @@ def rpc(method: str, params: dict, bearer: str | None = None) -> dict: with build_opener(ProxyHandler({})).open(request, timeout=15) as response: return json.load(response)["result"] - def prove_calls(generation: str) -> None: + def prove_calls(generation: str) -> int: api = compose("ps", "--quiet", "api") def bearer(caller: str) -> str: return run('docker', 'exec', api, 'python', '-c', TOKEN_FIXTURE, caller, env=env) tools = rpc("tools/list", {}, bearer('alice'))["tools"] - assert len(tools) == len({tool["name"] for tool in tools}) == 132 - assert "workstream_submission_operation_get" in {tool["name"] for tool in tools} - - - assert [tool["name"] for tool in tools][-23:] == ['workstream_projects_list', 'workstream_service_actor_create', 'workstream_task_import_batch_create', 'workstream_management_tasks_list', 'workstream_management_task_create', 'workstream_operational_tasks_list', 'workstream_task_import_batch_screen', 'workstream_task_import_batch_release', 'workstream_task_import_batch_get', 'workstream_management_task_get', 'workstream_management_task_locked_context_get', 'workstream_operational_task_locked_context_get', 'workstream_audit_task_locked_context_get', 'workstream_task_revision_context_repair', 'workstream_audit_task_evidence_get', 'workstream_project_model_profile_provision', 'workstream_project_model_budget_configure', 'workstream_project_model_usage_effect_get', 'workstream_project_model_recovery_child_create', 'workstream_task_import_source_declare', 'workstream_task_import_source_content_upload', 'workstream_task_import_source_content_get', 'workstream_task_import_source_get'] + names = [tool["name"] for tool in tools] + assert len(names) == len(set(names)) == REVIEWED_TOOL_COUNT + assert { + "workstream_project_contributor_guide_get", + "workstream_project_contributor_guide_document_get", + "workstream_task_assignment_get", + "workstream_submission_operation_get", + } <= set(names) + assert names[-23:] == [ + "workstream_projects_list", + "workstream_service_actor_create", + "workstream_task_import_batch_create", + "workstream_management_tasks_list", + "workstream_management_task_create", + "workstream_operational_tasks_list", + "workstream_task_import_batch_screen", + "workstream_task_import_batch_release", + "workstream_task_import_batch_get", + "workstream_management_task_get", + "workstream_management_task_locked_context_get", + "workstream_operational_task_locked_context_get", + "workstream_audit_task_locked_context_get", + "workstream_task_revision_context_repair", + "workstream_audit_task_evidence_get", + "workstream_project_model_profile_provision", + "workstream_project_model_budget_configure", + "workstream_project_model_usage_effect_get", + "workstream_project_model_recovery_child_create", + "workstream_task_import_source_declare", + "workstream_task_import_source_content_upload", + "workstream_task_import_source_content_get", + "workstream_task_import_source_get", + ] params = {"name": "workstream_profile_get", "arguments": {}} for caller in ("alice", "bob"): result = rpc("tools/call", params, bearer(caller)) @@ -273,6 +302,7 @@ def bearer(caller: str) -> str: raise AssertionError('Unauthenticated MCP call did not reject') again = rpc("tools/call", params, bearer('alice')) assert again["structuredContent"]["display_name"] == "alice-" + generation + return len(names) write_fixture("initial") try: @@ -302,9 +332,9 @@ def bearer(caller: str) -> str: compose("up", "--detach", "--pull", "never", "--no-deps", "--force-recreate", "--wait", "--wait-timeout", "90", "mcp") current_api, current_mcp = healthy() assert current_api != original_api and current_mcp != original_mcp - prove_calls("replacement") + tools_count = prove_calls("replacement") print(json.dumps({"proof": "hosted MCP fixture transport", "image_id": image_id, - "tools": 132, "restart": "passed", "replacement": "passed", + "tools": tools_count, "restart": "passed", "replacement": "passed", "stale_namespace_counterexample": "passed"})) finally: compose("down", "--volumes", "--remove-orphans", "--timeout", "10", timeout=45) From 711c02b920f83a0ad91ba3c00447dbeb32f704cd Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:36:17 +0100 Subject: [PATCH 377/513] test: keep worker startup diagnostics free of raw logs --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 11 +++++++++++ backend/tests/test_celery_observability.py | 5 +---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b85170fd7..cc8f1e788 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11374,3 +11374,14 @@ format-check at the base, so this bounded fixture patch does not reformat those whole modules. Native execution has priority; the repaired real Redis/prefork probe and both PostgreSQL fence parameters have not run on this candidate. No production behavior change or aggregate runtime-pass claim. + +### Diagnostics startup failure disclosure correction (2026-11-26) + +Intent and bounded scope: remove the newly added raw worker.log tail from the +real-prefork startup assertion in tests/test_celery_observability.py. Independent +security review identified that early worker logs can contain a broker URL with +credentials before safe logging is installed. Retain the original exit-code +assertion and all dedicated queue, registration restoration, context and privacy +guards. The private log remains available to the test's existing safe-content +assertions; it is not copied into the public failure diagnostic. No production +changes or PG/broker/native rerun is required for this diagnostic-only removal. diff --git a/backend/tests/test_celery_observability.py b/backend/tests/test_celery_observability.py index 15806fa18..8e7e73c08 100644 --- a/backend/tests/test_celery_observability.py +++ b/backend/tests/test_celery_observability.py @@ -560,10 +560,7 @@ def capture_after_task(task_id=None, state=None, **_kwargs): try: deadline = time.monotonic() + 45 while time.monotonic() < deadline: - assert process.is_alive(), ( - f"worker startup failed: {process.exitcode}; " - + log_path.read_text(encoding="utf-8")[-8192:] - ) + assert process.is_alive(), f"worker startup failed: {process.exitcode}" if celery_app.control.ping(destination=[hostname], timeout=0.2): break await asyncio.sleep(0.1) From db9dc975acb885a1388c0de848d162e18351ba20 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:37:55 +0100 Subject: [PATCH 378/513] docs(submission): record host candidates and bounded replay evidence --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index cc8f1e788..a502e08c8 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11385,3 +11385,33 @@ assertion and all dedicated queue, registration restoration, context and privacy guards. The private log remains available to the test's existing safe-content assertions; it is not copied into the public failure diagnostic. No production changes or PG/broker/native rerun is required for this diagnostic-only removal. + + +### Integrated host qualification checkpoint (2026-11-26) + +Both backend SDK release images built from 1d28b567d and passed the existing +native-hosted image verifier on the API host. Receipt: +`/tmp/workstream-host-image-5fb26081a6c9/host-only-build-1d28.json`. +They are local candidate images, not published or deployed releases. The MCP +image built from the same source; its first container proof stopped at the +obsolete 132-tool expectation. Current authenticated catalogue and OpenAPI proof +passed 28 cases for 135 tools; the corrected existing container proof is pending. +The ignored CSV/XLSX contain no obsolete tool count; the workbook retains its +single WorkStream RoadMap sheet. + +The first paired CLI/MCP native probe stopped before submission because the +health contract reports a cache count, not manifest identities. d8046ea23 fixes +that comparison, retaining independent exact configuration/binary/cache custody; +the positive and wrong-count controls passed. Original failed receipt remains at +`/tmp/workstream-paired-native-5k85wccw/cleanup.json`, with database and storage +cleanup complete. A fresh independently checked runner custody envelope binds +config 7ceb63e3 and the clean d8046ea23 rerun. The running journey has no success +claim yet. Runtime package source is unchanged by the subsequent test/doc repairs. + +ARCH reviewed the historical fixture changes and QA selector/queue repairs. +The raw worker-log diagnostic finding was removed in 711c02b92. Exact historical +0088 replay passed with cleanup; remaining historical and broker cases still +need their terminal evidence. The unchanged local OTLP failure matrix passed +three cases but does not explain the earlier CI missing events. Main was fetched +with zero unseen commits. All work remains in PR 708, with production deployment, +final-head CI and acceptance/configuration reconciliation incomplete. From 0096a744cdd4afae760efe62f7b84d648a4f0aea Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:38:59 +0100 Subject: [PATCH 379/513] docs(submission): record MCP container proof and native startup failure --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a502e08c8..0e34da2d1 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11415,3 +11415,15 @@ need their terminal evidence. The unchanged local OTLP failure matrix passed three cases but does not explain the earlier CI missing events. Main was fetched with zero unseen commits. All work remains in PR 708, with production deployment, final-head CI and acceptance/configuration reconciliation incomplete. + + +Host MCP transport proof is now terminal PASS using unchanged image source +1d28b567d and corrected verifier 565cc143a. Receipt +`/tmp/workstream-mcp-proof-565.json` binds image ad364ad8, 135 tools, signed caller +isolation, restart, replacement and stale-network-namespace counterexample. +This is the shipped container against the fixture provider, not deployed OAuth +or submission outcome proof. The d8046ea23 native rerun passed runner health but +stopped when the dedicated cleanup worker refused startup configuration; the +other workers started. Its database/storage cleanup is complete at +`/tmp/workstream-paired-native-n7e8wt8w/cleanup.json`. Diagnose that exact +configuration before another full rerun; no acceptance or PRE success is claimed. From 4628604c19941034d8f8ae7b8fc4ec119af99be6 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:44:36 +0100 Subject: [PATCH 380/513] docs(submission): record eight focused runtime cases and cleanup --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0e34da2d1..0a0431137 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11427,3 +11427,15 @@ stopped when the dedicated cleanup worker refused startup configuration; the other workers started. Its database/storage cleanup is complete at `/tmp/workstream-paired-native-n7e8wt8w/cleanup.json`. Diagnose that exact configuration before another full rerun; no acceptance or PRE success is claimed. + + +Focused current-contract runtime closure: eight cases passed in 183.12 seconds +with real PostgreSQL/MinIO and the dedicated Redis consumer. Receipt +`/tmp/pr708-current-fixtures-runtime-v1.json` records 0096a744c, schema0092 and +complete database/storage cleanup. The launch observation db9dc975 differs only +in this record; all six executed test/helper modules match the reviewed fixture +commit. Covered three recovery consumers, exact guide/current-authority hints, +stored failure history, both SQL predecessor-fence parameters and the real +prefork observability probe on its declared queue. The existing synthetic-context +Pydantic warning remains visible. Broker-loss replay and the earlier CI OTLP +missing-events failure are not closed by these eight cases. From e38ad7542fb9e357cf7fc2449ea752299ab5b7f3 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:45:11 +0100 Subject: [PATCH 381/513] Prepare native fixture authority and versioned source storage before workers start --- .../test_journey_bucket_versioning.py | 14 +++-- cli/tests/journey/runtime.py | 8 +-- .../run_public_journey_probe.py | 51 +++++++++++++------ scripts/test_public_hosted_attachment.py | 7 ++- 4 files changed, 56 insertions(+), 24 deletions(-) diff --git a/cli/tests/integration/test_journey_bucket_versioning.py b/cli/tests/integration/test_journey_bucket_versioning.py index 08f502a60..6011f21ae 100644 --- a/cli/tests/integration/test_journey_bucket_versioning.py +++ b/cli/tests/integration/test_journey_bucket_versioning.py @@ -44,14 +44,18 @@ async def factory(endpoint): return factory -def test_journey_enables_and_reads_back_exact_owned_source_bucket(): +@pytest.mark.parametrize("lane", ["cli_full_journey", "guide_journey"]) +def test_journey_enables_and_reads_back_exact_owned_source_bucket(lane): client = VersioningClient() + bucket = f"workstream-ci-{lane.replace('_', '-')}-{SUFFIX}" MODULE.prepare_versioned_source_bucket( - ENVIRONMENT, client_factory=factory_for(client) + ENVIRONMENT | {"WORKSTREAM_TEST_MINIO_BUCKET": bucket, + "WORKSTREAM_TEST_MINIO_PREFIX": f"ci/{lane}/{SUFFIX}"}, + lane=lane, client_factory=factory_for(client), ) assert client.calls == [ - ("put", {"Bucket": BUCKET, "VersioningConfiguration": {"Status": "Enabled"}}), - ("get", {"Bucket": BUCKET}), + ("put", {"Bucket": bucket, "VersioningConfiguration": {"Status": "Enabled"}}), + ("get", {"Bucket": bucket}), ] @@ -59,6 +63,8 @@ def test_journey_enables_and_reads_back_exact_owned_source_bucket(): "change", [ {"WORKSTREAM_TEST_MINIO_BUCKET": "workstream-artifacts"}, + {"WORKSTREAM_TEST_MINIO_BUCKET": f"workstream-ci-guide-journey-{SUFFIX}", + "WORKSTREAM_TEST_MINIO_PREFIX": f"ci/guide_journey/{SUFFIX}"}, {"WORKSTREAM_TEST_MINIO_PREFIX": "ci/cli_full_journey/other"}, ], ) diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index 038b29814..ee4a6d16b 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -266,13 +266,15 @@ def load_journey_configuration(environment: dict[str, str]) -> dict[str, Path]: def prepare_versioned_source_bucket( - environment: dict[str, str], *, client_factory=None + environment: dict[str, str], *, lane: str = "cli_full_journey", client_factory=None ): """Enable required source versioning on this runner-owned isolated bucket.""" + if lane not in {"cli_full_journey", "guide_journey"}: + raise RuntimeError("journey source bucket is not runner-owned") bucket = environment.get("WORKSTREAM_TEST_MINIO_BUCKET", "") prefix = environment.get("WORKSTREAM_TEST_MINIO_PREFIX", "") - match = re.fullmatch(r"workstream-ci-cli-full-journey-([a-f0-9]{12})", bucket) - if match is None or prefix != f"ci/cli_full_journey/{match.group(1)}": + match = re.fullmatch(rf"workstream-ci-{lane.replace('_', '-')}-([a-f0-9]{{12}})", bucket) + if match is None or prefix != f"ci/{lane}/{match.group(1)}": raise RuntimeError("journey source bucket is not runner-owned") if client_factory is None: from run_isolated_tests import _minio_client diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 0334b0af4..990fab0d8 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -25,6 +25,7 @@ from uuid import UUID, uuid4 import httpx +from pydantic import SecretStr from sqlalchemy import func, select, text from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine @@ -74,7 +75,9 @@ from experiments.pilot04_external_checker_runtime.public_submission_clients import ( # noqa: E402 ContributorClients, seeded_issuer, ) -from cli.tests.journey.runtime import _interrupt_owned_groups, _live_group_members # noqa: E402 +from cli.tests.journey.runtime import ( # noqa: E402 + _interrupt_owned_groups, _live_group_members, prepare_versioned_source_bucket, +) def _settings_digests(settings, nonce: bytes) -> dict[str, str]: @@ -96,8 +99,9 @@ def _settings_digests(settings, nonce: bytes) -> dict[str, str]: } -def _celery_config_mismatches(settings) -> list[str]: - from app.workers.celery_app import celery_app +def _celery_config_mismatches(settings, worker_app=None) -> list[str]: + if worker_app is None: + from app.workers.celery_app import celery_app as worker_app expected = { "celery_broker_url": settings.celery_broker_url, @@ -105,9 +109,9 @@ def _celery_config_mismatches(settings) -> list[str]: "celery_task_always_eager": settings.celery_task_always_eager, } actual = { - "celery_broker_url": celery_app.conf.broker_url, - "celery_result_backend_url": celery_app.conf.result_backend, - "celery_task_always_eager": celery_app.conf.task_always_eager, + "celery_broker_url": worker_app.conf.broker_url, + "celery_result_backend_url": worker_app.conf.result_backend, + "celery_task_always_eager": worker_app.conf.task_always_eager, } return [name for name in expected if expected[name] != actual[name]] @@ -121,7 +125,10 @@ def _verify_child_configuration(role: str) -> int: actual = app.state.settings else: - from app.workers.celery_app import celery_app # noqa: F401 + if role == "guide": + from experiments.pilot04_external_checker_runtime.guide_worker import celery_app + else: + from app.workers.celery_app import celery_app actual = get_settings() observed = _settings_digests(actual, nonce) @@ -130,19 +137,24 @@ def _verify_child_configuration(role: str) -> int: name for name in expected.keys() | observed.keys() if expected.get(name) != observed.get(name) ) - if role == "worker": - mismatches.extend(_celery_config_mismatches(actual)) + if role != "api": + mismatches.extend(_celery_config_mismatches(actual, celery_app)) print(json.dumps(sorted(set(mismatches)), separators=(",", ":"))) return 0 -def _preflight_children(settings, env: dict[str, str], root: Path) -> None: +def _preflight_children(settings, env: dict[str, str], cleanup_env: dict[str, str], root: Path) -> None: """Reject API/worker drift before starting real services or public requests.""" nonce = os.urandom(32) - request = json.dumps({ - "nonce": nonce.hex(), "expected": _settings_digests(settings, nonce), + cleanup_settings = settings.model_copy(update={ + "artifact_s3_access_key_id": SecretStr(cleanup_env["WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID"]), + "artifact_s3_secret_access_key": SecretStr(cleanup_env["WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY"]), + "artifact_s3_session_token": None, }) - for role in ("api", "worker"): + for role in ("api", "guide", "worker", "source-cleanup"): + child_env = cleanup_env if role == "source-cleanup" else env + expected = cleanup_settings if role == "source-cleanup" else settings + request = json.dumps({"nonce": nonce.hex(), "expected": _settings_digests(expected, nonce)}) with (root / f"preflight-{role}.log").open("wb") as errors: result = subprocess.run( [ @@ -153,7 +165,7 @@ def _preflight_children(settings, env: dict[str, str], root: Path) -> None: "raise SystemExit(_verify_child_configuration(sys.argv[3]))", str(BACKEND.parent), str(BACKEND / "tests"), role, ], - cwd=BACKEND, env=env, input=request, text=True, + cwd=BACKEND, env=child_env, input=request, text=True, stdout=subprocess.PIPE, stderr=errors, timeout=300, check=False, ) _require(result.returncode == 0, @@ -225,6 +237,9 @@ def _source_cleanup_environment(env: dict[str, str], settings) -> dict[str, str] cleanup_env = dict(env) cleanup_env["WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID"] = cleanup_key cleanup_env["WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY"] = secret_file.read_text(encoding="ascii") + for setting in ("WORKSTREAM_ARTIFACT_S3_SESSION_TOKEN", "WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID", + "WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE"): + cleanup_env.pop(setting, None) return cleanup_env @@ -376,6 +391,9 @@ async def _provision_runtime_services(factory) -> None: async with factory() as session, session.begin(): for identity in (ServiceIdentity.OUTBOX_DISPATCHER, ServiceIdentity.ARTIFACT_SCHEDULER, + ServiceIdentity.ARTIFACT_SOURCE_CLEANUP, + ServiceIdentity.ARTIFACT_PUT_RESOLVER, + ServiceIdentity.ARTIFACT_VERIFIER, ServiceIdentity.ARTIFACT_GUIDE_READER, ServiceIdentity.PROJECT_SETUP): existing = await session.scalar(select(ActorProfile.id).where( ActorProfile.service_identity == identity.value @@ -1309,7 +1327,7 @@ async def run(database_url: str, image_reference: str, node_config: Path, "artifact_store_backend", "artifact_s3_provider_profile", "artifact_s3_region", "artifact_s3_endpoint_url", "artifact_s3_bucket", "artifact_s3_private_prefix", "artifact_s3_addressing_style", "artifact_s3_credential_mode", - "artifact_s3_access_key_id", "artifact_s3_secret_access_key", + "artifact_s3_access_key_id", "artifact_s3_secret_access_key", "artifact_s3_session_token", ): _require(getattr(runtime_settings, field) == getattr(settings, field), "API/worker artifact provider configuration differs from fixture") @@ -1326,7 +1344,8 @@ async def run(database_url: str, image_reference: str, node_config: Path, _require(not parent_celery_mismatches, "parent broker configuration differs from resolved Settings: " + ", ".join(parent_celery_mismatches)) - _preflight_children(runtime_settings, env, root) + await asyncio.to_thread(prepare_versioned_source_bucket, env, lane="guide_journey") + _preflight_children(runtime_settings, env, cleanup_env, root) engine = create_async_engine(database_url) factory = async_sessionmaker(engine, expire_on_commit=False) diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 48446114d..4a7638361 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -78,6 +78,7 @@ def test_cleanup_child_alone_receives_a_private_distinct_principal(self): original = { 'WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID': 'upload-key', 'WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY': 'upload-secret', + 'WORKSTREAM_ARTIFACT_S3_SESSION_TOKEN': 'upload-session', 'WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID': 'cleanup-key', 'WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE': str(path), } @@ -88,7 +89,11 @@ def test_cleanup_child_alone_receives_a_private_distinct_principal(self): self.assertEqual(original['WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID'], 'upload-key') self.assertEqual(child['WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID'], 'cleanup-key') self.assertEqual(child['WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY'], 'deletion-secret') - self.assertEqual(set(child) ^ set(original), set()) + self.assertEqual(set(original) - set(child), { + 'WORKSTREAM_ARTIFACT_S3_SESSION_TOKEN', + 'WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID', + 'WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE', + }) for change in ( {'WORKSTREAM_CLI_JOURNEY_CLEANUP_ACCESS_KEY_ID': 'upload-key'}, {'WORKSTREAM_CLI_JOURNEY_CLEANUP_SECRET_FILE': str(path.parent / 'missing')}, From ccf4c28cefd85b28a768eae0312fc6ea3e10441a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:47:41 +0100 Subject: [PATCH 382/513] Compare cleanup preflight against its distinct private environment --- .../run_public_journey_probe.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 990fab0d8..16f1fee3b 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -25,7 +25,6 @@ from uuid import UUID, uuid4 import httpx -from pydantic import SecretStr from sqlalchemy import func, select, text from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine @@ -80,7 +79,7 @@ ) -def _settings_digests(settings, nonce: bytes) -> dict[str, str]: +def _settings_digests(settings, nonce: bytes, *, cleanup_env: dict[str, str] | None = None) -> dict[str, str]: """Compare every resolved setting across processes without exposing values.""" values = settings.model_dump(mode="json") for name in ( @@ -90,6 +89,12 @@ def _settings_digests(settings, nonce: bytes) -> dict[str, str]: ): secret = getattr(settings, name) values[name] = None if secret is None else secret.get_secret_value() + if cleanup_env is not None: + values.update( + artifact_s3_access_key_id=cleanup_env["WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID"], + artifact_s3_secret_access_key=cleanup_env["WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY"], + artifact_s3_session_token=None, + ) return { name: hmac.new( nonce, json.dumps(value, sort_keys=True, separators=(",", ":")).encode(), @@ -146,15 +151,10 @@ def _verify_child_configuration(role: str) -> int: def _preflight_children(settings, env: dict[str, str], cleanup_env: dict[str, str], root: Path) -> None: """Reject API/worker drift before starting real services or public requests.""" nonce = os.urandom(32) - cleanup_settings = settings.model_copy(update={ - "artifact_s3_access_key_id": SecretStr(cleanup_env["WORKSTREAM_ARTIFACT_S3_ACCESS_KEY_ID"]), - "artifact_s3_secret_access_key": SecretStr(cleanup_env["WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY"]), - "artifact_s3_session_token": None, - }) for role in ("api", "guide", "worker", "source-cleanup"): child_env = cleanup_env if role == "source-cleanup" else env - expected = cleanup_settings if role == "source-cleanup" else settings - request = json.dumps({"nonce": nonce.hex(), "expected": _settings_digests(expected, nonce)}) + expected = _settings_digests(settings, nonce, cleanup_env=cleanup_env if role == "source-cleanup" else None) + request = json.dumps({"nonce": nonce.hex(), "expected": expected}) with (root / f"preflight-{role}.log").open("wb") as errors: result = subprocess.run( [ From a53ff5c7beb02cce28f3e7494faa2d290441e08f Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:49:00 +0100 Subject: [PATCH 383/513] docs(submission): record hosted API cutover inventory --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 0a0431137..d0a439bae 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11439,3 +11439,57 @@ stored failure history, both SQL predecessor-fence parameters and the real prefork observability probe on its declared queue. The existing synthetic-context Pydantic warning remains visible. Broker-loss replay and the earlier CI OTLP missing-events failure are not closed by these eight cases. + +### Hosted API cutover inventory (2026-11-26) + +Read-only inspection of the current API host and `deploy/hosted` composition +found the enabled `workstream-hosted.service` and healthy app-profile containers +still using release `013ffbac2291179c03ff6d832f52efee9382322d`; PostgreSQL is at +`0069_remove_artifact_proof`. The existing service unit points at that release +directory. The reviewed backend agents, omnicore, and MCP images built from +`1d28b567d` passed local hosted image verification (receipts +`/tmp/workstream-host-image-5fb26081a6c9/host-only-build-1d28.json` and +`/tmp/workstream-mcp-proof-565.json`), but have no published ECR digests and are +not deployed. Agents is the currently selected backend variant; the installed +model selection remains `openai_agents_sdk` / `openrouter` / +`openai/gpt-5.6-luna`. Neither guide nor artifact data was changed. + +The existing release environment already selects the runtime AWS credential, +database and Redis secret files, app profile, model proxy, S3 bucket and region. +Separate cleanup credentials are installed at +`/etc/workstream/aws/source-cleanup.json` for +`arn:aws:iam::094032936130:user/workstream-source-cleanup`, distinct from the +runtime `workstream-storage` principal. Runner TLS files are installed at +`/etc/workstream/runner-tls/{ca.crt,app.crt,app.key}`. Twelve unique preflight +selectors remain absent: cleanup principal ARN and credential host-file path; +submission execution and source-cleanup profile paths; runner CA, certificate, +private-key paths, host, port, and server name; trusted-intake image and config +digests. Bind the runner address and server name to its installed endpoint and +certificate, and the intake digests to its qualified custody receipt rather +than template values. The verified runner capture is recorded separately at +`/tmp/workstream-paired-native-e38-custody.json`; it does not qualify the blocked +native journey. + +The typed execution and cleanup JSON candidates under +`/tmp/workstream-hosted-submission-profile-candidate/` validate structurally. +Their PRE aggregate deadline is 120 seconds; **choosing 120 seconds for C01 is +an explicit production policy decision still outstanding**. The other candidate +capacity, quota, retry, sweep, and cleanup values need reconciliation against +measured hosted behavior; the local 496 MiB MinIO resource result does not by +itself qualify hosted AWS limits. This is evidence and configuration work, not +an additional approval gate for each field. + +After the native blocker and configuration reconciliation, cutover uses the +existing `deploy/hosted/compose.py` pull/migrate/up and `preflight.py` flow: +publish the exact verified agents and MCP images to the existing +`workstream-backend` ECR repository and record actual repository digests; stage +a new exact-source release directory while retaining the old directory/unit; +back up PostgreSQL and source custody, drain old producers, migrate forward to +`0092`, run full preflight, then start the dedicated app workers and verify the +public and durable journey before repointing the enabled service unit. Existing +guide and source data stay intact. Migration is forward-only: restoring the old +`013ffbac` image against `0092` is not a safe rollback without independent +compatibility proof. Preserve the pre-migration backup and prior image for a +controlled restore or use a reviewed forward repair. No host mutation, image +publication, migration, service restart, or production cutover was performed in +this inventory. From 1f35f7dfbe01ea8c139816451928ea48550048d7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:49:23 +0100 Subject: [PATCH 384/513] docs(submission): name hosted profile JSON values precisely --- .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d0a439bae..5c09c5894 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11462,7 +11462,7 @@ Separate cleanup credentials are installed at runtime `workstream-storage` principal. Runner TLS files are installed at `/etc/workstream/runner-tls/{ca.crt,app.crt,app.key}`. Twelve unique preflight selectors remain absent: cleanup principal ARN and credential host-file path; -submission execution and source-cleanup profile paths; runner CA, certificate, +submission execution and source-cleanup profile JSON values; runner CA, certificate, private-key paths, host, port, and server name; trusted-intake image and config digests. Bind the runner address and server name to its installed endpoint and certificate, and the intake digests to its qualified custody receipt rather From 8811e7990073e69e0d30afbe7b7da114953d5630 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 09:51:25 +0100 Subject: [PATCH 385/513] test: use current feedback in signed TUI read fixture --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 27 +++++++++++++++++++ cli/tests/integration/test_tui_public_api.py | 11 +++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 5c09c5894..a8f865be0 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11493,3 +11493,30 @@ compatibility proof. Preserve the pre-migration backup and prior image for a controlled restore or use a reviewed forward repair. No host mutation, image publication, migration, service restart, or production cutover was performed in this inventory. + +### Current TUI submission fixture feedback (2026-11-26) + +Intent and bounded scope: cli/tests/integration/test_tui_public_api.py and this +record only. New0096 Backend45784976520 job139790509318 has one failure and +24 passes: the signed TUI read/revocation test supplies retired summary and +contributor_attestation fields to the closed current SubmissionIntakeMetadata. +The actual local log is /tmp/pr708-0096-cli-api.log; the failure is before its +current source producer, not a TUI authorization failure. + +Use the same nonempty text as current optional feedback; require its exact +retained public value and a null historical summary. The native TUI must render +that feedback before revocation and remove it after fresh real grant revocation. +Preserve actual source/T5 fixture, signed identity, foreign actor404, no dependency +overrides, exact read-only requests and product counts. No retired field alias, +production DTO change or privacy assertion removal. PostgreSQL execution stays +pending while the parent-owned native cold-start prerequisite holds the slot. + +Static verification: evaluate the exact old and new constructor AST nodes against +the current production model. Old fails precisely on the two retired fields; new +retains exact task/assignment IDs and nonempty feedback. AST comparison preserves +all22 original assertions, changing only the approved privacy text selector, and +adds exact null-summary and retained-feedback assertions; all other module nodes +are identical. Ruff check/format and whitespace pass. No PG/native/TUI execution +on the repaired fixture yet; the original CI failed before that fixture setup +completed. Parent holds the slot for the native prerequisite and will obtain +runtime evidence in the coordinated run or new CI. diff --git a/cli/tests/integration/test_tui_public_api.py b/cli/tests/integration/test_tui_public_api.py index a561240c6..265128db7 100644 --- a/cli/tests/integration/test_tui_public_api.py +++ b/cli/tests/integration/test_tui_public_api.py @@ -79,8 +79,7 @@ async def test_tui_real_signed_owner_positive_reads_then_fresh_grant_revocation( SubmissionIntakeMetadata( task_id=h.task_id, assignment_id=h.assignment_id, - summary="Completed the required project work.", - contributor_attestation=" ".join(h.policy["attestation_terms"]), + feedback="Completed the required project work.", ), h.archive_bytes, ) @@ -111,6 +110,10 @@ async def test_tui_real_signed_owner_positive_reads_then_fresh_grant_revocation( submission_id ] assert direct["submission"]["task_id"] == task + assert direct["submission"]["summary"] is None + assert ( + direct["submission"]["feedback"] == "Completed the required project work." + ) assert ( direct["context"]["task"]["task_id"] == direct["intake"]["task_id"] == task ) @@ -194,7 +197,7 @@ async def wait(text): await wait(direct["attempts"]["items"][0]["title"]) terminal.send("\r") await wait(submission_id) - await wait(direct["submission"]["summary"]) + await wait(direct["submission"]["feedback"]) async with h.factory() as session: grant_id = await session.scalar( select(ProjectRoleGrant.id).where( @@ -215,7 +218,7 @@ async def wait(text): assert denied.status_code == 404 terminal.send("r") await wait("Denied") - assert direct["submission"]["summary"] not in terminal.screen + assert direct["submission"]["feedback"] not in terminal.screen assert submission_id not in terminal.screen await asyncio.to_thread(terminal.quit) assert owner.token.encode() not in terminal.raw From 09599d984f35b8537dc6874befeef8934c459674 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:03:16 +0100 Subject: [PATCH 386/513] docs(submission): record published candidates and guide-stage blocker --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index a8f865be0..92b014f6b 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11520,3 +11520,27 @@ are identical. Ruff check/format and whitespace pass. No PG/native/TUI execution on the repaired fixture yet; the original CI failed before that fixture setup completed. Parent holds the slot for the native prerequisite and will obtain runtime evidence in the coordinated run or new CI. + + +Native fixture startup prerequisites are now proved: the production cleanup +validator rejects the absent service identity and accepts the provisioned +fixture; exact upload resolver/verifier actions authorize; the owned bucket +reads back versioning. `/tmp/workstream-submitters-708-cleanup-startup.json` +records complete cleanup. The companion cold2 log proves the four real child +settings profiles; its later temporary proof-script alias error was repaired +without product changes. 1f35f7dfb then started all seven consumers and Beat, +processed public guide upload, but timed out waiting for policy_draft_ready. +`/tmp/workstream-paired-native-bm3qq35f/cleanup.json` confirms database/storage +cleanup. This remains a failed combined journey, with guide dispatch/execution +under diagnosis before another full run. + +Verified 1d28 backend agents and MCP images are now staged in immutable ECR, +without API deployment. `/tmp/workstream-published-1795683620543134554.json` +binds source, exact local image IDs and repository digests: agents +`sha256:5d7df0b2f3cd6528bc5e89f9bbfb8870b805e2298a984c8bd0dffde06e3f4176`, +MCP `sha256:ad364ad848e12618003314733ab9eecf262d9b55facae2ad5bd7957ea25205eb`. +ARCH reviewed the bounded staging operator before execution. ECR login-token +response remained in memory and the invocation's remote Docker credential file +was removed in finally; no running service configuration was changed. The prior +inventory's unpublished status is superseded by this staging receipt, while its +native/configuration/migration/deployed-proof limitations remain open. From eacb176b06a7bdec56d1018a8ef539004f1817e2 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:06:35 +0100 Subject: [PATCH 387/513] test: decode retained result JSON in history oracle --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 28 +++++++++++++++++++ .../submission_history/test_privacy.py | 3 +- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 92b014f6b..f81910b4d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11544,3 +11544,31 @@ response remained in memory and the invocation's remote Docker credential file was removed in finally; no running service configuration was changed. The prior inventory's unpublished status is superseded by this staging receipt, while its native/configuration/migration/deployed-proof limitations remain open. + +### Retained history expectation JSON decoding (2026-11-26) + +Intent and bounded scope: authorization/submission_history/test_privacy.py and +this record only, based on the new0096 Backend45784976520 failures, not the old +run. Job139790509476 task_lifecycle_c has303 passes/one manager-case failure; +job139790509472 task_lifecycle_e has325 passes/one contributor-case failure. +Both exact test_nested_values_match_exact_stored_parents parameters abort at +line147 indexing CheckerRun.result_json as a dictionary. The model maps it to +Text, and production history.py explicitly casts it to JSONB before selecting +the exact stored member/finding. Downloaded artifact logs are retained privately +under /tmp/pr708-0096-task-{c,e}-artifact/metadata/. + +Decode that exact persisted JSON text in the expected-value oracle, then retain +member_order/finding_order indexing and every exact message, fallback, parent, +evidence, foreign-history and manager/contributor assertion. No fixture row, +production projection or privacy guard changes. Parent authorized this narrow +follow-up after transferring file ownership from the historical reviewer. No PG +while the native guide proof owns the shared slot. + +Pure discrimination executes the exact old/new oracle AST block over stored JSON +text containing two members and nonfirst findings. Old raises the exact CI +TypeError; new selects the exact intended diagnosis, while null message and +absent finding retain the original status fallback. Reversing only json import +and json.loads makes the full module AST identical to0096, so no assertion, +fixture or other behavior changed. Ruff/whitespace and record checks pass. Both +actual PostgreSQL manager/contributor cases remain pending coordinated runtime +or CI; these pure checks do not qualify their database projection or privacy. diff --git a/backend/tests/authorization/submission_history/test_privacy.py b/backend/tests/authorization/submission_history/test_privacy.py index f1285ad67..365b2013e 100644 --- a/backend/tests/authorization/submission_history/test_privacy.py +++ b/backend/tests/authorization/submission_history/test_privacy.py @@ -1,5 +1,6 @@ """Fixed SQL projections and live grant privacy over retained checker results.""" +import json from uuid import uuid4 import pytest @@ -144,7 +145,7 @@ async def test_nested_values_match_exact_stored_parents(task_client, monkeypatch ) message, fix = RESULT_STATUS_MESSAGES[status] if finding is not None: - retained = runs[str(row.checker_run_id)].result_json["execution"]["external_members"] + retained = json.loads(runs[str(row.checker_run_id)].result_json)["execution"]["external_members"] text = retained[row.member_order]["result"]["findings"][finding.finding_order]["message"] if text is not None: message, fix = text, None From c27c0bce7def660d15972d4ea0131f9f6ed84772 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:10:57 +0100 Subject: [PATCH 388/513] test: request guide compilation explicitly in public journey --- .../guide_inputs.py | 4 +- .../guide_polling.py | 6 ++- .../guide_runtime.py | 1 - .../public_guide_setup.py | 51 +++++++++++++++---- .../public_hosted_attachment.py | 2 +- scripts/test_public_guide_journey.py | 8 +-- scripts/test_public_hosted_attachment.py | 28 ++++++++++ 7 files changed, 82 insertions(+), 18 deletions(-) diff --git a/experiments/pilot04_external_checker_runtime/guide_inputs.py b/experiments/pilot04_external_checker_runtime/guide_inputs.py index 377ea334b..26d091b17 100644 --- a/experiments/pilot04_external_checker_runtime/guide_inputs.py +++ b/experiments/pilot04_external_checker_runtime/guide_inputs.py @@ -8,8 +8,8 @@ GUIDE_BYTES = b"""# Sample worker repair project Investigate and repair the assigned sample worker. Submit one ZIP containing -`task.toml` and `evidence/results`. Explain the work in the submission summary -and confirm rights_confirmed in the attestation. Individual files must be at +`task.toml` and `evidence/results`. You can include optional feedback about +the task or these instructions. Individual files must be at most 1000000 bytes and the package at most 5000000 bytes. The project intake image checks the package's project-specific rules. The diff --git a/experiments/pilot04_external_checker_runtime/guide_polling.py b/experiments/pilot04_external_checker_runtime/guide_polling.py index 5212637e4..59bf09606 100644 --- a/experiments/pilot04_external_checker_runtime/guide_polling.py +++ b/experiments/pilot04_external_checker_runtime/guide_polling.py @@ -13,4 +13,8 @@ async def wait_for_guide_read(client, path, token, predicate, call): if value.get("error_code") not in {None, "provider_outcome_unresolved"}: raise AssertionError("guide worker failed: " + str(value["error_code"])) await asyncio.sleep(1) - raise AssertionError("public guide setup did not reach the expected state") + raise AssertionError( + "public guide setup did not reach the expected state " + f"(status={value.get('status')!r}, step={value.get('current_step')!r}, " + f"error_code={value.get('error_code')!r}, generation={value.get('setup_generation')!r})" + ) diff --git a/experiments/pilot04_external_checker_runtime/guide_runtime.py b/experiments/pilot04_external_checker_runtime/guide_runtime.py index 8be118930..e121a9e5a 100644 --- a/experiments/pilot04_external_checker_runtime/guide_runtime.py +++ b/experiments/pilot04_external_checker_runtime/guide_runtime.py @@ -59,7 +59,6 @@ async def compile_project_guide(self, context, capabilities): submission_artifact_policy=SubmissionArtifactPolicyProposal( maximum_file_size_bytes=1_000_000, maximum_package_size_bytes=5_000_000, required_artifacts=("task.toml",), required_evidence=("results",), - attestation_terms=("rights_confirmed",), ).model_dump(mode="json"), requirements=[item.model_dump(mode="json") for item in requirements], ) diff --git a/experiments/pilot04_external_checker_runtime/public_guide_setup.py b/experiments/pilot04_external_checker_runtime/public_guide_setup.py index 5c9632cc1..1fe7a0a79 100644 --- a/experiments/pilot04_external_checker_runtime/public_guide_setup.py +++ b/experiments/pilot04_external_checker_runtime/public_guide_setup.py @@ -108,6 +108,32 @@ async def _correct_public_proposal(client, compilation_root, package, token, cal return receipt +async def _request_initial_compilation(client, root, token, call, *, manager_authored): + setup_path = root + "/setup-runs/latest" + before = await call(client, "GET", setup_path, token, 200) + if (before["status"] != "not_requested" or before["celery_task_id"] is not None + or before["finalized_compilation_id"] is not None): + raise AssertionError("guide upload did not leave setup unrequested") + path = root + ("/requirements/compile" if manager_authored else "/setup") + headers = {"Idempotency-Key": str(uuid4())} + requested = await call(client, "POST", path, token, 202, headers=headers) + replay = await call(client, "POST", path, token, 202, headers=headers) + if any(requested[field] != replay[field] for field in + ("operation_id", "setup_run_id", "setup_generation")): + raise AssertionError("guide compilation replay changed durable request identity") + if (requested["setup_run_id"], requested["setup_generation"]) != ( + before["id"], before["setup_generation"], + ): + raise AssertionError("guide compilation acknowledged a different setup") + setup = await wait_for_guide_read(client, setup_path, token, + lambda v: v["status"] == "policy_draft_ready", call) + if (setup["id"], setup["setup_generation"]) != ( + requested["setup_run_id"], requested["setup_generation"], + ) or setup["finalized_compilation_id"] is None: + raise AssertionError("guide compilation finalized outside the requested setup") + return setup + + async def _approve_policies(client, compilation_root, token, call, attachments): package = await call(client, "GET", compilation_root + "/proposal", token, 200) if package["artifact_policy_status"] != "draft" or package["current_approval_operation_id"]: @@ -241,18 +267,23 @@ async def public_guide_setup(client, factory, human_review_required, call, token raise AssertionError("guide creation replay changed source") root += "/" + guide["id"] await _public_policy_settings(client, root, token, human_review_required, call) - upload = root + f"/documents/{guide['documents'][0]['document_id']}/content" - await call(client, "POST", upload, token, 202, - headers={"Idempotency-Key": str(uuid4()), "Content-Type": "text/markdown"}, - content=original) + originals = [original] if attachment: from experiments.pilot04_external_checker_runtime.public_hosted_attachment import manager_rules - await call(client, 'POST', root + f"/documents/{guide['documents'][1]['document_id']}/content", - token, 202, headers={'Idempotency-Key': str(uuid4()), 'Content-Type': 'text/markdown'}, - content=(model_post.rules(original, pre_requirements) if model_post else - manager_rules(original, pre_requirements))) - setup = await wait_for_guide_read(client, root + "/setup-runs/latest", token, - lambda v: v["status"] == "policy_draft_ready", call) + originals.append(model_post.rules(original, pre_requirements) if model_post else + manager_rules(original, pre_requirements)) + for document, content in zip(guide["documents"], originals, strict=True): + upload = root + f"/documents/{document['document_id']}/content" + receipt = await call(client, "POST", upload, token, 202, + headers={"Idempotency-Key": str(uuid4()), "Content-Type": "text/markdown"}, + content=content) + if (receipt["status"] != "object_confirmed" + or receipt["document_id"] != document["document_id"] + or receipt["sha256"] != "sha256:" + hashlib.sha256(content).hexdigest() + or receipt["byte_count"] != len(content)): + raise AssertionError("guide upload did not confirm the declared original bytes") + setup = await _request_initial_compilation(client, root, token, call, + manager_authored=attachment is not None) compilation_root = root + f"/compilations/{setup['finalized_compilation_id']}" initial = await call(client, "GET", compilation_root + "/proposal", token, 200) initial_setup = setup diff --git a/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py b/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py index 2e8f279c5..7ce1a9755 100644 --- a/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py +++ b/experiments/pilot04_external_checker_runtime/public_hosted_attachment.py @@ -499,7 +499,7 @@ def manager_rules(original, count): 'evidence_refs': refs}], 'submission_artifact_policy': {'maximum_file_size_bytes': 1_000_000, 'maximum_package_size_bytes': 5_000_000, 'required_artifacts': ['task.toml'], - 'required_evidence': ['results'], 'attestation_terms': ['rights_confirmed']}, + 'required_evidence': ['results']}, 'requirements': requirements, 'setup_notes': []}, sort_keys=True, separators=(',', ':')).encode() diff --git a/scripts/test_public_guide_journey.py b/scripts/test_public_guide_journey.py index 98c705671..7d5e2c121 100644 --- a/scripts/test_public_guide_journey.py +++ b/scripts/test_public_guide_journey.py @@ -79,10 +79,12 @@ async def test_inflight_unresolved_is_observed_without_retry_or_success(self): for item in call.await_args_list)) async def test_uncertainty_never_becomes_success_at_deadline(self): - call = AsyncMock(return_value={"status": "dispatch_pending", - "error_code": "provider_outcome_unresolved"}) - with self.assertRaisesRegex(AssertionError, "did not reach"): + call = AsyncMock(return_value={"status": "dispatch_pending", "current_step": "queued", + "error_code": "provider_outcome_unresolved", "setup_generation": 2, + "error_summary": "private guide contents"}) + with self.assertRaisesRegex(AssertionError, "did not reach.*dispatch_pending.*generation=2") as fault: await self.read(call) + self.assertNotIn("private guide contents", str(fault.exception)) self.assertEqual(call.await_count, 120) async def test_terminal_errors_and_http_failure_are_not_hidden(self): diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 4a7638361..9d9d6838c 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -927,6 +927,34 @@ def test_current_guide_refuses_zero_or_multiple_pre_before_setup(self): with self.subTest(count=count), self.assertRaisesRegex(ValueError, 'exactly one PRE'): asyncio.run(public_guide_setup(None, None, True, None, None, pre_requirements=count)) + def test_guide_setup_requires_explicit_request_and_preserves_generation(self): + from experiments.pilot04_external_checker_runtime.public_guide_setup import _request_initial_compilation + + root = '/api/v1/projects/project/guides/guide' + setup_path = root + '/setup-runs/latest' + before = {'id': 'setup', 'setup_generation': 1, 'status': 'not_requested', + 'celery_task_id': None, 'finalized_compilation_id': None} + receipt = {'operation_id': 'operation', 'setup_run_id': 'setup', 'setup_generation': 1, + 'status': 'queued'} + ready = before | {'status': 'policy_draft_ready', 'finalized_compilation_id': 'compilation'} + for manager_authored, route in ((False, '/setup'), (True, '/requirements/compile')): + with self.subTest(manager_authored=manager_authored): + call = AsyncMock(side_effect=[before, receipt, receipt | {'status': ready['status']}, ready]) + result = asyncio.run(_request_initial_compilation(None, root, 'token', call, + manager_authored=manager_authored)) + self.assertEqual(result, ready) + reads_and_writes = call.await_args_list + self.assertEqual([item.args[1:] for item in reads_and_writes], [ + ('GET', setup_path, 'token', 200), ('POST', root + route, 'token', 202), + ('POST', root + route, 'token', 202), ('GET', setup_path, 'token', 200), + ]) + self.assertEqual(reads_and_writes[1].kwargs, reads_and_writes[2].kwargs) + self.assertIn('Idempotency-Key', reads_and_writes[1].kwargs['headers']) + + call = AsyncMock(side_effect=[before, receipt, receipt, ready | {'setup_generation': 2}]) + with self.assertRaisesRegex(AssertionError, 'finalized outside the requested setup'): + asyncio.run(_request_initial_compilation(None, root, 'token', call, manager_authored=False)) + def test_source_failure_preserves_exact_charge_and_releases_only_task_pointer(self): from experiments.pilot04_external_checker_runtime import public_intake_trials as intake From c17b866dc2357c50f27c6d555ed305607d31a69a Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:13:31 +0100 Subject: [PATCH 389/513] test: check guide upload receipt at public boundary --- .../pilot04_external_checker_runtime/public_guide_setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/experiments/pilot04_external_checker_runtime/public_guide_setup.py b/experiments/pilot04_external_checker_runtime/public_guide_setup.py index 1fe7a0a79..6ca273d81 100644 --- a/experiments/pilot04_external_checker_runtime/public_guide_setup.py +++ b/experiments/pilot04_external_checker_runtime/public_guide_setup.py @@ -277,7 +277,7 @@ async def public_guide_setup(client, factory, human_review_required, call, token receipt = await call(client, "POST", upload, token, 202, headers={"Idempotency-Key": str(uuid4()), "Content-Type": "text/markdown"}, content=content) - if (receipt["status"] != "object_confirmed" + if (receipt["status"] != "document_stored" or receipt["document_id"] != document["document_id"] or receipt["sha256"] != "sha256:" + hashlib.sha256(content).hexdigest() or receipt["byte_count"] != len(content)): From eddb8b5600af085d391aa002ff885f4d6faa9abe Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:21:54 +0100 Subject: [PATCH 390/513] test: isolate OTLP log sources from migration configuration --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 40 +++++++++++++++++++ backend/tests/test_observability_otlp.py | 8 ++++ 2 files changed, 48 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f81910b4d..17e318205 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11572,3 +11572,43 @@ and json.loads makes the full module AST identical to0096, so no assertion, fixture or other behavior changed. Ruff/whitespace and record checks pass. Both actual PostgreSQL manager/contributor cases remain pending coordinated runtime or CI; these pure checks do not qualify their database projection or privacy. + +### OTLP failure-matrix logging precondition (2026-11-26) + +Intent and bounded scope: tests/test_observability_otlp.py and this record only. +New0096 schema_contracts_a job139790509534 has199 passes and one timeout-case +failure with an empty log event set. Exact artifact15102175569 is retained at +/tmp/pr708-0096-schema-a-artifact/metadata/schema_contracts_a.log. The standalone +three-mode matrix, partial-cleanup/timeout pair, and exact nine same-shard pure +observability predecessors pass; this does not explain away the repeated CI red. + +Causal probe: after importing the OTLP test, call the actual +logging.config.fileConfig('alembic.ini') used by alembic/env.py:19. It changes +existing Celery and OpenTelemetry logger.disabled flags to true. The unchanged +timeout case then fails exactly with events=set() in1.76s +(/tmp/pr708-0096-otlp-alembic-logging-before.log), without PG or broker. Prior +in-process migration tests configure logging before this synthetic log proof. + +Make the matrix's logging inputs explicit: temporarily enable existing loggers in +only its tested Celery/OpenTelemetry families through pytest monkeypatch, which +restores their prior disabled flags afterward. Preserve required event labels, +sanitization, registered task execution, fail-open results and all deadlines. No +production logger behavior, migration configuration/guard, provider or skip +change. Validate against the exact real Alembic logging precondition, including +restoration, rather than relaxing the event assertion. + +Final discriminator: under that same actual Alembic fileConfig precondition, all +three unchanged failure modes pass in2.67s +(/tmp/pr708-0096-otlp-alembic-logging-after.log). The probe checks every original +Celery/OpenTelemetry logger disabled flag is restored after pytest and an +unrelated disabled logger stays disabled. Old exact timeout fails; repaired +matrix retains exactly the original event set, output/privacy checks, registered +task execution and timings. Removing only the explicit logger-input setup gives +full module AST equality to the base. No test skip, production edit or node +inventory change. The exact partial-cleanup/timeout pair passed2 in4.88s and +nine same-shard pure observability predecessors passed9 in17.73s before this +repair, which narrowed the cause rather than qualifying a full CI shard. + +Ruff/whitespace and record/link checks pass. Full PG/backend/native qualification +was not rerun; this is local HTTP-only logging fixture isolation. No deployed +image rebuild is needed for a test setup correction. diff --git a/backend/tests/test_observability_otlp.py b/backend/tests/test_observability_otlp.py index 73ff6cda6..045640f2d 100644 --- a/backend/tests/test_observability_otlp.py +++ b/backend/tests/test_observability_otlp.py @@ -310,6 +310,14 @@ async def test_real_otlp_http_transport_is_sanitized_and_fail_open( failure_mode: str, monkeypatch: pytest.MonkeyPatch, ) -> None: + # In-process Alembic tests can disable existing library loggers. Supply + # enabled sources for this matrix, restoring their prior policy afterward. + for logger in tuple(logging.Logger.manager.loggerDict.values()): + if isinstance(logger, logging.Logger) and logger.name.split(".", 1)[0] in { + "celery", + "opentelemetry", + }: + monkeypatch.setattr(logger, "disabled", False) if failure_mode == "refusal": with socket.socket() as reservation: reservation.bind(("127.0.0.1", 0)) From ddc888caee66ef1bda027812ebf31acc5d6c7c5e Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:25:00 +0100 Subject: [PATCH 391/513] docs(submission): reconcile fixture repairs and staged deployment evidence --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 17e318205..5914bcd3f 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11612,3 +11612,37 @@ repair, which narrowed the cause rather than qualifying a full CI shard. Ruff/whitespace and record/link checks pass. Full PG/backend/native qualification was not rerun; this is local HTTP-only logging fixture isolation. No deployed image rebuild is needed for a test setup correction. + + +Guide caller reconciliation is integrated: explicitly request `/setup` or +`/requirements/compile`, verify same-key request identity and exact finalized +generation, and check the fresh upload's public `document_stored` receipt. +The caller suite passed 78 tests; actual guide-only proof remains unsuccessful. +Its final c17 run started all seven consumers/API/Redis/Beat but its temporary +HMAC issuer mismatched stored actor identity at project creation. Cleanup was +complete; that separate launcher was retired from this qualification attempt. +The paired native launcher had already proved signed project creation/uploads +and is now replaying the corrected caller from frozen eddb8b560. No end-to-end +success follows from startup, unit tests, or temporary launcher repairs. + +The 0096 CI run ended with four direct failures (TUI retired inputs, two exact +history JSON-text expectations, and the OTLP timeout test); aggregate failures +only propagated these. All four repairs are integrated, with the OTLP failure +reproduced by real Alembic fileConfig disabling existing loggers and its three +modes passing after narrowly restored test-local logger enablement. Required +events, deadlines and privacy assertions remain unchanged. Final-head CI is +still required. + +Local MinIO refused storage during guide qualification. Seven duplicate build +archive copies were SHA-256 verified against retained exact copies, then only +those duplicate files were unlinked, reclaiming 2,624,762,738 bytes. Every unique +archive and JSON manifest remains; `/tmp/workstream-pre-root-duplicate-reclaim.json` +records original inode/size/hash and retained-copy mapping. No Docker resources, +user source, database or deployed artifact storage was purged. + +The review-only overlay `/tmp/workstream-hosted-submission-profile-candidate-7ceb/` +contains published image digests plus the twelve absent deployment selectors. +Its two profiles validate through their current owner contracts, and the PRE +root digest now matches the independently checked runner rather than the old +root. This local preparation has not been applied; C01 and measured/deployed +qualification remain outstanding. From 825a9f3840e7576724ae1fc72b1e9e881b276928 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:31:37 +0100 Subject: [PATCH 392/513] test: bind PostgreSQL storage guards to current schema shards --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 28 +++++++++++++++++++ scripts/test_lightweight_agent_gates.py | 4 +-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 5914bcd3f..b0009de61 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11646,3 +11646,31 @@ Its two profiles validate through their current owner contracts, and the PRE root digest now matches the independently checked runner rather than the old root. This local preparation has not been applied; C01 and measured/deployed qualification remain outstanding. + +### Lightweight PostgreSQL shard predicate expectations (2026-11-26) + +Intent and bounded scope: scripts/test_lightweight_agent_gates.py and this +record only. Current ddc Agent Gates45791913261 reports precisely the two +PostgreSQL storage tests: their literals still expect retired unsuffixed +schema_contracts, while the actual workflow correctly binds all three +schema_contracts_a/b/c to disk. The authoritative failure log is +/tmp/pr708-ddc-agent-gates.log; the exact two local tests reproduce the same +literal failures (/tmp/pr708-postgres-storage-shards-before.log). + +Update both independent test predicates to the exact three-shard membership, +without an unsuffixed alias. No workflow, PostgreSQL configuration, budgets, +canonical inventory or production code changes. Retain the bounded2GiB tmpfs +contract for non-schema lanes, disk aggregate, guard-before-execution order and +every filesystem/size/data-directory/write-setting/error rejection. Parent owns +the heavy native slot; all validation here is local string/shell simulation, no +PG/broker/native process. + +Both exact storage tests pass in0.716s after the two literal corrections +(/tmp/pr708-postgres-storage-shards-after.log); all31 tests in the existing +lightweight-gates module pass in5.056s +(/tmp/pr708-postgres-storage-lightweight-after.log). Six isolated workflow-text +mutants omit each schema shard from both predicates; each named test rejects +every omission. The actual durability and storage shell remains unchanged, with +all original malformed/wrong-size/wrong-device/off-setting/error cases executed. +Ruff/whitespace and record/link checks pass. No backward-compatibility path, +storage relaxation, CI rerun, PostgreSQL/broker/native work or remote write. diff --git a/scripts/test_lightweight_agent_gates.py b/scripts/test_lightweight_agent_gates.py index 2e5f89f8c..6221a655f 100644 --- a/scripts/test_lightweight_agent_gates.py +++ b/scripts/test_lightweight_agent_gates.py @@ -1007,7 +1007,7 @@ def test_postgres_storage_is_bounded_and_disk_contracts_remain(self) -> None: "\n steps:", 1 )[0] self.assertIn( - "${{ matrix.lane != 'schema_contracts' && " + "${{ !contains(fromJSON('[\"schema_contracts_a\",\"schema_contracts_b\",\"schema_contracts_c\"]'), matrix.lane) && " "'--tmpfs /var/lib/postgresql/data:rw,nosuid,nodev,noexec,size=2147483648' || '' }}", lane_service, ) @@ -1024,7 +1024,7 @@ def test_postgres_storage_guard_rejects_wrong_mounts_and_write_settings(self) -> )[1].split("\n - name:", 1)[0] self.assertIn("POSTGRES_CONTAINER: ${{ job.services.postgres.id }}", step) self.assertIn( - "EXPECTED_PG_STORAGE: ${{ matrix.lane == 'schema_contracts' && 'disk' || 'tmpfs' }}", + "EXPECTED_PG_STORAGE: ${{ contains(fromJSON('[\"schema_contracts_a\",\"schema_contracts_b\",\"schema_contracts_c\"]'), matrix.lane) && 'disk' || 'tmpfs' }}", step, ) guard = textwrap.dedent(step.split(" run: |\n", 1)[1]) From eb74d39b864c248b20f4a5d63ef49c1bf2da2bc4 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:33:36 +0100 Subject: [PATCH 393/513] refactor(mcp): remove retired preparation mutation error token --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 17 +++++++++++++++++ mcp_server/workstream_mcp/http_gateway.py | 1 - 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b0009de61..8f02ee5b5 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11674,3 +11674,20 @@ every omission. The actual durability and storage shell remains unchanged, with all original malformed/wrong-size/wrong-device/off-setting/error cases executed. Ruff/whitespace and record/link checks pass. No backward-compatibility path, storage relaxation, CI rerun, PostgreSQL/broker/native work or remote write. + + +Bounded v0.1 retirement audit: the old public preparation mutation and retired +submission flags remain absent; CLI references to those flags are negative tests +requiring rejection before HTTP. Historical preparation reads protect A33 and +have no new submission writer. One genuinely orphaned MCP public-error token, +submission_preparation_headers_invalid, has no remaining backend emitter or +caller. Allowed change is its removal from http_gateway.py and this record; +no aliases, fallback behavior, historical deletion, route or permission change. +The existing gateway error/privacy tests verify the unchanged closed error +projection. Risk is low and root reviews the exact removal. Rebuild/reverify +MCP before deployment because its packaged bytes change; backend images are +unaffected. + +The existing MCP HTTP gateway suite passed 38 cases in 1.76 seconds after the +retired error token removal; its existing dependency deprecation warning remains +visible. No new mutation path or compatibility handling was introduced. diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py index e99316e76..7d977a156 100644 --- a/mcp_server/workstream_mcp/http_gateway.py +++ b/mcp_server/workstream_mcp/http_gateway.py @@ -98,7 +98,6 @@ "last_access_administrator", "invalid_role_scope", "service_unavailable", - "submission_preparation_headers_invalid", "submission_unavailable", "submission_packet_invalid", "submission_infrastructure_unavailable", From d37d990ca482f722a5dcbfe0d6f00c6dd7975410 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:43:18 +0100 Subject: [PATCH 394/513] test: compile paired native guides without inference --- .../guide_evidence.py | 23 ++++---- .../public_guide_setup.py | 35 ++++++++----- .../public_probe_support.py | 4 +- .../run_public_journey_probe.py | 46 +++++++++------- scripts/test_public_guide_journey.py | 20 ++++++- scripts/test_public_hosted_attachment.py | 52 +++++++++++++++++-- 6 files changed, 135 insertions(+), 45 deletions(-) diff --git a/experiments/pilot04_external_checker_runtime/guide_evidence.py b/experiments/pilot04_external_checker_runtime/guide_evidence.py index 6592afedf..d5a515816 100644 --- a/experiments/pilot04_external_checker_runtime/guide_evidence.py +++ b/experiments/pilot04_external_checker_runtime/guide_evidence.py @@ -1,8 +1,8 @@ -"""Small evidence oracle for the recorded guide drill; no product authority.""" +"""Evidence oracle for the public guide drill.""" def verify_source_commitment(source, attempt, *, examples, examples_hash, source_hash, - source_id, original_sha256, accesses): + source_id, original_sha256s, accesses, manager_authored): """Check persisted input lineage and original-read custody, never generated prose.""" if (source["task_examples"] != examples or source["task_examples_hash"] != examples_hash @@ -15,12 +15,17 @@ def verify_source_commitment(source, attempt, *, examples, examples_hash, source or str(attempt["source_snapshot_id"]) != source_id or attempt["canonical_input_hash"] != attempt["compiled_input_hash"]): raise AssertionError("worker input lineage differs") - if not any( - str(access["source_snapshot_id"]) == source_id - and access["sha256"] == original_sha256 - and access["manifest_sha256"] == attempt["guide_material_hash"] - and access["access_method"] == "trusted_parser" - and access["operation"] == "read" - for access in accesses + if manager_authored and ( + attempt["runtime_key"] != "manager_authored" or attempt["model_provider"] != "none" + or attempt["setup_model_slots"] != 0 ): + raise AssertionError("manager-authored guide used model assistance") + read_digests = { + access["sha256"] + for access in accesses + if str(access["source_snapshot_id"]) == source_id + and access["manifest_sha256"] == attempt["guide_material_hash"] + and access["access_method"] == "trusted_parser" and access["operation"] == "read" + } + if read_digests != set(original_sha256s): raise AssertionError("worker original-read custody is missing") diff --git a/experiments/pilot04_external_checker_runtime/public_guide_setup.py b/experiments/pilot04_external_checker_runtime/public_guide_setup.py index 6ca273d81..64eabae03 100644 --- a/experiments/pilot04_external_checker_runtime/public_guide_setup.py +++ b/experiments/pilot04_external_checker_runtime/public_guide_setup.py @@ -163,9 +163,10 @@ async def _approve_policies(client, compilation_root, token, call, attachments): return await call(client, "GET", post_root, token, 200) -async def _source_evidence(factory, guide, setup, package, original): +async def _source_evidence(factory, guide, setup, package, originals, *, manager_authored): expected_examples = [x.model_dump(mode="json") for x in validate_task_examples(TASK_EXAMPLES)] examples_hash = task_examples_hash(validate_task_examples(TASK_EXAMPLES)) + original_digests = tuple("sha256:" + hashlib.sha256(content).hexdigest() for content in originals) async with factory() as session: source = (await session.execute(text( "SELECT g.task_examples,g.task_examples_hash,s.manifest_json,s.bundle_hash " @@ -174,7 +175,11 @@ async def _source_evidence(factory, guide, setup, package, original): ), {"guide": guide["id"], "source": setup["source_snapshot_id"]})).one() attempt = (await session.execute(text( "SELECT a.id,a.canonical_input_hash,a.source_snapshot_hash,a.source_snapshot_id," - "a.guide_material_hash,a.status,c.canonical_input_hash AS compiled_input_hash " + "a.guide_material_hash,a.status,c.canonical_input_hash AS compiled_input_hash," + "a.runtime_configuration->>'runtime_key' AS runtime_key," + "a.runtime_configuration->>'model_provider' AS model_provider," + "(SELECT count(*) FROM setup_model_usage_slots m " + " WHERE m.compilation_attempt_id=a.id) AS setup_model_slots " "FROM project_guide_compilation_attempts a " "JOIN project_guide_compilations c ON c.id=a.persisted_compilation_id AND c.attempt_id=a.id " "WHERE a.setup_run_id=:setup" @@ -189,7 +194,7 @@ async def _source_evidence(factory, guide, setup, package, original): source._mapping, attempt._mapping, examples=expected_examples, examples_hash=examples_hash, source_hash=package["target"]["source_snapshot_hash"], source_id=setup["source_snapshot_id"], accesses=accesses, - original_sha256="sha256:" + hashlib.sha256(original).hexdigest(), + original_sha256s=original_digests, manager_authored=manager_authored, ) return {"guide_id": guide["id"], "setup_run_id": setup["id"], "setup_generation": setup["setup_generation"], @@ -197,7 +202,9 @@ async def _source_evidence(factory, guide, setup, package, original): "source_snapshot_hash": source.bundle_hash, "task_examples_hash": examples_hash, "canonical_input_hash": attempt.canonical_input_hash, - "uploaded_sha256": "sha256:" + hashlib.sha256(original).hexdigest()} + "guide_compilation_runtime": attempt.runtime_key, + "uploaded_sha256": original_digests[0], + **({"manager_rules_sha256": original_digests[1]} if manager_authored else {})} async def _local_approval_attachments(factory): @@ -227,10 +234,12 @@ async def _local_approval_attachments(factory): async def public_guide_setup(client, factory, human_review_required, call, token_for, *, - pre_requirements=1, attachment=None, issuer="https://identity.flowresearch.tech"): + pre_requirements=1, attachment=None, issuer="https://identity.flowresearch.tech", + manager_authored=False): if pre_requirements != 1: raise ValueError("current qualification requires exactly one PRE image") model_post = attachment.model_post if attachment else None + manager_authored = manager_authored or attachment is not None if model_post and 'project_id' in model_post.state: raise RuntimeError('this model qualification already owns one project') original = model_post.guide_bytes() if model_post else guide_bytes(pre_requirements) @@ -248,6 +257,7 @@ async def public_guide_setup(client, factory, human_review_required, call, token await attachment.grant(client, 'manager', 'project_manager', project['id']) else: await seed_review_actor(factory, UUID(project["id"]), actor=manager) + if not manager_authored: from guide_compilation_e2e import publish_scripted_model_profile operator, _ = await seed_review_actor(factory, None, role="operator", scope="system", issuer=issuer) profile = await publish_scripted_model_profile(client, token_for(operator), project["id"]) @@ -258,7 +268,7 @@ async def public_guide_setup(client, factory, human_review_required, call, token body = {"version": "initial", "change_summary": "Original sample worker guide", "task_examples": TASK_EXAMPLES, "documents": [{"label": "guide.md", "media_type": "text/markdown"}]} - if attachment: + if manager_authored: body['documents'].append({'label': 'workstream-rules.json', 'media_type': 'text/markdown'}) headers = {"Idempotency-Key": str(uuid4())} guide = await call(client, "POST", root, token, 201, headers=headers, json=body) @@ -268,7 +278,7 @@ async def public_guide_setup(client, factory, human_review_required, call, token root += "/" + guide["id"] await _public_policy_settings(client, root, token, human_review_required, call) originals = [original] - if attachment: + if manager_authored: from experiments.pilot04_external_checker_runtime.public_hosted_attachment import manager_rules originals.append(model_post.rules(original, pre_requirements) if model_post else manager_rules(original, pre_requirements)) @@ -283,14 +293,14 @@ async def public_guide_setup(client, factory, human_review_required, call, token or receipt["byte_count"] != len(content)): raise AssertionError("guide upload did not confirm the declared original bytes") setup = await _request_initial_compilation(client, root, token, call, - manager_authored=attachment is not None) + manager_authored=manager_authored) compilation_root = root + f"/compilations/{setup['finalized_compilation_id']}" - initial = await call(client, "GET", compilation_root + "/proposal", token, 200) - initial_setup = setup attachments = (model_post.approval_attachments() if model_post else attachment.approval_attachments(pre_requirements) if attachment else await _local_approval_attachments(factory)) - if human_review_required and attachment is None: + if human_review_required and not manager_authored: + initial = await call(client, "GET", compilation_root + "/proposal", token, 200) + initial_setup = setup correction = await _correct_public_proposal(client, compilation_root, initial, token, call) setup = await wait_for_guide_read(client, root + "/setup-runs/latest", token, lambda v: v["status"] == "policy_draft_ready" @@ -316,7 +326,8 @@ async def public_guide_setup(client, factory, human_review_required, call, token "post_approval_operation_id", "post_approval_output_digest", "guide_mutation_generation", "review", "revision", "expected_previous_active_guide_id", "expected_previous_active_guide_generation", )}, **context["contribution"]} - evidence = await _source_evidence(factory, guide, setup, post["proposal"], original) + evidence = await _source_evidence(factory, guide, setup, post["proposal"], originals, + manager_authored=manager_authored) target, upstream = post["target"], post["target"]["upstream"] evidence["locked_context"] = { "locked_guide_version": guide["version"], diff --git a/experiments/pilot04_external_checker_runtime/public_probe_support.py b/experiments/pilot04_external_checker_runtime/public_probe_support.py index f5434cc50..1e3071b12 100644 --- a/experiments/pilot04_external_checker_runtime/public_probe_support.py +++ b/experiments/pilot04_external_checker_runtime/public_probe_support.py @@ -223,7 +223,8 @@ async def _started_public_task(client, *, project_id: str, manager_token: str, return task_id, assignment_id -async def _public_project(client, factory, env, *, human_review_required, pre_requirements=1): +async def _public_project(client, factory, env, *, human_review_required, pre_requirements=1, + manager_authored=False): """Public guide activation and submitter grant shared by every runtime trial.""" from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment from experiments.pilot04_external_checker_runtime.public_submission_clients import seeded_issuer @@ -232,6 +233,7 @@ async def _public_project(client, factory, env, *, human_review_required, pre_re compilation = await public_guide_setup( client, factory, human_review_required, _json, lambda actor: _token(env, actor), pre_requirements=pre_requirements, attachment=attachment, issuer=seeded_issuer(env), + manager_authored=manager_authored, ) manager = compilation.manager guide_id = str(compilation.guide_id) diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 16f1fee3b..96fecb66f 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -1,7 +1,8 @@ """Exercise public original-guide setup through a governed contribution outcome. Run only with isolated PostgreSQL/MinIO and an owned disposable Redis broker. -Inference is explicitly recorded; real Celery executes the canonical setup owners. +The separate-runner journey compiles manager-authored rules in the production worker. +The same-host fault drill exercises explicitly recorded guide assistance. """ from __future__ import annotations @@ -13,6 +14,7 @@ from decimal import Decimal import hashlib import hmac +from importlib import import_module import json import os from pathlib import Path @@ -121,6 +123,12 @@ def _celery_config_mismatches(settings, worker_app=None) -> list[str]: return [name for name in expected if expected[name] != actual[name]] +def _worker_app_module(role: str, *, recorded_assistance: bool) -> str: + if role == "guide" and recorded_assistance: + return "experiments.pilot04_external_checker_runtime.guide_worker" + return "app.workers.celery_app" + + def _verify_child_configuration(role: str) -> int: """Import the same API or worker entry point and report only mismatched keys.""" request = json.load(sys.stdin) @@ -130,11 +138,9 @@ def _verify_child_configuration(role: str) -> int: actual = app.state.settings else: - if role == "guide": - from experiments.pilot04_external_checker_runtime.guide_worker import celery_app - else: - from app.workers.celery_app import celery_app - + celery_app = import_module(_worker_app_module( + role, recorded_assistance=request["recorded_assistance"], + )).celery_app actual = get_settings() observed = _settings_digests(actual, nonce) expected = request["expected"] @@ -148,13 +154,15 @@ def _verify_child_configuration(role: str) -> int: return 0 -def _preflight_children(settings, env: dict[str, str], cleanup_env: dict[str, str], root: Path) -> None: +def _preflight_children(settings, env: dict[str, str], cleanup_env: dict[str, str], root: Path, + *, recorded_assistance: bool) -> None: """Reject API/worker drift before starting real services or public requests.""" nonce = os.urandom(32) for role in ("api", "guide", "worker", "source-cleanup"): child_env = cleanup_env if role == "source-cleanup" else env expected = _settings_digests(settings, nonce, cleanup_env=cleanup_env if role == "source-cleanup" else None) - request = json.dumps({"nonce": nonce.hex(), "expected": expected}) + request = json.dumps({"nonce": nonce.hex(), "expected": expected, + "recorded_assistance": recorded_assistance}) with (root / f"preflight-{role}.log").open("wb") as errors: result = subprocess.run( [ @@ -198,11 +206,10 @@ def _process(command: list[str], *, env: dict[str, str], log: Path) -> subproces def _start_worker(env: dict[str, str], root: Path, role: str, queue: str, - generation: int = 1, *, launch=None) -> tuple[subprocess.Popen, str]: + generation: int = 1, *, launch=None, recorded_assistance=False) -> tuple[subprocess.Popen, str]: """Start one owned prefork worker for exactly one registered workload queue.""" hostname = f"first-journey-{role}-{uuid4().hex}@localhost" - celery_app = ("experiments.pilot04_external_checker_runtime.guide_worker" - if role == "guide" else "app.workers.celery_app") + celery_app = _worker_app_module(role, recorded_assistance=recorded_assistance) process = (launch or _process)([ sys.executable, "-m", "celery", "-A", celery_app, "worker", "--pool=prefork", "--concurrency=1", @@ -905,7 +912,7 @@ async def _one_mode(client, factory, env, *, stop_worker: Callable[[], None] | None = None, start_worker: Callable[[], Awaitable[None]] | None = None, fault_root=None, operator_token=None, clients: ContributorClients | None = None, - exercise_faults: bool = True) -> dict: + exercise_faults: bool = True, manager_authored: bool = False) -> dict: from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment attachment = env if isinstance(env, HostedAttachment) else None @@ -913,7 +920,7 @@ async def _one_mode(client, factory, env, *, from app.workers.outbox import deliver_event compilation, contributor, manager_token, contributor_token = await _public_project( - client, factory, env, human_review_required=human_review_required, + client, factory, env, human_review_required=human_review_required, manager_authored=manager_authored, ) project_id = str(compilation.project_id) approved_guide = await _json( @@ -1274,7 +1281,9 @@ async def run(database_url: str, image_reference: str, node_config: Path, "WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST": intake_image["config_image_id"], "PYTHONPATH": os.pathsep.join(map(str, (BACKEND, BACKEND / "tests", BACKEND.parent))), }) - configure_scripted_model_session_environment(env) + recorded_assistance = not separate_runner + if recorded_assistance: + configure_scripted_model_session_environment(env) env.pop("OPENAI_API_KEY", None) if clients is not None: env = clients.setup_authority(env) @@ -1345,7 +1354,7 @@ async def run(database_url: str, image_reference: str, node_config: Path, "parent broker configuration differs from resolved Settings: " + ", ".join(parent_celery_mismatches)) await asyncio.to_thread(prepare_versioned_source_bucket, env, lane="guide_journey") - _preflight_children(runtime_settings, env, cleanup_env, root) + _preflight_children(runtime_settings, env, cleanup_env, root, recorded_assistance=recorded_assistance) engine = create_async_engine(database_url) factory = async_sessionmaker(engine, expire_on_commit=False) @@ -1408,6 +1417,7 @@ async def start_owned_worker() -> None: for role, queue in WORKER_ROLES: process, hostname = _start_worker( cleanup_env if role == "source-cleanup" else env, root, role, queue, launch=launch, + recorded_assistance=recorded_assistance, ) workers.append(process) await _wait_worker(process, hostname) @@ -1436,14 +1446,14 @@ async def start_owned_worker() -> None: true = await _one_mode(client, factory, env, human_review_required=True, operator_id=operator.actor_profile_id, clients=clients, - exercise_faults=not separate_runner) + exercise_faults=not separate_runner, manager_authored=separate_runner) false = await _one_mode(client, factory, env, human_review_required=False, operator_id=operator.actor_profile_id, stop_worker=stop_owned_worker, start_worker=start_owned_worker, fault_root=fault_root, operator_token=_token(env, operator), clients=clients, - exercise_faults=not separate_runner) + exercise_faults=not separate_runner, manager_authored=separate_runner) _require(api.poll() is None and beat.poll() is None and all(process.poll() is None for process in workers), "API, dedicated prefork worker, or Beat exited during public journey") @@ -1460,7 +1470,7 @@ async def start_owned_worker() -> None: "scheduled_artifact_scans": True, "public_original_guide_setup": True, "connected_submitter_clients": ["cli", "mcp"] if clients is not None else [], - "recorded_inference": True, + "recorded_inference": recorded_assistance, "custody": {key: custody[key] for key in ( 'source_tree', 'config_sha256', 'service_sha256', 'smol_sha256', 'guest_sha256', ) + (() if separate_runner else ('wrapper_sha256',))}, diff --git a/scripts/test_public_guide_journey.py b/scripts/test_public_guide_journey.py index 7d5e2c121..a282da92f 100644 --- a/scripts/test_public_guide_journey.py +++ b/scripts/test_public_guide_journey.py @@ -22,7 +22,8 @@ def setUp(self): manifest_json={"task_examples_hash": self.expected["examples_hash"], "task_examples_count": 2}, bundle_hash=self.expected["source_hash"]) - self.expected.update(source_id="source-1", original_sha256="sha256:" + "e" * 64, + self.expected.update(source_id="source-1", original_sha256s=("sha256:" + "e" * 64,), + manager_authored=False, accesses=[{"source_snapshot_id": "source-1", "sha256": "sha256:" + "e" * 64, "manifest_sha256": "sha256:" + "f" * 64, "access_method": "trusted_parser", "operation": "read"}]) @@ -60,6 +61,23 @@ def test_correct_storage_cannot_hide_different_worker_inputs(self): with self.assertRaisesRegex(AssertionError, "original-read"): verify_source_commitment(self.source, self.attempt, **(self.expected | {"accesses": []})) + def test_manager_authored_compilation_binds_both_originals_without_model_slots(self): + rules_sha256 = "sha256:" + "7" * 64 + guide, = self.expected["accesses"] + both = self.expected | { + "manager_authored": True, "original_sha256s": (guide["sha256"], rules_sha256), + "accesses": [guide, guide | {"sha256": rules_sha256}], + } + runtime = self.attempt | {"runtime_key": "manager_authored", "model_provider": "none", + "setup_model_slots": 0} + verify_source_commitment(self.source, runtime, **both) + with self.assertRaisesRegex(AssertionError, "original-read"): + verify_source_commitment(self.source, runtime, **(both | {"accesses": [guide]})) + for field, value in (("runtime_key", "openai"), ("model_provider", "openai"), + ("setup_model_slots", 1)): + with self.subTest(field=field), self.assertRaisesRegex(AssertionError, "used model assistance"): + verify_source_commitment(self.source, runtime | {field: value}, **both) + class SetupPollingTests(unittest.IsolatedAsyncioTestCase): async def read(self, call): diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py index 9d9d6838c..48bea5107 100644 --- a/scripts/test_public_hosted_attachment.py +++ b/scripts/test_public_hosted_attachment.py @@ -118,16 +118,16 @@ def test_every_workload_starts_one_dedicated_queue_with_the_right_app(self): ) self.assertEqual(probe.WORKER_ROLES, expected) with patch.object(probe, '_process', return_value=object()) as launch: - for role, queue in expected: - with self.subTest(role=role): + for recorded_assistance in (False, True): + for role, queue in expected: launch.reset_mock() - probe._start_worker({}, Path('/owned'), role, queue) + probe._start_worker({}, Path('/owned'), role, queue, recorded_assistance=recorded_assistance) command = launch.call_args.args[0] self.assertEqual([part for part in command if part.startswith('--queues=')], [f'--queues={queue}']) self.assertEqual(command[command.index('-A') + 1], 'experiments.pilot04_external_checker_runtime.guide_worker' - if role == 'guide' else 'app.workers.celery_app') + if role == 'guide' and recorded_assistance else 'app.workers.celery_app') self.assertIn('--pool=prefork', command) self.assertIn('--concurrency=1', command) self.assertIn(f'{role}-worker-1.log', str(launch.call_args.kwargs['log'])) @@ -955,6 +955,50 @@ def test_guide_setup_requires_explicit_request_and_preserves_generation(self): with self.assertRaisesRegex(AssertionError, 'finalized outside the requested setup'): asyncio.run(_request_initial_compilation(None, root, 'token', call, manager_authored=False)) + def test_local_manager_authored_guide_submits_both_originals_and_preserves_approval_pins(self): + from experiments.pilot04_external_checker_runtime import public_guide_setup as setup + + project = {'id': str(uuid4())} + docs = [{'document_id': str(uuid4())}, {'document_id': str(uuid4())}] + guide = {'id': str(uuid4()), 'documents': docs} + root = f"/api/v1/projects/{project['id']}/guides/{guide['id']}" + guide_original = setup.guide_bytes() + originals = (guide_original, manager_rules(guide_original, 1)) + uploads = [{'status': 'document_stored', 'document_id': document['document_id'], + 'sha256': 'sha256:' + hashlib.sha256(content).hexdigest(), 'byte_count': len(content)} + for document, content in zip(docs, originals, strict=True)] + before = {'id': 'setup', 'setup_generation': 1, 'status': 'not_requested', + 'celery_task_id': None, 'finalized_compilation_id': None} + receipt = {'operation_id': 'operation', 'setup_run_id': 'setup', 'setup_generation': 1, + 'status': 'queued'} + ready = before | {'status': 'policy_draft_ready', 'finalized_compilation_id': 'compilation'} + pins = {'pre_submit_attachments': [object()], 'post_submit_attachments': [object()]} + for review_required in (True, False): + with self.subTest(review_required=review_required): + call = AsyncMock(side_effect=[project, guide, guide, *uploads, before, receipt, receipt, ready]) + with (patch.object(setup, 'seed_review_actor', new=AsyncMock(return_value=(object(), None))), + patch.object(setup, '_public_policy_settings', new=AsyncMock()) as policy, + patch.object(setup, '_local_approval_attachments', new=AsyncMock(return_value=pins)), + patch.object(setup, '_finance_policy', new=AsyncMock()) as finance, + patch.object(setup, '_approve_policies', new=AsyncMock(side_effect=RuntimeError('approval reached'))) as approve, + patch('guide_compilation_e2e.publish_scripted_model_profile', new=AsyncMock()) as profile, + patch.object(setup, '_correct_public_proposal', new=AsyncMock()) as correction): + with self.assertRaisesRegex(RuntimeError, 'approval reached'): + asyncio.run(setup.public_guide_setup(None, None, review_required, call, lambda _: 'token', + manager_authored=True)) + profile.assert_not_awaited() + correction.assert_not_awaited() + policy.assert_awaited_once_with(None, root, 'token', review_required, call) + self.assertIs(finance.await_args.args[4], not review_required) + approve.assert_awaited_once_with(None, root + '/compilations/compilation', 'token', call, pins) + self.assertEqual(call.await_args_list[1].kwargs['json']['documents'], [ + {'label': 'guide.md', 'media_type': 'text/markdown'}, + {'label': 'workstream-rules.json', 'media_type': 'text/markdown'}, + ]) + self.assertEqual(tuple(item.kwargs['content'] for item in call.await_args_list[3:5]), originals) + self.assertEqual([item.args[2] for item in call.await_args_list[6:8]], + [root + '/requirements/compile'] * 2) + def test_source_failure_preserves_exact_charge_and_releases_only_task_pointer(self): from experiments.pilot04_external_checker_runtime import public_intake_trials as intake From a9a186746dcdd05bce57f2f30a42528ad71d8ae8 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 10:50:26 +0100 Subject: [PATCH 395/513] docs(submission): bound guide parser startup CPU repair --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 8f02ee5b5..23b550322 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11691,3 +11691,21 @@ unaffected. The existing MCP HTTP gateway suite passed 38 cases in 1.76 seconds after the retired error token removal; its existing dependency deprecation warning remains visible. No new mutation path or compatibility handling was introduced. + +### Bound guide parser child startup CPU + +The paired native run at eddb8b560 timed out at the retained initial guide +compilation attempt. The exact local parser's hardened children consumed +4.095 and 4.085 CPU seconds and exited on SIGXCPU before writing a response. +At lower load, an import-only child consumed 1.911 CPU seconds and the same +framed parse consumed 1.973 CPU seconds. The release image contains no +Pydantic bytecode. The observations are retained in +`/tmp/workstream-paired-native-parser-child.log` and +`/tmp/workstream-paired-native-parser-import-profile.log`. + +Scope is the existing release image dependency installation and this record. +Test build-time bytecode compilation before changing parser imports. Verify +the same source frames through hardened children and a disposable parser +socket, using the existing resource limits, privilege drop, and file-system +isolation. The current parser daemon stays in service while the candidate is +measured. The paired native journey remains pending. From ea31dd60981ff650afdcde4ef5ba262bdb7b5c4c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:01:08 +0100 Subject: [PATCH 396/513] build: precompile parser imports in the backend release image --- docker/backend/Dockerfile.release | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docker/backend/Dockerfile.release b/docker/backend/Dockerfile.release index 31d40762b..5de3060d4 100644 --- a/docker/backend/Dockerfile.release +++ b/docker/backend/Dockerfile.release @@ -36,12 +36,14 @@ COPY packages/external-services/ /workspace/packages/external-services/ COPY backend/ ./ COPY docker/backend/release-entrypoint.sh /usr/local/bin/workstream-release-entrypoint +# The read-only guide parser starts a fresh Python child for each original. RUN --mount=type=cache,target=/root/.cache/uv \ case "${WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT}" in \ agents|omnicore) ;; \ *) echo "WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT must be agents or omnicore" >&2; exit 1 ;; \ esac \ - && uv sync --locked --extra "${WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT}" --no-dev --no-editable \ + && uv sync --locked --extra "${WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT}" --no-dev --no-editable --compile-bytecode \ + && python -m compileall -q -j 2 /usr/local/lib/python3.12 /workspace/backend/app \ && install -d -m 0755 /etc/workstream \ && printf '%s\n' "${WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT}" \ > /etc/workstream/project-agent-sdk-environment \ From 0d509b1b620af00f424b2253d171a1ee27a9214b Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:06:56 +0100 Subject: [PATCH 397/513] docs(submission): record release parser round-trip evidence --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 23b550322..965b270a9 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11709,3 +11709,22 @@ the same source frames through hardened children and a disposable parser socket, using the existing resource limits, privilege drop, and file-system isolation. The current parser daemon stays in service while the candidate is measured. The paired native journey remains pending. + +Compiling only the image's installed dependencies still left one guarded +parser child hitting SIGXCPU. The release recipe now compiles dependency, +standard-library, and application bytecode at build time. The full-cache +derivative parsed both the guide and manager rules on both child identities +in 1.073–1.317 CPU seconds per document. Its real parser socket returned both +originals and the production rules compiler verified their citations. + +The actual agents release image built from `6c2df5b7` produced +`sha256:086b7b2c97b868ae78952b4bb1e28eea80df8a8fc73b7d51ddaadbfabe901fdb`. +With the existing isolation and limits, the same four child checks used +1.002–1.542 CPU seconds. The real socket returned the 686-byte guide and +3,020-byte manager rules in 1.076 and 1.510 seconds. The production adapter +validated the full responses and their exact source and parser hashes. The +production compiler emitted source-cited PRE and POST rules. The disposable +container was removed, and the existing parser kept its original container +identity and start time. All 20 release contract tests passed. Build and +runtime receipts are in `/tmp/workstream-parser-bytecode.hUOuQAPF/`. +The separate-runner paired submission journey remains pending. From cb58b80a36c041fa1df579fe223c5d2ab5234284 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:10:24 +0100 Subject: [PATCH 398/513] style: format native journey versioning and runtime helpers --- .../test_journey_bucket_versioning.py | 16 +++++++++++----- cli/tests/journey/runtime.py | 4 +++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/cli/tests/integration/test_journey_bucket_versioning.py b/cli/tests/integration/test_journey_bucket_versioning.py index 6011f21ae..f0d84b59c 100644 --- a/cli/tests/integration/test_journey_bucket_versioning.py +++ b/cli/tests/integration/test_journey_bucket_versioning.py @@ -49,9 +49,13 @@ def test_journey_enables_and_reads_back_exact_owned_source_bucket(lane): client = VersioningClient() bucket = f"workstream-ci-{lane.replace('_', '-')}-{SUFFIX}" MODULE.prepare_versioned_source_bucket( - ENVIRONMENT | {"WORKSTREAM_TEST_MINIO_BUCKET": bucket, - "WORKSTREAM_TEST_MINIO_PREFIX": f"ci/{lane}/{SUFFIX}"}, - lane=lane, client_factory=factory_for(client), + ENVIRONMENT + | { + "WORKSTREAM_TEST_MINIO_BUCKET": bucket, + "WORKSTREAM_TEST_MINIO_PREFIX": f"ci/{lane}/{SUFFIX}", + }, + lane=lane, + client_factory=factory_for(client), ) assert client.calls == [ ("put", {"Bucket": bucket, "VersioningConfiguration": {"Status": "Enabled"}}), @@ -63,8 +67,10 @@ def test_journey_enables_and_reads_back_exact_owned_source_bucket(lane): "change", [ {"WORKSTREAM_TEST_MINIO_BUCKET": "workstream-artifacts"}, - {"WORKSTREAM_TEST_MINIO_BUCKET": f"workstream-ci-guide-journey-{SUFFIX}", - "WORKSTREAM_TEST_MINIO_PREFIX": f"ci/guide_journey/{SUFFIX}"}, + { + "WORKSTREAM_TEST_MINIO_BUCKET": f"workstream-ci-guide-journey-{SUFFIX}", + "WORKSTREAM_TEST_MINIO_PREFIX": f"ci/guide_journey/{SUFFIX}", + }, {"WORKSTREAM_TEST_MINIO_PREFIX": "ci/cli_full_journey/other"}, ], ) diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py index ee4a6d16b..add5bf179 100644 --- a/cli/tests/journey/runtime.py +++ b/cli/tests/journey/runtime.py @@ -273,7 +273,9 @@ def prepare_versioned_source_bucket( raise RuntimeError("journey source bucket is not runner-owned") bucket = environment.get("WORKSTREAM_TEST_MINIO_BUCKET", "") prefix = environment.get("WORKSTREAM_TEST_MINIO_PREFIX", "") - match = re.fullmatch(rf"workstream-ci-{lane.replace('_', '-')}-([a-f0-9]{{12}})", bucket) + match = re.fullmatch( + rf"workstream-ci-{lane.replace('_', '-')}-([a-f0-9]{{12}})", bucket + ) if match is None or prefix != f"ci/{lane}/{match.group(1)}": raise RuntimeError("journey source bucket is not runner-owned") if client_factory is None: From 458aa0a9711afdaf28de97e094ecb524fd18f280 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:11:23 +0100 Subject: [PATCH 399/513] docs(submission): track quality notification integration boundary --- .commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index d5bc61c48..ea0cf0e46 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -44,6 +44,7 @@ work. Existing reward owners remain authoritative. - [ ] Exact task/assignment status exposes current safe feedback, processing activity, revision terms and accepted evidence without internal-ID discovery. - [x] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits. - [ ] Combined public contributor journey proves correction, revision, replay, history and applicable existing awards on the integrated code. +- [ ] Quality-feedback email uses the stable assignment ID, with a dedicated consumer and no infrastructure-failure notifications; integrate and prove delivery after sender DNS verification and private key configuration. The checked items have focused contract and PostgreSQL proof. The guide and assignment status changes are implemented and await the connected native proof. From 95f24dd3d7c1cee761ab3b209cac57c78fbcc0ec Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:05:09 +0100 Subject: [PATCH 400/513] Resolve contributor feedback by assignment ID --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 21 +++++++++++++++++++ backend/app/api/deps/contributor_reads.py | 9 ++++---- backend/app/api/routes/contributor_reads.py | 10 ++++----- .../modules/tasks/api/contributor_reads.py | 4 ++-- .../app/modules/tasks/contributor_reads.py | 13 ++++++------ .../tests/contributor_reads/test_authority.py | 11 ++++++++++ .../test_revision_capacity.py | 2 +- .../tasks/test_public_submission_intake.py | 8 ++++--- backend/tests/test_api_controls.py | 7 +++++-- backend/tests/test_api_rate_controls.py | 2 +- 10 files changed, 62 insertions(+), 25 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 965b270a9..4735bb9c6 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -29,6 +29,27 @@ heads. The full specification remains unfinished. `interfaces/artifacts.py` derives keys from content SHA. The new design needs operation-based keys before bytes are known and exact durable identity afterward. +### Assignment-only contributor status and feedback + +The assignment ID is the stable contributor reference across intake attempts, +submitted versions and revisions. The contributor status read resolves the +exact owned assignment by that ID, checks the current Submitter grant in its +project, and derives the task and attempt from the existing response snapshot. +It returns the same current PRE, POST, revision and acceptance evidence. + +Allowed files are the contributor status route, response composition and TASK +read port, their CLI/MCP callers and selected contract, nearby tests, current +user documentation, and the public journey callers. Replace the nested task +selector with `/api/v1/actors/me/assignments/{assignment_id}` and align the CLI +and MCP inputs in this PR. Preserve the existing authorization action, query +scope, concealment, submission write contracts and immutable evidence IDs. +Leave notification delivery to its separate owner in this same PR. + +This read-selector change affects an authorization boundary. Verify the exact +route and clients, foreign or missing assignments, grant loss, and retained +attempt selection. Security, architecture, QA and documentation review focus +on owner-scoped lookup, exact current evidence and convergence of all clients. + ## Bounded change ### Allowed diff --git a/backend/app/api/deps/contributor_reads.py b/backend/app/api/deps/contributor_reads.py index 839a2535b..46fc515fe 100644 --- a/backend/app/api/deps/contributor_reads.py +++ b/backend/app/api/deps/contributor_reads.py @@ -260,11 +260,11 @@ async def read(_grant): await self._run(request, read) yield verified - async def assignment(self, task_id: UUID, assignment_id: UUID, *, limit: int, cursor: str | None): + async def assignment(self, assignment_id: UUID, *, limit: int, cursor: str | None): """Resolve only an exact owned assignment before project read authorization.""" try: await start_read_snapshot(self._session) - project_id = await self._work.resolve_own_assignment_project(task_id, assignment_id, self._actor_id) + project_id = await self._work.resolve_own_assignment_project(assignment_id, self._actor_id) except SQLAlchemyError as exc: await self._session.rollback() raise _unavailable() from exc @@ -272,16 +272,17 @@ async def assignment(self, task_id: UUID, assignment_id: UUID, *, limit: int, cu await self._session.rollback() raise _missing() request = self._request( - "task.assignment.read", {"task_id": str(task_id), "limit": limit}, + "task.assignment.read", {"limit": limit}, resource_id=assignment_id, project_id=project_id, cursor=cursor, ) async def read(grant): - selected = await self._work.read_own_assignment(project_id, task_id, assignment_id, self._actor_id) + selected = await self._work.read_own_assignment(project_id, assignment_id, self._actor_id) if selected is None: await self._session.commit() raise _missing() assignment = selected.assignment + task_id = assignment.task_id intake = await self._intake.read_assignment_attempt(AssignmentIntakeQuery( project_id, task_id, assignment_id, self._actor_id, selected.active_operation_id, )) diff --git a/backend/app/api/routes/contributor_reads.py b/backend/app/api/routes/contributor_reads.py index bdf4973c6..bf12c4015 100644 --- a/backend/app/api/routes/contributor_reads.py +++ b/backend/app/api/routes/contributor_reads.py @@ -54,15 +54,15 @@ async def list_my_assignments( @router.get( - "/tasks/{task_id}/assignments/{assignment_id}", response_model=ExactContributorAssignment, - tags=["tasks"], responses=_ERRORS, + "/actors/me/assignments/{assignment_id}", response_model=ExactContributorAssignment, + tags=["actors"], responses=_ERRORS, openapi_extra={"x-workstream-action-id": "task.assignment.read"}, ) async def read_my_assignment( - task_id: UUID, assignment_id: UUID, reads: Reads, limit: PageLimit = 25, cursor: PageCursor = None, + assignment_id: UUID, reads: Reads, limit: PageLimit = 25, cursor: PageCursor = None, ) -> ExactContributorAssignment: - """Read your assignment status, feedback and earned evidence by task and assignment.""" - return await reads.assignment(task_id, assignment_id, limit=limit, cursor=cursor) + """Read your assignment status, feedback and earned evidence by assignment ID.""" + return await reads.assignment(assignment_id, limit=limit, cursor=cursor) @router.get( diff --git a/backend/app/modules/tasks/api/contributor_reads.py b/backend/app/modules/tasks/api/contributor_reads.py index f882abc79..80cd63adf 100644 --- a/backend/app/modules/tasks/api/contributor_reads.py +++ b/backend/app/modules/tasks/api/contributor_reads.py @@ -147,11 +147,11 @@ class ContributorWorkReadPort(Protocol): """Read-only TASK projections; the caller owns authority and the transaction.""" async def resolve_own_assignment_project( - self, task_id: UUID, assignment_id: UUID, contributor_id: UUID, + self, assignment_id: UUID, contributor_id: UUID, ) -> UUID | None: ... async def read_own_assignment( - self, project_id: UUID, task_id: UUID, assignment_id: UUID, contributor_id: UUID, + self, project_id: UUID, assignment_id: UUID, contributor_id: UUID, ) -> OwnAssignmentSelection | None: ... async def read_assignments( diff --git a/backend/app/modules/tasks/contributor_reads.py b/backend/app/modules/tasks/contributor_reads.py index 05536c96d..aa2d48cba 100644 --- a/backend/app/modules/tasks/contributor_reads.py +++ b/backend/app/modules/tasks/contributor_reads.py @@ -240,24 +240,23 @@ def __init__( self._finding_counts = finding_counts @staticmethod - def _own_assignment_scope(task_id, assignment_id, contributor_id): + def _own_assignment_scope(assignment_id, contributor_id): return ( - TaskAssignment.task_id == str(task_id), TaskAssignment.id == str(assignment_id), TaskAssignment.contributor_id == str(contributor_id), ) - async def resolve_own_assignment_project(self, task_id, assignment_id, contributor_id) -> UUID | None: + async def resolve_own_assignment_project(self, assignment_id, contributor_id) -> UUID | None: project = await self._session.scalar(select(TaskAssignment.project_id).where( - *self._own_assignment_scope(task_id, assignment_id, contributor_id), + *self._own_assignment_scope(assignment_id, contributor_id), )) return UUID(project) if project is not None else None async def read_own_assignment( - self, project_id, task_id, assignment_id, contributor_id, + self, project_id, assignment_id, contributor_id, ) -> OwnAssignmentSelection | None: rows, _ = await read_assignment_page(self._session, self._tasks, ( - *self._own_assignment_scope(task_id, assignment_id, contributor_id), + *self._own_assignment_scope(assignment_id, contributor_id), TaskAssignment.project_id == str(project_id), ), state=None, updated_since=None, after=None, limit=1) if not rows: @@ -266,7 +265,7 @@ async def read_own_assignment( operation = None if assignment.state == "active": operation = await self._session.scalar(select(WorkstreamTask.active_submission_operation_id).where( - WorkstreamTask.id == str(task_id), WorkstreamTask.project_id == str(project_id), + WorkstreamTask.id == str(assignment.task_id), WorkstreamTask.project_id == str(project_id), WorkstreamTask.assigned_to == str(contributor_id), )) return OwnAssignmentSelection(assignment, UUID(operation) if operation is not None else None) diff --git a/backend/tests/contributor_reads/test_authority.py b/backend/tests/contributor_reads/test_authority.py index d8b04e2e0..ff369c383 100644 --- a/backend/tests/contributor_reads/test_authority.py +++ b/backend/tests/contributor_reads/test_authority.py @@ -25,6 +25,9 @@ async def _preparation(task): async def test_another_contributor_never_receives_the_owners_records(task_client, monkeypatch): project, task, _submission = await submitted_case(task_client, monkeypatch) preparation = await _preparation(task) + [assignment] = (await get_ok(task_client, f"{ME}/assignments", project_id=project))["items"] + assignment_path = f"{ME}/assignments/{assignment['assignment_id']}" + assert (await get_ok(task_client, assignment_path))["assignment"]["task_id"] == task await as_actor(task_client, monkeypatch, OTHER, grant_project=project) for name in LISTS: assert (await get_ok(task_client, f"{ME}/{name}"))["items"] == [] @@ -33,6 +36,10 @@ async def test_another_contributor_never_receives_the_owners_records(task_client assert summary["assignments"] == {"active": 0, "closed": 0} and not any(summary["submissions"].values()) assert await status_of(task_client, preparations_path(task)) == 404 assert await status_of(task_client, f"{preparations_path(task)}/{preparation.id}") == 404 + foreign = await task_client.get(assignment_path, headers=auth_headers()) + missing = await task_client.get(f"{ME}/assignments/{new_record_id()}", headers=auth_headers()) + assert foreign.status_code == missing.status_code == 404 + assert foreign.json()["error"]["code"] == missing.json()["error"]["code"] async def test_project_filter_without_a_submitter_grant_is_not_found(task_client, monkeypatch): @@ -54,6 +61,9 @@ async def test_project_filter_without_a_submitter_grant_is_not_found(task_client async def test_revoked_submitter_loses_every_own_work_read(task_client, monkeypatch): project, task, _submission = await submitted_case(task_client, monkeypatch) preparation = await _preparation(task) + [assignment] = (await get_ok(task_client, f"{ME}/assignments", project_id=project))["items"] + assignment_path = f"{ME}/assignments/{assignment['assignment_id']}" + assert await status_of(task_client, assignment_path) == 200 owner = await actor_id(OWNER) async with db_session.get_session_factory()() as session: grant = await session.scalar(select(ProjectRoleGrant.id).where( @@ -71,6 +81,7 @@ async def test_revoked_submitter_loses_every_own_work_read(task_client, monkeypa assert await status_of(task_client, f"{ME}/{name}", project_id=project) == 404 assert await status_of(task_client, preparations_path(task)) == 404 assert await status_of(task_client, f"{preparations_path(task)}/{preparation.id}") == 404 + assert await status_of(task_client, assignment_path) == 404 assert (await get_ok(task_client, f"{ME}/projects"))["items"] == [] diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index 641ddabd2..25886ff3d 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -387,7 +387,7 @@ async def test_rebase_retains_original_attempt_and_selects_current_terms( assert view["preparation_id"] == str(h.revision_preparation_id) assert view["outcome"] == "rebased" and view["disposition"] == "ready" assert "contribution" in {change["component"] for change in view["changes"]} - status = await client.get(f"/api/v1/tasks/{h.request.task_id}/assignments/{h.request.assignment_id}") + status = await client.get(f"/api/v1/actors/me/assignments/{h.request.assignment_id}") assert status.status_code == 200, status.text context = status.json() assert context["current_status"] == "needs_revision" and context["next_action"] == "revise" diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index cd781e47b..019840193 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -154,7 +154,7 @@ async def test_public_malformed_zip_preserves_task_and_retains_cleanup_custody( and item.get("failure_code") == "submission_archive_malformed" for item in results) assert not any(item["source"] == "project_external_checker" for item in results) status = await client.get( - f"/api/v1/tasks/{f.task}/assignments/{f.assignment}", headers=f.access.target.headers, + f"/api/v1/actors/me/assignments/{f.assignment}", headers=f.access.target.headers, ) assert status.status_code == 200, status.text assignment = status.json() @@ -218,15 +218,17 @@ async def test_public_minimal_submission_survives_acceptance_finalization_and_re assert first.status_code == 202, first.text receipt = first.json() assert receipt["status"] == "accepted" and receipt["replayed"] is False - status_path = f"/api/v1/tasks/{f.task}/assignments/{f.assignment}" + status_path = f"/api/v1/actors/me/assignments/{f.assignment}" pending = await client.get(status_path, headers=f.access.target.headers) assert pending.status_code == 200, pending.text assert pending.json()["current_status"] == "evaluation_pending" assert pending.json()["next_action"] == "awaiting_evaluation" + assert pending.json()["assignment"]["task_id"] == str(f.task) + assert pending.json()["assignment"]["assignment_id"] == str(f.assignment) assert pending.json()["assignment"]["latest_submission"] is None assert pending.json()["intake"]["pre_submission_results"] == receipt["pre_submission_results"] assert (await client.get( - f"/api/v1/tasks/{f.task}/assignments/{new_record_id()}", headers=f.access.target.headers, + f"/api/v1/actors/me/assignments/{new_record_id()}", headers=f.access.target.headers, )).status_code == 404 warnings = [item["warning_code"] for item in receipt["pre_submission_results"] if item["source"] == "workstream_default" and item["status"] == "warning"] diff --git a/backend/tests/test_api_controls.py b/backend/tests/test_api_controls.py index 9a28f4a9e..fcde80555 100644 --- a/backend/tests/test_api_controls.py +++ b/backend/tests/test_api_controls.py @@ -523,7 +523,7 @@ def test_openapi_documents_request_error_and_response_context() -> None: contributor_reads = { "GET /api/v1/actors/me/projects": "actor.project.list", "GET /api/v1/actors/me/assignments": "actor.assignment.list", - "GET /api/v1/tasks/{task_id}/assignments/{assignment_id}": "task.assignment.read", + "GET /api/v1/actors/me/assignments/{assignment_id}": "task.assignment.read", "GET /api/v1/projects/{project_id}/contributor-guide": "project.contributor_guide.read", "GET /api/v1/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content": "project.contributor_guide.read", @@ -670,7 +670,7 @@ def test_openapi_documents_request_error_and_response_context() -> None: assert operation["security"] assert len(route_inventory) == 137 contributor_journey_routes = { - "GET /api/v1/tasks/{task_id}/assignments/{assignment_id}", + "GET /api/v1/actors/me/assignments/{assignment_id}", "GET /api/v1/projects/{project_id}/contributor-guide", "GET /api/v1/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content", } @@ -684,6 +684,9 @@ def test_openapi_documents_request_error_and_response_context() -> None: "8aa0828260680a7bccdb055ebb3f21fcd06d4e37a808b4a0a37dcbf77ffa0732" ) assert "/api/v1/tasks/{task_id}/submission-precheck" not in schema["paths"] + assignment_route = schema["paths"]["/api/v1/actors/me/assignments/{assignment_id}"]["get"] + assert [p["name"] for p in assignment_route["parameters"] if p["in"] == "path"] == ["assignment_id"] + assert "/api/v1/tasks/{task_id}/assignments/{assignment_id}" not in schema["paths"] assert "/api/v1/workers/me/profile" not in schema["paths"] assert "post" in schema["paths"]["/api/v1/tasks/{task_id}/submissions"] assert "GET /api/v1/tasks/{task_id}/submissions" in protected_inventory diff --git a/backend/tests/test_api_rate_controls.py b/backend/tests/test_api_rate_controls.py index cec3660d8..46c0720dd 100644 --- a/backend/tests/test_api_rate_controls.py +++ b/backend/tests/test_api_rate_controls.py @@ -1014,7 +1014,7 @@ async def unavailable() -> None: ("GET", "/projects/{project_id}/contribution-policies"), ("GET", "/projects/{project_id}/contributor-guide"), ("GET", "/projects/{project_id}/contributor-guide/{guide_id}/documents/{document_id}/content"), - ("GET", "/tasks/{task_id}/assignments/{assignment_id}"), + ("GET", "/actors/me/assignments/{assignment_id}"), ("GET", "/projects/{project_id}/guides"), ("GET", "/projects/{project_id}/guides/{guide_id}"), ("GET", "/projects/{project_id}/guides/{guide_id}/activation-readiness"), From 56351def1ad8a7ec9ae77917f7af1519a0b381ea Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:08:19 +0100 Subject: [PATCH 401/513] Use assignment IDs in contributor feedback clients --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 2 +- README.md | 6 ++-- .../test_revision_capacity.py | 12 ++++++- cli/README.md | 13 ++++---- cli/internal/api/contributor_reads.go | 10 +++--- cli/internal/command/submission.go | 15 ++++----- .../test_contributor_reads_http.py | 32 +++++++++++++++++++ cli/tests/integration/test_submission_http.py | 1 + .../integration/test_submission_public_api.py | 2 +- docs/roadmap_status.md | 7 ++-- .../public_submission_clients.py | 6 ++-- .../run_public_journey_probe.py | 8 ++--- mcp_server/README.md | 7 ++-- mcp_server/contracts/task_assignment_get.json | 22 ++++--------- mcp_server/tests/test_task_execution.py | 28 +++++++++++++++- mcp_server/workstream_mcp/http_gateway.py | 10 +++--- mcp_server/workstream_mcp/schemas.py | 8 +++-- .../workstream_mcp/tools/task_execution.py | 4 ++- 18 files changed, 129 insertions(+), 64 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index ea0cf0e46..5bad05637 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -41,7 +41,7 @@ work. Existing reward owners remain authoritative. - [x] Four required submission inputs and optional feedback; backend-selected revision context and exact actor-scoped replay. - [x] Forward migration preserves historical accepted commands and refuses unsafe old in-flight work before mutation. - [ ] Approved project and governing task guides are readable/downloadable before claim under exact contributor authority. -- [ ] Exact task/assignment status exposes current safe feedback, processing activity, revision terms and accepted evidence without internal-ID discovery. +- [ ] Assignment-ID status exposes current safe feedback, processing activity, revision terms and accepted evidence without internal-ID discovery. - [x] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits. - [ ] Combined public contributor journey proves correction, revision, replay, history and applicable existing awards on the integrated code. - [ ] Quality-feedback email uses the stable assignment ID, with a dedicated consumer and no infrastructure-failure notifications; integrate and prove delivery after sender DNS verification and private key configuration. diff --git a/README.md b/README.md index bdbb13d96..c185704d5 100644 --- a/README.md +++ b/README.md @@ -191,9 +191,9 @@ It sends your Flow token, from An eligible Submitter can read the project's approved guide before claiming work. The CLI uses the same ZIP command for initial work and revisions. Run -`workstream task status TASK_ID --assignment ASSIGNMENT_ID` to read current -status, feedback and accepted evidence. The MCP exposes the same task and -assignment read. [Contributor CLI guide](cli/README.md#submit-and-inspect-contributor-work). +`workstream task status ASSIGNMENT_ID` to read current status, feedback and +accepted evidence. The API and MCP use the same assignment ID through revisions. +[Contributor CLI guide](cli/README.md#submit-and-inspect-contributor-work). ## Repository layout diff --git a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py index 25886ff3d..1f2eefa03 100644 --- a/backend/tests/tasks/submission_dispatch/test_revision_capacity.py +++ b/backend/tests/tasks/submission_dispatch/test_revision_capacity.py @@ -387,7 +387,8 @@ async def test_rebase_retains_original_attempt_and_selects_current_terms( assert view["preparation_id"] == str(h.revision_preparation_id) assert view["outcome"] == "rebased" and view["disposition"] == "ready" assert "contribution" in {change["component"] for change in view["changes"]} - status = await client.get(f"/api/v1/actors/me/assignments/{h.request.assignment_id}") + status_path = f"/api/v1/actors/me/assignments/{h.request.assignment_id}" + status = await client.get(status_path) assert status.status_code == 200, status.text context = status.json() assert context["current_status"] == "needs_revision" and context["next_action"] == "revise" @@ -423,6 +424,15 @@ async def test_rebase_retains_original_attempt_and_selects_current_terms( submission_id = await finalize_retained_intake(h.factory, SimpleNamespace( operation_id=UUID(created.json()["operation_id"]), store=h.store.wrapped, namespace=h.namespace, settings=settings)) + updated = await client.get(status_path) + assert updated.status_code == 200, updated.text + view = updated.json() + assert view["current_status"] == "evaluation_pending" + assert view["assignment"]["assignment_id"] == str(h.request.assignment_id) + assert view["assignment"]["latest_submission"]["submission_id"] == str(submission_id) + assert view["assignment"]["latest_submission"]["version"] == 2 + assert view["feedback_submission_id"] in (None, str(submission_id)) + assert view["post_submission_results"] == [] async with h.factory() as session: dispatch = await session.get(SubmissionDispatch, submission_id) assert dispatch.submission_version == 2 diff --git a/cli/README.md b/cli/README.md index 82e092f63..2db7f6e80 100644 --- a/cli/README.md +++ b/cli/README.md @@ -1113,7 +1113,7 @@ delivery, worker completion, live setup inference or deployed Flow behavior. ```sh workstream task submit TASK_ID --assignment ASSIGNMENT_ID --file work.zip \ --idempotency-key CALLER_UUID -workstream task status TASK_ID --assignment ASSIGNMENT_ID +workstream task status ASSIGNMENT_ID # After correcting work, use the same command and a new key. workstream task submit TASK_ID --assignment ASSIGNMENT_ID --file revision.zip \ --idempotency-key REVISION_KEY --feedback 'Updated the examples.' @@ -1138,11 +1138,12 @@ ID. Nullable Submission/evaluation IDs remain null before finalization. The operation's processing stage, PRE feedback and next-action advice come from the server; current task status is contextual and may differ from a historical outcome. -Use `task status` with the task and assignment IDs to see current work status, -the relevant intake and evaluation feedback, revision deadline and terms, and -accepted contribution evidence. A status read is available throughout ordinary -revisions and afterwards in the assignment history. The backend selects the -current predecessor and revision terms under lock. It refuses an attempt if +Use `task status ASSIGNMENT_ID` to see current work status, intake and evaluation +feedback, revision deadline and terms, and accepted contribution evidence. The +same assignment ID works throughout revisions and afterwards in the assignment +history. API clients use `GET /api/v1/actors/me/assignments/{assignment_id}`. +The status response includes the task ID for `task submit`. The backend selects +the current predecessor and revision terms under lock. It refuses an attempt if eligibility or the selected terms change while intake is in progress. Optional `--feedback` is project feedback. The header accepts up to 4096 printable diff --git a/cli/internal/api/contributor_reads.go b/cli/internal/api/contributor_reads.go index 37c5b45c8..0b573cfdb 100644 --- a/cli/internal/api/contributor_reads.go +++ b/cli/internal/api/contributor_reads.go @@ -339,17 +339,17 @@ func decodeContributorAssignment(raw json.RawMessage) (ContributorAssignment, bo } // TaskAssignment reads current status and bounded intake and evaluation feedback for an owned claim. -func (c *Client) TaskAssignment(ctx context.Context, task, assignment string, limit int, cursor *string) (Result[AssignmentStatus], error) { +func (c *Client) TaskAssignment(ctx context.Context, assignment string, limit int, cursor *string) (Result[AssignmentStatus], error) { var result Result[AssignmentStatus] - if !submissionSelector(task) || !submissionSelector(assignment) || + if !submissionSelector(assignment) || limit < 1 || limit > 100 || (cursor != nil && !validTaskCursor(*cursor)) { - return result, errors.New("task status requires task and assignment UUIDs and a valid feedback page") + return result, errors.New("task status requires an assignment UUID and a valid feedback page") } query := url.Values{"limit": {strconv.Itoa(limit)}} if cursor != nil { query.Set("cursor", *cursor) } - path := "/api/v1/tasks/" + canonicalUUID(task) + "/assignments/" + canonicalUUID(assignment) + path := "/api/v1/actors/me/assignments/" + canonicalUUID(assignment) raw, err := c.request(ctx, http.MethodGet, path, query.Encode(), nil) if err != nil { return result, err @@ -365,7 +365,7 @@ func (c *Client) TaskAssignment(ctx context.Context, task, assignment string, li return result, &Failure{Code: "invalid_api_response"} } row, ok := decodeContributorAssignment(fields["assignment"]) - if !ok || !sameUUID(row.TaskID, task) || !sameUUID(row.AssignmentID, assignment) || + if !ok || !sameUUID(row.AssignmentID, assignment) || (value.FeedbackSubmissionID != nil && (row.LatestSubmission == nil || !sameUUID(*value.FeedbackSubmissionID, row.LatestSubmission.SubmissionID))) { return result, &Failure{Code: "invalid_api_response"} diff --git a/cli/internal/command/submission.go b/cli/internal/command/submission.go index 9a5f6e2e5..60e4a5b5b 100644 --- a/cli/internal/command/submission.go +++ b/cli/internal/command/submission.go @@ -55,34 +55,33 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client return err } } - _, err = fmt.Fprintln(stdout, "Initial checks passed. Evaluation is pending. Use workstream task status with this task and assignment to see the outcome.") + _, err = fmt.Fprintf(stdout, "Initial checks passed. Evaluation is pending. Run workstream task status %s to see the outcome.\n", receipt.AssignmentID) return err } task.AddCommand(cmd) } { - var assignment string var page pageFlags - status := &cobra.Command{Use: "status TASK_ID", Short: "Read your assignment status and feedback", Args: cobra.ExactArgs(1)} - status.Flags().StringVar(&assignment, "assignment", "", "Required task-assignment UUID") + status := &cobra.Command{Use: "status ASSIGNMENT_ID", Short: "Read your assignment status and feedback", Args: cobra.ExactArgs(1)} page.bind(status, 25) status.RunE = func(cmd *cobra.Command, args []string) error { - if !api.ValidUUID(assignment) { - return commandError{"invalid_arguments", "--assignment must be a UUID"} + if !api.ValidUUID(args[0]) { + return commandError{"invalid_arguments", "assignment ID must be a UUID"} } transport, err := client() if err != nil { return err } query := page.query(cmd) - result, err := transport.TaskAssignment(cmd.Context(), args[0], assignment, query.Limit, query.Cursor) + result, err := transport.TaskAssignment(cmd.Context(), args[0], query.Limit, query.Cursor) if err != nil || *output == "json" { return jsonOrError(stdout, result.Raw, err) } value := result.Value fields := []contextField{ - {"Assignment", value.Assignment.AssignmentID}, {"Status", value.CurrentStatus}, + {"Assignment", value.Assignment.AssignmentID}, {"Task", value.Assignment.TaskID}, + {"Status", value.CurrentStatus}, {"Reason", optional(value.StatusReason)}, {"Next action", value.NextAction}, {"Terms", value.Assignment.Compensation}, {"Revision", value.Assignment.Revision}, {"Latest submitted attempt", value.Assignment.LatestSubmission}, diff --git a/cli/tests/integration/test_contributor_reads_http.py b/cli/tests/integration/test_contributor_reads_http.py index d53619efe..779decc9c 100644 --- a/cli/tests/integration/test_contributor_reads_http.py +++ b/cli/tests/integration/test_contributor_reads_http.py @@ -127,6 +127,38 @@ def test_own_work_pages_preserve_bodies_and_wire(cli): ) +def test_assignment_status_uses_only_the_assignment_id(cli): + body = { + "assignment": ASSIGNMENT_ROW, + "current_status": "needs_revision", + "status_reason": None, + "next_action": "revise", + "intake": None, + "feedback_submission_id": SUBMISSION, + "post_submission_results": [], + "next_cursor": None, + "accepted_evidence": None, + } + with http_fixture() as (origin, response, requests): + response["body"] = json.dumps(body).encode() + args = ("task", "status", ASSIGNMENT, "--limit", "2", "--cursor", "next", "-o", "json") + result = cli(origin, TOKEN, *args) + assert result.returncode == 0 and json.loads(result.stdout) == body, result.stderr + method, target, authorization = requests[-1] + assert method == "GET" and authorization == "Bearer " + TOKEN + assert urlsplit(target).path == f"/api/v1/actors/me/assignments/{ASSIGNMENT}" + assert parse_qs(urlsplit(target).query) == {"limit": ["2"], "cursor": ["next"]} + text = cli(origin, TOKEN, "task", "status", ASSIGNMENT) + assert text.returncode == 0 and f'Task: "{TASK}"\n' in text.stdout, text.stderr + + response["body"] = json.dumps(body | { + "assignment": ASSIGNMENT_ROW | {"assignment_id": SUBMISSION}, + }).encode() + assert_failure(cli(origin, TOKEN, *args), "invalid_api_response") + assert cli(origin, TOKEN, "task", "status", TASK, "--assignment", ASSIGNMENT).returncode == 2 + assert len(requests) == 3 + + def test_assignment_revision_is_the_work_context_projection(cli): paused = deepcopy(REVISION_CONTEXT) | { "max_revision_rounds": 0, diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py index 6297a3c72..8173ba9db 100644 --- a/cli/tests/integration/test_submission_http.py +++ b/cli/tests/integration/test_submission_http.py @@ -152,6 +152,7 @@ def test_accepted_submission_shows_nonblocking_intake_feedback(cli, tmp_path): assert result.returncode == 0, result.stderr receipt_line = result.stdout.splitlines()[0] assert receipt_line.startswith("Submission accepted for evaluation") + assert f"Run workstream task status {ASSIGNMENT} to see the outcome." in result.stdout assert "pre_submission_results" not in receipt_line assert ( "Intake feedback: coverage_incomplete coverage.files results/vendor.bin: " diff --git a/cli/tests/integration/test_submission_public_api.py b/cli/tests/integration/test_submission_public_api.py index af7df66ce..91210c7d2 100644 --- a/cli/tests/integration/test_submission_public_api.py +++ b/cli/tests/integration/test_submission_public_api.py @@ -397,7 +397,7 @@ async def call(*args, denied=None, token=None): changed = list(submit) changed[changed.index("--feedback") + 1] += " changed" await call(*changed, denied=409) - status_args = ("task", "status", str(f.task), "--assignment", str(f.assignment)) + status_args = ("task", "status", str(f.assignment)) status = await call(*status_args) assert status["current_status"] == "evaluation_pending" assert status["next_action"] == "awaiting_evaluation" diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 3292ec8f6..1114f2e8f 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -704,9 +704,10 @@ cannot be reused as post-submission review-gate evidence. See the | Runtime diagnostics | **Implemented foundation; release configuration prepared** | Closed structured logging, explicit API/Celery tracing, bounded metrics, safe correlation and optional typed OTLP export; hosted composition accepts only an optional HTTPS collector origin and keeps exporter outage outside product correctness | Restrict broker publishers and secure log access, encryption and finite deletion; prove actual-service privacy/correlation. Recorded hosted configuration disables export. If an approved collector is enabled, qualify its access, egress, retention and outage behavior; absence is not an outage pass and optional collector deployment is not a first-journey prerequisite | | Frontend and pilot | **Small hosted backend journey proven; operational release checks remain** | The [incident-summary pilot](../pilots/terminal_systems/mvp/README.md) exercised real source-only setup, separate human-selected PRE/POST approvals, guide activation, task creation and immediate claim, PRE rejection without a Submission, verified S3 intake, POST failure and a genuine corrected v2. Passing POST reached shared FinalAcceptance and one submitter ContributionRecord. Contributor/manager exports agree on exact artifact, assignment and locked policy; unpaid policy creates no awards or fabricated review. The [Garden hosted drill](reports/garden-hosted-drill-2026-11-06.md) separately passed an open-PR current-head check through accepted Submission and one 100 FLOW earned award with no Review. | Ordinary final-data database restore and same-Submission infrastructure retry to acceptance passed. Complete final-head verification; keep broader ART/UNKNOWN interruption and isolation limits explicit. Earlier complex benchmark/model failures remain retained and do not block this small project; their grading quality is not certified. Live human review, paid fulfillment and frontend remain deferred. Garden positive-approval and live POST-negative branches remain separate. [Current drill evidence](reports/terminal-systems-hosted-drill-2026-10-27.md). | -The PR #708 contributor reconciliation adds an exact own-assignment status -and feedback read, preclaim approved project and task guide originals, and the -same minimal ZIP command for initial work and revisions. Backend-selected terms +The PR #708 contributor reconciliation adds current status and feedback by the +contributor's assignment ID, preclaim approved project and task guide originals, +and the same minimal ZIP command for initial work and revisions. The assignment +ID remains stable across intake attempts and submission versions. Backend-selected terms are retained through finalization and can be read before resubmission. Existing contribution evidence shows earned awards. Hosted qualification and the separately reviewed sized-award fields remain outside this exposure claim. diff --git a/experiments/pilot04_external_checker_runtime/public_submission_clients.py b/experiments/pilot04_external_checker_runtime/public_submission_clients.py index c9c55736b..c8116bcd5 100644 --- a/experiments/pilot04_external_checker_runtime/public_submission_clients.py +++ b/experiments/pilot04_external_checker_runtime/public_submission_clients.py @@ -129,8 +129,8 @@ async def submit(self, contributor, token, task, assignment, key, archive, *, cl finally: path.unlink() - async def status(self, contributor, token, task, assignment, expected): - cli = await asyncio.to_thread(self.cli.call, token, "task", "status", task, "--assignment", assignment) - mcp = await self.mcp(contributor, "task_assignment_get", {"task_id": task, "assignment_id": assignment}) + async def status(self, contributor, token, assignment, expected): + cli = await asyncio.to_thread(self.cli.call, token, "task", "status", assignment) + mcp = await self.mcp(contributor, "task_assignment_get", {"assignment_id": assignment}) if cli != expected or mcp != expected: raise AssertionError("CLI or MCP exact assignment status differs from the governed public response") diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 96fecb66f..a212cf74f 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -978,10 +978,10 @@ async def submit_zip(archive, key, *, using, failed=False): and all(item.get("failure_code") is None for item in results if item["source"] == "workstream_default"), "public external PRE rejection did not preserve passing defaults") - status_path = f"/api/v1/tasks/{task_id}/assignments/{assignment_id}" + status_path = f"/api/v1/actors/me/assignments/{assignment_id}" rejected = await _json(client, "GET", status_path, contributor_token, 200) if clients is not None: - await clients.status(contributor, contributor_token, task_id, assignment_id, rejected) + await clients.status(contributor, contributor_token, assignment_id, rejected) _require(rejected["current_status"] == "in_progress" and rejected["assignment"]["latest_submission"] is None and rejected["next_action"] == "submit" @@ -1042,7 +1042,7 @@ async def fail_post_launch(): ) revision = await _json(client, "GET", status_path, contributor_token, 200) if clients is not None: - await clients.status(contributor, contributor_token, task_id, assignment_id, revision) + await clients.status(contributor, contributor_token, assignment_id, revision) _require(revision["current_status"] == "needs_revision" and revision["next_action"] == "revise" and revision["feedback_submission_id"] == first_submission_id @@ -1113,7 +1113,7 @@ async def fail_post_launch(): "public contribution source or award set differs") final_status = await _json(client, "GET", status_path, contributor_token, 200) if clients is not None: - await clients.status(contributor, contributor_token, task_id, assignment_id, final_status) + await clients.status(contributor, contributor_token, assignment_id, final_status) if human_review_required: _require(final_status["current_status"] == "review_pending" and final_status["accepted_evidence"] is None, "the exact assignment changed required human-review custody") diff --git a/mcp_server/README.md b/mcp_server/README.md index 18b73d7b5..3d7e42b3a 100644 --- a/mcp_server/README.md +++ b/mcp_server/README.md @@ -255,9 +255,10 @@ internally. A raw-ZIP `202` means Workstream admitted the attempt for durable evaluation. Both successful and rejected tool responses include applicable contributor-safe -PRE findings. Read `workstream_task_assignment_get` with `task_id` and -`assignment_id` for current status, feedback, revision terms and accepted -evidence. Continue larger feedback sets with the returned cursor. +PRE findings. Use `workstream_task_assignment_get` with the `assignment_id` +to read current status, feedback, revision terms and accepted evidence. The same +ID works through revisions. Continue larger feedback sets with the returned +cursor. Use `workstream_submission_operation_get` with `task_id` and the operation ID or original key to recover the precise request outcome. A write with an uncertain outcome is never retried automatically. Preserve the original task, diff --git a/mcp_server/contracts/task_assignment_get.json b/mcp_server/contracts/task_assignment_get.json index 817dfca63..8401b7a80 100644 --- a/mcp_server/contracts/task_assignment_get.json +++ b/mcp_server/contracts/task_assignment_get.json @@ -1,5 +1,5 @@ { - "canonical_sha256": "520b366d4593eca5073cecba771d8321bd467750c85fe46eb8cbb5477b939a82", + "canonical_sha256": "4eb6fbe4174d135c9e76cf50806677ff944e3f9fafa06eb2f81d6aba73194733", "components": { "schemas": { "AcceptedAssignmentEvidence": { @@ -1325,19 +1325,9 @@ } }, "operation": { - "description": "Read your assignment status, feedback and earned evidence by task and assignment.", - "operationId": "read_my_assignment_api_v1_tasks__task_id__assignments__assignment_id__get", + "description": "Read your assignment status, feedback and earned evidence by assignment ID.", + "operationId": "read_my_assignment_api_v1_actors_me_assignments__assignment_id__get", "parameters": [ - { - "in": "path", - "name": "task_id", - "required": true, - "schema": { - "format": "uuid", - "title": "Task Id", - "type": "string" - } - }, { "in": "path", "name": "assignment_id", @@ -1623,7 +1613,7 @@ ], "summary": "Read My Assignment", "tags": [ - "tasks" + "actors" ], "x-workstream-action-id": "task.assignment.read" }, @@ -1631,7 +1621,7 @@ "source": { "method": "GET", "openapi_version": "3.1.0", - "path": "/api/v1/tasks/{task_id}/assignments/{assignment_id}", - "repository_sha": "c853743b689a46711c13e1d800cdd27ab8230ac2" + "path": "/api/v1/actors/me/assignments/{assignment_id}", + "repository_sha": "21e682a9f878bfda6cde31152ac1122e503a9285" } } diff --git a/mcp_server/tests/test_task_execution.py b/mcp_server/tests/test_task_execution.py index ab502581f..98fe97161 100644 --- a/mcp_server/tests/test_task_execution.py +++ b/mcp_server/tests/test_task_execution.py @@ -44,7 +44,7 @@ def _arguments(name: str) -> dict[str, Any]: "task_release": {"task_id": TASK_ID, "idempotency_key": KEY}, "task_claim": {"task_id": TASK_ID, "idempotency_key": KEY}, "task_work_context_get": {"task_id": TASK_ID}, - "task_assignment_get": {"task_id": TASK_ID, "assignment_id": ASSIGNMENT_ID}, + "task_assignment_get": {"assignment_id": ASSIGNMENT_ID}, "project_contributor_guide_get": {"project_id": PROJECT_ID}, "project_contributor_guide_document_get": { "project_id": PROJECT_ID, "guide_id": PREPARATION_ID, "document_id": DOCUMENT_ID, @@ -212,6 +212,32 @@ async def request(_: WorkstreamGateway, *args: Any, **kwargs: Any) -> GatewayRes assert captured["kwargs"]["idempotency_key"] == arguments.get("idempotency_key") +@pytest.mark.asyncio +async def test_assignment_feedback_uses_one_selector_and_rejects_substitution(monkeypatch): + name = "task_assignment_get" + args = {"assignment_id": ASSIGNMENT_ID, "limit": 2, "cursor": "next"} + validator = Draft202012Validator(TASK_EXECUTION_INPUT_SCHEMAS[name]) + assert validator.is_valid(args) + assert not validator.is_valid(args | {"task_id": TASK_ID}) + assert not validator.is_valid({"task_id": TASK_ID}) + assert not validator.is_valid(args | {"cursor": "x" * 513}) + + async def request(_gateway, method, path, bearer, _validator, _correlation, **kwargs): + assert (method, path, bearer) == ( + "GET", f"/api/v1/actors/me/assignments/{ASSIGNMENT_ID}", "Bearer caller", + ) + assert kwargs["params"] == {"limit": "2", "cursor": "next"} + return GatewayResult(data={ + "assignment": {"assignment_id": SUBMISSION_ID, "task_id": TASK_ID}, + }) + + monkeypatch.setattr(WorkstreamGateway, "_request", request) + async with httpx.AsyncClient(base_url="http://workstream.test") as client: + gateway = WorkstreamGateway(Settings(api_url="http://127.0.0.1:8000"), client) + result = await gateway.task_execution_operation(name, "Bearer caller", args) + assert result.failure is not None and result.failure.error == "invalid_api_response" + + @pytest.mark.asyncio async def test_claim_dispatches_one_atomic_claim_request( monkeypatch: pytest.MonkeyPatch, diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py index 7d977a156..0d66f3979 100644 --- a/mcp_server/workstream_mcp/http_gateway.py +++ b/mcp_server/workstream_mcp/http_gateway.py @@ -391,7 +391,7 @@ "task_release": ("POST", "/api/v1/tasks/{task_id}/release", 200), "task_claim": ("POST", "/api/v1/tasks/{task_id}/claim", 200), "task_work_context_get": ("GET", "/api/v1/tasks/{task_id}/work-context", 200), - "task_assignment_get": ("GET", "/api/v1/tasks/{task_id}/assignments/{assignment_id}", 200), + "task_assignment_get": ("GET", "/api/v1/actors/me/assignments/{assignment_id}", 200), "project_contributor_guide_get": ( "GET", "/api/v1/projects/{project_id}/contributor-guide", 200, ), @@ -1575,18 +1575,16 @@ def _task_execution_response_matches( return isinstance(project_id, str) and cls._same_uuid( data.get("project_id"), project_id, ) - if not isinstance(task_id, str): - return False if name == "task_assignment_get": assignment = data.get("assignment") assignment_id = arguments.get("assignment_id") return ( isinstance(assignment, dict) and isinstance(assignment_id, str) - and cls._fields_match( - assignment, {"task_id": task_id, "assignment_id": assignment_id}, - ) + and cls._same_uuid(assignment.get("assignment_id"), assignment_id) ) + if not isinstance(task_id, str): + return False if project_id is not None and not isinstance(project_id, str): return False if name == "submission_operation_get": diff --git a/mcp_server/workstream_mcp/schemas.py b/mcp_server/workstream_mcp/schemas.py index bd1c1e7c1..cbf47cee8 100644 --- a/mcp_server/workstream_mcp/schemas.py +++ b/mcp_server/workstream_mcp/schemas.py @@ -905,8 +905,12 @@ def _task_transition_input() -> dict[str, Any]: }, "task_assignment_get": { "type": "object", - "properties": {"assignment_id": _UUID_INPUT, **_TASK_PAGE_PROPERTIES}, - "required": ["task_id", "assignment_id"], + "properties": { + "assignment_id": _UUID_INPUT, + "limit": _TASK_PAGE_PROPERTIES["limit"], + "cursor": {**_TASK_PAGE_PROPERTIES["cursor"], "maxLength": 512}, + }, + "required": ["assignment_id"], "additionalProperties": False, }, "project_contributor_guide_get": { diff --git a/mcp_server/workstream_mcp/tools/task_execution.py b/mcp_server/workstream_mcp/tools/task_execution.py index 3e66cca03..58835363a 100644 --- a/mcp_server/workstream_mcp/tools/task_execution.py +++ b/mcp_server/workstream_mcp/tools/task_execution.py @@ -31,7 +31,9 @@ "task_release": "Release one screened task to the contributor queue.", "task_claim": "Claim and start one ready task atomically.", "task_work_context_get": "Read the current contributor work context for one task.", - "task_assignment_get": "Read your exact assignment status, feedback and earned evidence.", + "task_assignment_get": ( + "Read your assignment status, feedback and earned evidence by assignment ID." + ), "project_contributor_guide_get": ( "Read the project's approved guide before claiming a task." ), From a41cfb57e5fe98c7073d9316ffcd70fcae289327 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:10:55 +0100 Subject: [PATCH 402/513] Format contributor assignment CLI proofs --- .../test_contributor_reads_http.py | 32 +++++++++++++++---- cli/tests/integration/test_submission_http.py | 5 ++- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/cli/tests/integration/test_contributor_reads_http.py b/cli/tests/integration/test_contributor_reads_http.py index 779decc9c..9b72cd177 100644 --- a/cli/tests/integration/test_contributor_reads_http.py +++ b/cli/tests/integration/test_contributor_reads_http.py @@ -141,9 +141,21 @@ def test_assignment_status_uses_only_the_assignment_id(cli): } with http_fixture() as (origin, response, requests): response["body"] = json.dumps(body).encode() - args = ("task", "status", ASSIGNMENT, "--limit", "2", "--cursor", "next", "-o", "json") + args = ( + "task", + "status", + ASSIGNMENT, + "--limit", + "2", + "--cursor", + "next", + "-o", + "json", + ) result = cli(origin, TOKEN, *args) - assert result.returncode == 0 and json.loads(result.stdout) == body, result.stderr + assert result.returncode == 0 and json.loads(result.stdout) == body, ( + result.stderr + ) method, target, authorization = requests[-1] assert method == "GET" and authorization == "Bearer " + TOKEN assert urlsplit(target).path == f"/api/v1/actors/me/assignments/{ASSIGNMENT}" @@ -151,11 +163,19 @@ def test_assignment_status_uses_only_the_assignment_id(cli): text = cli(origin, TOKEN, "task", "status", ASSIGNMENT) assert text.returncode == 0 and f'Task: "{TASK}"\n' in text.stdout, text.stderr - response["body"] = json.dumps(body | { - "assignment": ASSIGNMENT_ROW | {"assignment_id": SUBMISSION}, - }).encode() + response["body"] = json.dumps( + body + | { + "assignment": ASSIGNMENT_ROW | {"assignment_id": SUBMISSION}, + } + ).encode() assert_failure(cli(origin, TOKEN, *args), "invalid_api_response") - assert cli(origin, TOKEN, "task", "status", TASK, "--assignment", ASSIGNMENT).returncode == 2 + assert ( + cli( + origin, TOKEN, "task", "status", TASK, "--assignment", ASSIGNMENT + ).returncode + == 2 + ) assert len(requests) == 3 diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py index 8173ba9db..15a8fbb3e 100644 --- a/cli/tests/integration/test_submission_http.py +++ b/cli/tests/integration/test_submission_http.py @@ -152,7 +152,10 @@ def test_accepted_submission_shows_nonblocking_intake_feedback(cli, tmp_path): assert result.returncode == 0, result.stderr receipt_line = result.stdout.splitlines()[0] assert receipt_line.startswith("Submission accepted for evaluation") - assert f"Run workstream task status {ASSIGNMENT} to see the outcome." in result.stdout + assert ( + f"Run workstream task status {ASSIGNMENT} to see the outcome." + in result.stdout + ) assert "pre_submission_results" not in receipt_line assert ( "Intake feedback: coverage_incomplete coverage.files results/vendor.bin: " From e9381afa57f4810b996735ad3e389ef46b45d969 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:13:27 +0100 Subject: [PATCH 403/513] docs(submission): record assignment lookup integration review --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 4735bb9c6..b1be1b171 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11749,3 +11749,16 @@ container was removed, and the existing parser kept its original container identity and start time. All 20 release contract tests passed. Build and runtime receipts are in `/tmp/workstream-parser-bytecode.hUOuQAPF/`. The separate-runner paired submission journey remains pending. + + +### Assignment-only integration review + +Integrated assignment lookup and client commits `21e682a9f`, `71b44b576`, +and formatting `8ab56e9ab` into the PR 708 branch. Independent static review +by the submitter-journey agent found no blocking authorization or caller gaps: +lookup retains actor ownership, project grant, repeatable-read snapshot, signed +cursor binding and assignment/submission foreign-key custody. All three native +status checkpoints use the stable assignment ID. The retired API route and CLI +flag occur only in rejection tests. Built the integrated Go CLI and installed +the assignment-only MCP wheel for the next native run. Connected proof remains +open; this review does not substitute for that run. From bd4bfbf5a5ee246cfea744159bbbabbdef1dba13 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:11:58 +0100 Subject: [PATCH 404/513] feat(submission): send governed POST feedback alerts by assignment --- .../initiatives/WS-SUBMIT-001/OVERVIEW.md | 2 +- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 34 +++ backend/alembic/env.py | 4 +- .../0093_verified_email_observation.py | 25 ++ backend/app/adapters/actors/__init__.py | 10 + backend/app/adapters/auth/__init__.py | 9 + backend/app/adapters/auth/flow.py | 1 + backend/app/adapters/outbox/__init__.py | 185 ++++++++------ .../app/adapters/submission_feedback_email.py | 158 ++++++++++++ backend/app/adapters/tasks/__init__.py | 4 + backend/app/core/config.py | 2 + .../interfaces/submission_feedback_email.py | 39 +++ backend/app/modules/actors/models.py | 6 + backend/app/modules/actors/repository.py | 13 + backend/app/modules/actors/service.py | 14 +- .../app/modules/tasks/api/routing_outcome.py | 2 + .../post_submit_routing/feedback_email.py | 132 ++++++++++ .../tasks/post_submit_routing/outcome.py | 61 +++-- backend/app/schemas/auth.py | 1 + backend/app/workers/celery_app.py | 13 +- backend/app/workers/outbox.py | 37 ++- backend/app/workers/outbox_topology.py | 50 +++- backend/tests/actors/test_issuer_profile.py | 45 ++++ .../post_submit/test_migration.py | 6 +- .../setup_finalization/test_structure.py | 5 +- backend/tests/migration_revision_fixtures.py | 7 + .../tests/outbox/test_delivery_topology.py | 35 ++- .../tests/outbox/test_worker_postgresql.py | 4 +- .../lifecycle/test_participant_control.py | 5 +- .../evaluation_delivery/test_completion.py | 2 +- .../test_feedback_email.py | 241 ++++++++++++++++++ backend/tests/test_alembic.py | 5 +- deploy/hosted/README.md | 33 +++ .../compose.submission-feedback-email.yml | 32 +++ deploy/hosted/compose.yml | 1 + deploy/hosted/preflight.py | 51 +++- deploy/hosted/release.env.example | 5 + deploy/identity/README.md | 12 + deploy/identity/realm_config.py | 3 + docs/roadmap_status.md | 9 + scripts/test_hosted_release_config.py | 33 +++ scripts/test_keycloak_configuration.py | 5 + 42 files changed, 1192 insertions(+), 149 deletions(-) create mode 100644 backend/alembic/versions/0093_verified_email_observation.py create mode 100644 backend/app/adapters/submission_feedback_email.py create mode 100644 backend/app/interfaces/submission_feedback_email.py create mode 100644 backend/app/modules/tasks/post_submit_routing/feedback_email.py create mode 100644 backend/tests/tasks/post_submit_routing/test_feedback_email.py create mode 100644 deploy/hosted/compose.submission-feedback-email.yml diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md index 5bad05637..48bf9e663 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md @@ -44,7 +44,7 @@ work. Existing reward owners remain authoritative. - [ ] Assignment-ID status exposes current safe feedback, processing activity, revision terms and accepted evidence without internal-ID discovery. - [x] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits. - [ ] Combined public contributor journey proves correction, revision, replay, history and applicable existing awards on the integrated code. -- [ ] Quality-feedback email uses the stable assignment ID, with a dedicated consumer and no infrastructure-failure notifications; integrate and prove delivery after sender DNS verification and private key configuration. +- [ ] Quality-feedback email uses the stable assignment ID for POST revision requests and revision-limit rejection, with a dedicated consumer and no infrastructure-failure notifications; qualify delivery after sender DNS verification and private key configuration. The checked items have focused contract and PostgreSQL proof. The guide and assignment status changes are implemented and await the connected native proof. diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b1be1b171..e3191db76 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11762,3 +11762,37 @@ status checkpoints use the stable assignment ID. The retired API route and CLI flag occur only in rejection tests. Built the integrated Go CLI and installed the assignment-only MCP wheel for the next native run. Connected proof remains open; this review does not substitute for that run. + +### Contributor email for governed POST quality feedback + +Intent: alert the contributor when the latest submitted work was returned for +revision or rejected because it exhausted its allowed revisions. The exact +authorized assignment read remains the feedback source for people and agents. +The user confirmed that the notification and public read use the stable +assignment ID throughout one contributor's work. PRE attempts, formal +Submission versions and post-check evidence retain their exact owner IDs. + +Allowed scope: the existing TASK routing outcome and outbox worker composition, +ACTORS issuer metadata and private recipient read, the Flow Identity signed +claim mapper, one forward migration, the typed Resend mail adapter, its worker +configuration and operating documentation, and focused tests. Append the +notification intent to the routing transaction and dispatch it after commit +with the existing outbox recovery rules and an exclusive email worker queue. +Email delivery is disabled by default. Use a stable event-derived Resend key +and a retry lifetime shorter than the provider's idempotency window. The email +identifies the assignment and gives the existing client command without a link. + +Prohibited changes: PRE and human review behavior, product outcomes, awards, +provider credentials in source, public recipient overrides, plaintext mailbox +data in outbox payloads, private check evidence in email, new frontend work, +and sends to existing contributors during qualification. Require an active +exact-project contributor with issuer-signed verified mailbox evidence and +recheck the exact assignment, attempt and current work state before dispatch. +Coverage gaps and infrastructure/provider failures are outside the email scope. + +Risk is security-sensitive and crosses an external delivery boundary. Verify +rollback, replay and retry, stale or foreign source and recipient refusal, +transport status mapping, bounded delivery, and queue isolation. Focused +security, architecture, QA and operating documentation review are required. +Human review focuses on verified recipient evidence, email wording and the +configured authenticated feedback destination before activation. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index a6b8a8620..37a0f9554 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -21,7 +21,7 @@ target_metadata = Base.metadata _BASELINE_REVISION = "0001_uuid7_v01" -_CURRENT_HEAD_REVISION = "0092_submission_feedback" +_CURRENT_HEAD_REVISION = "0093_verified_email_observation" _RECREATE_GUIDANCE = ( "Workstream v0.1 requires a fresh database; recreate this database before " "running the 0001_uuid7_v01 migration" @@ -146,6 +146,8 @@ def do_run_migrations(connection: Connection) -> None: ("0089_observed_upload_cleanup",), ("0069_remove_artifact_proof",), ("0090_merge_direct_storage",), + ("0091_qualified_aws_source",), + ("0092_submission_feedback",), (_CURRENT_HEAD_REVISION,), ): raise RuntimeError(_RECREATE_GUIDANCE) diff --git a/backend/alembic/versions/0093_verified_email_observation.py b/backend/alembic/versions/0093_verified_email_observation.py new file mode 100644 index 000000000..811cd239a --- /dev/null +++ b/backend/alembic/versions/0093_verified_email_observation.py @@ -0,0 +1,25 @@ +"""Require a fresh signed mailbox verification observation for email delivery.""" + +from alembic import op +import sqlalchemy as sa + +revision = "0093_verified_email_observation" +down_revision = "0092_submission_feedback" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Treat all historical signed mailbox addresses as unverified.""" + op.add_column("actor_identity_links", sa.Column( + "email_verified", sa.Boolean(), nullable=False, server_default=sa.false(), + )) + op.create_check_constraint( + "ck_actor_identity_links_email_verified_observation", "actor_identity_links", + "not email_verified or (subject_kind = 'human' and email_observed_issued_at is not null)", + ) + + +def downgrade() -> None: + """Refuse removal of retained mailbox-verification custody.""" + raise RuntimeError("Workstream v0.1 migrations cannot be downgraded; recreate the database") diff --git a/backend/app/adapters/actors/__init__.py b/backend/app/adapters/actors/__init__.py index 76988e4c5..4bb742d3b 100644 --- a/backend/app/adapters/actors/__init__.py +++ b/backend/app/adapters/actors/__init__.py @@ -1,11 +1,21 @@ """ACTORS-owned composition for narrowly selected contribution display labels.""" +from uuid import UUID + from sqlalchemy.ext.asyncio import AsyncSession from app.modules.actors.api.contribution_labels import ContributionActorLabelPort from app.modules.actors.contribution_labels import ContributionActorLabelRepository +from app.modules.actors.repository import ActorRepository def contribution_actor_label_port(session: AsyncSession) -> ContributionActorLabelPort: """Read selected labels on the export's authorized caller-owned snapshot.""" return ContributionActorLabelRepository(session) + + +async def verified_notification_email( + session: AsyncSession, actor_id: UUID, issuer: str, +) -> str | None: + """Expose private issuer-observed email only to the notification composition.""" + return await ActorRepository(session).verified_notification_email(actor_id, issuer) diff --git a/backend/app/adapters/auth/__init__.py b/backend/app/adapters/auth/__init__.py index 6ebbc00a9..627ae86f5 100644 --- a/backend/app/adapters/auth/__init__.py +++ b/backend/app/adapters/auth/__init__.py @@ -65,6 +65,15 @@ from app.modules.tasks.api.routing_outcome import RoutingAuthorityFacts +async def has_submission_feedback_recipient_grant( + session: AsyncSession, project_id: UUID, actor_id: UUID, +) -> bool: + """Require the same exact active Submitter grant as the assignment feedback read.""" + return await AdminAuthorizationRepository(session).find_active_project_role( + project_id=project_id, actor_profile_id=actor_id, role="submitter", + ) is not None + + def artifact_operator_read_authorization( session: AsyncSession, context: AuthorizationContext, ) -> ArtifactOperatorReadAuthorization: diff --git a/backend/app/adapters/auth/flow.py b/backend/app/adapters/auth/flow.py index 90e2100e1..952b8d821 100644 --- a/backend/app/adapters/auth/flow.py +++ b/backend/app/adapters/auth/flow.py @@ -452,6 +452,7 @@ def _result_from_verified_claims( subject_kind=subject_kind, scopes=scopes, email=claims.get("email"), + email_verified=claims.get("email_verified") is True and claims.get("email") is not None, name=claims.get("name"), ) return AuthVerificationResult(token=verified) diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py index 5e682d021..ed7616c43 100644 --- a/backend/app/adapters/outbox/__init__.py +++ b/backend/app/adapters/outbox/__init__.py @@ -1,6 +1,7 @@ """Explicit composition of the shared delivery owner; feature registration is separate.""" from collections.abc import Callable, Mapping +from typing import Literal from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker from app.modules.authorization.api.outbox_dispatch import OutboxDispatchAuthorizationPort @@ -45,7 +46,9 @@ def outbox_delivery( ) -def production_outbox_delivery(session_factory, *, finalization_worker: bool | None = None): +def production_outbox_delivery( + session_factory, *, worker_group: Literal["post", "finalization", "feedback"] | None = None, +): """Compose all handlers for discovery, or one explicit worker group for delivery.""" from app.adapters.artifacts import worker_post_submission_materialization from app.adapters.artifacts import ( @@ -81,104 +84,120 @@ def production_outbox_delivery(session_factory, *, finalization_worker: bool | N from app.modules.tasks.api.revision_expiry import ( REVISION_EXPIRY_EVENT, REVISION_EXPIRED_EVENT, REVISION_CONTEXT_BLOCKED_EVENT, ) + from app.adapters.submission_feedback_email import submission_feedback_email_handler + from app.core.config import get_settings + from app.modules.tasks.api.routing_outcome import SUBMISSION_FEEDBACK_EMAIL_EVENT finalization_options = DeliveryOptions(lease_seconds=SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS) - registry = HandlerRegistry( - [ - ( - "SubmissionFinalizationRequested", - 1, - worker_submission_finalization_handler( - sessions=session_factory, delivery_options=finalization_options, - ), + feedback_options = DeliveryOptions(lease_seconds=60, handler_timeout_seconds=20, + retry_base_seconds=60) + feedback_key = (SUBMISSION_FEEDBACK_EMAIL_EVENT, 1) + settings = get_settings() + entries = [ + ( + "SubmissionFinalizationRequested", + 1, + worker_submission_finalization_handler( + sessions=session_factory, delivery_options=finalization_options, ), - ( - FINALIZATION_RECOVERY_EVENT, - 1, - worker_submission_finalization_recovery_handler( - sessions=session_factory, delivery_options=finalization_options, - ), + ), + ( + FINALIZATION_RECOVERY_EVENT, + 1, + worker_submission_finalization_recovery_handler( + sessions=session_factory, delivery_options=finalization_options, ), - ( - ASSIGNMENT_INVALIDATION_EVENT, - 1, - TransactionalAssignmentInvalidationHandler( - session_factory, - observer=CommittedInvocationReader(session_factory), - authorization_factory=assignment_invalidation_authorization, - ), + ), + ( + ASSIGNMENT_INVALIDATION_EVENT, + 1, + TransactionalAssignmentInvalidationHandler( + session_factory, + observer=CommittedInvocationReader(session_factory), + authorization_factory=assignment_invalidation_authorization, ), - ( - REVISION_EXPIRY_EVENT, - 1, - TransactionalTaskRevisionExpiryHandler( - session_factory, - observer=CommittedInvocationReader(session_factory), - authorization_factory=revision_expiry_authorization, - ), + ), + ( + REVISION_EXPIRY_EVENT, + 1, + TransactionalTaskRevisionExpiryHandler( + session_factory, + observer=CommittedInvocationReader(session_factory), + authorization_factory=revision_expiry_authorization, ), - ( - REVISION_EXPIRED_EVENT, - 1, - TransactionalTaskRevisionExpiredNoticeHandler( - session_factory, - observer=CommittedInvocationReader(session_factory), - ), + ), + ( + REVISION_EXPIRED_EVENT, + 1, + TransactionalTaskRevisionExpiredNoticeHandler( + session_factory, + observer=CommittedInvocationReader(session_factory), ), - ( - REVISION_CONTEXT_BLOCKED_EVENT, - 1, - TransactionalTaskRevisionBlockedNoticeHandler( - session_factory, - observer=CommittedInvocationReader(session_factory), - ), + ), + ( + REVISION_CONTEXT_BLOCKED_EVENT, + 1, + TransactionalTaskRevisionBlockedNoticeHandler( + session_factory, + observer=CommittedInvocationReader(session_factory), ), - ( - REVISION_EXHAUSTED_EVENT, - 1, - TransactionalTaskRevisionExhaustedNoticeHandler( - session_factory, - observer=CommittedInvocationReader(session_factory), - ), + ), + ( + REVISION_EXHAUSTED_EVENT, + 1, + TransactionalTaskRevisionExhaustedNoticeHandler( + session_factory, + observer=CommittedInvocationReader(session_factory), ), - ( - REQUEST_EVENT, - 1, - evaluation_request_handler( - sessions=session_factory, - materialization=worker_post_submission_materialization( - sessions=session_factory - ), + ), + ( + REQUEST_EVENT, + 1, + evaluation_request_handler( + sessions=session_factory, + materialization=worker_post_submission_materialization( + sessions=session_factory ), ), - ( - COMPLETION_EVENT, - 1, - evaluation_completion_handler(sessions=session_factory), - ), - ( - RECONCILIATION_EVENT, - 1, - post_submit_delivery_reconciliation_handler( - sessions=session_factory, - materialization=worker_post_submission_materialization( - sessions=session_factory - ), + ), + ( + COMPLETION_EVENT, + 1, + evaluation_completion_handler(sessions=session_factory), + ), + ( + RECONCILIATION_EVENT, + 1, + post_submit_delivery_reconciliation_handler( + sessions=session_factory, + materialization=worker_post_submission_materialization( + sessions=session_factory ), ), - ], - replay_safe=frozenset({("SubmissionFinalizationRequested", 1), (FINALIZATION_RECOVERY_EVENT, 1), (REVISION_EXPIRY_EVENT, 1), (REVISION_EXPIRED_EVENT, 1), (REVISION_CONTEXT_BLOCKED_EVENT, 1), (REVISION_EXHAUSTED_EVENT, 1)}), - ) - if finalization_worker is not None: - keys = tuple(key for key in registry.keys - if (key[0] in {"SubmissionFinalizationRequested", FINALIZATION_RECOVERY_EVENT}) == finalization_worker) - registry = HandlerRegistry( - [(kind, version, registry.get(kind, version)) for kind, version in keys], - replay_safe=frozenset(key for key in keys if registry.can_retry_unknown(*key)), - ) + ), + ] + if settings.submission_feedback_email_enabled: + entries.append((*feedback_key, submission_feedback_email_handler( + session_factory, observer=CommittedInvocationReader(session_factory), settings=settings, + ))) + finalization_keys = frozenset({("SubmissionFinalizationRequested", 1), (FINALIZATION_RECOVERY_EVENT, 1)}) + replay_safe = finalization_keys | { + (REVISION_EXPIRY_EVENT, 1), (REVISION_EXPIRED_EVENT, 1), (REVISION_CONTEXT_BLOCKED_EVENT, 1), + (REVISION_EXHAUSTED_EVENT, 1), feedback_key, + } + groups = { + "finalization": finalization_keys, "feedback": {feedback_key}, + "post": {(kind, version) for kind, version, _handler in entries} - finalization_keys - {feedback_key}, + } + if worker_group is not None: + entries = [entry for entry in entries if entry[:2] in groups[worker_group]] + registry = HandlerRegistry(entries, replay_safe=frozenset( + (kind, version) for kind, version, _handler in entries if (kind, version) in replay_safe + )) event_options = { ("SubmissionFinalizationRequested", 1): finalization_options, (FINALIZATION_RECOVERY_EVENT, 1): finalization_options, + feedback_key: feedback_options, (REQUEST_EVENT, 1): DeliveryOptions( lease_seconds=SELECTED_POST_DELIVERY_LEASE_SECONDS, handler_timeout_seconds=SELECTED_POST_HANDLER_TIMEOUT_SECONDS, diff --git a/backend/app/adapters/submission_feedback_email.py b/backend/app/adapters/submission_feedback_email.py new file mode 100644 index 000000000..12b1e410e --- /dev/null +++ b/backend/app/adapters/submission_feedback_email.py @@ -0,0 +1,158 @@ +"""Explicit Resend composition and bounded email transport (ADR 0014).""" + +import asyncio +import json +import os +from pathlib import Path +import re +import stat +from uuid import UUID + +import httpx +from workstream_external_services import ( + ExternalServiceAdapterFactory, ExternalServiceAdapterIdentity, + ExternalServiceConfigurationError, ExternalServiceProtocolError, + ExternalServiceUnavailableError, +) + +from app.core.config import Settings +from app.interfaces.submission_feedback_email import ( + RESEND_PROVIDER, SUBMISSION_FEEDBACK_EMAIL_CAPABILITY, + SubmissionFeedbackEmail, SubmissionFeedbackEmailAdapter, is_single_mailbox, +) +from app.modules.outbox.api import HandlerOutcome + +_IDENTITY = ExternalServiceAdapterIdentity(SUBMISSION_FEEDBACK_EMAIL_CAPABILITY, RESEND_PROVIDER) +_KEY = re.compile(rb"re_[A-Za-z0-9_-]{1,256}") +_MAX_RESPONSE_BYTES = 4096 +_TIMEOUT_SECONDS = 10 +_SENDER = "Workstream " +_ENDPOINT = "https://api.resend.com/emails" + + +def _read_key(path: Path | None) -> str | None: + """Read only a bounded regular private file owned by the worker identity.""" + if path is None or not path.is_absolute(): + return None + try: + descriptor = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NONBLOCK | os.O_NOFOLLOW) + try: + metadata = os.fstat(descriptor) + if (not stat.S_ISREG(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o400 + or metadata.st_uid != os.geteuid() or metadata.st_nlink != 1 + or not 4 <= metadata.st_size < 512): + return None + key = os.read(descriptor, 512).rstrip(b"\r\n") + finally: + os.close(descriptor) + return key.decode("ascii") if _KEY.fullmatch(key) is not None else None + except OSError: + return None + + +class ResendSubmissionFeedbackEmailAdapter: + """Send one plaintext message to one mailbox using Resend's idempotency key.""" + + identity = _IDENTITY + + def __init__(self, key: str, transport: httpx.AsyncBaseTransport | None): + """Keep the private key confined to this provider adapter.""" + self._key, self._transport = key, transport + + async def send(self, message: SubmissionFeedbackEmail) -> None: + """Map only safe outcomes, keeping response content out of errors and logs.""" + if not is_single_mailbox(message.recipient): + raise ExternalServiceProtocolError(self.identity) + try: + async with asyncio.timeout(_TIMEOUT_SECONDS), httpx.AsyncClient( + transport=self._transport, timeout=_TIMEOUT_SECONDS, + trust_env=False, follow_redirects=False, + ) as client, client.stream( + "POST", _ENDPOINT, + headers={ + "Authorization": f"Bearer {self._key}", + "Idempotency-Key": f"workstream-submission-feedback/{message.event_id}", + "Accept-Encoding": "identity", + }, + json={"from": _SENDER, "to": [message.recipient], + "subject": message.subject, "text": message.text}, + ) as response: + await _require_acceptance(response) + except (httpx.TransportError, TimeoutError): + raise ExternalServiceUnavailableError(self.identity) from None + + +async def _require_acceptance(response: httpx.Response) -> None: + """Classify response status and inspect only bounded success or conflict data.""" + status = response.status_code + if status in {408, 429} or status >= 500: + raise ExternalServiceUnavailableError(_IDENTITY) + if not (response.is_success or status == 409): + raise ExternalServiceProtocolError(_IDENTITY) + raw = bytearray() + async for chunk in response.aiter_raw(chunk_size=1024): + raw.extend(chunk) + if len(raw) > _MAX_RESPONSE_BYTES: + raise ExternalServiceProtocolError(_IDENTITY) + body = None + try: + body = json.loads(raw) + if response.is_success and type(body) is dict and type(body.get("id")) is str: + if str(UUID(body["id"])) == body["id"]: + return + except (TypeError, ValueError, RecursionError): + pass + if status == 409 and type(body) is dict and body.get("name") == "concurrent_idempotent_requests": + raise ExternalServiceUnavailableError(_IDENTITY) + raise ExternalServiceProtocolError(_IDENTITY) + + +def submission_feedback_email_factory( + settings: Settings, *, transport: httpx.AsyncBaseTransport | None = None, +) -> ExternalServiceAdapterFactory[SubmissionFeedbackEmailAdapter]: + """Register the one operational sender and keep key loading on its worker.""" + factory = ExternalServiceAdapterFactory[SubmissionFeedbackEmailAdapter]( + SUBMISSION_FEEDBACK_EMAIL_CAPABILITY, + ) + + def build() -> SubmissionFeedbackEmailAdapter: + key = _read_key(settings.resend_api_key_file) + if key is None: + raise ExternalServiceConfigurationError(_IDENTITY) + return ResendSubmissionFeedbackEmailAdapter(key, transport) + + factory.register(RESEND_PROVIDER, build) + return factory + + +def validate_submission_feedback_email_worker(settings: Settings) -> None: + """Require an explicitly enabled verified issuer and readable sending key at startup.""" + if (not settings.submission_feedback_email_enabled or settings.auth_provider != "flow" + or settings.flow_auth_local_hmac_secret is not None or settings.token_issuer is None): + raise ExternalServiceConfigurationError(_IDENTITY) + submission_feedback_email_factory(settings).create(RESEND_PROVIDER) + + +def submission_feedback_email_handler(sessions, *, observer, settings: Settings): + """Register without loading a key on the worker that discovers pending events.""" + from app.adapters.actors import verified_notification_email + from app.adapters.auth import has_submission_feedback_recipient_grant + from app.modules.tasks.post_submit_routing.feedback_email import TaskSubmissionFeedbackEmailHandler + + issuer = settings.token_issuer + + async def recipient(session, project_id, actor_id): + if issuer is None or not await has_submission_feedback_recipient_grant(session, project_id, actor_id): + return None + return await verified_notification_email(session, actor_id, issuer) + + async def handle(envelope): + try: + adapter = submission_feedback_email_factory(settings).create(RESEND_PROVIDER) + except ExternalServiceConfigurationError: + return HandlerOutcome.REJECT + return await TaskSubmissionFeedbackEmailHandler( + sessions, observer=observer, recipient=recipient, adapter=adapter, + )(envelope) + + return handle diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py index 1ec716f32..2fc88fcb6 100644 --- a/backend/app/adapters/tasks/__init__.py +++ b/backend/app/adapters/tasks/__init__.py @@ -490,6 +490,7 @@ def task_post_submit_outcome(session, sessions): from app.adapters.auth import task_routing_authorization from app.adapters.checkers import evaluation_coordinator from app.adapters.projects import project_locked_policy_context_port + from app.core.config import get_settings from app.modules.tasks.post_submit_routing.outcome import TaskPostSubmitOutcome return TaskPostSubmitOutcome( @@ -502,6 +503,7 @@ def task_post_submit_outcome(session, sessions): invocation_fence=outbox_invocation_fence(session), audit=task_routing_audit(session), outbox=outbox_append(session), + feedback_email_enabled=get_settings().submission_feedback_email_enabled, ) @@ -521,6 +523,7 @@ def reconciliation_task_post_submit_outcome( from app.adapters.checkers import evaluation_coordinator from app.adapters.outbox import outbox_append from app.adapters.projects import project_locked_policy_context_port + from app.core.config import get_settings from app.adapters.tasks.routing_acceptance import RoutingAcceptanceAdapter from app.modules.tasks.post_submit_routing.outcome import TaskPostSubmitOutcome @@ -535,6 +538,7 @@ def reconciliation_task_post_submit_outcome( audit=task_routing_audit(session), outbox=outbox_append(session), reconciliation_claim=reconciliation_claim, + feedback_email_enabled=get_settings().submission_feedback_email_enabled, )) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index f33d848e6..b8e9483f1 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -92,6 +92,8 @@ class Settings(BaseSettings): flow_auth_audience: str = "workstream-api" flow_auth_local_hmac_secret: str | None = None token_issuer: str | None = None + submission_feedback_email_enabled: bool = False + resend_api_key_file: Path | None = None token_audience: str = "workstream" token_jwks_url: str | None = None token_algorithms: str = "" diff --git a/backend/app/interfaces/submission_feedback_email.py b/backend/app/interfaces/submission_feedback_email.py new file mode 100644 index 000000000..a90193a00 --- /dev/null +++ b/backend/app/interfaces/submission_feedback_email.py @@ -0,0 +1,39 @@ +"""Transactional contributor email capability for governed POST feedback.""" + +from dataclasses import dataclass, field +import re +from typing import Protocol +from uuid import UUID + +from workstream_external_services import ExternalServiceAdapter + +SUBMISSION_FEEDBACK_EMAIL_CAPABILITY = "submission_feedback_email" +RESEND_PROVIDER = "resend" +_LOCAL_PART = re.compile(r"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*") +_DNS_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?") + + +def is_single_mailbox(value: str) -> bool: + """Accept a single unadorned ASCII mailbox with no list or header syntax.""" + local, separator, domain = value.partition("@") + labels = domain.split(".") + return (len(value) <= 254 and len(local) <= 64 and bool(separator) + and _LOCAL_PART.fullmatch(local) is not None and len(labels) >= 2 + and all(_DNS_LABEL.fullmatch(label) is not None for label in labels)) + + +@dataclass(frozen=True, slots=True) +class SubmissionFeedbackEmail: + """One exact event, verified recipient and bounded message.""" + + event_id: UUID + recipient: str = field(repr=False) + subject: str + text: str = field(repr=False) + + +class SubmissionFeedbackEmailAdapter(ExternalServiceAdapter, Protocol): + """Send one email with provider idempotency supplied by its event ID.""" + + async def send(self, message: SubmissionFeedbackEmail) -> None: + """Return only after the provider acknowledges the send request.""" diff --git a/backend/app/modules/actors/models.py b/backend/app/modules/actors/models.py index 59988d1c0..6cea82548 100644 --- a/backend/app/modules/actors/models.py +++ b/backend/app/modules/actors/models.py @@ -15,6 +15,7 @@ JSON, String, UniqueConstraint, + text, ) from sqlalchemy.orm import Mapped, mapped_column, relationship from sqlalchemy.sql import func @@ -146,6 +147,10 @@ class ActorIdentityLink(Base): "subject_kind = 'service' or last_verified_at is not null", name="human_verified", ), + CheckConstraint( + "not email_verified or (subject_kind = 'human' and email_observed_issued_at is not null)", + name="email_verified_observation", + ), CheckConstraint( "(reactivated_by is null and reactivated_at is null and reactivation_reason is null) or " "(reactivated_by is not null and reactivated_at is not null and reactivation_reason is not null)", @@ -182,6 +187,7 @@ class ActorIdentityLink(Base): linked_by: Mapped[str] = mapped_column(String(120), nullable=False) linked_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) email_observed_issued_at: Mapped[int | None] = mapped_column(BigInteger) + email_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false")) last_verified_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) revoked_by: Mapped[str | None] = mapped_column(String(120)) revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/backend/app/modules/actors/repository.py b/backend/app/modules/actors/repository.py index 76066f5af..f2b98626e 100644 --- a/backend/app/modules/actors/repository.py +++ b/backend/app/modules/actors/repository.py @@ -21,6 +21,19 @@ class ActorRepository: def __init__(self, session: AsyncSession) -> None: self._session = session + async def verified_notification_email(self, actor_id: UUID, issuer: str) -> str | None: + """Read the active human's exact issuer-observed, verified mailbox.""" + return await self._session.scalar( + select(ActorProfile.contact_email).join( + ActorIdentityLink, ActorIdentityLink.actor_profile_id == ActorProfile.id, + ).where( + ActorProfile.id == str(actor_id), ActorProfile.actor_kind == "human", + ActorProfile.status == "active", ActorIdentityLink.subject_kind == "human", + ActorIdentityLink.status == "active", ActorIdentityLink.issuer == issuer, + ActorIdentityLink.email_verified.is_(True), + ) + ) + async def lock_external_identity(self, issuer: str, subject: str) -> None: """Serialize first access for one exact external identity.""" key = self._advisory_key(issuer, subject) diff --git a/backend/app/modules/actors/service.py b/backend/app/modules/actors/service.py index 7917a2ae4..84993de15 100644 --- a/backend/app/modules/actors/service.py +++ b/backend/app/modules/actors/service.py @@ -180,6 +180,7 @@ async def resolve_verified_actor( status="active", linked_by=profile_id, email_observed_issued_at=token.issued_at if token.email is not None else None, + email_verified=token.email is not None and token.email_verified, last_verified_at=func.clock_timestamp(), ) await self._repo.add_actor_profile(profile) @@ -294,13 +295,20 @@ async def synchronize_identity_email( self._require_active_human(profile) if token.issuer != link.issuer or token.subject != link.subject: raise RuntimeError("verified identity does not match resolved actor") - if token.email is not None and ( + if (token.email is not None or link.email_verified) and ( link.email_observed_issued_at is None or token.issued_at > link.email_observed_issued_at ): - profile.contact_email = token.email + if token.email is not None: + profile.contact_email = token.email + link.email_verified = token.email is not None and token.email_verified link.email_observed_issued_at = token.issued_at - await self._session.flush() + elif (link.email_verified and token.issued_at == link.email_observed_issued_at + and (not token.email_verified or token.email != profile.contact_email)): + link.email_verified = False + else: + return resolved + await self._session.flush() return resolved async def touch_after_authorization(self, resolved: ResolvedActor) -> ResolvedActor: diff --git a/backend/app/modules/tasks/api/routing_outcome.py b/backend/app/modules/tasks/api/routing_outcome.py index fc6406b7c..d4c74604b 100644 --- a/backend/app/modules/tasks/api/routing_outcome.py +++ b/backend/app/modules/tasks/api/routing_outcome.py @@ -4,6 +4,8 @@ from uuid import UUID from pydantic import BaseModel, ConfigDict, model_validator +SUBMISSION_FEEDBACK_EMAIL_EVENT = "SubmissionFeedbackEmailRequested" + class TaskRoutingLifecycleDeferred(RuntimeError): """Known pre-effect REV enablement refusal; the caller may retry after rollback.""" diff --git a/backend/app/modules/tasks/post_submit_routing/feedback_email.py b/backend/app/modules/tasks/post_submit_routing/feedback_email.py new file mode 100644 index 000000000..67a83782b --- /dev/null +++ b/backend/app/modules/tasks/post_submit_routing/feedback_email.py @@ -0,0 +1,132 @@ +"""Send one private alert for current, committed contributor quality feedback.""" + +from collections.abc import Awaitable, Callable +from datetime import timedelta +import json +from uuid import UUID + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker +from workstream_external_services import ExternalServiceAdapterError + +from app.interfaces.submission_feedback_email import ( + SubmissionFeedbackEmail, SubmissionFeedbackEmailAdapter, is_single_mailbox, +) +from app.modules.outbox.api import CommittedInvocationPort, HandlerOutcome, OutboxEventEnvelope +from app.modules.tasks.models import Submission, WorkstreamTask +from app.modules.tasks.post_submit_routing.models import TaskPostSubmitRoutingManifest +from app.modules.tasks.post_submit_routing.outcome import ( + FeedbackOutcome, routing_outcome_complete, submission_feedback_email_event, +) +from app.modules.tasks.revision.service import read_task_revision + +SUBMISSION_FEEDBACK_EMAIL_LIFETIME = timedelta(hours=12) + + +class TaskSubmissionFeedbackEmailHandler: + """Read an independently committed source before allowing any external effect.""" + + def __init__( + self, sessions: async_sessionmaker[AsyncSession], *, observer: CommittedInvocationPort, + recipient: Callable[[AsyncSession, UUID, UUID], Awaitable[str | None]], + adapter: SubmissionFeedbackEmailAdapter, + ) -> None: + """Receive scoped recipient lookup and the typed transport from composition.""" + self._sessions, self._observer, self._recipient = sessions, observer, recipient + self._adapter = adapter + + async def __call__(self, envelope: OutboxEventEnvelope) -> HandlerOutcome: + """Stop at expiry and prevent foreign or obsolete effects before the HTTP call.""" + try: + payload = json.loads(envelope.payload_json) + manifest_id = UUID(payload["routing_manifest_id"]) + outcome = payload["outcome"] + except (TypeError, ValueError, KeyError): + return HandlerOutcome.REJECT + if outcome not in ("needs_revision", "rejected"): + return HandlerOutcome.REJECT + observed = await self._observer.observe_invocation(envelope) + if (observed is None or not envelope.occurred_at <= observed.observed_at + < envelope.occurred_at + SUBMISSION_FEEDBACK_EMAIL_LIFETIME): + return HandlerOutcome.REJECT + async with self._sessions() as session: + await session.connection(execution_options={"isolation_level": "REPEATABLE READ"}) + manifest = await session.get(TaskPostSubmitRoutingManifest, manifest_id) + if manifest is None or not _matches(envelope, payload, manifest, outcome): + return HandlerOutcome.REJECT + if not await _current_outcome(session, manifest, outcome): + return HandlerOutcome.ACKNOWLEDGE + recipient = await self._recipient(session, UUID(manifest.project_id), UUID(manifest.contributor_id)) + if recipient is None or not is_single_mailbox(recipient): + return HandlerOutcome.ACKNOWLEDGE + message = _message(envelope.claim.event_id, manifest, outcome, recipient) + try: + await self._adapter.send(message) + except ExternalServiceAdapterError as error: + return HandlerOutcome.RETRY if error.retryable else HandlerOutcome.REJECT + return HandlerOutcome.ACKNOWLEDGE + + +def _matches( + envelope: OutboxEventEnvelope, payload: dict, manifest: TaskPostSubmitRoutingManifest, + outcome: FeedbackOutcome, +) -> bool: + expected = submission_feedback_email_event(manifest, outcome) + return (envelope.event_type == expected.event_type + and envelope.event_version == expected.event_version + and envelope.aggregate_type == expected.aggregate_type + and envelope.aggregate_id == expected.aggregate_id + and envelope.claim.project_id == expected.project_id + and envelope.correlation_id == expected.correlation_id + and envelope.causation_event_id == expected.causation_event_id + and envelope.idempotency_key == expected.idempotency_key + and payload == expected.payload) + + +async def _current_outcome( + session: AsyncSession, manifest: TaskPostSubmitRoutingManifest, outcome: FeedbackOutcome, +) -> bool: + """Reuse TASK's exact outcome closure and current revision projection.""" + if manifest.routing_recommendation != "needs_revision": + return False + latest = (await session.execute(select( + Submission.id, Submission.attempt_status, Submission.status_reason, + ).where( + Submission.task_assignment_id == manifest.assignment_id, + ).order_by(Submission.version.desc()).limit(1))).one_or_none() + expected_reason = "revision_limit_reached" if outcome == "rejected" else None + if (latest is None or latest.id != manifest.submission_id + or latest.attempt_status != outcome or latest.status_reason != expected_reason): + return False + if not await routing_outcome_complete(session, manifest.id): + return False + if outcome == "rejected": + return True + task = (await session.execute(select( + WorkstreamTask.status, WorkstreamTask.assigned_to, WorkstreamTask.active_submission_operation_id, + ).where(WorkstreamTask.id == manifest.task_id))).one_or_none() + if (task is None or task.assigned_to != manifest.contributor_id + or task.active_submission_operation_id is not None): + return False + revision = await read_task_revision( + session, task_id=manifest.task_id, status=task.status, assignment_id=manifest.assignment_id, + ) + return revision is not None and revision.disposition in {"ready", "context_blocked"} + + +def _message( + event_id: UUID, manifest: TaskPostSubmitRoutingManifest, outcome: FeedbackOutcome, recipient: str, +) -> SubmissionFeedbackEmail: + if outcome == "needs_revision": + subject = "Action required: Workstream submission feedback available" + status = (f"Workstream assignment {manifest.assignment_id} needs revision. " + "Review the feedback, fix your submission and resubmit when the assignment allows it.") + else: + subject = "Workstream assignment reached its revision limit" + status = (f"Workstream assignment {manifest.assignment_id} reached its revision limit. " + "Its submission was rejected.") + hint = f"workstream task status {manifest.assignment_id}" + return SubmissionFeedbackEmail(event_id, recipient, subject, ( + f"{status}\n\nRead your assignment feedback in Workstream using the API, CLI or MCP.\n\n" + f"CLI: {hint}\n" + )) diff --git a/backend/app/modules/tasks/post_submit_routing/outcome.py b/backend/app/modules/tasks/post_submit_routing/outcome.py index f8c6b3d95..4249ab9d4 100644 --- a/backend/app/modules/tasks/post_submit_routing/outcome.py +++ b/backend/app/modules/tasks/post_submit_routing/outcome.py @@ -3,9 +3,11 @@ import json from collections.abc import Awaitable, Callable from contextlib import AsyncExitStack +from typing import Literal from uuid import UUID from sqlalchemy import select, text +from sqlalchemy.ext.asyncio import AsyncSession from app.core.identifiers import new_record_id from app.modules.checkers.api.execution import COMPLETION_EVENT, EvaluationCompletion @@ -18,7 +20,9 @@ from app.modules.tasks.revision.models import TaskRevisionPreparation from app.modules.tasks.revision.exhaustion import exhaust_assignment from app.modules.tasks.post_submit_routing.models import TaskPostSubmitRoutingManifest -from app.modules.tasks.api.routing_outcome import RoutingAuthorityFacts, TaskRoutingOutcome +from app.modules.tasks.api.routing_outcome import ( + SUBMISSION_FEEDBACK_EMAIL_EVENT, RoutingAuthorityFacts, TaskRoutingOutcome, +) from app.modules.tasks.post_submit_routing.requests import ( TaskRoutingRequestUnavailable, require_routing_transaction, @@ -26,6 +30,15 @@ from app.modules.tasks.post_submit_routing.source import TaskRoutingSourcePreparer OUTCOME_EVENT = "TaskPostSubmitRouted" +FeedbackOutcome = Literal["needs_revision", "rejected"] + + +async def routing_outcome_complete(session: AsyncSession, manifest_id: UUID) -> bool: + """Delegate complete retained effect closure to TASK's database owner.""" + return await session.scalar(text( + "SELECT public.task_routing_outcome_complete(m) " + "FROM public.task_post_submit_routing_manifests m WHERE m.id=:manifest_id" + ), {"manifest_id": manifest_id}) is True class TaskPostSubmitOutcome: @@ -44,6 +57,7 @@ def __init__( audit, outbox, reconciliation_claim: Callable[[], Awaitable[OutboxClaim]] | None = None, + feedback_email_enabled: bool = False, ): """Inject existing owner ports into one caller-owned transaction.""" self._session, self._projects = session, projects @@ -54,6 +68,7 @@ def __init__( self._observer, self._invocation_fence = observer, invocation_fence self._audit, self._outbox = audit, outbox self._reconciliation_claim = reconciliation_claim + self._feedback_email_enabled = feedback_email_enabled async def apply(self, envelope: OutboxEventEnvelope, *, current_generation: int | None) -> TaskRoutingOutcome: """Return durable identities only after staging complete new or exact replay facts.""" @@ -174,6 +189,8 @@ async def apply(self, envelope: OutboxEventEnvelope, *, current_generation: int )) if root is not None: await self._outbox.require_existing(None, revision_preparation_event(stored, root)) + if self._feedback_email_enabled and not replay: + await self._request_feedback_email(stored) elif human: task = await self._session.get(WorkstreamTask, str(source.source.task_id)) if not replay: @@ -240,7 +257,7 @@ async def classify_uncertain_delivery( return "unresolved" return ( "committed" - if await self._routing_complete(retained.id) + if await routing_outcome_complete(self._session, retained.id) else "unresolved" ) except TaskRoutingRequestUnavailable: @@ -265,7 +282,7 @@ async def verify_retained_delivery( if source.source.human_review_required is not human: raise TaskRoutingRequestUnavailable("routing branch changed") stored = await self._retained(envelope, completion) - if stored is None or not await self._routing_complete(stored.id): + if stored is None or not await routing_outcome_complete(self._session, stored.id): raise TaskRoutingRequestUnavailable("routing retained outcome unavailable") authorized_generation = stored.authorized_lifecycle_generation acceptance_id = stored.final_acceptance_id @@ -308,7 +325,7 @@ async def verify_retained_delivery( stored.outcome_event_id, _notice(source, receipt, acceptance_id), ) - if not await self._routing_complete(stored.id): + if not await routing_outcome_complete(self._session, stored.id): raise TaskRoutingRequestUnavailable( "routing retained outcome unavailable" ) @@ -356,18 +373,6 @@ async def _retained(self, envelope, completion): ).execution_options(populate_existing=True) ) - async def _routing_complete(self, manifest_id: UUID) -> bool: - """Delegate complete retained effect closure to TASK's database owner.""" - return ( - await self._session.scalar( - text( - "SELECT public.task_routing_outcome_complete(m) " - "FROM public.task_post_submit_routing_manifests m WHERE m.id=:manifest_id" - ), - {"manifest_id": manifest_id}, - ) - ) is True - async def _observe_review_mode(self, completion: EvaluationCompletion) -> bool: """Observe exact task policy; authoritative source preparation rechecks it.""" # This observation grants nothing. It selects lock order, and the complete @@ -397,6 +402,16 @@ async def _append_notice(self, source, receipt, acceptance_id): with self._session.no_autoflush: return await self._outbox.append(_notice(source, receipt, acceptance_id)) + async def _request_feedback_email(self, manifest: TaskPostSubmitRoutingManifest) -> None: + """Use the exact database-derived quality outcome after staging its evidence.""" + status, reason = (await self._session.execute(select( + Submission.attempt_status, Submission.status_reason, + ).where(Submission.id == manifest.submission_id))).one() + if status == "needs_revision" and reason is None: + await self._outbox.append(submission_feedback_email_event(manifest, "needs_revision")) + elif status == "rejected" and reason == "revision_limit_reached": + await self._outbox.append(submission_feedback_email_event(manifest, "rejected")) + def _notice(source, receipt, acceptance_id): """Build the bounded shared outbox consequence from exact source and authority.""" @@ -425,6 +440,20 @@ def _notice(source, receipt, acceptance_id): ) +def submission_feedback_email_event( + manifest: TaskPostSubmitRoutingManifest, outcome: FeedbackOutcome, +) -> OutboxAppendInput: + """Use only exact routing identities as durable notification intent.""" + return OutboxAppendInput( + event_type=SUBMISSION_FEEDBACK_EMAIL_EVENT, event_version=1, aggregate_type="task", + aggregate_id=UUID(manifest.task_id), project_id=UUID(manifest.project_id), + correlation_id=manifest.authority_context["request"]["route_operation_id"], + causation_event_id=manifest.outcome_event_id, + idempotency_key=f"submission-feedback-email:{manifest.id}", + payload={"routing_manifest_id": str(manifest.id), "outcome": outcome}, + ) + + def _manifest(source, receipt, acceptance_id, generation, audit_id): """Bind the source to actual authority and consequence using owner column types.""" columns = set(TaskPostSubmitRoutingManifest.__table__.columns.keys()) diff --git a/backend/app/schemas/auth.py b/backend/app/schemas/auth.py index 7b5219e69..314ada63d 100644 --- a/backend/app/schemas/auth.py +++ b/backend/app/schemas/auth.py @@ -28,6 +28,7 @@ class VerifiedIssuerToken(BaseModel): subject_kind: SubjectKind scopes: frozenset[str] email: str | None = Field(default=None, strict=True, min_length=1, max_length=320, pattern=r"^[^\x00\r\n]+$") + email_verified: bool = Field(default=False, strict=True) name: str | None = Field(default=None, strict=True, min_length=1, max_length=200, pattern=r"^[^\x00\r\n]+$") diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py index a19f9c5a3..6704188a3 100644 --- a/backend/app/workers/celery_app.py +++ b/backend/app/workers/celery_app.py @@ -8,7 +8,8 @@ from app.workers.outbox_topology import ( OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE, OUTBOX_SCAN_TASK, OUTBOX_SCAN_QUEUE, FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE, is_finalization_worker_process, - is_outbox_scan_worker_process, + is_outbox_scan_worker_process, FEEDBACK_EMAIL_DELIVERY_TASK, FEEDBACK_EMAIL_QUEUE, + is_feedback_email_worker_process, ) from app.workers.source_cleanup_topology import ( SOURCE_CLEANUP_QUEUE, SOURCE_CLEANUP_TASK, SOURCE_CLEANUP_SCHEDULE, @@ -60,6 +61,7 @@ { OUTBOX_DELIVERY_TASK, FINALIZATION_DELIVERY_TASK, + FEEDBACK_EMAIL_DELIVERY_TASK, SOURCE_CLEANUP_TASK, OUTBOX_SCAN_TASK, RETAINED_REVISION_SCAN_TASK, @@ -90,6 +92,7 @@ OUTBOX_SCAN_TASK: {"queue": OUTBOX_SCAN_QUEUE}, OUTBOX_DELIVERY_TASK: {"queue": OUTBOX_QUEUE}, FINALIZATION_DELIVERY_TASK: {"queue": FINALIZATION_QUEUE}, + FEEDBACK_EMAIL_DELIVERY_TASK: {"queue": FEEDBACK_EMAIL_QUEUE}, SOURCE_CLEANUP_TASK: {"queue": SOURCE_CLEANUP_QUEUE}, } @@ -105,9 +108,10 @@ def initialize_artifact_runtime_for_process(**_kwargs: object) -> None: if is_source_cleanup_worker_process(): # Parent validated cleanup startup; each sweep rechecks current authority. return - if is_finalization_worker_process() or is_outbox_scan_worker_process(): - # Scanning uses SQL and broker only. Finalized replay uses retained SQL; - # unfinished finalization initializes its provider on actual observation. + if (is_finalization_worker_process() or is_outbox_scan_worker_process() + or is_feedback_email_worker_process()): + # Scanner, email and finalized replay need no artifact provider. + # Unfinished finalization initializes its provider on actual observation. return run_async_task(initialize_artifact_internal_runtime) @@ -179,6 +183,7 @@ def create_celery_app() -> Celery: task_queues=tuple(Queue(name) for name in ( PROJECT_GUIDE_QUEUE, PROJECT_CONTROL_QUEUE, ARTIFACT_WORK_QUEUE, OUTBOX_SCAN_QUEUE, OUTBOX_QUEUE, FINALIZATION_QUEUE, SOURCE_CLEANUP_QUEUE, + FEEDBACK_EMAIL_QUEUE, )), task_default_queue=PROJECT_GUIDE_QUEUE, task_create_missing_queues=False, diff --git a/backend/app/workers/outbox.py b/backend/app/workers/outbox.py index aa816b787..a762d13c8 100644 --- a/backend/app/workers/outbox.py +++ b/backend/app/workers/outbox.py @@ -7,11 +7,15 @@ from app.adapters.outbox import production_outbox_delivery from app.db.session import get_database_url +from app.modules.artifacts.api.submission_recovery import FINALIZATION_RECOVERY_EVENT +from app.modules.tasks.api.routing_outcome import SUBMISSION_FEEDBACK_EMAIL_EVENT from app.workers.async_runner import run_async_task from app.workers.celery_app import celery_app from app.workers.outbox_topology import ( require_outbox_worker, require_outbox_scan_worker, OUTBOX_HARD_LIMIT_SECONDS, OUTBOX_SCAN_TASK, OUTBOX_SCAN_HARD_LIMIT_SECONDS, FINALIZATION_HARD_LIMIT_SECONDS, + FEEDBACK_EMAIL_DELIVERY_TASK, FEEDBACK_EMAIL_HARD_LIMIT_SECONDS, FEEDBACK_EMAIL_QUEUE, + FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE, OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE, ) logger = get_task_logger(__name__) @@ -28,31 +32,40 @@ def _uuid(value): @celery_app.task( - name="workstream.outbox.deliver_event", bind=True, acks_late=True, + name=OUTBOX_DELIVERY_TASK, bind=True, acks_late=True, reject_on_worker_lost=True, acks_on_failure_or_timeout=True, time_limit=OUTBOX_HARD_LIMIT_SECONDS, ) def deliver_event(self, event_id, project_id): """Run under prefork: its hard limit also bounds async shutdown after UNKNOWN.""" - return _run_delivery(self, event_id, project_id, finalization=False) + return _run_delivery(self, event_id, project_id, queue=OUTBOX_QUEUE, group="post") @celery_app.task( - name="workstream.outbox.finalize_submission", bind=True, acks_late=True, + name=FINALIZATION_DELIVERY_TASK, bind=True, acks_late=True, reject_on_worker_lost=True, acks_on_failure_or_timeout=True, time_limit=FINALIZATION_HARD_LIMIT_SECONDS, ) def finalize_submission(self, event_id, project_id): """Use reserved finalization workers and the same durable delivery owner.""" - return _run_delivery(self, event_id, project_id, finalization=True) + return _run_delivery(self, event_id, project_id, queue=FINALIZATION_QUEUE, group="finalization") -def _run_delivery(self, event_id, project_id, *, finalization): - require_outbox_worker(self, finalization=finalization) +@celery_app.task( + name=FEEDBACK_EMAIL_DELIVERY_TASK, bind=True, acks_late=True, + reject_on_worker_lost=True, acks_on_failure_or_timeout=True, time_limit=FEEDBACK_EMAIL_HARD_LIMIT_SECONDS, +) +def send_submission_feedback_email(self, event_id, project_id): + """Process only feedback email selectors on the exclusive email queue.""" + return _run_delivery(self, event_id, project_id, queue=FEEDBACK_EMAIL_QUEUE, group="feedback") + + +def _run_delivery(self, event_id, project_id, *, queue, group): + require_outbox_worker(self, queue=queue) try: event, project, task = _uuid(event_id), _uuid(project_id), _uuid(self.request.id) except (TypeError, ValueError): return {"status": "delivery_rejected"} try: - return run_async_task(lambda: _deliver(event, project, task, finalization)) + return run_async_task(lambda: _deliver(event, project, task, group)) except Exception: logger.warning("outbox delivery unavailable") raise self.retry( @@ -62,12 +75,12 @@ def _run_delivery(self, event_id, project_id, *, finalization): ) from None -async def _deliver(event_id, project_id, task_id, finalization=False): +async def _deliver(event_id, project_id, task_id, group): """Compose once; shared delivery owns short transactions and invocation custody.""" engine = create_async_engine(get_database_url(), pool_pre_ping=True) try: receipt = await production_outbox_delivery( - async_sessionmaker(engine, expire_on_commit=False), finalization_worker=finalization, + async_sessionmaker(engine, expire_on_commit=False), worker_group=group, ).deliver(event_id, project_id, "celery:" + str(task_id), registered_only=True) return {"status": "delivery_recorded" if receipt is not None else "delivery_unavailable"} finally: @@ -99,7 +112,11 @@ def _scan_pending(self, after=None): published = 0 for candidate in page.items: try: - task = finalize_submission if candidate.event_type in {"SubmissionFinalizationRequested", "SubmissionFinalizationRecoveryRequested"} else deliver_event + task = { + "SubmissionFinalizationRequested": finalize_submission, + FINALIZATION_RECOVERY_EVENT: finalize_submission, + SUBMISSION_FEEDBACK_EMAIL_EVENT: send_submission_feedback_email, + }.get(candidate.event_type, deliver_event) task.apply_async(args=(str(candidate.event_id), str(candidate.project_id))) published += 1 except Exception: diff --git a/backend/app/workers/outbox_topology.py b/backend/app/workers/outbox_topology.py index 1c579f5cb..0afd5e948 100644 --- a/backend/app/workers/outbox_topology.py +++ b/backend/app/workers/outbox_topology.py @@ -21,20 +21,26 @@ FINALIZATION_QUEUE = "workstream.submission_finalization" FINALIZATION_DELIVERY_TASK = "workstream.outbox.finalize_submission" FINALIZATION_HARD_LIMIT_SECONDS = SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS + OUTBOX_PROCESS_SHUTDOWN_MARGIN_SECONDS +FEEDBACK_EMAIL_QUEUE = "workstream.submission_feedback_email" +FEEDBACK_EMAIL_DELIVERY_TASK = "workstream.outbox.send_submission_feedback_email" +FEEDBACK_EMAIL_HARD_LIMIT_SECONDS = 55 +_DELIVERY_LIMITS = { + OUTBOX_QUEUE: OUTBOX_HARD_LIMIT_SECONDS, + FINALIZATION_QUEUE: FINALIZATION_HARD_LIMIT_SECONDS, + FEEDBACK_EMAIL_QUEUE: FEEDBACK_EMAIL_HARD_LIMIT_SECONDS, +} _validated_parent: int | None = None -_validated_finalization = False -_validated_scan = False +_validated_queue: str | None = None @worker_init.connect def validate_outbox_worker(sender, **_kwargs): """Validate the actual selected queues and pool before the worker starts.""" - global _validated_parent, _validated_finalization, _validated_scan + global _validated_parent, _validated_queue _validated_parent = None + _validated_queue = None queues = set(sender.app.amqp.queues.consume_from) - _validated_finalization = FINALIZATION_QUEUE in queues - _validated_scan = OUTBOX_SCAN_QUEUE in queues - selected = queues & {OUTBOX_QUEUE, OUTBOX_SCAN_QUEUE, FINALIZATION_QUEUE} + selected = queues & (_DELIVERY_LIMITS.keys() | {OUTBOX_SCAN_QUEUE}) if not selected: return if queues != selected or len(selected) != 1: @@ -44,19 +50,36 @@ def validate_outbox_worker(sender, **_kwargs): pool = get_implementation(pool) if pool is not TaskPool or sender.app.conf.task_always_eager: raise WorkerShutdown("OUTBOX delivery requires a non-eager prefork worker") + queue = next(iter(selected)) + if queue == FEEDBACK_EMAIL_QUEUE: + from app.adapters.submission_feedback_email import validate_submission_feedback_email_worker + from app.core.config import get_settings + + try: + validate_submission_feedback_email_worker(get_settings()) + except Exception: + raise WorkerShutdown("submission feedback email worker configuration invalid") from None + _validated_queue = queue _validated_parent = os.getpid() def is_finalization_worker_process() -> bool: """Identify only a child of the validated exclusive finalization consumer.""" - return (_validated_finalization and _validated_parent is not None - and os.getppid() == _validated_parent) + return _is_validated_child(FINALIZATION_QUEUE) def is_outbox_scan_worker_process() -> bool: """Identify only a child of the validated exclusive scanner consumer.""" - return (_validated_scan and _validated_parent is not None - and os.getppid() == _validated_parent) + return _is_validated_child(OUTBOX_SCAN_QUEUE) + + +def is_feedback_email_worker_process() -> bool: + """Identify only a child of the validated exclusive feedback email consumer.""" + return _is_validated_child(FEEDBACK_EMAIL_QUEUE) + + +def _is_validated_child(queue: str) -> bool: + return _validated_queue == queue and _validated_parent is not None and os.getppid() == _validated_parent def require_outbox_scan_worker(task) -> None: @@ -75,17 +98,16 @@ def require_outbox_scan_worker(task) -> None: raise RuntimeError("OUTBOX scan requires a bounded hard time limit") -def require_outbox_worker(task, *, finalization=False): +def require_outbox_worker(task, *, queue=OUTBOX_QUEUE): """Reject direct/eager delivery and consumers not validated for this queue.""" if ( - _validated_parent is None or os.getppid() != _validated_parent + not _is_validated_child(queue) or task.app.conf.task_always_eager or task.request.is_eager or task.request.called_directly - or finalization != _validated_finalization or _validated_scan ): raise RuntimeError("OUTBOX delivery requires a validated prefork worker") message_limit = (task.request.timelimit or (None, None))[0] - expected_limit = FINALIZATION_HARD_LIMIT_SECONDS if finalization else OUTBOX_HARD_LIMIT_SECONDS + expected_limit = _DELIVERY_LIMITS[queue] if ( type(task.time_limit) is not int or task.time_limit != expected_limit or message_limit is not None diff --git a/backend/tests/actors/test_issuer_profile.py b/backend/tests/actors/test_issuer_profile.py index 9af280d5e..6ed61ee98 100644 --- a/backend/tests/actors/test_issuer_profile.py +++ b/backend/tests/actors/test_issuer_profile.py @@ -8,6 +8,7 @@ from sqlalchemy import func, select, text from sqlalchemy.exc import SQLAlchemyError from app.adapters.auth.flow import FlowAuthVerifier +from app.adapters.actors import verified_notification_email from app.core.identifiers import new_record_id from app.db import session as db_session from app.main import create_app @@ -85,6 +86,50 @@ def headers(email, tick, *, subject="email-owner", name="Issuer Name"): assert link.email_observed_issued_at == issued + 3 +async def test_notification_recipient_follows_exact_signed_mailbox_verification( + auth_database_env, rsa_signing_material, +): + """Current verified mailbox only, with stale, conflicting and missing proof refused.""" + import time + from uuid import UUID + + private_key, settings, app = _profile_app(auth_database_env, rsa_signing_material) + issued = int(time.time()) - 20 + + async def observe(client, *, tick, email, proof): + claims = {"sub": "feedback-email-owner", "email": email, "iat": issued + tick} + if proof is not None: + claims["email_verified"] = proof + token = issue_asymmetric_token(private_key, claims=claims) + result = await client.get("/api/v1/actors/me", headers={"Authorization": f"Bearer {token}"}) + assert result.status_code == 200 + assert "email_verified" not in result.json() + actor_id = UUID(result.json()["actor_profile_id"]) + async with db_session.get_session_factory()() as session: + assert await verified_notification_email(session, actor_id, "https://foreign.example.test") is None + return actor_id, await verified_notification_email(session, actor_id, settings.token_issuer) + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as client: + initial = "first@example.test" + corrected = "current@example.test" + actor, recipient = await observe(client, tick=0, email=initial, proof="true") + assert recipient is None + phases = ( + (1, initial, True, initial), + (2, corrected, False, None), + (1, initial, True, None), + (3, corrected, True, corrected), + (3, initial, True, None), + (3, corrected, True, None), + (4, corrected, True, corrected), + (5, None, None, None), + (4, corrected, True, None), + (6, corrected, True, corrected), + ) + for tick, email, proof, expected in phases: + assert await observe(client, tick=tick, email=email, proof=proof) == (actor, expected) + + @pytest.mark.parametrize("blocked", ["suspended", "revoked", "rollback"]) async def test_issuer_email_sync_does_not_survive_denial_or_failed_update( auth_database_env, rsa_signing_material, monkeypatch, blocked, diff --git a/backend/tests/authorization/post_submit/test_migration.py b/backend/tests/authorization/post_submit/test_migration.py index 7e7f9f848..fcdca5e42 100644 --- a/backend/tests/authorization/post_submit/test_migration.py +++ b/backend/tests/authorization/post_submit/test_migration.py @@ -118,14 +118,16 @@ async def write_predecessor_receipt(): # the predecessor receipt migration has already run above. async with h.factory() as session, session.begin(): await session.execute(text( - "ALTER TABLE actor_identity_links ADD COLUMN email_observed_issued_at bigint" + "ALTER TABLE actor_identity_links ADD COLUMN email_observed_issued_at bigint, " + "ADD COLUMN email_verified boolean DEFAULT false" )) try: await provision_post_submit_service(h.factory) finally: async with h.factory() as session, session.begin(): await session.execute(text( - "ALTER TABLE actor_identity_links DROP COLUMN email_observed_issued_at" + "ALTER TABLE actor_identity_links DROP COLUMN email_observed_issued_at, " + "DROP COLUMN email_verified" )) valid = await seed_archived_running_checker(h) assert valid["reservation"]["attempt_id"] == reserved["attempt_id"] diff --git a/backend/tests/authorization/setup_finalization/test_structure.py b/backend/tests/authorization/setup_finalization/test_structure.py index 10ed81e58..0e80a8952 100644 --- a/backend/tests/authorization/setup_finalization/test_structure.py +++ b/backend/tests/authorization/setup_finalization/test_structure.py @@ -21,7 +21,10 @@ def assert_no_live_finalization(paths): assert "setup_finalization_authorization" in imports imports.remove("setup_finalization_authorization") topology = { - ROOT / "app/workers/outbox.py": {"FINALIZATION_HARD_LIMIT_SECONDS"}, + ROOT / "app/workers/outbox.py": { + "FINALIZATION_DELIVERY_TASK", "FINALIZATION_HARD_LIMIT_SECONDS", + "FINALIZATION_QUEUE", "FINALIZATION_RECOVERY_EVENT", + }, ROOT / "app/workers/celery_app.py": { "FINALIZATION_DELIVERY_TASK", "FINALIZATION_QUEUE", "is_finalization_worker_process", }, diff --git a/backend/tests/migration_revision_fixtures.py b/backend/tests/migration_revision_fixtures.py index 5eb38543c..459cfc9de 100644 --- a/backend/tests/migration_revision_fixtures.py +++ b/backend/tests/migration_revision_fixtures.py @@ -59,6 +59,9 @@ async def add_retained_owner_read_projection(connection): await connection.execute(text( f"ALTER TABLE public.{table} ADD COLUMN {column} {column_type}" )) + await connection.execute(text( + "ALTER TABLE public.actor_identity_links ADD COLUMN email_verified boolean DEFAULT false" + )) async def drop_retained_owner_read_projection(connection): @@ -69,6 +72,10 @@ async def drop_retained_owner_read_projection(connection): )) == 0, f"historical owner projection contains new evidence: {table}.{column}" for table, column, _column_type in _OWNER_READ_PROJECTION_COLUMNS: await connection.execute(text(f"ALTER TABLE public.{table} DROP COLUMN {column}")) + assert await connection.scalar(text( + "SELECT count(*) FROM public.actor_identity_links WHERE email_verified IS TRUE" + )) == 0 + await connection.execute(text("ALTER TABLE public.actor_identity_links DROP COLUMN email_verified")) async def add_historical_revision_read_projection(connection): diff --git a/backend/tests/outbox/test_delivery_topology.py b/backend/tests/outbox/test_delivery_topology.py index 16fc7aa20..4eb6131cf 100644 --- a/backend/tests/outbox/test_delivery_topology.py +++ b/backend/tests/outbox/test_delivery_topology.py @@ -24,8 +24,7 @@ def restore_process_state(monkeypatch): original_join_guard = task_join_will_block() monkeypatch.setattr(topology, "_validated_parent", None) - monkeypatch.setattr(topology, "_validated_finalization", False) - monkeypatch.setattr(topology, "_validated_scan", False) + monkeypatch.setattr(topology, "_validated_queue", None) try: yield finally: @@ -172,7 +171,7 @@ def test_finalization_prefork_worker_rejects_general_delivery(monkeypatch): monkeypatch.setattr(topology.os, "getppid", os.getpid) task = SimpleNamespace(app=configured.app, time_limit=topology.FINALIZATION_HARD_LIMIT_SECONDS, request=SimpleNamespace(is_eager=False, called_directly=False, timelimit=None)) - topology.require_outbox_worker(task, finalization=True) + topology.require_outbox_worker(task, queue=topology.FINALIZATION_QUEUE) with pytest.raises(RuntimeError, match="validated prefork"): topology.require_outbox_worker(task) @@ -221,6 +220,7 @@ def test_every_registered_workstream_task_has_one_explicit_queue(monkeypatch): "workstream.outbox.scan_pending": "workstream.outbox_scan", "workstream.outbox.deliver_event": "workstream.outbox", "workstream.outbox.finalize_submission": "workstream.submission_finalization", + "workstream.outbox.send_submission_feedback_email": "workstream.submission_feedback_email", "workstream.artifacts.sweep_submission_sources": "workstream.source_cleanup", } try: @@ -242,6 +242,7 @@ def test_every_registered_workstream_task_has_one_explicit_queue(monkeypatch): @pytest.mark.parametrize("queues", [ (topology.OUTBOX_SCAN_QUEUE, topology.OUTBOX_QUEUE), (topology.OUTBOX_SCAN_QUEUE, topology.FINALIZATION_QUEUE), + (topology.OUTBOX_SCAN_QUEUE, topology.FEEDBACK_EMAIL_QUEUE), (topology.OUTBOX_SCAN_QUEUE, "celery"), ]) def test_scan_worker_refuses_shared_queues(queues): @@ -265,6 +266,26 @@ def test_scan_entry_requires_dedicated_prefork_and_sixty_second_limit(monkeypatc topology.require_outbox_worker(task) +def test_feedback_email_requires_its_own_validated_child(monkeypatch): + from app.adapters import submission_feedback_email + + configured = worker(queues=(topology.FEEDBACK_EMAIL_QUEUE,)) + with pytest.raises(WorkerShutdown, match="feedback email worker configuration invalid"): + topology.validate_outbox_worker(configured) + validated = [] + monkeypatch.setattr(submission_feedback_email, "validate_submission_feedback_email_worker", validated.append) + topology.validate_outbox_worker(configured) + assert len(validated) == 1 + task = SimpleNamespace(app=configured.app, time_limit=topology.FEEDBACK_EMAIL_HARD_LIMIT_SECONDS, + request=SimpleNamespace(is_eager=False, called_directly=False, timelimit=None)) + with pytest.raises(RuntimeError, match="validated prefork"): + topology.require_outbox_worker(task, queue=topology.FEEDBACK_EMAIL_QUEUE) + monkeypatch.setattr(topology.os, "getppid", os.getpid) + topology.require_outbox_worker(task, queue=topology.FEEDBACK_EMAIL_QUEUE) + with pytest.raises(RuntimeError, match="validated prefork"): + topology.require_outbox_worker(task) + + @pytest.mark.parametrize("selected,name,routing_key", [ ("workstream.outbox_scan", "workstream.outbox.deliver_event", "workstream.outbox_scan"), ("workstream.project_control", "workstream.artifacts.verify_object", "workstream.project_control"), @@ -299,11 +320,12 @@ def test_scan_routes_each_event_group_without_acknowledging(monkeypatch): from app.core.config import get_settings from app.core.identifiers import new_record_id from app.modules.outbox.api import DeliveryCandidate, DeliveryCandidatePage + from app.modules.tasks.api.routing_outcome import SUBMISSION_FEEDBACK_EMAIL_EVENT monkeypatch.setenv("WORKSTREAM_CELERY_TASK_ALWAYS_EAGER", "true") get_settings.cache_clear() from app.workers import outbox items = tuple(DeliveryCandidate(event_id=new_record_id(), project_id=new_record_id(), event_type=kind) - for kind in ("PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested", "SubmissionFinalizationRecoveryRequested")) + for kind in ("PostSubmissionEvaluationRequested", "SubmissionFinalizationRequested", "SubmissionFinalizationRecoveryRequested", SUBMISSION_FEEDBACK_EMAIL_EVENT)) async def candidates(_after): return DeliveryCandidatePage(items=items, next_after=None) published = [] @@ -311,10 +333,11 @@ async def candidates(_after): monkeypatch.setattr(outbox, "require_outbox_scan_worker", lambda _task: None) monkeypatch.setattr(outbox.deliver_event, "apply_async", lambda **kwargs: published.append(("post", kwargs))) monkeypatch.setattr(outbox.finalize_submission, "apply_async", lambda **kwargs: published.append(("final", kwargs))) + monkeypatch.setattr(outbox.send_submission_feedback_email, "apply_async", lambda **kwargs: published.append(("feedback", kwargs))) try: - assert outbox.scan_pending.apply(task_id=str(new_record_id()), throw=True).get() == {"selected": 3, "published": 3} + assert outbox.scan_pending.apply(task_id=str(new_record_id()), throw=True).get() == {"selected": 4, "published": 4} assert published == [(kind, {"args": (str(item.event_id), str(item.project_id))}) - for kind, item in zip(("post", "final", "final"), items, strict=True)] + for kind, item in zip(("post", "final", "final", "feedback"), items, strict=True)] finally: get_settings.cache_clear() diff --git a/backend/tests/outbox/test_worker_postgresql.py b/backend/tests/outbox/test_worker_postgresql.py index 08634abf3..cee66496b 100644 --- a/backend/tests/outbox/test_worker_postgresql.py +++ b/backend/tests/outbox/test_worker_postgresql.py @@ -81,7 +81,7 @@ async def test_app_worker_discovers_remote_post_and_recovers_expired_custody(del monkeypatch.setenv("WORKSTREAM_HOSTED_PROFILE", "app") get_settings.cache_clear() try: - app_delivery = production_outbox_delivery(h.factory, finalization_worker=False) + app_delivery = production_outbox_delivery(h.factory, worker_group="post") for _ in range(2): page = await app_delivery.candidates(limit=2) assert tuple(item.event_id for item in page.items) == ( @@ -418,7 +418,7 @@ async def test_finalization_worker_cannot_deliver_or_recover_post_event(delivery monkeypatch.setenv("WORKSTREAM_HOSTED_PROFILE", "app") get_settings.cache_clear() try: - finalization = production_outbox_delivery(h.factory, finalization_worker=True) + finalization = production_outbox_delivery(h.factory, worker_group="finalization") assert finalization._registry.keys == (("SubmissionFinalizationRequested", 1), ("SubmissionFinalizationRecoveryRequested", 1)) assert await finalization.deliver(event.event_id, h.project, "wrong-worker", registered_only=True) is None async with h.factory() as session: diff --git a/backend/tests/reviews/lifecycle/test_participant_control.py b/backend/tests/reviews/lifecycle/test_participant_control.py index be9b5d696..9283ed0b8 100644 --- a/backend/tests/reviews/lifecycle/test_participant_control.py +++ b/backend/tests/reviews/lifecycle/test_participant_control.py @@ -257,7 +257,8 @@ async def test_0038_old_manifest_live_upgrade_denies_new_effects_until_renewed( # Remove it before the real migration introduces the column. async with db_session.get_engine().begin() as connection: await connection.execute(text( - "ALTER TABLE actor_identity_links ADD COLUMN email_observed_issued_at bigint" + "ALTER TABLE actor_identity_links ADD COLUMN email_observed_issued_at bigint, " + "ADD COLUMN email_verified boolean DEFAULT false" )) access = await _provision_0038_operator(admin_access) _set_runtime_manifest(monkeypatch, migration._OLD_MANIFEST) @@ -286,7 +287,7 @@ async def test_0038_old_manifest_live_upgrade_denies_new_effects_until_renewed( async with db_session.get_engine().begin() as connection: await connection.execute(text( - "ALTER TABLE actor_identity_links DROP COLUMN email_observed_issued_at" + "ALTER TABLE actor_identity_links DROP COLUMN email_observed_issued_at, DROP COLUMN email_verified" )) # The retained 0039 control is unchanged; current runtime owners require # their complete schema before exercising new submissions and acceptance. diff --git a/backend/tests/tasks/evaluation_delivery/test_completion.py b/backend/tests/tasks/evaluation_delivery/test_completion.py index 84f04953e..04e32393a 100644 --- a/backend/tests/tasks/evaluation_delivery/test_completion.py +++ b/backend/tests/tasks/evaluation_delivery/test_completion.py @@ -319,7 +319,7 @@ async def test_production_registry_delivers_request_then_completion_exactly_once "worker_post_submission_materialization", lambda *, sessions: h.service, ) - delivery = production_outbox_delivery(h.factory, finalization_worker=False) + delivery = production_outbox_delivery(h.factory, worker_group="post") assert delivery._registry.keys[-3:] == ( (REQUEST_EVENT, 1), (COMPLETION_EVENT, 1), diff --git a/backend/tests/tasks/post_submit_routing/test_feedback_email.py b/backend/tests/tasks/post_submit_routing/test_feedback_email.py new file mode 100644 index 000000000..787e74aca --- /dev/null +++ b/backend/tests/tasks/post_submit_routing/test_feedback_email.py @@ -0,0 +1,241 @@ +"""Committed routing and Resend HTTP behavior for assignment feedback email.""" + +import asyncio +from datetime import timedelta +import json +from uuid import UUID + +import httpx +import pytest +from sqlalchemy import select, text +from workstream_external_services import ( + ExternalServiceConfigurationError, ExternalServiceProtocolError, + ExternalServiceUnavailableError, +) + +from app.adapters import submission_feedback_email as email_adapter +from app.adapters.outbox import production_outbox_delivery +from app.adapters.tasks import task_post_submit_outcome +from app.core.config import Settings +from app.core.identifiers import new_record_id +from app.interfaces.submission_feedback_email import RESEND_PROVIDER, SubmissionFeedbackEmail +from app.modules.actors.models import ActorIdentityLink, ActorProfile +from app.modules.checkers.models import CheckerRun +from app.modules.outbox.api import DeliveryOptions, HandlerOutcome +from app.modules.outbox.models import OutboxEvent +from app.modules.tasks.api.routing_outcome import SUBMISSION_FEEDBACK_EMAIL_EVENT +from tests.checkers.execution.support import live_executor, reserve +from tests.checkers.external.support import post_registry_spec +from tests.post_submit_materialization_helpers import material_fixture +from tests.tasks.post_submit_routing.remediation_support import remediation_source +from tests.tasks.submission_dispatch.test_revision_capacity import COVERAGE_GAP + + +def _private_key(tmp_path): + path = tmp_path / "resend-key" + path.write_text("re_fake_testing_key\n", encoding="ascii") + path.chmod(0o400) + return path + + +class ResponseStream(httpx.AsyncByteStream): + def __init__(self, payload): + self._payload = payload + + async def __aiter__(self): + yield self._payload + + +def _response(status, **body): + return httpx.Response(status, stream=ResponseStream(json.dumps(body).encode())) + + +@pytest.mark.parametrize("status,body,error", [ + (200, {"id": "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794"}, None), + (200, {"id": "not-an-id"}, ExternalServiceProtocolError), + (409, {"name": "concurrent_idempotent_requests"}, ExternalServiceUnavailableError), + (409, {"name": "invalid_idempotent_request"}, ExternalServiceProtocolError), + (429, {"message": "sensitive@example.test"}, ExternalServiceUnavailableError), + (503, {"message": "sensitive@example.test"}, ExternalServiceUnavailableError), + (401, {}, ExternalServiceProtocolError), + (307, {}, ExternalServiceProtocolError), +]) +async def test_resend_http_mapping_and_request_privacy(tmp_path, status, body, error): + async def server(request): + assert str(request.url) == "https://api.resend.com/emails" + assert request.method == "POST" + assert request.headers["Authorization"] == "Bearer re_fake_testing_key" + assert request.headers["Idempotency-Key"] == f"workstream-submission-feedback/{event_id}" + assert json.loads(request.content) == { + "from": "Workstream ", + "to": ["verified@example.test"], "subject": "Assignment needs revision", "text": "Read feedback.", + } + return _response(status, **body) + + settings = Settings(environment="test", resend_api_key_file=_private_key(tmp_path)) + adapter = email_adapter.submission_feedback_email_factory( + settings, transport=httpx.MockTransport(server), + ).create(RESEND_PROVIDER) + event_id = new_record_id() + message = SubmissionFeedbackEmail(event_id, "verified@example.test", "Assignment needs revision", "Read feedback.") + if error is None: + await adapter.send(message) + else: + with pytest.raises(error) as failure: + await adapter.send(message) + assert "sensitive@example.test" not in str(failure.value) + assert "re_fake_testing_key" not in str(failure.value) + + +def test_resend_worker_rejects_missing_or_nonprivate_key(tmp_path): + key = _private_key(tmp_path) + settings = Settings(environment="test", submission_feedback_email_enabled=True, + token_issuer="https://identity.example.test/realms/flow") + for path in (None, tmp_path / "absent"): + with pytest.raises(ExternalServiceConfigurationError): + email_adapter.validate_submission_feedback_email_worker(settings.model_copy(update={"resend_api_key_file": path})) + key.chmod(0o644) + settings = settings.model_copy(update={"resend_api_key_file": key}) + with pytest.raises(ExternalServiceConfigurationError): + email_adapter.validate_submission_feedback_email_worker(settings) + key.chmod(0o400) + email_adapter.validate_submission_feedback_email_worker(settings) + with pytest.raises(ExternalServiceConfigurationError): + email_adapter.validate_submission_feedback_email_worker(settings.model_copy(update={"submission_feedback_email_enabled": False})) + + +async def _email_events(factory): + async with factory() as session: + return tuple(await session.scalars(select(OutboxEvent).where( + OutboxEvent.event_type == SUBMISSION_FEEDBACK_EMAIL_EVENT, + ))) + + +@pytest.mark.parametrize("case", ["retry", "stale", "unverified", "exhausted", "coverage", "disabled"]) +async def test_only_committed_current_quality_routes_send( + tmp_path, isolated_database_env, monkeypatch, case, +): + options = {"findings": COVERAGE_GAP, "human_review_required": False} if case == "coverage" else {} + if case == "exhausted": + options["max_revision_rounds"] = 0 + async with remediation_source(tmp_path, isolated_database_env, **options) as h: + async with h.factory() as session, session.begin(): + actor_id = str(h.actor_context.actor_profile_id) + link = await session.get(ActorIdentityLink, str(h.actor_context.identity_link_id)) + profile = await session.get(ActorProfile, actor_id) + issuer = link.issuer + # The signed profile test separately verifies how this state is observed. + profile.contact_email = "exact-recipient@example.test" + link.email_observed_issued_at = 1 + link.email_verified = case != "unverified" + settings = h.settings.model_copy(update={ + "submission_feedback_email_enabled": case != "disabled", "token_issuer": issuer, + "resend_api_key_file": _private_key(tmp_path), + }) + monkeypatch.setattr("app.core.config.get_settings", lambda: settings) + calls = [] + + async def server(request): + calls.append((request.headers["Idempotency-Key"], json.loads(request.content))) + if case == "retry" and len(calls) == 1: + raise httpx.ReadTimeout("lost provider acknowledgement", request=request) + return _response(200, id="49a3999c-0ce1-4ea6-ab68-afcd6dc2e794") + + factory = email_adapter.submission_feedback_email_factory + monkeypatch.setattr(email_adapter, "submission_feedback_email_factory", lambda configured: factory( + configured, transport=httpx.MockTransport(server), + )) + if case == "retry": + async with h.factory() as session: + await task_post_submit_outcome(session, h.factory).apply(h.envelope, current_generation=None) + assert await _email_events(h.factory) == () + await session.rollback() + assert await _email_events(h.factory) == () + async with h.factory() as session, session.begin(): + outcome = await task_post_submit_outcome(session, h.factory).apply(h.envelope, current_generation=None) + assert outcome.routing_recommendation == "needs_revision" + events = await _email_events(h.factory) + if case in {"coverage", "disabled"}: + assert events == () and calls == [] + return + event, = events + assert event.causation_event_id == outcome.outcome_event_id + assert event.payload == {"routing_manifest_id": str(outcome.routing_manifest_id), + "outcome": "rejected" if case == "exhausted" else "needs_revision"} + async with h.factory() as session, session.begin(): + replay = await task_post_submit_outcome(session, h.factory).apply(h.envelope, current_generation=None) + assert replay.replayed and [item.event_id for item in await _email_events(h.factory)] == [event.event_id] + if case == "stale": + async with h.factory() as session, session.begin(): + await session.execute(text( + "UPDATE public.workstream_tasks SET status='evaluation_pending' WHERE id=:task_id" + ), {"task_id": h.request.task_id}) + scanner = production_outbox_delivery(h.factory) + delivery = production_outbox_delivery(h.factory, worker_group="feedback") + assert (SUBMISSION_FEEDBACK_EMAIL_EVENT, 1) in scanner._registry.keys + post = production_outbox_delivery(h.factory, worker_group="post") + assert await post.deliver(event.event_id, UUID(event.project_id), "wrong-queue", registered_only=True) is None + assert await delivery.deliver(event.event_id, new_record_id(), "wrong-project", registered_only=True) is None + if case == "retry": + delivery._event_options = { + (SUBMISSION_FEEDBACK_EMAIL_EVENT, 1): DeliveryOptions(retry_base_seconds=1), + } + receipt = await delivery.deliver(event.event_id, UUID(event.project_id), "email-worker", registered_only=True) + assert receipt is not None + if case == "retry": + assert json.loads(receipt.outcome_json)["delivery_state"] == "retryable" + await asyncio.sleep(1.05) + receipt = await delivery.deliver(event.event_id, UUID(event.project_id), "email-worker", registered_only=True) + assert json.loads(receipt.outcome_json)["delivery_state"] == "acknowledged" + assert await delivery.deliver(event.event_id, UUID(event.project_id), "duplicate", registered_only=True) is None + if case in {"stale", "unverified"}: + assert calls == [] + else: + assert len(calls) == (2 if case == "retry" else 1) + assert len(set(key for key, _ in calls)) == 1 + assert all(body == calls[0][1] for _, body in calls) + body = calls[0][1] + assert body["to"] == ["exact-recipient@example.test"] + assert str(h.request.assignment_id) in body["text"] + assert str(h.request.submission_id) not in body["text"] + assert str(h.request.task_id) not in body["text"] + assert ("resubmit" in body["text"]) is (case != "exhausted") + + +async def test_post_provider_failure_does_not_request_email(tmp_path, isolated_database_env, monkeypatch): + class UnavailableChecker: + async def execute(self, _request, _grant): + raise ExternalServiceUnavailableError() + + monkeypatch.setenv("WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED", "true") + async with material_fixture( + tmp_path, isolated_database_env, post_submit_registry_spec=post_registry_spec(), + ) as h: + await reserve(h) + result = await live_executor(h, selected_execution=UnavailableChecker()).evaluate_post_submission(h.request) + assert result.outcome == "infrastructure_failed" + async with h.factory() as session: + run = await session.get(CheckerRun, str(result.attempt_id)) + assert run.routing_recommendation == "not_evaluated" and run.completion_event_id is None + assert await _email_events(h.factory) == () + + +async def test_expired_invocation_skips_recipient_and_resend(): + from types import SimpleNamespace + from datetime import UTC, datetime + from app.modules.tasks.post_submit_routing.feedback_email import ( + SUBMISSION_FEEDBACK_EMAIL_LIFETIME, TaskSubmissionFeedbackEmailHandler, + ) + + class Observer: + async def observe_invocation(self, envelope): + return SimpleNamespace(observed_at=envelope.occurred_at + SUBMISSION_FEEDBACK_EMAIL_LIFETIME + timedelta(seconds=1)) + + def forbidden(*args, **kwargs): + pytest.fail("expired email reached database or provider") + + owner = TaskSubmissionFeedbackEmailHandler(forbidden, observer=Observer(), recipient=forbidden, adapter=forbidden) + envelope = SimpleNamespace(occurred_at=datetime.now(UTC), payload_json=json.dumps({ + "routing_manifest_id": str(new_record_id()), "outcome": "needs_revision", + })) + assert await owner(envelope) is HandlerOutcome.REJECT diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py index 2a4ee6409..f33308a72 100644 --- a/backend/tests/test_alembic.py +++ b/backend/tests/test_alembic.py @@ -395,7 +395,7 @@ async def _migration_resume_custody(database_url: str, snapshot_id) -> dict[str, export = await connection.fetchrow( """ SELECT to_jsonb(s)::text,to_jsonb(a)::text, - ('{"email_observed_issued_at":null}'::jsonb || to_jsonb(l))::text, + ('{"email_observed_issued_at":null,"email_verified":false}'::jsonb || to_jsonb(l))::text, s.tableoid::bigint,a.tableoid::bigint,l.tableoid::bigint, s.xmin::text,a.xmin::text,l.xmin::text FROM public.contribution_export_snapshots s @@ -439,6 +439,7 @@ def test_v01_graph_has_one_root_and_head() -> None: assert [revision.revision for revision in revisions] == [ HEAD_REVISION, + "0092_submission_feedback", "0091_qualified_aws_source", "0090_merge_direct_storage", "0089_observed_upload_cleanup", @@ -535,7 +536,7 @@ def test_v01_graph_has_one_root_and_head() -> None: assert script.get_revision("0090_merge_direct_storage").down_revision == ( "0089_observed_upload_cleanup", "0069_remove_artifact_proof", ) - assert script.get_revision(HEAD_REVISION).down_revision == "0091_qualified_aws_source" + assert script.get_revision(HEAD_REVISION).down_revision == "0092_submission_feedback" assert revisions[-1].down_revision is None assert script.get_heads() == [HEAD_REVISION] diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md index 14c3d6d88..d3b529178 100644 --- a/deploy/hosted/README.md +++ b/deploy/hosted/README.md @@ -180,6 +180,7 @@ metadata only; the worker loader sets the adapter's existing private-key variabl without evaluating or logging its contents. Never put a raw private key in the release environment. Follow the [GitHub App instructions](../../pilots/garden/github-app.md) for read-only permissions. + `WORKSTREAM_MODEL_PROXY_ENABLED=true` starts one trusted model-proxy process independently of the setup runtime. Only that process gets the database, each configured provider credential and the runtime ART identity. @@ -296,6 +297,38 @@ qualification receipt record actual health, PRE/POST execution and cleanup. App preflight validates only the configured endpoint, TLS files and intake digests; it does not infer runner qualification from local files. +### Contributor feedback email + +`WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED` defaults to `false`. To enable +delivery, verify `workstream.flowresearch.tech` in Resend and provide a sending +key scoped to that domain. Set `WORKSTREAM_RESEND_API_KEY_FILE` to its private +absolute host path outside the deployment runtime tree. Give the regular file +the release runtime UID/GID and mode `0400`. Store only the key on one line. +Set `WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED=true`. Release preflight +selects the email overlay and checks that only the dedicated +`workstream.submission_feedback_email` worker mounts the key. This worker uses +SQL, Redis and the fixed Resend HTTPS endpoint. + +Before activation, apply the mailbox claim and verify a fresh signed contributor +self-profile observation with a designated test account. The worker uses the +active Workstream actor's latest signed, verified mailbox and current exact-project +Submitter grant. Existing actors can refresh the observation through an authorized +`GET /api/v1/actors/me` using a fresh token. Historical or unverified mailboxes +are ineligible. [Flow Identity mailbox claim](../identity/README.md#workstream-feedback-email-claim). + +New governed POST quality outcomes request an email for a current revision +return or immediate revision-limit rejection. The message uses the assignment +ID and the same authorized assignment status and feedback read available in +the API, CLI and MCP. The assignment read remains the source of feedback and +revision terms. Workstream continues processing assignments if email fails. + +Temporary Resend errors and uncertain HTTP outcomes retry through the shared +outbox using a stable event key and an absolute 12-hour send cutoff. Outbox +acknowledgement records a handled request, including suppression if the +assignment no longer needs its alert or the recipient is ineligible. Resend +acceptance acknowledges the request, and inbox delivery has separate provider +status. [Resend's 24-hour idempotency window](https://resend.com/docs/dashboard/emails/idempotency-keys). + ## Validate without disclosure The directory commands above describe the default app production root. Runner diff --git a/deploy/hosted/compose.submission-feedback-email.yml b/deploy/hosted/compose.submission-feedback-email.yml new file mode 100644 index 000000000..797384ec2 --- /dev/null +++ b/deploy/hosted/compose.submission-feedback-email.yml @@ -0,0 +1,32 @@ +services: + submission-feedback-email-worker: + extends: + file: compose.yml + service: outbox-scan-worker + environment: + WORKSTREAM_RESEND_API_KEY_FILE: /run/secrets/resend_api_key + secrets: + - source: resend_api_key + target: resend_api_key + uid: "${WORKSTREAM_RUNTIME_UID}" + gid: "${WORKSTREAM_RUNTIME_GID}" + mode: 0400 + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=submission-feedback-email@%h + - --queues=workstream.submission_feedback_email + - --pidfile=/tmp/celery-submission-feedback-email.pid + - --loglevel=INFO + healthcheck: + test: [CMD-SHELL, "test -s /tmp/celery-submission-feedback-email.pid && kill -0 $$(cat /tmp/celery-submission-feedback-email.pid)"] + +secrets: + resend_api_key: + file: ${WORKSTREAM_RESEND_API_KEY_FILE:?set the private Resend API key file} diff --git a/deploy/hosted/compose.yml b/deploy/hosted/compose.yml index b38f4b797..a0ec11370 100644 --- a/deploy/hosted/compose.yml +++ b/deploy/hosted/compose.yml @@ -52,6 +52,7 @@ x-backend-environment: &backend-environment WORKSTREAM_TOKEN_ISSUER: ${WORKSTREAM_TOKEN_ISSUER:?set the Flow issuer} WORKSTREAM_TOKEN_JWKS_URL: ${WORKSTREAM_TOKEN_JWKS_URL:?set the Flow JWKS URL} WORKSTREAM_SUBMISSION_EXECUTION_PROFILE: ${WORKSTREAM_SUBMISSION_EXECUTION_PROFILE:?set the approved finite submission execution profile JSON} + WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED: ${WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED:-false} WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE: ${WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE:?set the approved finite submission source-cleanup profile JSON} x-backend-runtime: &backend-runtime diff --git a/deploy/hosted/preflight.py b/deploy/hosted/preflight.py index 84b026705..82aa812fd 100644 --- a/deploy/hosted/preflight.py +++ b/deploy/hosted/preflight.py @@ -21,6 +21,10 @@ COMPOSE_PATH = Path(__file__).with_name("compose.yml") +FEEDBACK_EMAIL_COMPOSE_PATH = Path(__file__).with_name("compose.submission-feedback-email.yml") +FEEDBACK_EMAIL_WORKER = "submission-feedback-email-worker" +FEEDBACK_EMAIL_ENABLED_KEY = "WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED" +RESEND_KEY_FILE = "WORKSTREAM_RESEND_API_KEY_FILE" INFERENCE_COMPOSE_PATH = Path(__file__).with_name("compose.inference.yml") TRIAL_COMPOSE_PATH = Path(__file__).with_name("compose.trials.yml") TRIAL_MANIFEST_TARGET = Path("/etc/workstream/trial-authority.json") @@ -172,8 +176,10 @@ def deployment_paths(values: dict[str, str]) -> HostedPaths: *BASE_SECRET_FILE_KEYS, *MODEL_PROXY_SECRET_FILE_KEYS, GITHUB_APP_KEYS[1], + RESEND_KEY_FILE, ) SECRET_FILE_TARGETS = { + RESEND_KEY_FILE: ("resend_api_key", "/run/secrets/resend_api_key"), "WORKSTREAM_GITHUB_APP_PRIVATE_KEY_FILE": ( "github_app_private_key", "/run/secrets/github_app_private_key", @@ -233,6 +239,7 @@ def deployment_paths(values: dict[str, str]) -> HostedPaths: "model-proxy": ("WORKSTREAM_DATABASE_URL_FILE",), } FORBIDDEN_RELEASE_KEYS = ( + "WORKSTREAM_RESEND_API_KEY", "WORKSTREAM_GITHUB_APP_PRIVATE_KEY", "AWS_ACCESS_KEY_ID", "AWS_CONFIG_FILE", @@ -354,6 +361,8 @@ def deployment_paths(values: dict[str, str]) -> HostedPaths: "WORKSTREAM_OBSERVABILITY_OTLP_ENDPOINT", "WORKSTREAM_OBSERVABILITY_TRACE_SAMPLE_RATIO", *MODEL_PROXY_SECRET_FILE_KEYS, + FEEDBACK_EMAIL_ENABLED_KEY, + RESEND_KEY_FILE, ) RELEASE_KEYS = frozenset((*REQUIRED_RELEASE_KEYS, *OPTIONAL_RELEASE_KEYS)) @@ -514,6 +523,18 @@ def validate_environment(values: dict[str, str]) -> None: validate_identity_environment(values) validate_mcp_environment(values) validate_local_data_environment(values) + feedback_enabled = values.get(FEEDBACK_EMAIL_ENABLED_KEY, "false") + if feedback_enabled not in {"true", "false"} or ( + (feedback_enabled == "true") != bool(values.get(RESEND_KEY_FILE)) + ): + raise PreflightError("submission feedback email requires an explicit flag and its private key file") + if feedback_enabled == "true": + key_file = Path(values[RESEND_KEY_FILE]) + root = deployment_paths(values).root + if (not key_file.is_absolute() or key_file != key_file.resolve(strict=False) + or key_file.is_relative_to(root) or root.is_relative_to(key_file) + or any(character.isspace() or character in ",:" for character in str(key_file))): + raise PreflightError("Resend key file must use a canonical private path outside deployment storage") github_app_id, github_key_file, github_installation_id = ( values.get(key, "") for key in GITHUB_APP_KEYS ) @@ -857,6 +878,7 @@ def _secret_file_keys(values: dict[str, str]) -> tuple[str, ...]: if values["WORKSTREAM_MODEL_PROXY_ENABLED"] == "true" and values.get(key) ), *((GITHUB_APP_KEYS[1],) if values.get(GITHUB_APP_KEYS[0]) else ()), + *((RESEND_KEY_FILE,) if values.get(FEEDBACK_EMAIL_ENABLED_KEY) == "true" else ()), ) @@ -1002,6 +1024,8 @@ def _compose_file_arguments(values: dict[str, str]) -> list[str]: arguments.extend(("--file", str(IDENTITY_COMPOSE_PATH))) if values.get(GITHUB_APP_KEYS[0]): arguments.extend(("--file", str(GITHUB_COMPOSE_PATH))) + if values.get(FEEDBACK_EMAIL_ENABLED_KEY) == "true": + arguments.extend(("--file", str(FEEDBACK_EMAIL_COMPOSE_PATH))) if values["WORKSTREAM_MODEL_PROXY_ENABLED"] == "true": arguments.extend(("--file", str(INFERENCE_COMPOSE_PATH))) for provider, key in MODEL_PROVIDER_SECRET_FILE_KEYS.items(): @@ -1104,6 +1128,7 @@ def run_compose( "outbox-scan-worker", "outbox-worker", "submission-finalization-worker", "submission-source-cleanup-worker", "beat", "model-proxy", "identity", "guide-document-parser", + FEEDBACK_EMAIL_WORKER, } targets_api = not selected_services or "api" in selected_services or ( "--no-deps" not in compose_arguments @@ -1111,6 +1136,7 @@ def run_compose( "mcp", "beat", "worker", "project-control-worker", "artifact-worker", "outbox-scan-worker", "outbox-worker", "submission-finalization-worker", "submission-source-cleanup-worker", + FEEDBACK_EMAIL_WORKER, }) ) couple_mcp = bool(values.get("WORKSTREAM_MCP_IMAGE")) and ( @@ -1139,6 +1165,8 @@ def run_compose( compose_arguments.append("identity") if values["WORKSTREAM_MODEL_PROXY_ENABLED"] == "true": compose_arguments.append("model-proxy") + if values.get(FEEDBACK_EMAIL_ENABLED_KEY) == "true": + compose_arguments.append(FEEDBACK_EMAIL_WORKER) else: compose_arguments = [item for item in compose_arguments if item != "mcp"] if selected_services == {"mcp"}: @@ -1310,6 +1338,8 @@ def run_shutdown(environment_path: Path, values: dict[str, str]) -> int: ] if values.get("WORKSTREAM_MCP_IMAGE"): phases.insert(0, ["stop", "mcp"]) + if values.get(FEEDBACK_EMAIL_ENABLED_KEY) == "true": + phases.append(["stop", "--timeout", "120", FEEDBACK_EMAIL_WORKER]) if values["WORKSTREAM_MODEL_PROXY_ENABLED"] == "true": phases.append(["stop", "--timeout", "7320", "model-proxy"]) phases.append(["stop", "guide-document-parser"]) @@ -1578,6 +1608,9 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: "outbox-scan-worker", "submission-finalization-worker", "submission-source-cleanup-worker", } + feedback_enabled = values.get(FEEDBACK_EMAIL_ENABLED_KEY, "false") + if feedback_enabled == "true": + bounded_workers.add(FEEDBACK_EMAIL_WORKER) all_workers = standard_workers | bounded_workers expected_services = { "api", @@ -1710,6 +1743,8 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: str(paths.guide_root): (str(paths.guide_root), False), }, } + if feedback_enabled == "true": + expected_mounts[FEEDBACK_EMAIL_WORKER] = {} if model_proxy_enabled: expected_mounts["model-proxy"] = { str(paths.scratch): (str(paths.scratch), False), @@ -1880,12 +1915,18 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: "--pidfile=/tmp/celery-submission-source-cleanup.pid", ), } + if feedback_enabled == "true": + bounded_worker_profiles[FEEDBACK_EMAIL_WORKER] = ( + "--queues=workstream.submission_feedback_email", + "--hostname=submission-feedback-email@%h", + "--pidfile=/tmp/celery-submission-feedback-email.pid", + ) for name, required_arguments in bounded_worker_profiles.items(): bounded_worker = services[name] command = bounded_worker.get("command") if ( bounded_worker.get("stop_grace_period") not in ( - {"120s", "2m0s"} if name == "outbox-scan-worker" else + {"120s", "2m0s"} if name in {"outbox-scan-worker", FEEDBACK_EMAIL_WORKER} else {"7320s", "2h2m0s"} if name in { "project-control-worker", "artifact-worker", "outbox-worker", } else {"420s", "7m0s"} @@ -1953,6 +1994,8 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: if role in standard_workers - {"worker"} else set(_role_secret_file_keys(policy_role, values)) ) + if role == FEEDBACK_EMAIL_WORKER: + required_file_keys.add(RESEND_KEY_FILE) for key, (_, target) in SECRET_FILE_TARGETS.items(): if key in REMOTE_RUNNER_SECRET_FILE_KEYS: if key in environment: @@ -2062,6 +2105,8 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: service_environment = services[name].get("environment") if not isinstance(service_environment, dict): raise PreflightError(f"{name} release environment is unavailable") + if service_environment.get(FEEDBACK_EMAIL_ENABLED_KEY) != feedback_enabled: + raise PreflightError(f"rendered submission feedback email flag differs from release: {name}") deadline_key = "WORKSTREAM_ARTIFACT_PREPARATION_TOTAL_DEADLINE_SECONDS" if str(service_environment.get(deadline_key, "")) != values[deadline_key]: raise PreflightError( @@ -2081,6 +2126,10 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None: ) for name, service in services.items(): environment = service.get("environment") or {} + if "WORKSTREAM_RESEND_API_KEY" in environment or ( + RESEND_KEY_FILE in environment and name != FEEDBACK_EMAIL_WORKER + ): + raise PreflightError(f"Resend credential is exposed outside its email worker: {name}") expected_remote = ( { "WORKSTREAM_EXTERNAL_RUNNER_HOST": values["WORKSTREAM_EXTERNAL_RUNNER_HOST"], diff --git a/deploy/hosted/release.env.example b/deploy/hosted/release.env.example index 8552b19a3..b75875358 100644 --- a/deploy/hosted/release.env.example +++ b/deploy/hosted/release.env.example @@ -43,6 +43,11 @@ WORKSTREAM_PAGINATION_CURSOR_HMAC_SECRET_FILE=/etc/workstream/secrets/pagination WORKSTREAM_GITHUB_APP_ID= WORKSTREAM_GITHUB_APP_PRIVATE_KEY_FILE= WORKSTREAM_GITHUB_APP_INSTALLATION_ID= + +# Optional POST quality feedback email. The key file is mounted only on its +# dedicated consumer. Keep both entries at their defaults until qualification. +WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED=false +WORKSTREAM_RESEND_API_KEY_FILE= # Nonempty paths select the matching provider overlay. The selected setup # provider is required; the other provider is optional for approved POST # profiles. Manager-authored setup requires at least one. Leave both blank when diff --git a/deploy/identity/README.md b/deploy/identity/README.md index a7acf60ad..bd8464deb 100644 --- a/deploy/identity/README.md +++ b/deploy/identity/README.md @@ -162,6 +162,18 @@ The confidential MCP client exchanges an MCP token into a short-lived API token for the same subject. Its secret is mounted only into MCP through `WORKSTREAM_MCP_EXCHANGE_SECRET_FILE`; it is not a backend or browser credential. +## Workstream feedback email claim + +Fresh realm configuration includes the `account-email-verified` mapper on the +`workstream-identity` client scope. For an existing realm, add that one mapper +from the rendered `realm_config.py` output to the existing scope through the +authenticated Keycloak administration interface. Preserve the other mappings +and realm settings. The stock user-property mapper reads `emailVerified` as a +boolean `email_verified` access-token claim alongside the existing signed +`email` claim. Verify that a fresh token for a designated verified participant +includes the email and boolean `true` for the Workstream audience. False or +missing mailbox evidence leaves the participant ineligible for feedback email. + ## Participant CLI and direct API access Flow Identity issues API credentials as well as MCP credentials. A participant diff --git a/deploy/identity/realm_config.py b/deploy/identity/realm_config.py index 33347d248..8bfd31cd0 100644 --- a/deploy/identity/realm_config.py +++ b/deploy/identity/realm_config.py @@ -155,6 +155,9 @@ def realm() -> dict: claim_mapper("account-email", "oidc-usermodel-property-mapper", { "user.attribute": "email", "claim.name": "email", "jsonType.label": "String", }), + claim_mapper("account-email-verified", "oidc-usermodel-property-mapper", { + "user.attribute": "emailVerified", "claim.name": "email_verified", "jsonType.label": "boolean", + }), claim_mapper("account-name", "oidc-full-name-mapper", {}), ]) exchange = restricted_client(EXCHANGE_CLIENT) diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md index 1114f2e8f..77e4dbf71 100644 --- a/docs/roadmap_status.md +++ b/docs/roadmap_status.md @@ -106,6 +106,9 @@ refreshes on authorized self-profile GET/PATCH when the token is newer. Workstre CLI and MCP cannot edit email. Optional issuer name seeds first admission; subsequent display-name edits, including clearing it, remain local. Identity and authority remain bound to issuer/subject, not email; signed email is not proof of mailbox verification. +The optional POST quality email uses a signed positive mailbox-verification +claim for the active exact-project contributor and refreshes it through the same +issuer-owned observation. The [single-request submission specification](spec_submission_execution.md) governs [WS-SUBMIT-001](../.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md). The current @@ -712,6 +715,12 @@ are retained through finalization and can be read before resubmission. Existing contribution evidence shows earned awards. Hosted qualification and the separately reviewed sized-award fields remain outside this exposure claim. +PR #708 provides optional email for new governed POST revision returns and +immediate revision-limit rejections. The dedicated outbox consumer uses the +assignment ID and directs the contributor to the existing authorized feedback +read. Hosted email activation and a live provider receipt remain pending. +[Hosted email configuration](../deploy/hosted/README.md#contributor-feedback-email). + ## What Has Been Completed ### Security and platform foundations diff --git a/scripts/test_hosted_release_config.py b/scripts/test_hosted_release_config.py index f1127022c..5eace3b93 100644 --- a/scripts/test_hosted_release_config.py +++ b/scripts/test_hosted_release_config.py @@ -340,6 +340,39 @@ def test_exclusive_submission_workers_have_one_queue_and_separate_credentials(se with self.assertRaisesRegex(preflight.PreflightError, "exclusive worker"): preflight.validate_compose(changed, values) + def test_feedback_email_overlay_restricts_key_and_queue_to_its_worker(self): + disabled = self.app_environment() + rendered = preflight.render_compose(self.environment_path, disabled) + worker = preflight.FEEDBACK_EMAIL_WORKER + self.assertNotIn(worker, rendered["services"]) + with self.assertRaises(preflight.PreflightError): + preflight.validate_environment(disabled | {preflight.FEEDBACK_EMAIL_ENABLED_KEY: "true"}) + values = disabled | { + preflight.FEEDBACK_EMAIL_ENABLED_KEY: "true", + preflight.RESEND_KEY_FILE: str(self.root / "resend-api-key"), + } + self.environment_path.write_text( + "\n".join(f"{name}={value}" for name, value in values.items()) + "\n", encoding="utf-8", + ) + preflight.validate_environment(values) + rendered = preflight.render_compose(self.environment_path, values) + preflight.validate_compose(rendered, values) + services = rendered["services"] + self.assertEqual( + [name for name, item in services.items() + if any(secret.get("source") == "resend_api_key" for secret in item.get("secrets", []))], + [worker], + ) + self.assertIn("--queues=workstream.submission_feedback_email", services[worker]["command"]) + changed = copy.deepcopy(rendered) + changed["services"][worker]["command"].append("--queues=workstream.outbox") + with self.assertRaisesRegex(preflight.PreflightError, "exclusive worker"): + preflight.validate_compose(changed, values) + changed = copy.deepcopy(rendered) + changed["services"]["outbox-scan-worker"]["environment"][preflight.RESEND_KEY_FILE] = "/run/secrets/resend_api_key" + with self.assertRaisesRegex(preflight.PreflightError, "unrelated secret selector"): + preflight.validate_compose(changed, values) + def test_image_owned_profile_validation_is_fixed_and_fail_closed(self): completed = subprocess.CompletedProcess([], 0) with patch.object(preflight.subprocess, "run", return_value=completed) as run: diff --git a/scripts/test_keycloak_configuration.py b/scripts/test_keycloak_configuration.py index 6a86e2e6f..f0b2b17cf 100644 --- a/scripts/test_keycloak_configuration.py +++ b/scripts/test_keycloak_configuration.py @@ -224,6 +224,11 @@ def test_profile_claims_are_on_access_tokens_without_hardcoded_human(self): mappers = {m["name"]: m for m in scope["protocolMappers"]} self.assertEqual(mappers["account-email"]["config"]["user.attribute"], "email") self.assertEqual(mappers["account-email"]["config"]["claim.name"], "email") + verification = mappers["account-email-verified"] + self.assertEqual(verification["protocolMapper"], "oidc-usermodel-property-mapper") + self.assertEqual(verification["config"]["user.attribute"], "emailVerified") + self.assertEqual(verification["config"]["claim.name"], "email_verified") + self.assertEqual(verification["config"]["jsonType.label"], "boolean") self.assertEqual(mappers["subject-kind"]["protocolMapper"], "oidc-usermodel-attribute-mapper") for mapper in mappers.values(): self.assertEqual(mapper["config"]["access.token.claim"], "true") From 224493ca2cf909b9097b578ce2da23e06335c207 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:32:58 +0100 Subject: [PATCH 405/513] fix(submission): fence verified email updates and recover uncertain sends --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++ .env.example | 7 ++ .../0093_verified_email_observation.py | 14 +++- backend/app/adapters/outbox/__init__.py | 2 +- .../app/adapters/submission_feedback_email.py | 28 +------- backend/app/adapters/tasks/__init__.py | 29 ++++++++ backend/app/modules/actors/service.py | 7 +- .../post_submit_routing/feedback_email.py | 4 +- backend/scripts/test_lane_catalogue.py | 1 + backend/tests/actors/test_issuer_profile.py | 14 ++-- backend/tests/conftest.py | 2 +- .../test_feedback_email.py | 25 +++++-- deploy/hosted/README.md | 6 +- docker-compose.submission-feedback-email.yml | 67 +++++++++++++++++++ docker-compose.yml | 1 + docs/architecture_data_model.md | 13 ++-- docs/engineering/local-pilot.md | 26 +++++++ .../run_public_journey_probe.py | 4 ++ scripts/test_local_guide_runtime.py | 31 +++++++++ 19 files changed, 234 insertions(+), 56 deletions(-) create mode 100644 docker-compose.submission-feedback-email.yml diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e3191db76..d10a76891 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11782,6 +11782,15 @@ Email delivery is disabled by default. Use a stable event-derived Resend key and a retry lifetime shorter than the provider's idempotency window. The email identifies the assignment and gives the existing client command without a link. +The existing email observation watermark advances on newer signed observations, +including omitted addresses. Omission preserves the retained contact value and +clears delivery eligibility. Only a positive boolean claim for the observed +address can make it eligible. Migration 0093 adds the false-by-default proof +bit and extends the existing closed SQL unknown-retry guard for the one email +event version. The dedicated consumer only changes outbox delivery state. Hosted +and local Compose mount the sending key only on this consumer. The native +submission drill explicitly disables email for its fixture participants. + Prohibited changes: PRE and human review behavior, product outcomes, awards, provider credentials in source, public recipient overrides, plaintext mailbox data in outbox payloads, private check evidence in email, new frontend work, diff --git a/.env.example b/.env.example index 44307c486..8c0ba61cb 100644 --- a/.env.example +++ b/.env.example @@ -35,3 +35,10 @@ WORKSTREAM_CELERY_WORKER_CONCURRENCY=2 # Required only when enabling the separate submission-intake worker profile. # Supply a qualified positive value; no deployment default is selected. WORKSTREAM_SUBMISSION_FINALIZATION_CONCURRENCY= + +# Optional local feedback email uses the external Flow issuer and a verified +# sending key file. Leave disabled for the ordinary HMAC pilot. +WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED=false +WORKSTREAM_RESEND_API_KEY_FILE= +WORKSTREAM_TOKEN_ISSUER= +WORKSTREAM_TOKEN_JWKS_URL= diff --git a/backend/alembic/versions/0093_verified_email_observation.py b/backend/alembic/versions/0093_verified_email_observation.py index 811cd239a..75f17a976 100644 --- a/backend/alembic/versions/0093_verified_email_observation.py +++ b/backend/alembic/versions/0093_verified_email_observation.py @@ -1,4 +1,4 @@ -"""Require a fresh signed mailbox verification observation for email delivery.""" +"""Persist verified mailbox proof and allow bounded recovery of feedback email.""" from alembic import op import sqlalchemy as sa @@ -13,11 +13,21 @@ def upgrade() -> None: """Treat all historical signed mailbox addresses as unverified.""" op.add_column("actor_identity_links", sa.Column( "email_verified", sa.Boolean(), nullable=False, server_default=sa.false(), - )) + ), schema="public") op.create_check_constraint( "ck_actor_identity_links_email_verified_observation", "actor_identity_links", "not email_verified or (subject_kind = 'human' and email_observed_issued_at is not null)", + schema="public", ) + op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp") + op.execute("LOCK TABLE public.outbox_events IN SHARE ROW EXCLUSIVE MODE") + body = op.get_bind().execute(sa.text( + "SELECT pg_catalog.pg_get_functiondef('public.check_outbox_delivery_projection()'::regprocedure)" + )).scalar_one() + old = "'TaskRevisionExpired','SubmissionFinalizationRequested','SubmissionFinalizationRecoveryRequested')" + if body.count(old) != 1: + raise RuntimeError("feedback email retry predecessor shape changed") + op.execute(body.replace(old, old[:-1] + ",'SubmissionFeedbackEmailRequested')")) def downgrade() -> None: diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py index ed7616c43..2185aecc1 100644 --- a/backend/app/adapters/outbox/__init__.py +++ b/backend/app/adapters/outbox/__init__.py @@ -69,6 +69,7 @@ def production_outbox_delivery( TransactionalTaskRevisionExhaustedNoticeHandler, evaluation_completion_handler, evaluation_request_handler, + submission_feedback_email_handler, ) from app.adapters.checkers import post_submit_delivery_reconciliation_handler from app.modules.checkers.api.delivery_reconciliation import ( @@ -84,7 +85,6 @@ def production_outbox_delivery( from app.modules.tasks.api.revision_expiry import ( REVISION_EXPIRY_EVENT, REVISION_EXPIRED_EVENT, REVISION_CONTEXT_BLOCKED_EVENT, ) - from app.adapters.submission_feedback_email import submission_feedback_email_handler from app.core.config import get_settings from app.modules.tasks.api.routing_outcome import SUBMISSION_FEEDBACK_EMAIL_EVENT diff --git a/backend/app/adapters/submission_feedback_email.py b/backend/app/adapters/submission_feedback_email.py index 12b1e410e..eae7d2d6a 100644 --- a/backend/app/adapters/submission_feedback_email.py +++ b/backend/app/adapters/submission_feedback_email.py @@ -20,7 +20,6 @@ RESEND_PROVIDER, SUBMISSION_FEEDBACK_EMAIL_CAPABILITY, SubmissionFeedbackEmail, SubmissionFeedbackEmailAdapter, is_single_mailbox, ) -from app.modules.outbox.api import HandlerOutcome _IDENTITY = ExternalServiceAdapterIdentity(SUBMISSION_FEEDBACK_EMAIL_CAPABILITY, RESEND_PROVIDER) _KEY = re.compile(rb"re_[A-Za-z0-9_-]{1,256}") @@ -128,31 +127,6 @@ def build() -> SubmissionFeedbackEmailAdapter: def validate_submission_feedback_email_worker(settings: Settings) -> None: """Require an explicitly enabled verified issuer and readable sending key at startup.""" if (not settings.submission_feedback_email_enabled or settings.auth_provider != "flow" - or settings.flow_auth_local_hmac_secret is not None or settings.token_issuer is None): + or settings.flow_auth_local_hmac_secret or not settings.token_issuer): raise ExternalServiceConfigurationError(_IDENTITY) submission_feedback_email_factory(settings).create(RESEND_PROVIDER) - - -def submission_feedback_email_handler(sessions, *, observer, settings: Settings): - """Register without loading a key on the worker that discovers pending events.""" - from app.adapters.actors import verified_notification_email - from app.adapters.auth import has_submission_feedback_recipient_grant - from app.modules.tasks.post_submit_routing.feedback_email import TaskSubmissionFeedbackEmailHandler - - issuer = settings.token_issuer - - async def recipient(session, project_id, actor_id): - if issuer is None or not await has_submission_feedback_recipient_grant(session, project_id, actor_id): - return None - return await verified_notification_email(session, actor_id, issuer) - - async def handle(envelope): - try: - adapter = submission_feedback_email_factory(settings).create(RESEND_PROVIDER) - except ExternalServiceConfigurationError: - return HandlerOutcome.REJECT - return await TaskSubmissionFeedbackEmailHandler( - sessions, observer=observer, recipient=recipient, adapter=adapter, - )(envelope) - - return handle diff --git a/backend/app/adapters/tasks/__init__.py b/backend/app/adapters/tasks/__init__.py index 2fc88fcb6..03a4675ee 100644 --- a/backend/app/adapters/tasks/__init__.py +++ b/backend/app/adapters/tasks/__init__.py @@ -608,6 +608,35 @@ def evaluation_completion_handler(*, sessions): ) +def submission_feedback_email_handler(sessions, *, observer, settings: Settings): + """Compose TASK's email handler without loading a key on the outbox scanner.""" + from workstream_external_services import ExternalServiceConfigurationError + + from app.adapters.actors import verified_notification_email + from app.adapters.auth import has_submission_feedback_recipient_grant + from app.adapters.submission_feedback_email import submission_feedback_email_factory + from app.interfaces.submission_feedback_email import RESEND_PROVIDER + from app.modules.tasks.post_submit_routing.feedback_email import TaskSubmissionFeedbackEmailHandler + + issuer = settings.token_issuer + + async def recipient(session, project_id, actor_id): + if issuer is None or not await has_submission_feedback_recipient_grant(session, project_id, actor_id): + return None + return await verified_notification_email(session, actor_id, issuer) + + async def handle(envelope): + try: + adapter = submission_feedback_email_factory(settings).create(RESEND_PROVIDER) + except ExternalServiceConfigurationError: + return HandlerOutcome.REJECT + return await TaskSubmissionFeedbackEmailHandler( + sessions, observer=observer, recipient=recipient, adapter=adapter, + )(envelope) + + return handle + + def contribution_task_evidence_port(session): """Read exact selected source labels without claims, activation or task mutation.""" from app.modules.tasks.contribution_evidence import ContributionTaskEvidenceRepository diff --git a/backend/app/modules/actors/service.py b/backend/app/modules/actors/service.py index 84993de15..409160a9c 100644 --- a/backend/app/modules/actors/service.py +++ b/backend/app/modules/actors/service.py @@ -179,7 +179,7 @@ async def resolve_verified_actor( subject_kind="human", status="active", linked_by=profile_id, - email_observed_issued_at=token.issued_at if token.email is not None else None, + email_observed_issued_at=token.issued_at, email_verified=token.email is not None and token.email_verified, last_verified_at=func.clock_timestamp(), ) @@ -295,10 +295,7 @@ async def synchronize_identity_email( self._require_active_human(profile) if token.issuer != link.issuer or token.subject != link.subject: raise RuntimeError("verified identity does not match resolved actor") - if (token.email is not None or link.email_verified) and ( - link.email_observed_issued_at is None - or token.issued_at > link.email_observed_issued_at - ): + if link.email_observed_issued_at is None or token.issued_at > link.email_observed_issued_at: if token.email is not None: profile.contact_email = token.email link.email_verified = token.email is not None and token.email_verified diff --git a/backend/app/modules/tasks/post_submit_routing/feedback_email.py b/backend/app/modules/tasks/post_submit_routing/feedback_email.py index 67a83782b..b0e56ec46 100644 --- a/backend/app/modules/tasks/post_submit_routing/feedback_email.py +++ b/backend/app/modules/tasks/post_submit_routing/feedback_email.py @@ -118,7 +118,7 @@ def _message( event_id: UUID, manifest: TaskPostSubmitRoutingManifest, outcome: FeedbackOutcome, recipient: str, ) -> SubmissionFeedbackEmail: if outcome == "needs_revision": - subject = "Action required: Workstream submission feedback available" + subject = "Action required for your Workstream assignment" status = (f"Workstream assignment {manifest.assignment_id} needs revision. " "Review the feedback, fix your submission and resubmit when the assignment allows it.") else: @@ -128,5 +128,5 @@ def _message( hint = f"workstream task status {manifest.assignment_id}" return SubmissionFeedbackEmail(event_id, recipient, subject, ( f"{status}\n\nRead your assignment feedback in Workstream using the API, CLI or MCP.\n\n" - f"CLI: {hint}\n" + f"CLI command\n{hint}\n" )) diff --git a/backend/scripts/test_lane_catalogue.py b/backend/scripts/test_lane_catalogue.py index 8a4e48a18..b93baf688 100644 --- a/backend/scripts/test_lane_catalogue.py +++ b/backend/scripts/test_lane_catalogue.py @@ -617,6 +617,7 @@ class TestLane: "tests/tasks/post_submit_routing/test_remediation_storage.py", "tests/tasks/post_submit_routing/test_remediation_currentness.py", "tests/tasks/post_submit_routing/test_remediation_migration.py", + "tests/tasks/post_submit_routing/test_feedback_email.py", # Stored attempt-outcome proofs use TASK custody; every project lane runs # within measured variance of the hosted execution deadline. "tests/tasks/post_submit_routing/test_attempt_outcome_custody.py", diff --git a/backend/tests/actors/test_issuer_profile.py b/backend/tests/actors/test_issuer_profile.py index 6ed61ee98..0f7d132bb 100644 --- a/backend/tests/actors/test_issuer_profile.py +++ b/backend/tests/actors/test_issuer_profile.py @@ -67,23 +67,25 @@ def headers(email, tick, *, subject="email-owner", name="Issuer Name"): assert read.json()["contact_email"] == "second@example.test" assert read.json()["display_name"] == display_name assert read.json()["actor_profile_id"] == actor_id - changed = await client.get("/api/v1/actors/me", headers=headers("third@example.test", issued + 3)) + older = await client.get("/api/v1/actors/me", headers=headers("stale@example.test", issued + 3)) + assert older.json()["contact_email"] == "second@example.test" + changed = await client.get("/api/v1/actors/me", headers=headers("third@example.test", issued + 11)) assert changed.json()["contact_email"] == "third@example.test" assert changed.json()["actor_profile_id"] == actor_id for body in ({"contact_email": "forged@example.test"}, {"contact_email": None}, {"display_name": "Must not persist", "contact_email": "forged@example.test"}): - denied = await client.patch("/api/v1/actors/me", headers=headers("third@example.test", issued + 3), json=body) + denied = await client.patch("/api/v1/actors/me", headers=headers("third@example.test", issued + 11), json=body) assert denied.status_code == 422, denied.text other = await client.get("/api/v1/actors/me", headers=headers("third@example.test", issued + 4, subject="other-owner")) assert other.status_code == 200, other.text assert other.json()["actor_profile_id"] != actor_id - retained = await client.get("/api/v1/actors/me", headers=headers("third@example.test", issued + 3)) + retained = await client.get("/api/v1/actors/me", headers=headers("third@example.test", issued + 11)) assert retained.json()["display_name"] is None assert retained.json()["admin_roles"] == first.json()["admin_roles"] == [] async with db_session.get_session_factory()() as session: link = await session.scalar(select(ActorIdentityLink).where(ActorIdentityLink.actor_profile_id == actor_id)) assert link.subject == "email-owner" - assert link.email_observed_issued_at == issued + 3 + assert link.email_observed_issued_at == issued + 11 async def test_notification_recipient_follows_exact_signed_mailbox_verification( @@ -124,7 +126,9 @@ async def observe(client, *, tick, email, proof): (4, corrected, True, corrected), (5, None, None, None), (4, corrected, True, None), - (6, corrected, True, corrected), + (7, None, None, None), + (6, corrected, True, None), + (8, corrected, True, corrected), ) for tick, email, proof, expected in phases: assert await observe(client, tick=tick, email=email, proof=proof) == (actor, expected) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 2447172a9..9d44508a7 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "03192dcee654b3e4322b2ed1bbbb7b45293008a156df7bbe750c1de2a26b6b7e" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "8ccae4095de9e13c5f0f3549d18010809e2f0d80ad3ea29a346d20248cb32073" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/tasks/post_submit_routing/test_feedback_email.py b/backend/tests/tasks/post_submit_routing/test_feedback_email.py index 787e74aca..18dc168f0 100644 --- a/backend/tests/tasks/post_submit_routing/test_feedback_email.py +++ b/backend/tests/tasks/post_submit_routing/test_feedback_email.py @@ -111,7 +111,7 @@ async def _email_events(factory): ))) -@pytest.mark.parametrize("case", ["retry", "stale", "unverified", "exhausted", "coverage", "disabled"]) +@pytest.mark.parametrize("case", ["retry", "unknown", "stale", "unverified", "exhausted", "coverage", "disabled"]) async def test_only_committed_current_quality_routes_send( tmp_path, isolated_database_env, monkeypatch, case, ): @@ -176,13 +176,26 @@ async def server(request): post = production_outbox_delivery(h.factory, worker_group="post") assert await post.deliver(event.event_id, UUID(event.project_id), "wrong-queue", registered_only=True) is None assert await delivery.deliver(event.event_id, new_record_id(), "wrong-project", registered_only=True) is None - if case == "retry": + if case in {"retry", "unknown"}: delivery._event_options = { - (SUBMISSION_FEEDBACK_EMAIL_EVENT, 1): DeliveryOptions(retry_base_seconds=1), + (SUBMISSION_FEEDBACK_EMAIL_EVENT, 1): DeliveryOptions( + lease_seconds=6, handler_timeout_seconds=4, retry_base_seconds=1, + ), } - receipt = await delivery.deliver(event.event_id, UUID(event.project_id), "email-worker", registered_only=True) + if case == "unknown": + claim = await delivery.claim(event.event_id, UUID(event.project_id), "pre-crash-worker") + envelope = await delivery._begin_invocation(claim) + handler = delivery._registry.get(SUBMISSION_FEEDBACK_EMAIL_EVENT, 1) + assert await handler(envelope) is HandlerOutcome.ACKNOWLEDGE + assert len(calls) == 1 + # Commit of invocation survived the lost worker. The provider receipt did not. + await asyncio.sleep(6.05) + receipt = await delivery.recover(event.event_id, UUID(event.project_id)) + assert json.loads(receipt.outcome_json)["invocation_unknown"] is True + else: + receipt = await delivery.deliver(event.event_id, UUID(event.project_id), "email-worker", registered_only=True) assert receipt is not None - if case == "retry": + if case in {"retry", "unknown"}: assert json.loads(receipt.outcome_json)["delivery_state"] == "retryable" await asyncio.sleep(1.05) receipt = await delivery.deliver(event.event_id, UUID(event.project_id), "email-worker", registered_only=True) @@ -191,7 +204,7 @@ async def server(request): if case in {"stale", "unverified"}: assert calls == [] else: - assert len(calls) == (2 if case == "retry" else 1) + assert len(calls) == (2 if case in {"retry", "unknown"} else 1) assert len(set(key for key, _ in calls)) == 1 assert all(body == calls[0][1] for _, body in calls) body = calls[0][1] diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md index d3b529178..4d9652e67 100644 --- a/deploy/hosted/README.md +++ b/deploy/hosted/README.md @@ -322,12 +322,14 @@ ID and the same authorized assignment status and feedback read available in the API, CLI and MCP. The assignment read remains the source of feedback and revision terms. Workstream continues processing assignments if email fails. -Temporary Resend errors and uncertain HTTP outcomes retry through the shared +Temporary Resend errors and uncertain transport outcomes retry through the shared outbox using a stable event key and an absolute 12-hour send cutoff. Outbox acknowledgement records a handled request, including suppression if the assignment no longer needs its alert or the recipient is ineligible. Resend acceptance acknowledges the request, and inbox delivery has separate provider -status. [Resend's 24-hour idempotency window](https://resend.com/docs/dashboard/emails/idempotency-keys). +status. If the verified address changes after an uncertain send, Resend can +reject the changed payload under that key. The outbox records the rejection +and never replaces the key. [Resend's 24-hour idempotency window](https://resend.com/docs/dashboard/emails/idempotency-keys). ## Validate without disclosure diff --git a/docker-compose.submission-feedback-email.yml b/docker-compose.submission-feedback-email.yml new file mode 100644 index 000000000..b648717a3 --- /dev/null +++ b/docker-compose.submission-feedback-email.yml @@ -0,0 +1,67 @@ +services: + backend: + environment: + WORKSTREAM_FLOW_AUTH_LOCAL_HMAC_SECRET: "" + WORKSTREAM_TOKEN_ISSUER: ${WORKSTREAM_TOKEN_ISSUER:?set the external Flow issuer} + WORKSTREAM_TOKEN_AUDIENCE: ${WORKSTREAM_TOKEN_AUDIENCE:-workstream-api} + WORKSTREAM_TOKEN_JWKS_URL: ${WORKSTREAM_TOKEN_JWKS_URL:?set the external Flow JWKS URL} + WORKSTREAM_TOKEN_ALGORITHMS: RS256 + WORKSTREAM_TOKEN_INTROSPECTION_MODE: disabled + WORKSTREAM_TOKEN_INTROSPECTION_DISABLED_REASON: Flow issues short-lived Workstream access tokens + + submission-feedback-email-worker: + profiles: [submission-feedback-email] + image: ${COMPOSE_PROJECT_NAME}-backend:local + pull_policy: never + init: true + user: "${LOCAL_UID:-1000}:${LOCAL_GID:-1000}" + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + tmpfs: + - /tmp:mode=0700,uid=${LOCAL_UID:-1000},gid=${LOCAL_GID:-1000} + environment: + WORKSTREAM_ENVIRONMENT: local + WORKSTREAM_AUTH_PROVIDER: flow + WORKSTREAM_DATABASE_URL: ${WORKSTREAM_DATABASE_URL:?set WORKSTREAM_DATABASE_URL in .env} + WORKSTREAM_CELERY_BROKER_URL: redis://redis:6379/0 + WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED: ${WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED:-false} + WORKSTREAM_TOKEN_ISSUER: ${WORKSTREAM_TOKEN_ISSUER:?set the external Flow issuer} + WORKSTREAM_RESEND_API_KEY_FILE: /run/secrets/resend_api_key + volumes: + - ./backend:/workspace/backend:ro + secrets: + - source: resend_api_key + target: resend_api_key + uid: "${LOCAL_UID:-1000}" + gid: "${LOCAL_GID:-1000}" + mode: 0400 + command: + - python + - -m + - celery + - -A + - app.workers.celery_app + - worker + - --pool=prefork + - --concurrency=1 + - --hostname=submission-feedback-email@%h + - --queues=workstream.submission_feedback_email + - --pidfile=/tmp/celery-submission-feedback-email.pid + - --loglevel=INFO + depends_on: + backend: + condition: service_healthy + redis: + condition: service_healthy + stop_grace_period: 120s + healthcheck: + test: [CMD-SHELL, "test -s /tmp/celery-submission-feedback-email.pid && kill -0 $$(cat /tmp/celery-submission-feedback-email.pid)"] + interval: 10s + timeout: 8s + retries: 12 + start_period: 20s + +secrets: + resend_api_key: + file: ${WORKSTREAM_RESEND_API_KEY_FILE:?set the private Resend API key file} diff --git a/docker-compose.yml b/docker-compose.yml index 775206034..5063acbc9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -43,6 +43,7 @@ x-backend-runtime: &backend-runtime WORKSTREAM_PROJECT_AGENT_MODEL_API: ${WORKSTREAM_PROJECT_AGENT_MODEL_API:-chat_completions} WORKSTREAM_PROJECT_AGENT_MODEL: ${WORKSTREAM_PROJECT_AGENT_MODEL:-openai/gpt-5.6-terra} WORKSTREAM_PROJECT_AGENT_RUNTIME_OPTIONS: ${WORKSTREAM_PROJECT_AGENT_RUNTIME_OPTIONS:?set WORKSTREAM_PROJECT_AGENT_RUNTIME_OPTIONS to a JSON object} + WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED: ${WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED:-false} volumes: - ./backend:/workspace/backend - workstream_scratch_data:/workspace/scratch diff --git a/docs/architecture_data_model.md b/docs/architecture_data_model.md index c52b2fe2f..9e235089f 100644 --- a/docs/architecture_data_model.md +++ b/docs/architecture_data_model.md @@ -107,11 +107,14 @@ link revoke/reactivate mutations. Append-only audit evidence preserves immutable transition history; the current row carries only the latest state-compatible attribution. Raw tokens, provider credentials, and full claim payloads are not stored. `email_observed_issued_at` records the newest signed email observation for this -exact link. Authorized self-profile reads/updates replace `contact_email` only -from a strictly later-issued token with an email claim; absence/null and older -or equal-issued tokens leave the retained value unchanged. This metadata grants -no authority and does not verify mailbox ownership. The optional issuer name -seeds first admission only; later display-name edits remain local. +exact link, including an absent email claim. A later authorized self-profile +observation can update `contact_email` when the token contains an address. +An absent address preserves the retained contact value and clears delivery +eligibility. `email_verified` is true only for an exact issuer-signed positive +mailbox observation. Conflicting same-time proof also clears eligibility until +a newer observation. Account authority remains bound to the issuer and subject. +The optional issuer name seeds first admission. Later display-name edits remain +local. The database enforces a unique `(issuer, subject)` pair across all links and, in v0.1, at most one active identity link per ActorProfile. Revocation preserves the immutable link and provenance; it does not free the pair for rebinding. diff --git a/docs/engineering/local-pilot.md b/docs/engineering/local-pilot.md index 4fb96bbe8..9c03ab6d8 100644 --- a/docs/engineering/local-pilot.md +++ b/docs/engineering/local-pilot.md @@ -88,6 +88,32 @@ docker compose --profile backend run --rm --no-deps -e WORKSTREAM_ARTIFACT_STORE 'from app.adapters.artifacts import create_artifact_store_bootstrap; from app.core.config import get_settings; settings = get_settings(); create_artifact_store_bootstrap(settings)' ``` +## Configure optional contributor email + +The ordinary local pilot keeps POST feedback email disabled. To qualify email +using designated test accounts, use the submission feedback overlay with a +trusted external Flow issuer. Set `WORKSTREAM_TOKEN_ISSUER` and +`WORKSTREAM_TOKEN_JWKS_URL` for that issuer. The overlay configures the API to +use issuer-signed RS256 access tokens. It delivers through a dedicated consumer +and uses the same mailbox claim and verified sender as hosted Workstream. +[Hosted email configuration](../../deploy/hosted/README.md#contributor-feedback-email). + +Set `WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED=true` and give +`WORKSTREAM_RESEND_API_KEY_FILE` the private absolute key path. The file must +be owned by `LOCAL_UID`/`LOCAL_GID` with `0400` permissions. Start the ordinary +local submission configuration with the extra Compose file and profile. + +```bash +docker compose -f docker-compose.yml -f docker-compose.submission-feedback-email.yml \ + --profile backend --profile submission-intake --profile submission-feedback-email \ + up --build --wait +``` + +Use the same files and profiles to inspect and stop the run. The email consumer +receives only its database connection, broker connection, issuer selection and +private sending key. Use the [local agent loop overlay](local-agent-loop.md) +to add the runner and project-specific PRE/POST execution for a complete drill. + ## Create distinct identities and grant authority The helper signs short-lived tokens using the exact local Flow-HMAC settings diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index a212cf74f..3d70e464c 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -1274,6 +1274,7 @@ async def run(database_url: str, image_reference: str, node_config: Path, "WORKSTREAM_CELERY_BROKER_URL": broker_url, "WORKSTREAM_CELERY_RESULT_BACKEND_URL": broker_url, "WORKSTREAM_CELERY_TASK_ALWAYS_EAGER": "false", + "WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED": "false", "WORKSTREAM_ARTIFACT_PENDING_WORK_SCAN_INTERVAL_SECONDS": "10", "WORKSTREAM_ARTIFACT_SCRATCH_ROOT": str(scratch), "WORKSTREAM_ARTIFACT_SCRATCH_MINIMUM_FREE_BYTES": "0", @@ -1285,6 +1286,9 @@ async def run(database_url: str, image_reference: str, node_config: Path, if recorded_assistance: configure_scripted_model_session_environment(env) env.pop("OPENAI_API_KEY", None) + # Native workload checks use qualified fixture actors, without email effects. + env.pop("WORKSTREAM_RESEND_API_KEY_FILE", None) + os.environ.pop("WORKSTREAM_RESEND_API_KEY_FILE", None) if clients is not None: env = clients.setup_authority(env) os.environ.pop("WORKSTREAM_FLOW_AUTH_LOCAL_HMAC_SECRET", None) diff --git a/scripts/test_local_guide_runtime.py b/scripts/test_local_guide_runtime.py index 224afde89..e29129941 100644 --- a/scripts/test_local_guide_runtime.py +++ b/scripts/test_local_guide_runtime.py @@ -113,6 +113,37 @@ def test_worker_receives_readonly_parser_socket(self): self.assertIn("guide_parser_socket:/var/lib/workstream/guide-runtime:ro", worker["volumes"]) self.assertEqual(worker["depends_on"]["guide-document-parser"]["condition"], "service_healthy") + def test_feedback_email_is_opt_in_and_key_is_dedicated(self): + command = ["docker", "compose", "--env-file", ".env.example", "-f", "docker-compose.yml"] + environment = { + key: value for key, value in os.environ.items() + if not key.startswith(("WORKSTREAM_", "COMPOSE_")) + } + disabled = subprocess.run( + [*command, "--profile", "backend", "config", "--format", "json"], + cwd=ROOT, env=environment, capture_output=True, text=True, check=True, + ) + worker = "submission-feedback-email-worker" + self.assertNotIn(worker, json.loads(disabled.stdout)["services"]) + environment.update({ + "WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED": "true", + "WORKSTREAM_TOKEN_ISSUER": "https://issuer.example.test/realms/flow", + "WORKSTREAM_TOKEN_JWKS_URL": "https://issuer.example.test/realms/flow/certs", + "WORKSTREAM_RESEND_API_KEY_FILE": "/private/test-resend-key", + }) + configured = subprocess.run( + [*command, "-f", "docker-compose.submission-feedback-email.yml", "--profile", "backend", + "--profile", "submission-feedback-email", "config", "--format", "json"], + cwd=ROOT, env=environment, capture_output=True, text=True, check=True, + ) + services = json.loads(configured.stdout)["services"] + self.assertEqual(services["backend"]["environment"]["WORKSTREAM_FLOW_AUTH_LOCAL_HMAC_SECRET"], "") + self.assertIn("--queues=workstream.submission_feedback_email", services[worker]["command"]) + self.assertEqual([name for name, service in services.items() + if service.get("secrets")], [worker]) + self.assertEqual(services[worker]["secrets"][0]["source"], "resend_api_key") + self.assertNotIn("WORKSTREAM_ARTIFACT_S3_SECRET_ACCESS_KEY", services[worker]["environment"]) + def test_finalization_consumer_requires_explicit_positive_capacity(self): service = self.services["submission-finalizer"] self.assertEqual(service["profiles"], ["submission-intake"]) From cab8feb0854fd3a20ec226166b391a907e5726d0 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:35:51 +0100 Subject: [PATCH 406/513] test: observe the native duplicate delivery result explicitly --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ .../run_public_journey_probe.py | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d10a76891..3495004f5 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11805,3 +11805,18 @@ transport status mapping, bounded delivery, and queue isolation. Focused security, architecture, QA and operating documentation review are required. Human review focuses on verified recipient evidence, email wording and the configured authenticated feedback destination before activation. + + +### Paired native duplicate-result observation repair + +Source `e9381afa5` passed provider-free guide setup, both PRE quality rejection +paths, accepted/finalized v1, POST needs_revision, correction under the same +assignment and finalized v2 reaching review_pending. The run then failed its +duplicate-delivery observer; automatic acceptance was not reached. Isolated +cleanup completed (`/tmp/workstream-paired-native-qqq7n4s1/cleanup.json`). +The production Celery app intentionally ignores task results. Celery +`AsyncResult.get()` returns immediately with None for an ignored result, so +the probe was not observing the duplicate worker result despite configuring +a result backend. The local probe now explicitly requests a result for this +one duplicate publication. Production task defaults and the exact duplicate +refusal/custody assertions remain unchanged. A connected rerun remains required. diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 3d70e464c..2b0f6aae1 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -1133,7 +1133,7 @@ async def fail_post_launch(): duplicate_task_id = duplicate_receipt['task_id'] else: duplicate = await asyncio.to_thread(deliver_event.apply_async, - args=(str(completion_id), project_id)) + args=(str(completion_id), project_id), ignore_result=False) duplicate_task_id = duplicate.id try: duplicate_result = await asyncio.to_thread( From f480146ca248c6a1d8c622af1fcd316f4024f656 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:38:40 +0100 Subject: [PATCH 407/513] test(submission): pin exact feedback email schema and rollback proof --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 16 +++++++++++++++- .../versions/0093_verified_email_observation.py | 2 +- backend/tests/conftest.py | 2 +- .../post_submit_routing/test_feedback_email.py | 6 +++++- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3495004f5..b0091b007 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11804,7 +11804,7 @@ rollback, replay and retry, stale or foreign source and recipient refusal, transport status mapping, bounded delivery, and queue isolation. Focused security, architecture, QA and operating documentation review are required. Human review focuses on verified recipient evidence, email wording and the -configured authenticated feedback destination before activation. +authenticated assignment read before activation. ### Paired native duplicate-result observation repair @@ -11820,3 +11820,17 @@ the probe was not observing the duplicate worker result despite configuring a result backend. The local probe now explicitly requests a result for this one duplicate publication. Production task defaults and the exact duplicate refusal/custody assertions remain unchanged. A connected rerun remains required. + +The PostgreSQL 16 catalog comparison for migration 0093 reversed only the +new mailbox column and check plus the exact email event in the existing +outbox retry function, inside an isolated rolled-back transaction. This +recovered the established 0092 fingerprint `03192dcee654b3e4322b2ed1bbbb7b45293008a156df7bbe750c1de2a26b6b7e`. +The current schema uses the ORM's exact check name and fingerprint +`3e045ec0e2fe6f0b14b19ea1404f4500b1cde5d440c1a7ddd76d90bab1ffed0b`. +Hosted release and Keycloak tests passed 80 cases, including opt-in key and +consumer isolation. The local Compose overlay rendered with that same key and +queue isolation. The architecture and authorization boundary suite passed 56 +cases after moving the handler composition to the TASK adapter root. The fake +HTTP tests passed 10 cases including expiry, provider errors and redirect +refusal. Live delivery still depends on the verified sender, the secret file +and a designated verified recipient. diff --git a/backend/alembic/versions/0093_verified_email_observation.py b/backend/alembic/versions/0093_verified_email_observation.py index 75f17a976..afecfe6ae 100644 --- a/backend/alembic/versions/0093_verified_email_observation.py +++ b/backend/alembic/versions/0093_verified_email_observation.py @@ -15,7 +15,7 @@ def upgrade() -> None: "email_verified", sa.Boolean(), nullable=False, server_default=sa.false(), ), schema="public") op.create_check_constraint( - "ck_actor_identity_links_email_verified_observation", "actor_identity_links", + op.f("ck_actor_identity_links_email_verified_observation"), "actor_identity_links", "not email_verified or (subject_kind = 'human' and email_observed_issued_at is not null)", schema="public", ) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 9d44508a7..1adcedd5c 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -23,7 +23,7 @@ DDL_LOCK_DIRECTORY = Path("/tmp") # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering # differs across major versions; regenerate only after comparing actual objects. -EXPECTED_PUBLIC_SCHEMA_SHA256 = "8ccae4095de9e13c5f0f3549d18010809e2f0d80ad3ea29a346d20248cb32073" +EXPECTED_PUBLIC_SCHEMA_SHA256 = "3e045ec0e2fe6f0b14b19ea1404f4500b1cde5d440c1a7ddd76d90bab1ffed0b" PROTECTED_TEST_TABLES = ( "actor_profile_migration_state", "alembic_version", diff --git a/backend/tests/tasks/post_submit_routing/test_feedback_email.py b/backend/tests/tasks/post_submit_routing/test_feedback_email.py index 18dc168f0..229bc768f 100644 --- a/backend/tests/tasks/post_submit_routing/test_feedback_email.py +++ b/backend/tests/tasks/post_submit_routing/test_feedback_email.py @@ -70,7 +70,10 @@ async def server(request): "from": "Workstream ", "to": ["verified@example.test"], "subject": "Assignment needs revision", "text": "Read feedback.", } - return _response(status, **body) + response = _response(status, **body) + if status == 307: + response.headers["Location"] = "https://untrusted.example.test/emails" + return response settings = Settings(environment="test", resend_api_key_file=_private_key(tmp_path)) adapter = email_adapter.submission_feedback_email_factory( @@ -147,6 +150,7 @@ async def server(request): )) if case == "retry": async with h.factory() as session: + await session.begin() await task_post_submit_outcome(session, h.factory).apply(h.envelope, current_generation=None) assert await _email_events(h.factory) == () await session.rollback() From 72e71a79260a96751b7653395beba4eb59ddd4e7 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 12:01:14 +0100 Subject: [PATCH 408/513] test: verify release bytecode against retained Python source --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 14 +++++++ scripts/test_hosted_release_images.py | 33 ++++++++++++++++ scripts/verify_hosted_release_images.py | 38 +++++++++++++++++++ 3 files changed, 85 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index b0091b007..f49a9f77c 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11834,3 +11834,17 @@ cases after moving the handler composition to the TASK adapter root. The fake HTTP tests passed 10 cases including expiry, provider errors and redirect refusal. Live delivery still depends on the verified sender, the secret file and a designated verified recipient. + + +### Release image bytecode custody + +The f480 host image builds completed, but source inventory verification rejected +716 extra files. An exact inside-image comparison found only canonical Python +cache paths, with no missing or changed source files. The parser performance +repair deliberately generates these caches. Allowed changes: the existing +release-image verifier, its counterexample tests and this record. Validate +canonical cache/source correspondence, Python header freshness and compiled +code equivalence before excluding generated caches from source-only inventory. +Preserve rejection of symlinks, extra source, package drift and malformed or +substituted bytecode. Reuse the existing built images for focused verification; +no live deployment or backend behavior change is required by this repair. diff --git a/scripts/test_hosted_release_images.py b/scripts/test_hosted_release_images.py index c4e09dcf9..a4360e201 100644 --- a/scripts/test_hosted_release_images.py +++ b/scripts/test_hosted_release_images.py @@ -3,7 +3,9 @@ import ast import copy import json +import os from pathlib import Path +import py_compile import re import sys import tempfile @@ -415,6 +417,37 @@ def test_inventory_rejects_links_and_detects_extra_regular_file(self): with self.assertRaisesRegex(ValueError, "symlink"): proof.source_inventory(root) + def test_inventory_checks_generated_bytecode_against_exact_source(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for name in proof.SOURCE_PATHS: + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_text("source") + (root / "app").unlink() + (root / "app").mkdir() + source = root / "app/example.py" + source.write_text("def value():\n return 1\n") + original = proof.source_inventory(root) + cache = Path(py_compile.compile(str(source), doraise=True)) + self.assertEqual(proof.source_inventory(root), original) + + substitute = root / "substitute.py" + substitute.write_text("def value():\n return 2\n") + os.utime(substitute, ns=(source.stat().st_atime_ns, source.stat().st_mtime_ns)) + py_compile.compile(str(substitute), cfile=str(cache), dfile=str(source), doraise=True) + with self.assertRaisesRegex(ValueError, "source cache code differs"): + proof.source_inventory(root) + + py_compile.compile(str(source), doraise=True) + cache.write_bytes(cache.read_bytes() + b"untracked payload") + with self.assertRaisesRegex(ValueError, "trailing bytes"): + proof.source_inventory(root) + + py_compile.compile(str(source), doraise=True) + source.write_text("def value():\n return 'changed source'\n") + with self.assertRaisesRegex(ValueError, "source cache is stale"): + proof.source_inventory(root) + def test_evidence_is_closed_and_never_overwrites_a_symlink_target(self): evidence = { key: "a" * 64 diff --git a/scripts/verify_hosted_release_images.py b/scripts/verify_hosted_release_images.py index 3c920d0a8..a731274b5 100644 --- a/scripts/verify_hosted_release_images.py +++ b/scripts/verify_hosted_release_images.py @@ -5,7 +5,10 @@ import argparse import hashlib import importlib.metadata +import importlib.util +import io import json +import marshal import os from pathlib import Path import re @@ -15,6 +18,7 @@ import sys import tempfile import tomllib +from types import CodeType import uuid @@ -53,6 +57,37 @@ def file_hash(path: Path) -> str: return hashlib.sha256(content).hexdigest() +def validate_source_cache(path: Path) -> None: + """Accept only fresh canonical bytecode compiled from its retained source.""" + source = Path(importlib.util.source_from_cache(str(path))) + require(str(path) == importlib.util.cache_from_source(str(source)), "source cache path differs") + info = source.lstat() + require(stat.S_ISREG(info.st_mode), "source cache has no regular source") + require(info.st_size <= MAX_BYTES, "source cache input exceeds limit") + raw, content = path.read_bytes(), source.read_bytes() + require(len(raw) >= 16 and raw[:4] == importlib.util.MAGIC_NUMBER, "source cache header differs") + flags = int.from_bytes(raw[4:8], "little") + require(flags in {0, 1, 3}, "source cache flags differ") + if flags & 1: + require(raw[8:16] == importlib.util.source_hash(content), "source cache is stale") + else: + require( + int.from_bytes(raw[8:12], "little") == int(info.st_mtime) & 0xFFFFFFFF + and int.from_bytes(raw[12:16], "little") == len(content), + "source cache is stale", + ) + expected = compile(content, str(source), "exec", dont_inherit=True, optimize=0) + payload = io.BytesIO(raw[16:]) + actual = marshal.load(payload) + require(payload.tell() == len(raw) - 16, "source cache has trailing bytes") + require(isinstance(actual, CodeType) and actual == expected, "source cache code differs") + pending = [actual] + while pending: + code = pending.pop() + require(code.co_filename == str(source), "source cache filename differs") + pending.extend(value for value in code.co_consts if isinstance(value, CodeType)) + + def source_inventory(root: Path, shared_root: Path | None = None) -> dict[str, str]: found: dict[str, str] = {} total = 0 @@ -68,6 +103,9 @@ def visit(path: Path, base: Path, prefix: str = "") -> None: require(stat.S_ISREG(info.st_mode), "source special file refused") total += info.st_size require(len(found) < MAX_FILES and total <= MAX_BYTES, "source inventory limit") + if path.suffix == ".pyc": + validate_source_cache(path) + return found[prefix + str(path.relative_to(base))] = file_hash(path) for relative in SOURCE_PATHS: From ade1097c7cb4d315ae76f6b4479477db166db4be Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 12:04:25 +0100 Subject: [PATCH 409/513] test: bind cached bytecode to the exact compiled payload --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 9 +++++++++ scripts/test_hosted_release_images.py | 18 +++++++++++++++++- scripts/verify_hosted_release_images.py | 18 +++++------------- 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f49a9f77c..3e8e71078 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11848,3 +11848,12 @@ code equivalence before excluding generated caches from source-only inventory. Preserve rejection of symlinks, extra source, package drift and malformed or substituted bytecode. Reuse the existing built images for focused verification; no live deployment or backend behavior change is required by this repair. + +Independent review found that Python code-object equality omits executable +fields. The verifier now compares the original cache payload directly with +`marshal.dumps(compile(source))`, without deserializing it. File-count limits +include caches. Counterexamples cover changed nested stack size, qualified +name, filename, executable code, stale source and trailing payload; all 21 +release-verifier tests pass in the backend environment. Exact built-image +verification remains the next check; 65 reviewer-generated cache samples +matched the deterministic payload comparison. diff --git a/scripts/test_hosted_release_images.py b/scripts/test_hosted_release_images.py index a4360e201..6623ad9fa 100644 --- a/scripts/test_hosted_release_images.py +++ b/scripts/test_hosted_release_images.py @@ -3,6 +3,7 @@ import ast import copy import json +import marshal import os from pathlib import Path import py_compile @@ -430,6 +431,21 @@ def test_inventory_checks_generated_bytecode_against_exact_source(self): original = proof.source_inventory(root) cache = Path(py_compile.compile(str(source), doraise=True)) self.assertEqual(proof.source_inventory(root), original) + with patch.object(proof, "MAX_FILES", len(original)): + with self.assertRaisesRegex(ValueError, "inventory limit"): + proof.source_inventory(root) + + valid = cache.read_bytes() + compiled = marshal.loads(valid[16:]) + nested = next(value for value in compiled.co_consts if hasattr(value, "co_code")) + for field, value in (("co_stacksize", 1000), ("co_qualname", "substituted"), + ("co_filename", "/substituted.py")): + with self.subTest(field=field): + constants = tuple(nested.replace(**{field: value}) if item is nested else item + for item in compiled.co_consts) + cache.write_bytes(valid[:16] + marshal.dumps(compiled.replace(co_consts=constants))) + with self.assertRaisesRegex(ValueError, "source cache code differs"): + proof.source_inventory(root) substitute = root / "substitute.py" substitute.write_text("def value():\n return 2\n") @@ -440,7 +456,7 @@ def test_inventory_checks_generated_bytecode_against_exact_source(self): py_compile.compile(str(source), doraise=True) cache.write_bytes(cache.read_bytes() + b"untracked payload") - with self.assertRaisesRegex(ValueError, "trailing bytes"): + with self.assertRaisesRegex(ValueError, "source cache code differs"): proof.source_inventory(root) py_compile.compile(str(source), doraise=True) diff --git a/scripts/verify_hosted_release_images.py b/scripts/verify_hosted_release_images.py index a731274b5..c62dbe77f 100644 --- a/scripts/verify_hosted_release_images.py +++ b/scripts/verify_hosted_release_images.py @@ -6,7 +6,6 @@ import hashlib import importlib.metadata import importlib.util -import io import json import marshal import os @@ -18,7 +17,6 @@ import sys import tempfile import tomllib -from types import CodeType import uuid @@ -77,23 +75,16 @@ def validate_source_cache(path: Path) -> None: "source cache is stale", ) expected = compile(content, str(source), "exec", dont_inherit=True, optimize=0) - payload = io.BytesIO(raw[16:]) - actual = marshal.load(payload) - require(payload.tell() == len(raw) - 16, "source cache has trailing bytes") - require(isinstance(actual, CodeType) and actual == expected, "source cache code differs") - pending = [actual] - while pending: - code = pending.pop() - require(code.co_filename == str(source), "source cache filename differs") - pending.extend(value for value in code.co_consts if isinstance(value, CodeType)) + require(raw[16:] == marshal.dumps(expected), "source cache code differs") def source_inventory(root: Path, shared_root: Path | None = None) -> dict[str, str]: found: dict[str, str] = {} total = 0 + visited = 0 def visit(path: Path, base: Path, prefix: str = "") -> None: - nonlocal total + nonlocal total, visited info = path.lstat() require(not stat.S_ISLNK(info.st_mode), "source symlink refused") if stat.S_ISDIR(info.st_mode): @@ -102,7 +93,8 @@ def visit(path: Path, base: Path, prefix: str = "") -> None: return require(stat.S_ISREG(info.st_mode), "source special file refused") total += info.st_size - require(len(found) < MAX_FILES and total <= MAX_BYTES, "source inventory limit") + visited += 1 + require(visited <= MAX_FILES and total <= MAX_BYTES, "source inventory limit") if path.suffix == ".pyc": validate_source_cache(path) return From d0413580ba3c881744f5b0759280fbe333aa478c Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 12:00:00 +0100 Subject: [PATCH 410/513] docs(submission): record PostgreSQL feedback email qualification --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index 3e8e71078..e7c7f3f51 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11857,3 +11857,22 @@ name, filename, executable code, stale source and trailing payload; all 21 release-verifier tests pass in the backend environment. Exact built-image verification remains the next check; 65 reviewer-generated cache samples matched the deterministic payload comparison. + +Four PostgreSQL cases passed in 409.04 seconds. They cover atomic rollback and +retry, an expired committed invocation returning to retryable custody and +resending the identical Resend key and payload, immediate revision-limit +rejection, and the monotonic signed mailbox observation. The test run recorded +launch HEAD `5788a731e` with the corrected input files later frozen in +`d56e4230c`. The migration blob was `afecfe6aeb85d2dfaba288c8613146c63d0cd959`, +the schema guard blob was `1adcedd5c4f6ed33ec41a99bcd81ac6065fdfa76`, and the +feedback test blob was `229bc768fb187a7451cdef7d920d66611c2c99e8`. The catalog +probe pinned the exact schema guard before pytest. The PostgreSQL database and +the test role were cleaned up. The Resend transport used synthetic HTTP in +these cases. + +Five further PostgreSQL cases passed in 528.81 seconds on the exact code of +`d56e4230c`. They cover suppression for stale work, an unverified mailbox, +checker coverage gaps, disabled delivery and POST provider infrastructure +failure. Isolated database and role cleanup completed. These cases and the +four delivery cases qualify the local routing and recovery boundaries. Live +qualification still requires the verified sender and designated test mailbox. From 07c83654498e9a2cfdcdb4cdd71e60cba2dc3746 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:52:20 +0100 Subject: [PATCH 411/513] Prove sealed upload replay rejects changed bytes --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ .../tests/tasks/test_public_submission_intake.py | 10 +++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e7c7f3f51..d0de145a2 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -50,6 +50,21 @@ route and clients, foreign or missing assignments, grant loss, and retained attempt selection. Security, architecture, QA and documentation review focus on owner-scoped lookup, exact current evidence and convergence of all clients. +### Sealed changed-body replay proof + +The durable EOF test covers changed bytes before storage seals the source. A05 +also needs the public conflict after sealing. Extend the existing accepted ZIP +replay test with a second valid, same-length archive under the original actor, +key and metadata. Require the exact 409 while the existing test forbids all +provider uploads, retains a single PRE run and checks the original source +charge. Changes are limited to that test and this record. No production code, +deployment, new test module or transport contract changes are in scope. + +Run the exact existing test through isolated PostgreSQL. Risk is low for this +test-only extension. Focused QA and human review should distinguish the new +body digest check from the existing changed-metadata conflict and verify the +same-body replay still succeeds. + ## Bounded change ### Allowed diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py index 019840193..6fbbbfeb9 100644 --- a/backend/tests/tasks/test_public_submission_intake.py +++ b/backend/tests/tasks/test_public_submission_intake.py @@ -406,6 +406,11 @@ async def no_new_upload(*args, **kwargs): replay_patch.setattr(LocalStorageAdapter, "complete_source_upload", no_new_upload) replay = await client.post(route, headers=headers, content=payload) assert replay.status_code == 202 and replay.json() == dict(receipt, replayed=True), replay.text + changed_payload = _archive(content=b"modified work") + assert changed_payload != payload and len(changed_payload) == len(payload) + changed_body = await client.post(route, headers=headers, content=changed_payload) + assert changed_body.status_code == 409, changed_body.text + assert changed_body.json()["error"]["code"] == "submission_idempotency_conflict" changed = await client.post(route, headers=headers | {"X-Submission-Feedback": "changed"}, content=payload) assert changed.status_code == 409, changed.text @@ -450,7 +455,10 @@ async def no_new_upload(*args, **kwargs): assert stored.summary is stored.worker_attestation is None assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 1 assert await session.scalar(select(func.count()).select_from(SelectedPreSubmitRun)) == 1 - assert await session.scalar(text("SELECT count(*) FROM submission_source_charges")) == 1 + charge = (await session.execute(text( + "SELECT operation_id,state,accounted_bytes FROM submission_source_charges" + ))).one() + assert tuple(charge) == (UUID(receipt["operation_id"]), "sealed", len(payload)) assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations")) == 1 admission = (await session.scalars(select(SubmissionBundleAdmission))).one() assert admission.status == "consumed" From 3d3a56695c736bdde29ab9d49b42d380b88cb179 Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 11:53:31 +0100 Subject: [PATCH 412/513] Verify mailbox defaults in retained admission upgrades --- .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++ .../tests/migrations/test_source_pre_cutover.py | 12 +++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index d0de145a2..f5c1b8668 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -65,6 +65,21 @@ test-only extension. Focused QA and human review should distinguish the new body digest check from the existing changed-metadata conflict and verify the same-body replay still succeeds. +### Retained admission history at the current schema head + +The ready and consumed admission captures each include historical actor identity +links. The current-head comparison must account for the false mailbox-verification +value added by migration 0093. Require that exact value for every retained link +and omit only the new column from the row comparison. Retain the existing +optional-feedback treatment and exact comparison of all other captured fields +and of the 0084 custody function delta. + +Scope is the fixture comparison in `backend/tests/migrations/test_source_pre_cutover.py` +and this record. Keep migrations, production code and archived fixture bytes +unchanged. Risk is low and verification uses both existing PostgreSQL cases. +Focused QA and human review should check that previously retained identities +cannot acquire verified addresses through the upgrade. + ## Bounded change ### Allowed diff --git a/backend/tests/migrations/test_source_pre_cutover.py b/backend/tests/migrations/test_source_pre_cutover.py index 863cd35f9..2dbac89a0 100644 --- a/backend/tests/migrations/test_source_pre_cutover.py +++ b/backend/tests/migrations/test_source_pre_cutover.py @@ -139,7 +139,7 @@ def _admission_archive(): return snapshots -async def _retained_rows_and_functions(url, tables, *, current_feedback=False): +async def _retained_rows_and_functions(url, tables, *, current_schema=False): """Compare all captured nonempty tables and all public function definitions.""" connection = await asyncpg.connect(url.replace('+asyncpg', '')) try: @@ -147,11 +147,17 @@ async def _retained_rows_and_functions(url, tables, *, current_feedback=False): for table in tables: if table != 'alembic_version': value = 'to_jsonb(r)' - if current_feedback and table == 'submissions': + if current_schema and table == 'submissions': assert await connection.fetchval( 'SELECT count(*) FROM public.submissions WHERE feedback IS NOT NULL' ) == 0 value += "-'feedback'" + if current_schema and table == 'actor_identity_links': + assert await connection.fetchval( + 'SELECT count(*) FROM public.actor_identity_links ' + 'WHERE email_verified IS DISTINCT FROM false' + ) == 0 + value += "-'email_verified'" rows[table] = await connection.fetchval( f'SELECT coalesce(jsonb_agg({value} ORDER BY ({value})::text),\'[]\')::text FROM public."{table}" r' ) @@ -249,7 +255,7 @@ async def test_source_binding_cutover_preserves_history_and_closes_old_consumpti assert {k for k in old_functions if old_functions[k] != new_functions[k]} == {'guard_submission_bundle_admission_lineage()'} await asyncio.to_thread(command.upgrade, _config(), current_schema_revision()) current_rows, _ = await _retained_rows_and_functions( - isolated_database_env, snapshot['tables'], current_feedback=True, + isolated_database_env, snapshot['tables'], current_schema=True, ) assert current_rows == after if state == 'ready': From 8fe8e330b7ffc9ae10b83f8eca5e4c0f1fccb8cb Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 12:19:13 +0100 Subject: [PATCH 413/513] build: cache parser dependencies while preserving exact source verification --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 ++++++ docker/backend/Dockerfile.release | 5 +- scripts/test_hosted_release_images.py | 49 ------------------- scripts/verify_hosted_release_images.py | 34 +------------ 4 files changed, 21 insertions(+), 82 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index f5c1b8668..e45cc99c3 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11906,3 +11906,18 @@ checker coverage gaps, disabled delivery and POST provider infrastructure failure. Isolated database and role cleanup completed. These cases and the four delivery cases qualify the local routing and recovery boundaries. Live qualification still requires the verified sender and designated test mailbox. + + +### Narrow parser cache repair; preserve exact source verification + +The bytecode-verifier approach is superseded. Raw marshal encodings differed +for valid uv caches; normalized encodings do not prove reference identity. +A disposable derivative retained only standard-library and third-party caches, +removing Workstream app/shared caches. Under the exact existing hardened parser +configuration, both UIDs parsed both originals in 0.533–0.657 CPU seconds; both +real socket calls and production source-cited PRE/POST compilation passed. +Receipt: `/tmp/workstream-parser-stdlib-only/proof.log`. The owned container was +removed; the running parser was unchanged. The release recipe now uses this +narrow cache scope. Original verifier and counterexample tests are restored +exactly; there is no new bytecode admission or source-inventory exception. +Actual recipe image build and verification remain required. diff --git a/docker/backend/Dockerfile.release b/docker/backend/Dockerfile.release index 5de3060d4..3d9949ffd 100644 --- a/docker/backend/Dockerfile.release +++ b/docker/backend/Dockerfile.release @@ -43,7 +43,10 @@ RUN --mount=type=cache,target=/root/.cache/uv \ *) echo "WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT must be agents or omnicore" >&2; exit 1 ;; \ esac \ && uv sync --locked --extra "${WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT}" --no-dev --no-editable --compile-bytecode \ - && python -m compileall -q -j 2 /usr/local/lib/python3.12 /workspace/backend/app \ + && python -m compileall -q -j 2 /usr/local/lib/python3.12 \ + && find /opt/venv/lib/python3.12/site-packages/app \ + /opt/venv/lib/python3.12/site-packages/workstream_external_services \ + -type f -name '*.pyc' -delete \ && install -d -m 0755 /etc/workstream \ && printf '%s\n' "${WORKSTREAM_PROJECT_AGENT_SDK_ENVIRONMENT}" \ > /etc/workstream/project-agent-sdk-environment \ diff --git a/scripts/test_hosted_release_images.py b/scripts/test_hosted_release_images.py index 6623ad9fa..c4e09dcf9 100644 --- a/scripts/test_hosted_release_images.py +++ b/scripts/test_hosted_release_images.py @@ -3,10 +3,7 @@ import ast import copy import json -import marshal -import os from pathlib import Path -import py_compile import re import sys import tempfile @@ -418,52 +415,6 @@ def test_inventory_rejects_links_and_detects_extra_regular_file(self): with self.assertRaisesRegex(ValueError, "symlink"): proof.source_inventory(root) - def test_inventory_checks_generated_bytecode_against_exact_source(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - for name in proof.SOURCE_PATHS: - (root / name).parent.mkdir(parents=True, exist_ok=True) - (root / name).write_text("source") - (root / "app").unlink() - (root / "app").mkdir() - source = root / "app/example.py" - source.write_text("def value():\n return 1\n") - original = proof.source_inventory(root) - cache = Path(py_compile.compile(str(source), doraise=True)) - self.assertEqual(proof.source_inventory(root), original) - with patch.object(proof, "MAX_FILES", len(original)): - with self.assertRaisesRegex(ValueError, "inventory limit"): - proof.source_inventory(root) - - valid = cache.read_bytes() - compiled = marshal.loads(valid[16:]) - nested = next(value for value in compiled.co_consts if hasattr(value, "co_code")) - for field, value in (("co_stacksize", 1000), ("co_qualname", "substituted"), - ("co_filename", "/substituted.py")): - with self.subTest(field=field): - constants = tuple(nested.replace(**{field: value}) if item is nested else item - for item in compiled.co_consts) - cache.write_bytes(valid[:16] + marshal.dumps(compiled.replace(co_consts=constants))) - with self.assertRaisesRegex(ValueError, "source cache code differs"): - proof.source_inventory(root) - - substitute = root / "substitute.py" - substitute.write_text("def value():\n return 2\n") - os.utime(substitute, ns=(source.stat().st_atime_ns, source.stat().st_mtime_ns)) - py_compile.compile(str(substitute), cfile=str(cache), dfile=str(source), doraise=True) - with self.assertRaisesRegex(ValueError, "source cache code differs"): - proof.source_inventory(root) - - py_compile.compile(str(source), doraise=True) - cache.write_bytes(cache.read_bytes() + b"untracked payload") - with self.assertRaisesRegex(ValueError, "source cache code differs"): - proof.source_inventory(root) - - py_compile.compile(str(source), doraise=True) - source.write_text("def value():\n return 'changed source'\n") - with self.assertRaisesRegex(ValueError, "source cache is stale"): - proof.source_inventory(root) - def test_evidence_is_closed_and_never_overwrites_a_symlink_target(self): evidence = { key: "a" * 64 diff --git a/scripts/verify_hosted_release_images.py b/scripts/verify_hosted_release_images.py index c62dbe77f..3c920d0a8 100644 --- a/scripts/verify_hosted_release_images.py +++ b/scripts/verify_hosted_release_images.py @@ -5,9 +5,7 @@ import argparse import hashlib import importlib.metadata -import importlib.util import json -import marshal import os from pathlib import Path import re @@ -55,36 +53,12 @@ def file_hash(path: Path) -> str: return hashlib.sha256(content).hexdigest() -def validate_source_cache(path: Path) -> None: - """Accept only fresh canonical bytecode compiled from its retained source.""" - source = Path(importlib.util.source_from_cache(str(path))) - require(str(path) == importlib.util.cache_from_source(str(source)), "source cache path differs") - info = source.lstat() - require(stat.S_ISREG(info.st_mode), "source cache has no regular source") - require(info.st_size <= MAX_BYTES, "source cache input exceeds limit") - raw, content = path.read_bytes(), source.read_bytes() - require(len(raw) >= 16 and raw[:4] == importlib.util.MAGIC_NUMBER, "source cache header differs") - flags = int.from_bytes(raw[4:8], "little") - require(flags in {0, 1, 3}, "source cache flags differ") - if flags & 1: - require(raw[8:16] == importlib.util.source_hash(content), "source cache is stale") - else: - require( - int.from_bytes(raw[8:12], "little") == int(info.st_mtime) & 0xFFFFFFFF - and int.from_bytes(raw[12:16], "little") == len(content), - "source cache is stale", - ) - expected = compile(content, str(source), "exec", dont_inherit=True, optimize=0) - require(raw[16:] == marshal.dumps(expected), "source cache code differs") - - def source_inventory(root: Path, shared_root: Path | None = None) -> dict[str, str]: found: dict[str, str] = {} total = 0 - visited = 0 def visit(path: Path, base: Path, prefix: str = "") -> None: - nonlocal total, visited + nonlocal total info = path.lstat() require(not stat.S_ISLNK(info.st_mode), "source symlink refused") if stat.S_ISDIR(info.st_mode): @@ -93,11 +67,7 @@ def visit(path: Path, base: Path, prefix: str = "") -> None: return require(stat.S_ISREG(info.st_mode), "source special file refused") total += info.st_size - visited += 1 - require(visited <= MAX_FILES and total <= MAX_BYTES, "source inventory limit") - if path.suffix == ".pyc": - validate_source_cache(path) - return + require(len(found) < MAX_FILES and total <= MAX_BYTES, "source inventory limit") found[prefix + str(path.relative_to(base))] = file_hash(path) for relative in SOURCE_PATHS: From 15fcde2ab7e5376094212f1eda3a93b712cc094b Mon Sep 17 00:00:00 2001 From: Abiorh001 Date: Thu, 26 Nov 2026 12:06:26 +0100 Subject: [PATCH 414/513] Reserve interactive PRE capacity within Smol admission --- .../WS-SUBMIT-001/WS-SUBMIT-001-01.md | 50 ++++ .../README.md | 5 +- .../public_node_faults.py | 9 +- .../run_public_journey_probe.py | 8 +- external_checkers/README.md | 14 ++ .../workstream-checker-service/src/smol.rs | 21 +- .../src/smol/admission.rs | 220 +++++++++++++++--- .../src/smol/intake.rs | 16 +- .../src/smol/pre.rs | 1 + .../src/smol/pre/admission.rs | 63 ++--- .../src/smol/pre/admission/tests.rs | 21 ++ .../src/smol/pre/tests.rs | 11 +- .../src/smol/tests.rs | 16 +- .../src/smol/trial.rs | 7 +- .../src/trial_smol.rs | 4 +- scripts/test_public_hosted_attachment.py | 8 +- scripts/test_public_smol_proof.py | 11 +- 17 files changed, 391 insertions(+), 94 deletions(-) diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md index e45cc99c3..ea9e5808d 100644 --- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md +++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md @@ -11921,3 +11921,53 @@ removed; the running parser was unchanged. The release recipe now uses this narrow cache scope. Original verifier and counterexample tests are restored exactly; there is no new bytecode admission or source-inventory exception. Actual recipe image build and verification remain required. + +### A29 independent runner admission + +Intent. A selected POST invocation and its reserved trial can occupy the +entire current runtime budget before a foreground PRE arrives. Both phases +already use the same authoritative Smol node admission owner. Keep that owner +and protect a bounded PRE budget inside the existing total node capacity. + +Allowed scope. `external_checkers/workstream-checker-service/src/smol.rs`, +`src/smol/admission.rs`, `src/smol/pre.rs`, `src/smol/pre/admission.rs`, and +`src/smol/intake.rs` under the same service own partitioned reservation and its +callers. Update their affected Rust fixtures, including `src/trial_smol.rs` and +`src/smol/trial.rs`, the operational admission documentation in +`external_checkers/README.md`, the existing public Smol proof and fault owner in +`experiments/pilot04_external_checker_runtime/` with their focused +`scripts/test_public_smol_proof.py` and `scripts/test_public_hosted_attachment.py` +tests, and this record. The isolated local +fault harness keeps one slot for each phase. The separate-runner proof keeps +its independent config and executable custody check. + +Acceptance. A PRE-enabled node explicitly reserves slots, RAM, and disk for +PRE. Startup rejects a reserve smaller than one maximum configured PRE or a +reserve without a positive POST complement. Trusted ART intake uses the same +background budget as POST. An outer POST and its sequential child reserve +their combined peak atomically. Verify PRE can reserve beside saturated POST, +release is exact, physical headroom protects PRE storage, and unsettled +cleanup still closes the entire node until existing reconciliation succeeds. +Existing per-VM CPU ceilings, deadlines, and lease/journal ownership stay in +force. This work changes source and focused fixtures. Separate-runner overlap, +foreground latency under contention, and deployed configuration still require +measured qualification. + +Verification from the isolated `f480146ca`-based worktree. The checker service +`smol::` selector passed 56 tests with the offline locked Cargo build. This +includes saturated POST with a held child, simultaneously admitted PRE, +physical disk headroom, exact release, invalid startup capacity and whole-node +quarantine. The public Smol and hosted custody unit suite passed 64 tests, and +the final separate-runner missing-reserve preflight regression passed on its +own. `cargo fmt --check`, Python compilation and `git diff --check` passed. +These were source and fixture checks. No node configuration, active process, +deployed service or admission deadline was changed. + +The `7ceb63e3` runner custody capture has a 2 GiB PRE guest and 2 GiB overlay. +The source/root/scratch disk calculation rounds to 3 GiB outside the overlay. +That exact profile requires one slot, 2.5 GiB memory including host overhead, +and 5 GiB disk before allocating POST capacity. The current one-slot node +requires a measured two-phase configuration before installing this revision. +Use an owned saturation test to measure true POST/PRE/T5 overlap and the +interactive tail on the existing host. A POST profile that reserves a trial +also requires a second POST slot and its exact memory/disk peak. diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md index 98d6e9a1f..f16cafb6a 100644 --- a/experiments/pilot04_external_checker_runtime/README.md +++ b/experiments/pilot04_external_checker_runtime/README.md @@ -99,8 +99,9 @@ The command below describes the operator-local fault harness, not a qualified two-host deployment. Production API/workers must stay on an app-only host and KVM on a separate Linux x86-64 runner. Remote fault transport is still missing, as detailed below. Use disposable PostgreSQL, MinIO and Redis. Provision the [Smol node](../../external_checkers/README.md#smol-microvm-engine) -with `maximum_parallel=1`, the pinned trusted intake image and this directory's -project fixture image. Both are operator-provisioned cache entries; no registry +with two total slots and one expressly reserved for PRE. Use the pinned trusted +intake image and this directory's project fixture image. Both are +operator-provisioned cache entries. No registry or Docker socket is needed by the API/worker or running guests. Build the Rust service and native guest from this checkout. The probe takes the exact node configuration and checks both typed adapter identities before starting services. diff --git a/experiments/pilot04_external_checker_runtime/public_node_faults.py b/experiments/pilot04_external_checker_runtime/public_node_faults.py index 87e69a6a6..119f66e06 100644 --- a/experiments/pilot04_external_checker_runtime/public_node_faults.py +++ b/experiments/pilot04_external_checker_runtime/public_node_faults.py @@ -371,9 +371,14 @@ def write_node_config(config_path, data, identity, *, hosted_runtime=False): raise ValueError('node config custody changed during write') +def validate_fault_capacity(config): + pre_slots = config.get('pre', {}).get('reserved_capacity', {}).get('slots') + if pre_slots != 1 or config['smol'].get('maximum_parallel') != 2: + raise ValueError('public fault proof requires one slot per phase') + + def validate_node(config_path, config, unit, manifest_path, *, hosted_runtime=False): - if config['smol'].get('maximum_parallel') != 1: - raise ValueError('public proof requires a one-slot node') + validate_fault_capacity(config) original, _ = _read_config(config_path, hosted_runtime) if json.loads(original) != config: raise ValueError('node config changed during validation') diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py index 2b0f6aae1..6acf21126 100644 --- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py +++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py @@ -1200,14 +1200,17 @@ def _read_runner_configuration(node_config: Path, root: Path, custody: dict, *, ['git', 'rev-parse', 'HEAD'], cwd=BACKEND, text=True).strip(), 'custody source differs') raw = node_config.read_bytes() service_config = json.loads(raw) + _require(isinstance(service_config.get('pre'), dict) + and isinstance(service_config['pre'].get('reserved_capacity'), dict), + 'public proof requires an explicit PRE reservation') if separate_runner: _require(service_config == custody['node_config'] and 'sha256:' + hashlib.sha256(raw).hexdigest() == custody['config_sha256'] and service_config['smol']['binary_sha256'] == custody['smol_sha256'], 'separate runner configuration differs from reviewed custody') return service_config - _require(service_config["smol"].get("maximum_parallel") == 1, - "public proof requires a one-slot node") + from experiments.pilot04_external_checker_runtime.public_node_faults import validate_fault_capacity + validate_fault_capacity(service_config) original_config = json.loads(json.dumps(service_config)) wrapper = root / 'node-control/runtime-wrapper' _require(service_config['smol']['binary'] == str(wrapper) @@ -1470,6 +1473,7 @@ async def start_owned_worker() -> None: "public_api": True, "prefork_worker": True, "prefork_finalization_worker": True, "dedicated_worker_queues": [queue for _, queue in WORKER_ROLES], "maximum_parallel": service_config["smol"]["maximum_parallel"], + "pre_reserved_capacity": service_config["pre"]["reserved_capacity"], "separate_runner": separate_runner, "scheduled_artifact_scans": True, "public_original_guide_setup": True, diff --git a/external_checkers/README.md b/external_checkers/README.md index c8062d620..0d30f49d5 100644 --- a/external_checkers/README.md +++ b/external_checkers/README.md @@ -315,6 +315,20 @@ For this engine omit `docker_binary`, and configure `smol` with absolute `binary and required positive `maximum_parallel` and `maximum_storage_bytes`. Install the verified Smol release bundle together and keep it operator-controlled. Build `workstream-checker-guest` for `x86_64-unknown-linux-musl`; the node and bootstrap must come from the same source. + +When the node enables `pre`, set `pre.reserved_capacity` with positive `slots`, +`memory_bytes`, and `storage_bytes`. The reserve must fit the largest PRE shape +permitted by the configured source limit, root and profile. The check includes +host memory overhead and separately rounded VM and overlay disk. The remaining +node capacity must have positive slots, memory, and storage for POST and +trusted ART preparation. The node derives its total allocable memory from +the delegated cgroup and checks actual disk space before creating each VM. +Background reservations leave the configured PRE disk budget available while +PRE is idle. POST with a trial consumes capacity for the outer VM and one +sequential child at their combined peak. Per-VM CPU ceilings still share the +parent cgroup limit. Size and measure concurrency on the chosen host before +publishing an interactive latency envelope. + Each existing cache entry additionally has `smol.archive`, `smol.archive_sha256` and `smol.image_config`. The [cache preparation command](../backend/scripts/checker_smol_cache.py) verifies an already local diff --git a/external_checkers/workstream-checker-service/src/smol.rs b/external_checkers/workstream-checker-service/src/smol.rs index 6c5017dd9..169e15e5b 100644 --- a/external_checkers/workstream-checker-service/src/smol.rs +++ b/external_checkers/workstream-checker-service/src/smol.rs @@ -28,7 +28,7 @@ pub(super) fn validate_child_home_root(root: &Path) -> Result<(), String> { } mod admission; -pub(crate) use admission::{Admission, Capacity, Reservation}; +pub(crate) use admission::{Admission, Capacity, Phase, Reservation}; mod intake; pub(crate) mod trial; mod trial_io; @@ -131,7 +131,12 @@ fn reserve_resources( config: &ServiceConfig, resources: Resources, ) -> Result, String> { - reserve_capacity(config, resource_capacity(resources, None)?, None) + reserve_capacity( + config, + Phase::Background, + resource_capacity(resources, None)?, + None, + ) } pub(super) fn reserve_invocation( config: &ServiceConfig, @@ -140,6 +145,7 @@ pub(super) fn reserve_invocation( ) -> Result, String> { reserve_capacity( config, + Phase::Background, resource_capacity(request.into(), None)?, Some(child), ) @@ -185,6 +191,7 @@ pub(crate) fn quarantine(config: &ServiceConfig) { } fn reserve_capacity( config: &ServiceConfig, + phase: Phase, outer: Capacity, child: Option, ) -> Result, String> { @@ -192,10 +199,10 @@ fn reserve_capacity( .smol_admission .as_ref() .ok_or("admission unavailable")?; - let reservation = admission.reserve(outer, child)?; + let reservation = admission.reserve(phase, outer, child)?; // Reserve atomically first, then recheck physical space. A failure drops the // complete reservation; no VM or provider operation has begun. - let required = admission.reserved_storage_bytes()?; + let required = admission.required_storage_bytes(phase)?; if available_storage(settings(config)?)? < required { return Err("node storage unavailable".into()); } @@ -1331,12 +1338,18 @@ where { let maximum = settings(config)?.maximum_parallel; let mut config = config.clone(); + let pre_reserve = config + .pre + .as_ref() + .map(PreConfig::node_reserve) + .transpose()?; config.smol_admission = Some(Arc::new(Admission::new( Capacity { slots: maximum, memory_bytes: memory_capacity(settings(&config)?)? as u64, storage_bytes: settings(&config)?.maximum_storage_bytes, }, + pre_reserve, random_token()?, )?)); let config = Arc::new(config); diff --git a/external_checkers/workstream-checker-service/src/smol/admission.rs b/external_checkers/workstream-checker-service/src/smol/admission.rs index c822f7c72..a4e7e4512 100644 --- a/external_checkers/workstream-checker-service/src/smol/admission.rs +++ b/external_checkers/workstream-checker-service/src/smol/admission.rs @@ -1,10 +1,12 @@ //! One atomic node reservation for a checker and its sequential child trials. +use serde::Deserialize; use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] pub(crate) struct Capacity { pub(crate) slots: usize, pub(crate) memory_bytes: u64, @@ -20,17 +22,51 @@ impl Capacity { }) } - fn fits(self, maximum: Self) -> bool { + fn checked_sub(self, other: Self) -> Option { + Some(Self { + slots: self.slots.checked_sub(other.slots)?, + memory_bytes: self.memory_bytes.checked_sub(other.memory_bytes)?, + storage_bytes: self.storage_bytes.checked_sub(other.storage_bytes)?, + }) + } + + pub(super) fn fits(self, maximum: Self) -> bool { self.slots <= maximum.slots && self.memory_bytes <= maximum.memory_bytes && self.storage_bytes <= maximum.storage_bytes } + + fn bounded(self) -> bool { + self.slots > 0 && self.memory_bytes > 0 && self.storage_bytes > 0 + } +} + +#[derive(Clone, Copy, Debug)] +pub(crate) enum Phase { + Pre, + Background, +} + +#[derive(Debug, Default, PartialEq, Eq)] +struct Usage { + pre: Capacity, + background: Capacity, +} + +impl Usage { + fn for_phase(&mut self, phase: Phase) -> &mut Capacity { + match phase { + Phase::Pre => &mut self.pre, + Phase::Background => &mut self.background, + } + } } #[derive(Debug)] pub(crate) struct Admission { - used: Mutex, - maximum: Capacity, + used: Mutex, + pre_maximum: Capacity, + background_maximum: Capacity, pub(crate) epoch: String, poisoned: AtomicBool, } @@ -45,16 +81,43 @@ impl Admission { if self.poisoned.load(Ordering::SeqCst) { return Err("node admission quarantined".into()); } - Ok(used.storage_bytes) + Ok(used.pre.storage_bytes + used.background.storage_bytes) } - pub(crate) fn new(maximum: Capacity, epoch: String) -> Result { - if maximum.slots == 0 || maximum.memory_bytes == 0 || maximum.storage_bytes == 0 { + // For a background reservation, keep space for PRE even while the PRE partition is empty. + pub(super) fn required_storage_bytes(&self, phase: Phase) -> Result { + match phase { + Phase::Pre => self.reserved_storage_bytes(), + Phase::Background => { + let used = self.used.lock().map_err(|_| "node admission unavailable")?; + if self.poisoned.load(Ordering::SeqCst) { + return Err("node admission quarantined".into()); + } + Ok(self.pre_maximum.storage_bytes + used.background.storage_bytes) + } + } + } + + pub(crate) fn new( + maximum: Capacity, + pre: Option, + epoch: String, + ) -> Result { + if !maximum.bounded() { return Err("node capacity must be bounded".into()); } + if pre.is_some_and(|capacity| !capacity.bounded()) { + return Err("PRE reserve must be bounded".into()); + } + let pre_maximum = pre.unwrap_or_default(); + let background_maximum = maximum + .checked_sub(pre_maximum) + .filter(|capacity| capacity.bounded()) + .ok_or("background capacity must remain bounded after PRE reserve")?; Ok(Self { - used: Mutex::new(Capacity::default()), - maximum, + used: Mutex::new(Usage::default()), + pre_maximum, + background_maximum, epoch, poisoned: AtomicBool::new(false), }) @@ -62,6 +125,7 @@ impl Admission { pub(crate) fn reserve( self: &Arc, + phase: Phase, outer: Capacity, child: Option, ) -> Result, String> { @@ -69,6 +133,7 @@ impl Admission { || outer.memory_bytes == 0 || outer.storage_bytes == 0 || child.is_some_and(|c| c.slots != 1 || c.memory_bytes == 0 || c.storage_bytes == 0) + || (matches!(phase, Phase::Pre) && child.is_some()) { return Err("invalid invocation capacity".into()); } @@ -79,13 +144,21 @@ impl Admission { if self.poisoned.load(Ordering::SeqCst) { return Err("node admission quarantined".into()); } - let next = used + let maximum = match phase { + Phase::Pre => self.pre_maximum, + Phase::Background => self.background_maximum, + }; + // Both ceilings are disjoint partitions of the node maximum. Charging either + // under this same lock keeps their aggregate within the node maximum. + let phase_usage = used.for_phase(phase); + let next = phase_usage .checked_add(charge) - .filter(|v| v.fits(self.maximum)) + .filter(|v| v.fits(maximum)) .ok_or("capacity unavailable")?; - *used = next; + *phase_usage = next; Ok(Arc::new(Reservation { admission: self.clone(), + phase, charge, child, child_active: AtomicBool::new(false), @@ -96,6 +169,7 @@ impl Admission { #[derive(Debug)] pub(crate) struct Reservation { pub(crate) admission: Arc, + phase: Phase, charge: Capacity, child: Option, child_active: AtomicBool, @@ -133,6 +207,7 @@ impl Drop for Reservation { fn drop(&mut self) { // Poisoned admission remains closed; never invent capacity after a panic. if let Ok(mut used) = self.admission.used.lock() { + let used = used.for_phase(self.phase); used.slots -= self.charge.slots; used.memory_bytes -= self.charge.memory_bytes; used.storage_bytes -= self.charge.storage_bytes; @@ -174,43 +249,101 @@ mod tests { #[test] fn one_slot_node_refuses_trial_before_reserving_outer() { - let node = Arc::new(Admission::new(amount(1, 200, 200), "test".into()).unwrap()); + let node = Arc::new(Admission::new(amount(1, 200, 200), None, "test".into()).unwrap()); assert!(node - .reserve(amount(1, 10, 10), Some(amount(1, 10, 10))) + .reserve( + Phase::Background, + amount(1, 10, 10), + Some(amount(1, 10, 10)) + ) .is_err()); - assert!(node.reserve(amount(1, 10, 10), None).is_ok()); + assert!(node + .reserve(Phase::Background, amount(1, 10, 10), None) + .is_ok()); + assert!(node.reserve(Phase::Pre, amount(1, 10, 10), None).is_err()); + } + + #[test] + fn pre_reserve_must_leave_bounded_background_capacity() { + let maximum = amount(2, 20, 20); + for invalid in [ + amount(0, 10, 10), + amount(1, 0, 10), + amount(1, 10, 0), + amount(2, 10, 10), + amount(1, 20, 10), + amount(1, 10, 20), + amount(3, 21, 21), + ] { + assert!(Admission::new(maximum, Some(invalid), "test".into()).is_err()); + } + } + + #[test] + fn saturated_background_trial_leaves_pre_capacity_and_disk_headroom() { + let pre = amount(1, 8, 16); + let job = amount(1, 6, 7); + let node = Arc::new(Admission::new(amount(3, 20, 30), Some(pre), "test".into()).unwrap()); + let post = node.reserve(Phase::Background, job, Some(job)).unwrap(); + let child = post.child(job).unwrap(); + assert_eq!(node.reserved_storage_bytes().unwrap(), 14); + assert_eq!(node.required_storage_bytes(Phase::Background).unwrap(), 30); + assert!(node.reserve(Phase::Background, job, None).is_err()); + let foreground = node.reserve(Phase::Pre, pre, None).unwrap(); + assert_eq!(node.required_storage_bytes(Phase::Pre).unwrap(), 30); + assert!(node.reserve(Phase::Pre, pre, None).is_err()); + + drop(post); + assert!(node.reserve(Phase::Background, job, None).is_err()); + drop(child); + assert_eq!(node.reserved_storage_bytes().unwrap(), 16); + assert!(node.reserve(Phase::Background, job, Some(job)).is_ok()); + drop(foreground); + assert_eq!(node.reserved_storage_bytes().unwrap(), 0); } #[test] fn every_limit_is_atomic_and_failed_admission_leaks_nothing() { for limit in [amount(1, 200, 200), amount(2, 19, 200), amount(2, 200, 19)] { - let node = Arc::new(Admission::new(limit, "test".into()).unwrap()); + let node = Arc::new(Admission::new(limit, None, "test".into()).unwrap()); assert!(node - .reserve(amount(1, 10, 10), Some(amount(1, 10, 10))) + .reserve( + Phase::Background, + amount(1, 10, 10), + Some(amount(1, 10, 10)) + ) .is_err()); - assert_eq!(*node.used.lock().unwrap(), Capacity::default()); + assert_eq!(*node.used.lock().unwrap(), Usage::default()); } } #[test] fn child_keeps_peak_reservation_alive_and_is_exclusive() { - let node = Arc::new(Admission::new(amount(2, 20, 20), "test".into()).unwrap()); + let node = Arc::new(Admission::new(amount(2, 20, 20), None, "test".into()).unwrap()); let held = node - .reserve(amount(1, 10, 10), Some(amount(1, 10, 10))) + .reserve( + Phase::Background, + amount(1, 10, 10), + Some(amount(1, 10, 10)), + ) .unwrap(); assert!(held.child(amount(1, 11, 10)).is_err()); let child = held.child(amount(1, 10, 10)).unwrap(); assert!(held.child(amount(1, 10, 10)).is_err()); drop(held); - assert!(node.reserve(amount(1, 1, 1), None).is_err()); + assert!(node + .reserve(Phase::Background, amount(1, 1, 1), None) + .is_err()); drop(child); - assert_eq!(*node.used.lock().unwrap(), Capacity::default()); - assert!(node.reserve(amount(1, 10, 10), None).is_ok()); + assert_eq!(*node.used.lock().unwrap(), Usage::default()); + assert!(node + .reserve(Phase::Background, amount(1, 10, 10), None) + .is_ok()); } #[test] fn competing_invocations_cannot_split_peak_capacity() { - let node = Arc::new(Admission::new(amount(2, 20, 20), "test".into()).unwrap()); + let node = Arc::new(Admission::new(amount(2, 20, 20), None, "test".into()).unwrap()); let barrier = Arc::new(Barrier::new(3)); let workers: Vec<_> = (0..2) .map(|_| { @@ -218,7 +351,11 @@ mod tests { let barrier = barrier.clone(); std::thread::spawn(move || { barrier.wait(); - let held = node.reserve(amount(1, 10, 10), Some(amount(1, 10, 10))); + let held = node.reserve( + Phase::Background, + amount(1, 10, 10), + Some(amount(1, 10, 10)), + ); barrier.wait(); held }) @@ -229,32 +366,47 @@ mod tests { let held: Vec<_> = workers.into_iter().map(|w| w.join().unwrap()).collect(); assert_eq!(held.iter().filter(|v| v.is_ok()).count(), 1); drop(held); - assert_eq!(*node.used.lock().unwrap(), Capacity::default()); + assert_eq!(*node.used.lock().unwrap(), Usage::default()); } #[test] fn unsettled_child_quarantines_the_node_until_restart() { - let node = Arc::new(Admission::new(amount(2, 20, 20), "test".into()).unwrap()); + let node = Arc::new( + Admission::new(amount(3, 30, 30), Some(amount(1, 10, 10)), "test".into()).unwrap(), + ); let held = node - .reserve(amount(1, 10, 10), Some(amount(1, 10, 10))) + .reserve( + Phase::Background, + amount(1, 10, 10), + Some(amount(1, 10, 10)), + ) .unwrap(); held.child(amount(1, 10, 10)).unwrap().quarantine(); drop(held); - assert!(node.reserve(amount(1, 1, 1), None).is_err()); + assert!(node.reserve(Phase::Pre, amount(1, 1, 1), None).is_err()); + assert!(node + .reserve(Phase::Background, amount(1, 1, 1), None) + .is_err()); assert!(node.reserved_storage_bytes().is_err()); - assert_eq!(node.used.lock().unwrap().storage_bytes, 20); + assert_eq!(node.used.lock().unwrap().background.storage_bytes, 20); } #[test] fn uncertain_scratch_cleanup_closes_admission_after_credit_release() { - let node = Arc::new(Admission::new(amount(2, 20, 20), "test".into()).unwrap()); + let node = Arc::new(Admission::new(amount(2, 20, 20), None, "test".into()).unwrap()); let held = node - .reserve(amount(1, 10, 10), Some(amount(1, 10, 10))) + .reserve( + Phase::Background, + amount(1, 10, 10), + Some(amount(1, 10, 10)), + ) .unwrap(); node.quarantine(); drop(held); - assert_eq!(*node.used.lock().unwrap(), Capacity::default()); - assert!(node.reserve(amount(1, 1, 1), None).is_err()); + assert_eq!(*node.used.lock().unwrap(), Usage::default()); + assert!(node + .reserve(Phase::Background, amount(1, 1, 1), None) + .is_err()); assert!(node.reserved_storage_bytes().is_err()); } } diff --git a/external_checkers/workstream-checker-service/src/smol/intake.rs b/external_checkers/workstream-checker-service/src/smol/intake.rs index 852ea795d..327a43b71 100644 --- a/external_checkers/workstream-checker-service/src/smol/intake.rs +++ b/external_checkers/workstream-checker-service/src/smol/intake.rs @@ -285,7 +285,7 @@ pub(crate) fn serve( let deadline = Instant::now() + Duration::from_millis(request.deadline_ms); // Intake explicitly allocates a separate 1 GiB writable root overlay. let capacity = resource_capacity(resources, Some(1))?; - let reservation = match reserve_capacity(config, capacity, None) { + let reservation = match reserve_capacity(config, Phase::Background, capacity, None) { Ok(value) => value, Err(_) => { return send( @@ -926,15 +926,17 @@ mod tests { assert_eq!(intake.storage_bytes, data_only.storage_bytes + GIB); assert_eq!(intake.slots, data_only.slots); assert_eq!(intake.memory_bytes, data_only.memory_bytes); - let insufficient = Arc::new(Admission::new(data_only, "a".repeat(64)).unwrap()); - assert!(insufficient.reserve(intake, None).is_err()); - let node = Arc::new(Admission::new(intake, "b".repeat(64)).unwrap()); - let reservation = node.reserve(intake, None).unwrap(); + let insufficient = Arc::new(Admission::new(data_only, None, "a".repeat(64)).unwrap()); + assert!(insufficient + .reserve(Phase::Background, intake, None) + .is_err()); + let node = Arc::new(Admission::new(intake, None, "b".repeat(64)).unwrap()); + let reservation = node.reserve(Phase::Background, intake, None).unwrap(); assert_eq!(node.reserved_storage_bytes().unwrap(), intake.storage_bytes); - assert!(node.reserve(intake, None).is_err()); + assert!(node.reserve(Phase::Background, intake, None).is_err()); drop(reservation); assert_eq!(node.reserved_storage_bytes().unwrap(), 0); - assert!(node.reserve(intake, None).is_ok()); + assert!(node.reserve(Phase::Background, intake, None).is_ok()); assert!(resource_capacity( Resources { storage_gib: u64::MAX, diff --git a/external_checkers/workstream-checker-service/src/smol/pre.rs b/external_checkers/workstream-checker-service/src/smol/pre.rs index e63eadb5f..2149f286d 100644 --- a/external_checkers/workstream-checker-service/src/smol/pre.rs +++ b/external_checkers/workstream-checker-service/src/smol/pre.rs @@ -45,6 +45,7 @@ pub(crate) fn serve( let deadline = prepared.deadline; let _reservation = reserve_capacity( config, + Phase::Pre, resource_capacity(prepared.resources, Some(prepared.overlay_gib))?, None, )?; diff --git a/external_checkers/workstream-checker-service/src/smol/pre/admission.rs b/external_checkers/workstream-checker-service/src/smol/pre/admission.rs index af5c3c92b..9d4bbeb31 100644 --- a/external_checkers/workstream-checker-service/src/smol/pre/admission.rs +++ b/external_checkers/workstream-checker-service/src/smol/pre/admission.rs @@ -12,10 +12,46 @@ pub(crate) struct Config { pub root: RootDescriptor, pub root_limits: RootLimits, pub limits: PreBootstrapLimits, + pub reserved_capacity: Capacity, pub smol_binary_sha256: String, pub guest_sha256: String, } +impl Config { + pub(in crate::smol) fn node_reserve(&self) -> Result { + let (resources, overlay_gib) = self.resources(self.limits.maximum_source_bytes)?; + let required = resource_capacity(resources, Some(overlay_gib))?; + if !required.fits(self.reserved_capacity) { + return Err("PRE reserve cannot fit the configured profile".into()); + } + Ok(self.reserved_capacity) + } + + fn resources(&self, source_bytes: u64) -> Result<(Resources, u64), String> { + let limits = &self.limits; + let storage = sum([ + self.root.bundle_byte_count, + self.root.expanded_bytes, + source_bytes, + number(&self.profile["archive_limits"], "maximum_expanded_bytes")?, + limits.worker_scratch_bytes, + limits.project_scratch_bytes, + limits.filesystem_overhead_bytes, + ])?; + if sum([storage, limits.overlay_bytes])? > number(&self.profile, "temporary_disk_bytes")? { + return Err("PRE disk exceeds profile".into()); + } + const GIB: u64 = 1 << 30; + let resources = Resources { + cpu_millis: number(&self.profile, "cpu_millis")?, + memory_bytes: number(&self.profile, "memory_bytes")?, + pids: number(&self.profile, "maximum_processes")?, + storage_gib: storage.div_ceil(GIB), + }; + Ok((resources, limits.overlay_bytes.div_ceil(GIB))) + } +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Header { @@ -414,32 +450,7 @@ pub(super) fn prepare<'a>(config: &'a ServiceConfig, bytes: &[u8]) -> Result

 number(profile, "temporary_disk_bytes")? {
-        return Err("PRE disk exceeds profile".into());
-    }
-    let gib = |bytes: u64| {
-        bytes
-            .checked_add((1 << 30) - 1)
-            .map(|n| n / (1 << 30))
-            .ok_or("PRE capacity overflow")
-    };
-    let resources = Resources {
-        cpu_millis: number(profile, "cpu_millis")?,
-        memory_bytes: number(profile, "memory_bytes")?,
-        pids: number(profile, "maximum_processes")?,
-        storage_gib: gib(storage)?,
-    };
-    let overlay_gib = gib(limits.overlay_bytes)?;
-    resource_capacity(resources, Some(overlay_gib))?;
+    let (resources, overlay_gib) = configured.resources(number(source, "raw_byte_count")?)?;
     let invocation = Invocation {
         operation: Operation::ExecutePre,
         run_id: text(reservation, "attempt_id")?.into(),
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs
index 9a9220c6e..27604cb3a 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/admission/tests.rs
@@ -37,6 +37,11 @@ pub(crate) fn fixture() -> (PathBuf, ServiceConfig, Value) {
     config.pre = Some(Config {
         profile_sha256: hash(&profile).unwrap(),
         profile,
+        reserved_capacity: Capacity {
+            slots: 1,
+            memory_bytes: (2 << 30) + 512 * 1024 * 1024,
+            storage_bytes: 2 << 30,
+        },
         root_bundle: root.join("root.bundle"),
         root: RootDescriptor {
             schema_version: "workstream.trusted_root.v1".into(),
@@ -94,6 +99,22 @@ pub(crate) fn fixture() -> (PathBuf, ServiceConfig, Value) {
     (root, config, header)
 }
 
+#[test]
+fn node_reserve_covers_maximum_configured_pre_and_rounds_overlay_separately() {
+    let (root, mut config, _) = fixture();
+    let pre = config.pre.as_mut().unwrap();
+    let reserve = pre.node_reserve().unwrap();
+    pre.reserved_capacity.memory_bytes -= 1;
+    assert!(pre.node_reserve().is_err());
+    pre.reserved_capacity = reserve;
+    pre.reserved_capacity.storage_bytes -= 1;
+    assert!(pre.node_reserve().is_err());
+    pre.reserved_capacity = reserve;
+    pre.limits.maximum_source_bytes += 1 << 30;
+    assert!(pre.node_reserve().is_err());
+    fs::remove_dir_all(root).unwrap();
+}
+
 #[test]
 fn pre_admission_binds_actual_run_and_charges_rounded_storage_and_overlay() {
     let (root, config, header) = fixture();
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
index 97958ea91..d5abbf2fe 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
@@ -59,17 +59,22 @@ pub(super) fn fixture() -> (PathBuf, ServiceConfig, Lease, Journal) {
         guest_binary: root.join("guest"),
         guest_sha256: format!("sha256:{}", "b".repeat(64)),
         cgroup_root: root.join("groups"),
-        maximum_parallel: 1,
+        maximum_parallel: 2,
         maximum_storage_bytes: 4 * 1024 * 1024 * 1024,
     };
     config.smol = Some(runtime.clone());
     config.smol_admission = Some(Arc::new(
         Admission::new(
             Capacity {
-                slots: 1,
+                slots: 2,
                 memory_bytes: u64::MAX,
                 storage_bytes: u64::MAX,
             },
+            Some(Capacity {
+                slots: 1,
+                memory_bytes: 1,
+                storage_bytes: 1,
+            }),
             "e".repeat(64),
         )
         .unwrap(),
@@ -122,6 +127,7 @@ fn pending_cleanup_requires_exact_pre_journal_and_quarantines_admission() {
         .as_ref()
         .unwrap()
         .reserve(
+            Phase::Pre,
             Capacity {
                 slots: 1,
                 memory_bytes: 1,
@@ -154,6 +160,7 @@ fn lost_journal_still_quarantines_the_node() {
         .as_ref()
         .unwrap()
         .reserve(
+            Phase::Pre,
             Capacity {
                 slots: 1,
                 memory_bytes: 1,
diff --git a/external_checkers/workstream-checker-service/src/smol/tests.rs b/external_checkers/workstream-checker-service/src/smol/tests.rs
index 8ed7b0913..8304a494e 100644
--- a/external_checkers/workstream-checker-service/src/smol/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/tests.rs
@@ -49,19 +49,19 @@ fn trial_peak_reservation_admits_maximum_memory_and_overrun_atomically() {
         memory_bytes: outer.memory_bytes + peak.memory_bytes,
         storage_bytes: outer.storage_bytes + peak.storage_bytes,
     };
-    let node = Arc::new(Admission::new(maximum, "e".repeat(64)).unwrap());
-    let invocation = node.reserve(outer, Some(peak)).unwrap();
+    let node = Arc::new(Admission::new(maximum, None, "e".repeat(64)).unwrap());
+    let invocation = node.reserve(Phase::Background, outer, Some(peak)).unwrap();
     let child = invocation
         .child(trial_capacity(maximum_memory + overrun, disk).unwrap())
         .unwrap();
-    assert!(node.reserve(outer, None).is_err());
+    assert!(node.reserve(Phase::Background, outer, None).is_err());
     drop(child);
     drop(invocation);
     let mut insufficient = maximum;
     insufficient.memory_bytes -= 1;
-    let node = Arc::new(Admission::new(insufficient, "f".repeat(64)).unwrap());
-    assert!(node.reserve(outer, Some(peak)).is_err());
-    assert!(node.reserve(outer, None).is_ok());
+    let node = Arc::new(Admission::new(insufficient, None, "f".repeat(64)).unwrap());
+    assert!(node.reserve(Phase::Background, outer, Some(peak)).is_err());
+    assert!(node.reserve(Phase::Background, outer, None).is_ok());
     assert!(trial_peak_capacity(u64::MAX, 1, disk).is_err());
 }
 
@@ -136,6 +136,7 @@ fn missing_lease_directory_does_not_poison_node_admission() {
                 memory_bytes: 1024 * 1024 * 1024,
                 storage_bytes: 4 * 1024 * 1024 * 1024,
             },
+            None,
             "e".repeat(64),
         )
         .unwrap(),
@@ -196,6 +197,7 @@ fn concurrent_capacity_is_reserved_until_its_owner_releases_it() {
                 memory_bytes: capacity,
                 storage_bytes: 4 * 1024 * 1024 * 1024,
             },
+            None,
             "e".repeat(64),
         )
         .unwrap(),
@@ -305,12 +307,14 @@ fn quarantined_admission_makes_runtime_health_unavailable() {
                 memory_bytes: 20,
                 storage_bytes: 20,
             },
+            None,
             "e".repeat(64),
         )
         .unwrap(),
     );
     let held = admission
         .reserve(
+            Phase::Background,
             Capacity {
                 slots: 1,
                 memory_bytes: 10,
diff --git a/external_checkers/workstream-checker-service/src/smol/trial.rs b/external_checkers/workstream-checker-service/src/smol/trial.rs
index 9cfb61c1a..3bbd01585 100644
--- a/external_checkers/workstream-checker-service/src/smol/trial.rs
+++ b/external_checkers/workstream-checker-service/src/smol/trial.rs
@@ -1119,7 +1119,7 @@ impl SmolTrialRuntime for Runtime {
 #[cfg(test)]
 mod tests {
     use super::*;
-    use crate::smol::{Admission, Capacity};
+    use crate::smol::{Admission, Capacity, Phase};
     use crate::trial_engine::{image_archive::ValidatedImageArchive, SandboxEnforcementOverruns};
     use crate::trial_relay::TrialResources;
     use std::os::unix::fs::PermissionsExt;
@@ -1204,11 +1204,14 @@ mod tests {
                     memory_bytes: 2,
                     storage_bytes: 2,
                 },
+                None,
                 "test".into(),
             )
             .unwrap(),
         );
-        let reservation = admission.reserve(credit, Some(credit)).unwrap();
+        let reservation = admission
+            .reserve(Phase::Background, credit, Some(credit))
+            .unwrap();
         let invocation_cancelled = Arc::new(AtomicBool::new(false));
         let (client, _connected_peer) = UnixStream::pair().unwrap();
         let deadline = Instant::now() + Duration::from_secs(5);
diff --git a/external_checkers/workstream-checker-service/src/trial_smol.rs b/external_checkers/workstream-checker-service/src/trial_smol.rs
index 38de596e3..1597f10b5 100644
--- a/external_checkers/workstream-checker-service/src/trial_smol.rs
+++ b/external_checkers/workstream-checker-service/src/trial_smol.rs
@@ -606,7 +606,7 @@ fn infrastructure(code: TrialRelayFailure) -> SandboxFailure {
 #[cfg(test)]
 mod tests {
     use super::*;
-    use crate::smol::{Admission, Capacity};
+    use crate::smol::{Admission, Capacity, Phase};
     use crate::trial_engine::SandboxEnforcementOverruns;
 
     struct NoopRuntime;
@@ -681,12 +681,14 @@ mod tests {
                     memory_bytes: 2 * 1024 * 1024,
                     storage_bytes: 2 * 1024 * 1024,
                 },
+                None,
                 "epoch".into(),
             )
             .unwrap(),
         );
         let reservation = admission
             .reserve(
+                Phase::Background,
                 Capacity {
                     slots: 1,
                     memory_bytes: 1024,
diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py
index 48bea5107..286d5753b 100644
--- a/scripts/test_public_hosted_attachment.py
+++ b/scripts/test_public_hosted_attachment.py
@@ -46,7 +46,10 @@ def test_separate_runner_uses_exact_baseline_config_without_local_fault_files(se
         from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe
 
         source, binary = 'b' * 40, 'sha256:' + 'c' * 64
-        configuration = {"smol": {"binary": "/runner/smolvm", "binary_sha256": binary}}
+        configuration = {
+            "smol": {"binary": "/runner/smolvm", "binary_sha256": binary, "maximum_parallel": 2},
+            "pre": {"reserved_capacity": {"slots": 1, "memory_bytes": 2684354560, "storage_bytes": 5368709120}},
+        }
         encoded = json.dumps(configuration).encode()
         custody = {
             'source_tree': source,
@@ -66,6 +69,9 @@ def test_separate_runner_uses_exact_baseline_config_without_local_fault_files(se
             config.write_bytes(encoded + b'\n')
             with self.assertRaisesRegex(RuntimeError, 'separate runner configuration differs'):
                 probe._read_runner_configuration(config, root, custody, separate_runner=True)
+            config.write_text(json.dumps({"smol": configuration["smol"]}))
+            with self.assertRaisesRegex(RuntimeError, 'requires an explicit PRE reservation'):
+                probe._read_runner_configuration(config, root, custody, separate_runner=True)
 
     def test_cleanup_child_alone_receives_a_private_distinct_principal(self):
         from pydantic import SecretStr
diff --git a/scripts/test_public_smol_proof.py b/scripts/test_public_smol_proof.py
index f4276f002..9527dfd45 100644
--- a/scripts/test_public_smol_proof.py
+++ b/scripts/test_public_smol_proof.py
@@ -373,8 +373,9 @@ def test_exact_live_unit_binding_rejects_foreign_unit_config_and_binary(self):
         owner.chmod(0o600)
         config_path = self.root / 'service.json'
         config = {'socket_path': str(socket_root / 'checker.sock'), 'smol': {
-            'binary': str(smol), 'guest_binary': str(guest), 'maximum_parallel': 1,
-            'cgroup_root': '/sys/fs/cgroup/system.slice/ws-proof.service'}}
+            'binary': str(smol), 'guest_binary': str(guest), 'maximum_parallel': 2,
+            'cgroup_root': '/sys/fs/cgroup/system.slice/ws-proof.service'},
+            'pre': {'reserved_capacity': {'slots': 1, 'memory_bytes': 3 << 30, 'storage_bytes': 5 << 30}}}
         config_path.write_text(json.dumps(config))
         config_path.chmod(0o600)
         manifest = {'unit': 'ws-proof.service', 'config': str(config_path),
@@ -409,14 +410,14 @@ def output(command, **kwargs):
             with self.assertRaises(ValueError):
                 validate_node(config_path, config, 'ws-proof.service', manifest_path)
             argv[1] = str(config_path)
-            config['smol']['maximum_parallel'] = 2
+            config['smol']['maximum_parallel'] = 1
             config_path.write_text(json.dumps(config))
             manifest['node_config'] = config
             manifest['config_sha256'] = digest(config_path)
             manifest_path.write_text(json.dumps(manifest))
-            with self.assertRaisesRegex(ValueError, 'one-slot'):
+            with self.assertRaisesRegex(ValueError, 'one slot per phase'):
                 validate_node(config_path, config, 'ws-proof.service', manifest_path)
-            config['smol']['maximum_parallel'] = 1
+            config['smol']['maximum_parallel'] = 2
             config_path.write_text(json.dumps(config))
             manifest['node_config'] = config
             manifest['config_sha256'] = digest(config_path)

From 65a81f49869fc27ee80eae79b833dfe3b725324c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 12:24:37 +0100
Subject: [PATCH 415/513] Protect PRE physical disk before background admission

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  30 +++++
 external_checkers/README.md                   |  17 ++-
 .../workstream-checker-service/src/smol.rs    |   9 +-
 .../src/smol/admission.rs                     | 107 +++++++++++++++---
 .../src/smol/tests.rs                         |  76 +++++++++++++
 .../tests/smol_creation.py                    |   9 +-
 .../tests/smol_recovery.py                    |  35 +++---
 .../tests/smol_runtime.py                     |   9 ++
 8 files changed, 242 insertions(+), 50 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index ea9e5808d..56df9d7c9 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -11971,3 +11971,33 @@ requires a measured two-phase configuration before installing this revision.
 Use an owned saturation test to measure true POST/PRE/T5 overlap and the
 interactive tail on the existing host. A POST profile that reserves a trial
 also requires a second POST slot and its exact memory/disk peak.
+
+Admission review found a physical disk edge. At the exact combined free-space
+floor, a live POST can allocate its reserved bytes before PRE checks current
+free space. The shared physical check must still count all live commitments
+because active VM and trial disks can grow. The bounded correction stays in
+`src/smol/admission.rs`, `src/smol.rs`, their existing filesystem test owner,
+`external_checkers/README.md`, and this record. A PRE-enabled node requires
+twice the sum of the PRE pool and occupied background peak in currently free
+disk before starting background work. This leaves room for potential allocation and
+the conservative concurrent check. It assumes each admitted invocation obeys
+its existing peak and cannot guard disk use outside the node's reservations.
+The filesystem observation and reservation decision now share the admission
+lock, and a rejected proposal never becomes visible as live usage. Recheck
+whole-node quarantine after the observation.
+
+The generic `execute` fixture in `tests/smol_runtime.py` is also in scope with
+its `tests/smol_creation.py` and `tests/smol_recovery.py` callers. Use only
+background slots in all three probes, including PRE-shaped inputs. The
+creation probe passes a second check alongside the long-running control
+before fault injection, establishing physical capacity to reach the faults.
+The recovery probe matches the framed refusal to the exact extra request and
+requires an infrastructure result without guest isolation evidence.
+
+The final targeted `smol::` run passed 58 tests, including the concurrent
+refusal and real filesystem allocation regressions. One unchanged PRE
+transport fixture exceeded its 500 ms deadline during the parallel run and
+passed when rerun individually. Its deadline remains intact. The three
+Python fixtures compiled and their shared background-slot calculation passed
+both single-pool and partitioned examples. The native probes still require an
+owned runner and were not started for this review correction.
diff --git a/external_checkers/README.md b/external_checkers/README.md
index 0d30f49d5..3d7f4ec34 100644
--- a/external_checkers/README.md
+++ b/external_checkers/README.md
@@ -323,11 +323,14 @@ host memory overhead and separately rounded VM and overlay disk. The remaining
 node capacity must have positive slots, memory, and storage for POST and
 trusted ART preparation. The node derives its total allocable memory from
 the delegated cgroup and checks actual disk space before creating each VM.
-Background reservations leave the configured PRE disk budget available while
-PRE is idle. POST with a trial consumes capacity for the outer VM and one
-sequential child at their combined peak. Per-VM CPU ceilings still share the
-parent cgroup limit. Size and measure concurrency on the chosen host before
-publishing an interactive latency envelope.
+Before starting POST or trusted ART preparation on a PRE-enabled node, free
+disk must cover twice the sum of the PRE disk reserve and the admitted
+background peak including the incoming job. This conservative threshold keeps
+room for the live reservations and their physical allocation. Disk use outside
+the node still reduces available space. POST with a trial consumes capacity for
+the outer VM and one sequential child at their combined peak. Per-VM CPU
+ceilings still share the parent cgroup limit. Size and measure concurrency on
+the chosen host before publishing an interactive latency envelope.
 
 Each existing cache entry additionally has `smol.archive`,
 `smol.archive_sha256` and `smol.image_config`. The
@@ -395,7 +398,9 @@ failure while checking foreign VM/cgroup survival, bounded cleanup and closed
 readiness. The [creation proof](workstream-checker-service/tests/smol_creation.py)
 checks that denied lease or cgroup creation preserves an already running check
 and keeps the controller available after confirmed cleanup. Never run either
-proof against a shared production node.
+proof against a shared production node. The runtime, recovery and creation
+drills send the generic execution operation. Their slot measurements use only
+background capacity, including steps with a PRE-shaped request.
 The [guest mount proof](workstream-checker-service/tests/smol_guest_mounts.py)
 uses a clean image and two variants built from the
 [test Dockerfile](workstream-checker-service/tests/fixtures/mount-targets/Dockerfile)
diff --git a/external_checkers/workstream-checker-service/src/smol.rs b/external_checkers/workstream-checker-service/src/smol.rs
index 169e15e5b..15bff2c84 100644
--- a/external_checkers/workstream-checker-service/src/smol.rs
+++ b/external_checkers/workstream-checker-service/src/smol.rs
@@ -199,14 +199,7 @@ fn reserve_capacity(
         .smol_admission
         .as_ref()
         .ok_or("admission unavailable")?;
-    let reservation = admission.reserve(phase, outer, child)?;
-    // Reserve atomically first, then recheck physical space. A failure drops the
-    // complete reservation; no VM or provider operation has begun.
-    let required = admission.required_storage_bytes(phase)?;
-    if available_storage(settings(config)?)? < required {
-        return Err("node storage unavailable".into());
-    }
-    Ok(reservation)
+    admission.reserve_with_storage(phase, outer, child, || available_storage(settings(config)?))
 }
 fn available_storage(s: &SmolConfig) -> Result {
     let directory = File::open(&s.home).map_err(|_| "Smol storage unavailable")?;
diff --git a/external_checkers/workstream-checker-service/src/smol/admission.rs b/external_checkers/workstream-checker-service/src/smol/admission.rs
index a4e7e4512..64b2ea827 100644
--- a/external_checkers/workstream-checker-service/src/smol/admission.rs
+++ b/external_checkers/workstream-checker-service/src/smol/admission.rs
@@ -47,7 +47,7 @@ pub(crate) enum Phase {
     Background,
 }
 
-#[derive(Debug, Default, PartialEq, Eq)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
 struct Usage {
     pre: Capacity,
     background: Capacity,
@@ -84,16 +84,19 @@ impl Admission {
         Ok(used.pre.storage_bytes + used.background.storage_bytes)
     }
 
-    // For a background reservation, keep space for PRE even while the PRE partition is empty.
-    pub(super) fn required_storage_bytes(&self, phase: Phase) -> Result {
+    fn required_storage_bytes(&self, phase: Phase, used: Usage) -> Result {
         match phase {
-            Phase::Pre => self.reserved_storage_bytes(),
+            Phase::Pre => Ok(used.pre.storage_bytes + used.background.storage_bytes),
             Phase::Background => {
-                let used = self.used.lock().map_err(|_| "node admission unavailable")?;
-                if self.poisoned.load(Ordering::SeqCst) {
-                    return Err("node admission quarantined".into());
+                if self.pre_maximum.slots == 0 {
+                    return Ok(used.background.storage_bytes);
                 }
-                Ok(self.pre_maximum.storage_bytes + used.background.storage_bytes)
+                // The free-space sample falls as active disks are physically allocated.
+                // Leave PRE sufficient free space for the conservative live-peak check
+                // even after all declared foreground and background bytes materialize.
+                (self.pre_maximum.storage_bytes + used.background.storage_bytes)
+                    .checked_mul(2)
+                    .ok_or_else(|| "node storage capacity overflow".into())
             }
         }
     }
@@ -123,11 +126,12 @@ impl Admission {
         })
     }
 
-    pub(crate) fn reserve(
+    pub(super) fn reserve_with_storage(
         self: &Arc,
         phase: Phase,
         outer: Capacity,
         child: Option,
+        available_storage: impl FnOnce() -> Result,
     ) -> Result, String> {
         if outer.slots != 1
             || outer.memory_bytes == 0
@@ -150,12 +154,21 @@ impl Admission {
         };
         // Both ceilings are disjoint partitions of the node maximum. Charging either
         // under this same lock keeps their aggregate within the node maximum.
-        let phase_usage = used.for_phase(phase);
-        let next = phase_usage
+        let mut proposed = *used;
+        let phase_usage = proposed.for_phase(phase);
+        *phase_usage = phase_usage
             .checked_add(charge)
             .filter(|v| v.fits(maximum))
             .ok_or("capacity unavailable")?;
-        *phase_usage = next;
+        // The storage observation and both charges share one admission decision.
+        // A refused background request never takes even temporary PRE headroom.
+        if available_storage()? < self.required_storage_bytes(phase, proposed)? {
+            return Err("node storage unavailable".into());
+        }
+        if self.poisoned.load(Ordering::SeqCst) {
+            return Err("node admission quarantined".into());
+        }
+        *used = proposed;
         Ok(Arc::new(Reservation {
             admission: self.clone(),
             phase,
@@ -164,6 +177,16 @@ impl Admission {
             child_active: AtomicBool::new(false),
         }))
     }
+
+    #[cfg(test)]
+    pub(crate) fn reserve(
+        self: &Arc,
+        phase: Phase,
+        outer: Capacity,
+        child: Option,
+    ) -> Result, String> {
+        self.reserve_with_storage(phase, outer, child, || Ok(u64::MAX))
+    }
 }
 
 #[derive(Debug)]
@@ -284,13 +307,15 @@ mod tests {
         let pre = amount(1, 8, 16);
         let job = amount(1, 6, 7);
         let node = Arc::new(Admission::new(amount(3, 20, 30), Some(pre), "test".into()).unwrap());
-        let post = node.reserve(Phase::Background, job, Some(job)).unwrap();
+        let post = node
+            .reserve_with_storage(Phase::Background, job, Some(job), || Ok(60))
+            .unwrap();
         let child = post.child(job).unwrap();
         assert_eq!(node.reserved_storage_bytes().unwrap(), 14);
-        assert_eq!(node.required_storage_bytes(Phase::Background).unwrap(), 30);
         assert!(node.reserve(Phase::Background, job, None).is_err());
-        let foreground = node.reserve(Phase::Pre, pre, None).unwrap();
-        assert_eq!(node.required_storage_bytes(Phase::Pre).unwrap(), 30);
+        let foreground = node
+            .reserve_with_storage(Phase::Pre, pre, None, || Ok(30))
+            .unwrap();
         assert!(node.reserve(Phase::Pre, pre, None).is_err());
 
         drop(post);
@@ -302,6 +327,56 @@ mod tests {
         assert_eq!(node.reserved_storage_bytes().unwrap(), 0);
     }
 
+    #[test]
+    fn physical_headroom_overflow_refuses_background_without_changing_pre() {
+        let pre = amount(1, 10, 1);
+        let background = amount(1, 10, u64::MAX / 2);
+        let node =
+            Arc::new(Admission::new(amount(2, 20, u64::MAX), Some(pre), "test".into()).unwrap());
+        assert!(node.reserve(Phase::Background, background, None).is_err());
+        assert_eq!(node.reserved_storage_bytes().unwrap(), 0);
+        assert!(node
+            .reserve_with_storage(Phase::Pre, pre, None, || Ok(pre.storage_bytes))
+            .is_ok());
+    }
+
+    #[test]
+    fn tentative_background_storage_cannot_displace_foreground() {
+        let pre = amount(1, 10, 16);
+        let post = amount(1, 10, 14);
+        let node = Arc::new(Admission::new(amount(2, 20, 30), Some(pre), "test".into()).unwrap());
+        let checking_storage = Arc::new(Barrier::new(2));
+        let finish_storage_check = Arc::new(Barrier::new(2));
+        let background = {
+            let node = node.clone();
+            let checking_storage = checking_storage.clone();
+            let finish_storage_check = finish_storage_check.clone();
+            std::thread::spawn(move || {
+                node.reserve_with_storage(Phase::Background, post, None, || {
+                    checking_storage.wait();
+                    finish_storage_check.wait();
+                    Ok(30)
+                })
+            })
+        };
+        checking_storage.wait();
+        let free = 16;
+        let storage_and_usage_locked = matches!(
+            node.used.try_lock(),
+            Err(std::sync::TryLockError::WouldBlock)
+        );
+        let foreground = {
+            let node = node.clone();
+            std::thread::spawn(move || {
+                node.reserve_with_storage(Phase::Pre, pre, None, || Ok(free))
+            })
+        };
+        finish_storage_check.wait();
+        assert!(background.join().unwrap().is_err());
+        assert!(foreground.join().unwrap().is_ok());
+        assert!(storage_and_usage_locked);
+    }
+
     #[test]
     fn every_limit_is_atomic_and_failed_admission_leaks_nothing() {
         for limit in [amount(1, 200, 200), amount(2, 19, 200), amount(2, 200, 19)] {
diff --git a/external_checkers/workstream-checker-service/src/smol/tests.rs b/external_checkers/workstream-checker-service/src/smol/tests.rs
index 8304a494e..45b87a4c1 100644
--- a/external_checkers/workstream-checker-service/src/smol/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/tests.rs
@@ -65,6 +65,82 @@ fn trial_peak_reservation_admits_maximum_memory_and_overrun_atomically() {
     assert!(trial_peak_capacity(u64::MAX, 1, disk).is_err());
 }
 
+#[test]
+fn background_disk_allocation_preserves_physical_pre_headroom() {
+    let (root, _) = super::super::tests::test_config();
+    const MIB: u64 = 1024 * 1024;
+    let pre = Capacity {
+        slots: 1,
+        memory_bytes: 1,
+        storage_bytes: 64 * MIB,
+    };
+    let post = Capacity {
+        storage_bytes: 4 * MIB,
+        ..pre
+    };
+    let total_disk = pre.storage_bytes + post.storage_bytes;
+    let smol = SmolConfig {
+        binary: root.join("unused-runtime"),
+        binary_sha256: "unused".into(),
+        home: root.clone(),
+        guest_binary: root.join("unused-guest"),
+        guest_sha256: "unused".into(),
+        cgroup_root: root.join("unused-cgroup"),
+        maximum_parallel: 2,
+        maximum_storage_bytes: total_disk,
+    };
+    let node = Arc::new(
+        Admission::new(
+            Capacity {
+                slots: 2,
+                memory_bytes: 2,
+                storage_bytes: total_disk,
+            },
+            Some(pre),
+            "test".into(),
+        )
+        .unwrap(),
+    );
+
+    let free_at_start = available_storage(&smol).unwrap();
+    // Model a smaller node budget without filling a shared test filesystem.
+    let outside_tight_budget = free_at_start.checked_sub(total_disk).unwrap();
+    let tight_free = free_at_start - outside_tight_budget;
+    assert!(node
+        .reserve_with_storage(Phase::Background, post, None, || Ok(tight_free))
+        .is_err());
+    let foreground = node
+        .reserve_with_storage(Phase::Pre, pre, None, || Ok(tight_free))
+        .unwrap();
+    drop(foreground);
+
+    let outside_sufficient_budget = free_at_start.checked_sub(2 * total_disk).unwrap();
+    let background = node
+        .reserve_with_storage(Phase::Background, post, None, || {
+            Ok(free_at_start - outside_sufficient_budget)
+        })
+        .unwrap();
+    let disk = OpenOptions::new()
+        .write(true)
+        .create_new(true)
+        .open(root.join("background-disk"))
+        .unwrap();
+    // Unlike set_len(), fallocate actually consumes filesystem blocks.
+    let allocation =
+        unsafe { libc::posix_fallocate(disk.as_raw_fd(), 0, post.storage_bytes as i64) };
+    assert_eq!(allocation, 0);
+    disk.sync_all().unwrap();
+    assert!(disk.metadata().unwrap().blocks() * 512 >= post.storage_bytes);
+
+    let foreground = node
+        .reserve_with_storage(Phase::Pre, pre, None, || {
+            Ok(available_storage(&smol)? - outside_sufficient_budget)
+        })
+        .unwrap();
+    drop((foreground, background, disk));
+    fs::remove_dir_all(root).unwrap();
+}
+
 #[test]
 fn foreign_lease_refuses_recovery_before_any_runtime_or_owned_cleanup() {
     let (root, mut config) = super::super::tests::test_config();
diff --git a/external_checkers/workstream-checker-service/tests/smol_creation.py b/external_checkers/workstream-checker-service/tests/smol_creation.py
index c0eb5a56d..9e611e2fd 100644
--- a/external_checkers/workstream-checker-service/tests/smol_creation.py
+++ b/external_checkers/workstream-checker-service/tests/smol_creation.py
@@ -14,7 +14,7 @@
 import subprocess
 
 from smol_recovery import wait_until
-from smol_runtime import Proof, exchange
+from smol_runtime import Proof, background_slots, exchange
 
 
 def main():
@@ -28,8 +28,8 @@ def main():
         raise RuntimeError('run as the non-root node identity')
     leases = Path(config['socket_path']).parent / 'smol-leases'
     groups = Path(config['smol']['cgroup_root'])
-    if groups.name != args.unit or config['smol']['maximum_parallel'] < 2:
-        raise RuntimeError('expected isolated unit with two execution slots')
+    if groups.name != args.unit or background_slots(config) < 2:
+        raise RuntimeError('expected isolated unit with two background slots')
     depth = groups / 'cgroup.max.depth'
     original_depth = depth.read_text()
     original_mode = leases.stat().st_mode & 0o777
@@ -60,6 +60,9 @@ def set_depth(value):
             active = pool.submit(proof.execute, image, 'post_submit', 'sleep',
                                  expected='deadline_exceeded', deadline_ms=10000)
             wait_until(running, 'unrelated workload did not start')
+            proof.execute(image, 'pre_submit', 'pass')
+            if active.done() or not running():
+                raise AssertionError('parallel capacity control did not overlap unrelated work')
             for case in ('lease_create_denied', 'cgroup_create_denied'):
                 try:
                     if case == 'lease_create_denied':
diff --git a/external_checkers/workstream-checker-service/tests/smol_recovery.py b/external_checkers/workstream-checker-service/tests/smol_recovery.py
index 3408a40b8..d7948b0d7 100644
--- a/external_checkers/workstream-checker-service/tests/smol_recovery.py
+++ b/external_checkers/workstream-checker-service/tests/smol_recovery.py
@@ -25,7 +25,7 @@
 import tempfile
 import zipfile
 
-from smol_runtime import Proof, canonical, exchange, smol_vm_inventory
+from smol_runtime import Proof, background_slots, canonical, exchange, smol_vm_inventory
 
 
 def wait_until(predicate, description, timeout=30):
@@ -465,9 +465,9 @@ async def exercise(self, *, executor, harness, controller, service_binary,
                 assert controller.poll() is None
                 assert self.process_identity(controller.pid, service_binary) == controller_identity
 
-            # Two simultaneous real preparations fill this node's two slots.
+            # Two simultaneous real preparations fill this node's background slots.
             # A health response alone would not prove admission capacity reuse.
-            assert config["smol"]["maximum_parallel"] == 2
+            assert background_slots(config) == 2
             probe = io.BytesIO()
             with zipfile.ZipFile(probe, "w") as archive:
                 archive.writestr("capacity-probe.txt", b"bounded capacity probe")
@@ -952,6 +952,15 @@ def restart(self):
         subprocess.run(['sudo', 'systemctl', 'restart', self.unit], check=True, timeout=30)
         wait_until(self.ready, 'node failed to become ready')
 
+    def require_rejected_before_guest(self):
+        envelope = self.proof.request(self.image, 'pre_submit', 'pass')
+        response = exchange(self.config['socket_path'], envelope)
+        result = response['result']
+        assert result['request_digest'] == envelope['request']['request_digest']
+        assert result['outcome'] == 'infrastructure_failed'
+        assert result['infrastructure_failure_code'] == 'implementation_unavailable'
+        assert response['isolation'] is None
+
     def retry_proof(self):
         for remaining, expected_creates, case in (
             (1, 2, 'retry_after_confirmed_cleanup'),
@@ -961,12 +970,7 @@ def retry_proof(self):
             self.trace.write_text('')
             self.mode.write_text(str(remaining))
             if remaining == -1:
-                envelope = self.proof.request(self.image, 'pre_submit', 'pass')
-                response = exchange(self.config['socket_path'], envelope)
-                assert response['result']['request_digest'] == envelope['request']['request_digest']
-                assert response['result']['outcome'] == 'infrastructure_failed'
-                assert response['result']['infrastructure_failure_code'] == 'implementation_unavailable'
-                assert response['isolation'] is None
+                self.require_rejected_before_guest()
             elif remaining:
                 self.proof.execute(self.image, 'pre_submit', 'pass')
             else:
@@ -1003,15 +1007,12 @@ def run(self):
             wait_until(self.clean, 'disconnect leaked resources', timeout=15)
             self.report('disconnect_cleanup')
 
-            for _ in range(self.config['smol']['maximum_parallel']):
+            slots = background_slots(self.config)
+            for _ in range(slots):
                 self.start()
-            wait_until(lambda: self.running(self.config['smol']['maximum_parallel']), 'VMs did not overlap')
-            try:
-                extra = self.start()
-                assert extra.recv(1) == b'', 'capacity overflow was accepted'
-            except (ConnectionResetError, BrokenPipeError):
-                pass
-            assert len(self.owned()) == self.config['smol']['maximum_parallel']
+            wait_until(lambda: self.running(slots), 'VMs did not overlap')
+            self.require_rejected_before_guest()
+            assert len(self.owned()) == slots
             self.disconnect()
             wait_until(self.clean, 'capacity test leaked resources', timeout=15)
             self.report('concurrent_capacity_rejection')
diff --git a/external_checkers/workstream-checker-service/tests/smol_runtime.py b/external_checkers/workstream-checker-service/tests/smol_runtime.py
index 8bd58ad7d..9e41c66d1 100644
--- a/external_checkers/workstream-checker-service/tests/smol_runtime.py
+++ b/external_checkers/workstream-checker-service/tests/smol_runtime.py
@@ -78,6 +78,13 @@ def exchange(address, envelope):
         return json.loads(receive(connection, length))
 
 
+def background_slots(config):
+    """Generic execute and trusted intake use background capacity for either phase label."""
+    pre = config.get("pre")
+    reserved = pre["reserved_capacity"]["slots"] if pre is not None else 0
+    return config["smol"]["maximum_parallel"] - reserved
+
+
 class Proof:
     def __init__(self, config, fixtures):
         self.config = config
@@ -158,6 +165,8 @@ def main():
     parser.add_argument("--fixtures", type=Path, required=True)
     args = parser.parse_args()
     config = json.loads(args.config.read_text())
+    if background_slots(config) < 2:
+        raise ValueError("runtime matrix requires two background slots")
     assert config["sandbox_uid"] == os.geteuid() and config["sandbox_gid"] == os.getegid()
     python = next(c for c in config["cache"] if c["repository"] == "workstream-test/smol-python")
     native = next(c for c in config["cache"] if c["repository"] == "workstream-test/smol-native")

From a4b31f99d457c84021b1a19890e92f825079112e Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 12:37:50 +0100
Subject: [PATCH 416/513] test: qualify native policy cases with independent
 receipts

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 15 ++++++++
 .../run_public_journey_probe.py               | 34 +++++++++++++++++--
 scripts/test_public_hosted_attachment.py      | 20 +++++++++++
 3 files changed, 66 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 56df9d7c9..24eed6154 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12001,3 +12001,18 @@ passed when rerun individually. Its deadline remains intact. The three
 Python fixtures compiled and their shared background-slot calculation passed
 both single-pool and partitioned examples. The native probes still require an
 owned runner and were not started for this review correction.
+
+
+### Bound connected qualification by policy case
+
+The combined f480 run reached the automatic project after completing the
+default-policy revision and duplicate-delivery assertions, but the 2400-second
+harness bound expired before its final automatic receipt. Cleanup is true in
+`/tmp/workstream-paired-native-pefexu4d/cleanup.json`; the in-progress checkpoint
+is not a terminal pass. Allowed files: the existing public probe and its focused
+proof tests, plus this record. Add an explicit separate-runner policy-case
+selector and exclusive per-case receipts after unchanged outcome assertions.
+Default remains both cases. Selected-case reports must identify the executed
+case and leave unexecuted outcomes empty; no business deadline/resource or
+assertion changes. This permits bounded final-head qualification without
+repeating a completed independent case or calling partial output a full pass.
diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
index 6acf21126..04b089e23 100644
--- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
+++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
@@ -1238,7 +1238,10 @@ def _require_runner_health(execution: ExternalCheckerServiceHealth, intake: Trus
 
 async def run(database_url: str, image_reference: str, node_config: Path,
               broker_url: str, root: Path, expected_custody: Path,
-              clients: ContributorClients | None = None, *, separate_runner: bool = False) -> dict:
+              clients: ContributorClients | None = None, *, separate_runner: bool = False,
+              policy_case: str = "both") -> dict:
+    _require(policy_case in {"both", "human", "automatic"}, "unknown policy qualification case")
+    _require(policy_case == "both" or separate_runner, "single policy case requires separate runner")
     root.mkdir(parents=True, mode=0o700, exist_ok=True)
     _require(not separate_runner or clients is not None, 'separate runner proof needs both clients')
     custody = json.loads(expected_custody.read_text())
@@ -1450,17 +1453,22 @@ async def start_owned_worker() -> None:
                 _require((fault_root / "supervisor-ready").exists(), "owned node supervisor is absent")
                 runtime_trials = await public_runtime_trials(client, factory, env, fault_root,
                     stop_worker=stop_owned_worker, start_worker=start_owned_worker, operator_token=_token(env, operator))
-            true = await _one_mode(client, factory, env,
+            true = false = None
+            if policy_case in {"both", "human"}:
+                true = await _one_mode(client, factory, env,
                                    human_review_required=True,
                                    operator_id=operator.actor_profile_id, clients=clients,
                                    exercise_faults=not separate_runner, manager_authored=separate_runner)
-            false = await _one_mode(client, factory, env,
+                _write_policy_receipt(root, "human", true, custody)
+            if policy_case in {"both", "automatic"}:
+                false = await _one_mode(client, factory, env,
                                     human_review_required=False,
                                     operator_id=operator.actor_profile_id,
                                     stop_worker=stop_owned_worker,
                                     start_worker=start_owned_worker, fault_root=fault_root,
                                     operator_token=_token(env, operator), clients=clients,
                                     exercise_faults=not separate_runner, manager_authored=separate_runner)
+                _write_policy_receipt(root, "automatic", false, custody)
         _require(api.poll() is None and beat.poll() is None
                  and all(process.poll() is None for process in workers),
                  "API, dedicated prefork worker, or Beat exited during public journey")
@@ -1475,6 +1483,8 @@ async def start_owned_worker() -> None:
                 "maximum_parallel": service_config["smol"]["maximum_parallel"],
                 "pre_reserved_capacity": service_config["pre"]["reserved_capacity"],
                 "separate_runner": separate_runner,
+                "completed_policy_cases": [name for name, outcome in (("human", true), ("automatic", false))
+                                           if outcome is not None],
                 "scheduled_artifact_scans": True,
                 "public_original_guide_setup": True,
                 "connected_submitter_clients": ["cli", "mcp"] if clients is not None else [],
@@ -1495,6 +1505,19 @@ async def start_owned_worker() -> None:
                 await engine.dispose()
 
 
+def _write_policy_receipt(root: Path, case: str, result: dict, custody: dict) -> None:
+    """Retain a completed case without claiming the other case or overall cleanup."""
+    selected = {key: custody[key] for key in (
+        "source_tree", "config_sha256", "service_sha256", "smol_sha256", "guest_sha256",
+    )}
+    with (root / f"policy-{case}.json").open("x", encoding="utf-8") as stream:
+        json.dump({"completed_policy_case": case, "custody": selected, "result": result,
+                   "overall_cleanup_requires_separate_receipt": True}, stream, sort_keys=True)
+        stream.write("\n")
+        stream.flush()
+        os.fsync(stream.fileno())
+
+
 def main() -> int:
     parser = argparse.ArgumentParser()
     parser.add_argument("--database-url", default=os.environ.get("WORKSTREAM_TEST_DATABASE_URL"))
@@ -1508,6 +1531,8 @@ def main() -> int:
     parser.add_argument("--mcp-executable", type=Path, help="Installed MCP for connected submitter verification")
     parser.add_argument("--separate-runner", action="store_true",
                         help="Use baseline remote runner custody without local host fault controls")
+    parser.add_argument("--policy-case", choices=("both", "human", "automatic"), default="both",
+                        help="Qualify one independent policy case on the separate runner, or both")
     parser.add_argument('--hosted-attachment', type=Path,
                         help='Private attachment manifest for an existing hosted API/worker/Beat')
     parser.add_argument('--hosted-model-post', type=Path,
@@ -1521,6 +1546,8 @@ def main() -> int:
         parser.error("connected submitter verification requires both client executables")
     if args.separate_runner and not args.cli_executable:
         parser.error("the separate runner proof requires both client executables")
+    if args.policy_case != "both" and not args.separate_runner:
+        parser.error("a single policy case requires --separate-runner")
     if args.hosted_attachment:
         if (not args.broker_url or args.image_reference or args.node_config
                 or args.work_dir or args.expected_custody or args.cli_executable or args.mcp_executable
@@ -1544,6 +1571,7 @@ def main() -> int:
         value = asyncio.run(run(
             args.database_url, args.image_reference, args.node_config,
             args.broker_url, Path(directory), args.expected_custody, clients, separate_runner=args.separate_runner,
+            policy_case=args.policy_case,
         ))
     print(json.dumps(value, sort_keys=True, separators=(",", ":")))
     return 0
diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py
index 286d5753b..803fdb250 100644
--- a/scripts/test_public_hosted_attachment.py
+++ b/scripts/test_public_hosted_attachment.py
@@ -29,6 +29,26 @@
 
 
 class PublicJourneyWorkerCustody(unittest.TestCase):
+    def test_completed_policy_receipt_cannot_overwrite_or_claim_both_cases(self):
+        from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe
+
+        custody = {key: "sha256:" + "1" * 64 for key in (
+            "source_tree", "config_sha256", "service_sha256", "smol_sha256", "guest_sha256",
+        )}
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            probe._write_policy_receipt(root, "automatic", {"submission_id": "first"}, custody)
+            receipt = root / "policy-automatic.json"
+            original = receipt.read_bytes()
+            value = json.loads(original)
+            self.assertEqual(value["completed_policy_case"], "automatic")
+            self.assertEqual(value["custody"], custody)
+            self.assertTrue(value["overall_cleanup_requires_separate_receipt"])
+            self.assertFalse((root / "policy-human.json").exists())
+            with self.assertRaises(FileExistsError):
+                probe._write_policy_receipt(root, "automatic", {"submission_id": "different"}, custody)
+            self.assertEqual(receipt.read_bytes(), original)
+
     def test_runner_health_reports_reviewed_cache_size_as_a_count(self):
         from app.interfaces.external_checker_execution import ExternalCheckerServiceHealth
         from app.interfaces.trusted_submission_intake import TrustedIntakeIdentity

From 7337e118cb52f79d2851b894b1db6fe3166085ab Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 12:52:54 +0100
Subject: [PATCH 417/513] test(submissions): bind policy receipts to owned
 storage and terminal evidence

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md |  6 ++++++
 .../run_public_journey_probe.py                   | 15 +++++++++++----
 scripts/test_public_hosted_attachment.py          | 10 ++++++++--
 3 files changed, 25 insertions(+), 6 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 24eed6154..c98b5b406 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12016,3 +12016,9 @@ Default remains both cases. Selected-case reports must identify the executed
 case and leave unexecuted outcomes empty; no business deadline/resource or
 assertion changes. This permits bounded final-head qualification without
 repeating a completed independent case or calling partial output a full pass.
+
+The reviewed receipt follow-up binds each completed separate-runner case to
+its exact object bucket/prefix and CLI/MCP custody. It explicitly requires
+separate terminal-exit and overall-cleanup evidence. Local fault simulations
+do not emit these receipts. The focused receipt regression passed (one test),
+and Ruff passed; independent review approved the provenance correction.
diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
index 04b089e23..9b0290cf5 100644
--- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
+++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
@@ -1459,7 +1459,8 @@ async def start_owned_worker() -> None:
                                    human_review_required=True,
                                    operator_id=operator.actor_profile_id, clients=clients,
                                    exercise_faults=not separate_runner, manager_authored=separate_runner)
-                _write_policy_receipt(root, "human", true, custody)
+                if separate_runner:
+                    _write_policy_receipt(root, "human", true, custody, bucket=bucket, prefix=prefix)
             if policy_case in {"both", "automatic"}:
                 false = await _one_mode(client, factory, env,
                                     human_review_required=False,
@@ -1468,7 +1469,8 @@ async def start_owned_worker() -> None:
                                     start_worker=start_owned_worker, fault_root=fault_root,
                                     operator_token=_token(env, operator), clients=clients,
                                     exercise_faults=not separate_runner, manager_authored=separate_runner)
-                _write_policy_receipt(root, "automatic", false, custody)
+                if separate_runner:
+                    _write_policy_receipt(root, "automatic", false, custody, bucket=bucket, prefix=prefix)
         _require(api.poll() is None and beat.poll() is None
                  and all(process.poll() is None for process in workers),
                  "API, dedicated prefork worker, or Beat exited during public journey")
@@ -1505,14 +1507,19 @@ async def start_owned_worker() -> None:
                 await engine.dispose()
 
 
-def _write_policy_receipt(root: Path, case: str, result: dict, custody: dict) -> None:
+def _write_policy_receipt(
+    root: Path, case: str, result: dict, custody: dict, *, bucket: str, prefix: str,
+) -> None:
     """Retain a completed case without claiming the other case or overall cleanup."""
     selected = {key: custody[key] for key in (
         "source_tree", "config_sha256", "service_sha256", "smol_sha256", "guest_sha256",
     )}
     with (root / f"policy-{case}.json").open("x", encoding="utf-8") as stream:
         json.dump({"completed_policy_case": case, "custody": selected, "result": result,
-                   "overall_cleanup_requires_separate_receipt": True}, stream, sort_keys=True)
+                   "separate_runner": True, "connected_submitter_clients": ["cli", "mcp"],
+                   "minio_bucket": bucket, "minio_prefix": prefix,
+                   "overall_cleanup_requires_separate_receipt": True,
+                   "terminal_probe_exit_requires_separate_receipt": True}, stream, sort_keys=True)
         stream.write("\n")
         stream.flush()
         os.fsync(stream.fileno())
diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py
index 803fdb250..29857bf36 100644
--- a/scripts/test_public_hosted_attachment.py
+++ b/scripts/test_public_hosted_attachment.py
@@ -37,16 +37,22 @@ def test_completed_policy_receipt_cannot_overwrite_or_claim_both_cases(self):
         )}
         with tempfile.TemporaryDirectory() as directory:
             root = Path(directory)
-            probe._write_policy_receipt(root, "automatic", {"submission_id": "first"}, custody)
+            storage = {"bucket": "owned-bucket", "prefix": "owned-run/"}
+            probe._write_policy_receipt(root, "automatic", {"submission_id": "first"}, custody, **storage)
             receipt = root / "policy-automatic.json"
             original = receipt.read_bytes()
             value = json.loads(original)
             self.assertEqual(value["completed_policy_case"], "automatic")
             self.assertEqual(value["custody"], custody)
             self.assertTrue(value["overall_cleanup_requires_separate_receipt"])
+            self.assertTrue(value["terminal_probe_exit_requires_separate_receipt"])
+            self.assertTrue(value["separate_runner"])
+            self.assertEqual(value["connected_submitter_clients"], ["cli", "mcp"])
+            self.assertEqual((value["minio_bucket"], value["minio_prefix"]), ("owned-bucket", "owned-run/"))
             self.assertFalse((root / "policy-human.json").exists())
             with self.assertRaises(FileExistsError):
-                probe._write_policy_receipt(root, "automatic", {"submission_id": "different"}, custody)
+                probe._write_policy_receipt(root, "automatic", {"submission_id": "different"}, custody,
+                                            bucket="another-bucket", prefix="another-run/")
             self.assertEqual(receipt.read_bytes(), original)
 
     def test_runner_health_reports_reviewed_cache_size_as_a_count(self):

From 5107daa3dbd08c1306f86bb4b737fc6e36280dac Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 12:39:02 +0100
Subject: [PATCH 418/513] Exercise POST recovery after a T5 broker outage

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  34 ++++
 ...est_submission_finalization_worker_loss.py | 165 ++++++++++++++++--
 2 files changed, 187 insertions(+), 12 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index c98b5b406..05b83daa8 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9196,6 +9196,40 @@ Ruff/structure/diff pass (structure log
 /tmp/submission-finalizer-broker-death-structure.log); final Commitrail check
 runs after this append. No production or lane changes, no remote mutation.
 
+### Broker publication recovery after T5
+
+A10 has a real broker-refusal case after public T4. Add a separate case for
+the initial POST event committed by T5. Scope is the existing finalization
+worker-loss test module and this record. Reuse its signed upload, prefork
+finalizer, Redis proxy and owned cleanup. Close the proxy after observing
+committed T5, attempt the canonical scan, and require zero publication with
+the exact source, charge, task, and POST request unchanged. Reopen the same
+proxy to real Redis and require one production POST delivery. Deliver a
+duplicate to verify one actual evaluation and one durable completion.
+
+Use the existing local intake and controlled selected-execution transports
+behind the registered worker's real ART, CHECKERS, and OUTBOX owners. Production
+code, retry settings, deployment, native execution setup and shared broker
+configuration stay outside this test-only change. Risk is medium for worker
+and shared-resource custody. Verify the focused real PostgreSQL/Redis test and
+existing post-T4 control, with focused QA and architecture review. Human
+review should verify the recovered message selects the original request and
+the test only closes its own proxy, worker processes and Redis prefix.
+
+The first run observed finalized T5 and the original pending POST event. It
+stalled before the outage scan because Python 3.12 waits for active connections
+when `Server.wait_closed()` runs after closing a listener. The test now closes
+the listener, drains its forwarding tasks, then awaits server closure. An
+isolated socket probe timed out with the prior order and completed with the
+repaired helper. The interrupted PostgreSQL and Redis run cleaned both owned
+services and supplies no recovery result.
+
+The post-T4 control passed on rerun. The new case reached the explicit TCP
+refusal check, which found that the live prefork finalizer still held its
+inherited copy of the proxy listener. The test now stops that owned finalizer
+after observing T5 and before disconnecting the proxy. It starts the separate
+POST worker after republication. The refusal assertion stays intact.
+
 ### Genuine-orphan scope clarification
 
 Read-only ARCH/SEC assessment at08fd205d0 confirms that spec17.4 makes
diff --git a/backend/tests/artifacts/test_submission_finalization_worker_loss.py b/backend/tests/artifacts/test_submission_finalization_worker_loss.py
index e44290bd5..3650820a3 100644
--- a/backend/tests/artifacts/test_submission_finalization_worker_loss.py
+++ b/backend/tests/artifacts/test_submission_finalization_worker_loss.py
@@ -165,6 +165,33 @@ def record(task_id, task, retval, state, **_kwargs):
                without_heartbeat=True).start()
 
 
+def _broker_post_worker(app, hostname, completed):
+    """Run the registered POST delivery with controlled checker transports."""
+    from unittest.mock import patch
+    from celery.signals import task_postrun
+    from app.workers.outbox_topology import OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE
+    from tests.checkers.execution.support import ControlledSelectedExecution
+    from tests.trusted_intake_fixtures import LocalIntakeAdapter
+
+    execution = ControlledSelectedExecution()
+
+    def record(task_id, task, retval, state, **_kwargs):
+        if task.name == OUTBOX_DELIVERY_TASK:
+            completed.put((task_id, state, retval, os.getpid(), task.request.is_eager,
+                           task.request.delivery_info["routing_key"], len(execution.requests)))
+
+    os.setsid()
+    task_postrun.connect(record, weak=False)
+    with (
+        patch("app.adapters.artifacts.trusted_submission_intake", lambda _settings: LocalIntakeAdapter()),
+        patch("app.adapters.checkers.configured_post_submit_external_execution",
+              lambda _settings, *, sessions: execution),
+    ):
+        app.Worker(pool="prefork", concurrency=1, queues=[OUTBOX_QUEUE], hostname=hostname,
+                   loglevel="ERROR", without_gossip=True, without_mingle=True,
+                   without_heartbeat=True).start()
+
+
 def _broker_scanner(app, hostname, completed):
     """Run the production scan task with its own real prefork consumer."""
     from celery.signals import task_postrun
@@ -370,15 +397,7 @@ async def _close_broker_case(case):
     case.endpoint.close()
     await _stop_broker_worker(case.scan_process, case.scan_completed)
     await _stop_broker_worker(case.process, case.completed)
-    for pool in (case.app.amqp._producer_pool, case.app._pool):
-        if pool is not None:
-            pool.force_close_all()
-    if case.proxy is not None:
-        case.proxy.close()
-        await case.proxy.wait_closed()
-    for pending in tuple(case.connections):
-        pending.cancel()
-    await asyncio.gather(*tuple(case.connections), return_exceptions=True)
+    await _disconnect_broker_endpoint(case, terminal=True)
     keys = list(case.connection.scan_iter(match=case.prefix + "*"))
     if keys:
         case.connection.delete(*keys)
@@ -387,6 +406,24 @@ async def _close_broker_case(case):
     get_settings.cache_clear()
 
 
+async def _disconnect_broker_endpoint(case, *, terminal=False):
+    """Refuse new publication and drain only this case's existing connections."""
+    proxy, case.proxy = case.proxy, None
+    if proxy is not None:
+        proxy.close()
+    for pending in tuple(case.connections):
+        pending.cancel()
+    await asyncio.gather(*tuple(case.connections), return_exceptions=True)
+    if proxy is not None:
+        await proxy.wait_closed()
+    for pool in (case.app.amqp._producer_pool, case.app._pool):
+        if pool is not None:
+            if terminal:
+                pool.force_close_all()
+            else:
+                pool.resize(pool.limit, reset=True)
+
+
 async def _restore_broker_endpoint(case):
     """Make the unchanged producer endpoint forward to real Redis again."""
     case.endpoint.close()
@@ -395,7 +432,7 @@ async def _restore_broker_endpoint(case):
         "127.0.0.1", case.port)
 
 
-async def _next_broker_result(case):
+async def _next_broker_result(case, *, expected_queue=None):
     """Observe a real task return while the proxy event loop remains live."""
     import queue
     import time
@@ -409,9 +446,12 @@ async def _next_broker_result(case):
             continue
         from app.workers.outbox_topology import FINALIZATION_QUEUE
         assert result[1] == "SUCCESS" and result[3] not in {os.getpid(), case.process.pid}, result
-        assert result[4:] == (False, FINALIZATION_QUEUE), result
+        if expected_queue is None:
+            assert result[4:] == (False, FINALIZATION_QUEUE), result
+        else:
+            assert result[4:6] == (False, expected_queue), result
         return result
-    raise AssertionError("production finalization task did not return")
+    raise AssertionError("production outbox task did not return")
 
 
 async def _next_scan_result(case):
@@ -523,6 +563,107 @@ async def test_real_broker_recovers_public_acceptance_and_deduplicates_finalizat
         await _assert_broker_finalized_once(f, case.operation_id, case.before[1])
 
 
+async def _post_broker_facts(f, operation_id):
+    """Pin the exact accepted source and initial evaluation selected by T5."""
+    from app.modules.checkers.api.execution import COMPLETION_EVENT, REQUEST_EVENT
+    from app.modules.checkers.models import CheckerRun
+    from app.modules.tasks.models import SubmissionDispatch, WorkstreamTask
+
+    async with f.factory() as session:
+        operation = await session.get(SubmissionIntakeOperation, operation_id)
+        task = await session.get(WorkstreamTask, str(f.task))
+        dispatch = await session.get(SubmissionDispatch, operation.finalized_submission_id)
+        event = await session.get(OutboxEvent, dispatch.evaluation_event_id)
+        run = await session.get(CheckerRun, dispatch.evaluation_attempt_id)
+        assert event.event_type == REQUEST_EVENT and event.aggregate_id == UUID(dispatch.submission_id)
+        completions = tuple(await session.scalars(select(OutboxEvent.event_id).where(
+            OutboxEvent.project_id == str(f.project), OutboxEvent.event_type == COMPLETION_EVENT,
+        )))
+        return {
+            "source": (operation.object_ref, operation.provider_generation,
+                       operation.raw_sha256, operation.raw_byte_count),
+            "task_status": task.status,
+            "request": (event.event_id, event.payload_digest, event.payload),
+            "delivery": (event.delivery_state, event.attempt_count),
+            "execution": (run.id, run.status, run.worker_lease_generation),
+            "material": run.material_custody,
+            "completion": run.completion_event_id,
+            "completions": completions,
+        }
+
+
+async def _prepare_post_broker_worker(case):
+    """Release the finalizer's inherited listener before testing broker loss."""
+    from app.core.identifiers import new_record_id
+
+    context = multiprocessing.get_context("fork")
+    finalizer, completed = case.process, case.completed
+    case.process, case.completed = None, context.Queue()
+    await _stop_broker_worker(finalizer, completed)
+    case.process = context.Process(target=_broker_post_worker,
+        args=(case.app, f"post-delivery-{new_record_id()}@localhost", case.completed))
+
+
+async def test_real_broker_recovers_committed_t5_and_executes_original_post_once(
+    admission_intake, tmp_path, monkeypatch,
+):
+    """Losing the broker after T5 leaves one recoverable POST request and source."""
+    from app.core.identifiers import new_record_id
+    from app.workers.outbox_topology import OUTBOX_QUEUE
+
+    f = admission_intake
+    async with _public_broker_case(f, tmp_path, monkeypatch) as case:
+        async def scan():
+            return await asyncio.to_thread(case.worker._scan_pending, case.worker.scan_pending)
+
+        await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_POST_SUBMIT)
+        await _restore_broker_endpoint(case)
+        assert await scan() == {"selected": 1, "published": 1}
+        case.process.start()
+        assert (await _next_broker_result(case))[2] == {"status": "delivery_recorded"}
+        submission = await _assert_broker_finalized_once(f, case.operation_id, case.before[1])
+        accepted = await _accepted_broker_facts(f, case.operation_id)
+        pending = await _post_broker_facts(f, case.operation_id)
+        assert pending["delivery"] == ("pending", 0)
+        assert pending["execution"][1:] == ("queued", 0) and pending["completions"] == ()
+        assert pending["task_status"] == "evaluation_pending"
+
+        await _prepare_post_broker_worker(case)
+        await _disconnect_broker_endpoint(case)
+        with pytest.raises(ConnectionRefusedError):
+            await asyncio.open_connection("127.0.0.1", case.port)
+        assert await scan() == {"selected": 1, "published": 0}
+        assert case.connection.llen(case.prefix + OUTBOX_QUEUE) == 0
+        assert await _accepted_broker_facts(f, case.operation_id) == accepted
+        assert await _post_broker_facts(f, case.operation_id) == pending
+
+        await _restore_broker_endpoint(case)
+        assert await scan() == {"selected": 1, "published": 1}
+        assert case.connection.llen(case.prefix + OUTBOX_QUEUE) == 1
+        duplicate = str(new_record_id())
+        await asyncio.to_thread(case.worker.deliver_event.apply_async,
+            args=(str(pending["request"][0]), str(f.project)), task_id=duplicate)
+        assert case.connection.llen(case.prefix + OUTBOX_QUEUE) == 2
+        case.process.start()
+        original = await _next_broker_result(case, expected_queue=OUTBOX_QUEUE)
+        replay = await _next_broker_result(case, expected_queue=OUTBOX_QUEUE)
+        assert original[0] != duplicate and original[2] == {"status": "delivery_recorded"}
+        assert replay[0] == duplicate and replay[2] == {"status": "delivery_unavailable"}
+        assert original[3] == replay[3] and original[6] == replay[6] == 1
+
+        completed = await _post_broker_facts(f, case.operation_id)
+        for key in ("source", "task_status", "request"):
+            assert completed[key] == pending[key]
+        assert completed["delivery"] == ("acknowledged", 1)
+        assert completed["execution"] == (pending["execution"][0], "completed", 1)
+        assert completed["completion"] is not None
+        assert completed["completions"] == (completed["completion"],)
+        assert completed["material"]["content_sha256"] == pending["source"][2]
+        assert completed["material"]["byte_count"] == pending["source"][3]
+        await _assert_public_broker_replay(case)
+        assert await _assert_broker_finalized_once(f, case.operation_id, case.before[1]) == submission
+
+
 def _record_broker_trace(path, body):
     """Make each observed boundary durable before its process can be killed."""
     import json

From 5de66e572f30a315dbb7d7b25bd403a883516aad Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 12:56:13 +0100
Subject: [PATCH 419/513] Record real Redis recovery after T5

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md  | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 05b83daa8..359642b87 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9230,6 +9230,20 @@ inherited copy of the proxy listener. The test now stops that owned finalizer
 after observing T5 and before disconnecting the proxy. It starts the separate
 POST worker after republication. The refusal assertion stays intact.
 
+The corrected post-T5 case passed in 82.41 seconds at `9991c3954` on
+PostgreSQL schema 0093. The closed proxy refused TCP and the production outbox
+scan selected the original POST event with zero publications. Reopening the
+same proxy produced one publication. Production prefork delivery consumed the
+recovered and duplicate messages with one controlled evaluation, one completed
+checker lease and one durable completion. Exact source, charge, task and request
+custody survived. The post-T4 control passed at `56dfd128b` with the same
+shared shutdown helper. The isolated database, login, Redis process and test
+keys were cleaned on both runs. Python's fork-with-threads warning remains
+visible. The post-T5 receipt is `/tmp/pr708-a10-post-t5-isolated.log` with its
+adjacent metadata JSON. This evidence covers local Redis and registered workers
+with controlled checker transports. The deployed release remains a separate
+qualification.
+
 ### Genuine-orphan scope clarification
 
 Read-only ARCH/SEC assessment at08fd205d0 confirms that spec17.4 makes

From d6c32a890965064bab172c073ae1f0faaa4752f9 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 12:36:28 +0100
Subject: [PATCH 420/513] Preserve unknown custody after possible POST
 invocation

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 34 ++++++++
 .../app/adapters/checkers/external_service.py | 26 +++---
 .../interfaces/external_checker_execution.py  | 12 ++-
 backend/app/modules/artifacts/preparation.py  | 25 +++---
 .../test_delivery_reconciliation_public.py    | 83 +++++++++++++++++--
 .../checkers/external/test_remote_node.py     | 57 +++++++++++++
 .../tests/checkers/external/test_runtime.py   | 22 ++++-
 7 files changed, 222 insertions(+), 37 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 359642b87..b3ec4fd71 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12070,3 +12070,37 @@ its exact object bucket/prefix and CLI/MCP custody. It explicitly requires
 separate terminal-exit and overall-cleanup evidence. Local fault simulations
 do not emit these receipts. The focused receipt regression passed (one test),
 and Ruff passed; independent review approved the provenance correction.
+
+### A28 preserve unknown POST invocation custody
+
+Intent. A remote POST disconnect after an executable frame can leave the
+runner active. Converting that disconnect into a terminal infrastructure
+result lets the existing Operator checker retry create another evaluation
+generation. Preserve the committed execution claim and OUTBOX unknown outcome
+when the service has not returned an exact terminal response.
+
+Allowed scope. `backend/app/interfaces/external_checker_execution.py` owns
+the typed boundary outcome, `backend/app/adapters/checkers/external_service.py`
+owns the first possibly transmitted POST or forge control frame and response
+validation, and `backend/app/modules/artifacts/preparation.py` owns draining
+the existing callback on cancellation. Extend the existing transport tests,
+ART cancellation test, real PostgreSQL public held and no-effect Operator
+proof, and this record. Keep the existing dispatcher one-invocation marker
+and CHECKERS recovery authority. The authorized reconciliation child can invoke only
+an exact never-started run. No new state, endpoint configuration or migration.
+
+Acceptance. Known pre-send transport refusal and validated terminal results
+keep their established meanings. Loss, invalid output or timeout after possible
+invocation cannot mint a terminal retry source, even when cancellation drains
+the ART callback. Its exact run stays held, with no new result, member, routing
+or award. Show the Operator can still reconcile a proven no-effect source.
+PRE retains its one-use source/run lease and bounded expiry. A fresh authorized
+operation following a fenced failure is a separate attempt.
+
+The targeted pure run passed 112 cases. It includes the known terminal mTLS
+response, POST connect/write/EOF/output/deadline/cancel cases, ART cleanup
+across both cancellation and deadline, and the PRE lease and source guards.
+The product dispatcher commits an invocation once. Its recovery child can
+only execute an exact queued generation-zero run, and rejects a running row
+after fresh classification. The private expired-running claim branch is
+unreachable through these supported owners and is outside this change.
diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index bff3fb8d1..cb6e00a28 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -14,11 +14,10 @@
 import struct
 from typing import Literal
 
-from pydantic import ValidationError
-
 from app.core.cancellation import await_cancellation_resistant
 
 from app.interfaces.external_checker_execution import (
+    ExternalCheckerExecutionOutcomeUnknown,
     ExternalCheckerExecutionResponse,
     ExternalPreSubmitSourceGrant,
     MAXIMUM_PRE_SOURCE_CHUNK_BYTES,
@@ -36,7 +35,6 @@
 from app.modules.checkers.api.external import (
     EXTERNAL_CHECKER_EXECUTION_CLEANUP_MARGIN_MS,
     MAX_RESULT_BYTES,
-    ExternalCheckerContractError,
     ExternalCheckerExecutionRequest,
     ExternalCheckerExecutionResult,
 )
@@ -271,6 +269,7 @@ async def locate_forge_change(self, request, grant) -> ExternalCheckerForgeLocat
 
     async def _exchange(self, request, grant, *, model_grant, locate):
         """Exchange one bounded request and revalidate every returned fact."""
+        possibly_invoked = False
         try:
             checked = ExternalCheckerExecutionRequest.model_validate(request)
             if locate:
@@ -340,6 +339,9 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                         allow_nan=False,
                         separators=(",", ":"),
                     ).encode()
+                    # A failed drain can follow successful transmission. Treat
+                    # this call as possibly invoked before its first write.
+                    possibly_invoked = True
                     await self._send_frame(writer, control)
                     await self._send_frame(writer, manifest)
                     for item in files:
@@ -395,14 +397,6 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                 finally:
                     writer.close()
                     await await_cancellation_resistant(writer.wait_closed())
-        except ExternalServiceProtocolError:
-            raise
-        except (TimeoutError, OSError, asyncio.IncompleteReadError) as exc:
-            raise ExternalServiceUnavailableError(self._identity) from exc
-        except (TypeError, ValueError, ValidationError, UnicodeError, json.JSONDecodeError) as exc:
-            raise ExternalServiceProtocolError(self._identity) from exc
-
-        try:
             body = json.loads(raw)
             if (
                 type(body) is not dict
@@ -437,8 +431,14 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                 ExternalCheckerForgeLocatorResponse if locate else ExternalCheckerExecutionResponse
             )
             return response_type(result=result, isolation=isolation)
-        except (TypeError, ValueError, ValidationError, ExternalCheckerContractError) as exc:
-            raise ExternalServiceProtocolError(self._identity) from exc
+        except (Exception, asyncio.CancelledError) as exc:
+            if possibly_invoked:
+                raise ExternalCheckerExecutionOutcomeUnknown() from None
+            if isinstance(exc, (TimeoutError, OSError, asyncio.IncompleteReadError)):
+                raise ExternalServiceUnavailableError(self._identity) from exc
+            if isinstance(exc, (TypeError, ValueError)):
+                raise ExternalServiceProtocolError(self._identity) from exc
+            raise
 
     async def health(self) -> ExternalCheckerServiceHealth:
         """Require the service to recheck its configured engine and report readiness."""
diff --git a/backend/app/interfaces/external_checker_execution.py b/backend/app/interfaces/external_checker_execution.py
index b186f45a3..d869cf248 100644
--- a/backend/app/interfaces/external_checker_execution.py
+++ b/backend/app/interfaces/external_checker_execution.py
@@ -29,6 +29,13 @@
 )
 
 
+class ExternalCheckerExecutionOutcomeUnknown(RuntimeError):
+    """A possibly invoked POST/locator lacks an authoritative terminal response."""
+
+    def __init__(self) -> None:
+        super().__init__("checker_execution_outcome_unknown")
+
+
 @dataclass(frozen=True, slots=True)
 class ExternalCheckerMaterialGrant:
     """Opaque callback-scoped ART capability; never a filesystem path."""
@@ -201,7 +208,7 @@ async def locate_forge_change(
         request: ExternalCheckerExecutionRequest,
         grant: ExternalCheckerMaterialGrant,
     ) -> ExternalCheckerForgeLocatorResponse:
-        """Read a project-owned selector inside the same bounded offline image."""
+        """Read a project-owned selector or raise if invocation custody is unresolved."""
         ...
 
     async def execute(
@@ -211,7 +218,7 @@ async def execute(
         *,
         model_grant: ExternalCheckerModelGrant | None = None,
     ) -> ExternalCheckerExecutionResponse:
-        """Return a request-bound result or a sanitized transport failure."""
+        """Return a request-bound result or report invocation custody as unresolved."""
 
     async def health(self) -> ExternalCheckerServiceHealth:
         """Return current runtime and cache readiness from the service."""
@@ -221,6 +228,7 @@ async def health(self) -> ExternalCheckerServiceHealth:
     "ExternalCheckerExecutionAdapter",
     "ExternalPreSubmitSourceGrant",
     "MAXIMUM_PRE_SOURCE_CHUNK_BYTES",
+    "ExternalCheckerExecutionOutcomeUnknown",
     "ExternalCheckerExecutionResponse",
     "ExternalCheckerIsolationReceipt",
     "ExternalCheckerMaterialGrant",
diff --git a/backend/app/modules/artifacts/preparation.py b/backend/app/modules/artifacts/preparation.py
index 00cb0beb4..df5d1934e 100644
--- a/backend/app/modules/artifacts/preparation.py
+++ b/backend/app/modules/artifacts/preparation.py
@@ -27,6 +27,7 @@
     ArtifactScratchIntegrityError,
     ArtifactStoreUnavailableError,
 )
+from app.interfaces.external_checker_execution import ExternalCheckerExecutionOutcomeUnknown
 from app.core.cancellation import (
     await_completion_preserving_cancellation,
     await_cancellation_resistant,
@@ -2768,6 +2769,18 @@ async def process_and_cleanup() -> tuple[_InspectionResult | None, BaseException
                 ) from None
 
         operation = asyncio.create_task(process_and_cleanup())
+
+        async def abort_and_drain() -> None:
+            processor.abort()
+            try:
+                _, error = await await_cancellation_resistant(operation)
+            except asyncio.CancelledError:
+                return
+            # A cancelled transport can leave the checker running after local
+            # scratch cleanup. Preserve that outcome across the deadline boundary.
+            if isinstance(error, ExternalCheckerExecutionOutcomeUnknown):
+                raise error from None
+
         try:
             async with asyncio.timeout_at(deadline):
                 result, error = await asyncio.shield(operation)
@@ -2775,20 +2788,12 @@ async def process_and_cleanup() -> tuple[_InspectionResult | None, BaseException
                     raise error
                 return cast(_InspectionResult, result)
         except TimeoutError:
-            processor.abort()
-            try:
-                await await_cancellation_resistant(operation)
-            except asyncio.CancelledError:
-                pass
+            await abort_and_drain()
             raise ArtifactPreparationDeadlineError(
                 "artifact preparation deadline exceeded"
             ) from None
         except asyncio.CancelledError as cancellation:
-            processor.abort()
-            try:
-                await await_cancellation_resistant(operation)
-            except asyncio.CancelledError:
-                pass
+            await abort_and_drain()
             raise cancellation from None
 
     async def _release_unhanded_preparation(
diff --git a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
index b27781421..957ab7db7 100644
--- a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
+++ b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
@@ -1,7 +1,9 @@
 """Public PostgreSQL proof for one-shot uncertain post-submit delivery recovery."""
 
 import asyncio
-
+import json
+from pathlib import Path
+from tempfile import TemporaryDirectory
 from uuid import UUID
 
 import pytest
@@ -9,6 +11,7 @@
 from sqlalchemy.engine import Engine
 
 from app.adapters import artifacts as artifact_adapters
+from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter
 from app.adapters.outbox import production_outbox_delivery
 from app.adapters.tasks import evaluation_completion_handler
 from app.core.identifiers import new_record_id
@@ -35,6 +38,7 @@
 )
 from tests.tasks.evaluation_delivery.support import delivery_fixture, invoked, outcome, state
 from tests.checkers.execution.support import ControlledSelectedExecution
+from tests.checkers.external.test_remote_node import _read_frame, remote_adapter_endpoint
 from tests.tasks.post_submit_routing.outcome_support import (
     apply_outcome,
     authorized_routing_source,
@@ -370,6 +374,11 @@ async def test_public_operator_retries_proven_no_effect_request_once(
         )
         assert outcome(receipt)["delivery_state"] == "dead_letter"
         assert outcome(receipt)["error_code"] == "INVOKE_OUTCOME_UNKNOWN"
+        unstarted = await state(h)
+        assert unstarted["run"]["status"] == "queued"
+        assert unstarted["run"]["worker_lease_generation"] == 0
+        assert unstarted["run"]["execute_evidence_id"] is None
+        assert not h.store.opens
         original_before, _ = await _delivery_rows(h.factory, original.claim.event_id)
 
         source = await _discover_one(
@@ -766,8 +775,9 @@ async def test_public_operator_projects_uncertain_child_as_permanently_held(
     tmp_path,
     auth_database_env,
     admin_access,
+    monkeypatch,
 ) -> None:
-    """A child UNKNOWN is visible as held and can never create another child."""
+    """A lost POST response holds the actual child execution and both retry paths."""
     async with material_fixture(tmp_path, auth_database_env) as h:
         await admin_access.signed.grant(admin_access.admin, admin_access.target)
         prepared = await delivery_fixture(h)
@@ -794,14 +804,55 @@ async def test_public_operator_projects_uncertain_child_as_permanently_held(
         assert created.status_code == 201, created.text
         child_id = UUID(created.json()["successor"]["event_id"])
 
-        delivery = production_outbox_delivery(h.factory)
-        claim = await delivery.claim(child_id, h.request.project_id, "unknown-child")
-        assert claim is not None
-        envelope = await delivery._begin_invocation(claim)
-        assert envelope is not None
-        child_unknown = await delivery.finalize(claim, FinalizationCause.UNKNOWN)
+        before = await _project_facts(h.factory, h.request.project_id)
+        received = []
+
+        async def receive_without_result(reader, writer):
+            try:
+                received.append(json.loads(await _read_frame(reader)))
+            finally:
+                writer.close()
+                await writer.wait_closed()
+
+        monkeypatch.setattr("app.core.config.get_settings", lambda: h.settings)
+        monkeypatch.setattr(
+            artifact_adapters, "worker_post_submission_materialization", lambda *, sessions: h.service,
+        )
+        with TemporaryDirectory(prefix="ws-a28-post-") as directory:
+            native_socket = Path(directory) / "native.sock"
+            native = await asyncio.start_unix_server(receive_without_result, native_socket)
+            try:
+                async with remote_adapter_endpoint(tmp_path, native_socket) as endpoint:
+                    selected = RemoteTlsExternalCheckerAdapter(
+                        **endpoint, timeout_seconds=90.0,
+                        source_contracts=artifact_adapters.selected_pre_submit_source_contracts(),
+                    )
+                    monkeypatch.setattr(
+                        "app.adapters.checkers.configured_post_submit_external_execution",
+                        lambda settings, *, sessions: selected,
+                    )
+                    delivery = production_outbox_delivery(h.factory, worker_group="post")
+                    child_unknown = await delivery.deliver(child_id, h.request.project_id, "unknown-child")
+                    assert await delivery.deliver(child_id, h.request.project_id, "duplicate-child") is None
+            finally:
+                native.close()
+                await native.wait_closed()
+
         assert outcome(child_unknown)["delivery_state"] == "dead_letter"
-        assert not delivery._registry.can_retry_unknown(envelope.event_type, 1)
+        assert outcome(child_unknown)["error_code"] == "INVOKE_OUTCOME_UNKNOWN"
+        assert outcome(child_unknown)["invocation_unknown"] is True
+        assert len(received) == 1
+        assert received[0]["operation"] == "execute"
+        assert received[0]["request"]["identity"]["evaluation_request_id"] == str(h.request.evaluation_request_id)
+        running = await state(h)
+        assert running["run"]["status"] == "running"
+        assert running["run"]["worker_lease_generation"] == 1
+        assert running["run"]["execute_evidence_id"] in running["allows"]
+        assert running["run"]["finalize_evidence_id"] is None
+        assert running["run"]["result_json"] is None
+        assert running["members"] == running["events"] == 0
+        assert not h.preparation._active and not list((h.scratch / "workspaces").iterdir())
+        assert await _project_facts(h.factory, h.request.project_id) == before
 
         held = await _discover_one(
             admin_access, h.request.project_id, classification="unresolved"
@@ -825,6 +876,20 @@ async def test_public_operator_projects_uncertain_child_as_permanently_held(
             new_record_id(),
         )
         assert refused.status_code == 409, refused.text
+        scope = f"/api/v1/operations/projects/{h.request.project_id}"
+        retry_sources = await admin_access.signed.client.get(
+            f"{scope}/checker-retry-sources", headers=admin_access.target.headers,
+        )
+        assert retry_sources.status_code == 200, retry_sources.text
+        assert retry_sources.json()["items"] == []
+        new_generation = await admin_access.signed.client.post(
+            f"{scope}/checker-runs/{h.created.evaluation_attempt_id}/retry",
+            headers=admin_access.target.headers | {"Idempotency-Key": str(new_record_id())},
+            json={"reason": "Check that a possibly invoked runner cannot start another generation"},
+        )
+        assert new_generation.status_code == 404, new_generation.text
+        assert new_generation.json()["error"]["code"] == "checker_recovery_source_not_found"
+        assert await state(h) == running
 
 
 @pytest.mark.asyncio
diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py
index dbea9f06f..c2384a2a0 100644
--- a/backend/tests/checkers/external/test_remote_node.py
+++ b/backend/tests/checkers/external/test_remote_node.py
@@ -236,6 +236,63 @@ async def native(reader, writer):
             await app_server.wait_closed()
 
 
+@pytest.mark.asyncio
+@pytest.mark.parametrize("fault", ["connect", "write", "eof", "invalid_result", "timeout", "cancel"])
+async def test_remote_post_failure_preserves_possible_invocation(tmp_path, monkeypatch, fault):
+    from unittest.mock import AsyncMock, Mock
+
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
+    from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter
+    from app.interfaces.external_checker_execution import ExternalCheckerExecutionOutcomeUnknown
+    from tests.checkers.external.support import empty_external_material_grant
+    from tests.checkers.external.test_model_transport import request
+    from workstream_external_services import ExternalServiceUnavailableError
+
+    adapter = RemoteTlsExternalCheckerAdapter(
+        host="127.0.0.1", port=1, server_name="runner.test",
+        ca_path=tmp_path / "ca.pem", certificate_path=tmp_path / "client.pem",
+        private_key_path=tmp_path / "key.pem", model_proxy_socket_path=None,
+        timeout_seconds=90.0, source_contracts=selected_pre_submit_source_contracts(),
+    )
+    reader = asyncio.StreamReader()
+    writer = Mock(spec=asyncio.StreamWriter)
+    writer.drain = AsyncMock(side_effect=OSError if fault == "write" else None)
+    writer.wait_closed = AsyncMock()
+    connect = AsyncMock(return_value=(reader, writer), side_effect=OSError if fault == "connect" else None)
+    monkeypatch.setattr(adapter, "_open", connect)
+    waiting = asyncio.Event()
+
+    async def interrupt_read(_size):
+        waiting.set()
+        if fault == "timeout":
+            raise TimeoutError
+        await asyncio.Future()
+
+    if fault in {"timeout", "cancel"}:
+        monkeypatch.setattr(reader, "readexactly", interrupt_read)
+    elif fault == "invalid_result":
+        reader.feed_data(_frame(b'{"protocol_version":"workstream.remote_runner.v1",'
+                                b'"operation":"execution_result"}') + _frame(b'{}'))
+    reader.feed_eof()
+
+    value = request()
+    task = asyncio.create_task(adapter.execute(value, empty_external_material_grant(value, suffix="c")))
+    if fault == "cancel":
+        await asyncio.wait_for(waiting.wait(), 1)
+        task.cancel()
+    expected = ExternalServiceUnavailableError if fault == "connect" else ExternalCheckerExecutionOutcomeUnknown
+    with pytest.raises(expected):
+        await asyncio.wait_for(task, 2)
+    connect.assert_awaited_once_with()
+    if fault == "connect":
+        writer.write.assert_not_called()
+    else:
+        control = json.loads(writer.write.call_args_list[0].args[0][4:])
+        assert control["service_request"]["request"]["request_digest"] == value.request_digest
+        writer.close.assert_called_once_with()
+        writer.wait_closed.assert_awaited_once_with()
+
+
 @pytest.mark.asyncio
 async def test_remote_adapter_endpoint_invalid_explicit_root_cleans_helper_socket_root(tmp_path, monkeypatch):
     """Fail before native contact and leave no helper-owned directory on rejection."""
diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py
index db7e56618..d6b65705a 100644
--- a/backend/tests/checkers/external/test_runtime.py
+++ b/backend/tests/checkers/external/test_runtime.py
@@ -31,6 +31,7 @@
 from app.core.config import Settings
 from app.core.hashing import canonical_json_hash
 from app.interfaces.external_checker_execution import (
+    ExternalCheckerExecutionOutcomeUnknown,
     ExternalCheckerIsolationReceipt,
     ExternalCheckerServiceHealth,
 )
@@ -40,6 +41,7 @@
 from app.modules.artifacts.preparation import (
     HARD_MAXIMUM_ARTIFACT_BYTES,
     ArtifactPreparationLimits,
+    ArtifactPreparationDeadlineError,
     ArtifactPreparationService,
     ArtifactScratchCapacityError,
     ArtifactScratchIntegrityError,
@@ -862,8 +864,12 @@ def test_post_aggregate_workspace_enforces_combined_quota_and_cleanup(
 
 
 @pytest.mark.asyncio
+@pytest.mark.parametrize("interruption", ["cancelled", "deadline"])
+@pytest.mark.parametrize("unknown", [False, True])
 async def test_post_aggregate_rejects_duplicate_sources_and_drains_cancellation(
     tmp_path: Path,
+    interruption,
+    unknown,
 ) -> None:
     """Duplicate custody is rejected before scratch; cancellation drains both readers."""
     (
@@ -909,8 +915,14 @@ async def process(self, readers, workspace):
             }
             entered.set()
             await aborted.wait()
+            if unknown:
+                raise ExternalCheckerExecutionOutcomeUnknown()
             raise RuntimeError("aborted callback result must not replace cancellation")
 
+    if interruption == "deadline":
+        deadline = asyncio.get_running_loop().time() + 1.0
+        for prepared in (current, prior):
+            service._active[prepared._binding].deadline = deadline
     task = asyncio.create_task(
         service._process_prepared_post_submission(
             (
@@ -923,9 +935,13 @@ async def process(self, readers, workspace):
         )
     )
     await asyncio.wait_for(entered.wait(), 1)
-    task.cancel()
-    with pytest.raises(asyncio.CancelledError):
-        await asyncio.wait_for(task, 1)
+    if interruption == "cancelled":
+        task.cancel()
+    expected = ExternalCheckerExecutionOutcomeUnknown if unknown else (
+        asyncio.CancelledError if interruption == "cancelled" else ArtifactPreparationDeadlineError
+    )
+    with pytest.raises(expected):
+        await asyncio.wait_for(task, 3)
     assert aborted.is_set()
     assert list((tmp_path / "scratch" / "workspaces").iterdir()) == []
     assert not service._external_grant_workspaces

From 394dd80ca938b0c2e988650c631b21172545fe49 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 12:40:55 +0100
Subject: [PATCH 421/513] Verify forge and PRE invocation custody boundaries

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 22 +++++++++++++++++++
 .../checkers/external/test_forge_locator.py   |  9 ++++----
 .../test_selected_pre_submit_coordination.py  |  6 ++++-
 3 files changed, 32 insertions(+), 5 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index b3ec4fd71..755ca93e2 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12104,3 +12104,25 @@ The product dispatcher commits an invocation once. Its recovery child can
 only execute an exact queued generation-zero run, and rejects a running row
 after fresh classification. The private expired-running claim branch is
 unreachable through these supported owners and is outside this change.
+
+Caller verification also covers the existing forge locator transport and the
+source PRE claim test. Forge transport tests require an unresolved outcome
+after a malformed response, while keeping exact pre-send marker refusals and
+validated terminal infrastructure results. The PRE claim test exercises the
+same committed run twice and requires one lease and one authority consumption.
+
+Three public Operator cases passed against PostgreSQL on frozen
+`b11f13e83c9f86714371e36709858e773f7f8935`, schema `0093`, in 127.14 seconds.
+The isolated-runner receipt records database and MinIO cleanup. The held case
+used the real application, AUTH, OUTBOX, ART preparation, mTLS adapter and
+gateway. Its controlled Unix peer received one bound POST request and closed
+before returning a result. The child was dead-lettered with unknown invocation,
+and the exact CHECKERS claim stayed running without a result, finalization,
+or project effects. Other delivery and Operator retries could not invoke it.
+The never-started source reconciled once, and a queued-to-running change
+before recovery prevented a child from invoking. The controlled peer does not
+qualify hardware runtime cleanup or two-node placement.
+
+The additional forge and repeated PRE claim checks passed 21 cases. The three
+selected ART architecture guards passed. This follow-up changes only test
+expectations and the record. No running service or runner was changed.
diff --git a/backend/tests/checkers/external/test_forge_locator.py b/backend/tests/checkers/external/test_forge_locator.py
index c3618fbcc..9a0c4ef96 100644
--- a/backend/tests/checkers/external/test_forge_locator.py
+++ b/backend/tests/checkers/external/test_forge_locator.py
@@ -13,6 +13,7 @@
 
 from app.adapters.checkers import external_checker_execution_factory
 from app.adapters.checkers.model_execution import ModelAwareExternalExecution
+from app.interfaces.external_checker_execution import ExternalCheckerExecutionOutcomeUnknown
 from workstream_external_services import ExternalServiceProtocolError
 from app.modules.checkers.api.external import (
     ExternalCheckerContractError,
@@ -215,7 +216,7 @@ async def test_locator_socket_uses_separate_operation_and_no_model_grant(tmp_pat
 async def test_locator_socket_rejects_resigned_substitutions_and_invalid_values(tmp_path, changes):
     request = _request()
     async with _service(tmp_path, request, _locator(request, **changes)) as (adapter, _):
-        with pytest.raises(ExternalServiceProtocolError):
+        with pytest.raises(ExternalCheckerExecutionOutcomeUnknown):
             await adapter.locate_forge_change(request, _grant(request))
 
 
@@ -232,7 +233,7 @@ async def test_locator_socket_rejects_changed_digest_missing_isolation_and_compl
         (_work_result(request), True),
     ]:
         async with _service(tmp_path, request, value, isolation=isolation) as (adapter, _):
-            with pytest.raises(ExternalServiceProtocolError):
+            with pytest.raises(ExternalCheckerExecutionOutcomeUnknown):
                 await adapter.locate_forge_change(request, _grant(request))
 
 
@@ -257,7 +258,7 @@ async def test_socket_operation_rejects_marker_mismatches_and_locator_as_work_re
         with pytest.raises(ExternalServiceProtocolError):
             await adapter.locate_forge_change(ordinary, _grant(ordinary))
         assert received == []
-        with pytest.raises(ExternalServiceProtocolError):
+        with pytest.raises(ExternalCheckerExecutionOutcomeUnknown):
             await adapter.execute(ordinary, _grant(ordinary))
     assert received[0]["operation"] == "execute"
 
@@ -273,7 +274,7 @@ async def test_locator_validates_locked_output_schema_and_output_byte_limit(tmp_
         with pytest.raises(ExternalCheckerContractError):
             parsed.validate_request(request)
         async with _service(tmp_path, request, value) as (adapter, _):
-            with pytest.raises(ExternalServiceProtocolError):
+            with pytest.raises(ExternalCheckerExecutionOutcomeUnknown):
                 await adapter.locate_forge_change(request, _grant(request))
 
 
diff --git a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
index cce0c7e00..f4f0f1e2d 100644
--- a/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
+++ b/backend/tests/checkers/external/test_selected_pre_submit_coordination.py
@@ -759,7 +759,7 @@ async def test_source_first_claim_caps_lease_at_existing_hard_deadline() -> None
     )
     session = SimpleNamespace(
         sync_session=SimpleNamespace(get_transaction=lambda: SimpleNamespace(is_active=True)),
-        in_nested_transaction=lambda: False, scalar=AsyncMock(side_effect=[row, now]),
+        in_nested_transaction=lambda: False, scalar=AsyncMock(side_effect=[row, now, row]),
         flush=AsyncMock(),
     )
     async def consume(facts):
@@ -772,6 +772,10 @@ async def consume(facts):
     lease = await coordinator.claim(run_id=request.attempt_id, facts=request, authority=authority)
     assert lease.lease_expires_at == request.pre_deadline_at
     assert row.started_at == now
+    with pytest.raises(SelectedPreSubmitUnavailable, match="selected_pre_submit_lease_unavailable"):
+        await coordinator.claim(run_id=request.attempt_id, facts=request, authority=authority)
+    authority.consume.assert_awaited_once()
+    assert (row.lease_id, row.lease_generation) == (str(lease.lease_id), lease.lease_generation)
 
 
 def test_source_first_lease_cannot_extend_aggregate_deadline() -> None:

From d4213eebdd79d335790726c8991c2789519984b0 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 12:57:11 +0100
Subject: [PATCH 422/513] Keep POST invocation ambiguity through outer source
 cleanup

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  18 +++
 .../artifacts/post_submit_materialization.py  |  74 ++++++++-----
 .../artifacts/test_post_source_cleanup.py     | 104 ++++++++++++++++++
 3 files changed, 167 insertions(+), 29 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 755ca93e2..a86efe82e 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12126,3 +12126,21 @@ qualify hardware runtime cleanup or two-node placement.
 The additional forge and repeated PRE claim checks passed 21 cases. The three
 selected ART architecture guards passed. This follow-up changes only test
 expectations and the record. No running service or runner was changed.
+
+Independent review reproduced a second cancellation boundary. The outer POST
+deadline can fire while the materializer drains the sealed source after a
+known unknown invocation. Under the ordinary timeout path that would create
+a terminal retry source. The allowed correction is
+`backend/app/modules/artifacts/post_submit_materialization.py`, its existing
+`backend/tests/artifacts/test_post_source_cleanup.py` owner, and this record.
+Retain the exact invocation error across the real cleanup stack. A failed
+scratch cleanup still takes precedence. Preserve the existing deadline and
+fresh custody check where no invocation ambiguity was observed.
+
+The focused pre-fix run returned `TimeoutError` through the production sealed
+source close for the unknown case. Both controls passed. With the correction,
+16 targeted cases passed in 5.22 seconds, including the four outer materializer
+cases, repeated cancellation cleanup, and the transport boundary. The test
+reschedules an actual outer deadline during source close, waits for cleanup,
+and requires the exact original unknown outcome. Before-send timeout and
+scratch failure preserve their own behavior. No services changed for this proof.
diff --git a/backend/app/modules/artifacts/post_submit_materialization.py b/backend/app/modules/artifacts/post_submit_materialization.py
index 5b2b5c3d0..57546dda0 100644
--- a/backend/app/modules/artifacts/post_submit_materialization.py
+++ b/backend/app/modules/artifacts/post_submit_materialization.py
@@ -17,7 +17,10 @@
     ArtifactLimitExceededError,
     ArtifactStoreUnavailableError,
 )
-from app.interfaces.external_checker_execution import ExternalCheckerMaterialGrant
+from app.interfaces.external_checker_execution import (
+    ExternalCheckerExecutionOutcomeUnknown,
+    ExternalCheckerMaterialGrant,
+)
 from app.interfaces.trusted_submission_intake import (
 
     TrustedSubmissionIntakeAdapter,
@@ -709,6 +712,7 @@ async def materialize(
         selected, evidence_id = await self._select(facts)
         sources = []
         failure = None
+        unknown_invocation = None
         deadline = asyncio.get_running_loop().time() + self._artifact_deadline_ms / 1000
         try:
             materialization_facts = self._authority_facts(facts, selected)
@@ -759,38 +763,45 @@ async def materialize(
                     inspections[role] = inspection
                     intakes[role] = intake
                     media_types[role] = selection.media_type
-                evaluation = await self._preparation._process_prepared_post_submission(
-                    tuple(sources),
-                    _MaterialProcessor(
-                        intakes,
-                        inspections,
-                        request,
-                        consumer,
-                        limits=self._archive_limits,
-                        preparation=self._preparation,
-                        sources=tuple(sources),
-                        execution=facts,
-                        materialization=materialization_facts,
-                        media_types=media_types,
-                    ),
-                    reserved_bytes=expanded_bytes,
-                    # Aggregate materials root, each role root and one temporary grant.
-                    maximum_entries=entries + len(sources) + 2,
+                try:
+                    evaluation = await self._preparation._process_prepared_post_submission(
+                        tuple(sources),
+                        _MaterialProcessor(
+                            intakes,
+                            inspections,
+                            request,
+                            consumer,
+                            limits=self._archive_limits,
+                            preparation=self._preparation,
+                            sources=tuple(sources),
+                            execution=facts,
+                            materialization=materialization_facts,
+                            media_types=media_types,
+                        ),
+                        reserved_bytes=expanded_bytes,
+                        # Aggregate materials root, each role root and one temporary grant.
+                        maximum_entries=entries + len(sources) + 2,
+                    )
+                except ExternalCheckerExecutionOutcomeUnknown as error:
+                    # Stack cleanup can replace the active exception. Preserve the known
+                    # invocation ambiguity before allowing cleanup to run normally.
+                    unknown_invocation = error
+                    raise
+        except (asyncio.CancelledError, TimeoutError) as error:
+            if unknown_invocation is not None:
+                raise unknown_invocation from None
+            if isinstance(error, asyncio.CancelledError):
+                # Before invocation, the executor may convert its deadline cancellation
+                # into a terminal timeout. Fresh custody must still permit that result.
+                await await_cancellation_resistant(
+                    self._select(facts, original=selected, evidence_id=evidence_id)
                 )
-        except asyncio.CancelledError:
-            # The executor may convert its deadline cancellation into a terminal
-            # timeout. Validate the completed read before allowing that conversion.
-            # Denial/drift must win over cancellation; cleanup has already finished.
-            await await_cancellation_resistant(
-                self._select(facts, original=selected, evidence_id=evidence_id)
-            )
             raise
         except ArtifactScratchIntegrityError:
             # Unconfirmed cleanup must never become a retained terminal result.
             raise
-        except PostSubmissionMaterializationFailure as error:
-            failure = error
         except (
+            PostSubmissionMaterializationFailure,
             ArtifactObjectMissingError,
             ArtifactInputMismatchError,
             ArtifactIntegrityError,
@@ -799,8 +810,13 @@ async def materialize(
             SubmissionArchiveRejectedError,
             ExternalServiceAdapterError,
         ) as error:
-            failure = PostSubmissionMaterializationFailure("post_submit_material_unavailable")
-            failure.__cause__ = error
+            if unknown_invocation is not None:
+                raise unknown_invocation from None
+            if isinstance(error, PostSubmissionMaterializationFailure):
+                failure = error
+            else:
+                failure = PostSubmissionMaterializationFailure("post_submit_material_unavailable")
+                failure.__cause__ = error
         await self._select(facts, original=selected, evidence_id=evidence_id)
         if failure is not None:
             raise failure
diff --git a/backend/tests/artifacts/test_post_source_cleanup.py b/backend/tests/artifacts/test_post_source_cleanup.py
index dd2bdd421..ddd954161 100644
--- a/backend/tests/artifacts/test_post_source_cleanup.py
+++ b/backend/tests/artifacts/test_post_source_cleanup.py
@@ -118,3 +118,107 @@ async def source():
     assert await anext(stream) == b"source"
     with pytest.raises(ArtifactScratchIntegrityError, match="source stream cleanup is unconfirmed"):
         await _close_source_stream(stream)
+
+
+@pytest.mark.parametrize("case", ["unknown", "before_send", "scratch_failure", "material_failure"])
+async def test_outer_post_deadline_drains_source_and_preserves_invocation_custody(monkeypatch, case):
+    from contextlib import asynccontextmanager
+    from datetime import UTC, datetime, timedelta
+    from types import SimpleNamespace
+    from unittest.mock import AsyncMock, Mock
+
+    from app.core.identifiers import new_record_id
+    from app.interfaces.external_checker_execution import ExternalCheckerExecutionOutcomeUnknown
+    from app.modules.artifacts import post_submit_materialization as materialization
+    from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits
+    from app.modules.checkers.api.execution import EvaluationReservation, ExecuteFacts, ExecutionLease
+    from tests.checkers.execution.support import selected_request
+
+    request = selected_request()
+    facts = ExecuteFacts(request=request, lease=ExecutionLease(
+        reservation=EvaluationReservation(
+            request_id=request.evaluation_request_id, request_digest=request.request_sha256,
+            attempt_id=new_record_id(), result_id=new_record_id(), evaluation_generation=1,
+        ),
+        lease_id=new_record_id(), lease_generation=1, expires_at=datetime.now(UTC) + timedelta(minutes=1),
+    ))
+    selected = SimpleNamespace(current=SimpleNamespace(
+        sealed_source="fixture-source", media_type="application/zip", sha256=request.content_sha256,
+        byte_count=1, semantic_manifest_sha256=request.content_sha256,
+    ))
+    closing, release, drained = asyncio.Event(), asyncio.Event(), asyncio.Event()
+
+    async def source(reference):
+        assert reference == selected.current.sealed_source
+        try:
+            yield b"x"
+        finally:
+            closing.set()
+            await release.wait()
+            drained.set()
+            if case == "scratch_failure":
+                raise RuntimeError("controlled source close failure")
+
+    async def prepare(stream, **_kwargs):
+        assert await anext(stream) == b"x"
+        return SimpleNamespace(commitment=object(), inspect=AsyncMock())
+
+    @asynccontextmanager
+    async def prepared_intake(_adapter, preparation, **_kwargs):
+        try:
+            yield await preparation, SimpleNamespace(abort=Mock())
+        finally:
+            if case == "material_failure":
+                raise PostSubmissionMaterializationFailure("controlled material cleanup failure")
+
+    original_error = (PostSubmissionMaterializationFailure("before_send") if case == "before_send"
+                      else ExternalCheckerExecutionOutcomeUnknown())
+    processor = AsyncMock(side_effect=original_error)
+    owner = materialization.PostSubmissionMaterializer(
+        sessions=None, tasks=None, store=SimpleNamespace(open_source=source), namespace=None,
+        preparation=SimpleNamespace(prepare=prepare, _process_prepared_post_submission=processor),
+        intake=None, archive_limits=SubmissionArchiveLimits(), artifact_deadline_ms=30_000,
+        authority=None, current_execution=None, revision_tasks=None, revision_feedback=None,
+    )
+    read = AsyncMock(return_value=(selected, new_record_id()))
+    monkeypatch.setattr(owner, "_select", read)
+    monkeypatch.setattr(owner, "_authority_facts", Mock(return_value=SimpleNamespace(predecessor=None)))
+    monkeypatch.setattr(materialization, "prepared_trusted_intake", prepared_intake)
+    monkeypatch.setattr(materialization, "build_submission_manifest", Mock(return_value=SimpleNamespace(
+        sha256=request.content_sha256, total_expanded_bytes=1, entry_count=1,
+    )))
+
+    deadline = asyncio.timeout(None)
+
+    async def execute():
+        async with deadline:
+            return await owner.materialize(facts, _ForbiddenConsumer())
+
+    operation = asyncio.create_task(execute())
+    try:
+        await asyncio.wait_for(closing.wait(), 2)
+        processor.assert_awaited_once()
+        if case != "material_failure":
+            deadline.reschedule(asyncio.get_running_loop().time())
+            await asyncio.sleep(0)
+            assert operation.cancelling()
+        assert not operation.done() and not drained.is_set()
+        release.set()
+        expected = {
+            "unknown": ExternalCheckerExecutionOutcomeUnknown,
+            "before_send": TimeoutError,
+            "scratch_failure": ArtifactScratchIntegrityError,
+            "material_failure": ExternalCheckerExecutionOutcomeUnknown,
+        }[case]
+        with pytest.raises(expected) as result:
+            await asyncio.wait_for(operation, 2)
+        assert deadline.expired() == (case != "material_failure")
+        assert drained.is_set()
+        if case in {"unknown", "material_failure"}:
+            assert result.value is original_error
+        assert read.await_count == (2 if case == "before_send" else 1)
+    finally:
+        release.set()
+        if not operation.done():
+            operation.cancel()
+        await asyncio.gather(operation, return_exceptions=True)

From 9080bf773a4a57f423698e8af0248f0c13353958 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:04:32 +0100
Subject: [PATCH 423/513] docs: record separate runner PRE reservation
 activation

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 22 +++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index a86efe82e..e58d94f51 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12144,3 +12144,25 @@ cases, repeated cancellation cleanup, and the transport boundary. The test
 reschedules an actual outer deadline during source close, waits for cleanup,
 and requires the exact original unknown outcome. Before-send timeout and
 scratch failure preserve their own behavior. No services changed for this proof.
+
+### Reserved PRE capacity activated for native qualification
+
+The existing separate runner was idle (no machines, leases, workspaces,
+workload cgroups, live journey process or established runner TLS connection).
+An independently reviewed bounded operator preserved the old binary, config
+and unit under `/opt/workstream/a29-backup-745a93552b09`, stopped both runner
+units, checked absence again, installed the pinned candidate and restarted.
+The running `/proc/8195/exe` digest is
+`745a93552b09b1ef3573c07feab7a5119dbf91ddd6bbd6933a9a4336347f8bb3`;
+config digest is
+`a25f372fb6aee18ddf1769b774aea60ff949b8726082a327af759c43cf7bb628`.
+The delegated service limit is 6 GiB. Two slots are partitioned into one PRE
+slot (2.5 GiB memory, 5 GiB disk) and one background slot (3.375 GiB memory,
+7 GiB disk); existing CPU and per-invocation bounds are unchanged.
+Native framed health returned ready with four exact cached manifests.
+Activation and post-start observations are retained in
+`/tmp/workstream-a29-runner-candidate/activation-receipt.json` and
+`live-health.json`. This is qualification sizing, not a published production
+latency/resource approval or an overlap-test pass. The current public fixture
+prepares its current archive before running POST; predecessor-archive and
+trial policies need additional background capacity. API deployment is unchanged.

From d5977981914c75147420a6baa337ba989f2a98da Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:02:36 +0100
Subject: [PATCH 424/513] Prove independent custody for equal finalized
 submission sources

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 18 ++++
 .../tasks/test_public_submission_intake.py    | 99 +++++++++++++++++++
 2 files changed, 117 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index e58d94f51..e7883fd4c 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9244,6 +9244,24 @@ adjacent metadata JSON. This evidence covers local Redis and registered workers
 with controlled checker transports. The deployed release remains a separate
 qualification.
 
+### Equal content in separate finalized operations
+
+The A18 custody test seals and rejects two equal-byte sources. The public
+T5 test proves one retained binding. Add one case to
+`backend/tests/tasks/test_public_submission_intake.py` using the signed
+ZIP command, two started tasks and the existing OUTBOX finalization fixture.
+Require two committed submissions, each bound to its own exact source, and
+one logical content identity. Confirm both local object generations remain
+readable and separately charged at the actual byte count after finalization.
+
+Scope is the existing test module and this record. Reuse the approved project,
+local provider, and controlled PRE transport. Production owners, schema,
+storage configuration, live infrastructure, and notification sends are outside
+scope. Low-risk test evidence. Run the focused case in the owned PostgreSQL
+fixture and check Ruff and the diff. Focused QA and architecture review should
+verify that the assertion follows each committed binding to its own exact copy
+and charge, and that logical deduplication cannot hide physical coalescing.
+
 ### Genuine-orphan scope clarification
 
 Read-only ARCH/SEC assessment at08fd205d0 confirms that spec17.4 makes
diff --git a/backend/tests/tasks/test_public_submission_intake.py b/backend/tests/tasks/test_public_submission_intake.py
index 6fbbbfeb9..f4c20c502 100644
--- a/backend/tests/tasks/test_public_submission_intake.py
+++ b/backend/tests/tasks/test_public_submission_intake.py
@@ -193,6 +193,105 @@ async def test_public_malformed_zip_preserves_task_and_retains_cleanup_custody(
     assert valid.json()["status"] == "accepted" and valid.json()["replayed"] is False
 
 
+async def test_public_equal_content_finalizes_distinct_charged_sources(
+    admission_intake, tmp_path, monkeypatch,
+):
+    """Logical deduplication preserves both retained source objects and charges."""
+    from contextlib import aclosing
+    from uuid import UUID
+
+    from sqlalchemy import text
+
+    from app.modules.artifacts.intake.models import SubmissionIntakeOperation, SubmissionSourceCharge
+    from app.modules.artifacts.intake.repository import SubmissionIntakeRepository
+    from app.modules.artifacts.models import ArtifactBinding, ArtifactContent, ArtifactReplica
+    from app.modules.tasks.models import SubmissionDispatch
+    from tests.artifacts.test_submission_foreground_command import configure_source_http
+    from tests.retained_material_fixtures import finalize_retained_intake
+    from tests.tasks.lineage_fixtures import seed_started_task_for_artifact_test
+    from tests.test_artifact_admission import _local_store
+    from tests.test_trusted_intake import _archive
+
+    f, payload = admission_intake, _archive()
+    other_task, other_assignment = new_record_id(), new_record_id()
+    async with f.factory.kw["bind"].begin() as connection:
+        await seed_started_task_for_artifact_test(connection, dict(
+            task=str(other_task), assignment=str(other_assignment), project=str(f.project),
+            actor=str(f.actor.actor_profile_id),
+        ))
+        await connection.execute(text(
+            "UPDATE task_assignments SET accepted_at=clock_timestamp() WHERE id=:id"
+        ), {"id": other_assignment})
+
+    accepted = []
+    for task, assignment in ((f.task, f.assignment), (other_task, other_assignment)):
+        # Give each controlled PRE worker its own scratch directory on the same source store.
+        client, settings, errors, calls = await configure_source_http(
+            f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "completed",
+        )
+        response = await client.post(
+            f"/api/v1/tasks/{task}/submissions",
+            headers=f.access.target.headers | {
+                "Content-Type": "application/zip", "X-Task-Assignment-Id": str(assignment),
+                "Idempotency-Key": str(new_record_id()),
+            },
+            content=payload,
+        )
+        assert not errors, "\n".join(errors)
+        assert response.status_code == 202, response.text
+        receipt = response.json()
+        assert receipt["status"] == "accepted" and receipt["replayed"] is False
+        assert len(calls) == 1
+        operation_id = UUID(receipt["operation_id"])
+        async with f.factory() as session:
+            operation = await session.get(SubmissionIntakeOperation, str(operation_id))
+            assert operation.state == "finalization_pending"
+            source = SubmissionIntakeRepository._sealed_source(operation)
+        accepted.append((str(task), str(assignment), operation_id, source))
+
+    results = []
+    bootstrap, store = _local_store(settings, f.namespace)
+    try:
+        for task, assignment, operation_id, source in accepted:
+            submission_id = await finalize_retained_intake(f.factory, SimpleNamespace(
+                operation_id=operation_id, settings=settings, store=store, namespace=f.namespace,
+            ))
+            results.append((task, assignment, source, submission_id))
+
+        replicas, contents, bindings = set(), set(), set()
+        async with f.factory() as session:
+            for task, assignment, source, submission_id in results:
+                operation = await session.get(SubmissionIntakeOperation, str(source.location.operation_id))
+                assert SubmissionIntakeRepository._sealed_source(operation) == source
+                dispatch = await session.get(SubmissionDispatch, submission_id)
+                assert (dispatch.task_id, dispatch.assignment_id, dispatch.submission_version) == (task, assignment, 1)
+                assert dispatch.admission_id == operation.finalized_admission_id
+                binding = await session.get(ArtifactBinding, dispatch.artifact_binding_id)
+                admission = await session.get(SubmissionBundleAdmission, dispatch.admission_id)
+                replica = await session.get(ArtifactReplica, admission.verified_replica_id)
+                content = await session.get(ArtifactContent, dispatch.artifact_content_id)
+                charge = await session.get(SubmissionSourceCharge, operation.id)
+                assert binding.resource_type == "submission" and binding.resource_id == submission_id
+                assert binding.content_id == admission.artifact_content_id == replica.content_id == content.id
+                assert admission.status == "consumed" and admission.consumed_by_submission_id == submission_id
+                assert admission.source_operation_id == replica.source_operation_id == operation.id
+                assert replica.provider_object_ref == operation.object_ref == source.location.object_ref
+                assert (content.sha256, content.byte_count) == (source.raw_sha256, len(payload))
+                assert (charge.state, charge.accounted_bytes) == ("sealed", len(payload))
+                replicas.add(replica.id)
+                bindings.add(binding.id)
+                contents.add(content.id)
+
+        assert len(replicas) == len(bindings) == 2
+        assert len(contents) == 1
+        assert len({source.location.object_ref for _, _, source, _ in results}) == 2
+        for _, _, source, _ in results:
+            async with aclosing(store.open_source(source)) as reader:
+                assert b"".join([chunk async for chunk in reader]) == payload
+    finally:
+        bootstrap.close()
+
+
 async def test_public_minimal_submission_survives_acceptance_finalization_and_replay(
     admission_intake, tmp_path, monkeypatch,
 ):

From e1599807dadffce53b298da814e568ccaa0073f4 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:06:07 +0100
Subject: [PATCH 425/513] Record verified equal-source finalization custody

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md    | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index e7883fd4c..9c2c01138 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9262,6 +9262,18 @@ fixture and check Ruff and the diff. Focused QA and architecture review should
 verify that the assertion follows each committed binding to its own exact copy
 and charge, and that logical deduplication cannot hide physical coalescing.
 
+The focused PostgreSQL case passed in 107.10 seconds at `8a03d1ac1`, schema
+0093. Distinct task assignments completed signed ZIP acceptance and canonical
+T5 OUTBOX delivery. Each submission's consumed admission selected its own
+replica and retained seal, with one independent sealed charge at the ZIP byte
+count. Both exact source reads succeeded after both commits. The local provider
+rechecks the seal and single-link inode generation on each read. The two
+bindings shared the same logical content ID. This run qualifies local source
+retention with controlled PRE execution. The isolated-runner log and metadata
+are `/tmp/pr708-a18-finalized-isolated.log` and
+`/tmp/pr708-a18-finalized-isolated.json`. Owned resources cleaned successfully.
+Ruff, diff validation, and Commitrail validation passed.
+
 ### Genuine-orphan scope clarification
 
 Read-only ARCH/SEC assessment at08fd205d0 confirms that spec17.4 makes

From 5368b70a5d88308e4b0f8943f2115c88e5d15fe7 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:16:49 +0100
Subject: [PATCH 426/513] Register feedback email owners in the protected
 partition

---
 .ci/behavior-ownership/partition.v1.json      | 14 ++++++++++-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 23 +++++++++++++++++++
 backend/scripts/behavior_ownership.py         |  3 +++
 backend/tests/test_behavior_ownership.py      |  3 +++
 4 files changed, 42 insertions(+), 1 deletion(-)

diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json
index 6a43a6f76..32112d8e9 100644
--- a/.ci/behavior-ownership/partition.v1.json
+++ b/.ci/behavior-ownership/partition.v1.json
@@ -180,6 +180,10 @@
       "group": "lifecycle",
       "target": "backend/app/adapters/reviews/contribution_reads.py"
     },
+    {
+      "group": "lifecycle",
+      "target": "backend/app/adapters/submission_feedback_email.py"
+    },
     {
       "group": "lifecycle",
       "target": "backend/app/adapters/tasks/contribution_reads.py"
@@ -468,6 +472,10 @@
       "group": "shared",
       "target": "backend/app/interfaces/setup_model_proxy.py"
     },
+    {
+      "group": "lifecycle",
+      "target": "backend/app/interfaces/submission_feedback_email.py"
+    },
     {
       "group": "shared",
       "target": "backend/app/interfaces/trial_execution.py"
@@ -2384,6 +2392,10 @@
       "group": "lifecycle",
       "target": "backend/app/modules/tasks/post_submit_routing/evaluation_guard.py"
     },
+    {
+      "group": "lifecycle",
+      "target": "backend/app/modules/tasks/post_submit_routing/feedback_email.py"
+    },
     {
       "group": "lifecycle",
       "target": "backend/app/modules/tasks/post_submit_routing/models.py"
@@ -2749,7 +2761,7 @@
       "target": "backend/scripts/validate_test_lane_evidence.py"
     }
   ],
-  "authority_digest": "ec63dcd5f70071cd2dcb69a2c3e127162a2b017aa3734bed14d12440c38d8bdc",
+  "authority_digest": "14aa921cf9fc07a0779144d16686327eaa779d64e06fa40d383137a387d8b791",
   "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6",
   "schema": "workstream.behavior-ownership-partition.v1"
 }
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 9c2c01138..ad9dded00 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9291,6 +9291,29 @@ and links the canonical source-key specification instead of duplicating its
 versioned key example. This resolves stale-vocabulary scan false positives
 without changing the scanner, IAM policy, runtime behavior or key format.
 
+### Register feedback email behavior ownership
+
+The AUTH preflight passed 98 tests on `f480` before the ownership
+validator reported `partition_target_mismatch`. Comparing the current
+tracked inventory with the protected partition identifies three missing
+lifecycle targets for the feedback email adapter, interface, and TASK owner.
+Authorize these exact additions in the existing submission-intake target
+set and its focused test. Regenerate the canonical partition with the
+same protected base and retain every existing assignment.
+
+Scope is `.ci/behavior-ownership/partition.v1.json`,
+`backend/scripts/behavior_ownership.py`, the existing
+`backend/tests/test_behavior_ownership.py` test, and this record. The
+validator, workflow, mutation policy, existing test claims and product
+behavior remain outside this correction. Low risk. Focused QA review should
+verify the unchanged protected base and reject unrelated targets. Run the
+existing ownership test, canonical ownership validation, Ruff and diff checks.
+
+The generated partition diff added exactly three lifecycle assignments and
+updated the authority digest. Four targeted ownership tests passed. The
+canonical validator passed against the protected PR base
+`d713594ebf04a125917edb0ec981d380cf8047b4`. Ruff and diff checks passed.
+
 ### Refresh pending-operation MCP schema descriptions
 
 Configured backend OpenAPI comparison atc853743b6 passed142 and failed2
diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py
index 585a166e0..f93251722 100644
--- a/backend/scripts/behavior_ownership.py
+++ b/backend/scripts/behavior_ownership.py
@@ -996,6 +996,9 @@
     "backend/app/modules/tasks/api/intake_custody.py",
     "backend/app/modules/tasks/api/pending_submission.py",
     "backend/app/modules/tasks/intake_custody.py",
+    "backend/app/adapters/submission_feedback_email.py",
+    "backend/app/interfaces/submission_feedback_email.py",
+    "backend/app/modules/tasks/post_submit_routing/feedback_email.py",
 })
 FORGE_PROOF_FACTS_TARGETS = frozenset({
     "backend/app/adapters/github/app_facts.py",
diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py
index 502df11e5..3a4f52787 100644
--- a/backend/tests/test_behavior_ownership.py
+++ b/backend/tests/test_behavior_ownership.py
@@ -2803,6 +2803,9 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ
         "backend/app/modules/tasks/api/intake_custody.py",
         "backend/app/modules/tasks/api/pending_submission.py",
         "backend/app/modules/tasks/intake_custody.py",
+        "backend/app/adapters/submission_feedback_email.py",
+        "backend/app/interfaces/submission_feedback_email.py",
+        "backend/app/modules/tasks/post_submit_routing/feedback_email.py",
     }
     assert ownership.SUBMISSION_INTAKE_TARGETS == additions
     trusted = _partition([retained])

From fc05f6987afca623af059bfe41d874825141949f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:20:33 +0100
Subject: [PATCH 427/513] Align CI assertions and predecessor fixtures with
 verified email

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 27 +++++++++++++++++++
 .../authentication/test_token_contract.py     |  2 ++
 .../migrations/test_claim_starts_work.py      |  9 +++++++
 .../test_unsealed_source_cleanup_migration.py | 11 +++++++-
 backend/tests/test_artifact_architecture.py   |  4 +++
 backend/tests/test_ci_lane_catalogue.py       |  4 +--
 6 files changed, 54 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index ad9dded00..0b8bb4780 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9314,6 +9314,33 @@ updated the authority digest. Four targeted ownership tests passed. The
 canonical validator passed against the protected PR base
 `d713594ebf04a125917edb0ec981d380cf8047b4`. Ruff and diff checks passed.
 
+### Align existing test evidence with verified email
+
+The failed f480 lane bundles collected the complete suite and then reported
+separate assertion and fixture failures. The feedback email composition root
+and token verification field need exact test expectations. The TASK lane
+already includes the new feedback email test module. Update the independent
+fingerprint for that single addition using the same digest calculation.
+
+The cleanup migration fixture uses current actor ORM during setup on 0087
+and 0088. Supply the required false-only projection during fixture reads and
+remove it before taking the predecessor snapshot. The claim-start fixture
+uses current dev auth on 0064. Assert the exact two fixture-created identity
+links have no verified mailbox and remove only their post-0064 observation
+timestamps before dropping the existing null-only projection. Preserve the
+task, assignment, receipt, audit and migration assertions.
+
+Allowed files are the existing tests
+`test_artifact_architecture.py`, `authentication/test_token_contract.py`,
+`test_ci_lane_catalogue.py`, `migrations/test_unsealed_source_cleanup_migration.py`,
+`migrations/test_claim_starts_work.py`, and this record. Changes are confined
+to test expectations and historical fixtures. No production or migration
+changes, routing or timing allowances, workflow changes, or scope expansion.
+Focused QA should check the exact factory count, exact token fields, the single
+module fingerprint delta, and that each historical upgrade starts from the
+original predecessor shape. Run the selected pure checks and exact three
+historical cases in separate owned PostgreSQL after the native run releases it.
+
 ### Refresh pending-operation MCP schema descriptions
 
 Configured backend OpenAPI comparison atc853743b6 passed142 and failed2
diff --git a/backend/tests/authentication/test_token_contract.py b/backend/tests/authentication/test_token_contract.py
index 719f58d18..2e6a6015f 100644
--- a/backend/tests/authentication/test_token_contract.py
+++ b/backend/tests/authentication/test_token_contract.py
@@ -50,11 +50,13 @@ async def test_asymmetric_token_returns_minimal_canonical_contract(
         "subject_kind",
         "scopes",
         "email",
+        "email_verified",
         "name",
     }
     assert result.token.subject == "opaque-subject-1"
     assert not hasattr(result.token, "roles")
     assert result.token.email == "issuer-profile@example.test"
+    assert result.token.email_verified is False
     assert result.token.name == "Issuer Profile"
 
 
diff --git a/backend/tests/migrations/test_claim_starts_work.py b/backend/tests/migrations/test_claim_starts_work.py
index e63204475..af6d8be01 100644
--- a/backend/tests/migrations/test_claim_starts_work.py
+++ b/backend/tests/migrations/test_claim_starts_work.py
@@ -194,6 +194,15 @@ async def test_upgrade_starts_only_retained_claim_and_preserves_evidence(predece
         assignment_id = assignment.id
         await session.commit()
     async with db_session.get_engine().begin() as connection:
+        # Only current dev-auth setup wrote these later identity observations.
+        observed = list(await connection.scalars(text("""
+            UPDATE public.actor_identity_links
+            SET email_observed_issued_at=NULL
+            WHERE issuer='flow-test' AND subject IN ('project-manager-subject', 'historical-claimant')
+              AND email_verified IS FALSE AND email_observed_issued_at IS NOT NULL
+            RETURNING subject
+        """)))
+        assert sorted(observed) == ["historical-claimant", "project-manager-subject"]
         await drop_retained_owner_read_projection(connection)
     await db_session.dispose_engine()
     await asyncio.to_thread(command.upgrade, _config(), "head")
diff --git a/backend/tests/migrations/test_unsealed_source_cleanup_migration.py b/backend/tests/migrations/test_unsealed_source_cleanup_migration.py
index d23797fbe..65c640816 100644
--- a/backend/tests/migrations/test_unsealed_source_cleanup_migration.py
+++ b/backend/tests/migrations/test_unsealed_source_cleanup_migration.py
@@ -26,7 +26,7 @@
 
 @asynccontextmanager
 async def predecessor_submission_read_projection(intake):
-    """Construct old v1 commands, then restore the exact predecessor schema."""
+    """Construct old v1 commands and remove both current ORM projections."""
     def bind_old_metadata(_mapper, _connection, row):
         assert row.command_metadata["feedback"] is None
         metadata = {
@@ -55,6 +55,10 @@ def bind_old_metadata(_mapper, _connection, row):
                 "SELECT count(*) FROM public.submissions WHERE feedback IS NOT NULL"
             )) == 0
             await connection.execute(text("ALTER TABLE public.submissions DROP COLUMN feedback"))
+            assert await connection.scalar(text(
+                "SELECT count(*) FROM public.actor_identity_links WHERE email_verified IS DISTINCT FROM false"
+            )) == 0
+            await connection.execute(text("ALTER TABLE public.actor_identity_links DROP COLUMN email_verified"))
 
 
 @pytest.fixture(autouse=True, params=["0087_source_cleanup_candidates", "0088_unsealed_source_cleanup"])
@@ -65,6 +69,11 @@ async def predecessor_schema(isolated_database_env, migration_lock, request):
         await _drop_test_database_schema(isolated_database_env)
         try:
             await asyncio.to_thread(command.upgrade, _config(), request.param)
+            # The intake fixture uses the current ORM to create fixture identities.
+            async with db_session.get_engine().begin() as connection:
+                await connection.execute(text(
+                    "ALTER TABLE public.actor_identity_links ADD COLUMN email_verified boolean NOT NULL DEFAULT false"
+                ))
             yield request.param
         finally:
             await db_session.dispose_engine()
diff --git a/backend/tests/test_artifact_architecture.py b/backend/tests/test_artifact_architecture.py
index 0c4a6b2f9..26479e876 100644
--- a/backend/tests/test_artifact_architecture.py
+++ b/backend/tests/test_artifact_architecture.py
@@ -33,6 +33,7 @@
 GUIDE_PARSER_COMPOSITION_ROOT = APP_ROOT / "adapters/guide_document_tools/__init__.py"
 OBSERVABILITY_COMPOSITION_ROOT = APP_ROOT / "adapters" / "observability.py"
 GITHUB_COMPOSITION_ROOT = APP_ROOT / "adapters" / "github" / "__init__.py"
+FEEDBACK_EMAIL_COMPOSITION_ROOT = APP_ROOT / "adapters" / "submission_feedback_email.py"
 AGENT_ADAPTER_MODULES = {
     "app.adapters.project_agents.manager_authored",
     "app.adapters.project_agents.omnicore_agent",
@@ -379,6 +380,7 @@ def _assert_concrete_adapter_composition(
                 "RemoteTlsTrustedIntakeAdapter",
                 "OpenAIResponsesCheckerModelProvider",
                 "OpenRouterCheckerModelProvider",
+                "ResendSubmissionFeedbackEmailAdapter",
             }
         )
         agent_calls.extend(path for name in calls if name in AGENT_RUNTIME_CONSTRUCTORS)
@@ -396,9 +398,11 @@ def _assert_concrete_adapter_composition(
         OBSERVABILITY_COMPOSITION_ROOT: 1,
         GUIDE_PARSER_COMPOSITION_ROOT: 1,
         GITHUB_COMPOSITION_ROOT: 1,
+        FEEDBACK_EMAIL_COMPOSITION_ROOT: 1,
     }
     assert Counter(adapter_calls) == {
         COMPOSITION_ROOT: 2, S3_ADAPTER_MODULE: 1, CHECKER_COMPOSITION_ROOT: 3,
+        FEEDBACK_EMAIL_COMPOSITION_ROOT: 1,
     }
     assert set(concrete_imports) == {
         COMPOSITION_ROOT,
diff --git a/backend/tests/test_ci_lane_catalogue.py b/backend/tests/test_ci_lane_catalogue.py
index 05174e28c..eff0f8d1e 100644
--- a/backend/tests/test_ci_lane_catalogue.py
+++ b/backend/tests/test_ci_lane_catalogue.py
@@ -340,8 +340,8 @@ def test_semantic_family_membership_has_an_independent_fingerprint() -> None:
             "39504157bb06c4da278a8682230d5e76ce820d7ce3c88cd59af08f8693f293c6",
         ),
         "task": (
-            96,
-            "dfd8a2c63b43d85422eaf9f98fe30ef9a044a492a7e8270261de9c2b491a0eb3",
+            97,
+            "f0e63da8bf843db9a83028c428b080504ca4566c36e7764b4cb6840592166364",
         ),
     }
     actual = {

From 1af1c148b3ec962fff700b5f985b93f18e8f9f2a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:21:36 +0100
Subject: [PATCH 428/513] test(submissions): qualify native POST PRE and T5
 overlap

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  33 +++
 .../README.md                                 |  15 ++
 .../public_guide_setup.py                     |   8 +-
 .../public_intake_observer.py                 |  25 ++
 .../public_probe_support.py                   |  11 +-
 .../read_native_admission.py                  | 119 ++++++++
 .../run_public_journey_probe.py               | 255 +++++++++++++++++-
 scripts/test_public_hosted_attachment.py      |  64 +++++
 8 files changed, 512 insertions(+), 18 deletions(-)
 create mode 100644 experiments/pilot04_external_checker_runtime/read_native_admission.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 0b8bb4780..2a9bc60e0 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12246,3 +12246,36 @@ Activation and post-start observations are retained in
 latency/resource approval or an overlap-test pass. The current public fixture
 prepares its current archive before running POST; predecessor-archive and
 trial policies need additional background capacity. API deployment is unchanged.
+
+### A29 native overlap fixture
+
+Prove separate-runner overlap on the reviewed one-PRE/one-Background node.
+Run a selected POST checker with the pinned fixture image's existing
+`mode=deadline` sleep, with its ordinary checker deadline. Submit another
+unmarked ZIP through public selected PRE and pause its test adapter at the
+existing native call boundary until the POST lease and populated cgroup are
+observed. Resume an already prepared third T4 through the exclusive
+finalization worker while the two native admissions overlap. Require the exact
+sealed source and original T5 outbox acknowledgement, with its POST request
+still parked. Finish the distinct PRE within the unchanged runtime budget.
+
+Use the existing separate-runner public journey, fixture image selection and
+owned worker controls. Add only an opt-in overlap probe, its read-only native
+observer and focused checks. The ordinary policy cases, production adapters,
+runner image and resource guards stay unchanged. Keep the overlap receipt
+separate from completed policy cases and require the terminal command and its
+matching isolated cleanup evidence. The implementing worktree does not start
+or change the deployed runner.
+
+The probe starts the same seven dedicated workers before waiting for their
+existing readiness checks. Beat and public workload requests still start only
+after every check passes. The native readonly sampler pins the live checker
+binary and config and binds the observed PRE journal hash to the final destroyed
+receipt. It confirms the held POST's exact durable attempt through the native
+grant and populated cgroup. No production timeout or capacity setting changed.
+
+Four focused local tests passed, including the existing exclusive policy receipt,
+the held fixture's unchanged resource limits, the native POST grant and journal
+reader, and refusal of unpopulated or mismatched background state. Compilation,
+focused Ruff and diff checks passed. Native overlap remains for the exclusive
+runner qualification; no service, broker or PostgreSQL was used for these checks.
diff --git a/experiments/pilot04_external_checker_runtime/README.md b/experiments/pilot04_external_checker_runtime/README.md
index f16cafb6a..fac360cd0 100644
--- a/experiments/pilot04_external_checker_runtime/README.md
+++ b/experiments/pilot04_external_checker_runtime/README.md
@@ -161,6 +161,21 @@ configured mTLS route. The client host keeps its own artifact scratch.
 This mode records null intake and runtime fault trials. The existing remote
 PRE fault bridge covers its independently supervised fault stage.
 
+Run the A29 admission proof separately by adding `--admission-overlap-observer`
+with the absolute path of an owned executable. The executable receives the
+reviewed configuration and checker executable SHA-256 values. Have it execute
+`read_native_admission.py` on the runner through the existing private SSH route
+with the active checker config path followed by those two values, and return
+its JSON unchanged. The observer reads native journals, cgroup population, and
+the POST grant binding. It requires no runner restart or fixture image change.
+
+The proof approves the pinned project fixture's existing `mode=deadline` on
+POST and holds the independent public selected PRE at its dispatch boundary.
+It brackets the exact T5 acknowledgement with the same active Background and
+PRE reservations, then checks the completed PRE and the parked evaluation
+requests. `admission_overlap` belongs to this proof only. Retain the terminal
+result and matching isolated cleanup receipt for this run.
+
 ```sh
 PYTHONPATH=.:tests:.. .venv/bin/python scripts/run_isolated_tests.py \
   --metadata-json /tmp/guide-journey-cleanup.json --timeout-seconds 1500 \
diff --git a/experiments/pilot04_external_checker_runtime/public_guide_setup.py b/experiments/pilot04_external_checker_runtime/public_guide_setup.py
index 64eabae03..b12bad2bd 100644
--- a/experiments/pilot04_external_checker_runtime/public_guide_setup.py
+++ b/experiments/pilot04_external_checker_runtime/public_guide_setup.py
@@ -207,7 +207,7 @@ async def _source_evidence(factory, guide, setup, package, originals, *, manager
             **({"manager_rules_sha256": original_digests[1]} if manager_authored else {})}
 
 
-async def _local_approval_attachments(factory):
+async def _local_approval_attachments(factory, *, hold_post=False):
     """Select the exact previously published fixture identities, never empty phases."""
     from app.modules.checkers.api.external_policy import ExternalCheckerImageAttachment
     from app.modules.checkers.external_registry import ExternalCheckerRegistryReader
@@ -228,14 +228,14 @@ async def _local_approval_attachments(factory):
                 requirement_id="project." + spec.phase,
                 registry_entry_id=entry.registry_entry_id,
                 registry_entry_digest=entry.entry_digest,
-                configuration={},
+                configuration={"mode": "deadline"} if hold_post and spec.phase == "post_submit" else {},
             ).model_dump(mode="json")]
     return attachments
 
 
 async def public_guide_setup(client, factory, human_review_required, call, token_for, *,
                              pre_requirements=1, attachment=None, issuer="https://identity.flowresearch.tech",
-                             manager_authored=False):
+                             manager_authored=False, hold_post=False):
     if pre_requirements != 1:
         raise ValueError("current qualification requires exactly one PRE image")
     model_post = attachment.model_post if attachment else None
@@ -297,7 +297,7 @@ async def public_guide_setup(client, factory, human_review_required, call, token
     compilation_root = root + f"/compilations/{setup['finalized_compilation_id']}"
     attachments = (model_post.approval_attachments() if model_post else
                    attachment.approval_attachments(pre_requirements) if attachment else
-                   await _local_approval_attachments(factory))
+                   await _local_approval_attachments(factory, hold_post=hold_post))
     if human_review_required and not manager_authored:
         initial = await call(client, "GET", compilation_root + "/proposal", token, 200)
         initial_setup = setup
diff --git a/experiments/pilot04_external_checker_runtime/public_intake_observer.py b/experiments/pilot04_external_checker_runtime/public_intake_observer.py
index b4f9f9a89..5efba31c8 100644
--- a/experiments/pilot04_external_checker_runtime/public_intake_observer.py
+++ b/experiments/pilot04_external_checker_runtime/public_intake_observer.py
@@ -1,5 +1,6 @@
 """Opt-in drill entry point recording real adapter acknowledgements, never faking them."""
 
+import asyncio
 import json
 import os
 from pathlib import Path
@@ -10,8 +11,10 @@
 from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter
 
 _TRACE = Path(os.environ["WORKSTREAM_PROBE_INTAKE_TRACE"])
+_PRE_BARRIER = os.environ.get("WORKSTREAM_PROBE_PRE_BARRIER")
 _prepare = RemoteTlsTrustedIntakeAdapter.prepare
 _execute = RemoteTlsExternalCheckerAdapter.execute
+_execute_pre = RemoteTlsExternalCheckerAdapter.execute_pre
 
 
 def _record(event, identifier, **facts):
@@ -50,8 +53,30 @@ async def _observe_execute(self, request, grant, *, model_grant=None):
     return result
 
 
+async def _observe_pre(self, lease, grant):
+    if _PRE_BARRIER is not None:
+        root = Path(_PRE_BARRIER)
+        selector = root / "source.sha256"
+        source = lease.reservation.source
+        if selector.exists() and selector.read_text().strip() == source.raw_sha256:
+            temporary = root / "pre-dispatch.pending"
+            with temporary.open("x") as output:
+                json.dump({"run_id": str(lease.reservation.attempt_id),
+                           "source_operation_id": str(source.location.operation_id),
+                           "request_digest": lease.reservation.request_digest,
+                           "lease_id": str(lease.lease_id),
+                           "lease_generation": lease.lease_generation}, output)
+            temporary.rename(root / "pre-dispatch.json")
+            while not (root / "release-pre").exists():
+                if time.time() >= lease.lease_expires_at.timestamp():
+                    raise TimeoutError("PRE overlap fixture missed its original lease")
+                await asyncio.sleep(0.05)
+    return await _execute_pre(self, lease, grant)
+
+
 # This explicitly selected proof entry point delegates all work to the original
 # typed adapter. Production app imports and ordinary workers never install it.
 RemoteTlsTrustedIntakeAdapter.prepare = _observe_prepare
 RemoteTlsExternalCheckerAdapter.execute = _observe_execute
+RemoteTlsExternalCheckerAdapter.execute_pre = _observe_pre
 from app.main import app as app  # noqa: E402
diff --git a/experiments/pilot04_external_checker_runtime/public_probe_support.py b/experiments/pilot04_external_checker_runtime/public_probe_support.py
index 1e3071b12..2687ddb70 100644
--- a/experiments/pilot04_external_checker_runtime/public_probe_support.py
+++ b/experiments/pilot04_external_checker_runtime/public_probe_support.py
@@ -224,7 +224,7 @@ async def _started_public_task(client, *, project_id: str, manager_token: str,
 
 
 async def _public_project(client, factory, env, *, human_review_required, pre_requirements=1,
-                          manager_authored=False):
+                          manager_authored=False, hold_post=False):
     """Public guide activation and submitter grant shared by every runtime trial."""
     from experiments.pilot04_external_checker_runtime.public_hosted_attachment import HostedAttachment
     from experiments.pilot04_external_checker_runtime.public_submission_clients import seeded_issuer
@@ -233,7 +233,7 @@ async def _public_project(client, factory, env, *, human_review_required, pre_re
     compilation = await public_guide_setup(
         client, factory, human_review_required, _json, lambda actor: _token(env, actor),
         pre_requirements=pre_requirements, attachment=attachment, issuer=seeded_issuer(env),
-        manager_authored=manager_authored,
+        manager_authored=manager_authored, hold_post=hold_post,
     )
     manager = compilation.manager
     guide_id = str(compilation.guide_id)
@@ -293,7 +293,7 @@ async def _public_project(client, factory, env, *, human_review_required, pre_re
     return compilation, contributor, manager_token, contributor_token
 
 
-def _locked_spec(phase: str, image: dict[str, str]) -> ExternalCheckerRegistrySpec:
+def _locked_spec(phase: str, image: dict[str, str], *, hold_post=False) -> ExternalCheckerRegistrySpec:
     source = registry_spec("pre_submit") if phase == "pre_submit" else post_registry_spec()
     values = source.model_dump(mode="json")
     if phase == "pre_submit":
@@ -304,6 +304,11 @@ def _locked_spec(phase: str, image: dict[str, str]) -> ExternalCheckerRegistrySp
             document=document,
             schema_sha256=external_checker_json_hash(document),
         ).model_dump(mode="json")
+    if phase == "post_submit" and hold_post:
+        document = {"type": "object", "properties": {"mode": {"enum": ["deadline"]}},
+                    "required": ["mode"], "additionalProperties": False}
+        values["configuration_schema"] |= {"document": document,
+                                            "schema_sha256": external_checker_json_hash(document)}
     values["image_digest"] = image["platform_manifest_digest"]
     values["resources"] |= {"deadline_ms": 30_000, "maximum_output_bytes": 8_192}
     return ExternalCheckerRegistrySpec.model_validate(values)
diff --git a/experiments/pilot04_external_checker_runtime/read_native_admission.py b/experiments/pilot04_external_checker_runtime/read_native_admission.py
new file mode 100644
index 000000000..a3f4ff1e4
--- /dev/null
+++ b/experiments/pilot04_external_checker_runtime/read_native_admission.py
@@ -0,0 +1,119 @@
+"""Read one bounded A29 runner snapshot without invoking or changing the service."""
+
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import time
+
+
+_VM_NAME = re.compile(r"ws-[0-9a-f]{32}")
+_GRANT_NAME = re.compile(r"extract_[0-9a-f]{32}")
+_PRE_FIELDS = ("run_id", "source_operation_id", "request_digest", "lease_id", "lease_generation")
+_POST_FIELDS = ("project_id", "task_id", "submission_id", "evaluation_request_id", "attempt_id", "lease_id")
+
+
+def _read(path, maximum):
+    fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
+    with os.fdopen(fd, "rb") as stream:
+        payload = stream.read(maximum + 1)
+    if len(payload) > maximum:
+        raise ValueError("native observation exceeded its input bound")
+    return payload
+
+
+def _sha(payload):
+    return "sha256:" + hashlib.sha256(payload).hexdigest()
+
+
+def _lease_journal(path):
+    # The owner creates each lease file before writing its fsynced contents.
+    # A partial first read cannot count as an idle node or a completed admission.
+    for attempt in range(3):
+        journal = _read(path, 16_384)
+        try:
+            return journal, json.loads(journal)
+        except json.JSONDecodeError:
+            if attempt == 2:
+                raise
+            time.sleep(0.02)
+
+
+def _controller_pid():
+    value = subprocess.check_output(
+        ["systemctl", "show", "workstream-checker.service", "-p", "MainPID", "--value"],
+        timeout=3,
+    )
+    return int(value)
+
+
+def observe(config_path, config_sha256, service_sha256):
+    raw = _read(config_path, 65_536)
+    if _sha(raw) != config_sha256:
+        raise ValueError("active runner configuration differs from the reviewed copy")
+    config = json.loads(raw)
+    pid = _controller_pid()
+    if pid <= 0:
+        raise ValueError("native runner is not active")
+    with Path(f"/proc/{pid}/exe").open("rb") as executable:
+        if "sha256:" + hashlib.file_digest(executable, "sha256").hexdigest() != service_sha256:
+            raise ValueError("active runner executable differs from the reviewed copy")
+    lease_root = Path(config["socket_path"]).parent / "smol-leases"
+    owner = _read(lease_root.parent / ".workstream-checker-owner", 128).decode().strip()
+    groups = Path(config["smol"]["cgroup_root"])
+    leases = []
+    for path in sorted(lease_root.glob("ws-*.json")):
+        if _VM_NAME.fullmatch(path.stem) is None or len(leases) == 2:
+            raise ValueError("unexpected native lease inventory")
+        try:
+            journal, lease = _lease_journal(path)
+        except FileNotFoundError:
+            continue
+        if lease["name"] != path.stem or lease["owner"] != owner:
+            raise ValueError("native lease owner differs")
+        try:
+            events = _read(groups / path.stem / "cgroup.events", 1_024).splitlines()
+        except FileNotFoundError:
+            events = []
+        if lease["pre"] is not None and lease["pre"]["operation"] != "execute_pre":
+            raise ValueError("unknown native PRE lease operation")
+        selected = None if lease["pre"] is None else {key: lease["pre"][key] for key in _PRE_FIELDS}
+        leases.append({"name": path.stem, "epoch": lease["epoch"],
+                       "journal_sha256": _sha(journal), "populated": b"populated 1" in events, "pre": selected})
+    grants = []
+    for path in sorted((Path(config["material_root"]) / "workspaces").glob("extract_*")):
+        if _GRANT_NAME.fullmatch(path.name) is None or len(grants) == 1:
+            raise ValueError("unexpected native material inventory")
+        try:
+            manifest = json.loads(_read(path / ".external-checker-grant.json", 2_097_152))
+        except FileNotFoundError:
+            continue
+        binding = manifest.pop("binding_digest")
+        canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"),
+                               ensure_ascii=False, allow_nan=False).encode()
+        if (manifest["protocol_version"] != "workstream.external_checker_material_grant.v2"
+                or manifest["grant_id"] != path.name or manifest["phase"] != "post_submit"
+                or manifest["identity"]["phase"] != "post_submit" or binding != _sha(canonical)):
+            raise ValueError("native POST grant identity differs")
+        grants.append({"grant_id": path.name, "request_digest": manifest["request_digest"],
+                       **{key: manifest["identity"][key] for key in _POST_FIELDS}})
+    if _controller_pid() != pid or _read(config_path, 65_536) != raw:
+        raise ValueError("native runner changed during observation")
+    return {"config_sha256": config_sha256, "service_sha256": service_sha256,
+            "checker_pid": pid, "leases": leases, "post_grants": grants}
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("config", type=Path)
+    parser.add_argument("config_sha256")
+    parser.add_argument("service_sha256")
+    args = parser.parse_args()
+    print(json.dumps(observe(args.config, args.config_sha256, args.service_sha256), sort_keys=True))
+
+
+if __name__ == "__main__":
+    main()
diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
index 9b0290cf5..46f78bc90 100644
--- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
+++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
@@ -1194,6 +1194,204 @@ async def _pre_runs(factory, task_id: str) -> list[str]:
         ).order_by(SelectedPreSubmitRun.queued_at)))
 
 
+async def _overlap_consumer(host, queue, enabled):
+    """Change only the named proof worker's consumption of its own queue."""
+    from app.workers.celery_app import celery_app
+
+    control = celery_app.control.add_consumer if enabled else celery_app.control.cancel_consumer
+    replies = await asyncio.to_thread(control, queue, destination=[host], reply=True, timeout=3)
+    _require(len(replies) == 1 and set(replies[0]) == {host} and "ok" in replies[0][host],
+             "owned overlap worker did not confirm its queue transition")
+
+
+async def _overlap_snapshot(observer, custody):
+    process = await asyncio.create_subprocess_exec(
+        str(observer), custody["config_sha256"], custody["service_sha256"],
+        stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL,
+        start_new_session=True,
+    )
+    try:
+        stdout, _ = await asyncio.wait_for(process.communicate(), timeout=6)
+    finally:
+        if process.returncode is None:
+            try:
+                os.killpg(process.pid, signal.SIGKILL)
+            except ProcessLookupError:
+                pass
+            await process.wait()
+    _require(process.returncode == 0 and len(stdout) <= 65_536, "native overlap observer failed")
+    value = json.loads(stdout)
+    _require(set(value) == {"checker_pid", "config_sha256", "service_sha256", "leases", "post_grants"}
+             and value["config_sha256"] == custody["config_sha256"]
+             and value["service_sha256"] == custody["service_sha256"]
+             and type(value["checker_pid"]) is int and value["checker_pid"] > 0,
+             "native overlap observation differs from the reviewed node")
+    return value
+
+
+def _overlap_post(snapshot, expected_grant):
+    background = [lease for lease in snapshot["leases"] if lease["pre"] is None]
+    grants = snapshot["post_grants"]
+    if len(background) == len(grants) == 1 and background[0]["populated"] is True and all(
+        grants[0].get(key) == value for key, value in expected_grant.items()
+    ):
+        return background[0], grants[0]
+    return None
+
+
+async def _assert_overlap_parked(factory, submission_id):
+    async with factory() as session:
+        dispatch = await session.get(SubmissionDispatch, submission_id)
+        event = await session.get(OutboxEvent, dispatch.evaluation_event_id)
+        run = await session.get(CheckerRun, dispatch.evaluation_attempt_id)
+        _require(event.delivery_state == "pending" and event.attempt_count == 0
+                 and run.status == "queued" and run.worker_lease_generation == 0,
+                 "parked POST escaped its dedicated consumer boundary")
+        return str(event.event_id)
+
+
+async def _run_admission_overlap(client, factory, env, root, observer, custody, hosts):
+    """Observe a selected POST, independently bounded selected PRE, and exact T5."""
+    from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+    from app.workers.outbox import scan_pending
+    from app.workers.outbox_topology import FINALIZATION_QUEUE, OUTBOX_QUEUE
+
+    guide, _, manager, token = await _public_project(
+        client, factory, env, human_review_required=True, manager_authored=True, hold_post=True,
+    )
+    project = str(guide.project_id)
+    tasks = [await _started_public_task(client, project_id=project, manager_token=manager,
+             contributor_token=token, source_ref=f"admission-overlap-{role}")
+             for role in ("post", "t5", "pre")]
+    post_task, t5_task, pre_task = tasks
+    archive = archive_with_modes("evidence/results", guide.project_id)
+    pre_archive = _with_fixture_file(archive, "admission-overlap-pre.txt")
+    _require(len({task_id for task_id, _ in tasks}) == 3, "overlap requires three distinct tasks")
+
+    async def accept(task, payload):
+        task_id, assignment_id = task
+        key = str(uuid4())
+        accepted = await _json(client, "POST", f"/api/v1/tasks/{task_id}/submissions", token, 202,
+                               headers=_source_headers(assignment_id, payload, key), content=payload)
+        _require(accepted["status"] == "accepted" and accepted["replayed"] is False
+                 and accepted["task_id"] == task_id and accepted["assignment_id"] == assignment_id
+                 and accepted["pre_submission_results"], "overlap received incorrect source acceptance")
+        return {"acceptance_receipt": accepted, "idempotency_key": key}
+
+    await _overlap_consumer(hosts["outbox"], OUTBOX_QUEUE, False)
+    post = await _submit(client, factory, task_id=post_task[0], assignment_id=post_task[1],
+                         contributor_token=token, archive=archive)
+    await _assert_overlap_parked(factory, post["submission_id"])
+    await _overlap_consumer(hosts["finalization"], FINALIZATION_QUEUE, False)
+    t5_context = await accept(t5_task, archive)
+    t5_operation_id = t5_context["acceptance_receipt"]["operation_id"]
+    async with factory() as session:
+        t5_operation = await session.get(SubmissionIntakeOperation, t5_operation_id)
+        t5_event = await session.get(OutboxEvent, UUID(t5_operation.finalization_event_id))
+        _require(t5_operation.state == "finalization_pending" and t5_operation.finalized_submission_id is None
+                 and t5_event.delivery_state == "pending" and t5_event.attempt_count == 0,
+                 "T5 completed before the overlap fixture released it")
+        t5_event_id = str(t5_event.event_id)
+
+    initial = await _overlap_snapshot(observer, custody)
+    _require(initial["leases"] == initial["post_grants"] == [], "overlap node did not start idle")
+    # Stage publication while both owners are parked so overlap timing does not
+    # depend on when the next Beat scan happens to run.
+    scan = await asyncio.to_thread(scan_pending.apply_async, ignore_result=False)
+    try:
+        scanned = await asyncio.to_thread(scan.get, timeout=30, propagate=True)
+        _require(scanned["published"] >= 2, "owned scanner did not publish both initial requests")
+    finally:
+        await asyncio.to_thread(scan.forget)
+    (root / "source.sha256").write_text(_fixture_hashes(pre_archive)["archive_sha256"] + "\n")
+    pre = asyncio.create_task(accept(pre_task, pre_archive))
+    try:
+        async with asyncio.timeout(30):
+            while not (root / "pre-dispatch.json").is_file():
+                _require(not pre.done(), "PRE exited before the native dispatch barrier")
+                await asyncio.sleep(0.05)
+        expected_pre = json.loads((root / "pre-dispatch.json").read_text())
+        _require(len({post["operation_id"], t5_operation_id, expected_pre["source_operation_id"]}) == 3,
+                 "overlap reused a source operation")
+        await _overlap_consumer(hosts["outbox"], OUTBOX_QUEUE, True)
+
+        expected_post = {"project_id": project, "task_id": post_task[0], "submission_id": post["submission_id"],
+                         "evaluation_request_id": post["evaluation_request_id"]}
+        async with asyncio.timeout(60):
+            while (held := _overlap_post(await _overlap_snapshot(observer, custody), expected_post)) is None:
+                _require(not pre.done(), "PRE exhausted its original lease before POST held capacity")
+                await asyncio.sleep(0.15)
+        post_lease, post_grant = held
+        async with factory() as session:
+            run = await session.get(CheckerRun, post_grant["attempt_id"])
+            _require(run is not None and run.status == "running" and run.worker_lease_id == post_grant["lease_id"]
+                     and run.worker_lease_generation == 1, "native POST is not the retained selected attempt")
+        await _overlap_consumer(hosts["outbox"], OUTBOX_QUEUE, False)
+        released = time.monotonic()
+        (root / "release-pre").touch(exist_ok=False)
+
+        async def require_held_post():
+            snapshot = await _overlap_snapshot(observer, custody)
+            _require(snapshot["checker_pid"] == initial["checker_pid"]
+                     and _overlap_post(snapshot, expected_post) == held,
+                     "selected POST released Background capacity before the overlap was proved")
+            return snapshot
+
+        async with asyncio.timeout(20):
+            while True:
+                overlap = await require_held_post()
+                admitted = [lease for lease in overlap["leases"] if lease["pre"] == expected_pre]
+                if admitted:
+                    break
+                await asyncio.sleep(0.15)
+            pre_lease, = admitted
+            _require(pre_lease["name"] != post_lease["name"] and pre_lease["epoch"] == post_lease["epoch"],
+                     "PRE did not reserve independently on the same admission epoch")
+            await _overlap_consumer(hosts["finalization"], FINALIZATION_QUEUE, True)
+            t5 = await _await_finalized_source(client, factory, *t5_task, token, t5_context, archive)
+            async with factory() as session:
+                t5_event = await session.get(OutboxEvent, UUID(t5_event_id))
+                _require(t5_event.delivery_state == "acknowledged" and t5_event.attempt_count == 1,
+                         "overlap T5 did not acknowledge the original delivery once")
+            proved = await require_held_post()
+            _require(any(lease["name"] == pre_lease["name"] and lease["pre"] == expected_pre
+                         and lease["epoch"] == pre_lease["epoch"]
+                         and lease["journal_sha256"] == pre_lease["journal_sha256"] for lease in proved["leases"]),
+                     "selected PRE released its reservation before T5 acknowledged")
+        t5_post_event = await _assert_overlap_parked(factory, t5["submission_id"])
+        pre_context = await pre
+        elapsed = time.monotonic() - released
+        pre_acceptance = pre_context["acceptance_receipt"]
+        _require(pre_acceptance["operation_id"] == expected_pre["source_operation_id"],
+                 "accepted PRE operation differs from the admitted native lease")
+        selected = await _await_finalized_source(client, factory, *pre_task, token, pre_context, pre_archive)
+        async with factory() as session:
+            pre_run = await session.get(SelectedPreSubmitRun, expected_pre["run_id"])
+            receipt = pre_run.terminal_json["invocation_receipt"]
+            _require(receipt["provider_invocation_id"] == pre_lease["name"]
+                     and receipt["cleanup"]["journal_sha256"] == pre_lease["journal_sha256"]
+                     and receipt["cleanup"]["disposition"] == "destroyed"
+                     and receipt["timings_ms"]["total"] <= 120_000,
+                     "completed PRE did not retain exact bounded native reservation evidence")
+        await _assert_overlap_parked(factory, selected["submission_id"])
+        await _assert_overlap_parked(factory, t5["submission_id"])
+        post_attempt, completion = await _complete_post(
+            factory, submission_id=post["submission_id"], project_id=guide.project_id,
+            recommendation="allow_review", deliver_completion=False,
+        )
+        _require(post_attempt == post_grant["attempt_id"], "completed POST differs from the held run")
+        return {"fixture_post_mode": "deadline", "post_lease": post_lease, "post_grant": post_grant,
+                "pre_lease": pre_lease, "pre_seconds_after_release": round(elapsed, 3),
+                "pre_runtime_ms": receipt["timings_ms"]["total"],
+                "pre": selected, "t5_operation_id": t5_operation_id, "t5_event_id": t5_event_id,
+                "t5": t5, "t5_post_parked_event_id": t5_post_event, "post_completion_event_id": str(completion),
+                "checker_pid": initial["checker_pid"]}
+    finally:
+        if not pre.done():
+            pre.cancel()
+        await asyncio.gather(pre, return_exceptions=True)
+
+
 def _read_runner_configuration(node_config: Path, root: Path, custody: dict, *, separate_runner: bool) -> dict:
     """Bind a copied baseline config or the exact locally supervised wrapper."""
     _require(custody['source_tree'] == subprocess.check_output(
@@ -1239,13 +1437,23 @@ def _require_runner_health(execution: ExternalCheckerServiceHealth, intake: Trus
 async def run(database_url: str, image_reference: str, node_config: Path,
               broker_url: str, root: Path, expected_custody: Path,
               clients: ContributorClients | None = None, *, separate_runner: bool = False,
-              policy_case: str = "both") -> dict:
+              policy_case: str = "both", overlap_observer: Path | None = None) -> dict:
     _require(policy_case in {"both", "human", "automatic"}, "unknown policy qualification case")
     _require(policy_case == "both" or separate_runner, "single policy case requires separate runner")
+    _require(overlap_observer is None or (separate_runner and policy_case == "both"),
+             "native admission overlap requires its own separate-runner proof")
+    if overlap_observer is not None:
+        overlap_observer = overlap_observer.resolve(strict=True)
+        _require(overlap_observer.is_file() and os.access(overlap_observer, os.X_OK),
+                 "native admission observer must be executable")
     root.mkdir(parents=True, mode=0o700, exist_ok=True)
     _require(not separate_runner or clients is not None, 'separate runner proof needs both clients')
     custody = json.loads(expected_custody.read_text())
     service_config = _read_runner_configuration(node_config, root, custody, separate_runner=separate_runner)
+    if overlap_observer is not None:
+        _require(service_config["smol"]["maximum_parallel"] == 2
+                 and service_config["pre"]["reserved_capacity"]["slots"] == 1,
+                 "native overlap requires exactly one PRE and one Background slot")
     _require((service_config["runtime"], service_config["isolation_mode"])
              == ("smolvm", "smol-microvm"), "public drill requires the provisioned Smol node")
     repository, digest = image_reference.rsplit("@", 1)
@@ -1370,6 +1578,7 @@ async def run(database_url: str, image_reference: str, node_config: Path,
     factory = async_sessionmaker(engine, expire_on_commit=False)
     api = worker = beat = mcp = None
     workers: list[subprocess.Popen] = []
+    worker_hosts = {}
     processes: list[subprocess.Popen] = []
     signals = ExitStack()
     worker_generation = 0
@@ -1401,7 +1610,9 @@ async def start_owned_worker() -> None:
         await provision_reconciler(factory)
         await _provision_runtime_services(factory)
         for phase in ("pre_submit", "post_submit"):
-            await _register_external_checker_fixture(factory, _locked_spec(phase, image))
+            await _register_external_checker_fixture(factory, _locked_spec(
+                phase, image, hold_post=overlap_observer is not None,
+            ))
         operator, _ = await seed_review_actor(factory, None, role="operator", scope="system", issuer=seeded_issuer(env))
         from tests.reviews.lifecycle.transition_support import command_for, transition
         await transition(await command_for(operator.actor_profile_id, "shadow"))
@@ -1413,27 +1624,38 @@ async def start_owned_worker() -> None:
         _require_runner_health(execution_health, intake_health, len(service_config["cache"]))
         port = find_free_port()
         origin = f"http://127.0.0.1:{port}"
+        api_module, api_env = "app.main:app", env
+        if overlap_observer is not None:
+            overlap_root = root / "admission-overlap"
+            overlap_root.mkdir(mode=0o700)
+            api_module = "experiments.pilot04_external_checker_runtime.public_intake_observer:app"
+            api_env = env | {"WORKSTREAM_PROBE_INTAKE_TRACE": str(overlap_root / "adapter.jsonl"),
+                             "WORKSTREAM_PROBE_PRE_BARRIER": str(overlap_root)}
         api = launch([
             sys.executable, "-m", "uvicorn",
-            "app.main:app",
+            api_module,
             "--host", "127.0.0.1", "--port", str(port),
             "--log-level", "error", "--no-access-log",
-        ], env=env, log=root / "api.log")
+        ], env=api_env, log=root / "api.log")
         await _wait_api(origin, api)
         if clients is not None:
             clients.configure_processes(origin, find_free_port())
             mcp = launch([str(clients.mcp_executable)], env=clients.mcp_env, log=root / "mcp.log")
             await clients.wait_ready(mcp)
+        starting_workers = []
         for role, queue in WORKER_ROLES:
             process, hostname = _start_worker(
                 cleanup_env if role == "source-cleanup" else env, root, role, queue, launch=launch,
                 recorded_assistance=recorded_assistance,
             )
             workers.append(process)
-            await _wait_worker(process, hostname)
+            starting_workers.append((process, hostname))
+            worker_hosts[role] = hostname
             if role == "outbox":
                 worker = process
                 worker_generation = 1
+        for process, hostname in starting_workers:
+            await _wait_worker(process, hostname)
         scans_before_beat = await _scan_audit_count(factory)
         beat = launch([
             sys.executable, "-m", "celery", "-A", "app.workers.celery_app",
@@ -1453,15 +1675,19 @@ async def start_owned_worker() -> None:
                 _require((fault_root / "supervisor-ready").exists(), "owned node supervisor is absent")
                 runtime_trials = await public_runtime_trials(client, factory, env, fault_root,
                     stop_worker=stop_owned_worker, start_worker=start_owned_worker, operator_token=_token(env, operator))
-            true = false = None
-            if policy_case in {"both", "human"}:
+            true = false = admission_overlap = None
+            if overlap_observer is not None:
+                admission_overlap = await _run_admission_overlap(
+                    client, factory, env, overlap_root, overlap_observer, custody, worker_hosts,
+                )
+            if overlap_observer is None and policy_case in {"both", "human"}:
                 true = await _one_mode(client, factory, env,
                                    human_review_required=True,
                                    operator_id=operator.actor_profile_id, clients=clients,
                                    exercise_faults=not separate_runner, manager_authored=separate_runner)
                 if separate_runner:
                     _write_policy_receipt(root, "human", true, custody, bucket=bucket, prefix=prefix)
-            if policy_case in {"both", "automatic"}:
+            if overlap_observer is None and policy_case in {"both", "automatic"}:
                 false = await _one_mode(client, factory, env,
                                     human_review_required=False,
                                     operator_id=operator.actor_profile_id,
@@ -1489,12 +1715,15 @@ async def start_owned_worker() -> None:
                                            if outcome is not None],
                 "scheduled_artifact_scans": True,
                 "public_original_guide_setup": True,
-                "connected_submitter_clients": ["cli", "mcp"] if clients is not None else [],
+                "connected_submitter_clients": ["cli", "mcp"] if clients is not None and overlap_observer is None else [],
                 "recorded_inference": recorded_assistance,
                 "custody": {key: custody[key] for key in (
                     'source_tree', 'config_sha256', 'service_sha256', 'smol_sha256', 'guest_sha256',
                 ) + (() if separate_runner else ('wrapper_sha256',))},
-                "runtime_trials": runtime_trials, "intake_trials": intake_trials, "human": true, "automatic": false}
+                "runtime_trials": runtime_trials, "intake_trials": intake_trials,
+                "human": true, "automatic": false} | (
+                    {"admission_overlap": admission_overlap} if overlap_observer is not None else {}
+                )
     finally:
         try:
             _stop_owned_processes(tuple(reversed(processes)))
@@ -1540,6 +1769,8 @@ def main() -> int:
                         help="Use baseline remote runner custody without local host fault controls")
     parser.add_argument("--policy-case", choices=("both", "human", "automatic"), default="both",
                         help="Qualify one independent policy case on the separate runner, or both")
+    parser.add_argument("--admission-overlap-observer", type=Path,
+                        help="Run only the separate-runner overlap proof with this read-only native observer")
     parser.add_argument('--hosted-attachment', type=Path,
                         help='Private attachment manifest for an existing hosted API/worker/Beat')
     parser.add_argument('--hosted-model-post', type=Path,
@@ -1555,6 +1786,8 @@ def main() -> int:
         parser.error("the separate runner proof requires both client executables")
     if args.policy_case != "both" and not args.separate_runner:
         parser.error("a single policy case requires --separate-runner")
+    if args.admission_overlap_observer and (not args.separate_runner or args.policy_case != "both"):
+        parser.error("admission overlap requires --separate-runner and chooses its own proof")
     if args.hosted_attachment:
         if (not args.broker_url or args.image_reference or args.node_config
                 or args.work_dir or args.expected_custody or args.cli_executable or args.mcp_executable
@@ -1578,7 +1811,7 @@ def main() -> int:
         value = asyncio.run(run(
             args.database_url, args.image_reference, args.node_config,
             args.broker_url, Path(directory), args.expected_custody, clients, separate_runner=args.separate_runner,
-            policy_case=args.policy_case,
+            policy_case=args.policy_case, overlap_observer=args.admission_overlap_observer,
         ))
     print(json.dumps(value, sort_keys=True, separators=(",", ":")))
     return 0
diff --git a/scripts/test_public_hosted_attachment.py b/scripts/test_public_hosted_attachment.py
index 29857bf36..ea1e63d2c 100644
--- a/scripts/test_public_hosted_attachment.py
+++ b/scripts/test_public_hosted_attachment.py
@@ -29,6 +29,70 @@
 
 
 class PublicJourneyWorkerCustody(unittest.TestCase):
+    def test_overlap_holds_only_the_bound_live_post_attempt(self):
+        from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe
+
+        post = {"name": "post", "epoch": "one", "populated": True, "pre": None}
+        pre = {"name": "pre", "epoch": "one", "populated": False, "pre": {"run_id": "pre-run"}}
+        grant = {"evaluation_request_id": "evaluation", "attempt_id": "attempt", "task_id": "task"}
+        snapshot = {"leases": [post, pre], "post_grants": [grant]}
+        expected = {"evaluation_request_id": "evaluation", "task_id": "task"}
+        self.assertEqual(probe._overlap_post(snapshot, expected), (post, grant))
+        self.assertIsNone(probe._overlap_post(snapshot, expected | {"task_id": "foreign"}))
+        self.assertIsNone(probe._overlap_post(snapshot | {"leases": [post | {"populated": False}, pre]}, expected))
+        self.assertIsNone(probe._overlap_post(snapshot | {"leases": [post, post, pre]}, expected))
+
+    def test_overlap_fixture_hold_keeps_pinned_checker_resource_limits(self):
+        from app.modules.checkers.api.external import ExternalCheckerContractError
+        from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe
+
+        image = {"platform_manifest_digest": "sha256:" + "e" * 64}
+        normal = probe._locked_spec("post_submit", image)
+        held = probe._locked_spec("post_submit", image, hold_post=True)
+        self.assertEqual((held.resources, held.image_digest), (normal.resources, normal.image_digest))
+        held.configuration_schema.validate_instance({"mode": "deadline"})
+        with self.assertRaises(ExternalCheckerContractError):
+            normal.configuration_schema.validate_instance({"mode": "deadline"})
+        self.assertEqual(probe._locked_spec("pre_submit", image, hold_post=True),
+                         probe._locked_spec("pre_submit", image))
+
+    def test_overlap_native_observer_pins_the_journal_and_post_grant(self):
+        from experiments.pilot04_external_checker_runtime import read_native_admission as native
+
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            leases = root / "smol-leases"
+            leases.mkdir()
+            (root / ".workstream-checker-owner").write_text("fixture-owner\n")
+            vm = "ws-" + "c" * 32
+            group = root / "groups" / vm
+            group.mkdir(parents=True)
+            (group / "cgroup.events").write_text("populated 1\nfrozen 0\n")
+            journal = json.dumps({"name": vm, "owner": "fixture-owner", "epoch": "epoch", "pre": None}).encode()
+            (leases / f"{vm}.json").write_bytes(journal)
+            grant = "extract_" + "d" * 32
+            workspace = root / "workspaces" / grant
+            workspace.mkdir(parents=True)
+            manifest = {"protocol_version": "workstream.external_checker_material_grant.v2",
+                        "grant_id": grant, "request_digest": "request", "phase": "post_submit",
+                        "identity": {key: key for key in native._POST_FIELDS} | {"phase": "post_submit"}}
+            binding = native._sha(json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode())
+            grant_path = workspace / ".external-checker-grant.json"
+            grant_path.write_text(json.dumps(manifest | {"binding_digest": binding}))
+            config_path = root / "config.json"
+            raw = json.dumps({"socket_path": str(root / "checker.sock"), "material_root": str(root),
+                              "smol": {"cgroup_root": str(root / "groups")}}).encode()
+            config_path.write_bytes(raw)
+            executable_sha = native._sha(Path("/proc/self/exe").read_bytes())
+            with patch.object(native, "_controller_pid", return_value=os.getpid()):
+                sample = native.observe(config_path, native._sha(raw), executable_sha)
+                self.assertEqual(sample["leases"], [{"name": vm, "epoch": "epoch", "pre": None,
+                    "populated": True, "journal_sha256": native._sha(journal)}])
+                self.assertEqual(sample["post_grants"][0]["evaluation_request_id"], "evaluation_request_id")
+                grant_path.write_text(json.dumps(manifest | {"binding_digest": "substituted"}))
+                with self.assertRaisesRegex(ValueError, "native POST grant identity differs"):
+                    native.observe(config_path, native._sha(raw), executable_sha)
+
     def test_completed_policy_receipt_cannot_overwrite_or_claim_both_cases(self):
         from experiments.pilot04_external_checker_runtime import run_public_journey_probe as probe
 

From 0fdbf860360fa56560052323268c86843962b8f2 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:24:17 +0100
Subject: [PATCH 429/513] test(submissions): allow prior overlap queue
 publication

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md        | 6 ++++++
 .../run_public_journey_probe.py                          | 9 ++++++---
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 2a9bc60e0..18e825075 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12279,3 +12279,9 @@ the held fixture's unchanged resource limits, the native POST grant and journal
 reader, and refusal of unpopulated or mismatched background state. Compilation,
 focused Ruff and diff checks passed. Native overlap remains for the exclusive
 runner qualification; no service, broker or PostgreSQL was used for these checks.
+
+The overlap probe validates the dedicated scanner's bounded terminal report
+and permits zero new publications in that particular pass. Its positive
+evidence comes from the exact live POST request and the original T5
+acknowledgement, whether the scheduled scanner or the explicit pass
+published either parked event.
diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
index 46f78bc90..38b6ae6c7 100644
--- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
+++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
@@ -1295,12 +1295,15 @@ async def accept(task, payload):
 
     initial = await _overlap_snapshot(observer, custody)
     _require(initial["leases"] == initial["post_grants"] == [], "overlap node did not start idle")
-    # Stage publication while both owners are parked so overlap timing does not
-    # depend on when the next Beat scan happens to run.
+    # Let the dedicated scanner stage any remaining publications while both owners
+    # are parked. A prior Beat scan may already have staged either exact event.
     scan = await asyncio.to_thread(scan_pending.apply_async, ignore_result=False)
     try:
         scanned = await asyncio.to_thread(scan.get, timeout=30, propagate=True)
-        _require(scanned["published"] >= 2, "owned scanner did not publish both initial requests")
+        _require(type(scanned) is dict and set(scanned) == {"selected", "published"}
+                 and type(scanned["selected"]) is int and type(scanned["published"]) is int
+                 and 0 <= scanned["published"] <= scanned["selected"],
+                 "owned scanner did not return a valid terminal result")
     finally:
         await asyncio.to_thread(scan.forget)
     (root / "source.sha256").write_text(_fixture_hashes(pre_archive)["archive_sha256"] + "\n")

From bc3aceb544b8373591ce6ab647e9f5a006c1f615 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:39:34 +0100
Subject: [PATCH 430/513] test(submissions): retain safe diagnostics for
 unexpected PRE failures

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md    | 12 ++++++++++++
 .../run_public_journey_probe.py                      |  8 +++++++-
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 18e825075..4a2e8a2b9 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12285,3 +12285,15 @@ and permits zero new publications in that particular pass. Its positive
 evidence comes from the exact live POST request and the original T5
 acknowledgement, whether the scheduled scanner or the explicit pass
 published either parked event.
+
+### Automatic native probe failure diagnostics
+
+The frozen d4213eebd automatic-case run stopped at the MCP project-PRE negative
+case after the initial default-PRE rejection. Its response did not contain the
+expected feedback details, and the probe obscured that distinction with a
+KeyError. Database and bucket cleanup passed at schema 0093 in
+`/tmp/workstream-paired-native-mwdtw6b5/cleanup.json`. Preserve the original
+feedback assertion, but validate its envelope first and report only the safe
+error/code/status/correlation fields on mismatch. The original response was
+not retained; no specific provider or MCP failure cause is claimed from this
+run. This changes only diagnostic evidence, not accepted outcomes or deadlines.
diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
index 38b6ae6c7..00e1b05d0 100644
--- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
+++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
@@ -968,7 +968,13 @@ async def submit_zip(archive, key, *, using, failed=False):
     )
     external_bad = await submit_zip(_with_fixture_file(archive, "project-rejected.txt"), str(uuid4()),
                                     using="mcp", failed=True)
-    results = external_bad["error"]["details"]["results"]
+    failure = external_bad["error"]
+    diagnostic = {key: failure.get(key) for key in ("error", "code", "status", "correlation_id")}
+    _require(failure.get("code") == "pre_submission_checker_failed"
+             and (clients is None or failure.get("status") == 422)
+             and isinstance(failure.get("details"), dict),
+             "public external PRE returned a different failure: " + json.dumps(diagnostic, sort_keys=True))
+    results = failure["details"]["results"]
     external = [item for item in results
                 if item["source"] == "project_external_checker"]
     _require(external_bad["error"]["code"] == "pre_submission_checker_failed"

From a26bc62ea4c1cb6b0688598a8da9ab0f4b0bd41f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:49:29 +0100
Subject: [PATCH 431/513] fix(mcp): preserve safe submission recovery guidance
 on uncertain responses

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 26 ++++++++
 mcp_server/tests/test_task_execution.py       | 65 +++++++++++++++++++
 mcp_server/workstream_mcp/http_gateway.py     | 25 +++++--
 3 files changed, 112 insertions(+), 4 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 4a2e8a2b9..b8b1a22a3 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12297,3 +12297,29 @@ feedback assertion, but validate its envelope first and report only the safe
 error/code/status/correlation fields on mismatch. The original response was
 not retained; no specific provider or MCP failure cause is claimed from this
 run. This changes only diagnostic evidence, not accepted outcomes or deadlines.
+
+### Preserve safe MCP source recovery guidance
+
+Inspection of the unexpected MCP failure exposed a separate reproducible gap:
+raw-ZIP HTTP 503 responses lost the API's outcome-unknown code and bounded
+recovery message. Two focused caller tests reproduce missing recovery guidance.
+This is not claimed as the cause of the prior native failure. Scope is the
+existing MCP gateway and task-execution tests. Preserve the existing
+`workstream_execution_uncertain` classification and false automatic-retry hint,
+while retaining only the two current submission infrastructure/outcome-unknown
+codes and bounded printable messages on 503. Provider details remain omitted;
+other server/proxy errors and unexpected successes remain uncertain. Existing
+4xx PRE quality-feedback validation stays intact. No retries or aliases added.
+
+Independent review rejected reflecting arbitrary upstream 503 message text even
+with an allowed code. The revised branch uses fixed canonical recovery text
+for those two codes; counterexamples supply a printable private URL/token and
+assert neither it nor provider details reaches the caller. Unrelated formatting
+changes were removed. The earlier four-case run passed before this stricter
+review repair; the final six-case result is recorded separately.
+
+The final reviewed 503 mapping precedes the unchanged 4xx code allowlist; the
+new recovery codes do not widen accepted 4xx messages. Six focused cases passed
+(including private-text counterexamples and existing quality/uncertainty
+controls), with Ruff and whitespace checks passing. A final frozen-source
+rerun follows integration; the previous native cause remains unproven.
diff --git a/mcp_server/tests/test_task_execution.py b/mcp_server/tests/test_task_execution.py
index 98fe97161..a431b0ccc 100644
--- a/mcp_server/tests/test_task_execution.py
+++ b/mcp_server/tests/test_task_execution.py
@@ -621,3 +621,68 @@ def test_operation_progress_rejects_unbound_or_noncontract_response(
             "arguments": {"task_id": TASK_ID, "operation_id": OPERATION_ID}}})
     assert response.json()["result"]["isError"] is True
     assert len(received) == 1
+
+
+@pytest.mark.parametrize("private_message", [False, True])
+@pytest.mark.parametrize(
+    ("code", "message"),
+    [
+        (
+            "submission_outcome_unknown",
+            "Check the original submission operation or retry with the same idempotency key",
+        ),
+        (
+            "submission_infrastructure_unavailable",
+            "Submission processing is temporarily unavailable",
+        ),
+    ],
+)
+def test_submission_transport_failure_preserves_safe_recovery_guidance(
+    adapter: Adapter,
+    code: str,
+    message: str,
+    private_message: bool,
+) -> None:
+    client, received, upstream = adapter
+    upstream["status"] = 503
+    supplied_message = (
+        "https://private-provider.invalid?token=private-token" if private_message else message
+    )
+    upstream["json"] = {
+        "error": {
+            "code": code,
+            "message": supplied_message,
+            "details": {"private_provider_diagnostic": "must not escape"},
+        }
+    }
+    response = client.post(
+        "/mcp",
+        headers={
+            "authorization": "Bearer fixture-token",
+            "accept": "application/json, text/event-stream",
+        },
+        json={
+            "jsonrpc": "2.0",
+            "id": 1,
+            "method": "tools/call",
+            "params": {
+                "name": "workstream_submission_create",
+                "arguments": _arguments("submission_create"),
+            },
+        },
+    )
+    result = response.json()["result"]
+    assert result["isError"] is True
+    error = result["structuredContent"]
+    assert (error["status"], error.get("code"), error.get("message"), error["retryable"]) == (
+        503,
+        code,
+        message,
+        False,
+    )
+    assert error["error"] == "workstream_execution_uncertain"
+    assert "details" not in error
+    assert "must not escape" not in response.text
+    assert "private-provider" not in response.text
+    assert "private-token" not in response.text
+    assert len(received) == 1
diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py
index 0d66f3979..70406fa87 100644
--- a/mcp_server/workstream_mcp/http_gateway.py
+++ b/mcp_server/workstream_mcp/http_gateway.py
@@ -2234,8 +2234,6 @@ async def _request(
                         correlation_id = self._correlation_id(response, request_id)
                         if response.status_code != expected_status:
                             failure = self._api_failure(response.status_code, body, correlation_id)
-                            if submission_upload and 400 <= response.status_code < 500:
-                                failure = self._submission_failure(failure, body, output_validator)
                             # Proxy errors and unexpected successes cannot prove rollback.
                             if mutation and (
                                 response.status_code < 400 or response.status_code >= 500
@@ -2246,6 +2244,10 @@ async def _request(
                                     code=failure.code,
                                     correlation_id=correlation_id,
                                 )
+                            if submission_upload and (
+                                400 <= response.status_code < 500 or response.status_code == 503
+                            ):
+                                failure = self._submission_failure(failure, body, output_validator)
                             return GatewayResult(failure=failure)
                         media_type = (
                             response.headers.get("content-type", "")
@@ -2405,9 +2407,24 @@ def _submission_failure(
         try:
             decoded = json.loads(body)
             error = decoded["error"]
-            if not isinstance(error, dict) or error.get("code") not in _SUBMISSION_ERROR_CODES:
+            if not isinstance(error, dict):
+                return failure
+            code = error.get("code")
+            if failure.status == 503:
+                # Proxy errors cannot authorize reflection of upstream diagnostic text.
+                recovery = {
+                    "submission_infrastructure_unavailable": (
+                        "Submission processing is temporarily unavailable"
+                    ),
+                    "submission_outcome_unknown": (
+                        "Check the original submission operation or retry "
+                        "with the same idempotency key"
+                    ),
+                }.get(code)
+                return replace(failure, code=code, message=recovery) if recovery else failure
+            if code not in _SUBMISSION_ERROR_CODES:
                 return failure
-            code, details = error["code"], error.get("details")
+            details = error.get("details")
             message = error.get("message")
             if not isinstance(message, str) or len(message) > 512 or not message.isprintable():
                 message = None

From e5345a0cee76614a16ef505b09c44ce80b503447 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:10:36 +0100
Subject: [PATCH 432/513] Define qualified mTLS runner placement contract

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  36 ++++
 backend/app/adapters/runner.py                | 154 ++++++++++++++++++
 backend/app/core/runner_endpoints.py          |  36 ++++
 .../checkers/external/test_remote_node.py     | 121 ++++++++++++++
 4 files changed, 347 insertions(+)
 create mode 100644 backend/app/adapters/runner.py
 create mode 100644 backend/app/core/runner_endpoints.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index b8b1a22a3..00d90d7c5 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12323,3 +12323,39 @@ new recovery codes do not widen accepted 4xx messages. Six focused cases passed
 (including private-text counterexamples and existing quality/uncertainty
 controls), with Ruff and whitespace checks passing. A final frozen-source
 rerun follows integration; the previous native cause remains unproven.
+
+### A28 qualify one runner endpoint per execution claim
+
+Intent. Select a currently qualified self-hosted runner without changing the
+CHECKERS, ART, TASK or OUTBOX ownership of the request. The same configuration
+supports one inexpensive node and a bounded set of nodes.
+
+Allowed scope. The first reviewed slice owns the strict endpoint and readiness
+contracts in `backend/app/core/runner_endpoints.py` and the shared mTLS runner
+adapter helper in `backend/app/adapters/runner.py`, plus focused checks in the
+existing remote-node test owner and this record. Activate those contracts with
+the existing CHECKERS and ART adapter factories and typed Settings only when
+the native gateway and admission path also enforce them. Then replace the
+existing hosted release/preflight, public proof and CLI configuration where
+they supply a singleton endpoint. Native work stays in the existing service,
+Smol admission and the mTLS gateway. The existing directly owned Unix tests
+exercise their private inner protocol unchanged. No migration, operator
+workflow or additional scheduler.
+
+Acceptance. Strict bounded settings reject duplicate endpoints and require an
+authenticated exact certificate name and loaded node config digest. Probes
+run within the existing request deadline and carry no source, material grant,
+or mutation. Readiness reports exact capability, profile and boot epoch.
+Select only one qualified endpoint. A POST claim pins the same node for its
+locator and final result. The runtime validates the selected boot epoch and
+checks authoritative drain and capacity before admitting new work. Existing
+holders can complete and retain exact lease/cleanup custody. Ambiguous
+invocation must never move elsewhere or create a terminal retry source.
+Source tests do not qualify two replicas, two real nodes, live drain or restart.
+
+The first contract passed seven focused cases. The loopback mTLS fixture
+verifies the exact certificate and the observed loaded configuration claim,
+and rejects invalid epoch, extra data, and a changed configuration digest.
+The selector test checks drain and capability exclusion, and stable selection
+after reordering the same configured endpoints. The change is staged without
+activating a new runtime path until the native authority can enforce it.
diff --git a/backend/app/adapters/runner.py b/backend/app/adapters/runner.py
new file mode 100644
index 000000000..c2a00fb61
--- /dev/null
+++ b/backend/app/adapters/runner.py
@@ -0,0 +1,154 @@
+"""Authenticated read-only placement for the existing remote runner transports."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Callable
+from dataclasses import dataclass
+import hashlib
+from pathlib import Path
+import ssl
+import struct
+from typing import Annotated, Literal, Self
+
+from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator
+
+from app.core.cancellation import await_cancellation_resistant
+from app.core.runner_endpoints import ExternalRunnerEndpoint, ExternalRunnerEndpoints, RunnerDigest
+from app.interfaces.external_checker_execution import ExternalCheckerServiceHealth
+from app.interfaces.trusted_submission_intake import TrustedIntakeIdentity
+
+
+_PROBE = b'{"protocol_version":"workstream.remote_runner.v1","operation":"placement"}'
+_PROBE_SECONDS = 2.0
+_MAXIMUM_PLACEMENT_BYTES = 32_768
+
+
+class RunnerImage(BaseModel):
+    """One exact image cached by the native service."""
+
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+    platform_manifest_digest: RunnerDigest
+    config_image_id: RunnerDigest
+
+
+class RunnerPreProfile(BaseModel):
+    """The source-bound PRE profile enforced by the native service."""
+
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+    profile_sha256: RunnerDigest
+    root_sha256: RunnerDigest
+
+
+class RunnerReadiness(BaseModel):
+    """Closed native placement facts, observed over the authenticated runner connection."""
+
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+    protocol_version: Literal["external_checker_service.v1"]
+    operation: Literal["placement"]
+    config_sha256: RunnerDigest
+    epoch: Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")]
+    health: ExternalCheckerServiceHealth
+    draining: bool
+    pre_available: bool
+    background_available: bool
+    images: tuple[RunnerImage, ...] = Field(min_length=1, max_length=64)
+    pre: RunnerPreProfile | None
+    intake: TrustedIntakeIdentity | None
+    model_callbacks: bool
+    trial_authority_manifest_sha256: RunnerDigest | None
+
+    @model_validator(mode="after")
+    def exact_readiness(self) -> Self:
+        if (
+            (self.health.runtime, self.health.isolation_mode) != ("smolvm", "smol-microvm")
+            or self.health.cached_platform_manifests != len(self.images)
+            or len({image.platform_manifest_digest for image in self.images}) != len(self.images)
+            or self.pre_available and self.pre is None
+            or self.draining and (self.pre_available or self.background_available)
+            or self.trial_authority_manifest_sha256 is not None and not self.model_callbacks
+        ):
+            raise ValueError("external runner readiness disagrees with its capabilities")
+        return self
+
+
+@dataclass(frozen=True, slots=True)
+class RunnerPlacement:
+    """An authenticated endpoint and its observed native boot epoch."""
+
+    endpoint: ExternalRunnerEndpoint
+    readiness: RunnerReadiness
+
+
+@dataclass(frozen=True, slots=True)
+class RunnerTransport:
+    """Share exact mTLS and a bounded read-only selection across CHECKERS and ART."""
+
+    endpoints: ExternalRunnerEndpoints
+    ca_path: Path
+    certificate_path: Path
+    private_key_path: Path
+
+    def tls_context(self) -> ssl.SSLContext:
+        context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=str(self.ca_path))
+        context.minimum_version = ssl.TLSVersion.TLSv1_3
+        context.check_hostname = True
+        context.load_cert_chain(certfile=str(self.certificate_path), keyfile=str(self.private_key_path))
+        return context
+
+    @staticmethod
+    def require_peer(transport: ssl.SSLObject | ssl.SSLSocket, endpoint: ExternalRunnerEndpoint) -> None:
+        """Require the exact DNS SAN independently of TLS wildcard matching."""
+        certificate = transport.getpeercert()
+        if not certificate or ("DNS", endpoint.server_name) not in certificate.get("subjectAltName", ()):
+            raise ssl.SSLError("external runner certificate identity differs")
+
+    async def open(self, endpoint: ExternalRunnerEndpoint) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
+        reader, writer = await asyncio.open_connection(
+            endpoint.host, endpoint.port, ssl=self.tls_context(), server_hostname=endpoint.server_name,
+        )
+        try:
+            self.require_peer(writer.get_extra_info("ssl_object"), endpoint)
+        except BaseException:
+            writer.close()
+            await await_cancellation_resistant(writer.wait_closed())
+            raise
+        return reader, writer
+
+    async def probe(self, endpoint: ExternalRunnerEndpoint) -> RunnerPlacement | None:
+        """Observe authenticated readiness without sending an execution or a grant."""
+        try:
+            async with asyncio.timeout(_PROBE_SECONDS):
+                reader, writer = await self.open(endpoint)
+                try:
+                    writer.write(struct.pack(">I", len(_PROBE)) + _PROBE)
+                    await writer.drain()
+                    size = struct.unpack(">I", await reader.readexactly(4))[0]
+                    if not 0 < size <= _MAXIMUM_PLACEMENT_BYTES:
+                        return None
+                    readiness = RunnerReadiness.model_validate_json(await reader.readexactly(size))
+                    if await reader.read(1) or readiness.config_sha256 != endpoint.config_sha256:
+                        return None
+                finally:
+                    writer.close()
+                    await writer.wait_closed()
+        except (OSError, TimeoutError, asyncio.IncompleteReadError, ValueError):
+            return None
+        return RunnerPlacement(endpoint, readiness)
+
+    async def select(
+        self, claim_key: str, *, qualifies: Callable[[RunnerReadiness], bool],
+    ) -> RunnerPlacement | None:
+        """Pick one qualified node deterministically, independent of probe arrival order."""
+        observed = await asyncio.gather(*(self.probe(endpoint) for endpoint in self.endpoints.root))
+        return min(
+            (placement for placement in observed if placement is not None
+             and not placement.readiness.draining and qualifies(placement.readiness)),
+            key=lambda placement: hashlib.sha256(
+                f"{claim_key}\0{placement.endpoint.server_name}".encode()
+            ).digest(),
+            default=None,
+        )
diff --git a/backend/app/core/runner_endpoints.py b/backend/app/core/runner_endpoints.py
new file mode 100644
index 000000000..f1770e524
--- /dev/null
+++ b/backend/app/core/runner_endpoints.py
@@ -0,0 +1,36 @@
+"""Strict operator configuration for the authenticated external runner endpoints."""
+
+from typing import Annotated, Self
+
+from pydantic import BaseModel, ConfigDict, Field, RootModel, StringConstraints, model_validator
+
+
+_DNS_NAME = r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$"
+RunnerName = Annotated[str, StringConstraints(min_length=1, max_length=253, pattern=_DNS_NAME)]
+RunnerDigest = Annotated[str, StringConstraints(pattern=r"^sha256:[0-9a-f]{64}$")]
+
+
+class ExternalRunnerEndpoint(BaseModel):
+    """An address, exact certificate DNS identity and independently reviewed config."""
+
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+    host: RunnerName
+    port: int = Field(ge=1, le=65_535)
+    server_name: RunnerName
+    config_sha256: RunnerDigest
+
+
+class ExternalRunnerEndpoints(RootModel[Annotated[tuple[ExternalRunnerEndpoint, ...], Field(min_length=1, max_length=8)]]):
+    """One bounded endpoint set, with no repeated route or TLS identity."""
+
+    model_config = ConfigDict(frozen=True)
+
+    @model_validator(mode="after")
+    def distinct_endpoints(self) -> Self:
+        if (
+            len({(endpoint.host, endpoint.port) for endpoint in self.root}) != len(self.root)
+            or len({endpoint.server_name for endpoint in self.root}) != len(self.root)
+        ):
+            raise ValueError("external runner endpoints must have distinct addresses and certificate names")
+        return self
diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py
index c2384a2a0..77ed543ab 100644
--- a/backend/tests/checkers/external/test_remote_node.py
+++ b/backend/tests/checkers/external/test_remote_node.py
@@ -96,6 +96,127 @@ def _frame(value: bytes) -> bytes:
     return struct.pack(">I", len(value)) + value
 
 
+def _placement_body():
+    return {
+        "protocol_version": "external_checker_service.v1", "operation": "placement",
+        "config_sha256": "sha256:" + "a" * 64, "epoch": "e" * 64,
+        "health": {"operating_system": "linux", "architecture": "amd64", "runtime": "smolvm",
+                   "isolation_mode": "smol-microvm", "cached_platform_manifests": 1,
+                   "sandbox_uid": 10001, "sandbox_gid": 10001},
+        "draining": False, "pre_available": True, "background_available": True,
+        "images": [{"platform_manifest_digest": "sha256:" + "b" * 64,
+                    "config_image_id": "sha256:" + "c" * 64}],
+        "pre": {"profile_sha256": "sha256:" + "d" * 64, "root_sha256": "sha256:" + "f" * 64},
+        "intake": None, "model_callbacks": False, "trial_authority_manifest_sha256": None,
+    }
+
+
+def test_external_runner_endpoint_set_is_closed_and_unique():
+    from pydantic import ValidationError
+
+    from app.core.runner_endpoints import ExternalRunnerEndpoints
+
+    endpoint = {"host": "127.0.0.1", "port": 9443, "server_name": "runner.test",
+                "config_sha256": "sha256:" + "a" * 64}
+    assert ExternalRunnerEndpoints.model_validate_json(json.dumps([endpoint])).root[0].port == 9443
+    for invalid in ([], [endpoint] * 9, [endpoint | {"port": "9443"}],
+                    [endpoint | {"host": "127.0.0.1 "}], [endpoint | {"server_name": "*.test"}],
+                    [endpoint | {"config_sha256": "stale"}], [endpoint | {"legacy_name": "x"}],
+                    [endpoint, endpoint | {"server_name": "others.test"}],
+                    [endpoint, endpoint | {"port": 9444}]):
+        with pytest.raises(ValidationError):
+            ExternalRunnerEndpoints.model_validate_json(json.dumps(invalid))
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("changed", [None, "config", "epoch", "extra", "trailing"])
+async def test_runner_placement_probe_authenticates_loaded_identity(tmp_path, changed):
+    from app.adapters.runner import RunnerTransport
+    from app.core.runner_endpoints import ExternalRunnerEndpoints
+
+    certificates = _certificate_files(tmp_path)
+    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+    context.minimum_version = ssl.TLSVersion.TLSv1_3
+    context.verify_mode = ssl.CERT_REQUIRED
+    context.load_cert_chain(certificates["server_certificate"], certificates["server_key"])
+    context.load_verify_locations(certificates["ca"])
+    body = _placement_body()
+    expected_config = body["config_sha256"]
+    if changed == "config":
+        body["config_sha256"] = "sha256:" + "0" * 64
+    if changed == "epoch":
+        body["epoch"] = "unbound"
+    if changed == "extra":
+        body["unexpected"] = "value"
+    requests = []
+
+    async def observe(reader, writer):
+        try:
+            requests.append(json.loads(await _read_frame(reader)))
+            writer.write(_frame(json.dumps(body).encode()) + (b"x" if changed == "trailing" else b""))
+            await writer.drain()
+        finally:
+            writer.close()
+            await writer.wait_closed()
+
+    server = await asyncio.start_server(observe, "127.0.0.1", 0, ssl=context)
+    async with server:
+        endpoints = ExternalRunnerEndpoints.model_validate([{
+            "host": "127.0.0.1", "port": server.sockets[0].getsockname()[1], "server_name": "runner.test",
+            "config_sha256": expected_config,
+        }])
+        transport = RunnerTransport(endpoints, certificates["ca"], certificates["client_certificate"],
+                                    certificates["client_key"])
+        matched = await transport.select("attempt-1", qualifies=lambda readiness: readiness.pre_available)
+        if changed is None:
+            assert matched is not None and matched.readiness.epoch == body["epoch"]
+            assert matched.readiness.images[0].config_image_id == body["images"][0]["config_image_id"]
+        else:
+            assert matched is None
+    assert requests == [{"protocol_version": "workstream.remote_runner.v1", "operation": "placement"}]
+
+
+@pytest.mark.asyncio
+async def test_runner_selection_uses_only_qualified_ready_targets(tmp_path, monkeypatch):
+    from types import SimpleNamespace
+
+    from app.adapters.runner import RunnerPlacement, RunnerReadiness, RunnerTransport
+    from app.core.runner_endpoints import ExternalRunnerEndpoints
+
+    endpoints = ExternalRunnerEndpoints.model_validate([
+        {"host": "127.0.0.1", "port": 9443 + index, "server_name": f"{name}.test",
+         "config_sha256": "sha256:" + "a" * 64}
+        for index, name in enumerate(("qualified-a", "qualified-b", "drained", "other-profile", "unreachable"))
+    ])
+    calls = []
+
+    async def probe(_transport, endpoint):
+        calls.append(endpoint.server_name)
+        state = _placement_body()
+        if endpoint.server_name == "drained.test":
+            state.update(draining=True, pre_available=False, background_available=False)
+        if endpoint.server_name == "other-profile.test":
+            state["pre"]["profile_sha256"] = "sha256:" + "0" * 64
+        if endpoint.server_name == "unreachable.test":
+            return None
+        return RunnerPlacement(endpoint, RunnerReadiness.model_validate_json(json.dumps(state)))
+
+    monkeypatch.setattr(RunnerTransport, "probe", probe)
+    transport = RunnerTransport(endpoints, tmp_path, tmp_path, tmp_path)
+    reordered = RunnerTransport(ExternalRunnerEndpoints(tuple(reversed(endpoints.root))), tmp_path, tmp_path, tmp_path)
+
+    def qualifies(readiness):
+        return readiness.pre_available and readiness.pre.profile_sha256 == "sha256:" + "d" * 64
+
+    chosen = await transport.select("stable-attempt", qualifies=qualifies)
+    assert chosen == await reordered.select("stable-attempt", qualifies=qualifies)
+    assert chosen.endpoint.server_name in {"qualified-a.test", "qualified-b.test"}
+    assert len(calls) == 2 * len(endpoints.root)
+    cert = SimpleNamespace(getpeercert=lambda: {"subjectAltName": (("DNS", "*.test"),)})
+    with pytest.raises(ssl.SSLError, match="certificate identity differs"):
+        transport.require_peer(cert, chosen.endpoint)
+
+
 @asynccontextmanager
 async def remote_adapter_endpoint(
     tmp_path: Path,

From ab33b3116297440d9f9e731d39908192a8d28ca0 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:33:14 +0100
Subject: [PATCH 433/513] Fence runner placement against native capacity and
 drain

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  27 +++
 backend/app/adapters/runner.py                |  57 +++--
 .../checkers/external/test_remote_node.py     |  50 +++-
 .../workstream-checker-service/src/main.rs    | 219 +++++++++++++++++-
 .../workstream-checker-service/src/smol.rs    | 110 ++++++++-
 .../src/smol/admission.rs                     |  88 ++++++-
 .../src/smol/intake.rs                        |  19 +-
 .../src/smol/pre/admission.rs                 |  11 +-
 .../src/smol/tests.rs                         |  80 +++++++
 .../src/trial_profiles.rs                     |  52 ++++-
 10 files changed, 652 insertions(+), 61 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 00d90d7c5..77400ffc9 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12359,3 +12359,30 @@ and rejects invalid epoch, extra data, and a changed configuration digest.
 The selector test checks drain and capability exclusion, and stable selection
 after reordering the same configured endpoints. The change is staged without
 activating a new runtime path until the native authority can enforce it.
+
+Native authority scope. The captured startup config digest and verified
+control-root descriptor belong to `src/main.rs`. The existing `smol.rs` and
+`smol/admission.rs` read native capacity and refuse new work during drain. The
+existing `smol/intake.rs` identity supplies the ART capability. Native tests
+cover the private bind frame, exact drain inventory and settled existing
+reservations. The gateway will require the bound epoch when the application
+starts using the new endpoint set.
+
+The placement query carries a bounded read-only demand so an available slot
+alone cannot qualify insufficient memory or disk. Reuse the existing PRE and
+ART capacities and the exact approved trial catalogue in `smol/pre/admission.rs`
+and `trial_profiles.rs`. Both snapshot and reservation evaluate the same
+prospective charge and physical storage gate under the admission lock. Only
+the execution changes usage. The query has no source, execution payload or grant.
+
+Drain readiness includes an authoritative `drained` observation. The same
+admission lock checks the private marker and zero usage, including reserved
+children and work that has acquired capacity but has yet to publish its
+journal. Quarantine prevents a drained reply. A separate visible VM inventory
+cannot certify this boundary.
+
+The native runner selector passed the three placement, drain and epoch cases
+and one existing matching relay case. A separate eight-case transport run
+passed the closed observations and proved that a wedged TLS read cannot
+extend selection through TLS shutdown. These checks use owned local fixtures
+with no new runtime deployment.
diff --git a/backend/app/adapters/runner.py b/backend/app/adapters/runner.py
index c2a00fb61..d485ab0eb 100644
--- a/backend/app/adapters/runner.py
+++ b/backend/app/adapters/runner.py
@@ -6,6 +6,7 @@
 from collections.abc import Callable
 from dataclasses import dataclass
 import hashlib
+import json
 from pathlib import Path
 import ssl
 import struct
@@ -13,13 +14,11 @@
 
 from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator
 
-from app.core.cancellation import await_cancellation_resistant
 from app.core.runner_endpoints import ExternalRunnerEndpoint, ExternalRunnerEndpoints, RunnerDigest
 from app.interfaces.external_checker_execution import ExternalCheckerServiceHealth
 from app.interfaces.trusted_submission_intake import TrustedIntakeIdentity
 
 
-_PROBE = b'{"protocol_version":"workstream.remote_runner.v1","operation":"placement"}'
 _PROBE_SECONDS = 2.0
 _MAXIMUM_PLACEMENT_BYTES = 32_768
 
@@ -53,23 +52,26 @@ class RunnerReadiness(BaseModel):
     epoch: Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")]
     health: ExternalCheckerServiceHealth
     draining: bool
-    pre_available: bool
-    background_available: bool
+    drained: bool
+    fits_admission: bool | None
     images: tuple[RunnerImage, ...] = Field(min_length=1, max_length=64)
     pre: RunnerPreProfile | None
     intake: TrustedIntakeIdentity | None
-    model_callbacks: bool
+    callback_relay: bool
     trial_authority_manifest_sha256: RunnerDigest | None
 
+    def image(self, platform_manifest_digest: str) -> RunnerImage | None:
+        return next((image for image in self.images if image.platform_manifest_digest == platform_manifest_digest), None)
+
     @model_validator(mode="after")
     def exact_readiness(self) -> Self:
         if (
             (self.health.runtime, self.health.isolation_mode) != ("smolvm", "smol-microvm")
             or self.health.cached_platform_manifests != len(self.images)
             or len({image.platform_manifest_digest for image in self.images}) != len(self.images)
-            or self.pre_available and self.pre is None
-            or self.draining and (self.pre_available or self.background_available)
-            or self.trial_authority_manifest_sha256 is not None and not self.model_callbacks
+            or self.draining and self.fits_admission is True
+            or self.drained and not self.draining
+            or self.trial_authority_manifest_sha256 is not None and not self.callback_relay
         ):
             raise ValueError("external runner readiness disagrees with its capabilities")
         return self
@@ -82,6 +84,9 @@ class RunnerPlacement:
     endpoint: ExternalRunnerEndpoint
     readiness: RunnerReadiness
 
+    def binding(self) -> dict[str, str]:
+        return {"epoch": self.readiness.epoch, "config_sha256": self.readiness.config_sha256}
+
 
 @dataclass(frozen=True, slots=True)
 class RunnerTransport:
@@ -92,6 +97,12 @@ class RunnerTransport:
     certificate_path: Path
     private_key_path: Path
 
+    def __post_init__(self) -> None:
+        if any(not path.is_absolute() or path.is_symlink() for path in (
+            self.ca_path, self.certificate_path, self.private_key_path,
+        )):
+            raise ValueError("external runner credential paths are invalid")
+
     def tls_context(self) -> ssl.SSLContext:
         context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=str(self.ca_path))
         context.minimum_version = ssl.TLSVersion.TLSv1_3
@@ -113,40 +124,52 @@ async def open(self, endpoint: ExternalRunnerEndpoint) -> tuple[asyncio.StreamRe
         try:
             self.require_peer(writer.get_extra_info("ssl_object"), endpoint)
         except BaseException:
-            writer.close()
-            await await_cancellation_resistant(writer.wait_closed())
+            writer.transport.abort()
             raise
         return reader, writer
 
-    async def probe(self, endpoint: ExternalRunnerEndpoint) -> RunnerPlacement | None:
+    async def probe(
+        self, endpoint: ExternalRunnerEndpoint, *, demand: dict[str, object] | None,
+    ) -> RunnerPlacement | None:
         """Observe authenticated readiness without sending an execution or a grant."""
         try:
+            request = json.dumps({
+                "protocol_version": "workstream.remote_runner.v1", "operation": "placement", "demand": demand,
+            }, allow_nan=False, separators=(",", ":")).encode()
             async with asyncio.timeout(_PROBE_SECONDS):
                 reader, writer = await self.open(endpoint)
                 try:
-                    writer.write(struct.pack(">I", len(_PROBE)) + _PROBE)
+                    writer.write(struct.pack(">I", len(request)) + request)
                     await writer.drain()
                     size = struct.unpack(">I", await reader.readexactly(4))[0]
                     if not 0 < size <= _MAXIMUM_PLACEMENT_BYTES:
                         return None
                     readiness = RunnerReadiness.model_validate_json(await reader.readexactly(size))
-                    if await reader.read(1) or readiness.config_sha256 != endpoint.config_sha256:
+                    if (
+                        await reader.read(1)
+                        or readiness.config_sha256 != endpoint.config_sha256
+                        or (readiness.fits_admission is None) != (demand is None)
+                    ):
                         return None
                 finally:
-                    writer.close()
-                    await writer.wait_closed()
+                    # A read-only probe has no remote lease to settle. Do not let
+                    # SSL shutdown extend either the probe cap or original caller budget.
+                    writer.transport.abort()
         except (OSError, TimeoutError, asyncio.IncompleteReadError, ValueError):
             return None
         return RunnerPlacement(endpoint, readiness)
 
     async def select(
         self, claim_key: str, *, qualifies: Callable[[RunnerReadiness], bool],
+        demand: dict[str, object] | None = None,
     ) -> RunnerPlacement | None:
         """Pick one qualified node deterministically, independent of probe arrival order."""
-        observed = await asyncio.gather(*(self.probe(endpoint) for endpoint in self.endpoints.root))
+        observed = await asyncio.gather(*(self.probe(endpoint, demand=demand) for endpoint in self.endpoints.root))
         return min(
             (placement for placement in observed if placement is not None
-             and not placement.readiness.draining and qualifies(placement.readiness)),
+             and not placement.readiness.draining
+             and (demand is None or placement.readiness.fits_admission is True)
+             and qualifies(placement.readiness)),
             key=lambda placement: hashlib.sha256(
                 f"{claim_key}\0{placement.endpoint.server_name}".encode()
             ).digest(),
diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py
index 77ed543ab..b2cef011f 100644
--- a/backend/tests/checkers/external/test_remote_node.py
+++ b/backend/tests/checkers/external/test_remote_node.py
@@ -103,11 +103,11 @@ def _placement_body():
         "health": {"operating_system": "linux", "architecture": "amd64", "runtime": "smolvm",
                    "isolation_mode": "smol-microvm", "cached_platform_manifests": 1,
                    "sandbox_uid": 10001, "sandbox_gid": 10001},
-        "draining": False, "pre_available": True, "background_available": True,
+        "draining": False, "drained": False, "fits_admission": None,
         "images": [{"platform_manifest_digest": "sha256:" + "b" * 64,
                     "config_image_id": "sha256:" + "c" * 64}],
         "pre": {"profile_sha256": "sha256:" + "d" * 64, "root_sha256": "sha256:" + "f" * 64},
-        "intake": None, "model_callbacks": False, "trial_authority_manifest_sha256": None,
+        "intake": None, "callback_relay": False, "trial_authority_manifest_sha256": None,
     }
 
 
@@ -167,13 +167,13 @@ async def observe(reader, writer):
         }])
         transport = RunnerTransport(endpoints, certificates["ca"], certificates["client_certificate"],
                                     certificates["client_key"])
-        matched = await transport.select("attempt-1", qualifies=lambda readiness: readiness.pre_available)
+        matched = await transport.select("attempt-1", qualifies=lambda readiness: readiness.pre is not None)
         if changed is None:
             assert matched is not None and matched.readiness.epoch == body["epoch"]
             assert matched.readiness.images[0].config_image_id == body["images"][0]["config_image_id"]
         else:
             assert matched is None
-    assert requests == [{"protocol_version": "workstream.remote_runner.v1", "operation": "placement"}]
+    assert requests == [{"protocol_version": "workstream.remote_runner.v1", "operation": "placement", "demand": None}]
 
 
 @pytest.mark.asyncio
@@ -186,15 +186,21 @@ async def test_runner_selection_uses_only_qualified_ready_targets(tmp_path, monk
     endpoints = ExternalRunnerEndpoints.model_validate([
         {"host": "127.0.0.1", "port": 9443 + index, "server_name": f"{name}.test",
          "config_sha256": "sha256:" + "a" * 64}
-        for index, name in enumerate(("qualified-a", "qualified-b", "drained", "other-profile", "unreachable"))
+        for index, name in enumerate(("qualified-a", "qualified-b", "drained", "other-profile", "full", "unreachable"))
     ])
     calls = []
 
-    async def probe(_transport, endpoint):
+    demand = {"kind": "pre", "source_bytes": 200}
+
+    async def probe(_transport, endpoint, *, demand):
+        assert demand == {"kind": "pre", "source_bytes": 200}
         calls.append(endpoint.server_name)
         state = _placement_body()
+        state["fits_admission"] = True
         if endpoint.server_name == "drained.test":
-            state.update(draining=True, pre_available=False, background_available=False)
+            state.update(draining=True, fits_admission=False)
+        if endpoint.server_name == "full.test":
+            state.update(fits_admission=False)
         if endpoint.server_name == "other-profile.test":
             state["pre"]["profile_sha256"] = "sha256:" + "0" * 64
         if endpoint.server_name == "unreachable.test":
@@ -206,10 +212,10 @@ async def probe(_transport, endpoint):
     reordered = RunnerTransport(ExternalRunnerEndpoints(tuple(reversed(endpoints.root))), tmp_path, tmp_path, tmp_path)
 
     def qualifies(readiness):
-        return readiness.pre_available and readiness.pre.profile_sha256 == "sha256:" + "d" * 64
+        return readiness.pre.profile_sha256 == "sha256:" + "d" * 64
 
-    chosen = await transport.select("stable-attempt", qualifies=qualifies)
-    assert chosen == await reordered.select("stable-attempt", qualifies=qualifies)
+    chosen = await transport.select("stable-attempt", qualifies=qualifies, demand=demand)
+    assert chosen == await reordered.select("stable-attempt", qualifies=qualifies, demand=demand)
     assert chosen.endpoint.server_name in {"qualified-a.test", "qualified-b.test"}
     assert len(calls) == 2 * len(endpoints.root)
     cert = SimpleNamespace(getpeercert=lambda: {"subjectAltName": (("DNS", "*.test"),)})
@@ -217,6 +223,30 @@ def qualifies(readiness):
         transport.require_peer(cert, chosen.endpoint)
 
 
+@pytest.mark.asyncio
+async def test_runner_probe_aborts_without_waiting_for_tls_shutdown(tmp_path, monkeypatch):
+    from unittest.mock import AsyncMock, Mock
+
+    from app.adapters import runner
+    from app.core.runner_endpoints import ExternalRunnerEndpoints
+
+    async def no_result(*_args):
+        await asyncio.Future()
+
+    endpoints = ExternalRunnerEndpoints.model_validate([{
+        "host": "127.0.0.1", "port": 9443, "server_name": "runner.test",
+        "config_sha256": _placement_body()["config_sha256"],
+    }])
+    reader = Mock(readexactly=AsyncMock(side_effect=no_result))
+    writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock(side_effect=no_result))
+    monkeypatch.setattr(runner.RunnerTransport, "open", AsyncMock(return_value=(reader, writer)))
+    monkeypatch.setattr(runner, "_PROBE_SECONDS", 0.02)
+    transport = runner.RunnerTransport(endpoints, tmp_path, tmp_path, tmp_path)
+    assert await asyncio.wait_for(transport.select("claim", qualifies=lambda _state: True), 1) is None
+    writer.transport.abort.assert_called_once_with()
+    writer.wait_closed.assert_not_awaited()
+
+
 @asynccontextmanager
 async def remote_adapter_endpoint(
     tmp_path: Path,
diff --git a/external_checkers/workstream-checker-service/src/main.rs b/external_checkers/workstream-checker-service/src/main.rs
index 87fcea473..b15f9a58a 100644
--- a/external_checkers/workstream-checker-service/src/main.rs
+++ b/external_checkers/workstream-checker-service/src/main.rs
@@ -63,6 +63,10 @@ struct ServiceConfig {
     #[serde(skip)]
     container_owner: Option,
     #[serde(skip)]
+    control_root: Option>,
+    #[serde(skip)]
+    startup_config_sha256: String,
+    #[serde(skip)]
     smol_admission: Option>,
     socket_path: PathBuf,
     model_proxy_socket: Option,
@@ -160,6 +164,38 @@ struct HealthEnvelope {
     operation: String,
 }
 
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct BindEpochEnvelope {
+    protocol_version: String,
+    operation: String,
+    config_sha256: String,
+    epoch: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct PlacementEnvelope {
+    protocol_version: String,
+    operation: String,
+    demand: Option,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
+enum PlacementDemand {
+    Pre {
+        source_bytes: u64,
+    },
+    Intake {
+        preparation: Value,
+    },
+    Post {
+        memory_bytes: u64,
+        trial: Option,
+    },
+}
+
 #[derive(Debug, Deserialize)]
 #[serde(deny_unknown_fields)]
 struct GrantReference {
@@ -231,6 +267,12 @@ struct HealthReceipt<'a> {
     protocol_version: &'static str,
     operation: &'static str,
     status: &'static str,
+    #[serde(flatten)]
+    runtime: RuntimeHealth<'a>,
+}
+
+#[derive(Debug, Serialize)]
+struct RuntimeHealth<'a> {
     operating_system: &'a str,
     architecture: &'a str,
     runtime: &'a str,
@@ -485,6 +527,7 @@ fn run() -> Result<(), String> {
     let bytes = fs::read(path).map_err(|_| "configuration unavailable")?;
     let mut config: ServiceConfig =
         serde_json::from_slice(&bytes).map_err(|_| "configuration invalid")?;
+    config.startup_config_sha256 = format!("sha256:{:x}", Sha256::digest(&bytes));
     load_trial_profiles(&mut config)?;
     let listener = prepare_listener(&mut config)?;
     if config.runtime == "smolvm" {
@@ -780,6 +823,12 @@ fn prepare_listener(config: &mut ServiceConfig) -> Result(bytes)
             .ok()
@@ -914,6 +963,35 @@ fn serve_connection(
     Ok(())
 }
 
+fn read_connection_frame(
+    config: &ServiceConfig,
+    stream: &mut UnixStream,
+    deadline: Instant,
+) -> Result, String> {
+    let frame = read_frame_until(stream, MAX_ENVELOPE_BYTES, deadline)?;
+    if !serde_json::from_slice::(&frame)
+        .ok()
+        .is_some_and(|value| value["operation"] == "bind_epoch")
+    {
+        return Ok(frame);
+    }
+    let binding: BindEpochEnvelope =
+        serde_json::from_slice(&frame).map_err(|_| "runner binding invalid")?;
+    let admission = config
+        .smol_admission
+        .as_ref()
+        .ok_or("runner epoch unavailable")?;
+    if binding.protocol_version != PROTOCOL
+        || binding.operation != "bind_epoch"
+        || binding.config_sha256 != config.startup_config_sha256
+        || binding.epoch != admission.epoch
+    {
+        return Err("runner binding differs".into());
+    }
+    // A bound frame never changes the original private request or its read deadline.
+    read_frame_until(stream, MAX_ENVELOPE_BYTES, deadline)
+}
+
 fn connection_response(response: Result, String>) -> Result>, String> {
     match response {
         Ok(bytes) => Ok(Some(bytes)),
@@ -934,6 +1012,7 @@ fn validate_config(config: &ServiceConfig) -> Result<(), String> {
         || config.sandbox_uid == 0
         || config.sandbox_gid == 0
         || config.cache.is_empty()
+        || config.cache.len() > 64
     {
         return Err("configuration values invalid".into());
     }
@@ -1033,7 +1112,16 @@ fn handle_frame(
     bytes: &[u8],
 ) -> Result, String> {
     let value: Value = serde_json::from_slice(bytes).map_err(|_| "request envelope invalid")?;
-    if value.get("operation").and_then(Value::as_str) == Some("health") {
+    if value["operation"] == "placement" {
+        let envelope: PlacementEnvelope =
+            serde_json::from_value(value).map_err(|_| "runner placement envelope invalid")?;
+        if envelope.protocol_version != PROTOCOL || envelope.operation != "placement" {
+            return Err("request operation invalid".into());
+        }
+        runtime_ready(config)?;
+        return placement_reply(config, envelope.demand.as_ref());
+    }
+    if value["operation"] == "health" {
         let envelope: HealthEnvelope =
             serde_json::from_value(value).map_err(|_| "health envelope invalid")?;
         if envelope.protocol_version != PROTOCOL || envelope.operation != "health" {
@@ -1044,13 +1132,7 @@ fn handle_frame(
             protocol_version: PROTOCOL,
             operation: "health",
             status: "ready",
-            operating_system: &config.operating_system,
-            architecture: &config.architecture,
-            runtime: &config.runtime,
-            isolation_mode: &config.isolation_mode,
-            cached_platform_manifests: config.cache.len(),
-            sandbox_uid: config.sandbox_uid,
-            sandbox_gid: config.sandbox_gid,
+            runtime: runtime_health(config),
         })
         .map_err(|_| "health encoding failed".into());
     }
@@ -1149,6 +1231,64 @@ fn handle_frame(
     encode_response(result, isolation)
 }
 
+fn runtime_health(config: &ServiceConfig) -> RuntimeHealth<'_> {
+    RuntimeHealth {
+        operating_system: &config.operating_system,
+        architecture: &config.architecture,
+        runtime: &config.runtime,
+        isolation_mode: &config.isolation_mode,
+        cached_platform_manifests: config.cache.len(),
+        sandbox_uid: config.sandbox_uid,
+        sandbox_gid: config.sandbox_gid,
+    }
+}
+
+fn placement_reply(
+    config: &ServiceConfig,
+    demand: Option<&PlacementDemand>,
+) -> Result, String> {
+    let admission = config
+        .smol_admission
+        .as_ref()
+        .ok_or("runner epoch unavailable")?;
+    let (draining, drained) = admission.drain_state(|| smol::node_draining(config))?;
+    let fits_admission = demand
+        .map(|demand| match draining {
+            true => Ok(false),
+            false => smol::fits_placement(config, demand),
+        })
+        .transpose()?;
+    let images: Vec<_> = config
+        .cache
+        .iter()
+        .map(|entry| {
+            serde_json::json!({
+                "platform_manifest_digest": entry.platform_manifest_digest,
+                "config_image_id": entry.config_image_id,
+            })
+        })
+        .collect();
+    let intake = config
+        .trusted_intake
+        .as_ref()
+        .map(|_| smol::intake_identity(config))
+        .transpose()?;
+    serde_json::to_vec(&serde_json::json!({
+        "protocol_version": PROTOCOL, "operation": "placement",
+        "config_sha256": config.startup_config_sha256, "epoch": admission.epoch,
+        "health": runtime_health(config), "draining": draining, "drained": drained,
+        "fits_admission": fits_admission,
+        "images": images,
+        "pre": config.pre.as_ref().map(|pre| serde_json::json!({
+            "profile_sha256": pre.profile_sha256, "root_sha256": pre.root.bundle_sha256,
+        })),
+        "intake": intake,
+        "callback_relay": config.model_proxy_socket.is_some(),
+        "trial_authority_manifest_sha256": config.trial_authority_manifest_digest,
+    }))
+    .map_err(|_| "runner placement encoding failed".into())
+}
+
 fn validate_execution_operation(
     operation: &str,
     request: &ValidatedRequest,
@@ -3061,6 +3201,8 @@ mod tests {
             trusted_intake: None,
             pre: None,
             smol_admission: None,
+            control_root: Some(std::sync::Arc::new(File::open(&socket_root).unwrap())),
+            startup_config_sha256: format!("sha256:{}", "a".repeat(64)),
             container_owner: Some(
                 load_container_owner(&File::open(&socket_root).unwrap()).unwrap(),
             ),
@@ -3093,6 +3235,65 @@ mod tests {
         (root, config)
     }
 
+    #[test]
+    fn runner_binding_requires_loaded_config_and_current_epoch() {
+        let (root, mut config) = test_config();
+        config.smol_admission = Some(std::sync::Arc::new(
+            smol::Admission::new(
+                smol::Capacity {
+                    slots: 1,
+                    memory_bytes: 1,
+                    storage_bytes: 1,
+                },
+                None,
+                "e".repeat(64),
+            )
+            .unwrap(),
+        ));
+        let inner = serde_json::to_vec(&serde_json::json!({
+            "protocol_version": PROTOCOL, "operation": "health",
+        }))
+        .unwrap();
+        let binding = serde_json::json!({
+            "protocol_version": PROTOCOL, "operation": "bind_epoch",
+            "config_sha256": config.startup_config_sha256, "epoch": "e".repeat(64),
+        });
+        for field in [
+            None,
+            Some("epoch"),
+            Some("config_sha256"),
+            Some("unexpected"),
+        ] {
+            let mut proposed = binding.clone();
+            if let Some(name) = field {
+                proposed[name] = serde_json::json!("different");
+            }
+            let (mut client, mut service) = UnixStream::pair().unwrap();
+            let deadline = Instant::now() + Duration::from_secs(1);
+            write_frame_until(
+                &mut client,
+                &serde_json::to_vec(&proposed).unwrap(),
+                deadline,
+            )
+            .unwrap();
+            write_frame_until(&mut client, &inner, deadline).unwrap();
+            let observed = read_connection_frame(&config, &mut service, deadline);
+            if field.is_none() {
+                assert_eq!(observed.unwrap(), inner);
+            } else {
+                assert!(observed.is_err());
+            }
+        }
+        let (mut client, mut service) = UnixStream::pair().unwrap();
+        let deadline = Instant::now() + Duration::from_secs(1);
+        write_frame_until(&mut client, &inner, deadline).unwrap();
+        assert_eq!(
+            read_connection_frame(&config, &mut service, deadline).unwrap(),
+            inner
+        );
+        fs::remove_dir_all(root).unwrap();
+    }
+
     #[test]
     fn trial_manifest_reader_rejects_growth_and_path_replacement() {
         let (root, _) = test_config();
diff --git a/external_checkers/workstream-checker-service/src/smol.rs b/external_checkers/workstream-checker-service/src/smol.rs
index 15bff2c84..0fcfcc485 100644
--- a/external_checkers/workstream-checker-service/src/smol.rs
+++ b/external_checkers/workstream-checker-service/src/smol.rs
@@ -32,6 +32,7 @@ pub(crate) use admission::{Admission, Capacity, Phase, Reservation};
 mod intake;
 pub(crate) mod trial;
 mod trial_io;
+pub(super) use intake::identity as intake_identity;
 pub(super) use intake::{serve as serve_intake, IntakeConfig};
 mod io;
 mod pre;
@@ -48,16 +49,20 @@ struct Resources {
 }
 impl From<&ValidatedRequest> for Resources {
     fn from(value: &ValidatedRequest) -> Self {
+        Self::checker(value.cpu_millis, value.memory_bytes)
+    }
+}
+
+impl Resources {
+    fn checker(cpu_millis: u64, memory_bytes: u64) -> Self {
         Self {
-            cpu_millis: value.cpu_millis,
-            memory_bytes: value.memory_bytes,
+            cpu_millis,
+            memory_bytes,
             storage_gib: 1,
-            pids: (value.memory_bytes / (16 * 1024 * 1024)).clamp(16, 256),
+            pids: (memory_bytes / (16 * 1024 * 1024)).clamp(16, 256),
         }
     }
-}
 
-impl Resources {
     fn host_pids(self) -> u64 {
         // The VMM needs host threads independently of the guest workload's
         // process ceiling. The pinned runtime reaches 57 during cold startup.
@@ -199,7 +204,100 @@ fn reserve_capacity(
         .smol_admission
         .as_ref()
         .ok_or("admission unavailable")?;
-    admission.reserve_with_storage(phase, outer, child, || available_storage(settings(config)?))
+    admission.reserve_with_storage(phase, outer, child, || storage_open_for_admission(config))
+}
+
+fn storage_open_for_admission(config: &ServiceConfig) -> Result {
+    let available = available_storage(settings(config)?)?;
+    // Read the operator gate under the same lock as the final reservation.
+    if node_draining(config)? {
+        return Err("runner is draining".into());
+    }
+    Ok(available)
+}
+
+pub(super) fn fits_placement(
+    config: &ServiceConfig,
+    demand: &PlacementDemand,
+) -> Result {
+    let admission = config
+        .smol_admission
+        .as_ref()
+        .ok_or("runner epoch unavailable")?;
+    let (phase, outer, child) = match demand {
+        PlacementDemand::Pre { source_bytes } => (
+            Phase::Pre,
+            config
+                .pre
+                .as_ref()
+                .ok_or("PRE unavailable")?
+                .capacity(*source_bytes)?,
+            None,
+        ),
+        PlacementDemand::Intake { preparation } => (
+            Phase::Background,
+            intake::placement_capacity(config, preparation)?,
+            None,
+        ),
+        PlacementDemand::Post {
+            memory_bytes,
+            trial,
+        } => {
+            let child = trial
+                .as_ref()
+                .map(|binding| {
+                    let profile = config
+                        .trial_profiles
+                        .as_ref()
+                        .and_then(|catalog| catalog.resolve_placement(binding))
+                        .ok_or("trial authority unavailable")?;
+                    trial_peak_capacity(
+                        profile.maximum_memory_bytes,
+                        profile.maximum_memory_overrun_bytes,
+                        profile.maximum_disk_bytes,
+                    )
+                })
+                .transpose()?;
+            (
+                Phase::Background,
+                resource_capacity(Resources::checker(0, *memory_bytes), None)?,
+                child,
+            )
+        }
+    };
+    admission.fits_with_storage(phase, outer, child, || storage_open_for_admission(config))
+}
+
+pub(super) const DRAIN_MARKER: &str = ".workstream-checker-drain";
+
+pub(super) fn node_draining(config: &ServiceConfig) -> Result {
+    let root = config
+        .control_root
+        .as_ref()
+        .ok_or("runner control root unavailable")?;
+    let path = PathBuf::from(format!(
+        "/proc/self/fd/{}/{}",
+        root.as_raw_fd(),
+        DRAIN_MARKER
+    ));
+    let metadata = match fs::symlink_metadata(path) {
+        Ok(metadata) => metadata,
+        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+        Err(_) => return Err("runner drain marker unavailable".into()),
+    };
+    let owner = root
+        .metadata()
+        .map_err(|_| "runner control root unavailable")?;
+    if !metadata.is_file()
+        || metadata.uid() != owner.uid()
+        || metadata.gid() != owner.gid()
+        || metadata.mode() & 0o7777 != 0o600
+        || metadata.nlink() != 1
+        || metadata.len() != 0
+    {
+        return Err("runner drain marker custody invalid".into());
+    }
+    Ok(true)
 }
 fn available_storage(s: &SmolConfig) -> Result {
     let directory = File::open(&s.home).map_err(|_| "Smol storage unavailable")?;
diff --git a/external_checkers/workstream-checker-service/src/smol/admission.rs b/external_checkers/workstream-checker-service/src/smol/admission.rs
index 64b2ea827..fbae426fa 100644
--- a/external_checkers/workstream-checker-service/src/smol/admission.rs
+++ b/external_checkers/workstream-checker-service/src/smol/admission.rs
@@ -84,6 +84,18 @@ impl Admission {
         Ok(used.pre.storage_bytes + used.background.storage_bytes)
     }
 
+    pub(crate) fn drain_state(
+        &self,
+        marker: impl FnOnce() -> Result,
+    ) -> Result<(bool, bool), String> {
+        let used = self.used.lock().map_err(|_| "node admission unavailable")?;
+        if self.poisoned.load(Ordering::SeqCst) {
+            return Err("node admission quarantined".into());
+        }
+        let draining = marker()?;
+        Ok((draining, draining && *used == Usage::default()))
+    }
+
     fn required_storage_bytes(&self, phase: Phase, used: Usage) -> Result {
         match phase {
             Phase::Pre => Ok(used.pre.storage_bytes + used.background.storage_bytes),
@@ -133,6 +145,40 @@ impl Admission {
         child: Option,
         available_storage: impl FnOnce() -> Result,
     ) -> Result, String> {
+        let mut used = self.used.lock().map_err(|_| "node admission unavailable")?;
+        let (proposed, charge) =
+            self.proposed_usage(*used, phase, outer, child, available_storage)?;
+        *used = proposed;
+        Ok(Arc::new(Reservation {
+            admission: self.clone(),
+            phase,
+            charge,
+            child,
+            child_active: AtomicBool::new(false),
+        }))
+    }
+
+    pub(super) fn fits_with_storage(
+        &self,
+        phase: Phase,
+        outer: Capacity,
+        child: Option,
+        available_storage: impl FnOnce() -> Result,
+    ) -> Result {
+        let used = self.used.lock().map_err(|_| "node admission unavailable")?;
+        Ok(self
+            .proposed_usage(*used, phase, outer, child, available_storage)
+            .is_ok())
+    }
+
+    fn proposed_usage(
+        &self,
+        used: Usage,
+        phase: Phase,
+        outer: Capacity,
+        child: Option,
+        available_storage: impl FnOnce() -> Result,
+    ) -> Result<(Usage, Capacity), String> {
         if outer.slots != 1
             || outer.memory_bytes == 0
             || outer.storage_bytes == 0
@@ -144,7 +190,6 @@ impl Admission {
         let charge = outer
             .checked_add(child.unwrap_or_default())
             .ok_or("capacity overflow")?;
-        let mut used = self.used.lock().map_err(|_| "node admission unavailable")?;
         if self.poisoned.load(Ordering::SeqCst) {
             return Err("node admission quarantined".into());
         }
@@ -154,7 +199,7 @@ impl Admission {
         };
         // Both ceilings are disjoint partitions of the node maximum. Charging either
         // under this same lock keeps their aggregate within the node maximum.
-        let mut proposed = *used;
+        let mut proposed = used;
         let phase_usage = proposed.for_phase(phase);
         *phase_usage = phase_usage
             .checked_add(charge)
@@ -168,14 +213,7 @@ impl Admission {
         if self.poisoned.load(Ordering::SeqCst) {
             return Err("node admission quarantined".into());
         }
-        *used = proposed;
-        Ok(Arc::new(Reservation {
-            admission: self.clone(),
-            phase,
-            charge,
-            child,
-            child_active: AtomicBool::new(false),
-        }))
+        Ok((proposed, charge))
     }
 
     #[cfg(test)]
@@ -302,6 +340,36 @@ mod tests {
         }
     }
 
+    #[test]
+    fn runner_placement_checks_exact_peak_and_storage_without_claiming() {
+        let pre = amount(1, 8, 16);
+        let job = amount(1, 6, 7);
+        let node = Arc::new(Admission::new(amount(3, 20, 30), Some(pre), "test".into()).unwrap());
+        for (outer, child, free) in [
+            (amount(1, 7, 7), job, 60),
+            (job, amount(1, 6, 8), 60),
+            (job, job, 59),
+        ] {
+            assert!(!node
+                .fits_with_storage(Phase::Background, outer, Some(child), || Ok(free))
+                .unwrap());
+        }
+        assert!(node
+            .fits_with_storage(Phase::Background, job, Some(job), || Ok(60))
+            .unwrap());
+        assert_eq!(node.reserved_storage_bytes().unwrap(), 0);
+        let _held = node
+            .reserve_with_storage(Phase::Background, job, Some(job), || Ok(60))
+            .unwrap();
+        assert!(!node
+            .fits_with_storage(Phase::Background, job, None, || Ok(60))
+            .unwrap());
+        assert!(node
+            .fits_with_storage(Phase::Pre, pre, None, || Ok(30))
+            .unwrap());
+        assert_eq!(node.reserved_storage_bytes().unwrap(), 14);
+    }
+
     #[test]
     fn saturated_background_trial_leaves_pre_capacity_and_disk_headroom() {
         let pre = amount(1, 8, 16);
diff --git a/external_checkers/workstream-checker-service/src/smol/intake.rs b/external_checkers/workstream-checker-service/src/smol/intake.rs
index 327a43b71..06551e6fb 100644
--- a/external_checkers/workstream-checker-service/src/smol/intake.rs
+++ b/external_checkers/workstream-checker-service/src/smol/intake.rs
@@ -159,7 +159,7 @@ fn image(config: &ServiceConfig) -> Result<(&IntakeConfig, &CacheEntry), String>
     inspect_image(cache)?;
     Ok((intake, cache))
 }
-fn identity(config: &ServiceConfig) -> Result {
+pub(crate) fn identity(config: &ServiceConfig) -> Result {
     let (intake, cache) = image(config)?;
     Ok(
         json!({"image_digest": cache.platform_manifest_digest, "config_digest": cache.config_image_id,
@@ -168,6 +168,20 @@ fn identity(config: &ServiceConfig) -> Result {
         "memory_bytes": BASE_RESOURCES.memory_bytes}),
     )
 }
+
+pub(super) fn placement_capacity(
+    config: &ServiceConfig,
+    payload: &Value,
+) -> Result {
+    let request = preparation(payload)?;
+    let (intake, _) = image(config)?;
+    intake_capacity(resources(&request, &intake.storage_envelope)?)
+}
+
+fn intake_capacity(resources: Resources) -> Result {
+    // Intake explicitly allocates a separate 1 GiB writable root overlay.
+    resource_capacity(resources, Some(1))
+}
 fn preparation(value: &Value) -> Result {
     let request: Preparation =
         serde_json::from_value(value.clone()).map_err(|_| "intake preparation invalid")?;
@@ -283,8 +297,7 @@ pub(crate) fn serve(
     let (intake, cache) = image(config)?;
     let resources = resources(&request, &intake.storage_envelope)?;
     let deadline = Instant::now() + Duration::from_millis(request.deadline_ms);
-    // Intake explicitly allocates a separate 1 GiB writable root overlay.
-    let capacity = resource_capacity(resources, Some(1))?;
+    let capacity = intake_capacity(resources)?;
     let reservation = match reserve_capacity(config, Phase::Background, capacity, None) {
         Ok(value) => value,
         Err(_) => {
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/admission.rs b/external_checkers/workstream-checker-service/src/smol/pre/admission.rs
index 9d4bbeb31..83d7c01da 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/admission.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/admission.rs
@@ -19,14 +19,21 @@ pub(crate) struct Config {
 
 impl Config {
     pub(in crate::smol) fn node_reserve(&self) -> Result {
-        let (resources, overlay_gib) = self.resources(self.limits.maximum_source_bytes)?;
-        let required = resource_capacity(resources, Some(overlay_gib))?;
+        let required = self.capacity(self.limits.maximum_source_bytes)?;
         if !required.fits(self.reserved_capacity) {
             return Err("PRE reserve cannot fit the configured profile".into());
         }
         Ok(self.reserved_capacity)
     }
 
+    pub(in crate::smol) fn capacity(&self, source_bytes: u64) -> Result {
+        if source_bytes == 0 || source_bytes > self.limits.maximum_source_bytes {
+            return Err("PRE source bound differs".into());
+        }
+        let (resources, overlay_gib) = self.resources(source_bytes)?;
+        resource_capacity(resources, Some(overlay_gib))
+    }
+
     fn resources(&self, source_bytes: u64) -> Result<(Resources, u64), String> {
         let limits = &self.limits;
         let storage = sum([
diff --git a/external_checkers/workstream-checker-service/src/smol/tests.rs b/external_checkers/workstream-checker-service/src/smol/tests.rs
index 45b87a4c1..05e4d9c51 100644
--- a/external_checkers/workstream-checker-service/src/smol/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/tests.rs
@@ -141,6 +141,86 @@ fn background_disk_allocation_preserves_physical_pre_headroom() {
     fs::remove_dir_all(root).unwrap();
 }
 
+#[test]
+fn runner_drain_uses_owned_control_root_and_preserves_admitted_child() {
+    let (root, mut config) = super::super::tests::test_config();
+    const MIB: u64 = 1024 * 1024;
+    let one = Capacity {
+        slots: 1,
+        memory_bytes: MIB,
+        storage_bytes: MIB,
+    };
+    config.smol = Some(SmolConfig {
+        binary: root.join("unused-runtime"),
+        binary_sha256: "unused".into(),
+        home: root.clone(),
+        guest_binary: root.join("unused-guest"),
+        guest_sha256: "unused".into(),
+        cgroup_root: root.join("unused-cgroup"),
+        maximum_parallel: 4,
+        maximum_storage_bytes: 4 * MIB,
+    });
+    let admission = Arc::new(
+        Admission::new(
+            Capacity {
+                slots: 4,
+                memory_bytes: 4 * MIB,
+                storage_bytes: 4 * MIB,
+            },
+            Some(one),
+            "e".repeat(64),
+        )
+        .unwrap(),
+    );
+    config.smol_admission = Some(admission.clone());
+    let held = reserve_capacity(&config, Phase::Background, one, Some(one)).unwrap();
+    assert!(admission
+        .fits_with_storage(Phase::Pre, one, None, || Ok(u64::MAX))
+        .unwrap());
+
+    let control = config.socket_path.parent().unwrap();
+    let marker = control.join(DRAIN_MARKER);
+    fs::write(&marker, b"bad marker").unwrap();
+    assert!(node_draining(&config).is_err());
+    fs::remove_file(&marker).unwrap();
+    OpenOptions::new()
+        .write(true)
+        .create_new(true)
+        .mode(0o600)
+        .open(&marker)
+        .unwrap();
+    assert!(node_draining(&config).unwrap());
+    let owned_control = root.join("owned-control");
+    fs::rename(control, &owned_control).unwrap();
+    fs::create_dir(control).unwrap();
+    assert!(node_draining(&config).unwrap());
+    assert_eq!(
+        admission.drain_state(|| node_draining(&config)).unwrap(),
+        (true, false)
+    );
+
+    for phase in [Phase::Pre, Phase::Background] {
+        assert_eq!(
+            reserve_capacity(&config, phase, one, None).unwrap_err(),
+            "runner is draining"
+        );
+    }
+    let child = held.child(one).unwrap();
+    drop((child, held));
+    assert_eq!(admission.reserved_storage_bytes().unwrap(), 0);
+    assert_eq!(
+        admission.drain_state(|| node_draining(&config)).unwrap(),
+        (true, true)
+    );
+    fs::remove_file(owned_control.join(DRAIN_MARKER)).unwrap();
+    assert_eq!(
+        admission.drain_state(|| node_draining(&config)).unwrap(),
+        (false, false)
+    );
+    assert!(reserve_capacity(&config, Phase::Pre, one, None).is_ok());
+    fs::remove_dir_all(root).unwrap();
+}
+
 #[test]
 fn foreign_lease_refuses_recovery_before_any_runtime_or_owned_cleanup() {
     let (root, mut config) = super::super::tests::test_config();
diff --git a/external_checkers/workstream-checker-service/src/trial_profiles.rs b/external_checkers/workstream-checker-service/src/trial_profiles.rs
index 626db4545..d036ff556 100644
--- a/external_checkers/workstream-checker-service/src/trial_profiles.rs
+++ b/external_checkers/workstream-checker-service/src/trial_profiles.rs
@@ -257,6 +257,30 @@ pub(crate) struct TrialProfileCatalog {
     entries: Vec,
 }
 
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub(crate) struct TrialPlacementBinding {
+    registry_entry_id: String,
+    registry_entry_digest: String,
+    image_digest: String,
+    configuration_sha256: String,
+    profile_digest: String,
+    projection_digest: String,
+}
+
+fn matches_binding(
+    profile: &TrialProfile,
+    registry_entry_id: &str,
+    registry_entry_digest: &str,
+    image_digest: &str,
+    configuration_sha256: &str,
+) -> bool {
+    profile.registry_entry_id == registry_entry_id
+        && profile.registry_entry_digest == registry_entry_digest
+        && profile.checker_image_digest == image_digest
+        && profile.configuration_sha256 == configuration_sha256
+}
+
 impl TrialProfileCatalog {
     #[cfg(test)]
     pub(crate) fn empty_for_test() -> Self {
@@ -324,10 +348,13 @@ impl TrialProfileCatalog {
             .iter()
             .filter(|profile| {
                 selector_from_profile(profile) == selected
-                    && profile.registry_entry_id == request.registry_entry_id
-                    && profile.registry_entry_digest == request.registry_entry_digest
-                    && profile.checker_image_digest == request.image_digest
-                    && profile.configuration_sha256 == request.configuration_digest
+                    && matches_binding(
+                        profile,
+                        &request.registry_entry_id,
+                        &request.registry_entry_digest,
+                        &request.image_digest,
+                        &request.configuration_digest,
+                    )
             })
             .collect::>();
         match matches.as_slice() {
@@ -335,6 +362,23 @@ impl TrialProfileCatalog {
             _ => Err("trial authority unavailable"),
         }
     }
+
+    pub(crate) fn resolve_placement(
+        &self,
+        binding: &TrialPlacementBinding,
+    ) -> Option<&TrialProfile> {
+        // The approved authority catalogue requires distinct exact binding tuples.
+        self.entries.iter().find(|profile| {
+            matches_binding(
+                profile,
+                &binding.registry_entry_id,
+                &binding.registry_entry_digest,
+                &binding.image_digest,
+                &binding.configuration_sha256,
+            ) && profile.profile_digest == binding.profile_digest
+                && profile.projection_digest == binding.projection_digest
+        })
+    }
 }
 
 fn selector_from_profile(profile: &TrialProfile) -> Selector {

From 02b805740263482e9948dcb81889ee17d5ec1f8c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:47:02 +0100
Subject: [PATCH 434/513] Route execution claims through qualified runner
 placement

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  21 ++
 backend/app/adapters/artifacts/__init__.py    |   8 +-
 .../app/adapters/artifacts/trusted_intake.py  |  97 ++++-----
 backend/app/adapters/checkers/__init__.py     |  30 ++-
 .../app/adapters/checkers/external_service.py | 184 ++++++++----------
 backend/app/core/config.py                    |  17 +-
 .../test_delivery_reconciliation_public.py    |  11 +-
 .../checkers/external/test_forge_locator.py   |  23 ++-
 .../checkers/external/test_model_transport.py |  18 +-
 .../checkers/external/test_remote_node.py     | 110 +++++++++--
 .../tests/checkers/external/test_runtime.py   |  78 +++++---
 backend/tests/test_trusted_intake.py          |  89 +++++----
 cli/README.md                                 |   4 +-
 cli/tests/journey/runtime.py                  |  16 +-
 deploy/hosted/README.md                       |  12 +-
 deploy/hosted/compose.yml                     |   8 +-
 deploy/hosted/preflight.py                    |  49 +++--
 deploy/hosted/release.env.example             |   5 +-
 .../run_public_journey_probe.py               |   6 +-
 external_checkers/README.md                   |   9 +
 .../deploy/runner-qualification-20261124.md   |   4 +-
 external_checkers/remote_node.py              |  48 ++++-
 .../terminal_systems_smol_composition.py      |   1 +
 scripts/test_hosted_release_config.py         |  13 ++
 24 files changed, 504 insertions(+), 357 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 77400ffc9..30709e0ce 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12386,3 +12386,24 @@ and one existing matching relay case. A separate eight-case transport run
 passed the closed observations and proved that a wedged TLS read cannot
 extend selection through TLS shutdown. These checks use owned local fixtures
 with no new runtime deployment.
+
+Runtime wiring scope. Replace the active singleton settings with a bounded
+`WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS` JSON set. CHECKERS and ART share the
+transport and keep existing preparation, OAuth, lease, cleanup and retry
+owners. A POST locator and execution on one claim retain the selected node
+and its boot epoch. PRE compares its locked runtime profile and OCI identity.
+ART prepares its lease with the remaining time after selection and TLS. The
+existing mTLS edge uses the native bind frame before the canonical Unix
+request. Hosted configuration, preflight, CLI test transport and paired proof
+read the same endpoint settings. Operator drain requires the authenticated
+native observation and separate edge workspace and inventory checks.
+
+The initial loopback adapter and gateway batch had 75 passes and two fixture
+failures. Both failures were corrected in their existing test owners. One
+fixture now uses a valid approved profile ID and a local callback socket. The
+other makes the leased clock expire after actual PRE response decoding begins.
+A subsequent seven-case run passed both corrections, the typed environment
+read, the same-claim endpoint pin and the private bind rejection. Two hosted
+settings and render cases passed. These results use owned local fixtures and
+leave hardware latency, two-replica and two-node race, reload and drain
+qualification pending. No deployed service was changed.
diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py
index a0b4107d6..6072047a1 100644
--- a/backend/app/adapters/artifacts/__init__.py
+++ b/backend/app/adapters/artifacts/__init__.py
@@ -102,9 +102,7 @@
 def trusted_submission_intake(settings: Settings) -> TrustedSubmissionIntakeAdapter:
     """Register the sole ART capability provider with explicit pinned identity."""
     if any(value is None for value in (
-        settings.external_runner_host,
-        settings.external_runner_port,
-        settings.external_runner_server_name,
+        settings.external_runner_endpoints,
         settings.external_runner_ca_path,
         settings.external_runner_certificate_path,
         settings.external_runner_private_key_path,
@@ -114,9 +112,7 @@ def trusted_submission_intake(settings: Settings) -> TrustedSubmissionIntakeAdap
         raise ExternalServiceConfigurationError()
     factory = ExternalServiceAdapterFactory[TrustedSubmissionIntakeAdapter](CAPABILITY)
     factory.register(PROVIDER, lambda: RemoteTlsTrustedIntakeAdapter(
-        host=settings.external_runner_host,
-        port=settings.external_runner_port,
-        server_name=settings.external_runner_server_name,
+        endpoints=settings.external_runner_endpoints,
         ca_path=settings.external_runner_ca_path,
         certificate_path=settings.external_runner_certificate_path,
         private_key_path=settings.external_runner_private_key_path,
diff --git a/backend/app/adapters/artifacts/trusted_intake.py b/backend/app/adapters/artifacts/trusted_intake.py
index 7d0f5433e..eaa1e8fed 100644
--- a/backend/app/adapters/artifacts/trusted_intake.py
+++ b/backend/app/adapters/artifacts/trusted_intake.py
@@ -19,6 +19,8 @@
 from pydantic import TypeAdapter
 
 from app.core.cancellation import await_cancellation_resistant
+from app.core.runner_endpoints import ExternalRunnerEndpoints
+from app.adapters.runner import RunnerPlacement, RunnerReadiness, RunnerTransport
 from workstream_external_services import (
     ExternalServiceAdapterIdentity,
     ExternalServiceProtocolError,
@@ -93,9 +95,7 @@ class RemoteTlsTrustedIntakeAdapter:
     def __init__(
         self,
         *,
-        host: str,
-        port: int,
-        server_name: str,
+        endpoints: ExternalRunnerEndpoints,
         ca_path: Path,
         certificate_path: Path,
         private_key_path: Path,
@@ -103,44 +103,13 @@ def __init__(
         config_digest: str,
     ) -> None:
         """Bind a pinned TLS identity to operator-pinned image and config identities."""
-        if (
-            type(host) is not str
-            or not host
-            or len(host) > 255
-            or type(port) is not int
-            or not 1 <= port <= 65_535
-            or type(server_name) is not str
-            or not server_name
-            or len(server_name) > 255
-            or any(not path.is_absolute() or path.is_symlink() for path in (
-                ca_path, certificate_path, private_key_path
-            ))
-            or any(
-                type(v) is not str or re.fullmatch(r"sha256:[0-9a-f]{64}", v) is None
-                for v in (image_digest, config_digest)
-            )
-        ):
+        if any(type(v) is not str or re.fullmatch(r"sha256:[0-9a-f]{64}", v) is None
+               for v in (image_digest, config_digest)):
             raise ValueError("trusted intake configuration invalid")
-        self._host, self._port, self._server_name = host, port, server_name
-        self._ca_path = ca_path
-        self._certificate_path = certificate_path
-        self._private_key_path = private_key_path
+        self._transport = RunnerTransport(endpoints, ca_path, certificate_path, private_key_path)
         self._image = image_digest
         self._config = config_digest
 
-    def _tls_context(self) -> ssl.SSLContext:
-        context = ssl.create_default_context(
-            ssl.Purpose.SERVER_AUTH,
-            cafile=str(self._ca_path),
-        )
-        context.minimum_version = ssl.TLSVersion.TLSv1_3
-        context.check_hostname = True
-        context.load_cert_chain(
-            certfile=str(self._certificate_path),
-            keyfile=str(self._private_key_path),
-        )
-        return context
-
     @property
     def identity(self) -> ExternalServiceAdapterIdentity:
         """Identify this typed capability and its explicitly registered provider."""
@@ -163,17 +132,32 @@ def _validate_identity(self, raw: object) -> TrustedIntakeIdentity:
 
     async def health(self) -> TrustedIntakeIdentity:
         """Check the pinned node identity without reserving a VM."""
-        session = _Session(self, time.monotonic() + 10)
-        try:
-            return await session._async(session._health)
-        finally:
-            session.abort()
+        placement = await self._transport.select("trusted_intake", qualifies=self._qualifies)
+        if placement is None or placement.readiness.intake is None:
+            raise ExternalServiceUnavailableError(self.identity)
+        return placement.readiness.intake
+
+    def _qualifies(self, readiness: RunnerReadiness) -> bool:
+        intake = readiness.intake
+        return intake is not None and (intake.image_digest, intake.config_digest) == (self._image, self._config)
 
     async def prepare(self, request: TrustedIntakePreparation) -> _Session:
         """Acquire one lease within the original deadline and abort failed preparation."""
         if type(request) is not TrustedIntakePreparation:
             raise ExternalServiceProtocolError(self.identity)
-        session = _Session(self, time.monotonic() + request.deadline_ms / 1000, request)
+        duration = request.deadline_ms / 1000
+        deadline = time.monotonic() + duration
+        try:
+            async with asyncio.timeout(duration):
+                placement = await self._transport.select(
+                    f"{request.phase}:{request.policy_sha256}:{request.archive_byte_count}",
+                    qualifies=self._qualifies, demand={"kind": "intake", "preparation": asdict(request)},
+                )
+        except TimeoutError as exc:
+            raise ExternalServiceUnavailableError(self.identity) from exc
+        if placement is None:
+            raise ExternalServiceUnavailableError(self.identity)
+        session = _Session(self, deadline, placement, request)
         try:
             await session._async(session._prepare)
             return session
@@ -189,11 +173,13 @@ def __init__(
         self,
         adapter: RemoteTlsTrustedIntakeAdapter,
         deadline: float,
-        request: TrustedIntakePreparation | None = None,
+        placement: RunnerPlacement,
+        request: TrustedIntakePreparation,
     ) -> None:
         """Own one socket, deadline and serialized state machine for this lease."""
         self._adapter = adapter
         self._deadline = deadline
+        self._placement = placement
         self._request = request
         self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self._lock = threading.Lock()
@@ -321,16 +307,20 @@ def _connect(self) -> None:
         """Connect only to the authenticated runner within the lease deadline."""
         self._timeout()
         try:
-            self._socket.connect((self._adapter._host, self._adapter._port))
-            self._socket = self._adapter._tls_context().wrap_socket(
+            endpoint = self._placement.endpoint
+            transport = self._adapter._transport
+            self._socket.connect((endpoint.host, endpoint.port))
+            self._socket = transport.tls_context().wrap_socket(
                 self._socket,
-                server_hostname=self._adapter._server_name,
+                server_hostname=endpoint.server_name,
             )
+            transport.require_peer(self._socket, endpoint)
             control = json.dumps(
                 {
                     "protocol_version": _REMOTE_PROTOCOL,
                     "operation": "proxy",
                     "capability": CAPABILITY,
+                    **self._placement.binding(),
                 },
                 separators=(",", ":"),
             ).encode()
@@ -338,18 +328,17 @@ def _connect(self) -> None:
         except (OSError, ssl.SSLError) as exc:
             raise ExternalServiceUnavailableError(self._adapter.identity) from exc
 
-    def _health(self) -> TrustedIntakeIdentity:
-        """Read and verify the node identity on a temporary health connection."""
-        self._connect()
-        self._command("health", {})
-        return self._adapter._validate_identity(self._response("health"))
-
     def _prepare(self) -> None:
         """Accept the boot-scoped lease only after the node confirms readiness."""
         with self._lock:
             self._connect()
-            self._command("prepare", asdict(self._request))
+            remaining_ms = int((self._deadline - time.monotonic()) * 1000)
+            if remaining_ms <= 0:
+                raise ExternalServiceUnavailableError(self._adapter.identity)
+            self._command("prepare", asdict(self._request) | {"deadline_ms": remaining_ms})
             self._identity = self._adapter._validate_identity(self._response("prepare"))
+            if self._identity != self._placement.readiness.intake:
+                raise ExternalServiceProtocolError(self._adapter.identity)
             self._state = "prepared"
 
     def inspect(
diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py
index 95df6d315..24d075c62 100644
--- a/backend/app/adapters/checkers/__init__.py
+++ b/backend/app/adapters/checkers/__init__.py
@@ -55,9 +55,7 @@ def revision_feedback_port(session) -> RevisionFeedbackPort:
 
 def external_checker_execution_factory(
     *,
-    host: str,
-    port: int,
-    server_name: str,
+    endpoints,
     ca_path: Path,
     certificate_path: Path,
     private_key_path: Path,
@@ -72,9 +70,7 @@ def external_checker_execution_factory(
     factory.register(
         EXTERNAL_CHECKER_PROVIDER_KEY,
         lambda: RemoteTlsExternalCheckerAdapter(
-            host=host,
-            port=port,
-            server_name=server_name,
+            endpoints=endpoints,
             ca_path=ca_path,
             certificate_path=certificate_path,
             private_key_path=private_key_path,
@@ -160,18 +156,14 @@ def openrouter_provider():
 def configured_external_checker_execution_factory(settings):
     """Map configured image-execution settings into the sole adapter factory."""
     if (
-        settings.external_runner_host is None
-        or settings.external_runner_port is None
-        or settings.external_runner_server_name is None
+        settings.external_runner_endpoints is None
         or settings.external_runner_ca_path is None
         or settings.external_runner_certificate_path is None
         or settings.external_runner_private_key_path is None
     ):
         raise ValueError("external checker service is not configured")
     return external_checker_execution_factory(
-        host=settings.external_runner_host,
-        port=settings.external_runner_port,
-        server_name=settings.external_runner_server_name,
+        endpoints=settings.external_runner_endpoints,
         ca_path=settings.external_runner_ca_path,
         certificate_path=settings.external_runner_certificate_path,
         private_key_path=settings.external_runner_private_key_path,
@@ -185,6 +177,7 @@ class _ConfiguredExternalCheckerExecution:
 
     def __init__(self, settings) -> None:
         self._settings = settings
+        self._adapter: ExternalCheckerExecutionAdapter | None = None
         self._identity = ExternalServiceAdapterIdentity(
             EXTERNAL_CHECKER_CAPABILITY_KEY,
             EXTERNAL_CHECKER_PROVIDER_KEY,
@@ -202,14 +195,13 @@ def pre_runtime_provider(self) -> Literal["smolvm", "managed"]:
 
     def _resolve(self) -> ExternalCheckerExecutionAdapter:
         """Create the fixed provider or report absent runtime configuration."""
-        if (
-            self._settings.external_runner_host is None
-            and self._settings.external_runner_port is None
-        ):
+        if self._settings.external_runner_endpoints is None:
             raise ExternalServiceUnavailableError(self._identity)
-        return configured_external_checker_execution_factory(self._settings).create(
-            EXTERNAL_CHECKER_PROVIDER_KEY
-        )
+        if self._adapter is None:
+            self._adapter = configured_external_checker_execution_factory(self._settings).create(
+                EXTERNAL_CHECKER_PROVIDER_KEY
+            )
+        return self._adapter
 
     async def execute_pre(self, lease, grant):
         """Resolve the same provider for the source-bound single PRE session."""
diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index cb6e00a28..3824c8d5d 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -10,11 +10,13 @@
 from datetime import datetime, timezone
 from pathlib import Path
 import re
-import ssl
 import struct
 from typing import Literal
 
 from app.core.cancellation import await_cancellation_resistant
+from app.core.hashing import canonical_json_hash
+from app.core.runner_endpoints import ExternalRunnerEndpoints
+from app.adapters.runner import RunnerPlacement, RunnerTransport
 
 from app.interfaces.external_checker_execution import (
     ExternalCheckerExecutionOutcomeUnknown,
@@ -49,6 +51,8 @@
     ExternalCheckerForgeLocator,
     require_forge_locator_request,
 )
+from app.modules.checkers.api.external_policy import validated_trial_configuration
+from app.modules.checkers.api.model_profiles import configured_model_profile_selector
 
 EXTERNAL_CHECKER_CAPABILITY_KEY = "external_checker_execution"
 EXTERNAL_CHECKER_PROVIDER_KEY = "remote_tls"
@@ -65,9 +69,7 @@ class RemoteTlsExternalCheckerAdapter:
     def __init__(
         self,
         *,
-        host: str,
-        port: int,
-        server_name: str,
+        endpoints: ExternalRunnerEndpoints,
         ca_path: Path,
         certificate_path: Path,
         private_key_path: Path,
@@ -77,28 +79,16 @@ def __init__(
     ) -> None:
         """Validate immutable endpoint settings without opening a connection."""
         if (
-            type(host) is not str
-            or not host
-            or len(host) > 255
-            or type(port) is not int
-            or not 1 <= port <= 65_535
-            or type(server_name) is not str
-            or not server_name
-            or len(server_name) > 255
-            or any(not path.is_absolute() or path.is_symlink() for path in (
-                ca_path, certificate_path, private_key_path
-            ))
-            or model_proxy_socket_path is not None
+            model_proxy_socket_path is not None
             and (not model_proxy_socket_path.is_absolute() or model_proxy_socket_path.is_symlink())
             or type(timeout_seconds) is not float
             or not 0.1 <= timeout_seconds <= 3_700.0
         ):
             raise ValueError("external checker service configuration is invalid")
         self._source_contracts = source_contracts
-        self._host, self._port, self._server_name = host, port, server_name
-        self._ca_path = ca_path
-        self._certificate_path = certificate_path
-        self._private_key_path = private_key_path
+        self._transport = RunnerTransport(endpoints, ca_path, certificate_path, private_key_path)
+        self._post_claim: tuple | None = None
+        self._post_placement: RunnerPlacement | None = None
         self._model_proxy_socket_path = model_proxy_socket_path
         self._timeout_seconds = timeout_seconds
         self._identity = ExternalServiceAdapterIdentity(
@@ -116,26 +106,8 @@ def pre_runtime_provider(self) -> Literal["smolvm"]:
         """The dedicated native node accepts only Smol runtime evidence."""
         return "smolvm"
 
-    def _tls_context(self) -> ssl.SSLContext:
-        context = ssl.create_default_context(
-            ssl.Purpose.SERVER_AUTH,
-            cafile=str(self._ca_path),
-        )
-        context.minimum_version = ssl.TLSVersion.TLSv1_3
-        context.check_hostname = True
-        context.load_cert_chain(
-            certfile=str(self._certificate_path),
-            keyfile=str(self._private_key_path),
-        )
-        return context
-
-    async def _open(self) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
-        return await asyncio.open_connection(
-            self._host,
-            self._port,
-            ssl=self._tls_context(),
-            server_hostname=self._server_name,
-        )
+    async def _open(self, placement: RunnerPlacement) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
+        return await self._transport.open(placement.endpoint)
 
     @staticmethod
     async def _send_frame(writer: asyncio.StreamWriter, payload: bytes) -> None:
@@ -144,17 +116,23 @@ async def _send_frame(writer: asyncio.StreamWriter, payload: bytes) -> None:
         writer.write(struct.pack(">I", len(payload)) + payload)
         await writer.drain()
 
-    async def _proxy_connection(self) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
-        reader, writer = await self._open()
+    async def _proxy_connection(self, placement: RunnerPlacement) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
+        reader, writer = await self._open(placement)
         control = json.dumps(
             {
                 "protocol_version": _REMOTE_PROTOCOL,
                 "operation": "proxy",
                 "capability": EXTERNAL_CHECKER_CAPABILITY_KEY,
+                **placement.binding(),
             },
             separators=(",", ":"),
         ).encode()
-        await self._send_frame(writer, control)
+        try:
+            await self._send_frame(writer, control)
+        except BaseException:
+            writer.close()
+            await await_cancellation_resistant(writer.wait_closed())
+            raise
         return reader, writer
 
     @staticmethod
@@ -198,7 +176,17 @@ async def execute_pre(
                 raise SelectedPreSubmitInfrastructureUnavailable("deadline_exceeded")
             deadline = asyncio.get_running_loop().time() + timeout
             async with asyncio.timeout_at(deadline):
-                reader, writer = await self._proxy_connection()
+                image_digest = reservation.policy.entries[0].registry.image_digest
+                profile_sha256 = canonical_json_hash(reservation.runtime_profile.model_dump(mode="json"))
+                placement = await self._transport.select(
+                    str(reservation.attempt_id), demand={"kind": "pre", "source_bytes": reservation.source.raw_byte_count},
+                    qualifies=lambda state: state.image(image_digest) is not None
+                    and state.pre is not None and state.pre.profile_sha256 == profile_sha256
+                    and state.pre.root_sha256 == reservation.runtime_profile.platform_root_sha256,
+                )
+                if placement is None:
+                    raise ExternalServiceUnavailableError(self._identity)
+                reader, writer = await self._proxy_connection(placement)
                 try:
                     writer.write(struct.pack(">I", len(payload)) + payload)
                     await writer.drain()
@@ -237,6 +225,8 @@ async def execute_pre(
             result = SelectedPreSubmitInvocationResult.from_canonical_body(body, source_contracts=self._source_contracts)
             if result.receipt.runtime.provider != "smolvm":
                 raise ValueError("PRE runtime provider differs")
+            if result.receipt.invocation.config_image_id != placement.readiness.image(image_digest).config_image_id:
+                raise ValueError("PRE image configuration differs from placement")
             result.validate_lease(lease, source_contracts=self._source_contracts)
             if (asyncio.get_running_loop().time() >= deadline
                     or datetime.now(timezone.utc) >= lease.lease_expires_at):
@@ -267,6 +257,42 @@ async def locate_forge_change(self, request, grant) -> ExternalCheckerForgeLocat
         """Use the same bounded transport without issuing model or trial authority."""
         return await self._exchange(request, grant, model_grant=None, locate=True)
 
+    async def _place_post(
+        self, request: ExternalCheckerExecutionRequest, *, with_model_grant: bool,
+    ) -> RunnerPlacement:
+        identity = request.identity
+        claim = (identity.attempt_id, identity.lease_id, identity.lease_generation)
+        registry = request.registry
+        trial = validated_trial_configuration(request.configuration, registry)
+        callbacks = with_model_grant or trial is not None or configured_model_profile_selector(
+            request.configuration, stage=identity.phase,
+        ) is not None
+        if callbacks and (self._model_proxy_socket_path is None or not self._model_proxy_socket_path.is_socket()):
+            raise ExternalServiceUnavailableError(self._identity)
+        if self._post_placement is not None:
+            if (self._post_claim != claim
+                    or self._post_placement.readiness.image(request.registry.image_digest) is None
+                    or callbacks and not self._post_placement.readiness.callback_relay):
+                raise ValueError("external checker adapter is bound to another claim")
+            return self._post_placement
+
+        trial_binding = None if trial is None else {
+            "registry_entry_id": str(registry.registry_entry_id), "registry_entry_digest": registry.entry_digest,
+            "image_digest": registry.image_digest, "configuration_sha256": request.configuration_sha256,
+            "profile_digest": trial.profile.profile_digest, "projection_digest": trial.projection.projection_digest,
+        }
+        placement = await self._transport.select(
+            str(identity.attempt_id), demand={"kind": "post", "memory_bytes": registry.resources.memory_bytes,
+                                             "trial": trial_binding},
+            qualifies=lambda state: state.image(registry.image_digest) is not None
+            and (not callbacks or state.callback_relay)
+            and (trial is None or state.trial_authority_manifest_sha256 is not None),
+        )
+        if placement is None:
+            raise ExternalServiceUnavailableError(self._identity)
+        self._post_claim, self._post_placement = claim, placement
+        return placement
+
     async def _exchange(self, request, grant, *, model_grant, locate):
         """Exchange one bounded request and revalidate every returned fact."""
         possibly_invoked = False
@@ -312,7 +338,8 @@ async def _exchange(self, request, grant, *, model_grant, locate):
             if self._timeout_seconds < required_timeout:
                 raise ExternalServiceUnavailableError(self._identity)
             async with asyncio.timeout(self._timeout_seconds):
-                reader, writer = await self._open()
+                placement = await self._place_post(checked, with_model_grant=model_grant is not None)
+                reader, writer = await self._open(placement)
                 try:
                     manifest = grant.source.manifest
                     files = grant.source.files
@@ -334,6 +361,7 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                             "manifest_byte_count": len(manifest),
                             "file_count": len(files),
                             "total_byte_count": total_bytes,
+                            **placement.binding(),
                         },
                         ensure_ascii=False,
                         allow_nan=False,
@@ -423,6 +451,10 @@ async def _exchange(self, request, grant, *, model_grant, locate):
             )
             if isolation is not None and (
                 isolation.platform_manifest_digest != checked.registry.image_digest
+                or isolation.config_image_id != placement.readiness.image(checked.registry.image_digest).config_image_id
+                or any(getattr(isolation, field) != getattr(placement.readiness.health, field) for field in (
+                    "operating_system", "architecture", "runtime", "isolation_mode", "sandbox_uid", "sandbox_gid",
+                ))
             ):
                 raise ValueError("external checker isolation receipt is invalid")
             if (locator or result.outcome == "completed") and isolation is None:
@@ -441,63 +473,11 @@ async def _exchange(self, request, grant, *, model_grant, locate):
             raise
 
     async def health(self) -> ExternalCheckerServiceHealth:
-        """Require the service to recheck its configured engine and report readiness."""
-        payload = json.dumps(
-            {"protocol_version": _PROTOCOL, "operation": "health"},
-            separators=(",", ":"),
-        ).encode("utf-8")
-        try:
-            async with asyncio.timeout(self._timeout_seconds):
-                reader, writer = await self._proxy_connection()
-                try:
-                    writer.write(struct.pack(">I", len(payload)) + payload)
-                    await writer.drain()
-                    size = struct.unpack(">I", await reader.readexactly(4))[0]
-                    if size == 0 or size > 16_384:
-                        raise ExternalServiceProtocolError(self._identity)
-                    raw = await reader.readexactly(size)
-                    if await reader.read(1):
-                        raise ExternalServiceProtocolError(self._identity)
-                finally:
-                    writer.close()
-                    await writer.wait_closed()
-        except ExternalServiceProtocolError:
-            raise
-        except (TimeoutError, OSError, asyncio.IncompleteReadError) as exc:
-            raise ExternalServiceUnavailableError(self._identity) from exc
-        try:
-            body = json.loads(raw)
-            expected = {
-                "protocol_version",
-                "operation",
-                "status",
-                "operating_system",
-                "architecture",
-                "runtime",
-                "isolation_mode",
-                "cached_platform_manifests",
-                "sandbox_uid",
-                "sandbox_gid",
-            }
-            if (
-                type(body) is not dict
-                or set(body) != expected
-                or body["protocol_version"] != _PROTOCOL
-                or body["operation"] != "health"
-                or body["status"] != "ready"
-            ):
-                raise ValueError("external checker health response is invalid")
-            return ExternalCheckerServiceHealth(
-                operating_system=body["operating_system"],
-                architecture=body["architecture"],
-                runtime=body["runtime"],
-                isolation_mode=body["isolation_mode"],
-                cached_platform_manifests=body["cached_platform_manifests"],
-                sandbox_uid=body["sandbox_uid"],
-                sandbox_gid=body["sandbox_gid"],
-            )
-        except (TypeError, ValueError, UnicodeError, json.JSONDecodeError) as exc:
-            raise ExternalServiceProtocolError(self._identity) from exc
+        """Return authenticated readiness from one qualified configured node."""
+        placement = await self._transport.select("health", qualifies=lambda _state: True)
+        if placement is None:
+            raise ExternalServiceUnavailableError(self._identity)
+        return placement.readiness.health
 
 
 __all__ = (
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index b8e9483f1..b94bb6591 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -30,6 +30,7 @@
     is_canonical_s3_prefix,
     is_canonical_s3_region,
 )
+from app.core.runner_endpoints import ExternalRunnerEndpoints
 from app.interfaces.forge_facts import FORGE_FACTS_MAXIMUM_READ_SECONDS
 from app.interfaces.project_guide_runtime import (
     AdapterProfileValue,
@@ -262,9 +263,7 @@ class Settings(BaseSettings):
     submission_source_cleanup_profile: dict[str, object] | None = None
     artifact_intake_image_digest: str | None = None
     artifact_intake_config_digest: str | None = None
-    external_runner_host: str | None = None
-    external_runner_port: int | None = Field(default=None, ge=1, le=65_535)
-    external_runner_server_name: str | None = None
+    external_runner_endpoints: ExternalRunnerEndpoints | None = None
     external_runner_ca_path: Path | None = None
     external_runner_certificate_path: Path | None = None
     external_runner_private_key_path: Path | None = None
@@ -704,9 +703,7 @@ def validate_artifact_storage(self) -> Settings:
                     "artifact scratch and durable local storage roots must be separate"
                 )
         external_values = (
-            self.external_runner_host,
-            self.external_runner_port,
-            self.external_runner_server_name,
+            self.external_runner_endpoints,
             self.external_runner_ca_path,
             self.external_runner_certificate_path,
             self.external_runner_private_key_path,
@@ -714,13 +711,7 @@ def validate_artifact_storage(self) -> Settings:
         if any(value is not None for value in external_values):
             if any(value is None for value in external_values):
                 raise ValueError("external runner TLS settings must be complete")
-            assert self.external_runner_host is not None
-            assert self.external_runner_server_name is not None
-            if not self.external_runner_host or len(self.external_runner_host) > 255:
-                raise ValueError("external runner host is invalid")
-            if not self.external_runner_server_name or len(self.external_runner_server_name) > 255:
-                raise ValueError("external runner server name is invalid")
-            for path in external_values[3:]:
+            for path in external_values[1:]:
                 assert isinstance(path, Path)
                 if not path.is_absolute():
                     raise ValueError("external runner TLS paths must be absolute")
diff --git a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
index 957ab7db7..6c1ceaf2a 100644
--- a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
+++ b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
@@ -38,7 +38,7 @@
 )
 from tests.tasks.evaluation_delivery.support import delivery_fixture, invoked, outcome, state
 from tests.checkers.execution.support import ControlledSelectedExecution
-from tests.checkers.external.test_remote_node import _read_frame, remote_adapter_endpoint
+from tests.checkers.external.test_remote_node import fixture_placement, read_fixture_native_request, remote_adapter_endpoint
 from tests.tasks.post_submit_routing.outcome_support import (
     apply_outcome,
     authorized_routing_source,
@@ -423,8 +423,7 @@ async def test_public_operator_retries_proven_no_effect_request_once(
 
         settings = h.settings.model_copy(
             update={
-                "external_runner_host": None,
-                "external_runner_port": None,
+                "external_runner_endpoints": None,
             }
         )
         monkeypatch.setattr("app.core.config.get_settings", lambda: settings)
@@ -809,7 +808,11 @@ async def test_public_operator_projects_uncertain_child_as_permanently_held(
 
         async def receive_without_result(reader, writer):
             try:
-                received.append(json.loads(await _read_frame(reader)))
+                observed = await read_fixture_native_request(
+                    reader, writer, fixture_placement(h.request.policy.entries[0].registry.image_digest),
+                )
+                if observed is not None:
+                    received.append(observed)
             finally:
                 writer.close()
                 await writer.wait_closed()
diff --git a/backend/tests/checkers/external/test_forge_locator.py b/backend/tests/checkers/external/test_forge_locator.py
index 9a0c4ef96..55376061f 100644
--- a/backend/tests/checkers/external/test_forge_locator.py
+++ b/backend/tests/checkers/external/test_forge_locator.py
@@ -13,6 +13,7 @@
 
 from app.adapters.checkers import external_checker_execution_factory
 from app.adapters.checkers.model_execution import ModelAwareExternalExecution
+from app.core.identifiers import new_record_id
 from app.interfaces.external_checker_execution import ExternalCheckerExecutionOutcomeUnknown
 from workstream_external_services import ExternalServiceProtocolError
 from app.modules.checkers.api.external import (
@@ -67,7 +68,7 @@ def _request(*, locate=True, maximum_output_bytes=32768, output_document=None, m
     configuration = {"workstream_forge_facts_version": "v1"}
     if model:
         configuration.update(
-            model_profile_id=str(uuid4()), model_profile_version=1, model_profile_digest=SHA
+            model_profile_id=str(new_record_id()), model_profile_version=1, model_profile_digest=SHA
         )
     inputs = {"task_version": "v1"}
     if locate:
@@ -119,10 +120,10 @@ def _isolation(request):
         operating_system="linux",
         architecture="amd64",
         config_image_id=SHA,
-        runtime="runc",
-        isolation_mode="docker-dev",
-        sandbox_uid=65532,
-        sandbox_gid=65532,
+        runtime="smolvm",
+        isolation_mode="smol-microvm",
+        sandbox_uid=10001,
+        sandbox_gid=10001,
     )
 
 
@@ -133,8 +134,12 @@ async def _service(tmp_path, request, result, *, isolation=True):
 
     async def handle(reader, writer):
         try:
-            size = struct.unpack(">I", await reader.readexactly(4))[0]
-            received.append(json.loads(await reader.readexactly(size)))
+            observed = await read_fixture_native_request(
+                reader, writer, fixture_placement(request.registry.image_digest, SHA, callback_relay=True),
+            )
+            if observed is None:
+                return
+            received.append(observed)
             body = json.dumps(
                 dict(
                     protocol_version="external_checker_service.v1",
@@ -151,10 +156,10 @@ async def handle(reader, writer):
             await writer.wait_closed()
 
     server = await asyncio.start_unix_server(handle, socket)
-    from tests.checkers.external.test_remote_node import remote_adapter_endpoint
+    from tests.checkers.external.test_remote_node import fixture_placement, read_fixture_native_request, remote_adapter_endpoint
 
     try:
-        async with remote_adapter_endpoint(tmp_path, socket) as endpoint:
+        async with remote_adapter_endpoint(tmp_path, socket, model_proxy_socket_path=socket) as endpoint:
             yield (
                 external_checker_execution_factory(
                     **endpoint,
diff --git a/backend/tests/checkers/external/test_model_transport.py b/backend/tests/checkers/external/test_model_transport.py
index edcc2f781..c5cb84d27 100644
--- a/backend/tests/checkers/external/test_model_transport.py
+++ b/backend/tests/checkers/external/test_model_transport.py
@@ -58,8 +58,12 @@ async def test_model_selector_is_outside_image_request(tmp_path):
 
     async def handle(reader, writer):
         try:
-            size = struct.unpack(">I", await reader.readexactly(4))[0]
-            received.set_result(json.loads(await reader.readexactly(size)))
+            observed = await read_fixture_native_request(
+                reader, writer, fixture_placement(value.registry.image_digest, callback_relay=True),
+            )
+            if observed is None:
+                return
+            received.set_result(observed)
             body = json.dumps({
                 "protocol_version": "external_checker_service.v1",
                 "result": result.model_dump(mode="json"),
@@ -73,10 +77,10 @@ async def handle(reader, writer):
 
     path = tmp_path / "checker.sock"
     server = await asyncio.start_unix_server(handle, path)
-    from tests.checkers.external.test_remote_node import remote_adapter_endpoint
+    from tests.checkers.external.test_remote_node import fixture_placement, read_fixture_native_request, remote_adapter_endpoint
 
     try:
-        async with remote_adapter_endpoint(tmp_path, path) as endpoint:
+        async with remote_adapter_endpoint(tmp_path, path, model_proxy_socket_path=path) as endpoint:
             adapter = external_checker_execution_factory(
                 **endpoint, timeout_seconds=90.0,
             ).create("remote_tls")
@@ -104,13 +108,11 @@ async def test_wrong_phase_or_request_cannot_open_model_transport(tmp_path, monk
     value = request(phase)
     connect = AsyncMock()
     monkeypatch.setattr(asyncio, "open_connection", connect)
-    from tests.checkers.external.test_remote_node import _certificate_files
+    from tests.checkers.external.test_remote_node import _certificate_files, fixture_runner_endpoints
 
     certificates = _certificate_files(tmp_path)
     adapter = external_checker_execution_factory(
-        host="127.0.0.1",
-        port=1,
-        server_name="runner.test",
+        endpoints=fixture_runner_endpoints(),
         ca_path=certificates["ca"],
         certificate_path=certificates["client_certificate"],
         private_key_path=certificates["client_key"],
diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py
index b2cef011f..98948bc7f 100644
--- a/backend/tests/checkers/external/test_remote_node.py
+++ b/backend/tests/checkers/external/test_remote_node.py
@@ -111,6 +111,41 @@ def _placement_body():
     }
 
 
+def fixture_runner_endpoints(port=1, *, config_sha256=None):
+    from app.core.runner_endpoints import ExternalRunnerEndpoints
+
+    return ExternalRunnerEndpoints.model_validate([{
+        "host": "127.0.0.1", "port": port, "server_name": "runner.test",
+        "config_sha256": config_sha256 or _placement_body()["config_sha256"],
+    }])
+
+
+def fixture_placement(image_digest=None, config_image_id=None, **changes):
+    data = _placement_body() | changes
+    if image_digest is not None:
+        data["images"][0]["platform_manifest_digest"] = image_digest
+    if config_image_id is not None:
+        data["images"][0]["config_image_id"] = config_image_id
+    return data
+
+
+async def read_fixture_native_request(reader, writer, placement):
+    """Distinguish the read-only native projection from one epoch-bound execution."""
+    control = json.loads(await _read_frame(reader))
+    if control["operation"] == "placement":
+        assert set(control) == {"protocol_version", "operation", "demand"}
+        assert control["protocol_version"] == "external_checker_service.v1"
+        body = placement | {"fits_admission": None if control["demand"] is None else True}
+        writer.write(_frame(json.dumps(body).encode()))
+        await writer.drain()
+        return None
+    assert control == {
+        "protocol_version": "external_checker_service.v1", "operation": "bind_epoch",
+        "config_sha256": placement["config_sha256"], "epoch": placement["epoch"],
+    }
+    return json.loads(await _read_frame(reader))
+
+
 def test_external_runner_endpoint_set_is_closed_and_unique():
     from pydantic import ValidationError
 
@@ -247,6 +282,41 @@ async def no_result(*_args):
     writer.wait_closed.assert_not_awaited()
 
 
+@pytest.mark.asyncio
+async def test_post_claim_pins_first_runner_epoch(tmp_path, monkeypatch):
+    from unittest.mock import AsyncMock
+
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
+    from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter
+    from app.adapters.runner import RunnerPlacement, RunnerReadiness, RunnerTransport
+    from tests.checkers.external.test_model_transport import request
+    from workstream_external_services import ExternalServiceUnavailableError
+
+    value = request()
+    endpoints = fixture_runner_endpoints()
+    observed = RunnerReadiness.model_validate_json(json.dumps(fixture_placement(
+        value.registry.image_digest, fits_admission=True,
+    )))
+    first = RunnerPlacement(endpoints.root[0], observed)
+    restarted = RunnerPlacement(endpoints.root[0], observed.model_copy(update={"epoch": "a" * 64}))
+    select = AsyncMock(side_effect=[first, restarted])
+    monkeypatch.setattr(RunnerTransport, "select", select)
+    adapter = RemoteTlsExternalCheckerAdapter(
+        endpoints=endpoints, ca_path=tmp_path / "ca.pem", certificate_path=tmp_path / "client.pem",
+        private_key_path=tmp_path / "key.pem", model_proxy_socket_path=None, timeout_seconds=90.0,
+        source_contracts=selected_pre_submit_source_contracts(),
+    )
+    with pytest.raises(ExternalServiceUnavailableError):
+        await adapter._place_post(value, with_model_grant=True)
+    select.assert_not_awaited()
+    assert await adapter._place_post(value, with_model_grant=False) is first
+    assert await adapter._place_post(value, with_model_grant=False) is first
+    assert select.await_count == 1
+    with pytest.raises(ValueError, match="bound to another claim"):
+        await adapter._place_post(request(), with_model_grant=False)
+    assert select.await_count == 1
+
+
 @asynccontextmanager
 async def remote_adapter_endpoint(
     tmp_path: Path,
@@ -256,6 +326,7 @@ async def remote_adapter_endpoint(
     material_root: Path | None = None,
     native_model_proxy_socket_path: Path | None = None,
     session_timeout_seconds: float = 10.0,
+    config_sha256: str | None = None,
 ):
     """Expose one test-native service with explicit finite owner roots/windows."""
     certificates = _certificate_files(tmp_path)
@@ -286,9 +357,7 @@ async def remote_adapter_endpoint(
             node.handle, "127.0.0.1", 0, ssl=node.ssl_context
         )
         yield {
-            "host": "127.0.0.1",
-            "port": remote.sockets[0].getsockname()[1],
-            "server_name": "runner.test",
+            "endpoints": fixture_runner_endpoints(remote.sockets[0].getsockname()[1], config_sha256=config_sha256),
             "ca_path": certificates["ca"],
             "certificate_path": certificates["client_certificate"],
             "private_key_path": certificates["client_key"],
@@ -343,7 +412,11 @@ async def app(reader, writer):
                 await writer.wait_closed()
         async def native(reader, writer):
             try:
-                wire = json.loads(await _read_frame(reader))
+                wire = await read_fixture_native_request(
+                    reader, writer, fixture_placement(value.registry.image_digest, callback_relay=True),
+                )
+                if wire is None:
+                    return
                 grant_id = wire["grant"]["grant_id"]
                 assert (material / "workspaces" / grant_id).is_dir()
                 assert wire["model_grant"]["grant_id"] == "model_" + "a" * 32
@@ -394,13 +467,14 @@ async def test_remote_post_failure_preserves_possible_invocation(tmp_path, monke
 
     from app.adapters.artifacts import selected_pre_submit_source_contracts
     from app.adapters.checkers.external_service import RemoteTlsExternalCheckerAdapter
+    from app.adapters.runner import RunnerPlacement, RunnerReadiness, RunnerTransport
     from app.interfaces.external_checker_execution import ExternalCheckerExecutionOutcomeUnknown
     from tests.checkers.external.support import empty_external_material_grant
     from tests.checkers.external.test_model_transport import request
     from workstream_external_services import ExternalServiceUnavailableError
 
     adapter = RemoteTlsExternalCheckerAdapter(
-        host="127.0.0.1", port=1, server_name="runner.test",
+        endpoints=fixture_runner_endpoints(),
         ca_path=tmp_path / "ca.pem", certificate_path=tmp_path / "client.pem",
         private_key_path=tmp_path / "key.pem", model_proxy_socket_path=None,
         timeout_seconds=90.0, source_contracts=selected_pre_submit_source_contracts(),
@@ -427,6 +501,10 @@ async def interrupt_read(_size):
     reader.feed_eof()
 
     value = request()
+    placement = RunnerPlacement(adapter._transport.endpoints.root[0], RunnerReadiness.model_validate_json(
+        json.dumps(fixture_placement(value.registry.image_digest, fits_admission=True)),
+    ))
+    monkeypatch.setattr(RunnerTransport, "select", AsyncMock(return_value=placement))
     task = asyncio.create_task(adapter.execute(value, empty_external_material_grant(value, suffix="c")))
     if fault == "cancel":
         await asyncio.wait_for(waiting.wait(), 1)
@@ -434,7 +512,7 @@ async def interrupt_read(_size):
     expected = ExternalServiceUnavailableError if fault == "connect" else ExternalCheckerExecutionOutcomeUnknown
     with pytest.raises(expected):
         await asyncio.wait_for(task, 2)
-    connect.assert_awaited_once_with()
+    connect.assert_awaited_once_with(placement)
     if fault == "connect":
         writer.write.assert_not_called()
     else:
@@ -478,7 +556,7 @@ async def test_remote_post_stages_bound_material_and_removes_session(tmp_path: P
     observed = asyncio.Event()
 
     async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
-        request = json.loads(await _read_frame(reader))
+        request = await read_fixture_native_request(reader, writer, _placement_body())
         root = material_root / "workspaces" / grant_id
         path = root / "materials" / "submission_archive" / "work.txt"
         assert request["request"]["request_digest"] == request_digest
@@ -577,6 +655,7 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) ->
             "manifest_byte_count": len(manifest),
             "file_count": 1,
             "total_byte_count": len(content),
+            "epoch": _placement_body()["epoch"], "config_sha256": _placement_body()["config_sha256"],
         },
         separators=(",", ":"),
     ).encode()
@@ -716,7 +795,7 @@ async def answer(reader, writer, prefix):
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize("exit_kind", ["disconnect", "timeout"])
+@pytest.mark.parametrize("exit_kind", ["disconnect", "timeout", "unbound"])
 async def test_proxy_exit_closes_native_connection_and_copy_tasks(
     tmp_path: Path, exit_kind: str,
 ):
@@ -760,13 +839,22 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) ->
             "127.0.0.1", server.sockets[0].getsockname()[1],
             ssl=client_context, server_hostname="runner.test",
         )
-        control = json.dumps({
+        control_value = {
             "protocol_version": _REMOTE.PROTOCOL,
             "operation": "proxy",
             "capability": _REMOTE.CHECKER_CAPABILITY,
-        }, separators=(",", ":")).encode()
-        writer.write(_frame(control))
+            "epoch": _placement_body()["epoch"], "config_sha256": _placement_body()["config_sha256"],
+        }
+        if exit_kind == "unbound":
+            del control_value["epoch"], control_value["config_sha256"]
+        writer.write(_frame(json.dumps(control_value).encode()))
         await writer.drain()
+        if exit_kind == "unbound":
+            assert await asyncio.wait_for(reader.read(), 2) == b""
+            writer.close()
+            await writer.wait_closed()
+            assert not native_started.is_set()
+            return
         await asyncio.wait_for(native_started.wait(), 1)
         if exit_kind == "disconnect":
             writer.close()
diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py
index d6b65705a..ac7a97256 100644
--- a/backend/tests/checkers/external/test_runtime.py
+++ b/backend/tests/checkers/external/test_runtime.py
@@ -74,6 +74,7 @@
     make_external_checker_execution_request,
 )
 from tests.checkers.external.support import SHA, execution_identity, registry_entry
+from tests.checkers.external.test_remote_node import fixture_placement, fixture_runner_endpoints, read_fixture_native_request
 
 
 FIXTURES = Path(__file__).parents[4] / "external_checkers" / "fixtures"
@@ -131,19 +132,22 @@ def test_shared_rust_fixtures_preserve_python_contract_and_derived_digests():
         )
 
 
-def test_external_service_settings_require_one_complete_remote_identity(tmp_path: Path):
+def test_external_service_settings_require_one_complete_remote_identity(tmp_path: Path, monkeypatch):
     settings = Settings(
-        external_runner_host="runner.internal",
-        external_runner_port=9443,
-        external_runner_server_name="runner.internal",
+        external_runner_endpoints=fixture_runner_endpoints(9443),
         external_runner_ca_path=tmp_path / "ca.crt",
         external_runner_certificate_path=tmp_path / "app.crt",
         external_runner_private_key_path=tmp_path / "app.key",
     )
-    assert settings.external_runner_host == "runner.internal"
+    assert settings.external_runner_endpoints.root[0].server_name == "runner.test"
     assert settings.external_checker_service_timeout_seconds == 3660.0
     with pytest.raises(ValidationError, match="must be complete"):
-        Settings(external_runner_host="runner.internal")
+        Settings(external_runner_endpoints=fixture_runner_endpoints(9443))
+    monkeypatch.setenv("WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS", settings.external_runner_endpoints.model_dump_json())
+    for key in ("ca_path", "certificate_path", "private_key_path"):
+        name = f"external_runner_{key}"
+        monkeypatch.setenv(f"WORKSTREAM_{name.upper()}", str(getattr(settings, name)))
+    assert Settings(_env_file=None).external_runner_endpoints == settings.external_runner_endpoints
     with pytest.raises(ValueError, match="isolation receipt"):
         ExternalCheckerIsolationReceipt(
             repository="--network/host",
@@ -989,7 +993,7 @@ def _pre_transport_processor(lease, endpoint, changed):
     adapter = RemoteTlsExternalCheckerAdapter(
         **endpoint,
         model_proxy_socket_path=None,
-        timeout_seconds=0.2 if changed == "slow_decode" else 5.0,
+        timeout_seconds=5.0,
         source_contracts=selected_pre_submit_source_contracts(),
     )
     if changed in {"configured", "model_wrapper"}:
@@ -998,9 +1002,7 @@ def _pre_transport_processor(lease, endpoint, changed):
             SelectedPreSubmitCheckerExecutionAdapter,
         )
         settings = Settings(
-            external_runner_host=endpoint["host"],
-            external_runner_port=endpoint["port"],
-            external_runner_server_name=endpoint["server_name"],
+            external_runner_endpoints=endpoint["endpoints"],
             external_runner_ca_path=endpoint["ca_path"],
             external_runner_certificate_path=endpoint["certificate_path"],
             external_runner_private_key_path=endpoint["private_key_path"],
@@ -1017,8 +1019,17 @@ def forbidden_sessions():
     return processor
 
 
+def _pre_placement(reservation, config_image_id=None):
+    runtime = reservation.runtime_profile
+    return fixture_placement(
+        reservation.policy.entries[0].registry.image_digest, config_image_id,
+        pre={"profile_sha256": canonical_json_hash(runtime.model_dump(mode="json")),
+             "root_sha256": runtime.platform_root_sha256},
+    )
+
+
 @pytest.mark.asyncio
-@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing", "chunk_oversized", "slow_decode", "managed_runtime", "provider_from_wire", "configured", "model_wrapper"])
+@pytest.mark.parametrize("changed", [None, "source_hash", "source_short", "source_long", "result_fence", "trailing", "chunk_oversized", "expired_after_decode", "managed_runtime", "provider_from_wire", "configured", "model_wrapper"])
 async def test_single_pre_transport_streams_source_and_validates_combined_result(tmp_path, monkeypatch, changed):
     from dataclasses import replace
     from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitLeaseFacts
@@ -1051,9 +1062,14 @@ async def test_single_pre_transport_streams_source_and_validates_combined_result
     requests = []
 
     async def handle(reader, writer):
+        request = None
         try:
-            size = struct.unpack(">I", await reader.readexactly(4))[0]
-            requests.append(json.loads(await reader.readexactly(size)))
+            request = await read_fixture_native_request(
+                reader, writer, _pre_placement(reservation, body["invocation"]["config_image_id"]),
+            )
+            if request is None:
+                return
+            requests.append(request)
             while True:
                 size = struct.unpack(">I", await reader.readexactly(4))[0]
                 if size == 0:
@@ -1070,7 +1086,8 @@ async def handle(reader, writer):
         finally:
             writer.close()
             await writer.wait_closed()
-            finished.set()
+            if request is not None:
+                finished.set()
 
     class Grant:
         closed = False
@@ -1092,14 +1109,19 @@ async def open_source(self, *, lease):
                 self.closed = True
 
     decode_called = []
-    if changed == "slow_decode":
-        import time
+    if changed == "expired_after_decode":
+        from datetime import datetime as real_datetime
+        from app.adapters.checkers import external_service
         from app.modules.checkers.api.selected_pre_submit import SelectedPreSubmitExecutionFacts
         decode = SelectedPreSubmitExecutionFacts.from_canonical_body
+        class Clock:
+            @staticmethod
+            def now(zone):
+                return lease.lease_expires_at if decode_called else real_datetime.now(zone)
         def delayed_decode(cls, value, *, source_contracts):
             decode_called.append(True)
-            time.sleep(0.3)
             return decode(value, source_contracts=source_contracts)
+        monkeypatch.setattr(external_service, "datetime", Clock)
         monkeypatch.setattr(SelectedPreSubmitExecutionFacts, "from_canonical_body", classmethod(delayed_decode))
     expected_lease = lease
     grant = Grant()
@@ -1119,8 +1141,7 @@ def delayed_decode(cls, value, *, source_contracts):
     })
     remote = await asyncio.start_server(node.handle, "127.0.0.1", 0, ssl=node.ssl_context)
     endpoint = {
-        "host": "127.0.0.1", "port": remote.sockets[0].getsockname()[1],
-        "server_name": "runner.test", "ca_path": certificates["ca"],
+        "endpoints": fixture_runner_endpoints(remote.sockets[0].getsockname()[1]), "ca_path": certificates["ca"],
         "certificate_path": certificates["client_certificate"],
         "private_key_path": certificates["client_key"],
     }
@@ -1133,10 +1154,10 @@ def delayed_decode(cls, value, *, source_contracts):
             with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="material_unavailable"):
                 await processor.process(grant)
         else:
-            code = "deadline_exceeded" if changed == "slow_decode" else "invalid_output"
+            code = "deadline_exceeded" if changed == "expired_after_decode" else "invalid_output"
             with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match=code):
                 await processor.process(grant)
-        if changed == "slow_decode":
+        if changed == "expired_after_decode":
             assert decode_called == [True]
         if changed == "chunk_oversized":
             assert not sizes
@@ -1170,7 +1191,7 @@ def open_source(self, **kwargs):
     from tests.checkers.external.test_remote_node import _certificate_files
     certificates = _certificate_files(tmp_path)
     adapter = RemoteTlsExternalCheckerAdapter(
-        host="127.0.0.1", port=1, server_name="runner.test",
+        endpoints=fixture_runner_endpoints(),
         ca_path=certificates["ca"], certificate_path=certificates["client_certificate"],
         private_key_path=certificates["client_key"], model_proxy_socket_path=None,
         timeout_seconds=5.0,
@@ -1217,11 +1238,13 @@ async def open_source(self, *, lease):
                 source_closed.set()
 
     async def handle(reader, writer):
+        request = None
         try:
+            request = await read_fixture_native_request(reader, writer, _pre_placement(reservation))
+            if request is None:
+                return
+            assert request["request_digest"] == reservation.request_digest
             if stage == "execution":
-                request_size = struct.unpack(">I", await reader.readexactly(4))[0]
-                request = json.loads(await reader.readexactly(request_size))
-                assert request["request_digest"] == reservation.request_digest
                 received = bytearray()
                 while True:
                     size = struct.unpack(">I", await reader.readexactly(4))[0]
@@ -1234,7 +1257,8 @@ async def handle(reader, writer):
         finally:
             writer.close()
             await writer.wait_closed()
-            connection_closed.set()
+            if request is not None:
+                connection_closed.set()
 
     socket = tmp_path / "cancel.sock"
     server = await asyncio.start_unix_server(handle, socket)
@@ -1252,7 +1276,7 @@ async def handle(reader, writer):
     })
     remote = await asyncio.start_server(node.handle, "127.0.0.1", 0, ssl=node.ssl_context)
     adapter = RemoteTlsExternalCheckerAdapter(
-        host="127.0.0.1", port=remote.sockets[0].getsockname()[1], server_name="runner.test",
+        endpoints=fixture_runner_endpoints(remote.sockets[0].getsockname()[1]),
         ca_path=certificates["ca"], certificate_path=certificates["client_certificate"],
         private_key_path=certificates["client_key"], model_proxy_socket_path=None,
         timeout_seconds=5.0,
diff --git a/backend/tests/test_trusted_intake.py b/backend/tests/test_trusted_intake.py
index bb2b1250a..4df045135 100644
--- a/backend/tests/test_trusted_intake.py
+++ b/backend/tests/test_trusted_intake.py
@@ -34,6 +34,7 @@
 )
 from app.modules.checkers.api.material import SubmissionMaterialEntry
 from app.modules.checkers.api.pre_submit_material import SubmissionPacketView
+from tests.checkers.external.test_remote_node import fixture_placement, fixture_runner_endpoints
 
 _SPEC = importlib.util.spec_from_file_location(
     "trusted_intake_worker",
@@ -47,6 +48,23 @@
 _IMAGE = "sha256:" + "c" * 64
 _CONFIG = "sha256:" + "d" * 64
 
+def _intake_placement(**identity_changes):
+    identity = {
+        "image_digest": _IMAGE, "config_digest": _CONFIG,
+        "default_behavior_sha256": WORKSTREAM_DEFAULT_BEHAVIOR_SHA256,
+        "runtime": "smolvm", "isolation_mode": "smol-microvm",
+        "cpu_millis": 1000, "memory_bytes": 2 * 1024**3,
+    }
+    return fixture_placement(_IMAGE, _CONFIG, intake=identity | identity_changes)
+
+
+def _session_placement(adapter):
+    from app.adapters.runner import RunnerPlacement, RunnerReadiness
+
+    return RunnerPlacement(adapter._transport.endpoints.root[0], RunnerReadiness.model_validate_json(
+        json.dumps(_intake_placement() | {"fits_admission": True}),
+    ))
+
 
 async def _remote_adapter(tmp_path: Path, socket_path: Path):
     from tests.checkers.external.test_remote_node import _certificate_files, _REMOTE
@@ -64,8 +82,7 @@ async def _remote_adapter(tmp_path: Path, socket_path: Path):
     })
     server = await asyncio.start_server(node.handle, "127.0.0.1", 0, ssl=node.ssl_context)
     adapter = RemoteTlsTrustedIntakeAdapter(
-        host="127.0.0.1", port=server.sockets[0].getsockname()[1],
-        server_name="runner.test", ca_path=certificates["ca"],
+        endpoints=fixture_runner_endpoints(server.sockets[0].getsockname()[1]), ca_path=certificates["ca"],
         certificate_path=certificates["client_certificate"],
         private_key_path=certificates["client_key"], image_digest=_IMAGE,
         config_digest=_CONFIG,
@@ -78,7 +95,7 @@ def _unconnected_adapter(tmp_path: Path) -> RemoteTlsTrustedIntakeAdapter:
 
     certificates = _certificate_files(tmp_path)
     return RemoteTlsTrustedIntakeAdapter(
-        host="127.0.0.1", port=1, server_name="runner.test",
+        endpoints=fixture_runner_endpoints(),
         ca_path=certificates["ca"], certificate_path=certificates["client_certificate"],
         private_key_path=certificates["client_key"], image_digest=_IMAGE,
         config_digest=_CONFIG,
@@ -187,12 +204,22 @@ async def test_cancelled_prepare_closes_connection_and_drains_blocking_io(tmp_pa
     entered, disconnected = threading.Event(), threading.Event()
 
     def node():
-        with listener, listener.accept()[0] as connection:
-            reader = connection.makefile("rb")
-            assert _read(reader)["operation"] == "prepare"
-            entered.set()
-            assert reader.read() == b""
-            disconnected.set()
+        with listener:
+            with listener.accept()[0] as probe:
+                observed = _read(probe.makefile("rb"))
+                assert observed["operation"] == "placement" and observed["demand"]["kind"] == "intake"
+                probe.sendall(_frame(_intake_placement() | {"fits_admission": True}))
+            with listener.accept()[0] as connection:
+                reader = connection.makefile("rb")
+                placement = _intake_placement()
+                assert _read(reader) == {"protocol_version": "external_checker_service.v1", "operation": "bind_epoch",
+                                        "epoch": placement["epoch"], "config_sha256": placement["config_sha256"]}
+                command = _read(reader)
+                assert command["operation"] == "prepare"
+                assert 0 < command["payload"]["deadline_ms"] < _request().deadline_ms
+                entered.set()
+                assert reader.read() == b""
+                disconnected.set()
 
     thread = threading.Thread(target=node)
     thread.start()
@@ -220,6 +247,8 @@ def node():
     ],
 )
 async def test_health_rejects_other_engine_or_trusted_identity(tmp_path, field, value):
+    from workstream_external_services import ExternalServiceUnavailableError
+
     path = tmp_path / "node.sock"
     listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     listener.bind(str(path))
@@ -227,33 +256,13 @@ async def test_health_rejects_other_engine_or_trusted_identity(tmp_path, field,
 
     def node():
         with listener, listener.accept()[0] as connection:
-            assert _read(connection.makefile("rb"))["operation"] == "health"
-            identity = {
-                "image_digest": _IMAGE,
-                "config_digest": _CONFIG,
-                "default_behavior_sha256": WORKSTREAM_DEFAULT_BEHAVIOR_SHA256,
-                "runtime": "smolvm",
-                "isolation_mode": "smol-microvm",
-                "cpu_millis": 1000,
-                "memory_bytes": 2 * 1024**3,
-            }
-            identity[field] = value
-            connection.sendall(
-                _frame(
-                    {
-                        "protocol_version": _PROTOCOL,
-                        "operation": "health",
-                        "lease": None,
-                        "status": "ok",
-                        "payload": identity,
-                    }
-                )
-            )
+            assert _read(connection.makefile("rb"))["operation"] == "placement"
+            connection.sendall(_frame(_intake_placement(**{field: value})))
 
     thread = threading.Thread(target=node)
     thread.start()
     remote, adapter = await _remote_adapter(tmp_path, path)
-    with pytest.raises(ExternalServiceProtocolError):
+    with pytest.raises(ExternalServiceUnavailableError):
         await adapter.health()
     thread.join(2)
     remote.close()
@@ -311,9 +320,7 @@ def consume():
 @pytest.mark.parametrize(
     "missing",
     [
-        "external_runner_host",
-        "external_runner_port",
-        "external_runner_server_name",
+        "external_runner_endpoints",
         "external_runner_ca_path",
         "external_runner_certificate_path",
         "external_runner_private_key_path",
@@ -327,9 +334,7 @@ def test_composition_requires_every_trusted_intake_identity(tmp_path, missing):
     from workstream_external_services import ExternalServiceConfigurationError
 
     settings = Settings(
-        external_runner_host="runner.internal",
-        external_runner_port=9443,
-        external_runner_server_name="runner.internal",
+        external_runner_endpoints=fixture_runner_endpoints(9443),
         external_runner_ca_path=tmp_path / "ca.crt",
         external_runner_certificate_path=tmp_path / "app.crt",
         external_runner_private_key_path=tmp_path / "app.key",
@@ -346,9 +351,7 @@ def test_intake_factory_is_independent_of_project_engine(tmp_path):
 
     adapter = trusted_submission_intake(
         Settings(
-            external_runner_host="runner.internal",
-            external_runner_port=9443,
-            external_runner_server_name="runner.internal",
+            external_runner_endpoints=fixture_runner_endpoints(9443),
             external_runner_ca_path=tmp_path / "ca.crt",
             external_runner_certificate_path=tmp_path / "app.crt",
             external_runner_private_key_path=tmp_path / "app.key",
@@ -372,7 +375,7 @@ async def test_interrupted_export_disconnects_before_cleanup_can_read_raw_bytes(
         BytesIO(_archive(content=content)))
     entry = inspection.entries[0]
     adapter = _unconnected_adapter(tmp_path)
-    session = _Session(adapter, time.monotonic() + 60, _request())
+    session = _Session(adapter, time.monotonic() + 60, _session_placement(adapter), _request())
     session._socket.close()
     session._socket, peer = socket.socketpair()
     session._state, session._lease, session._inspection = "inspected", _LEASE, inspection
@@ -420,7 +423,7 @@ def test_inspect_size_substitution_is_rejected_before_command_or_archive_bytes(t
 
     data = _archive()
     adapter = _unconnected_adapter(tmp_path)
-    session = _Session(adapter, time.monotonic() + 10, _request(archive_byte_count=len(data)))
+    session = _Session(adapter, time.monotonic() + 10, _session_placement(adapter), _request(archive_byte_count=len(data)))
     session._state = "prepared"
     commands = []
 
diff --git a/cli/README.md b/cli/README.md
index 2db7f6e80..bd2ad4f8b 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -2228,9 +2228,7 @@ before running the drill. No credential or runtime profile is inferred from a
 local Docker installation:
 
 ```sh
-export WORKSTREAM_EXTERNAL_RUNNER_HOST=127.0.0.1
-export WORKSTREAM_EXTERNAL_RUNNER_PORT="$OWNED_TUNNEL_PORT"
-export WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME=runner.workstream.internal
+export WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS="$(printf '[{"host":"127.0.0.1","port":%s,"server_name":"runner.workstream.internal","config_sha256":"%s"}]' "$OWNED_TUNNEL_PORT" "$PINNED_RUNNER_CONFIG_SHA256")"
 export WORKSTREAM_EXTERNAL_RUNNER_CA_PATH="$PRIVATE_TLS/ca.crt"
 export WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH="$PRIVATE_TLS/app.crt"
 export WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH="$PRIVATE_TLS/app.key"
diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py
index add5bf179..7694807e3 100644
--- a/cli/tests/journey/runtime.py
+++ b/cli/tests/journey/runtime.py
@@ -148,6 +148,7 @@ def load_journey_configuration(environment: dict[str, str]) -> dict[str, Path]:
     from jsonschema import Draft202012Validator
 
     from app.adapters.artifacts import selected_pre_submit_source_contracts
+    from app.core.runner_endpoints import ExternalRunnerEndpoints
     from app.modules.artifacts.api.submission_cleanup import (
         SubmissionSourceCleanupProfile,
     )
@@ -156,16 +157,11 @@ def load_journey_configuration(environment: dict[str, str]) -> dict[str, Path]:
     from app.modules.checkers.api.source_contracts import source_contracts_context
     from public_setup import validate_authored_rules_template
 
-    host = environment.get("WORKSTREAM_EXTERNAL_RUNNER_HOST")
-    port = environment.get("WORKSTREAM_EXTERNAL_RUNNER_PORT")
-    server_name = environment.get("WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME")
-    if (
-        host != "127.0.0.1"
-        or not port
-        or not port.isdecimal()
-        or not 1 <= int(port) <= 65_535
-        or not server_name
-    ):
+    try:
+        endpoints = ExternalRunnerEndpoints.model_validate_json(environment.get("WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS", ""))
+    except ValueError as exc:
+        raise RuntimeError("journey requires reviewed TLS runner endpoints") from exc
+    if any(endpoint.host != "127.0.0.1" for endpoint in endpoints.root):
         raise RuntimeError("journey requires an explicit loopback TLS runner tunnel")
     for name in (
         "WORKSTREAM_EXTERNAL_RUNNER_CA_PATH",
diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md
index 4d9652e67..37642ed13 100644
--- a/deploy/hosted/README.md
+++ b/deploy/hosted/README.md
@@ -20,7 +20,8 @@ A render, image build or preflight alone is not deployment evidence.
 
 Hosted releases set `WORKSTREAM_HOSTED_PROFILE=app`. Supply the private runner
 address, port and certificate name through
-`WORKSTREAM_EXTERNAL_RUNNER_{HOST,PORT,SERVER_NAME}`; supply the CA, client
+`WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS` with the reviewed private address, port,
+exact certificate DNS name and loaded config SHA-256 for each node. Supply the CA, client
 certificate and client key through the corresponding `*_FILE` selectors.
 Pin `WORKSTREAM_ARTIFACT_INTAKE_IMAGE_DIGEST` and
 `WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST` to the images installed on the
@@ -565,8 +566,13 @@ If retained work remains, complete its recovery under the original configuration
 before changing the pool.
 
 Before restarting or stopping a runner unit, first drain producers and the
-worker through the wrapper, retain the proxy until calls settle, and independently
-confirm that the runner has no active owned leases, VMs or cgroups.
+worker through the wrapper. Keep the native drain marker in its existing
+private control directory and require an authenticated placement observation
+of the reviewed loaded config and current epoch with `drained: true`. This
+covers native reservations before their VM or lease is visible. Also require
+the remote relay workspace to be empty and its transport sessions to settle.
+Retain the proxy until its calls settle, and independently inspect the owned
+leases, VMs and cgroups.
 Preserve guardian recovery and use the exact owner-scoped inventory; never prune
 shared resources or stop another deployment. Exercise an interrupted
 job and verify the existing exact retry/reconciliation operations rather than
diff --git a/deploy/hosted/compose.yml b/deploy/hosted/compose.yml
index a0ec11370..7e5f32840 100644
--- a/deploy/hosted/compose.yml
+++ b/deploy/hosted/compose.yml
@@ -116,9 +116,7 @@ services:
       WORKSTREAM_API_RATE_LIMIT_KEY_SECRET_FILE: /run/secrets/api_rate_limit_key
       WORKSTREAM_PAGINATION_CURSOR_HMAC_SECRET_FILE: /run/secrets/pagination_cursor_hmac
       WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE: /run/workstream-artifact-credentials/aws-access-key.json
-      WORKSTREAM_EXTERNAL_RUNNER_HOST: ${WORKSTREAM_EXTERNAL_RUNNER_HOST:?set the private runner address}
-      WORKSTREAM_EXTERNAL_RUNNER_PORT: ${WORKSTREAM_EXTERNAL_RUNNER_PORT:-9443}
-      WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME: ${WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME:?set the runner certificate name}
+      WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS: ${WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS:?set reviewed runner endpoints}
       WORKSTREAM_EXTERNAL_RUNNER_CA_PATH: /run/secrets/external_runner_ca
       WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH: /run/secrets/external_runner_certificate
       WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH: /run/secrets/external_runner_private_key
@@ -197,9 +195,7 @@ services:
       WORKSTREAM_CELERY_BROKER_URL_FILE: /run/secrets/celery_broker_url
       WORKSTREAM_GUIDE_DOCUMENT_PARSER_SOCKET: ${WORKSTREAM_DEPLOYMENT_ROOT:-/var/lib/workstream}/guide-runtime/guide.sock
       WORKSTREAM_ARTIFACT_S3_DIRECT_USER_CREDENTIAL_FILE: /run/workstream-artifact-credentials/aws-access-key.json
-      WORKSTREAM_EXTERNAL_RUNNER_HOST: ${WORKSTREAM_EXTERNAL_RUNNER_HOST:?set the private runner address}
-      WORKSTREAM_EXTERNAL_RUNNER_PORT: ${WORKSTREAM_EXTERNAL_RUNNER_PORT:-9443}
-      WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME: ${WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME:?set the runner certificate name}
+      WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS: ${WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS:?set reviewed runner endpoints}
       WORKSTREAM_EXTERNAL_RUNNER_CA_PATH: /run/secrets/external_runner_ca
       WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH: /run/secrets/external_runner_certificate
       WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH: /run/secrets/external_runner_private_key
diff --git a/deploy/hosted/preflight.py b/deploy/hosted/preflight.py
index 82aa812fd..d043e2d06 100644
--- a/deploy/hosted/preflight.py
+++ b/deploy/hosted/preflight.py
@@ -62,20 +62,19 @@
     "WORKSTREAM_ARTIFACT_INTAKE_CONFIG_DIGEST",
 )
 HOSTED_PROFILE_KEY = "WORKSTREAM_HOSTED_PROFILE"
-REMOTE_RUNNER_KEYS = (
-    "WORKSTREAM_EXTERNAL_RUNNER_HOST",
-    "WORKSTREAM_EXTERNAL_RUNNER_PORT",
-    "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME",
+REMOTE_RUNNER_ENDPOINTS_KEY = "WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS"
+REMOTE_RUNNER_SECRET_FILE_KEYS = (
     "WORKSTREAM_EXTERNAL_RUNNER_CA_FILE",
     "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE",
     "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE",
+)
+REMOTE_RUNNER_KEYS = (
+    REMOTE_RUNNER_ENDPOINTS_KEY,
+    *REMOTE_RUNNER_SECRET_FILE_KEYS,
     *INTAKE_DIGEST_KEYS,
 )
-REMOTE_RUNNER_SECRET_FILE_KEYS = REMOTE_RUNNER_KEYS[3:6]
 REMOTE_RUNNER_ENVIRONMENT_KEYS = (
-    "WORKSTREAM_EXTERNAL_RUNNER_HOST",
-    "WORKSTREAM_EXTERNAL_RUNNER_PORT",
-    "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME",
+    REMOTE_RUNNER_ENDPOINTS_KEY,
     "WORKSTREAM_EXTERNAL_RUNNER_CA_PATH",
     "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH",
     "WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_PATH",
@@ -145,6 +144,7 @@ def deployment_paths(values: dict[str, str]) -> HostedPaths:
     "WORKSTREAM_SUBMISSION_SOURCE_CLEANUP_PROFILE",
 )
 DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z")
+RUNNER_DNS_NAME = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*")
 IMAGE_REFERENCE = re.compile(r"[^\s@]+@sha256:[0-9a-f]{64}\Z")
 ENVIRONMENT_KEY = re.compile(r"[A-Z][A-Z0-9_]*\Z")
 IAM_USER_ARN = re.compile(
@@ -596,20 +596,23 @@ def validate_environment(values: dict[str, str]) -> None:
     for key in INTAKE_DIGEST_KEYS:
         if not DIGEST.fullmatch(_required(values, key)):
             raise PreflightError(f"trusted intake requires a pinned digest: {key}")
-    runner_host = _required(values, "WORKSTREAM_EXTERNAL_RUNNER_HOST")
-    runner_name = _required(values, "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME")
-    if (
-        len(runner_host) > 255
-        or len(runner_name) > 255
-        or any(character.isspace() for character in runner_host + runner_name)
-    ):
-        raise PreflightError("external runner endpoint is invalid")
     try:
-        runner_port = int(_required(values, "WORKSTREAM_EXTERNAL_RUNNER_PORT"))
+        endpoints = json.loads(_required(values, REMOTE_RUNNER_ENDPOINTS_KEY))
     except ValueError as exc:
-        raise PreflightError("external runner port is invalid") from exc
-    if not 1 <= runner_port <= 65_535:
-        raise PreflightError("external runner port is invalid")
+        raise PreflightError("external runner endpoints must be JSON") from exc
+    if type(endpoints) is not list or not 1 <= len(endpoints) <= 8:
+        raise PreflightError("external runner endpoint set is invalid")
+    for endpoint in endpoints:
+        if (type(endpoint) is not dict or set(endpoint) != {"host", "port", "server_name", "config_sha256"}
+                or any(type(endpoint[name]) is not str for name in ("host", "server_name", "config_sha256"))
+                or any(len(endpoint[name]) > 253 or not RUNNER_DNS_NAME.fullmatch(endpoint[name])
+                       for name in ("host", "server_name"))
+                or type(endpoint["port"]) is not int or not 1 <= endpoint["port"] <= 65_535
+                or not DIGEST.fullmatch(endpoint["config_sha256"])):
+            raise PreflightError("external runner endpoint is invalid")
+    if (len({(endpoint["host"], endpoint["port"]) for endpoint in endpoints}) != len(endpoints)
+            or len({endpoint["server_name"] for endpoint in endpoints}) != len(endpoints)):
+        raise PreflightError("external runner endpoint identities must be distinct")
     for key in FORBIDDEN_RELEASE_KEYS:
         if values.get(key):
             raise PreflightError(
@@ -2132,11 +2135,7 @@ def validate_compose(rendered: dict[str, Any], values: dict[str, str]) -> None:
             raise PreflightError(f"Resend credential is exposed outside its email worker: {name}")
         expected_remote = (
             {
-                "WORKSTREAM_EXTERNAL_RUNNER_HOST": values["WORKSTREAM_EXTERNAL_RUNNER_HOST"],
-                "WORKSTREAM_EXTERNAL_RUNNER_PORT": values["WORKSTREAM_EXTERNAL_RUNNER_PORT"],
-                "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME": values[
-                    "WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME"
-                ],
+                REMOTE_RUNNER_ENDPOINTS_KEY: values[REMOTE_RUNNER_ENDPOINTS_KEY],
                 "WORKSTREAM_EXTERNAL_RUNNER_CA_PATH": "/run/secrets/external_runner_ca",
                 "WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_PATH": (
                     "/run/secrets/external_runner_certificate"
diff --git a/deploy/hosted/release.env.example b/deploy/hosted/release.env.example
index b75875358..1deb713d0 100644
--- a/deploy/hosted/release.env.example
+++ b/deploy/hosted/release.env.example
@@ -124,9 +124,8 @@ WORKSTREAM_OBSERVABILITY_LOG_LEVEL=INFO
 # The app and runner certificates are issued by a dedicated private CA. These
 # files are runtime-owned 0400 files; the private key is mounted only into API
 # and worker. The runner firewall admits port 9443 only from the app security group.
-WORKSTREAM_EXTERNAL_RUNNER_HOST=172.31.21.182
-WORKSTREAM_EXTERNAL_RUNNER_PORT=9443
-WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME=runner.workstream.internal
+# Replace the example config digest with the independently verified loaded node config SHA-256.
+WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS=[{"host":"172.31.21.182","port":9443,"server_name":"runner.workstream.internal","config_sha256":"sha256:3333333333333333333333333333333333333333333333333333333333333333"}]
 WORKSTREAM_EXTERNAL_RUNNER_CA_FILE=/etc/workstream/runner-tls/ca.crt
 WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE=/etc/workstream/runner-tls/app.crt
 WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE=/etc/workstream/runner-tls/app.key
diff --git a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
index 00e1b05d0..328d27d01 100644
--- a/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
+++ b/experiments/pilot04_external_checker_runtime/run_public_journey_probe.py
@@ -1549,9 +1549,11 @@ async def run(database_url: str, image_reference: str, node_config: Path,
     _require(runtime_settings.artifact_scratch_root == scratch
              and runtime_settings.artifact_scratch_minimum_free_bytes == 0,
              "API/worker scratch configuration differs from fixture")
-    _require(runtime_settings.external_runner_host is not None
+    endpoints = runtime_settings.external_runner_endpoints
+    _require(endpoints is not None and len(endpoints.root) == 1
+             and endpoints.root[0].config_sha256 == "sha256:" + hashlib.sha256(node_config.read_bytes()).hexdigest()
              and runtime_settings.submission_execution_profile is not None,
-             "supply explicit remote TLS runner and source execution profile before qualification")
+             "supply one TLS runner with the exact reviewed node config and source execution profile")
     source_profile = _require_source_runtime_window(runtime_settings)
     _require(runtime_settings.submission_source_cleanup_profile is not None,
              "supply explicit source cleanup profile for the dedicated worker")
diff --git a/external_checkers/README.md b/external_checkers/README.md
index 3d7f4ec34..ba0bdebaf 100644
--- a/external_checkers/README.md
+++ b/external_checkers/README.md
@@ -332,6 +332,15 @@ the outer VM and one sequential child at their combined peak. Per-VM CPU
 ceilings still share the parent cgroup limit. Size and measure concurrency on
 the chosen host before publishing an interactive latency envelope.
 
+For a drain, the operator keeps an empty regular `.workstream-checker-drain`
+file in the checker's existing private socket directory. Use the directory
+owner and mode `0600`. An authenticated placement response with `drained`
+true confirms zero native admission usage under the active boot epoch. Hold
+the marker through restart and keep the existing guardian recovery and
+separate mTLS workspace cleanup checks. The mTLS callback host continues to
+own its own approved trial catalogue. Runner placement checks the native
+approved catalogue and exact selected entry.
+
 Each existing cache entry additionally has `smol.archive`,
 `smol.archive_sha256` and `smol.image_config`. The
 [cache preparation command](../backend/scripts/checker_smol_cache.py) verifies an already local
diff --git a/external_checkers/deploy/runner-qualification-20261124.md b/external_checkers/deploy/runner-qualification-20261124.md
index 3d10ea6c1..75ff0c475 100644
--- a/external_checkers/deploy/runner-qualification-20261124.md
+++ b/external_checkers/deploy/runner-qualification-20261124.md
@@ -206,9 +206,7 @@ link); the API intentionally has no model callback socket.
 The exact non-secret release additions are:
 
 ```dotenv
-WORKSTREAM_EXTERNAL_RUNNER_HOST=172.31.21.182
-WORKSTREAM_EXTERNAL_RUNNER_PORT=9443
-WORKSTREAM_EXTERNAL_RUNNER_SERVER_NAME=runner.workstream.internal
+WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS=[{"host":"172.31.21.182","port":9443,"server_name":"runner.workstream.internal","config_sha256":"sha256:"}]
 WORKSTREAM_EXTERNAL_RUNNER_CA_FILE=/etc/workstream/runner-tls/ca.crt
 WORKSTREAM_EXTERNAL_RUNNER_CERTIFICATE_FILE=/etc/workstream/runner-tls/app.crt
 WORKSTREAM_EXTERNAL_RUNNER_PRIVATE_KEY_FILE=/etc/workstream/runner-tls/app.key
diff --git a/external_checkers/remote_node.py b/external_checkers/remote_node.py
index 74aa9b8ec..7ffe4e12d 100644
--- a/external_checkers/remote_node.py
+++ b/external_checkers/remote_node.py
@@ -79,6 +79,17 @@ async def _write_frame(writer: asyncio.StreamWriter, body: bytes) -> None:
     await writer.drain()
 
 
+def _epoch_binding(control: dict[str, Any]) -> bytes:
+    epoch, config = control.get("epoch"), control.get("config_sha256")
+    if (type(epoch) is not str or re.fullmatch(r"[0-9a-f]{64}", epoch) is None
+            or type(config) is not str or _SHA256.fullmatch(config) is None):
+        raise ProtocolError("runner epoch binding is invalid")
+    return json.dumps({
+        "protocol_version": "external_checker_service.v1", "operation": "bind_epoch",
+        "epoch": epoch, "config_sha256": config,
+    }, separators=(",", ":")).encode()
+
+
 class ExecutionChannel:
     """Multiplex native callback frames over the exact owning execute connection."""
 
@@ -465,12 +476,18 @@ async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWrite
                     raise ProtocolError("remote protocol differs")
                 operation = control.get("operation")
                 capability = control.get("capability")
-                if operation == "proxy":
-                    if set(control) != {"protocol_version", "operation", "capability"} or capability not in {
+                if operation == "placement":
+                    if set(control) != {"protocol_version", "operation", "demand"} or (
+                        control["demand"] is not None and type(control["demand"]) is not dict
+                    ):
+                        raise ProtocolError("placement request is invalid")
+                    await self._placement(control["demand"], writer)
+                elif operation == "proxy":
+                    if set(control) != {"protocol_version", "operation", "capability", "epoch", "config_sha256"} or capability not in {
                         CHECKER_CAPABILITY, INTAKE_CAPABILITY
                     }:
                         raise ProtocolError("proxy request is invalid")
-                    await self._proxy(reader, writer)
+                    await self._proxy(reader, writer, _epoch_binding(control))
                 elif operation == "execute":
                     if capability != CHECKER_CAPABILITY:
                         raise ProtocolError("execute capability differs")
@@ -486,7 +503,22 @@ async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWrite
             except (OSError, ssl.SSLError):
                 pass
 
-    async def _proxy(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+    async def _placement(self, demand: dict[str, Any] | None, writer: asyncio.StreamWriter) -> None:
+        """Forward one closed read-only request without allowing an inner execution frame."""
+        native_reader, native_writer = await asyncio.open_unix_connection(self.socket_path)
+        try:
+            await _write_frame(native_writer, json.dumps({
+                "protocol_version": "external_checker_service.v1", "operation": "placement", "demand": demand,
+            }, separators=(",", ":")).encode())
+            response = await _read_frame(native_reader, 32_768)
+            if await native_reader.read(1):
+                raise ProtocolError("native placement reply has trailing data")
+            await _write_frame(writer, response)
+        finally:
+            native_writer.close()
+            await native_writer.wait_closed()
+
+    async def _proxy(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, binding: bytes) -> None:
         native_reader, native_writer = await asyncio.open_unix_connection(self.socket_path)
 
         async def copy(source: asyncio.StreamReader, target: asyncio.StreamWriter) -> None:
@@ -496,6 +528,7 @@ async def copy(source: asyncio.StreamReader, target: asyncio.StreamWriter) -> No
 
         tasks: set[asyncio.Task[None]] = set()
         try:
+            await _write_frame(native_writer, binding)
             tasks = {
                 asyncio.create_task(copy(reader, native_writer)),
                 asyncio.create_task(copy(native_reader, writer)),
@@ -520,10 +553,11 @@ async def _execute(
     ) -> None:
         expected = {
             "protocol_version", "operation", "capability", "service_request",
-            "manifest_byte_count", "file_count", "total_byte_count",
+            "manifest_byte_count", "file_count", "total_byte_count", "epoch", "config_sha256",
         }
         if set(control) != expected or type(control["service_request"]) is not dict:
             raise ProtocolError("execute request is invalid")
+        binding_frame = _epoch_binding(control)
         request = control["service_request"]
         if request.get("operation") not in {"execute", "locate_forge_change"}:
             raise ProtocolError("service operation is invalid")
@@ -568,7 +602,7 @@ async def _execute(
             raise ProtocolError("material bounds differ")
         async with self._execution:
             await self._stage_and_execute(
-                grant_id, raw_manifest, manifest, files, request, reader, writer
+                grant_id, raw_manifest, manifest, files, request, reader, writer, binding_frame
             )
 
     async def _stage_and_execute(
@@ -580,6 +614,7 @@ async def _stage_and_execute(
         request: dict[str, Any],
         reader: asyncio.StreamReader,
         writer: asyncio.StreamWriter,
+        binding_frame: bytes,
     ) -> None:
         target = self.workspaces / grant_id
         incoming = self.workspaces / f".incoming-{uuid.uuid4().hex}"
@@ -627,6 +662,7 @@ async def _stage_and_execute(
             if self._active_channel is not None:
                 raise ProtocolError("execute callback owner is already active")
             self._active_channel = channel
+            await _write_frame(native_writer, binding_frame)
             await _write_frame(native_writer, encoded)
             response_task = asyncio.create_task(_read_frame(native_reader, MAXIMUM_FRAME_BYTES))
             disconnect_task = asyncio.create_task(channel.closed.wait())
diff --git a/external_checkers/workstream-checker-service/tests/terminal_systems_smol_composition.py b/external_checkers/workstream-checker-service/tests/terminal_systems_smol_composition.py
index 2e3b3d755..af24d2b89 100644
--- a/external_checkers/workstream-checker-service/tests/terminal_systems_smol_composition.py
+++ b/external_checkers/workstream-checker-service/tests/terminal_systems_smol_composition.py
@@ -1138,6 +1138,7 @@ def trial_reservations(session, external):
                     material_root=runner_material_root,
                     native_model_proxy_socket_path=runner_proxy_path,
                     session_timeout_seconds=720.0,
+                    config_sha256="sha256:" + hashlib.sha256(config_path.read_bytes()).hexdigest(),
                 ) as endpoint,
             ):
                 service = subprocess.Popen(
diff --git a/scripts/test_hosted_release_config.py b/scripts/test_hosted_release_config.py
index 5eace3b93..aebf7e00f 100644
--- a/scripts/test_hosted_release_config.py
+++ b/scripts/test_hosted_release_config.py
@@ -1946,6 +1946,19 @@ def test_trusted_intake_requires_pins_without_shared_runner_mounts(self) -> None
                 preflight._service_mounts(rendered["services"][role]),
             )
 
+    def test_runner_endpoints_match_the_closed_release_contract(self) -> None:
+        key = preflight.REMOTE_RUNNER_ENDPOINTS_KEY
+        endpoint = json.loads(self.environment[key])[0]
+        for invalid in (
+            [],
+            [endpoint | {"host": "a..b"}],
+            [endpoint | {"server_name": "*.test"}],
+            [endpoint | {"config_sha256": "newest"}],
+            [endpoint, endpoint | {"port": endpoint["port"] + 1}],
+        ):
+            with self.subTest(invalid=invalid), self.assertRaisesRegex(preflight.PreflightError, "external runner endpoint"):
+                preflight.validate_environment(self.environment | {key: json.dumps(invalid)})
+
 
 
 class ReleaseSecretLoaderTests(unittest.TestCase):

From 20821ef082ba086ac1de0a2bde98ada8c5dbeaaf Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:43:52 +0100
Subject: [PATCH 435/513] Record verified cleanup upgrades and claim fixture
 trigger evidence

---
 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 30709e0ce..53fab2ffe 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9341,6 +9341,14 @@ module fingerprint delta, and that each historical upgrade starts from the
 original predecessor shape. Run the selected pure checks and exact three
 historical cases in separate owned PostgreSQL after the native run releases it.
 
+The 18 selected pure checks passed in 31.80 seconds, with Ruff and Commitrail
+passing. Both cleanup migration cases passed on PostgreSQL at `2341967c4`.
+The claim-start case matched both expected unverified fixture links, then
+PostgreSQL refused to remove the projection while its deferred checks were
+pending. Complete those checks in the same transaction before the fixture DDL.
+The original validation and all predecessor guards remain active. The first
+run `/tmp/pr708-feedback-historical-isolated.log` cleaned its isolated resources.
+
 ### Refresh pending-operation MCP schema descriptions
 
 Configured backend OpenAPI comparison atc853743b6 passed142 and failed2

From e896e81915ddc0680902e929ded94e9f307806d4 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:43:52 +0100
Subject: [PATCH 436/513] Drain deferred claim fixture guards before projection
 removal

---
 backend/tests/migrations/test_claim_starts_work.py | 1 +
 1 file changed, 1 insertion(+)

diff --git a/backend/tests/migrations/test_claim_starts_work.py b/backend/tests/migrations/test_claim_starts_work.py
index af6d8be01..aa0e3676d 100644
--- a/backend/tests/migrations/test_claim_starts_work.py
+++ b/backend/tests/migrations/test_claim_starts_work.py
@@ -203,6 +203,7 @@ async def test_upgrade_starts_only_retained_claim_and_preserves_evidence(predece
             RETURNING subject
         """)))
         assert sorted(observed) == ["historical-claimant", "project-manager-subject"]
+        await connection.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
         await drop_retained_owner_read_projection(connection)
     await db_session.dispose_engine()
     await asyncio.to_thread(command.upgrade, _config(), "head")

From feffb4ce34a2bcb08064b3561f255d0b1645d879 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:50:22 +0100
Subject: [PATCH 437/513] Record passing claim-start predecessor upgrade

---
 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 53fab2ffe..907973131 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9349,6 +9349,12 @@ pending. Complete those checks in the same transaction before the fixture DDL.
 The original validation and all predecessor guards remain active. The first
 run `/tmp/pr708-feedback-historical-isolated.log` cleaned its isolated resources.
 
+After completing the deferred checks before the DDL, the exact claim-start
+case passed in 268.55 seconds at `14a010262`, schema 0093. The existing
+post-upgrade comparisons and database guards ran through completion. The
+isolated runner confirmed cleanup. The terminal receipt is
+`/tmp/pr708-feedback-claim-start-isolated.log` with its adjacent metadata JSON.
+
 ### Refresh pending-operation MCP schema descriptions
 
 Configured backend OpenAPI comparison atc853743b6 passed142 and failed2

From acf72173e4b22c46f512950c320aa3bc09a30397 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:54:37 +0100
Subject: [PATCH 438/513] Restore PRE adapter after observer fixture

---
 backend/tests/checkers/external/test_runtime.py | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/backend/tests/checkers/external/test_runtime.py b/backend/tests/checkers/external/test_runtime.py
index ac7a97256..39cec69f5 100644
--- a/backend/tests/checkers/external/test_runtime.py
+++ b/backend/tests/checkers/external/test_runtime.py
@@ -968,7 +968,9 @@ async def test_public_trace_preserves_execution_arguments(monkeypatch, tmp_path,
     trace = tmp_path / "trace.jsonl"
     monkeypatch.setenv("WORKSTREAM_PROBE_INTAKE_TRACE", str(trace))
     original_prepare = RemoteTlsTrustedIntakeAdapter.prepare
+    original_execute_pre = RemoteTlsExternalCheckerAdapter.execute_pre
     monkeypatch.setattr(RemoteTlsTrustedIntakeAdapter, "prepare", original_prepare)
+    monkeypatch.setattr(RemoteTlsExternalCheckerAdapter, "execute_pre", original_execute_pre)
     expected = object()
     execute = AsyncMock(return_value=expected)
     monkeypatch.setattr(RemoteTlsExternalCheckerAdapter, "execute", execute)

From 26dd6ec8e44e6d61b3ac0a9cfcf31fbb83800b02 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 13:55:49 +0100
Subject: [PATCH 439/513] Register qualified runner placement ownership

---
 .ci/behavior-ownership/partition.v1.json      | 10 ++++++++-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 22 +++++++++++++++++++
 backend/scripts/behavior_ownership.py         |  2 ++
 backend/tests/test_behavior_ownership.py      |  2 ++
 4 files changed, 35 insertions(+), 1 deletion(-)

diff --git a/.ci/behavior-ownership/partition.v1.json b/.ci/behavior-ownership/partition.v1.json
index 32112d8e9..c14627200 100644
--- a/.ci/behavior-ownership/partition.v1.json
+++ b/.ci/behavior-ownership/partition.v1.json
@@ -180,6 +180,10 @@
       "group": "lifecycle",
       "target": "backend/app/adapters/reviews/contribution_reads.py"
     },
+    {
+      "group": "shared",
+      "target": "backend/app/adapters/runner.py"
+    },
     {
       "group": "lifecycle",
       "target": "backend/app/adapters/submission_feedback_email.py"
@@ -396,6 +400,10 @@
       "group": "lifecycle",
       "target": "backend/app/core/project_guide_instructions.py"
     },
+    {
+      "group": "shared",
+      "target": "backend/app/core/runner_endpoints.py"
+    },
     {
       "group": "shared",
       "target": "backend/app/core/s3_validation.py"
@@ -2761,7 +2769,7 @@
       "target": "backend/scripts/validate_test_lane_evidence.py"
     }
   ],
-  "authority_digest": "14aa921cf9fc07a0779144d16686327eaa779d64e06fa40d383137a387d8b791",
+  "authority_digest": "9c68637f899c62f695b18ecffa768597d8e9ac09aaaf1d39a3b339ef3a60f4af",
   "protected_base_commit": "7676ce4347db0c9694962a9b587a20765e16eac6",
   "schema": "workstream.behavior-ownership-partition.v1"
 }
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 907973131..ce7c0ee6b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -9355,6 +9355,28 @@ post-upgrade comparisons and database guards ran through completion. The
 isolated runner confirmed cleanup. The terminal receipt is
 `/tmp/pr708-feedback-claim-start-isolated.log` with its adjacent metadata JSON.
 
+### Register runner placement behavior ownership
+
+The canonical behavior ownership check at `feffb4ce3` rejected the
+placement additions because the protected partition lacked exactly
+`backend/app/adapters/runner.py` and `backend/app/core/runner_endpoints.py`.
+The existing classifier assigns both to the shared group. Register those
+two paths in the existing submission target set and its exact test, then
+regenerate the partition with the same protected base and retained assignments.
+
+Scope is `.ci/behavior-ownership/partition.v1.json`,
+`backend/scripts/behavior_ownership.py`, its existing test, and this record.
+Low risk. Focused QA should check that only the two approved shared targets
+and the authority digest change. Verify the canonical ownership check and
+the unchanged semantic-family, project ownership and concrete factory
+inventory tests. No validator policy, lane, workflow, runtime or gate change.
+
+The regenerated partition contains 692 targets with exactly those additions
+and an updated digest. The canonical validator passed against the protected
+PR base `d713594ebf04a125917edb0ec981d380cf8047b4`. Twenty focused tests
+passed in 23.79 seconds. The semantic fingerprints and exact factory counts
+matched their existing expectations. Ruff and diff checks passed.
+
 ### Refresh pending-operation MCP schema descriptions
 
 Configured backend OpenAPI comparison atc853743b6 passed142 and failed2
diff --git a/backend/scripts/behavior_ownership.py b/backend/scripts/behavior_ownership.py
index f93251722..6b1d382e2 100644
--- a/backend/scripts/behavior_ownership.py
+++ b/backend/scripts/behavior_ownership.py
@@ -999,6 +999,8 @@
     "backend/app/adapters/submission_feedback_email.py",
     "backend/app/interfaces/submission_feedback_email.py",
     "backend/app/modules/tasks/post_submit_routing/feedback_email.py",
+    "backend/app/adapters/runner.py",
+    "backend/app/core/runner_endpoints.py",
 })
 FORGE_PROOF_FACTS_TARGETS = frozenset({
     "backend/app/adapters/github/app_facts.py",
diff --git a/backend/tests/test_behavior_ownership.py b/backend/tests/test_behavior_ownership.py
index 3a4f52787..e69eaba6c 100644
--- a/backend/tests/test_behavior_ownership.py
+++ b/backend/tests/test_behavior_ownership.py
@@ -2806,6 +2806,8 @@ def test_submission_intake_partition_addition_is_exact_and_retains_existing_targ
         "backend/app/adapters/submission_feedback_email.py",
         "backend/app/interfaces/submission_feedback_email.py",
         "backend/app/modules/tasks/post_submit_routing/feedback_email.py",
+        "backend/app/adapters/runner.py",
+        "backend/app/core/runner_endpoints.py",
     }
     assert ownership.SUBMISSION_INTAKE_TARGETS == additions
     trusted = _partition([retained])

From 1f53f1faa991f4d256a3b53d88608fea0c4b999c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:11:58 +0100
Subject: [PATCH 440/513] Record matching runner placement activation and
 readiness

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 22 +++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 353364e11..b014ed168 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12480,3 +12480,25 @@ produces the reconciled file exactly; no other production test changed there.
 The staged source/config inventory has no old experiment/pilot imports or paths.
 The moved Garden fixture path was also corrected in its existing runtime test.
 These are merge regression results, not new deployed qualification.
+
+
+### Matching runner placement activation after main reconciliation
+
+Activated the reviewed native service `bd8833d5a91c…f618e` and mTLS gateway
+`9579ca6d1da2…03cc` on the separate runner. Their source is unchanged between
+`02b805740` and reconciled `c0b6b5180`. Exact old/new file pins, fresh idle
+inventory, no running local journeys, and zero established port-9443 sessions
+preceded the bounded replacement. Both services became active (native PID9789,
+gateway PID9785). Config `a25f372fb6ae…b628` and unit `e84782092a7b…fd48`
+were verified/backed up but not replaced; no resource, guest, image, credential,
+API-host or database changes occurred. Explicit rollback bytes are retained at
+`/opt/workstream/a28-backup-bd8833d5a91c`; a later rollback requires authenticated
+drain and separate edge cleanup, never an automatic retry after unknown drain.
+
+The current Python RunnerTransport completed an authenticated read-only mTLS
+placement probe with exact DNS identity and loaded config digest. It observed
+boot epoch `b6c854a71d11f32454ab92661d076c4c4799c431b47b3c8074d4d32e3733ea41`,
+four exact cached images, configured PRE root/profile, trusted intake and
+callback relay, with draining=false. Local receipts are under
+`/tmp/workstream-a28-runner-candidate/` (stage, activation, live-placement).
+This proves current remote readiness, not execution or multi-node qualification.

From c715dbd4767079cc0e513378f913ba28b996f36b Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:16:30 +0100
Subject: [PATCH 441/513] Verify locked guide downloads through the current
 envelope

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 17 ++++++
 .../integration/test_journey_locked_guide.py  | 52 +++++++++++++++++++
 cli/tests/journey/task_work.py                |  5 +-
 3 files changed, 72 insertions(+), 2 deletions(-)
 create mode 100644 cli/tests/integration/test_journey_locked_guide.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index b014ed168..f21f6a85b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12502,3 +12502,20 @@ four exact cached images, configured PRE root/profile, trusted intake and
 callback relay, with draining=false. Local receipts are under
 `/tmp/workstream-a28-runner-candidate/` (stage, activation, live-placement).
 This proves current remote readiness, not execution or multi-node qualification.
+
+
+### Maintained CLI guide-envelope correction
+
+The current-source native journey at `c0b6b5180` passed public identity/authority,
+project setup and authored guide activation, then stopped before submission.
+`claim_and_read` compared the current guide envelope as if it were the retired
+bare document list. Receipts 0080 and 0082 are identical envelopes with
+project_id, guide_id, version and documents; the four-key length caused the
+failure. Read documents through their current envelope while preserving exact
+before/after envelope equality, concealed foreign-actor denial and SHA/size
+verification of both downloaded originals. No product response or guard changes.
+A focused regression fails before the fix; afterward the valid envelope and
+both changed-version/corrupted-byte negative controls pass (3 cases). Ruff passes.
+The failed journey is retained under `/tmp/workstream-paired-native-4g1j5bbe`;
+its schema0093 database and MinIO cleanup are all confirmed. No PRE/POST outcome
+was reached by this run. Repeat the maintained journey with the corrected caller.
diff --git a/cli/tests/integration/test_journey_locked_guide.py b/cli/tests/integration/test_journey_locked_guide.py
new file mode 100644
index 000000000..2363ccbc5
--- /dev/null
+++ b/cli/tests/integration/test_journey_locked_guide.py
@@ -0,0 +1,52 @@
+"""The maintained journey verifies the current guide envelope and exact bytes."""
+
+import hashlib
+import importlib.util
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+
+@pytest.mark.parametrize("fault", [None, "version", "bytes"])
+def test_locked_guide_download_preserves_envelope_and_bytes(monkeypatch, tmp_path, fault):
+    monkeypatch.setitem(sys.modules, "public_setup", SimpleNamespace(TASK="task"))
+    path = Path(__file__).resolve().parents[1] / "journey/task_work.py"
+    spec = importlib.util.spec_from_file_location("journey_locked_guide", path)
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    monkeypatch.setattr(module, "issue_submitter", lambda *args: "grant")
+    monkeypatch.setattr(module, "create_claimed_task", lambda *args, **kwargs: ("task", "assignment"))
+    bodies = [b"original guide", b"original rules"]
+    envelope = {
+        "project_id": "project", "guide_id": "guide", "version": 1,
+        "documents": [{"sha256": "sha256:" + hashlib.sha256(body).hexdigest(),
+                       "byte_count": len(body)} for body in bodies],
+    }
+
+    class Client:
+        directory = tmp_path
+
+        def call(self, token, *arguments, expected_exit=0):
+            if arguments[:2] in (("project", "create"), ("project", "show")):
+                return {"id": "other"}
+            assert arguments[:3] == ("task", "guide", "task")
+            if token == "bob":
+                assert expected_exit == 1
+                return {"error": {"status": 404}}
+            if "--download" in arguments:
+                destination = Path(arguments[-1])
+                for index, body in enumerate(bodies):
+                    (destination / str(index)).write_bytes(b"corrupted" if fault == "bytes" else body)
+                return envelope | {"version": 2} if fault == "version" else envelope
+            return envelope
+
+    args = (Client(), {name: name for name in ("manager", "alice", "bob")},
+            {"alice": "alice", "bob": "bob"}, "project")
+    if fault:
+        message = "listing changed" if fault == "version" else "originals differ"
+        with pytest.raises(AssertionError, match=message):
+            module.claim_and_read(*args)
+    else:
+        assert module.claim_and_read(*args) == ("task", "assignment", "grant")
diff --git a/cli/tests/journey/task_work.py b/cli/tests/journey/task_work.py
index 78f0f5fd0..7b57b38f5 100644
--- a/cli/tests/journey/task_work.py
+++ b/cli/tests/journey/task_work.py
@@ -95,7 +95,7 @@ def claim_and_read(client, tokens, actors, project_id):
     task_id, assignment_id = create_claimed_task(
         client, tokens, project_id, title="Summarize the fixed incident events"
     )
-    documents = client.call(tokens["alice"], "task", "guide", task_id)
+    guide = client.call(tokens["alice"], "task", "guide", task_id)
     denied = client.call(tokens["bob"], "task", "guide", task_id, expected_exit=1)
     if denied["error"].get("status") != 404:
         raise AssertionError("unassigned actor did not receive concealed guide denial")
@@ -104,8 +104,9 @@ def claim_and_read(client, tokens, actors, project_id):
     downloaded = client.call(
         tokens["alice"], "task", "guide", task_id, "--download", str(destination)
     )
-    if downloaded != documents or len(documents) != 2:
+    if downloaded != guide or len(guide["documents"]) != 2:
         raise AssertionError("locked guide listing changed during download")
+    documents = guide["documents"]
     actual = sorted(
         ("sha256:" + hashlib.sha256(path.read_bytes()).hexdigest(), path.stat().st_size)
         for path in destination.iterdir()

From 07b1b56c2d52cb1de398c4e69f2802ec4bc9cd1b Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:22:03 +0100
Subject: [PATCH 442/513] Exercise corrected assignment submissions through
 maintained clients

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  46 +++++
 .../test_journey_progress_identity.py         | 107 ++++++++++-
 cli/tests/journey/bootstrap.py                | 119 ++++++++++--
 cli/tests/journey/client.py                   | 176 +++++++++++++++++-
 cli/tests/journey/source_audit.py             |  38 +++-
 cli/tests/journey/submission_work.py          | 150 +++++++++++----
 6 files changed, 576 insertions(+), 60 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index f21f6a85b..cfc34126b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12519,3 +12519,49 @@ both changed-version/corrupted-byte negative controls pass (3 cases). Ruff passe
 The failed journey is retained under `/tmp/workstream-paired-native-4g1j5bbe`;
 its schema0093 database and MinIO cleanup are all confirmed. No PRE/POST outcome
 was reached by this run. Repeat the maintained journey with the corrected caller.
+
+### Keep the contributor revision proof in the maintained journey
+
+Allowed scope. Extend the existing `cli/tests/journey` bootstrap, public client,
+submission checks and read-only source audit. Use the maintained incident
+summary example and the installed MCP binary over its published HTTP tool
+endpoint. Keep the existing worker lifecycle and default human review branch.
+Focused checks belong with the existing CLI integration tests. No product
+authentication edits, retired harness, provisioner or deployed service changes.
+
+Acceptance. A malformed submission returns the exact actionable PRE finding,
+and leaves no Submission. A valid ZIP with incorrect counts reaches POST and
+requests one revision on the original assignment. The corrected ZIP uses that
+same assignment with a fresh key and no client-controlled revision fields.
+Require two immutable attempts, one preparation and one final acceptance. The
+optional installed MCP check exercises the same API and verifies shared public
+findings, assignment status and command replay. Keep local proof and real
+provider/deployment qualification distinct.
+
+The maintained command is `cli/tests/journey/bootstrap.py` under the existing
+isolated PostgreSQL and MinIO launcher. Its regular CLI path retains the
+explicit local HMAC fixture. To also run MCP, point
+`WORKSTREAM_CLI_JOURNEY_MCP_EXECUTABLE` at the installed current OAuth wheel
+entry point and keep `SETUP`, `TASKS` and `SUBMIT` enabled through the existing
+`WORKSTREAM_CLI_JOURNEY_` settings. The proof interpreter needs the matching
+MCP SDK. Supply the existing `WORKSTREAM_TOKEN_ISSUER` for `/realms/flow`,
+`WORKSTREAM_TOKEN_AUDIENCE=workstream-api`, and the provider's existing JWKS,
+RS256 and introspection settings. This selection removes local HMAC from the
+fixture API and workers. Use its real, TLS-verified provider configuration.
+
+`WORKSTREAM_CLI_JOURNEY_REFRESH_FILE` is an absolute owned mode-0600 JSON object
+with fresh registered CLI refresh grants in `administrator`, `manager`,
+`finance`, `operator`, `alice`, and `bob`, plus `mcp` for the same Alice's
+registered MCP proof client. The maintained provider helper renews them and
+keeps rotated values in process memory. Supply `WORKSTREAM_MCP_RESOURCE_URL`
+for that registered MCP audience and `WORKSTREAM_MCP_EXCHANGE_SECRET_FILE` for
+the current confidential exchange client. MCP listens only on loopback and
+calls the isolated API. This proof disables application feedback email.
+
+31 focused CLI integration fixture cases passed, including exact cross-client
+replay, refusal of substituted feedback and the rotating grant contract. The
+installed OAuth-enabled MCP wheel passed public metadata readiness and clean
+process teardown. The earlier non-OAuth wheel did not provide that metadata.
+These local checks used no authentication request to a provider and no native
+submission. Real paired-tool, corrected same-assignment and live deployment
+qualification remain open until the maintained journey runs end to end.
diff --git a/cli/tests/integration/test_journey_progress_identity.py b/cli/tests/integration/test_journey_progress_identity.py
index 8d4f83dfa..518042d4f 100644
--- a/cli/tests/integration/test_journey_progress_identity.py
+++ b/cli/tests/integration/test_journey_progress_identity.py
@@ -33,10 +33,7 @@
 
 
 @pytest.fixture
-def progress(monkeypatch):
-    monkeypatch.setitem(
-        sys.modules, "task_work", SimpleNamespace(create_claimed_task=None)
-    )
+def journey(monkeypatch):
     monkeypatch.setitem(
         sys.modules, "source_audit", SimpleNamespace(audit_accepted_source=None)
     )
@@ -44,7 +41,12 @@ def progress(monkeypatch):
     assert spec is not None and spec.loader is not None
     module = importlib.util.module_from_spec(spec)
     spec.loader.exec_module(module)
-    return module._progress
+    return module
+
+
+@pytest.fixture
+def progress(journey):
+    return journey._progress
 
 
 class Client:
@@ -85,3 +87,98 @@ def test_key_and_id_reads_reject_state_regression(progress):
     client = Client(FINALIZED, PENDING)
     with pytest.raises(AssertionError, match="durable identity"):
         progress(client, "token", "task-1", "key-1", "operation-1")
+
+
+@pytest.mark.parametrize("different", [False, True])
+def test_corrected_bundle_replays_one_mcp_command_in_cli(journey, tmp_path, different):
+    archive = tmp_path / "correct.zip"
+    archive.write_bytes(b"corrected bytes")
+    receipt = {
+        "status": "accepted",
+        "processing_stage_at_acceptance": "finalization_pending",
+        "task_id": "task-1",
+        "assignment_id": "assignment-1",
+        "operation_id": "operation-1",
+        "replayed": False,
+        "pre_submission_results": PENDING["pre_submission_results"],
+    }
+    replay = receipt | {"replayed": True}
+    if different:
+        replay["operation_id"] = "operation-2"
+    cli = Client(replay, PENDING)
+    cli.reads.append(PENDING)
+    mcp_commands = []
+
+    def mcp_submit(*args):
+        mcp_commands.append(args)
+        return receipt
+
+    mcp = SimpleNamespace(submit=mcp_submit)
+    if different:
+        with pytest.raises(AssertionError, match="exact source replay"):
+            journey._submit(cli, "token", "task-1", "assignment-1", archive, mcp=mcp)
+    else:
+        key, actual = journey._submit(
+            cli, "token", "task-1", "assignment-1", archive, mcp=mcp
+        )
+        assert actual == receipt
+        assert mcp_commands == [("task-1", "assignment-1", archive, key)]
+        assert cli.commands[0] == journey._command(
+            "task-1", "assignment-1", archive, key
+        )
+
+
+def test_exact_assignment_read_rejects_mcp_feedback_substitution(journey):
+    status = {
+        "assignment": {"assignment_id": "assignment-1", "task_id": "task-1"},
+        "current_status": "needs_revision",
+        "next_action": "revise",
+        "feedback_submission_id": "submission-1",
+    }
+    cli = Client(status, status)
+
+    def mcp_call(name, params):
+        assert name == "workstream_task_assignment_get"
+        assert params == {"assignment_id": "assignment-1"}
+        return status | {"feedback_submission_id": "submission-2"}
+
+    with pytest.raises(AssertionError, match="assignment status differ"):
+        journey._assignment_status(
+            cli, "token", "task-1", "assignment-1", mcp=SimpleNamespace(call=mcp_call)
+        )
+
+
+def test_mcp_renewal_uses_rotated_grant_and_exact_resource(monkeypatch):
+    spec = importlib.util.spec_from_file_location(
+        "journey_refresh_client", PATH.with_name("client.py")
+    )
+    assert spec is not None and spec.loader is not None
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    now = 10
+    monkeypatch.setattr(module.time, "monotonic", lambda: now)
+    grants = []
+
+    def request(path, document, *, form):
+        assert path == "/realms/flow/protocol/openid-connect/token" and form
+        grants.append(document)
+        return {"access_token": "access", "refresh_token": "rotated", "expires_in": 300}
+
+    token = module.RefreshingToken(
+        SimpleNamespace(request=request),
+        "workstream-mcp-proof",
+        "first",
+        resource="https://mcp.example/mcp",
+    )
+    assert token() == token() == "access"
+    now += 160
+    assert token() == "access"
+    assert grants == [
+        {
+            "grant_type": "refresh_token",
+            "client_id": "workstream-mcp-proof",
+            "refresh_token": value,
+            "resource": "https://mcp.example/mcp",
+        }
+        for value in ("first", "rotated")
+    ]
diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py
index 18e97809d..47b15a467 100644
--- a/cli/tests/journey/bootstrap.py
+++ b/cli/tests/journey/bootstrap.py
@@ -12,6 +12,8 @@
 from pathlib import Path
 import secrets
 import socket
+import ssl
+import stat
 import subprocess
 import sys
 import tempfile
@@ -19,7 +21,7 @@
 from urllib.request import urlopen
 from uuid import uuid4
 
-from client import JourneyClient
+from client import JourneyClient, RefreshingToken, installed_mcp
 from public_setup import configure_guide, publish_unpaid_terms, approve_and_activate
 from runtime import (
     durable_runtime,
@@ -35,10 +37,69 @@
 sys.path.insert(0, str(ROOT))
 sys.path.insert(0, str(BACKEND))
 sys.path.insert(0, str(BACKEND / "scripts"))
+sys.path.insert(0, str(ROOT / "scripts"))
+from identity_protocol_probe import IdentityProtocolProbe  # noqa: E402
 from local_flow_tokens import issue_flow_token  # noqa: E402
 from run_isolated_tests import NAME_RE  # noqa: E402
 from urllib.parse import urlsplit  # noqa: E402
 
+ACTORS = ("administrator", "manager", "finance", "operator", "alice", "bob")
+
+
+def connected_tokens(environment):
+    """Read rotating grants for isolated actors from the configured real provider."""
+    issuer = environment["WORKSTREAM_TOKEN_ISSUER"]
+    suffix = "/realms/flow"
+    if (
+        not issuer.endswith(suffix)
+        or environment.get("WORKSTREAM_TOKEN_AUDIENCE") != "workstream-api"
+    ):
+        raise RuntimeError(
+            "paired proof requires the configured Flow API issuer and audience"
+        )
+    provider = IdentityProtocolProbe(
+        issuer.removesuffix(suffix), ssl.create_default_context()
+    )
+    path = Path(environment["WORKSTREAM_CLI_JOURNEY_REFRESH_FILE"])
+    if not path.is_absolute():
+        raise RuntimeError("paired proof refresh file must be absolute")
+    descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+    with os.fdopen(descriptor, "rb") as stream:
+        metadata = os.fstat(stream.fileno())
+        if (
+            not stat.S_ISREG(metadata.st_mode)
+            or stat.S_IMODE(metadata.st_mode) != 0o600
+            or metadata.st_uid != os.getuid()
+            or not 0 < metadata.st_size <= 65_536
+        ):
+            raise RuntimeError("paired proof requires an owned private refresh file")
+        try:
+            grants = json.loads(stream.read(65_537))
+        except (ValueError, UnicodeError):
+            raise RuntimeError("paired proof refresh file is invalid") from None
+    if (
+        type(grants) is not dict
+        or set(grants) != {*ACTORS, "mcp"}
+        or any(
+            type(token) is not str or not 0 < len(token) <= 8192
+            for token in grants.values()
+        )
+    ):
+        raise RuntimeError(
+            "paired proof requires one refresh grant for each fixture actor and MCP"
+        )
+    return {
+        name: RefreshingToken(provider, "workstream-cli-login", grants[name])
+        for name in ACTORS
+    } | {
+        "mcp": RefreshingToken(
+            provider,
+            "workstream-mcp-proof",
+            grants["mcp"],
+            resource=environment["WORKSTREAM_MCP_RESOURCE_URL"],
+        ),
+    }
+
 
 def run_default_review_branch(client, tokens, actors, registry_entries):
     """Use the same public setup but leave required human review untouched."""
@@ -107,6 +168,7 @@ def main():
         WORKSTREAM_PROJECT_AGENT_MODEL_API="none",
         WORKSTREAM_PROJECT_AGENT_MODEL="none",
         WORKSTREAM_CELERY_TASK_ALWAYS_EAGER="false",
+        WORKSTREAM_SUBMISSION_FEEDBACK_EMAIL_ENABLED="false",
         WORKSTREAM_API_RATE_LIMIT_KEY_SECRET=base64.b64encode(
             secrets.token_bytes(32)
         ).decode(),
@@ -114,6 +176,18 @@ def main():
             secrets.token_bytes(32)
         ).decode(),
     )
+    mcp_executable = environment.get("WORKSTREAM_CLI_JOURNEY_MCP_EXECUTABLE")
+    paired_tokens = None
+    if mcp_executable:
+        if any(
+            environment.get(f"WORKSTREAM_CLI_JOURNEY_{stage}") != "1"
+            for stage in ("SETUP", "TASKS", "SUBMIT")
+        ):
+            raise RuntimeError(
+                "installed MCP proof requires the isolated submission stages"
+            )
+        paired_tokens = connected_tokens(environment)
+        environment.pop("WORKSTREAM_FLOW_AUTH_LOCAL_HMAC_SECRET")
     with socket.socket() as listener:
         listener.bind(("127.0.0.1", 0))
         port = listener.getsockname()[1]
@@ -168,7 +242,7 @@ def main():
                         "API readiness deadline exceeded; no journey pass"
                     )
                 client = JourneyClient(executable, origin, directory)
-                tokens = {
+                tokens = paired_tokens or {
                     name: issue_flow_token(
                         f"cli-journey-{name}",
                         [],
@@ -176,19 +250,30 @@ def main():
                         audience=audience,
                         secret=secret,
                     )
-                    for name in (
-                        "administrator",
-                        "manager",
-                        "finance",
-                        "operator",
-                        "alice",
-                        "bob",
-                    )
+                    for name in ACTORS
                 }
                 actors = {
-                    name: client.call(token, "whoami")["actor_profile_id"]
-                    for name, token in tokens.items()
+                    name: client.call(tokens[name], "whoami")["actor_profile_id"]
+                    for name in ACTORS
                 }
+                mcp = None
+                if mcp_executable:
+                    mcp = stack.enter_context(
+                        installed_mcp(
+                            Path(mcp_executable),
+                            origin,
+                            directory,
+                            environment,
+                            tokens["mcp"],
+                        )
+                    )
+                    if (
+                        mcp.call("workstream_profile_get", {})["actor_profile_id"]
+                        != actors["alice"]
+                    ):
+                        raise AssertionError(
+                            "MCP and CLI contributor identities differ"
+                        )
                 bootstrap = subprocess.run(
                     [
                         sys.executable,
@@ -344,10 +429,15 @@ def main():
                                 task_id,
                                 assignment_id,
                                 grant,
+                                mcp=mcp,
                             )
                             client.complete_stage(
                                 "submission_contribution_export_revocation"
                             )
+                            if mcp is not None:
+                                client.complete_stage(
+                                    "installed_mcp_submission_revision"
+                                )
                             inspect_submission_custody(
                                 client,
                                 tokens,
@@ -366,7 +456,10 @@ def main():
                             "result": "passed",
                             "cli_invocations": len(client.steps),
                             "verified_stages": client.completed_stages,
-                            "scope": "local manager-authored unpaid automated-acceptance branch",
+                            "scope": "isolated manager-authored unpaid submission journey",
+                            "authentication": "configured_flow_provider"
+                            if mcp
+                            else "isolated_local_hmac",
                         }
                     )
                 )
diff --git a/cli/tests/journey/client.py b/cli/tests/journey/client.py
index a8ba7d2e4..5b5072738 100644
--- a/cli/tests/journey/client.py
+++ b/cli/tests/journey/client.py
@@ -2,11 +2,18 @@
 
 from __future__ import annotations
 
+import asyncio
+import base64
+from collections.abc import Callable
+from contextlib import contextmanager
 import json
 import os
 from pathlib import Path
+import socket
 import subprocess
 import tempfile
+import time
+from urllib.request import ProxyHandler, build_opener
 from uuid import uuid4
 
 
@@ -26,7 +33,13 @@ def complete_stage(self, stage: str):
         self.completed_stages.append(stage)
         print(json.dumps({"stage": stage, "result": "passed"}), flush=True)
 
-    def call(self, token: str, *arguments: str, expected_exit: int | None = 0):
+    def call(
+        self,
+        token: str | Callable[[], str],
+        *arguments: str,
+        expected_exit: int | None = 0,
+    ):
+        token = token() if callable(token) else token
         environment = {
             key: value
             for key, value in os.environ.items()
@@ -97,3 +110,164 @@ def write_and_replay(self, token: str, *arguments: str, body: dict):
         if replay != first:
             raise AssertionError(f"exact replay changed receipt at {arguments[:3]!r}")
         return first
+
+
+class RefreshingToken:
+    """Use the provider's existing rotating refresh grant in this isolated proof."""
+
+    def __init__(
+        self,
+        provider,
+        client_id: str,
+        refresh_token: str,
+        *,
+        resource: str | None = None,
+    ):
+        self.provider = provider
+        self.client_id = client_id
+        self.refresh_token = refresh_token
+        self.resource = resource
+        self.access_token = ""
+        self.expires_at = 0.0
+
+    def __call__(self) -> str:
+        now = time.monotonic()
+        if self.expires_at - now < 150:
+            grant = {
+                "grant_type": "refresh_token",
+                "client_id": self.client_id,
+                "refresh_token": self.refresh_token,
+            }
+            if self.resource is not None:
+                grant["resource"] = self.resource
+            result = self.provider.request(
+                "/realms/flow/protocol/openid-connect/token", grant, form=True
+            )
+            access = result["access_token"]
+            refreshed = result["refresh_token"]
+            expires = result["expires_in"]
+            if (
+                type(expires) is not int
+                or expires <= 0
+                or any(
+                    type(value) is not str or not value for value in (access, refreshed)
+                )
+            ):
+                raise RuntimeError("identity provider returned unusable credentials")
+            self.access_token, self.refresh_token = access, refreshed
+            self.expires_at = now + expires
+        return self.access_token
+
+
+class McpJourneyClient:
+    """Drive the installed OAuth-protected MCP server through the SDK's HTTP transport."""
+
+    def __init__(self, origin: str, token: Callable[[], str]):
+        self.origin = origin
+        self.token = token
+
+    async def _call(self, name: str, arguments: dict, rejected: bool):
+        import httpx2
+        from mcp import ClientSession
+        from mcp.client.streamable_http import streamable_http_client
+        from mcp.types import CallToolResult
+
+        bearer = self.token()
+        async with (
+            asyncio.timeout(135),
+            httpx2.AsyncClient(
+                headers={"Authorization": "Bearer " + bearer},
+                timeout=130,
+                trust_env=False,
+            ) as transport,
+            streamable_http_client(
+                self.origin + "/mcp", http_client=transport
+            ) as streams,
+        ):
+            async with ClientSession(*streams, read_timeout_seconds=130) as session:
+                await session.initialize()
+                result = await session.call_tool(name, arguments)
+        if (
+            not isinstance(result, CallToolResult)
+            or result.is_error is not rejected
+            or not isinstance(result.structured_content, dict)
+        ):
+            raise AssertionError(
+                f"installed MCP tool returned an unexpected outcome for {name}"
+            )
+        if bearer in result.model_dump_json():
+            raise AssertionError("MCP credential disclosure; output withheld")
+        return result.structured_content
+
+    def call(self, name: str, arguments: dict, *, rejected: bool = False):
+        return asyncio.run(self._call(name, arguments, rejected))
+
+    def submit(self, task_id, assignment_id, archive, key, *, rejected=False):
+        return self.call(
+            "workstream_submission_create",
+            {
+                "task_id": task_id,
+                "assignment_id": assignment_id,
+                "idempotency_key": key,
+                "zip_base64": base64.b64encode(archive.read_bytes()).decode("ascii"),
+            },
+            rejected=rejected,
+        )
+
+
+@contextmanager
+def installed_mcp(
+    executable: Path, api_origin: str, directory: Path, environment: dict, token
+):
+    """Start and reap only the fixture's installed MCP process on loopback."""
+    with socket.socket() as listener:
+        listener.bind(("127.0.0.1", 0))
+        port = listener.getsockname()[1]
+    origin = f"http://127.0.0.1:{port}"
+    child = {
+        key: value
+        for key, value in os.environ.items()
+        if key in {"PATH", "LANG", "LC_ALL"}
+    }
+    child.update(
+        WORKSTREAM_API_URL=api_origin,
+        WORKSTREAM_MCP_HOST="127.0.0.1",
+        WORKSTREAM_MCP_PORT=str(port),
+        WORKSTREAM_MCP_TOKEN_ISSUER=environment["WORKSTREAM_TOKEN_ISSUER"],
+        WORKSTREAM_MCP_RESOURCE_URL=environment["WORKSTREAM_MCP_RESOURCE_URL"],
+        WORKSTREAM_MCP_EXCHANGE_SECRET_FILE=environment[
+            "WORKSTREAM_MCP_EXCHANGE_SECRET_FILE"
+        ],
+    )
+    opener = build_opener(ProxyHandler({}))
+    with (
+        (directory / "mcp.log").open("wb") as log,
+        subprocess.Popen(
+            [str(executable.resolve(strict=True))],
+            cwd=directory,
+            env=child,
+            stdout=log,
+            stderr=subprocess.STDOUT,
+        ) as process,
+    ):
+        try:
+            deadline = time.monotonic() + 30
+            while time.monotonic() < deadline and process.poll() is None:
+                try:
+                    with opener.open(
+                        origin + "/.well-known/oauth-protected-resource/mcp", timeout=1
+                    ) as response:
+                        if response.status == 200:
+                            break
+                except OSError:
+                    time.sleep(0.2)
+            else:
+                raise RuntimeError("installed MCP did not become ready")
+            yield McpJourneyClient(origin, token)
+        finally:
+            process.terminate()
+            try:
+                process.wait(timeout=10)
+            except subprocess.TimeoutExpired:
+                process.kill()
+                process.wait(timeout=10)
diff --git a/cli/tests/journey/source_audit.py b/cli/tests/journey/source_audit.py
index 43a67b3db..45f6cfbf0 100644
--- a/cli/tests/journey/source_audit.py
+++ b/cli/tests/journey/source_audit.py
@@ -36,6 +36,7 @@ async def _audit(
     byte_count: int,
     *,
     accepted: bool,
+    predecessor_submission_id: str | None,
 ) -> None:
     url = os.environ["WORKSTREAM_DATABASE_URL"]
     if not urlsplit(url).path.lstrip("/").startswith("workstream_test_"):
@@ -53,6 +54,7 @@ async def _audit(
                     o.raw_sha256, o.raw_byte_count, o.provider_generation,
                     o.sealed_upload_fence, o.namespace_id, o.namespace_fingerprint,
                     o.provider_profile, o.object_ref, o.accepted_source_sha256,
+                    o.assignment_id::text AS assignment_id, o.command_metadata,
                     selected.request_json AS selected_request,
                     charge.state AS charge_state, charge.accounted_bytes,
                     admission.source_operation_id::text AS admission_source,
@@ -151,10 +153,11 @@ async def _audit(
                 name: await connection.scalar(text(query), {"task_id": task_id})
                 for name, query in _COUNTS.items()
             }
+            attempts = 1 + int(predecessor_submission_id is not None)
             expected_counts = {
-                "submissions": 1,
-                "dispatches": 1,
-                "checker_runs": 1,
+                "submissions": attempts,
+                "dispatches": attempts,
+                "checker_runs": attempts,
                 "acceptances": int(accepted),
                 "reviews": 0,
                 "contributions": int(accepted),
@@ -164,6 +167,33 @@ async def _audit(
                 raise AssertionError(
                     "isolated task effect counts differ from the governed outcome"
                 )
+            if predecessor_submission_id is not None:
+                preparations = (
+                    await connection.execute(
+                        text("""
+                    SELECT id::text, submission_id::text, assignment_id::text,
+                        sequence, next_revision_round, preparation_sha256
+                    FROM task_revision_preparations WHERE task_id = CAST(:task_id AS uuid)
+                """),
+                        {"task_id": task_id},
+                    )
+                ).all()
+                metadata = row["command_metadata"]
+                if metadata[
+                    "predecessor_submission_id"
+                ] != predecessor_submission_id or preparations != [
+                    (
+                        metadata["revision_preparation_id"],
+                        predecessor_submission_id,
+                        row["assignment_id"],
+                        1,
+                        1,
+                        metadata["revision_preparation_sha256"],
+                    )
+                ]:
+                    raise AssertionError(
+                        "corrected source did not consume the one retained revision context"
+                    )
     finally:
         await engine.dispose()
 
@@ -175,6 +205,7 @@ def audit_accepted_source(
     archive: Path,
     *,
     accepted: bool,
+    predecessor_submission_id: str | None = None,
 ) -> None:
     """Observe exact source graph and downstream counts without changing state."""
     data = archive.read_bytes()
@@ -186,5 +217,6 @@ def audit_accepted_source(
             "sha256:" + sha256(data).hexdigest(),
             len(data),
             accepted=accepted,
+            predecessor_submission_id=predecessor_submission_id,
         )
     )
diff --git a/cli/tests/journey/submission_work.py b/cli/tests/journey/submission_work.py
index 71b8c6a1e..c7dd28f39 100644
--- a/cli/tests/journey/submission_work.py
+++ b/cli/tests/journey/submission_work.py
@@ -8,7 +8,6 @@
 import time
 from uuid import uuid4
 
-from task_work import create_claimed_task
 from source_audit import audit_accepted_source
 
 EXAMPLE = Path(__file__).resolve().parents[3] / "examples/incident_summary"
@@ -112,13 +111,20 @@ def _wait_for_stage(client, token, task_id, key, receipt, expected_stage):
     raise AssertionError("durable evaluation did not reach its governed outcome")
 
 
-def _submit(client, token, task_id, assignment_id, archive):
+def _submit(client, token, task_id, assignment_id, archive, *, mcp=None):
     key = str(uuid4())
     command = _command(task_id, assignment_id, archive, key)
-    receipt = client.call(token, *command)
+    receipt = (
+        client.call(token, *command)
+        if mcp is None
+        else mcp.submit(task_id, assignment_id, archive, key)
+    )
     if (
         receipt["status"] != "accepted"
         or receipt["processing_stage_at_acceptance"] != "finalization_pending"
+        or receipt["task_id"] != task_id
+        or receipt["assignment_id"] != assignment_id
+        or receipt["replayed"] is not False
     ):
         raise AssertionError("source command did not return T4 acceptance")
     replay = client.call(token, *command)
@@ -130,12 +136,37 @@ def _submit(client, token, task_id, assignment_id, archive):
     return key, receipt
 
 
-def _pre_missing_has_no_submission(client, token, task_id, assignment_id):
+def _assignment_status(client, token, task_id, assignment_id, *, mcp=None):
+    status = client.call(token, "task", "status", assignment_id)
+    if (status["assignment"]["assignment_id"], status["assignment"]["task_id"]) != (
+        assignment_id,
+        task_id,
+    ):
+        raise AssertionError("status did not retain the exact assignment")
+    if (
+        mcp is not None
+        and mcp.call("workstream_task_assignment_get", {"assignment_id": assignment_id})
+        != status
+    ):
+        raise AssertionError("CLI and MCP assignment status differ")
+    return status
+
+
+def _pre_missing_has_no_submission(client, token, task_id, assignment_id, *, mcp=None):
     key = str(uuid4())
-    command = _command(task_id, assignment_id, _package(client, "pre-missing"), key)
+    archive = _package(client, "pre-missing")
+    command = _command(task_id, assignment_id, archive, key)
     failure = client.call(token, *command, expected_exit=1)
     if failure["error"]["code"] != "pre_submission_checker_failed":
         raise AssertionError("missing summary was not rejected by real PRE")
+    details = failure["error"]["details"]
+    if mcp is not None:
+        rejected = mcp.submit(task_id, assignment_id, archive, key, rejected=True)
+        if (
+            rejected["code"] != "pre_submission_checker_failed"
+            or rejected["details"] != details
+        ):
+            raise AssertionError("MCP did not preserve the exact PRE rejection")
     observed = _progress(client, token, task_id, key)
     if (
         observed["operation_state"] != "rejected"
@@ -146,38 +177,55 @@ def _pre_missing_has_no_submission(client, token, task_id, assignment_id):
         raise AssertionError("rejected PRE candidate created downstream work")
     if client.call(token, "me", "submissions", "--task", task_id)["items"]:
         raise AssertionError("rejected PRE candidate created a Submission")
+    status = _assignment_status(client, token, task_id, assignment_id, mcp=mcp)
+    if (
+        status["next_action"] != "submit"
+        or status["intake"]["operation_id"] != observed["operation_id"]
+        or status["intake"]["pre_submission_results"] != details["results"]
+        or not any(
+            finding["code"] == "summary_missing"
+            and finding["message"] == "Add summary.json at the ZIP root."
+            and finding["path"] == "summary.json"
+            for result in details["results"]
+            if result["source"] == "project_external_checker"
+            for finding in result["findings"]
+        )
+    ):
+        raise AssertionError("PRE status lacks the exact actionable finding")
 
 
-def _incorrect_post_has_no_acceptance(client, tokens, project_id, previous_records):
-    task_id, assignment_id = create_claimed_task(
-        client, tokens, project_id, title="Reject incorrect incident counts"
-    )
+def _require_revision(client, token, project_id, task_id, assignment_id, *, mcp=None):
     archive = _package(client, "incorrect")
-    key, receipt = _submit(client, tokens["alice"], task_id, assignment_id, archive)
-    observed = _wait_for_stage(
-        client, tokens["alice"], task_id, key, receipt, "needs_revision"
-    )
+    key, receipt = _submit(client, token, task_id, assignment_id, archive)
+    observed = _wait_for_stage(client, token, task_id, key, receipt, "needs_revision")
     submission_id = observed["submission_id"]
-    outcome = client.call(tokens["alice"], "submission", "show", submission_id)
-    if outcome["status"] != "needs_revision":
-        raise AssertionError("incorrect shaped summary bypassed governed revision")
-    runs = client.call(tokens["alice"], "submission", "findings", submission_id)
-    if len(runs["items"]) != 1 or not any(
-        result["checker_name"] == "terminal.post.incident_summary_counts"
-        and result["status"] == "failed"
-        for result in runs["items"][0]["results"]
-    ):
-        raise AssertionError("incorrect counts lack real failed POST evidence")
-    records = client.call(tokens["alice"], "contributions", "--project", project_id)[
-        "items"
-    ]
-    if records != previous_records or any(
-        item["task_id"] == task_id for item in records
+    status = _assignment_status(client, token, task_id, assignment_id, mcp=mcp)
+    revision = status["assignment"]["revision"]
+    if (
+        status["current_status"] != "needs_revision"
+        or status["next_action"] != "revise"
+        or status["feedback_submission_id"] != submission_id
+        or revision["source_submission_id"] != submission_id
+        or revision["sequence"] != 1
+        or revision["next_revision_round"] != 1
+        or revision["disposition"] != "ready"
+        or not revision["deadline_at"]
+        or not any(
+            result["checker_name"] == "terminal.post.incident_summary_counts"
+            and result["status"] == "failed"
+            and result["path"] == "summary.json"
+            and result["worker_message"]
+            == "Recount all events and error events for each service."
+            for result in status["post_submission_results"]
+        )
     ):
+        raise AssertionError("POST status lacks the exact finding and revision terms")
+    if client.call(token, "contributions", "--project", project_id)["items"]:
         raise AssertionError("failed POST created acceptance, award or contribution")
     audit_accepted_source(
         receipt["operation_id"], submission_id, task_id, archive, accepted=False
     )
+    return submission_id
 
 
 def observe_review_pending(client, tokens, project_id, task_id, assignment_id):
@@ -210,13 +258,16 @@ def observe_review_pending(client, tokens, project_id, task_id, assignment_id):
 
 
 def submit_and_observe(
-    client, tokens, actors, project_id, task_id, assignment_id, grant
+    client, tokens, actors, project_id, task_id, assignment_id, grant, *, mcp=None
 ):
     token = tokens["alice"]
-    _pre_missing_has_no_submission(client, token, task_id, assignment_id)
+    _pre_missing_has_no_submission(client, token, task_id, assignment_id, mcp=mcp)
+    predecessor = _require_revision(
+        client, token, project_id, task_id, assignment_id, mcp=mcp
+    )
     archive = _package(client, "correct")
     archive_hash = "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest()
-    key, accepted = _submit(client, token, task_id, assignment_id, archive)
+    key, accepted = _submit(client, token, task_id, assignment_id, archive, mcp=mcp)
     observed = _wait_for_stage(client, token, task_id, key, accepted, "accepted")
     receipt = {
         "submission_id": observed["submission_id"],
@@ -224,21 +275,28 @@ def submit_and_observe(
     }
     outcome = client.call(token, "submission", "show", receipt["submission_id"])
     retained = client.call(token, "me", "submissions", "--task", task_id)
-    if retained["next_cursor"] is not None or len(retained["items"]) != 1:
-        raise AssertionError("submission replay did not retain exactly one attempt")
+    history = {item["version"]: item for item in retained["items"]}
     if (
-        retained["items"][0]["submission_id"] != receipt["submission_id"]
+        retained["next_cursor"] is not None
+        or len(retained["items"]) != 2
+        or set(history) != {1, 2}
+        or receipt["submission_version"] != 2
+        or (history[1]["submission_id"], history[1]["status"])
+        != (predecessor, "needs_revision")
+        or history[2]["submission_id"] != receipt["submission_id"]
         or outcome["id"] != receipt["submission_id"]
     ):
-        raise AssertionError("retained submission differs from accepted operation")
+        raise AssertionError(
+            "assignment did not retain exactly one revision and its original attempt"
+        )
     for field, value in {
         "task_id": task_id,
         "version": receipt["submission_version"],
         "status": "accepted",
     }.items():
-        if retained["items"][0][field] != value or outcome[field] != value:
+        if history[2][field] != value or outcome[field] != value:
             raise AssertionError("retained submission differs from accepted operation")
-    if retained["items"][0].get("artifact_hash") not in (None, archive_hash):
+    if history[2].get("artifact_hash") not in (None, archive_hash):
         raise AssertionError("retained submission differs from submitted ZIP")
     runs = client.call(token, "submission", "findings", receipt["submission_id"])
     if runs["next_cursor"] is not None or len(runs["items"]) != 1:
@@ -292,6 +350,22 @@ def submit_and_observe(
         raise AssertionError("accepted contribution lacks final acceptance provenance")
     if record["artifact_hash"] != archive_hash:
         raise AssertionError("accepted contribution does not bind the original ZIP")
+    status = _assignment_status(client, token, task_id, assignment_id, mcp=mcp)
+    if (
+        status["current_status"] != "accepted"
+        or status["next_action"] != "none"
+        or status["feedback_submission_id"] != receipt["submission_id"]
+        or status["accepted_evidence"]
+        != {
+            "contribution_id": record["contribution_id"],
+            "submission_id": receipt["submission_id"],
+            "artifact_hash": archive_hash,
+            "awards": [],
+        }
+    ):
+        raise AssertionError(
+            "assignment accepted evidence differs from its corrected ZIP"
+        )
     exported = client.call(tokens["finance"], "project", "contributions", project_id)
     if exported["items"] != records:
         raise AssertionError("authorized project export differs from own evidence")
@@ -324,8 +398,8 @@ def submit_and_observe(
         task_id,
         archive,
         accepted=True,
+        predecessor_submission_id=predecessor,
     )
-    _incorrect_post_has_no_acceptance(client, tokens, project_id, records)
     client.call(token, "project", "show", project_id)
     client.write_and_replay(
         tokens["manager"],

From 2f7d8d95c18598f36e869be1de16263c8bacf81d Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:29:52 +0100
Subject: [PATCH 443/513] Use current MCP protocol and distinct journey actors

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 15 +++++--
 .../test_journey_progress_identity.py         | 15 +++++++
 cli/tests/journey/bootstrap.py                | 42 +++++++++++++------
 cli/tests/journey/client.py                   | 23 ++++++----
 4 files changed, 71 insertions(+), 24 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index cfc34126b..19c06abd2 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12551,9 +12551,10 @@ fixture API and workers. Use its real, TLS-verified provider configuration.
 
 `WORKSTREAM_CLI_JOURNEY_REFRESH_FILE` is an absolute owned mode-0600 JSON object
 with fresh registered CLI refresh grants in `administrator`, `manager`,
-`finance`, `operator`, `alice`, and `bob`, plus `mcp` for the same Alice's
-registered MCP proof client. The maintained provider helper renews them and
-keeps rotated values in process memory. Supply `WORKSTREAM_MCP_RESOURCE_URL`
+`finance`, `operator`, `alice`, and `bob`, plus `mcp` containing `refresh_token`
+and the original `scope` from the same Alice's registered MCP proof client.
+The maintained provider helper renews them and keeps rotated values in process
+memory. Supply `WORKSTREAM_MCP_RESOURCE_URL`
 for that registered MCP audience and `WORKSTREAM_MCP_EXCHANGE_SECRET_FILE` for
 the current confidential exchange client. MCP listens only on loopback and
 calls the isolated API. This proof disables application feedback email.
@@ -12565,3 +12566,11 @@ process teardown. The earlier non-OAuth wheel did not provide that metadata.
 These local checks used no authentication request to a provider and no native
 submission. Real paired-tool, corrected same-assignment and live deployment
 qualification remain open until the maintained journey runs end to end.
+
+Independent review required the maintained MCP SDK mode `2026-07-28`, the exact
+negotiated protocol, distinct public actors before bootstrap and the original
+scope in the MCP refresh grant. The paired mode explicitly overrides any local
+dotenv HMAC setting with an empty value. 35 focused CLI cases passed after these
+corrections. An independent in-memory transport check used installed SDK 2.2.0
+and observed the current protocol and one exchanged request. No live provider
+account or token operation took place for this review.
diff --git a/cli/tests/integration/test_journey_progress_identity.py b/cli/tests/integration/test_journey_progress_identity.py
index 518042d4f..f5baadfc9 100644
--- a/cli/tests/integration/test_journey_progress_identity.py
+++ b/cli/tests/integration/test_journey_progress_identity.py
@@ -169,6 +169,7 @@ def request(path, document, *, form):
         "workstream-mcp-proof",
         "first",
         resource="https://mcp.example/mcp",
+        scope="workstream:access workstream-mcp-audience",
     )
     assert token() == token() == "access"
     now += 160
@@ -179,6 +180,20 @@ def request(path, document, *, form):
             "client_id": "workstream-mcp-proof",
             "refresh_token": value,
             "resource": "https://mcp.example/mcp",
+            "scope": "workstream:access workstream-mcp-audience",
         }
         for value in ("first", "rotated")
     ]
+
+
+def test_public_identity_rejects_shared_role_subject_before_bootstrap(monkeypatch):
+    monkeypatch.syspath_prepend(str(PATH.parent))
+    monkeypatch.syspath_prepend(str(PATH.parents[3] / "backend"))
+    from bootstrap import ACTORS, public_actors
+
+    tokens = {name: name for name in ACTORS}
+    client = SimpleNamespace(call=lambda token, command: {"actor_profile_id": token})
+    assert public_actors(client, tokens) == tokens
+    tokens["finance"] = tokens["manager"]
+    with pytest.raises(AssertionError, match="six distinct public actor profiles"):
+        public_actors(client, tokens)
diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py
index 47b15a467..8bde939fb 100644
--- a/cli/tests/journey/bootstrap.py
+++ b/cli/tests/journey/bootstrap.py
@@ -46,6 +46,15 @@
 ACTORS = ("administrator", "manager", "finance", "operator", "alice", "bob")
 
 
+def public_actors(client, tokens):
+    actors = {
+        name: client.call(tokens[name], "whoami")["actor_profile_id"] for name in ACTORS
+    }
+    if len(set(actors.values())) != len(ACTORS):
+        raise AssertionError("journey requires six distinct public actor profiles")
+    return actors
+
+
 def connected_tokens(environment):
     """Read rotating grants for isolated actors from the configured real provider."""
     issuer = environment["WORKSTREAM_TOKEN_ISSUER"]
@@ -77,17 +86,26 @@ def connected_tokens(environment):
             grants = json.loads(stream.read(65_537))
         except (ValueError, UnicodeError):
             raise RuntimeError("paired proof refresh file is invalid") from None
-    if (
-        type(grants) is not dict
-        or set(grants) != {*ACTORS, "mcp"}
-        or any(
-            type(token) is not str or not 0 < len(token) <= 8192
-            for token in grants.values()
+    if type(grants) is not dict or set(grants) != {*ACTORS, "mcp"}:
+        raise RuntimeError(
+            "paired proof requires one refresh grant for each fixture actor and MCP"
         )
+    mcp = grants["mcp"]
+    if (
+        type(mcp) is not dict
+        or set(mcp) != {"refresh_token", "scope"}
+        or type(mcp["scope"]) is not str
+        or not 0 < len(mcp["scope"]) <= 128
+        or "workstream:access" not in mcp["scope"].split()
     ):
         raise RuntimeError(
-            "paired proof requires one refresh grant for each fixture actor and MCP"
+            "paired proof requires the original MCP refresh grant and scopes"
         )
+    if any(
+        type(token) is not str or not 0 < len(token) <= 8192
+        for token in [*(grants[name] for name in ACTORS), mcp["refresh_token"]]
+    ):
+        raise RuntimeError("paired proof received an invalid refresh grant")
     return {
         name: RefreshingToken(provider, "workstream-cli-login", grants[name])
         for name in ACTORS
@@ -95,8 +113,9 @@ def connected_tokens(environment):
         "mcp": RefreshingToken(
             provider,
             "workstream-mcp-proof",
-            grants["mcp"],
+            mcp["refresh_token"],
             resource=environment["WORKSTREAM_MCP_RESOURCE_URL"],
+            scope=mcp["scope"],
         ),
     }
 
@@ -187,7 +206,7 @@ def main():
                 "installed MCP proof requires the isolated submission stages"
             )
         paired_tokens = connected_tokens(environment)
-        environment.pop("WORKSTREAM_FLOW_AUTH_LOCAL_HMAC_SECRET")
+        environment["WORKSTREAM_FLOW_AUTH_LOCAL_HMAC_SECRET"] = ""
     with socket.socket() as listener:
         listener.bind(("127.0.0.1", 0))
         port = listener.getsockname()[1]
@@ -252,10 +271,7 @@ def main():
                     )
                     for name in ACTORS
                 }
-                actors = {
-                    name: client.call(tokens[name], "whoami")["actor_profile_id"]
-                    for name in ACTORS
-                }
+                actors = public_actors(client, tokens)
                 mcp = None
                 if mcp_executable:
                     mcp = stack.enter_context(
diff --git a/cli/tests/journey/client.py b/cli/tests/journey/client.py
index 5b5072738..d8279ebbd 100644
--- a/cli/tests/journey/client.py
+++ b/cli/tests/journey/client.py
@@ -122,11 +122,13 @@ def __init__(
         refresh_token: str,
         *,
         resource: str | None = None,
+        scope: str | None = None,
     ):
         self.provider = provider
         self.client_id = client_id
         self.refresh_token = refresh_token
         self.resource = resource
+        self.scope = scope
         self.access_token = ""
         self.expires_at = 0.0
 
@@ -140,6 +142,7 @@ def __call__(self) -> str:
             }
             if self.resource is not None:
                 grant["resource"] = self.resource
+                grant["scope"] = self.scope
             result = self.provider.request(
                 "/realms/flow/protocol/openid-connect/token", grant, form=True
             )
@@ -168,7 +171,7 @@ def __init__(self, origin: str, token: Callable[[], str]):
 
     async def _call(self, name: str, arguments: dict, rejected: bool):
         import httpx2
-        from mcp import ClientSession
+        from mcp import Client
         from mcp.client.streamable_http import streamable_http_client
         from mcp.types import CallToolResult
 
@@ -177,16 +180,20 @@ async def _call(self, name: str, arguments: dict, rejected: bool):
             asyncio.timeout(135),
             httpx2.AsyncClient(
                 headers={"Authorization": "Bearer " + bearer},
+                follow_redirects=False,
                 timeout=130,
                 trust_env=False,
-            ) as transport,
-            streamable_http_client(
-                self.origin + "/mcp", http_client=transport
-            ) as streams,
+            ) as http_client,
         ):
-            async with ClientSession(*streams, read_timeout_seconds=130) as session:
-                await session.initialize()
-                result = await session.call_tool(name, arguments)
+            transport = streamable_http_client(
+                self.origin + "/mcp", http_client=http_client
+            )
+            async with Client(server=transport, mode="2026-07-28") as client:
+                if client.protocol_version != "2026-07-28":
+                    raise AssertionError(
+                        "installed MCP negotiated a different protocol"
+                    )
+                result = await client.call_tool(name, arguments)
         if (
             not isinstance(result, CallToolResult)
             or result.is_error is not rejected

From c3299a1da34540082b834affebb7d7fdf8238e6b Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:36:23 +0100
Subject: [PATCH 444/513] Record passing maintained native journey and release
 candidates

---
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     |  1 +
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 44 +++++++++++++++++++
 2 files changed, 45 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index 64d38f9e8..6110ac47d 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -43,6 +43,7 @@ work. Existing reward owners remain authoritative.
 - [ ] Approved project and governing task guides are readable/downloadable before claim under exact contributor authority.
 - [ ] Assignment-ID status exposes current safe feedback, processing activity, revision terms and accepted evidence without internal-ID discovery.
 - [x] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits.
+- [x] Maintained CLI baseline at `c715dbd47`: real remote PRE rejection, acceptance/replay, T5, automatic POST acceptance, incorrect POST revision, unpaid contribution custody and default review_pending; schema0093 test cleanup passed.
 - [ ] Combined public contributor journey proves correction, revision, replay, history and applicable existing awards on the integrated code.
 - [ ] Quality-feedback email uses the stable assignment ID for POST revision requests and revision-limit rejection, with a dedicated consumer and no infrastructure-failure notifications; qualify delivery after sender DNS verification and private key configuration.
 
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 19c06abd2..f1436e2cc 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12574,3 +12574,47 @@ dotenv HMAC setting with an empty value. 35 focused CLI cases passed after these
 corrections. An independent in-memory transport check used installed SDK 2.2.0
 and observed the current protocol and one exchanged request. No live provider
 account or token operation took place for this review.
+
+
+### Maintained current-source native CLI journey: passed
+
+The corrected maintained CLI journey completed at frozen `c715dbd47` against
+real isolated PostgreSQL/MinIO and the dedicated remote Smol runner with current
+placement binary/gateway and unchanged exact profile. All 540 built-CLI calls
+completed their expected checks. Public authored guide activation and claim,
+real selected PRE rejection without Submission, corrected T4 and exact replay,
+T5 retained-source finalization, required POST automatic acceptance and exact
+unpaid contribution/source lineage, incorrect POST `needs_revision`, export and
+role-revocation checks, Operator custody, and default `review_pending` all passed.
+No human Review or unpaid award was fabricated. The finalizer, POST, scanner and
+other workload consumers ran on their dedicated queues.
+
+Terminal receipt: `/tmp/workstream-paired-native-aopmeffy/journey.log`; launcher
+exit0. `cleanup.json` records schema `0093_verified_email_observation`, exact
+source commit and successful database, MinIO and overall cleanup. CLI receipts
+and runtime logs are retained privately in that run's evidence directory. This
+is a local API using the maintained isolated identity fixture and a real remote
+runner, not a deployed API or real hosted identity qualification. Same-assignment
+corrected revision/MCP, source-first fault/isolation/capacity, multiple nodes and
+hosted cutover remain open. The fixture-only guide fix is in `c715dbd47`.
+
+### Reconciled release candidates: built and backend published
+
+Both backend SDK variants from source `c715dbd47`, tree
+`aeddbbc03510250eaf8cd948853e8df86ba50773`, passed the strict native-hosted image
+verifier on the API host. Agents image digest:
+`sha256:33158596d19bf26dbdd669f403a465b981572b6a0ae80eefbc1bdb863f6c0251`;
+OmniCore image digest:
+`sha256:d294054ecde8bcfc04c2be1dee505b9958d8c303bd666bd829afde074edec0d7`.
+Both were published to immutable candidate tags in workstream-backend ECR and
+read back by exact repository digest. The temporary Docker registry credential
+file was removed by the publisher's finally block. Build receipt is
+`/tmp/workstream-host-image-c715dbd47001/host-only-build.json`; publication is
+`/tmp/workstream-published-1795699780475858533.json`.
+
+Matching MCP image `sha256:47e49c0861a970d5e220187b5722d5623a0304b0deaef276cb503956c140c2f9`
+built and passed the maintained container fixture:135 tools, restart,
+replacement and stale-namespace negative control. Receipt:
+`/tmp/workstream-mcp-host-proof-c715.json`. That fixture is not real provider
+or connected submission proof. No running API service, migration, hosted
+configuration or deployed image changed in these build/publication operations.

From 33f1cae8852860e45adaf742343cb4164bd0cd9f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:37:05 +0100
Subject: [PATCH 445/513] Measure command latency in private journey receipts

---
 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 7 +++++++
 cli/tests/journey/client.py                               | 3 +++
 2 files changed, 10 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index f1436e2cc..514a7f8b2 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12618,3 +12618,10 @@ replacement and stale-namespace negative control. Receipt:
 `/tmp/workstream-mcp-host-proof-c715.json`. That fixture is not real provider
 or connected submission proof. No running API service, migration, hosted
 configuration or deployed image changed in these build/publication operations.
+
+
+For the next maintained journey, private CLI receipts additionally record
+monotonic command elapsed seconds around the built subprocess. This measures
+upload/PRE round-trip latency without tokens, new product settings or a changed
+timeout, so C01 can use observed durations rather than an assumed latency target.
+It does not change CLI responses, pass criteria or execution deadlines.
diff --git a/cli/tests/journey/client.py b/cli/tests/journey/client.py
index d8279ebbd..92c7413b4 100644
--- a/cli/tests/journey/client.py
+++ b/cli/tests/journey/client.py
@@ -46,6 +46,7 @@ def call(
             if key in {"PATH", "LANG", "LC_ALL"}
         }
         environment.update(WORKSTREAM_API_URL=self.origin, WORKSTREAM_TOKEN=token)
+        started = time.monotonic()
         result = subprocess.run(
             [str(self.executable), *arguments, "--output", "json"],
             env=environment,
@@ -55,6 +56,7 @@ def call(
             timeout=180,
             check=False,
         )
+        elapsed_seconds = time.monotonic() - started
         if token and token in result.stdout + result.stderr:
             raise AssertionError("CLI credential disclosure; output withheld")
         # Never print input contents, credentials, or arbitrary server output.
@@ -67,6 +69,7 @@ def call(
                     {
                         "arguments": arguments,
                         "exit_code": result.returncode,
+                        "elapsed_seconds": elapsed_seconds,
                         "stdout": result.stdout,
                         "stderr": result.stderr,
                     },

From 73d81da662dfa4ec61856e6b5c71d906946a55ec Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:40:38 +0100
Subject: [PATCH 446/513] Record current managed PRE substitution qualification

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md    | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 514a7f8b2..9173977ea 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -11137,6 +11137,18 @@ Ruff/whitespace checks and unchanged structure passed. Root inspected the bounde
 draft with no scoped code blocker; final clean content binding follows this
 evidence-only append. Full goal/hosted CI qualification remains outside scope.
 
+At clean `2f7d8d95c18598f36e869be1de16263c8bacf81d`, the retained public
+managed-style substitution passed in 62.94 seconds on schema 0093. The
+test exercised signed ZIP intake, bound managed PRE evidence and cleanup,
+acceptance replay, and production OUTBOX/T5 finalization of the exact source.
+The separate selected factory/runtime and failure/cancellation contract
+passed four cases in 4.72 seconds. The isolated launcher provisioned and
+probed MinIO and cleaned its owned bucket, database, and role. The exact ZIP
+case stores its source through the Local adapter. This qualifies controlled
+managed-style substitution through the current typed contracts. Receipts:
+`/tmp/pr708-a30-2f7d-pure.log` and `/tmp/pr708-a30-2f7d-isolated.log`
+with its adjacent metadata JSON.
+
 ### Dedicated worker queues and durable outbox publication
 
 PRE6 proved the public native launch failure, same-key failed replay, and fresh

From cce8894fabf510f33c3139c1ea29423d7a2d1c51 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:55:28 +0100
Subject: [PATCH 447/513] Record MCP publication and read-only deployed schema
 census

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md    | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 9173977ea..73a4bce90 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12637,3 +12637,15 @@ monotonic command elapsed seconds around the built subprocess. This measures
 upload/PRE round-trip latency without tokens, new product settings or a changed
 timeout, so C01 can use observed durations rather than an assumed latency target.
 It does not change CLI responses, pass criteria or execution deadlines.
+
+
+The matching MCP candidate was subsequently published and read back at ECR
+repository digest `sha256:47e49c0861a970d5e220187b5722d5623a0304b0deaef276cb503956c140c2f9`.
+Publisher exit0 and private receipt
+`/tmp/workstream-published-1795700199907300212.json` confirm the digest; its
+owned Docker registry credential file was removed. This is publication only.
+A fresh read-only deployed database census still reports
+`0069_remove_artifact_proof`, with zero workstream_tasks, submissions,
+contribution_records and final_acceptances. Other retained tables are not
+claimed empty. A fresh drain, backup and complete retained-data check remain
+necessary immediately before migration. No live service or schema changed.

From 71410b055ac19e0b509c77a4937581822d2f6ca5 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 15:17:10 +0100
Subject: [PATCH 448/513] Record real-provider CLI and MCP revision journey
 proof

---
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     | 22 +++++++++-------
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 26 +++++++++++++++++++
 docs/roadmap_status.md                        |  8 +++---
 3 files changed, 42 insertions(+), 14 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index 6110ac47d..c5de61832 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -41,18 +41,20 @@ work. Existing reward owners remain authoritative.
 - [x] Four required submission inputs and optional feedback; backend-selected revision context and exact actor-scoped replay.
 - [x] Forward migration preserves historical accepted commands and refuses unsafe old in-flight work before mutation.
 - [ ] Approved project and governing task guides are readable/downloadable before claim under exact contributor authority.
-- [ ] Assignment-ID status exposes current safe feedback, processing activity, revision terms and accepted evidence without internal-ID discovery.
+- [x] Assignment-ID status exposes rejected intake feedback, revision terms and accepted evidence in the connected journey without internal-ID discovery.
+- [ ] Qualify live pending processing through assignment status; the connected journey observed it through operation progress.
 - [x] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits.
 - [x] Maintained CLI baseline at `c715dbd47`: real remote PRE rejection, acceptance/replay, T5, automatic POST acceptance, incorrect POST revision, unpaid contribution custody and default review_pending; schema0093 test cleanup passed.
-- [ ] Combined public contributor journey proves correction, revision, replay, history and applicable existing awards on the integrated code.
+- [x] Combined CLI/MCP journey at `73d81da66` proves actionable PRE/POST feedback, same-assignment correction, replay, retained versions and exact unpaid acceptance/contribution through real isolated Keycloak and the remote runner.
 - [ ] Quality-feedback email uses the stable assignment ID for POST revision requests and revision-limit rejection, with a dedicated consumer and no infrastructure-failure notifications; qualify delivery after sender DNS verification and private key configuration.
 
-The checked items have focused contract and PostgreSQL proof. The guide and
-assignment status changes are implemented and await the connected native proof.
+The checked items have focused contract/PostgreSQL proof and the maintained
+connected CLI/MCP journey described above. Hosted deployment remains separate.
 The dedicated queue topology and isolated scanner-to-T5 regression are integrated.
 PR722 removes the retired experimental native harness, including branch-only
 extensions. Its receipts remain historical; current native qualification must
-use maintained client/runtime owners and the current authentication boundary. Combined native execution and deployed
+use maintained client/runtime owners and the current authentication boundary.
+The connected real-provider journey now passes; native fault/capacity and deployed
 qualification remain open. The managed-style adapter substitution passed through public
 ZIP acceptance, retained source custody, real T5 owner delivery and replay;
 it does not establish a deployed managed provider or broker-consumer proof.
@@ -66,7 +68,7 @@ publication must remain available while POST execution is stopped or saturated;
 it must not share the POST or submission-finalization consumer. The PRE6 drill
 accepted a fresh source but exposed publication waiting behind the paused general
 worker. Dedicated scanner delivery now has a real Redis/prefork T5 proof;
-combined native and deployed confirmation remain open.
+the connected journey passes, while saturation and deployed confirmation remain open.
 The application instance is a verified t3.large; the dedicated always-on runner
 is an m7i.large with native KVM. App-origin mTLS health and native transport
 smoke receipts establish connectivity. V14 also proves the connected local API
@@ -120,13 +122,13 @@ journey. The remaining cleanup and verification requirements below still apply.
 
 | Order | Required outcome | Concrete finishing evidence |
 | --- | --- | --- |
-| 1 | Reproduce the connected proof on the deployed API | V14 passes real PRE/T5/POST, automatic acceptance, exact ZIP/Contribution export, rejection, replay and default review_pending with a local API and separate AWS runner. The actual deployed API/consumers remain to activate and prove. |
-| 2 | Finish affected qualification callers | Preparation API/materialization and the admission-only TASK writer are removed. PR722 retires the experimental harness; complete current native journey and fault proof through maintained client/runtime owners using raw ZIP acceptance and dedicated finalization. Do not restore the old harness. |
+| 1 | Reproduce the connected proof on the deployed API | The maintained paired journey at `73d81da66` passes real PRE/T5/POST, same-assignment correction, automatic acceptance, exact ZIP/Contribution export, rejection, replay and default review_pending with an isolated real identity provider, local API and separate AWS runner. The actual deployed API/consumers remain to activate and prove. |
+| 2 | Finish affected qualification callers | Preparation API/materialization and the admission-only TASK writer are removed. PR722 retires the experimental harness; the maintained native CLI/MCP journey passes; complete its remaining fault proof through the same owners using raw ZIP acceptance and dedicated finalization. Do not restore the old harness. |
 | 3 | Complete separate-runner integration and runtime/provider/resource qualification | Activate the prepared authenticated remote configuration on the app deployment; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. |
 | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. |
 | 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. |
 
-The connected public journey passed at 85ce76e17 (V14): 573 CLI invocations,
+The historical connected public journey passed at 85ce76e17 (V14): 573 CLI invocations,
 real PRE/T4/T5/POST, exact source and Contribution/export custody, PRE/POST
 rejection and default review_pending; owned database/bucket cleanup passed.
 Live AWS source qualification passed at 074cade5e with the actual restricted
@@ -159,7 +161,7 @@ This is the final qualification queue, not a claim that all listed code is absen
 
 | IDs | Existing implementation/focused evidence | Required closure |
 | --- | --- | --- |
-| A01–A03 | V14 connected public API/CLI journey with real separate-runner PRE and POST, T4/T5 and exact source checks | Reconcile each requirement and reproduce on the deployed release. |
+| A01–A03 | Current paired CLI/MCP journey at `73d81da66` with real isolated Keycloak, separate-runner PRE and POST, T4/T5 and exact source checks | Reconcile each requirement and reproduce on the deployed release. |
 | A04–A08 | Metadata/body replay, competing custody, interruption and T4 uncertainty tests | Reconcile exact cases and execute integrated final-head failure/retry matrix. |
 | A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Redis publication outage and Celery child-redelivery proofs passed; reconcile the remaining exact cases at the final head. |
 | A14–A18 | Cleanup lock/retention/charge owners, Local/MinIO tests and live AWS exact-version/lost-ack cleanup with retained-source survival | Production worker sweeps and exact acceptance-case reconciliation. |
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 73a4bce90..1c6982124 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12649,3 +12649,29 @@ A fresh read-only deployed database census still reports
 contribution_records and final_acceptances. Other retained tables are not
 claimed empty. A fresh drain, backup and complete retained-data check remain
 necessary immediately before migration. No live service or schema changed.
+
+
+### Maintained real-provider CLI/MCP revision journey: passed
+
+Frozen `73d81da66` completed all seven maintained journey stages using real
+Keycloak 26.8.2, six distinct PKCE/refresh identities, same-subject MCP exchange,
+the installed OAuth MCP wheel on protocol 2026-07-28, real PostgreSQL/MinIO and
+the separate native runner. PRE rejection was shared exactly across CLI/MCP;
+wrong-count POST required revision; corrected ZIP upload through MCP reused the
+original assignment and replayed exactly through CLI. Version1 history, one
+revision preparation, version2 final acceptance and one unpaid contribution
+were verified, with no fabricated Review or award. Exact source retention,
+export/revocation, Operator custody and default review_pending checks passed.
+There were 477 CLI calls; the full command latency receipts include 85.09s PRE
+rejection, 88.46s initial acceptance and sub-two-second exact replay. These are
+observations under the qualification profile, not production latency promises.
+
+The launcher terminated exit0. Evidence is retained privately under
+`/tmp/workstream-paired-native-m66en19e`; cleanup.json confirms schema0093 and
+successful database/MinIO/overall cleanup. The real identity fixture also
+terminated exit0; `/tmp/workstream-local-flow-2f7d8d95.D5Vz8y/cleanup.json`
+confirms its containers/network are gone and shared CA bundles unchanged.
+Its private refresh grants, exchange secret and environment handoff were
+removed. Only disposable copied interpreter trust stores were modified.
+This qualifies the current connected client/runtime path with an isolated real
+provider; it does not claim the hosted API/worker release or live email delivery.
diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md
index 368c2b14b..37a29ad29 100644
--- a/docs/roadmap_status.md
+++ b/docs/roadmap_status.md
@@ -696,15 +696,15 @@ cannot be reused as post-submission review-gate evidence. See the
 | Project Guide source custody | **Live foundation** | Guide creation declares documents and task examples; public document upload; immutable internal metadata snapshots; draft guide and review/revision policy writes with fresh-authorized exact replay of original receipts; exact run-scoped setup reads and assigned-task locked-original reads; S3-backed originals and isolated agent document inspection; exact document generation through separate manager approvals and public exact-authorized CP07 activation; Project Manager guide list, guide detail, activation readiness dry run and verified original read-back (PILOT-READ-3); the CLI exposes existing administrative active-chain and retained sufficiency/artifact-policy reads, keyed human sufficiency writes, and separate manual artifact-policy draft create/update with backend-owned policy decisions | Hosted original upload/read-back, task examples and Celery inference are proven. The current guide has independent human attachments, separate approvals and activation; earlier guide approvals remain retained history. Complete reader/isolation and contribution-journey scenarios; manual drafts are not compiled activation proposals and deployed CLI remains separate |
 | Unified Project Guide compilation | **Live setup and manager proposal operations** | Upload commits custody only; an explicit exact-project PM request selects assistance (`/setup`) or provider-free uploaded manager rules (`/requirements/compile`) and dispatches one immutable attempt through Celery; complete result and crash/recovery custody; distinct pre/post proposals; typed per-requirement classification and checker specifications; deterministic sufficiency and submission-artifact-policy projections; immutable authorized setup finalization; public exact manager review, pre-submit approval and manual correction dispatch; automatic deterministic post-policy derivation, public complete policy read, separate approval and shared correction custody. Neutral read/search tools support statically registered OpenAI Agents SDK and OmniCoreAgent adapters in mutually exclusive inference images, while provider-free `manager_authored` compiles a manager-uploaded rules document with no inference or provider resources ([runtime initiative](../.commitrail/initiatives/WS-AGENT-001/OVERVIEW.md), [manager-authored record](../.commitrail/changes/manager-authored-guide-runtime.md)). Inference attempts snapshot an exact immutable model profile and use the shared project-funded proxy; fixed document-tool limits must fit that profile and provider credentials remain outside the setup process. PR #697 supplies a source-sufficient proposal even without registered implementations; retained prior results keep exact hashes and reads and cannot execute through a compatibility path. Exact Omni SDK, mutually exclusive release-image, parser-isolation and real-MinIO proofs pass. Both inference adapters pass the same original-guide public API, durable Celery, real-parser and MinIO path; the Omni run stopped at a warning-ready manager draft with no bindings, approval or activation. The Terminal Systems handoff has project-owned PRE and POST implementations. POST uses the shared bounded model session, isolated trial capability and approved revision material. PR #697 removes registry, image and runtime choices from model input and output; human-selected phase attachments are validated at approval. Initial setup receives assigned guide documents and task examples only, apart from trusted system instructions. Explicit corrections additionally receive the PM's bounded written feedback, without prior proposals or image selections. Project semantics remain outside the generic Rust service. The [checker implementation](../examples/terminal_systems/checkers/README.md) separates rule, service-image, storage and trial qualification. | Historical source-only setup and explicit PM correction are live-proven. Hosted Garden uploads prove no implicit request or model effects; explicit provider-free compilation/replay, separate approvals/activation, task claim and real PRE failure/replay are proven without a Submission. Optional inference-request deployment and committed-request recovery remain separate; the live Garden v3 drill separately verified the open PR current head and trusted CI under an explicit zero-GitHub-approval configuration, then accepted one Submission with an earned 100 FLOW award. Earlier guides and tasks retain their original locks. Controlled composition alone establishes no live GitHub or review fact. [Garden evidence](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/garden-hosted-drill-2026-11-06.md). Guide 28 suggestions were independently mapped by the manager to one external PRE and POST image; separate approvals/activation led to the small task's accepted v2 and public contribution. Earlier guide 25/26 evidence remains retained. [Current checkpoint](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/terminal-systems-hosted-drill-2026-10-27.md). |
 | Contribution policy administration | **Public Finance policy workflow; binding administration internal** | Internal Finance Authority adapter-binding lifecycle; public ContributionPolicy discovery/read/create/update/publish/retire with exact Finance Authority and recoverable draft selectors, and a Finance list of every version (PILOT-READ-3); immutable operation and event history; internal exact selected-version validation; CP07 binding with live exact-project manager authority of the selected published version to the active guide generation | The bounded local drill and hosted unpaid-policy publication/read-back passed. Remaining policy branches and complete contribution effects need qualification; publication alone creates no contribution |
-| Task readiness and claim | **Foundation with grant-backed manager and contributor commands** | Task records, assignments and locked work context; guide-bound ContributionPolicyVersion locked before `READY` and copied to TaskAssignment; detached project/guide display; public project-scoped ready, management and operational queues with distinct current grant authority and signed bounded live pagination, with typed task status and manager filters by status, assignee, native import batch and update time (PILOT-READ-2); contributor cross-project own-assignment, attempt and summary reads under current Submitter grants (PILOT-READ-2); Project Manager project-wide attempt, claim, summary and import-batch reads (PILOT-READ-3); public contributor/management detail with exact project and assignment authority; PR #708 adds approved project originals before claim and an exact own-assignment status, feedback and evidence read; separate current live work-context projections with exact receipt-selected review/revision/ContributionPolicy identities and no obsolete economic fields; explicit management/operational/audit locked-context projections using one historical resolver, with separate public manager, system-Operator and Audit Authority access; immutable contributor/management requirements using one historical translator, with public exact Contributor and Manager authority; the CLI exposes the three exact manager requirements/context reads separately from contributor commands (WS-CLI-001-27); bounded public Audit Authority lifecycle evidence with atomic project/task scoping and exact transition references; separate CLI audit commands consume those two existing Audit Authority GETs with explicit continuation; public manager create/screen/release use exact covered Project Manager authority, atomic audit and replay; claim/contributor context use exact-project Submitter grants; ready and own-assignment context list exact locked originals and `task.guide.read` verifies each download before delivery; separate manager context; durable claim retry receipts with fresh authority and exact assignment checks; hidden exact-assignment invalidation with committed cause verification, delivery fencing, exact fixed-service authority and decision-bound immutable release evidence; atomic authority-loss publication and registered prefork delivery; PILOT-14 exposes both locked contribution types in ready rows and Contributor detail for active exact-project Submitters or Reviewers as unpaid or exact instrument/unit/quantity awards, without Finance binding facts; claim remain Submitter-only | The bounded local journey passed; hosted import, screening, release, immediate claim and exact Claim replay passed for queue recovery. Complete the remaining authority/recovery matrix and contribution journey |
+| Task readiness and claim | **Foundation with grant-backed manager and contributor commands** | Task records, assignments and locked work context; guide-bound ContributionPolicyVersion locked before `READY` and copied to TaskAssignment; detached project/guide display; public project-scoped ready, management and operational queues with distinct current grant authority and signed bounded live pagination, with typed task status and manager filters by status, assignee, native import batch and update time (PILOT-READ-2); contributor cross-project own-assignment, attempt and summary reads under current Submitter grants (PILOT-READ-2); Project Manager project-wide attempt, claim, summary and import-batch reads (PILOT-READ-3); public contributor/management detail with exact project and assignment authority; PR #708 adds approved project originals before claim and an exact own-assignment status, feedback and evidence read; separate current live work-context projections with exact receipt-selected review/revision/ContributionPolicy identities and no obsolete economic fields; explicit management/operational/audit locked-context projections using one historical resolver, with separate public manager, system-Operator and Audit Authority access; immutable contributor/management requirements using one historical translator, with public exact Contributor and Manager authority; the CLI exposes the three exact manager requirements/context reads separately from contributor commands (WS-CLI-001-27); bounded public Audit Authority lifecycle evidence with atomic project/task scoping and exact transition references; separate CLI audit commands consume those two existing Audit Authority GETs with explicit continuation; public manager create/screen/release use exact covered Project Manager authority, atomic audit and replay; claim/contributor context use exact-project Submitter grants; ready and own-assignment context list exact locked originals and `task.guide.read` verifies each download before delivery; separate manager context; durable claim retry receipts with fresh authority and exact assignment checks; hidden exact-assignment invalidation with committed cause verification, delivery fencing, exact fixed-service authority and decision-bound immutable release evidence; atomic authority-loss publication and registered prefork delivery; PILOT-14 exposes both locked contribution types in ready rows and Contributor detail for active exact-project Submitters or Reviewers as unpaid or exact instrument/unit/quantity awards, without Finance binding facts; claim remain Submitter-only | The bounded local journey passed; hosted import, screening, release, immediate claim and exact Claim replay passed for queue recovery. Complete the remaining authority/recovery matrix and hosted contribution journey; the isolated real-provider CLI/MCP contribution journey passes |
 | Operator task CLI | **Existing public task operations consumed by the CLI** | The Operator CLI provides separate status-only project pages and exact-project locked-reference reads. Backend Operator authority, assignment consistency, locked lineage and audit remain decisive. Claim starts contributor work atomically; there is no Operator start command. | Native public-API proof is bounded to existing fixtures; hosted/deployed operation, other Operator workflows and published binary remain separate |
 | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent |
 | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS |
 | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate |
-| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | Qualify the combined CLI/MCP submitter journey against the updated trusted intake image and dedicated Celery workers. Preserve rejection, correction, replay and closed-assignment evidence. |
+| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | The maintained CLI/MCP journey passes with real isolated Keycloak, the separate native runner and dedicated workers: shared PRE feedback, POST revision, same-assignment corrected upload, replay, retained history and unpaid final acceptance. See the [submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md). Hosted cutover, native fault/capacity and maximum-input qualification remain open. |
 | Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. Remaining gates are native fault, isolation, capacity and maximum-input qualification, qualified AWS admission activation and deployed API/consumer cutover. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. |
-| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Complete the connected native public journey, AWS exact-version qualification, hosted cutover and final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. |
-| Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. Earlier local API/Celery evidence covered both policy branches, prefork recovery and later authority revocation. Current qualification uses the intended identity deployment and exact runner profile | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate |
+| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | The connected native CLI/MCP journey and scoped AWS exact-version qualification pass. Complete AWS admission activation, hosted cutover and the final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. |
+| Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. Earlier local API/Celery evidence covered both policy branches, prefork recovery and later authority revocation. Current connected qualification uses real isolated Keycloak and the exact separate-runner profile; hosted identity qualification remains separate | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate |
 | Operator uncertain-delivery CLI | **Existing public delivery routes consumed by explicit CLI commands** | WS-CLI-001-40 adds one project-bound page of finalized UNKNOWN deliveries and a deliberate reasoned, UUID-keyed reconciliation of one exact event. Fresh backend authority and classification remain decisive; a page never authorizes a later write. | Native signed PostgreSQL proof is scoped to an owner-produced source; a hosted interruption and deployed CLI remain unproven |
 | Review queue and lease | **Hidden persistence foundation** | Queue/admission idempotency and ReviewLease/preference persistence; complete unavailable REV action/principal catalogue and typed AUTH contracts; ART-07A1 metadata-only packet contract and REV-03B immutable normalized packet persistence with live ingest custody; REV-04A Review/finding/resolution and completed request storage | Future resolver proof; canonical admission from `allow_review`; claim/lease/packet authority; lease copies the Submission-stamped policy version with no CON lookup |
 | Review decision and revision | **Checker revision implemented; human decisions planned** | Review/revision policy identities and mutation authority, with `requires_second_review` fixed false through typed and database boundaries; REV-04A immutable Review storage; REV-04B source storage; REV-04C hidden source-neutral FinalAcceptance/TASK/CON participant; ARCH-04E2-B source AUTH and complete database/audit/outbox closure for hidden automated outcomes. PILOT-08 supplies required project-policy N>=0, assignment-scoped attempts, immediate exhaustion/release, atomic complete-context rebase and acknowledgement, setup-blocked clock pause/resume, PM attention/repair, and durable timeout rejection/reclaim. The CLI now makes the existing exact manager repair POST available with caller-owned key and source, preserving backend eligibility and replay authority | Genuine human decision authority/composition and revision integration remain #554 work under the same intended policy; hosted operation remains unproven |

From dd6ff14927dd08cc584c921e9fb05f795f57dc70 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 14:36:07 +0100
Subject: [PATCH 449/513] Exercise selected PRE timeout and isolation in the
 maintained journey

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  22 ++
 cli/README.md                                 |  36 +++
 .../test_journey_pre_qualification.py         | 138 +++++++++
 cli/tests/journey/bootstrap.py                |  30 +-
 cli/tests/journey/pre_qualification.py        | 287 ++++++++++++++++++
 cli/tests/journey/runtime.py                  |  31 +-
 .../tests/smol_fixture/checker.py             |  47 +++
 .../tests/smol_fixture/runtime_wrapper.py     |  26 ++
 8 files changed, 610 insertions(+), 7 deletions(-)
 create mode 100644 cli/tests/integration/test_journey_pre_qualification.py
 create mode 100644 cli/tests/journey/pre_qualification.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 1c6982124..99f411cb2 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12675,3 +12675,25 @@ Its private refresh grants, exchange secret and environment handoff were
 removed. Only disposable copied interpreter trust stores were modified.
 This qualifies the current connected client/runtime path with an isolated real
 provider; it does not claim the hosted API/worker release or live email delivery.
+
+### Qualify source-first PRE timeout and isolation
+
+Scope. Extend the maintained CLI journey with an explicit qualification
+selection and use the retained Smol runtime fixture as the pinned PRE checker.
+Exercise its actual source-first request through the public raw ZIP command,
+with fixture inputs selected by the test archive and pinned only for the
+qualification project.
+
+Acceptance. A selected project stage deadline produces a durable infrastructure
+failure and preserves the assignment's revision allowance. Retain its exact
+source version and charge during the two-hour reclamation grace, together
+with the runtime-destroyed receipt and the separate fixture teardown evidence. The isolation probe returns a valid passing result
+only after checking read-only source bytes, inaccessible supervisor state and
+credential boundaries. Bind both observations to their exact selected PRE
+terminal receipt. Unknown destruction (A26) requires a separate approved
+runner ownership domain and remains outside this change.
+
+Nine focused trace and observer cases exercise the exact stage, lease and
+cleanup evidence, including absent, foreign and duplicate observations. The
+maintained guide and submission-progress regressions pass in the same run.
+The test image build and isolated KVM run are pending.
diff --git a/cli/README.md b/cli/README.md
index a98dab89d..568db7b22 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -2278,3 +2278,39 @@ public retained evidence, Operator custody and non-Operator concealment.
 The real checker validates only the fixed incident-summary exercise; this is
 not hosted deployment, external Flow issuer, model inference, broad ZIP-size
 performance qualification or compensation fulfillment certification.
+
+#### Source-first PRE qualification
+
+Run the same isolated command with
+`WORKSTREAM_CLI_JOURNEY_PRE_QUALIFICATION_IMAGE_DIGEST` set to the approved
+manifest digest of the retained
+[Smol Python fixture](../external_checkers/workstream-checker-service/tests/smol_fixture/python.Dockerfile).
+Build it with the sibling `smol_fixture` directory as context and install it
+using the same [verified cache preparation](../external_checkers/README.md#smol-microvm-engine).
+Generate the PRE registration with this digest and set
+`resources.deadline_ms` to `5000`. Keep the ordinary incident-summary image
+and registration for POST. Use the local isolated CLI authentication path,
+the existing qualified PRE runtime profile, and a fresh evidence directory.
+
+Use an independently owned test runner with the retained
+[runtime wrapper](../external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py).
+Configure its adjacent JSON with the real Smol binary, an owned empty trace,
+the normal `mode` file containing `0`, the owned cgroup directory, an absent
+`delete_fault` marker and `observe_pre_exit` set to `true`. Pin the wrapper
+bytes in the test runner's `smol.binary_sha256`, `pre.smol_binary_sha256` and
+`trusted_intake.storage_envelope.smol_binary_sha256`. Pin the exact loaded
+runner configuration in the existing TLS endpoint input. Preserve the
+runner and guest resource envelope. Record the source commit, fixture image
+manifest/config, and the exact installed configuration and executable hashes.
+
+The first ZIP reaches the selected checker and exceeds its stage deadline.
+The same assignment accepts the isolation probe on a fresh key as Submission
+version 1. The failed source stays charged during the two-hour reclamation
+grace. Keep the isolated launcher cleanup receipt for its test bucket and
+require the native observer's matching lease trace before recording a pass.
+
+```sh
+python cli/tests/journey/pre_qualification.py \
+  "$WORKSTREAM_CLI_JOURNEY_EVIDENCE/pre-qualification-client.json" \
+  "$OWNED_NATIVE_TRACE"
+```
diff --git a/cli/tests/integration/test_journey_pre_qualification.py b/cli/tests/integration/test_journey_pre_qualification.py
new file mode 100644
index 000000000..73f93c620
--- /dev/null
+++ b/cli/tests/integration/test_journey_pre_qualification.py
@@ -0,0 +1,138 @@
+"""Reject missing or foreign native evidence for the source-first PRE probes."""
+
+from hashlib import sha256
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+
+JOURNEY = Path(__file__).resolve().parents[1] / "journey/pre_qualification.py"
+WRAPPER = (
+    JOURNEY.parents[3]
+    / "external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py"
+)
+SPEC = importlib.util.spec_from_file_location("journey_pre_qualification", JOURNEY)
+MODULE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(MODULE)
+
+
+@pytest.mark.parametrize(
+    "fault",
+    [
+        None,
+        "wrong_lease",
+        "aggregate_timeout",
+        "duplicate_exec",
+        "no_delete",
+        "pending_cleanup",
+        "wrong_runtime",
+    ],
+)
+def test_native_trace_requires_exact_project_stage_and_cleanup(fault):
+    evidence = {}
+    trace = []
+    wrapper_digest = "sha256:" + sha256(WRAPPER.read_bytes()).hexdigest()
+    for name, outcome, exit_code in (
+        ("timeout", "infrastructure_failure", 125),
+        ("isolation", "completed", 0),
+    ):
+        evidence[name] = {
+            "invocation": {
+                "provider_invocation_id": name,
+                "operation": "execute_pre",
+                "outcome": outcome,
+                "cleanup": {"obligation_id": name, "disposition": "destroyed"},
+                "runtime": {"binary_sha256": wrapper_digest},
+            }
+        }
+        trace.extend(
+            [
+                {"name": name, "operation": "create"},
+                {"name": name, "operation": "start"},
+                {"name": name, "operation": "exec"},
+                {
+                    "name": name,
+                    "operation": "pre_exit",
+                    "exit_code": exit_code,
+                    "project_deadline_exceeded": name == "timeout",
+                },
+                {"name": name, "operation": "delete"},
+            ]
+        )
+    if fault == "wrong_lease":
+        trace[3]["name"] = "foreign"
+    if fault == "aggregate_timeout":
+        trace[3]["project_deadline_exceeded"] = False
+    if fault == "duplicate_exec":
+        trace.insert(2, trace[2].copy())
+    if fault == "no_delete":
+        trace.pop(4)
+    if fault == "pending_cleanup":
+        evidence["timeout"]["invocation"]["cleanup"]["disposition"] = "pending"
+    if fault == "wrong_runtime":
+        evidence["timeout"]["invocation"]["runtime"]["binary_sha256"] = "foreign"
+    if fault:
+        with pytest.raises(AssertionError):
+            MODULE.verify_native_trace(evidence, trace)
+    else:
+        MODULE.verify_native_trace(evidence, trace)
+
+
+@pytest.mark.parametrize("exact", [True, False])
+def test_runtime_fixture_classifies_only_the_trusted_deadline_line(tmp_path, exact):
+    wrapper = tmp_path / "runtime_wrapper.py"
+    wrapper.write_bytes(WRAPPER.read_bytes())
+    guest = tmp_path / "smol"
+    diagnostic = "workstream guest bootstrap failed: project deadline exceeded"
+    if not exact:
+        diagnostic += " (other diagnostic)"
+    guest.write_text(
+        f"#!{sys.executable}\n"
+        "import os\n"
+        "assert os.environ['WORKSTREAM_PRE_QUALIFICATION_PRIVATE_CANARY'] == 'test-only'\n"
+        f"message = {diagnostic.encode()!r}\n"
+        "os.write(2, message[:20])\n"
+        "os.write(2, message[20:] + b'\\n')\n"
+        "raise SystemExit(125)\n",
+        encoding="utf-8",
+    )
+    guest.chmod(0o700)
+    trace = tmp_path / "trace.jsonl"
+    wrapper.with_suffix(".json").write_text(
+        json.dumps(
+            {"binary": str(guest), "trace": str(trace), "observe_pre_exit": True}
+        ),
+        encoding="utf-8",
+    )
+    invocation = subprocess.run(
+        [
+            sys.executable,
+            str(wrapper),
+            "machine",
+            "exec",
+            "--name",
+            "owned",
+            "--",
+            "/.workstream-guest",
+            "--pre-limits",
+            "{}",
+        ],
+        capture_output=True,
+        check=False,
+        timeout=10,
+    )
+    assert invocation.returncode == 125
+    assert invocation.stderr.decode().rstrip() == diagnostic
+    assert [json.loads(line) for line in trace.read_text().splitlines()] == [
+        {"name": "owned", "operation": "exec"},
+        {
+            "name": "owned",
+            "operation": "pre_exit",
+            "exit_code": 125,
+            "project_deadline_exceeded": exact,
+        },
+    ]
diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py
index 8bde939fb..d640e9ca6 100644
--- a/cli/tests/journey/bootstrap.py
+++ b/cli/tests/journey/bootstrap.py
@@ -196,6 +196,19 @@ def main():
         ).decode(),
     )
     mcp_executable = environment.get("WORKSTREAM_CLI_JOURNEY_MCP_EXECUTABLE")
+    pre_qualification = environment.get(
+        "WORKSTREAM_CLI_JOURNEY_PRE_QUALIFICATION_IMAGE_DIGEST"
+    )
+    if pre_qualification is not None and (
+        mcp_executable
+        or any(
+            environment.get(f"WORKSTREAM_CLI_JOURNEY_{stage}") != "1"
+            for stage in ("SETUP", "TASKS", "SUBMIT")
+        )
+    ):
+        raise RuntimeError(
+            "PRE qualification requires the isolated CLI submission stages"
+        )
     paired_tokens = None
     if mcp_executable:
         if any(
@@ -436,7 +449,18 @@ def main():
                             client, tokens, actors, project_id
                         )
                         client.complete_stage("task_claim_and_guide")
-                        if os.environ.get("WORKSTREAM_CLI_JOURNEY_SUBMIT") == "1":
+                        if pre_qualification is not None:
+                            from pre_qualification import qualify
+
+                            qualify(
+                                client,
+                                tokens["alice"],
+                                task_id,
+                                assignment_id,
+                                environment,
+                            )
+                            client.complete_stage("source_first_pre_client_evidence")
+                        elif os.environ.get("WORKSTREAM_CLI_JOURNEY_SUBMIT") == "1":
                             receipt = submit_and_observe(
                                 client,
                                 tokens,
@@ -472,7 +496,9 @@ def main():
                             "result": "passed",
                             "cli_invocations": len(client.steps),
                             "verified_stages": client.completed_stages,
-                            "scope": "isolated manager-authored unpaid submission journey",
+                            "scope": "source-first PRE client evidence, native trace required"
+                            if pre_qualification is not None
+                            else "isolated manager-authored unpaid submission journey",
                             "authentication": "configured_flow_provider"
                             if mcp
                             else "isolated_local_hmac",
diff --git a/cli/tests/journey/pre_qualification.py b/cli/tests/journey/pre_qualification.py
new file mode 100644
index 000000000..7ab13526b
--- /dev/null
+++ b/cli/tests/journey/pre_qualification.py
@@ -0,0 +1,287 @@
+"""Exact source-first PRE fault/isolation evidence for the maintained CLI journey."""
+
+import argparse
+import asyncio
+from hashlib import sha256
+import json
+from pathlib import Path
+from urllib.parse import urlsplit
+from uuid import uuid4
+from zipfile import ZipFile, ZipInfo
+
+INFRASTRUCTURE_FAILURE = "submission_infrastructure_unavailable"
+WRAPPER = (
+    Path(__file__).resolve().parents[3]
+    / "external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py"
+)
+
+
+async def _terminal(
+    environment, operation_id, task_id, assignment_id, archive, *, timeout
+):
+    from sqlalchemy import text
+    from sqlalchemy.ext.asyncio import create_async_engine
+
+    from app.adapters.artifacts import selected_pre_submit_source_contracts
+    from app.modules.checkers.api.selected_pre_submit import (
+        SelectedPreSubmitTerminalFacts,
+    )
+    from run_isolated_tests import _minio_client
+    from runtime import PRE_QUALIFICATION_DEADLINE_MS
+    from source_audit import _COUNTS
+
+    url = environment["WORKSTREAM_DATABASE_URL"]
+    assert urlsplit(url).path.lstrip("/").startswith("workstream_test_")
+    parameters = {"operation_id": operation_id, "task_id": task_id}
+    engine = create_async_engine(url, pool_pre_ping=True)
+    try:
+        async with engine.connect() as connection, connection.begin():
+            await connection.execute(text("SET TRANSACTION READ ONLY"))
+            row = (
+                (
+                    await connection.execute(
+                        text("""
+                    SELECT o.state, o.task_id::text, o.assignment_id::text,
+                        o.object_ref, o.raw_sha256, o.raw_byte_count,
+                        o.provider_generation, o.sealed_upload_fence,
+                        o.finalization_event_id, charge.state AS charge_state,
+                        charge.accounted_bytes, selected.terminal_json,
+                        selected.terminal_digest, selected.eligible,
+                        selected.execute_evidence_id, selected.finalize_evidence_id
+                    FROM submission_intake_operations AS o
+                    JOIN submission_source_charges AS charge ON charge.operation_id = o.id
+                    JOIN selected_pre_submit_runs AS selected ON selected.source_operation_id = o.id
+                    WHERE o.id = CAST(:operation_id AS uuid)
+                    """),
+                        parameters,
+                    )
+                )
+                .mappings()
+                .one()
+            )
+            if timeout:
+                for query in _COUNTS.values():
+                    assert await connection.scalar(text(query), parameters) == 0
+                assert (
+                    await connection.scalar(
+                        text(
+                            "SELECT count(*) FROM task_revision_preparations WHERE task_id = CAST(:task_id AS uuid)"
+                        ),
+                        parameters,
+                    )
+                    == 0
+                )
+                assert (
+                    await connection.scalar(
+                        text(
+                            "SELECT count(*) FROM submission_intake_operations WHERE task_id = CAST(:task_id AS uuid)"
+                        ),
+                        parameters,
+                    )
+                    == 1
+                )
+    finally:
+        await engine.dispose()
+
+    data = archive.read_bytes()
+    raw_digest = "sha256:" + sha256(data).hexdigest()
+    assert (row["task_id"], row["assignment_id"]) == (task_id, assignment_id)
+    assert (row["raw_sha256"], row["raw_byte_count"]) == (raw_digest, len(data))
+    assert (row["charge_state"], row["accounted_bytes"]) == ("sealed", len(data))
+    assert row["execute_evidence_id"] and row["finalize_evidence_id"]
+    terminal = SelectedPreSubmitTerminalFacts.from_canonical_body(
+        row["terminal_json"], source_contracts=selected_pre_submit_source_contracts()
+    )
+    assert terminal.terminal_digest == row["terminal_digest"]
+    reservation = terminal.lease.reservation
+    source = reservation.source
+    invocation = terminal.invocation_receipt
+    assert invocation and invocation.operation == "execute_pre"
+    assert invocation.runtime.provider == "smolvm"
+    assert invocation.cleanup.disposition == "destroyed"
+    assert str(source.location.operation_id) == operation_id
+    assert str(reservation.assignment_id) == assignment_id
+    assert source.location.object_ref == row["object_ref"]
+    assert source.raw_sha256 == raw_digest and source.raw_byte_count == len(data)
+    assert source.provider_generation == row["provider_generation"]
+    assert source.sealed_upload_fence == row["sealed_upload_fence"]
+    assert (
+        invocation.invocation.image_digest
+        == environment["WORKSTREAM_CLI_JOURNEY_PRE_QUALIFICATION_IMAGE_DIGEST"]
+    )
+    assert (
+        reservation.policy.entries[0].registry.resources.deadline_ms
+        == PRE_QUALIFICATION_DEADLINE_MS
+    )
+    if timeout:
+        assert row["state"] == "failed" and row["finalization_event_id"] is None
+        assert row["eligible"] is None and terminal.execution is None
+        assert terminal.outcome == "infrastructure_failed"
+        assert terminal.infrastructure_failure_code == "implementation_unavailable"
+        assert invocation.outcome == "infrastructure_failure"
+        assert invocation.timings_ms.execution >= PRE_QUALIFICATION_DEADLINE_MS
+        # The real source remains charged during the configured reclamation grace.
+        async with _minio_client(
+            environment["WORKSTREAM_TEST_MINIO_ENDPOINT"]
+        ) as client:
+            observed = await client.head_object(
+                Bucket=environment["WORKSTREAM_TEST_MINIO_BUCKET"],
+                Key=f"{environment['WORKSTREAM_TEST_MINIO_PREFIX']}/{row['object_ref']}",
+                VersionId=source.provider_generation,
+            )
+        assert observed["VersionId"] == source.provider_generation
+        assert observed["ContentLength"] == len(data)
+    else:
+        assert row["state"] == "finalized" and row["finalization_event_id"]
+        assert terminal.outcome == "completed" and invocation.outcome == "completed"
+        assert terminal.execution and terminal.execution.eligible
+        assert row["eligible"] is True
+        assert len(terminal.execution.external_members) == 1
+        assert terminal.execution.external_members[0].result.verdict == "passed"
+
+    return {
+        "source_operation_id": operation_id,
+        "raw_sha256": raw_digest,
+        "terminal_sha256": row["terminal_digest"],
+        "invocation": invocation.canonical_body(),
+    }
+
+
+def qualify(client, token, task_id, assignment_id, environment):
+    """Exercise a real selected timeout and one successful source fence probe."""
+    from source_audit import audit_accepted_source
+    from submission_work import (
+        _assignment_status,
+        _command,
+        _package,
+        _progress,
+        _submit,
+        _wait_for_stage,
+    )
+
+    if not __debug__:
+        raise RuntimeError("PRE qualification requires Python assertions")
+    if client.evidence is None:
+        raise RuntimeError(
+            "PRE qualification requires a private journey evidence directory"
+        )
+    good = _package(client, "correct")
+    timed = client.directory / "qualification-timeout.zip"
+    timed.write_bytes(good.read_bytes())
+    marker = ZipInfo("pre-qualification-timeout.txt", date_time=(2020, 1, 1, 0, 0, 0))
+    marker.external_attr = 0o100644 << 16
+    with ZipFile(timed, "a") as archive:
+        archive.writestr(marker, b"selected PRE deadline fixture\n")
+    key = str(uuid4())
+    arguments = _command(task_id, assignment_id, timed, key)
+    first = client.call(token, *arguments, expected_exit=1)
+    assert first["error"]["code"] == INFRASTRUCTURE_FAILURE
+    assert client.call(token, *arguments, expected_exit=1) == first
+    observed = _progress(client, token, task_id, key)
+    assert observed["operation_state"] == observed["processing_stage"] == "failed"
+    assert observed["failure_code"] == INFRASTRUCTURE_FAILURE
+    assert observed["next_action"] == "retry_new_key_after_terminal"
+    assert observed["pre_submission_results"] == []
+    assert observed["submission_id"] is None
+    status = _assignment_status(client, token, task_id, assignment_id)
+    assert (
+        status["current_status"] == "in_progress"
+        and status["assignment"]["revision"] is None
+    )
+    timeout = asyncio.run(
+        _terminal(
+            environment,
+            observed["operation_id"],
+            task_id,
+            assignment_id,
+            timed,
+            timeout=True,
+        )
+    )
+
+    accepted_key, receipt = _submit(client, token, task_id, assignment_id, good)
+    finalized = _wait_for_stage(
+        client, token, task_id, accepted_key, receipt, "accepted"
+    )
+    assert finalized["submission_version"] == 1
+    audit_accepted_source(
+        receipt["operation_id"],
+        finalized["submission_id"],
+        task_id,
+        good,
+        accepted=True,
+    )
+    isolation = asyncio.run(
+        _terminal(
+            environment,
+            receipt["operation_id"],
+            task_id,
+            assignment_id,
+            good,
+            timeout=False,
+        )
+    )
+    with (client.evidence.parent / "pre-qualification-client.json").open(
+        "x", encoding="utf-8"
+    ) as stream:
+        Path(stream.name).chmod(0o600)
+        json.dump(
+            {
+                "assignment_id": assignment_id,
+                "timeout": timeout,
+                "isolation": isolation,
+            },
+            stream,
+        )
+
+
+def verify_native_trace(evidence, trace):
+    """Bind the trusted guest's classified stage exit to both committed receipts."""
+    wrapper_digest = "sha256:" + sha256(WRAPPER.read_bytes()).hexdigest()
+    seen = set()
+    for name, outcome, exit_code, expired in (
+        ("timeout", "infrastructure_failure", 125, True),
+        ("isolation", "completed", 0, False),
+    ):
+        invocation = evidence[name]["invocation"]
+        lease = invocation["provider_invocation_id"]
+        if (
+            lease in seen
+            or invocation["cleanup"]["obligation_id"] != lease
+            or invocation["cleanup"]["disposition"] != "destroyed"
+            or invocation["operation"] != "execute_pre"
+            or invocation["outcome"] != outcome
+            or invocation["runtime"]["binary_sha256"] != wrapper_digest
+        ):
+            raise AssertionError(f"{name} has no exact destroyed PRE invocation")
+        seen.add(lease)
+        rows = [row for row in trace if row["name"] == lease]
+        operations = [row["operation"] for row in rows]
+        if (
+            operations[:4] != ["create", "start", "exec", "pre_exit"]
+            or set(operations[4:]) != {"delete"}
+            or rows[3]["exit_code"] != exit_code
+            or rows[3]["project_deadline_exceeded"] is not expired
+        ):
+            raise AssertionError(
+                f"{name} did not have the expected native stage and cleanup trace"
+            )
+
+
+def main():
+    parser = argparse.ArgumentParser(description=verify_native_trace.__doc__)
+    parser.add_argument("client_evidence", type=Path)
+    parser.add_argument("native_trace", type=Path)
+    arguments = parser.parse_args()
+    for path in (arguments.client_evidence, arguments.native_trace):
+        if not path.is_file() or path.stat().st_size > 256 * 1024:
+            parser.error("PRE qualification evidence must be a bounded regular file")
+    verify_native_trace(
+        json.loads(arguments.client_evidence.read_bytes()),
+        [json.loads(line) for line in arguments.native_trace.read_bytes().splitlines()],
+    )
+    print(json.dumps({"timeout": "verified", "isolation": "verified"}))
+
+
+if __name__ == "__main__":
+    main()
diff --git a/cli/tests/journey/runtime.py b/cli/tests/journey/runtime.py
index 7694807e3..4a1ce5e66 100644
--- a/cli/tests/journey/runtime.py
+++ b/cli/tests/journey/runtime.py
@@ -16,6 +16,7 @@
 
 
 SHA256 = re.compile(r"sha256:[0-9a-f]{64}\Z")
+PRE_QUALIFICATION_DEADLINE_MS = 5_000
 PILOT_CHECKS = {
     "pre": ("pre_submit", "incident_summary_layout"),
     "post": ("post_submit", "incident_summary_counts"),
@@ -158,7 +159,9 @@ def load_journey_configuration(environment: dict[str, str]) -> dict[str, Path]:
     from public_setup import validate_authored_rules_template
 
     try:
-        endpoints = ExternalRunnerEndpoints.model_validate_json(environment.get("WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS", ""))
+        endpoints = ExternalRunnerEndpoints.model_validate_json(
+            environment.get("WORKSTREAM_EXTERNAL_RUNNER_ENDPOINTS", "")
+        )
     except ValueError as exc:
         raise RuntimeError("journey requires reviewed TLS runner endpoints") from exc
     if any(endpoint.host != "127.0.0.1" for endpoint in endpoints.root):
@@ -222,17 +225,35 @@ def load_journey_configuration(environment: dict[str, str]) -> dict[str, Path]:
         raise RuntimeError("journey PRE runtime differs from qualified profile")
 
     registry_files = {}
+    qualification_image = environment.get(
+        "WORKSTREAM_CLI_JOURNEY_PRE_QUALIFICATION_IMAGE_DIGEST"
+    )
+    pilot_image = environment["WORKSTREAM_CLI_JOURNEY_CHECKER_IMAGE_DIGEST"]
+    if qualification_image is not None and (
+        SHA256.fullmatch(qualification_image) is None
+        or qualification_image == pilot_image
+    ):
+        raise RuntimeError("PRE qualification requires a distinct pinned fixture image")
     for name, (phase, check) in PILOT_CHECKS.items():
         path, body = _required_json(
             environment, f"WORKSTREAM_CLI_JOURNEY_REGISTRY_{name.upper()}_FILE"
         )
         spec = ExternalCheckerRegistrySpec.model_validate(body)
+        expected_image = (
+            qualification_image
+            if name == "pre" and qualification_image
+            else pilot_image
+        )
+        if spec.phase != phase or spec.image_digest != expected_image:
+            raise RuntimeError("journey checker phase or pinned image differs")
         if (
-            spec.phase != phase
-            or spec.image_digest
-            != environment["WORKSTREAM_CLI_JOURNEY_CHECKER_IMAGE_DIGEST"]
+            name == "pre"
+            and qualification_image
+            and spec.resources.deadline_ms != PRE_QUALIFICATION_DEADLINE_MS
         ):
-            raise RuntimeError("journey checker phase or pinned image differs")
+            raise RuntimeError(
+                "PRE qualification requires the exact selected stage deadline"
+            )
         if (
             spec.resources.cpu_millis > profile.runtime.cpu_millis
             or spec.resources.memory_bytes > profile.runtime.memory_bytes
diff --git a/external_checkers/workstream-checker-service/tests/smol_fixture/checker.py b/external_checkers/workstream-checker-service/tests/smol_fixture/checker.py
index a160e11da..5cb783538 100644
--- a/external_checkers/workstream-checker-service/tests/smol_fixture/checker.py
+++ b/external_checkers/workstream-checker-service/tests/smol_fixture/checker.py
@@ -1,5 +1,6 @@
 """Adversarial runtime fixture. Never registered as a project evaluator."""
 import errno
+import fcntl
 import hashlib
 import json
 import os
@@ -11,6 +12,10 @@
 import time
 
 
+PRE_SOURCE_SCHEMA = "workstream.external_checker_pre_submit_input.v1"
+TIMEOUT_MARKER = "pre-qualification-timeout.txt"
+
+
 def denied(operation, *, expected_errno=None):
     try:
         value = operation()
@@ -23,7 +28,49 @@ def denied(operation, *, expected_errno=None):
     raise AssertionError("operation was allowed")
 
 
+def evaluate_source_first(request):
+    """Pass only after the selected PRE safety observations complete."""
+    assert request["identity"]["phase"] == "pre_submit"
+    assert request["input"]["schema_version"] == PRE_SOURCE_SCHEMA
+    assert os.getuid() != 0 and os.getgid() != 0
+    input_root = Path("/work/input")
+    manifest = request["input"]["manifest"]
+    assert all(entry["entry_type"] == "file" for entry in manifest)
+    assert {path.name for path in input_root.iterdir()} == {
+        entry["normalized_path"] for entry in manifest
+    }
+    assert os.statvfs(input_root).f_flag & os.ST_RDONLY
+    for entry in manifest:
+        path = input_root / entry["normalized_path"]
+        data = path.read_bytes()
+        assert len(data) == entry["byte_count"]
+        assert "sha256:" + hashlib.sha256(data).hexdigest() == entry["sha256"]
+        denied(lambda: path.open("ab"))
+        assert path.read_bytes() == data
+
+    assert fcntl.fcntl(0, fcntl.F_GETFL) & os.O_ACCMODE == os.O_RDONLY
+    for descriptor in Path("/proc/self/fd").iterdir():
+        if int(descriptor.name) > 2:
+            denied(lambda: os.fstat(int(descriptor.name)), expected_errno=errno.EBADF)
+    (private,) = Path("/").glob(".workstream-pre-*")
+    denied(lambda: list(private.iterdir()), expected_errno=errno.EACCES)
+    worker_control = private / "worker-view/request.json"
+    denied(lambda: worker_control.open("rb"), expected_errno=errno.EACCES)
+    denied(lambda: worker_control.open("ab"), expected_errno=errno.EACCES)
+    assert not list(Path("/run").iterdir())
+    assert not list(Path("/sys").iterdir())
+    assert "WORKSTREAM_PRE_QUALIFICATION_PRIVATE_CANARY" not in os.environ
+    denied(lambda: socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM))
+
+    if (input_root / TIMEOUT_MARKER).is_file():
+        assert (input_root / TIMEOUT_MARKER).read_bytes() == b"selected PRE deadline fixture\n"
+        time.sleep(30)
+
+
 def evaluate(request):
+    if request["configuration"] == {"check": "incident_summary_layout"}:
+        evaluate_source_first(request)
+        return
     case = request["configuration"]["case"]
     if case == "sleep":
         time.sleep(30)
diff --git a/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py b/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
index 8aa87cd07..74f8b6ede 100644
--- a/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
+++ b/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
@@ -8,6 +8,30 @@
 import subprocess
 import sys
 
+
+def observe_pre_exit(binary, arguments, trace, name):
+    # The trusted guest emits the fixed diagnostic after killing the project.
+    # Forward stderr as usual. Retain only one bounded, classified observation.
+    diagnostic = b'workstream guest bootstrap failed: project deadline exceeded'
+    captured = bytearray()
+    environment = os.environ | {'WORKSTREAM_PRE_QUALIFICATION_PRIVATE_CANARY': 'test-only'}
+    with subprocess.Popen([binary, *arguments], stderr=subprocess.PIPE, env=environment) as child:
+        while chunk := child.stderr.read1(4096):
+            captured.extend(chunk[:max(0, 16384 - len(captured))])
+            sys.stderr.buffer.write(chunk)
+            sys.stderr.buffer.flush()
+        code = child.wait()
+    with trace.open('a') as output:
+        fcntl.flock(output, fcntl.LOCK_EX)
+        output.write(json.dumps({
+            'operation': 'pre_exit', 'name': name, 'exit_code': code,
+            'project_deadline_exceeded': diagnostic in captured.splitlines(),
+        }) + '\n')
+        output.flush()
+        os.fsync(output.fileno())
+    return code
+
+
 settings = json.loads(Path(__file__).with_suffix('.json').read_text())
 arguments = sys.argv[1:]
 if len(arguments) >= 2 and arguments[0] == 'machine':
@@ -44,4 +68,6 @@
                     sys.exit(93)
         if operation == 'delete' and Path(settings['delete_fault']).exists():
             sys.exit(93)
+        if operation == 'exec' and '--pre-limits' in arguments and settings.get('observe_pre_exit') is True:
+            sys.exit(observe_pre_exit(settings['binary'], arguments, trace, name))
 os.execv(settings['binary'], [settings['binary'], *arguments])

From 7e566ae2f7fa03949d03cc904a88833937be2f62 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 15:17:13 +0100
Subject: [PATCH 450/513] Bind PRE qualification to the effective deadline and
 exact VM trace

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 15 ++++---
 cli/README.md                                 | 15 ++++---
 .../test_journey_pre_qualification.py         | 30 ++++++++++++--
 cli/tests/journey/pre_qualification.py        | 41 +++++++++++++++----
 .../tests/smol_fixture/runtime_wrapper.py     |  7 +++-
 5 files changed, 85 insertions(+), 23 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 99f411cb2..10b4f9e50 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12684,8 +12684,10 @@ Exercise its actual source-first request through the public raw ZIP command,
 with fixture inputs selected by the test archive and pinned only for the
 qualification project.
 
-Acceptance. A selected project stage deadline produces a durable infrastructure
-failure and preserves the assignment's revision allowance. Retain its exact
+Acceptance. The effective project-stage deadline produces a durable infrastructure
+failure and preserves the assignment's revision allowance. The trusted guest
+diagnostic covers preparation in the project stage as well as execution, so
+child start, OOM and crash require their own evidence. Retain the failed ZIP's exact
 source version and charge during the two-hour reclamation grace, together
 with the runtime-destroyed receipt and the separate fixture teardown evidence. The isolation probe returns a valid passing result
 only after checking read-only source bytes, inaccessible supervisor state and
@@ -12693,7 +12695,10 @@ credential boundaries. Bind both observations to their exact selected PRE
 terminal receipt. Unknown destruction (A26) requires a separate approved
 runner ownership domain and remains outside this change.
 
-Nine focused trace and observer cases exercise the exact stage, lease and
-cleanup evidence, including absent, foreign and duplicate observations. The
-maintained guide and submission-progress regressions pass in the same run.
+The trace accounts for every source-first PRE execution and checks for the
+timed-out VM's resource absence at the next create. The same-key CLI 503 replay
+excludes each request's correlation identifier when comparing business fields.
 The test image build and isolated KVM run are pending.
+
+31 focused CLI checks pass, including 15 qualification observer, replay and
+resource counterexamples. Ruff checks the changed files and the CLI format.
diff --git a/cli/README.md b/cli/README.md
index 568db7b22..a93d6aabf 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -2303,11 +2303,16 @@ runner configuration in the existing TLS endpoint input. Preserve the
 runner and guest resource envelope. Record the source commit, fixture image
 manifest/config, and the exact installed configuration and executable hashes.
 
-The first ZIP reaches the selected checker and exceeds its stage deadline.
-The same assignment accepts the isolation probe on a fresh key as Submission
-version 1. The failed source stays charged during the two-hour reclamation
-grace. Keep the isolated launcher cleanup receipt for its test bucket and
-require the native observer's matching lease trace before recording a pass.
+The first ZIP reaches source-first PRE and triggers the trusted guest's
+effective project-stage deadline, which can elapse before the checker process
+starts. The fixture includes a sleeper to exercise this deadline if the process
+starts. Child-start, child OOM and child crash require separate evidence.
+The same assignment accepts the executed isolation probe on a fresh key as
+Submission version 1. The failed source stays charged during the two-hour
+reclamation grace. Keep the isolated launcher cleanup receipt for its test
+bucket and require the native observer's matching lease trace before recording
+a pass. The trace accounts for both source-first guest executions and checks
+that the timeout VM left no resources at the isolation VM's creation.
 
 ```sh
 python cli/tests/journey/pre_qualification.py \
diff --git a/cli/tests/integration/test_journey_pre_qualification.py b/cli/tests/integration/test_journey_pre_qualification.py
index 73f93c620..c690b17a0 100644
--- a/cli/tests/integration/test_journey_pre_qualification.py
+++ b/cli/tests/integration/test_journey_pre_qualification.py
@@ -30,6 +30,9 @@
         "no_delete",
         "pending_cleanup",
         "wrong_runtime",
+        "extra_pre",
+        "leaked_timeout_vm",
+        "unclassified_exec",
     ],
 )
 def test_native_trace_requires_exact_project_stage_and_cleanup(fault):
@@ -51,9 +54,9 @@ def test_native_trace_requires_exact_project_stage_and_cleanup(fault):
         }
         trace.extend(
             [
-                {"name": name, "operation": "create"},
+                {"name": name, "operation": "create", "prior_resources": []},
                 {"name": name, "operation": "start"},
-                {"name": name, "operation": "exec"},
+                {"name": name, "operation": "exec", "source_pre": True},
                 {
                     "name": name,
                     "operation": "pre_exit",
@@ -63,6 +66,7 @@ def test_native_trace_requires_exact_project_stage_and_cleanup(fault):
                 {"name": name, "operation": "delete"},
             ]
         )
+    trace.append({"name": "post", "operation": "exec", "source_pre": False})
     if fault == "wrong_lease":
         trace[3]["name"] = "foreign"
     if fault == "aggregate_timeout":
@@ -75,6 +79,12 @@ def test_native_trace_requires_exact_project_stage_and_cleanup(fault):
         evidence["timeout"]["invocation"]["cleanup"]["disposition"] = "pending"
     if fault == "wrong_runtime":
         evidence["timeout"]["invocation"]["runtime"]["binary_sha256"] = "foreign"
+    if fault == "extra_pre":
+        trace.append({"name": "extra", "operation": "exec", "source_pre": True})
+    if fault == "leaked_timeout_vm":
+        trace[5]["prior_resources"] = ["timeout"]
+    if fault == "unclassified_exec":
+        trace[-1].pop("source_pre")
     if fault:
         with pytest.raises(AssertionError):
             MODULE.verify_native_trace(evidence, trace)
@@ -82,6 +92,20 @@ def test_native_trace_requires_exact_project_stage_and_cleanup(fault):
         MODULE.verify_native_trace(evidence, trace)
 
 
+@pytest.mark.parametrize(
+    "change", [{}, {"code": "submission_unavailable"}, {"status": 409}]
+)
+def test_timeout_replay_compares_stable_business_fields(change):
+    failure = {"code": "submission_infrastructure_unavailable", "status": 503}
+    first = {"error": failure | {"correlation_id": "first-request"}}
+    replay = {"error": failure | {"correlation_id": "second-request"} | change}
+    if change:
+        with pytest.raises(AssertionError):
+            MODULE._verify_timeout_replay(first, replay)
+    else:
+        MODULE._verify_timeout_replay(first, replay)
+
+
 @pytest.mark.parametrize("exact", [True, False])
 def test_runtime_fixture_classifies_only_the_trusted_deadline_line(tmp_path, exact):
     wrapper = tmp_path / "runtime_wrapper.py"
@@ -128,7 +152,7 @@ def test_runtime_fixture_classifies_only_the_trusted_deadline_line(tmp_path, exa
     assert invocation.returncode == 125
     assert invocation.stderr.decode().rstrip() == diagnostic
     assert [json.loads(line) for line in trace.read_text().splitlines()] == [
-        {"name": "owned", "operation": "exec"},
+        {"name": "owned", "operation": "exec", "source_pre": True},
         {
             "name": "owned",
             "operation": "pre_exit",
diff --git a/cli/tests/journey/pre_qualification.py b/cli/tests/journey/pre_qualification.py
index 7ab13526b..3fa41fda0 100644
--- a/cli/tests/journey/pre_qualification.py
+++ b/cli/tests/journey/pre_qualification.py
@@ -119,7 +119,6 @@ async def _terminal(
         assert terminal.outcome == "infrastructure_failed"
         assert terminal.infrastructure_failure_code == "implementation_unavailable"
         assert invocation.outcome == "infrastructure_failure"
-        assert invocation.timings_ms.execution >= PRE_QUALIFICATION_DEADLINE_MS
         # The real source remains charged during the configured reclamation grace.
         async with _minio_client(
             environment["WORKSTREAM_TEST_MINIO_ENDPOINT"]
@@ -147,8 +146,19 @@ async def _terminal(
     }
 
 
+def _verify_timeout_replay(first, replay):
+    def stable(response):
+        error = response["error"].copy()
+        error.pop("correlation_id", None)
+        return response | {"error": error}
+
+    assert first["error"]["code"] == INFRASTRUCTURE_FAILURE
+    assert first["error"]["status"] == 503
+    assert stable(first) == stable(replay)
+
+
 def qualify(client, token, task_id, assignment_id, environment):
-    """Exercise a real selected timeout and one successful source fence probe."""
+    """Exercise an effective project-stage deadline and a successful source fence probe."""
     from source_audit import audit_accepted_source
     from submission_work import (
         _assignment_status,
@@ -175,8 +185,8 @@ def qualify(client, token, task_id, assignment_id, environment):
     key = str(uuid4())
     arguments = _command(task_id, assignment_id, timed, key)
     first = client.call(token, *arguments, expected_exit=1)
-    assert first["error"]["code"] == INFRASTRUCTURE_FAILURE
-    assert client.call(token, *arguments, expected_exit=1) == first
+    replay = client.call(token, *arguments, expected_exit=1)
+    _verify_timeout_replay(first, replay)
     observed = _progress(client, token, task_id, key)
     assert observed["operation_state"] == observed["processing_stage"] == "failed"
     assert observed["failure_code"] == INFRASTRUCTURE_FAILURE
@@ -238,7 +248,7 @@ def qualify(client, token, task_id, assignment_id, environment):
 def verify_native_trace(evidence, trace):
     """Bind the trusted guest's classified stage exit to both committed receipts."""
     wrapper_digest = "sha256:" + sha256(WRAPPER.read_bytes()).hexdigest()
-    seen = set()
+    leases = []
     for name, outcome, exit_code, expired in (
         ("timeout", "infrastructure_failure", 125, True),
         ("isolation", "completed", 0, False),
@@ -246,7 +256,7 @@ def verify_native_trace(evidence, trace):
         invocation = evidence[name]["invocation"]
         lease = invocation["provider_invocation_id"]
         if (
-            lease in seen
+            lease in leases
             or invocation["cleanup"]["obligation_id"] != lease
             or invocation["cleanup"]["disposition"] != "destroyed"
             or invocation["operation"] != "execute_pre"
@@ -254,7 +264,7 @@ def verify_native_trace(evidence, trace):
             or invocation["runtime"]["binary_sha256"] != wrapper_digest
         ):
             raise AssertionError(f"{name} has no exact destroyed PRE invocation")
-        seen.add(lease)
+        leases.append(lease)
         rows = [row for row in trace if row["name"] == lease]
         operations = [row["operation"] for row in rows]
         if (
@@ -266,6 +276,21 @@ def verify_native_trace(evidence, trace):
             raise AssertionError(
                 f"{name} did not have the expected native stage and cleanup trace"
             )
+        if name == "isolation":
+            prior_resources = rows[0].get("prior_resources")
+            if type(prior_resources) is not list or leases[0] in prior_resources:
+                raise AssertionError(
+                    "timeout VM resources remained at isolation create"
+                )
+
+    executions = [row for row in trace if row["operation"] == "exec"]
+    if (
+        any(type(row.get("source_pre")) is not bool for row in executions)
+        or [row["name"] for row in executions if row["source_pre"]] != leases
+    ):
+        raise AssertionError(
+            "native trace contains a different set of source-first PRE executions"
+        )
 
 
 def main():
@@ -280,7 +305,7 @@ def main():
         json.loads(arguments.client_evidence.read_bytes()),
         [json.loads(line) for line in arguments.native_trace.read_bytes().splitlines()],
     )
-    print(json.dumps({"timeout": "verified", "isolation": "verified"}))
+    print(json.dumps({"project_stage_deadline": "verified", "isolation": "verified"}))
 
 
 if __name__ == "__main__":
diff --git a/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py b/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
index 74f8b6ede..fc9b043d1 100644
--- a/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
+++ b/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
@@ -10,7 +10,7 @@
 
 
 def observe_pre_exit(binary, arguments, trace, name):
-    # The trusted guest emits the fixed diagnostic after killing the project.
+    # The trusted guest emits the fixed diagnostic on the effective project-stage deadline.
     # Forward stderr as usual. Retain only one bounded, classified observation.
     diagnostic = b'workstream guest bootstrap failed: project deadline exceeded'
     captured = bytearray()
@@ -38,12 +38,15 @@ def observe_pre_exit(binary, arguments, trace, name):
     operation = arguments[1]
     name = arguments[arguments.index('--name') + 1] if '--name' in arguments else None
     trace = Path(settings['trace'])
+    source_pre = operation == 'exec' and '--pre-limits' in arguments
     if operation in {'create', 'start', 'exec', 'delete'}:
         with trace.open('a+') as output:
             fcntl.flock(output, fcntl.LOCK_EX)
             output.seek(0)
             prior = [json.loads(line)['name'] for line in output if json.loads(line)['operation'] == 'create']
             event = {'operation': operation, 'name': name}
+            if operation == 'exec':
+                event['source_pre'] = source_pre
             if operation == 'create':
                 rows = json.loads(subprocess.check_output([settings['binary'], 'machine', 'ls', '--json']))
                 event['prior_resources'] = [row['name'] for row in rows if row['name'] in prior]
@@ -68,6 +71,6 @@ def observe_pre_exit(binary, arguments, trace, name):
                     sys.exit(93)
         if operation == 'delete' and Path(settings['delete_fault']).exists():
             sys.exit(93)
-        if operation == 'exec' and '--pre-limits' in arguments and settings.get('observe_pre_exit') is True:
+        if source_pre and settings.get('observe_pre_exit') is True:
             sys.exit(observe_pre_exit(settings['binary'], arguments, trace, name))
 os.execv(settings['binary'], [settings['binary'], *arguments])

From f793f5c780d0cfb7866c7b182e79a9d1cd8a1c44 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 15:20:38 +0100
Subject: [PATCH 451/513] Record verified native qualification fixture build

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md  | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 10b4f9e50..851e5f82b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12702,3 +12702,17 @@ The test image build and isolated KVM run are pending.
 
 31 focused CLI checks pass, including 15 qualification observer, replay and
 resource counterexamples. Ruff checks the changed files and the CLI format.
+
+
+### Reviewed native qualification fixture and verified cache build
+
+Integrated `7f7e20e11` and its independently approved correction `30ded73d9`
+as `dd6ff1492` and `7e566ae2f`. The 15 exact trace/replay regression cases pass
+on the integrated source. The pinned Python fixture built successfully; its
+platform manifest is `sha256:addfba441ef831881fb2c6563291639c385d3dd4d7c7873abc10286aeb887b0d`
+and config is `sha256:bf8ef119fca0125a6f826c23a2cd7db53f160d4fb46aa17e208d18647b8e77ad`.
+The existing cache provisioner verified the saved platform/config/layer graph
+and produced a canonical archive and image configuration. Private build receipt:
+`/tmp/workstream-pre-qualification-7e566ae2f/build-receipt.json`.
+This is build and focused-test evidence only: no runner configuration changed,
+and actual native deadline/isolation execution remains pending.

From 072bfa746ac74f8e63962086e3ebe7caa255a474 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 15:38:11 +0100
Subject: [PATCH 452/513] Defer scalability qualification and prioritize hosted
 delivery

---
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     | 45 ++++++++++++++++---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 12 +++++
 docs/roadmap_status.md                        |  4 +-
 3 files changed, 54 insertions(+), 7 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index c5de61832..05d10acf1 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -4,6 +4,38 @@
 - Target: the complete [submission execution specification](../../../docs/spec_submission_execution.md).
 - Delivery: one PR, #708, with focused commits; no merge request before complete verification.
 
+## Current delivery scope — user decision, 2026-11-26
+
+The user explicitly defers scalability until the existing deployment works end
+to end, is reviewed/merged, and launch verification finishes. This instruction
+supersedes specification completion requirements for the deferred scope.
+A28 multi-API/multi-runner races, scale-out/restart qualification, a temporary
+second EC2 runner, and broad saturation/load campaigns are deferred, not passed.
+No additional AWS provisioning permission is required for current delivery.
+Retain existing dedicated queues and correctness/resource guards; do not remove
+working scale-out code merely because its deployment qualification is deferred.
+
+Current finish list, in execution order:
+
+- [x] Reconcile main cleanup and preserve required owners/tests in PR708.
+- [x] Prove the connected raw-ZIP PRE -> T5 -> POST -> same-assignment revision
+  -> acceptance journey through CLI/MCP with the separate runner.
+- [ ] Integrate/review the prepared preclaim-guide and pending-status assertions.
+- [ ] Finish essential native isolation, bounded failure and cleanup proof for
+  the existing runner; fix only observed defects needed for this deployment.
+- [ ] Stage the existing hosted API release, set its explicit operational
+  profiles, back up retained data, migrate and activate dedicated workers/MCP.
+- [ ] Prove the hosted contributor journey, actionable failure/retry feedback,
+  retained ZIP custody and actual S3 cleanup; verify supported upload bounds.
+- [ ] Run required final-head checks, resolve actual failures, and present PR708
+  for explicit merge approval. Merge and post-merge smoke require that approval.
+- [ ] Complete post-deployment/merge verification and hand over the release.
+
+Live email delivery remains separately dependent on the user's sender DNS/key
+setup. Keep notifications disabled until qualified. Live human review and a paid
+sandbox provider remain outside current implementation scope. Do not reopen
+completed proofs without a relevant change, failed check or uncovered requirement.
+
 ## Implemented on this branch
 
 Checked items describe implementation with focused proof. They do not mean the
@@ -124,8 +156,8 @@ journey. The remaining cleanup and verification requirements below still apply.
 | --- | --- | --- |
 | 1 | Reproduce the connected proof on the deployed API | The maintained paired journey at `73d81da66` passes real PRE/T5/POST, same-assignment correction, automatic acceptance, exact ZIP/Contribution export, rejection, replay and default review_pending with an isolated real identity provider, local API and separate AWS runner. The actual deployed API/consumers remain to activate and prove. |
 | 2 | Finish affected qualification callers | Preparation API/materialization and the admission-only TASK writer are removed. PR722 retires the experimental harness; the maintained native CLI/MCP journey passes; complete its remaining fault proof through the same owners using raw ZIP acceptance and dedicated finalization. Do not restore the old harness. |
-| 3 | Complete separate-runner integration and runtime/provider/resource qualification | Activate the prepared authenticated remote configuration on the app deployment; actual Smol one-session/isolation proof on runner infrastructure; representative maxima, cold paths, concurrency and timing measurements; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. |
-| 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; every A01–A35 row linked to an executed, scope-matching result. Fix actual failures without weakening requirements. |
+| 3 | Complete separate-runner integration and runtime/provider/resource qualification | Activate the prepared authenticated remote configuration on the app deployment; actual Smol one-session/isolation proof on runner infrastructure; supported input bounds, bounded failure/cleanup and timing measurements on the existing runner; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. |
+| 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; each current-scope acceptance row linked to an executed, scope-matching result, with user-deferred scalability explicitly excluded. Fix actual failures without weakening requirements. |
 | 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. |
 
 The historical connected public journey passed at 85ce76e17 (V14): 573 CLI invocations,
@@ -166,7 +198,8 @@ This is the final qualification queue, not a claim that all listed code is absen
 | A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Redis publication outage and Celery child-redelivery proofs passed; reconcile the remaining exact cases at the final head. |
 | A14–A18 | Cleanup lock/retention/charge owners, Local/MinIO tests and live AWS exact-version/lost-ack cleanup with retained-source survival | Production worker sweeps and exact acceptance-case reconciliation. |
 | A19–A23 | Streaming/framing, safe archives, semantic identity and findings tests; local A19 496 MiB slow-provider memory/backpressure drill | Full permitted maxima and safety matrix, native/deployment scope where required. |
-| A24–A30 | Source/result/fence contracts and runtime/capacity/substitution tests | Actual native isolation/failure/cleanup, multiple replicas/nodes, saturation and adapter qualification. |
+| A24–A27, A29–A30 | Source/result/fence contracts, dedicated queue and managed-style substitution tests | Essential native isolation/failure/cleanup and single-runner queue correctness remain; broad saturation/load qualification is user-deferred. |
+| A28 | Multi-replica/multi-runner implementation and focused tests | User-deferred until after existing deployment delivery; no second instance is required now. Not claimed passed. |
 | A31–A32 | V14 proves real POST automatic acceptance, exact Contribution/export and default review_pending; focused tests cover applicable awards/replay | Deployed release and final downstream tests. Keep default review_pending guards; live human review remains explicitly deferred by the user. |
 | A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | Affected old writers are retired; finish current-head migration/client convergence and remaining qualification callers. |
 
@@ -183,5 +216,7 @@ submission work must not reinstate the retired activation subsystem.
 Request only concrete missing access or decisions after the corresponding drill
 and proposed values are prepared.
 
-The full goal includes D01–D18, I01–I12, T1–T5 and A01–A35. A partial green
-suite, fixture capture, review approval or a single commit does not complete it.
+The original specification includes D01–D18, I01–I12, T1–T5 and A01–A35.
+Apply the explicit user scope decision above when assessing current delivery;
+do not claim deferred scalability is complete. A partial green suite, fixture
+capture, review approval or a single commit does not complete current delivery.
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 851e5f82b..84f5c6fb7 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12716,3 +12716,15 @@ and produced a canonical archive and image configuration. Private build receipt:
 `/tmp/workstream-pre-qualification-7e566ae2f/build-receipt.json`.
 This is build and focused-test evidence only: no runner configuration changed,
 and actual native deadline/isolation execution remains pending.
+
+
+### User delivery boundary: defer scalability
+
+On 2026-11-26 the user explicitly directed finishing the existing API and single
+runner end to end before scalability work, regardless of the original spec.
+A28 multiple API replicas/execution nodes and broad saturation campaigns are
+deferred, not passed. The temporary EC2 instance and its proposed IAM grant are
+not needed for current delivery and must not be provisioned/applied on this
+workstream now. Existing implemented correctness guards and dedicated queues
+remain. The overview carries the ordered remaining delivery checklist.
+No live deployment or infrastructure changed for this scope reconciliation.
diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md
index 37a29ad29..340103533 100644
--- a/docs/roadmap_status.md
+++ b/docs/roadmap_status.md
@@ -701,8 +701,8 @@ cannot be reused as post-submission review-gate evidence. See the
 | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent |
 | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS |
 | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate |
-| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | The maintained CLI/MCP journey passes with real isolated Keycloak, the separate native runner and dedicated workers: shared PRE feedback, POST revision, same-assignment corrected upload, replay, retained history and unpaid final acceptance. See the [submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md). Hosted cutover, native fault/capacity and maximum-input qualification remain open. |
-| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. Remaining gates are native fault, isolation, capacity and maximum-input qualification, qualified AWS admission activation and deployed API/consumer cutover. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. |
+| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | The maintained CLI/MCP journey passes with real isolated Keycloak, the separate native runner and dedicated workers: shared PRE feedback, POST revision, same-assignment corrected upload, replay, retained history and unpaid final acceptance. See the [submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md). Hosted cutover, essential single-runner failure/isolation and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing until after delivery. |
+| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. Remaining delivery gates are essential native failure/isolation, supported-upload qualification, qualified AWS admission activation and deployed API/consumer cutover. Multi-replica/multi-runner scalability qualification is user-deferred until after delivery. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. |
 | Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | The connected native CLI/MCP journey and scoped AWS exact-version qualification pass. Complete AWS admission activation, hosted cutover and the final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. |
 | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. Earlier local API/Celery evidence covered both policy branches, prefork recovery and later authority revocation. Current connected qualification uses real isolated Keycloak and the exact separate-runner profile; hosted identity qualification remains separate | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate |
 | Operator uncertain-delivery CLI | **Existing public delivery routes consumed by explicit CLI commands** | WS-CLI-001-40 adds one project-bound page of finalized UNKNOWN deliveries and a deliberate reasoned, UUID-keyed reconciliation of one exact event. Fresh backend authority and classification remain decisive; a page never authorizes a later write. | Native signed PostgreSQL proof is scoped to an owner-produced source; a hosted interruption and deployed CLI remain unproven |

From 30c822ae222f405503af2887b6b42f72c863b177 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 15:40:18 +0100
Subject: [PATCH 453/513] Reconcile remaining delivery gates against submission
 specification

---
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     | 43 ++++++++++++++-----
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 21 +++++++++
 2 files changed, 53 insertions(+), 11 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index 05d10acf1..0a6ea7939 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -198,23 +198,44 @@ This is the final qualification queue, not a claim that all listed code is absen
 | A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Redis publication outage and Celery child-redelivery proofs passed; reconcile the remaining exact cases at the final head. |
 | A14–A18 | Cleanup lock/retention/charge owners, Local/MinIO tests and live AWS exact-version/lost-ack cleanup with retained-source survival | Production worker sweeps and exact acceptance-case reconciliation. |
 | A19–A23 | Streaming/framing, safe archives, semantic identity and findings tests; local A19 496 MiB slow-provider memory/backpressure drill | Full permitted maxima and safety matrix, native/deployment scope where required. |
-| A24–A27, A29–A30 | Source/result/fence contracts, dedicated queue and managed-style substitution tests | Essential native isolation/failure/cleanup and single-runner queue correctness remain; broad saturation/load qualification is user-deferred. |
+| A24–A27, A29 | Source/result/fence contracts and dedicated queue tests | Essential native isolation/failure/cleanup and single-runner queue correctness remain; broad saturation/load qualification is user-deferred. |
+| A30 | Managed-style public source acceptance/T5/replay and four typed cases passed at `2f7d8d95c` | Substitution proof complete in its stated scope; no paid-provider integration is selected or required. |
 | A28 | Multi-replica/multi-runner implementation and focused tests | User-deferred until after existing deployment delivery; no second instance is required now. Not claimed passed. |
 | A31–A32 | V14 proves real POST automatic acceptance, exact Contribution/export and default review_pending; focused tests cover applicable awards/replay | Deployed release and final downstream tests. Keep default review_pending guards; live human review remains explicitly deferred by the user. |
 | A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | Affected old writers are retired; finish current-head migration/client convergence and remaining qualification callers. |
 
 ## Configuration and external evidence
 
-C01–C07 remain open until individually reconciled with the specification and
-actual deployment evidence. Test-only leases/profiles are not approved defaults.
-Native Smol qualification must run on the dedicated execution infrastructure,
-not the API host. V14 records connected public native proof; remaining runtime
-faults/capacity and deployed API proof need their own receipts. Live AWS source
-qualification passed separately from MinIO and ordinary SHA-object operation.
-Current main's dedicated credentials replace expiring provider activation;
-submission work must not reinstate the retired activation subsystem.
-Request only concrete missing access or decisions after the corresponding drill
-and proposed values are prepared.
+| Register | Current evidence | Remaining current-delivery action |
+| --- | --- | --- |
+| C01 | Connected CLI receipts observed 85.09s PRE rejection and 88.46s initial acceptance under a 120s qualification deadline; these are command durations, not isolated PRE-stage percentiles. | Set the explicit hosted hard deadline and matching HTTP envelope using measured stages; the approximately 60s target is not proved and 120s is not silently an approved production default. |
+| C02 | Exact native guest/root/image and resource profile passed the connected small-input journey. | Confirm the chosen existing-runner deployment profile against essential native isolation/failure and supported inputs. No new paid provider or hardware design. |
+| C03 | Bounded upload/framing owner tests exist; the earlier 496 MiB slow-provider drill did not complete successfully. | Verify supported input size, memory/backpressure, idle/total timeout and edge limits through the deployed path. A failed near-limit upload is not a pass. |
+| C04 | Dedicated queues and single-runner PRE/background resource reservations are implemented. | Verify the configured single-runner bounds and queue independence on deployment. Multi-replica/multi-runner and broad saturation testing are user-deferred. |
+| C05 | Existing lease/retry/outbox owners have PostgreSQL and real broker/child-redelivery proof. | Reconcile exact release settings and hosted consumer/recovery behavior; reuse current owners. |
+| C06 | The 12h sweep/2h minimum age and guarded exact-version cleanup are implemented; native AWS source permissions and lost-ack reconciliation passed. | Activate and prove the actual cleanup consumer and bounded runtime reaping, preserving accepted sources. No new S3 credential grant is currently requested. |
+| C07 | Managed-style public source/T5/replay substitution and four typed cases passed at `2f7d8d95c`, recorded in `73d81da66`. | No selected paid provider and no vendor integration required for this delivery. Do not call the substitution proof live vendor qualification. |
+
+## Spec reconciliation: bounded remaining delivery work
+
+This reconciliation uses sections 5, 9, 12–18, 20, 23 and 24 of the canonical
+specification, D01–D18/I01–I12, and the user's PR708 submitter-experience
+addition. Apply the explicit scalability and human-review deferrals above.
+Existing implementation/focused proof is not the same as deployed proof.
+
+| Delivery gate | Type of remaining work | Concrete closure |
+| --- | --- | --- |
+| Contributor reads and revision terms (A13, A32, A35; PR708 addition) | Prepared assertions need integration/review and connected execution, not a new status subsystem. | Integrate `44d89caac` for preclaim guides and pending assignment reads; verify authorization/history/deadline cases and applicable reward-changing revision evidence through the current ZIP owner. The passing paired run proves unpaid acceptance only; reuse existing reward owners/tests and do not expand PR709/Finance. |
+| Native failure and isolation (A24–A27) | Test execution and fixes only for demonstrated defects. | Execute the reviewed deadline/isolation fixture and reconcile OOM/crash/output and uncertain-destroy requirements with matching maintained evidence. Valid accepted input must continue when destroy is uncertain, with capacity held. Fixture build alone closes none of these native outcomes. |
+| Upload/retention limits (A14–A23) | Remaining deployed/provider verification. | Supported maximum/slow upload and framing/resource bounds pass; actual cleanup worker deletes only eligible exact versions and preserves accepted/retained sources. Retain already-passing AWS adapter evidence rather than repeating unrelated IAM setup. |
+| Hosted cutover (section 20, A33–A35) | Deployment still outstanding. | Fresh full inventory/drain/backup, retained-data migration from deployed 0069 to current 0093, configured API/MCP/dedicated workers and separate runner, readiness, and forward-repair plan. Published images are prepared, not deployed. |
+| Hosted end-to-end and recovery (A01–A18, A29 single-runner, A31–A32) | Connected production-path verification. | PRE reject/correct, accepted T4/T5, POST revision/correct, exact assignment history and acceptance/contribution, replay, infrastructure distinction, required-review guard, queue independence and bounded worker recovery on the deployed stack. |
+| Release checks and handoff | Final verification/review. | Required final-head backend/CLI/MCP/migration/security checks and actual review findings resolved; PR708 presented for explicit merge approval; post-merge/deployment smoke and accurate operational handoff. No new PR or automatic merge. |
+
+Email delivery is a separate user-deferred external setup item: notification code
+exists, but DNS/key/test delivery remain incomplete. It must not block status
+reads or falsely be reported as working. No second EC2 runner or its proposed
+provisioning policy is part of the current finish list.
 
 The original specification includes D01–D18, I01–I12, T1–T5 and A01–A35.
 Apply the explicit user scope decision above when assessing current delivery;
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 84f5c6fb7..c82d112c9 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12728,3 +12728,24 @@ not needed for current delivery and must not be provisioned/applied on this
 workstream now. Existing implemented correctness guards and dedicated queues
 remain. The overview carries the ordered remaining delivery checklist.
 No live deployment or infrastructure changed for this scope reconciliation.
+
+
+### Reconcile finish list against the specification and PR708 addition
+
+Re-read the decision/invariant ledgers, single-command/read contracts, transaction
+boundaries, failure/cleanup rules, limits, cutover, acceptance matrix and C01–C07,
+plus the contributor-experience addition. The overview now separates prepared
+implementation, missing execution evidence and deployment into six finite gates.
+A30 substitution is recorded as passed in scope; A28 and broad scalability are
+user-deferred, not failures or hidden delivery prerequisites. Paid-provider and
+live human-review work remain excluded. The paired journey proves unpaid
+acceptance; applicable changed-reward/closed-assignment cases must be reconciled
+with existing focused owner tests, not inferred or used to expand Finance.
+
+Current observed PR708 head before this editorial change is `072bfa746`; its
+required GitHub checks are queued, not passing evidence. The retained deployed
+census is schema0069, not the tested schema0093. No deployment occurred during
+this status audit. The reviewed native fixture is built, but its raw transfer
+timed out and left an incomplete owned test archive; no test runner was started
+and normal services/configuration were unchanged. Reconcile that exact partial
+file before a subsequent transfer. Native outcomes remain unproved.

From 19c046b95c9e133f325aaebd99cc17a7605dcf6b Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 15:47:52 +0100
Subject: [PATCH 454/513] Record approved hosted deadlines and staged release
 preflight

---
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     |  2 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 19 +++++++++++++++++++
 2 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index 0a6ea7939..c8f5c93c6 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -208,7 +208,7 @@ This is the final qualification queue, not a claim that all listed code is absen
 
 | Register | Current evidence | Remaining current-delivery action |
 | --- | --- | --- |
-| C01 | Connected CLI receipts observed 85.09s PRE rejection and 88.46s initial acceptance under a 120s qualification deadline; these are command durations, not isolated PRE-stage percentiles. | Set the explicit hosted hard deadline and matching HTTP envelope using measured stages; the approximately 60s target is not proved and 120s is not silently an approved production default. |
+| C01 | Connected CLI receipts observed 85.09s PRE rejection and 88.46s initial acceptance under a 120s qualification deadline; these are command durations, not isolated PRE-stage percentiles. | User approved initial 120s PRE hard deadline, 300s upload total and 30s upload idle on 2026-11-26. Activate the matching HTTP envelope and verify it on the hosted path; the approximately 60s target remains unmet. |
 | C02 | Exact native guest/root/image and resource profile passed the connected small-input journey. | Confirm the chosen existing-runner deployment profile against essential native isolation/failure and supported inputs. No new paid provider or hardware design. |
 | C03 | Bounded upload/framing owner tests exist; the earlier 496 MiB slow-provider drill did not complete successfully. | Verify supported input size, memory/backpressure, idle/total timeout and edge limits through the deployed path. A failed near-limit upload is not a pass. |
 | C04 | Dedicated queues and single-runner PRE/background resource reservations are implemented. | Verify the configured single-runner bounds and queue independence on deployment. Multi-replica/multi-runner and broad saturation testing are user-deferred. |
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index c82d112c9..bda7a3522 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12749,3 +12749,22 @@ this status audit. The reviewed native fixture is built, but its raw transfer
 timed out and left an incomplete owned test archive; no test runner was started
 and normal services/configuration were unchanged. Reconcile that exact partial
 file before a subsequent transfer. Native outcomes remain unproved.
+
+
+### Hosted candidate staged; contributor time limits approved
+
+The user explicitly approved initial 120s PRE hard deadline, separate 300s
+upload total and 30s upload idle on 2026-11-26. These replace the unresolved
+C01 decision; the approximately 60s target is not claimed achieved. Candidate
+`/etc/workstream/release-708-candidate.env` is staged on the app host with the
+published c715 backend/MCP images, exact current runner endpoint/profile,
+installed TLS and separate cleanup credential selectors. Configuration-only
+validation passed. Full preflight failed at image-owned validator startup;
+activation is held pending diagnosis. Active release/environment are unchanged.
+
+An online preflight database snapshot is retained at
+`/var/backups/workstream/pr708-preflight-1795704276863695662/workstream.dump`,
+3,202,574 bytes, SHA256
+`a2d8d08dda64d804c3a73dbd6b0206ef73d84dd62cafdc96ea601758596a0e19`.
+pg_restore list verifies its archive structure, not a full restore. This is not
+a quiesced final cutover backup; take a fresh backup after draining producers.

From 7a1cb659ae18dbc6042d594b934f2bffd7ec95e4 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 15:23:48 +0100
Subject: [PATCH 455/513] Verify preclaim guides and pending assignments in the
 native journey

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 25 +++++
 .../integration/test_journey_locked_guide.py  | 79 +++++++++++++---
 .../test_journey_progress_identity.py         | 38 ++++++++
 cli/tests/journey/bootstrap.py                | 16 +++-
 cli/tests/journey/submission_work.py          | 68 +++++++++++++-
 cli/tests/journey/task_work.py                | 94 ++++++++++++++-----
 6 files changed, 274 insertions(+), 46 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index bda7a3522..fb9b7f61e 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12768,3 +12768,28 @@ An online preflight database snapshot is retained at
 `a2d8d08dda64d804c3a73dbd6b0206ef73d84dd62cafdc96ea601758596a0e19`.
 pg_restore list verifies its archive structure, not a full restore. This is not
 a quiesced final cutover backup; take a fresh backup after draining producers.
+
+### Observe approved originals and live pending assignment activity
+
+Allowed scope. Extend the maintained CLI journey's task, submission and
+bootstrap checks and their focused regressions. Reuse the current isolated
+worker controls. The real state and existing public transport stay the
+qualification boundary. No API, queue, runner or identity changes.
+
+Acceptance. Before claim, the exact contributor reads the approved project
+and ready-task guide, verifies both originals for each public view, and sees
+concealed refusal for a contributor to another project. Claim retains the
+same locked guide. For the first accepted source, park only the fixture POST
+consumer and let the dedicated finalizer complete the exact Submission.
+Verify assignment-ID pending processing and PRE feedback through the built CLI
+and optional installed MCP, then resume the worker and finish normal revision.
+
+39 focused journey cases passed. The guide regression checks two real route
+selectors with distinct download references, denies claim after changed
+identity or bytes, and verifies the locked manifest after claim. The pending
+regression refuses unfinalized intake and operation substitution. During the
+connected fixture the existing graceful POST-worker control stops before any
+accepted source exists. Only a successful pending check restarts it. The outer
+runtime owns teardown on failure while the dedicated scanner and finalizer
+remain active. These cases verify the maintained proof owners. The new native
+preclaim and pending checks still need a matching terminal journey receipt.
diff --git a/cli/tests/integration/test_journey_locked_guide.py b/cli/tests/integration/test_journey_locked_guide.py
index 2363ccbc5..0582f17e4 100644
--- a/cli/tests/integration/test_journey_locked_guide.py
+++ b/cli/tests/integration/test_journey_locked_guide.py
@@ -9,20 +9,35 @@
 import pytest
 
 
-@pytest.mark.parametrize("fault", [None, "version", "bytes"])
-def test_locked_guide_download_preserves_envelope_and_bytes(monkeypatch, tmp_path, fault):
+@pytest.mark.parametrize("fault", [None, "version", "bytes", "locked_guide"])
+def test_locked_guide_download_preserves_envelope_and_bytes(
+    monkeypatch, tmp_path, fault
+):
     monkeypatch.setitem(sys.modules, "public_setup", SimpleNamespace(TASK="task"))
     path = Path(__file__).resolve().parents[1] / "journey/task_work.py"
     spec = importlib.util.spec_from_file_location("journey_locked_guide", path)
     module = importlib.util.module_from_spec(spec)
     spec.loader.exec_module(module)
     monkeypatch.setattr(module, "issue_submitter", lambda *args: "grant")
-    monkeypatch.setattr(module, "create_claimed_task", lambda *args, **kwargs: ("task", "assignment"))
+    monkeypatch.setattr(module, "_release_task", lambda *args, **kwargs: "task")
+    events = []
+
+    def claim(_client, token, task_id):
+        assert (token, task_id) == ("alice", "task")
+        assert events == [
+            (scope, action)
+            for scope in ("project", "task")
+            for action in ("read", "denied", "download")
+        ]
+        events.append(("task", "claim"))
+        return "assignment"
+
+    monkeypatch.setattr(module, "_claim_task", claim)
     bodies = [b"original guide", b"original rules"]
     envelope = {
-        "project_id": "project", "guide_id": "guide", "version": 1,
-        "documents": [{"sha256": "sha256:" + hashlib.sha256(body).hexdigest(),
-                       "byte_count": len(body)} for body in bodies],
+        "project_id": "project",
+        "guide_id": "guide",
+        "version": "v1",
     }
 
     class Client:
@@ -31,22 +46,60 @@ class Client:
         def call(self, token, *arguments, expected_exit=0):
             if arguments[:2] in (("project", "create"), ("project", "show")):
                 return {"id": "other"}
-            assert arguments[:3] == ("task", "guide", "task")
+            scope = arguments[0]
+            selector = (
+                ("project", "guide", "approved", "project")
+                if scope == "project"
+                else ("task", "guide", "task")
+            )
+            assert arguments[: len(selector)] == selector
+            response = envelope | {
+                "documents": [
+                    {
+                        "sha256": "sha256:" + hashlib.sha256(body).hexdigest(),
+                        "byte_count": len(body),
+                        "read_reference": f"/{scope}/document-{i}",
+                    }
+                    for i, body in enumerate(bodies)
+                ]
+            }
+            if scope == "task" and fault == "locked_guide":
+                response["guide_id"] = "other-guide"
             if token == "bob":
                 assert expected_exit == 1
+                events.append((scope, "denied"))
                 return {"error": {"status": 404}}
             if "--download" in arguments:
+                events.append((scope, "download"))
                 destination = Path(arguments[-1])
                 for index, body in enumerate(bodies):
-                    (destination / str(index)).write_bytes(b"corrupted" if fault == "bytes" else body)
-                return envelope | {"version": 2} if fault == "version" else envelope
-            return envelope
+                    (destination / str(index)).write_bytes(
+                        b"corrupted" if (scope, fault) == ("task", "bytes") else body
+                    )
+                return (
+                    response | {"version": "v2"}
+                    if (scope, fault) == ("task", "version")
+                    else response
+                )
+            events.append((scope, "read"))
+            return response
 
-    args = (Client(), {name: name for name in ("manager", "alice", "bob")},
-            {"alice": "alice", "bob": "bob"}, "project")
+    args = (
+        Client(),
+        {name: name for name in ("manager", "alice", "bob")},
+        {"alice": "alice", "bob": "bob"},
+        "project",
+        "guide",
+    )
     if fault:
-        message = "listing changed" if fault == "version" else "originals differ"
+        message = {
+            "version": "listing changed",
+            "bytes": "originals differ",
+            "locked_guide": "exact approved guide",
+        }[fault]
         with pytest.raises(AssertionError, match=message):
             module.claim_and_read(*args)
+        assert ("task", "claim") not in events
     else:
         assert module.claim_and_read(*args) == ("task", "assignment", "grant")
+        assert events[-2:] == [("task", "claim"), ("task", "read")]
diff --git a/cli/tests/integration/test_journey_progress_identity.py b/cli/tests/integration/test_journey_progress_identity.py
index f5baadfc9..a84309fde 100644
--- a/cli/tests/integration/test_journey_progress_identity.py
+++ b/cli/tests/integration/test_journey_progress_identity.py
@@ -148,6 +148,44 @@ def mcp_call(name, params):
         )
 
 
+@pytest.mark.parametrize("fault", [None, "early", "different_source"])
+def test_assignment_pending_binds_completed_finalization(journey, fault):
+    status = {
+        "assignment": {
+            "assignment_id": "assignment-1",
+            "task_id": "task-1",
+            "latest_submission": {
+                "submission_id": "submission-1",
+                "status": "evaluation_pending",
+            },
+        },
+        "current_status": "evaluation_pending",
+        "next_action": "awaiting_evaluation",
+        "post_submission_results": [],
+        "accepted_evidence": None,
+        "feedback_submission_id": None,
+        "intake": {
+            "stage": "evaluation_pending",
+            "operationally_stalled": False,
+            "submission_id": "submission-1",
+            "operation_id": "operation-1",
+            "pre_submission_results": PENDING["pre_submission_results"],
+        },
+    }
+    if fault == "early":
+        status["intake"]["stage"] = "finalization_pending"
+    elif fault == "different_source":
+        status["intake"]["operation_id"] = "operation-2"
+    cli = Client(status, status)
+    mcp = SimpleNamespace(call=lambda *_: status)
+    args = (cli, "token", "task-1", "assignment-1", PENDING, "submission-1")
+    if fault:
+        with pytest.raises(AssertionError, match="exact finalized source"):
+            journey._require_pending_assignment(*args, mcp=mcp)
+    else:
+        journey._require_pending_assignment(*args, mcp=mcp)
+
+
 def test_mcp_renewal_uses_rotated_grant_and_exact_resource(monkeypatch):
     spec = importlib.util.spec_from_file_location(
         "journey_refresh_client", PATH.with_name("client.py")
diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py
index d640e9ca6..2b06172e1 100644
--- a/cli/tests/journey/bootstrap.py
+++ b/cli/tests/journey/bootstrap.py
@@ -5,8 +5,9 @@
 
 from __future__ import annotations
 
+import asyncio
 import base64
-from contextlib import ExitStack
+from contextlib import ExitStack, contextmanager
 import json
 import os
 from pathlib import Path
@@ -46,6 +47,14 @@
 ACTORS = ("administrator", "manager", "finance", "operator", "alice", "bob")
 
 
+@contextmanager
+def pause_post_delivery(stop, start):
+    """Pause the owned effect worker before POST exists; fail into runtime cleanup."""
+    stop()
+    yield
+    asyncio.run(start())
+
+
 def public_actors(client, tokens):
     actors = {
         name: client.call(tokens[name], "whoami")["actor_profile_id"] for name in ACTORS
@@ -416,7 +425,7 @@ def main():
                             str(uuid4()),
                         )
                     project_id = project["id"]
-                    start_workers()
+                    post_worker = start_workers()
                     publish_unpaid_terms(client, tokens["finance"], project_id)
                     guide_id = configure_guide(client, tokens, project_id)
                     approve_and_activate(
@@ -446,7 +455,7 @@ def main():
                         if activation.returncode:
                             raise RuntimeError("documented lifecycle activation failed")
                         task_id, assignment_id, grant = claim_and_read(
-                            client, tokens, actors, project_id
+                            client, tokens, actors, project_id, guide_id
                         )
                         client.complete_stage("task_claim_and_guide")
                         if pre_qualification is not None:
@@ -469,6 +478,7 @@ def main():
                                 task_id,
                                 assignment_id,
                                 grant,
+                                post_delivery_pause=pause_post_delivery(*post_worker),
                                 mcp=mcp,
                             )
                             client.complete_stage(
diff --git a/cli/tests/journey/submission_work.py b/cli/tests/journey/submission_work.py
index c7dd28f39..bed8a31fb 100644
--- a/cli/tests/journey/submission_work.py
+++ b/cli/tests/journey/submission_work.py
@@ -194,11 +194,56 @@ def _pre_missing_has_no_submission(client, token, task_id, assignment_id, *, mcp
         raise AssertionError("PRE status lacks the exact actionable finding")
 
 
-def _require_revision(client, token, project_id, task_id, assignment_id, *, mcp=None):
+def _require_pending_assignment(
+    client, token, task_id, assignment_id, receipt, submission_id, *, mcp=None
+):
+    status = _assignment_status(client, token, task_id, assignment_id, mcp=mcp)
+    intake, latest = status["intake"], status["assignment"]["latest_submission"]
+    if (
+        status["current_status"] != "evaluation_pending"
+        or status["next_action"] != "awaiting_evaluation"
+        or status["post_submission_results"]
+        or status["accepted_evidence"] is not None
+        or status["feedback_submission_id"] not in (None, submission_id)
+        or intake is None
+        or latest is None
+        or intake["stage"] != "evaluation_pending"
+        or intake["operationally_stalled"]
+        or intake["submission_id"] != submission_id
+        or intake["operation_id"] != receipt["operation_id"]
+        or intake["pre_submission_results"] != receipt["pre_submission_results"]
+        or latest["submission_id"] != submission_id
+        or latest["status"] != "evaluation_pending"
+    ):
+        raise AssertionError(
+            "pending assignment differs from its exact finalized source"
+        )
+
+
+def _require_revision(
+    client, token, project_id, task_id, assignment_id, *, post_delivery_pause, mcp=None
+):
     archive = _package(client, "incorrect")
-    key, receipt = _submit(client, token, task_id, assignment_id, archive)
+    with post_delivery_pause:
+        key, receipt = _submit(client, token, task_id, assignment_id, archive)
+        pending = _wait_for_stage(
+            client, token, task_id, key, receipt, "evaluation_pending"
+        )
+        _require_pending_assignment(
+            client,
+            token,
+            task_id,
+            assignment_id,
+            receipt,
+            pending["submission_id"],
+            mcp=mcp,
+        )
     observed = _wait_for_stage(client, token, task_id, key, receipt, "needs_revision")
     submission_id = observed["submission_id"]
+    if submission_id != pending["submission_id"]:
+        raise AssertionError(
+            "pending assignment and POST revision refer to different submissions"
+        )
     status = _assignment_status(client, token, task_id, assignment_id, mcp=mcp)
     revision = status["assignment"]["revision"]
     if (
@@ -258,12 +303,27 @@ def observe_review_pending(client, tokens, project_id, task_id, assignment_id):
 
 
 def submit_and_observe(
-    client, tokens, actors, project_id, task_id, assignment_id, grant, *, mcp=None
+    client,
+    tokens,
+    actors,
+    project_id,
+    task_id,
+    assignment_id,
+    grant,
+    *,
+    post_delivery_pause,
+    mcp=None,
 ):
     token = tokens["alice"]
     _pre_missing_has_no_submission(client, token, task_id, assignment_id, mcp=mcp)
     predecessor = _require_revision(
-        client, token, project_id, task_id, assignment_id, mcp=mcp
+        client,
+        token,
+        project_id,
+        task_id,
+        assignment_id,
+        post_delivery_pause=post_delivery_pause,
+        mcp=mcp,
     )
     archive = _package(client, "correct")
     archive_hash = "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest()
diff --git a/cli/tests/journey/task_work.py b/cli/tests/journey/task_work.py
index 7b57b38f5..c9dba14a9 100644
--- a/cli/tests/journey/task_work.py
+++ b/cli/tests/journey/task_work.py
@@ -46,8 +46,7 @@ def issue_submitter(client, manager, actor_id, project_id):
     )
 
 
-def create_claimed_task(client, tokens, project_id, *, title: str):
-    """Reuse the public manager and contributor lifecycle for each real output."""
+def _release_task(client, tokens, project_id, *, title: str):
     task = client.write_and_replay(
         tokens["manager"],
         "project",
@@ -70,13 +69,59 @@ def create_claimed_task(client, tokens, project_id, *, title: str):
         replay_transition(
             client, tokens["manager"], "project", "task", action, project_id, task_id
         )
-    claimed = replay_transition(client, tokens["alice"], "task", "claim", task_id)
+    return task_id
+
+
+def _claim_task(client, token, task_id):
+    claimed = replay_transition(client, token, "task", "claim", task_id)
     if claimed["task"]["status"] != "in_progress":
         raise AssertionError("claim did not immediately start work")
-    return task_id, claimed["assignment"]["id"]
+    return claimed["assignment"]["id"]
+
+
+def create_claimed_task(client, tokens, project_id, *, title: str):
+    """Reuse the public manager and contributor lifecycle for each real output."""
+    task_id = _release_task(client, tokens, project_id, title=title)
+    return task_id, _claim_task(client, tokens["alice"], task_id)
 
 
-def claim_and_read(client, tokens, actors, project_id):
+def _verified_guide(client, tokens, command, directory):
+    guide = client.call(tokens["alice"], *command)
+    denied = client.call(tokens["bob"], *command, expected_exit=1)
+    if denied["error"].get("status") != 404:
+        raise AssertionError(
+            "foreign-project contributor did not receive concealed guide denial"
+        )
+    destination = client.directory / directory
+    destination.mkdir(mode=0o700)
+    downloaded = client.call(tokens["alice"], *command, "--download", str(destination))
+    if downloaded != guide or len(guide["documents"]) != 2:
+        raise AssertionError("guide listing changed during download")
+    actual = sorted(
+        ("sha256:" + hashlib.sha256(path.read_bytes()).hexdigest(), path.stat().st_size)
+        for path in destination.iterdir()
+    )
+    expected = sorted(
+        (item["sha256"], item["byte_count"]) for item in guide["documents"]
+    )
+    if actual != expected:
+        raise AssertionError(
+            "downloaded originals differ from the exact public manifest"
+        )
+    return guide
+
+
+def _guide_identity(manifest):
+    # Each shipped client already validates read_reference against its own route.
+    return manifest | {
+        "documents": [
+            {key: value for key, value in document.items() if key != "read_reference"}
+            for document in manifest["documents"]
+        ]
+    }
+
+
+def claim_and_read(client, tokens, actors, project_id, guide_id):
     grant = issue_submitter(client, tokens["manager"], actors["alice"], project_id)
     other = client.call(
         tokens["manager"],
@@ -92,28 +137,25 @@ def claim_and_read(client, tokens, actors, project_id):
     issue_submitter(client, tokens["manager"], actors["bob"], other["id"])
     if client.call(tokens["bob"], "project", "show", other["id"])["id"] != other["id"]:
         raise AssertionError("foreign-project contributor setup failed")
-    task_id, assignment_id = create_claimed_task(
-        client, tokens, project_id, title="Summarize the fixed incident events"
-    )
-    guide = client.call(tokens["alice"], "task", "guide", task_id)
-    denied = client.call(tokens["bob"], "task", "guide", task_id, expected_exit=1)
-    if denied["error"].get("status") != 404:
-        raise AssertionError("unassigned actor did not receive concealed guide denial")
-    destination = client.directory / "locked-guide"
-    destination.mkdir(mode=0o700)
-    downloaded = client.call(
-        tokens["alice"], "task", "guide", task_id, "--download", str(destination)
+    approved = _verified_guide(
+        client,
+        tokens,
+        ("project", "guide", "approved", project_id),
+        "approved-guide",
     )
-    if downloaded != guide or len(guide["documents"]) != 2:
-        raise AssertionError("locked guide listing changed during download")
-    documents = guide["documents"]
-    actual = sorted(
-        ("sha256:" + hashlib.sha256(path.read_bytes()).hexdigest(), path.stat().st_size)
-        for path in destination.iterdir()
-    )
-    expected = sorted((item["sha256"], item["byte_count"]) for item in documents)
-    if actual != expected:
+    if (approved["project_id"], approved["guide_id"]) != (project_id, guide_id):
         raise AssertionError(
-            "downloaded originals differ from the locked public manifest"
+            "approved contributor guide differs from the activated project guide"
         )
+    task_id = _release_task(
+        client, tokens, project_id, title="Summarize the fixed incident events"
+    )
+    before_claim = _verified_guide(
+        client, tokens, ("task", "guide", task_id), "locked-guide"
+    )
+    if _guide_identity(before_claim) != _guide_identity(approved):
+        raise AssertionError("released task did not lock the exact approved guide")
+    assignment_id = _claim_task(client, tokens["alice"], task_id)
+    if client.call(tokens["alice"], "task", "guide", task_id) != before_claim:
+        raise AssertionError("claim changed the locked guide manifest")
     return task_id, assignment_id, grant

From 961d5606d0e08afcd2e40b3674cae48d23643604 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 16:13:52 +0100
Subject: [PATCH 456/513] Make packaged release code readable to the guide
 parser

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md      | 10 ++++++++++
 docker/backend/Dockerfile.release                      |  3 ++-
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index fb9b7f61e..e004d4902 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12793,3 +12793,13 @@ accepted source exists. Only a successful pending check restarts it. The outer
 runtime owns teardown on failure while the dedicated scanner and finalizer
 remain active. These cases verify the maintained proof owners. The new native
 preclaim and pending checks still need a matching terminal journey receipt.
+
+
+### Make release code readable to the isolated guide parser
+
+The hosted cutover reached schema 0093. The candidate guide parser then
+failed to import `app` because the archived source carried owner-only file
+modes. The bounded repair covers the backend release Dockerfile and its
+image verifier. The isolated parser must import the packaged code both as
+capability-restricted root and as the broker UID. Runtime and secret
+directories retain their existing permissions.
diff --git a/docker/backend/Dockerfile.release b/docker/backend/Dockerfile.release
index 3d9949ffd..dbe9e9de9 100644
--- a/docker/backend/Dockerfile.release
+++ b/docker/backend/Dockerfile.release
@@ -53,7 +53,8 @@ RUN --mount=type=cache,target=/root/.cache/uv \
     && chmod 0444 /etc/workstream/project-agent-sdk-environment \
     && rm -rf /workspace/backend/build /workspace/backend/workstream_backend.egg-info \
     && chmod 0555 /usr/local/bin/workstream-release-entrypoint \
-    && chown -R workstream:workstream /workspace /opt/venv
+    && chown -R workstream:workstream /workspace /opt/venv \
+    && chmod -R a+rX /workspace /opt/venv
 
 USER workstream
 

From 2942dd4e76b1c8a82a1d7a4070ceff79246f6732 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 16:17:46 +0100
Subject: [PATCH 457/513] Verify packaged imports under both guide parser
 identities

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  6 ++
 scripts/test_hosted_release_images.py         | 66 ++++++++++++++-----
 scripts/verify_hosted_release_images.py       | 37 +++++++++--
 3 files changed, 87 insertions(+), 22 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index e004d4902..591fbc616 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12803,3 +12803,9 @@ modes. The bounded repair covers the backend release Dockerfile and its
 image verifier. The isolated parser must import the packaged code both as
 capability-restricted root and as the broker UID. Runtime and secret
 directories retain their existing permissions.
+
+The release image verifier now reads the packaged source bytes and imports
+the exact parser module as both identities. A local Docker fixture with
+owner-only application source reproduced the permission failure for both
+identities and the verifier rejected it. The verifier passed the readable
+release fixture, and all 20 focused verifier tests passed.
diff --git a/scripts/test_hosted_release_images.py b/scripts/test_hosted_release_images.py
index c4e09dcf9..275e19336 100644
--- a/scripts/test_hosted_release_images.py
+++ b/scripts/test_hosted_release_images.py
@@ -267,41 +267,71 @@ def test_backend_entrypoint_accepts_neutral_parser_and_rejects_wrong_sdk(self):
         ):
             with (
                 self.subTest(sdk_environment=sdk_environment),
-                patch.object(proof, "run", side_effect=[parser, mismatch]) as runs,
+                patch.object(
+                    proof, "run", side_effect=[parser, parser, mismatch]
+                ) as runs,
                 patch.object(proof, "checked", return_value=b"") as cleanup,
             ):
                 proof.verify_backend_entrypoint(
                     "sha256:" + "a" * 64, sdk_environment, "123-1"
                 )
-            parser_command = runs.call_args_list[0].args[0]
-            mismatch_command = runs.call_args_list[1].args[0]
-            self.assertIn("WORKSTREAM_RELEASE_ROLE=parser", parser_command)
-            self.assertFalse(
-                any(
-                    value.startswith("WORKSTREAM_PROJECT_AGENT_RUNTIME=")
-                    for value in parser_command
-                )
+            root_command, broker_command, mismatch_command = (
+                invocation.args[0] for invocation in runs.call_args_list
             )
+            for command, identity, capabilities in (
+                (root_command, "0:0", ["KILL", "SETGID", "SETUID"]),
+                (broker_command, "10002:10001", []),
+            ):
+                self.assertIn("WORKSTREAM_RELEASE_ROLE=parser", command)
+                self.assertFalse(
+                    any(
+                        value.startswith("WORKSTREAM_PROJECT_AGENT_RUNTIME=")
+                        for value in command
+                    )
+                )
+                self.assertEqual(command[command.index("--user") + 1], identity)
+                self.assertEqual(command[command.index("--cap-drop") + 1], "ALL")
+                self.assertEqual(
+                    [
+                        command[i + 1]
+                        for i, option in enumerate(command)
+                        if option == "--cap-add"
+                    ],
+                    capabilities,
+                )
+                self.assertEqual(command[-4:-1], ["python", "-B", "-c"])
+                self.assertIn(
+                    "from app.adapters.guide_document_tools import service", command[-1]
+                )
+                self.assertIn(
+                    "Path('/workspace/backend/app/__init__.py').read_bytes()",
+                    command[-1],
+                )
+                self.assertIn("Path(service.__file__).read_bytes()", command[-1])
             self.assertIn("WORKSTREAM_RELEASE_ROLE=worker", mismatch_command)
             self.assertIn(
                 f"WORKSTREAM_PROJECT_AGENT_RUNTIME={wrong_runtime}",
                 mismatch_command,
             )
-            self.assertEqual(cleanup.call_count, 2)
+            self.assertEqual(cleanup.call_count, 3)
 
     def test_backend_entrypoint_smoke_rejects_changed_outcomes(self):
         failures = (
             SimpleNamespace(returncode=1, stdout=b"", stderr=b"private"),
             SimpleNamespace(returncode=0, stdout=b"private", stderr=b""),
         )
-        for failure in failures:
-            with (
-                self.subTest(failure=failure),
-                patch.object(proof, "run", return_value=failure),
-                patch.object(proof, "checked", return_value=b""),
-                self.assertRaisesRegex(ValueError, "entrypoint behavior differs"),
-            ):
-                proof.verify_backend_entrypoint("fixture", "agents", "123-1")
+        parser = SimpleNamespace(returncode=0, stdout=b"", stderr=b"")
+        for previous, case in (([], "parser-root"), ([parser], "parser-broker")):
+            for failure in failures:
+                with (
+                    self.subTest(case=case, failure=failure),
+                    patch.object(proof, "run", side_effect=[*previous, failure]),
+                    patch.object(proof, "checked", return_value=b""),
+                    self.assertRaisesRegex(
+                        ValueError, f"backend {case} entrypoint behavior differs"
+                    ),
+                ):
+                    proof.verify_backend_entrypoint("fixture", "agents", "123-1")
 
     def test_loader_must_have_the_exact_nonwritable_executable_mode(self):
         with tempfile.TemporaryDirectory() as directory:
diff --git a/scripts/verify_hosted_release_images.py b/scripts/verify_hosted_release_images.py
index 3c920d0a8..1e0e753e6 100644
--- a/scripts/verify_hosted_release_images.py
+++ b/scripts/verify_hosted_release_images.py
@@ -367,15 +367,42 @@ def inspect_image(image: str, role: str, owner: str) -> dict:
 
 
 def verify_backend_entrypoint(image: str, sdk_environment: str, owner: str) -> None:
-    """Exercise neutral parser startup and fail-closed inference SDK binding."""
+    """Check restricted parser code access and fail-closed inference SDK binding."""
     require(sdk_environment in {"agents", "omnicore"}, "SDK environment differs")
     wrong_runtime = (
         "omnicore_agent" if sdk_environment == "agents" else "openai_agents_sdk"
     )
+    parser_import = (
+        "from pathlib import Path; "
+        "Path('/workspace/backend/app/__init__.py').read_bytes(); "
+        "from app.adapters.guide_document_tools import service; "
+        "assert service.__file__ == "
+        "'/workspace/backend/app/adapters/guide_document_tools/service.py'; "
+        "Path(service.__file__).read_bytes()"
+    )
     cases = (
         (
-            "parser",
+            "parser-root",
+            ["WORKSTREAM_RELEASE_ROLE=parser"],
+            [
+                "--user",
+                "0:0",
+                "--cap-add",
+                "KILL",
+                "--cap-add",
+                "SETGID",
+                "--cap-add",
+                "SETUID",
+            ],
+            ["python", "-B", "-c", parser_import],
+            0,
+            b"",
+        ),
+        (
+            "parser-broker",
             ["WORKSTREAM_RELEASE_ROLE=parser"],
+            ["--user", "10002:10001"],
+            ["python", "-B", "-c", parser_import],
             0,
             b"",
         ),
@@ -385,11 +412,13 @@ def verify_backend_entrypoint(image: str, sdk_environment: str, owner: str) -> N
                 "WORKSTREAM_RELEASE_ROLE=worker",
                 f"WORKSTREAM_PROJECT_AGENT_RUNTIME={wrong_runtime}",
             ],
+            [],
+            ["/bin/true"],
             1,
             b"project agent runtime does not match the installed SDK environment\n",
         ),
     )
-    for case, environment, expected_status, expected_stderr in cases:
+    for case, environment, identity, invocation, expected_status, expected_stderr in cases:
         name = "workstream-release-proof-" + uuid.uuid4().hex
         command = [
             "docker",
@@ -416,7 +445,7 @@ def verify_backend_entrypoint(image: str, sdk_environment: str, owner: str) -> N
         ]
         for setting in environment:
             command.extend(("--env", setting))
-        command.extend((image, "/bin/true"))
+        command.extend((*identity, image, *invocation))
         try:
             result = run(command)
             require(

From 01f7fbeb07344d58d1cf5bc250043f8533295065 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 16:44:50 +0100
Subject: [PATCH 458/513] Record hosted submission cutover and cleanup
 principal

---
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     | 33 +++++++--------
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 41 +++++++++++++++++++
 deploy/hosted/README.md                       |  8 ++++
 docs/roadmap_status.md                        |  6 +--
 4 files changed, 69 insertions(+), 19 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index c8f5c93c6..7bc8a0542 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -20,11 +20,11 @@ Current finish list, in execution order:
 - [x] Reconcile main cleanup and preserve required owners/tests in PR708.
 - [x] Prove the connected raw-ZIP PRE -> T5 -> POST -> same-assignment revision
   -> acceptance journey through CLI/MCP with the separate runner.
-- [ ] Integrate/review the prepared preclaim-guide and pending-status assertions.
+- [x] Integrate the reviewed preclaim-guide and pending-status assertions.
+- [x] Back up retained data, migrate and activate the hosted API, MCP and
+  dedicated Celery workers with the approved operational profiles.
 - [ ] Finish essential native isolation, bounded failure and cleanup proof for
   the existing runner; fix only observed defects needed for this deployment.
-- [ ] Stage the existing hosted API release, set its explicit operational
-  profiles, back up retained data, migrate and activate dedicated workers/MCP.
 - [ ] Prove the hosted contributor journey, actionable failure/retry feedback,
   retained ZIP custody and actual S3 cleanup; verify supported upload bounds.
 - [ ] Run required final-head checks, resolve actual failures, and present PR708
@@ -81,7 +81,8 @@ work. Existing reward owners remain authoritative.
 - [ ] Quality-feedback email uses the stable assignment ID for POST revision requests and revision-limit rejection, with a dedicated consumer and no infrastructure-failure notifications; qualify delivery after sender DNS verification and private key configuration.
 
 The checked items have focused contract/PostgreSQL proof and the maintained
-connected CLI/MCP journey described above. Hosted deployment remains separate.
+connected CLI/MCP journey described above. Hosted deployment is active, and its
+contributor submission qualification remains open.
 The dedicated queue topology and isolated scanner-to-T5 regression are integrated.
 PR722 removes the retired experimental native harness, including branch-only
 extensions. Its receipts remain historical; current native qualification must
@@ -99,8 +100,9 @@ mixed queue list, and no catch-all worker handles unrelated workloads. Outbox
 publication must remain available while POST execution is stopped or saturated;
 it must not share the POST or submission-finalization consumer. The PRE6 drill
 accepted a fresh source but exposed publication waiting behind the paused general
-worker. Dedicated scanner delivery now has a real Redis/prefork T5 proof;
-the connected journey passes, while saturation and deployed confirmation remain open.
+worker. Dedicated scanner delivery has real Redis/prefork T5 proof. Live queue
+inspection found seven consumers with one named queue each. The hosted journey
+still needs to verify scoped queue independence.
 The application instance is a verified t3.large; the dedicated always-on runner
 is an m7i.large with native KVM. App-origin mTLS health and native transport
 smoke receipts establish connectivity. V14 also proves the connected local API
@@ -154,9 +156,9 @@ journey. The remaining cleanup and verification requirements below still apply.
 
 | Order | Required outcome | Concrete finishing evidence |
 | --- | --- | --- |
-| 1 | Reproduce the connected proof on the deployed API | The maintained paired journey at `73d81da66` passes real PRE/T5/POST, same-assignment correction, automatic acceptance, exact ZIP/Contribution export, rejection, replay and default review_pending with an isolated real identity provider, local API and separate AWS runner. The actual deployed API/consumers remain to activate and prove. |
+| 1 | Reproduce the connected proof on the deployed API | The maintained paired journey at `73d81da66` passes real PRE/T5/POST, same-assignment correction, automatic acceptance, exact ZIP/Contribution export, rejection, replay and default review_pending with an isolated real identity provider, local API and separate AWS runner. The hosted API and consumers are active at `2942dd4e7`; reproduce the contributor journey on that release. |
 | 2 | Finish affected qualification callers | Preparation API/materialization and the admission-only TASK writer are removed. PR722 retires the experimental harness; the maintained native CLI/MCP journey passes; complete its remaining fault proof through the same owners using raw ZIP acceptance and dedicated finalization. Do not restore the old harness. |
-| 3 | Complete separate-runner integration and runtime/provider/resource qualification | Activate the prepared authenticated remote configuration on the app deployment; actual Smol one-session/isolation proof on runner infrastructure; supported input bounds, bounded failure/cleanup and timing measurements on the existing runner; applicable AWS exact-version/uncertain multipart proof. Portable/MinIO evidence is insufficient for these claims. |
+| 3 | Complete separate-runner integration and runtime/provider/resource qualification | The hosted app uses the authenticated separate runner. Finish Smol one-session/isolation, bounded failure/cleanup and timing measurements on that runner. Verify supported input bounds and applicable AWS exact-version/uncertain multipart behavior through the deployed path. |
 | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; each current-scope acceptance row linked to an executed, scope-matching result, with user-deferred scalability explicitly excluded. Fix actual failures without weakening requirements. |
 | 5 | Reconcile configuration and delivery documentation | Resolve C01–C07 using measured/approved values; update affected roadmap/overview/index and local spreadsheet exports; preserve the distinction between implemented, exposed and deployed. |
 
@@ -165,9 +167,8 @@ real PRE/T4/T5/POST, exact source and Contribution/export custody, PRE/POST
 rejection and default review_pending; owned database/bucket cleanup passed.
 Live AWS source qualification passed at 074cade5e with the actual restricted
 runtime/cleanup identities, pinned versions, lost acknowledgements and exact
-cleanup. Neither result claims a deployed API journey. The next boundary is
-qualified AWS admission activation, separate-runner hosted cutover and remaining
-native fault/isolation/capacity and final full-head qualification. Ordinary
+cleanup. The hosted cutover is complete. The deployed contributor journey,
+native fault/isolation/capacity and full-head qualification remain open. Ordinary
 indexed unsealed cleanup is implemented; optional absent-operation inventory is
 not a new prerequisite. Known uncertain writes stay owned and charged until
 settled. Do not repeat completed local proofs instead of closing these gaps.
@@ -202,18 +203,18 @@ This is the final qualification queue, not a claim that all listed code is absen
 | A30 | Managed-style public source acceptance/T5/replay and four typed cases passed at `2f7d8d95c` | Substitution proof complete in its stated scope; no paid-provider integration is selected or required. |
 | A28 | Multi-replica/multi-runner implementation and focused tests | User-deferred until after existing deployment delivery; no second instance is required now. Not claimed passed. |
 | A31–A32 | V14 proves real POST automatic acceptance, exact Contribution/export and default review_pending; focused tests cover applicable awards/replay | Deployed release and final downstream tests. Keep default review_pending guards; live human review remains explicitly deferred by the user. |
-| A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | Affected old writers are retired; finish current-head migration/client convergence and remaining qualification callers. |
+| A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | The hosted schema migrated from 0069 to 0093 with retained counts verified. Finish connected client contract and qualification evidence on the deployed release. |
 
 ## Configuration and external evidence
 
 | Register | Current evidence | Remaining current-delivery action |
 | --- | --- | --- |
-| C01 | Connected CLI receipts observed 85.09s PRE rejection and 88.46s initial acceptance under a 120s qualification deadline; these are command durations, not isolated PRE-stage percentiles. | User approved initial 120s PRE hard deadline, 300s upload total and 30s upload idle on 2026-11-26. Activate the matching HTTP envelope and verify it on the hosted path; the approximately 60s target remains unmet. |
+| C01 | Connected CLI receipts observed 85.09s PRE rejection and 88.46s initial acceptance under a 120s qualification deadline; these are command durations, not isolated PRE-stage percentiles. | The hosted release uses the approved 120s PRE hard deadline, 300s upload total and 30s upload idle. Verify the HTTP envelope on the hosted path. The approximately 60s target remains unmet. |
 | C02 | Exact native guest/root/image and resource profile passed the connected small-input journey. | Confirm the chosen existing-runner deployment profile against essential native isolation/failure and supported inputs. No new paid provider or hardware design. |
 | C03 | Bounded upload/framing owner tests exist; the earlier 496 MiB slow-provider drill did not complete successfully. | Verify supported input size, memory/backpressure, idle/total timeout and edge limits through the deployed path. A failed near-limit upload is not a pass. |
 | C04 | Dedicated queues and single-runner PRE/background resource reservations are implemented. | Verify the configured single-runner bounds and queue independence on deployment. Multi-replica/multi-runner and broad saturation testing are user-deferred. |
 | C05 | Existing lease/retry/outbox owners have PostgreSQL and real broker/child-redelivery proof. | Reconcile exact release settings and hosted consumer/recovery behavior; reuse current owners. |
-| C06 | The 12h sweep/2h minimum age and guarded exact-version cleanup are implemented; native AWS source permissions and lost-ack reconciliation passed. | Activate and prove the actual cleanup consumer and bounded runtime reaping, preserving accepted sources. No new S3 credential grant is currently requested. |
+| C06 | The 12h sweep/2h minimum age and guarded exact-version cleanup are implemented; native AWS source permissions and lost-ack reconciliation passed. | The dedicated cleanup consumer is healthy with its provisioned fixed principal. Prove exact-version deletion and bounded runtime reaping on the hosted path while preserving accepted sources. |
 | C07 | Managed-style public source/T5/replay substitution and four typed cases passed at `2f7d8d95c`, recorded in `73d81da66`. | No selected paid provider and no vendor integration required for this delivery. Do not call the substitution proof live vendor qualification. |
 
 ## Spec reconciliation: bounded remaining delivery work
@@ -225,10 +226,10 @@ Existing implementation/focused proof is not the same as deployed proof.
 
 | Delivery gate | Type of remaining work | Concrete closure |
 | --- | --- | --- |
-| Contributor reads and revision terms (A13, A32, A35; PR708 addition) | Prepared assertions need integration/review and connected execution, not a new status subsystem. | Integrate `44d89caac` for preclaim guides and pending assignment reads; verify authorization/history/deadline cases and applicable reward-changing revision evidence through the current ZIP owner. The passing paired run proves unpaid acceptance only; reuse existing reward owners/tests and do not expand PR709/Finance. |
+| Contributor reads and revision terms (A13, A32, A35; PR708 addition) | Connected execution remains. | The preclaim-guide and pending assignment checks are integrated. Verify authorization, history and deadline cases with the current ZIP owner, and reconcile applicable reward-changing revision evidence with existing reward owners/tests. The passing paired run proves unpaid acceptance. |
 | Native failure and isolation (A24–A27) | Test execution and fixes only for demonstrated defects. | Execute the reviewed deadline/isolation fixture and reconcile OOM/crash/output and uncertain-destroy requirements with matching maintained evidence. Valid accepted input must continue when destroy is uncertain, with capacity held. Fixture build alone closes none of these native outcomes. |
 | Upload/retention limits (A14–A23) | Remaining deployed/provider verification. | Supported maximum/slow upload and framing/resource bounds pass; actual cleanup worker deletes only eligible exact versions and preserves accepted/retained sources. Retain already-passing AWS adapter evidence rather than repeating unrelated IAM setup. |
-| Hosted cutover (section 20, A33–A35) | Deployment still outstanding. | Fresh full inventory/drain/backup, retained-data migration from deployed 0069 to current 0093, configured API/MCP/dedicated workers and separate runner, readiness, and forward-repair plan. Published images are prepared, not deployed. |
+| Hosted cutover (section 20, A33–A35) | **Deployment complete.** | The drained backup and 0069-to-0093 migration retained all 132 existing table counts. The repaired `2942dd4e7` API, coupled MCP and seven dedicated Celery workers are active. The installed boot unit points to the repaired source. See the [cutover evidence](WS-SUBMIT-001-01.md#hosted-schema-and-release-cutover-completed). |
 | Hosted end-to-end and recovery (A01–A18, A29 single-runner, A31–A32) | Connected production-path verification. | PRE reject/correct, accepted T4/T5, POST revision/correct, exact assignment history and acceptance/contribution, replay, infrastructure distinction, required-review guard, queue independence and bounded worker recovery on the deployed stack. |
 | Release checks and handoff | Final verification/review. | Required final-head backend/CLI/MCP/migration/security checks and actual review findings resolved; PR708 presented for explicit merge approval; post-merge/deployment smoke and accurate operational handoff. No new PR or automatic merge. |
 
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 591fbc616..a1d2e9387 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12809,3 +12809,44 @@ the exact parser module as both identities. A local Docker fixture with
 owner-only application source reproduced the permission failure for both
 identities and the verifier rejected it. The verifier passed the readable
 release fixture, and all 20 focused verifier tests passed.
+
+
+### Hosted schema and release cutover completed
+
+This update records the observed hosted cutover and recovery, updates the
+initiative overview and status ledger, and documents the existing cleanup
+principal prerequisite. It includes the roadmap terminology correction for
+Agent Gates job 139990856480. Hosted submission qualification remains separate.
+
+The drained custom-format backup and cutover journal are retained privately at
+`/var/backups/workstream/pr708-cutover-1795705616912693356`. Alembic migrated
+`0069_remove_artifact_proof` to `0093_verified_email_observation`. All 132
+retained table counts matched before and after migration, with 137 public tables
+afterward. PostgreSQL, Redis and identity retained their original container IDs
+through activation. The deployed environment carries the approved 120s PRE,
+300s total upload and 30s idle limits. The existing single separate runner
+remains the configured mTLS execution endpoint.
+
+The repaired release was built and verified at
+`2942dd4e76b1c8a82a1d7a4070ceff79246f6732`. Publication receipt
+`/tmp/workstream-published-1795706971727723546.json` records the agents and
+omnicore repository digests, respectively
+`sha256:3379e66e69592694c0faf4009d05a5d831cb03a214cbdd9e7a01e0600bb54108` and
+`sha256:9deca7aa4df2a70f28a639a2492a8764be1e5036c48e6fdd23a82ea3ea048c0b`.
+API and model proxy use the agents image. The existing MCP artifact was recreated
+against the new API namespace, and the installed boot unit points to the verified
+source. The forward journal reached `repaired-release-healthy-pending-public-proof`
+and its owned boot guard was released.
+
+The existing Access Administrator provisioned the required fixed principal
+`workstream.artifact.source_cleanup` through the public service-actor owner,
+which returned HTTP 201. The cleanup consumer became healthy after recreation.
+Live Celery inspection returned seven distinct consumers with exactly one named
+queue each. Public CLI identity reads passed for the Project Manager, Finance and
+Operator, and the original Project Manager grant was preserved. Provider-free
+hosted guide activation completed through the public owner, with private receipt
+`/tmp/workstream-hosted-journey-2942/guide/result.json`.
+
+The hosted contributor ZIP journey and recovery, exact-version cleanup, maximum
+supported upload and remaining single-runner native failure/isolation still
+need matching evidence. Email remains disabled pending the sender/key proof.
diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md
index e54c223fa..6fef38f89 100644
--- a/deploy/hosted/README.md
+++ b/deploy/hosted/README.md
@@ -259,6 +259,14 @@ authorized deletion identity. Only the exclusive source-cleanup worker receives
 that file; preflight rejects a reused ARN, path or inode. Beat, MCP, parser and
 checker guests receive no storage key.
 
+Before starting the source-cleanup consumer, have an Access Administrator
+provision the fixed service identity `workstream.artifact.source_cleanup` through
+`POST /api/v1/service-actors` or
+`workstream admin service-actor provision --input FILE --idempotency-key UUID`.
+Use a stable deployment subject and keep the original key for retries. The
+cleanup startup check requires the active service actor and identity link. The
+S3 deletion credential supplies storage access separately.
+
 Follow [S3 credential setup](../../docs/operations_aws_s3_credentials.md) for
 restricted policies and rotation. Qualification verifies real conditional
 upload/readback and denied destructive access before cutover. There are no
diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md
index 340103533..d82d55e71 100644
--- a/docs/roadmap_status.md
+++ b/docs/roadmap_status.md
@@ -701,9 +701,9 @@ cannot be reused as post-submission review-gate evidence. See the
 | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent |
 | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS |
 | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate |
-| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | The maintained CLI/MCP journey passes with real isolated Keycloak, the separate native runner and dedicated workers: shared PRE feedback, POST revision, same-assignment corrected upload, replay, retained history and unpaid final acceptance. See the [submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md). Hosted cutover, essential single-runner failure/isolation and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing until after delivery. |
-| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. Remaining delivery gates are essential native failure/isolation, supported-upload qualification, qualified AWS admission activation and deployed API/consumer cutover. Multi-replica/multi-runner scalability qualification is user-deferred until after delivery. Historical upload-overlap/zero-or-multiple-PRE drills do not qualify the current flow. |
-| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | The connected native CLI/MCP journey and scoped AWS exact-version qualification pass. Complete AWS admission activation, hosted cutover and the final acceptance matrix. Earlier preparation/admission and Garden receipts remain historical, not qualification of the replacement flow. Live human review remains deferred. |
+| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | The maintained CLI/MCP journey with real isolated Keycloak, the separate native runner and dedicated Celery workers proves shared PRE feedback, POST revision, same-assignment correction, replay, retained history and unpaid final acceptance. The schema 0093 hosted release is active. Hosted contributor submission, exact cleanup, essential single-runner failure/isolation and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing. See the [submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md). |
+| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. The hosted API and dedicated consumers are active. Verify hosted intake, supported uploads and essential native failure/isolation on that release. Multi-replica/multi-runner scalability qualification is user-deferred until after delivery. |
+| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | The connected native CLI/MCP journey and scoped AWS exact-version qualification pass. The dedicated finalizer is deployed. Verify hosted T4/T5 and exact retained source custody and close the applicable acceptance matrix. Live human review remains deferred. |
 | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. Earlier local API/Celery evidence covered both policy branches, prefork recovery and later authority revocation. Current connected qualification uses real isolated Keycloak and the exact separate-runner profile; hosted identity qualification remains separate | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate |
 | Operator uncertain-delivery CLI | **Existing public delivery routes consumed by explicit CLI commands** | WS-CLI-001-40 adds one project-bound page of finalized UNKNOWN deliveries and a deliberate reasoned, UUID-keyed reconciliation of one exact event. Fresh backend authority and classification remain decisive; a page never authorizes a later write. | Native signed PostgreSQL proof is scoped to an owner-produced source; a hosted interruption and deployed CLI remain unproven |
 | Review queue and lease | **Hidden persistence foundation** | Queue/admission idempotency and ReviewLease/preference persistence; complete unavailable REV action/principal catalogue and typed AUTH contracts; ART-07A1 metadata-only packet contract and REV-03B immutable normalized packet persistence with live ingest custody; REV-04A Review/finding/resolution and completed request storage | Future resolver proof; canonical admission from `allow_review`; claim/lease/packet authority; lease copies the Submission-stamped policy version with no CON lookup |

From 5ff6af009feab54c81b7ae59c53f9981c471d4d6 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:04:15 +0100
Subject: [PATCH 459/513] Repair old-head MCP type gate and runner restart
 fixture

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 22 ++++++++++
 .../workstream-checker-service/src/main.rs    |  2 +
 mcp_server/tests/test_task_execution.py       | 40 +++++++++++++++++++
 mcp_server/workstream_mcp/http_gateway.py     |  2 +
 4 files changed, 66 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index a1d2e9387..5b6aa31db 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12850,3 +12850,25 @@ hosted guide activation completed through the public owner, with private receipt
 The hosted contributor ZIP journey and recovery, exact-version cleanup, maximum
 supported upload and remaining single-runner native failure/isolation still
 need matching evidence. Email remains disabled pending the sender/key proof.
+
+### Old-head CI failure reconciliation
+
+The `7a1cb659a` CI run failed four selected jobs. `auth-boundary-preflight`
+and `shared_foundations_d` both rejected the same ownership partition transition;
+the merge of `origin/main` into PR708 added the exact retired
+`mutation_policy.py`/replacement `behavior_source.py` transition, and the
+current-head ownership validator passes. The shared lane artifact recorded 730
+passed and only that one ownership failure.
+
+The MCP package type gate found an upstream JSON error code typed as `Any | None`
+used as a dictionary key. The gateway now accepts only a string before looking
+up safe contributor recovery wording. Focused transport tests include malformed
+non-string codes and keep private upstream text out of the response; mypy passes.
+
+The Rust service test `startup_recovery_is_instance_scoped` kept a cloned
+socket-parent descriptor in its same-process test configuration after dropping
+the listener. That descriptor kept the exclusive lock, unlike a fresh process.
+The test releases this retained descriptor before simulating restart, preserving
+the real lock and custody checks. The exact test passes. These repairs concern
+the old-head CI run; the new-head workflow and hosted public journey must still
+finish before any full release claim.
diff --git a/external_checkers/workstream-checker-service/src/main.rs b/external_checkers/workstream-checker-service/src/main.rs
index b15f9a58a..23684c9c6 100644
--- a/external_checkers/workstream-checker-service/src/main.rs
+++ b/external_checkers/workstream-checker-service/src/main.rs
@@ -3810,6 +3810,8 @@ esac
             "own stale container was not recovered"
         );
         drop(b_listener);
+        // A new process has no cloned descriptor for the previous listener lock.
+        b.control_root = None;
         let restarted = prepare_listener(&mut b).unwrap();
         assert_eq!(container_owner(&b).unwrap(), b_owner);
         drop(restarted);
diff --git a/mcp_server/tests/test_task_execution.py b/mcp_server/tests/test_task_execution.py
index a431b0ccc..87f78ec29 100644
--- a/mcp_server/tests/test_task_execution.py
+++ b/mcp_server/tests/test_task_execution.py
@@ -686,3 +686,43 @@ def test_submission_transport_failure_preserves_safe_recovery_guidance(
     assert "private-provider" not in response.text
     assert "private-token" not in response.text
     assert len(received) == 1
+
+
+@pytest.mark.parametrize(
+    "malformed_code",
+    [None, 17, ["submission_outcome_unknown"], {"code": "submission_outcome_unknown"}],
+)
+def test_submission_transport_failure_rejects_nonstring_error_code(
+    adapter: Adapter, malformed_code: object
+) -> None:
+    client, received, upstream = adapter
+    upstream["status"] = 503
+    upstream["json"] = {
+        "error": {
+            "code": malformed_code,
+            "message": "private-provider-token",
+            "details": {"private_provider_diagnostic": "must not escape"},
+        }
+    }
+    response = client.post(
+        "/mcp",
+        headers={
+            "authorization": "Bearer fixture-token",
+            "accept": "application/json, text/event-stream",
+        },
+        json={
+            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
+            "params": {
+                "name": "workstream_submission_create",
+                "arguments": _arguments("submission_create"),
+            },
+        },
+    )
+    result = response.json()["result"]
+    assert result["isError"] is True
+    error = result["structuredContent"]
+    assert error["status"] == 503 and error.get("code") is None
+    assert error["error"] == "workstream_execution_uncertain"
+    assert "private-provider-token" not in response.text
+    assert "must not escape" not in response.text
+    assert len(received) == 1
diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py
index 70406fa87..043faf8d5 100644
--- a/mcp_server/workstream_mcp/http_gateway.py
+++ b/mcp_server/workstream_mcp/http_gateway.py
@@ -2410,6 +2410,8 @@ def _submission_failure(
             if not isinstance(error, dict):
                 return failure
             code = error.get("code")
+            if not isinstance(code, str):
+                return failure
             if failure.status == 503:
                 # Proxy errors cannot authorize reflection of upstream diagnostic text.
                 recovery = {

From 9fad17a045db3a8054d2896b05f4363e9b0371fc Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:06:01 +0100
Subject: [PATCH 460/513] Record the hosted contributor ZIP journey and paired
 replay

---
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     | 25 ++++++-----
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 42 ++++++++++++++++++-
 deploy/hosted/README.md                       | 15 +++++++
 docs/roadmap_status.md                        |  6 +--
 4 files changed, 72 insertions(+), 16 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index 7bc8a0542..8a1c2e2ac 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -25,8 +25,10 @@ Current finish list, in execution order:
   dedicated Celery workers with the approved operational profiles.
 - [ ] Finish essential native isolation, bounded failure and cleanup proof for
   the existing runner; fix only observed defects needed for this deployment.
-- [ ] Prove the hosted contributor journey, actionable failure/retry feedback,
-  retained ZIP custody and actual S3 cleanup; verify supported upload bounds.
+- [x] Prove the hosted contributor ZIP journey through PRE rejection, pending
+  status, POST revision, same-assignment MCP correction and unpaid acceptance.
+- [ ] Finish hosted failure recovery, the required-review branch, retained ZIP
+  custody, age-eligible S3 cleanup and supported upload bounds.
 - [ ] Run required final-head checks, resolve actual failures, and present PR708
   for explicit merge approval. Merge and post-merge smoke require that approval.
 - [ ] Complete post-deployment/merge verification and hand over the release.
@@ -81,8 +83,8 @@ work. Existing reward owners remain authoritative.
 - [ ] Quality-feedback email uses the stable assignment ID for POST revision requests and revision-limit rejection, with a dedicated consumer and no infrastructure-failure notifications; qualify delivery after sender DNS verification and private key configuration.
 
 The checked items have focused contract/PostgreSQL proof and the maintained
-connected CLI/MCP journey described above. Hosted deployment is active, and its
-contributor submission qualification remains open.
+connected CLI/MCP journey described above. The deployed core contributor
+journey and paired replay passed. Remaining hosted qualification is listed below.
 The dedicated queue topology and isolated scanner-to-T5 regression are integrated.
 PR722 removes the retired experimental native harness, including branch-only
 extensions. Its receipts remain historical; current native qualification must
@@ -156,7 +158,7 @@ journey. The remaining cleanup and verification requirements below still apply.
 
 | Order | Required outcome | Concrete finishing evidence |
 | --- | --- | --- |
-| 1 | Reproduce the connected proof on the deployed API | The maintained paired journey at `73d81da66` passes real PRE/T5/POST, same-assignment correction, automatic acceptance, exact ZIP/Contribution export, rejection, replay and default review_pending with an isolated real identity provider, local API and separate AWS runner. The hosted API and consumers are active at `2942dd4e7`; reproduce the contributor journey on that release. |
+| 1 | Verify the contributor flow on the deployed API | The hosted release `2942dd4e7` passed the core contributor ZIP journey and paired CLI/MCP replay. The required-review branch, scoped failure recovery and remaining custody checks still need hosted evidence. |
 | 2 | Finish affected qualification callers | Preparation API/materialization and the admission-only TASK writer are removed. PR722 retires the experimental harness; the maintained native CLI/MCP journey passes; complete its remaining fault proof through the same owners using raw ZIP acceptance and dedicated finalization. Do not restore the old harness. |
 | 3 | Complete separate-runner integration and runtime/provider/resource qualification | The hosted app uses the authenticated separate runner. Finish Smol one-session/isolation, bounded failure/cleanup and timing measurements on that runner. Verify supported input bounds and applicable AWS exact-version/uncertain multipart behavior through the deployed path. |
 | 4 | Execute final full-system verification and close the acceptance matrix | Full backend lanes, CLI/MCP contracts and CI at the final head; each current-scope acceptance row linked to an executed, scope-matching result, with user-deferred scalability explicitly excluded. Fix actual failures without weakening requirements. |
@@ -167,8 +169,9 @@ real PRE/T4/T5/POST, exact source and Contribution/export custody, PRE/POST
 rejection and default review_pending; owned database/bucket cleanup passed.
 Live AWS source qualification passed at 074cade5e with the actual restricted
 runtime/cleanup identities, pinned versions, lost acknowledgements and exact
-cleanup. The hosted cutover is complete. The deployed contributor journey,
-native fault/isolation/capacity and full-head qualification remain open. Ordinary
+cleanup. The hosted cutover and core contributor journey passed. Native
+fault/isolation, supported upload bounds, aged hosted cleanup, the hosted
+required-review branch and full-head qualification remain open. Ordinary
 indexed unsealed cleanup is implemented; optional absent-operation inventory is
 not a new prerequisite. Known uncertain writes stay owned and charged until
 settled. Do not repeat completed local proofs instead of closing these gaps.
@@ -194,7 +197,7 @@ This is the final qualification queue, not a claim that all listed code is absen
 
 | IDs | Existing implementation/focused evidence | Required closure |
 | --- | --- | --- |
-| A01–A03 | Current paired CLI/MCP journey at `73d81da66` with real isolated Keycloak, separate-runner PRE and POST, T4/T5 and exact source checks | Reconcile each requirement and reproduce on the deployed release. |
+| A01–A03 | Hosted `2942dd4e7` passed PRE rejection, T4/T5, POST revision and same-assignment correction through CLI/MCP; paired replay passed. | Reconcile any remaining scope in the exact acceptance rows. |
 | A04–A08 | Metadata/body replay, competing custody, interruption and T4 uncertainty tests | Reconcile exact cases and execute integrated final-head failure/retry matrix. |
 | A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Redis publication outage and Celery child-redelivery proofs passed; reconcile the remaining exact cases at the final head. |
 | A14–A18 | Cleanup lock/retention/charge owners, Local/MinIO tests and live AWS exact-version/lost-ack cleanup with retained-source survival | Production worker sweeps and exact acceptance-case reconciliation. |
@@ -202,7 +205,7 @@ This is the final qualification queue, not a claim that all listed code is absen
 | A24–A27, A29 | Source/result/fence contracts and dedicated queue tests | Essential native isolation/failure/cleanup and single-runner queue correctness remain; broad saturation/load qualification is user-deferred. |
 | A30 | Managed-style public source acceptance/T5/replay and four typed cases passed at `2f7d8d95c` | Substitution proof complete in its stated scope; no paid-provider integration is selected or required. |
 | A28 | Multi-replica/multi-runner implementation and focused tests | User-deferred until after existing deployment delivery; no second instance is required now. Not claimed passed. |
-| A31–A32 | V14 proves real POST automatic acceptance, exact Contribution/export and default review_pending; focused tests cover applicable awards/replay | Deployed release and final downstream tests. Keep default review_pending guards; live human review remains explicitly deferred by the user. |
+| A31–A32 | Hosted corrected version 2 reached automatic acceptance with one unpaid contribution, zero Reviews and zero awards. The maintained isolated journey proves default review_pending. | Finish the hosted required-review guard and applicable downstream checks. Live human review remains deferred. |
 | A33–A35 | Retained migrations, cardinality guards and API/CLI/MCP cutover | The hosted schema migrated from 0069 to 0093 with retained counts verified. Finish connected client contract and qualification evidence on the deployed release. |
 
 ## Configuration and external evidence
@@ -226,11 +229,11 @@ Existing implementation/focused proof is not the same as deployed proof.
 
 | Delivery gate | Type of remaining work | Concrete closure |
 | --- | --- | --- |
-| Contributor reads and revision terms (A13, A32, A35; PR708 addition) | Connected execution remains. | The preclaim-guide and pending assignment checks are integrated. Verify authorization, history and deadline cases with the current ZIP owner, and reconcile applicable reward-changing revision evidence with existing reward owners/tests. The passing paired run proves unpaid acceptance. |
+| Contributor reads and revision terms (A13, A32, A35; PR708 addition) | Core hosted reads passed. | The contributor verified preclaim originals and the exact pending, revision and accepted assignment through the paired clients. Reconcile the remaining authorization, full history and applicable reward-changing cases through current owners. |
 | Native failure and isolation (A24–A27) | Test execution and fixes only for demonstrated defects. | Execute the reviewed deadline/isolation fixture and reconcile OOM/crash/output and uncertain-destroy requirements with matching maintained evidence. Valid accepted input must continue when destroy is uncertain, with capacity held. Fixture build alone closes none of these native outcomes. |
 | Upload/retention limits (A14–A23) | Remaining deployed/provider verification. | Supported maximum/slow upload and framing/resource bounds pass; actual cleanup worker deletes only eligible exact versions and preserves accepted/retained sources. Retain already-passing AWS adapter evidence rather than repeating unrelated IAM setup. |
 | Hosted cutover (section 20, A33–A35) | **Deployment complete.** | The drained backup and 0069-to-0093 migration retained all 132 existing table counts. The repaired `2942dd4e7` API, coupled MCP and seven dedicated Celery workers are active. The installed boot unit points to the repaired source. See the [cutover evidence](WS-SUBMIT-001-01.md#hosted-schema-and-release-cutover-completed). |
-| Hosted end-to-end and recovery (A01–A18, A29 single-runner, A31–A32) | Connected production-path verification. | PRE reject/correct, accepted T4/T5, POST revision/correct, exact assignment history and acceptance/contribution, replay, infrastructure distinction, required-review guard, queue independence and bounded worker recovery on the deployed stack. |
+| Hosted end-to-end and recovery (A01–A18, A29 single-runner, A31–A32) | Core journey and paired replay passed. | PRE rejection, pending and revision under one assignment, MCP correction, exact replay and unpaid acceptance passed. Finish hosted failure distinction and recovery, retained-source checks, required-review guard and scoped queue independence. See the [hosted journey evidence](WS-SUBMIT-001-01.md#hosted-contributor-zip-journey-and-paired-replay-passed). |
 | Release checks and handoff | Final verification/review. | Required final-head backend/CLI/MCP/migration/security checks and actual review findings resolved; PR708 presented for explicit merge approval; post-merge/deployment smoke and accurate operational handoff. No new PR or automatic merge. |
 
 Email delivery is a separate user-deferred external setup item: notification code
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 5b6aa31db..dcfe85006 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12870,5 +12870,43 @@ socket-parent descriptor in its same-process test configuration after dropping
 the listener. That descriptor kept the exclusive lock, unlike a fresh process.
 The test releases this retained descriptor before simulating restart, preserving
 the real lock and custody checks. The exact test passes. These repairs concern
-the old-head CI run; the new-head workflow and hosted public journey must still
-finish before any full release claim.
+the old-head CI run; the new-head workflow must still finish before any full
+release claim.
+
+### Hosted contributor ZIP journey and paired replay passed
+
+This update records the completed contributor path and the existing review
+lifecycle prerequisite. The hosted runtime remains `2942dd4e7` at schema 0093.
+The installed CLI uses `da4912fea` and the raw-ZIP submission contract.
+
+The hosted sequence activated the provider-free guide, released its task and
+verified the approved originals before contributor claim. The first contributor
+ZIP returned HTTP 422 with `pre_submission_checker_failed` in 83.724 seconds of
+CLI elapsed time and created no Submission. A valid source produced a T4
+receipt and T5 finalized submission version 1. The assignment-only read showed
+`evaluation_pending` and identified that exact submission and intake operation.
+POST requested revision with a deadline on the same assignment.
+
+The contributor submitted the corrected ZIP through installed MCP. The exact
+CLI replay returned the same accepted receipt. Version 2 reached automatic
+acceptance on the original assignment with one unpaid submitter contribution,
+zero Reviews and zero awards. The paired replay matched the original PRE
+rejection and corrected acceptance through MCP and matched the exact CLI and
+MCP assignment status. The private evidence is under
+`/tmp/workstream-hosted-journey-2942`, including the `guide`, `release`,
+`contributor-claim`, `contributor-pre`, `contributor-revision`,
+`contributor-observe-corrected` and `contributor-paired-replay` result receipts
+and `observed-evaluation-pending.json`.
+
+The acceptance controller began at `disabled` generation 0. The persisted
+Operator used `scripts/transition_review_lifecycle.py` in the deployed API
+container to move it through `shadow` generation 1 and `live` generation 2.
+`acceptance-controller-activation.json` records both committed transitions.
+Queued completion then reached acknowledgement on normal delivery attempt 5
+and committed acceptance through its owner. The controller and completion
+used their existing authorized operations.
+
+The hosted required-review branch still needs a matching receipt. Maximum
+upload, native failure/isolation and age-eligible exact S3 deletion through the
+cleanup consumer remain open, along with the applicable final-head checks.
+Feedback email remains disabled pending sender and key configuration.
diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md
index 6fef38f89..afe84613d 100644
--- a/deploy/hosted/README.md
+++ b/deploy/hosted/README.md
@@ -267,6 +267,21 @@ Use a stable deployment subject and keep the original key for retries. The
 cleanup startup check requires the active service actor and identity link. The
 S3 deletion credential supplies storage access separately.
 
+For automatic acceptance under a locked policy with `human_review_required=false`,
+activate the review lifecycle before exercising submission. From the authorized
+app host, run the maintained controller command in the API container with the
+profile ID of a current system Operator.
+
+```sh
+docker exec workstream-api-1 /usr/local/bin/workstream-release-entrypoint \
+  python scripts/transition_review_lifecycle.py \
+  --actor-profile-id OPERATOR_PROFILE_UUID --phase live \
+  --reason "Activate governed automatic acceptance for the reviewed release"
+```
+
+The controller verifies the Operator grant and records each transition through
+`shadow` to `live`. Running it again at `live` leaves the generation unchanged.
+
 Follow [S3 credential setup](../../docs/operations_aws_s3_credentials.md) for
 restricted policies and rotation. Qualification verifies real conditional
 upload/readback and denied destructive access before cutover. There are no
diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md
index d82d55e71..a79a48f35 100644
--- a/docs/roadmap_status.md
+++ b/docs/roadmap_status.md
@@ -701,9 +701,9 @@ cannot be reused as post-submission review-gate evidence. See the
 | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent |
 | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS |
 | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate |
-| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | The maintained CLI/MCP journey with real isolated Keycloak, the separate native runner and dedicated Celery workers proves shared PRE feedback, POST revision, same-assignment correction, replay, retained history and unpaid final acceptance. The schema 0093 hosted release is active. Hosted contributor submission, exact cleanup, essential single-runner failure/isolation and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing. See the [submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md). |
-| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | The local API/separate AWS runner journey and live AWS source/cleanup drill pass. The hosted API and dedicated consumers are active. Verify hosted intake, supported uploads and essential native failure/isolation on that release. Multi-replica/multi-runner scalability qualification is user-deferred until after delivery. |
-| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | The connected native CLI/MCP journey and scoped AWS exact-version qualification pass. The dedicated finalizer is deployed. Verify hosted T4/T5 and exact retained source custody and close the applicable acceptance matrix. Live human review remains deferred. |
+| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | The hosted CLI/MCP journey passed preclaim guide reads, PRE rejection, pending assignment status, POST revision, same-assignment MCP correction, paired replay and unpaid final acceptance. The hosted required-review branch, exact cleanup, essential single-runner failure/isolation and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing. See the [hosted submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md#hosted-contributor-zip-journey-and-paired-replay-passed). |
+| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | Hosted intake returned actionable PRE rejection without creating a Submission and retained the accepted T4 receipts for valid sources. Verify supported upload bounds and essential native failure/isolation on the deployed runner. Multi-replica/multi-runner scalability qualification is user-deferred until after delivery. |
+| Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Hosted T4/T5 produced two immutable submission versions for the same assignment. Pending and corrected acceptance reads retained their exact operation and submission identities. Verify remaining exact retained-source custody and cleanup and close the applicable acceptance matrix. Live human review remains deferred. |
 | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. Earlier local API/Celery evidence covered both policy branches, prefork recovery and later authority revocation. Current connected qualification uses real isolated Keycloak and the exact separate-runner profile; hosted identity qualification remains separate | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate |
 | Operator uncertain-delivery CLI | **Existing public delivery routes consumed by explicit CLI commands** | WS-CLI-001-40 adds one project-bound page of finalized UNKNOWN deliveries and a deliberate reasoned, UUID-keyed reconciliation of one exact event. Fresh backend authority and classification remain decisive; a page never authorizes a later write. | Native signed PostgreSQL proof is scoped to an owner-produced source; a hosted interruption and deployed CLI remain unproven |
 | Review queue and lease | **Hidden persistence foundation** | Queue/admission idempotency and ReviewLease/preference persistence; complete unavailable REV action/principal catalogue and typed AUTH contracts; ART-07A1 metadata-only packet contract and REV-03B immutable normalized packet persistence with live ingest custody; REV-04A Review/finding/resolution and completed request storage | Future resolver proof; canonical admission from `allow_review`; claim/lease/packet authority; lease copies the Submission-stamped policy version with no CON lookup |

From fca69068c886caf32cfbe21bfe9247b7afbbf57e Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:26:22 +0100
Subject: [PATCH 461/513] Clear hosted preflight lint and document current
 worker bounds

---
 backend/app/adapters/artifacts/source_cleanup_worker.py         | 1 +
 backend/app/api/routes/artifact_submissions.py                  | 1 +
 backend/app/api/submission_intake.py                            | 1 +
 backend/app/modules/artifacts/api/submission_cleanup.py         | 2 ++
 backend/app/workers/outbox.py                                   | 1 +
 backend/app/workers/outbox_topology.py                          | 1 +
 backend/app/workers/source_cleanup_topology.py                  | 1 +
 .../checkers/execution/test_delivery_reconciliation_public.py   | 1 -
 8 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/backend/app/adapters/artifacts/source_cleanup_worker.py b/backend/app/adapters/artifacts/source_cleanup_worker.py
index c42b2a5e3..43199c4d7 100644
--- a/backend/app/adapters/artifacts/source_cleanup_worker.py
+++ b/backend/app/adapters/artifacts/source_cleanup_worker.py
@@ -19,6 +19,7 @@
 
 
 def _configuration(settings):
+    """Bind the cleanup profile to the configured artifact namespace claim."""
     profile = SubmissionSourceCleanupProfile.model_validate(settings.submission_source_cleanup_profile)
     bootstrap = create_artifact_store_bootstrap(settings)
     try:
diff --git a/backend/app/api/routes/artifact_submissions.py b/backend/app/api/routes/artifact_submissions.py
index c8c1a3928..72c0b4268 100644
--- a/backend/app/api/routes/artifact_submissions.py
+++ b/backend/app/api/routes/artifact_submissions.py
@@ -49,6 +49,7 @@
 
 
 def _failure_status(code: str) -> int:
+    """Map a closed submission failure code to its public HTTP status."""
     if code == "submission_unavailable":
         return 404
     if code == "submission_archive_limit_exceeded":
diff --git a/backend/app/api/submission_intake.py b/backend/app/api/submission_intake.py
index 3920e0b75..a21331135 100644
--- a/backend/app/api/submission_intake.py
+++ b/backend/app/api/submission_intake.py
@@ -28,6 +28,7 @@ class SubmissionIntakeHeaders:
 
 
 def _reject(code: str, status_code: int, message: str) -> NoReturn:
+    """Raise a structured public intake error without reading request bytes."""
     raise StructuredHTTPException(status_code=status_code, detail=message,
                                   error_code=code, error_message=message)
 
diff --git a/backend/app/modules/artifacts/api/submission_cleanup.py b/backend/app/modules/artifacts/api/submission_cleanup.py
index 6a4e4b075..585cb8f98 100644
--- a/backend/app/modules/artifacts/api/submission_cleanup.py
+++ b/backend/app/modules/artifacts/api/submission_cleanup.py
@@ -41,6 +41,7 @@ class UnsealedSubmissionSource(BaseModel):
 
     @model_validator(mode="after")
     def receipt_shape(self):
+        """Require complete handle and EOF custody for unfinished writes."""
         if self.upload_fence is None and (self.provider_upload_id is not None or self.raw_sha256 is not None):
             raise ValueError("unsealed source requires initiation custody")
         if (self.raw_sha256 is None) != (self.raw_byte_count is None):
@@ -165,6 +166,7 @@ class SubmissionSourceCleanupProfile(BaseModel):
 
     @model_validator(mode="after")
     def ordered_bounds(self):
+        """Keep each cleanup claim within the bounded sweep lifetime."""
         if self.lease_seconds > self.run_seconds:
             raise ValueError("cleanup lease exceeds sweep execution envelope")
         return self
diff --git a/backend/app/workers/outbox.py b/backend/app/workers/outbox.py
index a762d13c8..a041af7e1 100644
--- a/backend/app/workers/outbox.py
+++ b/backend/app/workers/outbox.py
@@ -59,6 +59,7 @@ def send_submission_feedback_email(self, event_id, project_id):
 
 
 def _run_delivery(self, event_id, project_id, *, queue, group):
+    """Deliver an event only from its validated dedicated worker queue."""
     require_outbox_worker(self, queue=queue)
     try:
         event, project, task = _uuid(event_id), _uuid(project_id), _uuid(self.request.id)
diff --git a/backend/app/workers/outbox_topology.py b/backend/app/workers/outbox_topology.py
index 0afd5e948..78bfa2626 100644
--- a/backend/app/workers/outbox_topology.py
+++ b/backend/app/workers/outbox_topology.py
@@ -79,6 +79,7 @@ def is_feedback_email_worker_process() -> bool:
 
 
 def _is_validated_child(queue: str) -> bool:
+    """Match the requested queue and the live validated worker parent."""
     return _validated_queue == queue and _validated_parent is not None and os.getppid() == _validated_parent
 
 
diff --git a/backend/app/workers/source_cleanup_topology.py b/backend/app/workers/source_cleanup_topology.py
index 36da0a55e..3f61969a1 100644
--- a/backend/app/workers/source_cleanup_topology.py
+++ b/backend/app/workers/source_cleanup_topology.py
@@ -69,6 +69,7 @@ def validate_source_cleanup_worker(sender, **_kwargs):
 
 
 def is_source_cleanup_worker_process():
+    """Recognize only a child of the source cleanup startup validator."""
     return _validated_parent is not None and os.getppid() == _validated_parent
 
 
diff --git a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
index 6c1ceaf2a..29b3eec30 100644
--- a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
+++ b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
@@ -1,7 +1,6 @@
 """Public PostgreSQL proof for one-shot uncertain post-submit delivery recovery."""
 
 import asyncio
-import json
 from pathlib import Path
 from tempfile import TemporaryDirectory
 from uuid import UUID

From 78667ccc47b50087e5c31ea469c145a2006d4332 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:33:20 +0100
Subject: [PATCH 462/513] Record native PRE deadline and isolation proof with
 restored admission

---
 .commitrail/INDEX.md                          |  2 +-
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     | 21 +++++----
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 44 +++++++++++++++++++
 docs/roadmap_status.md                        | 19 +++++---
 4 files changed, 69 insertions(+), 17 deletions(-)

diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md
index 7ae33d27e..00860ee5b 100644
--- a/.commitrail/INDEX.md
+++ b/.commitrail/INDEX.md
@@ -6,7 +6,7 @@ for current product capability.
 
 | Initiative | Durable disposition | Next usable boundary |
 |---|---|---|
-| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP API/CLI/MCP, PRE/T4/T5, indexed cleanup and POST policy routing are implemented; superseded writers are retired and real Redis/Celery child recovery is proved. The local API/separate AWS runner journey and live AWS source cleanup are proved. Next: qualified AWS admission activation, remaining runtime/resource qualification, hosted activation and full acceptance/configuration closure. Live human review remains deferred. See the overview for checked implementation versus remaining evidence. |
+| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP API/CLI/MCP and dedicated workers are deployed. The hosted contributor journey proves PRE rejection, POST revision, same-assignment correction and unpaid acceptance; the separate Smol deadline/isolation fixture and current MCP replay pass. Next: remaining native faults, supported input/project-limit proof, age-eligible cleanup-worker deletion, hosted required-review guard and final release checks. Scalability and live human review remain deferred. |
 | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. |
 | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. |
 | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. |
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index 8a1c2e2ac..f616d67dc 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -23,8 +23,10 @@ Current finish list, in execution order:
 - [x] Integrate the reviewed preclaim-guide and pending-status assertions.
 - [x] Back up retained data, migrate and activate the hosted API, MCP and
   dedicated Celery workers with the approved operational profiles.
-- [ ] Finish essential native isolation, bounded failure and cleanup proof for
-  the existing runner; fix only observed defects needed for this deployment.
+- [x] Prove the native project PRE deadline and isolation fixture, fresh-VM retry
+  to acceptance, test cleanup and restoration of normal runner admission.
+- [ ] Reconcile the remaining native fault and uncertain-destroy cases for the
+  existing runner; fix only observed defects needed for this deployment.
 - [x] Prove the hosted contributor ZIP journey through PRE rejection, pending
   status, POST revision, same-assignment MCP correction and unpaid acceptance.
 - [ ] Finish hosted failure recovery, the required-review branch, retained ZIP
@@ -74,9 +76,9 @@ work. Existing reward owners remain authoritative.
 
 - [x] Four required submission inputs and optional feedback; backend-selected revision context and exact actor-scoped replay.
 - [x] Forward migration preserves historical accepted commands and refuses unsafe old in-flight work before mutation.
-- [ ] Approved project and governing task guides are readable/downloadable before claim under exact contributor authority.
+- [x] Approved project and governing task guides are readable/downloadable before claim under exact contributor authority; hosted originals were verified before claim.
 - [x] Assignment-ID status exposes rejected intake feedback, revision terms and accepted evidence in the connected journey without internal-ID discovery.
-- [ ] Qualify live pending processing through assignment status; the connected journey observed it through operation progress.
+- [x] Qualify live pending processing through assignment status; the hosted journey observed the exact assignment in evaluation_pending.
 - [x] CLI/MCP use the same contract, preserve useful PRE findings and document their distinct upload limits.
 - [x] Maintained CLI baseline at `c715dbd47`: real remote PRE rejection, acceptance/replay, T5, automatic POST acceptance, incorrect POST revision, unpaid contribution custody and default review_pending; schema0093 test cleanup passed.
 - [x] Combined CLI/MCP journey at `73d81da66` proves actionable PRE/POST feedback, same-assignment correction, replay, retained versions and exact unpaid acceptance/contribution through real isolated Keycloak and the remote runner.
@@ -89,8 +91,9 @@ The dedicated queue topology and isolated scanner-to-T5 regression are integrate
 PR722 removes the retired experimental native harness, including branch-only
 extensions. Its receipts remain historical; current native qualification must
 use maintained client/runtime owners and the current authentication boundary.
-The connected real-provider journey now passes; native fault/capacity and deployed
-qualification remain open. The managed-style adapter substitution passed through public
+The connected real-provider and hosted contributor journeys pass. The native
+project-deadline/isolation fixture also passes; remaining native faults, cleanup
+and supported-input qualification remain open. The managed-style adapter substitution passed through public
 ZIP acceptance, retained source custody, real T5 owner delivery and replay;
 it does not establish a deployed managed provider or broker-consumer proof.
 
@@ -202,7 +205,7 @@ This is the final qualification queue, not a claim that all listed code is absen
 | A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Redis publication outage and Celery child-redelivery proofs passed; reconcile the remaining exact cases at the final head. |
 | A14–A18 | Cleanup lock/retention/charge owners, Local/MinIO tests and live AWS exact-version/lost-ack cleanup with retained-source survival | Production worker sweeps and exact acceptance-case reconciliation. |
 | A19–A23 | Streaming/framing, safe archives, semantic identity and findings tests; local A19 496 MiB slow-provider memory/backpressure drill | Full permitted maxima and safety matrix, native/deployment scope where required. |
-| A24–A27, A29 | Source/result/fence contracts and dedicated queue tests | Essential native isolation/failure/cleanup and single-runner queue correctness remain; broad saturation/load qualification is user-deferred. |
+| A24–A27, A29 | Source/result/fence contracts, dedicated queue tests and the real Smol project-deadline/isolation fixture passed | Reconcile remaining OOM/crash/output, uncertain-destroy and single-runner queue cases; broad saturation/load qualification is user-deferred. |
 | A30 | Managed-style public source acceptance/T5/replay and four typed cases passed at `2f7d8d95c` | Substitution proof complete in its stated scope; no paid-provider integration is selected or required. |
 | A28 | Multi-replica/multi-runner implementation and focused tests | User-deferred until after existing deployment delivery; no second instance is required now. Not claimed passed. |
 | A31–A32 | Hosted corrected version 2 reached automatic acceptance with one unpaid contribution, zero Reviews and zero awards. The maintained isolated journey proves default review_pending. | Finish the hosted required-review guard and applicable downstream checks. Live human review remains deferred. |
@@ -230,8 +233,8 @@ Existing implementation/focused proof is not the same as deployed proof.
 | Delivery gate | Type of remaining work | Concrete closure |
 | --- | --- | --- |
 | Contributor reads and revision terms (A13, A32, A35; PR708 addition) | Core hosted reads passed. | The contributor verified preclaim originals and the exact pending, revision and accepted assignment through the paired clients. Reconcile the remaining authorization, full history and applicable reward-changing cases through current owners. |
-| Native failure and isolation (A24–A27) | Test execution and fixes only for demonstrated defects. | Execute the reviewed deadline/isolation fixture and reconcile OOM/crash/output and uncertain-destroy requirements with matching maintained evidence. Valid accepted input must continue when destroy is uncertain, with capacity held. Fixture build alone closes none of these native outcomes. |
-| Upload/retention limits (A14–A23) | Remaining deployed/provider verification. | Supported maximum/slow upload and framing/resource bounds pass; actual cleanup worker deletes only eligible exact versions and preserves accepted/retained sources. Retain already-passing AWS adapter evidence rather than repeating unrelated IAM setup. |
+| Native failure and isolation (A24–A27) | Test execution and fixes only for demonstrated defects. | The maintained deadline/isolation fixture passed at `9fad17a04`, including destroyed VMs and normal admission restoration. Reconcile OOM/crash/output and uncertain-destroy requirements with matching maintained evidence. Valid accepted input must continue when destroy is uncertain, with capacity held. Fixture build alone closes none of these native outcomes. |
+| Upload/retention limits (A14–A23) | Remaining deployed/provider verification. | Prove supported maximum/slow upload and framing/resource bounds, including tighter project archive-limit enforcement; the actual cleanup worker must delete only eligible exact versions and preserve accepted/retained sources. Retain already-passing AWS adapter evidence rather than repeating unrelated IAM setup. |
 | Hosted cutover (section 20, A33–A35) | **Deployment complete.** | The drained backup and 0069-to-0093 migration retained all 132 existing table counts. The repaired `2942dd4e7` API, coupled MCP and seven dedicated Celery workers are active. The installed boot unit points to the repaired source. See the [cutover evidence](WS-SUBMIT-001-01.md#hosted-schema-and-release-cutover-completed). |
 | Hosted end-to-end and recovery (A01–A18, A29 single-runner, A31–A32) | Core journey and paired replay passed. | PRE rejection, pending and revision under one assignment, MCP correction, exact replay and unpaid acceptance passed. Finish hosted failure distinction and recovery, retained-source checks, required-review guard and scoped queue independence. See the [hosted journey evidence](WS-SUBMIT-001-01.md#hosted-contributor-zip-journey-and-paired-replay-passed). |
 | Release checks and handoff | Final verification/review. | Required final-head backend/CLI/MCP/migration/security checks and actual review findings resolved; PR708 presented for explicit merge approval; post-merge/deployment smoke and accurate operational handoff. No new PR or automatic merge. |
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index dcfe85006..c1f623bdd 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12910,3 +12910,47 @@ The hosted required-review branch still needs a matching receipt. Maximum
 upload, native failure/isolation and age-eligible exact S3 deletion through the
 cleanup consumer remain open, along with the applicable final-head checks.
 Feedback email remains disabled pending sender and key configuration.
+
+
+### Native PRE deadline and isolation, and current MCP replay
+
+This documentation-only reconciliation changes the existing submission record,
+overview, initiative index, roadmap and local spreadsheet exports. Runtime code,
+policy, service configuration and retained data are outside its scope. Review
+focus is exact proof scope and the remaining release boundaries; verification
+uses the retained client/trace receipts, documentation checks and export parity.
+
+At source `9fad17a04`, the maintained isolated CLI journey completed 170 CLI
+invocations and all four stages, including `source_first_pre_client_evidence`.
+`pre_qualification.py` verified the client evidence against the real remote Smol
+trace: the selected project's PRE deadline produced exit 125 with the deadline
+flag and destroyed its VM; a fresh key used a different VM with no prior VM
+resources, completed PRE with exit 0, and reached normal POST and unpaid
+acceptance. The failed intake had no downstream Submission or revision penalty.
+The fixture also checked the selected project's input/supervisor/credential
+isolation assertions. This proves the bounded deadline/isolation cases, not
+OOM, guest crash, oversized output, uncertain destroy or upload maxima.
+
+Private evidence is in `/tmp/workstream-native-pre-qualified-21i9dlu1`:
+`evidence/pre-qualification-client.json`, `native-trace.jsonl`, `journey.log`
+and `cleanup.json`. The test used isolated local HMAC authentication,
+PostgreSQL and MinIO with the real separate Smol runner; it is not a replacement
+for the independently completed hosted Flow/AWS contributor journey. Its database
+and bucket cleanup completed. Both temporary runner units stopped with empty
+lease, VM, workspace and cgroup inventories. Authenticated normal placement
+returned the original configuration and epoch with admission enabled; the hosted
+API health route remained healthy. Restore receipts are in
+`/tmp/workstream-pre-qualification-7e566ae2f`.
+
+The hosted MCP image now uses source `9fad17a04`, digest
+`sha256:7f6fd13c1ada0bc6cf527b29f52b669ba41cff991ed40042cf66699fa2df2056`.
+Its 135-tool restart/replacement proof passed, followed by paired replay of the
+original PRE rejection, corrected acceptance and exact assignment status in
+`/tmp/workstream-hosted-journey-2942/mcp9fad-paired-replay/result.json`.
+The API/worker release remains `2942dd4e7`; the MCP replacement preserved those
+containers and the database, Redis and identity containers.
+
+Remaining release proof includes the other required native fault/cleanup cases,
+supported upload bounds and tighter project archive-limit enforcement,
+age-eligible S3 deletion through the cleanup worker, the hosted required-review
+guard and applicable final-head checks. This update does not close those gates.
diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md
index a79a48f35..d38666898 100644
--- a/docs/roadmap_status.md
+++ b/docs/roadmap_status.md
@@ -136,9 +136,13 @@ Scoped PostgreSQL/MinIO, client and real Redis/Celery child-recovery proofs exis
 The connected local API/separate AWS runner journey proves automatic acceptance,
 PRE and POST rejection, exact source/contribution custody and default review_pending.
 Live AWS versioned-source permissions, cleanup and lost-acknowledgement recovery
-are qualified. Remaining native faults, isolation/capacity/maxima, deployed API
-activation and A01–A35/C01–C07 closure remain release gates. Local journey evidence
-does not establish hosted API deployment.
+are qualified. The hosted API/worker release and contributor CLI/MCP journey now
+prove PRE rejection, POST revision, same-assignment correction and unpaid acceptance.
+The separate Smol deadline/isolation fixture passes with normal admission restored.
+Remaining native fault cases, supported uploads and tighter project-limit enforcement,
+age-eligible cleanup-worker deletion, the hosted required-review guard and final
+release checks remain open. Multiple API replicas/runners and broad load campaigns
+are user-deferred; the completed fixture does not qualify them.
 
 ## Product Goal
 
@@ -701,8 +705,8 @@ cannot be reused as post-submission review-gate evidence. See the
 | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent |
 | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS |
 | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate |
-| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Project limits apply. Contributor and manager preparation reads preserve historical evidence. | The hosted CLI/MCP journey passed preclaim guide reads, PRE rejection, pending assignment status, POST revision, same-assignment MCP correction, paired replay and unpaid final acceptance. The hosted required-review branch, exact cleanup, essential single-runner failure/isolation and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing. See the [hosted submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md#hosted-contributor-zip-journey-and-paired-replay-passed). |
-| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | Hosted intake returned actionable PRE rejection without creating a Submission and retained the accepted T4 receipts for valid sources. Verify supported upload bounds and essential native failure/isolation on the deployed runner. Multi-replica/multi-runner scalability qualification is user-deferred until after delivery. |
+| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Tighter project archive-limit enforcement remains under qualification. Contributor and manager preparation reads preserve historical evidence. | The hosted CLI/MCP journey passed preclaim guide reads, PRE rejection, pending assignment status, POST revision, same-assignment MCP correction, paired replay and unpaid final acceptance. The native project-deadline/isolation fixture also passed with VMs destroyed and normal admission restored. The hosted required-review branch, exact cleanup, remaining native fault cases and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing. See the [hosted submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md#hosted-contributor-zip-journey-and-paired-replay-passed). |
+| Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | Hosted intake returned actionable PRE rejection without creating a Submission and retained the accepted T4 receipts for valid sources. The real Smol project-deadline/isolation fixture passed. Verify supported upload/project bounds and the remaining native fault/cleanup cases. Multi-replica/multi-runner scalability qualification is user-deferred until after delivery. |
 | Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Hosted T4/T5 produced two immutable submission versions for the same assignment. Pending and corrected acceptance reads retained their exact operation and submission identities. Verify remaining exact retained-source custody and cleanup and close the applicable acceptance matrix. Live human review remains deferred. |
 | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. Earlier local API/Celery evidence covered both policy branches, prefork recovery and later authority revocation. Current connected qualification uses real isolated Keycloak and the exact separate-runner profile; hosted identity qualification remains separate | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate |
 | Operator uncertain-delivery CLI | **Existing public delivery routes consumed by explicit CLI commands** | WS-CLI-001-40 adds one project-bound page of finalized UNKNOWN deliveries and a deliberate reasoned, UUID-keyed reconciliation of one exact event. Fresh backend authority and classification remain decisive; a page never authorizes a later write. | Native signed PostgreSQL proof is scoped to an owner-produced source; a hosted interruption and deployed CLI remain unproven |
@@ -1579,7 +1583,7 @@ service drill starts from public guide inputs with recorded inference.
 ## Critical Dependency Map
 
 ```text
-Delivered foundations (bounded local journey proven; no deployment claim)
+Delivered foundations (evidence scope stated per capability)
   privacy-bounded API/Celery diagnostics (current export disabled; collector optional)
   digest-only API/Celery/Beat/checker release configuration (hosted proof still required)
   WS-EXEC-001-01 Smol node + existing typed execution adapter + exact-lease recovery
@@ -1587,7 +1591,8 @@ Delivered foundations (bounded local journey proven; no deployment claim)
   WS-SUBMIT-001 raw ZIP -> sealed source -> one PRE -> atomic T4 pending custody
     -> dedicated durable T5 -> immutable Submission/binding -> POST
     -> locked true: review_pending; locked false: shared acceptance + contribution + applicable award
-    -> separate API/runner transport verified; complete native/hosted journey remains required
+    -> hosted CLI/MCP contributor journey + separate Smol deadline/isolation verified
+    -> remaining native faults, upload/project limits and aged cleanup-worker proof
   verified guide originals -> explicit PM assistance OR provider-free uploaded rules
     -> unified compilation -> separate manager pre/post approvals
     -> existing activation guards (human review defaults true; approved false supported)

From 486b408bd4f33d3cc1cbb18e584429b272640155 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:39:28 +0100
Subject: [PATCH 463/513] Enforce the locked project archive limits before
 project PRE

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 36 +++++++++
 .../artifacts/intake/foreground_admission.py  | 18 ++++-
 .../selected_pre_submit_admission.py          | 20 ++++-
 .../modules/checkers/api/default_checker.py   | 30 +++++++-
 .../checkers/api/selected_pre_submit.py       | 29 +++++++-
 .../test_submission_foreground_command.py     | 42 ++++++++++-
 .../test_submission_intake_admission.py       | 34 ++++++++-
 backend/tests/selected_policy_fixtures.py     |  2 +
 backend/tests/test_trusted_intake.py          | 73 +++++++++++++++++++
 external_checkers/intake/worker.py            |  6 +-
 10 files changed, 277 insertions(+), 13 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index c1f623bdd..245ac1dc6 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12954,3 +12954,39 @@ Remaining release proof includes the other required native fault/cleanup cases,
 supported upload bounds and tighter project archive-limit enforcement,
 age-eligible S3 deletion through the cleanup worker, the hosted required-review
 guard and applicable final-head checks. This update does not close those gates.
+
+### Enforce locked project archive limits in source-first intake
+
+The public Task requirements expose the locked project archive limits, but
+source-first intake used deployment limits alone. The bounded change selects
+the approved raw cap during initial ART reservation, carries the expanded
+package, file and entry bounds in the digest-bound default context, and uses
+the same narrowed inspection limits in the trusted PRE worker and server
+manifest validation. Existing runtime resource reservations, selected project
+image, and deployment ceilings keep their identities. Existing accepted
+requests and their canonical evidence remain readable.
+
+Scope includes the ART foreground reservation and locked PRE binding,
+CHECKERS default context and selected input validation, the trusted intake
+worker's PRE branch, and the existing ART and worker regressions. Verify
+compressed refusals before object allocation, expanded refusals before project
+execution, and exact accepted/replay boundaries. The changed trusted worker
+requires a rebuilt and re-pinned PRE root before deployment. Source tests and
+the existing hosted fixture do not qualify that rebuilt root.
+
+The existing trusted-root provisioner is `backend/scripts/checker_trusted_root.py`.
+Build the frozen source with `external_checkers/intake/Dockerfile`, retain its
+approved Docker-save graph and exact linux/amd64 manifest/config, then provision
+new archive, config, bundle and descriptor files under the existing verified
+bounds. Keep the default behavior digest and the selected project image. Stage
+the new content-addressed bundle and matching descriptor, update its native PRE
+profile root digest and recompute that profile's digest. Bind the application
+execution profile and authenticated runner endpoint to those same values.
+The POST intake mode and transport are unchanged. Coordinate the backend and
+PRE root cutover under the existing drain so new qualified requests never reach
+the preceding root. The new root still requires its own native qualification.
+
+The focused trusted-worker suite passed 25 tests, including each exact approved
+limit and plus-one refusal before project execution, and retained protocol and
+source substitution cases. The source changes passed production lint and diff
+checks. Hosted activation and the maximum accepted ZIP remain separate proof.
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index 2b6e6f427..55a9a1395 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -17,6 +17,7 @@
 from app.core.cancellation import await_completion_preserving_cancellation
 from app.core.identifiers import new_record_id
 from app.db.errors import integrity_constraint_name
+from app.interfaces.artifacts import ArtifactLimitExceededError
 from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
 from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakeFailure, SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
 from app.modules.artifacts.api.submission_preparation import public_pre_submission_results
@@ -25,7 +26,9 @@
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
 from app.modules.artifacts.intake.streaming import hash_submission_replay
 from app.modules.artifacts.models import ArtifactStorageNamespace, SubmissionBundleAdmission
-from app.modules.artifacts.selected_pre_submit_admission import bind_selected_pre_submit_admission, build_selected_pre_submit_reservation
+from app.modules.artifacts.selected_pre_submit_admission import (
+    bind_selected_pre_submit_admission, build_selected_pre_submit_reservation, project_submission_archive_limits,
+)
 from app.modules.artifacts.submission_manifest import SubmissionCanonicalPredecessor
 from app.modules.artifacts.service import ArtifactStorageNamespaceSpec
 from app.modules.authorization.api.submission_intake import (
@@ -161,12 +164,18 @@ async def _reserve(self, metadata, actor_id, identity_link_id, key, declared):
             await authority.preflight(selectors)
             if await repository.find_actor_key(actor_id, key) is not None:
                 raise _ExistingKey()
-            await self._validate_context(session, metadata, actor_id)
+            _, project = await self._validate_context(session, metadata, actor_id)
+            caps = project_submission_archive_limits(project)
+            maximum = self._maximum
+            if caps is not None and caps.maximum_archive_size_bytes is not None:
+                maximum = min(maximum, caps.maximum_archive_size_bytes)
+            if declared is not None and declared > maximum:
+                raise ArtifactLimitExceededError("submission exceeds the locked project raw ZIP limit")
             now = await session.scalar(select(func.clock_timestamp()))
             row = await repository.reserve(
                 operation_id=selectors.operation_id, metadata=metadata, actor_id=actor_id,
                 identity_link_id=identity_link_id, idempotency_key=key,
-                maximum_raw_bytes=self._maximum, capacity_limits=self._capacity,
+                maximum_raw_bytes=maximum, capacity_limits=self._capacity,
                 declared_raw_bytes=declared, upload_deadline_at=now + self._upload_duration,
                 lease_expires_at=now + self._lease_duration,
             )
@@ -403,6 +412,7 @@ async def _accept_new(self, session, authority, repository, row, owner,
                 or (predecessor.submission_id if predecessor else None) != lineage.predecessor_submission_id
                 or (predecessor.version if predecessor else None) != lineage.predecessor_submission_version
                 or task.checker_remediation_manifest_id != lineage.checker_remediation_manifest_id
+                or request.default_context.project_archive_limits != project_submission_archive_limits(project)
                 or LockedExternalCheckerPolicies.model_validate_json(project.external_checker_policies.value).pre_submit != request.policy):
             raise IntakeCustodyConflict("intake_acceptance_context_changed")
         terminal = await checkers(session).lock_acceptance(
@@ -517,6 +527,8 @@ async def replay(
                 return original
             code = "submission_operation_in_progress" if original.state in {"receiving", "pre_checking"} else "submission_operation_terminal"
             raise IntakeCustodyConflict(code)
+        if declared_raw_bytes is not None and declared_raw_bytes > original.maximum_raw_bytes:
+            raise IntakeCustodyConflict("submission_idempotency_conflict")
         raw = await hash_submission_replay(
             chunks, maximum_raw_bytes=original.maximum_raw_bytes, declared_raw_bytes=declared_raw_bytes,
             idle_timeout_seconds=idle_timeout_seconds, deadline_at=datetime.now(UTC) + replay_duration,
diff --git a/backend/app/modules/artifacts/selected_pre_submit_admission.py b/backend/app/modules/artifacts/selected_pre_submit_admission.py
index 36acdf27c..4ceac6c7c 100644
--- a/backend/app/modules/artifacts/selected_pre_submit_admission.py
+++ b/backend/app/modules/artifacts/selected_pre_submit_admission.py
@@ -2,17 +2,18 @@
 
 from __future__ import annotations
 
-from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts
-
 from dataclasses import dataclass
+import json
 from uuid import UUID
 
 from app.core.hashing import canonical_json_hash
 from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata, SubmissionIntakePreSourceFacts
+from app.modules.artifacts.selected_pre_submit_source_contracts import ArtifactPreSubmitSourceContracts
 from app.modules.artifacts.submission_manifest import (
     SubmissionCanonicalPredecessor,
 )
 from app.modules.checkers.api.default_checker import (
+    ProjectSubmissionArchiveLimits,
     WorkstreamDefaultContext,
     WorkstreamDefaultPredecessor,
 )
@@ -81,6 +82,19 @@ class SelectedPreSubmitAdmissionContext:
     rules_sha256: str
 
 
+def project_submission_archive_limits(
+    project: ProjectLockedPolicyContextFacts,
+) -> ProjectSubmissionArchiveLimits | None:
+    """Read only archive caps from the validated locked project policy."""
+    policy = json.loads(project.effective_policy.value)
+    caps = {
+        name: policy[name]
+        for name in ProjectSubmissionArchiveLimits.model_fields
+        if policy.get(name) is not None
+    }
+    return ProjectSubmissionArchiveLimits.model_validate(caps) if caps else None
+
+
 def build_selected_pre_submit_reservation(
     *,
     source: SubmissionIntakePreSourceFacts,
@@ -114,6 +128,7 @@ def build_selected_pre_submit_reservation(
         or references.effective_policy_hash != project.effective_policy_hash
         or references.pre_submit_policy_id != project.pre_submit_policy_id
         or references.pre_submit_policy_bundle_hash != project.pre_submit_policy_bundle_hash
+        or selected.default_context.project_archive_limits != project_submission_archive_limits(project)
         or selected.default_context.packet != packet
         or selected.default_context.predecessor_exists != (task.predecessor is not None)
         or selected.default_context.current_predecessor != selected.default_context.predecessor
@@ -257,6 +272,7 @@ def bind_selected_pre_submit_admission(
             current_rules_sha256=rules_sha256,
             predecessor_rules_sha256=predecessor_rules_sha256,
             packet=packet,
+            project_archive_limits=project_submission_archive_limits(project),
         ),
         rules_sha256=rules_sha256,
     )
diff --git a/backend/app/modules/checkers/api/default_checker.py b/backend/app/modules/checkers/api/default_checker.py
index 912dfc87e..cb44417a5 100644
--- a/backend/app/modules/checkers/api/default_checker.py
+++ b/backend/app/modules/checkers/api/default_checker.py
@@ -120,6 +120,23 @@ def __post_init__(self) -> None:
         _require_sha256(self.semantic_manifest_sha256)
 
 
+class ProjectSubmissionArchiveLimits(BaseModel):
+    """Approved project caps carried in the digest-bound PRE context."""
+
+    model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+    maximum_archive_size_bytes: int | None = Field(default=None, gt=0)
+    maximum_file_size_bytes: int | None = Field(default=None, gt=0)
+    maximum_package_size_bytes: int | None = Field(default=None, gt=0)
+    maximum_archive_entries: int | None = Field(default=None, gt=0)
+
+    @model_validator(mode="after")
+    def require_cap(self) -> Self:
+        if not self.model_dump(exclude_none=True):
+            raise ValueError("project submission archive limits are empty")
+        return self
+
+
 @dataclass(frozen=True, slots=True)
 class WorkstreamDefaultContext:
     """Locked facts known before source inspection; no derived input identity.
@@ -134,6 +151,7 @@ class WorkstreamDefaultContext:
     current_rules_sha256: str
     predecessor_rules_sha256: str | None
     packet: SubmissionPacketView
+    project_archive_limits: ProjectSubmissionArchiveLimits | None = None
 
     def __post_init__(self) -> None:
         """Validate detached rule and predecessor facts before any source read."""
@@ -145,6 +163,8 @@ def __post_init__(self) -> None:
                 and type(self.current_predecessor) is not WorkstreamDefaultPredecessor)
             or type(self.predecessor_exists) is not bool
             or type(self.packet) is not SubmissionPacketView
+            or (self.project_archive_limits is not None
+                and type(self.project_archive_limits) is not ProjectSubmissionArchiveLimits)
             or (self.predecessor_rules_sha256 is None) != (self.predecessor is None)
         ):
             raise ValueError("default checker context is invalid")
@@ -162,7 +182,7 @@ def predecessor_body(value: WorkstreamDefaultPredecessor | None):
                 "archive_sha256": value.archive_sha256,
                 "semantic_manifest_sha256": value.semantic_manifest_sha256,
             }
-        return {
+        body = {
             "predecessor": predecessor_body(self.predecessor),
             "predecessor_exists": self.predecessor_exists,
             "current_predecessor": predecessor_body(self.current_predecessor),
@@ -170,6 +190,9 @@ def predecessor_body(value: WorkstreamDefaultPredecessor | None):
             "predecessor_rules_sha256": self.predecessor_rules_sha256,
             "packet": self.packet.canonical_body(),
         }
+        if self.project_archive_limits is not None:
+            body["project_archive_limits"] = self.project_archive_limits.model_dump(exclude_none=True)
+        return body
 
     @classmethod
     def from_canonical_body(cls, body: object) -> WorkstreamDefaultContext:
@@ -190,6 +213,10 @@ def predecessor(value):
                 current_rules_sha256=body["current_rules_sha256"],
                 predecessor_rules_sha256=body["predecessor_rules_sha256"],
                 packet=SubmissionPacketView(**body["packet"]),
+                project_archive_limits=(
+                    ProjectSubmissionArchiveLimits.model_validate(body["project_archive_limits"])
+                    if "project_archive_limits" in body else None
+                ),
             )
             if value.canonical_body() != body:
                 raise ValueError("default checker context is not canonical")
@@ -406,6 +433,7 @@ def _failure_matches_check(
     "WORKSTREAM_DEFAULT_CHECK_IDS",
     "WORKSTREAM_DEFAULT_SECRET_SIGNATURES",
     "WORKSTREAM_DEFAULT_WARNING_CODES",
+    "ProjectSubmissionArchiveLimits",
     "WorkstreamDefaultArchiveFailureCode",
     "WorkstreamDefaultCheck",
     "WorkstreamDefaultCheckId",
diff --git a/backend/app/modules/checkers/api/selected_pre_submit.py b/backend/app/modules/checkers/api/selected_pre_submit.py
index 3e83e1c96..76faac2c4 100644
--- a/backend/app/modules/checkers/api/selected_pre_submit.py
+++ b/backend/app/modules/checkers/api/selected_pre_submit.py
@@ -689,6 +689,32 @@ def __post_init__(self) -> None:
             raise ValueError("selected PRE lease facts are invalid")
 
 
+def selected_pre_submit_archive_limits(
+    reservation: SelectedPreSubmitReservationFacts,
+    source_contracts: SelectedPreSubmitSourceContracts,
+) -> SubmissionArchiveLimitsView:
+    """Narrow inspection without changing the qualified runtime profile."""
+    platform = reservation.runtime_profile.archive_limits
+    project = reservation.default_context.project_archive_limits
+    if project is None:
+        return platform
+    expanded = min(
+        platform.maximum_expanded_bytes,
+        project.maximum_package_size_bytes or platform.maximum_expanded_bytes,
+    )
+    return source_contracts.parse_limits(platform.canonical_body() | {
+        "maximum_entries": min(
+            platform.maximum_entries,
+            project.maximum_archive_entries or platform.maximum_entries,
+        ),
+        "maximum_entry_bytes": min(
+            platform.maximum_entry_bytes, expanded,
+            project.maximum_file_size_bytes or platform.maximum_entry_bytes,
+        ),
+        "maximum_expanded_bytes": expanded,
+    })
+
+
 def derive_selected_pre_submit_default_input(
     lease: SelectedPreSubmitLeaseFacts, *, manifest_body: object, manifest_sha256: str,
     source_contracts: SelectedPreSubmitSourceContracts,
@@ -699,7 +725,8 @@ def derive_selected_pre_submit_default_input(
     reservation = lease.reservation
     source = reservation.source
     entries = source_contracts.validate_manifest(
-        manifest_body, sha256=manifest_sha256, limits=reservation.runtime_profile.archive_limits,
+        manifest_body, sha256=manifest_sha256,
+        limits=selected_pre_submit_archive_limits(reservation, source_contracts),
     )
     return reservation.default_context.bind_verified_input(
         archive_sha256=source.raw_sha256, archive_byte_count=source.raw_byte_count,
diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py
index e08a87e46..9153f50ea 100644
--- a/backend/tests/artifacts/test_submission_foreground_command.py
+++ b/backend/tests/artifacts/test_submission_foreground_command.py
@@ -62,7 +62,13 @@ async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admi
     f, key = admission_intake, new_record_id()
     payload = _archive("../escape") if outcome == "rejected" else _archive()
     if framing.startswith("large"):
-        payload = _archive(content=b"finished work\n" * 90_000)
+        from io import BytesIO
+        from zipfile import ZipFile
+        archive = BytesIO()
+        with ZipFile(archive, "w") as output:
+            for path in ("part-one.txt", "part-two.txt"):
+                output.writestr(path, b"finished work\n" * 45_000)
+        payload = archive.getvalue()
         assert 1024 * 1024 < len(payload) < 2 * 1024 * 1024
     def body(split):
         if not split:
@@ -135,6 +141,40 @@ async def chunks():
         assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations WHERE task_id=:id"), {"id": f.task}) == 1
 
 
+@pytest.mark.parametrize("admission_intake", ["project_archive_cap"], indirect=True)
+async def test_public_replay_refuses_changed_length_over_locked_raw_cap(admission_intake, tmp_path, monkeypatch):
+    from tests.test_trusted_intake import _archive
+
+    f = admission_intake
+    payload = _archive()
+    assert len(payload) < 256
+    client, _, errors, calls = await configure_source_http(
+        f.factory, f.access.signed.client, tmp_path, monkeypatch, payload, "completed",
+    )
+    key = str(new_record_id())
+    headers = f.access.target.headers | {
+        "Content-Type": "application/zip",
+        "X-Task-Assignment-Id": str(f.assignment),
+        "Idempotency-Key": key,
+    }
+    path = f"/api/v1/tasks/{f.task}/submissions"
+
+    refused = await client.post(path, headers=headers | {"Idempotency-Key": str(new_record_id())}, content=b"x" * 257)
+    assert refused.status_code == 413, refused.text
+    assert refused.json()["error"]["code"] == "submission_archive_limit_exceeded"
+    assert not calls
+
+    first = await client.post(path, headers=headers, content=payload)
+    assert first.status_code == 202, first.text
+    changed = await client.post(path, headers=headers, content=b"x" * 257)
+    assert changed.status_code == 409, changed.text
+    assert changed.json()["error"]["code"] == "submission_idempotency_conflict"
+    replay = await client.post(path, headers=headers, content=payload)
+    assert replay.status_code == 202, replay.text
+    assert replay.json() == dict(first.json(), replayed=True)
+    assert len(calls) == 1 and not errors
+
+
 async def test_foreground_command_upload_timeout_retains_charge(admission_intake, tmp_path):
     from sqlalchemy import text
     from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
diff --git a/backend/tests/artifacts/test_submission_intake_admission.py b/backend/tests/artifacts/test_submission_intake_admission.py
index f529e0d6b..2722b71e8 100644
--- a/backend/tests/artifacts/test_submission_intake_admission.py
+++ b/backend/tests/artifacts/test_submission_intake_admission.py
@@ -69,11 +69,12 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
     factory = async_sessionmaker(engine, expire_on_commit=False)
     namespace = _namespace(_settings(tmp_path))
     source_store_factory = None
-    automatic_acceptance = getattr(request, "param", None) == "automatic_acceptance"
-    if getattr(request, "param", None) == "minio":
+    variant = getattr(request, "param", None)
+    automatic_acceptance = variant == "automatic_acceptance"
+    if variant == "minio":
         from tests.artifacts.intake_post_support import minio_source_fixture
         namespace, source_store_factory = await minio_source_fixture()
-    if getattr(request, "param", None) == "aws":
+    if variant == "aws":
         from app.interfaces.artifacts import ArtifactStoreNamespaceIdentity, artifact_store_namespace_material
         from workstream_external_services import ExternalServiceAdapterIdentity
         from app.modules.artifacts.service import ArtifactStorageNamespaceSpec
@@ -91,6 +92,7 @@ async def admission_intake(tmp_path, isolated_database_env, admin_access, reques
         plan, _ = await approved_selected_policy_fixture(
             factory, namespace, guide_version="v1",
             human_review_required=not automatic_acceptance,
+            maximum_archive_size_bytes=256 if variant == "project_archive_cap" else None,
             contribution_awards=("money", "project_points") if automatic_acceptance else (),
             pre_submit_registry_spec=pre_registry_spec(),
             post_submit_registry_spec=post_registry_spec(),
@@ -138,6 +140,32 @@ def intake_admission(factory, actor, namespace):
     )
 
 
+@pytest.mark.parametrize("admission_intake", ["project_archive_cap"], indirect=True)
+async def test_t1_enforces_locked_project_raw_archive_cap_before_reservation(admission_intake):
+    from sqlalchemy import text
+    from app.interfaces.artifacts import ArtifactLimitExceededError
+
+    f = admission_intake
+    metadata = SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment)
+    actor = {"actor_id": f.actor.actor_profile_id, "identity_link_id": f.actor.identity_link_id}
+    with pytest.raises(ArtifactLimitExceededError, match="locked project raw ZIP limit"):
+        await f.admission.admit(
+            metadata, **actor, idempotency_key=new_record_id(), declared_raw_bytes=257,
+        )
+    async with f.factory() as session:
+        assert await session.scalar(text("SELECT count(*) FROM submission_intake_operations WHERE task_id=:task"),
+                                    {"task": f.task}) == 0
+    owner = await f.admission.admit(
+        metadata, **actor, idempotency_key=new_record_id(), declared_raw_bytes=None,
+    )
+    async with f.factory() as session:
+        row = (await session.execute(text(
+            "SELECT o.maximum_raw_bytes,c.accounted_bytes FROM submission_intake_operations AS o "
+            "JOIN submission_source_charges AS c ON c.operation_id=o.id WHERE o.id=:operation"
+        ), {"operation": owner.operation_id})).one()
+        assert tuple(row) == (256, 256)
+
+
 async def admit_new(fixture, *, key=None, metadata=None):
     return await fixture.admission.admit(
         metadata or SubmissionIntakeMetadata(task_id=fixture.task, assignment_id=fixture.assignment),
diff --git a/backend/tests/selected_policy_fixtures.py b/backend/tests/selected_policy_fixtures.py
index fa61a3859..bac4e7a06 100644
--- a/backend/tests/selected_policy_fixtures.py
+++ b/backend/tests/selected_policy_fixtures.py
@@ -16,6 +16,7 @@ async def approved_selected_policy_fixture(
     contribution_awards=(),
     human_review_required=True,
     max_revision_rounds=2,
+    maximum_archive_size_bytes=None,
     pre_submit_registry_spec=pre_registry_spec(),
     post_submit_registry_spec=post_registry_spec(),
     post_submit_configuration_setup=None,
@@ -37,6 +38,7 @@ async def approved_selected_policy_fixture(
         artifact_proposal=SubmissionArtifactPolicyProposal(
             maximum_file_size_bytes=1_000_000,
             maximum_package_size_bytes=5_000_000,
+            maximum_archive_size_bytes=maximum_archive_size_bytes,
             required_artifacts=("task.toml",),
             required_evidence=("results",),
             attestation_terms=("rights_confirmed",),
diff --git a/backend/tests/test_trusted_intake.py b/backend/tests/test_trusted_intake.py
index 4df045135..36f686b63 100644
--- a/backend/tests/test_trusted_intake.py
+++ b/backend/tests/test_trusted_intake.py
@@ -30,6 +30,7 @@
 )
 from app.modules.checkers.api.default_checker import (
     WORKSTREAM_DEFAULT_BEHAVIOR_SHA256,
+    ProjectSubmissionArchiveLimits,
     WorkstreamDefaultCheckerInput,
 )
 from app.modules.checkers.api.material import SubmissionMaterialEntry
@@ -580,6 +581,78 @@ def test_pre_worker_default_blocker_never_requests_project(tmp_path, data):
     assert output.read() == b"" and not (tmp_path / "escape").exists()
 
 
+@pytest.mark.parametrize(
+    "cap, boundary",
+    [
+        ("maximum_file_size_bytes", 13),
+        ("maximum_package_size_bytes", 26),
+        ("maximum_archive_entries", 2),
+    ],
+)
+@pytest.mark.parametrize("within", [True, False])
+def test_pre_worker_enforces_locked_project_archive_limits(tmp_path, cap, boundary, within):
+    from app.modules.checkers.api.selected_pre_submit import (
+        SelectedPreSubmitExecutionFacts, SelectedPreSubmitReservationFacts,
+        derive_selected_pre_submit_default_input,
+    )
+
+    archive = BytesIO()
+    with zipfile.ZipFile(archive, "w") as output:
+        for path in ("first.txt", "second.txt"):
+            output.writestr(path, b"finished work")
+    contracts = selected_pre_submit_source_contracts()
+    limits = ProjectSubmissionArchiveLimits.model_validate({cap: boundary if within else boundary - 1})
+
+    def bind(reservation):
+        return replace(
+            reservation, source_contracts=contracts,
+            default_context=replace(reservation.default_context, project_archive_limits=limits),
+        )
+
+    worker, output, project, lease = _pre_worker(
+        tmp_path, archive.getvalue(), reservation_change=bind,
+    )
+    original = lease.reservation
+    decoded = SelectedPreSubmitReservationFacts.from_canonical_body(
+        original.canonical_body(), source_contracts=contracts,
+    )
+    assert decoded.default_context.project_archive_limits == limits
+    assert decoded.runtime_profile == original.runtime_profile
+    assert decoded.request_digest == original.request_digest
+    unbounded = replace(
+        original, source_contracts=contracts,
+        default_context=replace(original.default_context, project_archive_limits=None),
+    )
+    assert unbounded.request_digest != original.request_digest
+
+    worker.run()
+    output.seek(0)
+    message = _read(output)
+    if within:
+        assert message["operation"] == "project"
+        message = _read(output)
+    assert message["operation"] == "completed"
+    assert project.calls == (1 if within else 0)
+    assert output.read() == b""
+    result = SelectedPreSubmitExecutionFacts.from_canonical_body(
+        message["payload"], source_contracts=contracts,
+    )
+    assert result.eligible is within
+    if not within:
+        assert result.manifest_body is None
+        assert result.external_members == ()
+        assert result.workstream_default.checks[0].failure_code == "submission_archive_limit_exceeded"
+        # A manifest that is safe under the unchanged profile alone cannot
+        # authorize the project stage or a forged eligible result.
+        inspection = SubmissionArchiveInspector(original.runtime_profile.archive_limits).inspect(archive)
+        manifest = build_submission_manifest(inspection)
+        with pytest.raises(ValueError, match="manifest exceeds execution limits"):
+            derive_selected_pre_submit_default_input(
+                lease, manifest_body=manifest.as_dict(), manifest_sha256=manifest.sha256,
+                source_contracts=contracts,
+            )
+
+
 @pytest.mark.parametrize("field", ["manifest", "default_input", "prepared_generation_id"])
 def test_pre_worker_refuses_host_derived_inputs(tmp_path, field):
     with pytest.raises(ValueError, match="protocol invalid"):
diff --git a/external_checkers/intake/worker.py b/external_checkers/intake/worker.py
index e5d1b057b..a77968536 100644
--- a/external_checkers/intake/worker.py
+++ b/external_checkers/intake/worker.py
@@ -292,7 +292,7 @@ def _finish(self, default, manifest=None, default_input=None, members=()):
     def run(self):
         from app.modules.checkers.api.selected_pre_submit import (
             ExternalPreSubmitMemberFacts, derive_selected_pre_submit_default_input,
-            derive_selected_pre_submit_input,
+            derive_selected_pre_submit_input, selected_pre_submit_archive_limits,
         )
         from app.modules.checkers.default_checker import evaluate_rejected_archive
         if self._started:
@@ -311,7 +311,9 @@ def run(self):
                 digest.update(chunk)
             if size != source.raw_byte_count or "sha256:" + digest.hexdigest() != source.raw_sha256:
                 raise ValueError("PRE source identity differs")
-            inspector = SubmissionArchiveInspector(reservation.runtime_profile.archive_limits)
+            inspector = SubmissionArchiveInspector(selected_pre_submit_archive_limits(
+                reservation, ArtifactPreSubmitSourceContracts(),
+            ))
             try:
                 inspection = inspector.inspect(archive)
                 manifest = build_submission_manifest(inspection)

From b3bced248e28a6161be9cd2733eb892da6c63a2b Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:49:39 +0100
Subject: [PATCH 464/513] Bind project archive limits in the selected PRE SQL
 guard

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 21 ++++++
 .../versions/0094_project_archive_limits.py   | 71 +++++++++++++++++++
 .../test_submission_intake_custody.py         |  1 +
 .../artifacts/test_submission_pre_source.py   | 26 +++++--
 backend/tests/conftest.py                     |  2 +-
 5 files changed, 116 insertions(+), 5 deletions(-)
 create mode 100644 backend/alembic/versions/0094_project_archive_limits.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 245ac1dc6..2788ecba0 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -12990,3 +12990,24 @@ The focused trusted-worker suite passed 25 tests, including each exact approved
 limit and plus-one refusal before project execution, and retained protocol and
 source substitution cases. The source changes passed production lint and diff
 checks. Hosted activation and the maximum accepted ZIP remain separate proof.
+
+The first PostgreSQL run passed the raw reservation test and exposed the exact
+SQL dependency before any guest invocation. The existing
+`require_selected_pre_source(selected_pre_submit_runs)` function reconstructs
+the canonical default context and rejected the added project facts. Migration
+`0094_project_archive_limits` narrowly extends that function to derive the
+four caps from the exact locked effective-policy row. It refuses active
+receiving or PRE-checking operations while replacing the guard. It rewrites no
+historical rows, and retained accepted operations can continue finalization.
+The schema fingerprint and existing direct SQL source substitution tests must
+match this one function-definition change.
+
+The isolated 0094 catalogue fingerprint is
+`a92907ed73f32d8af6056ee18ef5fca372d7c8629fcd1fd3f730d25b6effd0d3`.
+Reversing only the changed PRE function definition recovers the exact 0093
+fingerprint `3e045ec0e2fe6f0b14b19ea1404f4500b1cde5d440c1a7ddd76d90bab1ffed0b`.
+The isolated resources were cleaned. The guarded raw-ceiling case pairs an
+otherwise valid 100-byte source with a stored 1,024-byte allowance under an
+approved 256-byte compressed cap. The separate missing and widened cases
+reconstruct the supplied digest to exercise the binding rather than a stale
+digest failure.
diff --git a/backend/alembic/versions/0094_project_archive_limits.py b/backend/alembic/versions/0094_project_archive_limits.py
new file mode 100644
index 000000000..b4a517901
--- /dev/null
+++ b/backend/alembic/versions/0094_project_archive_limits.py
@@ -0,0 +1,71 @@
+"""Require approved project archive limits in the source-first PRE SQL guard."""
+
+from alembic import op
+from sqlalchemy import text
+
+revision = "0094_project_archive_limits"
+down_revision = "0093_verified_email_observation"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute(
+        "LOCK TABLE public.submission_intake_operations, public.selected_pre_submit_runs "
+        "IN ACCESS EXCLUSIVE MODE"
+    )
+    op.execute("""
+        DO $$
+        BEGIN
+          IF EXISTS (SELECT 1 FROM public.submission_intake_operations
+                     WHERE state IN ('receiving', 'pre_checking')) THEN
+            RAISE EXCEPTION 'wait for active submission uploads and PRE checks to end before upgrading';
+          END IF;
+        END $$;
+    """)
+    signature = "public.require_selected_pre_source(public.selected_pre_submit_runs)"
+    definition = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))"
+    ), {"signature": signature}).scalar_one()
+    declaration = " rules text; expected_context jsonb; predecessor_id uuid;"
+    comparison = " IF request->'default_context' IS DISTINCT FROM expected_context THEN"
+    if definition.count(declaration) != 1 or definition.count(comparison) != 1:
+        raise RuntimeError("project archive limits predecessor guard changed")
+    definition = definition.replace(
+        declaration, declaration + "\n locked_policy jsonb; project_caps jsonb;",
+    )
+    definition = definition.replace(comparison, """
+ SELECT p.effective_policy::jsonb INTO locked_policy
+ FROM public.effective_project_submission_artifact_policies p
+ WHERE p.id=t.locked_effective_project_submission_artifact_policy_id
+   AND p.effective_policy_hash=t.locked_effective_project_submission_artifact_policy_hash
+   AND p.project_id=r.project_id AND p.guide_version=t.locked_guide_version
+   AND p.source_snapshot_id=t.locked_guide_source_snapshot_id
+   AND p.source_snapshot_hash=t.locked_guide_source_snapshot_hash
+   AND p.lifecycle_status IN ('approved','superseded');
+ IF NOT FOUND OR jsonb_typeof(locked_policy) IS DISTINCT FROM 'object' THEN
+   RAISE EXCEPTION 'selected PRE locked artifact policy mismatch' USING ERRCODE='23514';
+ END IF;
+ SELECT jsonb_object_agg(key,value) INTO project_caps FROM jsonb_each(locked_policy)
+ WHERE key IN ('maximum_archive_size_bytes','maximum_file_size_bytes',
+               'maximum_package_size_bytes','maximum_archive_entries')
+   AND value IS DISTINCT FROM 'null'::jsonb;
+ IF project_caps IS NOT NULL THEN
+   IF EXISTS(SELECT 1 FROM jsonb_each(project_caps)
+             WHERE jsonb_typeof(value) IS DISTINCT FROM 'number'
+                OR value::text !~ '^[1-9][0-9]*$') THEN
+     RAISE EXCEPTION 'selected PRE locked artifact limits invalid' USING ERRCODE='23514';
+   END IF;
+   IF project_caps ? 'maximum_archive_size_bytes'
+      AND o.maximum_raw_bytes>(project_caps->>'maximum_archive_size_bytes')::numeric THEN
+     RAISE EXCEPTION 'selected PRE locked raw archive limit mismatch' USING ERRCODE='23514';
+   END IF;
+   expected_context:=expected_context||jsonb_build_object('project_archive_limits',project_caps);
+ END IF;
+""" + comparison)
+    op.execute(definition)
+
+
+def downgrade() -> None:
+    raise RuntimeError("project archive limits migration is forward-only")
diff --git a/backend/tests/artifacts/test_submission_intake_custody.py b/backend/tests/artifacts/test_submission_intake_custody.py
index 7bbfbde5b..ce410f125 100644
--- a/backend/tests/artifacts/test_submission_intake_custody.py
+++ b/backend/tests/artifacts/test_submission_intake_custody.py
@@ -48,6 +48,7 @@ async def intake(tmp_path, isolated_database_env, capacity_limits, request):
         from tests.checkers.external.support import pre_registry_spec
         plan, _ = await approved_selected_policy_fixture(
             factory, _namespace(_settings(tmp_path)), guide_version="v1",
+            maximum_archive_size_bytes=256 if getattr(request, "param", None) == "project_archive_cap" else None,
             pre_submit_registry_spec=pre_registry_spec(),
         )
         actor = _context()
diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py
index ad34af5b6..b57400316 100644
--- a/backend/tests/artifacts/test_submission_pre_source.py
+++ b/backend/tests/artifacts/test_submission_pre_source.py
@@ -72,6 +72,10 @@ def _substitute_pre_source_request(body, changed, deadline):
         body["pre_deadline_at"] = (deadline + timedelta(seconds=1)).isoformat()
     elif changed == "storage_scheme":
         body["admission_lineage"]["storage_scheme"] = "s3"
+    elif changed == "project_caps_missing":
+        del body["default_context"]["project_archive_limits"]
+    elif changed == "project_caps_widened":
+        body["default_context"]["project_archive_limits"]["maximum_file_size_bytes"] += 1
     elif changed == "rules":
         body["default_context"]["current_rules_sha256"] = "sha256:" + "f" * 64
         body["admission_lineage"]["rules_sha256"] = "sha256:" + "f" * 64
@@ -165,8 +169,17 @@ async def test_pre_source_custody_rejects_substitution_or_stale_owner(intake, ch
             await session.rollback()
 
 
-@pytest.mark.parametrize("intake", [True], indirect=True)
-@pytest.mark.parametrize("changed", [None, "source", "packet", "policy", "post_policy", "fence", "deadline", "actor", "rules", "predecessor", "predecessor_identity", "storage_scheme"])
+@pytest.mark.parametrize(
+    "intake, changed",
+    [
+        pytest.param(True, changed, id=f"{changed}-True") for changed in (
+            None, "source", "packet", "policy", "post_policy", "fence", "deadline",
+            "actor", "rules", "predecessor", "predecessor_identity", "storage_scheme",
+            "project_caps_missing", "project_caps_widened",
+        )
+    ] + [pytest.param("project_archive_cap", "project_raw_cap", id="project_raw_cap")],
+    indirect=["intake"],
+)
 async def test_selected_pre_sql_requires_exact_live_source(intake, changed):
     """Exercise the SQL source participant; not full PRE execution or T4 proof."""
     from app.core.hashing import canonical_json_hash
@@ -241,7 +254,12 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed):
         if changed is None:
             await session.execute(statement, {"value": json.dumps(value)})
         else:
-            with pytest.raises(DBAPIError, match="selected PRE"):
+            expected = {
+                "project_caps_missing": "selected PRE default context mismatch",
+                "project_caps_widened": "selected PRE default context mismatch",
+                "project_raw_cap": "selected PRE locked raw archive limit mismatch",
+            }.get(changed, "selected PRE")
+            with pytest.raises(DBAPIError, match=expected):
                 await session.execute(statement, {"value": json.dumps(value)})
             await session.rollback()
     from app.modules.checkers.models import SelectedPreSubmitRun
@@ -259,7 +277,7 @@ async def test_selected_pre_sql_requires_exact_live_source(intake, changed):
         if changed is None:
             await session.flush()
         else:
-            with pytest.raises(DBAPIError, match="selected PRE"):
+            with pytest.raises(DBAPIError, match=expected):
                 await session.flush()
             await session.rollback()
     if changed is None:
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 1adcedd5c..4ecf4ffe5 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "3e045ec0e2fe6f0b14b19ea1404f4500b1cde5d440c1a7ddd76d90bab1ffed0b"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "a92907ed73f32d8af6056ee18ef5fca372d7c8629fcd1fd3f730d25b6effd0d3"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",

From e5e26fee48aa13eb97931a0d4786a3a2925f7474 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:50:42 +0100
Subject: [PATCH 465/513] Recognize the project archive guard as the current
 schema head

---
 backend/alembic/env.py | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/backend/alembic/env.py b/backend/alembic/env.py
index 37a0f9554..88ff603f9 100644
--- a/backend/alembic/env.py
+++ b/backend/alembic/env.py
@@ -21,7 +21,7 @@
 target_metadata = Base.metadata
 
 _BASELINE_REVISION = "0001_uuid7_v01"
-_CURRENT_HEAD_REVISION = "0093_verified_email_observation"
+_CURRENT_HEAD_REVISION = "0094_project_archive_limits"
 _RECREATE_GUIDANCE = (
     "Workstream v0.1 requires a fresh database; recreate this database before "
     "running the 0001_uuid7_v01 migration"
@@ -148,6 +148,7 @@ def do_run_migrations(connection: Connection) -> None:
             ("0090_merge_direct_storage",),
             ("0091_qualified_aws_source",),
             ("0092_submission_feedback",),
+            ("0093_verified_email_observation",),
             (_CURRENT_HEAD_REVISION,),
         ):
             raise RuntimeError(_RECREATE_GUIDANCE)

From ba58139cb008b09f9969c14a96c9982bd0503dbe Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:54:11 +0100
Subject: [PATCH 466/513] Document canonical cap omission and migration custody

---
 backend/alembic/versions/0094_project_archive_limits.py | 2 ++
 backend/app/modules/checkers/api/default_checker.py     | 1 +
 2 files changed, 3 insertions(+)

diff --git a/backend/alembic/versions/0094_project_archive_limits.py b/backend/alembic/versions/0094_project_archive_limits.py
index b4a517901..f281c96cd 100644
--- a/backend/alembic/versions/0094_project_archive_limits.py
+++ b/backend/alembic/versions/0094_project_archive_limits.py
@@ -10,6 +10,7 @@
 
 
 def upgrade() -> None:
+    """Replace the current PRE guard after excluding active source writers."""
     op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
     op.execute(
         "LOCK TABLE public.submission_intake_operations, public.selected_pre_submit_runs "
@@ -68,4 +69,5 @@ def upgrade() -> None:
 
 
 def downgrade() -> None:
+    """Preserve the canonical context already committed for new requests."""
     raise RuntimeError("project archive limits migration is forward-only")
diff --git a/backend/app/modules/checkers/api/default_checker.py b/backend/app/modules/checkers/api/default_checker.py
index cb44417a5..d1b55785d 100644
--- a/backend/app/modules/checkers/api/default_checker.py
+++ b/backend/app/modules/checkers/api/default_checker.py
@@ -132,6 +132,7 @@ class ProjectSubmissionArchiveLimits(BaseModel):
 
     @model_validator(mode="after")
     def require_cap(self) -> Self:
+        """Represent no configured caps by omission, not an empty object."""
         if not self.model_dump(exclude_none=True):
             raise ValueError("project submission archive limits are empty")
         return self

From d473bab3eabc2f148f5005bfc79d2efc0a12425f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 18:08:41 +0100
Subject: [PATCH 467/513] Pair PRE source clocks after authorization waits

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  25 ++++
 .../selected_pre_submit_execution.py          |   6 +-
 .../artifacts/test_submission_pre_source.py   | 111 ++++++++++++++++++
 3 files changed, 140 insertions(+), 2 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 2788ecba0..9e9148c0f 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13011,3 +13011,28 @@ otherwise valid 100-byte source with a stored 1,024-byte allowance under an
 approved 256-byte compressed cap. The separate missing and widened cases
 reconstruct the supplied digest to exercise the binding rather than a stale
 digest failure.
+
+### Preserve the remaining PRE source-read deadline after authorization
+
+The source-read grant sampled its monotonic start before authorization and locks,
+but paired that start with a later database wall-clock reading. Authorization
+latency was therefore deducted twice, allowing `material_unavailable` before
+the recorded PRE deadline. This bounded repair changes only the source-read
+clock pairing and a deterministic service regression: sample monotonic time
+immediately before the database clock query. Query/commit time remains charged,
+and the absolute stored expiry and every authorization/custody check remain.
+No configured timeout, source identity, policy, SQL guard or runtime changes.
+Security review focuses on not extending the durable expiry; verification must
+show delayed authorization still permits a current read, elapsed commit time
+cannot mint a stale grant, and expiry still refuses additional reads. The
+observed hosted large-source failure is not attributed to this bug without
+matching authorization timing evidence.
+
+The deterministic service regression failed only the delayed-authorization case
+on the preceding code (one failure, two passes), then passed all three cases with
+the clock pairing repaired. It verifies reading at 90 seconds after a 40-second
+authorization delay, refusal at the unchanged 120-second expiry, and refusal to
+issue a grant after an expired commit. This is clock/owner service proof, not a
+new PostgreSQL or native-runtime claim. The hosted failed operation's materialize
+audit occurred about 0.125 seconds after PRE started, so it does not establish
+that this clock defect caused the observed large-input failure.
diff --git a/backend/app/modules/artifacts/selected_pre_submit_execution.py b/backend/app/modules/artifacts/selected_pre_submit_execution.py
index d1c08814a..768a7d27f 100644
--- a/backend/app/modules/artifacts/selected_pre_submit_execution.py
+++ b/backend/app/modules/artifacts/selected_pre_submit_execution.py
@@ -155,7 +155,6 @@ async def issue(
         if checked != lease:
             raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable")
         facts = source_read_facts(lease)
-        started = asyncio.get_running_loop().time()
         grant = None
         try:
             async with self._session.begin():
@@ -171,10 +170,13 @@ async def issue(
                         or live.lease_generation != facts.foreground_lease_generation):
                     raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable")
                 expires_at = min(live.lease_expires_at, lease.lease_expires_at, live.pre_deadline_at)
+                # Pair clocks after authority/lock waits; sample before the query
+                # so its round trip and the following commit cannot extend expiry.
+                sampled_monotonic = asyncio.get_running_loop().time()
                 now = await self._session.scalar(select(func.clock_timestamp()))
                 if now is None or expires_at <= now:
                     raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable")
-                deadline = started + (expires_at - now).total_seconds()
+                deadline = sampled_monotonic + (expires_at - now).total_seconds()
                 await self._authority.consume(prepared_authorization=handle, facts=facts)
             # No grant exists if commit fails, including a lost acknowledgement.
             grant = _PreSubmitSourceGrant._issued(self, lease, expires_at, deadline)
diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py
index b57400316..6d72b5249 100644
--- a/backend/tests/artifacts/test_submission_pre_source.py
+++ b/backend/tests/artifacts/test_submission_pre_source.py
@@ -713,3 +713,114 @@ async def invoke():
                     await invoke()
     finally:
         await engine.dispose()
+
+
+@pytest.mark.parametrize("authorization_delay, commit_delay", [(0, 0), (40, 0), (40, 90)])
+async def test_source_read_deadline_charges_authorization_once(monkeypatch, authorization_delay, commit_delay):
+    """Slow authority must not shorten, or a slow commit extend, the stored expiry."""
+    import asyncio
+    from contextlib import asynccontextmanager
+    from dataclasses import replace
+    from types import SimpleNamespace
+    from app.modules.artifacts import selected_pre_submit_execution as source_reads
+    from app.modules.checkers.api.selected_pre_submit import (
+        SelectedPreSubmitInfrastructureUnavailable, SelectedPreSubmitLeaseFacts,
+    )
+    from tests.checkers.external.test_selected_pre_submit_coordination import _source_reservation
+    start = asyncio.get_running_loop().time()
+    elapsed = [0.0]
+    wall_start = datetime.now(UTC)
+    expires = wall_start + timedelta(seconds=120)
+    request = replace(_source_reservation(), pre_deadline_at=expires,
+                      source_contracts=source_reads.ArtifactPreSubmitSourceContracts())
+    lease = SelectedPreSubmitLeaseFacts(request, new_record_id(), 1, expires)
+    facts = source_reads.source_read_facts(lease)
+
+    class ClockDateTime(datetime):
+        @classmethod
+        def now(cls, tz=None):
+            return wall_start + timedelta(seconds=elapsed[0])
+
+    class ClockAsyncio:
+        def __getattr__(self, name):
+            return getattr(asyncio, name)
+
+        def get_running_loop(self):
+            return SimpleNamespace(time=lambda: start + elapsed[0])
+
+    class Session:
+        active = False
+
+        def in_transaction(self):
+            return self.active
+
+        @asynccontextmanager
+        async def begin(self):
+            self.active = True
+            try:
+                yield
+            finally:
+                elapsed[0] += commit_delay
+                self.active = False
+
+        async def scalar(self, _query):
+            # The database samples between send and receive. Sampling monotonic
+            # before this query conservatively charges its round trip.
+            elapsed[0] += 1
+            observed = wall_start + timedelta(seconds=elapsed[0])
+            elapsed[0] += 1
+            return observed
+
+    session = Session()
+    closed = []
+
+    class Authority:
+        async def prepare(self, **_kwargs):
+            elapsed[0] += authorization_delay
+            return object()
+
+        async def consume(self, **_kwargs):
+            assert session.in_transaction()
+
+        def close(self):
+            closed.append(True)
+
+    class Sources:
+        async def lock_pre_source(self, **_kwargs):
+            return SimpleNamespace(**{
+                name: getattr(facts, name) for name in (
+                    "source", "project_id", "task_id", "assignment_id", "actor_profile_id",
+                    "identity_link_id", "metadata_sha256", "locked_context_sha256", "pre_deadline_at",
+                )
+            }, lease_id=facts.foreground_lease_id, lease_generation=facts.foreground_lease_generation,
+                lease_expires_at=expires)
+
+    observed_reads = []
+
+    class Store:
+        async def open_source(self, source, **_kwargs):
+            assert not session.in_transaction() and source == request.source
+            observed_reads.append(True)
+            yield b"x" * source.raw_byte_count
+
+    monkeypatch.setattr(source_reads, "asyncio", ClockAsyncio())
+    monkeypatch.setattr(source_reads, "datetime", ClockDateTime)
+    reader = source_reads.SelectedPreSubmitSourceReads(
+        session=session, sources=Sources(), authority=Authority(), store=Store(),
+    )
+    capability = SimpleNamespace(consume=lambda **_kwargs: lease)
+    if commit_delay:
+        with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="material_unavailable"):
+            async with reader.issue(lease=lease, execution_authority=capability):
+                pytest.fail("expired commit issued a source grant")
+        assert not observed_reads
+    else:
+        async with reader.issue(lease=lease, execution_authority=capability) as grant:
+            elapsed[0] = 90
+            stream = grant.open_source(lease=lease)
+            assert await anext(stream) == b"x" * request.source.raw_byte_count
+            elapsed[0] = 120
+            with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="material_unavailable"):
+                await anext(stream)
+        assert observed_reads == [True]
+    assert closed == [True]

From 95d935ac516414cf52f21d851df17b54a40570fc Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 17:46:16 +0100
Subject: [PATCH 468/513] Bound remaining native PRE failure qualification
 fixture

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  28 ++
 .../test_journey_pre_qualification.py         | 193 +++++++++++++-
 cli/tests/journey/pre_qualification.py        | 251 +++++++++++++++++-
 .../tests/smol_fixture/checker.py             |  18 ++
 .../tests/smol_fixture/runtime_wrapper.py     |  21 +-
 5 files changed, 495 insertions(+), 16 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 9e9148c0f..a80a57684 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13036,3 +13036,31 @@ issue a grant after an expired commit. This is clock/owner service proof, not a
 new PostgreSQL or native-runtime claim. The hosted failed operation's materialize
 audit occurred about 0.125 seconds after PRE started, so it does not establish
 that this clock defect caused the observed large-input failure.
+
+### Bound the remaining current-source native failure probes
+
+The maintained PRE qualification fixture now has a separate `failure_cleanup`
+selection. It sends three bounded ZIP markers through the existing public raw
+ZIP command: committed guest memory above the locked 128 MiB limit, a guest
+process exit, and output above the locked 32 KiB limit. Each failed operation
+must retain its exact source and charge, return the same-key infrastructure
+failure without a revision penalty, and bind a native create/start/exec/exit/
+delete trace. A final valid ZIP tests completed PRE with one exact lease's
+delete failure. It must retain a pending cleanup obligation while T4 accepts
+the source and T5 creates the Submission. The same isolated CLI process then
+writes a private, exact-lease pending receipt and waits at most 300 seconds
+for an operator-owned matching reconciliation receipt. The operator must
+independently observe the held lease and unavailable capacity, unarm only the
+test wrapper fault, and let the existing Smol startup recovery clear the owned
+lease before acknowledging readiness. The same client then waits for real POST
+acceptance and audits the contribution before its database and bucket are
+cleaned. Only afterward may the operator use the established drained test
+domain stop and normal runner restoration. The existing deadline and
+isolation selection remains unchanged.
+
+The fixture and trace verifier are source preparation, not native evidence.
+Portable tests protect the exact failure and pending-cleanup trace shapes and
+the one-lease delete fault and exact bounded handoff. The real runner cases,
+physical resource custody, and post-reconciliation continuation remain required
+before A25/A26 can be marked
+qualified. The previous 9fad deadline/isolation receipt is separate evidence.
diff --git a/cli/tests/integration/test_journey_pre_qualification.py b/cli/tests/integration/test_journey_pre_qualification.py
index c690b17a0..60b8c426a 100644
--- a/cli/tests/integration/test_journey_pre_qualification.py
+++ b/cli/tests/integration/test_journey_pre_qualification.py
@@ -101,19 +101,24 @@ def test_timeout_replay_compares_stable_business_fields(change):
     replay = {"error": failure | {"correlation_id": "second-request"} | change}
     if change:
         with pytest.raises(AssertionError):
-            MODULE._verify_timeout_replay(first, replay)
+            MODULE._verify_failure_replay(first, replay)
     else:
-        MODULE._verify_timeout_replay(first, replay)
+        MODULE._verify_failure_replay(first, replay)
 
 
 @pytest.mark.parametrize("exact", [True, False])
-def test_runtime_fixture_classifies_only_the_trusted_deadline_line(tmp_path, exact):
+@pytest.mark.parametrize("limit", [None, "memory", "output"])
+def test_runtime_fixture_classifies_only_the_trusted_deadline_line(
+    tmp_path, exact, limit
+):
     wrapper = tmp_path / "runtime_wrapper.py"
     wrapper.write_bytes(WRAPPER.read_bytes())
     guest = tmp_path / "smol"
     diagnostic = "workstream guest bootstrap failed: project deadline exceeded"
     if not exact:
         diagnostic += " (other diagnostic)"
+    if limit is not None:
+        diagnostic += f"\nAssertionError: guest {limit} ceiling was not enforced"
     guest.write_text(
         f"#!{sys.executable}\n"
         "import os\n"
@@ -128,7 +133,11 @@ def test_runtime_fixture_classifies_only_the_trusted_deadline_line(tmp_path, exa
     trace = tmp_path / "trace.jsonl"
     wrapper.with_suffix(".json").write_text(
         json.dumps(
-            {"binary": str(guest), "trace": str(trace), "observe_pre_exit": True}
+            {
+                "binary": str(guest),
+                "trace": str(trace),
+                "observe_pre_exit": True,
+            }
         ),
         encoding="utf-8",
     )
@@ -158,5 +167,181 @@ def test_runtime_fixture_classifies_only_the_trusted_deadline_line(tmp_path, exa
             "operation": "pre_exit",
             "exit_code": 125,
             "project_deadline_exceeded": exact,
+            "guest_limit_unenforced": limit is not None,
         },
     ]
+
+
+@pytest.mark.parametrize(
+    "fault",
+    [
+        None,
+        "limit_unenforced",
+        "wrong_cleanup",
+        "no_delete",
+        "leaked_guest",
+        "extra_pre",
+        "completed_failure",
+    ],
+)
+def test_remaining_native_trace_binds_each_failure_and_pending_lease(fault):
+    wrapper_digest = "sha256:" + sha256(WRAPPER.read_bytes()).hexdigest()
+    evidence = {"mode": "failure_cleanup", "failures": {}}
+    trace = []
+    for name in ("memory", "crash", "output", "pending"):
+        invocation = {
+            "provider_invocation_id": name,
+            "operation": "execute_pre",
+            "outcome": "completed" if name == "pending" else "infrastructure_failure",
+            "cleanup": {
+                "obligation_id": name,
+                "disposition": "pending" if name == "pending" else "destroyed",
+            },
+            "runtime": {"binary_sha256": wrapper_digest},
+        }
+        item = {"invocation": invocation}
+        if name == "pending":
+            evidence["pending"] = item
+        else:
+            evidence["failures"][name] = item
+        trace.extend(
+            [
+                {"name": name, "operation": "create", "prior_resources": []},
+                {"name": name, "operation": "start"},
+                {"name": name, "operation": "exec", "source_pre": True},
+                {
+                    "name": name,
+                    "operation": "pre_exit",
+                    "exit_code": 0 if name == "pending" else 37,
+                    "project_deadline_exceeded": False,
+                    "guest_limit_unenforced": False,
+                },
+                {"name": name, "operation": "delete"},
+            ]
+        )
+    if fault == "limit_unenforced":
+        trace[3]["guest_limit_unenforced"] = True
+    elif fault == "wrong_cleanup":
+        evidence["pending"]["invocation"]["cleanup"]["disposition"] = "destroyed"
+    elif fault == "no_delete":
+        trace.pop()
+    elif fault == "leaked_guest":
+        trace[15]["prior_resources"] = ["memory"]
+    elif fault == "extra_pre":
+        trace.append({"name": "extra", "operation": "exec", "source_pre": True})
+    elif fault == "completed_failure":
+        trace[8]["exit_code"] = 0
+    if fault:
+        with pytest.raises(AssertionError):
+            MODULE.verify_native_trace(evidence, trace)
+    else:
+        MODULE.verify_native_trace(evidence, trace)
+
+
+def test_completed_pre_delete_fault_targets_only_its_traced_lease(tmp_path):
+    wrapper = tmp_path / "runtime_wrapper.py"
+    wrapper.write_bytes(WRAPPER.read_bytes())
+    guest = tmp_path / "smol"
+    guest.write_text(f"#!{sys.executable}\nraise SystemExit(0)\n")
+    guest.chmod(0o700)
+    trace = tmp_path / "trace.jsonl"
+    wrapper.with_suffix(".json").write_text(
+        json.dumps(
+            {
+                "binary": str(guest),
+                "trace": str(trace),
+                "delete_fault": str(tmp_path / "absent-fault"),
+                "observe_pre_exit": True,
+                "fault_completed_pre_delete": True,
+            }
+        )
+    )
+    base = [sys.executable, str(wrapper), "machine"]
+    exec_result = subprocess.run(
+        [
+            *base,
+            "exec",
+            "--name",
+            "owned",
+            "--",
+            "/.workstream-guest",
+            "--pre-limits",
+            "{}",
+        ],
+        capture_output=True,
+        check=False,
+        timeout=10,
+    )
+    assert exec_result.returncode == 0
+    second = subprocess.run(
+        [
+            *base,
+            "exec",
+            "--name",
+            "other",
+            "--",
+            "/.workstream-guest",
+            "--pre-limits",
+            "{}",
+        ],
+        capture_output=True,
+        check=False,
+        timeout=10,
+    )
+    assert second.returncode == 0
+    owned = subprocess.run(
+        [*base, "delete", "--name", "owned"],
+        capture_output=True,
+        check=False,
+        timeout=10,
+    )
+    foreign = subprocess.run(
+        [*base, "delete", "--name", "other"],
+        capture_output=True,
+        check=False,
+        timeout=10,
+    )
+    assert owned.returncode == 93 and foreign.returncode == 0
+    assert [
+        row["operation"] for row in map(json.loads, trace.read_text().splitlines())
+    ] == ["exec", "pre_exit", "exec", "pre_exit", "delete", "delete"]
+
+
+@pytest.mark.parametrize("case", ["exact", "wrong_lease", "wrong_nonce", "symlink"])
+def test_pending_pre_reconciliation_requires_one_private_matching_receipt(
+    tmp_path, case
+):
+    handoff = {
+        "schema_version": "workstream.pre_qualification_restore.v1",
+        "nonce": "fresh-nonce",
+        "source_operation_id": "source",
+        "submission_id": "submission",
+        "provider_invocation_id": "lease",
+        "terminal_sha256": "sha256:" + "a" * 64,
+    }
+    receipt = handoff | {"owned_resources_empty": True, "test_service_ready": True}
+    if case == "wrong_lease":
+        receipt["provider_invocation_id"] = "other-lease"
+    if case == "wrong_nonce":
+        receipt["nonce"] = "old-nonce"
+    path = tmp_path / "pre-qualification-reconciled.json"
+    if case == "symlink":
+        destination = tmp_path / "foreign.json"
+        destination.write_text(json.dumps(receipt))
+        destination.chmod(0o600)
+        path.symlink_to(destination)
+    else:
+        path.write_text(json.dumps(receipt))
+        path.chmod(0o600)
+    if case == "exact":
+        MODULE._await_reconciled(tmp_path, handoff)
+    else:
+        with pytest.raises((AssertionError, OSError)):
+            MODULE._await_reconciled(tmp_path, handoff)
+
+
+def test_pending_pre_reconciliation_has_finite_deadline(tmp_path, monkeypatch):
+    clock = iter((0.0, 301.0))
+    monkeypatch.setattr(MODULE.time, "monotonic", lambda: next(clock))
+    with pytest.raises(AssertionError, match="not acknowledged"):
+        MODULE._await_reconciled(tmp_path, {"nonce": "fresh"})
diff --git a/cli/tests/journey/pre_qualification.py b/cli/tests/journey/pre_qualification.py
index 3fa41fda0..ea67dd169 100644
--- a/cli/tests/journey/pre_qualification.py
+++ b/cli/tests/journey/pre_qualification.py
@@ -4,7 +4,10 @@
 import asyncio
 from hashlib import sha256
 import json
+import os
 from pathlib import Path
+import stat
+import time
 from urllib.parse import urlsplit
 from uuid import uuid4
 from zipfile import ZipFile, ZipInfo
@@ -17,7 +20,15 @@
 
 
 async def _terminal(
-    environment, operation_id, task_id, assignment_id, archive, *, timeout
+    environment,
+    operation_id,
+    task_id,
+    assignment_id,
+    archive,
+    *,
+    failed,
+    cleanup="destroyed",
+    expected_operations=1,
 ):
     from sqlalchemy import text
     from sqlalchemy.ext.asyncio import create_async_engine
@@ -59,7 +70,7 @@ async def _terminal(
                 .mappings()
                 .one()
             )
-            if timeout:
+            if failed:
                 for query in _COUNTS.values():
                     assert await connection.scalar(text(query), parameters) == 0
                 assert (
@@ -78,7 +89,7 @@ async def _terminal(
                         ),
                         parameters,
                     )
-                    == 1
+                    == expected_operations
                 )
     finally:
         await engine.dispose()
@@ -98,7 +109,7 @@ async def _terminal(
     invocation = terminal.invocation_receipt
     assert invocation and invocation.operation == "execute_pre"
     assert invocation.runtime.provider == "smolvm"
-    assert invocation.cleanup.disposition == "destroyed"
+    assert invocation.cleanup.disposition == cleanup
     assert str(source.location.operation_id) == operation_id
     assert str(reservation.assignment_id) == assignment_id
     assert source.location.object_ref == row["object_ref"]
@@ -113,7 +124,7 @@ async def _terminal(
         reservation.policy.entries[0].registry.resources.deadline_ms
         == PRE_QUALIFICATION_DEADLINE_MS
     )
-    if timeout:
+    if failed:
         assert row["state"] == "failed" and row["finalization_event_id"] is None
         assert row["eligible"] is None and terminal.execution is None
         assert terminal.outcome == "infrastructure_failed"
@@ -146,7 +157,7 @@ async def _terminal(
     }
 
 
-def _verify_timeout_replay(first, replay):
+def _verify_failure_replay(first, replay):
     def stable(response):
         error = response["error"].copy()
         error.pop("correlation_id", None)
@@ -158,7 +169,16 @@ def stable(response):
 
 
 def qualify(client, token, task_id, assignment_id, environment):
-    """Exercise an effective project-stage deadline and a successful source fence probe."""
+    """Exercise one closed current-source native qualification selection."""
+    mode = environment.get(
+        "WORKSTREAM_CLI_JOURNEY_PRE_QUALIFICATION_MODE", "deadline_isolation"
+    )
+    if mode == "failure_cleanup":
+        return _qualify_failure_cleanup(
+            client, token, task_id, assignment_id, environment
+        )
+    if mode != "deadline_isolation":
+        raise RuntimeError("unknown PRE qualification selection")
     from source_audit import audit_accepted_source
     from submission_work import (
         _assignment_status,
@@ -186,7 +206,7 @@ def qualify(client, token, task_id, assignment_id, environment):
     arguments = _command(task_id, assignment_id, timed, key)
     first = client.call(token, *arguments, expected_exit=1)
     replay = client.call(token, *arguments, expected_exit=1)
-    _verify_timeout_replay(first, replay)
+    _verify_failure_replay(first, replay)
     observed = _progress(client, token, task_id, key)
     assert observed["operation_state"] == observed["processing_stage"] == "failed"
     assert observed["failure_code"] == INFRASTRUCTURE_FAILURE
@@ -205,7 +225,7 @@ def qualify(client, token, task_id, assignment_id, environment):
             task_id,
             assignment_id,
             timed,
-            timeout=True,
+            failed=True,
         )
     )
 
@@ -228,7 +248,7 @@ def qualify(client, token, task_id, assignment_id, environment):
             task_id,
             assignment_id,
             good,
-            timeout=False,
+            failed=False,
         )
     )
     with (client.evidence.parent / "pre-qualification-client.json").open(
@@ -245,8 +265,161 @@ def qualify(client, token, task_id, assignment_id, environment):
         )
 
 
+def _qualify_failure_cleanup(client, token, task_id, assignment_id, environment):
+    """Prove failed guests, then accept one result with unresolved VM deletion."""
+    from source_audit import audit_accepted_source
+    from submission_work import (
+        _assignment_status,
+        _command,
+        _package,
+        _progress,
+        _submit,
+        _wait_for_stage,
+    )
+
+    if not __debug__ or client.evidence is None:
+        raise RuntimeError("PRE qualification requires private Python assertions")
+    good = _package(client, "correct")
+    failures = {}
+    for name in ("memory", "crash", "output"):
+        archive_path = client.directory / f"qualification-{name}.zip"
+        archive_path.write_bytes(good.read_bytes())
+        marker = ZipInfo(
+            f"pre-qualification-{name}.txt", date_time=(2020, 1, 1, 0, 0, 0)
+        )
+        marker.external_attr = 0o100644 << 16
+        with ZipFile(archive_path, "a") as archive:
+            archive.writestr(marker, f"selected PRE {name} fixture\n".encode())
+        key = str(uuid4())
+        arguments = _command(task_id, assignment_id, archive_path, key)
+        first = client.call(token, *arguments, expected_exit=1)
+        replay = client.call(token, *arguments, expected_exit=1)
+        _verify_failure_replay(first, replay)
+        observed = _progress(client, token, task_id, key)
+        assert observed["operation_state"] == observed["processing_stage"] == "failed"
+        assert observed["failure_code"] == INFRASTRUCTURE_FAILURE
+        assert observed["next_action"] == "retry_new_key_after_terminal"
+        assert observed["pre_submission_results"] == []
+        assert observed["submission_id"] is None
+        status = _assignment_status(client, token, task_id, assignment_id)
+        assert status["current_status"] == "in_progress"
+        assert status["assignment"]["revision"] is None
+        failures[name] = asyncio.run(
+            _terminal(
+                environment,
+                observed["operation_id"],
+                task_id,
+                assignment_id,
+                archive_path,
+                failed=True,
+                expected_operations=len(failures) + 1,
+            )
+        )
+
+    key, receipt = _submit(client, token, task_id, assignment_id, good)
+    deadline = time.monotonic() + 180
+    while time.monotonic() < deadline:
+        observed = _progress(client, token, task_id, key, receipt["operation_id"])
+        if observed["operation_state"] == "finalized":
+            break
+        if observed["operation_state"] in {"failed", "abandoned", "cancelled"}:
+            raise AssertionError("completed PRE did not reach durable T5")
+        time.sleep(1)
+    else:
+        raise AssertionError("completed PRE did not reach durable T5")
+    assert observed["submission_id"] and observed["submission_version"] == 1
+    assert observed["processing_stage"] in {"evaluation_pending", "evaluation_running"}
+    audit_accepted_source(
+        receipt["operation_id"],
+        observed["submission_id"],
+        task_id,
+        good,
+        accepted=False,
+    )
+    pending = asyncio.run(
+        _terminal(
+            environment,
+            receipt["operation_id"],
+            task_id,
+            assignment_id,
+            good,
+            failed=False,
+            cleanup="pending",
+        )
+    )
+    handoff = {
+        "schema_version": "workstream.pre_qualification_restore.v1",
+        "nonce": str(uuid4()),
+        "source_operation_id": receipt["operation_id"],
+        "submission_id": observed["submission_id"],
+        "provider_invocation_id": pending["invocation"]["provider_invocation_id"],
+        "terminal_sha256": pending["terminal_sha256"],
+    }
+    handoff_path = client.evidence.parent / "pre-qualification-pending.json"
+    with handoff_path.open("x", encoding="utf-8") as stream:
+        handoff_path.chmod(0o600)
+        json.dump(handoff, stream)
+        stream.flush()
+        os.fsync(stream.fileno())
+    _await_reconciled(client.evidence.parent, handoff)
+    accepted = _wait_for_stage(client, token, task_id, key, receipt, "accepted")
+    assert accepted["submission_id"] == observed["submission_id"]
+    audit_accepted_source(
+        receipt["operation_id"],
+        accepted["submission_id"],
+        task_id,
+        good,
+        accepted=True,
+    )
+    destination = client.evidence.parent / "pre-qualification-client.json"
+    with destination.open("x", encoding="utf-8") as stream:
+        destination.chmod(0o600)
+        json.dump(
+            {
+                "mode": "failure_cleanup",
+                "assignment_id": assignment_id,
+                "failures": failures,
+                "pending": pending,
+                "submission_id": observed["submission_id"],
+                "accepted_submission_id": accepted["submission_id"],
+            },
+            stream,
+        )
+
+
+def _await_reconciled(directory, handoff):
+    """Keep the isolated public client alive until this lease is reconciled."""
+    path = directory / "pre-qualification-reconciled.json"
+    deadline = time.monotonic() + 300
+    expected = handoff | {"owned_resources_empty": True, "test_service_ready": True}
+    while time.monotonic() < deadline:
+        try:
+            descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
+        except FileNotFoundError:
+            time.sleep(0.5)
+            continue
+        with os.fdopen(descriptor, "rb") as stream:
+            metadata = os.fstat(stream.fileno())
+            valid = (
+                stat.S_ISREG(metadata.st_mode)
+                and stat.S_IMODE(metadata.st_mode) == 0o600
+                and metadata.st_uid == os.geteuid()
+                and metadata.st_nlink == 1
+                and 0 < metadata.st_size <= 4096
+                and json.loads(stream.read(4097)) == expected
+            )
+        if not valid:
+            raise AssertionError("PRE cleanup reconciliation receipt differs")
+        return
+    raise AssertionError("PRE cleanup reconciliation was not acknowledged")
+
+
 def verify_native_trace(evidence, trace):
     """Bind the trusted guest's classified stage exit to both committed receipts."""
+    if evidence.get("mode") == "failure_cleanup":
+        return _verify_failure_cleanup_trace(evidence, trace)
+    if evidence.get("mode") not in {None, "deadline_isolation"}:
+        raise AssertionError("unknown PRE qualification evidence selection")
     wrapper_digest = "sha256:" + sha256(WRAPPER.read_bytes()).hexdigest()
     leases = []
     for name, outcome, exit_code, expired in (
@@ -293,6 +466,53 @@ def verify_native_trace(evidence, trace):
         )
 
 
+def _verify_failure_cleanup_trace(evidence, trace):
+    """Bind three guest failures and one exact unsettled delete to current PRE leases."""
+    wrapper_digest = "sha256:" + sha256(WRAPPER.read_bytes()).hexdigest()
+    leases = []
+    for name in ("memory", "crash", "output", "pending"):
+        item = evidence["pending"] if name == "pending" else evidence["failures"][name]
+        invocation = item["invocation"]
+        lease = invocation["provider_invocation_id"]
+        expected_outcome = (
+            "completed" if name == "pending" else "infrastructure_failure"
+        )
+        expected_cleanup = "pending" if name == "pending" else "destroyed"
+        if (
+            lease in leases
+            or invocation["operation"] != "execute_pre"
+            or invocation["outcome"] != expected_outcome
+            or invocation["cleanup"]["obligation_id"] != lease
+            or invocation["cleanup"]["disposition"] != expected_cleanup
+            or invocation["runtime"]["binary_sha256"] != wrapper_digest
+        ):
+            raise AssertionError(f"{name} has no exact PRE invocation")
+        rows = [row for row in trace if row["name"] == lease]
+        operations = [row["operation"] for row in rows]
+        if (
+            operations[:4] != ["create", "start", "exec", "pre_exit"]
+            or not operations[4:]
+            or set(operations[4:]) != {"delete"}
+            or rows[2].get("source_pre") is not True
+            or any(prior in rows[0].get("prior_resources", []) for prior in leases)
+            or rows[3]["project_deadline_exceeded"] is not False
+            or rows[3].get("guest_limit_unenforced") is not False
+        ):
+            raise AssertionError(f"{name} lacks exact native execution and cleanup")
+        if name == "pending":
+            if rows[3]["exit_code"] != 0:
+                raise AssertionError("pending cleanup did not follow a completed guest")
+        elif rows[3]["exit_code"] == 0:
+            raise AssertionError(f"{name} native failure differs")
+        leases.append(lease)
+    executions = [row for row in trace if row["operation"] == "exec"]
+    if (
+        any(type(row.get("source_pre")) is not bool for row in executions)
+        or [row["name"] for row in executions if row["source_pre"]] != leases
+    ):
+        raise AssertionError("native trace contains a different PRE execution")
+
+
 def main():
     parser = argparse.ArgumentParser(description=verify_native_trace.__doc__)
     parser.add_argument("client_evidence", type=Path)
@@ -305,7 +525,16 @@ def main():
         json.loads(arguments.client_evidence.read_bytes()),
         [json.loads(line) for line in arguments.native_trace.read_bytes().splitlines()],
     )
-    print(json.dumps({"project_stage_deadline": "verified", "isolation": "verified"}))
+    print(
+        json.dumps(
+            {
+                "selection": json.loads(arguments.client_evidence.read_bytes()).get(
+                    "mode", "deadline_isolation"
+                ),
+                "native_trace": "verified",
+            }
+        )
+    )
 
 
 if __name__ == "__main__":
diff --git a/external_checkers/workstream-checker-service/tests/smol_fixture/checker.py b/external_checkers/workstream-checker-service/tests/smol_fixture/checker.py
index 5cb783538..19b27a700 100644
--- a/external_checkers/workstream-checker-service/tests/smol_fixture/checker.py
+++ b/external_checkers/workstream-checker-service/tests/smol_fixture/checker.py
@@ -14,6 +14,9 @@
 
 PRE_SOURCE_SCHEMA = "workstream.external_checker_pre_submit_input.v1"
 TIMEOUT_MARKER = "pre-qualification-timeout.txt"
+MEMORY_MARKER = "pre-qualification-memory.txt"
+CRASH_MARKER = "pre-qualification-crash.txt"
+OUTPUT_MARKER = "pre-qualification-output.txt"
 
 
 def denied(operation, *, expected_errno=None):
@@ -65,6 +68,21 @@ def evaluate_source_first(request):
     if (input_root / TIMEOUT_MARKER).is_file():
         assert (input_root / TIMEOUT_MARKER).read_bytes() == b"selected PRE deadline fixture\n"
         time.sleep(30)
+    if (input_root / MEMORY_MARKER).is_file():
+        assert (input_root / MEMORY_MARKER).read_bytes() == b"selected PRE memory fixture\n"
+        # Commit more than the selected 128 MiB guest ceiling in bounded pages.
+        allocated = []
+        for _ in range(128):
+            allocated.append(bytearray(4 * 1024 * 1024))
+        raise AssertionError("guest memory ceiling was not enforced")
+    if (input_root / CRASH_MARKER).is_file():
+        assert (input_root / CRASH_MARKER).read_bytes() == b"selected PRE crash fixture\n"
+        os._exit(37)
+    if (input_root / OUTPUT_MARKER).is_file():
+        assert (input_root / OUTPUT_MARKER).read_bytes() == b"selected PRE output fixture\n"
+        sys.stdout.write("x" * 1024 * 1024)
+        sys.stdout.flush()
+        raise AssertionError("guest output ceiling was not enforced")
 
 
 def evaluate(request):
diff --git a/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py b/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
index fc9b043d1..207b0a239 100644
--- a/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
+++ b/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
@@ -21,11 +21,19 @@ def observe_pre_exit(binary, arguments, trace, name):
             sys.stderr.buffer.write(chunk)
             sys.stderr.buffer.flush()
         code = child.wait()
+    limit_unenforced = any(
+        message in captured
+        for message in (
+            b'guest memory ceiling was not enforced',
+            b'guest output ceiling was not enforced',
+        )
+    )
     with trace.open('a') as output:
         fcntl.flock(output, fcntl.LOCK_EX)
         output.write(json.dumps({
             'operation': 'pre_exit', 'name': name, 'exit_code': code,
             'project_deadline_exceeded': diagnostic in captured.splitlines(),
+            'guest_limit_unenforced': limit_unenforced,
         }) + '\n')
         output.flush()
         os.fsync(output.fileno())
@@ -69,7 +77,18 @@ def observe_pre_exit(binary, arguments, trace, name):
                     state.flush()
                     os.fsync(state.fileno())
                     sys.exit(93)
-        if operation == 'delete' and Path(settings['delete_fault']).exists():
+        if operation == 'delete' and (
+            Path(settings['delete_fault']).exists()
+            or (
+                settings.get('fault_completed_pre_delete') is True
+                and next(
+                    (row['name'] for row in
+                     (json.loads(line) for line in trace.read_text().splitlines())
+                     if row['operation'] == 'pre_exit' and row['exit_code'] == 0),
+                    None,
+                ) == name
+            )
+        ):
             sys.exit(93)
         if source_pre and settings.get('observe_pre_exit') is True:
             sys.exit(observe_pre_exit(settings['binary'], arguments, trace, name))

From fd3ac94369e87ed963da14768a642799f07e9766 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 18:12:52 +0100
Subject: [PATCH 469/513] test: pause POST delivery during pending PRE cleanup
 proof

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 11 ++-
 .../test_journey_pre_qualification.py         | 12 +++
 cli/tests/journey/bootstrap.py                |  1 +
 cli/tests/journey/pre_qualification.py        | 95 ++++++++++---------
 4 files changed, 71 insertions(+), 48 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index a80a57684..189605d57 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13046,14 +13046,17 @@ process exit, and output above the locked 32 KiB limit. Each failed operation
 must retain its exact source and charge, return the same-key infrastructure
 failure without a revision penalty, and bind a native create/start/exec/exit/
 delete trace. A final valid ZIP tests completed PRE with one exact lease's
-delete failure. It must retain a pending cleanup obligation while T4 accepts
-the source and T5 creates the Submission. The same isolated CLI process then
+delete failure. The existing isolated POST effect worker is stopped before this
+last submission; the finalizer and outbox scanner remain live. It must retain
+a pending cleanup obligation while T4 accepts the source and T5 creates the
+Submission without consuming POST retries. The same isolated CLI process then
 writes a private, exact-lease pending receipt and waits at most 300 seconds
 for an operator-owned matching reconciliation receipt. The operator must
 independently observe the held lease and unavailable capacity, unarm only the
 test wrapper fault, and let the existing Smol startup recovery clear the owned
-lease before acknowledging readiness. The same client then waits for real POST
-acceptance and audits the contribution before its database and bucket are
+lease before acknowledging readiness. The owned POST worker resumes only after
+that acknowledgement. The same client then waits for real POST acceptance and
+audits the contribution before its database and bucket are
 cleaned. Only afterward may the operator use the established drained test
 domain stop and normal runner restoration. The existing deadline and
 isolation selection remains unchanged.
diff --git a/cli/tests/integration/test_journey_pre_qualification.py b/cli/tests/integration/test_journey_pre_qualification.py
index 60b8c426a..61f471bc8 100644
--- a/cli/tests/integration/test_journey_pre_qualification.py
+++ b/cli/tests/integration/test_journey_pre_qualification.py
@@ -20,6 +20,18 @@
 SPEC.loader.exec_module(MODULE)
 
 
+def test_failure_cleanup_requires_the_owned_post_delivery_pause(monkeypatch):
+    pause = object()
+    monkeypatch.setattr(MODULE, "_qualify_failure_cleanup", lambda *args: args[-1])
+    environment = {"WORKSTREAM_CLI_JOURNEY_PRE_QUALIFICATION_MODE": "failure_cleanup"}
+    with pytest.raises(RuntimeError, match="owned POST pause"):
+        MODULE.qualify(None, None, None, None, environment)
+    assert (
+        MODULE.qualify(None, None, None, None, environment, post_delivery_pause=pause)
+        is pause
+    )
+
+
 @pytest.mark.parametrize(
     "fault",
     [
diff --git a/cli/tests/journey/bootstrap.py b/cli/tests/journey/bootstrap.py
index 2b06172e1..1ee65be1a 100644
--- a/cli/tests/journey/bootstrap.py
+++ b/cli/tests/journey/bootstrap.py
@@ -467,6 +467,7 @@ def main():
                                 task_id,
                                 assignment_id,
                                 environment,
+                                post_delivery_pause=pause_post_delivery(*post_worker),
                             )
                             client.complete_stage("source_first_pre_client_evidence")
                         elif os.environ.get("WORKSTREAM_CLI_JOURNEY_SUBMIT") == "1":
diff --git a/cli/tests/journey/pre_qualification.py b/cli/tests/journey/pre_qualification.py
index ea67dd169..a2128597d 100644
--- a/cli/tests/journey/pre_qualification.py
+++ b/cli/tests/journey/pre_qualification.py
@@ -168,14 +168,18 @@ def stable(response):
     assert stable(first) == stable(replay)
 
 
-def qualify(client, token, task_id, assignment_id, environment):
+def qualify(
+    client, token, task_id, assignment_id, environment, *, post_delivery_pause=None
+):
     """Exercise one closed current-source native qualification selection."""
     mode = environment.get(
         "WORKSTREAM_CLI_JOURNEY_PRE_QUALIFICATION_MODE", "deadline_isolation"
     )
     if mode == "failure_cleanup":
+        if post_delivery_pause is None:
+            raise RuntimeError("pending PRE cleanup requires an owned POST pause")
         return _qualify_failure_cleanup(
-            client, token, task_id, assignment_id, environment
+            client, token, task_id, assignment_id, environment, post_delivery_pause
         )
     if mode != "deadline_isolation":
         raise RuntimeError("unknown PRE qualification selection")
@@ -265,7 +269,9 @@ def qualify(client, token, task_id, assignment_id, environment):
         )
 
 
-def _qualify_failure_cleanup(client, token, task_id, assignment_id, environment):
+def _qualify_failure_cleanup(
+    client, token, task_id, assignment_id, environment, post_delivery_pause
+):
     """Prove failed guests, then accept one result with unresolved VM deletion."""
     from source_audit import audit_accepted_source
     from submission_work import (
@@ -316,52 +322,53 @@ def _qualify_failure_cleanup(client, token, task_id, assignment_id, environment)
             )
         )
 
-    key, receipt = _submit(client, token, task_id, assignment_id, good)
-    deadline = time.monotonic() + 180
-    while time.monotonic() < deadline:
-        observed = _progress(client, token, task_id, key, receipt["operation_id"])
-        if observed["operation_state"] == "finalized":
-            break
-        if observed["operation_state"] in {"failed", "abandoned", "cancelled"}:
+    with post_delivery_pause:
+        key, receipt = _submit(client, token, task_id, assignment_id, good)
+        deadline = time.monotonic() + 180
+        while time.monotonic() < deadline:
+            observed = _progress(client, token, task_id, key, receipt["operation_id"])
+            if observed["operation_state"] == "finalized":
+                break
+            if observed["operation_state"] in {"failed", "abandoned", "cancelled"}:
+                raise AssertionError("completed PRE did not reach durable T5")
+            time.sleep(1)
+        else:
             raise AssertionError("completed PRE did not reach durable T5")
-        time.sleep(1)
-    else:
-        raise AssertionError("completed PRE did not reach durable T5")
-    assert observed["submission_id"] and observed["submission_version"] == 1
-    assert observed["processing_stage"] in {"evaluation_pending", "evaluation_running"}
-    audit_accepted_source(
-        receipt["operation_id"],
-        observed["submission_id"],
-        task_id,
-        good,
-        accepted=False,
-    )
-    pending = asyncio.run(
-        _terminal(
-            environment,
+        assert observed["submission_id"] and observed["submission_version"] == 1
+        assert observed["processing_stage"] == "evaluation_pending"
+        audit_accepted_source(
             receipt["operation_id"],
+            observed["submission_id"],
             task_id,
-            assignment_id,
             good,
-            failed=False,
-            cleanup="pending",
+            accepted=False,
         )
-    )
-    handoff = {
-        "schema_version": "workstream.pre_qualification_restore.v1",
-        "nonce": str(uuid4()),
-        "source_operation_id": receipt["operation_id"],
-        "submission_id": observed["submission_id"],
-        "provider_invocation_id": pending["invocation"]["provider_invocation_id"],
-        "terminal_sha256": pending["terminal_sha256"],
-    }
-    handoff_path = client.evidence.parent / "pre-qualification-pending.json"
-    with handoff_path.open("x", encoding="utf-8") as stream:
-        handoff_path.chmod(0o600)
-        json.dump(handoff, stream)
-        stream.flush()
-        os.fsync(stream.fileno())
-    _await_reconciled(client.evidence.parent, handoff)
+        pending = asyncio.run(
+            _terminal(
+                environment,
+                receipt["operation_id"],
+                task_id,
+                assignment_id,
+                good,
+                failed=False,
+                cleanup="pending",
+            )
+        )
+        handoff = {
+            "schema_version": "workstream.pre_qualification_restore.v1",
+            "nonce": str(uuid4()),
+            "source_operation_id": receipt["operation_id"],
+            "submission_id": observed["submission_id"],
+            "provider_invocation_id": pending["invocation"]["provider_invocation_id"],
+            "terminal_sha256": pending["terminal_sha256"],
+        }
+        handoff_path = client.evidence.parent / "pre-qualification-pending.json"
+        with handoff_path.open("x", encoding="utf-8") as stream:
+            handoff_path.chmod(0o600)
+            json.dump(handoff, stream)
+            stream.flush()
+            os.fsync(stream.fileno())
+        _await_reconciled(client.evidence.parent, handoff)
     accepted = _wait_for_stage(client, token, task_id, key, receipt, "accepted")
     assert accepted["submission_id"] == observed["submission_id"]
     audit_accepted_source(

From e51ad8a1a4f8977e35abd0c6a88cf62e12f090e2 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 18:13:35 +0100
Subject: [PATCH 470/513] Record archive guard and retained upgrade
 qualification

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 +++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 189605d57..cde1ce416 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13012,6 +13012,26 @@ approved 256-byte compressed cap. The separate missing and widened cases
 reconstruct the supplied digest to exercise the binding rather than a stale
 digest failure.
 
+Six named PostgreSQL tests passed on `73b466b25` at `0094_project_archive_limits`.
+The exact context and source passed the SQL function and insertion trigger.
+Both denied missing caps, widened caps, and a stored compressed limit above
+policy. The public HTTP tests passed streamed submission and replay, a 413
+before reservation, a 409 for a changed replay length, and exact receipt reuse.
+An earlier batch timed out after four unnamed passing assertions. Both runs
+confirmed isolated database cleanup.
+
+An isolated PostgreSQL upgrade created an accepted operation on `9fad17a04`
+under an approved guide with archive caps. The original PRE context omitted
+those caps. The candidate migration refused both receiving and PRE-checking
+operations and preserved the 0093 head and original receipt on each refusal.
+After the old foreground owner drained, the migration and its no-op reentry
+passed. The candidate finalized the original accepted source into one immutable
+Submission. Source identities, PRE request and result bytes and digests, and
+acceptance receipt remained unchanged. The upgrade drill passed and cleaned its
+isolated database. The coordinated hosted cutover and new native PRE root
+qualification remain pending.
+
+
 ### Preserve the remaining PRE source-read deadline after authorization
 
 The source-read grant sampled its monotonic start before authorization and locks,

From b9123afa4d2ddebf3aa0eac532654db17e09eed0 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 18:26:08 +0100
Subject: [PATCH 471/513] Keep authorized PRE reads under committed foreground
 renewal

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 16 +++++
 .../artifacts/intake/foreground_lease.py      | 18 ++++-
 .../selected_pre_submit_execution.py          |  9 ++-
 .../test_submission_intake_contracts.py       | 68 +++++++++++++++++++
 .../artifacts/test_submission_pre_source.py   | 11 +--
 5 files changed, 112 insertions(+), 10 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index cde1ce416..a57ad0dac 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13087,3 +13087,19 @@ the one-lease delete fault and exact bounded handoff. The real runner cases,
 physical resource custody, and post-reconciliation continuation remain required
 before A25/A26 can be marked
 qualified. The previous 9fad deadline/isolation receipt is separate evidence.
+
+### Keep PRE source reads under the renewed foreground owner
+
+Two hosted 500 MiB uploads sealed normally and ended as material unavailable
+about 80 seconds into PRE. The same immutable object streamed through the API
+host under 85 seconds of receiver backpressure with its full byte count and
+SHA-256. The issued source grant kept a snapshot of the 60-second foreground
+lease despite renewal of the same fence. An actual blocked socket drain can
+cross that snapshot before the source iterator next checks it.
+
+The bounded change belongs to the existing foreground lease and authorized PRE
+source-read owners. The foreground command runs under one local deadline that
+advances only after the same owner commits renewal. A missed deadline cancels
+that command before draining renewal cleanup. Source grant issuance still
+requires live foreground authority, and the grant uses the fixed CHECKERS and
+original PRE deadlines. The original T4 authority and replay remain in force.
diff --git a/backend/app/modules/artifacts/intake/foreground_lease.py b/backend/app/modules/artifacts/intake/foreground_lease.py
index 42c44752c..c94ffe145 100644
--- a/backend/app/modules/artifacts/intake/foreground_lease.py
+++ b/backend/app/modules/artifacts/intake/foreground_lease.py
@@ -51,18 +51,30 @@ async def run(
     ) -> Result:
         """Invoke once after committed renewal; drain all work before returning."""
         budget = await self._renew(operation_id, lease_id, generation)
+        loop = asyncio.get_running_loop()
+        watchdog = asyncio.timeout(budget)
 
         async def pulse() -> None:
-            remaining = budget
             while True:
-                await asyncio.sleep(min(self._interval, remaining / 2))
+                deadline = watchdog.when()
+                assert deadline is not None
+                await asyncio.sleep(min(self._interval, (deadline - loop.time()) / 2))
                 remaining = await self._renew(operation_id, lease_id, generation)
+                renewed_at = loop.time()
+                if renewed_at >= deadline:
+                    raise IntakeCustodyConflict("intake_owner_renewal_expired")
+                watchdog.reschedule(renewed_at + remaining)
 
         command = asyncio.create_task(command_factory(operation_id, lease_id, generation),
                                       name=f"submission-foreground:{operation_id}")
         renewal = asyncio.create_task(pulse(), name=f"submission-lease:{operation_id}")
         try:
-            await asyncio.wait((command, renewal), return_when=asyncio.FIRST_COMPLETED)
+            try:
+                async with watchdog:
+                    await asyncio.wait((command, renewal), return_when=asyncio.FIRST_COMPLETED)
+            except TimeoutError as exc:
+                if not command.done():
+                    raise IntakeCustodyConflict("intake_owner_renewal_expired") from exc
             if command.done():
                 return command.result()
             renewal.result()
diff --git a/backend/app/modules/artifacts/selected_pre_submit_execution.py b/backend/app/modules/artifacts/selected_pre_submit_execution.py
index 768a7d27f..8c2d23dce 100644
--- a/backend/app/modules/artifacts/selected_pre_submit_execution.py
+++ b/backend/app/modules/artifacts/selected_pre_submit_execution.py
@@ -169,16 +169,21 @@ async def issue(
                         or live.lease_id != facts.foreground_lease_id
                         or live.lease_generation != facts.foreground_lease_generation):
                     raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable")
-                expires_at = min(live.lease_expires_at, lease.lease_expires_at, live.pre_deadline_at)
+                expires_at = min(lease.lease_expires_at, live.pre_deadline_at)
+                issue_expires_at = min(live.lease_expires_at, expires_at)
                 # Pair clocks after authority/lock waits; sample before the query
                 # so its round trip and the following commit cannot extend expiry.
                 sampled_monotonic = asyncio.get_running_loop().time()
                 now = await self._session.scalar(select(func.clock_timestamp()))
-                if now is None or expires_at <= now:
+                if now is None or issue_expires_at <= now:
                     raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable")
+                issue_deadline = sampled_monotonic + (issue_expires_at - now).total_seconds()
                 deadline = sampled_monotonic + (expires_at - now).total_seconds()
                 await self._authority.consume(prepared_authorization=handle, facts=facts)
             # No grant exists if commit fails, including a lost acknowledgement.
+            if asyncio.get_running_loop().time() >= issue_deadline:
+                raise SelectedPreSubmitInfrastructureUnavailable("material_unavailable")
+            # The foreground command watchdog continues to track committed renewal.
             grant = _PreSubmitSourceGrant._issued(self, lease, expires_at, deadline)
             grant._require_current()
             yield grant
diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py
index b7f44d41f..b7c1fed7a 100644
--- a/backend/tests/artifacts/test_submission_intake_contracts.py
+++ b/backend/tests/artifacts/test_submission_intake_contracts.py
@@ -398,6 +398,74 @@ async def command(*owner):
     assert await runner.run(new_record_id(), new_record_id(), 1, command) == "committed"
 
 
+@pytest.mark.parametrize("renewed", [True, False])
+async def test_foreground_lease_uses_only_the_last_committed_deadline(monkeypatch, renewed):
+    """Keep a renewed command alive and cancel an expired command before rollback drains."""
+    from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease
+    from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+
+    loop = asyncio.get_running_loop()
+    clock = loop.time()
+    monkeypatch.setattr(loop, "time", lambda: clock)
+    runner = ForegroundIntakeLease(None, None, lease_duration=timedelta(seconds=60),
+                                  heartbeat_interval=timedelta(seconds=10))
+    reading = asyncio.Event()
+    renewals = asyncio.Queue()
+    finish, cancelled = asyncio.Event(), asyncio.Event()
+    rollback, release_rollback = asyncio.Event(), asyncio.Event()
+    calls = 0
+
+    async def renew(*owner):
+        nonlocal calls
+        calls += 1
+        if calls == 1:
+            return 60
+        renewals.put_nowait(calls)
+        if renewed and calls <= 4:
+            return 60
+        try:
+            await loop.create_future()
+        finally:
+            rollback.set()
+            await release_rollback.wait()
+
+    async def command(*owner):
+        reading.set()
+        try:
+            await finish.wait()
+            return "committed"
+        except asyncio.CancelledError:
+            cancelled.set()
+            raise
+
+    monkeypatch.setattr(runner, "_renew", renew)
+    running = asyncio.create_task(runner.run(new_record_id(), new_record_id(), 1, command))
+    try:
+        await reading.wait()
+        for attempt in ((2, 3, 4) if renewed else (2,)):
+            clock += 10
+            assert await renewals.get() == attempt
+        clock += 50
+        # Advance scheduled timeout, owner and child cancellation callbacks.
+        for _ in range(5):
+            await asyncio.sleep(0)
+        if renewed:
+            assert not running.done() and not cancelled.is_set()
+            release_rollback.set()
+            finish.set()
+            assert await running == "committed"
+        else:
+            assert cancelled.is_set() and rollback.is_set() and not running.done()
+            release_rollback.set()
+            with pytest.raises(IntakeCustodyConflict, match="intake_owner_renewal_expired"):
+                await running
+    finally:
+        release_rollback.set()
+        if not running.done():
+            running.cancel()
+        await asyncio.gather(running, return_exceptions=True)
+
+
 @pytest.mark.asyncio
 async def test_discard_replay_hashes_exact_raw_bytes_across_chunk_boundaries():
     from app.modules.artifacts.intake.streaming import hash_submission_replay
diff --git a/backend/tests/artifacts/test_submission_pre_source.py b/backend/tests/artifacts/test_submission_pre_source.py
index 6d72b5249..04cb2ab1b 100644
--- a/backend/tests/artifacts/test_submission_pre_source.py
+++ b/backend/tests/artifacts/test_submission_pre_source.py
@@ -715,9 +715,9 @@ async def invoke():
         await engine.dispose()
 
 
-@pytest.mark.parametrize("authorization_delay, commit_delay", [(0, 0), (40, 0), (40, 90)])
+@pytest.mark.parametrize("authorization_delay, commit_delay", [(0, 0), (40, 0), (40, 20), (60, 0)])
 async def test_source_read_deadline_charges_authorization_once(monkeypatch, authorization_delay, commit_delay):
-    """Slow authority must not shorten, or a slow commit extend, the stored expiry."""
+    """Issue under a live foreground lease and read up to the fixed execution expiry."""
     import asyncio
     from contextlib import asynccontextmanager
     from dataclasses import replace
@@ -731,6 +731,7 @@ async def test_source_read_deadline_charges_authorization_once(monkeypatch, auth
     elapsed = [0.0]
     wall_start = datetime.now(UTC)
     expires = wall_start + timedelta(seconds=120)
+    initial_foreground_expiry = wall_start + timedelta(seconds=60)
     request = replace(_source_reservation(), pre_deadline_at=expires,
                       source_contracts=source_reads.ArtifactPreSubmitSourceContracts())
     lease = SelectedPreSubmitLeaseFacts(request, new_record_id(), 1, expires)
@@ -793,7 +794,7 @@ async def lock_pre_source(self, **_kwargs):
                     "identity_link_id", "metadata_sha256", "locked_context_sha256", "pre_deadline_at",
                 )
             }, lease_id=facts.foreground_lease_id, lease_generation=facts.foreground_lease_generation,
-                lease_expires_at=expires)
+                lease_expires_at=initial_foreground_expiry)
 
     observed_reads = []
 
@@ -809,14 +810,14 @@ async def open_source(self, source, **_kwargs):
         session=session, sources=Sources(), authority=Authority(), store=Store(),
     )
     capability = SimpleNamespace(consume=lambda **_kwargs: lease)
-    if commit_delay:
+    if commit_delay or authorization_delay >= 60:
         with pytest.raises(SelectedPreSubmitInfrastructureUnavailable, match="material_unavailable"):
             async with reader.issue(lease=lease, execution_authority=capability):
                 pytest.fail("expired commit issued a source grant")
         assert not observed_reads
     else:
         async with reader.issue(lease=lease, execution_authority=capability) as grant:
-            elapsed[0] = 90
+            elapsed[0] = 80
             stream = grant.open_source(lease=lease)
             assert await anext(stream) == b"x" * request.source.raw_byte_count
             elapsed[0] = 120

From a3c9f0d7e60d5489518e62bd491e50ccb2eb2a23 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 18:29:55 +0100
Subject: [PATCH 472/513] Record PRE foreground renewal regression evidence

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md   | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index a57ad0dac..fc44df9fc 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13103,3 +13103,16 @@ advances only after the same owner commits renewal. A missed deadline cancels
 that command before draining renewal cleanup. Source grant issuance still
 requires live foreground authority, and the grant uses the fixed CHECKERS and
 original PRE deadlines. The original T4 authority and replay remain in force.
+
+The hosted read-only diagnostic transferred the exact 524,288,000 bytes and
+verified SHA-256 through 64 KiB frames after an 84.521-second blocked drain.
+A second run with the deployed source grant and a shortened captured expiry
+returned `material_unavailable` on the first read after the blocked write.
+
+The same three regression cases failed on `e51ad8a1a`. Both 80-second reads
+hit the captured expiry and the stalled renewal left its command running.
+The candidate `72df337ae` passed those cases and 21 other focused cases. It
+retained the original PRE deadline and cancelled the expired command while
+renewal rollback was still held. The integrated `b9123afa4` has identical
+production and regression files. Both test processes exited. Hosted acceptance
+of the maximum-size archive remains pending.

From 1de2c690f8a439ccd2eb48d59615960556a46355 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 18:33:24 +0100
Subject: [PATCH 473/513] Name Celery and source cleanup explicitly in roadmap

---
 docs/roadmap_status.md | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md
index d38666898..c4d32b980 100644
--- a/docs/roadmap_status.md
+++ b/docs/roadmap_status.md
@@ -136,11 +136,11 @@ Scoped PostgreSQL/MinIO, client and real Redis/Celery child-recovery proofs exis
 The connected local API/separate AWS runner journey proves automatic acceptance,
 PRE and POST rejection, exact source/contribution custody and default review_pending.
 Live AWS versioned-source permissions, cleanup and lost-acknowledgement recovery
-are qualified. The hosted API/worker release and contributor CLI/MCP journey now
-prove PRE rejection, POST revision, same-assignment correction and unpaid acceptance.
+are qualified. The contributor CLI/MCP journey through the deployed API and Celery
+services proves PRE rejection, POST revision, same-assignment correction and unpaid acceptance.
 The separate Smol deadline/isolation fixture passes with normal admission restored.
 Remaining native fault cases, supported uploads and tighter project-limit enforcement,
-age-eligible cleanup-worker deletion, the hosted required-review guard and final
+source cleanup for age-eligible objects, the hosted required-review guard and final
 release checks remain open. Multiple API replicas/runners and broad load campaigns
 are user-deferred; the completed fixture does not qualify them.
 
@@ -1592,7 +1592,7 @@ Delivered foundations (evidence scope stated per capability)
     -> dedicated durable T5 -> immutable Submission/binding -> POST
     -> locked true: review_pending; locked false: shared acceptance + contribution + applicable award
     -> hosted CLI/MCP contributor journey + separate Smol deadline/isolation verified
-    -> remaining native faults, upload/project limits and aged cleanup-worker proof
+    -> remaining native faults, upload/project limits and age-eligible source cleanup proof
   verified guide originals -> explicit PM assistance OR provider-free uploaded rules
     -> unified compilation -> separate manager pre/post approvals
     -> existing activation guards (human review defaults true; approved false supported)

From 3fd229274ce6833d75b774ea0f3453bfb57e137d Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 18:57:20 +0100
Subject: [PATCH 474/513] Record hosted age-eligible exact source cleanup

---
 .commitrail/INDEX.md                          |  2 +-
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md     | 22 ++++++++++---------
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 +++++++++++++++++
 docs/roadmap_status.md                        | 12 +++++-----
 4 files changed, 40 insertions(+), 16 deletions(-)

diff --git a/.commitrail/INDEX.md b/.commitrail/INDEX.md
index 00860ee5b..2199d9d0c 100644
--- a/.commitrail/INDEX.md
+++ b/.commitrail/INDEX.md
@@ -6,7 +6,7 @@ for current product capability.
 
 | Initiative | Durable disposition | Next usable boundary |
 |---|---|---|
-| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP API/CLI/MCP and dedicated workers are deployed. The hosted contributor journey proves PRE rejection, POST revision, same-assignment correction and unpaid acceptance; the separate Smol deadline/isolation fixture and current MCP replay pass. Next: remaining native faults, supported input/project-limit proof, age-eligible cleanup-worker deletion, hosted required-review guard and final release checks. Scalability and live human review remain deferred. |
+| [WS-SUBMIT-001](initiatives/WS-SUBMIT-001/OVERVIEW.md) | Planned | Raw-ZIP API/CLI/MCP and dedicated Celery workers are deployed. The hosted contributor journey proves PRE rejection, POST revision, same-assignment correction and unpaid acceptance. The separate Smol deadline/isolation fixture, current MCP replay and deployed exact aged rejection cleanup passed. Remaining work includes native faults, supported input/project-limit proof, the hosted required-review guard and final release checks. Scalability and live human review remain deferred. |
 | [WS-EXEC-001](initiatives/WS-EXEC-001/OVERVIEW.md) | Complete | Self-hosted Smol lifecycle, typed upload/download intake, required hosted configuration and public API/Celery proof cover both policy branches and recovery. Next: provision the intended hosted deployment and repeat with actual Flow/AWS identities; local fixtures and MinIO do not certify it. |
 | [WS-GHPROOF-001](initiatives/WS-GHPROOF-001/OVERVIEW.md) | Planned | Checker-owned forge selection (04A) separates project proof parsing from scoped fact retrieval; completed evaluations bind selection, facts and material evidence. Next: hosted credentials and the project drill; separate fetched-byte custody and broader routing remain distinct scope. |
 | [WS-AGENT-001](initiatives/WS-AGENT-001/OVERVIEW.md) | Planned | Neutral document tools plus OpenAI Agents SDK and OmniCoreAgent original-guide qualifications are delivered through the same public API, durable worker, parser and MinIO path. Retain the exact external provider/account and selected-image AWS evidence, then prove the broader hosted Flow contribution journey before deployment claims. |
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index f616d67dc..cf9a18a2c 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -29,8 +29,10 @@ Current finish list, in execution order:
   existing runner; fix only observed defects needed for this deployment.
 - [x] Prove the hosted contributor ZIP journey through PRE rejection, pending
   status, POST revision, same-assignment MCP correction and unpaid acceptance.
+- [x] Confirm exact aged rejected-source deletion and accepted-version retention
+  through the deployed Celery cleanup consumer. [Hosted cleanup evidence](WS-SUBMIT-001-01.md#hosted-age-eligible-source-cleanup)
 - [ ] Finish hosted failure recovery, the required-review branch, retained ZIP
-  custody, age-eligible S3 cleanup and supported upload bounds.
+  custody checks and supported upload bounds.
 - [ ] Run required final-head checks, resolve actual failures, and present PR708
   for explicit merge approval. Merge and post-merge smoke require that approval.
 - [ ] Complete post-deployment/merge verification and hand over the release.
@@ -172,8 +174,9 @@ real PRE/T4/T5/POST, exact source and Contribution/export custody, PRE/POST
 rejection and default review_pending; owned database/bucket cleanup passed.
 Live AWS source qualification passed at 074cade5e with the actual restricted
 runtime/cleanup identities, pinned versions, lost acknowledgements and exact
-cleanup. The hosted cutover and core contributor journey passed. Native
-fault/isolation, supported upload bounds, aged hosted cleanup, the hosted
+cleanup. The hosted cutover and core contributor journey passed. The deployed
+cleanup consumer deleted the age-eligible rejected S3 version and preserved both
+accepted versions. Remaining native faults, supported upload bounds, the hosted
 required-review branch and full-head qualification remain open. Ordinary
 indexed unsealed cleanup is implemented; optional absent-operation inventory is
 not a new prerequisite. Known uncertain writes stay owned and charged until
@@ -188,10 +191,9 @@ lost-abort/replay case proves conservative charge retention then one release.
 Remote initiation without a recorded handle now retains discovered IDs before
 abort and binds them to a fresh cleanup authorization. Focused PostgreSQL/MinIO
 checks cover growing observations and lost-abort replay. Empty ambiguous
-discovery remains charged; deployed cleanup qualification remains open. Real
-Redis outage recovery and Celery child redelivery are proved with unchanged
-production leases/backoff; these do not qualify broker-server loss or hosted
-operation.
+discovery remains charged. Real Redis outage recovery and Celery child
+redelivery are proved with unchanged production leases and backoff. Broker-server
+loss and hosted operation remain separate proofs.
 
 ## Acceptance evidence still to close
 
@@ -203,7 +205,7 @@ This is the final qualification queue, not a claim that all listed code is absen
 | A01–A03 | Hosted `2942dd4e7` passed PRE rejection, T4/T5, POST revision and same-assignment correction through CLI/MCP; paired replay passed. | Reconcile any remaining scope in the exact acceptance rows. |
 | A04–A08 | Metadata/body replay, competing custody, interruption and T4 uncertainty tests | Reconcile exact cases and execute integrated final-head failure/retry matrix. |
 | A09–A13 | T5 rollback/redelivery, actual local SIGKILL recovery, accepted authority, pending reads and old-POST guard | Real Redis publication outage and Celery child-redelivery proofs passed; reconcile the remaining exact cases at the final head. |
-| A14–A18 | Cleanup lock/retention/charge owners, Local/MinIO tests and live AWS exact-version/lost-ack cleanup with retained-source survival | Production worker sweeps and exact acceptance-case reconciliation. |
+| A14–A18 | Cleanup lock/retention/charge owners, Local/MinIO tests, live AWS lost-ack cleanup and deployed exact aged rejection deletion with both accepted sources preserved | Reconcile the remaining exact cases and scheduled sweep coverage. |
 | A19–A23 | Streaming/framing, safe archives, semantic identity and findings tests; local A19 496 MiB slow-provider memory/backpressure drill | Full permitted maxima and safety matrix, native/deployment scope where required. |
 | A24–A27, A29 | Source/result/fence contracts, dedicated queue tests and the real Smol project-deadline/isolation fixture passed | Reconcile remaining OOM/crash/output, uncertain-destroy and single-runner queue cases; broad saturation/load qualification is user-deferred. |
 | A30 | Managed-style public source acceptance/T5/replay and four typed cases passed at `2f7d8d95c` | Substitution proof complete in its stated scope; no paid-provider integration is selected or required. |
@@ -220,7 +222,7 @@ This is the final qualification queue, not a claim that all listed code is absen
 | C03 | Bounded upload/framing owner tests exist; the earlier 496 MiB slow-provider drill did not complete successfully. | Verify supported input size, memory/backpressure, idle/total timeout and edge limits through the deployed path. A failed near-limit upload is not a pass. |
 | C04 | Dedicated queues and single-runner PRE/background resource reservations are implemented. | Verify the configured single-runner bounds and queue independence on deployment. Multi-replica/multi-runner and broad saturation testing are user-deferred. |
 | C05 | Existing lease/retry/outbox owners have PostgreSQL and real broker/child-redelivery proof. | Reconcile exact release settings and hosted consumer/recovery behavior; reuse current owners. |
-| C06 | The 12h sweep/2h minimum age and guarded exact-version cleanup are implemented; native AWS source permissions and lost-ack reconciliation passed. | The dedicated cleanup consumer is healthy with its provisioned fixed principal. Prove exact-version deletion and bounded runtime reaping on the hosted path while preserving accepted sources. |
+| C06 | The 12h sweep/2h minimum age and guarded exact-version cleanup are implemented. The deployed cleanup consumer deleted an eligible rejected version and preserved both accepted versions. AWS source permissions and lost-ack reconciliation passed. | Reconcile bounded runtime reaping on the hosted path. |
 | C07 | Managed-style public source/T5/replay substitution and four typed cases passed at `2f7d8d95c`, recorded in `73d81da66`. | No selected paid provider and no vendor integration required for this delivery. Do not call the substitution proof live vendor qualification. |
 
 ## Spec reconciliation: bounded remaining delivery work
@@ -234,7 +236,7 @@ Existing implementation/focused proof is not the same as deployed proof.
 | --- | --- | --- |
 | Contributor reads and revision terms (A13, A32, A35; PR708 addition) | Core hosted reads passed. | The contributor verified preclaim originals and the exact pending, revision and accepted assignment through the paired clients. Reconcile the remaining authorization, full history and applicable reward-changing cases through current owners. |
 | Native failure and isolation (A24–A27) | Test execution and fixes only for demonstrated defects. | The maintained deadline/isolation fixture passed at `9fad17a04`, including destroyed VMs and normal admission restoration. Reconcile OOM/crash/output and uncertain-destroy requirements with matching maintained evidence. Valid accepted input must continue when destroy is uncertain, with capacity held. Fixture build alone closes none of these native outcomes. |
-| Upload/retention limits (A14–A23) | Remaining deployed/provider verification. | Prove supported maximum/slow upload and framing/resource bounds, including tighter project archive-limit enforcement; the actual cleanup worker must delete only eligible exact versions and preserve accepted/retained sources. Retain already-passing AWS adapter evidence rather than repeating unrelated IAM setup. |
+| Upload/retention limits (A14–A23) | Remaining deployed/provider verification. | Prove supported maximum/slow upload and framing/resource bounds, including tighter project archive-limit enforcement. The deployed exact-version cleanup preserved accepted sources. Reuse that result and the existing AWS adapter evidence. |
 | Hosted cutover (section 20, A33–A35) | **Deployment complete.** | The drained backup and 0069-to-0093 migration retained all 132 existing table counts. The repaired `2942dd4e7` API, coupled MCP and seven dedicated Celery workers are active. The installed boot unit points to the repaired source. See the [cutover evidence](WS-SUBMIT-001-01.md#hosted-schema-and-release-cutover-completed). |
 | Hosted end-to-end and recovery (A01–A18, A29 single-runner, A31–A32) | Core journey and paired replay passed. | PRE rejection, pending and revision under one assignment, MCP correction, exact replay and unpaid acceptance passed. Finish hosted failure distinction and recovery, retained-source checks, required-review guard and scoped queue independence. See the [hosted journey evidence](WS-SUBMIT-001-01.md#hosted-contributor-zip-journey-and-paired-replay-passed). |
 | Release checks and handoff | Final verification/review. | Required final-head backend/CLI/MCP/migration/security checks and actual review findings resolved; PR708 presented for explicit merge approval; post-merge/deployment smoke and accurate operational handoff. No new PR or automatic merge. |
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index fc44df9fc..b3e9e23a8 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13116,3 +13116,23 @@ retained the original PRE deadline and cancelled the expired command while
 renewal rollback was still held. The integrated `b9123afa4` has identical
 production and regression files. Both test processes exited. Hosted acceptance
 of the maximum-size archive remains pending.
+
+### Hosted age-eligible source cleanup
+
+The deployed Celery cleanup consumer processed task
+`47b58f4f-44bb-431a-927d-6696f613f321` for rejected source
+`01a21888-f356-77d3-9b5e-759fe1f31dea` after the two-hour retention minimum.
+The fixed service principal's claim and confirmation released the 373-byte
+charge to zero. Exact-version S3 HEAD confirmed the rejected version was absent
+and accepted versions 1 and 2 were present. Both accepted custody hashes matched
+the pre-cleanup snapshot, and the cleanup consumer returned to idle.
+
+The first monitor expected a plain-text Celery success message that the deployed
+structured logs omit. A read-only reconciliation matched the original task ID
+in the logs to the committed owner records, S3 observations and idle consumer.
+The reconciliation used the one original publication. Its local receipt is
+`/tmp/workstream-hosted-cleanup-reconciled.json`. The complete private receipt is
+`/var/backups/workstream/pr708-cleanup-01a21888-f356-77d3-9b5e-759fe1f31dea/reconciled-confirmed.json`
+on the API host. This proof covers exact aged rejection cleanup and accepted
+retention on the deployed release. Remaining native faults, supported maximum
+upload acceptance and final release activation still require evidence.
diff --git a/docs/roadmap_status.md b/docs/roadmap_status.md
index c4d32b980..8e585f3fa 100644
--- a/docs/roadmap_status.md
+++ b/docs/roadmap_status.md
@@ -139,10 +139,11 @@ Live AWS versioned-source permissions, cleanup and lost-acknowledgement recovery
 are qualified. The contributor CLI/MCP journey through the deployed API and Celery
 services proves PRE rejection, POST revision, same-assignment correction and unpaid acceptance.
 The separate Smol deadline/isolation fixture passes with normal admission restored.
+The deployed Celery cleanup consumer deleted the exact age-eligible rejected
+S3 version and preserved both accepted versions.
 Remaining native fault cases, supported uploads and tighter project-limit enforcement,
-source cleanup for age-eligible objects, the hosted required-review guard and final
-release checks remain open. Multiple API replicas/runners and broad load campaigns
-are user-deferred; the completed fixture does not qualify them.
+the hosted required-review guard and final release checks remain open. Multiple API
+replicas/runners and broad load campaigns are user-deferred.
 
 ## Product Goal
 
@@ -705,7 +706,7 @@ cannot be reused as post-submission review-gate evidence. See the
 | CLI binary distribution | **Release path prepared; no public release** | WS-CLI-001-44 defines four native targets, `cli-v` exact-source versioning, deterministic archives and SHA-256 manifest, pull-request native installation/API/upgrade/rollback/removal smoke, and separately gated manual GitHub Releases publication | Confirm `cli-release` environment and immutable `cli-v*` tag ruleset; approve an annotated tag and first publication, then download and independently install all public assets. First-release smoke uses a same-source prior-version stand-in, not a previous published release; signing/notarization are absent |
 | Operator artifact diagnosis | **Public API and CLI with exact Operator authority** | Eight bounded artifact GETs use current persisted system-Operator grants and exact AUTH decisions, with response-validated read commits and concealed denials. An independently guarded reasoned verification retry atomically records its decisions, recovery chain and audit; exact replay rechecks authority. The CLI consumes all nine routes, with malformed-lineage rejection and receipt-specific pagination. Signed PostgreSQL proof covers eligible retry, exact replay, wrong-resource refusal and revoked-Operator concealment. | Hosted S3 proof remains separate; diagnosis does not grant provider access or activate AWS |
 | Bulk task import | **Public backend and CLI batch journey** | PILOT-02A supplies exact source custody; PILOT-02B imports 1..500 verified JSON rows under one immutable native batch, retains per-Task AUTH/TaskCreated facts, recovers exact original IDs with fresh authority and exposes batch status; actual 200-row, rollback, concurrent-wait and SQL-custody controls pass on PostgreSQL/MinIO. PILOT-02C adds atomic whole-batch screen/release with fresh per-Task authority, locked guide/policy custody and explicit CLI/CSV commands. WS-CLI-001-31 adds bounded, hash-checked CLI source download through public custody with no-overwrite local publication. Optional task-local criteria remain optional through single/bulk screening and release; required instructions and guide locks remain enforced. | No remaining PILOT-02 implementation gate; deployment and full contributor-lifecycle proof are separate |
-| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Tighter project archive-limit enforcement remains under qualification. Contributor and manager preparation reads preserve historical evidence. | The hosted CLI/MCP journey passed preclaim guide reads, PRE rejection, pending assignment status, POST revision, same-assignment MCP correction, paired replay and unpaid final acceptance. The native project-deadline/isolation fixture also passed with VMs destroyed and normal admission restored. The hosted required-review branch, exact cleanup, remaining native fault cases and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing. See the [hosted submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md#hosted-contributor-zip-journey-and-paired-replay-passed). |
+| Contributor ZIP submission | **One raw-ZIP API for initial work and revisions** | PR #708 takes the task, assignment, explicit idempotency key and ZIP, plus optional project feedback. The backend selects and freezes the governing revision and compensation context. The CLI streams up to 500 MiB; MCP carries up to 64 MiB of raw ZIP in Base64. Tighter project archive-limit enforcement remains under qualification. Contributor and manager preparation reads preserve historical evidence. | The hosted CLI/MCP journey passed preclaim guide reads, PRE rejection, pending assignment status, POST revision, same-assignment MCP correction, paired replay and unpaid final acceptance. The native project-deadline/isolation fixture also passed with VMs destroyed and normal admission restored. The deployed Celery cleanup consumer deleted the exact aged rejected S3 version and preserved both accepted versions. The hosted required-review branch, remaining native fault cases and supported-upload qualification remain open. The user defers multiple API replicas/runners and broad scalability testing. See the [hosted submission evidence](../.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md#hosted-contributor-zip-journey-and-paired-replay-passed). |
 | Pre-submission intake checking | **Public raw-ZIP intake with durable source custody** | Bounded streaming seals one exact source before one PRE session runs the Workstream default and, on success, one approved project image. Current authorization, leases, task locks, source generations and replay fences guard T4. Bounded findings distinguish QC rejection from infrastructure failure. The remote typed adapter separates API/application services from native execution; host-specific isolation stays in the provider. | Hosted intake returned actionable PRE rejection without creating a Submission and retained the accepted T4 receipts for valid sources. The real Smol project-deadline/isolation fixture passed. Verify supported upload/project bounds and the remaining native fault/cleanup cases. Multi-replica/multi-runner scalability qualification is user-deferred until after delivery. |
 | Immutable Submission creation | **Accepted-source finalization with API/CLI/MCP progress** | T4 atomically records pending task custody, accepted receipt and outbox event. Dedicated durable T5 consumes that exact source into one Submission, retained binding and initial POST dispatch under recorded authority. The operation and Submission preserve the terms selected at admission. Source cleanup cannot delete accepted work. Real Redis publication outage and Celery child-death/redelivery preserve one graph; exact replay and rollback have scoped PostgreSQL proof. | Hosted T4/T5 produced two immutable submission versions for the same assignment. Pending and corrected acceptance reads retained their exact operation and submission identities. Verify remaining exact retained-source custody and cleanup and close the applicable acceptance matrix. Live human review remains deferred. |
 | Post-submission evaluation and governed outcome | **Selected external execution and production completion routing** | Immutable approved image bindings, Rust service/SDK and typed ART callback grants; exact verified input custody, bounded normalized JSON results and phase authority. Project-owned digest-pinned images implement project requirements inside the generic service contract; the former named terminal-benchmark continuation is retired. The shared service does not interpret project-private build plans or provide a host-side continuation. Production outbox request/completion handlers run selected images and preserve exact restart/replay. True-policy success reaches review_pending; false-policy success invokes shared authorized FinalAcceptance and atomically creates the submitter ContributionRecord and complete frozen award set. Contributor-correctable failures retain exact remediation causes; a supported public system-Operator read and explicit CLI page list expose known finalized infrastructure failures; exact public/CLI retry invokes the existing owner with fresh authority and no spent contributor round. Supported uncertain request/completion reconciliation uses at most one immutable child to verify committed facts or invoke the existing owner after proving no effect; unresolved sources and an UNKNOWN child stay held. PILOT-READ-1 extends the single external result contract with findings carrying `check_id`, `path`, `line` and the `coverage_incomplete` level, and stores each finding immutably. A coverage gap without errors never auto-accepts: under a true ReviewPolicy it reaches review_pending, otherwise it returns to the contributor as `needs_revision` (`checker_coverage_incomplete`) without spending a revision round. Each Submission records its evidence-guarded attempt outcome and decision time. Earlier local API/Celery evidence covered both policy branches, prefork recovery and later authority revocation. Current connected qualification uses real isolated Keycloak and the exact separate-runner profile; hosted identity qualification remains separate | Live human review and human-triggered contributor revision remain separate #554 work. The merged false-activation guard uses the earlier approved requirement inventory; PR #697 replaces that dependency with explicit human phase attachments and the locked ReviewPolicy guard. New false/pass effects require LIVE REV bound to the current reviewed manifest; a known pre-effect refusal retries within the existing OUTBOX budget, then dead-letters if exhausted. The full hosted interruption drill for uncertain request/completion reconciliation remains outstanding. True handoff has no REV/CON prerequisite. Project-specific image correctness, registration, approved-policy activation and qualification on the intended runtime remain separate requirements. Former named-profile experiments are historical evidence. Hosted automatic dispatch and infrastructure-failure retention were observed. The repaired image passed controlled native trials and additive deployment; the small incident-summary pilot independently proves a real negative, corrected positive and exact contribution outcome. [Garden v3](https://github.com/Flow-Research/workstream/blob/d713594ebf04a125917edb0ec981d380cf8047b4/docs/reports/garden-hosted-drill-2026-11-06.md) adds one open-PR current-head POST pass through durable workers to shared acceptance and a 100 FLOW award; its POST negative cases are controlled image evidence only. Advanced benchmark trials/model grading and broader interruption proof remain separate |
@@ -1592,7 +1593,8 @@ Delivered foundations (evidence scope stated per capability)
     -> dedicated durable T5 -> immutable Submission/binding -> POST
     -> locked true: review_pending; locked false: shared acceptance + contribution + applicable award
     -> hosted CLI/MCP contributor journey + separate Smol deadline/isolation verified
-    -> remaining native faults, upload/project limits and age-eligible source cleanup proof
+    -> exact aged rejection cleanup confirmed and both accepted versions retained
+    -> remaining native faults and upload/project limits
   verified guide originals -> explicit PM assistance OR provider-free uploaded rules
     -> unified compilation -> separate manager pre/post approvals
     -> existing activation guards (human review defaults true; approved false supported)

From 747685d310dcaf1b497b370b862006e5279e2a81 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 19:06:31 +0100
Subject: [PATCH 475/513] Align migration and PRE fixtures with archive limit
 custody

---
 .../tests/checkers/external/test_selected_pre_submit.py   | 8 +++++++-
 backend/tests/test_alembic.py                             | 5 +++--
 2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/backend/tests/checkers/external/test_selected_pre_submit.py b/backend/tests/checkers/external/test_selected_pre_submit.py
index a0e830f26..e73af5af5 100644
--- a/backend/tests/checkers/external/test_selected_pre_submit.py
+++ b/backend/tests/checkers/external/test_selected_pre_submit.py
@@ -419,6 +419,7 @@ async def test_selected_admission_binds_unchanged_work_to_current_task_rules() -
     """Bind prior content/rules before inspection, then derive unchanged input in PRE."""
     from app.modules.artifacts.api.submission_intake import SubmissionIntakeMetadata
     from app.modules.checkers.api.selected_pre_submit import derive_selected_pre_submit_default_input
+    from app.modules.projects.api.locked_policy import CanonicalJsonObject
     from tests.checkers.external.test_selected_pre_submit_coordination import (
         _source_reservation, _source_guard, _source_completed_execution,
     )
@@ -432,10 +433,11 @@ async def test_selected_admission_binds_unchanged_work_to_current_task_rules() -
         archive_sha256=original.source.raw_sha256,
         semantic_manifest_sha256=derived.manifest_sha256,
     )
+    effective_policy = CanonicalJsonObject.from_mapping({"maximum_file_size_bytes": 1_000_000})
     references = SimpleNamespace(
         project_id=original.project_id, guide_version=lineage.guide_version,
         source_snapshot_id=lineage.source_snapshot_id, source_snapshot_hash=lineage.source_snapshot_sha256,
-        effective_policy_id=lineage.effective_policy_id, effective_policy_hash=lineage.effective_policy_sha256,
+        effective_policy_id=lineage.effective_policy_id, effective_policy_hash=effective_policy.sha256,
         pre_submit_policy_id=lineage.pre_submit_policy_id, pre_submit_policy_bundle_hash=lineage.pre_submit_policy_sha256,
     )
     task = SimpleNamespace(
@@ -449,6 +451,7 @@ async def test_selected_admission_binds_unchanged_work_to_current_task_rules() -
         }),
     )
     project = SimpleNamespace(**vars(references), guide_id=lineage.guide_id,
+        effective_policy=effective_policy,
         external_checker_policies=SimpleNamespace(value=policies.model_dump_json()))
     packet = SubmissionPacketView()
     metadata = SubmissionIntakeMetadata(task_id=task.task_id, assignment_id=task.assignment_id)
@@ -469,6 +472,9 @@ async def test_selected_admission_binds_unchanged_work_to_current_task_rules() -
         runtime_profile=original.runtime_profile,
     )
     assert "semantic_manifest_body" not in reservation.admission_lineage.canonical_body()
+    assert reservation.default_context.canonical_body()["project_archive_limits"] == {
+        "maximum_file_size_bytes": 1_000_000,
+    }
     assert reservation.admission_lineage.packet_sha256 == packet.sha256
     assert reservation.admission_lineage.revision_preparation_id == task.revision_context.preparation_id
     assert reservation.admission_lineage.revision_preparation_sha256 == task.revision_context.preparation_sha256
diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py
index f33308a72..0524671c1 100644
--- a/backend/tests/test_alembic.py
+++ b/backend/tests/test_alembic.py
@@ -439,6 +439,7 @@ def test_v01_graph_has_one_root_and_head() -> None:
 
     assert [revision.revision for revision in revisions] == [
         HEAD_REVISION,
+        "0093_verified_email_observation",
         "0092_submission_feedback",
         "0091_qualified_aws_source",
         "0090_merge_direct_storage",
@@ -536,7 +537,7 @@ def test_v01_graph_has_one_root_and_head() -> None:
     assert script.get_revision("0090_merge_direct_storage").down_revision == (
         "0089_observed_upload_cleanup", "0069_remove_artifact_proof",
     )
-    assert script.get_revision(HEAD_REVISION).down_revision == "0092_submission_feedback"
+    assert script.get_revision(HEAD_REVISION).down_revision == "0093_verified_email_observation"
     assert revisions[-1].down_revision is None
     assert script.get_heads() == [HEAD_REVISION]
 
@@ -1980,7 +1981,7 @@ def test_root_upgrade_refuses_nonempty_unstamped_schema_before_product_ddl(
             "0004_task_context_authority",
             "Workstream v0.1 migrations cannot be downgraded; recreate the database",
         ),
-        (HEAD_REVISION, "Workstream v0.1 migrations cannot be downgraded; recreate the database"),
+        (HEAD_REVISION, "project archive limits migration is forward-only"),
     ],
 )
 def test_downgrade_refuses_without_mutation(

From 5394c694c23e11ebbfe3822c712906fff2f499d3 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 19:20:42 +0100
Subject: [PATCH 476/513] Record archive-limit CI fixture corrections

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md            | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index b3e9e23a8..68fb55cff 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13136,3 +13136,19 @@ The reconciliation used the one original publication. Its local receipt is
 on the API host. This proof covers exact aged rejection cleanup and accepted
 retention on the deployed release. Remaining native faults, supported maximum
 upload acceptance and final release activation still require evidence.
+
+### Archive-limit test contract corrections
+
+Backend run `45868305617` identified three test failures. The schema graph
+omitted retained parent `0093_verified_email_observation`. The downgrade test
+expected another revision's refusal message. The selected PRE revision fixture
+omitted the canonical locked effective policy now consumed at reservation.
+
+Test-only commit `3f06b9f2e` asserts the full graph and exact current parent,
+retains the exact refusal and unchanged database snapshots, and verifies the
+approved file limit in the revision's canonical PRE request. The graph and PRE
+cases passed as a focused pair. The isolated PostgreSQL downgrade case reported
+`PASSED` for the exact refusal and unchanged snapshots. Its 660-second wrapper
+cap expired before pytest finished schema teardown. The wrapper confirmed
+isolated database cleanup. The three complete CI lane reruns remain the
+release evidence for this correction.

From ca6fb7c2a52a3bd3dd8298deed6b31c44f6819a1 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 20:05:50 +0100
Subject: [PATCH 477/513] Settle known submission deadlines and return safe
 retry guidance

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 15 ++++
 .../app/api/routes/artifact_submissions.py    |  8 +-
 .../artifacts/intake/foreground_admission.py  | 29 +++++--
 .../artifacts/intake/foreground_command.py    | 17 ++--
 .../artifacts/intake/foreground_lease.py      | 34 ++++++--
 .../app/modules/artifacts/intake/progress.py  |  1 +
 .../modules/artifacts/intake/repository.py    | 38 +++++++--
 .../test_submission_foreground_command.py     | 82 ++++++++++++++++++-
 .../test_submission_intake_contracts.py       | 20 +++--
 cli/internal/api/client.go                    | 20 +++--
 cli/internal/api/submission.go                | 42 ++++++++--
 cli/internal/command/command.go               |  4 +-
 cli/tests/integration/test_submission_http.py | 27 ++++++
 cli/tests/journey/client.py                   |  2 +-
 deploy/hosted/README.md                       | 10 +++
 deploy/hosted/public.Caddyfile                |  3 +-
 docs/spec_submission_execution.md             |  1 +
 mcp_server/tests/test_task_execution.py       | 32 ++++++++
 mcp_server/workstream_mcp/http_gateway.py     | 54 ++++++++++--
 19 files changed, 377 insertions(+), 62 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 68fb55cff..a6080504f 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13152,3 +13152,18 @@ cases passed as a focused pair. The isolated PostgreSQL downgrade case reported
 cap expired before pytest finished schema teardown. The wrapper confirmed
 isolated database cleanup. The three complete CI lane reruns remain the
 release evidence for this correction.
+
+### End a known PRE timeout under the original foreground fence
+
+The hosted 500 MiB operation reached the original PRE deadline with its lease
+renewed. The native checker restarted and reclaimed its VM. The CLI stopped
+waiting at the same boundary and the expired intake held TASK until the source
+cleanup sweep. The user approved a 300-second PRE profile using the existing
+configuration. Upload and source retention keep their separate bounds.
+
+This slice updates the existing foreground lease, ART settlement and public
+submission error owners, the submission-specific CLI/MCP and proxy time bounds,
+and focused regressions. Carry the committed stage deadline in the watchdog.
+Release the task under live ownership or the exact expired-owner abandonment
+guard. Return new-key guidance only for a durably closed PRE timeout. Preserve
+caller cancellation, uncertain acceptance and dedicated source cleanup ownership.
diff --git a/backend/app/api/routes/artifact_submissions.py b/backend/app/api/routes/artifact_submissions.py
index 72c0b4268..4eb73cef0 100644
--- a/backend/app/api/routes/artifact_submissions.py
+++ b/backend/app/api/routes/artifact_submissions.py
@@ -34,6 +34,7 @@
     "submission_packet_invalid": "The submitted ZIP or request was invalid",
     "submission_archive_limit_exceeded": "The ZIP exceeds the permitted archive limits",
     "submission_upload_timeout": "The ZIP upload timed out",
+    "submission_pre_timeout": "The ZIP uploaded, but pre-submission checks timed out. No Submission was created. Retry this assignment with a new idempotency key.",
     "submission_capacity_exceeded": "Submission processing is at capacity. Try again later.",
     "submission_infrastructure_unavailable": "Submission processing is temporarily unavailable",
     "submission_outcome_unknown": "Check the original submission operation or retry with the same idempotency key",
@@ -56,6 +57,8 @@ def _failure_status(code: str) -> int:
         return 413
     if code == "submission_upload_timeout":
         return 408
+    if code == "submission_pre_timeout":
+        return 504
     if code == "submission_capacity_exceeded":
         return 429
     if code in {"submission_packet_invalid", "pre_submission_checker_failed"}:
@@ -83,6 +86,7 @@ def _failure_status(code: str) -> int:
         422: {"description": "Invalid packet or bounded pre-submission QC feedback"},
         429: {"description": "Submission capacity exhausted"},
         503: {"description": "Infrastructure unavailable or acceptance outcome unknown"},
+        504: {"description": "Pre-submission deadline expired and the operation durably ended"},
     },
 )
 async def submit_source(
@@ -103,10 +107,12 @@ async def submit_source(
         details = None
         if exc.code == "pre_submission_checker_failed":
             details = {"status": "failed", "eligible_to_submit": False, "results": exc.pre_submission_results or []}
+        elif exc.code == "submission_pre_timeout":
+            details = {"next_action": "retry_new_key_after_terminal"}
         return error_response(
             request, status_code=_failure_status(exc.code), code=exc.code,
             message=_FAILURE_MESSAGES.get(exc.code, "Submission could not be completed"),
-            details=details, retryable=exc.code in {"submission_capacity_exceeded", "submission_infrastructure_unavailable", "submission_outcome_unknown"},
+            details=details, retryable=exc.code in {"submission_capacity_exceeded", "submission_infrastructure_unavailable", "submission_outcome_unknown", "submission_pre_timeout"},
         )
     return SubmissionAcceptedResponse.model_validate(receipt)
 
diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index 55a9a1395..64562e7b7 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -21,7 +21,9 @@
 from app.modules.artifacts.api.submission_archive import MAXIMUM_SUBMISSION_ZIP_BYTES
 from app.modules.artifacts.api.submission_intake import SealedSubmissionSource, SubmissionIntakeFailure, SubmissionIntakeMetadata, SubmissionSourceCapacityLimits
 from app.modules.artifacts.api.submission_preparation import public_pre_submission_results
-from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
+from app.modules.artifacts.intake.repository import (
+    ForegroundDeadline, IntakeCustodyConflict, SubmissionIntakeRepository, clamped_foreground_deadline,
+)
 from app.modules.artifacts.intake.progress import finalization_progress
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
 from app.modules.artifacts.intake.streaming import hash_submission_replay
@@ -332,7 +334,10 @@ async def accept(
                 self._match_acceptance_command(row, request, terminal_digest, accepted=True)
                 return await self._accepted_receipt(session, authority, row)
 
-    async def finish(self, owner: IntakeReservationOwner, *, state: str, failure_code: str) -> bool:
+    async def finish(
+        self, owner: IntakeReservationOwner, *, state: str, failure_code: str,
+        deadline: ForegroundDeadline | None = None,
+    ) -> str | None:
         """End drained foreground work, retaining all physical source obligations.
 
         A committed acceptance, another generation or an expired owner cannot be
@@ -341,20 +346,22 @@ async def finish(self, owner: IntakeReservationOwner, *, state: str, failure_cod
         async with self._root() as (session, _authority):
             repository = SubmissionIntakeRepository(session, self._tasks(session))
             try:
-                await repository._owned(owner.operation_id, owner.lease_id, owner.generation)
+                row = await repository._owned(owner.operation_id, owner.lease_id, owner.generation)
             except IntakeCustodyConflict:
-                return False
+                return None
+            if deadline is not None and deadline == clamped_foreground_deadline(row):
+                failure_code = deadline.failure_code
             await repository.terminalize(
                 owner.operation_id, owner.lease_id, owner.generation,
                 state=state, failure_code=failure_code,
             )
-        return True
+        return failure_code
 
-    async def assignment_release_failure(
+    async def settle_expired_foreground(
         self, owner: IntakeReservationOwner, metadata: SubmissionIntakeMetadata, *,
         actor_id: UUID, idempotency_key: UUID,
     ) -> str | None:
-        """Resolve a release-fenced foreground owner under current read authority."""
+        """Settle exact hard expiry or observe the original assignment release."""
         async with self._root() as (session, authority):
             repository = SubmissionIntakeRepository(session, self._tasks(session))
             row = await repository._lock(owner.operation_id)
@@ -368,6 +375,11 @@ async def assignment_release_failure(
                        and row.lease_id == str(owner.lease_id)
                        and row.lease_generation == owner.generation + 1)
             code = row.failure_code if released else None
+            deadline = clamped_foreground_deadline(row)
+            if deadline is not None and await repository.abandon_expired(
+                owner.operation_id, deadline_owner=(owner.lease_id, owner.generation),
+            ):
+                code = deadline.failure_code
         return code
 
     @staticmethod
@@ -504,7 +516,8 @@ async def replay_failure(
             else:
                 code = row.failure_code if row.failure_code in {
                     "submission_packet_invalid", "submission_archive_limit_exceeded",
-                    "submission_upload_timeout", "submission_infrastructure_unavailable", "revision_deadline_expired",
+                    "submission_upload_timeout", "submission_pre_timeout",
+                    "submission_infrastructure_unavailable", "revision_deadline_expired",
                     "submission_unavailable", "revision_limit_reached", "revision_context_changed",
                     "revision_context_blocked", "task_submission_predecessor_changed",
                 } else "submission_operation_terminal"
diff --git a/backend/app/modules/artifacts/intake/foreground_command.py b/backend/app/modules/artifacts/intake/foreground_command.py
index 6fa10f181..b8d29e62c 100644
--- a/backend/app/modules/artifacts/intake/foreground_command.py
+++ b/backend/app/modules/artifacts/intake/foreground_command.py
@@ -18,7 +18,7 @@
 from app.modules.artifacts.intake.foreground_admission import (
     ForegroundIntakeAdmission, IntakeCommitUnknown, IntakeReplay, IntakeReservationOwner,
 )
-from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease
+from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeExpired, ForegroundIntakeLease
 from app.modules.artifacts.intake.foreground_upload import ForegroundSourceUpload
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict
 from app.modules.artifacts.intake.streaming import SubmissionUploadTimeout
@@ -107,6 +107,7 @@ async def run(_operation_id, _lease_id, _generation):
         except BaseException as exc:
             state = "cancelled" if isinstance(exc, asyncio.CancelledError) else "failed"
             code = "submission_cancelled" if state == "cancelled" else "submission_infrastructure_unavailable"
+            deadline = exc.deadline if isinstance(exc, ForegroundIntakeExpired) else None
             if isinstance(exc, SubmissionIntakeFailure):
                 code = exc.code
                 if code == "pre_submission_checker_failed":
@@ -124,21 +125,25 @@ async def run(_operation_id, _lease_id, _generation):
             elif isinstance(exc, SubmissionUploadTimeout):
                 code = "submission_upload_timeout"
             try:
-                finished = await await_cancellation_resistant(self._admission.finish(owner, state=state, failure_code=code))
+                finished = await await_cancellation_resistant(self._admission.finish(
+                    owner, state=state, failure_code=code, deadline=deadline,
+                ))
             except BaseException:
                 logger.exception("Submission foreground terminalization failed", extra={"operation_id": str(owner.operation_id)})
                 if not isinstance(exc, asyncio.CancelledError):
                     raise IntakeCommitUnknown("submission terminal outcome is unresolved") from None
             else:
                 if not finished and not isinstance(exc, asyncio.CancelledError):
-                    release_failure = await self._admission.assignment_release_failure(
+                    release_failure = await self._admission.settle_expired_foreground(
                         owner, metadata, actor_id=actor_id, idempotency_key=idempotency_key,
                     )
                     if release_failure is not None:
                         raise SubmissionIntakeFailure(release_failure) from None
                     raise IntakeCommitUnknown("submission foreground ownership has changed") from None
-            if isinstance(exc, SubmissionUploadTimeout):
-                raise SubmissionIntakeFailure(code) from None
+                if isinstance(exc, (SubmissionUploadTimeout, ForegroundIntakeExpired)) and finished in {
+                    "submission_upload_timeout", "submission_pre_timeout",
+                }:
+                    raise SubmissionIntakeFailure(finished) from None
             raise
 
     async def _run(self, owner: IntakeReservationOwner, chunks: AsyncIterator[bytes]) -> dict:
@@ -157,6 +162,8 @@ async def _run(self, owner: IntakeReservationOwner, chunks: AsyncIterator[bytes]
         if terminal.lease.reservation != reservation:
             raise IntakeCustodyConflict("intake_pre_result_mismatch")
         if terminal.execution is None:
+            if terminal.infrastructure_failure_code == "deadline_exceeded":
+                raise SubmissionIntakeFailure("submission_pre_timeout")
             raise SubmissionIntakeFailure("submission_infrastructure_unavailable")
         if not terminal.execution.eligible:
             raise SubmissionIntakeFailure(
diff --git a/backend/app/modules/artifacts/intake/foreground_lease.py b/backend/app/modules/artifacts/intake/foreground_lease.py
index c94ffe145..57e1dd109 100644
--- a/backend/app/modules/artifacts/intake/foreground_lease.py
+++ b/backend/app/modules/artifacts/intake/foreground_lease.py
@@ -10,12 +10,21 @@
 from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
 
 from app.core.cancellation import await_completion_preserving_cancellation
-from app.modules.artifacts.intake.repository import IntakeCustodyConflict, SubmissionIntakeRepository
+from app.modules.artifacts.intake.repository import ForegroundDeadline, IntakeCustodyConflict, SubmissionIntakeRepository
 from app.modules.tasks.api.intake_custody import IntakeTaskCustodyPort
 
 Result = TypeVar("Result")
 
 
+class ForegroundIntakeExpired(IntakeCustodyConflict):
+    """Stop an expired watchdog, retaining the last committed deadline kind."""
+
+    def __init__(self, deadline: ForegroundDeadline | None) -> None:
+        """Distinguish a committed stage cap from an ordinary rolling lease loss."""
+        super().__init__("intake_owner_renewal_expired")
+        self.deadline = deadline
+
+
 class ForegroundIntakeLease:
     """Renew the pinned owner in short transactions beside its foreground work."""
 
@@ -32,38 +41,45 @@ def __init__(
         self._duration = lease_duration
         self._interval = heartbeat_interval.total_seconds()
 
-    async def _renew(self, operation_id: UUID, lease_id: UUID, generation: int) -> float:
+    async def _renew(
+        self, operation_id: UUID, lease_id: UUID, generation: int,
+    ) -> tuple[float, ForegroundDeadline | None]:
         loop = asyncio.get_running_loop()
         started = loop.time()
         async with self._sessions.begin() as session:
-            remaining = await SubmissionIntakeRepository(session, self._tasks(session)).heartbeat(
+            remaining, hard_deadline = await SubmissionIntakeRepository(session, self._tasks(session)).heartbeat(
                 operation_id, lease_id, generation, lease_duration=self._duration,
             )
         # Conservative: includes lock wait, flush and commit response, not host wall time.
         budget = remaining - (loop.time() - started)
         if budget <= 0:
-            raise IntakeCustodyConflict("intake_owner_renewal_expired")
-        return budget
+            raise ForegroundIntakeExpired(hard_deadline)
+        return budget, hard_deadline
 
     async def run(
         self, operation_id: UUID, lease_id: UUID, generation: int,
         command_factory: Callable[[UUID, UUID, int], Coroutine[Any, Any, Result]],
     ) -> Result:
         """Invoke once after committed renewal; drain all work before returning."""
-        budget = await self._renew(operation_id, lease_id, generation)
+        budget, hard_deadline = await self._renew(operation_id, lease_id, generation)
         loop = asyncio.get_running_loop()
         watchdog = asyncio.timeout(budget)
 
         async def pulse() -> None:
+            nonlocal hard_deadline
             while True:
                 deadline = watchdog.when()
                 assert deadline is not None
                 await asyncio.sleep(min(self._interval, (deadline - loop.time()) / 2))
-                remaining = await self._renew(operation_id, lease_id, generation)
+                try:
+                    remaining, renewed_deadline = await self._renew(operation_id, lease_id, generation)
+                except ForegroundIntakeExpired as exc:
+                    raise ForegroundIntakeExpired(hard_deadline) from exc
                 renewed_at = loop.time()
                 if renewed_at >= deadline:
-                    raise IntakeCustodyConflict("intake_owner_renewal_expired")
+                    raise ForegroundIntakeExpired(hard_deadline)
                 watchdog.reschedule(renewed_at + remaining)
+                hard_deadline = renewed_deadline
 
         command = asyncio.create_task(command_factory(operation_id, lease_id, generation),
                                       name=f"submission-foreground:{operation_id}")
@@ -74,7 +90,7 @@ async def pulse() -> None:
                     await asyncio.wait((command, renewal), return_when=asyncio.FIRST_COMPLETED)
             except TimeoutError as exc:
                 if not command.done():
-                    raise IntakeCustodyConflict("intake_owner_renewal_expired") from exc
+                    raise ForegroundIntakeExpired(hard_deadline) from exc
             if command.done():
                 return command.result()
             renewal.result()
diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py
index 48c5cc1b9..505548300 100644
--- a/backend/app/modules/artifacts/intake/progress.py
+++ b/backend/app/modules/artifacts/intake/progress.py
@@ -164,6 +164,7 @@ async def read(self, task_id, selector, *, actor_id):
     def _public_failure(code):
         if code is not None and code not in {
             "submission_packet_invalid", "submission_archive_limit_exceeded", "submission_upload_timeout",
+            "submission_pre_timeout",
             "submission_infrastructure_unavailable", "pre_submission_checker_failed",
             "submission_foreground_expired", "submission_operation_cancelled", "revision_deadline_expired",
             "submission_unavailable", "revision_context_changed", "revision_context_blocked",
diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py
index f44eec60d..5dbe5380b 100644
--- a/backend/app/modules/artifacts/intake/repository.py
+++ b/backend/app/modules/artifacts/intake/repository.py
@@ -6,6 +6,7 @@
 resumed by another request or by a background PRE worker.
 """
 
+from dataclasses import dataclass
 from datetime import datetime, timedelta
 import json
 import re
@@ -37,6 +38,23 @@ class IntakeCustodyConflict(RuntimeError):
     """A private owner conflict, never a quality verdict or permission grant."""
 
 
+@dataclass(frozen=True, slots=True)
+class ForegroundDeadline:
+    """A fixed stage deadline observed on its clamped foreground lease."""
+
+    expires_at: datetime
+    failure_code: str
+
+
+def clamped_foreground_deadline(row: SubmissionIntakeOperation) -> ForegroundDeadline | None:
+    """Identify a hard stage deadline independently of an earlier rolling expiry."""
+    if row.state == "receiving" and row.lease_expires_at == row.upload_deadline_at:
+        return ForegroundDeadline(row.upload_deadline_at, "submission_upload_timeout")
+    if row.state == "pre_checking" and row.lease_expires_at == row.pre_deadline_at:
+        return ForegroundDeadline(row.lease_expires_at, "submission_pre_timeout")
+    return None
+
+
 class SubmissionIntakeRepository:
     """Persist exact source facts under TASK-first locks and a live owner fence."""
 
@@ -249,8 +267,8 @@ async def seal(self, operation_id: UUID, lease_id: UUID, generation: int,
         return self._sealed_source(row)
 
     async def heartbeat(self, operation_id: UUID, lease_id: UUID, generation: int,
-                        *, lease_duration: timedelta) -> float:
-        """Renew without shortening custody; return DB remaining seconds after flush."""
+                        *, lease_duration: timedelta) -> tuple[float, ForegroundDeadline | None]:
+        """Renew custody and report remaining time and any binding stage deadline."""
         if not isinstance(lease_duration, timedelta) or lease_duration <= timedelta(0):
             raise ValueError("foreground lease duration must be positive")
         row = await self._owned(operation_id, lease_id, generation)
@@ -260,7 +278,7 @@ async def heartbeat(self, operation_id: UUID, lease_id: UUID, generation: int,
         row.lease_expires_at = max(row.lease_expires_at, now + extension)
         await self._session.flush()
         now = await self._session.scalar(select(func.clock_timestamp()))
-        return (row.lease_expires_at - now).total_seconds()
+        return (row.lease_expires_at - now).total_seconds(), clamped_foreground_deadline(row)
 
     async def terminalize(self, operation_id: UUID, lease_id: UUID, generation: int,
                           *, state: str, failure_code: str) -> None:
@@ -304,13 +322,23 @@ async def cancel_assignment(self, operation_id: UUID, target: AssignmentInvalida
         state = "abandoned" if row.lease_expires_at <= now else "cancelled"
         await self._terminal(row, state, "submission_unavailable")
 
-    async def abandon_expired(self, operation_id: UUID) -> bool:
+    async def abandon_expired(
+        self, operation_id: UUID, *, deadline_owner: tuple[UUID, int] | None = None,
+    ) -> bool:
         """Recovery can end expired foreground custody, never resume or accept it."""
         row = await self._lock(operation_id)
         now = await self._session.scalar(select(func.clock_timestamp()))
         if row.state not in {"receiving", "pre_checking"} or row.lease_expires_at > now:
             return False
-        await self._terminal(row, "abandoned", "submission_foreground_expired")
+        code = "submission_foreground_expired"
+        if deadline_owner is not None:
+            lease_id, generation = deadline_owner
+            deadline = clamped_foreground_deadline(row)
+            if (deadline is None
+                    or row.lease_id != str(lease_id) or row.lease_generation != generation):
+                return False
+            code = deadline.failure_code
+        await self._terminal(row, "abandoned", code)
         return True
 
     async def _terminal(self, row: SubmissionIntakeOperation, state: str, code: str) -> None:
diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py
index 9153f50ea..c98d72748 100644
--- a/backend/tests/artifacts/test_submission_foreground_command.py
+++ b/backend/tests/artifacts/test_submission_foreground_command.py
@@ -53,6 +53,7 @@ async def execute(lease, grant):
 
 @pytest.mark.parametrize("outcome,framing", [
     ("completed", "small"), ("rejected", "small"),
+    ("deadline_exceeded", "small"),
     ("completed", "large-single"), ("completed", "large-split"),
 ])
 async def test_public_raw_zip_submission_uses_real_owners_and_stable_replay(admission_intake, tmp_path, monkeypatch, outcome, framing):
@@ -96,6 +97,12 @@ async def chunks():
         assert receipt["status"] == "accepted" and receipt["replayed"] is False
         assert set(receipt) == {"operation_id", "task_id", "assignment_id", "status", "accepted_at",
                                 "task_status_at_acceptance", "processing_stage_at_acceptance", "replayed", "pre_submission_results"}
+    elif outcome == "deadline_exceeded":
+        assert first.status_code == second.status_code == 504, (first.text, second.text)
+        for reply in (first, second):
+            failure = reply.json()["error"]
+            assert failure["code"] == "submission_pre_timeout" and failure["retryable"] is True
+            assert failure["details"] == {"next_action": "retry_new_key_after_terminal"}
     else:
         assert first.status_code == second.status_code == 422, (first.text, second.text)
         assert first.json()["error"]["code"] == second.json()["error"]["code"] == "pre_submission_checker_failed"
@@ -109,14 +116,18 @@ async def chunks():
                                     params={"idempotency_key": str(key)})
         assert progress.status_code == 200, progress.text
         observed = progress.json()
-        expected = "finalization_pending" if outcome == "completed" else "rejected"
+        expected = {"completed": "finalization_pending", "rejected": "rejected", "deadline_exceeded": "failed"}[outcome]
         assert observed["operation_state"] == observed["processing_stage"] == expected
-        assert observed["next_action"] == ("wait" if outcome == "completed" else "correct_and_submit_new_key")
+        assert observed["next_action"] == {
+            "completed": "wait", "rejected": "correct_and_submit_new_key", "deadline_exceeded": "retry_new_key_after_terminal",
+        }[outcome]
         assert observed["operationally_stalled"] is False
         assert observed["current_task_status"] == ("evaluation_pending" if outcome == "completed" else "in_progress")
         assert observed["submission_id"] is observed["submission_version"] is observed["evaluation_request_id"] is None
         assert observed["pre_submission_results"] == (receipt["pre_submission_results"] if outcome == "completed"
-                                                       else first.json()["error"]["details"]["results"])
+                                                       else first.json()["error"]["details"].get("results", []))
+        if outcome == "deadline_exceeded":
+            assert observed["failure_code"] == "submission_pre_timeout"
         by_id = await client.get(progress_url, headers=f.access.target.headers,
                                  params={"operation_id": observed["operation_id"]})
         assert by_id.status_code == 200 and by_id.json() == observed, by_id.text
@@ -202,6 +213,71 @@ async def stalled_body():
             assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": row.id}) == 1024
 
 
+async def test_timeout_settlement_requires_exact_expired_owner(admission_intake, tmp_path, monkeypatch):
+    """Hard upload or PRE expiry may close the exact owner and preserve source custody."""
+    from dataclasses import replace
+    from datetime import timedelta
+    from sqlalchemy import text
+    from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
+    from app.modules.artifacts.intake.foreground_admission import IntakeReservationOwner
+    from tests.artifact_store_helpers import initialize_local_store
+    from tests.artifacts.intake_acceptance_support import wait_foreground_expired
+    from tests.artifacts.test_submission_intake_custody import foreground_upload, repository
+    from tests.test_trusted_intake import _archive
+
+    f = admission_intake
+    metadata = SubmissionIntakeMetadata(task_id=f.task, assignment_id=f.assignment)
+    payload = _archive()
+    actor_id, identity_link_id = f.actor.actor_profile_id, f.actor.identity_link_id
+
+    async def body():
+        yield payload
+
+    store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
+    try:
+        for pre_timeout in (None, 60.0, 1.5):
+            key = new_record_id()
+            with monkeypatch.context() as configured:
+                if pre_timeout is None:
+                    configured.setattr(f.admission, "_upload_duration", timedelta(seconds=1.5))
+                    configured.setattr(f.admission, "_lease_duration", timedelta(seconds=1.5))
+                owner = await f.admission.admit(metadata, actor_id=actor_id, identity_link_id=identity_link_id,
+                                                 idempotency_key=key, declared_raw_bytes=len(payload))
+            if pre_timeout is not None:
+                await foreground_upload(f, store).receive(
+                    owner.operation_id, owner.lease_id, owner.generation, body(), part_bytes=5 * 1024**2,
+                    idle_timeout_seconds=10, pre_timeout_seconds=pre_timeout, pre_lease_seconds=1.5,
+                )
+            async with f.factory() as session:
+                await wait_foreground_expired(session, owner.operation_id)
+            arguments = dict(metadata=metadata, actor_id=actor_id, idempotency_key=key)
+            if pre_timeout == 60.0:
+                assert await f.admission.settle_expired_foreground(owner, **arguments) is None
+                async with f.factory.begin() as session:
+                    assert await repository(session).abandon_expired(owner.operation_id)
+                continue
+            for substitute in (replace(owner, lease_id=new_record_id()), replace(owner, generation=2)):
+                assert await f.admission.settle_expired_foreground(substitute, **arguments) is None
+            code = "submission_upload_timeout" if pre_timeout is None else "submission_pre_timeout"
+            assert await f.admission.settle_expired_foreground(owner, **arguments) == code
+            if pre_timeout is not None:
+                with pytest.raises(SubmissionIntakeFailure, match=code):
+                    await f.admission.replay_failure(operation_id=owner.operation_id, checkers=None, **arguments)
+            async with f.factory() as session:
+                row = (await session.execute(text(
+                    "SELECT state, lease_generation, failure_code FROM submission_intake_operations WHERE id=:id"
+                ), {"id": owner.operation_id})).one()
+                assert tuple(row) == ("abandoned", 2, code)
+                assert await session.scalar(text("SELECT active_submission_operation_id FROM workstream_tasks WHERE id=:id"), {"id": f.task}) is None
+                assert await session.scalar(text("SELECT accounted_bytes FROM submission_source_charges WHERE operation_id=:id"), {"id": owner.operation_id}) == len(payload)
+                assert await session.scalar(text("SELECT count(*) FROM submissions WHERE task_id=:id"), {"id": f.task}) == 0
+        retry = await f.admission.admit(metadata, actor_id=actor_id, identity_link_id=identity_link_id,
+                                         idempotency_key=new_record_id(), declared_raw_bytes=len(payload))
+        assert isinstance(retry, IntakeReservationOwner) and retry.operation_id != owner.operation_id
+    finally:
+        store.close()
+
+
 @pytest.mark.parametrize("outcome", ["completed", "received_failure", "rejected"])
 async def test_foreground_command_accepts_or_fails_and_replays_without_new_pre(admission_intake, tmp_path, outcome):
     from sqlalchemy import text
diff --git a/backend/tests/artifacts/test_submission_intake_contracts.py b/backend/tests/artifacts/test_submission_intake_contracts.py
index b7c1fed7a..ce0dc5f13 100644
--- a/backend/tests/artifacts/test_submission_intake_contracts.py
+++ b/backend/tests/artifacts/test_submission_intake_contracts.py
@@ -386,7 +386,7 @@ async def renew(*owner):
         nonlocal calls
         calls += 1
         if calls == 1:
-            return 1
+            return 1, None
         release.set()
         raise IntakeCustodyConflict("fixture_after_commit")
 
@@ -398,11 +398,13 @@ async def command(*owner):
     assert await runner.run(new_record_id(), new_record_id(), 1, command) == "committed"
 
 
-@pytest.mark.parametrize("renewed", [True, False])
-async def test_foreground_lease_uses_only_the_last_committed_deadline(monkeypatch, renewed):
+@pytest.mark.parametrize("renewed, timeout_code", [
+    (True, None), (False, None), (False, "submission_upload_timeout"), (False, "submission_pre_timeout"),
+])
+async def test_foreground_lease_uses_only_the_last_committed_deadline(monkeypatch, renewed, timeout_code):
     """Keep a renewed command alive and cancel an expired command before rollback drains."""
-    from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeLease
-    from app.modules.artifacts.intake.repository import IntakeCustodyConflict
+    from app.modules.artifacts.intake.foreground_lease import ForegroundIntakeExpired, ForegroundIntakeLease
+    from app.modules.artifacts.intake.repository import ForegroundDeadline
 
     loop = asyncio.get_running_loop()
     clock = loop.time()
@@ -414,15 +416,16 @@ async def test_foreground_lease_uses_only_the_last_committed_deadline(monkeypatc
     finish, cancelled = asyncio.Event(), asyncio.Event()
     rollback, release_rollback = asyncio.Event(), asyncio.Event()
     calls = 0
+    hard_deadline = ForegroundDeadline(datetime.now(UTC) + timedelta(seconds=60), timeout_code) if timeout_code else None
 
     async def renew(*owner):
         nonlocal calls
         calls += 1
         if calls == 1:
-            return 60
+            return 60, hard_deadline
         renewals.put_nowait(calls)
         if renewed and calls <= 4:
-            return 60
+            return 60, None
         try:
             await loop.create_future()
         finally:
@@ -457,8 +460,9 @@ async def command(*owner):
         else:
             assert cancelled.is_set() and rollback.is_set() and not running.done()
             release_rollback.set()
-            with pytest.raises(IntakeCustodyConflict, match="intake_owner_renewal_expired"):
+            with pytest.raises(ForegroundIntakeExpired, match="intake_owner_renewal_expired") as expired:
                 await running
+            assert expired.value.deadline == hard_deadline
     finally:
         release_rollback.set()
         if not running.done():
diff --git a/cli/internal/api/client.go b/cli/internal/api/client.go
index b7f271edc..c7f5dd7b3 100644
--- a/cli/internal/api/client.go
+++ b/cli/internal/api/client.go
@@ -60,11 +60,12 @@ func (f *Failure) Error() string {
 }
 
 type Client struct {
-	origin        string
-	token         string
-	http          *http.Client
-	guideHTTP     *http.Client
-	taskBatchHTTP *http.Client
+	origin         string
+	token          string
+	http           *http.Client
+	guideHTTP      *http.Client
+	submissionHTTP *http.Client
+	taskBatchHTTP  *http.Client
 }
 
 type Profile struct {
@@ -126,11 +127,18 @@ func New(origin, token string) (*Client, error) {
 	guideHTTP := *client
 	guideHTTP.Transport = guideTransport
 	guideHTTP.Timeout = 10 * time.Minute
+	// Submissions have independent five-minute upload and PRE envelopes.
+	// Keep a response margin after both and leave guide transfers unchanged.
+	submissionTransport := transport.Clone()
+	submissionTransport.ResponseHeaderTimeout = 6 * time.Minute
+	submissionHTTP := *client
+	submissionHTTP.Transport = submissionTransport
+	submissionHTTP.Timeout = 11 * time.Minute
 	// Complete 1..500-member writes include fresh per-Task authorization and one
 	// atomic commit. Keep their measured budget separate from ordinary requests.
 	taskBatchHTTP := *client
 	taskBatchHTTP.Timeout = 3 * time.Minute
-	return &Client{origin: normalized, token: token, http: client, guideHTTP: &guideHTTP, taskBatchHTTP: &taskBatchHTTP}, nil
+	return &Client{origin: normalized, token: token, http: client, guideHTTP: &guideHTTP, submissionHTTP: &submissionHTTP, taskBatchHTTP: &taskBatchHTTP}, nil
 }
 
 func validateOrigin(raw string) (string, error) {
diff --git a/cli/internal/api/submission.go b/cli/internal/api/submission.go
index 5a7678e52..986c3f8a6 100644
--- a/cli/internal/api/submission.go
+++ b/cli/internal/api/submission.go
@@ -60,12 +60,34 @@ func (p SubmissionInput) validate(task string) error {
 
 func submissionFailure(err error) error {
 	var failure *Failure
-	if errors.As(err, &failure) && failure.OutcomeUnknown {
-		failure.RecoveryHint = "Observe the submission operation using the same actor and idempotency key, or explicitly replay the same task, assignment, ZIP bytes and feedback; do not create a new key while the outcome is unknown"
+	if errors.As(err, &failure) {
+		if failure.OutcomeUnknown {
+			failure.RecoveryHint = "Observe the submission operation using the same actor and idempotency key, or explicitly replay the same task, assignment, ZIP bytes and feedback; do not create a new key while the outcome is unknown"
+		} else if failure.Status == http.StatusRequestTimeout && failure.Code == "submission_upload_timeout" {
+			failure.RecoveryHint = "The ZIP upload timed out before pre-submission checks started."
+		}
 	}
 	return err
 }
 
+func submissionPreTimeout(raw []byte, contentType string) bool {
+	if !canonicalMutationError(raw, contentType) {
+		return false
+	}
+	var envelope struct {
+		Error struct {
+			Details   json.RawMessage `json:"details"`
+			Retryable bool            `json:"retryable"`
+		} `json:"error"`
+	}
+	var details struct {
+		NextAction string `json:"next_action"`
+	}
+	return json.Unmarshal(raw, &envelope) == nil && envelope.Error.Retryable &&
+		decode(envelope.Error.Details, &details, []string{"next_action"}, nil) == nil &&
+		details.NextAction == "retry_new_key_after_terminal"
+}
+
 // SubmitSubmission streams one regular ZIP once and returns its committed acceptance snapshot.
 func (c *Client) SubmitSubmission(ctx context.Context, task, key string, input SubmissionInput, source *os.File) (Result[SubmissionReceipt], error) {
 	var result Result[SubmissionReceipt]
@@ -87,7 +109,7 @@ func (c *Client) SubmitSubmission(ctx context.Context, task, key string, input S
 	if input.Feedback != nil {
 		headers.Set("X-Submission-Feedback", *input.Feedback)
 	}
-	response, err := c.openBodyRequest(ctx, c.guideHTTP, http.MethodPost,
+	response, err := c.openBodyRequest(ctx, c.submissionHTTP, http.MethodPost,
 		"/api/v1/tasks/"+url.PathEscape(task)+"/submissions", "",
 		io.NewSectionReader(source, 0, initial.Size()), initial.Size(), key, "application/json", "application/zip", headers)
 	if err != nil {
@@ -101,9 +123,17 @@ func (c *Client) SubmitSubmission(ctx context.Context, task, key string, input S
 	}
 	if response.StatusCode != http.StatusAccepted {
 		failure := c.responseFailure(http.MethodPost, response, raw)
-		if response.StatusCode == 422 {
-			var typed *Failure
-			if errors.As(failure, &typed) && typed.Code == "pre_submission_checker_failed" {
+		var typed *Failure
+		if errors.As(failure, &typed) {
+			if response.StatusCode == http.StatusGatewayTimeout && typed.Code == "submission_pre_timeout" {
+				if !c.safeMutationResponse(raw) || !submissionPreTimeout(raw, response.Header.Get("Content-Type")) {
+					return result, submissionFailure(invalid)
+				}
+				typed.OutcomeUnknown = false
+				typed.Details = json.RawMessage(`{"next_action":"retry_new_key_after_terminal"}`)
+				typed.RecoveryHint = "The ZIP uploaded, but pre-submission checks timed out. No Submission was created. Retry this assignment with a new idempotency key."
+			}
+			if response.StatusCode == 422 && typed.Code == "pre_submission_checker_failed" {
 				if typed.OutcomeUnknown || !c.safeMutationResponse(raw) {
 					return result, submissionFailure(invalid)
 				}
diff --git a/cli/internal/command/command.go b/cli/internal/command/command.go
index f7a5b51dd..01282f4a7 100644
--- a/cli/internal/command/command.go
+++ b/cli/internal/command/command.go
@@ -264,7 +264,9 @@ func writeFailure(w io.Writer, output string, f api.Failure) {
 		return
 	}
 	_, _ = fmt.Fprintln(w, "Error:", f.Error())
-	if len(f.Details) != 0 {
+	if !f.OutcomeUnknown && f.RecoveryHint != "" {
+		_, _ = fmt.Fprintln(w, f.RecoveryHint)
+	} else if len(f.Details) != 0 {
 		_, _ = fmt.Fprintln(w, "Intake findings:", safeText(string(f.Details)))
 	}
 }
diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py
index 15a8fbb3e..536844f8a 100644
--- a/cli/tests/integration/test_submission_http.py
+++ b/cli/tests/integration/test_submission_http.py
@@ -381,6 +381,33 @@ def test_submission_feedback_is_closed_safe_and_not_a_submission(cli, tmp_path):
         assert len(requests) == 5
 
 
+def test_submission_stage_timeouts_and_unknown_gateway_response(cli, tmp_path):
+    """Expose new-key guidance only for the closed PRE timeout envelope."""
+    path = tmp_path / "source.zip"
+    path.write_bytes(b"ZIP")
+    action = {"next_action": "retry_new_key_after_terminal"}
+    envelope = {"code": "submission_pre_timeout", "message": "upstream private diagnostic",
+                "details": action, "correlation_id": RUN, "retryable": True}
+    with http_fixture() as (origin, response, requests):
+        respond(response, {"error": envelope}, 504)
+        first = cli(origin, TOKEN, *submit_args(path))
+        assert_failure(first, "submission_pre_timeout")
+        error = json.loads(first.stderr)["error"]
+        assert error["details"] == action and not error.get("outcome_unknown", False)
+        text = cli(origin, TOKEN, *submit_args(path)[:-2])
+        assert "The ZIP uploaded, but pre-submission checks timed out" in text.stderr
+        assert "No Submission was created" in text.stderr and "new idempotency key" in text.stderr
+        assert "upstream private diagnostic" not in text.stderr
+        respond(response, {"error": envelope | {"details": {}}}, 504)
+        unknown = cli(origin, TOKEN, *submit_args(path))
+        assert_failure(unknown, "invalid_api_response")
+        assert json.loads(unknown.stderr)["error"]["outcome_unknown"] is True
+        respond(response, {"error": envelope | {"code": "submission_upload_timeout", "details": {}, "retryable": False}}, 408)
+        upload = cli(origin, TOKEN, *submit_args(path)[:-2])
+        assert "The ZIP upload timed out before pre-submission checks started" in upload.stderr
+        assert len(requests) == 4
+
+
 def test_submission_history_and_findings_are_bounded_and_preserve_evidence(cli):
     with http_fixture() as (origin, response, requests):
         respond(response, HISTORY)
diff --git a/cli/tests/journey/client.py b/cli/tests/journey/client.py
index 92c7413b4..7fff3edb0 100644
--- a/cli/tests/journey/client.py
+++ b/cli/tests/journey/client.py
@@ -53,7 +53,7 @@ def call(
             cwd=self.directory,
             capture_output=True,
             text=True,
-            timeout=180,
+            timeout=675 if arguments[:2] == ("task", "submit") else 180,
             check=False,
         )
         elapsed_seconds = time.monotonic() - started
diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md
index afe84613d..2b2cb3f95 100644
--- a/deploy/hosted/README.md
+++ b/deploy/hosted/README.md
@@ -302,6 +302,16 @@ worker consuming exactly one named queue. Beat always
 receives the required cleanup profile, so the cleanup schedule cannot disappear
 because of an omitted setting.
 
+Set the PRE window in `WORKSTREAM_SUBMISSION_EXECUTION_PROFILE` at
+`runtime.aggregate_deadline_ms`. Use `300000` for five minutes and bind the same
+approved runtime profile and digest on the runner. Keep `upload_total_seconds`
+and `upload_idle_seconds` separately configured. The CLI allows 360 seconds for
+response headers and 660 seconds overall. The MCP submission tool allows 660
+seconds overall and the hosted `/mcp` proxy allows 675 seconds for headers.
+Guide transfers retain their own deadlines. If a later deployment extends the
+upload or PRE window beyond these client budgets, adjust and qualify the matching
+submission client and proxy limits together.
+
 `WORKSTREAM_ARTIFACT_PREPARATION_TOTAL_DEADLINE_SECONDS` explicitly carries the
 existing ART processing deadline to every backend role. The
 template preserves its 3,400-second default. With the unchanged ZIP inspection,
diff --git a/deploy/hosted/public.Caddyfile b/deploy/hosted/public.Caddyfile
index 6c91ed540..dae30b0d1 100644
--- a/deploy/hosted/public.Caddyfile
+++ b/deploy/hosted/public.Caddyfile
@@ -91,7 +91,8 @@
 				flush_interval -1
 				transport http {
 					dial_timeout 5s
-					response_header_timeout 180s
+					# The submission tool may spend 660s at its upstream API.
+					response_header_timeout 675s
 					max_conns_per_host 16
 				}
 			}
diff --git a/docs/spec_submission_execution.md b/docs/spec_submission_execution.md
index bbbbc1359..0e73d4955 100644
--- a/docs/spec_submission_execution.md
+++ b/docs/spec_submission_execution.md
@@ -284,6 +284,7 @@ Use the existing structured error envelope, correlation/request IDs, sanitizatio
 | 422 | `submission_packet_invalid` | Invalid task/assignment selectors, feedback or ZIP framing. |
 | 422 | `pre_submission_checker_failed` | Validated platform/project QC rejection. Include bounded actionable PRE results; `eligible_to_submit=false`; no new Submission. |
 | 408 | `submission_upload_timeout` | The client upload breached its explicit idle/total upload limit before handoff. No accepted work is implied. |
+| 504 | `submission_pre_timeout` | The ZIP sealed, PRE timed out and the foreground operation durably ended before acceptance. The actor may retry the assignment with a new key after this terminal response. The same key replays the original timeout. |
 | 429 | `submission_capacity_exceeded` | Admission or quota/rate bound prevents this request from proceeding. Include a finite retry hint where one is known. |
 | 503 | `submission_infrastructure_unavailable` | Storage/runtime/DB/protocol failure before accepted handoff; not a QC verdict. |
 | 503 | `submission_outcome_unknown` | The API cannot determine whether its acceptance commit succeeded. Client must observe/replay the same key; it must not blindly create new work. |
diff --git a/mcp_server/tests/test_task_execution.py b/mcp_server/tests/test_task_execution.py
index 87f78ec29..20eca7158 100644
--- a/mcp_server/tests/test_task_execution.py
+++ b/mcp_server/tests/test_task_execution.py
@@ -623,6 +623,38 @@ def test_operation_progress_rejects_unbound_or_noncontract_response(
     assert len(received) == 1
 
 
+@pytest.mark.parametrize("valid", [True, False])
+def test_submission_pre_timeout_requires_closed_terminal_envelope(
+    adapter: Adapter, valid: bool,
+) -> None:
+    """Forward known timeout guidance while leaving a malformed 504 uncertain."""
+    client, received, upstream = adapter
+    action = {"next_action": "retry_new_key_after_terminal"}
+    upstream["status"] = 504
+    upstream["json"] = {"error": {
+        "code": "submission_pre_timeout",
+        "message": "private runner diagnostic",
+        "details": action if valid else action | {"private": "opaque value"},
+        "correlation_id": "a92cd489-0aef-4e95-97c9-e10b4ae52b68",
+        "retryable": True,
+    }}
+    response = client.post("/mcp", headers={"authorization": "Bearer fixture-token",
+                 "accept": "application/json, text/event-stream"},
+        json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {
+            "name": "workstream_submission_create", "arguments": _arguments("submission_create")}})
+    result = response.json()["result"]
+    assert result["isError"] is True and len(received) == 1
+    error = result["structuredContent"]
+    if valid:
+        assert error["error"] == "workstream_request_failed"
+        assert error["code"] == "submission_pre_timeout" and error["details"] == action
+        assert error["retryable"] is True and "new idempotency key" in error["message"]
+    else:
+        assert error["error"] == "workstream_execution_uncertain" and error["retryable"] is False
+        assert "code" not in error and "details" not in error
+    assert "private runner diagnostic" not in response.text and "opaque value" not in response.text
+
+
 @pytest.mark.parametrize("private_message", [False, True])
 @pytest.mark.parametrize(
     ("code", "message"),
diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py
index 043faf8d5..6db950a73 100644
--- a/mcp_server/workstream_mcp/http_gateway.py
+++ b/mcp_server/workstream_mcp/http_gateway.py
@@ -40,6 +40,8 @@
     re.ASCII,
 )
 _CORRELATION_HEADERS = ("x-request-id", "x-correlation-id")
+# Upload and PRE each need up to 300s, with a separate response margin.
+_SUBMISSION_TIMEOUT_SECONDS = 660.0
 _SUBMISSION_ERROR_CODES = frozenset({
     "submission_unavailable", "submission_packet_invalid", "submission_media_type_unsupported",
     "submission_archive_limit_exceeded", "submission_upload_timeout",
@@ -1544,7 +1546,7 @@ async def task_execution_operation(
             raw_body=upload,
             content_type="application/zip" if name == "submission_create" else None,
             operation_timeout_seconds=(
-                self._settings.document_timeout_seconds
+                _SUBMISSION_TIMEOUT_SECONDS
                 if name == "submission_create"
                 else None
             ),
@@ -2232,6 +2234,12 @@ async def _request(
                     ) as response:
                         body = await self._bounded_body(response)
                         correlation_id = self._correlation_id(response, request_id)
+                        media_type = (
+                            response.headers.get("content-type", "")
+                            .split(";", 1)[0]
+                            .strip()
+                            .lower()
+                        )
                         if response.status_code != expected_status:
                             failure = self._api_failure(response.status_code, body, correlation_id)
                             # Proxy errors and unexpected successes cannot prove rollback.
@@ -2246,15 +2254,10 @@ async def _request(
                                 )
                             if submission_upload and (
                                 400 <= response.status_code < 500 or response.status_code == 503
+                                or response.status_code == 504 and media_type == "application/json"
                             ):
                                 failure = self._submission_failure(failure, body, output_validator)
                             return GatewayResult(failure=failure)
-                        media_type = (
-                            response.headers.get("content-type", "")
-                            .split(";", 1)[0]
-                            .strip()
-                            .lower()
-                        )
                         if media_type != "application/json":
                             return GatewayResult(
                                 failure=SafeFailure(
@@ -2404,14 +2407,44 @@ def _submission_failure(
         failure: SafeFailure, body: bytes, validator: Draft202012Validator,
     ) -> SafeFailure:
         """Expose only the contributor-safe error fields of the raw ZIP route."""
+        def unique_fields(pairs):
+            """Refuse duplicate fields when validating a terminal response."""
+            value = dict(pairs)
+            if len(value) != len(pairs):
+                raise ValueError("duplicate timeout response field")
+            return value
+
         try:
-            decoded = json.loads(body)
+            decoded = json.loads(
+                body, object_pairs_hook=unique_fields if failure.status == 504 else None,
+            )
             error = decoded["error"]
             if not isinstance(error, dict):
                 return failure
             code = error.get("code")
             if not isinstance(code, str):
                 return failure
+            if failure.status == 504:
+                details = {"next_action": "retry_new_key_after_terminal"}
+                fields = {"code", "message", "details", "correlation_id", "retryable"}
+                if (
+                    code != "submission_pre_timeout" or decoded.keys() != {"error"}
+                    or error.keys() != fields or not isinstance(error["message"], str)
+                    or not 0 < len(error["message"]) <= 512
+                    or not isinstance(error["correlation_id"], str)
+                    or str(UUID(error["correlation_id"])) != error["correlation_id"]
+                    or error["retryable"] is not True or error["details"] != details
+                ):
+                    return failure
+                return replace(
+                    failure, error="workstream_request_failed", code=code, retryable=True,
+                    details=details,
+                    message=(
+                        "The ZIP uploaded, but pre-submission checks timed out. "
+                        "No Submission was created. Retry this assignment with a new "
+                        "idempotency key."
+                    ),
+                )
             if failure.status == 503:
                 # Proxy errors cannot authorize reflection of upstream diagnostic text.
                 recovery = {
@@ -2426,6 +2459,11 @@ def _submission_failure(
                 return replace(failure, code=code, message=recovery) if recovery else failure
             if code not in _SUBMISSION_ERROR_CODES:
                 return failure
+            if code == "submission_upload_timeout" and failure.status == 408:
+                return replace(
+                    failure, code=code,
+                    message="The ZIP upload timed out before pre-submission checks started.",
+                )
             details = error.get("details")
             message = error.get("message")
             if not isinstance(message, str) or len(message) > 512 or not message.isprintable():

From a0e389a897c2c2c0396d23403ded0eb9c50375db Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 20:11:06 +0100
Subject: [PATCH 478/513] Recover when the database fence expires during
 terminalization

---
 .../artifacts/intake/foreground_admission.py  | 31 +++++++++++--------
 .../modules/artifacts/intake/repository.py    |  9 ++++--
 .../test_submission_foreground_command.py     | 29 +++++++++++++++--
 3 files changed, 52 insertions(+), 17 deletions(-)

diff --git a/backend/app/modules/artifacts/intake/foreground_admission.py b/backend/app/modules/artifacts/intake/foreground_admission.py
index 64562e7b7..98a2445b1 100644
--- a/backend/app/modules/artifacts/intake/foreground_admission.py
+++ b/backend/app/modules/artifacts/intake/foreground_admission.py
@@ -343,19 +343,24 @@ async def finish(
         A committed acceptance, another generation or an expired owner cannot be
         overwritten by a late request exception. Expiry remains the reaper's job.
         """
-        async with self._root() as (session, _authority):
-            repository = SubmissionIntakeRepository(session, self._tasks(session))
-            try:
-                row = await repository._owned(owner.operation_id, owner.lease_id, owner.generation)
-            except IntakeCustodyConflict:
-                return None
-            if deadline is not None and deadline == clamped_foreground_deadline(row):
-                failure_code = deadline.failure_code
-            await repository.terminalize(
-                owner.operation_id, owner.lease_id, owner.generation,
-                state=state, failure_code=failure_code,
-            )
-        return failure_code
+        try:
+            async with self._root() as (session, _authority):
+                repository = SubmissionIntakeRepository(session, self._tasks(session))
+                return await repository.terminalize(
+                    owner.operation_id, owner.lease_id, owner.generation,
+                    state=state, failure_code=failure_code, deadline=deadline,
+                )
+        except IntakeCustodyConflict as exc:
+            if str(exc) != "intake_owner_stale":
+                raise
+        except IntegrityError as exc:
+            # The lease can expire after the locked read but before the SQL
+            # trigger checks the update. The failed root is closed before recovery.
+            error = getattr(exc.orig, "__cause__", None)
+            if (getattr(exc.orig, "sqlstate", None) != "23514"
+                    or getattr(error, "message", None) != "expired intake requires abandonment"):
+                raise
+        return None
 
     async def settle_expired_foreground(
         self, owner: IntakeReservationOwner, metadata: SubmissionIntakeMetadata, *,
diff --git a/backend/app/modules/artifacts/intake/repository.py b/backend/app/modules/artifacts/intake/repository.py
index 5dbe5380b..2004090b2 100644
--- a/backend/app/modules/artifacts/intake/repository.py
+++ b/backend/app/modules/artifacts/intake/repository.py
@@ -280,13 +280,18 @@ async def heartbeat(self, operation_id: UUID, lease_id: UUID, generation: int,
         now = await self._session.scalar(select(func.clock_timestamp()))
         return (row.lease_expires_at - now).total_seconds(), clamped_foreground_deadline(row)
 
-    async def terminalize(self, operation_id: UUID, lease_id: UUID, generation: int,
-                          *, state: str, failure_code: str) -> None:
+    async def terminalize(
+        self, operation_id: UUID, lease_id: UUID, generation: int, *,
+        state: str, failure_code: str, deadline: ForegroundDeadline | None = None,
+    ) -> str:
         """Fence conclusively ended foreground work and clear only its task guard."""
         if state not in {"failed", "rejected", "cancelled"}:
             raise IntakeCustodyConflict("intake_terminal_state_invalid")
         row = await self._owned(operation_id, lease_id, generation)
+        if deadline is not None and deadline == clamped_foreground_deadline(row):
+            failure_code = deadline.failure_code
         await self._terminal(row, state, failure_code)
+        return failure_code
 
     async def expire_revision(self, operation_id: UUID, target: TaskRevisionExpiryTarget) -> None:
         """Participate only after TASK consumed expiry authority and fenced its event.
diff --git a/backend/tests/artifacts/test_submission_foreground_command.py b/backend/tests/artifacts/test_submission_foreground_command.py
index c98d72748..7dd1eb029 100644
--- a/backend/tests/artifacts/test_submission_foreground_command.py
+++ b/backend/tests/artifacts/test_submission_foreground_command.py
@@ -220,6 +220,8 @@ async def test_timeout_settlement_requires_exact_expired_owner(admission_intake,
     from sqlalchemy import text
     from app.modules.artifacts.api.submission_intake import SubmissionIntakeFailure
     from app.modules.artifacts.intake.foreground_admission import IntakeReservationOwner
+    from app.modules.artifacts.intake.models import SubmissionIntakeOperation
+    from app.modules.artifacts.intake.repository import SubmissionIntakeRepository, clamped_foreground_deadline
     from tests.artifact_store_helpers import initialize_local_store
     from tests.artifacts.intake_acceptance_support import wait_foreground_expired
     from tests.artifacts.test_submission_intake_custody import foreground_upload, repository
@@ -235,7 +237,7 @@ async def body():
 
     store = initialize_local_store(root=tmp_path / "durable", buffer_bytes=256 * 1024)
     try:
-        for pre_timeout in (None, 60.0, 1.5):
+        for pre_timeout in (None, 60.0, 5.0):
             key = new_record_id()
             with monkeypatch.context() as configured:
                 if pre_timeout is None:
@@ -246,8 +248,31 @@ async def body():
             if pre_timeout is not None:
                 await foreground_upload(f, store).receive(
                     owner.operation_id, owner.lease_id, owner.generation, body(), part_bytes=5 * 1024**2,
-                    idle_timeout_seconds=10, pre_timeout_seconds=pre_timeout, pre_lease_seconds=1.5,
+                    idle_timeout_seconds=10, pre_timeout_seconds=pre_timeout,
+                    pre_lease_seconds=1.5 if pre_timeout == 60.0 else pre_timeout,
                 )
+            if pre_timeout == 5.0:
+                async with f.factory() as session:
+                    row = await session.get(SubmissionIntakeOperation, str(owner.operation_id))
+                    hard_deadline = clamped_foreground_deadline(row)
+                assert hard_deadline is not None
+                guarded_terminalize = SubmissionIntakeRepository._terminal
+                crossed = False
+
+                async def cross_deadline(repository, row, state, code):
+                    """Advance past the database cutoff after the live fence check."""
+                    nonlocal crossed
+                    await wait_foreground_expired(repository._session, owner.operation_id)
+                    crossed = True
+                    await guarded_terminalize(repository, row, state, code)
+
+                with monkeypatch.context() as delayed:
+                    delayed.setattr(SubmissionIntakeRepository, "_terminal", cross_deadline)
+                    assert await f.admission.finish(
+                        owner, state="failed", failure_code="submission_infrastructure_unavailable",
+                        deadline=hard_deadline,
+                    ) is None
+                assert crossed
             async with f.factory() as session:
                 await wait_foreground_expired(session, owner.operation_id)
             arguments = dict(metadata=metadata, actor_id=actor_id, idempotency_key=key)

From 1222fb0d7361d4c9fd460363e1cf902d8414e170 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 20:17:10 +0100
Subject: [PATCH 479/513] docs(submission): record exact deadline settlement
 evidence

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 +++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index a6080504f..2e1e19f3b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13167,3 +13167,23 @@ and focused regressions. Carry the committed stage deadline in the watchdog.
 Release the task under live ownership or the exact expired-owner abandonment
 guard. Return new-key guidance only for a durably closed PRE timeout. Preserve
 caller cancellation, uncertain acceptance and dedicated source cleanup ownership.
+
+Independent review reproduced a deadline race between the live owner check and
+terminalization. The follow-up at `a0e389a89` handles the database's exact expired
+fence refusal after rollback, then lets the original owner attempt durable expiry
+settlement. The reviewer verified the corrected path and the closed CLI and MCP
+error projections.
+
+At `a0e389a89`, three isolated PostgreSQL tests passed in 195.55 seconds. They
+crossed the database deadline during terminalization, then proved exact-owner
+expiry settlement, source charge retention and task release. They also verified
+caller cancellation and replay of an acceptance after a lost commit response.
+The launcher exited zero and confirmed database and MinIO cleanup. The exact
+receipt is `/tmp/workstream-deadline-crossing-pg.EmS932/cleanup.json`.
+
+The preceding signed HTTP and owner tests passed two cases covering the known
+504 and retry guidance. The unchanged watchdog, built CLI and installed MCP
+boundary tests passed 11, three and two cases respectively. The CLI and MCP
+cases distinguish known PRE timeout from an uncertain response and retain the
+original upload timeout. Hosted 300-second PRE and maximum-size acceptance
+still require live qualification.

From 420d79078ec24c2582e96a558758c350aeee50c9 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 20:29:23 +0100
Subject: [PATCH 480/513] Record deployed five-minute PRE deadline and separate
 upload bounds

---
 .../initiatives/WS-SUBMIT-001/OVERVIEW.md        |  2 +-
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md            | 16 ++++++++++++++--
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
index cf9a18a2c..158b548e1 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/OVERVIEW.md
@@ -217,7 +217,7 @@ This is the final qualification queue, not a claim that all listed code is absen
 
 | Register | Current evidence | Remaining current-delivery action |
 | --- | --- | --- |
-| C01 | Connected CLI receipts observed 85.09s PRE rejection and 88.46s initial acceptance under a 120s qualification deadline; these are command durations, not isolated PRE-stage percentiles. | The hosted release uses the approved 120s PRE hard deadline, 300s upload total and 30s upload idle. Verify the HTTP envelope on the hosted path. The approximately 60s target remains unmet. |
+| C01 | Connected CLI receipts observed 85.09s PRE rejection and 88.46s initial acceptance under the earlier 120s qualification deadline; these are command durations, not isolated PRE-stage percentiles. | The hosted release now uses the user-approved 300s PRE hard deadline, starting after upload, with separate 300s upload total and 30s upload idle limits. API, runner, CLI, MCP and proxy bounds are aligned. The maximum-size hosted retry remains to be qualified. The approximately 60s target remains unmet. |
 | C02 | Exact native guest/root/image and resource profile passed the connected small-input journey. | Confirm the chosen existing-runner deployment profile against essential native isolation/failure and supported inputs. No new paid provider or hardware design. |
 | C03 | Bounded upload/framing owner tests exist; the earlier 496 MiB slow-provider drill did not complete successfully. | Verify supported input size, memory/backpressure, idle/total timeout and edge limits through the deployed path. A failed near-limit upload is not a pass. |
 | C04 | Dedicated queues and single-runner PRE/background resource reservations are implemented. | Verify the configured single-runner bounds and queue independence on deployment. Multi-replica/multi-runner and broad saturation testing are user-deferred. |
diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 2e1e19f3b..9f6edf6ee 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13185,5 +13185,17 @@ The preceding signed HTTP and owner tests passed two cases covering the known
 504 and retry guidance. The unchanged watchdog, built CLI and installed MCP
 boundary tests passed 11, three and two cases respectively. The CLI and MCP
 cases distinguish known PRE timeout from an uncertain response and retain the
-original upload timeout. Hosted 300-second PRE and maximum-size acceptance
-still require live qualification.
+original upload timeout.
+
+Runtime source `a0e389a89` is deployed with the approved 300-second PRE profile;
+upload total remains 300 seconds and upload idle remains 30 seconds. The separate
+runner's authenticated readiness matched the new profile and configuration. All
+15 hosted containers were healthy after activation, protected data and identity
+containers retained their original IDs, MCP shares the replacement API's network
+namespace, and the public `/api/v1/health` returned 200. The updated native CLI is
+installed locally and staged on the API host. The live readback receipt is
+`/tmp/workstream-pre300-live-readback.json`; the coordinated deployment and backup
+are retained under `/var/backups/workstream/pr708-pre300-a0e389a8` on the API host.
+The hosted maximum-size retry stopped before upload because the saved CLI login
+reported an uncertain prior refresh and requires interactive login recovery.
+Maximum-size acceptance is not yet claimed.

From bbe1446200cac1dba4db0731b613d97a76eb8938 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 20:53:48 +0100
Subject: [PATCH 481/513] Record hosted maximum ZIP acceptance and separate
 POST deadline failure

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 23 ++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 9f6edf6ee..2a045ff05 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13196,6 +13196,23 @@ namespace, and the public `/api/v1/health` returned 200. The updated native CLI
 installed locally and staged on the API host. The live readback receipt is
 `/tmp/workstream-pre300-live-readback.json`; the coordinated deployment and backup
 are retained under `/var/backups/workstream/pr708-pre300-a0e389a8` on the API host.
-The hosted maximum-size retry stopped before upload because the saved CLI login
-reported an uncertain prior refresh and requires interactive login recovery.
-Maximum-size acceptance is not yet claimed.
+After interactive login recovery, the exact 500 MiB source passed PRE and received
+an accepted receipt for operation `01a21960-0907-73d4-b1db-ec72fdf4dd33`, under the
+unchanged assignment `01a2191d-4ce8-7b0c-b7fc-ac35cfea7aa0`. Upload sealed in
+19.612 seconds, with a separate 299.992-second PRE window; sealed-to-acceptance
+took 237.583 seconds. The CLI exited zero after 262.133 seconds. All four
+Workstream default checks and the approved project PRE passed. Durable finalization
+created Submission `01a21964-b3fd-7721-b479-2be35410ff00`; public operation reads
+then showed POST evaluation running. The maximum-size PRE receipt and timing are
+retained under `/tmp/workstream-hosted-maximum-qualification/maximum-submit-pre300`.
+POST subsequently reported `operationally_stalled`, retaining the task in
+`evaluation_pending`. The original evaluation event dead-lettered with
+`INVOKE_OUTCOME_UNKNOWN` 150.273 seconds after the checker started. Its checker
+row retains `running`, no result and the original 210-second lease. This matches
+the separate POST execution-budget calculation (60-second materialization,
+30-second selected checker and 60-second cleanup). The exact provider phase at
+cutoff has not been established, so no selected-checker verdict or safe retry is
+claimed. Existing reconciliation holds this unresolved attempt. The read-only
+receipt is `/tmp/workstream-maximum-post-stall-readback.json`; no recovery write,
+policy change or automatic retry was performed. Maximum-size PRE acceptance and
+finalization passed; maximum-size POST acceptance remains open.

From 973a87665abe0a720df51df5a58fad8eb47662b7 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:07:03 +0100
Subject: [PATCH 482/513] Require explicit execution start after remote
 material staging

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 21 +++++
 .../app/adapters/checkers/external_service.py | 19 ++++-
 .../checkers/external/test_remote_node.py     | 81 ++++++++++++++++---
 external_checkers/remote_node.py              | 41 ++++++++++
 4 files changed, 149 insertions(+), 13 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 2a045ff05..fd483c971 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13216,3 +13216,24 @@ claimed. Existing reconciliation holds this unresolved attempt. The read-only
 receipt is `/tmp/workstream-maximum-post-stall-readback.json`; no recovery write,
 policy change or automatic retry was performed. Maximum-size PRE acceptance and
 finalization passed; maximum-size POST acceptance remains open.
+
+### Separate POST transport from execution and recover infrastructure failures
+
+The user requests explicit POST infrastructure feedback, bounded automatic retries
+before Operator escalation, and removal of the short whole-POST cutoff. The
+current remote client declares possible execution before transmitting material,
+although the remote owner only invokes native execution after staging every file.
+Replace that ambiguous handoff with an exact material-ready/start exchange. Allow
+only a confirmed start write to create execution uncertainty. Preserve uncertain
+post-start outcomes, locked checker limits, immutable results and accepted work.
+
+Allowed transport files are the existing remote checker adapter and node and
+their focused tests. No compatibility path, new queue, provider or permission
+change is authorized by this slice. Verification must prove disconnect/timeout
+before start cannot invoke native execution, failed start writes remain uncertain,
+and valid execution/callback/material cleanup still pass. Security/architecture
+review must inspect the handshake and its cancellation boundary before deployment.
+The CHECKERS retry slice must reuse current reservation, Outbox and authority
+owners with explicit service provenance; it must not fabricate an Operator actor
+or retry a running unknown invocation. Its source/result uniqueness and rollback
+remain required acceptance criteria. This is a security/workflow-risk change.
diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index 3824c8d5d..152536fd0 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -367,9 +367,6 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                         allow_nan=False,
                         separators=(",", ":"),
                     ).encode()
-                    # A failed drain can follow successful transmission. Treat
-                    # this call as possibly invoked before its first write.
-                    possibly_invoked = True
                     await self._send_frame(writer, control)
                     await self._send_frame(writer, manifest)
                     for item in files:
@@ -383,6 +380,22 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                             await await_cancellation_resistant(stream.aclose())
                         writer.write(struct.pack(">I", 0))
                         await writer.drain()
+                    ready = {
+                        "protocol_version": _REMOTE_PROTOCOL,
+                        "operation": "material_ready",
+                        "grant_id": grant.grant_id,
+                        "binding_digest": grant.binding_digest,
+                    }
+                    if json.loads(await self._read_frame(reader, 16_384)) != ready:
+                        raise ValueError("remote material readiness differs")
+                    # The remote owner cannot invoke native execution before
+                    # this explicit start. A failed drain of this write may
+                    # still follow successful transmission, so retain uncertainty.
+                    possibly_invoked = True
+                    await self._send_frame(writer, json.dumps(
+                        dict(ready, operation="start_execution"),
+                        separators=(",", ":"),
+                    ).encode())
                     while True:
                         header = json.loads(await self._read_frame(reader, 16_384))
                         if (
diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py
index 98948bc7f..ed13e14b8 100644
--- a/backend/tests/checkers/external/test_remote_node.py
+++ b/backend/tests/checkers/external/test_remote_node.py
@@ -461,8 +461,11 @@ async def native(reader, writer):
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize("fault", ["connect", "write", "eof", "invalid_result", "timeout", "cancel"])
-async def test_remote_post_failure_preserves_possible_invocation(tmp_path, monkeypatch, fault):
+@pytest.mark.parametrize("fault,started", [("connect", False)] + [
+    (fault, started) for fault in ("write", "eof", "invalid_result", "timeout", "cancel")
+    for started in (False, True)
+])
+async def test_remote_post_failure_preserves_possible_invocation(tmp_path, monkeypatch, fault, started):
     from unittest.mock import AsyncMock, Mock
 
     from app.adapters.artifacts import selected_pre_submit_source_contracts
@@ -471,7 +474,7 @@ async def test_remote_post_failure_preserves_possible_invocation(tmp_path, monke
     from app.interfaces.external_checker_execution import ExternalCheckerExecutionOutcomeUnknown
     from tests.checkers.external.support import empty_external_material_grant
     from tests.checkers.external.test_model_transport import request
-    from workstream_external_services import ExternalServiceUnavailableError
+    from workstream_external_services import ExternalServiceProtocolError, ExternalServiceUnavailableError
 
     adapter = RemoteTlsExternalCheckerAdapter(
         endpoints=fixture_runner_endpoints(),
@@ -481,13 +484,34 @@ async def test_remote_post_failure_preserves_possible_invocation(tmp_path, monke
     )
     reader = asyncio.StreamReader()
     writer = Mock(spec=asyncio.StreamWriter)
-    writer.drain = AsyncMock(side_effect=OSError if fault == "write" else None)
+    drains = 0
+
+    async def drain():
+        nonlocal drains
+        drains += 1
+        if fault == "write" and drains == (3 if started else 1):
+            raise OSError
+
+    writer.drain = AsyncMock(side_effect=drain)
     writer.wait_closed = AsyncMock()
     connect = AsyncMock(return_value=(reader, writer), side_effect=OSError if fault == "connect" else None)
     monkeypatch.setattr(adapter, "_open", connect)
     waiting = asyncio.Event()
-
-    async def interrupt_read(_size):
+    value = request()
+    grant = empty_external_material_grant(value, suffix="c")
+    if started:
+        reader.feed_data(_frame(json.dumps({
+            "protocol_version": "workstream.remote_runner.v1", "operation": "material_ready",
+            "grant_id": grant.grant_id, "binding_digest": grant.binding_digest,
+        }).encode()))
+    original_read = reader.readexactly
+    reads = 0
+
+    async def interrupt_read(size):
+        nonlocal reads
+        reads += 1
+        if started and reads <= 2:
+            return await original_read(size)
         waiting.set()
         if fault == "timeout":
             raise TimeoutError
@@ -500,16 +524,20 @@ async def interrupt_read(_size):
                                 b'"operation":"execution_result"}') + _frame(b'{}'))
     reader.feed_eof()
 
-    value = request()
     placement = RunnerPlacement(adapter._transport.endpoints.root[0], RunnerReadiness.model_validate_json(
         json.dumps(fixture_placement(value.registry.image_digest, fits_admission=True)),
     ))
     monkeypatch.setattr(RunnerTransport, "select", AsyncMock(return_value=placement))
-    task = asyncio.create_task(adapter.execute(value, empty_external_material_grant(value, suffix="c")))
+    task = asyncio.create_task(adapter.execute(value, grant))
     if fault == "cancel":
         await asyncio.wait_for(waiting.wait(), 1)
         task.cancel()
-    expected = ExternalServiceUnavailableError if fault == "connect" else ExternalCheckerExecutionOutcomeUnknown
+    expected = (
+        ExternalCheckerExecutionOutcomeUnknown if started
+        else asyncio.CancelledError if fault == "cancel"
+        else ExternalServiceProtocolError if fault == "invalid_result"
+        else ExternalServiceUnavailableError
+    )
     with pytest.raises(expected):
         await asyncio.wait_for(task, 2)
     connect.assert_awaited_once_with(placement)
@@ -543,7 +571,8 @@ async def test_remote_adapter_endpoint_invalid_explicit_root_cleans_helper_socke
 
 
 @pytest.mark.asyncio
-async def test_remote_post_stages_bound_material_and_removes_session(tmp_path: Path):
+@pytest.mark.parametrize("start_mode", ["execute", "disconnect", "wrong_binding"])
+async def test_remote_post_stages_bound_material_and_removes_session(tmp_path: Path, start_mode, capsys):
     certificates = _certificate_files(tmp_path)
     material_root = tmp_path / "materials"
     material_root.mkdir(mode=0o700)
@@ -554,8 +583,10 @@ async def test_remote_post_stages_bound_material_and_removes_session(tmp_path: P
     content = b"remote material\n"
     content_digest = "sha256:" + hashlib.sha256(content).hexdigest()
     observed = asyncio.Event()
+    invoked = asyncio.Event()
 
     async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+        invoked.set()
         request = await read_fixture_native_request(reader, writer, _placement_body())
         root = material_root / "workspaces" / grant_id
         path = root / "materials" / "submission_archive" / "work.txt"
@@ -666,6 +697,36 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) ->
         )
         writer.write(_frame(control) + _frame(manifest) + _frame(content) + struct.pack(">I", 0))
         await writer.drain()
+        ready = json.loads(await _read_frame(reader))
+        assert ready == {
+            "protocol_version": _REMOTE.PROTOCOL, "operation": "material_ready",
+            "grant_id": grant_id, "binding_digest": binding,
+        }
+        assert not invoked.is_set()
+        if start_mode == "disconnect":
+            writer.close()
+            await writer.wait_closed()
+        else:
+            start = dict(ready, operation="start_execution")
+            if start_mode == "wrong_binding":
+                start["binding_digest"] = "sha256:" + "0" * 64
+            writer.write(_frame(json.dumps(start).encode()))
+            await writer.drain()
+        if start_mode != "execute":
+            if start_mode == "wrong_binding":
+                assert await asyncio.wait_for(reader.read(), 2) == b""
+                writer.close()
+                await writer.wait_closed()
+            for _ in range(100):
+                if not list((material_root / "workspaces").iterdir()):
+                    break
+                await asyncio.sleep(0.01)
+            assert not invoked.is_set()
+            assert list((material_root / "workspaces").iterdir()) == []
+            records = [json.loads(line) for line in capsys.readouterr().err.splitlines()]
+            assert any(row["stage"] == "awaiting_execution_start" and row["disposition"] == "interrupted" for row in records)
+            assert records[-1]["stage"] == "material_cleanup"
+            return
         callback_header = json.loads(await _read_frame(reader))
         assert callback_header["operation"] == "callback_request"
         assert await _read_frame(reader) == b'{"protocol_version":"workstream.setup_model_proxy.v1"}'
diff --git a/external_checkers/remote_node.py b/external_checkers/remote_node.py
index 7ffe4e12d..7608a94e1 100644
--- a/external_checkers/remote_node.py
+++ b/external_checkers/remote_node.py
@@ -14,6 +14,8 @@
 import ssl
 import stat
 import struct
+import sys
+import time
 from typing import Any
 import uuid
 
@@ -624,6 +626,24 @@ async def _stage_and_execute(
         if target.exists():
             raise ProtocolError("grant is already active")
         incoming.mkdir(mode=0o700)
+        started = time.monotonic()
+        transferred = 0
+        stage = "material_transfer"
+
+        def record(event: str, **facts: Any) -> None:
+            # Only owner-generated stages, validated grant identity and counters;
+            # never material paths, contents, credentials or exception messages.
+            try:
+                print(json.dumps({
+                    "event": "checker_remote_stage", "grant_id": grant_id,
+                    "stage": stage, "disposition": event,
+                    "elapsed_ms": round((time.monotonic() - started) * 1000),
+                    "transferred_bytes": transferred, **facts,
+                }, separators=(",", ":")), file=sys.stderr, flush=True)
+            except (OSError, ValueError):
+                pass  # Diagnostic output never changes execution or cleanup custody.
+
+        record("started", expected_bytes=sum(item[1] for item in files))
         try:
             _mkdir_inventory(incoming, manifest)
             for relative, expected_count, expected_digest, executable in files:
@@ -638,6 +658,7 @@ async def _stage_and_execute(
                             raise ProtocolError("material file is too large")
                         digest.update(chunk)
                         _write_descriptor(descriptor, chunk)
+                        transferred += len(chunk)
                     if count != expected_count or "sha256:" + digest.hexdigest() != expected_digest:
                         raise ProtocolError("material file content differs")
                     os.fsync(descriptor)
@@ -654,6 +675,18 @@ async def _stage_and_execute(
             _seal_directories(incoming)
             os.chmod(incoming, 0o700, follow_symlinks=False)
             os.rename(incoming, target)
+            record("completed")
+            stage = "awaiting_execution_start"
+            ready = {
+                "protocol_version": PROTOCOL, "operation": "material_ready",
+                "grant_id": grant_id, "binding_digest": manifest["binding_digest"],
+            }
+            await _write_frame(writer, json.dumps(ready, separators=(",", ":")).encode())
+            start = _decode_object(await _read_frame(reader, 16_384))
+            if start != dict(ready, operation="start_execution"):
+                raise ProtocolError("execution start binding differs")
+            stage = "native_execution"
+            record("started")
             native_reader, native_writer = await asyncio.open_unix_connection(self.socket_path)
             encoded = json.dumps(
                 request, ensure_ascii=False, allow_nan=False, separators=(",", ":")
@@ -673,7 +706,13 @@ async def _stage_and_execute(
             if disconnect_task in done:
                 raise ProtocolError("remote client disconnected")
             response = await response_task
+            record("completed")
+            stage = "result_delivery"
             await channel.result(response)
+            record("completed")
+        except BaseException as exc:
+            record("interrupted", error_type=type(exc).__name__)
+            raise
         finally:
             for task in wait_tasks:
                 if not task.done():
@@ -691,6 +730,8 @@ async def _stage_and_execute(
                     pass
             _remove_tree(target)
             _remove_tree(incoming)
+            stage = "material_cleanup"
+            record("completed")
 
 
 async def _main(config_path: Path) -> None:

From 5c5fc73c6b7c32b6f97bf7cb5c85803086dcb87a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:13:56 +0100
Subject: [PATCH 483/513] Reject checker execution peers without explicit start
 confirmation

---
 .../app/adapters/checkers/external_service.py |  1 +
 .../checkers/external/test_remote_node.py     | 33 ++++++++++++++++++-
 external_checkers/remote_node.py              |  4 ++-
 3 files changed, 36 insertions(+), 2 deletions(-)

diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index 152536fd0..06ab66b15 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -357,6 +357,7 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                             "protocol_version": _REMOTE_PROTOCOL,
                             "operation": "execute",
                             "capability": EXTERNAL_CHECKER_CAPABILITY_KEY,
+                            "start_confirmation_required": True,
                             "service_request": json.loads(payload),
                             "manifest_byte_count": len(manifest),
                             "file_count": len(files),
diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py
index ed13e14b8..01026be92 100644
--- a/backend/tests/checkers/external/test_remote_node.py
+++ b/backend/tests/checkers/external/test_remote_node.py
@@ -545,6 +545,7 @@ async def interrupt_read(size):
         writer.write.assert_not_called()
     else:
         control = json.loads(writer.write.call_args_list[0].args[0][4:])
+        assert control["start_confirmation_required"] is True
         assert control["service_request"]["request"]["request_digest"] == value.request_digest
         writer.close.assert_called_once_with()
         writer.wait_closed.assert_awaited_once_with()
@@ -571,7 +572,9 @@ async def test_remote_adapter_endpoint_invalid_explicit_root_cleans_helper_socke
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize("start_mode", ["execute", "disconnect", "wrong_binding"])
+@pytest.mark.parametrize("start_mode", [
+    "execute", "disconnect", "wrong_binding", "missing_confirmation", "false_confirmation", "old_node",
+])
 async def test_remote_post_stages_bound_material_and_removes_session(tmp_path: Path, start_mode, capsys):
     certificates = _certificate_files(tmp_path)
     material_root = tmp_path / "materials"
@@ -621,6 +624,18 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) ->
             "session_timeout_seconds": 10,
         }
     )
+    if start_mode == "old_node":
+        # The preceding deployed protocol rejects unknown control fields before
+        # staging or native invocation. This is a refusal proof, not a fallback.
+        async def old_execute(control, _reader, _writer):
+            old_keys = {
+                "protocol_version", "operation", "capability", "service_request",
+                "manifest_byte_count", "file_count", "total_byte_count", "epoch", "config_sha256",
+            }
+            if set(control) != old_keys:
+                raise _REMOTE.ProtocolError("execute request is invalid")
+            invoked.set()
+        node._execute = old_execute
     await node.start_model_proxy()
     server = await asyncio.start_server(
         node.handle, "127.0.0.1", 0, ssl=node.ssl_context,
@@ -682,6 +697,7 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) ->
             "protocol_version": _REMOTE.PROTOCOL,
             "operation": "execute",
             "capability": _REMOTE.CHECKER_CAPABILITY,
+            "start_confirmation_required": True,
             "service_request": service_request,
             "manifest_byte_count": len(manifest),
             "file_count": 1,
@@ -691,12 +707,27 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) ->
         separators=(",", ":"),
     ).encode()
 
+    if start_mode in {"missing_confirmation", "false_confirmation"}:
+        changed = json.loads(control)
+        if start_mode == "missing_confirmation":
+            del changed["start_confirmation_required"]
+        else:
+            changed["start_confirmation_required"] = False
+        control = json.dumps(changed).encode()
+
     try:
         reader, writer = await asyncio.open_connection(
             "127.0.0.1", port, ssl=client_context, server_hostname="runner.test"
         )
         writer.write(_frame(control) + _frame(manifest) + _frame(content) + struct.pack(">I", 0))
         await writer.drain()
+        if start_mode in {"missing_confirmation", "false_confirmation", "old_node"}:
+            assert await asyncio.wait_for(reader.read(), 2) == b""
+            writer.close()
+            await writer.wait_closed()
+            assert not invoked.is_set()
+            assert list((material_root / "workspaces").iterdir()) == []
+            return
         ready = json.loads(await _read_frame(reader))
         assert ready == {
             "protocol_version": _REMOTE.PROTOCOL, "operation": "material_ready",
diff --git a/external_checkers/remote_node.py b/external_checkers/remote_node.py
index 7608a94e1..5920aa3e5 100644
--- a/external_checkers/remote_node.py
+++ b/external_checkers/remote_node.py
@@ -556,8 +556,10 @@ async def _execute(
         expected = {
             "protocol_version", "operation", "capability", "service_request",
             "manifest_byte_count", "file_count", "total_byte_count", "epoch", "config_sha256",
+            "start_confirmation_required",
         }
-        if set(control) != expected or type(control["service_request"]) is not dict:
+        if (set(control) != expected or type(control["service_request"]) is not dict
+                or control["start_confirmation_required"] is not True):
             raise ProtocolError("execute request is invalid")
         binding_frame = _epoch_binding(control)
         request = control["service_request"]

From 4812b6d84e67d4678c987b9059ac1603f9d5b02e Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:13:57 +0100
Subject: [PATCH 484/513] Remove the short aggregate POST timer and align
 recovery worker bounds

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 +++++++++++++++
 backend/app/adapters/outbox/__init__.py       | 10 +++++---
 backend/app/modules/checkers/execution.py     | 18 +++++++------
 .../checkers/execution/test_execution.py      | 25 +++++++++++++++++++
 4 files changed, 62 insertions(+), 11 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index fd483c971..be5b78f15 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13237,3 +13237,23 @@ The CHECKERS retry slice must reuse current reservation, Outbox and authority
 owners with explicit service provenance; it must not fabricate an Operator actor
 or retry a running unknown invocation. Its source/result uniqueness and rollback
 remain required acceptance criteria. This is a security/workflow-risk change.
+
+The required start-confirmation control field makes the preceding strict runner
+reject the new request before execution; the new runner rejects absent or false
+confirmation requirements. This closes the mixed-release ambiguity identified
+by independent review without retaining an old execution path. All 34 focused
+remote transport cases passed, including old-admission refusal, missing/false
+flags, disconnect before start, incorrect binding, post-start uncertainty,
+callbacks and workspace cleanup. Diagnostics contain validated grant identifiers,
+byte counts, stage names and elapsed time, never artifact contents or file names.
+
+The background-time slice also permits changes to the existing CHECKERS executor,
+Outbox event options and execution regression. Remove CHECKERS' nominal aggregate
+timer; retain ART's separately configured processing guard and each approved
+checker's execution limit. Reserve the existing durable worker envelope rather
+than the nominal 60-second material estimate, and give an Operator reconciliation
+execution the same delivery envelope as an original POST. The existing 3,400-second
+ART ceiling, 3,520-second handler and 3,600-second delivery bounds remain explicit
+operational limits; this slice does not claim unbounded execution or renewable
+leases. A real PostgreSQL regression must prove successful material preparation
+beyond the nominal estimate while stale workers remain fenced after takeover.
diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py
index 2185aecc1..e7a793fab 100644
--- a/backend/app/adapters/outbox/__init__.py
+++ b/backend/app/adapters/outbox/__init__.py
@@ -194,14 +194,16 @@ def production_outbox_delivery(
     registry = HandlerRegistry(entries, replay_safe=frozenset(
         (kind, version) for kind, version, _handler in entries if (kind, version) in replay_safe
     ))
+    post_options = DeliveryOptions(
+        lease_seconds=SELECTED_POST_DELIVERY_LEASE_SECONDS,
+        handler_timeout_seconds=SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
+    )
     event_options = {
         ("SubmissionFinalizationRequested", 1): finalization_options,
         (FINALIZATION_RECOVERY_EVENT, 1): finalization_options,
         feedback_key: feedback_options,
-        (REQUEST_EVENT, 1): DeliveryOptions(
-            lease_seconds=SELECTED_POST_DELIVERY_LEASE_SECONDS,
-            handler_timeout_seconds=SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
-        ),
+        (REQUEST_EVENT, 1): post_options,
+        (RECONCILIATION_EVENT, 1): post_options,
     }
     return outbox_delivery(
         session_factory, authorization_factory=outbox_dispatch_authorization,
diff --git a/backend/app/modules/checkers/execution.py b/backend/app/modules/checkers/execution.py
index 92ff62ff0..2b8e533e7 100644
--- a/backend/app/modules/checkers/execution.py
+++ b/backend/app/modules/checkers/execution.py
@@ -1,6 +1,5 @@
 """One async post-submit execution path over reserved CHECKERS custody."""
 
-import asyncio
 import json
 import math
 from dataclasses import asdict
@@ -33,6 +32,7 @@
 from app.modules.checkers.api.external import PostSubmitExternalCheckerIdentity
 from app.modules.checkers.api.evaluation_context import PostSubmitInputContextCustody
 from app.modules.checkers.api.external_policy import (
+    MAXIMUM_SELECTED_POST_EXECUTION_BUDGET_MS,
     SELECTED_POST_FINALIZATION_MARGIN_MS,
     selected_post_submit_execution_budget_ms,
 )
@@ -162,7 +162,9 @@ def __init__(
 
     @staticmethod
     def _execution_budget_seconds(request: PostSubmissionExecutionRequest) -> int:
-        return math.ceil(selected_post_submit_execution_budget_ms(request.policy) / 1000)
+        """Reserve the durable worker envelope, not a short whole-POST cutoff."""
+        selected_post_submit_execution_budget_ms(request.policy)
+        return math.ceil(MAXIMUM_SELECTED_POST_EXECUTION_BUDGET_MS / 1000)
 
     def _consumer(self, request, lease):
         if self._selected_execution is None:
@@ -237,11 +239,13 @@ async def evaluate_post_submission(
         input_materialization_evidence_id = None
         input_context_custody = None
         try:
-            async with asyncio.timeout(self._execution_budget_seconds(request)):
-                materialized = await self._materialization.materialize(
-                    ExecuteFacts(request=request, lease=lease),
-                    self._consumer(request, lease),
-                )
+            # ART owns material/transport bounds; each registered checker owns
+            # its execution limit. Their foreground estimate is not a deadline
+            # for this background workflow.
+            materialized = await self._materialization.materialize(
+                ExecuteFacts(request=request, lease=lease),
+                self._consumer(request, lease),
+            )
             material = VerifiedMaterialFacts(
                 **{
                     k: v
diff --git a/backend/tests/checkers/execution/test_execution.py b/backend/tests/checkers/execution/test_execution.py
index 85759f5e1..2ce6b4896 100644
--- a/backend/tests/checkers/execution/test_execution.py
+++ b/backend/tests/checkers/execution/test_execution.py
@@ -38,6 +38,31 @@ async def test_missing_checker_principal_denies_before_access(tmp_path, isolated
         assert h.store.opens == [] and not h.preparation._active
 
 
+async def test_background_materialization_can_exceed_nominal_post_estimate(
+    tmp_path, isolated_database_env, monkeypatch,
+):
+    """Useful material work must not expire at the old estimated whole-run cap."""
+    import asyncio
+    import app.modules.checkers.execution as execution
+
+    async with material_fixture(tmp_path, isolated_database_env) as h:
+        await reserve(h)
+        materialize = h.service.materialize
+
+        async def slower_materialization(*args, **kwargs):
+            await asyncio.sleep(1.1)
+            return await materialize(*args, **kwargs)
+
+        monkeypatch.setattr(execution, "selected_post_submit_execution_budget_ms", lambda _policy: 1000)
+        monkeypatch.setattr(h.service, "materialize", slower_materialization)
+        result = await live_executor(h).evaluate_post_submission(h.request)
+        assert result.outcome == "completed"
+        async with h.factory() as session:
+            run = await session.get(CheckerRun, str(result.attempt_id))
+            assert run.status == "completed" and run.failure_code is None
+            assert run.worker_lease_expires_at > run.completed_at
+
+
 @pytest.mark.parametrize("provider", ["local", "minio"])
 async def test_verified_material_execution_and_replay(
     tmp_path, isolated_database_env, provider, autoflush_clock, monkeypatch

From 2c3c60d4c89d980530aa191f794e862d40e3698f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:05:56 +0100
Subject: [PATCH 485/513] Show verified POST infrastructure failures and
 Operator action

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 42 +++++++++++++++++++
 backend/app/api/deps/contributor_reads.py     |  7 +++-
 .../artifacts/api/submission_command.py       |  2 +-
 .../app/modules/artifacts/intake/progress.py  | 22 ++++++----
 backend/app/modules/checkers/api/execution.py |  5 ++-
 .../checkers/api/selected_post_submit.py      | 17 ++++----
 .../checkers/execution_coordination.py        |  7 +++-
 .../test_submission_intake_progress.py        | 19 +++++++--
 cli/internal/api/contributor_reads.go         |  2 +-
 cli/internal/api/submission_progress.go       |  2 +-
 cli/internal/api/submission_progress_test.go  |  9 +++-
 cli/internal/command/submission.go            | 28 ++++++++++++-
 docs/spec_submission_execution.md             |  7 ++++
 .../contracts/submission_operation_get.json   |  3 +-
 mcp_server/contracts/task_assignment_get.json |  1 +
 15 files changed, 142 insertions(+), 31 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index be5b78f15..abada6bfd 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13257,3 +13257,45 @@ ART ceiling, 3,520-second handler and 3,600-second delivery bounds remain explic
 operational limits; this slice does not claim unbounded execution or renewable
 leases. A real PostgreSQL regression must prove successful material preparation
 beyond the nominal estimate while stale workers remain fenced after takeover.
+
+### Explain held POST infrastructure outcomes
+
+The supported maximum ZIP reached immutable Submission and POST dispatch. Its
+POST delivery stopped with uncertain execution, while contributor reads showed
+only a stalled operation. A verified terminal POST failure and an uncertain
+execution require distinct feedback and the existing Operator recovery paths.
+
+This workflow-sensitive slice covers the CHECKERS execution progress contract,
+ART intake progress, the contributor assignment read, CLI submission status and
+its decoders, the two affected MCP read contracts, the submission execution
+specification and focused progress tests. Reuse the current authorized snapshot
+and the existing failure/action fields. Surface closed codes and an explicit
+Operator action while keeping the current Submission and governed task state.
+Preserve original PRE feedback, active recovery, and normal completed routing.
+Do not add delivery authority or change runtime deadlines in this slice.
+
+Verify signed operation and assignment reads for known terminal infrastructure
+failure and their clearing after the existing Operator schedules recovery.
+Exercise uncertain delivery projection and run focused CLI and MCP contract
+checks. Independent workflow and authorization review should check exact scoped
+source evidence and recovery guidance. Human review should verify that the
+contributor is never instructed to upload the ZIP again for a POST failure.
+
+The retry slice extends the existing CHECKERS finalization and reservation owners
+and their delivery composition. Extend checker-run custody with the exact
+scheduled OUTBOX event, and extend the existing deferred failed-supersession
+check in a forward migration. The service trigger uses the original fixed
+checker finalization decision. It does not create a human retry receipt. Reuse
+existing delivery options for the five-attempt allowance and exponential delay,
+and dispatch the successor through the same POST queue. The retry event, new
+checker generation and current pointer share the source result transaction.
+
+Allowed additional changes are the CHECKERS executor, coordination, retry and
+model files and public execution contract, their adapter wiring, the shared
+OUTBOX delay helper, the 0095 migration and affected schema expectations, and
+focused POST execution and progress tests. Retain the human Operator path and
+existing eligibility, invocation, immutable result and review guards. A running
+or uncertain invocation does not qualify for a successor. Verify one exact
+backoff event after a known failure, replay or rollback behavior, bounded
+exhaustion, and the contributor's attempt numbers and recovery action. Workflow
+and authorization review should examine the transaction and SQL guard together.
diff --git a/backend/app/api/deps/contributor_reads.py b/backend/app/api/deps/contributor_reads.py
index 46fc515fe..5a0c1e8d7 100644
--- a/backend/app/api/deps/contributor_reads.py
+++ b/backend/app/api/deps/contributor_reads.py
@@ -159,7 +159,9 @@ class ExactContributorAssignment(BaseModel):
     assignment: ContributorAssignment
     current_status: TaskStatus | Literal["closed", "rejected"]
     status_reason: str | None
-    next_action: Literal["submit", "awaiting_intake", "awaiting_evaluation", "revise", "wait_for_processing", "none"]
+    next_action: Literal[
+        "submit", "awaiting_intake", "awaiting_evaluation", "revise", "wait_for_processing", "contact_operator", "none",
+    ]
     intake: AssignmentIntakeAttempt | None
     feedback_submission_id: UUID | None
     post_submission_results: tuple[ContributorCheckerResult, ...] = Field(max_length=100)
@@ -347,6 +349,9 @@ def _assignment_status(assignment, intake, history):
             raise ValueError("active assignment is missing its task state")
         if intake is not None and intake.stage in {"receiving", "pre_checking"}:
             return status, "submission_in_progress", "awaiting_intake"
+        if (status == "evaluation_pending" and intake is not None and intake.operationally_stalled
+                and intake.failure_code is not None and intake.failure_code.startswith("post_submission_")):
+            return status, intake.failure_code, "contact_operator"
         if (intake is not None and intake.operationally_stalled
                 or status == "evaluation_pending" and history is not None and history.status == "infrastructure_failed"):
             return status, "processing_unavailable", "wait_for_processing"
diff --git a/backend/app/modules/artifacts/api/submission_command.py b/backend/app/modules/artifacts/api/submission_command.py
index 091f84d19..ee9c63390 100644
--- a/backend/app/modules/artifacts/api/submission_command.py
+++ b/backend/app/modules/artifacts/api/submission_command.py
@@ -174,7 +174,7 @@ class SubmissionOperationResponse(BaseModel):
     operationally_stalled: bool
     next_action: Literal[
         "wait", "correct_and_submit_new_key", "retry_new_key_after_terminal",
-        "inspect_governed_outcome",
+        "inspect_governed_outcome", "contact_operator",
     ]
 
 
diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py
index 505548300..70839ed6d 100644
--- a/backend/app/modules/artifacts/intake/progress.py
+++ b/backend/app/modules/artifacts/intake/progress.py
@@ -143,12 +143,14 @@ async def read(self, task_id, selector, *, actor_id):
         else:
             results = await self._feedback(row, repository)
         action = "wait"
-        stage, stalled, submission_id, version, request_id = await self._attempt_progress(row)
+        stage, stalled, submission_id, version, request_id, failure_code = await self._attempt_progress(row)
         if row.state in {"rejected", "failed", "abandoned", "cancelled"}:
             action = "inspect_governed_outcome"
             if row.state != "cancelled" and await self._permits_new_intake(current.candidate):
                 action = "correct_and_submit_new_key" if row.state == "rejected" else "retry_new_key_after_terminal"
-        elif row.state == "finalized" and stage not in {"evaluation_pending", "evaluation_running", "operationally_stalled"}:
+        elif row.state == "finalized" and stalled:
+            action = "contact_operator"
+        elif row.state == "finalized" and stage not in {"evaluation_pending", "evaluation_running"}:
             action = "inspect_governed_outcome"
         return SubmissionOperationResponse(
             operation_id=UUID(row.id), task_id=task_id, assignment_id=UUID(row.assignment_id),
@@ -157,7 +159,7 @@ async def read(self, task_id, selector, *, actor_id):
             task_status_at_acceptance="evaluation_pending" if accepted else None,
             current_task_status=current.current_task_status, submission_id=submission_id,
             submission_version=version, evaluation_request_id=request_id,
-            pre_submission_results=results, failure_code=self._public_failure(row.failure_code), operationally_stalled=stalled, next_action=action,
+            pre_submission_results=results, failure_code=failure_code, operationally_stalled=stalled, next_action=action,
         )
 
     @staticmethod
@@ -176,6 +178,7 @@ def _public_failure(code):
     async def _attempt_progress(self, row):
         stage, stalled = row.state, False
         submission_id = version = request_id = None
+        failure_code = self._public_failure(row.failure_code)
         task_id = UUID(row.task_id)
         if row.state == "finalization_pending":
             progress = await finalization_progress(row, self._events, self._deliveries)
@@ -201,10 +204,15 @@ async def _attempt_progress(self, row):
                 event_id = evaluation.completion_event_id or evaluation.retry_event_id or outcome.evaluation_event_id
                 event = OutboxAppendInput.model_validate_json(evaluation.delivery_event_json or outcome.evaluation_event_json)
                 delivery = await evaluation_delivery_progress(event_id, event, evaluation, self._events, self._deliveries)
-                stalled = evaluation.status == "infrastructure_failed" or delivery.state == "dead_letter"
+                if evaluation.failure_code is not None:
+                    failure_code = f"post_submission_{evaluation.failure_code}"
+                elif delivery.state == "dead_letter":
+                    failure_code = ("post_submission_outcome_unknown" if delivery.error_code == "INVOKE_OUTCOME_UNKNOWN"
+                                    else "post_submission_delivery_failed")
+                stalled = failure_code is not None
                 stage = ("operationally_stalled" if stalled else
                          "evaluation_running" if evaluation.live_worker_lease else "evaluation_pending")
-        return stage, stalled, submission_id, version, request_id
+        return stage, stalled, submission_id, version, request_id, failure_code
 
     async def read_assignment_attempt(self, query):
         """Read one assignment-scoped operation and the original PRE projection."""
@@ -233,9 +241,9 @@ async def read_assignment_attempt(self, query):
             else:
                 repository = SubmissionIntakeRepository(self._session, self._tasks)
                 results = await self._feedback(row, repository)
-            stage, stalled, submission_id, _, _ = await self._attempt_progress(row)
+            stage, stalled, submission_id, _, _, failure_code = await self._attempt_progress(row)
             return AssignmentIntakeAttempt(
-                operation_id=UUID(row.id), stage=stage, failure_code=self._public_failure(row.failure_code),
+                operation_id=UUID(row.id), stage=stage, failure_code=failure_code,
                 submission_id=submission_id, pre_submission_results=results,
                 operationally_stalled=stalled or row.failure_code == "submission_infrastructure_unavailable",
             )
diff --git a/backend/app/modules/checkers/api/execution.py b/backend/app/modules/checkers/api/execution.py
index c521bc8ea..d1abf44bd 100644
--- a/backend/app/modules/checkers/api/execution.py
+++ b/backend/app/modules/checkers/api/execution.py
@@ -15,7 +15,9 @@
     PostSubmissionExecutionRequest,
     PostSubmissionExecutionResult,
 )
-from app.modules.checkers.api.selected_post_submit import SelectedPostSubmitCurrentResultReference
+from app.modules.checkers.api.selected_post_submit import (
+    PostSubmissionInfrastructureFailureCode, SelectedPostSubmitCurrentResultReference,
+)
 from app.modules.checkers.api.evaluation_context import (
     PostSubmitInputContextCustody, validate_input_context_custody,
 )
@@ -345,6 +347,7 @@ class EvaluationProgress(CheckerValue):
     current: ReservedEvaluation
     status: Literal["queued", "running", "completed", "infrastructure_failed"]
     live_worker_lease: bool
+    failure_code: PostSubmissionInfrastructureFailureCode | None
     retry_event_id: ResourceId | None
     completion_event_id: ResourceId | None
     delivery_event_json: str | None
diff --git a/backend/app/modules/checkers/api/selected_post_submit.py b/backend/app/modules/checkers/api/selected_post_submit.py
index dd9d82211..6f962b1a5 100644
--- a/backend/app/modules/checkers/api/selected_post_submit.py
+++ b/backend/app/modules/checkers/api/selected_post_submit.py
@@ -269,6 +269,12 @@ def result_digest(self) -> str:
         return canonical_json_hash(self.canonical_body())
 
 
+PostSubmissionInfrastructureFailureCode = Literal[
+    "capacity_exceeded", "deadline_exceeded", "material_unavailable",
+    "implementation_unavailable", "invalid_output",
+]
+
+
 class SelectedPostSubmissionEvaluationResult(CheckerValue):
     """Durable selected POST evidence envelope with no acceptance authority."""
 
@@ -283,16 +289,7 @@ class SelectedPostSubmissionEvaluationResult(CheckerValue):
     result_digest: Sha256
     outcome: Literal["completed", "infrastructure_failed"]
     execution: SelectedPostSubmitExecutionFacts | None
-    infrastructure_failure_code: (
-        Literal[
-            "capacity_exceeded",
-            "deadline_exceeded",
-            "material_unavailable",
-            "implementation_unavailable",
-            "invalid_output",
-        ]
-        | None
-    ) = None
+    infrastructure_failure_code: PostSubmissionInfrastructureFailureCode | None = None
 
     @model_validator(mode="after")
     def validate_result(self) -> Self:
diff --git a/backend/app/modules/checkers/execution_coordination.py b/backend/app/modules/checkers/execution_coordination.py
index 34b779e62..851e77f4d 100644
--- a/backend/app/modules/checkers/execution_coordination.py
+++ b/backend/app/modules/checkers/execution_coordination.py
@@ -241,12 +241,15 @@ async def read_current_progress(
                 **expected.model_dump(exclude={"payload_json", "payload_digest"}),
                 project_id=project_id, payload=json.loads(expected.payload_json),
             )
+        failure_code = None
         terminal = run.status in {"completed", "infrastructure_failed"}
         if terminal:
             result = stored_result(run)
             if (result.outcome != run.status or run.finalize_evidence_id is None
-                    or (run.status == "completed") != (run.completion_event_id is not None)):
+                    or (run.status == "completed") != (run.completion_event_id is not None)
+                    or run.failure_code != result.infrastructure_failure_code):
                 raise CheckerExecutionUnavailable(unavailable)
+            failure_code = result.infrastructure_failure_code
             if run.status == "completed":
                 if run.execute_evidence_id is None:
                     raise CheckerExecutionUnavailable(unavailable)
@@ -263,7 +266,7 @@ async def read_current_progress(
                 and run.worker_lease_generation > 0 and run.worker_lease_expires_at is not None
                 and run.worker_lease_expires_at > now)
         return EvaluationProgress(
-            current=current, status=run.status, live_worker_lease=live,
+            current=current, status=run.status, live_worker_lease=live, failure_code=failure_code,
             retry_event_id=retry_event_id, completion_event_id=run.completion_event_id,
             delivery_event_json=delivery_event.model_dump_json() if delivery_event is not None else None,
         )
diff --git a/backend/tests/artifacts/test_submission_intake_progress.py b/backend/tests/artifacts/test_submission_intake_progress.py
index f2a6af745..beaefbf4b 100644
--- a/backend/tests/artifacts/test_submission_intake_progress.py
+++ b/backend/tests/artifacts/test_submission_intake_progress.py
@@ -158,7 +158,7 @@ def submissions(session):
         assert await finalizer.run(owner.operation_id) == result
         assert await f.admission.accept(owner, request, terminal.terminal_digest,
             checkers=selected_pre_submit_coordinator, outbox=outbox_append) == dict(accepted, replayed=True)
-        async def public_progress(stage, evaluation_request_id, *, stalled=False, governed=False):
+        async def public_progress(stage, evaluation_request_id, *, stalled=False, governed=False, failure_code=None):
             response = await f.access.signed.client.get(
                 f"/api/v1/tasks/{f.task}/submission-operations", headers=f.access.target.headers,
                 params={"operation_id": str(owner.operation_id)},
@@ -171,7 +171,19 @@ async def public_progress(stage, evaluation_request_id, *, stalled=False, govern
             assert observed["evaluation_request_id"] == str(evaluation_request_id)
             assert observed["processing_stage"] == stage
             assert observed["operationally_stalled"] is stalled
-            assert observed["next_action"] == ("inspect_governed_outcome" if governed else "wait")
+            action = "contact_operator" if stalled else "inspect_governed_outcome" if governed else "wait"
+            assert observed["next_action"] == action
+            assert observed["failure_code"] == failure_code
+            if not governed:
+                assignment = await f.access.signed.client.get(
+                    f"/api/v1/actors/me/assignments/{request.assignment_id}", headers=f.access.target.headers,
+                )
+                assert assignment.status_code == 200, assignment.text
+                current = assignment.json()
+                assert current["current_status"] == "evaluation_pending"
+                assert current["intake"]["submission_id"] == str(result.submission_id)
+                assert current["intake"]["failure_code"] == current["status_reason"] == failure_code
+                assert current["next_action"] == ("contact_operator" if stalled else "awaiting_evaluation")
             return observed
 
         await public_progress("evaluation_pending", result.evaluation_request_id)
@@ -212,7 +224,8 @@ def missing_source(*_args, **_kwargs):
                 )
                 assert pending_completion.state == "pending"
         await public_progress("operationally_stalled" if post_failure else "evaluation_pending",
-                              result.evaluation_request_id, stalled=post_failure)
+                              result.evaluation_request_id, stalled=post_failure,
+                              failure_code="post_submission_material_unavailable" if post_failure else None)
         if post_failure:
             harness = SimpleNamespace(factory=f.factory, request=queued.current.request, created=result)
             operator = await _operator_for(harness)
diff --git a/cli/internal/api/contributor_reads.go b/cli/internal/api/contributor_reads.go
index 0b573cfdb..bfe0c0233 100644
--- a/cli/internal/api/contributor_reads.go
+++ b/cli/internal/api/contributor_reads.go
@@ -359,7 +359,7 @@ func (c *Client) TaskAssignment(ctx context.Context, assignment string, limit in
 	if err != nil || !requiredNullable(fields, "status_reason", "intake", "feedback_submission_id", "next_cursor", "accepted_evidence") ||
 		!c.safeMutationResponse(raw) || !validOptionalID(value.FeedbackSubmissionID) ||
 		!oneOf(value.CurrentStatus, append(append([]string{}, taskStatuses...), "closed", "rejected")...) ||
-		!oneOf(value.NextAction, "submit", "awaiting_intake", "awaiting_evaluation", "revise", "wait_for_processing", "none") ||
+		!oneOf(value.NextAction, "submit", "awaiting_intake", "awaiting_evaluation", "revise", "wait_for_processing", "contact_operator", "none") ||
 		len(value.PostFindings) > limit || !validateContributorFindings(fields["post_submission_results"], value.PostFindings) ||
 		(value.NextCursor != nil && (!validTaskCursor(*value.NextCursor) || len(value.PostFindings) == 0)) {
 		return result, &Failure{Code: "invalid_api_response"}
diff --git a/cli/internal/api/submission_progress.go b/cli/internal/api/submission_progress.go
index 3ce6d644c..3eef1872e 100644
--- a/cli/internal/api/submission_progress.go
+++ b/cli/internal/api/submission_progress.go
@@ -38,7 +38,7 @@ func decodeSubmissionProgress(raw json.RawMessage, task, operation, key string)
 		(operation != "" && !sameUUID(value.OperationID, operation)) || (key != "" && !sameUUID(value.IdempotencyKey, key)) ||
 		!oneOf(value.State, "receiving", "pre_checking", "finalization_pending", "finalized", "rejected", "failed", "abandoned", "cancelled") ||
 		!oneOf(value.Stage, "receiving", "pre_checking", "finalization_pending", "evaluation_pending", "evaluation_running", "review_pending", "needs_revision", "accepted", "rejected", "failed", "abandoned", "cancelled", "operationally_stalled") ||
-		!oneOf(value.NextAction, "wait", "correct_and_submit_new_key", "retry_new_key_after_terminal", "inspect_governed_outcome") ||
+		!oneOf(value.NextAction, "wait", "correct_and_submit_new_key", "retry_new_key_after_terminal", "inspect_governed_outcome", "contact_operator") ||
 		(value.AcceptedAt != nil && !validTime(*value.AcceptedAt)) ||
 		(value.TaskStatusAtAcceptance != nil && *value.TaskStatusAtAcceptance != "evaluation_pending") ||
 		(value.CurrentTaskStatus != nil && !oneOf(*value.CurrentTaskStatus, "draft", "screening", "ready", "in_progress", "submitted", "evaluation_pending", "review_pending", "needs_revision", "accepted")) ||
diff --git a/cli/internal/api/submission_progress_test.go b/cli/internal/api/submission_progress_test.go
index 95a8b9b6d..9dbcbbd2c 100644
--- a/cli/internal/api/submission_progress_test.go
+++ b/cli/internal/api/submission_progress_test.go
@@ -77,10 +77,15 @@ func TestSubmissionProgressRefusesUnboundOrMalformedEvidence(t *testing.T) {
 		value["submission_version"] = 2
 		value["evaluation_request_id"] = testSubmission
 		value["operationally_stalled"] = stage == "operationally_stalled"
-		value["next_action"] = "inspect_governed_outcome"
+		action := "inspect_governed_outcome"
+		if stage == "operationally_stalled" {
+			action = "contact_operator"
+			value["failure_code"] = "post_submission_outcome_unknown"
+		}
+		value["next_action"] = action
 		raw, _ := json.Marshal(value)
 		got, err := decodeSubmissionProgress(raw, testTask, testRun, "")
-		if err != nil || got.Stage != stage || got.NextAction != "inspect_governed_outcome" {
+		if err != nil || got.Stage != stage || got.NextAction != action {
 			t.Fatal(stage, err)
 		}
 	}
diff --git a/cli/internal/command/submission.go b/cli/internal/command/submission.go
index 60e4a5b5b..fa43b61a7 100644
--- a/cli/internal/command/submission.go
+++ b/cli/internal/command/submission.go
@@ -9,6 +9,25 @@ import (
 	"github.com/spf13/cobra"
 )
 
+func postSubmissionRecovery(code *string) string {
+	if code == nil {
+		return ""
+	}
+	message := map[string]string{
+		"post_submission_capacity_exceeded":          "POST could not acquire enough checker capacity.",
+		"post_submission_deadline_exceeded":          "POST evaluation timed out.",
+		"post_submission_material_unavailable":       "POST could not read the retained submission material.",
+		"post_submission_implementation_unavailable": "The POST checker runtime is unavailable.",
+		"post_submission_invalid_output":             "The POST checker returned an invalid response.",
+		"post_submission_delivery_failed":            "The worker could not finish POST processing.",
+		"post_submission_outcome_unknown":            "The POST execution outcome is uncertain.",
+	}[*code]
+	if message == "" {
+		return ""
+	}
+	return message + " Your Submission is retained. Contact an Operator for recovery."
+}
+
 func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client, error), output *string, stdout io.Writer) {
 	{
 		var assignment, feedback, path, key string
@@ -86,6 +105,9 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 				{"Terms", value.Assignment.Compensation}, {"Revision", value.Assignment.Revision},
 				{"Latest submitted attempt", value.Assignment.LatestSubmission},
 			}
+			if value.NextAction == "contact_operator" {
+				fields = append(fields, contextField{"Evaluation recovery", postSubmissionRecovery(value.StatusReason)})
+			}
 			if value.Intake != nil {
 				fields = append(fields, contextField{"Intake stage", value.Intake.Stage},
 					contextField{"Intake feedback", api.IntakeFeedbackLines(value.Intake.Feedback)})
@@ -125,7 +147,11 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 			if *output == "json" {
 				return writeSafeJSON(stdout, result.Raw)
 			}
-			return writeTaskContextFields(stdout, []contextField{{"Submission operation", result.Value}})
+			fields := []contextField{{"Submission operation", result.Value}}
+			if result.Value.NextAction == "contact_operator" {
+				fields = append(fields, contextField{"Evaluation recovery", postSubmissionRecovery(result.Value.FailureCode)})
+			}
+			return writeTaskContextFields(stdout, fields)
 		}
 		task.AddCommand(progress)
 	}
diff --git a/docs/spec_submission_execution.md b/docs/spec_submission_execution.md
index 0e73d4955..5d1722b1c 100644
--- a/docs/spec_submission_execution.md
+++ b/docs/spec_submission_execution.md
@@ -289,6 +289,13 @@ Use the existing structured error envelope, correlation/request IDs, sanitizatio
 | 503 | `submission_infrastructure_unavailable` | Storage/runtime/DB/protocol failure before accepted handoff; not a QC verdict. |
 | 503 | `submission_outcome_unknown` | The API cannot determine whether its acceptance commit succeeded. Client must observe/replay the same key; it must not blindly create new work. |
 
+A finalized Submission remains retained when POST encounters an infrastructure
+failure. Its operation and assignment reads expose the verified
+`post_submission_*` failure code, distinct from PRE and work findings.
+`post_submission_outcome_unknown` identifies an uncertain delivery without a
+verified terminal result. A held POST exposes `contact_operator`. The Operator
+checks the source in the existing terminal retry or uncertain delivery surface.
+
 A platform-safe-archive rejection is QC feedback. A transport object mismatch, untrusted runtime response, unavailable provider, Celery worker failure or expired execution deadline is infrastructure failure unless an existing approved checker contract explicitly identifies a completed deterministic QC result.
 
 For an operation that reached a complete raw identity, persist the original terminal response classification and bounded findings for exact replay. Do not persist secrets or raw attacker-controlled logs in public error details.
diff --git a/mcp_server/contracts/submission_operation_get.json b/mcp_server/contracts/submission_operation_get.json
index 110c53a43..b887bccf7 100644
--- a/mcp_server/contracts/submission_operation_get.json
+++ b/mcp_server/contracts/submission_operation_get.json
@@ -354,7 +354,8 @@
               "wait",
               "correct_and_submit_new_key",
               "retry_new_key_after_terminal",
-              "inspect_governed_outcome"
+              "inspect_governed_outcome",
+              "contact_operator"
             ],
             "title": "Next Action",
             "type": "string"
diff --git a/mcp_server/contracts/task_assignment_get.json b/mcp_server/contracts/task_assignment_get.json
index 8401b7a80..ccf05b2c4 100644
--- a/mcp_server/contracts/task_assignment_get.json
+++ b/mcp_server/contracts/task_assignment_get.json
@@ -884,6 +884,7 @@
               "awaiting_evaluation",
               "revise",
               "wait_for_processing",
+              "contact_operator",
               "none"
             ],
             "title": "Next Action",

From 57ca86e2163826d1a89adff4aa1704dbb620eef9 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:14:26 +0100
Subject: [PATCH 486/513] Schedule bounded delayed POST retries from known
 terminal custody

---
 backend/alembic/env.py                        |   3 +-
 .../0095_post_infrastructure_retry.py         |  85 ++++++++++++
 backend/app/adapters/checkers/__init__.py     |   7 +-
 backend/app/api/deps/contributor_reads.py     |   3 +-
 .../artifacts/api/submission_command.py       |  11 ++
 .../app/modules/artifacts/intake/progress.py  |  21 ++-
 backend/app/modules/checkers/api/execution.py |   4 +
 backend/app/modules/checkers/checker_retry.py |  60 +++++---
 backend/app/modules/checkers/execution.py     |   8 +-
 .../checkers/execution_coordination.py        | 129 ++++++++++++++----
 backend/app/modules/checkers/models.py        |   7 +
 backend/app/modules/outbox/api.py             |   4 +
 backend/app/modules/outbox/delivery.py        |  10 +-
 .../checkers/execution/test_checker_retry.py  |   6 +
 .../evaluation_delivery/test_delivery.py      |  68 +++++++++
 backend/tests/test_alembic.py                 |   5 +-
 .../tests/test_checker_evidence_migrations.py |  14 +-
 cli/internal/api/contributor_reads.go         |  16 ++-
 cli/internal/api/submission_progress.go       |  53 ++++---
 cli/internal/api/submission_progress_test.go  |   2 +-
 cli/internal/command/submission.go            |  20 ++-
 cli/tests/integration/test_submission_http.py |   1 +
 .../contracts/submission_operation_get.json   |  48 ++++++-
 mcp_server/contracts/task_assignment_get.json |  50 ++++++-
 mcp_server/tests/test_task_execution.py       |   1 +
 25 files changed, 532 insertions(+), 104 deletions(-)
 create mode 100644 backend/alembic/versions/0095_post_infrastructure_retry.py

diff --git a/backend/alembic/env.py b/backend/alembic/env.py
index 88ff603f9..d176a1f0d 100644
--- a/backend/alembic/env.py
+++ b/backend/alembic/env.py
@@ -21,7 +21,7 @@
 target_metadata = Base.metadata
 
 _BASELINE_REVISION = "0001_uuid7_v01"
-_CURRENT_HEAD_REVISION = "0094_project_archive_limits"
+_CURRENT_HEAD_REVISION = "0095_post_infrastructure_retry"
 _RECREATE_GUIDANCE = (
     "Workstream v0.1 requires a fresh database; recreate this database before "
     "running the 0001_uuid7_v01 migration"
@@ -149,6 +149,7 @@ def do_run_migrations(connection: Connection) -> None:
             ("0091_qualified_aws_source",),
             ("0092_submission_feedback",),
             ("0093_verified_email_observation",),
+            ("0094_project_archive_limits",),
             (_CURRENT_HEAD_REVISION,),
         ):
             raise RuntimeError(_RECREATE_GUIDANCE)
diff --git a/backend/alembic/versions/0095_post_infrastructure_retry.py b/backend/alembic/versions/0095_post_infrastructure_retry.py
new file mode 100644
index 000000000..7e39e96fa
--- /dev/null
+++ b/backend/alembic/versions/0095_post_infrastructure_retry.py
@@ -0,0 +1,85 @@
+"""Bind one scheduled POST successor to a known service-finalized failure."""
+
+from alembic import op
+import sqlalchemy as sa
+
+revision = "0095_post_infrastructure_retry"
+down_revision = "0094_project_archive_limits"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+    """Extend the failed-supersession guard with an exact automatic source."""
+    op.add_column("checker_runs", sa.Column("automatic_retry_event_id", sa.Uuid(), nullable=True))
+    op.create_unique_constraint(
+        "uq_checker_runs_automatic_retry_event_id", "checker_runs", ["automatic_retry_event_id"],
+    )
+    op.create_foreign_key(
+        "fk_checker_runs_automatic_retry_event", "checker_runs", "outbox_events",
+        ["automatic_retry_event_id"], ["event_id"],
+    )
+    op.create_check_constraint(
+        op.f("ck_checker_runs_automatic_retry_scope"), "checker_runs",
+        "automatic_retry_event_id IS NULL OR (supersedes_checker_run_id IS NOT NULL "
+        "AND evaluation_generation BETWEEN 2 AND 5)",
+    )
+    op.execute("""
+    CREATE OR REPLACE FUNCTION public.require_checker_failed_supersession_receipt() RETURNS trigger
+    LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+    DECLARE prior public.checker_runs%ROWTYPE; successor public.checker_runs%ROWTYPE; receipt_id uuid;
+    BEGIN
+      IF TG_OP <> 'UPDATE' THEN RETURN NULL; END IF;
+      SELECT * INTO prior FROM public.checker_runs WHERE id=OLD.current_run_id;
+      SELECT * INTO successor FROM public.checker_runs WHERE id=NEW.current_run_id;
+      IF successor.automatic_retry_event_id IS NOT NULL THEN
+        IF prior.status IS DISTINCT FROM 'infrastructure_failed'
+          OR prior.completed_at IS NULL OR prior.completion_event_id IS NOT NULL
+          OR prior.routing_recommendation IS DISTINCT FROM 'not_evaluated'
+          OR prior.failure_code IS NULL OR prior.failure_code NOT IN ('capacity_exceeded','deadline_exceeded',
+              'material_unavailable','implementation_unavailable','invalid_output')
+          OR prior.evaluation_generation NOT BETWEEN 1 AND 4
+          OR successor.supersedes_checker_run_id IS DISTINCT FROM prior.id
+          OR successor.evaluation_generation IS DISTINCT FROM prior.evaluation_generation+1
+          OR successor.request_json::jsonb - ARRAY['evaluation_request_id','evaluation_generation']
+               IS DISTINCT FROM prior.request_json::jsonb - ARRAY['evaluation_request_id','evaluation_generation']
+          OR NOT public.checker_post_submit_receipt_valid(prior,'finalize',false)
+          OR NOT EXISTS (
+            SELECT 1 FROM public.outbox_events e
+            WHERE e.event_id=successor.automatic_retry_event_id
+              AND e.event_type='PostSubmissionEvaluationRequested' AND e.event_version=1
+              AND e.producer='workstream' AND e.aggregate_type='submission'
+              AND e.project_id=successor.project_id AND e.aggregate_id=successor.submission_id
+              AND e.correlation_id=prior.id::text AND e.causation_event_id IS NULL
+              AND e.idempotency_key='checker-auto-retry:'||prior.id::text
+              AND e.delivery_state='pending'
+              AND e.not_before_at=prior.completed_at + CASE prior.evaluation_generation
+                WHEN 1 THEN interval '5 seconds' WHEN 2 THEN interval '10 seconds'
+                WHEN 3 THEN interval '20 seconds' WHEN 4 THEN interval '40 seconds' END
+              AND e.payload::jsonb=jsonb_build_object(
+                'project_id',successor.project_id,'task_id',successor.task_id,
+                'submission_id',successor.submission_id,'submission_version',successor.submission_version,
+                'request_id',successor.evaluation_request_id,'request_digest',successor.request_digest,
+                'evaluation_generation',successor.evaluation_generation,'attempt_id',successor.id,
+                'result_id',successor.result_id,'source_run_id',prior.id,
+                'source_result_digest',prior.result_digest,'source_finalize_evidence_id',prior.finalize_evidence_id
+              )
+          ) THEN
+          RAISE EXCEPTION 'automatic checker retry requires exact terminal service custody' USING ERRCODE='23514';
+        END IF;
+        RETURN NULL;
+      END IF;
+      IF prior.status IS DISTINCT FROM 'infrastructure_failed' THEN RETURN NULL; END IF;
+      SELECT id INTO receipt_id FROM public.checker_retry_receipts
+        WHERE source_run_id=OLD.current_run_id AND successor_run_id=NEW.current_run_id;
+      IF receipt_id IS NULL OR NOT public.checker_retry_receipt_valid(receipt_id) THEN
+        RAISE EXCEPTION 'terminal checker infrastructure retry requires Operator receipt' USING ERRCODE='23514';
+      END IF;
+      RETURN NULL;
+    END $$
+    """)
+
+
+def downgrade() -> None:
+    """Keep scheduled successor references valid for their retained runs."""
+    raise RuntimeError("POST infrastructure retry migration is forward-only")
diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py
index 24d075c62..56e8ffe95 100644
--- a/backend/app/adapters/checkers/__init__.py
+++ b/backend/app/adapters/checkers/__init__.py
@@ -323,8 +323,9 @@ def evaluation_coordinator(session) -> EvaluationCoordinationPort:
     """Compose required TASK locking before CHECKERS reservation custody."""
     from app.modules.checkers.execution_coordination import EvaluationCoordinator
     from app.adapters.tasks import evaluation_task_guard
+    from app.adapters.outbox import outbox_append
 
-    return EvaluationCoordinator(session, tasks=evaluation_task_guard(session))
+    return EvaluationCoordinator(session, tasks=evaluation_task_guard(session), events=outbox_append(session))
 
 
 def checker_retry_service(session, context, *, cursor_secret=None):
@@ -345,7 +346,7 @@ def checker_retry_service(session, context, *, cursor_secret=None):
         session,
         actor_profile_id=context.actor_profile_id,
         tasks=tasks,
-        evaluations=EvaluationCoordinator(session, tasks=tasks),
+        evaluations=EvaluationCoordinator(session, tasks=tasks, events=outbox_append(session)),
         authorization=checker_retry_authorization(session, context),
         discovery=checker_retry_discovery_authorization(
             session,
@@ -563,6 +564,7 @@ def authority(session):
         forge_facts=forge_facts,
         outbox=outbox_append,
         review_modes=project_locked_policy_context_port,
+        retry_tasks=evaluation_task_guard,
     )
 
 
@@ -628,6 +630,7 @@ async def validate_cause():
         forge_facts=forge_facts,
         outbox=outbox_append,
         review_modes=project_locked_policy_context_port,
+        retry_tasks=evaluation_task_guard,
     )
 
 
diff --git a/backend/app/api/deps/contributor_reads.py b/backend/app/api/deps/contributor_reads.py
index 5a0c1e8d7..7e83e0a1d 100644
--- a/backend/app/api/deps/contributor_reads.py
+++ b/backend/app/api/deps/contributor_reads.py
@@ -356,7 +356,8 @@ def _assignment_status(assignment, intake, history):
                 or status == "evaluation_pending" and history is not None and history.status == "infrastructure_failed"):
             return status, "processing_unavailable", "wait_for_processing"
         if status in {"submitted", "evaluation_pending", "review_pending"}:
-            return status, None, "awaiting_evaluation"
+            reason = intake.failure_code if intake is not None and intake.post_submission_progress is not None else None
+            return status, reason, "awaiting_evaluation"
         reason = intake.failure_code if intake is not None else None
         if reason is None and status == "needs_revision" and assignment.revision is not None:
             reason = (latest.status_reason if latest is not None else None) if assignment.revision.disposition == "ready" else assignment.revision.disposition
diff --git a/backend/app/modules/artifacts/api/submission_command.py b/backend/app/modules/artifacts/api/submission_command.py
index ee9c63390..ca406c1d7 100644
--- a/backend/app/modules/artifacts/api/submission_command.py
+++ b/backend/app/modules/artifacts/api/submission_command.py
@@ -106,6 +106,15 @@ class AssignmentIntakeUnavailable(RuntimeError):
     """Exact owned custody could not be projected."""
 
 
+class PostSubmissionProgress(BaseModel):
+    """Current checker attempt and the due time of a scheduled retry."""
+
+    model_config = ConfigDict(extra="forbid", frozen=True)
+    attempt: Annotated[int, Field(strict=True, gt=0)]
+    automatic_attempt_limit: Annotated[int, Field(strict=True, gt=0)]
+    next_attempt_at: AwareDatetime | None
+
+
 class AssignmentIntakeAttempt(BaseModel):
     """Retained intake activity and its safe feedback for one assignment."""
 
@@ -116,6 +125,7 @@ class AssignmentIntakeAttempt(BaseModel):
     submission_id: UUID | None
     pre_submission_results: PreSubmissionResults
     operationally_stalled: bool
+    post_submission_progress: PostSubmissionProgress | None
 
 
 @dataclass(frozen=True, slots=True)
@@ -172,6 +182,7 @@ class SubmissionOperationResponse(BaseModel):
     pre_submission_results: PreSubmissionResults
     failure_code: str | None
     operationally_stalled: bool
+    post_submission_progress: PostSubmissionProgress | None
     next_action: Literal[
         "wait", "correct_and_submit_new_key", "retry_new_key_after_terminal",
         "inspect_governed_outcome", "contact_operator",
diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py
index 70839ed6d..0e4c1c902 100644
--- a/backend/app/modules/artifacts/intake/progress.py
+++ b/backend/app/modules/artifacts/intake/progress.py
@@ -4,7 +4,9 @@
 
 from app.core.hashing import canonical_json_hash
 
+from app.modules.artifacts.api.submission_command import PostSubmissionProgress
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
+from app.modules.checkers.api.execution import POST_SUBMISSION_RETRY_OPTIONS
 from app.modules.artifacts.intake.acceptance import finalization_event
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict
 from app.modules.artifacts.intake.recovery import recovery_event
@@ -143,7 +145,7 @@ async def read(self, task_id, selector, *, actor_id):
         else:
             results = await self._feedback(row, repository)
         action = "wait"
-        stage, stalled, submission_id, version, request_id, failure_code = await self._attempt_progress(row)
+        stage, stalled, submission_id, version, request_id, failure_code, post = await self._attempt_progress(row)
         if row.state in {"rejected", "failed", "abandoned", "cancelled"}:
             action = "inspect_governed_outcome"
             if row.state != "cancelled" and await self._permits_new_intake(current.candidate):
@@ -159,7 +161,8 @@ async def read(self, task_id, selector, *, actor_id):
             task_status_at_acceptance="evaluation_pending" if accepted else None,
             current_task_status=current.current_task_status, submission_id=submission_id,
             submission_version=version, evaluation_request_id=request_id,
-            pre_submission_results=results, failure_code=failure_code, operationally_stalled=stalled, next_action=action,
+            pre_submission_results=results, failure_code=failure_code, operationally_stalled=stalled,
+            post_submission_progress=post, next_action=action,
         )
 
     @staticmethod
@@ -179,6 +182,7 @@ async def _attempt_progress(self, row):
         stage, stalled = row.state, False
         submission_id = version = request_id = None
         failure_code = self._public_failure(row.failure_code)
+        post = None
         task_id = UUID(row.task_id)
         if row.state == "finalization_pending":
             progress = await finalization_progress(row, self._events, self._deliveries)
@@ -210,9 +214,16 @@ async def _attempt_progress(self, row):
                     failure_code = ("post_submission_outcome_unknown" if delivery.error_code == "INVOKE_OUTCOME_UNKNOWN"
                                     else "post_submission_delivery_failed")
                 stalled = failure_code is not None
+                if not stalled and evaluation.previous_failure_code is not None and evaluation.status in {"queued", "running"}:
+                    failure_code = f"post_submission_{evaluation.previous_failure_code}"
+                post = PostSubmissionProgress(
+                    attempt=evaluation.current.reservation.evaluation_generation,
+                    automatic_attempt_limit=POST_SUBMISSION_RETRY_OPTIONS.max_attempts,
+                    next_attempt_at=delivery.next_attempt_at if evaluation.status == "queued" else None,
+                )
                 stage = ("operationally_stalled" if stalled else
                          "evaluation_running" if evaluation.live_worker_lease else "evaluation_pending")
-        return stage, stalled, submission_id, version, request_id, failure_code
+        return stage, stalled, submission_id, version, request_id, failure_code, post
 
     async def read_assignment_attempt(self, query):
         """Read one assignment-scoped operation and the original PRE projection."""
@@ -241,10 +252,10 @@ async def read_assignment_attempt(self, query):
             else:
                 repository = SubmissionIntakeRepository(self._session, self._tasks)
                 results = await self._feedback(row, repository)
-            stage, stalled, submission_id, _, _, failure_code = await self._attempt_progress(row)
+            stage, stalled, submission_id, _, _, failure_code, post = await self._attempt_progress(row)
             return AssignmentIntakeAttempt(
                 operation_id=UUID(row.id), stage=stage, failure_code=failure_code,
-                submission_id=submission_id, pre_submission_results=results,
+                submission_id=submission_id, pre_submission_results=results, post_submission_progress=post,
                 operationally_stalled=stalled or row.failure_code == "submission_infrastructure_unavailable",
             )
         except IntakeCustodyConflict as exc:
diff --git a/backend/app/modules/checkers/api/execution.py b/backend/app/modules/checkers/api/execution.py
index d1abf44bd..82c9e7895 100644
--- a/backend/app/modules/checkers/api/execution.py
+++ b/backend/app/modules/checkers/api/execution.py
@@ -31,9 +31,11 @@
     PostSubmitRequestDeliveryFacts,
 )
 from app.modules.model_usage.api import ModelRecoveryCandidate
+from app.modules.outbox.api import DeliveryOptions
 
 REQUEST_EVENT = "PostSubmissionEvaluationRequested"
 COMPLETION_EVENT = "PostSubmissionEvaluationCompleted"
+POST_SUBMISSION_RETRY_OPTIONS = DeliveryOptions()
 
 
 class CheckerExecutionUnavailable(RuntimeError):
@@ -268,6 +270,7 @@ class CheckerRetryEventExpectation(CheckerValue):
     idempotency_key: str
     payload_json: str
     payload_digest: Sha256
+    not_before_at: AwareDatetime | None = None
 
 
 class CheckerRetryDelivery(CheckerValue):
@@ -348,6 +351,7 @@ class EvaluationProgress(CheckerValue):
     status: Literal["queued", "running", "completed", "infrastructure_failed"]
     live_worker_lease: bool
     failure_code: PostSubmissionInfrastructureFailureCode | None
+    previous_failure_code: PostSubmissionInfrastructureFailureCode | None
     retry_event_id: ResourceId | None
     completion_event_id: ResourceId | None
     delivery_event_json: str | None
diff --git a/backend/app/modules/checkers/checker_retry.py b/backend/app/modules/checkers/checker_retry.py
index 44b345479..a53051903 100644
--- a/backend/app/modules/checkers/checker_retry.py
+++ b/backend/app/modules/checkers/checker_retry.py
@@ -1,7 +1,8 @@
-"""One hidden Operator retry of a terminal checker infrastructure failure."""
+"""Exact automatic and Operator retry custody for terminal checker failures."""
 
 from __future__ import annotations
 
+from datetime import timedelta
 import json
 from typing import Literal
 from uuid import UUID
@@ -33,6 +34,7 @@
     CheckerRetrySourceQuery,
     CheckerRetrySuccessor,
     EvaluationTaskGuard,
+    POST_SUBMISSION_RETRY_OPTIONS, REQUEST_EVENT,
 )
 from app.modules.checkers.api.evaluation_contract import PostSubmissionExecutionRequest
 from app.modules.checkers.api.selected_post_submit import make_selected_post_submit_request
@@ -140,6 +142,44 @@ def _successor_from_receipt(receipt: CheckerRetryReceipt) -> CheckerRetrySuccess
         raise CheckerRetryOperationUnavailable("checker_retry_replay_unavailable") from exc
 
 
+def automatic_retry_event(prior: CheckerRun, successor: CheckerRun) -> OutboxAppendInput:
+    """Use the committed fixed-service finalization as the automatic retry cause."""
+    _, source = require_finalized_infrastructure_source(prior)
+    if prior.completed_at is None or source.source_generation >= POST_SUBMISSION_RETRY_OPTIONS.max_attempts:
+        raise CheckerRetrySourceUnavailable("checker_automatic_retry_source_unavailable")
+    return OutboxAppendInput(
+        event_type=REQUEST_EVENT, event_version=1, aggregate_type="submission",
+        aggregate_id=source.submission_id, project_id=source.project_id,
+        correlation_id=str(source.source_run_id),
+        idempotency_key="checker-auto-retry:" + str(source.source_run_id),
+        not_before_at=prior.completed_at + timedelta(seconds=POST_SUBMISSION_RETRY_OPTIONS.retry_delay_seconds(
+            source.source_generation,
+        )),
+        payload={
+            "project_id": str(source.project_id), "task_id": str(source.task_id),
+            "submission_id": str(source.submission_id), "submission_version": source.submission_version,
+            "request_id": successor.evaluation_request_id, "request_digest": successor.request_digest,
+            "evaluation_generation": successor.evaluation_generation, "attempt_id": successor.id,
+            "result_id": successor.result_id, "source_run_id": str(source.source_run_id),
+            "source_result_digest": source.source_result_digest,
+            "source_finalize_evidence_id": str(source.source_finalize_evidence_id),
+        },
+    )
+
+
+def retry_event_expectation(expected: OutboxAppendInput) -> CheckerRetryEventExpectation:
+    """Express the exact immutable event expected by TASK and progress readers."""
+    return CheckerRetryEventExpectation(
+        event_type=expected.event_type, event_version=expected.event_version,
+        aggregate_type=expected.aggregate_type, aggregate_id=expected.aggregate_id,
+        correlation_id=expected.correlation_id, causation_event_id=expected.causation_event_id,
+        idempotency_key=expected.idempotency_key, not_before_at=expected.not_before_at,
+        payload_json=json.dumps(expected.payload, sort_keys=True, separators=(",", ":"),
+                                ensure_ascii=False, allow_nan=False),
+        payload_digest=canonical_json_hash(expected.payload),
+    )
+
+
 def retry_request_event(
     source: CheckerRetrySource,
     *,
@@ -662,21 +702,5 @@ async def read_retry_delivery(
     )
     return CheckerRetryDelivery(
         request=stored.request,
-        expected_event=CheckerRetryEventExpectation(
-            event_type=expected.event_type,
-            event_version=expected.event_version,
-            aggregate_type=expected.aggregate_type,
-            aggregate_id=expected.aggregate_id,
-            correlation_id=expected.correlation_id,
-            causation_event_id=expected.causation_event_id,
-            idempotency_key=expected.idempotency_key,
-            payload_json=json.dumps(
-                expected.payload,
-                sort_keys=True,
-                separators=(",", ":"),
-                ensure_ascii=False,
-                allow_nan=False,
-            ),
-            payload_digest=canonical_json_hash(expected.payload),
-        ),
+        expected_event=retry_event_expectation(expected),
     )
diff --git a/backend/app/modules/checkers/execution.py b/backend/app/modules/checkers/execution.py
index 2b8e533e7..9cb558a1d 100644
--- a/backend/app/modules/checkers/execution.py
+++ b/backend/app/modules/checkers/execution.py
@@ -58,7 +58,8 @@
     PostSubmissionMaterializationFailure,
 )
 from app.modules.outbox.api import OutboxAppendPort
-from app.modules.checkers.api.execution import ReviewModePort
+from app.modules.checkers.api.execution import EvaluationTaskGuard, ReviewModePort
+from app.modules.checkers.execution_coordination import EvaluationCoordinator
 
 def _lease(run):
     """Recover the exact persisted lease, including its database expiry."""
@@ -151,6 +152,7 @@ def __init__(
         forge_facts: ForgeFactsResolver | None = None,
         outbox: Callable[[AsyncSession], OutboxAppendPort],
         review_modes: Callable[[AsyncSession], ReviewModePort],
+        retry_tasks: Callable[[AsyncSession], EvaluationTaskGuard] | None = None,
     ):
         """Receive explicit session, authority, materialization and publication ports."""
         self._sessions = sessions
@@ -159,6 +161,7 @@ def __init__(
         self._materialization, self._outbox = materialization, outbox
         self._selected_execution = selected_execution
         self._forge_facts = forge_facts
+        self._retry_tasks = retry_tasks
 
     @staticmethod
     def _execution_budget_seconds(request: PostSubmissionExecutionRequest) -> int:
@@ -395,4 +398,7 @@ async def finalize(self, facts: FinalizeFacts) -> PostSubmissionExecutionResult:
                 run.outcome_source = "auto_checker"
                 run.status = result.outcome
                 await session.flush()
+                if result.outcome == "infrastructure_failed" and self._retry_tasks is not None:
+                    coordinator = EvaluationCoordinator(session, tasks=self._retry_tasks(session), events=self._outbox(session))
+                    await coordinator.schedule_automatic_retry(run)
                 return result
diff --git a/backend/app/modules/checkers/execution_coordination.py b/backend/app/modules/checkers/execution_coordination.py
index 851e77f4d..9807e0458 100644
--- a/backend/app/modules/checkers/execution_coordination.py
+++ b/backend/app/modules/checkers/execution_coordination.py
@@ -18,7 +18,7 @@
     EvaluationProgress,
     ReservedEvaluation,
     EvaluationCompletion,
-    EvaluationTaskGuard,
+    EvaluationTaskGuard, POST_SUBMISSION_RETRY_OPTIONS,
     VerifiedMaterialFacts,
     VerifiedEvaluationCompletion,
 )
@@ -30,7 +30,7 @@
     PostSubmitRequestDeliveryFacts,
 )
 from app.modules.checkers.api.selected_post_submit import (
-    SelectedPostSubmitCurrentResultReference,
+    SelectedPostSubmitCurrentResultReference, make_selected_post_submit_request,
 )
 from app.modules.checkers.execution_repository import (
     ExecutionRepository,
@@ -40,7 +40,9 @@
     stored_result,
     stored_request,
 )
-from app.modules.outbox.api import OutboxAppendInput
+from app.modules.outbox.api import (
+    OutboxAppendInput, OutboxAppendPort, OutboxIdempotencyConflict, OutboxInputError, OutboxPersistenceError,
+)
 from app.modules.checkers.execution_results import evaluation_completion_event
 from app.modules.checkers.models import CheckerRun, CheckerSubmissionFence, CheckerRetryReceipt
 
@@ -48,10 +50,9 @@
 class EvaluationCoordinator:
     """Own exact request reservation and current-result reads in caller transactions."""
 
-    def __init__(self, session: AsyncSession, *, tasks: EvaluationTaskGuard):
+    def __init__(self, session: AsyncSession, *, tasks: EvaluationTaskGuard, events: OutboxAppendPort):
         """Use the supplied session without taking ownership of its commit."""
-        self._session = session
-        self._tasks = tasks
+        self._session, self._tasks, self._events = session, tasks, events
 
     async def reserve_current_evaluation(
         self, request: PostSubmissionExecutionRequest
@@ -67,8 +68,25 @@ async def reserve_current_evaluation(
                 return reservation(replay)
         return await self._reserve_after_task_lock(request)
 
+    async def schedule_automatic_retry(self, run: CheckerRun) -> None:
+        """Reserve a delayed successor only from exact known terminal custody."""
+        from app.modules.checkers.checker_retry import require_finalized_infrastructure_source
+
+        if run.evaluation_generation >= POST_SUBMISSION_RETRY_OPTIONS.max_attempts:
+            return
+        previous, source = require_finalized_infrastructure_source(run)
+        await self._tasks.lock_terminal_retry_scope(previous)
+        next_request = make_selected_post_submit_request(
+            **previous.model_dump(exclude={"evaluation_request_id", "evaluation_generation", "request_sha256"}),
+            evaluation_request_id=new_record_id(), evaluation_generation=source.source_generation + 1,
+        )
+        await self._reserve_after_task_lock(
+            next_request, terminal_source_id=source.source_run_id, automatic_retry=True,
+        )
+
     async def _reserve_after_task_lock(
         self, request: PostSubmissionExecutionRequest, *, terminal_source_id: UUID | None = None,
+        automatic_retry: bool = False,
     ) -> EvaluationReservation:
         """Use the existing CHECKERS locks after the caller has retained TASK custody."""
         require_transaction(self._session)
@@ -145,6 +163,13 @@ async def _reserve_after_task_lock(
             locked_revision_policy_generation=context.revision_generation,
             locked_revision_policy_hash=context.revision_hash,
         )
+        if automatic_retry:
+            from app.modules.checkers.checker_retry import automatic_retry_event
+
+            if terminal_source_id is None or prior is None:
+                raise CheckerRetrySourceUnavailable("checker_automatic_retry_source_unavailable")
+            appended = await self._events.append(automatic_retry_event(prior, run))
+            run.automatic_retry_event_id = appended.event_id
         self._session.add(run)
         try:
             await self._session.flush()
@@ -214,28 +239,32 @@ async def read_current_progress(
         if (current.request.assignment_id != original.request.assignment_id
                 or current.request.submission_version != original.request.submission_version):
             raise CheckerExecutionUnavailable(unavailable)
-        retry_event_id = None
+        retry_event_id = run.automatic_retry_event_id
         delivery_event = None
+        previous_failure_code = None
         if current.reservation.attempt_id == original.reservation.attempt_id:
-            if run.supersedes_checker_run_id is not None:
+            if run.supersedes_checker_run_id is not None or retry_event_id is not None:
                 raise CheckerExecutionUnavailable(unavailable)
         else:
-            receipt = await self._session.scalar(select(CheckerRetryReceipt).where(
-                CheckerRetryReceipt.successor_run_id == run.id,
-                CheckerRetryReceipt.project_id == str(project_id),
-                CheckerRetryReceipt.task_id == str(task_id),
-                CheckerRetryReceipt.submission_id == str(submission_id),
-                CheckerRetryReceipt.source_run_id == run.supersedes_checker_run_id,
-                CheckerRetryReceipt.successor_generation == run.evaluation_generation,
-            ))
-            if receipt is None or run.evaluation_generation <= 1:
-                raise CheckerExecutionUnavailable(unavailable)
-            retained = await self.read_retry_delivery(
-                project_id=project_id, submission_id=submission_id, event_id=receipt.event_id,
-            )
-            if retained is None or retained.request != current.request:
+            if retry_event_id is None:
+                receipt = await self._session.scalar(select(CheckerRetryReceipt).where(
+                    CheckerRetryReceipt.successor_run_id == run.id,
+                    CheckerRetryReceipt.project_id == str(project_id),
+                    CheckerRetryReceipt.task_id == str(task_id),
+                    CheckerRetryReceipt.submission_id == str(submission_id),
+                    CheckerRetryReceipt.source_run_id == run.supersedes_checker_run_id,
+                    CheckerRetryReceipt.successor_generation == run.evaluation_generation,
+                ))
+                if receipt is None:
+                    raise CheckerExecutionUnavailable(unavailable)
+                retry_event_id = receipt.event_id
+                retained = await self.read_retry_delivery(
+                    project_id=project_id, submission_id=submission_id, event_id=retry_event_id,
+                )
+            else:
+                retained, previous_failure_code = await self._read_automatic_retry(run)
+            if retained is None or retained.request != current.request or run.evaluation_generation <= 1:
                 raise CheckerExecutionUnavailable(unavailable)
-            retry_event_id = receipt.event_id
             expected = retained.expected_event
             delivery_event = OutboxAppendInput(
                 **expected.model_dump(exclude={"payload_json", "payload_digest"}),
@@ -267,6 +296,7 @@ async def read_current_progress(
                 and run.worker_lease_expires_at > now)
         return EvaluationProgress(
             current=current, status=run.status, live_worker_lease=live, failure_code=failure_code,
+            previous_failure_code=previous_failure_code,
             retry_event_id=retry_event_id, completion_event_id=run.completion_event_id,
             delivery_event_json=delivery_event.model_dump_json() if delivery_event is not None else None,
         )
@@ -277,11 +307,38 @@ async def read_retry_delivery(
         """Expose exact CHECKERS retry receipt facts without a private TASK import."""
         from app.modules.checkers.checker_retry import read_retry_delivery
         require_transaction(self._session)
+        automatic = await self._session.scalar(select(CheckerRun).where(
+            CheckerRun.automatic_retry_event_id == event_id,
+            CheckerRun.project_id == str(project_id),
+            CheckerRun.submission_id == str(submission_id),
+        ))
+        if automatic is not None:
+            retained, _ = await self._read_automatic_retry(automatic)
+            return retained
         return await read_retry_delivery(
             self._session, self, project_id=project_id,
             submission_id=submission_id, event_id=event_id,
         )
 
+    async def _read_automatic_retry(self, successor: CheckerRun):
+        """Verify the exact service-triggered event and immutable source before use."""
+        from app.modules.checkers.checker_retry import automatic_retry_event, retry_event_expectation
+
+        unavailable = "checker_automatic_retry_delivery_unavailable"
+        if successor.supersedes_checker_run_id is None or successor.automatic_retry_event_id is None:
+            raise CheckerExecutionUnavailable(unavailable)
+        source = await self._session.get(CheckerRun, successor.supersedes_checker_run_id, populate_existing=True)
+        if source is None:
+            raise CheckerExecutionUnavailable(unavailable)
+        expected = automatic_retry_event(source, successor)
+        try:
+            await self._events.require_existing(successor.automatic_retry_event_id, expected)
+        except (OutboxIdempotencyConflict, OutboxInputError, OutboxPersistenceError) as exc:
+            raise CheckerExecutionUnavailable(unavailable) from exc
+        return CheckerRetryDelivery(
+            request=stored_request(successor), expected_event=retry_event_expectation(expected),
+        ), stored_result(source).infrastructure_failure_code
+
     async def _lock_task_scope(self, request: PostSubmissionExecutionRequest) -> bool:
         """Retain root-transaction TASK custody before any coordination fence lock."""
         require_transaction(self._session)
@@ -343,7 +400,10 @@ async def classify_uncertain_delivery(
         request = validate_execution_request(request)
         with self._session.no_autoflush:
             await self._lock_task_scope(request)
-            run = await ExecutionRepository(self._session).lock_current(request)
+            try:
+                run = await ExecutionRepository(self._session).lock_current(request)
+            except CheckerExecutionUnavailable:
+                run = await self._closed_automatic_retry_source(request)
         if run.status == "queued":
             retry_safe = (
                 run.worker_lease_generation == 0
@@ -423,6 +483,27 @@ async def classify_uncertain_delivery(
             classification="unresolved",
         )
 
+    async def _closed_automatic_retry_source(self, request: PostSubmissionExecutionRequest) -> CheckerRun:
+        """Resolve a lost delivery ACK after the source and successor committed together."""
+        unavailable = "checker_uncertain_delivery_source_unavailable"
+        source = await self._session.scalar(select(CheckerRun).where(
+            CheckerRun.project_id == str(request.project_id), CheckerRun.task_id == str(request.task_id),
+            CheckerRun.submission_id == str(request.submission_id),
+            CheckerRun.evaluation_request_id == str(request.evaluation_request_id),
+        ))
+        if source is None or source.status != "infrastructure_failed" or stored_request(source) != request:
+            raise CheckerExecutionUnavailable(unavailable)
+        successor = await self._session.scalar(select(CheckerRun).where(
+            CheckerRun.submission_id == source.submission_id,
+            CheckerRun.evaluation_generation == source.evaluation_generation + 1,
+            CheckerRun.supersedes_checker_run_id == source.id,
+            CheckerRun.automatic_retry_event_id.is_not(None),
+        ))
+        if successor is None:
+            raise CheckerExecutionUnavailable(unavailable)
+        await self._read_automatic_retry(successor)
+        return source
+
     async def require_current_completion(
         self, event_id: UUID, completion: EvaluationCompletion
     ) -> VerifiedEvaluationCompletion:
diff --git a/backend/app/modules/checkers/models.py b/backend/app/modules/checkers/models.py
index 7ba3107fb..97159f6bf 100644
--- a/backend/app/modules/checkers/models.py
+++ b/backend/app/modules/checkers/models.py
@@ -213,6 +213,10 @@ class CheckerRun(Base):
         ),
         CheckConstraint("evaluation_generation > 0 and worker_lease_generation >= 0", name="generations"),
         CheckConstraint("status in ('queued','running','completed','infrastructure_failed')", name="state"),
+        CheckConstraint(
+            "automatic_retry_event_id IS NULL OR (supersedes_checker_run_id IS NOT NULL "
+            "AND evaluation_generation BETWEEN 2 AND 5)", name="automatic_retry_scope",
+        ),
         CheckConstraint("octet_length(request_json) <= 1048576 and request_digest = 'sha256:' || encode(sha256(convert_to(request_json, 'UTF8')), 'hex')", name="request_digest"),
         CheckConstraint("result_json is null or result_digest = 'sha256:' || encode(sha256(convert_to(result_json, 'UTF8')), 'hex')", name="result_digest"),
         Index(
@@ -263,6 +267,9 @@ class CheckerRun(Base):
     material_custody: Mapped[dict | None] = mapped_column(JSON(none_as_null=True))
     input_context_custody: Mapped[dict | None] = mapped_column(JSONB(none_as_null=True))
     completion_event_id: Mapped[UUID | None] = mapped_column(Uuid(), ForeignKey("outbox_events.event_id"))
+    automatic_retry_event_id: Mapped[UUID | None] = mapped_column(
+        Uuid(), ForeignKey("outbox_events.event_id", name="fk_checker_runs_automatic_retry_event"), unique=True,
+    )
     supersedes_checker_run_id: Mapped[str | None] = mapped_column(
         Uuid(as_uuid=False),
         index=True,
diff --git a/backend/app/modules/outbox/api.py b/backend/app/modules/outbox/api.py
index 825a79b68..43ef5fd79 100644
--- a/backend/app/modules/outbox/api.py
+++ b/backend/app/modules/outbox/api.py
@@ -152,6 +152,10 @@ class DeliveryOptions(DeliveryValue):
     retry_base_seconds: int = Field(default=5, ge=1, le=3600)
     retry_cap_seconds: int = Field(default=300, ge=1, le=86400)
 
+    def retry_delay_seconds(self, attempt: int) -> int:
+        """Return the bounded exponential delay after a one-based attempt."""
+        return min(self.retry_cap_seconds, self.retry_base_seconds * 2 ** min(attempt - 1, 30))
+
     @model_validator(mode="after")
     def ordered_limits(self) -> Self:
         """Leave a lease margin and bound retry scheduling."""
diff --git a/backend/app/modules/outbox/delivery.py b/backend/app/modules/outbox/delivery.py
index e4d7682ca..15ce5ba63 100644
--- a/backend/app/modules/outbox/delivery.py
+++ b/backend/app/modules/outbox/delivery.py
@@ -115,10 +115,7 @@ def _outcome(
         code = "INVOKE_OUTCOME_UNKNOWN"
         if retry_unknown and claim.claim_generation < options.max_attempts:
             state = "retryable"
-            delay = min(
-                options.retry_cap_seconds,
-                options.retry_base_seconds * 2 ** min(claim.claim_generation - 1, 30),
-            )
+            delay = options.retry_delay_seconds(claim.claim_generation)
             retry = now + timedelta(seconds=delay)
     elif cause is FinalizationCause.ACKNOWLEDGE:
         state, code = "acknowledged", None
@@ -128,10 +125,7 @@ def _outcome(
         else:
             state = "retryable"
             code = "RETRY_REQUESTED" if invoked_at is not None else "LEASE_EXPIRED_BEFORE_INVOKE"
-            delay = min(
-                options.retry_cap_seconds,
-                options.retry_base_seconds * 2 ** min(claim.claim_generation - 1, 30),
-            )
+            delay = options.retry_delay_seconds(claim.claim_generation)
             retry = now + timedelta(seconds=delay)
     return {
         "delivery_state": state,
diff --git a/backend/tests/checkers/execution/test_checker_retry.py b/backend/tests/checkers/execution/test_checker_retry.py
index 91efde603..056ac33b3 100644
--- a/backend/tests/checkers/execution/test_checker_retry.py
+++ b/backend/tests/checkers/execution/test_checker_retry.py
@@ -119,6 +119,12 @@ def missing(_store, _reference, **kwargs):
         try:
             delivery = await delivery_fixture(h, materialization=port)
             with monkeypatch.context() as patch:
+                from app.modules.checkers import execution_coordination
+
+                # Isolate the Operator path after escalation. The automatic policy
+                # and its durable retry chain are covered by delivery tests.
+                patch.setattr(execution_coordination, "POST_SUBMISSION_RETRY_OPTIONS",
+                    execution_coordination.POST_SUBMISSION_RETRY_OPTIONS.model_copy(update={"max_attempts": 1}))
                 patch.setattr(
                     LocalStorageAdapter if provider == "local" else S3CompatibleArtifactStore,
                     "open_source", missing,
diff --git a/backend/tests/tasks/evaluation_delivery/test_delivery.py b/backend/tests/tasks/evaluation_delivery/test_delivery.py
index 1f39b149f..3b073179a 100644
--- a/backend/tests/tasks/evaluation_delivery/test_delivery.py
+++ b/backend/tests/tasks/evaluation_delivery/test_delivery.py
@@ -112,3 +112,71 @@ async def controlled(guard, request):
         eligible = False
         assert await d.handler(envelope) is HandlerOutcome.ACKNOWLEDGE
         assert await state(h) == terminal and len(h.store.opens) == 1
+
+
+@pytest.mark.parametrize("rollback", [False, True])
+async def test_known_post_failure_schedules_one_delayed_service_retry(
+    tmp_path, isolated_database_env, monkeypatch, rollback,
+):
+    """Retain one exact successor for known failure, or roll it all back."""
+    from datetime import timedelta
+
+    from app.adapters.checkers import evaluation_coordinator
+    from app.modules.checkers.api.materialization import PostSubmissionMaterializationFailure
+    from app.modules.checkers.models import CheckerRetryReceipt, CheckerRun, CheckerSubmissionFence
+    from app.modules.outbox.api import OutboxPersistenceError
+    from app.modules.outbox.models import OutboxEvent
+    from app.modules.outbox.service import OutboxService
+
+    class MissingMaterial:
+        async def materialize(self, _facts, _consumer):
+            raise PostSubmissionMaterializationFailure("controlled missing material")
+
+    async with material_fixture(tmp_path, isolated_database_env) as h:
+        d = await delivery_fixture(h, materialization=MissingMaterial())
+        original_append = OutboxService.append
+
+        async def guarded_append(outbox, event):
+            if event.idempotency_key.startswith("checker-auto-retry:"):
+                raise OutboxPersistenceError("controlled retry persistence failure")
+            return await original_append(outbox, event)
+
+        if rollback:
+            monkeypatch.setattr(OutboxService, "append", guarded_append)
+        receipt = outcome(await d.delivery.deliver(h.created.evaluation_event_id, h.request.project_id, "worker"))
+        assert receipt["delivery_state"] == ("dead_letter" if rollback else "acknowledged")
+        assert receipt["invocation_unknown"] is rollback
+        async with h.factory.begin() as session:
+            runs = list(await session.scalars(select(CheckerRun).where(
+                CheckerRun.submission_id == str(h.request.submission_id),
+            ).order_by(CheckerRun.evaluation_generation)))
+            original = runs[0]
+            fence = await session.get(CheckerSubmissionFence, original.submission_id)
+            assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0
+            assert not d.selected.requests
+            if rollback:
+                assert len(runs) == 1 and fence.current_run_id == original.id
+                assert original.status == "running" and original.result_json is None
+                return
+            assert len(runs) == 2
+            successor = runs[1]
+            assert fence.current_run_id == successor.id
+            assert original.status == "infrastructure_failed" and original.failure_code == "material_unavailable"
+            assert successor.status == "queued" and successor.supersedes_checker_run_id == original.id
+            new_event = await session.get(OutboxEvent, successor.automatic_retry_event_id)
+            assert new_event.not_before_at == original.completed_at + timedelta(seconds=5)
+            event_id, due = new_event.event_id, new_event.not_before_at
+            assert (await evaluation_coordinator(session).classify_uncertain_delivery(h.request)).classification == "committed"
+            read = await evaluation_coordinator(session).read_current_progress(
+                project_id=h.request.project_id, task_id=h.request.task_id,
+                submission_id=h.request.submission_id, original_request_id=h.request.evaluation_request_id,
+            )
+            assert read.current.reservation.evaluation_generation == 2
+            assert read.previous_failure_code == "material_unavailable"
+            assert read.retry_event_id == event_id
+            assert new_event.payload["source_finalize_evidence_id"] == original.finalize_evidence_id
+        async with h.factory() as session:
+            now = await session.scalar(select(func.clock_timestamp()))
+            if now < due:
+                assert await d.delivery.claim(event_id, h.request.project_id, "worker") is None
+        assert await d.delivery.deliver(h.created.evaluation_event_id, h.request.project_id, "duplicate") is None
diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py
index 0524671c1..853ae7142 100644
--- a/backend/tests/test_alembic.py
+++ b/backend/tests/test_alembic.py
@@ -439,6 +439,7 @@ def test_v01_graph_has_one_root_and_head() -> None:
 
     assert [revision.revision for revision in revisions] == [
         HEAD_REVISION,
+        "0094_project_archive_limits",
         "0093_verified_email_observation",
         "0092_submission_feedback",
         "0091_qualified_aws_source",
@@ -537,7 +538,7 @@ def test_v01_graph_has_one_root_and_head() -> None:
     assert script.get_revision("0090_merge_direct_storage").down_revision == (
         "0089_observed_upload_cleanup", "0069_remove_artifact_proof",
     )
-    assert script.get_revision(HEAD_REVISION).down_revision == "0093_verified_email_observation"
+    assert script.get_revision(HEAD_REVISION).down_revision == "0094_project_archive_limits"
     assert revisions[-1].down_revision is None
     assert script.get_heads() == [HEAD_REVISION]
 
@@ -1981,7 +1982,7 @@ def test_root_upgrade_refuses_nonempty_unstamped_schema_before_product_ddl(
             "0004_task_context_authority",
             "Workstream v0.1 migrations cannot be downgraded; recreate the database",
         ),
-        (HEAD_REVISION, "project archive limits migration is forward-only"),
+        (HEAD_REVISION, "POST infrastructure retry migration is forward-only"),
     ],
 )
 def test_downgrade_refuses_without_mutation(
diff --git a/backend/tests/test_checker_evidence_migrations.py b/backend/tests/test_checker_evidence_migrations.py
index df98206de..1a99609fd 100644
--- a/backend/tests/test_checker_evidence_migrations.py
+++ b/backend/tests/test_checker_evidence_migrations.py
@@ -107,12 +107,12 @@ async def _retained_rows(database_url: str) -> dict[str, str]:
         result = {}
         for table in _RETAINED_TABLES:
             excluded = {
-                "checker_runs": "input_context_custody",
-                "artifact_put_attempts": "checker_trial_evidence_id",
-                "artifact_operation_receipts": "checker_trial_evidence_id",
-                "artifact_replicas": "source_operation_id",
-            }.get(table)
-            projection = "to_jsonb(value)" + (f" - '{excluded}'" if excluded else "")
+                "checker_runs": ("input_context_custody", "automatic_retry_event_id"),
+                "artifact_put_attempts": ("checker_trial_evidence_id",),
+                "artifact_operation_receipts": ("checker_trial_evidence_id",),
+                "artifact_replicas": ("source_operation_id",),
+            }.get(table, ())
+            projection = "to_jsonb(value)" + "".join(f" - '{column}'" for column in excluded)
             result[table] = await connection.fetchval(
                 f"select coalesce(jsonb_agg({projection} order by value.id),'[]')::text "
                 f"from {table} value"
@@ -153,7 +153,7 @@ async def _assert_head_lineage_projection(
         ) == 0
         assert (
             await connection.fetchval(
-                "select count(*) from checker_runs where input_context_custody is not null"
+                "select count(*) from checker_runs where input_context_custody is not null OR automatic_retry_event_id is not null"
             )
             == 0
         )
diff --git a/cli/internal/api/contributor_reads.go b/cli/internal/api/contributor_reads.go
index bfe0c0233..52b69b65b 100644
--- a/cli/internal/api/contributor_reads.go
+++ b/cli/internal/api/contributor_reads.go
@@ -73,12 +73,13 @@ type ContributorAssignment struct {
 }
 
 type AssignmentIntake struct {
-	OperationID string            `json:"operation_id"`
-	Stage       string            `json:"stage"`
-	FailureCode *string           `json:"failure_code"`
-	Submission  *string           `json:"submission_id"`
-	Feedback    []json.RawMessage `json:"pre_submission_results"`
-	Stalled     bool              `json:"operationally_stalled"`
+	OperationID  string                  `json:"operation_id"`
+	Stage        string                  `json:"stage"`
+	FailureCode  *string                 `json:"failure_code"`
+	Submission   *string                 `json:"submission_id"`
+	Feedback     []json.RawMessage       `json:"pre_submission_results"`
+	Stalled      bool                    `json:"operationally_stalled"`
+	PostProgress *PostSubmissionProgress `json:"post_submission_progress"`
 }
 
 type AcceptedAssignmentEvidence struct {
@@ -373,7 +374,8 @@ func (c *Client) TaskAssignment(ctx context.Context, assignment string, limit in
 	value.Assignment = row
 	if intake := value.Intake; intake != nil {
 		part, err := contextObject(fields["intake"], intake, []string{"operation_id", "stage", "pre_submission_results", "operationally_stalled"}, nil)
-		if err != nil || !requiredNullable(part, "failure_code", "submission_id") || !validUUID(intake.OperationID) ||
+		if err != nil || !requiredNullable(part, "failure_code", "submission_id", "post_submission_progress") ||
+			!validPostSubmissionProgress(part["post_submission_progress"], intake.PostProgress) || !validUUID(intake.OperationID) ||
 			!validOptionalID(intake.Submission) || intake.Feedback == nil || !validPreSubmissionResults(intake.Feedback, false) {
 			return result, &Failure{Code: "invalid_api_response"}
 		}
diff --git a/cli/internal/api/submission_progress.go b/cli/internal/api/submission_progress.go
index 3eef1872e..61c1506a9 100644
--- a/cli/internal/api/submission_progress.go
+++ b/cli/internal/api/submission_progress.go
@@ -9,31 +9,50 @@ import (
 	"net/url"
 )
 
+// PostSubmissionProgress reports the durable attempt and any scheduled delay.
+type PostSubmissionProgress struct {
+	Attempt               int     `json:"attempt"`
+	AutomaticAttemptLimit int     `json:"automatic_attempt_limit"`
+	NextAttemptAt         *string `json:"next_attempt_at"`
+}
+
+func validPostSubmissionProgress(raw json.RawMessage, value *PostSubmissionProgress) bool {
+	if value == nil {
+		return true
+	}
+	fields, err := contextObject(raw, value, []string{"attempt", "automatic_attempt_limit"}, nil)
+	return err == nil && requiredNullable(fields, "next_attempt_at") && value.Attempt > 0 &&
+		value.AutomaticAttemptLimit > 0 && value.AutomaticAttemptLimit <= 100 &&
+		(value.NextAttemptAt == nil || validTime(*value.NextAttemptAt))
+}
+
 // SubmissionProgress preserves the operation's outcome separately from current task context.
 type SubmissionProgress struct {
-	OperationID            string            `json:"operation_id"`
-	TaskID                 string            `json:"task_id"`
-	AssignmentID           string            `json:"assignment_id"`
-	IdempotencyKey         string            `json:"idempotency_key"`
-	State                  string            `json:"operation_state"`
-	Stage                  string            `json:"processing_stage"`
-	AcceptedAt             *string           `json:"accepted_at"`
-	TaskStatusAtAcceptance *string           `json:"task_status_at_acceptance"`
-	CurrentTaskStatus      *string           `json:"current_task_status"`
-	SubmissionID           *string           `json:"submission_id"`
-	SubmissionVersion      *big.Int          `json:"submission_version"`
-	EvaluationRequestID    *string           `json:"evaluation_request_id"`
-	Feedback               []json.RawMessage `json:"pre_submission_results"`
-	FailureCode            *string           `json:"failure_code"`
-	Stalled                bool              `json:"operationally_stalled"`
-	NextAction             string            `json:"next_action"`
+	OperationID            string                  `json:"operation_id"`
+	TaskID                 string                  `json:"task_id"`
+	AssignmentID           string                  `json:"assignment_id"`
+	IdempotencyKey         string                  `json:"idempotency_key"`
+	State                  string                  `json:"operation_state"`
+	Stage                  string                  `json:"processing_stage"`
+	AcceptedAt             *string                 `json:"accepted_at"`
+	TaskStatusAtAcceptance *string                 `json:"task_status_at_acceptance"`
+	CurrentTaskStatus      *string                 `json:"current_task_status"`
+	SubmissionID           *string                 `json:"submission_id"`
+	SubmissionVersion      *big.Int                `json:"submission_version"`
+	EvaluationRequestID    *string                 `json:"evaluation_request_id"`
+	Feedback               []json.RawMessage       `json:"pre_submission_results"`
+	FailureCode            *string                 `json:"failure_code"`
+	Stalled                bool                    `json:"operationally_stalled"`
+	NextAction             string                  `json:"next_action"`
+	PostProgress           *PostSubmissionProgress `json:"post_submission_progress"`
 }
 
 func decodeSubmissionProgress(raw json.RawMessage, task, operation, key string) (SubmissionProgress, error) {
 	var value SubmissionProgress
 	bad := &Failure{Code: "invalid_api_response"}
 	fields, err := contextObject(raw, &value, []string{"operation_id", "task_id", "assignment_id", "idempotency_key", "operation_state", "processing_stage", "pre_submission_results", "operationally_stalled", "next_action"}, nil)
-	if err != nil || !requiredNullable(fields, "accepted_at", "task_status_at_acceptance", "current_task_status", "submission_id", "submission_version", "evaluation_request_id", "failure_code") ||
+	if err != nil || !requiredNullable(fields, "accepted_at", "task_status_at_acceptance", "current_task_status", "submission_id", "submission_version", "evaluation_request_id", "failure_code", "post_submission_progress") ||
+		!validPostSubmissionProgress(fields["post_submission_progress"], value.PostProgress) ||
 		!validUUID(value.OperationID) || !sameUUID(value.TaskID, task) || !validUUID(value.AssignmentID) || !validUUID(value.IdempotencyKey) ||
 		(operation != "" && !sameUUID(value.OperationID, operation)) || (key != "" && !sameUUID(value.IdempotencyKey, key)) ||
 		!oneOf(value.State, "receiving", "pre_checking", "finalization_pending", "finalized", "rejected", "failed", "abandoned", "cancelled") ||
diff --git a/cli/internal/api/submission_progress_test.go b/cli/internal/api/submission_progress_test.go
index 9dbcbbd2c..db241de36 100644
--- a/cli/internal/api/submission_progress_test.go
+++ b/cli/internal/api/submission_progress_test.go
@@ -13,7 +13,7 @@ func progressJSON() map[string]any {
 		"idempotency_key": testSubmission, "operation_state": "finalization_pending", "processing_stage": "finalization_pending",
 		"accepted_at": "2026-11-16T12:00:00Z", "task_status_at_acceptance": "evaluation_pending", "current_task_status": nil,
 		"submission_id": nil, "submission_version": nil, "evaluation_request_id": nil, "pre_submission_results": []any{},
-		"failure_code": nil, "operationally_stalled": false, "next_action": "wait"}
+		"failure_code": nil, "operationally_stalled": false, "post_submission_progress": nil, "next_action": "wait"}
 }
 
 func TestSubmissionProgressSelectorsAndNoMutation(t *testing.T) {
diff --git a/cli/internal/command/submission.go b/cli/internal/command/submission.go
index fa43b61a7..b76564297 100644
--- a/cli/internal/command/submission.go
+++ b/cli/internal/command/submission.go
@@ -9,7 +9,7 @@ import (
 	"github.com/spf13/cobra"
 )
 
-func postSubmissionRecovery(code *string) string {
+func postSubmissionMessage(code *string, held bool) string {
 	if code == nil {
 		return ""
 	}
@@ -25,7 +25,10 @@ func postSubmissionRecovery(code *string) string {
 	if message == "" {
 		return ""
 	}
-	return message + " Your Submission is retained. Contact an Operator for recovery."
+	if held {
+		return message + " Your Submission is retained. Contact an Operator for recovery."
+	}
+	return message + " Workstream is retrying evaluation of your retained Submission."
 }
 
 func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client, error), output *string, stdout io.Writer) {
@@ -105,10 +108,13 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 				{"Terms", value.Assignment.Compensation}, {"Revision", value.Assignment.Revision},
 				{"Latest submitted attempt", value.Assignment.LatestSubmission},
 			}
-			if value.NextAction == "contact_operator" {
-				fields = append(fields, contextField{"Evaluation recovery", postSubmissionRecovery(value.StatusReason)})
-			}
 			if value.Intake != nil {
+				if value.Intake.PostProgress != nil {
+					fields = append(fields, contextField{"Evaluation progress", value.Intake.PostProgress})
+					if message := postSubmissionMessage(value.StatusReason, value.Intake.Stalled); message != "" {
+						fields = append(fields, contextField{"Evaluation recovery", message})
+					}
+				}
 				fields = append(fields, contextField{"Intake stage", value.Intake.Stage},
 					contextField{"Intake feedback", api.IntakeFeedbackLines(value.Intake.Feedback)})
 			}
@@ -148,8 +154,8 @@ func addSubmissionCommands(root, task *cobra.Command, client func() (*api.Client
 				return writeSafeJSON(stdout, result.Raw)
 			}
 			fields := []contextField{{"Submission operation", result.Value}}
-			if result.Value.NextAction == "contact_operator" {
-				fields = append(fields, contextField{"Evaluation recovery", postSubmissionRecovery(result.Value.FailureCode)})
+			if message := postSubmissionMessage(result.Value.FailureCode, result.Value.Stalled); message != "" {
+				fields = append(fields, contextField{"Evaluation recovery", message})
 			}
 			return writeTaskContextFields(stdout, fields)
 		}
diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py
index 536844f8a..8285de5df 100644
--- a/cli/tests/integration/test_submission_http.py
+++ b/cli/tests/integration/test_submission_http.py
@@ -742,6 +742,7 @@ def operation_progress():
         "pre_submission_results": [],
         "failure_code": None,
         "operationally_stalled": False,
+        "post_submission_progress": None,
         "next_action": "wait",
     }
 
diff --git a/mcp_server/contracts/submission_operation_get.json b/mcp_server/contracts/submission_operation_get.json
index b887bccf7..6e4eab5b8 100644
--- a/mcp_server/contracts/submission_operation_get.json
+++ b/mcp_server/contracts/submission_operation_get.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "e9cf7c4c35d072287b24a985a6ffb0de246e82adad1ab6f1a78abf66c42dd01c",
+  "canonical_sha256": "16f5cb07c998b4a5c93c18fa3cc2882b9c8af83e2ea43899a309f7d3a57bbf20",
   "components": {
     "schemas": {
       "ApiError": {
@@ -225,6 +225,41 @@
         "title": "ExternalCheckerFinding",
         "type": "object"
       },
+      "PostSubmissionProgress": {
+        "additionalProperties": false,
+        "description": "Current checker attempt and the due time of a scheduled retry.",
+        "properties": {
+          "attempt": {
+            "exclusiveMinimum": 0.0,
+            "title": "Attempt",
+            "type": "integer"
+          },
+          "automatic_attempt_limit": {
+            "exclusiveMinimum": 0.0,
+            "title": "Automatic Attempt Limit",
+            "type": "integer"
+          },
+          "next_attempt_at": {
+            "anyOf": [
+              {
+                "format": "date-time",
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Next Attempt At"
+          }
+        },
+        "required": [
+          "attempt",
+          "automatic_attempt_limit",
+          "next_attempt_at"
+        ],
+        "title": "PostSubmissionProgress",
+        "type": "object"
+      },
       "ProjectIntakeCheck": {
         "additionalProperties": false,
         "properties": {
@@ -383,6 +418,16 @@
             "title": "Operationally Stalled",
             "type": "boolean"
           },
+          "post_submission_progress": {
+            "anyOf": [
+              {
+                "$ref": "#/components/schemas/PostSubmissionProgress"
+              },
+              {
+                "type": "null"
+              }
+            ]
+          },
           "pre_submission_results": {
             "items": {
               "anyOf": [
@@ -478,6 +523,7 @@
           "pre_submission_results",
           "failure_code",
           "operationally_stalled",
+          "post_submission_progress",
           "next_action"
         ],
         "title": "SubmissionOperationResponse",
diff --git a/mcp_server/contracts/task_assignment_get.json b/mcp_server/contracts/task_assignment_get.json
index ccf05b2c4..1833bae09 100644
--- a/mcp_server/contracts/task_assignment_get.json
+++ b/mcp_server/contracts/task_assignment_get.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "4eb6fbe4174d135c9e76cf50806677ff944e3f9fafa06eb2f81d6aba73194733",
+  "canonical_sha256": "85deb7505c3c99c3c475b31592a6724f7c18a2e88c5868b1a32905e2240ed0e5",
   "components": {
     "schemas": {
       "AcceptedAssignmentEvidence": {
@@ -122,6 +122,16 @@
             "title": "Operationally Stalled",
             "type": "boolean"
           },
+          "post_submission_progress": {
+            "anyOf": [
+              {
+                "$ref": "#/components/schemas/PostSubmissionProgress"
+              },
+              {
+                "type": "null"
+              }
+            ]
+          },
           "pre_submission_results": {
             "items": {
               "anyOf": [
@@ -163,7 +173,8 @@
           "failure_code",
           "submission_id",
           "pre_submission_results",
-          "operationally_stalled"
+          "operationally_stalled",
+          "post_submission_progress"
         ],
         "title": "AssignmentIntakeAttempt",
         "type": "object"
@@ -1006,6 +1017,41 @@
         "title": "ExternalCheckerFinding",
         "type": "object"
       },
+      "PostSubmissionProgress": {
+        "additionalProperties": false,
+        "description": "Current checker attempt and the due time of a scheduled retry.",
+        "properties": {
+          "attempt": {
+            "exclusiveMinimum": 0.0,
+            "title": "Attempt",
+            "type": "integer"
+          },
+          "automatic_attempt_limit": {
+            "exclusiveMinimum": 0.0,
+            "title": "Automatic Attempt Limit",
+            "type": "integer"
+          },
+          "next_attempt_at": {
+            "anyOf": [
+              {
+                "format": "date-time",
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "title": "Next Attempt At"
+          }
+        },
+        "required": [
+          "attempt",
+          "automatic_attempt_limit",
+          "next_attempt_at"
+        ],
+        "title": "PostSubmissionProgress",
+        "type": "object"
+      },
       "ProjectIntakeCheck": {
         "additionalProperties": false,
         "properties": {
diff --git a/mcp_server/tests/test_task_execution.py b/mcp_server/tests/test_task_execution.py
index 20eca7158..13f9b54c7 100644
--- a/mcp_server/tests/test_task_execution.py
+++ b/mcp_server/tests/test_task_execution.py
@@ -529,6 +529,7 @@ def _operation_progress() -> dict[str, Any]:
         "pre_submission_results": [],
         "failure_code": None,
         "operationally_stalled": False,
+        "post_submission_progress": None,
         "next_action": "wait",
     }
 

From 40378b1b899059d68f06c3a4005bae47d184cbf8 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:19:57 +0100
Subject: [PATCH 487/513] Expose explicit Operator abandonment through the
 existing reconciliation clients

---
 cli/internal/api/post_submit_delivery.go       | 18 ++++++++++--------
 cli/internal/command/post_submit_delivery.go   |  4 +++-
 docs/operations_operator_workflow.md           |  9 +++++++--
 .../post_submit_deliveries_reconcile.json      | 16 +++++++++++++++-
 mcp_server/workstream_mcp/http_gateway.py      |  4 ++++
 5 files changed, 39 insertions(+), 12 deletions(-)

diff --git a/cli/internal/api/post_submit_delivery.go b/cli/internal/api/post_submit_delivery.go
index 2f691310e..145f783e9 100644
--- a/cli/internal/api/post_submit_delivery.go
+++ b/cli/internal/api/post_submit_delivery.go
@@ -136,7 +136,7 @@ func ValidPostSubmitDeliveryReason(reason string) bool {
 	return true
 }
 
-func (c *Client) ReconcilePostSubmitDelivery(ctx context.Context, project, event, reason, key string) (Result[PostSubmitDeliveryReceipt], error) {
+func (c *Client) ReconcilePostSubmitDelivery(ctx context.Context, project, event, reason, key string, abandonUnknown bool) (Result[PostSubmitDeliveryReceipt], error) {
 	var result Result[PostSubmitDeliveryReceipt]
 	if !validUUID(project) || !validUUID(event) || !validUUID(key) || len(project) > 100 || len(event) > 100 || len(key) > 100 {
 		return result, errors.New("PROJECT_ID, EVENT_ID and --idempotency-key must be UUIDs")
@@ -144,12 +144,14 @@ func (c *Client) ReconcilePostSubmitDelivery(ctx context.Context, project, event
 	if !ValidPostSubmitDeliveryReason(reason) {
 		return result, errors.New("--reason must be 1..500 characters without surrounding whitespace or ASCII controls")
 	}
-	body, _ := json.Marshal(struct {
-		Reason string `json:"reason"`
-	}{reason})
+	bodyFields := map[string]string{"reason": reason}
+	if abandonUnknown {
+		bodyFields["action"] = "abandon_unknown"
+	}
+	body, _ := json.Marshal(bodyFields)
 	path := "/api/v1/operations/projects/" + url.PathEscape(project) + "/post-submit-deliveries/" + url.PathEscape(event) + "/reconcile"
 	raw, err := c.requestWithResponseLimit(ctx, http.MethodPost, path, "", body, key, http.StatusCreated, MaxGuideInputBytes)
-	hint := "delivery reconciliation outcome unknown; manually replay only the unchanged project, event, reason and key"
+	hint := "delivery reconciliation outcome unknown; manually replay only the unchanged project, event, action, reason and key"
 	if err != nil {
 		return result, checkerMutationFailure(err, hint)
 	}
@@ -157,7 +159,7 @@ func (c *Client) ReconcilePostSubmitDelivery(ctx context.Context, project, event
 	fields, err := contextObject(raw, &receipt, []string{"source", "successor", "authorization_decision_id"}, nil)
 	if err != nil || !validUUID(receipt.AuthorizationDecisionID) ||
 		!validDeliverySource(fields["source"], &receipt.Source, project, event) ||
-		!validDeliverySuccessor(fields["successor"], &receipt.Successor) ||
+		!validDeliverySuccessor(fields["successor"], &receipt.Successor, abandonUnknown) ||
 		receipt.Source.ReconciliationEventID == nil || !sameUUID(*receipt.Source.ReconciliationEventID, receipt.Successor.EventID) ||
 		(receipt.Source.ReconciliationState != nil && *receipt.Source.ReconciliationState == "pending" && receipt.Source.Classification != receipt.Successor.Classification) ||
 		!c.safeMutationResponse(raw) {
@@ -166,8 +168,8 @@ func (c *Client) ReconcilePostSubmitDelivery(ctx context.Context, project, event
 	return Result[PostSubmitDeliveryReceipt]{Raw: raw, Value: receipt}, nil
 }
 
-func validDeliverySuccessor(raw json.RawMessage, value *PostSubmitDeliverySuccessor) bool {
+func validDeliverySuccessor(raw json.RawMessage, value *PostSubmitDeliverySuccessor, abandonUnknown bool) bool {
 	_, err := contextObject(raw, value, []string{"event_id", "payload_digest", "occurred_at", "classification"}, nil)
 	return err == nil && validUUID(value.EventID) && contextPolicyDigest.MatchString(value.PayloadDigest) &&
-		validAuditTime(value.OccurredAt) && (value.Classification == "committed" || value.Classification == "retry_safe")
+		validAuditTime(value.OccurredAt) && ((abandonUnknown && value.Classification == "unresolved") || (!abandonUnknown && (value.Classification == "committed" || value.Classification == "retry_safe")))
 }
diff --git a/cli/internal/command/post_submit_delivery.go b/cli/internal/command/post_submit_delivery.go
index 6f79960d5..9d481cde9 100644
--- a/cli/internal/command/post_submit_delivery.go
+++ b/cli/internal/command/post_submit_delivery.go
@@ -33,6 +33,7 @@ func addPostSubmitDeliveryOperations(operations *cobra.Command, client func() (*
 	delivery.AddCommand(list)
 
 	var reason, key string
+	var abandonUnknown bool
 	reconcile := &cobra.Command{
 		Use: "reconcile PROJECT_ID EVENT_ID", Short: "Request one governed reconciliation child for an exact UNKNOWN event", Args: cobra.ExactArgs(2),
 		RunE: func(cmd *cobra.Command, args []string) error {
@@ -43,7 +44,7 @@ func addPostSubmitDeliveryOperations(operations *cobra.Command, client func() (*
 			if err != nil {
 				return err
 			}
-			result, err := apiClient.ReconcilePostSubmitDelivery(cmd.Context(), args[0], args[1], reason, key)
+			result, err := apiClient.ReconcilePostSubmitDelivery(cmd.Context(), args[0], args[1], reason, key, abandonUnknown)
 			if err != nil {
 				return err
 			}
@@ -53,6 +54,7 @@ func addPostSubmitDeliveryOperations(operations *cobra.Command, client func() (*
 			return writeTaskContextFields(stdout, []contextField{{"Post-submit delivery reconciliation receipt (not acceptance)", result.Raw}})
 		},
 	}
+	reconcile.Flags().BoolVar(&abandonUnknown, "abandon-unknown", false, "Supersede the expired unresolved attempt and request another evaluation")
 	reconcile.Flags().StringVar(&reason, "reason", "", "Required operator explanation, 1..500 characters")
 	reconcile.Flags().StringVar(&key, "idempotency-key", "", "Required caller-owned UUID; reuse unchanged only for manual replay")
 	delivery.AddCommand(reconcile)
diff --git a/docs/operations_operator_workflow.md b/docs/operations_operator_workflow.md
index 4da49279f..d1c76dc05 100644
--- a/docs/operations_operator_workflow.md
+++ b/docs/operations_operator_workflow.md
@@ -203,16 +203,21 @@ raw event payloads, exception text, artifact contents or provider details.
 |---|---|
 | `committed` | The source owner verifies the exact retained checker result or routing effects. Reconciliation acknowledges those facts without another checker execution or acceptance. |
 | `retry_safe` | Current durable facts prove the original source has no execution or routing effect. Reconciliation may invoke the existing owner after checking the facts again under its locks. |
-| `unresolved` | Facts are incomplete, stale or uncertain. Keep the delivery held; this surface cannot authorize another attempt. |
+| `unresolved` | Facts are incomplete, stale or uncertain. Keep the delivery held until an Operator investigates. For an expired checker attempt, an Operator can explicitly abandon the unknown result and request a successor. |
 
 For a `committed` or `retry_safe` source without an existing child, send a bounded
 reason and one UUID `Idempotency-Key` to
 `POST /api/v1/operations/projects/{project_id}/post-submit-deliveries/{event_id}/reconcile`.
 This schedules one durable reconciliation child; it does not synchronously run
 the checker or accept the Submission. On response loss, repeat the exact project,
-event, reason and key. Fresh authority is required for replay, which returns the
+event, action, reason and key. Fresh authority is required for replay, which returns the
 same child. Every different key conflicts once a child exists.
 
+For a confirmed expired attempt whose result remains unknown, use
+`workstream operations delivery reconcile PROJECT_ID EVENT_ID --abandon-unknown --reason REASON --idempotency-key UUID`.
+API and MCP callers supply `"action": "abandon_unknown"` in the reconciliation body.
+The successor uses the same Submission. The original attempt keeps its unknown outcome.
+
 After a child is scheduled, `source.classification` records the scheduling
 decision, while `reconciliation_state` reports the child's current progress or
 outcome. For example, a `retry_safe` source can have an `acknowledged` child.
diff --git a/mcp_server/contracts/post_submit_deliveries_reconcile.json b/mcp_server/contracts/post_submit_deliveries_reconcile.json
index eb20766f4..4596f6104 100644
--- a/mcp_server/contracts/post_submit_deliveries_reconcile.json
+++ b/mcp_server/contracts/post_submit_deliveries_reconcile.json
@@ -84,6 +84,19 @@
         "additionalProperties": false,
         "description": "Public reason for one exact uncertain-delivery reconciliation.",
         "properties": {
+          "action": {
+            "anyOf": [
+              {
+                "const": "abandon_unknown",
+                "type": "string"
+              },
+              {
+                "type": "null"
+              }
+            ],
+            "default": null,
+            "title": "Action"
+          },
           "reason": {
             "maxLength": 500,
             "minLength": 1,
@@ -258,7 +271,8 @@
           "classification": {
             "enum": [
               "committed",
-              "retry_safe"
+              "retry_safe",
+              "unresolved"
             ],
             "title": "Classification",
             "type": "string"
diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py
index 6db950a73..8a5709d8a 100644
--- a/mcp_server/workstream_mcp/http_gateway.py
+++ b/mcp_server/workstream_mcp/http_gateway.py
@@ -1971,6 +1971,10 @@ def _checker_artifact_response_matches(
             )
         if name == "post_submit_deliveries_reconcile":
             source = data.get("source")
+            successor = data.get("successor")
+            abandoning = arguments["body"].get("action") == "abandon_unknown"
+            if not isinstance(successor, dict) or (successor.get("classification") == "unresolved") != abandoning:
+                return False
             return isinstance(source, dict) and cls._fields_match(
                 source,
                 {

From cd91458eead32e3b0b5e08381aeb62e177435ac9 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:20:53 +0100
Subject: [PATCH 488/513] Let Operators explicitly abandon an expired
 unresolved POST lease

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  21 +++
 .../0095_post_infrastructure_retry.py         | 128 ++++++++++++++++--
 backend/app/api/deps/checker_recovery.py      |   4 +-
 .../checkers/api/delivery_reconciliation.py   |  43 +++++-
 backend/app/modules/checkers/api/execution.py |  12 +-
 backend/app/modules/checkers/checker_retry.py |  42 ++++--
 .../checkers/delivery_reconciliation.py       |  20 ++-
 .../delivery_reconciliation_handler.py        |   8 ++
 .../checkers/execution_coordination.py        |  87 ++++++++----
 backend/app/modules/checkers/models.py        |  13 +-
 .../test_delivery_reconciliation_public.py    |  79 ++++++++++-
 backend/tests/conftest.py                     |   2 +-
 .../evaluation_delivery/test_delivery.py      |   2 +-
 .../tests/test_checker_evidence_migrations.py |   4 +-
 14 files changed, 395 insertions(+), 70 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index abada6bfd..1762963b5 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13299,3 +13299,24 @@ or uncertain invocation does not qualify for a successor. Verify one exact
 backoff event after a known failure, replay or rollback behavior, bounded
 exhaustion, and the contributor's attempt numbers and recovery action. Workflow
 and authorization review should examine the transaction and SQL guard together.
+
+### Explicit Operator abandonment of an unresolved POST execution
+
+The original hosted maximum-size attempt has finalized UNKNOWN delivery custody
+and a running checker without a result. The user wants an Operator-controlled
+recovery after automated handling cannot safely conclude. Extend the existing
+POST delivery reconciliation command and child handler with an explicit
+`abandon_unknown` choice. It binds the exact expired checker lease and original
+UNKNOWN delivery to the existing audited Operator reason. The child rechecks
+TASK and CHECKERS currentness, the original delivery and its own active
+invocation before atomically inserting one successor through the existing
+reservation owner. The original run and receipt remain unchanged.
+
+Allowed additional changes are the existing reconciliation contracts, service,
+handler, authorization request composition, Operator CLI/MCP contracts and the
+0095 custody guard and tests. This security-sensitive path must deny live or
+changed leases, ordinary unresolved reconciliation, completion-delivery
+abandonment, stale Operator authority, duplicate successors and late old-owner
+writes. It does not prove the provider stopped and does not authorize automatic
+retry of an unresolved invocation. Check exact replay, whole-transaction rollback
+and late-effect fencing through the existing signed Operator and database tests.
diff --git a/backend/alembic/versions/0095_post_infrastructure_retry.py b/backend/alembic/versions/0095_post_infrastructure_retry.py
index 7e39e96fa..53495d290 100644
--- a/backend/alembic/versions/0095_post_infrastructure_retry.py
+++ b/backend/alembic/versions/0095_post_infrastructure_retry.py
@@ -11,19 +11,29 @@
 
 def upgrade() -> None:
     """Extend the failed-supersession guard with an exact automatic source."""
-    op.add_column("checker_runs", sa.Column("automatic_retry_event_id", sa.Uuid(), nullable=True))
+    op.add_column("checker_runs", sa.Column("retry_delivery_event_id", sa.Uuid(), nullable=True))
     op.create_unique_constraint(
-        "uq_checker_runs_automatic_retry_event_id", "checker_runs", ["automatic_retry_event_id"],
+        "uq_checker_runs_retry_delivery_event_id", "checker_runs", ["retry_delivery_event_id"],
     )
     op.create_foreign_key(
-        "fk_checker_runs_automatic_retry_event", "checker_runs", "outbox_events",
-        ["automatic_retry_event_id"], ["event_id"],
+        "fk_checker_runs_retry_delivery_event", "checker_runs", "outbox_events",
+        ["retry_delivery_event_id"], ["event_id"],
+    )
+    op.add_column("checker_runs", sa.Column("retry_abandonment_event_id", sa.Uuid(), nullable=True))
+    op.create_unique_constraint(
+        "uq_checker_runs_retry_abandonment_event_id", "checker_runs", ["retry_abandonment_event_id"],
+    )
+    op.create_foreign_key(
+        "fk_checker_runs_retry_abandonment_event", "checker_runs", "outbox_events",
+        ["retry_abandonment_event_id"], ["event_id"],
     )
     op.create_check_constraint(
-        op.f("ck_checker_runs_automatic_retry_scope"), "checker_runs",
-        "automatic_retry_event_id IS NULL OR (supersedes_checker_run_id IS NOT NULL "
-        "AND evaluation_generation BETWEEN 2 AND 5)",
+        op.f("ck_checker_runs_service_retry_scope"), "checker_runs",
+        "(retry_abandonment_event_id IS NULL OR retry_delivery_event_id IS NOT NULL) AND "
+        "(retry_delivery_event_id IS NULL OR (supersedes_checker_run_id IS NOT NULL "
+        "AND (retry_abandonment_event_id IS NOT NULL OR evaluation_generation BETWEEN 2 AND 5)))",
     )
+    op.execute(_ABANDONMENT_GUARD)
     op.execute("""
     CREATE OR REPLACE FUNCTION public.require_checker_failed_supersession_receipt() RETURNS trigger
     LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
@@ -32,7 +42,13 @@ def upgrade() -> None:
       IF TG_OP <> 'UPDATE' THEN RETURN NULL; END IF;
       SELECT * INTO prior FROM public.checker_runs WHERE id=OLD.current_run_id;
       SELECT * INTO successor FROM public.checker_runs WHERE id=NEW.current_run_id;
-      IF successor.automatic_retry_event_id IS NOT NULL THEN
+      IF successor.retry_abandonment_event_id IS NOT NULL THEN
+        IF NOT public.checker_post_submit_abandonment_valid(prior,successor) THEN
+          RAISE EXCEPTION 'checker abandonment requires the exact expired invocation and Operator cause' USING ERRCODE='23514';
+        END IF;
+        RETURN NULL;
+      END IF;
+      IF successor.retry_delivery_event_id IS NOT NULL THEN
         IF prior.status IS DISTINCT FROM 'infrastructure_failed'
           OR prior.completed_at IS NULL OR prior.completion_event_id IS NOT NULL
           OR prior.routing_recommendation IS DISTINCT FROM 'not_evaluated'
@@ -46,7 +62,7 @@ def upgrade() -> None:
           OR NOT public.checker_post_submit_receipt_valid(prior,'finalize',false)
           OR NOT EXISTS (
             SELECT 1 FROM public.outbox_events e
-            WHERE e.event_id=successor.automatic_retry_event_id
+            WHERE e.event_id=successor.retry_delivery_event_id
               AND e.event_type='PostSubmissionEvaluationRequested' AND e.event_version=1
               AND e.producer='workstream' AND e.aggregate_type='submission'
               AND e.project_id=successor.project_id AND e.aggregate_id=successor.submission_id
@@ -83,3 +99,97 @@ def upgrade() -> None:
 def downgrade() -> None:
     """Keep scheduled successor references valid for their retained runs."""
     raise RuntimeError("POST infrastructure retry migration is forward-only")
+
+
+_ABANDONMENT_GUARD = """
+CREATE FUNCTION public.checker_post_submit_abandonment_valid(
+  source public.checker_runs, successor public.checker_runs
+) RETURNS boolean LANGUAGE sql SET search_path=pg_catalog,public,pg_temp AS $$
+  SELECT coalesce(source.status='running' AND source.result_json IS NULL
+    AND source.worker_lease_id IS NOT NULL AND source.worker_lease_expires_at<=clock_timestamp()
+    AND successor.supersedes_checker_run_id=source.id
+    AND successor.evaluation_generation=source.evaluation_generation+1
+    AND successor.request_json::jsonb - ARRAY['evaluation_request_id','evaluation_generation']
+          = source.request_json::jsonb - ARRAY['evaluation_request_id','evaluation_generation']
+    AND EXISTS (
+      SELECT 1 FROM public.outbox_events c
+      JOIN public.outbox_delivery_attempts ca ON ca.event_id=c.event_id AND ca.claim_generation=c.claim_generation
+      JOIN public.outbox_events o ON o.event_id=c.causation_event_id
+      JOIN public.outbox_delivery_attempts oa ON oa.event_id=o.event_id AND oa.claim_generation=o.claim_generation
+      JOIN public.audit_events a ON a.id::text=c.payload->>'authorization_decision_id'
+      JOIN public.actor_profiles actor ON actor.id::text=a.actor_id AND actor.actor_kind='human'
+      JOIN public.admin_role_grants g ON g.id::text=a.matched_grant_id AND g.target_actor_profile_id=actor.id
+      JOIN public.actor_identity_links l ON l.actor_profile_id=actor.id
+        AND l.id::text=c.payload->>'operator_identity_link_id'
+      JOIN public.outbox_events e ON e.event_id=successor.retry_delivery_event_id
+      CROSS JOIN LATERAL (
+        SELECT ((c.payload->>'authorization_resource_json')::jsonb)->'resource_context' AS data
+      ) r
+      WHERE c.event_id=successor.retry_abandonment_event_id
+        AND o.event_type='PostSubmissionEvaluationRequested' AND o.event_version=1
+        AND o.project_id=source.project_id AND o.aggregate_id=source.submission_id
+        AND o.payload->>'request_id'=source.evaluation_request_id::text
+        AND o.payload->>'request_digest'=source.request_digest
+        AND o.payload->>'attempt_id'=source.id::text
+        AND o.delivery_state='dead_letter' AND o.last_error_code='INVOKE_OUTCOME_UNKNOWN'
+        AND oa.stage='completed' AND oa.finalize_decision_event_id IS NOT NULL
+        AND oa.payload_digest=o.payload_digest AND oa.project_id=o.project_id
+        AND oa.outcome_json::jsonb->>'invocation_unknown'='true'
+        AND c.event_type='PostSubmissionDeliveryReconciliationRequested' AND c.event_version=1
+        AND c.producer='workstream' AND c.project_id=o.project_id
+        AND c.aggregate_type='outbox_delivery' AND c.aggregate_id=o.event_id
+        AND c.idempotency_key='post-submit-reconcile:'||o.event_id::text
+        AND c.delivery_state='claimed' AND ca.stage='invoked' AND ca.claim_expires_at>clock_timestamp()
+        AND ca.project_id=c.project_id AND ca.payload_digest=c.payload_digest
+        AND ca.finalize_decision_event_id IS NULL
+        AND c.payload->>'classification'='unresolved'
+        AND c.payload->>'checker_run_id'=source.id::text
+        AND c.payload->>'evaluation_request_id'=source.evaluation_request_id::text
+        AND c.payload->>'evaluation_generation'=source.evaluation_generation::text
+        AND c.payload->>'original_event_id'=o.event_id::text
+        AND c.payload->>'original_event_type'=o.event_type
+        AND c.payload->>'original_event_version'=o.event_version::text
+        AND c.payload->>'original_claim_generation'=oa.claim_generation::text
+        AND c.payload->>'original_payload_digest'=o.payload_digest
+        AND c.payload#>>'{abandonment,lease_id}'=source.worker_lease_id::text
+        AND c.payload#>>'{abandonment,lease_generation}'=source.worker_lease_generation::text
+        AND (c.payload#>>'{abandonment,expires_at}')::timestamptz=source.worker_lease_expires_at
+        AND r.data#>'{preparation,abandonment}'=c.payload->'abandonment'
+        AND r.data->>'resource_type'='outbox_delivery'
+        AND r.data->>'resource_id'=o.event_id::text AND r.data->>'scope_project_id'=source.project_id::text
+        AND r.data->>'identity_link_id'=l.id::text
+        AND r.data#>>'{preparation,command,action}'='abandon_unknown'
+        AND r.data#>>'{preparation,command,actor_profile_id}'=actor.id::text
+        AND r.data#>>'{preparation,command,event_id}'=o.event_id::text
+        AND r.data#>>'{preparation,command,project_id}'=source.project_id::text
+        AND r.data#>>'{preparation,command,request_key}'=a.request_id::text
+        AND r.data#>>'{preparation,source,event_id}'=o.event_id::text
+        AND r.data#>>'{preparation,source,checker_run_id}'=source.id::text
+        AND r.data#>>'{preparation,source,classification}'='unresolved'
+        AND g.role='operator' AND g.scope_type='system' AND g.scope_project_id IS NULL
+        AND a.event_domain='authority' AND a.event_type='SensitiveAuthorizationAllowed'
+        AND a.actor_ref_kind='actor_profile' AND a.actor_id=c.payload->>'operator_actor_profile_id'
+        AND a.project_id=source.project_id AND a.action_id='operations.post_submit_delivery.reconcile'
+        AND a.permission_id='operations.reconcile.run' AND a.resource_type='outbox_delivery'
+        AND a.resource_id=o.event_id::text AND a.request_id::text=c.payload->>'reconciliation_request_id'
+        AND a.correlation_id=a.request_id AND a.denial_code IS NULL
+        AND a.after_facts::jsonb=jsonb_build_object('allowed',true,'resource_context_digest',
+          'sha256:'||encode(sha256(convert_to(public.project_guide_projection_canonical_json(
+            jsonb_strip_nulls(jsonb_build_object('resource_context',r.data))), 'UTF8')), 'hex'))
+        AND e.event_type='PostSubmissionEvaluationRequested' AND e.event_version=1
+        AND e.producer='workstream' AND e.aggregate_type='submission'
+        AND e.project_id=successor.project_id AND e.aggregate_id=successor.submission_id
+        AND e.correlation_id=source.id::text AND e.causation_event_id=c.event_id
+        AND e.idempotency_key='checker-abandonment-retry:'||source.id::text
+        AND e.delivery_state='pending' AND e.not_before_at IS NULL
+        AND e.payload::jsonb=jsonb_build_object(
+          'project_id',successor.project_id,'task_id',successor.task_id,
+          'submission_id',successor.submission_id,'submission_version',successor.submission_version,
+          'request_id',successor.evaluation_request_id,'request_digest',successor.request_digest,
+          'evaluation_generation',successor.evaluation_generation,'attempt_id',successor.id,
+          'result_id',successor.result_id,'source_run_id',source.id,
+          'source_worker_lease_id',source.worker_lease_id,'source_worker_lease_generation',source.worker_lease_generation
+        )
+    ),false)
+$$
+"""
diff --git a/backend/app/api/deps/checker_recovery.py b/backend/app/api/deps/checker_recovery.py
index fbf321912..2f8de4c4d 100644
--- a/backend/app/api/deps/checker_recovery.py
+++ b/backend/app/api/deps/checker_recovery.py
@@ -161,13 +161,15 @@ def __init__(self, session, service, key, actor_profile_id) -> None:
         self._key, self._actor_profile_id = key, actor_profile_id
 
     async def reconcile(self, project_id, event_id, payload):
+        checked = PostSubmitDeliveryRequest.model_validate(payload)
         result = await self._service.reconcile(
             PostSubmitDeliveryCommand(
                 actor_profile_id=self._actor_profile_id,
                 project_id=project_id,
                 event_id=event_id,
                 request_key=self._key,
-                reason=PostSubmitDeliveryRequest.model_validate(payload).reason,
+                reason=checked.reason,
+                action=checked.action,
             )
         )
         await self._session.commit()
diff --git a/backend/app/modules/checkers/api/delivery_reconciliation.py b/backend/app/modules/checkers/api/delivery_reconciliation.py
index 96c1d72f7..d4b6921b8 100644
--- a/backend/app/modules/checkers/api/delivery_reconciliation.py
+++ b/backend/app/modules/checkers/api/delivery_reconciliation.py
@@ -86,6 +86,7 @@ class PostSubmitDeliveryRequest(BaseModel):
 
     model_config = _STRICT
     reason: PostSubmitDeliveryReason
+    action: Literal["abandon_unknown"] | None = None
 
 
 class PostSubmitDeliveryQuery(BaseModel):
@@ -193,6 +194,16 @@ class PostSubmitDeliveryCommand(BaseModel):
     event_id: UUID
     request_key: UUID
     reason: PostSubmitDeliveryReason
+    action: Literal["abandon_unknown"] | None = Field(default=None, exclude_if=lambda value: value is None)
+
+
+class PostSubmitExpiredLease(BaseModel):
+    """Exact worker custody displaced by an explicit Operator decision."""
+
+    model_config = _STRICT
+    lease_id: UUID
+    lease_generation: int = Field(ge=1)
+    expires_at: AwareDatetime
 
 
 class PostSubmitDeliveryPreparation(BaseModel):
@@ -201,13 +212,16 @@ class PostSubmitDeliveryPreparation(BaseModel):
     model_config = _STRICT
     command: PostSubmitDeliveryCommand
     source: PostSubmitDeliverySource
+    abandonment: PostSubmitExpiredLease | None = Field(default=None, exclude_if=lambda value: value is None)
 
     @model_validator(mode="after")
     def exact_source(self):
         if (
             self.command.project_id != self.source.project_id
             or self.command.event_id != self.source.event_id
-            or self.source.classification == "unresolved"
+            or (self.source.classification == "unresolved") != (self.abandonment is not None)
+            or (self.command.action == "abandon_unknown") != (self.abandonment is not None)
+            or (self.abandonment is not None and self.source.event_type != "PostSubmissionEvaluationRequested")
             or self.source.reconciliation_event_id is not None
         ):
             raise ValueError("post-submit delivery preparation differs")
@@ -245,7 +259,8 @@ class PostSubmitDeliveryChildPayload(BaseModel):
     evaluation_request_id: UUID
     checker_run_id: UUID
     evaluation_generation: int = Field(ge=1)
-    classification: Literal["committed", "retry_safe"]
+    classification: Literal["committed", "retry_safe", "unresolved"]
+    abandonment: PostSubmitExpiredLease | None = Field(default=None, exclude_if=lambda value: value is None)
     reconciliation_request_id: UUID
     request_digest: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
     authorization_decision_id: UUID
@@ -257,6 +272,10 @@ class PostSubmitDeliveryChildPayload(BaseModel):
     @model_validator(mode="after")
     def exact_authorization_resource(self):
         """Retain one canonical bounded Operator resource receipt."""
+        if (self.classification == "unresolved") != (self.abandonment is not None) or (
+            self.abandonment is not None and self.original_event_type != "PostSubmissionEvaluationRequested"
+        ):
+            raise ValueError("delivery abandonment facts differ")
         try:
             resource = json.loads(self.authorization_resource_json)
         except (TypeError, ValueError) as exc:
@@ -276,6 +295,24 @@ def exact_authorization_resource(self):
             != self.authorization_resource_digest
         ):
             raise ValueError("delivery authorization resource differs")
+        if self.abandonment is not None:
+            try:
+                preparation = PostSubmitDeliveryPreparation.model_validate_json(
+                    json.dumps(resource["resource_context"]["preparation"]),
+                )
+            except (KeyError, TypeError, ValueError) as exc:
+                raise ValueError("delivery abandonment authority is invalid") from exc
+            source, command = preparation.source, preparation.command
+            if (preparation.abandonment != self.abandonment or command.action != "abandon_unknown"
+                    or command.request_key != self.reconciliation_request_id
+                    or command.actor_profile_id != self.operator_actor_profile_id
+                    or source.event_id != self.original_event_id
+                    or source.claim_generation != self.original_claim_generation
+                    or source.payload_digest != self.original_payload_digest
+                    or source.checker_run_id != self.checker_run_id
+                    or source.evaluation_request_id != self.evaluation_request_id
+                    or source.evaluation_generation != self.evaluation_generation):
+                raise ValueError("delivery abandonment authority differs")
         return self
 
 
@@ -286,7 +323,7 @@ class PostSubmitDeliverySuccessor(BaseModel):
     event_id: UUID
     payload_digest: str = Field(pattern=r"^sha256:[0-9a-f]{64}$")
     occurred_at: AwareDatetime
-    classification: Literal["committed", "retry_safe"]
+    classification: Literal["committed", "retry_safe", "unresolved"]
 
 
 class PostSubmitDeliveryAuthorityReceipt(BaseModel):
diff --git a/backend/app/modules/checkers/api/execution.py b/backend/app/modules/checkers/api/execution.py
index 82c9e7895..f8a138256 100644
--- a/backend/app/modules/checkers/api/execution.py
+++ b/backend/app/modules/checkers/api/execution.py
@@ -28,7 +28,7 @@
     VersionNumber,
 )
 from app.modules.checkers.api.delivery_reconciliation import (
-    PostSubmitRequestDeliveryFacts,
+    PostSubmitExpiredLease, PostSubmitRequestDeliveryFacts,
 )
 from app.modules.model_usage.api import ModelRecoveryCandidate
 from app.modules.outbox.api import DeliveryOptions
@@ -599,6 +599,16 @@ async def read_current_progress(
         """Observe exact current attempt under caller-owned TASK-first custody."""
         ...
 
+    async def require_expired_unknown_lease(self, request: PostSubmissionExecutionRequest) -> PostSubmitExpiredLease:
+        """Lock exact current TASK and CHECKERS custody for explicit abandonment."""
+        ...
+
+    async def reserve_abandoned_evaluation(
+        self, request: PostSubmissionExecutionRequest, lease: PostSubmitExpiredLease, cause: ResourceId,
+    ) -> EvaluationReservation:
+        """Reserve one successor under exact authorized reconciliation child custody."""
+        ...
+
     async def read_retry_delivery(
         self, *, project_id: ResourceId, submission_id: ResourceId,
         event_id: ResourceId,
diff --git a/backend/app/modules/checkers/checker_retry.py b/backend/app/modules/checkers/checker_retry.py
index a53051903..c8540ee07 100644
--- a/backend/app/modules/checkers/checker_retry.py
+++ b/backend/app/modules/checkers/checker_retry.py
@@ -142,6 +142,35 @@ def _successor_from_receipt(receipt: CheckerRetryReceipt) -> CheckerRetrySuccess
         raise CheckerRetryOperationUnavailable("checker_retry_replay_unavailable") from exc
 
 
+def retry_successor_request(previous: PostSubmissionExecutionRequest) -> PostSubmissionExecutionRequest:
+    """Retain every locked request fact apart from identity and generation."""
+    return make_selected_post_submit_request(
+        **previous.model_dump(exclude={"evaluation_request_id", "evaluation_generation", "request_sha256"}),
+        evaluation_request_id=new_record_id(), evaluation_generation=previous.evaluation_generation + 1,
+    )
+
+
+def abandoned_retry_event(prior: CheckerRun, successor: CheckerRun, cause: UUID) -> OutboxAppendInput:
+    """Record an explicit abandonment child without asserting a checker result."""
+    if prior.status != "running" or prior.worker_lease_id is None:
+        raise CheckerRetrySourceUnavailable("checker_abandonment_source_unavailable")
+    return OutboxAppendInput(
+        event_type=REQUEST_EVENT, event_version=1, aggregate_type="submission",
+        aggregate_id=UUID(successor.submission_id), project_id=UUID(successor.project_id),
+        correlation_id=prior.id, causation_event_id=cause,
+        idempotency_key="checker-abandonment-retry:" + prior.id,
+        payload={
+            "project_id": successor.project_id, "task_id": successor.task_id,
+            "submission_id": successor.submission_id, "submission_version": successor.submission_version,
+            "request_id": successor.evaluation_request_id, "request_digest": successor.request_digest,
+            "evaluation_generation": successor.evaluation_generation, "attempt_id": successor.id,
+            "result_id": successor.result_id, "source_run_id": prior.id,
+            "source_worker_lease_id": prior.worker_lease_id,
+            "source_worker_lease_generation": prior.worker_lease_generation,
+        },
+    )
+
+
 def automatic_retry_event(prior: CheckerRun, successor: CheckerRun) -> OutboxAppendInput:
     """Use the committed fixed-service finalization as the automatic retry cause."""
     _, source = require_finalized_infrastructure_source(prior)
@@ -486,18 +515,7 @@ async def retry(self, command: CheckerRetryCommand) -> CheckerRetryResult:
         )
         handle = await self._authorization.prepare(preparation)
         try:
-            request_fields = {
-                **source_request.model_dump(
-                    exclude={
-                        "evaluation_request_id",
-                        "evaluation_generation",
-                        "request_sha256",
-                    }
-                ),
-                "evaluation_request_id": new_record_id(),
-                "evaluation_generation": source.source_generation + 1,
-            }
-            next_request = make_selected_post_submit_request(**request_fields)
+            next_request = retry_successor_request(source_request)
             try:
                 reserved = await self._evaluations._reserve_after_task_lock(
                     next_request,
diff --git a/backend/app/modules/checkers/delivery_reconciliation.py b/backend/app/modules/checkers/delivery_reconciliation.py
index e12e22afa..57a368e90 100644
--- a/backend/app/modules/checkers/delivery_reconciliation.py
+++ b/backend/app/modules/checkers/delivery_reconciliation.py
@@ -289,10 +289,17 @@ async def reconcile(
         classification = classified[0]
         if delivery.child is not None:
             return await self._replay(command, delivery, classified)
-        if classification == "unresolved":
+        abandonment = None
+        if command.action == "abandon_unknown" and classification == "unresolved" and delivery.envelope.event_type == REQUEST_EVENT:
+            try:
+                request = await self._requests.read(delivery.envelope)
+                abandonment = await self._evaluations.require_expired_unknown_lease(request)
+            except (PostSubmitDeliverySourceUnavailable, CheckerExecutionUnavailable) as exc:
+                raise PostSubmitDeliveryUnavailable("post_submit_delivery_unresolved") from exc
+        elif classification == "unresolved" or command.action is not None:
             raise PostSubmitDeliveryUnavailable("post_submit_delivery_unresolved")
         source = _public_source(delivery, classified)
-        preparation = PostSubmitDeliveryPreparation(command=command, source=source)
+        preparation = PostSubmitDeliveryPreparation(command=command, source=source, abandonment=abandonment)
         handle = await self._authorization.prepare(preparation)
         try:
             authority = await self._authorization.consume(handle, preparation)
@@ -313,6 +320,7 @@ async def reconcile(
                 checker_run_id=source.checker_run_id,
                 evaluation_generation=source.evaluation_generation,
                 classification=classification,
+                abandonment=abandonment,
                 reconciliation_request_id=command.request_key,
                 request_digest=post_submit_delivery_request_digest(preparation),
                 authorization_decision_id=authority.decision_id,
@@ -409,14 +417,16 @@ async def _replay(
                 payload.evaluation_generation,
             ),
         )
+        # Revalidate authority for the retained decision before revealing a mode conflict.
+        action = "abandon_unknown" if payload.abandonment is not None else None
         preparation = PostSubmitDeliveryPreparation(
-            command=command,
-            source=scheduled_source,
+            command=command.model_copy(update={"action": action}),
+            source=scheduled_source, abandonment=payload.abandonment,
         )
         handle = await self._authorization.prepare(preparation)
         try:
             await self._authorization.authorize_replay(handle, preparation)
-            if payload.request_digest != post_submit_delivery_request_digest(preparation):
+            if command.action != action or payload.request_digest != post_submit_delivery_request_digest(preparation):
                 raise PostSubmitDeliveryConflict(
                     "post_submit_delivery_request_conflict"
                 )
diff --git a/backend/app/modules/checkers/delivery_reconciliation_handler.py b/backend/app/modules/checkers/delivery_reconciliation_handler.py
index b0a7b391b..cb0ad8bfa 100644
--- a/backend/app/modules/checkers/delivery_reconciliation_handler.py
+++ b/backend/app/modules/checkers/delivery_reconciliation_handler.py
@@ -266,6 +266,14 @@ async def validate_cause() -> None:
         if original.event_type == REQUEST_EVENT:
             evaluations = self._evaluations(session)
             request = await self._requests(session, evaluations).read(original)
+            if payload.abandonment is not None:
+                if await evaluations.require_expired_unknown_lease(request) != payload.abandonment:
+                    return HandlerOutcome.REJECT
+                await validate_cause()
+                if await custody.fence_invocation(original) is None:
+                    return HandlerOutcome.REJECT
+                await evaluations.reserve_abandoned_evaluation(request, payload.abandonment, child.claim.event_id)
+                return HandlerOutcome.ACKNOWLEDGE
             facts = await evaluations.classify_uncertain_delivery(request)
             if facts.classification == "committed":
                 await validate_cause()
diff --git a/backend/app/modules/checkers/execution_coordination.py b/backend/app/modules/checkers/execution_coordination.py
index 9807e0458..e708096e9 100644
--- a/backend/app/modules/checkers/execution_coordination.py
+++ b/backend/app/modules/checkers/execution_coordination.py
@@ -27,10 +27,10 @@
     validate_execution_request,
 )
 from app.modules.checkers.api.delivery_reconciliation import (
-    PostSubmitRequestDeliveryFacts,
+    PostSubmitExpiredLease, PostSubmitRequestDeliveryFacts,
 )
 from app.modules.checkers.api.selected_post_submit import (
-    SelectedPostSubmitCurrentResultReference, make_selected_post_submit_request,
+    SelectedPostSubmitCurrentResultReference,
 )
 from app.modules.checkers.execution_repository import (
     ExecutionRepository,
@@ -70,23 +70,43 @@ async def reserve_current_evaluation(
 
     async def schedule_automatic_retry(self, run: CheckerRun) -> None:
         """Reserve a delayed successor only from exact known terminal custody."""
-        from app.modules.checkers.checker_retry import require_finalized_infrastructure_source
+        from app.modules.checkers.checker_retry import require_finalized_infrastructure_source, retry_successor_request
 
         if run.evaluation_generation >= POST_SUBMISSION_RETRY_OPTIONS.max_attempts:
             return
         previous, source = require_finalized_infrastructure_source(run)
         await self._tasks.lock_terminal_retry_scope(previous)
-        next_request = make_selected_post_submit_request(
-            **previous.model_dump(exclude={"evaluation_request_id", "evaluation_generation", "request_sha256"}),
-            evaluation_request_id=new_record_id(), evaluation_generation=source.source_generation + 1,
-        )
         await self._reserve_after_task_lock(
-            next_request, terminal_source_id=source.source_run_id, automatic_retry=True,
+            retry_successor_request(previous), terminal_source_id=source.source_run_id, automatic_retry=True,
+        )
+
+    async def require_expired_unknown_lease(self, request: PostSubmissionExecutionRequest) -> PostSubmitExpiredLease:
+        """Require exact still-current invocation custody with no retained result."""
+        await self._tasks.lock_terminal_retry_scope(request)
+        repo = ExecutionRepository(self._session)
+        run = await repo.lock_current(request)
+        if (run.status != "running" or run.worker_lease_id is None or run.worker_lease_expires_at is None
+                or run.worker_lease_expires_at > await repo.now() or run.result_json is not None):
+            raise CheckerRetrySourceUnavailable("checker_abandonment_source_unavailable")
+        return PostSubmitExpiredLease(lease_id=UUID(run.worker_lease_id), lease_generation=run.worker_lease_generation,
+                                      expires_at=run.worker_lease_expires_at)
+
+    async def reserve_abandoned_evaluation(
+        self, request: PostSubmissionExecutionRequest, lease: PostSubmitExpiredLease, cause: UUID,
+    ) -> EvaluationReservation:
+        """Atomically displace the same exact expired worker without terminalizing it."""
+        from app.modules.checkers.checker_retry import retry_successor_request
+
+        if await self.require_expired_unknown_lease(request) != lease:
+            raise CheckerRetrySourceUnavailable("checker_abandonment_source_unavailable")
+        run = await ExecutionRepository(self._session).lock_current(request)
+        return await self._reserve_after_task_lock(
+            retry_successor_request(request), terminal_source_id=UUID(run.id), abandonment_event_id=cause,
         )
 
     async def _reserve_after_task_lock(
         self, request: PostSubmissionExecutionRequest, *, terminal_source_id: UUID | None = None,
-        automatic_retry: bool = False,
+        automatic_retry: bool = False, abandonment_event_id: UUID | None = None,
     ) -> EvaluationReservation:
         """Use the existing CHECKERS locks after the caller has retained TASK custody."""
         require_transaction(self._session)
@@ -116,10 +136,11 @@ async def _reserve_after_task_lock(
                 .with_for_update()
                 .execution_options(populate_existing=True)
             )
-        if terminal_source_id is not None:
+        if terminal_source_id is not None and (prior is None or prior.id != str(terminal_source_id)):
+            raise CheckerRetrySourceUnavailable("checker_retry_source_unavailable")
+        if terminal_source_id is not None and abandonment_event_id is None:
             if (
-                prior is None or prior.id != str(terminal_source_id)
-                or prior.status != "infrastructure_failed"
+                prior.status != "infrastructure_failed"
                 or prior.finalize_evidence_id is None
                 or prior.result_json is None or prior.result_digest is None
                 or prior.completion_event_id is not None
@@ -163,13 +184,16 @@ async def _reserve_after_task_lock(
             locked_revision_policy_generation=context.revision_generation,
             locked_revision_policy_hash=context.revision_hash,
         )
-        if automatic_retry:
-            from app.modules.checkers.checker_retry import automatic_retry_event
+        if automatic_retry or abandonment_event_id is not None:
+            from app.modules.checkers.checker_retry import abandoned_retry_event, automatic_retry_event
 
             if terminal_source_id is None or prior is None:
-                raise CheckerRetrySourceUnavailable("checker_automatic_retry_source_unavailable")
-            appended = await self._events.append(automatic_retry_event(prior, run))
-            run.automatic_retry_event_id = appended.event_id
+                raise CheckerRetrySourceUnavailable("checker_retry_source_unavailable")
+            event = (abandoned_retry_event(prior, run, abandonment_event_id) if abandonment_event_id is not None
+                     else automatic_retry_event(prior, run))
+            appended = await self._events.append(event)
+            run.retry_delivery_event_id = appended.event_id
+            run.retry_abandonment_event_id = abandonment_event_id
         self._session.add(run)
         try:
             await self._session.flush()
@@ -239,7 +263,7 @@ async def read_current_progress(
         if (current.request.assignment_id != original.request.assignment_id
                 or current.request.submission_version != original.request.submission_version):
             raise CheckerExecutionUnavailable(unavailable)
-        retry_event_id = run.automatic_retry_event_id
+        retry_event_id = run.retry_delivery_event_id
         delivery_event = None
         previous_failure_code = None
         if current.reservation.attempt_id == original.reservation.attempt_id:
@@ -262,7 +286,7 @@ async def read_current_progress(
                     project_id=project_id, submission_id=submission_id, event_id=retry_event_id,
                 )
             else:
-                retained, previous_failure_code = await self._read_automatic_retry(run)
+                retained, previous_failure_code = await self._read_service_retry(run)
             if retained is None or retained.request != current.request or run.evaluation_generation <= 1:
                 raise CheckerExecutionUnavailable(unavailable)
             expected = retained.expected_event
@@ -308,36 +332,38 @@ async def read_retry_delivery(
         from app.modules.checkers.checker_retry import read_retry_delivery
         require_transaction(self._session)
         automatic = await self._session.scalar(select(CheckerRun).where(
-            CheckerRun.automatic_retry_event_id == event_id,
+            CheckerRun.retry_delivery_event_id == event_id,
             CheckerRun.project_id == str(project_id),
             CheckerRun.submission_id == str(submission_id),
         ))
         if automatic is not None:
-            retained, _ = await self._read_automatic_retry(automatic)
+            retained, _ = await self._read_service_retry(automatic)
             return retained
         return await read_retry_delivery(
             self._session, self, project_id=project_id,
             submission_id=submission_id, event_id=event_id,
         )
 
-    async def _read_automatic_retry(self, successor: CheckerRun):
-        """Verify the exact service-triggered event and immutable source before use."""
-        from app.modules.checkers.checker_retry import automatic_retry_event, retry_event_expectation
+    async def _read_service_retry(self, successor: CheckerRun):
+        """Verify the exact service-triggered event and its retained cause."""
+        from app.modules.checkers.checker_retry import abandoned_retry_event, automatic_retry_event, retry_event_expectation
 
         unavailable = "checker_automatic_retry_delivery_unavailable"
-        if successor.supersedes_checker_run_id is None or successor.automatic_retry_event_id is None:
+        if successor.supersedes_checker_run_id is None or successor.retry_delivery_event_id is None:
             raise CheckerExecutionUnavailable(unavailable)
         source = await self._session.get(CheckerRun, successor.supersedes_checker_run_id, populate_existing=True)
         if source is None:
             raise CheckerExecutionUnavailable(unavailable)
-        expected = automatic_retry_event(source, successor)
+        abandonment = successor.retry_abandonment_event_id
+        expected = (abandoned_retry_event(source, successor, abandonment) if abandonment is not None
+                    else automatic_retry_event(source, successor))
         try:
-            await self._events.require_existing(successor.automatic_retry_event_id, expected)
+            await self._events.require_existing(successor.retry_delivery_event_id, expected)
         except (OutboxIdempotencyConflict, OutboxInputError, OutboxPersistenceError) as exc:
             raise CheckerExecutionUnavailable(unavailable) from exc
         return CheckerRetryDelivery(
             request=stored_request(successor), expected_event=retry_event_expectation(expected),
-        ), stored_result(source).infrastructure_failure_code
+        ), stored_result(source).infrastructure_failure_code if abandonment is None else None
 
     async def _lock_task_scope(self, request: PostSubmissionExecutionRequest) -> bool:
         """Retain root-transaction TASK custody before any coordination fence lock."""
@@ -497,11 +523,12 @@ async def _closed_automatic_retry_source(self, request: PostSubmissionExecutionR
             CheckerRun.submission_id == source.submission_id,
             CheckerRun.evaluation_generation == source.evaluation_generation + 1,
             CheckerRun.supersedes_checker_run_id == source.id,
-            CheckerRun.automatic_retry_event_id.is_not(None),
+            CheckerRun.retry_delivery_event_id.is_not(None),
+            CheckerRun.retry_abandonment_event_id.is_(None),
         ))
         if successor is None:
             raise CheckerExecutionUnavailable(unavailable)
-        await self._read_automatic_retry(successor)
+        await self._read_service_retry(successor)
         return source
 
     async def require_current_completion(
diff --git a/backend/app/modules/checkers/models.py b/backend/app/modules/checkers/models.py
index 97159f6bf..84f1a8933 100644
--- a/backend/app/modules/checkers/models.py
+++ b/backend/app/modules/checkers/models.py
@@ -214,8 +214,10 @@ class CheckerRun(Base):
         CheckConstraint("evaluation_generation > 0 and worker_lease_generation >= 0", name="generations"),
         CheckConstraint("status in ('queued','running','completed','infrastructure_failed')", name="state"),
         CheckConstraint(
-            "automatic_retry_event_id IS NULL OR (supersedes_checker_run_id IS NOT NULL "
-            "AND evaluation_generation BETWEEN 2 AND 5)", name="automatic_retry_scope",
+            "(retry_abandonment_event_id IS NULL OR retry_delivery_event_id IS NOT NULL) AND "
+            "(retry_delivery_event_id IS NULL OR (supersedes_checker_run_id IS NOT NULL "
+            "AND (retry_abandonment_event_id IS NOT NULL OR evaluation_generation BETWEEN 2 AND 5)))",
+            name="service_retry_scope",
         ),
         CheckConstraint("octet_length(request_json) <= 1048576 and request_digest = 'sha256:' || encode(sha256(convert_to(request_json, 'UTF8')), 'hex')", name="request_digest"),
         CheckConstraint("result_json is null or result_digest = 'sha256:' || encode(sha256(convert_to(result_json, 'UTF8')), 'hex')", name="result_digest"),
@@ -267,8 +269,11 @@ class CheckerRun(Base):
     material_custody: Mapped[dict | None] = mapped_column(JSON(none_as_null=True))
     input_context_custody: Mapped[dict | None] = mapped_column(JSONB(none_as_null=True))
     completion_event_id: Mapped[UUID | None] = mapped_column(Uuid(), ForeignKey("outbox_events.event_id"))
-    automatic_retry_event_id: Mapped[UUID | None] = mapped_column(
-        Uuid(), ForeignKey("outbox_events.event_id", name="fk_checker_runs_automatic_retry_event"), unique=True,
+    retry_delivery_event_id: Mapped[UUID | None] = mapped_column(
+        Uuid(), ForeignKey("outbox_events.event_id", name="fk_checker_runs_retry_delivery_event"), unique=True,
+    )
+    retry_abandonment_event_id: Mapped[UUID | None] = mapped_column(
+        Uuid(), ForeignKey("outbox_events.event_id", name="fk_checker_runs_retry_abandonment_event"), unique=True,
     )
     supersedes_checker_run_id: Mapped[str | None] = mapped_column(
         Uuid(as_uuid=False),
diff --git a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
index 29b3eec30..9721c9014 100644
--- a/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
+++ b/backend/tests/checkers/execution/test_delivery_reconciliation_public.py
@@ -208,6 +208,7 @@ async def _reconcile(
     *,
     actor=None,
     reason="Reconcile one exact uncertain post-submit delivery",
+    action=None,
 ):
     _, command = _paths(project_id, event_id)
     assert command is not None
@@ -215,7 +216,7 @@ async def _reconcile(
     return await admin_access.signed.client.post(
         command,
         headers=caller.headers | {"Idempotency-Key": str(request_key)},
-        json={"reason": reason},
+        json={"reason": reason} if action is None else {"reason": reason, "action": action},
     )
 
 
@@ -1021,3 +1022,79 @@ def capture(_conn, _cursor, statement, _parameters, _context, _many):
             )
         assert children == 0
         assert denials == 1
+
+
+@pytest.mark.asyncio
+async def test_operator_abandons_exact_expired_unknown_once(
+    tmp_path, auth_database_env, admin_access, monkeypatch,
+) -> None:
+    """Expire the real owner and preserve its unresolved history through one successor."""
+    from sqlalchemy import func, select
+    from app.adapters.checkers import evaluation_coordinator
+    from app.modules.checkers import execution
+    from app.modules.checkers.api.execution import CheckerExecutionUnavailable
+    from app.modules.checkers.models import CheckerRetryReceipt, CheckerRun, CheckerSubmissionFence
+    from tests.checkers.execution.support import live_executor
+
+    async with material_fixture(tmp_path, auth_database_env) as h:
+        await admin_access.signed.grant(admin_access.admin, admin_access.target)
+        prepared = await delivery_fixture(h)
+        original = await invoked(h, prepared)
+        executor = live_executor(h)
+        with monkeypatch.context() as patch:
+            patch.setattr(executor, "_execution_budget_seconds", lambda _request: 6)
+            patch.setattr(execution, "SELECTED_POST_FINALIZATION_MARGIN_MS", 4_000)
+            lease, replay = await executor._claim(h.request)
+        assert replay is None
+        assert outcome(await prepared.delivery.finalize(original.claim, FinalizationCause.UNKNOWN))["invocation_unknown"]
+        original_before, _ = await _delivery_rows(h.factory, original.claim.event_id)
+        key = new_record_id()
+        project_id, event_id = h.request.project_id, original.claim.event_id
+        unexpired = await _reconcile(admin_access, project_id, event_id, key, action="abandon_unknown")
+        assert unexpired.status_code == 404, unexpired.text
+        async with h.factory() as session:
+            await session.execute(text(
+                "SELECT pg_sleep(GREATEST(EXTRACT(EPOCH FROM CAST(:expiry AS timestamptz)-clock_timestamp()),0)+0.05)"
+            ), {"expiry": lease.expires_at})
+        ignored = await _reconcile(admin_access, project_id, event_id, key)
+        assert ignored.status_code == 404, ignored.text
+        created = await _reconcile(admin_access, project_id, event_id, key, action="abandon_unknown")
+        assert created.status_code == 201, created.text
+        result = created.json()
+        assert result["source"]["classification"] == result["successor"]["classification"] == "unresolved"
+        child_id = UUID(result["successor"]["event_id"])
+        registry = production_outbox_delivery(h.factory, worker_group="post")
+        claim = await registry.claim(child_id, project_id, "abandonment-test")
+        assert claim is not None
+        child = await registry._begin_invocation(claim)
+        assert child is not None
+        assert await registry._registry.get(child.event_type, child.event_version)(child) is HandlerOutcome.ACKNOWLEDGE
+        await registry.finalize(claim, FinalizationCause.ACKNOWLEDGE)
+        replay = await _reconcile(admin_access, project_id, event_id, key, action="abandon_unknown")
+        assert replay.status_code == 201, replay.text
+        assert replay.json()["successor"] == result["successor"]
+        assert replay.json()["source"]["reconciliation_state"] == "acknowledged"
+        changed = await _reconcile(admin_access, project_id, event_id, key)
+        assert changed.status_code == 409, changed.text
+        assert (await _delivery_rows(h.factory, event_id))[0] == original_before
+        async with h.factory.begin() as session:
+            retained = await session.get(CheckerRun, str(lease.reservation.attempt_id))
+            assert retained.status == "running" and retained.result_json is None and retained.finalize_evidence_id is None
+            assert retained.worker_lease_id == str(lease.lease_id)
+            fence = await session.get(CheckerSubmissionFence, retained.submission_id)
+            successor = await session.get(CheckerRun, fence.current_run_id)
+            assert successor.evaluation_generation == 2 and successor.status == "queued"
+            assert successor.retry_abandonment_event_id == child_id
+            assert successor.supersedes_checker_run_id == retained.id
+            assert await session.scalar(select(func.count()).select_from(CheckerRetryReceipt)) == 0
+            assert await session.scalar(select(func.count()).select_from(CheckerRun)) == 2
+            evaluations = evaluation_coordinator(session)
+            observed = await evaluations.read_current_progress(
+                project_id=project_id, task_id=h.request.task_id,
+                submission_id=h.request.submission_id, original_request_id=h.request.evaluation_request_id,
+            )
+            assert observed.retry_event_id == successor.retry_delivery_event_id
+            assert observed.status == "queued" and observed.failure_code is None
+        with pytest.raises(CheckerExecutionUnavailable, match="checker_current_request_unavailable"):
+            await executor._claim(h.request)
+        assert not prepared.selected.requests
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 4ecf4ffe5..3bf5b25f7 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "a92907ed73f32d8af6056ee18ef5fca372d7c8629fcd1fd3f730d25b6effd0d3"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "efaf65a0b5cccff693ec8700a46f43fbc036206189af8d2f72cb1b521840fa99"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/backend/tests/tasks/evaluation_delivery/test_delivery.py b/backend/tests/tasks/evaluation_delivery/test_delivery.py
index 3b073179a..9e5e8a58d 100644
--- a/backend/tests/tasks/evaluation_delivery/test_delivery.py
+++ b/backend/tests/tasks/evaluation_delivery/test_delivery.py
@@ -163,7 +163,7 @@ async def guarded_append(outbox, event):
             assert fence.current_run_id == successor.id
             assert original.status == "infrastructure_failed" and original.failure_code == "material_unavailable"
             assert successor.status == "queued" and successor.supersedes_checker_run_id == original.id
-            new_event = await session.get(OutboxEvent, successor.automatic_retry_event_id)
+            new_event = await session.get(OutboxEvent, successor.retry_delivery_event_id)
             assert new_event.not_before_at == original.completed_at + timedelta(seconds=5)
             event_id, due = new_event.event_id, new_event.not_before_at
             assert (await evaluation_coordinator(session).classify_uncertain_delivery(h.request)).classification == "committed"
diff --git a/backend/tests/test_checker_evidence_migrations.py b/backend/tests/test_checker_evidence_migrations.py
index 1a99609fd..0d1afe60f 100644
--- a/backend/tests/test_checker_evidence_migrations.py
+++ b/backend/tests/test_checker_evidence_migrations.py
@@ -107,7 +107,7 @@ async def _retained_rows(database_url: str) -> dict[str, str]:
         result = {}
         for table in _RETAINED_TABLES:
             excluded = {
-                "checker_runs": ("input_context_custody", "automatic_retry_event_id"),
+                "checker_runs": ("input_context_custody", "retry_delivery_event_id", "retry_abandonment_event_id"),
                 "artifact_put_attempts": ("checker_trial_evidence_id",),
                 "artifact_operation_receipts": ("checker_trial_evidence_id",),
                 "artifact_replicas": ("source_operation_id",),
@@ -153,7 +153,7 @@ async def _assert_head_lineage_projection(
         ) == 0
         assert (
             await connection.fetchval(
-                "select count(*) from checker_runs where input_context_custody is not null OR automatic_retry_event_id is not null"
+                "select count(*) from checker_runs where input_context_custody is not null OR retry_delivery_event_id is not null OR retry_abandonment_event_id is not null"
             )
             == 0
         )

From abcb92da28b2dc13285e2eac5329fd5baa47e955 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:21:22 +0100
Subject: [PATCH 489/513] Exercise all four POST retry delays and exhaustion

---
 .../evaluation_delivery/test_delivery.py      | 30 ++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)

diff --git a/backend/tests/tasks/evaluation_delivery/test_delivery.py b/backend/tests/tasks/evaluation_delivery/test_delivery.py
index 9e5e8a58d..15a1788db 100644
--- a/backend/tests/tasks/evaluation_delivery/test_delivery.py
+++ b/backend/tests/tasks/evaluation_delivery/test_delivery.py
@@ -1,7 +1,7 @@
 """Actual request delivery, exact terminal replay, and hidden production scope."""
 
 import pytest
-from sqlalchemy import select, func
+from sqlalchemy import select, func, text
 
 from app.adapters.outbox import production_outbox_delivery
 from app.modules.actors.api import ServiceIdentity
@@ -180,3 +180,31 @@ async def guarded_append(outbox, event):
             if now < due:
                 assert await d.delivery.claim(event_id, h.request.project_id, "worker") is None
         assert await d.delivery.deliver(h.created.evaluation_event_id, h.request.project_id, "duplicate") is None
+        for generation in range(2, 6):
+            # Follow the committed retry schedule without changing clock or custody.
+            async with h.factory() as session:
+                await session.execute(text(
+                    "SELECT pg_sleep(GREATEST(EXTRACT(EPOCH FROM CAST(:due AS timestamptz)-clock_timestamp()),0)+0.02)"
+                ), {"due": due})
+            receipt = outcome(await d.delivery.deliver(event_id, h.request.project_id, "retry-worker"))
+            assert receipt["delivery_state"] == "acknowledged"
+            async with h.factory.begin() as session:
+                source = await session.scalar(select(CheckerRun).where(
+                    CheckerRun.submission_id == str(h.request.submission_id),
+                    CheckerRun.evaluation_generation == generation,
+                ))
+                assert source.status == "infrastructure_failed"
+                next_run = await session.scalar(select(CheckerRun).where(CheckerRun.supersedes_checker_run_id == source.id))
+                if generation == 5:
+                    assert next_run is None
+                    progress = await evaluation_coordinator(session).read_current_progress(
+                        project_id=h.request.project_id, task_id=h.request.task_id,
+                        submission_id=h.request.submission_id, original_request_id=h.request.evaluation_request_id,
+                    )
+                    assert progress.status == "infrastructure_failed" and progress.failure_code == "material_unavailable"
+                    assert progress.current.reservation.evaluation_generation == 5
+                else:
+                    next_event = await session.get(OutboxEvent, next_run.retry_delivery_event_id)
+                    assert next_event.not_before_at == source.completed_at + timedelta(seconds=5 * 2 ** (generation - 1))
+                    event_id, due = next_event.event_id, next_event.not_before_at
+        assert not d.selected.requests

From 4d1ba7464788f1a1766cec4eb2b63c5e59f7b5a3 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:27:48 +0100
Subject: [PATCH 490/513] Verify explicit recovery through the built CLI and
 generated API contract

---
 .../integration/test_post_submit_delivery_http.py  | 14 ++++++++++++++
 .../post_submit_deliveries_reconcile.json          |  3 +--
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/cli/tests/integration/test_post_submit_delivery_http.py b/cli/tests/integration/test_post_submit_delivery_http.py
index 6f57ff1d4..40a8ce4aa 100644
--- a/cli/tests/integration/test_post_submit_delivery_http.py
+++ b/cli/tests/integration/test_post_submit_delivery_http.py
@@ -273,3 +273,17 @@ def test_delivery_reconcile_invalid_arguments_do_not_send(cli):
         ):
             assert invoke(cli, origin, "reconcile", *args).returncode != 0
         assert not requests
+
+
+def test_explicit_abandonment_binds_action_to_unknown_successor(cli):
+    with http_fixture() as (origin, response, requests):
+        unresolved = receipt()
+        unresolved["source"]["classification"] = "unresolved"
+        unresolved["successor"]["classification"] = "unresolved"
+        response.update(status=201, body=json.dumps(unresolved).encode())
+        args = ("reconcile", PROJECT, EVENT, "--reason", "Expired unresolved run",
+                "--idempotency-key", KEY)
+        assert invoke(cli, origin, *args, "--abandon-unknown").returncode == 0
+        assert response["commands"][0][2]["action"] == "abandon_unknown"
+        assert invoke(cli, origin, *args).returncode != 0
+        assert len(requests) == 2
diff --git a/mcp_server/contracts/post_submit_deliveries_reconcile.json b/mcp_server/contracts/post_submit_deliveries_reconcile.json
index 4596f6104..77d2ed134 100644
--- a/mcp_server/contracts/post_submit_deliveries_reconcile.json
+++ b/mcp_server/contracts/post_submit_deliveries_reconcile.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "d46d082b8e1a768b590ba01523f7ce4479bc777e5fd4ebf4d6ad289821b4c244",
+  "canonical_sha256": "acea09d2e3658a33581402b1363bac0f350d1ef2f4a1e193dfe610f168d3eb8c",
   "components": {
     "schemas": {
       "ApiError": {
@@ -94,7 +94,6 @@
                 "type": "null"
               }
             ],
-            "default": null,
             "title": "Action"
           },
           "reason": {

From 9782e13d1e18e731596a5ae68cc9cb4cfabe95f9 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:30:28 +0100
Subject: [PATCH 491/513] Require the canonical POST retry owner at every
 composition

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  7 +++++++
 backend/app/adapters/checkers/__init__.py     | 18 ----------------
 backend/app/modules/checkers/execution.py     |  4 ++--
 .../tests/artifacts/intake_post_support.py    | 10 ++++++---
 .../test_submission_intake_progress.py        |  2 +-
 .../test_submission_source_post_minio.py      |  2 +-
 backend/tests/checkers/execution/support.py   | 16 +++++++++++++-
 .../checkers/execution/test_checker_retry.py  | 12 +++--------
 .../checkers/execution/test_execution.py      |  6 +++++-
 mcp_server/contracts/submission_create.json   | 21 ++++++++++++++++++-
 10 files changed, 61 insertions(+), 37 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 1762963b5..f9d9c14bc 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13320,3 +13320,10 @@ abandonment, stale Operator authority, duplicate successors and late old-owner
 writes. It does not prove the provider stopped and does not authorize automatic
 retry of an unresolved invocation. Check exact replay, whole-transaction rollback
 and late-effect fencing through the existing signed Operator and database tests.
+
+Independent review identified optional retry composition on the canonical
+executor. The executor now requires the TASK retry guard in every composition;
+the unused alternate builder was removed. Focused fixtures that exercise
+Operator recovery set an explicit exhausted allowance while the automatic
+retry regression uses the full production allowance. The MCP submission-create
+snapshot now retains the already deployed known PRE timeout response.
diff --git a/backend/app/adapters/checkers/__init__.py b/backend/app/adapters/checkers/__init__.py
index 56e8ffe95..985e08053 100644
--- a/backend/app/adapters/checkers/__init__.py
+++ b/backend/app/adapters/checkers/__init__.py
@@ -409,24 +409,6 @@ async def detached_classify(delivery):
     )
 
 
-def post_submission_executor(*, sessions, materialization):
-    """Compose the sole executor with exact fixed-service AUTH at both phases."""
-    from app.adapters.outbox import outbox_append
-    from app.modules.checkers.execution import PostSubmissionExecutor
-    from app.adapters.auth import post_submit_execution_authority
-
-    from app.adapters.projects import project_locked_policy_context_port
-
-    return PostSubmissionExecutor(
-        sessions=sessions,
-        materialization=materialization,
-        execute_authority=post_submit_execution_authority,
-        finalize_authority=post_submit_execution_authority,
-        outbox=outbox_append,
-        review_modes=project_locked_policy_context_port,
-    )
-
-
 def checker_output_reservations(session):
     """Resolve exact call custody with TASK-before-CHECKERS request locking."""
     from app.adapters.tasks import evaluation_task_guard
diff --git a/backend/app/modules/checkers/execution.py b/backend/app/modules/checkers/execution.py
index 9cb558a1d..94ca8a3f7 100644
--- a/backend/app/modules/checkers/execution.py
+++ b/backend/app/modules/checkers/execution.py
@@ -152,7 +152,7 @@ def __init__(
         forge_facts: ForgeFactsResolver | None = None,
         outbox: Callable[[AsyncSession], OutboxAppendPort],
         review_modes: Callable[[AsyncSession], ReviewModePort],
-        retry_tasks: Callable[[AsyncSession], EvaluationTaskGuard] | None = None,
+        retry_tasks: Callable[[AsyncSession], EvaluationTaskGuard],
     ):
         """Receive explicit session, authority, materialization and publication ports."""
         self._sessions = sessions
@@ -398,7 +398,7 @@ async def finalize(self, facts: FinalizeFacts) -> PostSubmissionExecutionResult:
                 run.outcome_source = "auto_checker"
                 run.status = result.outcome
                 await session.flush()
-                if result.outcome == "infrastructure_failed" and self._retry_tasks is not None:
+                if result.outcome == "infrastructure_failed":
                     coordinator = EvaluationCoordinator(session, tasks=self._retry_tasks(session), events=self._outbox(session))
                     await coordinator.schedule_automatic_retry(run)
                 return result
diff --git a/backend/tests/artifacts/intake_post_support.py b/backend/tests/artifacts/intake_post_support.py
index 37e3bca7a..56bf49dab 100644
--- a/backend/tests/artifacts/intake_post_support.py
+++ b/backend/tests/artifacts/intake_post_support.py
@@ -1,4 +1,5 @@
 """T5-to-POST owner integration with real storage and a controlled checker runtime."""
+from contextlib import nullcontext
 from types import SimpleNamespace
 from uuid import UUID
 
@@ -7,7 +8,9 @@
 from app.modules.actors.api import ServiceIdentity
 from app.modules.artifacts.api.submission_archive import SubmissionArchiveLimits
 from app.modules.artifacts.preparation import ArtifactPreparationService, ArtifactScratchManager
-from tests.checkers.execution.support import ControlledSelectedExecution, live_executor, provision_post_submit_service
+from tests.checkers.execution.support import (
+    ControlledSelectedExecution, final_post_attempt, live_executor, provision_post_submit_service,
+)
 from tests.test_checker_materialization import _limits
 from tests.trusted_intake_fixtures import LocalIntakeAdapter
 
@@ -26,7 +29,7 @@ def open_source(self, source, **kwargs):
         return self.store.open_source(source, **kwargs)
 
 
-async def exercise_source_post(f, created, store, source, tmp_path, *, missing=False):
+async def exercise_source_post(f, created, store, source, tmp_path, monkeypatch, *, missing=False):
     """Execute and retain POST with fresh AUTH, exact source I/O and replay."""
     await provision_post_submit_service(f.factory, ServiceIdentity.CHECKER_POST_SUBMIT)
     await provision_post_submit_service(f.factory, ServiceIdentity.ARTIFACT_MATERIALIZER)
@@ -44,7 +47,8 @@ async def exercise_source_post(f, created, store, source, tmp_path, *, missing=F
         runtime = ControlledSelectedExecution()
         harness = SimpleNamespace(factory=f.factory, service=service, request=reserved.request)
         executor = live_executor(harness, selected_execution=runtime)
-        result = await executor.evaluate_post_submission(reserved.request)
+        with final_post_attempt(monkeypatch) if missing else nullcontext():
+            result = await executor.evaluate_post_submission(reserved.request)
         assert result.outcome == ("infrastructure_failed" if missing else "completed")
         assert len(counted.opens) == 1
         assert len(runtime.requests) == (0 if missing else 1)
diff --git a/backend/tests/artifacts/test_submission_intake_progress.py b/backend/tests/artifacts/test_submission_intake_progress.py
index beaefbf4b..0415922c8 100644
--- a/backend/tests/artifacts/test_submission_intake_progress.py
+++ b/backend/tests/artifacts/test_submission_intake_progress.py
@@ -206,7 +206,7 @@ async def observe_running(runtime, execution_request, grant):
                 def missing_source(*_args, **_kwargs):
                     raise ArtifactObjectMissingError("controlled source unavailable")
                 patch.setattr(type(store), "open_source", missing_source)
-            await exercise_source_post(f, result, store, request.source, tmp_path, missing=post_failure)
+            await exercise_source_post(f, result, store, request.source, tmp_path, monkeypatch, missing=post_failure)
         assert len(running_observations) == (0 if post_failure else 1)
         async with f.factory.begin() as session:
             # Completed checker evidence alone does not change the governed attempt.
diff --git a/backend/tests/artifacts/test_submission_source_post_minio.py b/backend/tests/artifacts/test_submission_source_post_minio.py
index f6efc165a..005796fc0 100644
--- a/backend/tests/artifacts/test_submission_source_post_minio.py
+++ b/backend/tests/artifacts/test_submission_source_post_minio.py
@@ -68,7 +68,7 @@ async def recorded_reads():
             async with original_client() as client:
                 yield ReadOnlyClient(client)
         monkeypatch.setattr(store, "_client", recorded_reads)
-        await exercise_source_post(f, created, store, source, tmp_path, missing=remove_original)
+        await exercise_source_post(f, created, store, source, tmp_path, monkeypatch, missing=remove_original)
         assert reads == [dict(Bucket=MINIO_BUCKET, Key=store._source_key(source.location),
                               VersionId=source.provider_generation)]
         assert await finalizer.run(owner.operation_id) == created
diff --git a/backend/tests/checkers/execution/support.py b/backend/tests/checkers/execution/support.py
index 495c67eb4..e74beb435 100644
--- a/backend/tests/checkers/execution/support.py
+++ b/backend/tests/checkers/execution/support.py
@@ -1,5 +1,7 @@
 """Real fixed-service execution fixtures and explicit forbidden phase participants."""
 
+from contextlib import contextmanager
+
 import pytest
 from sqlalchemy import select
 
@@ -166,10 +168,22 @@ async def provision_post_submit_service(factory, identity=ServiceIdentity.CHECKE
         return actor_id
 
 
+@contextmanager
+def final_post_attempt(monkeypatch):
+    """Exercise exhaustion and manual recovery with one allowed attempt in this fixture."""
+    from app.modules.checkers import execution_coordination
+
+    options = execution_coordination.POST_SUBMISSION_RETRY_OPTIONS.model_copy(update={"max_attempts": 1})
+    with monkeypatch.context() as patch:
+        patch.setattr(execution_coordination, "POST_SUBMISSION_RETRY_OPTIONS", options)
+        yield
+
+
 def live_executor(h, *, outbox=None, selected_execution=None, forge_facts=None):
     from app.adapters.auth import post_submit_execution_authority
     from app.adapters.outbox import outbox_append
     from app.adapters.projects import project_locked_policy_context_port
+    from app.adapters.tasks import evaluation_task_guard
     from app.modules.checkers.execution import PostSubmissionExecutor
 
     return PostSubmissionExecutor(
@@ -180,7 +194,7 @@ def live_executor(h, *, outbox=None, selected_execution=None, forge_facts=None):
         selected_execution=selected_execution or ControlledSelectedExecution(),
         forge_facts=forge_facts,
         outbox=outbox if outbox is not None else outbox_append,
-        review_modes=project_locked_policy_context_port,
+        review_modes=project_locked_policy_context_port, retry_tasks=evaluation_task_guard,
     )
 
 
diff --git a/backend/tests/checkers/execution/test_checker_retry.py b/backend/tests/checkers/execution/test_checker_retry.py
index 056ac33b3..41e36a44d 100644
--- a/backend/tests/checkers/execution/test_checker_retry.py
+++ b/backend/tests/checkers/execution/test_checker_retry.py
@@ -73,7 +73,7 @@
 from tests.post_submit_materialization_helpers import material_fixture
 from tests.checkers.post_submit.support import change_request
 from tests.checkers.execution.completion_fixture import completed_evidence
-from tests.checkers.execution.support import live_executor, reserve
+from tests.checkers.execution.support import final_post_attempt, live_executor, reserve
 from tests.project_create_fixtures import grant_fixture_admin_role
 from tests.authentication.fixtures import (
     auth_database_env as auth_database_env,
@@ -118,13 +118,7 @@ def missing(_store, _reference, **kwargs):
 
         try:
             delivery = await delivery_fixture(h, materialization=port)
-            with monkeypatch.context() as patch:
-                from app.modules.checkers import execution_coordination
-
-                # Isolate the Operator path after escalation. The automatic policy
-                # and its durable retry chain are covered by delivery tests.
-                patch.setattr(execution_coordination, "POST_SUBMISSION_RETRY_OPTIONS",
-                    execution_coordination.POST_SUBMISSION_RETRY_OPTIONS.model_copy(update={"max_attempts": 1}))
+            with final_post_attempt(monkeypatch), monkeypatch.context() as patch:
                 patch.setattr(
                     LocalStorageAdapter if provider == "local" else S3CompatibleArtifactStore,
                     "open_source", missing,
@@ -999,7 +993,7 @@ def missing(_store, _reference, **kwargs):
 
         try:
             delivery = await delivery_fixture(h, materialization=port)
-            with monkeypatch.context() as patch:
+            with final_post_attempt(monkeypatch), monkeypatch.context() as patch:
                 patch.setattr(LocalStorageAdapter, "open_source", missing)
                 initial = await delivery.delivery.deliver(
                     h.created.evaluation_event_id, h.request.project_id, "concurrent-source",
diff --git a/backend/tests/checkers/execution/test_execution.py b/backend/tests/checkers/execution/test_execution.py
index 2ce6b4896..951451b64 100644
--- a/backend/tests/checkers/execution/test_execution.py
+++ b/backend/tests/checkers/execution/test_execution.py
@@ -159,6 +159,7 @@ async def forbidden_claim(request):
     executor = owner.PostSubmissionExecutor(
         sessions=None, execute_authority=None, finalize_authority=None,
         materialization=None, outbox=None, review_modes=None,
+        retry_tasks=lambda _: pytest.fail("unsupported request reached retry reservation"),
     )
     monkeypatch.setattr(executor, "_claim", forbidden_claim)
     for schema in ("post_submit_evaluation_request", "arbitrary_request.v1"):
@@ -395,7 +396,10 @@ async def retain_finalization(facts):
         await service_link_state(h.factory, ServiceIdentity.CHECKER_POST_SUBMIT, active=True)
         monkeypatch.setattr(executor, "finalize", finalize)
         assert len(pending) == 1
-        result = await finalize(pending[0])
+        from tests.checkers.execution.support import final_post_attempt
+
+        with final_post_attempt(monkeypatch):
+            result = await finalize(pending[0])
         assert result.outcome == "infrastructure_failed"
         assert result.infrastructure_failure_code == "material_unavailable"
         assert result.execution is None
diff --git a/mcp_server/contracts/submission_create.json b/mcp_server/contracts/submission_create.json
index 88a018f03..f2a81392a 100644
--- a/mcp_server/contracts/submission_create.json
+++ b/mcp_server/contracts/submission_create.json
@@ -1,5 +1,5 @@
 {
-  "canonical_sha256": "4b308da1c69b44193386ba0513cd9f41de2b33016c0a898bce65512e58861f63",
+  "canonical_sha256": "b273e18412acce287b8f55917d42ff06913afaa1e5fedc2d44b7372cfa5b6b0c",
   "components": {
     "schemas": {
       "ApiError": {
@@ -719,6 +719,25 @@
             }
           }
         }
+      },
+      "504": {
+        "description": "Pre-submission deadline expired and the operation durably ended",
+        "headers": {
+          "X-Correlation-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          },
+          "X-Request-ID": {
+            "required": true,
+            "schema": {
+              "format": "uuid",
+              "type": "string"
+            }
+          }
+        }
       }
     },
     "security": [

From 4505653ad5953406d34be0a2bbf3f30bb9634ef5 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:31:36 +0100
Subject: [PATCH 492/513] Remove the fixed process deadline from POST delivery
 workers

---
 backend/app/workers/outbox.py                 |  6 +++---
 backend/app/workers/outbox_topology.py        | 11 +++++-----
 .../tests/outbox/test_delivery_topology.py    | 19 +++++++++---------
 .../tests/outbox/test_worker_postgresql.py    | 20 ++++---------------
 4 files changed, 22 insertions(+), 34 deletions(-)

diff --git a/backend/app/workers/outbox.py b/backend/app/workers/outbox.py
index a041af7e1..e6def51d4 100644
--- a/backend/app/workers/outbox.py
+++ b/backend/app/workers/outbox.py
@@ -12,7 +12,7 @@
 from app.workers.async_runner import run_async_task
 from app.workers.celery_app import celery_app
 from app.workers.outbox_topology import (
-    require_outbox_worker, require_outbox_scan_worker, OUTBOX_HARD_LIMIT_SECONDS,
+    require_outbox_worker, require_outbox_scan_worker,
     OUTBOX_SCAN_TASK, OUTBOX_SCAN_HARD_LIMIT_SECONDS, FINALIZATION_HARD_LIMIT_SECONDS,
     FEEDBACK_EMAIL_DELIVERY_TASK, FEEDBACK_EMAIL_HARD_LIMIT_SECONDS, FEEDBACK_EMAIL_QUEUE,
     FINALIZATION_DELIVERY_TASK, FINALIZATION_QUEUE, OUTBOX_DELIVERY_TASK, OUTBOX_QUEUE,
@@ -33,10 +33,10 @@ def _uuid(value):
 
 @celery_app.task(
     name=OUTBOX_DELIVERY_TASK, bind=True, acks_late=True,
-    reject_on_worker_lost=True, acks_on_failure_or_timeout=True, time_limit=OUTBOX_HARD_LIMIT_SECONDS,
+    reject_on_worker_lost=True, acks_on_failure_or_timeout=True,
 )
 def deliver_event(self, event_id, project_id):
-    """Run under prefork: its hard limit also bounds async shutdown after UNKNOWN."""
+    """Process POST events under durable delivery ownership."""
     return _run_delivery(self, event_id, project_id, queue=OUTBOX_QUEUE, group="post")
 
 
diff --git a/backend/app/workers/outbox_topology.py b/backend/app/workers/outbox_topology.py
index 78bfa2626..30c0254c4 100644
--- a/backend/app/workers/outbox_topology.py
+++ b/backend/app/workers/outbox_topology.py
@@ -6,13 +6,9 @@
 from celery.concurrency.prefork import TaskPool
 from celery.exceptions import WorkerShutdown
 from celery.signals import worker_init
-from app.modules.checkers.api.external_policy import SELECTED_POST_DELIVERY_LEASE_SECONDS
 from app.modules.artifacts.api.submission_finalization import SUBMISSION_FINALIZATION_DELIVERY_LEASE_SECONDS
 
 OUTBOX_PROCESS_SHUTDOWN_MARGIN_SECONDS = 60
-OUTBOX_HARD_LIMIT_SECONDS = (
-    SELECTED_POST_DELIVERY_LEASE_SECONDS + OUTBOX_PROCESS_SHUTDOWN_MARGIN_SECONDS
-)
 OUTBOX_QUEUE = "workstream.outbox"
 OUTBOX_DELIVERY_TASK = "workstream.outbox.deliver_event"
 OUTBOX_SCAN_QUEUE = "workstream.outbox_scan"
@@ -25,7 +21,7 @@
 FEEDBACK_EMAIL_DELIVERY_TASK = "workstream.outbox.send_submission_feedback_email"
 FEEDBACK_EMAIL_HARD_LIMIT_SECONDS = 55
 _DELIVERY_LIMITS = {
-    OUTBOX_QUEUE: OUTBOX_HARD_LIMIT_SECONDS,
+    OUTBOX_QUEUE: None,
     FINALIZATION_QUEUE: FINALIZATION_HARD_LIMIT_SECONDS,
     FEEDBACK_EMAIL_QUEUE: FEEDBACK_EMAIL_HARD_LIMIT_SECONDS,
 }
@@ -107,6 +103,11 @@ def require_outbox_worker(task, *, queue=OUTBOX_QUEUE):
         or task.request.called_directly
     ):
         raise RuntimeError("OUTBOX delivery requires a validated prefork worker")
+    if queue == OUTBOX_QUEUE:
+        limits = (task.time_limit, task.soft_time_limit, *(task.request.timelimit or ()))
+        if any(limit is not None for limit in limits):
+            raise RuntimeError("POST worker requires renewable ownership without a process deadline")
+        return
     message_limit = (task.request.timelimit or (None, None))[0]
     expected_limit = _DELIVERY_LIMITS[queue]
     if (
diff --git a/backend/tests/outbox/test_delivery_topology.py b/backend/tests/outbox/test_delivery_topology.py
index 4eb6131cf..ad50b8ab6 100644
--- a/backend/tests/outbox/test_delivery_topology.py
+++ b/backend/tests/outbox/test_delivery_topology.py
@@ -69,7 +69,7 @@ def test_validated_prefork_child_enters(monkeypatch):
     topology.validate_outbox_worker(configured)
     monkeypatch.setattr(topology.os, "getppid", os.getpid)
     topology.require_outbox_worker(SimpleNamespace(app=configured.app,
-        time_limit=topology.OUTBOX_HARD_LIMIT_SECONDS,
+        time_limit=None, soft_time_limit=None,
         request=SimpleNamespace(is_eager=False, called_directly=False, timelimit=None)))
 
 
@@ -110,19 +110,18 @@ def test_delivery_routes_to_dedicated_queue(monkeypatch):
         get_settings.cache_clear()
 
 
-@pytest.mark.parametrize("task_limit,message_limit", [
-    (None, None), (300, None), (topology.OUTBOX_HARD_LIMIT_SECONDS + 1, None),
-    (topology.OUTBOX_HARD_LIMIT_SECONDS, 300),
-    (topology.OUTBOX_HARD_LIMIT_SECONDS, topology.OUTBOX_HARD_LIMIT_SECONDS + 1),
-    (topology.OUTBOX_HARD_LIMIT_SECONDS, 0),
+@pytest.mark.parametrize("hard,soft,message", [
+    (3600, None, None), (None, 3600, None),
+    (None, None, (3600, None)), (None, None, (None, 3600)),
 ])
-def test_delivery_cannot_disable_or_extend_process_bound(monkeypatch, task_limit, message_limit):
+def test_post_worker_rejects_fixed_process_deadlines(monkeypatch, hard, soft, message):
     configured = worker()
     topology.validate_outbox_worker(configured)
     monkeypatch.setattr(topology.os, "getppid", os.getpid)
-    with pytest.raises(RuntimeError, match="bounded hard time limit"):
-        topology.require_outbox_worker(SimpleNamespace(app=configured.app, time_limit=task_limit,
-            request=SimpleNamespace(is_eager=False, called_directly=False, timelimit=(message_limit, None))))
+    with pytest.raises(RuntimeError, match="process deadline"):
+        topology.require_outbox_worker(SimpleNamespace(app=configured.app, time_limit=hard,
+            soft_time_limit=soft,
+            request=SimpleNamespace(is_eager=False, called_directly=False, timelimit=message)))
 
 
 @pytest.mark.parametrize("pool,eager", [("solo", False), ("threads", False), ("prefork", True)])
diff --git a/backend/tests/outbox/test_worker_postgresql.py b/backend/tests/outbox/test_worker_postgresql.py
index cee66496b..301252745 100644
--- a/backend/tests/outbox/test_worker_postgresql.py
+++ b/backend/tests/outbox/test_worker_postgresql.py
@@ -275,7 +275,7 @@ async def test_production_registry_claims_only_registered_features(delivery_harn
         assert (await session.get(OutboxEvent, event.event_id)).delivery_state == "pending"
 
 
-async def test_prefork_bounds_cancellation_resistant_worker(
+async def test_prefork_bounds_cancellation_resistant_finalization_worker(
     delivery_harness, worker, monkeypatch, tmp_path
 ):
     """Actual sync task shutdown is bounded after real invocation records UNKNOWN."""
@@ -308,13 +308,11 @@ async def stubborn(envelope):
     h.handler_hook = stubborn
     h.options = DeliveryOptions(lease_seconds=30, handler_timeout_seconds=1)
     event = await h.append()
-    task = worker.deliver_event
+    task = worker.finalize_submission
     # Scale an installed process deadline only. Removing it leaves the real
     # prefork task hanging until the independent test watchdog detects it.
     if task.time_limit is not None:
         monkeypatch.setattr(task, "time_limit", 5)
-        from app.workers import outbox_topology
-        monkeypatch.setattr(outbox_topology, "OUTBOX_HARD_LIMIT_SECONDS", 5)
     monkeypatch.setenv("WORKSTREAM_ARTIFACT_STORE_BACKEND", "disabled")
     get_settings.cache_clear()
     acked = Event()
@@ -386,19 +384,9 @@ async def stubborn(envelope):
         assert len(attempts) == 1 and attempts[0].outcome_json == original
 
 
-def test_delivery_task_has_independent_hard_limit(worker):
-    from app.modules.outbox.api import DeliveryOptions
-
+def test_post_delivery_keeps_late_ack_without_a_process_deadline(worker):
     task = worker.deliver_event
-    from app.modules.checkers.api.external_policy import (
-        SELECTED_POST_DELIVERY_LEASE_SECONDS, SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
-    )
-    from app.workers.outbox_topology import OUTBOX_PROCESS_SHUTDOWN_MARGIN_SECONDS
-    assert task.time_limit == (
-        SELECTED_POST_DELIVERY_LEASE_SECONDS + OUTBOX_PROCESS_SHUTDOWN_MARGIN_SECONDS
-    )
-    assert task.time_limit > SELECTED_POST_HANDLER_TIMEOUT_SECONDS
-    assert task.time_limit > DeliveryOptions().handler_timeout_seconds
+    assert task.time_limit is None
     assert task.acks_late and task.acks_on_failure_or_timeout
     assert task.reject_on_worker_lost is True
     assert task.soft_time_limit is None

From fa27d789d148549745afeca8257723d98a18759c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:31:36 +0100
Subject: [PATCH 493/513] Reset POST transfer watchdog on progress before
 checker execution

---
 backend/app/adapters/checkers/external_service.py   |  5 ++++-
 backend/tests/checkers/external/test_remote_node.py |  2 +-
 external_checkers/remote_node.py                    | 12 +++++++++---
 3 files changed, 14 insertions(+), 5 deletions(-)

diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index 06ab66b15..1fcb9e86d 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -337,7 +337,8 @@ async def _exchange(self, request, grant, *, model_grant, locate):
             )
             if self._timeout_seconds < required_timeout:
                 raise ExternalServiceUnavailableError(self._identity)
-            async with asyncio.timeout(self._timeout_seconds):
+            loop = asyncio.get_running_loop()
+            async with asyncio.timeout(self._timeout_seconds) as transport_watchdog:
                 placement = await self._place_post(checked, with_model_grant=model_grant is not None)
                 reader, writer = await self._open(placement)
                 try:
@@ -377,6 +378,7 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                                 if type(chunk) is not bytes or not 0 < len(chunk) <= 64 * 1024:
                                     raise ValueError("external material export chunk is invalid")
                                 await self._send_frame(writer, chunk)
+                                transport_watchdog.reschedule(loop.time() + self._timeout_seconds)
                         finally:
                             await await_cancellation_resistant(stream.aclose())
                         writer.write(struct.pack(">I", 0))
@@ -392,6 +394,7 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                     # The remote owner cannot invoke native execution before
                     # this explicit start. A failed drain of this write may
                     # still follow successful transmission, so retain uncertainty.
+                    transport_watchdog.reschedule(loop.time() + required_timeout)
                     possibly_invoked = True
                     await self._send_frame(writer, json.dumps(
                         dict(ready, operation="start_execution"),
diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py
index 01026be92..08b11f70b 100644
--- a/backend/tests/checkers/external/test_remote_node.py
+++ b/backend/tests/checkers/external/test_remote_node.py
@@ -627,7 +627,7 @@ async def native(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) ->
     if start_mode == "old_node":
         # The preceding deployed protocol rejects unknown control fields before
         # staging or native invocation. This is a refusal proof, not a fallback.
-        async def old_execute(control, _reader, _writer):
+        async def old_execute(control, _reader, _writer, _watchdog):
             old_keys = {
                 "protocol_version", "operation", "capability", "service_request",
                 "manifest_byte_count", "file_count", "total_byte_count", "epoch", "config_sha256",
diff --git a/external_checkers/remote_node.py b/external_checkers/remote_node.py
index 5920aa3e5..a5f8d0f63 100644
--- a/external_checkers/remote_node.py
+++ b/external_checkers/remote_node.py
@@ -470,7 +470,7 @@ async def _handle_model_proxy(
 
     async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
         try:
-            async with asyncio.timeout(self.timeout):
+            async with asyncio.timeout(self.timeout) as transport_watchdog:
                 if self.client_name not in _peer_name(writer):
                     raise ProtocolError("client identity differs")
                 control = _decode_object(await _read_frame(reader, MAXIMUM_CONTROL_BYTES))
@@ -493,7 +493,7 @@ async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWrite
                 elif operation == "execute":
                     if capability != CHECKER_CAPABILITY:
                         raise ProtocolError("execute capability differs")
-                    await self._execute(control, reader, writer)
+                    await self._execute(control, reader, writer, transport_watchdog)
                 else:
                     raise ProtocolError("remote operation is invalid")
         except (ProtocolError, TimeoutError, OSError, ssl.SSLError, asyncio.IncompleteReadError):
@@ -552,6 +552,7 @@ async def _execute(
         control: dict[str, Any],
         reader: asyncio.StreamReader,
         writer: asyncio.StreamWriter,
+        transport_watchdog: asyncio.Timeout,
     ) -> None:
         expected = {
             "protocol_version", "operation", "capability", "service_request",
@@ -606,7 +607,7 @@ async def _execute(
             raise ProtocolError("material bounds differ")
         async with self._execution:
             await self._stage_and_execute(
-                grant_id, raw_manifest, manifest, files, request, reader, writer, binding_frame
+                grant_id, raw_manifest, manifest, files, request, reader, writer, binding_frame, transport_watchdog
             )
 
     async def _stage_and_execute(
@@ -619,6 +620,7 @@ async def _stage_and_execute(
         reader: asyncio.StreamReader,
         writer: asyncio.StreamWriter,
         binding_frame: bytes,
+        transport_watchdog: asyncio.Timeout,
     ) -> None:
         target = self.workspaces / grant_id
         incoming = self.workspaces / f".incoming-{uuid.uuid4().hex}"
@@ -661,6 +663,7 @@ def record(event: str, **facts: Any) -> None:
                         digest.update(chunk)
                         _write_descriptor(descriptor, chunk)
                         transferred += len(chunk)
+                        transport_watchdog.reschedule(asyncio.get_running_loop().time() + self.timeout)
                     if count != expected_count or "sha256:" + digest.hexdigest() != expected_digest:
                         raise ProtocolError("material file content differs")
                     os.fsync(descriptor)
@@ -687,6 +690,9 @@ def record(event: str, **facts: Any) -> None:
             start = _decode_object(await _read_frame(reader, 16_384))
             if start != dict(ready, operation="start_execution"):
                 raise ProtocolError("execution start binding differs")
+            # Native execution enforces its registered limits. Give the result
+            # exchange a fresh transport window after material staging.
+            transport_watchdog.reschedule(asyncio.get_running_loop().time() + self.timeout)
             stage = "native_execution"
             record("started")
             native_reader, native_writer = await asyncio.open_unix_connection(self.socket_path)

From 1f1251cedb160b3a47514653336fde585ae1a4ac Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:31:36 +0100
Subject: [PATCH 494/513] Check explicit Operator abandonment in MCP receipts

---
 mcp_server/tests/test_checker_artifacts.py | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/mcp_server/tests/test_checker_artifacts.py b/mcp_server/tests/test_checker_artifacts.py
index 798299caf..e475a03aa 100644
--- a/mcp_server/tests/test_checker_artifacts.py
+++ b/mcp_server/tests/test_checker_artifacts.py
@@ -158,7 +158,8 @@ def _bound_response(name: str) -> dict[str, Any]:
             "items": [{"project_id": PROJECT_ID, "event_id": EVENT_ID}],
         },
         "post_submit_deliveries_reconcile": {
-            "source": {"project_id": PROJECT_ID, "event_id": EVENT_ID}
+            "source": {"project_id": PROJECT_ID, "event_id": EVENT_ID},
+            "successor": {"classification": "retry_safe"},
         },
         "checker_registry_read": {"registry_entry_id": REGISTRY_ID},
         "checker_registry_register": {
@@ -417,6 +418,16 @@ def test_success_responses_are_bound_to_requested_selectors_and_receipts(name: s
     assert not WorkstreamGateway._checker_artifact_response_matches(name, response, arguments)
 
 
+def test_abandonment_receipt_requires_explicit_operator_action() -> None:
+    name = "post_submit_deliveries_reconcile"
+    arguments = _arguments(name)
+    response = _bound_response(name)
+    response["successor"]["classification"] = "unresolved"
+    assert not WorkstreamGateway._checker_artifact_response_matches(name, response, arguments)
+    arguments["body"]["action"] = "abandon_unknown"
+    assert WorkstreamGateway._checker_artifact_response_matches(name, response, arguments)
+
+
 def test_registry_receipt_allows_backend_defaults_but_binds_supplied_fields() -> None:
     arguments = _arguments("checker_registry_register")
     response = _bound_response("checker_registry_register")

From e87215872f6df38dac49c8fc0781e859a2660e21 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:31:57 +0100
Subject: [PATCH 495/513] Retain TASK scope before terminal checker retry locks

---
 .commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 3 +++
 backend/app/modules/checkers/execution.py                 | 7 ++++++-
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index f9d9c14bc..7493189b9 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13327,3 +13327,6 @@ the unused alternate builder was removed. Focused fixtures that exercise
 Operator recovery set an explicit exhausted allowance while the automatic
 retry regression uses the full production allowance. The MCP submission-create
 snapshot now retains the already deployed known PRE timeout response.
+Automatic-failure finalization also takes the exact TASK replay scope before
+CHECKERS ownership. This preserves lock ordering even for direct executor
+composition and checks active successor scope only on new retry creation.
diff --git a/backend/app/modules/checkers/execution.py b/backend/app/modules/checkers/execution.py
index 94ca8a3f7..1fa2a8eb3 100644
--- a/backend/app/modules/checkers/execution.py
+++ b/backend/app/modules/checkers/execution.py
@@ -318,6 +318,11 @@ async def finalize(self, facts: FinalizeFacts) -> PostSubmissionExecutionResult:
         ):
             raise CheckerExecutionUnavailable("checker_material_custody_unavailable")
         async with self._sessions() as session, session.begin():
+            retry_tasks = self._retry_tasks(session)
+            if result.outcome == "infrastructure_failed":
+                # Retain TASK before acquiring the current CHECKERS run. This
+                # historical scope still permits exact terminal replay.
+                await retry_tasks.lock_retry_replay_scope(request)
             human = await self._review_modes(session).observe_review_mode(
                 request.project_id, request.expected_context.review_policy_id,
             )
@@ -399,6 +404,6 @@ async def finalize(self, facts: FinalizeFacts) -> PostSubmissionExecutionResult:
                 run.status = result.outcome
                 await session.flush()
                 if result.outcome == "infrastructure_failed":
-                    coordinator = EvaluationCoordinator(session, tasks=self._retry_tasks(session), events=self._outbox(session))
+                    coordinator = EvaluationCoordinator(session, tasks=retry_tasks, events=self._outbox(session))
                     await coordinator.schedule_automatic_retry(run)
                 return result

From f91f7044937d471a8020d769dd86bf71cf2f6652 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:33:31 +0100
Subject: [PATCH 496/513] Record local POST retry and abandonment qualification

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++
 docs/spec_submission_execution.md                 | 11 +++++++++--
 2 files changed, 24 insertions(+), 2 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 7493189b9..12df97a4f 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13330,3 +13330,18 @@ snapshot now retains the already deployed known PRE timeout response.
 Automatic-failure finalization also takes the exact TASK replay scope before
 CHECKERS ownership. This preserves lock ordering even for direct executor
 composition and checks active successor scope only on new retry creation.
+
+The isolated schema probe applied `0095_post_infrastructure_retry` and captured
+its exact fingerprint. Nine PostgreSQL cases at `abcb92da2` exited zero in
+510.62 seconds. They verified the actual four delayed successors and exhaustion,
+atomic rollback, signed abandonment and replay of an expired UNKNOWN lease,
+contributor feedback through Operator recovery, longer background POST work,
+and stale-worker fencing. The launcher confirmed database and MinIO cleanup.
+Exact receipts are under `/tmp/workstream-post-0095-focused.p2eYBR`.
+
+The focused Go projection checks passed. The installed MCP test suite's six
+selected cases passed at `9782e13d1`, including exact backend OpenAPI comparison
+for all task execution contracts and response validation for the three submission
+snapshots. Independent source review passed the required-port and TASK-first
+correction at `e87215872`. These are local proofs. Hosted recovery and maximum ZIP
+POST completion still require deployment and qualification.
diff --git a/docs/spec_submission_execution.md b/docs/spec_submission_execution.md
index 5d1722b1c..18db92fac 100644
--- a/docs/spec_submission_execution.md
+++ b/docs/spec_submission_execution.md
@@ -293,8 +293,15 @@ A finalized Submission remains retained when POST encounters an infrastructure
 failure. Its operation and assignment reads expose the verified
 `post_submission_*` failure code, distinct from PRE and work findings.
 `post_submission_outcome_unknown` identifies an uncertain delivery without a
-verified terminal result. A held POST exposes `contact_operator`. The Operator
-checks the source in the existing terminal retry or uncertain delivery surface.
+verified terminal result. The progress object reports the current attempt, the
+automatic attempt limit and the earliest due time while another attempt is queued.
+A verified infrastructure failure schedules a successor after 5, 10, 20 or 40
+seconds, for five attempts including the original. The Submission and previous
+checker results remain retained. Once the automatic budget is exhausted, a held
+POST exposes `contact_operator`. An uncertain execution remains held unless the
+existing Operator reconciliation proves its outcome or an Operator explicitly
+abandons the exact expired lease. That decision preserves the uncertain source
+and moves the current fence to one new attempt.
 
 A platform-safe-archive rejection is QC feedback. A transport object mismatch, untrusted runtime response, unavailable provider, Celery worker failure or expired execution deadline is infrastructure failure unless an existing approved checker contract explicitly identifies a completed deterministic QC result.
 

From ff05d51239a22a9c03c2a0f9f976dd7de2d97820 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:36:27 +0100
Subject: [PATCH 497/513] Record exact reviewed POST retry follow-up proof

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md      | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 12df97a4f..598193a9a 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13322,8 +13322,8 @@ retry of an unresolved invocation. Check exact replay, whole-transaction rollbac
 and late-effect fencing through the existing signed Operator and database tests.
 
 Independent review identified optional retry composition on the canonical
-executor. The executor now requires the TASK retry guard in every composition;
-the unused alternate builder was removed. Focused fixtures that exercise
+executor. The executor now requires the TASK retry guard in every composition.
+The unused alternate builder was removed. Focused fixtures that exercise
 Operator recovery set an explicit exhausted allowance while the automatic
 retry regression uses the full production allowance. The MCP submission-create
 snapshot now retains the already deployed known PRE timeout response.
@@ -13345,3 +13345,9 @@ for all task execution contracts and response validation for the three submissio
 snapshots. Independent source review passed the required-port and TASK-first
 correction at `e87215872`. These are local proofs. Hosted recovery and maximum ZIP
 POST completion still require deployment and qualification.
+
+After the review corrections, four focused PostgreSQL cases at `e87215872`
+passed in 96.55 seconds with database and MinIO cleanup. The cases verified
+missing-byte terminalization and replay, refusal before lease work for an
+obsolete request, rollback on retry-event failure and the signed Operator path.
+The receipt is under `/tmp/workstream-post-canonical-retry.2nn3cm`.

From 9db17ab8908139ea81520064c8a031935288f32c Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:37:11 +0100
Subject: [PATCH 498/513] Keep active native POST sessions alive across
 transport idle intervals

---
 .../app/adapters/checkers/external_service.py | 14 ++++-------
 .../checkers/external/test_remote_node.py     |  9 ++++----
 external_checkers/remote_node.py              | 23 ++++++++++++++++---
 3 files changed, 30 insertions(+), 16 deletions(-)

diff --git a/backend/app/adapters/checkers/external_service.py b/backend/app/adapters/checkers/external_service.py
index 1fcb9e86d..d2a245093 100644
--- a/backend/app/adapters/checkers/external_service.py
+++ b/backend/app/adapters/checkers/external_service.py
@@ -35,7 +35,6 @@
     ExternalServiceUnavailableError,
 )
 from app.modules.checkers.api.external import (
-    EXTERNAL_CHECKER_EXECUTION_CLEANUP_MARGIN_MS,
     MAX_RESULT_BYTES,
     ExternalCheckerExecutionRequest,
     ExternalCheckerExecutionResult,
@@ -59,7 +58,6 @@
 _PROTOCOL = "external_checker_service.v1"
 _REMOTE_PROTOCOL = "workstream.remote_runner.v1"
 _MAXIMUM_RESPONSE_BYTES = MAX_RESULT_BYTES + 16_384
-_EXECUTION_OVERHEAD_SECONDS = EXTERNAL_CHECKER_EXECUTION_CLEANUP_MARGIN_MS / 1000
 _CHANNEL_ID = re.compile(r"[0-9a-f]{32}")
 
 
@@ -332,11 +330,6 @@ async def _exchange(self, request, grant, *, model_grant, locate):
             ).encode("utf-8")
             if len(payload) > 2 * 1024 * 1024:
                 raise ExternalServiceProtocolError(self._identity)
-            required_timeout = (
-                checked.registry.resources.deadline_ms / 1000 + _EXECUTION_OVERHEAD_SECONDS
-            )
-            if self._timeout_seconds < required_timeout:
-                raise ExternalServiceUnavailableError(self._identity)
             loop = asyncio.get_running_loop()
             async with asyncio.timeout(self._timeout_seconds) as transport_watchdog:
                 placement = await self._place_post(checked, with_model_grant=model_grant is not None)
@@ -394,10 +387,10 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                     # The remote owner cannot invoke native execution before
                     # this explicit start. A failed drain of this write may
                     # still follow successful transmission, so retain uncertainty.
-                    transport_watchdog.reschedule(loop.time() + required_timeout)
+                    transport_watchdog.reschedule(loop.time() + self._timeout_seconds)
                     possibly_invoked = True
                     await self._send_frame(writer, json.dumps(
-                        dict(ready, operation="start_execution"),
+                        dict(ready, operation="start_execution", idle_ms=int(self._timeout_seconds * 1000)),
                         separators=(",", ":"),
                     ).encode())
                     while True:
@@ -408,6 +401,9 @@ async def _exchange(self, request, grant, *, model_grant, locate):
                         ):
                             raise ValueError("remote runner response header is invalid")
                         operation = header.get("operation")
+                        if operation == "native_pending" and set(header) == {"protocol_version", "operation"}:
+                            transport_watchdog.reschedule(loop.time() + self._timeout_seconds)
+                            continue
                         if operation == "callback_request":
                             if (
                                 set(header)
diff --git a/backend/tests/checkers/external/test_remote_node.py b/backend/tests/checkers/external/test_remote_node.py
index 08b11f70b..ca42386d5 100644
--- a/backend/tests/checkers/external/test_remote_node.py
+++ b/backend/tests/checkers/external/test_remote_node.py
@@ -420,6 +420,7 @@ async def native(reader, writer):
                 grant_id = wire["grant"]["grant_id"]
                 assert (material / "workspaces" / grant_id).is_dir()
                 assert wire["model_grant"]["grant_id"] == "model_" + "a" * 32
+                await asyncio.sleep(1.3)  # Native work outlasts both transport idle intervals.
                 for payload in (b'{"callback":"model"}', b'{"callback":"trial"}'):
                     callback_reader, callback_writer = await asyncio.open_unix_connection(native_proxy)
                     callback_writer.write(_frame(payload))
@@ -440,11 +441,11 @@ async def native(reader, writer):
         try:
             async with remote_adapter_endpoint(tmp_path, native_socket, model_proxy_socket_path=app_proxy,
                     material_root=material, native_model_proxy_socket_path=native_proxy,
-                    session_timeout_seconds=720.0) as endpoint:
-                assert captured[0].timeout == 720.0
+                    session_timeout_seconds=1.0) as endpoint:
+                assert captured[0].timeout == 1.0
                 assert captured[0].material_root == material
                 assert captured[0].model_proxy_socket_path == native_proxy
-                adapter = RemoteTlsExternalCheckerAdapter(**endpoint, timeout_seconds=90.0,
+                adapter = RemoteTlsExternalCheckerAdapter(**endpoint, timeout_seconds=1.0,
                     source_contracts=selected_pre_submit_source_contracts())
                 observed = await adapter.execute(value, empty_external_material_grant(value, suffix="c"),
                     model_grant=ExternalCheckerModelGrant("model_" + "a" * 32, value.request_digest))
@@ -738,7 +739,7 @@ async def old_execute(control, _reader, _writer, _watchdog):
             writer.close()
             await writer.wait_closed()
         else:
-            start = dict(ready, operation="start_execution")
+            start = dict(ready, operation="start_execution", idle_ms=90000)
             if start_mode == "wrong_binding":
                 start["binding_digest"] = "sha256:" + "0" * 64
             writer.write(_frame(json.dumps(start).encode()))
diff --git a/external_checkers/remote_node.py b/external_checkers/remote_node.py
index a5f8d0f63..7c0281cb3 100644
--- a/external_checkers/remote_node.py
+++ b/external_checkers/remote_node.py
@@ -126,6 +126,12 @@ async def callback(self, request: bytes) -> bytes:
         finally:
             self._pending.pop(channel_id, None)
 
+    async def report_pending(self) -> None:
+        async with self._write_lock:
+            await _write_frame(self.writer, json.dumps({
+                "protocol_version": PROTOCOL, "operation": "native_pending",
+            }, separators=(",", ":")).encode())
+
     async def result(self, response: bytes) -> None:
         async with self._write_lock:
             if self.closed.is_set():
@@ -688,6 +694,9 @@ def record(event: str, **facts: Any) -> None:
             }
             await _write_frame(writer, json.dumps(ready, separators=(",", ":")).encode())
             start = _decode_object(await _read_frame(reader, 16_384))
+            idle_ms = start.pop("idle_ms", None)
+            if type(idle_ms) is not int or not 100 <= idle_ms <= 3_700_000:
+                raise ProtocolError("execution transport idle interval is invalid")
             if start != dict(ready, operation="start_execution"):
                 raise ProtocolError("execution start binding differs")
             # Native execution enforces its registered limits. Give the result
@@ -708,9 +717,17 @@ def record(event: str, **facts: Any) -> None:
             response_task = asyncio.create_task(_read_frame(native_reader, MAXIMUM_FRAME_BYTES))
             disconnect_task = asyncio.create_task(channel.closed.wait())
             wait_tasks = {response_task, disconnect_task}
-            done, _ = await asyncio.wait(
-                wait_tasks, return_when=asyncio.FIRST_COMPLETED
-            )
+            # The native service owns the checker deadline. An open request
+            # can span multiple transport idle intervals.
+            interval = min(self.timeout / 3, idle_ms / 3000, 600)
+            while True:
+                done, _ = await asyncio.wait(
+                    wait_tasks, timeout=interval, return_when=asyncio.FIRST_COMPLETED
+                )
+                if done:
+                    break
+                await channel.report_pending()
+                transport_watchdog.reschedule(asyncio.get_running_loop().time() + self.timeout)
             if disconnect_task in done:
                 raise ProtocolError("remote client disconnected")
             response = await response_task

From dc76448b5f2d0792942e76f1b53ef3a0dd22f8b0 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 21:41:18 +0100
Subject: [PATCH 499/513] Document explicit Operator recovery for an expired
 unknown POST

---
 cli/README.md | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/cli/README.md b/cli/README.md
index a93d6aabf..ea272d19c 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -215,7 +215,7 @@ the [terminal presentation contract](../docs/design/cli-terminal-experience.md).
 | `workstream operations checker retry-sources PROJECT_ID [--limit N] [--cursor TOKEN]` | `GET /api/v1/operations/projects/PROJECT_ID/checker-retry-sources` |
 | `workstream operations checker retry PROJECT_ID SOURCE_RUN_ID --reason TEXT --idempotency-key UUID` | `POST /api/v1/operations/projects/PROJECT_ID/checker-runs/SOURCE_RUN_ID/retry` |
 | `workstream operations delivery list PROJECT_ID [--limit N] [--cursor TOKEN]` | `GET /api/v1/operations/projects/PROJECT_ID/post-submit-deliveries` |
-| `workstream operations delivery reconcile PROJECT_ID EVENT_ID --reason TEXT --idempotency-key UUID` | `POST /api/v1/operations/projects/PROJECT_ID/post-submit-deliveries/EVENT_ID/reconcile` |
+| `workstream operations delivery reconcile PROJECT_ID EVENT_ID [--abandon-unknown] --reason TEXT --idempotency-key UUID` | `POST /api/v1/operations/projects/PROJECT_ID/post-submit-deliveries/EVENT_ID/reconcile` |
 | `workstream task ready PROJECT_ID` | `GET /api/v1/projects/PROJECT_ID/tasks/ready` |
 | `workstream task submit TASK_ID --assignment UUID --file ZIP --idempotency-key UUID` | `POST /api/v1/tasks/TASK_ID/submissions` |
 | `workstream task submission-operation TASK_ID --operation-id UUID` (or `--idempotency-key UUID`) | `GET /api/v1/tasks/TASK_ID/submission-operations` |
@@ -2058,11 +2058,20 @@ UUID key. Fresh backend authority and exact source/child guards decide whether
 one immutable reconciliation child may be appended. The CLI does not classify
 the original effect, invoke a checker, infer retry safety, or silently replay
 the write. On an uncertain response, JSON has `error.outcome_unknown: true`;
-text advises manual replay only with the unchanged project, event, reason and
-key. An existing child can later be active, acknowledged or held on exact
+text advises manual replay only with the unchanged project, event, action,
+reason and key. An existing child can later be active, acknowledged or held on exact
 replay. This is distinct from `operations checker retry`, which selects a
 known-terminal infrastructure-failed checker run.
 
+For a held request whose checker lease has expired and whose outcome remains
+unknown after investigation, an Operator can explicitly request one successor
+evaluation for the same submission and assignment. The original attempt retains
+its unknown outcome.
+
+```sh
+workstream operations delivery reconcile PROJECT_ID EVENT_ID --abandon-unknown --reason 'Confirmed expired attempt with no result' --idempotency-key UUID -o json
+```
+
 ## Inspect artifact custody and explicitly retry verification
 
 `operations artifact` uses the existing public `/api/v1/operator/artifacts`

From b1ac8af1848900b5f107ad7f8258d665f42d84fe Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:02:32 +0100
Subject: [PATCH 500/513] Make the synthetic PRE checker readable by its guest
 UID

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md            | 16 ++++++++++++++++
 .../tests/smol_fixture/python.Dockerfile         |  2 +-
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 598193a9a..7ab7b7437 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13351,3 +13351,19 @@ passed in 96.55 seconds with database and MinIO cleanup. The cases verified
 missing-byte terminalization and replay, refusal before lease work for an
 obsolete request, rollback on retry-event failure and the signed Operator path.
 The receipt is under `/tmp/workstream-post-canonical-retry.2nn3cm`.
+
+### Make the native PRE qualification checker readable
+
+The isolated PRE300 attempt restored the normal runner and cleared all test
+resources. All three fault inputs and the passing control returned outer guest
+exit 125. No completed guest or pending-delete handoff was observed. The new
+cached fixture contained a root-owned `0600` checker copied from its private
+build source. The earlier successfully qualified image had a readable checker.
+The image commands and first four uncompressed layer digests matched.
+
+This bounded fixture repair changes only the Python fixture Dockerfile and this
+record. Set the in-image checker permissions explicitly, preserving restrictive
+build staging and the native sandbox identity. Verify the resulting layer
+header and execute a single ordinary passing input in the isolated domain
+before arming the failure matrix. The normal runner must be restored after the
+control. Review exact image custody and entrypoint readability before the run.
diff --git a/external_checkers/workstream-checker-service/tests/smol_fixture/python.Dockerfile b/external_checkers/workstream-checker-service/tests/smol_fixture/python.Dockerfile
index 4d6882819..8cb3ae03e 100644
--- a/external_checkers/workstream-checker-service/tests/smol_fixture/python.Dockerfile
+++ b/external_checkers/workstream-checker-service/tests/smol_fixture/python.Dockerfile
@@ -1,4 +1,4 @@
 FROM python:3.12-slim-bookworm@sha256:4766d8b510c428e595d74b9cc5bbb2fae8e26316fffb4adc89908d79aacd58a2
-COPY checker.py /checker.py
+COPY --chmod=0444 checker.py /checker.py
 RUN mknod /image-owned-device c 1 3 && chmod 666 /image-owned-device
 ENTRYPOINT ["python", "-I", "/checker.py"]

From ef6e216fe2ee2e3d44cdc831b3846a7558b74734 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:12:02 +0100
Subject: [PATCH 501/513] Keep POST retry scheduling behind the checker public
 contract

---
 .../app/modules/artifacts/intake/progress.py  |  4 +--
 backend/app/modules/checkers/api/execution.py |  3 +-
 backend/app/modules/checkers/checker_retry.py |  4 +--
 .../checkers/execution_coordination.py        |  6 +++-
 .../test_post_submit_delivery_http.py         | 11 +++++--
 cli/tests/integration/test_submission_http.py | 32 ++++++++++++++++---
 mcp_server/workstream_mcp/http_gateway.py     |  4 ++-
 7 files changed, 49 insertions(+), 15 deletions(-)

diff --git a/backend/app/modules/artifacts/intake/progress.py b/backend/app/modules/artifacts/intake/progress.py
index 0e4c1c902..4147cf8ed 100644
--- a/backend/app/modules/artifacts/intake/progress.py
+++ b/backend/app/modules/artifacts/intake/progress.py
@@ -6,7 +6,7 @@
 
 from app.modules.artifacts.api.submission_command import PostSubmissionProgress
 from app.modules.artifacts.api.submission_finalization import SubmissionFinalizationProgress
-from app.modules.checkers.api.execution import POST_SUBMISSION_RETRY_OPTIONS
+from app.modules.checkers.api.execution import POST_SUBMISSION_ATTEMPT_LIMIT
 from app.modules.artifacts.intake.acceptance import finalization_event
 from app.modules.artifacts.intake.repository import IntakeCustodyConflict
 from app.modules.artifacts.intake.recovery import recovery_event
@@ -218,7 +218,7 @@ async def _attempt_progress(self, row):
                     failure_code = f"post_submission_{evaluation.previous_failure_code}"
                 post = PostSubmissionProgress(
                     attempt=evaluation.current.reservation.evaluation_generation,
-                    automatic_attempt_limit=POST_SUBMISSION_RETRY_OPTIONS.max_attempts,
+                    automatic_attempt_limit=POST_SUBMISSION_ATTEMPT_LIMIT,
                     next_attempt_at=delivery.next_attempt_at if evaluation.status == "queued" else None,
                 )
                 stage = ("operationally_stalled" if stalled else
diff --git a/backend/app/modules/checkers/api/execution.py b/backend/app/modules/checkers/api/execution.py
index f8a138256..67d79a719 100644
--- a/backend/app/modules/checkers/api/execution.py
+++ b/backend/app/modules/checkers/api/execution.py
@@ -31,11 +31,10 @@
     PostSubmitExpiredLease, PostSubmitRequestDeliveryFacts,
 )
 from app.modules.model_usage.api import ModelRecoveryCandidate
-from app.modules.outbox.api import DeliveryOptions
 
 REQUEST_EVENT = "PostSubmissionEvaluationRequested"
 COMPLETION_EVENT = "PostSubmissionEvaluationCompleted"
-POST_SUBMISSION_RETRY_OPTIONS = DeliveryOptions()
+POST_SUBMISSION_ATTEMPT_LIMIT = 5
 
 
 class CheckerExecutionUnavailable(RuntimeError):
diff --git a/backend/app/modules/checkers/checker_retry.py b/backend/app/modules/checkers/checker_retry.py
index c8540ee07..2399eb6fa 100644
--- a/backend/app/modules/checkers/checker_retry.py
+++ b/backend/app/modules/checkers/checker_retry.py
@@ -34,11 +34,11 @@
     CheckerRetrySourceQuery,
     CheckerRetrySuccessor,
     EvaluationTaskGuard,
-    POST_SUBMISSION_RETRY_OPTIONS, REQUEST_EVENT,
+    REQUEST_EVENT,
 )
 from app.modules.checkers.api.evaluation_contract import PostSubmissionExecutionRequest
 from app.modules.checkers.api.selected_post_submit import make_selected_post_submit_request
-from app.modules.checkers.execution_coordination import EvaluationCoordinator
+from app.modules.checkers.execution_coordination import EvaluationCoordinator, POST_SUBMISSION_RETRY_OPTIONS
 from app.modules.checkers.execution_repository import (
     require_transaction,
     stored_request,
diff --git a/backend/app/modules/checkers/execution_coordination.py b/backend/app/modules/checkers/execution_coordination.py
index e708096e9..8142ff95c 100644
--- a/backend/app/modules/checkers/execution_coordination.py
+++ b/backend/app/modules/checkers/execution_coordination.py
@@ -18,7 +18,7 @@
     EvaluationProgress,
     ReservedEvaluation,
     EvaluationCompletion,
-    EvaluationTaskGuard, POST_SUBMISSION_RETRY_OPTIONS,
+    EvaluationTaskGuard, POST_SUBMISSION_ATTEMPT_LIMIT,
     VerifiedMaterialFacts,
     VerifiedEvaluationCompletion,
 )
@@ -41,12 +41,16 @@
     stored_request,
 )
 from app.modules.outbox.api import (
+    DeliveryOptions,
     OutboxAppendInput, OutboxAppendPort, OutboxIdempotencyConflict, OutboxInputError, OutboxPersistenceError,
 )
 from app.modules.checkers.execution_results import evaluation_completion_event
 from app.modules.checkers.models import CheckerRun, CheckerSubmissionFence, CheckerRetryReceipt
 
 
+POST_SUBMISSION_RETRY_OPTIONS = DeliveryOptions(max_attempts=POST_SUBMISSION_ATTEMPT_LIMIT)
+
+
 class EvaluationCoordinator:
     """Own exact request reservation and current-result reads in caller transactions."""
 
diff --git a/cli/tests/integration/test_post_submit_delivery_http.py b/cli/tests/integration/test_post_submit_delivery_http.py
index 40a8ce4aa..2ae26c9bc 100644
--- a/cli/tests/integration/test_post_submit_delivery_http.py
+++ b/cli/tests/integration/test_post_submit_delivery_http.py
@@ -281,8 +281,15 @@ def test_explicit_abandonment_binds_action_to_unknown_successor(cli):
         unresolved["source"]["classification"] = "unresolved"
         unresolved["successor"]["classification"] = "unresolved"
         response.update(status=201, body=json.dumps(unresolved).encode())
-        args = ("reconcile", PROJECT, EVENT, "--reason", "Expired unresolved run",
-                "--idempotency-key", KEY)
+        args = (
+            "reconcile",
+            PROJECT,
+            EVENT,
+            "--reason",
+            "Expired unresolved run",
+            "--idempotency-key",
+            KEY,
+        )
         assert invoke(cli, origin, *args, "--abandon-unknown").returncode == 0
         assert response["commands"][0][2]["action"] == "abandon_unknown"
         assert invoke(cli, origin, *args).returncode != 0
diff --git a/cli/tests/integration/test_submission_http.py b/cli/tests/integration/test_submission_http.py
index 8285de5df..4f09d3a6b 100644
--- a/cli/tests/integration/test_submission_http.py
+++ b/cli/tests/integration/test_submission_http.py
@@ -386,8 +386,13 @@ def test_submission_stage_timeouts_and_unknown_gateway_response(cli, tmp_path):
     path = tmp_path / "source.zip"
     path.write_bytes(b"ZIP")
     action = {"next_action": "retry_new_key_after_terminal"}
-    envelope = {"code": "submission_pre_timeout", "message": "upstream private diagnostic",
-                "details": action, "correlation_id": RUN, "retryable": True}
+    envelope = {
+        "code": "submission_pre_timeout",
+        "message": "upstream private diagnostic",
+        "details": action,
+        "correlation_id": RUN,
+        "retryable": True,
+    }
     with http_fixture() as (origin, response, requests):
         respond(response, {"error": envelope}, 504)
         first = cli(origin, TOKEN, *submit_args(path))
@@ -396,15 +401,32 @@ def test_submission_stage_timeouts_and_unknown_gateway_response(cli, tmp_path):
         assert error["details"] == action and not error.get("outcome_unknown", False)
         text = cli(origin, TOKEN, *submit_args(path)[:-2])
         assert "The ZIP uploaded, but pre-submission checks timed out" in text.stderr
-        assert "No Submission was created" in text.stderr and "new idempotency key" in text.stderr
+        assert (
+            "No Submission was created" in text.stderr
+            and "new idempotency key" in text.stderr
+        )
         assert "upstream private diagnostic" not in text.stderr
         respond(response, {"error": envelope | {"details": {}}}, 504)
         unknown = cli(origin, TOKEN, *submit_args(path))
         assert_failure(unknown, "invalid_api_response")
         assert json.loads(unknown.stderr)["error"]["outcome_unknown"] is True
-        respond(response, {"error": envelope | {"code": "submission_upload_timeout", "details": {}, "retryable": False}}, 408)
+        respond(
+            response,
+            {
+                "error": envelope
+                | {
+                    "code": "submission_upload_timeout",
+                    "details": {},
+                    "retryable": False,
+                }
+            },
+            408,
+        )
         upload = cli(origin, TOKEN, *submit_args(path)[:-2])
-        assert "The ZIP upload timed out before pre-submission checks started" in upload.stderr
+        assert (
+            "The ZIP upload timed out before pre-submission checks started"
+            in upload.stderr
+        )
         assert len(requests) == 4
 
 
diff --git a/mcp_server/workstream_mcp/http_gateway.py b/mcp_server/workstream_mcp/http_gateway.py
index 8a5709d8a..59a0725b3 100644
--- a/mcp_server/workstream_mcp/http_gateway.py
+++ b/mcp_server/workstream_mcp/http_gateway.py
@@ -1973,7 +1973,9 @@ def _checker_artifact_response_matches(
             source = data.get("source")
             successor = data.get("successor")
             abandoning = arguments["body"].get("action") == "abandon_unknown"
-            if not isinstance(successor, dict) or (successor.get("classification") == "unresolved") != abandoning:
+            if not isinstance(successor, dict):
+                return False
+            if (successor.get("classification") == "unresolved") != abandoning:
                 return False
             return isinstance(source, dict) and cls._fields_match(
                 source,

From ef6383c0197610aa5ee7e6b4f313e45e1344914f Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:25:00 +0100
Subject: [PATCH 502/513] Renew healthy POST ownership with hourly custody
 checks

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         |  27 +++
 backend/alembic/env.py                        |   3 +-
 .../versions/0096_post_renewable_lifetimes.py | 218 ++++++++++++++++++
 backend/app/adapters/artifacts/__init__.py    |  19 --
 backend/app/adapters/outbox/__init__.py       |   4 +-
 backend/app/modules/artifacts/preparation.py  |  16 +-
 .../authorization/api/outbox_dispatch.py      |  15 ++
 .../modules/checkers/api/external_policy.py   |  27 +--
 backend/app/modules/checkers/execution.py     |  96 +++++++-
 .../checkers/execution_coordination.py        |   7 +-
 .../modules/checkers/execution_repository.py  |   2 +-
 .../modules/checkers/model_usage_custody.py   |   6 +-
 backend/app/modules/checkers/models.py        |   6 +
 backend/app/modules/model_usage/api.py        |   4 +-
 backend/app/modules/model_usage/grants.py     |  16 +-
 backend/app/modules/outbox/api.py             |  13 +-
 backend/app/modules/outbox/delivery.py        |  99 ++++++--
 .../app/modules/outbox/delivery_repository.py |   4 +-
 backend/app/modules/outbox/models.py          |  18 +-
 .../test_outbox_dispatch_contract.py          |  17 ++
 .../checkers/execution/test_execution.py      | 124 +++++++++-
 .../tests/checkers/external/test_policy.py    |  13 +-
 .../model_usage_boundary_support.py           |   3 +-
 ...test_model_invocation_grants_postgresql.py |   6 +-
 backend/tests/conftest.py                     |   2 +-
 .../test_authority_custody_postgresql.py      |   9 +-
 .../tests/outbox/test_authority_postgresql.py |  51 +++-
 .../tests/outbox/test_delivery_postgresql.py  |  52 ++++-
 backend/tests/test_alembic.py                 | 113 ++++++++-
 29 files changed, 873 insertions(+), 117 deletions(-)
 create mode 100644 backend/alembic/versions/0096_post_renewable_lifetimes.py

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 1762963b5..23bb12a49 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13320,3 +13320,30 @@ abandonment, stale Operator authority, duplicate successors and late old-owner
 writes. It does not prove the provider stopped and does not authorize automatic
 retry of an unresolved invocation. Check exact replay, whole-transaction rollback
 and late-effect fencing through the existing signed Operator and database tests.
+
+### Renewable ownership for healthy background POST
+
+The user requires no fixed aggregate lifetime for a healthy POST sequence. The
+existing checker execution, ART callback and OUTBOX delivery path now use the
+same hourly database inspection cadence. Each inspection verifies the exact
+current run or delivery generation and extends only a bounded three-hour live
+window. The original lease and claim expiry remain immutable in requests,
+receipts and historical records. A stopped inspector cannot renew; expiration
+then admits only the existing UNKNOWN/recovery path. Each selected checker
+retains its individually approved execution deadline and cleanup budget.
+
+Migration 0096 adds separate effective-liveness fields to CHECKERS and OUTBOX
+and an audited renewal decision on the delivery attempt. It is forward-only,
+requires active owners to drain before upgrade, backfills retained 0095 rows
+with exact original expiries and keeps the prior row facts unchanged. ART
+preparation and inspection retain their fixed limits; only the verified POST
+callback can continue across the former aggregate deadline. Model invocation
+grants and trial evidence use the current live lease for availability while
+binding the immutable execution identity. The dedicated OUTBOX worker's Celery
+hard limit is updated in a separate coordinated change.
+
+Required proof is a populated 0095 upgrade with terminal and expired UNKNOWN
+rows, accelerated real PostgreSQL renewal past original expiry, refusal of
+competing recovery, long single-checker callback, and existing authorization,
+model, ART and OUTBOX regressions. This private change alone does not qualify a
+remote provider's per-call timeout or a deployed worker process.
diff --git a/backend/alembic/env.py b/backend/alembic/env.py
index d176a1f0d..623d8101e 100644
--- a/backend/alembic/env.py
+++ b/backend/alembic/env.py
@@ -21,7 +21,7 @@
 target_metadata = Base.metadata
 
 _BASELINE_REVISION = "0001_uuid7_v01"
-_CURRENT_HEAD_REVISION = "0095_post_infrastructure_retry"
+_CURRENT_HEAD_REVISION = "0096_post_renewable_lifetimes"
 _RECREATE_GUIDANCE = (
     "Workstream v0.1 requires a fresh database; recreate this database before "
     "running the 0001_uuid7_v01 migration"
@@ -150,6 +150,7 @@ def do_run_migrations(connection: Connection) -> None:
             ("0092_submission_feedback",),
             ("0093_verified_email_observation",),
             ("0094_project_archive_limits",),
+            ("0095_post_infrastructure_retry",),
             (_CURRENT_HEAD_REVISION,),
         ):
             raise RuntimeError(_RECREATE_GUIDANCE)
diff --git a/backend/alembic/versions/0096_post_renewable_lifetimes.py b/backend/alembic/versions/0096_post_renewable_lifetimes.py
new file mode 100644
index 000000000..c63db4b0a
--- /dev/null
+++ b/backend/alembic/versions/0096_post_renewable_lifetimes.py
@@ -0,0 +1,218 @@
+"""Retain immutable POST identities while inspecting live background ownership."""
+
+from alembic import op
+from sqlalchemy import text
+
+revision = "0096_post_renewable_lifetimes"
+down_revision = "0095_post_infrastructure_retry"
+branch_labels = None
+depends_on = None
+
+
+def _replace(signature: str, *changes: tuple[str, str, int]) -> None:
+    """Change only the installed, identified owner routine's expected clauses."""
+    body = op.get_bind().execute(text(
+        "SELECT pg_catalog.pg_get_functiondef(CAST(:signature AS regprocedure))"
+    ), {"signature": signature}).scalar_one()
+    for old, new, count in changes:
+        if body.count(old) != count:
+            raise RuntimeError("POST lease predecessor shape changed: " + signature)
+        body = body.replace(old, new)
+    op.execute(body)
+
+
+def upgrade() -> None:
+    """Add bounded renewable liveness, retaining every original claim and receipt."""
+    op.execute("SET LOCAL search_path=pg_catalog,public,pg_temp")
+    op.execute("LOCK TABLE public.checker_runs, public.outbox_events, "
+               "public.outbox_delivery_attempts IN ACCESS EXCLUSIVE MODE")
+    if op.get_bind().execute(text("""
+        SELECT EXISTS(SELECT 1 FROM public.checker_runs
+          WHERE status='running' AND worker_lease_expires_at>clock_timestamp())
+          OR EXISTS(SELECT 1 FROM public.outbox_events
+          WHERE delivery_state='claimed' AND claim_expires_at>clock_timestamp())
+    """)).scalar_one():
+        raise RuntimeError("drain live POST and OUTBOX claims before renewable-lease migration")
+
+    op.execute("ALTER TABLE public.checker_runs ADD COLUMN worker_lease_live_until timestamptz")
+    # Rewrite the newly added projection under the table lock. A row UPDATE
+    # would queue old deferred custody checks for retained terminal history;
+    # those checks intentionally need not validate against today's schema.
+    # The DDL rewrite preserves row values without disabling any trigger.
+    op.execute("ALTER TABLE public.checker_runs ALTER COLUMN worker_lease_live_until "
+               "TYPE timestamptz USING worker_lease_expires_at")
+    op.execute("ALTER TABLE public.checker_runs ADD CONSTRAINT ck_checker_runs_live_lease_shape "
+               "CHECK ((worker_lease_id IS NULL AND worker_lease_live_until IS NULL) OR "
+               "(worker_lease_id IS NOT NULL AND worker_lease_live_until IS NOT NULL "
+               "AND worker_lease_live_until>=worker_lease_expires_at))")
+
+    op.execute("ALTER TABLE public.outbox_events ADD COLUMN claim_live_until timestamptz")
+    op.execute("ALTER TABLE public.outbox_events ALTER COLUMN claim_live_until "
+               "TYPE timestamptz USING CASE WHEN delivery_state='claimed' "
+               "THEN claim_expires_at ELSE NULL END")
+    op.execute("ALTER TABLE public.outbox_events ADD CONSTRAINT ck_outbox_events_claim_live_shape "
+               "CHECK ((delivery_state='claimed' AND claim_live_until IS NOT NULL "
+               "AND claim_live_until>=claim_expires_at) OR "
+               "(delivery_state<>'claimed' AND claim_live_until IS NULL))")
+    op.execute("DROP INDEX public.ix_outbox_events_expired_claims")
+    op.execute("CREATE INDEX ix_outbox_events_expired_claims ON public.outbox_events "
+               "(claim_live_until,event_id) WHERE delivery_state='claimed'")
+
+    op.execute("ALTER TABLE public.outbox_delivery_attempts ADD COLUMN claim_live_until timestamptz")
+    op.execute("ALTER TABLE public.outbox_delivery_attempts ALTER COLUMN claim_live_until "
+               "TYPE timestamptz USING claim_expires_at")
+    op.execute("ALTER TABLE public.outbox_delivery_attempts ALTER COLUMN claim_live_until SET NOT NULL")
+    op.execute("ALTER TABLE public.outbox_delivery_attempts ADD COLUMN renew_decision_event_id uuid "
+               "REFERENCES public.audit_events(id)")
+    op.execute("ALTER TABLE public.outbox_delivery_attempts ADD CONSTRAINT "
+               "ck_outbox_delivery_attempts_renewed_lease CHECK "
+               "((claim_live_until=claim_expires_at AND renew_decision_event_id IS NULL) OR "
+               "(claim_live_until>claim_expires_at AND renew_decision_event_id IS NOT NULL))")
+    op.execute("ALTER TABLE public.outbox_delivery_attempts DROP CONSTRAINT "
+               "ck_outbox_delivery_attempts_outcome")
+    op.execute("ALTER TABLE public.outbox_delivery_attempts ADD CONSTRAINT "
+               "ck_outbox_delivery_attempts_outcome CHECK (outcome_json IS NULL OR "
+               "coalesce(public.outbox_delivery_outcome_valid(outcome_json,outcome_digest,"
+               "claimed_at,claim_live_until,invoked_at),false))")
+
+    _replace("public.protect_checker_run_custody()",
+        ("'worker_lease_generation','worker_lease_expires_at','execute_evidence_id'",
+         "'worker_lease_generation','worker_lease_expires_at','worker_lease_live_until','execute_evidence_id'", 1),
+        ("IF NEW.status='running' THEN", _CHECKER_RENEW + "\n        IF NEW.status='running' THEN", 1),
+        ("OLD.worker_lease_expires_at > clock_timestamp()",
+         "OLD.worker_lease_live_until > clock_timestamp()", 1),
+        ("OR NEW.worker_lease_expires_at > clock_timestamp()+interval '1 hour'",
+         "OR NEW.worker_lease_expires_at > clock_timestamp()+interval '1 hour'\n"
+         "            OR NEW.worker_lease_live_until IS DISTINCT FROM NEW.worker_lease_expires_at", 1),
+        ("OLD.worker_lease_expires_at <= clock_timestamp()",
+         "OLD.worker_lease_live_until <= clock_timestamp()", 1),
+        ("OR NEW.worker_lease_expires_at IS DISTINCT FROM OLD.worker_lease_expires_at",
+         "OR NEW.worker_lease_expires_at IS DISTINCT FROM OLD.worker_lease_expires_at\n"
+         "            OR NEW.worker_lease_live_until IS DISTINCT FROM OLD.worker_lease_live_until", 1),
+        ("IF NEW.worker_lease_id IS NOT NULL OR NEW.worker_lease_expires_at IS NOT NULL",
+         "IF NEW.worker_lease_id IS NOT NULL OR NEW.worker_lease_expires_at IS NOT NULL\n"
+         "          OR NEW.worker_lease_live_until IS NOT NULL", 1),
+        ("ELSIF NEW.worker_lease_id IS NULL OR NEW.worker_lease_expires_at IS NULL",
+         "ELSIF NEW.worker_lease_id IS NULL OR NEW.worker_lease_expires_at IS NULL\n"
+         "        OR NEW.worker_lease_live_until IS NULL", 1),
+    )
+    _replace("public.checker_post_submit_abandonment_valid(public.checker_runs,public.checker_runs)",
+        ("source.worker_lease_expires_at<=clock_timestamp()",
+         "source.worker_lease_live_until<=clock_timestamp()", 1),
+        ("ca.claim_expires_at>clock_timestamp()",
+         "ca.claim_live_until>clock_timestamp()", 1))
+    _replace("public.guard_task_routing_authority()",
+        ("OR a.stage IS DISTINCT FROM 'invoked'\n"
+         "          OR a.finalize_decision_event_id IS NOT NULL\n"
+         "          OR a.claim_expires_at<=clock_timestamp()\n"
+         "          OR a.project_id IS DISTINCT FROM NEW.project_id",
+         "OR a.stage IS DISTINCT FROM 'invoked'\n"
+         "          OR a.finalize_decision_event_id IS NOT NULL\n"
+         "          OR a.claim_live_until<=clock_timestamp()\n"
+         "          OR a.project_id IS DISTINCT FROM NEW.project_id", 1))
+    _replace("public.guard_checker_model_invocation_grant()",
+        ("run.worker_lease_expires_at IS DISTINCT FROM NEW.expires_at",
+         "run.worker_lease_live_until IS DISTINCT FROM NEW.expires_at", 1),
+        ("run.status IS DISTINCT FROM 'running' OR run.phase IS DISTINCT FROM 'post_submission'",
+         "run.worker_lease_live_until<=clock_timestamp() OR "
+         "run.status IS DISTINCT FROM 'running' OR run.phase IS DISTINCT FROM 'post_submission'", 1))
+    _replace("public.guard_checker_trial_evidence()",
+        ("run.worker_lease_expires_at<=pg_catalog.clock_timestamp()",
+         "run.worker_lease_live_until<=pg_catalog.clock_timestamp()", 2))
+    _replace("public.guard_checker_trial_artifact_ancestry()",
+        ("run.worker_lease_expires_at<=pg_catalog.clock_timestamp()",
+         "run.worker_lease_live_until<=pg_catalog.clock_timestamp()", 1))
+
+    _replace("public.guard_outbox_event()",
+        ("new.claim_expires_at := null;", "new.claim_expires_at := null;\n            new.claim_live_until := null;", 1),
+        ("or new.last_error_code is distinct from old.last_error_code then\n              raise exception 'outbox claim generation must increment once'",
+         "or new.last_error_code is distinct from old.last_error_code\n"
+         "               or new.claim_live_until is distinct from new.claim_expires_at then\n"
+         "              raise exception 'outbox claim generation must increment once'", 1),
+        ("elsif old.delivery_state = 'claimed'\n                and new.delivery_state in",
+         _OUTBOX_RENEW + "\n          elsif old.delivery_state = 'claimed'\n                and new.delivery_state in", 1),
+        ("or new.last_attempt_at is distinct from old.last_attempt_at then\n              raise exception 'outbox outcome cannot change claim generation'",
+         "or new.last_attempt_at is distinct from old.last_attempt_at\n"
+         "               or new.claim_live_until is not null then\n"
+         "              raise exception 'outbox outcome cannot change claim generation'", 1))
+    _replace("public.check_outbox_delivery_projection()",
+        ("(e.claim_owner,e.claimed_at,e.claim_expires_at,e.last_attempt_at) is distinct from\n"
+         "               (a.claim_owner,a.claimed_at,a.claim_expires_at,a.claimed_at)",
+         "(e.claim_owner,e.claimed_at,e.claim_expires_at,e.claim_live_until,e.last_attempt_at) is distinct from\n"
+         "               (a.claim_owner,a.claimed_at,a.claim_expires_at,a.claim_live_until,a.claimed_at)", 1))
+    _replace("public.outbox_dispatch_authority_digest(public.outbox_delivery_attempts,text)",
+        ("'outcome_digest',case when phase='finalize' then a.outcome_digest else null end\n              )",
+         "'outcome_digest',case when phase='finalize' then a.outcome_digest else null end\n"
+         "              ) || case when phase='renew' then\n"
+         "                jsonb_build_object('live_until',outbox_dispatch_utc(a.claim_live_until))\n"
+         "                else '{}'::jsonb end", 1))
+    _replace("public.require_outbox_phase_authority()",
+        ("array['claim','invoke','finalize']", "array['claim','invoke','renew','finalize']", 1),
+        ("if previous_id is not null and decision_id is distinct from previous_id then",
+         "if phase<>'renew' and previous_id is not null "
+         "and decision_id is distinct from previous_id then", 1),
+        ("if previous_id is null and (actor.status is distinct from 'active' or link.status is distinct from 'active') then",
+         "if (previous_id is null or decision_id is distinct from previous_id) "
+         "and (actor.status is distinct from 'active' or link.status is distinct from 'active') then", 1))
+    op.execute(_OUTBOX_ATTEMPT_RENEW_GUARD)
+    op.execute("CREATE TRIGGER outbox_attempt_renewal_guard BEFORE UPDATE OF "
+               "claim_live_until,renew_decision_event_id ON public.outbox_delivery_attempts "
+               "FOR EACH ROW EXECUTE FUNCTION public.guard_outbox_attempt_renewal()")
+
+
+def downgrade() -> None:
+    """Retained running lease history cannot be truncated by a downgrade."""
+    raise RuntimeError("renewable POST custody is forward-only")
+
+
+_CHECKER_RENEW = """
+        IF OLD.status='running' AND NEW.status='running'
+          AND NEW.worker_lease_live_until IS DISTINCT FROM OLD.worker_lease_live_until THEN
+          IF (to_jsonb(NEW)-'worker_lease_live_until') IS DISTINCT FROM
+             (to_jsonb(OLD)-'worker_lease_live_until')
+            OR NEW.worker_lease_live_until IS NULL
+            OR OLD.worker_lease_live_until<=clock_timestamp()
+            OR NEW.worker_lease_live_until<=OLD.worker_lease_live_until
+            OR NEW.worker_lease_live_until>clock_timestamp()+interval '3 hours'
+            OR NOT public.checker_post_submit_receipt_valid(OLD,'execute',true)
+            OR NOT EXISTS (SELECT 1 FROM public.checker_submission_fences f
+              WHERE f.submission_id=OLD.submission_id AND f.current_run_id=OLD.id)
+          THEN RAISE EXCEPTION 'checker renewal custody is invalid' USING ERRCODE='23514'; END IF;
+          RETURN NEW;
+        END IF;"""
+
+
+_OUTBOX_RENEW = """elsif old.delivery_state = 'claimed' and new.delivery_state = 'claimed' then
+            if (to_jsonb(new)-'claim_live_until') is distinct from
+               (to_jsonb(old)-'claim_live_until')
+               or old.event_type not in ('PostSubmissionEvaluationRequested',
+                 'PostSubmissionDeliveryReconciliationRequested')
+               or old.event_version<>1
+               or old.claim_live_until<=clock_timestamp()
+               or new.claim_live_until<=old.claim_live_until
+               or new.claim_live_until>clock_timestamp()+interval '3 hours' then
+              raise exception 'outbox renewal custody is invalid' using errcode='23514';
+            end if;"""
+
+
+_OUTBOX_ATTEMPT_RENEW_GUARD = """
+CREATE FUNCTION public.guard_outbox_attempt_renewal() RETURNS trigger
+LANGUAGE plpgsql SET search_path=pg_catalog,public,pg_temp AS $$
+DECLARE event public.outbox_events%ROWTYPE;
+BEGIN
+  SELECT * INTO event FROM public.outbox_events WHERE event_id=OLD.event_id FOR UPDATE;
+  IF OLD.stage IS DISTINCT FROM 'invoked' OR NEW.stage IS DISTINCT FROM 'invoked'
+    OR (to_jsonb(NEW)-ARRAY['claim_live_until','renew_decision_event_id']) IS DISTINCT FROM
+       (to_jsonb(OLD)-ARRAY['claim_live_until','renew_decision_event_id'])
+    OR OLD.claim_live_until<=clock_timestamp()
+    OR NEW.claim_live_until<=OLD.claim_live_until
+    OR NEW.claim_live_until>clock_timestamp()+interval '3 hours'
+    OR NEW.renew_decision_event_id IS NULL
+    OR NEW.renew_decision_event_id IS NOT DISTINCT FROM OLD.renew_decision_event_id
+    OR event.delivery_state IS DISTINCT FROM 'claimed'
+    OR event.claim_generation IS DISTINCT FROM OLD.claim_generation
+    OR event.claim_live_until IS DISTINCT FROM NEW.claim_live_until
+  THEN RAISE EXCEPTION 'outbox attempt renewal custody is invalid' USING ERRCODE='23514'; END IF;
+  RETURN NEW;
+END $$
+"""
diff --git a/backend/app/adapters/artifacts/__init__.py b/backend/app/adapters/artifacts/__init__.py
index 6072047a1..2f21185df 100644
--- a/backend/app/adapters/artifacts/__init__.py
+++ b/backend/app/adapters/artifacts/__init__.py
@@ -493,26 +493,7 @@ async def materialize(
             _artifact_worker_database,
             initialize_artifact_internal_runtime,
         )
-        from app.modules.checkers.api.external_policy import (
-            ExternalCheckerPolicyError,
-            selected_post_submit_execution_budget_ms,
-        )
-        from app.modules.checkers.api.materialization import (
-            PostSubmissionMaterializationFailure,
-        )
-
         settings = get_settings()
-        try:
-            selected_post_submit_execution_budget_ms(
-                facts.request.policy,
-                artifact_deadline_ms=int(
-                    settings.artifact_preparation_total_deadline_seconds * 1000
-                ),
-            )
-        except ExternalCheckerPolicyError:
-            raise PostSubmissionMaterializationFailure(
-                "post_submit_material_deadline_unavailable"
-            ) from None
         async with _artifact_worker_database():
             await initialize_artifact_internal_runtime()
             with _artifact_internal_runtime() as (store, namespace):
diff --git a/backend/app/adapters/outbox/__init__.py b/backend/app/adapters/outbox/__init__.py
index e7a793fab..93bb7786b 100644
--- a/backend/app/adapters/outbox/__init__.py
+++ b/backend/app/adapters/outbox/__init__.py
@@ -78,7 +78,6 @@ def production_outbox_delivery(
     from app.modules.checkers.api.execution import COMPLETION_EVENT, REQUEST_EVENT
     from app.modules.checkers.api.external_policy import (
         SELECTED_POST_DELIVERY_LEASE_SECONDS,
-        SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
     )
     from app.modules.tasks.api.assignment_invalidation import ASSIGNMENT_INVALIDATION_EVENT
     from app.modules.tasks.api.revision_exhaustion import REVISION_EXHAUSTED_EVENT
@@ -196,7 +195,8 @@ def production_outbox_delivery(
     ))
     post_options = DeliveryOptions(
         lease_seconds=SELECTED_POST_DELIVERY_LEASE_SECONDS,
-        handler_timeout_seconds=SELECTED_POST_HANDLER_TIMEOUT_SECONDS,
+        handler_timeout_seconds=None,
+        background_heartbeat=True,
     )
     event_options = {
         ("SubmissionFinalizationRequested", 1): finalization_options,
diff --git a/backend/app/modules/artifacts/preparation.py b/backend/app/modules/artifacts/preparation.py
index df5d1934e..a4471f331 100644
--- a/backend/app/modules/artifacts/preparation.py
+++ b/backend/app/modules/artifacts/preparation.py
@@ -2679,6 +2679,7 @@ async def _process_prepared_post_submission(
             processor,
             reserved_bytes=reserved_bytes,
             maximum_entries=maximum_entries,
+            bound_callback=False,
         )
 
     async def _process_prepared_artifacts(
@@ -2688,6 +2689,7 @@ async def _process_prepared_artifacts(
         *,
         reserved_bytes: int,
         maximum_entries: int,
+        bound_callback: bool = True,
     ) -> _InspectionResult:
         """Use one quota-owned workspace and cancellation lifetime for every input."""
         if (
@@ -2782,11 +2784,17 @@ async def abort_and_drain() -> None:
                 raise error from None
 
         try:
-            async with asyncio.timeout_at(deadline):
+            if bound_callback:
+                async with asyncio.timeout_at(deadline):
+                    result, error = await asyncio.shield(operation)
+            else:
+                # POST preparation and inspection retain their own fixed limits.
+                # The callback runs approved checkers, each with its own limit;
+                # the whole background evaluation has no aggregate deadline.
                 result, error = await asyncio.shield(operation)
-                if error is not None:
-                    raise error
-                return cast(_InspectionResult, result)
+            if error is not None:
+                raise error
+            return cast(_InspectionResult, result)
         except TimeoutError:
             await abort_and_drain()
             raise ArtifactPreparationDeadlineError(
diff --git a/backend/app/modules/authorization/api/outbox_dispatch.py b/backend/app/modules/authorization/api/outbox_dispatch.py
index 0113b1e52..ed5fd89f6 100644
--- a/backend/app/modules/authorization/api/outbox_dispatch.py
+++ b/backend/app/modules/authorization/api/outbox_dispatch.py
@@ -28,6 +28,7 @@ class OutboxDispatchPhase(StrEnum):
 
     CLAIM = "claim"
     INVOKE = "invoke"
+    RENEW = "renew"
     FINALIZE = "finalize"
 
 
@@ -49,6 +50,7 @@ class OutboxDispatchFacts:
     claim_owner: str
     claimed_at: datetime
     claim_expires_at: datetime
+    live_until: datetime | None = None
     outcome_digest: str | None = None
 
     def __post_init__(self) -> None:
@@ -73,6 +75,11 @@ def __post_init__(self) -> None:
                 raise ValueError("outbox dispatch outcome is invalid")
         elif self.outcome_digest is not None:
             raise ValueError("outbox dispatch outcome is invalid")
+        if self.phase is OutboxDispatchPhase.RENEW:
+            if type(self.live_until) is not datetime:
+                raise ValueError("outbox renewal time is invalid")
+        elif self.live_until is not None:
+            raise ValueError("outbox renewal time is invalid")
         try:
             if self.claimed_at.utcoffset() is None or self.claim_expires_at.utcoffset() is None:
                 raise ValueError("naive lease timestamp")
@@ -80,10 +87,17 @@ def __post_init__(self) -> None:
             expires = self.claim_expires_at.astimezone(timezone.utc)
             if expires <= claimed:
                 raise ValueError("non-positive lease interval")
+            if self.live_until is not None and (
+                self.live_until.utcoffset() is None
+                or self.live_until.astimezone(timezone.utc) <= expires
+            ):
+                raise ValueError("outbox renewal time is invalid")
         except Exception:
             raise ValueError("outbox dispatch lease is invalid") from None
         object.__setattr__(self, "claimed_at", claimed)
         object.__setattr__(self, "claim_expires_at", expires)
+        if self.live_until is not None:
+            object.__setattr__(self, "live_until", self.live_until.astimezone(timezone.utc))
 
 
 def outbox_dispatch_resource_digest(facts: OutboxDispatchFacts) -> str:
@@ -97,6 +111,7 @@ def outbox_dispatch_resource_digest(facts: OutboxDispatchFacts) -> str:
             else str(value) if isinstance(value, UUID) else value
         )
         for field in fields(checked)
+        if field.name != "live_until" or checked.live_until is not None
         for value in (getattr(checked, field.name),)
     }
     body = json.dumps(
diff --git a/backend/app/modules/checkers/api/external_policy.py b/backend/app/modules/checkers/api/external_policy.py
index eef9783b2..f4927b060 100644
--- a/backend/app/modules/checkers/api/external_policy.py
+++ b/backend/app/modules/checkers/api/external_policy.py
@@ -44,16 +44,11 @@
 WORKSTREAM_DEFAULT_EXECUTION_BUDGET_MS = 60_000
 MAXIMUM_SELECTED_PRE_EXECUTION_BUDGET_MS = 7_200_000
 SELECTED_POST_MATERIALIZATION_BUDGET_MS = 60_000
-# The outbox claim is natively bounded to one hour. Keep explicit time for the
-# request reader/authority prelude, execution finalization and delivery commit.
-MAXIMUM_SELECTED_POST_EXECUTION_BUDGET_MS = 3_400_000
-SELECTED_POST_HANDLER_PRELUDE_MARGIN_MS = 60_000
+# Each selected checker retains its approved per-invocation deadline. The
+# background POST sequence is inspected and renewed rather than given one
+# aggregate execution deadline.
+SELECTED_POST_INITIAL_WORKER_WINDOW_MS = 3_400_000
 SELECTED_POST_FINALIZATION_MARGIN_MS = 60_000
-SELECTED_POST_HANDLER_TIMEOUT_SECONDS = (
-    MAXIMUM_SELECTED_POST_EXECUTION_BUDGET_MS
-    + SELECTED_POST_HANDLER_PRELUDE_MARGIN_MS
-    + SELECTED_POST_FINALIZATION_MARGIN_MS
-) // 1000
 SELECTED_POST_DELIVERY_LEASE_SECONDS = 3_600
 
 EVALUATION_CONTEXT_VERSION_KEY = "workstream_evaluation_context_version"
@@ -537,15 +532,9 @@ def selected_pre_submit_execution_budget_ms(
 
 def selected_post_submit_execution_budget_ms(
     policy: LockedExternalPostSubmitPolicy,
-    *,
-    artifact_deadline_ms: int | None = None,
 ) -> int:
-    """Bound ART materialization and every ordered POST image under one lease."""
-    if (
-        type(policy) is not LockedExternalPostSubmitPolicy
-        or artifact_deadline_ms is not None
-        and (type(artifact_deadline_ms) is not int or artifact_deadline_ms <= 0)
-    ):
+    """Estimate bounded individual work without imposing a whole-POST cutoff."""
+    if type(policy) is not LockedExternalPostSubmitPolicy:
         raise ExternalCheckerPolicyError("selected POST execution budget is invalid")
     required = SELECTED_POST_MATERIALIZATION_BUDGET_MS + sum(
         binding.registry.resources.deadline_ms
@@ -559,8 +548,4 @@ def selected_post_submit_execution_budget_ms(
         )
         for binding in policy.entries
     )
-    if required > MAXIMUM_SELECTED_POST_EXECUTION_BUDGET_MS:
-        raise ExternalCheckerPolicyError("selected POST execution exceeds durable worker deadline")
-    if artifact_deadline_ms is not None and required > artifact_deadline_ms:
-        raise ExternalCheckerPolicyError("selected POST execution exceeds ART custody deadline")
     return required
diff --git a/backend/app/modules/checkers/execution.py b/backend/app/modules/checkers/execution.py
index 9cb558a1d..907b73ede 100644
--- a/backend/app/modules/checkers/execution.py
+++ b/backend/app/modules/checkers/execution.py
@@ -1,5 +1,6 @@
 """One async post-submit execution path over reserved CHECKERS custody."""
 
+import asyncio
 import json
 import math
 from dataclasses import asdict
@@ -9,6 +10,7 @@
 from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
 
 from app.core.identifiers import new_record_id
+from app.core.cancellation import await_cancellation_resistant
 from app.modules.checkers.api.execution import (
     ExecutionAuthorityPort,
     FinalizationAuthorityPort,
@@ -32,7 +34,7 @@
 from app.modules.checkers.api.external import PostSubmitExternalCheckerIdentity
 from app.modules.checkers.api.evaluation_context import PostSubmitInputContextCustody
 from app.modules.checkers.api.external_policy import (
-    MAXIMUM_SELECTED_POST_EXECUTION_BUDGET_MS,
+    SELECTED_POST_INITIAL_WORKER_WINDOW_MS,
     SELECTED_POST_FINALIZATION_MARGIN_MS,
     selected_post_submit_execution_budget_ms,
 )
@@ -57,7 +59,11 @@
     PostSubmissionMaterializationPort,
     PostSubmissionMaterializationFailure,
 )
-from app.modules.outbox.api import OutboxAppendPort
+from app.modules.outbox.api import (
+    BACKGROUND_LIVE_WINDOW_SECONDS,
+    BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS,
+    OutboxAppendPort,
+)
 from app.modules.checkers.api.execution import EvaluationTaskGuard, ReviewModePort
 from app.modules.checkers.execution_coordination import EvaluationCoordinator
 
@@ -167,7 +173,83 @@ def __init__(
     def _execution_budget_seconds(request: PostSubmissionExecutionRequest) -> int:
         """Reserve the durable worker envelope, not a short whole-POST cutoff."""
         selected_post_submit_execution_budget_ms(request.policy)
-        return math.ceil(MAXIMUM_SELECTED_POST_EXECUTION_BUDGET_MS / 1000)
+        return math.ceil(SELECTED_POST_INITIAL_WORKER_WINDOW_MS / 1000)
+
+    async def _renew_running_lease(self, request, lease):
+        """Observe the exact current worker and extend only its live window."""
+        async with self._sessions() as session, session.begin():
+            repo = ExecutionRepository(session)
+            run = await repo.lock_current(request)
+            now = await repo.now()
+            if (
+                run.status != "running"
+                or reservation(run) != lease.reservation
+                or run.worker_lease_id != str(lease.lease_id)
+                or run.worker_lease_generation != lease.lease_generation
+                or run.worker_lease_expires_at != lease.expires_at
+                or run.worker_lease_live_until is None
+                or run.worker_lease_live_until <= now
+            ):
+                raise CheckerExecutionUnavailable("checker_execution_lease_unavailable")
+            run.worker_lease_live_until = now + timedelta(seconds=BACKGROUND_LIVE_WINDOW_SECONDS)
+            await session.flush()
+
+    async def _materialize_while_owned(self, request, lease):
+        """Check live database custody hourly while bounded provider calls run."""
+        inspection_timed_out = asyncio.Event()
+
+        async def inspect():
+            while True:
+                await asyncio.sleep(BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS)
+                renewal = asyncio.create_task(self._renew_running_lease(request, lease))
+                try:
+                    done, _ = await asyncio.wait(
+                        (renewal,), timeout=BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS,
+                    )
+                    if not done:
+                        # Stop native work before waiting for a blocked DB rollback.
+                        inspection_timed_out.set()
+                        work.cancel()
+                        raise CheckerExecutionUnavailable("checker_execution_lease_unavailable")
+                    try:
+                        await renewal
+                    except TimeoutError:
+                        raise CheckerExecutionUnavailable(
+                            "checker_execution_lease_unavailable"
+                        ) from None
+                finally:
+                    if not renewal.done():
+                        renewal.cancel()
+                        await asyncio.gather(renewal, return_exceptions=True)
+
+        try:
+            await asyncio.wait_for(
+                self._renew_running_lease(request, lease),
+                timeout=BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS,
+            )
+        except TimeoutError:
+            raise CheckerExecutionUnavailable("checker_execution_lease_unavailable") from None
+        work = asyncio.create_task(self._materialization.materialize(
+            ExecuteFacts(request=request, lease=lease), self._consumer(request, lease),
+        ))
+        inspection = asyncio.create_task(inspect())
+        try:
+            while True:
+                done, _ = await asyncio.wait((work, inspection), return_when=asyncio.FIRST_COMPLETED)
+                if inspection in done or inspection_timed_out.is_set():
+                    await inspection
+                if work in done:
+                    return await work
+        finally:
+            inspection.cancel()
+            work_was_running = not work.done()
+            if work_was_running:
+                work.cancel()
+            await asyncio.gather(inspection, return_exceptions=True)
+            try:
+                await await_cancellation_resistant(work)
+            except asyncio.CancelledError:
+                pass
 
     def _consumer(self, request, lease):
         if self._selected_execution is None:
@@ -207,7 +289,7 @@ async def _claim(self, request):
                         output_binding_ids=(),
                     )
                 now = await repo.now()
-                if run.status == "running" and run.worker_lease_expires_at > now:
+                if run.status == "running" and run.worker_lease_live_until > now:
                     raise CheckerExecutionUnavailable("checker_execution_lease_unavailable")
                 execution_seconds = self._execution_budget_seconds(request)
                 lease_seconds = execution_seconds + math.ceil(
@@ -224,6 +306,7 @@ async def _claim(self, request):
                 run.worker_lease_id = str(lease.lease_id)
                 run.worker_lease_generation = lease.lease_generation
                 run.worker_lease_expires_at = lease.expires_at
+                run.worker_lease_live_until = lease.expires_at
                 run.started_at = run.started_at or now
                 run.status = "running"
                 run.execute_evidence_id = str(evidence_id)
@@ -245,10 +328,7 @@ async def evaluate_post_submission(
             # ART owns material/transport bounds; each registered checker owns
             # its execution limit. Their foreground estimate is not a deadline
             # for this background workflow.
-            materialized = await self._materialization.materialize(
-                ExecuteFacts(request=request, lease=lease),
-                self._consumer(request, lease),
-            )
+            materialized = await self._materialize_while_owned(request, lease)
             material = VerifiedMaterialFacts(
                 **{
                     k: v
diff --git a/backend/app/modules/checkers/execution_coordination.py b/backend/app/modules/checkers/execution_coordination.py
index e708096e9..658a7f391 100644
--- a/backend/app/modules/checkers/execution_coordination.py
+++ b/backend/app/modules/checkers/execution_coordination.py
@@ -86,7 +86,8 @@ async def require_expired_unknown_lease(self, request: PostSubmissionExecutionRe
         repo = ExecutionRepository(self._session)
         run = await repo.lock_current(request)
         if (run.status != "running" or run.worker_lease_id is None or run.worker_lease_expires_at is None
-                or run.worker_lease_expires_at > await repo.now() or run.result_json is not None):
+                or run.worker_lease_live_until is None or run.worker_lease_live_until > await repo.now()
+                or run.result_json is not None):
             raise CheckerRetrySourceUnavailable("checker_abandonment_source_unavailable")
         return PostSubmitExpiredLease(lease_id=UUID(run.worker_lease_id), lease_generation=run.worker_lease_generation,
                                       expires_at=run.worker_lease_expires_at)
@@ -316,8 +317,8 @@ async def read_current_progress(
             raise CheckerExecutionUnavailable(unavailable)
         now = await self._session.scalar(select(func.clock_timestamp()))
         live = (run.status == "running" and run.worker_lease_id is not None
-                and run.worker_lease_generation > 0 and run.worker_lease_expires_at is not None
-                and run.worker_lease_expires_at > now)
+                and run.worker_lease_generation > 0 and run.worker_lease_live_until is not None
+                and run.worker_lease_live_until > now)
         return EvaluationProgress(
             current=current, status=run.status, live_worker_lease=live, failure_code=failure_code,
             previous_failure_code=previous_failure_code,
diff --git a/backend/app/modules/checkers/execution_repository.py b/backend/app/modules/checkers/execution_repository.py
index c01f28fc6..baf7d9ca9 100644
--- a/backend/app/modules/checkers/execution_repository.py
+++ b/backend/app/modules/checkers/execution_repository.py
@@ -139,7 +139,7 @@ async def require_lease(
             or run.worker_lease_id != str(lease.lease_id)
             or run.worker_lease_generation != lease.lease_generation
             or run.worker_lease_expires_at != lease.expires_at
-            or run.worker_lease_expires_at <= await self.now()
+            or run.worker_lease_live_until <= await self.now()
         ):
             raise CheckerExecutionUnavailable("checker_execution_lease_unavailable")
         return run
diff --git a/backend/app/modules/checkers/model_usage_custody.py b/backend/app/modules/checkers/model_usage_custody.py
index b8c1d8d7f..0eb73da9f 100644
--- a/backend/app/modules/checkers/model_usage_custody.py
+++ b/backend/app/modules/checkers/model_usage_custody.py
@@ -1,5 +1,6 @@
 """Current invocation and call-stable private evidence custody."""
 
+from datetime import datetime
 from uuid import UUID
 
 from sqlalchemy import select
@@ -77,7 +78,7 @@ async def require_current(
         self,
         facts: ModelCallExecutionFacts,
         slot: ModelPaidSlotKey,
-    ) -> None:
+    ) -> datetime:
         """Read immutable request facts, then lock TASK before the CHECKERS fence."""
         require_transaction(self._session)
         facts = ModelCallExecutionFacts.model_validate(facts)
@@ -115,6 +116,9 @@ async def require_current(
             )
         except CheckerExecutionUnavailable:
             raise ModelCallUnavailable("model_call_execution_unavailable") from None
+        if run.worker_lease_live_until is None:
+            raise ModelCallUnavailable("model_call_execution_unavailable")
+        return run.worker_lease_live_until
 
     async def require_recovery_current(
         self, slot: ModelPaidSlotKey, parent_attempt_id: UUID
diff --git a/backend/app/modules/checkers/models.py b/backend/app/modules/checkers/models.py
index 84f1a8933..9a747e7b7 100644
--- a/backend/app/modules/checkers/models.py
+++ b/backend/app/modules/checkers/models.py
@@ -213,6 +213,11 @@ class CheckerRun(Base):
         ),
         CheckConstraint("evaluation_generation > 0 and worker_lease_generation >= 0", name="generations"),
         CheckConstraint("status in ('queued','running','completed','infrastructure_failed')", name="state"),
+        CheckConstraint(
+            "(worker_lease_id is null and worker_lease_live_until is null) or "
+            "(worker_lease_id is not null and worker_lease_live_until>=worker_lease_expires_at)",
+            name="live_lease_shape",
+        ),
         CheckConstraint(
             "(retry_abandonment_event_id IS NULL OR retry_delivery_event_id IS NOT NULL) AND "
             "(retry_delivery_event_id IS NULL OR (supersedes_checker_run_id IS NOT NULL "
@@ -253,6 +258,7 @@ class CheckerRun(Base):
     worker_lease_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
     worker_lease_generation: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
     worker_lease_expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+    worker_lease_live_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
     execute_evidence_id: Mapped[str | None] = mapped_column(
         Uuid(as_uuid=False), ForeignKey("audit_events.id", name="fk_checker_runs_execute_evidence", deferrable=True, initially="DEFERRED"),
     )
diff --git a/backend/app/modules/model_usage/api.py b/backend/app/modules/model_usage/api.py
index ec55b85a9..63516fdc2 100644
--- a/backend/app/modules/model_usage/api.py
+++ b/backend/app/modules/model_usage/api.py
@@ -1095,8 +1095,8 @@ async def inspect_effect(self, facts: ModelUsageInspectionFacts) -> ModelUsageEf
 class ModelCallCurrentExecutionPort(Protocol):
     """Require one current authorized checker execution without granting model effects."""
 
-    async def require_current(self, facts: ModelCallExecutionFacts, slot: ModelPaidSlotKey) -> None:
-        """Require current TASK and checker lease custody before attaching a paid slot."""
+    async def require_current(self, facts: ModelCallExecutionFacts, slot: ModelPaidSlotKey) -> datetime:
+        """Require current custody and return its database-timed live grant limit."""
         ...
 
     async def require_recovery_current(
diff --git a/backend/app/modules/model_usage/grants.py b/backend/app/modules/model_usage/grants.py
index 7fa3ee13b..9f5793596 100644
--- a/backend/app/modules/model_usage/grants.py
+++ b/backend/app/modules/model_usage/grants.py
@@ -81,7 +81,9 @@ async def issue(
         }
         if evidence.facts_digest != model_action_digest("grant", facts):
             raise ModelCallUnavailable("model_grant_authority_unavailable")
-        await self._current.require_current(execution, slot)
+        live_until = await self._current.require_current(execution, slot)
+        if live_until is None or live_until < execution.worker_lease_expires_at:
+            raise ModelCallUnavailable("model_grant_unavailable")
         self._session.add(
             CheckerModelInvocationGrant(
                 id=str(new_record_id()),
@@ -92,7 +94,7 @@ async def issue(
                 execution_facts=execution.model_dump(mode="json"),
                 paid_slot=slot.model_dump(mode="json"),
                 external_request_digest=external_request_digest,
-                expires_at=execution.worker_lease_expires_at,
+                expires_at=live_until,
                 authorization_evidence_id=str(evidence.evidence_id),
             )
         )
@@ -115,13 +117,9 @@ async def resolve(self, token: str, request_digest: str) -> ModelInvocationGrant
         execution = ModelCallExecutionFacts.model_validate_json(json.dumps(row.execution_facts))
         slot = ModelPaidSlotKey.model_validate_json(json.dumps(row.paid_slot))
         if (
-            str(execution.project_id),
-            str(execution.checker_run_id),
-            execution.worker_lease_expires_at,
-        ) != (
-            row.project_id,
-            row.checker_run_id,
-            row.expires_at,
+            str(execution.project_id) != row.project_id
+            or str(execution.checker_run_id) != row.checker_run_id
+            or execution.worker_lease_expires_at > row.expires_at
         ):
             raise ModelCallUnavailable("model_grant_unavailable")
         return ModelInvocationGrantFacts(
diff --git a/backend/app/modules/outbox/api.py b/backend/app/modules/outbox/api.py
index 43ef5fd79..e571e5fe8 100644
--- a/backend/app/modules/outbox/api.py
+++ b/backend/app/modules/outbox/api.py
@@ -17,6 +17,10 @@ class DeliveryUnavailable(Exception):
     """Concealed invalid, stale, denied or unavailable delivery operation."""
 
 
+BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS = 3600
+BACKGROUND_LIVE_WINDOW_SECONDS = 10_800
+
+
 class DeliveryPersistenceError(Exception):
     """Sanitized database observation or delivery failure."""
 
@@ -147,7 +151,8 @@ class DeliveryOptions(DeliveryValue):
     """Explicit bounded composition options; no environment or plugin framework."""
 
     lease_seconds: int = Field(default=300, ge=1, le=3600)
-    handler_timeout_seconds: int = Field(default=240, ge=1, le=3600)
+    handler_timeout_seconds: int | None = Field(default=240, ge=1, le=3600)
+    background_heartbeat: bool = False
     max_attempts: int = Field(default=5, ge=1, le=100)
     retry_base_seconds: int = Field(default=5, ge=1, le=3600)
     retry_cap_seconds: int = Field(default=300, ge=1, le=86400)
@@ -160,7 +165,11 @@ def retry_delay_seconds(self, attempt: int) -> int:
     def ordered_limits(self) -> Self:
         """Leave a lease margin and bound retry scheduling."""
         if (
-            self.handler_timeout_seconds >= self.lease_seconds
+            (self.background_heartbeat and self.handler_timeout_seconds is not None)
+            or (not self.background_heartbeat and (
+                self.handler_timeout_seconds is None
+                or self.handler_timeout_seconds >= self.lease_seconds
+            ))
             or self.retry_cap_seconds < self.retry_base_seconds
         ):
             raise ValueError("outbox delivery limits are inconsistent")
diff --git a/backend/app/modules/outbox/delivery.py b/backend/app/modules/outbox/delivery.py
index 15ce5ba63..7c44a1a62 100644
--- a/backend/app/modules/outbox/delivery.py
+++ b/backend/app/modules/outbox/delivery.py
@@ -25,6 +25,8 @@
     OutboxDispatchPhase,
 )
 from app.modules.outbox.api import (
+    BACKGROUND_LIVE_WINDOW_SECONDS,
+    BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS,
     CommittedInvocationObservation,
     DeliveryOptions,
     DeliveryCandidatePage,
@@ -64,10 +66,12 @@ def _checked_claim(claim: OutboxClaim) -> OutboxClaim:
 
 
 def _facts(
-    claim: OutboxClaim, phase: OutboxDispatchPhase, digest: str | None = None
+    claim: OutboxClaim, phase: OutboxDispatchPhase, digest: str | None = None,
+    *, live_until: datetime | None = None,
 ) -> OutboxDispatchFacts:
     """Bind every lease scalar and, for finalization, the complete outcome."""
-    return OutboxDispatchFacts(**claim.model_dump(), phase=phase, outcome_digest=digest)
+    return OutboxDispatchFacts(**claim.model_dump(), phase=phase, outcome_digest=digest,
+                               live_until=live_until)
 
 
 def _allow(decision: AuthorizationDecision) -> str:
@@ -97,11 +101,12 @@ def _outcome(
     now: datetime,
     options: DeliveryOptions,
     retry_unknown: bool = False,
+    *, live_until: datetime | None = None,
 ) -> dict:
     """Map closed disposition to database-timed outcome with bounded backoff."""
     if type(cause) is not FinalizationCause:
         raise DeliveryUnavailable("outbox_delivery_unavailable")
-    expired = now >= claim.claim_expires_at
+    expired = now >= (live_until or claim.claim_expires_at)
     if (
         invoked_at is None
         and (cause is not FinalizationCause.EXPIRED or not expired)
@@ -271,11 +276,13 @@ async def claim(self, event_id: UUID, project_id: UUID, owner: str) -> OutboxCla
                     claim.claim_expires_at,
                     claim.claimed_at,
                 )
+                event.claim_live_until = claim.claim_expires_at
                 event.next_attempt_at = None
                 session.add(
                     OutboxDeliveryAttempt(
                         **{**claim.model_dump(), "project_id": str(project_id)},
                         stage="claimed", claim_decision_event_id=decision_id,
+                        claim_live_until=claim.claim_expires_at,
                     )
                 )
                 await session.flush()
@@ -342,19 +349,48 @@ async def invoke(self, claim: OutboxClaim) -> DeliveryReceipt | None:
         annotate_current_span(outbox_correlation_id=envelope.correlation_id)
         handler = self._registry.get(envelope.event_type, envelope.event_version)
         options = self._options_for(envelope.event_type, envelope.event_version)
+        if options.background_heartbeat:
+            await asyncio.wait_for(
+                self._renew_invocation(claim),
+                timeout=BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS,
+            )
         cause = FinalizationCause.UNKNOWN
         task = None
         try:
             loop = asyncio.get_running_loop()
-            deadline = loop.time() + options.handler_timeout_seconds
+            deadline = (loop.time() + options.handler_timeout_seconds
+                        if options.handler_timeout_seconds is not None else None)
             task = asyncio.create_task(handler(envelope))
             self._running_handlers.add(task)
             task.add_done_callback(self._handler_done)
-            done, _ = await asyncio.wait((task,), timeout=options.handler_timeout_seconds)
-            if done and loop.time() < deadline and not task.cancelled():
-                result = task.result()
-                if type(result) is HandlerOutcome:
-                    cause = FinalizationCause(result.value)
+            while True:
+                done, _ = await asyncio.wait(
+                    (task,), timeout=BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS if options.background_heartbeat
+                    else options.handler_timeout_seconds,
+                )
+                if done:
+                    if (deadline is None or loop.time() < deadline) and not task.cancelled():
+                        result = task.result()
+                        if type(result) is HandlerOutcome:
+                            cause = FinalizationCause(result.value)
+                    break
+                if not options.background_heartbeat:
+                    break
+                renewal = asyncio.create_task(self._renew_invocation(claim))
+                try:
+                    renewed, _ = await asyncio.wait(
+                        (renewal,), timeout=BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS,
+                    )
+                    if not renewed:
+                        # Cancel the handler before waiting for DB rollback/close.
+                        task.cancel()
+                        raise DeliveryUnavailable("outbox_delivery_unavailable")
+                    await renewal
+                finally:
+                    if not renewal.done():
+                        task.cancel()
+                        renewal.cancel()
+                        await asyncio.gather(renewal, return_exceptions=True)
         except Exception:
             # Do not retain or log provider payloads. Cancellation deliberately leaves
             # committed invoked custody for expiration recovery.
@@ -364,6 +400,38 @@ async def invoke(self, claim: OutboxClaim) -> DeliveryReceipt | None:
                 task.cancel()
         return await self.finalize(claim, cause)
 
+    async def _renew_invocation(self, claim: OutboxClaim) -> None:
+        """Inspect a live invoked claim and renew only its matching attempt."""
+        async with self._sessions() as session:
+            live_until = await database_time(session) + timedelta(seconds=BACKGROUND_LIVE_WINDOW_SECONDS)
+        facts = _facts(claim, OutboxDispatchPhase.RENEW, live_until=live_until)
+        async with self._sessions() as session, session.begin():
+            async with self._authority(session, facts=facts,
+                                       request_id=uuid4(), correlation_id=uuid4()) as prepared:
+                repo = DeliveryRepository(session)
+                event = await repo.event(claim.event_id, claim.project_id, lock=True)
+                attempt = await repo.attempt(claim, lock=True)
+                now = await database_time(session)
+                if (
+                    event is None or attempt is None or not matches_event(event, claim)
+                    or claim_from_attempt(attempt) != claim or attempt.stage != "invoked"
+                    or event.claim_live_until is None or attempt.claim_live_until != event.claim_live_until
+                    or event.claim_live_until <= now or live_until <= event.claim_live_until
+                    or live_until > now + timedelta(seconds=BACKGROUND_LIVE_WINDOW_SECONDS)
+                    or not self._options_for(event.event_type, event.event_version).background_heartbeat
+                ):
+                    raise DeliveryUnavailable("outbox_delivery_unavailable")
+                decision_id = _allow(await prepared.consume(facts))
+                if await database_time(session) >= event.claim_live_until:
+                    raise DeliveryUnavailable("outbox_delivery_unavailable")
+                event.claim_live_until = live_until
+                # The attempt guard verifies the already-renewed event under
+                # the same transaction and row lock.
+                await session.flush()
+                attempt.claim_live_until = live_until
+                attempt.renew_decision_event_id = decision_id
+                await session.flush()
+
     async def finalize(self, claim: OutboxClaim, cause: FinalizationCause) -> DeliveryReceipt:
         """Authorize the exact outcome; response loss replays original delivery facts."""
         claim = _checked_claim(claim)
@@ -380,7 +448,8 @@ async def finalize(self, claim: OutboxClaim, cause: FinalizationCause) -> Delive
                     json.loads(attempt.outcome_json)["receipt_completed_at"]
                 )
             retry_unknown = self._registry.can_retry_unknown(event.event_type, event.event_version)
-            value = _outcome(claim, attempt.invoked_at, cause, now, options, retry_unknown)
+            value = _outcome(claim, attempt.invoked_at, cause, now, options, retry_unknown,
+                             live_until=attempt.claim_live_until)
             proposed = DeliveryReceipt(
                 claim=claim, outcome_json=_encode(value), outcome_digest=canonical_json_hash(value)
             )
@@ -395,6 +464,7 @@ async def finalize(self, claim: OutboxClaim, cause: FinalizationCause) -> Delive
                 datetime.fromisoformat(stored["receipt_completed_at"]),
                 options,
                 retry_unknown,
+                live_until=attempt.claim_live_until,
             )
             if _encode(expected) != completed.receipt.outcome_json:
                 raise DeliveryUnavailable("outbox_delivery_unavailable") from None
@@ -439,12 +509,14 @@ async def _finalize(
                 expected = _outcome(
                     claim, attempt.invoked_at, cause, completed, options,
                     self._registry.can_retry_unknown(event.event_type, event.event_version),
+                    live_until=attempt.claim_live_until,
                 )
                 if (
                     completed > now
                     or _encode(expected) != receipt.outcome_json
                     or canonical_json_hash(expected) != receipt.outcome_digest
-                    or (completed < claim.claim_expires_at <= now)
+                    or event.claim_live_until != attempt.claim_live_until
+                    or (completed < attempt.claim_live_until <= now)
                 ):
                     raise DeliveryUnavailable("outbox_delivery_unavailable")
                 decision_id = _allow(
@@ -452,7 +524,7 @@ async def _finalize(
                         _facts(claim, OutboxDispatchPhase.FINALIZE, receipt.outcome_digest)
                     )
                 )
-                if completed < claim.claim_expires_at <= await database_time(session):
+                if completed < attempt.claim_live_until <= await database_time(session):
                     raise DeliveryUnavailable("outbox_delivery_unavailable")
                 attempt.finalize_decision_event_id = decision_id
                 attempt.stage, attempt.outcome_json, attempt.outcome_digest = (
@@ -473,6 +545,7 @@ async def _finalize(
                     datetime.fromisoformat(value["finalized_at"]) if value["finalized_at"] else None
                 )
                 event.claim_owner = event.claimed_at = event.claim_expires_at = None
+                event.claim_live_until = None
                 await session.flush()
         return receipt
 
@@ -485,7 +558,7 @@ async def recover(self, event_id: UUID, project_id: UUID) -> DeliveryReceipt | N
                 event is None
                 or (event.event_type, event.event_version) in self._excluded_events
                 or event.delivery_state != "claimed"
-                or event.claim_expires_at > now
+                or event.claim_live_until > now
             ):
                 return None
             claim = OutboxClaim(
diff --git a/backend/app/modules/outbox/delivery_repository.py b/backend/app/modules/outbox/delivery_repository.py
index 846d0b2d3..441884fd0 100644
--- a/backend/app/modules/outbox/delivery_repository.py
+++ b/backend/app/modules/outbox/delivery_repository.py
@@ -126,7 +126,7 @@ async def candidates(
         query = select(e.event_id, e.project_id, e.event_type).where(or_(
             and_(e.delivery_state.in_(("pending", "retryable")), e.next_attempt_at <= now,
                  tuple_(e.event_type, e.event_version).in_(sorted(registered))),
-            and_(e.delivery_state == "claimed", e.claim_expires_at <= now),
+            and_(e.delivery_state == "claimed", e.claim_live_until <= now),
         ))
         if excluded:
             query = query.where(tuple_(e.event_type, e.event_version).not_in(sorted(excluded)))
@@ -416,7 +416,7 @@ async def observe(self, envelope: OutboxEventEnvelope) -> CommittedInvocationObs
                 a.claim_owner == e.claim_owner,
                 a.claimed_at == e.claimed_at,
                 a.claim_expires_at == e.claim_expires_at,
-                e.claim_expires_at > func.statement_timestamp(),
+                e.claim_live_until > func.statement_timestamp(),
             )
         )
         observed = (await self.session.execute(query)).scalar_one_or_none()
diff --git a/backend/app/modules/outbox/models.py b/backend/app/modules/outbox/models.py
index e9e3471d6..c1cb2ca8d 100644
--- a/backend/app/modules/outbox/models.py
+++ b/backend/app/modules/outbox/models.py
@@ -83,6 +83,12 @@ class OutboxEvent(Base):
             "last_error_code is null or last_error_code ~ '^[A-Z][A-Z0-9_]{0,79}$'",
             name="error_code",
         ),
+        CheckConstraint(
+            "(delivery_state='claimed' and claim_live_until is not null "
+            "and claim_live_until>=claim_expires_at) or "
+            "(delivery_state<>'claimed' and claim_live_until is null)",
+            name="claim_live_shape",
+        ),
         CheckConstraint(
             "(next_attempt_at is null or next_attempt_at >= occurred_at) and "
             "(claimed_at is null or claimed_at >= occurred_at) and "
@@ -134,7 +140,7 @@ class OutboxEvent(Base):
         ),
         Index(
             "ix_outbox_events_expired_claims",
-            "claim_expires_at",
+            "claim_live_until",
             "event_id",
             postgresql_where=text("delivery_state = 'claimed'"),
         ),
@@ -194,6 +200,7 @@ class OutboxEvent(Base):
     )
     claimed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
     claim_expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+    claim_live_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
     last_attempt_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
     last_error_code: Mapped[str | None] = mapped_column(String(80))
     finalized_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
@@ -220,6 +227,11 @@ class OutboxDeliveryAttempt(Base):
             "claim_expires_at > claimed_at and claim_expires_at <= claimed_at + interval '1 hour'",
             name="lease",
         ),
+        CheckConstraint(
+            "(claim_live_until=claim_expires_at and renew_decision_event_id is null) or "
+            "(claim_live_until>claim_expires_at and renew_decision_event_id is not null)",
+            name="renewed_lease",
+        ),
         CheckConstraint(
             "(stage = 'claimed' and invoked_at is null and outcome_json is null "
             "and outcome_digest is null) or "
@@ -231,7 +243,7 @@ class OutboxDeliveryAttempt(Base):
         ),
         CheckConstraint(
             "outcome_json is null or coalesce(outbox_delivery_outcome_valid("
-            "outcome_json, outcome_digest, claimed_at, claim_expires_at, invoked_at), false)",
+            "outcome_json, outcome_digest, claimed_at, claim_live_until, invoked_at), false)",
             name="outcome",
         ),
     )
@@ -239,6 +251,7 @@ class OutboxDeliveryAttempt(Base):
     claim_decision_event_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey("audit_events.id"), unique=True, nullable=False)
     invoke_decision_event_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False), ForeignKey("audit_events.id"), unique=True)
     finalize_decision_event_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False), ForeignKey("audit_events.id"), unique=True)
+    renew_decision_event_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False), ForeignKey("audit_events.id"))
 
     event_id: Mapped[UUID] = mapped_column(ForeignKey("outbox_events.event_id"), primary_key=True)
     claim_generation: Mapped[int] = mapped_column(BigInteger, primary_key=True)
@@ -247,6 +260,7 @@ class OutboxDeliveryAttempt(Base):
     claim_owner: Mapped[str] = mapped_column(String(120), nullable=False)
     claimed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
     claim_expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
+    claim_live_until: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
     stage: Mapped[str] = mapped_column(String(16), nullable=False)
     invoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
     outcome_json: Mapped[str | None] = mapped_column(String(2048))
diff --git a/backend/tests/authorization/test_outbox_dispatch_contract.py b/backend/tests/authorization/test_outbox_dispatch_contract.py
index 75339cf52..f03e2a72b 100644
--- a/backend/tests/authorization/test_outbox_dispatch_contract.py
+++ b/backend/tests/authorization/test_outbox_dispatch_contract.py
@@ -36,6 +36,8 @@ def facts(phase=OutboxDispatchPhase.CLAIM):
         payload_digest='sha256:' + 'a' * 64, claim_generation=1, claim_owner='worker-1',
         claimed_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
         claim_expires_at=datetime(2026, 1, 1, 0, 5, tzinfo=timezone.utc),
+        live_until=(datetime(2026, 1, 1, 2, 0, tzinfo=timezone.utc)
+                    if phase is OutboxDispatchPhase.RENEW else None),
         outcome_digest=('sha256:' + 'b' * 64 if phase is OutboxDispatchPhase.FINALIZE else None),
     )
 
@@ -85,6 +87,21 @@ def test_dispatch_facts_validate_all_phases():
         replace(facts(), claimed_at=datetime.min.replace(tzinfo=timezone(timedelta(hours=1))))
 
 
+def test_renewal_binds_a_later_live_time_without_changing_original_claim():
+    original = facts(OutboxDispatchPhase.INVOKE)
+    renewed = facts(OutboxDispatchPhase.RENEW)
+    assert renewed.claimed_at == original.claimed_at
+    assert renewed.claim_expires_at == original.claim_expires_at
+    assert outbox_dispatch_resource_digest(renewed) != outbox_dispatch_resource_digest(
+        replace(renewed, live_until=renewed.live_until + timedelta(seconds=1))
+    )
+    for invalid in (None, original.claim_expires_at, original.claimed_at):
+        with pytest.raises(ValueError):
+            replace(renewed, live_until=invalid)
+    with pytest.raises(ValueError, match="renewal time"):
+        replace(original, live_until=renewed.live_until)
+
+
 @pytest.mark.parametrize("field", ["claimed_at", "claim_expires_at"])
 @pytest.mark.parametrize("failure", ["raises", "invalid_offset"])
 def test_dispatch_lease_sanitizes_timezone_failures(field, failure):
diff --git a/backend/tests/checkers/execution/test_execution.py b/backend/tests/checkers/execution/test_execution.py
index 2ce6b4896..90009a601 100644
--- a/backend/tests/checkers/execution/test_execution.py
+++ b/backend/tests/checkers/execution/test_execution.py
@@ -1,7 +1,8 @@
 """Execution through real verified input, immutable results and shared outbox."""
 
 import pytest
-from sqlalchemy import select, func
+from sqlalchemy import select, func, text
+from sqlalchemy.exc import DBAPIError
 
 from app.modules.checkers.api.execution import CheckerExecutionUnavailable, COMPLETION_EVENT
 from app.adapters.checkers import evaluation_coordinator
@@ -13,6 +14,102 @@
 from app.modules.actors.api import ServiceIdentity
 
 
+async def test_cancel_stops_material_work_before_inspection_rollback(monkeypatch):
+    """A blocked status rollback must not leave provider work active."""
+    import asyncio
+    import app.modules.checkers.execution as execution
+
+    inspection_entered = asyncio.Event()
+    release_inspection = asyncio.Event()
+    work_cancelled = asyncio.Event()
+
+    class Materialization:
+        async def materialize(self, _facts, _consumer):
+            try:
+                await asyncio.Event().wait()
+            except asyncio.CancelledError:
+                work_cancelled.set()
+                raise
+
+    executor = execution.PostSubmissionExecutor(
+        sessions=None, execute_authority=None, finalize_authority=None,
+        materialization=Materialization(), outbox=None, review_modes=None,
+    )
+    monkeypatch.setattr(execution, "ExecuteFacts", lambda **_facts: object())
+    monkeypatch.setattr(executor, "_consumer", lambda _request, _lease: object())
+    monkeypatch.setattr(execution, "BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS", 0.01)
+    renewals = 0
+
+    async def renewal(_request, _lease):
+        nonlocal renewals
+        renewals += 1
+        if renewals > 1:
+            inspection_entered.set()
+            try:
+                await asyncio.Event().wait()
+            except asyncio.CancelledError:
+                await release_inspection.wait()
+                raise
+
+    monkeypatch.setattr(executor, "_renew_running_lease", renewal)
+    running = asyncio.create_task(executor._materialize_while_owned(None, None))
+    await asyncio.wait_for(inspection_entered.wait(), 1)
+    running.cancel()
+    try:
+        await asyncio.wait_for(work_cancelled.wait(), 1)
+        assert not running.done()
+    finally:
+        release_inspection.set()
+    with pytest.raises(asyncio.CancelledError):
+        await asyncio.wait_for(running, 1)
+
+
+async def test_inspection_timeout_preserves_unknown_after_native_cancellation(monkeypatch):
+    import asyncio
+    import app.modules.checkers.execution as execution
+    from app.interfaces.external_checker_execution import ExternalCheckerExecutionOutcomeUnknown
+
+    cancelled = asyncio.Event()
+    release_rollback = asyncio.Event()
+
+    class Materialization:
+        async def materialize(self, _facts, _consumer):
+            try:
+                await asyncio.Event().wait()
+            except asyncio.CancelledError:
+                cancelled.set()
+                raise ExternalCheckerExecutionOutcomeUnknown() from None
+
+    executor = execution.PostSubmissionExecutor(
+        sessions=None, execute_authority=None, finalize_authority=None,
+        materialization=Materialization(), outbox=None, review_modes=None,
+    )
+    monkeypatch.setattr(execution, "ExecuteFacts", lambda **_facts: object())
+    monkeypatch.setattr(executor, "_consumer", lambda _request, _lease: object())
+    monkeypatch.setattr(execution, "BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS", 0.01)
+    calls = 0
+
+    async def renewal(_request, _lease):
+        nonlocal calls
+        calls += 1
+        if calls > 1:
+            try:
+                await asyncio.Event().wait()
+            except asyncio.CancelledError:
+                await release_rollback.wait()
+                raise
+
+    monkeypatch.setattr(executor, "_renew_running_lease", renewal)
+    running = asyncio.create_task(executor._materialize_while_owned(None, None))
+    try:
+        await asyncio.wait_for(cancelled.wait(), 1)
+        assert not running.done()
+    finally:
+        release_rollback.set()
+    with pytest.raises(ExternalCheckerExecutionOutcomeUnknown):
+        await asyncio.wait_for(running, 1)
+
+
 @pytest.fixture
 def autoflush_clock(monkeypatch):
     """Exercise a real ORM query flush at the database-clock boundary."""
@@ -50,17 +147,36 @@ async def test_background_materialization_can_exceed_nominal_post_estimate(
         materialize = h.service.materialize
 
         async def slower_materialization(*args, **kwargs):
-            await asyncio.sleep(1.1)
+            await asyncio.sleep(2.2)
             return await materialize(*args, **kwargs)
 
-        monkeypatch.setattr(execution, "selected_post_submit_execution_budget_ms", lambda _policy: 1000)
+        monkeypatch.setattr(execution, "SELECTED_POST_INITIAL_WORKER_WINDOW_MS", 100)
+        monkeypatch.setattr(execution, "SELECTED_POST_FINALIZATION_MARGIN_MS", 1_000)
         monkeypatch.setattr(h.service, "materialize", slower_materialization)
         result = await live_executor(h).evaluate_post_submission(h.request)
         assert result.outcome == "completed"
         async with h.factory() as session:
             run = await session.get(CheckerRun, str(result.attempt_id))
             assert run.status == "completed" and run.failure_code is None
-            assert run.worker_lease_expires_at > run.completed_at
+            assert run.worker_lease_expires_at < run.completed_at
+            assert run.worker_lease_live_until > run.completed_at
+
+
+async def test_running_checker_cannot_null_its_renewable_live_lease(tmp_path, isolated_database_env):
+    async with material_fixture(tmp_path, isolated_database_env) as h:
+        await reserve(h)
+        executor = live_executor(h)
+        lease, replay = await executor._claim(h.request)
+        assert replay is None
+        with pytest.raises(DBAPIError, match="checker renewal custody is invalid"):
+            async with h.factory() as session, session.begin():
+                await session.execute(text("""
+                    UPDATE public.checker_runs SET worker_lease_live_until=NULL WHERE id=:id
+                """), {"id": str(lease.reservation.attempt_id)})
+        async with h.factory() as session:
+            run = await session.get(CheckerRun, str(lease.reservation.attempt_id))
+            assert run.status == "running"
+            assert run.worker_lease_live_until == run.worker_lease_expires_at
 
 
 @pytest.mark.parametrize("provider", ["local", "minio"])
diff --git a/backend/tests/checkers/external/test_policy.py b/backend/tests/checkers/external/test_policy.py
index 47ed62b41..f328e9be6 100644
--- a/backend/tests/checkers/external/test_policy.py
+++ b/backend/tests/checkers/external/test_policy.py
@@ -311,7 +311,7 @@ async def test_model_profile_configuration_requires_exact_project_scope():
 
 
 @pytest.mark.asyncio
-async def test_retained_pre_and_new_post_budgets_reject_unrunnable_images():
+async def test_retained_pre_budget_and_long_post_policy():
     from app.modules.checkers.api.external_policy import validate_stored_external_pre_policy
 
     pre_entry = _entry("acme.pre", "pre_submit", deadline_ms=3_600_000)
@@ -326,11 +326,12 @@ async def test_retained_pre_and_new_post_budgets_reject_unrunnable_images():
     with pytest.raises(ValueError, match="ART custody deadline"):
         validate_stored_external_pre_policy(body | {"policy_sha256": canonical_json_hash(body)})
     post = _entry("acme.post", "post_submit", deadline_ms=3_600_000)
-    with pytest.raises(ValueError, match="durable worker deadline"):
-        await compile_external_checker_policies(
-            _request(pre=(_attachment(pre_entry, "a"),), post=(_attachment(post, "p"),)),
-            _Registry((pre_entry, post)),
-        )
+    _, locked_post = await compile_external_checker_policies(
+        _request(pre=(_attachment(pre_entry, "a"),), post=(_attachment(post, "p"),)),
+        _Registry((pre_entry, post)),
+    )
+    assert locked_post.entries[0].registry.resources.deadline_ms == 3_600_000
+    assert selected_post_submit_execution_budget_ms(locked_post) > 3_400_000
 
 
 @pytest.mark.asyncio
diff --git a/backend/tests/checkers_model_calls/model_usage_boundary_support.py b/backend/tests/checkers_model_calls/model_usage_boundary_support.py
index 897345f6e..3d07bfd22 100644
--- a/backend/tests/checkers_model_calls/model_usage_boundary_support.py
+++ b/backend/tests/checkers_model_calls/model_usage_boundary_support.py
@@ -192,6 +192,7 @@ async def require_setup_response(self, effect_id, evidence):
     async def require_current(self, facts, slot):
         self.current_checks += 1
         self.events.append("current")
+        return facts.worker_lease_expires_at
 
     async def require_recovery_current(self, slot, parent_attempt_id):
         self.current_checks += 1
@@ -582,7 +583,7 @@ async def require_setup_current(self, slot):
         )
 
     async def require_current(self, facts, slot):
-        await self._ports.require_current(facts, slot)
+        return await self._ports.require_current(facts, slot)
 
     async def require_recovery_current(self, slot, parent_attempt_id):
         await self._ports.require_recovery_current(slot, parent_attempt_id)
diff --git a/backend/tests/checkers_model_calls/test_model_invocation_grants_postgresql.py b/backend/tests/checkers_model_calls/test_model_invocation_grants_postgresql.py
index 2e24a3cfb..eba0ddc6f 100644
--- a/backend/tests/checkers_model_calls/test_model_invocation_grants_postgresql.py
+++ b/backend/tests/checkers_model_calls/test_model_invocation_grants_postgresql.py
@@ -148,10 +148,10 @@ async def authorize_grant(
 
     async def require_current(
         self,
-        _: ModelCallExecutionFacts,
+        facts: ModelCallExecutionFacts,
         __: ModelPaidSlotKey,
-    ) -> None:
-        return None
+    ):
+        return facts.worker_lease_expires_at
 
 
 def _isolated(statement: str, schema: str) -> str:
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 3bf5b25f7..ed6aadd1e 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "efaf65a0b5cccff693ec8700a46f43fbc036206189af8d2f72cb1b521840fa99"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "9c88847e28178b92dcc8262b5a9de600123d221e382f4b50ba4c606cb177288c"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",
diff --git a/backend/tests/outbox/test_authority_custody_postgresql.py b/backend/tests/outbox/test_authority_custody_postgresql.py
index 1ceebf68a..910196810 100644
--- a/backend/tests/outbox/test_authority_custody_postgresql.py
+++ b/backend/tests/outbox/test_authority_custody_postgresql.py
@@ -110,7 +110,7 @@ async def test_new_phase_reference_requires_current_authority(delivery_harness):
         assert attempt.stage == "claimed" and attempt.invoke_decision_event_id is None
 
 
-@pytest.mark.parametrize("phase", list(OutboxDispatchPhase))
+@pytest.mark.parametrize("phase", [OutboxDispatchPhase.CLAIM, OutboxDispatchPhase.INVOKE, OutboxDispatchPhase.FINALIZE])
 @pytest.mark.parametrize("microseconds", [0, 123400])
 async def test_sql_phase_digest_matches_exact_public_timestamp_format(
     delivery_harness, phase, microseconds
@@ -147,7 +147,7 @@ async def test_sql_phase_digest_matches_exact_public_timestamp_format(
         assert digest == outbox_dispatch_resource_digest(facts)
 
 
-@pytest.mark.parametrize("phase", list(OutboxDispatchPhase))
+@pytest.mark.parametrize("phase", [OutboxDispatchPhase.CLAIM, OutboxDispatchPhase.INVOKE, OutboxDispatchPhase.FINALIZE])
 async def test_missing_phase_decision_rolls_back_owner_write_and_audit(delivery_harness, phase):
     from sqlalchemy import event
     from sqlalchemy.orm import Session
@@ -194,7 +194,10 @@ def omit(session, context, instances):
                 select(AuditEvent).where(AuditEvent.action_id == "outbox.dispatch")
             )
         ).all()
-        assert len(audits) == list(OutboxDispatchPhase).index(phase)
+        assert len(audits) == (
+            [OutboxDispatchPhase.CLAIM, OutboxDispatchPhase.INVOKE, OutboxDispatchPhase.FINALIZE]
+            .index(phase)
+        )
         assert (await session.get(OutboxEvent, pending.event_id)).delivery_state == (
             "pending" if claim is None else "claimed"
         )
diff --git a/backend/tests/outbox/test_authority_postgresql.py b/backend/tests/outbox/test_authority_postgresql.py
index 1b410f5a1..12a641b16 100644
--- a/backend/tests/outbox/test_authority_postgresql.py
+++ b/backend/tests/outbox/test_authority_postgresql.py
@@ -19,11 +19,53 @@
     outbox_dispatch_resource_digest,
     PreparedAuthorizationInvalid,
 )
-from app.modules.outbox.api import DeliveryUnavailable, FinalizationCause
+from app.modules.outbox.api import DeliveryOptions, DeliveryUnavailable, FinalizationCause
 from app.modules.outbox.delivery_repository import DeliveryRepository
 from app.modules.outbox.models import OutboxDeliveryAttempt
+from app.modules.outbox.registry import HandlerRegistry
+from app.modules.checkers.api.execution import REQUEST_EVENT
 from app.modules.tasks.models import AuditEvent
-from tests.outbox.conftest import Harness
+from tests.outbox.conftest import Harness, phase_decision
+
+
+async def test_second_renewal_requires_live_dispatcher_despite_preexisting_audit(delivery_harness):
+    """A new decision cannot reuse a retired service link at the SQL boundary."""
+    import asyncio
+    h = delivery_harness
+    h.options = DeliveryOptions(lease_seconds=30, handler_timeout_seconds=None,
+                                background_heartbeat=True)
+    h.delivery = h.build(HandlerRegistry([(REQUEST_EVENT, 1, h.handle)]))
+    claim = await h.claim(event_type=REQUEST_EVENT, aggregate_type="submission")
+    assert await h.delivery._begin_invocation(claim)
+    await h.delivery._renew_invocation(claim)
+    async with h.factory() as session:
+        first = await DeliveryRepository(session).attempt(claim)
+        first_live_until = first.claim_live_until
+        first_decision = first.renew_decision_event_id
+    await asyncio.sleep(1.1)
+    later = first_live_until + timedelta(seconds=1)
+    facts = OutboxDispatchFacts(**claim.model_dump(), phase=OutboxDispatchPhase.RENEW,
+                                live_until=later)
+    async with h.factory() as session, session.begin():
+        second_decision = await phase_decision(session, facts)
+    async with h.factory() as session, session.begin():
+        await session.execute(text(
+            "UPDATE actor_identity_links SET status='revoked',revoked_by='test',"
+            "revoked_at=clock_timestamp(),revoked_reason='test' WHERE id=:id"
+        ), {"id": str(h.link_id)})
+    with pytest.raises(DBAPIError, match="outbox current dispatcher authority missing"):
+        async with h.factory() as session, session.begin():
+            await session.execute(text(
+                "UPDATE outbox_events SET claim_live_until=:later WHERE event_id=:id"
+            ), {"later": later, "id": claim.event_id})
+            await session.execute(text(
+                "UPDATE outbox_delivery_attempts SET claim_live_until=:later,"
+                "renew_decision_event_id=:decision WHERE event_id=:id"
+            ), {"later": later, "decision": second_decision, "id": claim.event_id})
+    async with h.factory() as session:
+        stored = await DeliveryRepository(session).attempt(claim)
+        assert stored.claim_live_until == first_live_until
+        assert stored.renew_decision_event_id == first_decision
 
 
 def phase_facts(claim, phase, outcome=None):
@@ -42,7 +84,10 @@ async def test_real_dispatcher_records_exact_phase_decisions(delivery_harness):
             attempt.finalize_decision_event_id,
         ]
         assert len(set(ids)) == 3 and all(ids)
-        for phase, decision_id in zip(OutboxDispatchPhase, ids, strict=True):
+        for phase, decision_id in zip(
+            (OutboxDispatchPhase.CLAIM, OutboxDispatchPhase.INVOKE, OutboxDispatchPhase.FINALIZE),
+            ids, strict=True,
+        ):
             event = await session.get(AuditEvent, decision_id)
             expected = phase_facts(
                 claim,
diff --git a/backend/tests/outbox/test_delivery_postgresql.py b/backend/tests/outbox/test_delivery_postgresql.py
index 0affeac03..780aa3eb9 100644
--- a/backend/tests/outbox/test_delivery_postgresql.py
+++ b/backend/tests/outbox/test_delivery_postgresql.py
@@ -10,12 +10,54 @@
 
 from app.adapters.auth import outbox_dispatch_authorization
 from app.modules.authorization.api.outbox_dispatch import OutboxDispatchFacts, OutboxDispatchPhase
-from app.modules.outbox.api import DeliveryUnavailable, FinalizationCause, HandlerOutcome
+from app.modules.outbox.api import DeliveryOptions, DeliveryUnavailable, FinalizationCause, HandlerOutcome
 from app.modules.outbox.api import OutboxEventEnvelope
 from app.modules.outbox import delivery as delivery_module
 from app.modules.outbox.delivery_repository import DeliveryRepository, database_time
 from app.modules.outbox.models import OutboxDeliveryAttempt, OutboxEvent
 from app.modules.outbox.registry import HandlerRegistry
+from app.modules.checkers.api.execution import REQUEST_EVENT
+
+
+async def test_background_invocation_survives_original_claim_expiry(delivery_harness, monkeypatch):
+    """A live inspected handler retains one claim without a whole-handler cutoff."""
+    h = delivery_harness
+    h.options = DeliveryOptions(
+        lease_seconds=1, handler_timeout_seconds=None, background_heartbeat=True,
+        retry_base_seconds=1,
+    )
+    h.delivery = h.build(HandlerRegistry([(REQUEST_EVENT, 1, h.handle)]))
+    monkeypatch.setattr(delivery_module, "BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS", 0.2)
+    entered, release = asyncio.Event(), asyncio.Event()
+
+    async def block(_envelope):
+        entered.set()
+        await release.wait()
+
+    h.handler_hook = block
+    claim = await h.claim(event_type=REQUEST_EVENT, aggregate_type="submission")
+    invoked = asyncio.create_task(h.delivery.invoke(claim))
+    try:
+        await asyncio.wait_for(entered.wait(), 10)
+        await asyncio.sleep(1.2)
+        async with h.factory() as session:
+            now = await database_time(session)
+            event = await session.get(OutboxEvent, claim.event_id)
+            attempt = await DeliveryRepository(session).attempt(claim)
+            assert claim.claim_expires_at < now < event.claim_live_until
+            assert attempt.claim_live_until == event.claim_live_until
+            assert attempt.renew_decision_event_id is not None
+            assert event.claim_generation == claim.claim_generation
+        assert await h.delivery.recover(claim.event_id, h.project) is None
+        assert await h.delivery.claim(claim.event_id, h.project, "competing-worker") is None
+    finally:
+        release.set()
+    receipt = await asyncio.wait_for(invoked, 10)
+    assert receipt is not None
+    assert len(h.handled) == 1
+    async with h.factory() as session:
+        event = await session.get(OutboxEvent, claim.event_id)
+        assert event.delivery_state == "acknowledged" and event.claim_live_until is None
 
 
 @pytest.mark.parametrize("hours", [-1, 168])
@@ -129,7 +171,7 @@ async def test_claim_validator_requires_committed_invocation(delivery_harness):
     assert await h.delivery.observe_invocation(envelope) is None
 
 
-@pytest.mark.parametrize("phase", list(OutboxDispatchPhase))
+@pytest.mark.parametrize("phase", [OutboxDispatchPhase.CLAIM, OutboxDispatchPhase.INVOKE, OutboxDispatchPhase.FINALIZE])
 @pytest.mark.parametrize("fault", ["phase", "facts"])
 async def test_each_phase_denies_mismatch_and_reused_authority(delivery_harness, phase, fault):
     h = delivery_harness
@@ -196,7 +238,9 @@ async def independent_lock(envelope):
     results = await asyncio.gather(h.delivery.invoke(claim), h.delivery.invoke(claim))
     assert sum(result is not None for result in results) == 1
     assert len(h.handled) == 1
-    assert [f.phase for f in h.consumed] == list(OutboxDispatchPhase)
+    assert [f.phase for f in h.consumed] == [
+        OutboxDispatchPhase.CLAIM, OutboxDispatchPhase.INVOKE, OutboxDispatchPhase.FINALIZE,
+    ]
 
 
 async def test_diagnostic_annotation_follows_committed_invocation_envelope(
@@ -261,7 +305,7 @@ async def observe_committed(_envelope):
     )
 
 
-@pytest.mark.parametrize("phase", list(OutboxDispatchPhase))
+@pytest.mark.parametrize("phase", [OutboxDispatchPhase.CLAIM, OutboxDispatchPhase.INVOKE, OutboxDispatchPhase.FINALIZE])
 async def test_authority_wait_cannot_commit_an_expired_live_phase(delivery_harness, phase):
     """A delay inside consume must roll back instead of committing stale live facts."""
     h = delivery_harness
diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py
index 853ae7142..effb50ac0 100644
--- a/backend/tests/test_alembic.py
+++ b/backend/tests/test_alembic.py
@@ -127,6 +127,115 @@ def test_current_installed_head_admits_noop_upgrade(isolated_database_env, migra
     assert asyncio.run(_database_snapshot(isolated_database_env)) == before
 
 
+@pytest.mark.parametrize(
+    ("archive", "predecessor", "expected_state"),
+    [
+        ("0031_routing_success_true_false", "0031_task_import_source", "claimed"),
+        ("0034_checker_retry_source", "0034_checker_replacement", "acknowledged"),
+    ],
+)
+def test_renewable_post_upgrade_preserves_retained_custody(
+    isolated_database_env, migration_lock, archive, predecessor, expected_state,
+):
+    """Upgrade populated 0095 rows with immutable and deferred guards active."""
+    from tests.historical_submission_fixtures import restore_archived_snapshot
+    from app.db import session as db_session
+
+    async def retained():
+        connection = await asyncpg.connect(isolated_database_env.replace("+asyncpg", ""))
+        try:
+            rows = {}
+            for table in (
+                "checker_runs", "outbox_events", "outbox_delivery_attempts", "audit_events",
+            ):
+                rows[table] = tuple(row["body"] for row in await connection.fetch(
+                    f"SELECT to_jsonb(r)::text body FROM public.{table} r ORDER BY body"
+                ))
+            return rows
+        finally:
+            await connection.close()
+
+    async def projected():
+        connection = await asyncpg.connect(isolated_database_env.replace("+asyncpg", ""))
+        try:
+            result = {}
+            removed = {
+                "checker_runs": "worker_lease_live_until",
+                "outbox_events": "claim_live_until",
+                "outbox_delivery_attempts": "claim_live_until,renew_decision_event_id",
+            }
+            for table in (
+                "checker_runs", "outbox_events", "outbox_delivery_attempts", "audit_events",
+            ):
+                projection = "to_jsonb(r)"
+                for column in removed.get(table, "").split(","):
+                    if column:
+                        projection += f"-'{column}'"
+                result[table] = tuple(row["body"] for row in await connection.fetch(
+                    f"SELECT ({projection})::text body FROM public.{table} r ORDER BY body"
+                ))
+            equality = await connection.fetchval("""
+                SELECT bool_and(worker_lease_live_until IS NOT DISTINCT FROM worker_lease_expires_at)
+                FROM public.checker_runs
+            """) and await connection.fetchval("""
+                SELECT bool_and(claim_live_until IS NOT DISTINCT FROM
+                  CASE WHEN delivery_state='claimed' THEN claim_expires_at ELSE NULL END)
+                FROM public.outbox_events
+            """) and await connection.fetchval("""
+                SELECT bool_and(claim_live_until=claim_expires_at
+                  AND renew_decision_event_id IS NULL)
+                FROM public.outbox_delivery_attempts
+            """)
+            states = tuple(row["delivery_state"] for row in await connection.fetch(
+                "SELECT delivery_state FROM public.outbox_events ORDER BY event_id"
+            ))
+            guards = await connection.fetch("""
+                SELECT tgname,tgenabled FROM pg_trigger WHERE tgname IN
+                  ('checker_run_custody','outbox_events_custody') ORDER BY tgname
+            """)
+            return result, equality, states, tuple((r["tgname"], r["tgenabled"]) for r in guards)
+        finally:
+            await connection.close()
+
+    config = _alembic_config()
+    with migration_lock():
+        asyncio.run(db_session.dispose_engine())
+        asyncio.run(_execute(isolated_database_env, "DROP SCHEMA public CASCADE; CREATE SCHEMA public"))
+        command.upgrade(config, predecessor)
+        asyncio.run(restore_archived_snapshot(isolated_database_env, archive))
+        command.upgrade(config, "0095_post_infrastructure_retry")
+        before = asyncio.run(retained())
+        assert all(before[table] for table in before)
+        async def predecessor_shape():
+            connection = await asyncpg.connect(isolated_database_env.replace("+asyncpg", ""))
+            try:
+                return (
+                    await connection.fetchval("""
+                        SELECT count(*) FROM public.outbox_events e
+                        JOIN public.outbox_delivery_attempts a ON a.event_id=e.event_id
+                        WHERE e.delivery_state='claimed' AND a.stage='invoked'
+                          AND e.claim_expires_at 0
+        else:
+            assert terminal_checker > 0
+        command.upgrade(config, HEAD_REVISION)
+        after, equality, states, guards = asyncio.run(projected())
+    assert after == before
+    assert equality is True
+    assert expected_state in states
+    assert guards == (("checker_run_custody", "O"), ("outbox_events_custody", "O"))
+
+
 @asynccontextmanager
 async def _historical_artifact_lineage_projection(database_url: str):
     """Expose null-only current ART lineage after restoring exact historical rows."""
@@ -538,7 +647,7 @@ def test_v01_graph_has_one_root_and_head() -> None:
     assert script.get_revision("0090_merge_direct_storage").down_revision == (
         "0089_observed_upload_cleanup", "0069_remove_artifact_proof",
     )
-    assert script.get_revision(HEAD_REVISION).down_revision == "0094_project_archive_limits"
+    assert script.get_revision(HEAD_REVISION).down_revision == "0095_post_infrastructure_retry"
     assert revisions[-1].down_revision is None
     assert script.get_heads() == [HEAD_REVISION]
 
@@ -1982,7 +2091,7 @@ def test_root_upgrade_refuses_nonempty_unstamped_schema_before_product_ddl(
             "0004_task_context_authority",
             "Workstream v0.1 migrations cannot be downgraded; recreate the database",
         ),
-        (HEAD_REVISION, "POST infrastructure retry migration is forward-only"),
+        (HEAD_REVISION, "renewable POST custody is forward-only"),
     ],
 )
 def test_downgrade_refuses_without_mutation(

From 14b6c321f79976bb9c4e7a5471961506b54d0a8a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:25:40 +0100
Subject: [PATCH 503/513] Record passing PRE fixture control and runner
 restoration

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 20 +++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 7ab7b7437..5722a1f02 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13367,3 +13367,23 @@ build staging and the native sandbox identity. Verify the resulting layer
 header and execute a single ordinary passing input in the isolated domain
 before arming the failure matrix. The normal runner must be restored after the
 control. Review exact image custody and entrypoint readability before the run.
+
+The exact `b1ac8af18` build produced the `8304b99e` fixture manifest. Canonical
+cache inspection verified `/checker.py` as root-owned mode `0444` with the
+tracked payload digest. The owned build registry was removed. A single
+fault-free public CLI submission using this image accepted in 104.35 seconds,
+then finalized revision 1 and passed POST. The native trace binds the accepted
+receipt to exactly one source-first PRE execution with outer exit 0 and an
+observed delete. The durable cleanup disposition is `destroyed`. The isolated
+0094 database and MinIO cleanup checks passed. Authenticated normal runner
+placement matched before and after, its two service PIDs were unchanged, and
+both isolated test services stopped with empty lease, VM, workspace and cgroup
+inventories.
+
+The proof is under `/tmp/workstream-native-pre-control-v_8aasi4`, with the
+cross-checked summary in `pre-control-summary.json`. This run qualifies the
+passing control for the rebuilt fixture. The OOM, crash, output limit and
+pending-delete cases still require evidence. The trusted PRE worker's
+infrastructure reply currently maps to outer exit 125, which can also occur
+before selected project execution. Exact fault qualification needs a trusted
+observation of the selected project outcome.

From 63e6ea4a948460a291fb5a1ce0f5b37193801187 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:29:45 +0100
Subject: [PATCH 504/513] Admit exact invoked OUTBOX lease renewal

---
 backend/alembic/versions/0096_post_renewable_lifetimes.py | 7 +++++++
 backend/tests/conftest.py                                 | 2 +-
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/backend/alembic/versions/0096_post_renewable_lifetimes.py b/backend/alembic/versions/0096_post_renewable_lifetimes.py
index c63db4b0a..321a4dbb7 100644
--- a/backend/alembic/versions/0096_post_renewable_lifetimes.py
+++ b/backend/alembic/versions/0096_post_renewable_lifetimes.py
@@ -135,6 +135,13 @@ def upgrade() -> None:
          "or new.last_attempt_at is distinct from old.last_attempt_at\n"
          "               or new.claim_live_until is not null then\n"
          "              raise exception 'outbox outcome cannot change claim generation'", 1))
+    _replace("public.guard_outbox_delivery_attempt()",
+        ("elsif tg_op = 'INSERT' then",
+         "elsif tg_op = 'UPDATE' and old.stage='invoked' and new.stage='invoked' "
+         "and new.claim_live_until is distinct from old.claim_live_until then\n"
+         "            -- The separate renewal trigger validates the exact row, event and decision.\n"
+         "            return new;\n"
+         "          elsif tg_op = 'INSERT' then", 1))
     _replace("public.check_outbox_delivery_projection()",
         ("(e.claim_owner,e.claimed_at,e.claim_expires_at,e.last_attempt_at) is distinct from\n"
          "               (a.claim_owner,a.claimed_at,a.claim_expires_at,a.claimed_at)",
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index ed6aadd1e..04e956582 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,7 +23,7 @@
 DDL_LOCK_DIRECTORY = Path("/tmp")
 # Match the PostgreSQL 16 engine used by Backend CI. Catalog identity rendering
 # differs across major versions; regenerate only after comparing actual objects.
-EXPECTED_PUBLIC_SCHEMA_SHA256 = "9c88847e28178b92dcc8262b5a9de600123d221e382f4b50ba4c606cb177288c"
+EXPECTED_PUBLIC_SCHEMA_SHA256 = "29ce2eb4eb0fb074aac2a780ba9e5928186b1cb870d95e753db0cee92a280dad"
 PROTECTED_TEST_TABLES = (
     "actor_profile_migration_state",
     "alembic_version",

From d377129a2cf98c9b468ff7fe04aa4add32028d39 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:32:18 +0100
Subject: [PATCH 505/513] Bind native PRE fault proof to trusted project
 outcome markers

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md         | 18 ++++++++
 .../test_journey_pre_qualification.py         | 44 +++++++++++++++----
 cli/tests/journey/pre_qualification.py        | 14 ++++--
 .../tests/smol_fixture/runtime_wrapper.py     | 10 ++++-
 4 files changed, 73 insertions(+), 13 deletions(-)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 5722a1f02..6373c8c5d 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13387,3 +13387,21 @@ pending-delete cases still require evidence. The trusted PRE worker's
 infrastructure reply currently maps to outer exit 125, which can also occur
 before selected project execution. Exact fault qualification needs a trusted
 observation of the selected project outcome.
+
+### Bind fault qualification to observed project outcomes
+
+The passing control supports executing the failure matrix with the readable
+fixture. Qualify OOM, the injected process exit 37, and captured output
+overflow by observing the supervisor's existing child outcome fields. A
+separate local build of the exact runner guest source adds three fixed
+observation strings only. The isolated test domain pins that binary. The
+normal runner keeps its current guest, resource limits and policy.
+
+The allowed repository paths are the test runtime wrapper, the maintained
+CLI PRE qualification assertion and its focused integration tests, plus this
+record. The wrapper retains a closed fault label and the matrix requires the
+matching trace, durable PRE receipt and cleanup disposition for each input.
+Verify missing, mismatched and repeated markers fail qualification. The
+pending-delete input must still pass PRE, reach the existing T5 owner and
+resume POST after the exact native lease is reconciled. Finally restore the
+normal runner and confirm unchanged authenticated placement and inventories.
diff --git a/cli/tests/integration/test_journey_pre_qualification.py b/cli/tests/integration/test_journey_pre_qualification.py
index 61f471bc8..518f4a539 100644
--- a/cli/tests/integration/test_journey_pre_qualification.py
+++ b/cli/tests/integration/test_journey_pre_qualification.py
@@ -119,9 +119,19 @@ def test_timeout_replay_compares_stable_business_fields(change):
 
 
 @pytest.mark.parametrize("exact", [True, False])
-@pytest.mark.parametrize("limit", [None, "memory", "output"])
-def test_runtime_fixture_classifies_only_the_trusted_deadline_line(
-    tmp_path, exact, limit
+@pytest.mark.parametrize(
+    ("marker", "expected_fault"),
+    [
+        (None, None),
+        ("observed_oom_kill", "oom_kill"),
+        ("observed_project_exit_37", "project_exit_37"),
+        ("observed_output_limit", "output_limit"),
+        ("observed_output_limit suffix", None),
+        ("observed_oom_kill\nWORKSTREAM_PRE_QUALIFICATION observed_oom_kill", None),
+    ],
+)
+def test_runtime_fixture_classifies_only_exact_trusted_lines(
+    tmp_path, exact, marker, expected_fault
 ):
     wrapper = tmp_path / "runtime_wrapper.py"
     wrapper.write_bytes(WRAPPER.read_bytes())
@@ -129,8 +139,10 @@ def test_runtime_fixture_classifies_only_the_trusted_deadline_line(
     diagnostic = "workstream guest bootstrap failed: project deadline exceeded"
     if not exact:
         diagnostic += " (other diagnostic)"
-    if limit is not None:
-        diagnostic += f"\nAssertionError: guest {limit} ceiling was not enforced"
+    if marker:
+        diagnostic += f"\nWORKSTREAM_PRE_QUALIFICATION {marker}"
+    else:
+        diagnostic += "\nAssertionError: guest memory ceiling was not enforced"
     guest.write_text(
         f"#!{sys.executable}\n"
         "import os\n"
@@ -179,7 +191,8 @@ def test_runtime_fixture_classifies_only_the_trusted_deadline_line(
             "operation": "pre_exit",
             "exit_code": 125,
             "project_deadline_exceeded": exact,
-            "guest_limit_unenforced": limit is not None,
+            "guest_limit_unenforced": marker is None,
+            "project_fault": expected_fault,
         },
     ]
 
@@ -194,13 +207,21 @@ def test_runtime_fixture_classifies_only_the_trusted_deadline_line(
         "leaked_guest",
         "extra_pre",
         "completed_failure",
+        "missing_marker",
+        "wrong_marker",
+        "pending_marker",
     ],
 )
 def test_remaining_native_trace_binds_each_failure_and_pending_lease(fault):
     wrapper_digest = "sha256:" + sha256(WRAPPER.read_bytes()).hexdigest()
     evidence = {"mode": "failure_cleanup", "failures": {}}
     trace = []
-    for name in ("memory", "crash", "output", "pending"):
+    for name, observation in (
+        ("memory", "oom_kill"),
+        ("crash", "project_exit_37"),
+        ("output", "output_limit"),
+        ("pending", None),
+    ):
         invocation = {
             "provider_invocation_id": name,
             "operation": "execute_pre",
@@ -224,7 +245,8 @@ def test_remaining_native_trace_binds_each_failure_and_pending_lease(fault):
                 {
                     "name": name,
                     "operation": "pre_exit",
-                    "exit_code": 0 if name == "pending" else 37,
+                    "exit_code": 0 if name == "pending" else 125,
+                    "project_fault": observation,
                     "project_deadline_exceeded": False,
                     "guest_limit_unenforced": False,
                 },
@@ -243,6 +265,12 @@ def test_remaining_native_trace_binds_each_failure_and_pending_lease(fault):
         trace.append({"name": "extra", "operation": "exec", "source_pre": True})
     elif fault == "completed_failure":
         trace[8]["exit_code"] = 0
+    elif fault == "missing_marker":
+        trace[3]["project_fault"] = None
+    elif fault == "wrong_marker":
+        trace[3]["project_fault"] = "output_limit"
+    elif fault == "pending_marker":
+        trace[18]["project_fault"] = "project_exit_37"
     if fault:
         with pytest.raises(AssertionError):
             MODULE.verify_native_trace(evidence, trace)
diff --git a/cli/tests/journey/pre_qualification.py b/cli/tests/journey/pre_qualification.py
index a2128597d..a89f81432 100644
--- a/cli/tests/journey/pre_qualification.py
+++ b/cli/tests/journey/pre_qualification.py
@@ -477,7 +477,13 @@ def _verify_failure_cleanup_trace(evidence, trace):
     """Bind three guest failures and one exact unsettled delete to current PRE leases."""
     wrapper_digest = "sha256:" + sha256(WRAPPER.read_bytes()).hexdigest()
     leases = []
-    for name in ("memory", "crash", "output", "pending"):
+    expected_faults = {
+        "memory": "oom_kill",
+        "crash": "project_exit_37",
+        "output": "output_limit",
+        "pending": None,
+    }
+    for name, expected_fault in expected_faults.items():
         item = evidence["pending"] if name == "pending" else evidence["failures"][name]
         invocation = item["invocation"]
         lease = invocation["provider_invocation_id"]
@@ -507,10 +513,10 @@ def _verify_failure_cleanup_trace(evidence, trace):
         ):
             raise AssertionError(f"{name} lacks exact native execution and cleanup")
         if name == "pending":
-            if rows[3]["exit_code"] != 0:
+            if rows[3]["exit_code"] != 0 or rows[3]["project_fault"] is not None:
                 raise AssertionError("pending cleanup did not follow a completed guest")
-        elif rows[3]["exit_code"] == 0:
-            raise AssertionError(f"{name} native failure differs")
+        elif rows[3]["exit_code"] != 125 or rows[3]["project_fault"] != expected_fault:
+            raise AssertionError(f"{name} lacks the exact trusted project fault")
         leases.append(lease)
     executions = [row for row in trace if row["operation"] == "exec"]
     if (
diff --git a/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py b/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
index 207b0a239..d3e9a04dc 100644
--- a/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
+++ b/external_checkers/workstream-checker-service/tests/smol_fixture/runtime_wrapper.py
@@ -28,11 +28,19 @@ def observe_pre_exit(binary, arguments, trace, name):
             b'guest output ceiling was not enforced',
         )
     )
+    markers = {
+        b'WORKSTREAM_PRE_QUALIFICATION observed_oom_kill': 'oom_kill',
+        b'WORKSTREAM_PRE_QUALIFICATION observed_project_exit_37': 'project_exit_37',
+        b'WORKSTREAM_PRE_QUALIFICATION observed_output_limit': 'output_limit',
+    }
+    lines = bytes(captured).splitlines()
+    observed = [markers[line] for line in lines if line in markers]
     with trace.open('a') as output:
         fcntl.flock(output, fcntl.LOCK_EX)
         output.write(json.dumps({
             'operation': 'pre_exit', 'name': name, 'exit_code': code,
-            'project_deadline_exceeded': diagnostic in captured.splitlines(),
+            'project_deadline_exceeded': diagnostic in lines,
+            'project_fault': observed[0] if len(observed) == 1 else None,
             'guest_limit_unenforced': limit_unenforced,
         }) + '\n')
         output.flush()

From 12b361b1ff81d106870be68c19f7b0a525efa1d2 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:35:21 +0100
Subject: [PATCH 506/513] Match PostgreSQL trigger flag byte in retained
 upgrade proof

---
 backend/tests/test_alembic.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/backend/tests/test_alembic.py b/backend/tests/test_alembic.py
index effb50ac0..8005a13b7 100644
--- a/backend/tests/test_alembic.py
+++ b/backend/tests/test_alembic.py
@@ -233,7 +233,7 @@ async def predecessor_shape():
     assert after == before
     assert equality is True
     assert expected_state in states
-    assert guards == (("checker_run_custody", "O"), ("outbox_events_custody", "O"))
+    assert guards == (("checker_run_custody", b"O"), ("outbox_events_custody", b"O"))
 
 
 @asynccontextmanager

From a7f33263299be65c16d05a85ce8547af751def23 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:36:58 +0100
Subject: [PATCH 507/513] Make original claim expiry proof robust to database
 startup

---
 backend/tests/outbox/test_delivery_postgresql.py | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/backend/tests/outbox/test_delivery_postgresql.py b/backend/tests/outbox/test_delivery_postgresql.py
index 780aa3eb9..b9e75258a 100644
--- a/backend/tests/outbox/test_delivery_postgresql.py
+++ b/backend/tests/outbox/test_delivery_postgresql.py
@@ -23,7 +23,7 @@ async def test_background_invocation_survives_original_claim_expiry(delivery_har
     """A live inspected handler retains one claim without a whole-handler cutoff."""
     h = delivery_harness
     h.options = DeliveryOptions(
-        lease_seconds=1, handler_timeout_seconds=None, background_heartbeat=True,
+        lease_seconds=5, handler_timeout_seconds=None, background_heartbeat=True,
         retry_base_seconds=1,
     )
     h.delivery = h.build(HandlerRegistry([(REQUEST_EVENT, 1, h.handle)]))
@@ -38,8 +38,13 @@ async def block(_envelope):
     claim = await h.claim(event_type=REQUEST_EVENT, aggregate_type="submission")
     invoked = asyncio.create_task(h.delivery.invoke(claim))
     try:
-        await asyncio.wait_for(entered.wait(), 10)
-        await asyncio.sleep(1.2)
+        try:
+            await asyncio.wait_for(entered.wait(), 15)
+        except TimeoutError:
+            if invoked.done():
+                await invoked
+            raise
+        await asyncio.sleep(5.2)
         async with h.factory() as session:
             now = await database_time(session)
             event = await session.get(OutboxEvent, claim.event_id)

From 97db48570e1e300786b76dc3633063d64de0eb9d Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:40:02 +0100
Subject: [PATCH 508/513] Exercise periodic OUTBOX inspection with viable
 database timeout

---
 backend/tests/outbox/test_delivery_postgresql.py | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/backend/tests/outbox/test_delivery_postgresql.py b/backend/tests/outbox/test_delivery_postgresql.py
index b9e75258a..7ebffdb59 100644
--- a/backend/tests/outbox/test_delivery_postgresql.py
+++ b/backend/tests/outbox/test_delivery_postgresql.py
@@ -27,7 +27,7 @@ async def test_background_invocation_survives_original_claim_expiry(delivery_har
         retry_base_seconds=1,
     )
     h.delivery = h.build(HandlerRegistry([(REQUEST_EVENT, 1, h.handle)]))
-    monkeypatch.setattr(delivery_module, "BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS", 0.2)
+    monkeypatch.setattr(delivery_module, "BACKGROUND_STATUS_INSPECTION_INTERVAL_SECONDS", 10)
     entered, release = asyncio.Event(), asyncio.Event()
 
     async def block(_envelope):
@@ -44,14 +44,18 @@ async def block(_envelope):
             if invoked.done():
                 await invoked
             raise
-        await asyncio.sleep(5.2)
+        async with h.factory() as session:
+            first = await DeliveryRepository(session).attempt(claim)
+            first_decision = first.renew_decision_event_id
+            assert first_decision is not None
+        await asyncio.sleep(12)
         async with h.factory() as session:
             now = await database_time(session)
             event = await session.get(OutboxEvent, claim.event_id)
             attempt = await DeliveryRepository(session).attempt(claim)
             assert claim.claim_expires_at < now < event.claim_live_until
             assert attempt.claim_live_until == event.claim_live_until
-            assert attempt.renew_decision_event_id is not None
+            assert attempt.renew_decision_event_id != first_decision
             assert event.claim_generation == claim.claim_generation
         assert await h.delivery.recover(claim.event_id, h.project) is None
         assert await h.delivery.claim(claim.event_id, h.project, "competing-worker") is None

From 69436c8c91424a1b56693467153f5aba6383eb1a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Thu, 26 Nov 2026 22:48:14 +0100
Subject: [PATCH 509/513] Record deployed POST renewal release and verified
 hosted state

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md          | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 593346c4b..126e584c4 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13431,3 +13431,21 @@ Verify missing, mismatched and repeated markers fail qualification. The
 pending-delete input must still pass PRE, reach the existing T5 owner and
 resume POST after the exact native lease is reconciled. Finally restore the
 normal runner and confirm unchanged authenticated placement and inventories.
+
+### Hosted POST renewal release, 26 November 2026
+
+The API host deployed release `a1061f392f45d17e51294573cab980d8874d677a` with
+schema `0096_post_renewable_lifetimes`. The drained upgrade compared retained
+rows before and after migration. The separate runner activated executable
+SHA-256 `314962d5079fb13a09c6fe226bf6a965baa7d32d5a7a49f448225d88275eef3f`.
+The API authenticated runner readiness with the existing PRE300 profile. Hosted
+activation verified application container health and the MCP container's
+attachment to the current API network namespace.
+
+PostgreSQL tests retained two archived datasets across the upgrade. A live
+handler outlasted its original claim, recorded a second renewal, refused a
+competitor and acknowledged once. The hosted 500 MiB assignment remained
+`evaluation_pending` immediately after deployment, with its original unknown
+attempt retained. The dedicated native PRE control passed with confirmed VM
+destruction. Individual native fault and pending-delete outcomes still require
+live evidence.

From 7330ad3cbfa6d6cf0222d5587cdd3affe82ddce3 Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 27 Nov 2026 06:39:45 +0100
Subject: [PATCH 510/513] Record hosted 500 MiB Operator recovery and automatic
 POST retries

---
 .../WS-SUBMIT-001/WS-SUBMIT-001-01.md            | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index 126e584c4..f764a28a5 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13449,3 +13449,19 @@ competitor and acknowledged once. The hosted 500 MiB assignment remained
 attempt retained. The dedicated native PRE control passed with confirmed VM
 destruction. Individual native fault and pending-delete outcomes still require
 live evidence.
+
+### Operator recovery of the hosted 500 MiB submission
+
+On 27 November the public Operator command reconciled retained delivery
+`01a21964-b5ec-7c61-82a8-5ce699683cf0`. The worker acknowledged reconciliation
+event `01a21b79-672f-79a3-aa67-d23f9f6fe321` on its first attempt. Generation 2
+ran against the original submission and assignment. Its runner receipt recorded
+524,287,258 material bytes transferred in 5.083 seconds. The native service
+returned `deadline_exceeded`. Generations 3 and 4 also returned that known
+infrastructure result, and the worker scheduled generation 5. The assignment
+remained pending evaluation throughout those retries.
+
+The registered checker specifies 30,000 ms. The native implementation starts
+that clock before image verification, VM creation, and guest staging. The
+receipt establishes successful transfer to the runner. It does not locate the
+precise point at which the deadline elapsed inside native execution.

From 1166df50deab8a8c3da3e7e8bd5ae32789c95a7a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 27 Nov 2026 07:20:55 +0100
Subject: [PATCH 511/513] fix(checkers): start native POST budget after staging

---
 external_checkers/README.md                   |  16 +-
 .../post-native-runtime-boundary-20261127.md  |  63 ++++++++
 .../workstream-checker-guest/src/lib.rs       |   6 +
 .../workstream-checker-guest/src/main.rs      |  10 ++
 .../workstream-checker-service/src/main.rs    |  78 +++++++--
 .../src/model_relay.rs                        | 118 +++++++++++++-
 .../workstream-checker-service/src/smol.rs    | 101 ++++++++----
 .../workstream-checker-service/src/smol/io.rs | 153 +++++++++++++++++-
 .../src/smol/pre.rs                           |   2 +-
 .../src/smol/pre/tests.rs                     |   2 -
 .../src/smol/tests.rs                         |  10 +-
 .../src/smol/trial.rs                         |   4 +
 .../src/smol/trial_io.rs                      |   1 +
 .../src/trial_roots.rs                        |   2 +-
 14 files changed, 491 insertions(+), 75 deletions(-)
 create mode 100644 external_checkers/deploy/post-native-runtime-boundary-20261127.md

diff --git a/external_checkers/README.md b/external_checkers/README.md
index cf22f8907..110acfd27 100644
--- a/external_checkers/README.md
+++ b/external_checkers/README.md
@@ -383,6 +383,17 @@ and charges virtualization overhead separately. Results are returned only after
 VM and cgroup removal is confirmed. Unknown cleanup closes admission and requires
 startup reconciliation. Failures before lease creation or after confirmed cleanup
 return recoverable infrastructure failure without stopping other checks.
+For an ordinary native project check, the registry `deadline_ms` is checker
+runtime, not a platform-transfer allowance. VM create/start/bootstrap retain
+their individual control-operation bounds, and the host-to-guest job/material
+stream retains a progress-reset inactivity bound. After staging, mount and
+cgroup setup, the trusted guest emits one `prepared` transition and waits. The
+host validates that transition, arms any invocation-local model relay, starts
+the declared runtime clock and sends the single `start` acknowledgement before
+the guest may fork the workload. Missing, malformed, repeated or out-of-order
+transitions fail closed. Trial and selected PRE paths keep their own existing
+aggregate envelopes; trusted intake continues to cover transfer and preparation
+with its artifact deadline.
 The private trial stream carries the export header, export bytes, retained stdout,
 retained stderr and final receipt in that order. Each output length and digest is
 bound by both header and final receipt; successful exit and exact EOF are required.
@@ -394,7 +405,10 @@ incomplete suffix (at most three bytes) is trimmed, without changing the
 `output_exceeded` outcome. Intrinsically invalid UTF-8 is an explicit unsupported
 text-protocol failure; it is never replaced, silently discarded or rehashed as
 empty output.
-Independent lease guardians survive controller death;
+Independent lease guardians survive controller death while the controller's
+exact owner pipe is live; EOF or owner loss triggers cleanup. Individual native
+control and stream interactions remain finitely bounded without treating a
+renewable healthy POST as expired at its immutable original lease timestamp.
 `KillMode=process` preserves that cleanup lifetime. Preserve the private owner
 file and lease directory across restarts. Never clone them between running nodes.
 
diff --git a/external_checkers/deploy/post-native-runtime-boundary-20261127.md b/external_checkers/deploy/post-native-runtime-boundary-20261127.md
new file mode 100644
index 000000000..3f2c51ddc
--- /dev/null
+++ b/external_checkers/deploy/post-native-runtime-boundary-20261127.md
@@ -0,0 +1,63 @@
+# Native POST runtime boundary — 2026-11-27
+
+This change corrects the native ordinary-POST deadline boundary. It is a build
+and rollout record, not live qualification evidence.
+
+## Diagnosis
+
+The service previously created `request.deadline_ms` before grant verification,
+workspace hashing, Smol machine creation/start, guest bootstrap copy, material
+streaming and guest staging. The guest ordinary-project supervisor had no
+separate runtime deadline. A 500 MiB incident-summary request could therefore
+consume its frozen 30,000 ms checker allowance before the checker entrypoint was
+launched. The earlier 462,365,541-byte qualification receipt independently
+recorded about 79.9 seconds from `machine exec` through transfer, validation,
+staging and checker execution, consistent with this path.
+
+## Corrected boundary
+
+- Grant verification, VM preparation and material staging no longer consume an
+  ordinary native checker's registry runtime.
+- Smol create/start/copy retain the existing per-control-operation timeout.
+  Job/material delivery and the preparation transition use the existing
+  progress-reset socket inactivity timeout and still observe caller disconnect.
+- After staging, mounts and cgroups are ready, the trusted guest emits exactly
+  one `prepared` frame and waits. The host validates it, arms the invocation's
+  model relay with `now + deadline_ms`, and sends exactly one `start` frame.
+  Only then may the guest fork and exec the checker.
+- The host applies that same runtime deadline to capability calls, completion
+  and process reaping. Missing, malformed, duplicate and unsolicited control
+  frames fail closed.
+- Trial executions preserve their existing aggregate envelope. PRE and trusted
+  intake retain their existing purpose-specific deadline semantics.
+- The guardian follows its exact controller owner pipe instead of the immutable
+  original POST lease timestamp. This preserves renewable background work while
+  controller EOF/loss still initiates owned cleanup.
+
+## Release procedure
+
+1. Build the service and the static `x86_64-unknown-linux-musl` guest from the
+   same reviewed source commit with `--locked`; record SHA-256 and ELF identity.
+2. Run the Rust workspace tests plus the maintained PRE and trusted-intake
+   compatibility lanes. On a fresh isolated KVM candidate, qualify a maximum
+   admitted ordinary POST whose checker runtime is independently observable;
+   verify staging can exceed `deadline_ms` while a checker exceeding its own
+   runtime still returns `deadline_exceeded`.
+3. Drain the runner and prove zero admission, remote sessions, material
+   workspaces, leases, VMs and owned cgroups. This is required because the
+   unreleased lease JSON drops the superseded fixed-expiry fields.
+4. Stop only the runner edge/native units under the reviewed maintenance
+   sequence. Preserve byte-identical rollback binaries, guest and node config.
+5. Install both reviewed binaries. Replace the guest SHA in all three bindings:
+   `smol.guest_sha256`, `pre.guest_sha256`, and
+   `trusted_intake.storage_envelope.guest_sha256`. Recompute the closed node
+   config digest; do not alter image, Smol, PRE-root or intake identities.
+6. Start native then edge, verify authenticated health/config epoch, and run
+   unchanged PRE and trusted-intake checks before ordinary POST. Then run the
+   500 MiB incident-summary POST and a bounded runtime-overrun case. Confirm
+   results, empty workspaces/leases/VMs/cgroups and no error-priority journal.
+7. Roll back both binaries and the exact prior config together on any binding,
+   readiness, PRE, intake, runtime-deadline or cleanup mismatch.
+
+No app-host configuration, policy, source gate, network or IAM change is part
+of this rollout.
diff --git a/external_checkers/workstream-checker-guest/src/lib.rs b/external_checkers/workstream-checker-guest/src/lib.rs
index 88cd9d7b9..c275444b3 100644
--- a/external_checkers/workstream-checker-guest/src/lib.rs
+++ b/external_checkers/workstream-checker-guest/src/lib.rs
@@ -95,6 +95,12 @@ pub enum GuestIoChannel {
 #[derive(Debug, Deserialize, Serialize)]
 #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
 pub enum GuestIoHeader {
+    Prepared {
+        protocol_version: String,
+    },
+    Start {
+        protocol_version: String,
+    },
     Request {
         protocol_version: String,
         sequence: u32,
diff --git a/external_checkers/workstream-checker-guest/src/main.rs b/external_checkers/workstream-checker-guest/src/main.rs
index fdace7824..adaa8261b 100644
--- a/external_checkers/workstream-checker-guest/src/main.rs
+++ b/external_checkers/workstream-checker-guest/src/main.rs
@@ -832,6 +832,16 @@ fn run_project(
         limits.maximum_processes,
     )
     .map_err(|error| format!("cgroup: {error}"))?;
+    // All host material and guest platform setup is complete. The workload is
+    // not forked until the host acknowledges this transition after arming the
+    // registry-declared checker runtime and invocation-local callbacks.
+    write_guest_header(&GuestIoHeader::Prepared {
+        protocol_version: GUEST_IO_PROTOCOL.into(),
+    })?;
+    match read_guest_header(&mut input)? {
+        GuestIoHeader::Start { protocol_version } if protocol_version == GUEST_IO_PROTOCOL => {}
+        _ => return Err("guest project start invalid".into()),
+    }
     // The supervisor retains the trusted stream and capability listeners. The
     // workload receives separate output pipes, so it cannot forge mux frames.
     let child = limits.fork_project()?;
diff --git a/external_checkers/workstream-checker-service/src/main.rs b/external_checkers/workstream-checker-service/src/main.rs
index 23684c9c6..110f9d1c0 100644
--- a/external_checkers/workstream-checker-service/src/main.rs
+++ b/external_checkers/workstream-checker-service/src/main.rs
@@ -305,10 +305,22 @@ struct OutputMeter {
 
 struct RequestExecutionBudget {
     deadline: Instant,
+    native_project: Option,
     output: OutputMeter,
     cleanup: EmergencyCleanupBudget,
 }
 
+#[derive(Clone, Copy)]
+struct NativeProjectBudget {
+    runtime: Duration,
+}
+
+#[derive(Clone, Copy)]
+enum ProjectExecutionBudget {
+    PreparationSeparated(Duration),
+    Aggregate(Instant),
+}
+
 #[derive(Debug, PartialEq, Eq)]
 struct ExecutionFailure {
     code: &'static str,
@@ -366,10 +378,17 @@ impl RequestExecutionBudget {
     fn new(deadline: Instant, maximum_output: usize) -> Self {
         Self {
             deadline,
+            native_project: None,
             output: OutputMeter::new(maximum_output),
             cleanup: EmergencyCleanupBudget::new(),
         }
     }
+
+    fn configure_native_project(&mut self, runtime_ms: u64) {
+        self.native_project = Some(NativeProjectBudget {
+            runtime: Duration::from_millis(runtime_ms),
+        });
+    }
 }
 
 #[derive(Debug)]
@@ -1187,6 +1206,9 @@ fn handle_frame(
         Instant::now() + Duration::from_millis(request.deadline_ms),
         request.maximum_output_bytes,
     );
+    if config.runtime == "smolvm" {
+        budget.configure_native_project(request.deadline_ms);
+    }
     let (result, isolation) = match verify_grant(config, &request, &envelope.grant) {
         Ok(grant) => match inspect_image(config, cache, stream, &mut budget) {
             Ok(()) => match execute_container(
@@ -2130,6 +2152,16 @@ fn execute_container(
         ));
     }
     let selected_trial = selected_trial_profile(config, request)?;
+    let native_project = if config.runtime == "smolvm" && selected_trial.is_none() {
+        Some(
+            budget
+                .native_project
+                .ok_or_else(|| ExecutionFailure::ordinary("implementation_unavailable", false))?,
+        )
+    } else {
+        None
+    };
+    let callback_deadline = budget.deadline;
     let reservation = if config.runtime == "smolvm" {
         let result = match selected_trial {
             Some(profile) => smol::trial_peak_capacity(
@@ -2166,7 +2198,7 @@ fn execute_container(
                     profile,
                     Arc::clone(held),
                     client,
-                    budget.deadline,
+                    callback_deadline,
                     Arc::clone(&invocation_cancelled),
                 )
                 .map_err(|_| ExecutionFailure::ordinary("implementation_unavailable", false))?;
@@ -2175,7 +2207,7 @@ fn execute_container(
                     Arc::clone(&receipt_registry),
                     request.request_digest.clone(),
                     profile.maximum_receipt_bytes,
-                    budget.deadline,
+                    callback_deadline,
                     Arc::clone(&invocation_cancelled),
                 )
                 .map_err(|_| ExecutionFailure::ordinary("implementation_unavailable", false))?;
@@ -2194,7 +2226,7 @@ fn execute_container(
                         engine,
                         config.sandbox_uid,
                         config.sandbox_gid,
-                        budget.deadline,
+                        callback_deadline,
                         Arc::clone(&invocation_cancelled),
                     )
                     .map_err(|failure| {
@@ -2223,16 +2255,29 @@ fn execute_container(
                     false,
                 ));
             };
-            match InvocationRelay::start_with_resolver(
-                relay_root,
-                proxy_path,
-                grant,
-                &request.request_digest,
-                Arc::clone(&receipt_registry) as Arc,
-                config.sandbox_uid,
-                config.sandbox_gid,
-                budget.deadline,
-            ) {
+            let relay = if native_project.is_some() {
+                InvocationRelay::start_with_resolver_unarmed(
+                    relay_root,
+                    proxy_path,
+                    grant,
+                    &request.request_digest,
+                    Arc::clone(&receipt_registry) as Arc,
+                    config.sandbox_uid,
+                    config.sandbox_gid,
+                )
+            } else {
+                InvocationRelay::start_with_resolver(
+                    relay_root,
+                    proxy_path,
+                    grant,
+                    &request.request_digest,
+                    Arc::clone(&receipt_registry) as Arc,
+                    config.sandbox_uid,
+                    config.sandbox_gid,
+                    callback_deadline,
+                )
+            };
+            match relay {
                 Ok(relay) => Some(relay),
                 Err(failure) => {
                     let trial_cleanup_unsettled = trial_relay
@@ -2268,12 +2313,17 @@ fn execute_container(
                 model: model_relay
                     .as_ref()
                     .map(|relay| relay.socket_path().to_owned()),
+                model_deadline: native_project
+                    .and_then(|_| model_relay.as_ref().map(InvocationRelay::deadline)),
                 execution: trial_relay
                     .as_ref()
                     .map(|relay| relay.socket_path().to_owned()),
             },
             client,
-            budget,
+            native_project.map_or(
+                ProjectExecutionBudget::Aggregate(budget.deadline),
+                |native| ProjectExecutionBudget::PreparationSeparated(native.runtime),
+            ),
             invocation_cancelled.as_ref(),
         )
     } else {
diff --git a/external_checkers/workstream-checker-service/src/model_relay.rs b/external_checkers/workstream-checker-service/src/model_relay.rs
index a9c97379f..7ca63d617 100644
--- a/external_checkers/workstream-checker-service/src/model_relay.rs
+++ b/external_checkers/workstream-checker-service/src/model_relay.rs
@@ -8,7 +8,7 @@ use sha2::{Digest, Sha256};
 use std::collections::{HashMap, HashSet};
 use std::fmt;
 use std::fs::{self, DirBuilder, File};
-use std::io::{Read, Write};
+use std::io::Read;
 use std::os::unix::ffi::OsStrExt;
 use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, PermissionsExt};
 use std::os::unix::net::{UnixListener, UnixStream};
@@ -290,9 +290,42 @@ struct RelayPaths {
 pub(crate) struct InvocationRelay {
     paths: RelayPaths,
     cancelled: Arc,
+    deadline: InvocationDeadline,
     worker: Option>>,
 }
 
+#[derive(Clone)]
+pub(crate) struct InvocationDeadline(Arc>>);
+
+impl InvocationDeadline {
+    fn fixed(deadline: Instant) -> Self {
+        Self(Arc::new(Mutex::new(Some(deadline))))
+    }
+
+    fn unarmed() -> Self {
+        Self(Arc::new(Mutex::new(None)))
+    }
+
+    pub(crate) fn arm(&self, deadline: Instant) -> Result<(), String> {
+        let mut current = self
+            .0
+            .lock()
+            .map_err(|_| "model relay deadline unavailable")?;
+        if current.is_some() || Instant::now() >= deadline {
+            return Err("model relay deadline invalid".into());
+        }
+        *current = Some(deadline);
+        Ok(())
+    }
+
+    fn current(&self) -> Result, String> {
+        self.0
+            .lock()
+            .map(|value| *value)
+            .map_err(|_| "model relay deadline unavailable".into())
+    }
+}
+
 impl InvocationRelay {
     pub(crate) fn start(
         relay_root: &Path,
@@ -325,6 +358,51 @@ impl InvocationRelay {
         sandbox_uid: u32,
         sandbox_gid: u32,
         deadline: Instant,
+    ) -> Result {
+        Self::start_with_deadline(
+            relay_root,
+            proxy_path,
+            grant,
+            request_digest,
+            receipt_resolver,
+            sandbox_uid,
+            sandbox_gid,
+            InvocationDeadline::fixed(deadline),
+        )
+    }
+
+    #[allow(clippy::too_many_arguments)]
+    pub(crate) fn start_with_resolver_unarmed(
+        relay_root: &Path,
+        proxy_path: &Path,
+        grant: &ModelGrant,
+        request_digest: &str,
+        receipt_resolver: Arc,
+        sandbox_uid: u32,
+        sandbox_gid: u32,
+    ) -> Result {
+        Self::start_with_deadline(
+            relay_root,
+            proxy_path,
+            grant,
+            request_digest,
+            receipt_resolver,
+            sandbox_uid,
+            sandbox_gid,
+            InvocationDeadline::unarmed(),
+        )
+    }
+
+    #[allow(clippy::too_many_arguments)]
+    fn start_with_deadline(
+        relay_root: &Path,
+        proxy_path: &Path,
+        grant: &ModelGrant,
+        request_digest: &str,
+        receipt_resolver: Arc,
+        sandbox_uid: u32,
+        sandbox_gid: u32,
+        deadline: InvocationDeadline,
     ) -> Result {
         validate_proxy_socket(proxy_path).map_err(|_| RelayStartFailure::ordinary())?;
         validate_relay_root(relay_root).map_err(|_| RelayStartFailure::ordinary())?;
@@ -388,6 +466,7 @@ impl InvocationRelay {
         let proxy = proxy_path.to_owned();
         let grant = grant.clone();
         let digest = request_digest.to_owned();
+        let worker_deadline = deadline.clone();
         let worker = match thread::Builder::new()
             .name("checker-model-relay".into())
             .spawn(move || {
@@ -397,7 +476,7 @@ impl InvocationRelay {
                     &grant,
                     &digest,
                     receipt_resolver.as_ref(),
-                    deadline,
+                    worker_deadline,
                     &worker_cancelled,
                 )
             }) {
@@ -411,6 +490,7 @@ impl InvocationRelay {
         Ok(Self {
             paths,
             cancelled,
+            deadline,
             worker: Some(worker),
         })
     }
@@ -426,6 +506,10 @@ impl InvocationRelay {
         &self.paths.socket
     }
 
+    pub(crate) fn deadline(&self) -> InvocationDeadline {
+        self.deadline.clone()
+    }
+
     pub(crate) fn finish(mut self) -> RelayFinish {
         self.cancelled.store(true, Ordering::Release);
         let failed = self
@@ -523,13 +607,21 @@ fn relay_once(
     grant: &ModelGrant,
     request_digest: &str,
     receipt_resolver: &dyn ModelReceiptResolver,
-    deadline: Instant,
+    deadline: InvocationDeadline,
     cancelled: &AtomicBool,
 ) -> Result<(), String> {
     let image = loop {
-        if Instant::now() >= deadline {
+        let armed = deadline.current()?;
+        if armed.is_some_and(|value| Instant::now() >= value) {
             return Err("model relay deadline exceeded".into());
         }
+        if armed.is_none() {
+            if cancelled.load(Ordering::Acquire) {
+                return Ok(());
+            }
+            thread::sleep(Duration::from_millis(2));
+            continue;
+        }
         match listener.accept() {
             Ok((stream, _)) => break stream,
             Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
@@ -541,6 +633,9 @@ fn relay_once(
             Err(_) => return Err("model relay accept failed".into()),
         }
     };
+    let deadline = deadline
+        .current()?
+        .ok_or("model relay deadline unavailable")?;
     drop(listener); // one bounded session: no second connection can be accepted.
     relay_session(
         image,
@@ -759,6 +854,19 @@ fn sandbox_socket(metadata: &fs::Metadata, uid: u32, gid: u32) -> bool {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use std::io::Write;
+
+    #[test]
+    fn invocation_deadline_arms_once_after_platform_preparation() {
+        let deadline = InvocationDeadline::unarmed();
+        assert_eq!(deadline.current().unwrap(), None);
+        let runtime_deadline = Instant::now() + Duration::from_secs(30);
+        deadline.arm(runtime_deadline).unwrap();
+        assert_eq!(deadline.current().unwrap(), Some(runtime_deadline));
+        assert!(deadline
+            .arm(runtime_deadline + Duration::from_secs(1))
+            .is_err());
+    }
     use std::sync::atomic::AtomicU64;
     use std::time::{SystemTime, UNIX_EPOCH};
 
@@ -1215,7 +1323,7 @@ mod tests {
             &grant,
             &digest,
             &InvocationReceiptRegistry::default(),
-            Instant::now() + Duration::from_secs(2),
+            InvocationDeadline::fixed(Instant::now() + Duration::from_secs(2)),
             &AtomicBool::new(false),
         )
         .is_err());
diff --git a/external_checkers/workstream-checker-service/src/smol.rs b/external_checkers/workstream-checker-service/src/smol.rs
index 0fcfcc485..d7a198e74 100644
--- a/external_checkers/workstream-checker-service/src/smol.rs
+++ b/external_checkers/workstream-checker-service/src/smol.rs
@@ -95,8 +95,6 @@ struct Lease {
     name: String,
     owner: String,
     epoch: String,
-    expires_ms: u64,
-    lifetime_ms: u64,
     root: PathBuf,
     runtime: SmolConfig,
     #[serde(default)]
@@ -334,9 +332,10 @@ fn random_token() -> Result {
 fn now_ms() -> Result {
     SystemTime::now()
         .duration_since(UNIX_EPOCH)
-        .map(|d| d.as_millis() as u64)
+        .map(|duration| duration.as_millis() as u64)
         .map_err(|_| "clock unavailable".into())
 }
+
 fn private_directory(path: &Path) -> Result<(), String> {
     let metadata = fs::symlink_metadata(path).map_err(|_| "private directory missing")?;
     if !private_socket_parent(&metadata)
@@ -806,6 +805,19 @@ impl Machine {
         Self::create_inner(config, resources, deadline, None, None)
     }
 
+    fn create_project(
+        config: &ServiceConfig,
+        resources: Resources,
+    ) -> Result {
+        Self::create_inner(
+            config,
+            resources,
+            Instant::now() + SOCKET_IO_TIMEOUT,
+            None,
+            None,
+        )
+    }
+
     pub(super) fn create_child(
         config: &ServiceConfig,
         resources: Resources,
@@ -836,7 +848,7 @@ impl Machine {
     fn create_inner(
         config: &ServiceConfig,
         resources: Resources,
-        deadline: Instant,
+        operation_deadline: Instant,
         private_home_root: Option,
         pre: Option,
     ) -> Result {
@@ -891,16 +903,6 @@ impl Machine {
                 .ok_or_else(|| ExecutionFailure::ordinary("implementation_unavailable", false))?
                 .epoch
                 .clone(),
-            expires_ms: now_ms()
-                .map_err(|_| ExecutionFailure::ordinary("implementation_unavailable", false))?
-                .saturating_add(
-                    deadline
-                        .saturating_duration_since(Instant::now())
-                        .as_millis() as u64,
-                ),
-            lifetime_ms: deadline
-                .saturating_duration_since(Instant::now())
-                .as_millis() as u64,
             root,
             runtime: s,
             private_home_root,
@@ -967,7 +969,7 @@ impl Machine {
             .ok_or_else(|| ExecutionFailure::unsettled(false))?;
         set_nonblocking(&handshake).map_err(|_| ExecutionFailure::unsettled(false))?;
         let mut bytes = Vec::new();
-        let handshake_deadline = deadline.min(Instant::now() + SOCKET_IO_TIMEOUT);
+        let handshake_deadline = operation_deadline.min(Instant::now() + SOCKET_IO_TIMEOUT);
         loop {
             read_available(&mut handshake, &mut bytes, 1)
                 .map_err(|_| ExecutionFailure::unsettled(false))?;
@@ -1029,7 +1031,23 @@ impl Machine {
             resources,
             overlay_gib,
             client,
-            deadline,
+            Some(deadline),
+            client_is_connected,
+        )
+    }
+    fn prepare_project(
+        &self,
+        cache: &CacheEntry,
+        resources: Resources,
+        overlay_gib: Option,
+        client: &UnixStream,
+    ) -> Result<(), String> {
+        self.prepare_with_connection(
+            cache,
+            resources,
+            overlay_gib,
+            client,
+            None,
             client_is_connected,
         )
     }
@@ -1039,7 +1057,7 @@ impl Machine {
         resources: Resources,
         overlay_gib: Option,
         client: &UnixStream,
-        deadline: Instant,
+        aggregate_deadline: Option,
         connected: fn(&UnixStream) -> bool,
     ) -> Result<(), String> {
         let lease = &self.lease;
@@ -1073,6 +1091,8 @@ impl Machine {
             args.extend(["--overlay", value]);
         }
         let checked = |args: &[&str]| -> Result<(), String> {
+            let deadline =
+                aggregate_deadline.unwrap_or_else(|| Instant::now() + DOCKER_CONTROL_TIMEOUT);
             if Instant::now() >= deadline {
                 return Err("deadline_exceeded".into());
             }
@@ -1099,7 +1119,11 @@ impl Machine {
         };
         checked(&args)?;
         // Closed argv omits network enablers; verify exact-owner state before start.
-        lease.verify_network_disabled(deadline, client, connected)?;
+        lease.verify_network_disabled(
+            aggregate_deadline.unwrap_or_else(|| Instant::now() + DOCKER_CONTROL_TIMEOUT),
+            client,
+            connected,
+        )?;
         checked(&["machine", "start", "--name", &lease.name, "--no-workload"])?;
         checked(&[
             "machine",
@@ -1118,7 +1142,7 @@ impl Machine {
         materials: ProjectMaterials<'_>,
         callbacks: &ProjectCallbacks,
         client: &UnixStream,
-        deadline: Instant,
+        budget: ProjectExecutionBudget,
         cancelled: &AtomicBool,
     ) -> Result {
         if self.consumed {
@@ -1199,7 +1223,7 @@ impl Machine {
             &job,
             &sources,
             callbacks,
-            deadline,
+            budget,
             request.maximum_output_bytes,
             client,
             cancelled,
@@ -1239,14 +1263,28 @@ pub(super) fn execute(
     materials: ProjectMaterials<'_>,
     callbacks: &ProjectCallbacks,
     client: &UnixStream,
-    budget: &mut RequestExecutionBudget,
+    execution_budget: ProjectExecutionBudget,
     cancelled: &AtomicBool,
 ) -> Result {
     io::validate_endpoints(callbacks)
         .map_err(|_| ExecutionFailure::ordinary("implementation_unavailable", false))?;
     for attempt in 0..3 {
-        let mut machine = Machine::create(config, request.into(), budget.deadline)?;
-        let prepared = machine.prepare(cache, request.into(), None, client, budget.deadline);
+        let mut machine = match execution_budget {
+            ProjectExecutionBudget::PreparationSeparated(_) => {
+                Machine::create_project(config, request.into())?
+            }
+            ProjectExecutionBudget::Aggregate(deadline) => {
+                Machine::create(config, request.into(), deadline)?
+            }
+        };
+        let prepared = match execution_budget {
+            ProjectExecutionBudget::PreparationSeparated(_) => {
+                machine.prepare_project(cache, request.into(), None, client)
+            }
+            ProjectExecutionBudget::Aggregate(deadline) => {
+                machine.prepare(cache, request.into(), None, client, deadline)
+            }
+        };
         let launched = prepared.is_ok();
         let result = prepared.and_then(|_| {
             machine.run(
@@ -1259,7 +1297,7 @@ pub(super) fn execute(
                 },
                 callbacks,
                 client,
-                budget.deadline,
+                execution_budget,
                 cancelled,
             )
         });
@@ -1268,7 +1306,10 @@ pub(super) fn execute(
         }
         if !launched
             && attempt < 2
-            && Instant::now() < budget.deadline
+            && !matches!(
+                execution_budget,
+                ProjectExecutionBudget::Aggregate(deadline) if Instant::now() >= deadline
+            )
             && client_is_connected(client)
         {
             continue;
@@ -1309,13 +1350,6 @@ pub(super) fn guardian() -> Result<(), String> {
         .write_all(&[1])
         .and_then(|_| std::io::stdout().flush())
         .map_err(|_| "guardian handshake failed")?;
-    let expires = Instant::now()
-        + Duration::from_millis(
-            lease
-                .expires_ms
-                .saturating_sub(now_ms()?)
-                .min(lease.lifetime_ms),
-        );
     let mut reader = input.lock();
     let mut byte = [0u8; 1];
     loop {
@@ -1324,9 +1358,6 @@ pub(super) fn guardian() -> Result<(), String> {
             Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
             Err(_) => break,
         }
-        if Instant::now() >= expires {
-            break;
-        }
         thread::sleep(Duration::from_millis(20));
     }
     lease.cleanup()
diff --git a/external_checkers/workstream-checker-service/src/smol/io.rs b/external_checkers/workstream-checker-service/src/smol/io.rs
index 0ee5462c5..5c0a6b2da 100644
--- a/external_checkers/workstream-checker-service/src/smol/io.rs
+++ b/external_checkers/workstream-checker-service/src/smol/io.rs
@@ -1,10 +1,12 @@
 //! Closed host side of the private Smol guest capability stream.
 
 use super::*;
+use crate::model_relay::InvocationDeadline;
 use crate::proxy_transport::{
     connect_private, read_frame as read_proxy_frame, validate_private_socket,
     write_frame as write_proxy_frame,
 };
+use std::cell::Cell;
 use std::process::{ChildStderr, ChildStdin, ChildStdout};
 use workstream_checker_guest::{
     GuestIoChannel, GuestIoHeader, GuestJob, MaterialRoot, CAPACITY_EXIT_CODE,
@@ -27,6 +29,7 @@ pub(crate) struct ProjectMaterials<'a> {
 #[derive(Clone, Default)]
 pub(crate) struct ProjectCallbacks {
     pub(crate) model: Option,
+    pub(crate) model_deadline: Option,
     pub(crate) execution: Option,
 }
 
@@ -60,6 +63,9 @@ pub(super) fn material_source(
 }
 
 pub(super) fn validate_endpoints(endpoints: &ProjectCallbacks) -> Result<(), String> {
+    if endpoints.model_deadline.is_some() && endpoints.model.is_none() {
+        return Err("model callback deadline binding invalid".into());
+    }
     for path in [endpoints.model.as_deref(), endpoints.execution.as_deref()]
         .into_iter()
         .flatten()
@@ -71,6 +77,7 @@ pub(super) fn validate_endpoints(endpoints: &ProjectCallbacks) -> Result<(), Str
 
 pub(super) struct IoGuard<'a> {
     pub(super) deadline: Instant,
+    pub(super) inactivity: Option<(Cell, Duration)>,
     pub(super) client: Option<&'a UnixStream>,
     pub(super) cancelled: &'a [&'a AtomicBool],
 }
@@ -82,6 +89,12 @@ impl IoGuard<'_> {
         }
     }
 
+    fn progressed(&self) {
+        if let Some((deadline, timeout)) = &self.inactivity {
+            deadline.set(Instant::now() + *timeout);
+        }
+    }
+
     pub(super) fn check(&self) -> Result<(), String> {
         if self
             .cancelled
@@ -90,7 +103,11 @@ impl IoGuard<'_> {
         {
             return Err("guest session cancelled".into());
         }
-        if Instant::now() >= self.deadline {
+        let deadline = self
+            .inactivity
+            .as_ref()
+            .map_or(self.deadline, |(deadline, _)| deadline.get());
+        if Instant::now() >= deadline {
             self.cancel();
             return Err("deadline_exceeded".into());
         }
@@ -115,7 +132,10 @@ pub(super) fn write_all(
         guard.check()?;
         match stream.write(&bytes[offset..]) {
             Ok(0) => return Err("guest input closed".into()),
-            Ok(count) => offset += count,
+            Ok(count) => {
+                offset += count;
+                guard.progressed();
+            }
             Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                 thread::sleep(Duration::from_millis(2));
             }
@@ -135,7 +155,10 @@ pub(super) fn read_exact(
         guard.check()?;
         match stream.read(&mut bytes[offset..]) {
             Ok(0) => return Err("guest output closed".into()),
-            Ok(count) => offset += count,
+            Ok(count) => {
+                offset += count;
+                guard.progressed();
+            }
             Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                 thread::sleep(Duration::from_millis(2));
             }
@@ -236,6 +259,7 @@ fn require_execution_eof(
 ) -> Result<(), String> {
     let guard = IoGuard {
         deadline,
+        inactivity: None,
         client: None,
         cancelled: &[cancelled],
     };
@@ -313,13 +337,36 @@ fn expected_guest_status(oom_kills: u64, output_exceeded: bool, exit_code: Optio
     }
 }
 
+fn prepared_runtime_deadline(
+    header: GuestIoHeader,
+    budget: ProjectExecutionBudget,
+    prepared_at: Instant,
+) -> Result {
+    match header {
+        GuestIoHeader::Prepared { protocol_version } if protocol_version == GUEST_IO_PROTOCOL => {}
+        _ => return Err("guest preparation transition invalid".into()),
+    }
+    Ok(match budget {
+        ProjectExecutionBudget::PreparationSeparated(runtime) => prepared_at + runtime,
+        ProjectExecutionBudget::Aggregate(deadline) => deadline,
+    })
+}
+
+fn reject_duplicate_prepared(header: &GuestIoHeader) -> Result<(), String> {
+    if matches!(header, GuestIoHeader::Prepared { .. }) {
+        Err("duplicate guest preparation transition".into())
+    } else {
+        Ok(())
+    }
+}
+
 #[allow(clippy::too_many_arguments)]
 pub(super) fn run_project(
     mut child: Child,
     job: &GuestJob,
     materials: &[MaterialSource],
     endpoints: &ProjectCallbacks,
-    deadline: Instant,
+    execution_budget: ProjectExecutionBudget,
     maximum_output: usize,
     client: &UnixStream,
     cancelled: &AtomicBool,
@@ -331,18 +378,48 @@ pub(super) fn run_project(
     set_nonblocking(&output)?;
     let mut error_reader = Some(thread::spawn(move || read_process_errors(errors)));
     let cancellation = [cancelled];
-    let guard = IoGuard {
-        deadline,
+    let (preparation_deadline, progress_timeout) = match execution_budget {
+        ProjectExecutionBudget::PreparationSeparated(_) => {
+            (Instant::now() + SOCKET_IO_TIMEOUT, Some(SOCKET_IO_TIMEOUT))
+        }
+        ProjectExecutionBudget::Aggregate(deadline) => (deadline, None),
+    };
+    let preparation_guard = IoGuard {
+        deadline: preparation_deadline,
+        inactivity: progress_timeout.map(|timeout| (Cell::new(preparation_deadline), timeout)),
         client: Some(client),
         cancelled: &cancellation,
     };
     let mut child_reaped = false;
     let result = (|| {
-        write_job(&mut input, job, materials, &guard)?;
+        write_job(&mut input, job, materials, &preparation_guard)?;
+        let deadline = prepared_runtime_deadline(
+            read_header(&mut output, &preparation_guard)?,
+            execution_budget,
+            Instant::now(),
+        )?;
+        if let Some(model_deadline) = &endpoints.model_deadline {
+            model_deadline.arm(deadline)?;
+        }
+        let guard = IoGuard {
+            deadline,
+            inactivity: None,
+            client: Some(client),
+            cancelled: &cancellation,
+        };
+        write_header(
+            &mut input,
+            &GuestIoHeader::Start {
+                protocol_version: GUEST_IO_PROTOCOL.into(),
+            },
+            &guard,
+        )?;
         let mut next_sequence = 1_u32;
         let mut relay_connections = RelayConnections::default();
         loop {
-            match read_header(&mut output, &guard)? {
+            let header = read_header(&mut output, &guard)?;
+            reject_duplicate_prepared(&header)?;
+            match header {
                 GuestIoHeader::Request {
                     protocol_version,
                     sequence,
@@ -436,6 +513,8 @@ pub(super) fn run_project(
                 GuestIoHeader::Response { .. } => {
                     return Err("unsolicited guest capability response".into())
                 }
+                GuestIoHeader::Prepared { .. } => unreachable!("checked above"),
+                GuestIoHeader::Start { .. } => return Err("unsolicited guest project start".into()),
             }
         }
     })();
@@ -528,6 +607,7 @@ mod tests {
             // to close or consume an oversized body before rejecting it.
             let guard = IoGuard {
                 deadline: Instant::now() + Duration::from_secs(2),
+                inactivity: None,
                 client: None,
                 cancelled: &[],
             };
@@ -558,6 +638,61 @@ mod tests {
         assert_eq!(expected_guest_status(1, true, None), CAPACITY_EXIT_CODE);
     }
 
+    #[test]
+    fn prepared_transition_starts_only_the_declared_runtime_and_is_single_use() {
+        let prepared_at = Instant::now();
+        let runtime = Duration::from_secs(30);
+        assert_eq!(
+            prepared_runtime_deadline(
+                GuestIoHeader::Prepared {
+                    protocol_version: GUEST_IO_PROTOCOL.into(),
+                },
+                ProjectExecutionBudget::PreparationSeparated(runtime),
+                prepared_at,
+            )
+            .unwrap(),
+            prepared_at + runtime,
+        );
+        let aggregate = prepared_at + Duration::from_secs(5);
+        assert_eq!(
+            prepared_runtime_deadline(
+                GuestIoHeader::Prepared {
+                    protocol_version: GUEST_IO_PROTOCOL.into(),
+                },
+                ProjectExecutionBudget::Aggregate(aggregate),
+                prepared_at,
+            )
+            .unwrap(),
+            aggregate,
+        );
+        assert!(prepared_runtime_deadline(
+            GuestIoHeader::Prepared {
+                protocol_version: "wrong".into(),
+            },
+            ProjectExecutionBudget::PreparationSeparated(runtime),
+            prepared_at,
+        )
+        .is_err());
+        assert!(prepared_runtime_deadline(
+            GuestIoHeader::Completed {
+                protocol_version: GUEST_IO_PROTOCOL.into(),
+                exit_code: Some(0),
+                signal: None,
+                oom_kills: 0,
+                output_exceeded: false,
+                stdout_bytes: 0,
+                stderr_bytes: 0,
+            },
+            ProjectExecutionBudget::PreparationSeparated(runtime),
+            prepared_at,
+        )
+        .is_err());
+        assert!(reject_duplicate_prepared(&GuestIoHeader::Prepared {
+            protocol_version: GUEST_IO_PROTOCOL.into(),
+        })
+        .is_err());
+    }
+
     #[test]
     fn guard_cancels_every_owner_on_terminal_deadline() {
         let first = AtomicBool::new(false);
@@ -565,6 +700,7 @@ mod tests {
         let cancellation = [&first, &second];
         let guard = IoGuard {
             deadline: Instant::now(),
+            inactivity: None,
             client: None,
             cancelled: &cancellation,
         };
@@ -620,6 +756,7 @@ mod tests {
         });
         let endpoints = ProjectCallbacks {
             model: Some(socket.clone()),
+            model_deadline: None,
             execution: Some(execution_socket.clone()),
         };
         let cancelled = AtomicBool::new(false);
diff --git a/external_checkers/workstream-checker-service/src/smol/pre.rs b/external_checkers/workstream-checker-service/src/smol/pre.rs
index 2149f286d..3063dff01 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre.rs
@@ -74,7 +74,7 @@ pub(crate) fn serve(
         prepared.resources,
         Some(prepared.overlay_gib),
         &client,
-        deadline,
+        Some(deadline),
         transport::connected,
     );
     let preparation_ms = preparing.elapsed().as_millis() as u64;
diff --git a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
index d5abbf2fe..4fa350cd4 100644
--- a/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/pre/tests.rs
@@ -83,8 +83,6 @@ pub(super) fn fixture() -> (PathBuf, ServiceConfig, Lease, Journal) {
         name: format!("ws-{}", "0".repeat(32)),
         owner: container_owner(&config).unwrap().to_owned(),
         epoch: "e".repeat(64),
-        expires_ms: 1,
-        lifetime_ms: 1,
         root: leases,
         runtime,
         private_home_root: None,
diff --git a/external_checkers/workstream-checker-service/src/smol/tests.rs b/external_checkers/workstream-checker-service/src/smol/tests.rs
index 05e4d9c51..725ee4561 100644
--- a/external_checkers/workstream-checker-service/src/smol/tests.rs
+++ b/external_checkers/workstream-checker-service/src/smol/tests.rs
@@ -250,8 +250,6 @@ fn foreign_lease_refuses_recovery_before_any_runtime_or_owned_cleanup() {
         name: format!("ws-{}", "0".repeat(32)),
         owner: container_owner(&config).unwrap().to_owned(),
         epoch: "e".repeat(64),
-        expires_ms: 1,
-        lifetime_ms: 1,
         root: leases.clone(),
         runtime,
         private_home_root: None,
@@ -299,7 +297,7 @@ fn missing_lease_directory_does_not_poison_node_admission() {
     ));
     let request = parse_request(include_bytes!("../../../fixtures/request.json")).unwrap();
     let (client, _peer) = UnixStream::pair().unwrap();
-    let mut budget = RequestExecutionBudget::new(Instant::now() + Duration::from_secs(1), 32768);
+    let deadline = Instant::now() + Duration::from_secs(1);
     let inventory = WorkspaceInventory {
         directories: Vec::new(),
         files: Vec::new(),
@@ -315,7 +313,7 @@ fn missing_lease_directory_does_not_poison_node_admission() {
         },
         &ProjectCallbacks::default(),
         &client,
-        &mut budget,
+        ProjectExecutionBudget::Aggregate(deadline),
         &cancelled,
     );
     assert_eq!(
@@ -440,8 +438,6 @@ fn private_child_home_is_derived_from_the_exact_lease() {
         name,
         owner: "b".repeat(64),
         epoch: "c".repeat(64),
-        expires_ms: 1,
-        lifetime_ms: 1,
         root: lease_root,
         runtime,
         private_home_root: Some(child_home_root),
@@ -528,8 +524,6 @@ fn intake_overlay_is_explicit_in_runtime_argv_and_project_creation_is_unchanged(
         name: format!("ws-{}", "0".repeat(32)),
         owner: "d".repeat(64),
         epoch: "e".repeat(64),
-        expires_ms: 1,
-        lifetime_ms: 1,
         root: root.join("leases"),
         runtime,
         private_home_root: None,
diff --git a/external_checkers/workstream-checker-service/src/smol/trial.rs b/external_checkers/workstream-checker-service/src/smol/trial.rs
index 3bbd01585..f227c1768 100644
--- a/external_checkers/workstream-checker-service/src/smol/trial.rs
+++ b/external_checkers/workstream-checker-service/src/smol/trial.rs
@@ -82,6 +82,7 @@ impl Runtime {
         let cancelled = [invocation_cancelled.as_ref()];
         let guard = IoGuard {
             deadline,
+            inactivity: None,
             client: Some(&client),
             cancelled: &cancelled,
         };
@@ -670,6 +671,7 @@ impl SmolTrialRuntime for Runtime {
         let cancelled = [self.invocation_cancelled.as_ref()];
         let guard = IoGuard {
             deadline: self.deadline,
+            inactivity: None,
             client: Some(&self.client),
             cancelled: &cancelled,
         };
@@ -703,6 +705,7 @@ impl SmolTrialRuntime for Runtime {
         let cancelled = [invocation_cancelled, relay_cancelled];
         let guard = IoGuard {
             deadline,
+            inactivity: None,
             client: Some(&self.client),
             cancelled: &cancelled,
         };
@@ -936,6 +939,7 @@ impl SmolTrialRuntime for Runtime {
         let cancelled = [invocation_cancelled, relay_cancelled];
         let guard = IoGuard {
             deadline,
+            inactivity: None,
             client: Some(&self.client),
             cancelled: &cancelled,
         };
diff --git a/external_checkers/workstream-checker-service/src/smol/trial_io.rs b/external_checkers/workstream-checker-service/src/smol/trial_io.rs
index a290f6e3d..7feec122d 100644
--- a/external_checkers/workstream-checker-service/src/smol/trial_io.rs
+++ b/external_checkers/workstream-checker-service/src/smol/trial_io.rs
@@ -771,6 +771,7 @@ mod tests {
             let target = root.0.join("candidate.tar");
             let guard = IoGuard {
                 deadline: Instant::now() + Duration::from_secs(5),
+                inactivity: None,
                 client: None,
                 cancelled: &[],
             };
diff --git a/external_checkers/workstream-checker-service/src/trial_roots.rs b/external_checkers/workstream-checker-service/src/trial_roots.rs
index f13d8a67c..a4b6dc048 100644
--- a/external_checkers/workstream-checker-service/src/trial_roots.rs
+++ b/external_checkers/workstream-checker-service/src/trial_roots.rs
@@ -520,7 +520,7 @@ esac
             &lease,
             serde_json::to_vec(&serde_json::json!({
                 "name": name, "owner": owner, "epoch": "e".repeat(64),
-                "expires_ms": 1, "lifetime_ms": 1, "root": leases,
+                "root": leases,
                 "runtime": child_runtime, "private_home_root": runtime.child_home_root,
             }))
             .unwrap(),

From 32a67dfdcd46c63a0da5c8c7f74f9113df4a762e Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 27 Nov 2026 07:25:23 +0100
Subject: [PATCH 512/513] fix(checkers): preserve PRE guest start authority

---
 .../workstream-checker-guest/src/main.rs      | 88 ++++++++++++++++---
 .../workstream-checker-guest/src/pre.rs       |  1 +
 2 files changed, 78 insertions(+), 11 deletions(-)

diff --git a/external_checkers/workstream-checker-guest/src/main.rs b/external_checkers/workstream-checker-guest/src/main.rs
index adaa8261b..04ed55a9c 100644
--- a/external_checkers/workstream-checker-guest/src/main.rs
+++ b/external_checkers/workstream-checker-guest/src/main.rs
@@ -303,7 +303,7 @@ fn write_guest_header_to(header: &GuestIoHeader, output: &mut impl Write) -> Res
     Ok(())
 }
 
-fn read_guest_header(input: &mut File) -> Result {
+fn read_guest_header(input: &mut impl Read) -> Result {
     let mut length = [0_u8; 4];
     input.read_exact(&mut length)?;
     let length = u32::from_be_bytes(length) as usize;
@@ -686,6 +686,34 @@ struct ProjectOutcome {
     stderr: Vec,
 }
 
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum ProjectRuntimeStart {
+    HostAfterPreparation,
+    GuestDeadline,
+}
+
+fn synchronize_project_start(
+    authority: ProjectRuntimeStart,
+    input: &mut impl Read,
+    output: &mut impl Write,
+) -> Result<()> {
+    if authority == ProjectRuntimeStart::GuestDeadline {
+        return Ok(());
+    }
+    write_guest_header_to(
+        &GuestIoHeader::Prepared {
+            protocol_version: GUEST_IO_PROTOCOL.into(),
+        },
+        output,
+    )?;
+    match read_guest_header(input)? {
+        GuestIoHeader::Start { protocol_version } if protocol_version == GUEST_IO_PROTOCOL => {
+            Ok(())
+        }
+        _ => Err("guest project start invalid".into()),
+    }
+}
+
 impl ProjectOutcome {
     fn exit_code(&self) -> i32 {
         if self.output_exceeded && self.oom_kills == 0 {
@@ -813,6 +841,7 @@ fn run_project(
     staged: StagedJob,
     mut input: File,
     limits: ProjectLimits,
+    runtime_start: ProjectRuntimeStart,
 ) -> Result {
     limits.validate(capabilities)?;
     bind_project_materials(&staged)?;
@@ -832,16 +861,10 @@ fn run_project(
         limits.maximum_processes,
     )
     .map_err(|error| format!("cgroup: {error}"))?;
-    // All host material and guest platform setup is complete. The workload is
-    // not forked until the host acknowledges this transition after arming the
-    // registry-declared checker runtime and invocation-local callbacks.
-    write_guest_header(&GuestIoHeader::Prepared {
-        protocol_version: GUEST_IO_PROTOCOL.into(),
-    })?;
-    match read_guest_header(&mut input)? {
-        GuestIoHeader::Start { protocol_version } if protocol_version == GUEST_IO_PROTOCOL => {}
-        _ => return Err("guest project start invalid".into()),
-    }
+    // All host material and guest platform setup is complete. Ordinary POST
+    // waits for the host to arm its registry runtime. PRE uses its existing
+    // guest absolute deadline and must never wait for this POST-only dialogue.
+    synchronize_project_start(runtime_start, &mut input, &mut std::io::stdout().lock())?;
     // The supervisor retains the trusted stream and capability listeners. The
     // workload receives separate output pipes, so it cannot forge mux frames.
     let child = limits.fork_project()?;
@@ -1024,6 +1047,48 @@ fn run_project(
 mod tests {
     use super::*;
     use std::time::Instant;
+
+    struct RefuseRead;
+
+    impl Read for RefuseRead {
+        fn read(&mut self, _bytes: &mut [u8]) -> std::io::Result {
+            panic!("PRE must not wait for an ordinary POST start frame")
+        }
+    }
+
+    #[test]
+    fn pre_guest_deadline_never_enters_the_ordinary_post_start_dialogue() {
+        let mut output = Vec::new();
+        synchronize_project_start(
+            ProjectRuntimeStart::GuestDeadline,
+            &mut RefuseRead,
+            &mut output,
+        )
+        .unwrap();
+        assert!(output.is_empty());
+
+        let mut start = Vec::new();
+        write_guest_header_to(
+            &GuestIoHeader::Start {
+                protocol_version: GUEST_IO_PROTOCOL.into(),
+            },
+            &mut start,
+        )
+        .unwrap();
+        synchronize_project_start(
+            ProjectRuntimeStart::HostAfterPreparation,
+            &mut start.as_slice(),
+            &mut output,
+        )
+        .unwrap();
+        let size = u32::from_be_bytes(output[..4].try_into().unwrap()) as usize;
+        assert!(matches!(
+            serde_json::from_slice::(&output[4..4 + size]).unwrap(),
+            GuestIoHeader::Prepared { protocol_version }
+                if protocol_version == GUEST_IO_PROTOCOL
+        ));
+    }
+
     #[test]
     fn captured_project_output_stays_payload_under_trusted_completion() {
         let untrusted = br#"{"kind":"completed","oom_kills":0,"exit_code":0}"#.to_vec();
@@ -1704,6 +1769,7 @@ fn run() -> Result<()> {
                 deadline: None,
                 cleanup_deadline: None,
             },
+            ProjectRuntimeStart::HostAfterPreparation,
         )?;
         outcome.write_completion(&mut std::io::stdout().lock())?;
         std::process::exit(outcome.exit_code());
diff --git a/external_checkers/workstream-checker-guest/src/pre.rs b/external_checkers/workstream-checker-guest/src/pre.rs
index 0772853ca..9d5b889e9 100644
--- a/external_checkers/workstream-checker-guest/src/pre.rs
+++ b/external_checkers/workstream-checker-guest/src/pre.rs
@@ -386,6 +386,7 @@ pub(super) fn run_project_phase(
         staged,
         File::open("/dev/null")?,
         limits,
+        ProjectRuntimeStart::GuestDeadline,
     )?;
     let result = if outcome.oom_kills > 0 {
         infrastructure_result(&request, "capacity_exceeded")?

From 4b763013920e79b6d70c99639f2d84e72341952a Mon Sep 17 00:00:00 2001
From: Abiorh001 
Date: Fri, 27 Nov 2026 07:44:31 +0100
Subject: [PATCH 513/513] Record hosted 500 MiB POST completion and automatic
 acceptance

---
 .../initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
index f764a28a5..95c64361b 100644
--- a/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
+++ b/.commitrail/initiatives/WS-SUBMIT-001/WS-SUBMIT-001-01.md
@@ -13465,3 +13465,18 @@ The registered checker specifies 30,000 ms. The native implementation starts
 that clock before image verification, VM creation, and guest staging. The
 receipt establishes successful transfer to the runner. It does not locate the
 precise point at which the deadline elapsed inside native execution.
+
+### Hosted 500 MiB automatic acceptance, 27 November 2026
+
+The dedicated runner deployed native service and guest code from `32a67dfdc`.
+A positive streamed PRE on the new guest returned eligible and confirmed VM
+destruction. The hosted trusted-intake adapter read the original 524,288,000-byte
+ZIP, inspected all six entries and closed its session.
+
+The Operator used the public checker retry command on the eligible generation
+5 infrastructure failure. Generation 6 began at 06:41:00 UTC and completed at
+06:43:42 UTC. The completion worker moved the task to `accepted` on assignment
+`01a2191d-4ce8-7b0c-b7fc-ac35cfea7aa0` using the existing submission. The API
+container restarted during the runner-pin switch and was healthy after cutover.
+The EC2 host remained online. This positive journey did not exercise the
+individual native failure fixtures or send a revision email.